From 820b2a202f2d75f15284d7dfffc91067406cde5c Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:41:35 +0100 Subject: [PATCH 01/17] M5 synthetic gate: d3d12_m5_world_test (ExecuteIndirect draws, 4-thread recording, 5120-SRV table, pipeline cache) Test d3d12_m5_world_test (D3D12 API only, translator-output shaders, every pixel against a CPU reference): (a) five ExecuteIndirect calls (DRAW and DRAW_INDEXED signatures, CPU- and GPU-written records at offsets in placed buffers, count buffer, count 0, count above MaxCommandCount), (b) four threads recording four lists run in one ExecuteCommandLists, eight rounds, (c) a descriptor table of 5120 SRVs of distinct textures read at a byte offset from a root constant, (d) a PSO created twice through the device's VkPipelineCache. Layer gaps fixed on the way: - ExecuteIndirect draws carry the list's graphics state and replay as whole draws; they used to replay as a bare vkCmdDraw*Indirect outside any render pass with no pipeline bound. - multiDrawIndirect, drawIndirectCount and drawIndirectFirstInstance are enabled on the layer's device where present (VulkanDeviceInfo::multi_draw_indirect / draw_indirect_count); without multiDrawIndirect each record is its own call. - One VkPipelineCache per device for every graphics and compute pipeline (was VK_NULL_HANDLE), with VkPipelineCreationFeedback hit counting (rt::d3d12::pipeline_cache_stats). Section 6 M5 row: synthetic part met except mesh shaders (D3D-29). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 11 +- runtime/CMakeLists.txt | 35 +- runtime/shims/d3d12_com.cpp | 24 +- runtime/shims/d3d12_com.h | 17 + runtime/shims/d3d12_vulkan_device.cpp | 101 +++- runtime/src/command_list.h | 7 + runtime/src/vulkan_backend.h | 9 +- runtime/src/vulkan_replay.h | 77 ++- runtime/test/d3d12_m5_world_test.cpp | 755 ++++++++++++++++++++++++++ runtime/test/d3d12_state_map_test.cpp | 16 + runtime/test/shaders/ps_m5_flat.asm | 11 + runtime/test/shaders/ps_m5_inst.asm | 24 + runtime/test/shaders/ps_m5_tex.asm | 19 + runtime/test/shaders/vs_m5.asm | 35 ++ runtime/test/vk_test_device.h | 9 + scripts/run_gpu_tests.py | 4 +- 16 files changed, 1114 insertions(+), 40 deletions(-) create mode 100644 runtime/test/d3d12_m5_world_test.cpp create mode 100644 runtime/test/shaders/ps_m5_flat.asm create mode 100644 runtime/test/shaders/ps_m5_inst.asm create mode 100644 runtime/test/shaders/ps_m5_tex.asm create mode 100644 runtime/test/shaders/vs_m5.asm diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e96dcae726..06baed49ee 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1345,6 +1345,11 @@ Pipeline creation: - Pipeline caches: use a `VkPipelineCache` keyed by driver/pipeline-cache UUID; the `pipelines` build stage already produces one. D3D12 `CachedPSO` blobs are driver-specific and are ignored (the PSO is rebuilt from its descriptors). `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan cache. + **Done:** the device keeps one in-memory `VkPipelineCache`, passed to every graphics and compute pipeline it creates + (the draw-time variants of a graphics PSO included), and with Vulkan 1.3 asks for `VkPipelineCreationFeedback` to count + the creations the cache answered (`rt::d3d12::pipeline_cache_stats`; `d3d12_m5_world_test` creates a PSO twice and + checks the second is a hit that adds nothing to the cache's data). **Open:** `ID3D12PipelineLibrary`, and + persisting or seeding the cache between runs. **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. @@ -2054,7 +2059,9 @@ Not implemented yet: - `D3D12_COMMAND_SIGNATURE_DESC` describes the argument stride and a list of argument types. Simple draw, draw-indexed, dispatch and mesh-dispatch signatures map to `vkCmdDraw*Indirect`, `vkCmdDispatchIndirect` and `vkCmdDrawMeshTasksIndirectEXT`; use the `*Count` variants (`VK_KHR_draw_indirect_count`, core 1.2) when the - `ExecuteIndirect` call supplies a count buffer. + `ExecuteIndirect` call supplies a count buffer. The draw kinds replay as whole draws (the list's graphics state at the + call is recorded with them, as for `DrawInstanced`); without `multiDrawIndirect` each record is its own call. + `d3d12_m5_world_test` runs them from CPU- and GPU-written records at offsets in placed buffers. - Signatures that change root constants, vertex/index buffers or descriptors per argument cannot be expressed by one Vulkan indirect call. Use a compute expansion pass that writes a Vulkan-shaped indirect buffer, or `VK_NV_device_generated_commands` on NVIDIA. Start with the simple signatures; the trace will show which @@ -2419,7 +2426,7 @@ M0–M2 do not need the executable. | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU), and texture formats other than R8G8B8A8_UNORM, mips and arrays through a PSO (the descriptor test covers views and sampling on a compute shader) | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check | -| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise | +| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met except mesh shaders (D3D-29, @Ryx69)** by `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 34 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, `StartIndexLocation`/`StartVertexLocation` picking the cell and a non-zero `StartInstanceLocation`. **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Still open for M5:** mesh shaders (D3D-29); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; Xbox DXIL path for the builder's 53 shaders (22 lowered so far) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the DXIL path or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; HDR, VRS, plane compose, alt-tab are open | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 6f135558a4..2dd597f67f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1176,8 +1176,41 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) set_tests_properties(d3d12_m3_frame PROPERTIES SKIP_RETURN_CODE 77) + + # M5 (synthetic part, without mesh shaders): ExecuteIndirect draws, command lists recorded on four threads, a + # descriptor table of 5120 SRVs, and a PSO created twice through the device's pipeline cache. vs_m5/ps_m5_inst + # (indirect cells), vs_m3/ps_m5_flat (rectangles from root constants), vs_m2/ps_m5_tex (T# at a byte offset). + set(LEONIDA_M5_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m5_shaders) + set(LEONIDA_M5_FILES ${LEONIDA_M5_DIR}/spirv/index.json ${LEONIDA_M5_DIR}/fssm/vs_m5.fssm + ${LEONIDA_M5_DIR}/fssm/ps_m5_inst.fssm ${LEONIDA_M5_DIR}/fssm/vs_m3.fssm + ${LEONIDA_M5_DIR}/fssm/ps_m5_flat.fssm ${LEONIDA_M5_DIR}/fssm/vs_m2.fssm + ${LEONIDA_M5_DIR}/fssm/ps_m5_tex.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M5_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M5_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M5_DIR} vs_m5 ps_m5_inst vs_m3 ps_m5_flat vs_m2 ps_m5_tex + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m5.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m5_inst.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m3.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m5_flat.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m5_tex.asm + ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py + COMMENT "Translating vs_m5, ps_m5_inst, vs_m3, ps_m5_flat, vs_m2 and ps_m5_tex for the M5 world test" + VERBATIM) + add_executable(d3d12_m5_world_test test/d3d12_m5_world_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M5_FILES}) + target_link_libraries(d3d12_m5_world_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m5_world_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M5_DIR="${LEONIDA_M5_DIR}") + target_compile_options(d3d12_m5_world_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m5_world COMMAND d3d12_m5_world_test) + set_tests_properties(d3d12_m5_world PROPERTIES SKIP_RETURN_CODE 77) else() - message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test and d3d12_m3_frame_test are not built") + message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m3_frame_test and d3d12_m5_world_test are not built") endif() # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the # host runtime and WARP; run explicitly on a Vulkan GPU. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 7e428735d6..5a96e8a182 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -584,6 +584,15 @@ class GraphicsCommandList final if (!command_signature_info(signature, kind, stride) || !argument_buffer) return check(false); leonida::ExecuteIndirect cmd{}; + // A draw takes the list's graphics state, as DrawInstanced does; with nothing to rasterize it is dropped. A + // list with no pipeline, root signature or topology yet records the bare call (it closes, as on the PC + // runtime; it is not a call replay can run). + if (kind != leonida::IndirectKind::dispatch && max_command_count && graphics_pipeline_ && graphics_.layout && + topology_) { + if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; + cmd.state = std::make_shared( + make_draw(kind == leonida::IndirectKind::draw_indexed, 0, 0, 0, 0, 0)); + } cmd.kind = kind; cmd.stride = stride; cmd.max_count = max_command_count; @@ -878,11 +887,16 @@ class GraphicsCommandList final // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; - leonida::Draw draw{graphics_pipeline_, graphics_.data, render_targets_, depth_, - {vertex_buffers_.begin(), vertex_buffers_.end()}, index_, topology_, viewport_, scissor_, - blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, - base_vertex, first_instance}; - check(list_.draw(draw)); + check(list_.draw(make_draw(indexed, count, instances, first, base_vertex, first_instance))); + } + + // The list's graphics state as a draw (see record_draw for what has to be set). + leonida::Draw make_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, + UINT first_instance) const { + return {graphics_pipeline_, graphics_.data, render_targets_, depth_, + {vertex_buffers_.begin(), vertex_buffers_.end()}, index_, topology_, viewport_, scissor_, + blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, + base_vertex, first_instance}; } }; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2e1f2d3c54..ffa5a802f5 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -90,6 +90,12 @@ struct VulkanDeviceInfo { // samplerAnisotropy, samplerMirrorClampToEdge and samplerFilterMinmax enabled; without them such samplers are // approximated. bool sampler_anisotropy = false; + // multiDrawIndirect is enabled: ExecuteIndirect hands all its commands to one vkCmdDraw*Indirect. Without it the + // layer issues one call per command (a drawCount above 1 is invalid without the feature). + bool multi_draw_indirect = false; + // drawIndirectCount (Vulkan 1.2) is enabled: ExecuteIndirect with a count buffer. True unless the creator says + // otherwise (it is the way callers that never set this behaved); without it such a call is unsupported. + bool draw_indirect_count = true; bool sampler_mirror_clamp_to_edge = false; bool sampler_filter_minmax = false; // VK_KHR_calibrated_timestamps or VK_EXT_calibrated_timestamps is enabled on `device` (QueueClock). @@ -198,6 +204,17 @@ VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device); // The bindless index the descriptor hash table holds for the 8 key dwords of a T# (or the 4 of an S# followed by // 0xFFFFFFFF x4), 0 (the fallback) when it has none or `device` has no such set. For tests. std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]); +// The device's VkPipelineCache: how many Vulkan pipelines were created through it (graphics, compute and the draw-time +// variants of a graphics PSO), how many of those the cache answered (VkPipelineCreationFeedback's application-cache +// hit bit), and the size of its data. `available` is false without Vulkan 1.3 feedback or without the cache; then the +// counts stay 0. For tests. +struct PipelineCacheStats { + bool available = false; + std::uint32_t created = 0; + std::uint32_t hits = 0; + std::size_t bytes = 0; +}; +PipelineCacheStats pipeline_cache_stats(ID3D12Device* device); // Gives each S# a sampler in that set and a key in its hash table, as CreateSampler does, without a heap slot: for // the literal S#s a shader builds from immediates (`literal_samplers` in the shader index). An S# that has them // already is left as it is. E_INVALIDARG when `device` is not such a device; E_FAIL when one of them could not be diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8d0cd21e47..23ed4c699f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -448,6 +448,64 @@ struct DeviceState { } } + // One VkPipelineCache for every pipeline the device creates (docs/d3d12_vulkan.md section 3.6): a PSO created a + // second time from the same shaders and state is satisfied from it. It is made on first use; without the entry + // points it stays null and pipelines are created as before. With Vulkan 1.3 every creation also asks for + // VkPipelineCreationFeedback, which is how the layer counts the creations the cache answered. + std::mutex pipeline_cache_mutex; + VkPipelineCache pipeline_cache = VK_NULL_HANDLE; + bool pipeline_cache_tried = false; + bool vulkan_1_3 = false; // the physical device's apiVersion allows VkPipelineCreationFeedback without an extension + std::atomic pipelines_created{0}; + std::atomic pipeline_cache_hits{0}; + + VkPipelineCache pipeline_cache_handle() { + std::lock_guard lock(pipeline_cache_mutex); + if (!pipeline_cache_tried) { + pipeline_cache_tried = true; + const auto& vk = context->vk; + VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || + vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache) != VK_SUCCESS) + pipeline_cache = VK_NULL_HANDLE; + } + return pipeline_cache; + } + + void destroy_pipeline_cache() { + if (pipeline_cache && context) context->vk.vkDestroyPipelineCache(info.device, pipeline_cache, nullptr); + pipeline_cache = VK_NULL_HANDLE; + } + + // The size of the cache's data in bytes, 0 without a cache. + std::size_t pipeline_cache_bytes() { + const VkPipelineCache cache = pipeline_cache_handle(); + std::size_t bytes = 0; + if (cache && context->vk.vkGetPipelineCacheData && + context->vk.vkGetPipelineCacheData(info.device, cache, &bytes, nullptr) != VK_SUCCESS) + bytes = 0; + return bytes; + } + + // `create(cache, info)` runs vkCreate*Pipelines with the device's cache and `create_info` (a graphics or compute + // create-info, taken by value so the feedback struct can be chained in front of its pNext). + template + VkResult create_pipeline(Create create, Info create_info) { + VkPipelineCreationFeedback total{}; + VkPipelineCreationFeedbackCreateInfo feedback{VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO}; + feedback.pPipelineCreationFeedback = &total; + if (vulkan_1_3) { + feedback.pNext = create_info.pNext; + create_info.pNext = &feedback; + } + const VkResult result = create(pipeline_cache_handle(), create_info); + if (result == VK_SUCCESS && vulkan_1_3 && (total.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT)) { + ++pipelines_created; + if (total.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) ++pipeline_cache_hits; + } + return result; + } + // The translator's output, loaded on first use. std::mutex library_mutex; bool library_tried = false; @@ -2465,8 +2523,11 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) + if (device_.create_pipeline( + [&](VkPipelineCache cache, const VkComputePipelineCreateInfo& create) { + return vk.vkCreateComputePipelines(dev, cache, 1, &create, nullptr, &pipeline_.pipeline); + }, + pipeline_info) != VK_SUCCESS) return E_FAIL; // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. @@ -2550,8 +2611,12 @@ class PipelineState final info.pDynamicState = &dynamic; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, VK_NULL_HANDLE, 1, &info, nullptr, - &pipeline) != VK_SUCCESS) + if (device_.create_pipeline( + [&](VkPipelineCache cache, const VkGraphicsPipelineCreateInfo& create) { + return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &create, + nullptr, &pipeline); + }, + info) != VK_SUCCESS) return VK_NULL_HANDLE; return pipeline; } @@ -2930,6 +2995,11 @@ class Device final return; state_.r9g9b9e5_uav_emulated = state_.probe_r9g9b9e5_uav_emulation(); memory_properties(info.physical, &state_.memory); + { + VkPhysicalDeviceProperties physical_properties{}; + device_properties(info.physical, &physical_properties); + state_.vulkan_1_3 = physical_properties.apiVersion >= VK_API_VERSION_1_3; + } { char text[4] = {}; size_t length = 0; @@ -2981,6 +3051,7 @@ class Device final info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address); + state_.context->set_indirect_features(info.multi_draw_indirect, info.draw_indirect_count); if (info.buffer_device_address && state_.context->loaded() && !create_arena()) std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); if (info.conditional_rendering) { @@ -3186,6 +3257,7 @@ class Device final state_.context->set_bindless_release(nullptr, nullptr); } state_.staging_queue.reset(); // it uses the context + state_.destroy_pipeline_cache(); if (state_.context && state_.bindless) { // Every texture is gone by now (each held this device), and its views with it; samplers remain. std::lock_guard lock(state_.descriptor_mutex); @@ -3210,6 +3282,7 @@ class Device final leonida::VulkanContext& context() { return *state_.context; } const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } const DeviceState& state() const { return state_; } + DeviceState& mutable_state() { return state_; } IUnknown* holder() { return identity(); } bool bind_sampler(const leonida::gfx10::SamplerWords& words) { return state_.bind_sampler(words); } void own(const OwnedRuntime& owned) { owned_ = owned; } @@ -5603,6 +5676,20 @@ std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&k return set ? set->table().lookup(key) : 0; } +PipelineCacheStats pipeline_cache_stats(ID3D12Device* device) { + PipelineCacheStats stats{}; + if (!device) return stats; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + Device* d = Device::from(real ? real : device); + if (!d) return stats; + DeviceState& state = d->mutable_state(); + stats.available = state.vulkan_1_3 && state.pipeline_cache_handle() != VK_NULL_HANDLE; + stats.created = state.pipelines_created; + stats.hits = state.pipeline_cache_hits; + stats.bytes = state.pipeline_cache_bytes(); + return stats; +} + WindowPresenter::WindowPresenter(IUnknown* device, std::unique_ptr presenter) : device_(device), presenter_(std::move(presenter)) { device_->AddRef(); @@ -5974,6 +6061,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { chosen12.descriptorBindingStorageBufferUpdateAfterBind; info.bindless_partially_bound = info.bindless && chosen12.descriptorBindingPartiallyBound; info.sampler_anisotropy = chosen_features.samplerAnisotropy; + // ExecuteIndirect: several commands per call, and a count buffer. + info.multi_draw_indirect = chosen_features.multiDrawIndirect == VK_TRUE; + info.draw_indirect_count = chosen12.drawIndirectCount == VK_TRUE; + enable12.drawIndirectCount = info.draw_indirect_count; info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; info.sampler_filter_minmax = chosen12.samplerFilterMinmax; enable12.runtimeDescriptorArray = info.bindless; @@ -6005,6 +6096,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { if (!chosen_features.shaderInt64) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderInt64; translated shaders (all declare Int64) will not load\n"); enable.samplerAnisotropy = info.sampler_anisotropy; + enable.multiDrawIndirect = info.multi_draw_indirect; + enable.drawIndirectFirstInstance = chosen_features.drawIndirectFirstInstance; // StartInstanceLocation in ExecuteIndirect enable.occlusionQueryPrecise = chosen_features.occlusionQueryPrecise; // exact D3D12 occlusion counts enable.pipelineStatisticsQuery = chosen_features.pipelineStatisticsQuery; info.occlusion_query_precise = chosen_features.occlusionQueryPrecise == VK_TRUE; diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 9c74994e18..db4ce718ab 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -565,6 +566,11 @@ struct ExecuteIndirect { std::uint64_t argument_offset = 0; ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount std::uint64_t count_offset = 0; + // The list's graphics state at the call (its count, instances and first fields are unused: the argument buffer + // holds them), for the draw kinds. Replay then makes the call a whole draw: it begins rendering into the targets, + // binds the pipeline and the dynamic state as for a Draw, and issues the indirect draw. Null: the caller has set + // all that up (a raw indirect call), as the unit tests of the indirect path do. + std::shared_ptr state; }; // Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). @@ -801,6 +807,7 @@ class CommandList { bool execute_indirect(const ExecuteIndirect& indirect) { if (!indirect.argument_buffer || !indirect.stride) return false; + if (indirect.state && (!indirect.state->pipeline || indirect.kind == IndirectKind::dispatch)) return false; if (!indirect.max_count) return !closed_; // the PC runtime takes MaxCommandCount 0 as a no-op return append(indirect); } diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 73232109e7..41a9c3099a 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -75,7 +75,8 @@ struct VulkanDeviceFunctions { X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ - X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) + X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER @@ -865,6 +866,12 @@ class VulkanContext { // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely. + // The indirect-draw features enabled on the device (VulkanDeviceInfo::multi_draw_indirect / draw_indirect_count). + void set_indirect_features(bool multi_draw, bool draw_count) { + replay_.multi_draw_indirect = multi_draw; + if (!draw_count) replay_.draw_indirect_count = replay_.draw_indexed_indirect_count = nullptr; + } + void set_heap_base(std::uint64_t heap_base) { std::unique_lock lock(resource_mutex_); replay_.heap_base = heap_base; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 887c95b72d..2109cf47de 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -782,6 +782,8 @@ struct ReplayFunctions { PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr; PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr; PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; + // multiDrawIndirect: one vkCmdDraw*Indirect may take a drawCount above 1; without it each command is its own call. + bool multi_draw_indirect = false; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder @@ -1645,6 +1647,44 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { } } +// The graphics state a command draws with: a Draw's own, or an indirect draw's. +inline const Draw* draw_of(const Command& command) { + if (const auto* draw = std::get_if(&command)) return draw; + if (const auto* indirect = std::get_if(&command)) return indirect->state.get(); + return nullptr; +} + +// The indirect call itself: p.binding is the argument buffer, p.source the count buffer. +inline void emit_indirect(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const Prepared& p, + const ExecuteIndirect& ind) { + const VkDeviceSize arguments = p.binding.buffer_offset + ind.argument_offset; + if (ind.count_buffer) { + const VkDeviceSize count = p.source.buffer_offset + ind.count_offset; + if (ind.kind == IndirectKind::draw) { + vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, count, ind.max_count, + ind.stride); + } else if (ind.kind == IndirectKind::draw_indexed) { + vk.draw_indexed_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, count, + ind.max_count, ind.stride); + } + return; + } + // Without multiDrawIndirect a call draws one command: loop over them. + const std::uint32_t per_call = vk.multi_draw_indirect ? ind.max_count : 1; + if (ind.kind == IndirectKind::draw) { + for (std::uint32_t k = 0; k < ind.max_count; k += per_call) + vk.draw_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, per_call, + ind.stride); + } else if (ind.kind == IndirectKind::draw_indexed) { + for (std::uint32_t k = 0; k < ind.max_count; k += per_call) + vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, + per_call, ind.stride); + } else if (ind.kind == IndirectKind::dispatch) { + for (std::uint32_t k = 0; k < ind.max_count; ++k) + vk.dispatch_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride); + } +} + // Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, Prepared::Attachment& a, VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, @@ -2232,6 +2272,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) return ReplayResult::unsupported; } + // A draw with the list's graphics state: prepared as a Draw is (the argument and count buffers stay in + // p.binding and p.source). + if (ind->state) + if (const auto r = detail::prepare_draw(*ind->state, resolve, vk, p); r != ReplayResult::success) return r; } else if (const auto* build = std::get_if(&command)) { if (vk.xdxr_check) { if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; @@ -2936,29 +2980,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); - } else if (const auto* ind = std::get_if(&command)) { - const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; - if (ind->count_buffer) { - const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; - if (ind->kind == IndirectKind::draw) { - vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, - count, ind->max_count, ind->stride); - } else if (ind->kind == IndirectKind::draw_indexed) { - vk.draw_indexed_indirect_count(command_buffer, p.binding.buffer, arguments, - p.source.buffer, count, ind->max_count, ind->stride); - } - } else { - if (ind->kind == IndirectKind::draw) { - vk.draw_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); - } else if (ind->kind == IndirectKind::draw_indexed) { - vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); - } else if (ind->kind == IndirectKind::dispatch) { - for (std::uint32_t k = 0; k < ind->max_count; ++k) { - vk.dispatch_indirect(command_buffer, p.binding.buffer, - arguments + VkDeviceSize(k) * ind->stride); - } - } - } + } else if (const auto* ind = std::get_if(&command); ind && !ind->state) { + detail::emit_indirect(vk, command_buffer, p, *ind); } else if (const auto* build = std::get_if(&command); build && vk.xdxr_record) { vk.xdxr_record(command_buffer, *build); } else if (const auto* build = std::get_if(&command)) { @@ -3025,7 +3048,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c &p.pipeline.bindless_set, 0, nullptr); vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); - } else if (const auto* draw = std::get_if(&command)) { + } else if (const Draw* draw = detail::draw_of(command)) { auto& prepared_draw = const_cast(p); constexpr VkAccessFlags color_access = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; @@ -3097,8 +3120,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_vertex_buffers2(command_buffer, slot, 1, &p.vertex_buffers[slot], &p.vertex_offsets[slot], &p.vertex_sizes[slot], &p.vertex_strides[slot]); } - if (draw->indexed) { - vk.bind_index_buffer(command_buffer, p.index_buffer, p.index_offset, p.index_type); + if (draw->indexed) vk.bind_index_buffer(command_buffer, p.index_buffer, p.index_offset, p.index_type); + if (const auto* indirect = std::get_if(&command)) { + detail::emit_indirect(vk, command_buffer, p, *indirect); // the arguments hold the counts + } else if (draw->indexed) { vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, draw->first_instance); } else { diff --git a/runtime/test/d3d12_m5_world_test.cpp b/runtime/test/d3d12_m5_world_test.cpp new file mode 100644 index 0000000000..eb57865fc4 --- /dev/null +++ b/runtime/test/d3d12_m5_world_test.cpp @@ -0,0 +1,755 @@ +// Milestone M5 (docs/d3d12_vulkan.md section 6), the synthetic part without mesh shaders: the four things a world +// frame leans on, each through the D3D12 API on the proxy only (as the M2 and M3 tests do), with shaders that are +// translator output (hand-written RDNA2 in test/shaders: vs_m5, ps_m5_inst, vs_m3, ps_m5_flat, vs_m2, ps_m5_tex), and +// every pixel compared with a CPU reference (error 0). +// +// (a) ExecuteIndirect draws. Command signatures for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), argument +// records written by the CPU into an upload buffer, and by the GPU (CopyBufferRegion into default-heap buffers +// placed at non-zero heap offsets, then a COPY_DEST -> INDIRECT_ARGUMENT barrier), argument offsets inside those +// buffers, a count buffer (the draw count is the smaller of it and MaxCommandCount; a count of 0 draws nothing). +// Each record draws one cell of an 8x8 grid (vs_m5.asm places a quad from the vertex index, so StartVertexLocation +// or StartIndexLocation pick the cell; the colour says which cell and which variant). +// (b) Multi-threaded recording. Four std::threads each create their own allocator and list and record 40 draws of +// random rectangles (root constants) at once; the four lists run in one ExecuteCommandLists between a clear list and +// a readback list. The rectangles overlap across the lists, so the list order shows in the pixels. Eight rounds of +// different seeds, each compared with the painter's-algorithm reference. +// (c) Bindless-table pressure. A shader-visible CBV/SRV/UAV heap of 5120 SRVs of 5120 distinct 2x2 textures, one +// descriptor table of all of them. Each of the 5120 pixels of a 128x40 target is a draw (scissor rectangle of one +// pixel) whose root constant is the byte offset of a slot (ps_m5_tex.asm s_loads the T# from table + offset); the +// slots are visited in a scrambled order, so the last slot and every other one is used exactly once. The 5120 T#s +// must all have distinct, non-zero entries in the descriptor hash table. +// (d) Pipeline cache. The same PSO created twice: the second creation must be answered by the device's VkPipelineCache +// (VkPipelineCreationFeedback's application-cache-hit bit, counted by the layer) and add nothing to the cache's +// data, and both PSOs draw identically. +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M5_DIR +#error "LEONIDA_TEST_M5_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +using Pixel = std::array; +constexpr Pixel clear_pixel{255, 0, 255, 255}; // magenta: a pixel nothing drew shows + +struct Image { + UINT width = 0, height = 0; + std::vector pixels; + Image(UINT w, UINT h, Pixel fill = clear_pixel) : width(w), height(h), pixels(std::size_t(w) * h, fill) {} + Pixel& at(UINT x, UINT y) { return pixels[std::size_t(y) * width + x]; } +}; + +// Compare a readback buffer (rows of `pitch` bytes) with the reference; the number of differing pixels. +unsigned compare(const char* what, const std::uint8_t* got, UINT pitch, Image& want) { + unsigned mismatches = 0; + for (UINT y = 0; y < want.height; ++y) + for (UINT x = 0; x < want.width; ++x) { + const std::uint8_t* g = got + std::size_t(y) * pitch + x * 4; + const Pixel& w = want.at(x, y); + if (std::memcmp(g, w.data(), 4) == 0) continue; + if (mismatches++ < 6) + std::fprintf(stderr, "%s pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", what, x, y, g[0], g[1], + g[2], g[3], w[0], w[1], w[2], w[3]); + } + return mismatches; +} + +// vs_m5.asm / ps_m5_inst.asm: cell k (0..63) of the 8x8 grid on a 64x64 target, variant w. +void paint_cell(Image& image, unsigned k, unsigned w) { + const Pixel colour{std::uint8_t(4 * k), std::uint8_t(4 * (63 - k)), std::uint8_t(128 * w), 255}; + for (UINT y = 0; y < 8; ++y) + for (UINT x = 0; x < 8; ++x) image.at((k & 7) * 8 + x, (k >> 3) * 8 + y) = colour; +} + +std::uint32_t next_random(std::uint32_t& state) { // xorshift32 + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; +} + +struct Rect { + UINT x0, y0, x1, y1; + std::uint8_t r, g, b; +}; + +// The eight root constants of vs_m3.asm / ps_m5_flat.asm for a rectangle in pixels of a 64x64 target (one pixel is +// 1/32 of the clip range, so every value is exact). +void rect_constants(const Rect& rect, float (&c)[8]) { + c[0] = -1.0f + float(rect.x0) / 32.0f; + c[1] = 1.0f - float(rect.y0) / 32.0f; + c[2] = -1.0f + float(rect.x1) / 32.0f; + c[3] = 1.0f - float(rect.y1) / 32.0f; + c[4] = 0.0f; + c[5] = float(rect.r) / 255.0f; + c[6] = float(rect.g) / 255.0f; + c[7] = float(rect.b) / 255.0f; +} + +void paint_rect(Image& image, const Rect& rect) { + for (UINT y = rect.y0; y < rect.y1; ++y) + for (UINT x = rect.x0; x < rect.x1; ++x) image.at(x, y) = {rect.r, rect.g, rect.b, 255}; +} + +// What a worker thread of (b) draws: 40 rectangles from its seed. +std::vector worker_rects(unsigned round, unsigned thread) { + std::uint32_t state = 0x9e3779b9u ^ ((round * 8u + thread + 1u) * 2654435761u); + std::vector rects; + for (unsigned i = 0; i < 40; ++i) { + Rect r{}; + r.x0 = next_random(state) % 60; + r.y0 = next_random(state) % 60; + r.x1 = std::min(64, r.x0 + 1 + next_random(state) % 24); + r.y1 = std::min(64, r.y0 + 1 + next_random(state) % 24); + const std::uint32_t colour = next_random(state); + r.r = std::uint8_t(colour); + r.g = std::uint8_t(colour >> 8); + r.b = std::uint8_t(colour >> 16); + rects.push_back(r); + } + return rects; +} + +// (c): the texel t (x + 2y) of texture i. +Pixel texel_colour(unsigned i, unsigned t) { + return {std::uint8_t(i), std::uint8_t((i >> 8) * 40 + t * 50), std::uint8_t(i * 13 + t * 101), 255}; +} +constexpr UINT texture_count = 5120; +constexpr UINT bindless_w = 128, bindless_h = 40; // one pixel per texture +unsigned scrambled(unsigned pixel) { return (pixel * 2003u + 17u) % texture_count; } // 2003 is coprime to 5120 + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + if (!d.bindless) { + std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); + return 77; + } + if (!d.multi_draw_indirect || !d.draw_indirect_count) + std::printf("note: multiDrawIndirect %d, drawIndirectCount %d: the layer's fallbacks are what runs\n", + int(d.multi_draw_indirect), int(d.draw_indirect_count)); + + const std::filesystem::path root_dir = LEONIDA_TEST_M5_DIR; + leonida::ShaderLibrary library; + EXPECT(library.load((root_dir / "spirv").string())); + const auto container_of = [&](const char* name, const char* stage, std::vector& out) { + const auto program = read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); + if (program.size() < 4 || !library.find(stage, leonida::sha256_hex(program))) return false; + out = shader_container(program); + return true; + }; + std::vector vs_cells, ps_cells, vs_rect, ps_flat, vs_quad, ps_tex; + EXPECT(container_of("vs_m5", "vs", vs_cells) && container_of("ps_m5_inst", "ps", ps_cells) && + container_of("vs_m3", "vs", vs_rect) && container_of("ps_m5_flat", "ps", ps_flat) && + container_of("vs_m2", "vs", vs_quad) && container_of("ps_m5_tex", "ps", ps_tex)); + + // Everything the four parts report. + unsigned indirect_mismatches = 0, thread_mismatches = 0, bindless_mismatches = 0, cache_mismatches = 0; + unsigned cells_drawn = 0, thread_draws = 0, distinct_indices = 0; + unsigned cache_first_created = 0, cache_second_created = 0, cache_second_hits = 0; + std::size_t cache_bytes_first = 0, cache_bytes_second = 0; + bool cache_available = false; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.bindless = d.bindless; + info.bindless_partially_bound = d.partially_bound; + info.image_view_min_lod = d.image_view_min_lod; + info.multi_draw_indirect = d.multi_draw_indirect; + info.draw_indirect_count = d.draw_indirect_count; + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + UINT64 fence_value = 0; + // Run `lists` in one ExecuteCommandLists and wait for them. + const auto run = [&](std::initializer_list lists) { + std::vector array(lists); + queue->ExecuteCommandLists(UINT(array.size()), array.data()); + if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + ++fence_value; + return SUCCEEDED(queue->Signal(fence.p, fence_value)) && + SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)); + }; + const auto new_buffer = [&](const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes, D3D12_RESOURCE_STATES state, + Ref& out) { + const auto desc = buffer_desc(bytes); + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + const auto make_root = [&](UINT count, const D3D12_ROOT_PARAMETER* params, Ref& out) { + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {count, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(root_desc); + return !blob.empty() && + SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&out.p))); + }; + const auto pso_desc_of = [&](ID3D12RootSignature* root, const std::vector& vs, + const std::vector& ps) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.VS = {vs.data(), vs.size()}; + desc.PS = {ps.data(), ps.size()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + return desc; + }; + + // Targets in COPY_SOURCE state, one RTV heap slot each, and a readback buffer for each. + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const std::uint64_t rtv_start = reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p); + const UINT rtv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + struct Target { + Ref image, readback; + D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; + UINT width = 0, height = 0, pitch = 0; + }; + const auto make_target = [&](Target& t, UINT slot_index, UINT w, UINT h) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = w; + desc.Height = h; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + t.width = w; + t.height = h; + t.pitch = (w * 4 + 255) & ~255u; + if (FAILED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_SOURCE, nullptr, + IID_PPV_ARGS(&t.image.p)))) + return false; + t.rtv = {SIZE_T(rtv_start + std::uint64_t(slot_index) * rtv_step)}; + device->CreateRenderTargetView(t.image.p, nullptr, t.rtv); + return new_buffer(readback_heap, std::uint64_t(t.pitch) * h, D3D12_RESOURCE_STATE_COPY_DEST, t.readback); + }; + Target cells_target, thread_target, bindless_target, cache_target; + EXPECT(make_target(cells_target, 0, 64, 64) && make_target(thread_target, 1, 64, 64) && + make_target(bindless_target, 2, bindless_w, bindless_h) && make_target(cache_target, 3, 64, 64)); + // COPY_SOURCE -> RENDER_TARGET and a clear; and RENDER_TARGET -> COPY_SOURCE and the copy to the readback. + const FLOAT clear_colour[4] = {1.0f, 0.0f, 1.0f, 1.0f}; + const auto begin_target = [&](ID3D12GraphicsCommandList* list, Target& t) { + const auto barrier = transition(t.image.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &barrier); + list->ClearRenderTargetView(t.rtv, clear_colour, 0, nullptr); + }; + const auto end_target = [&](ID3D12GraphicsCommandList* list, Target& t) { + const auto barrier = transition(t.image.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = t.readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, t.width, t.height, 1, t.pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = t.image.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + }; + const auto new_list = [&](Ref& allocator, Ref& list, + ID3D12PipelineState* pso) { + return SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso, + IID_PPV_ARGS(&list.p))); + }; + const auto set_target_state = [&](ID3D12GraphicsCommandList* list, Target& t) { + const D3D12_VIEWPORT viewport{0, 0, float(t.width), float(t.height), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(t.width), LONG(t.height)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &t.rtv, FALSE, nullptr); + }; + + // ===== (a) ExecuteIndirect ===== + { + Ref root; + EXPECT(make_root(0, nullptr, root)); + auto desc = pso_desc_of(root.p, vs_cells, ps_cells); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + + // The command signatures: strides 16 (draw), 20 and 32 (draw indexed; 32 leaves 12 bytes of padding). + Ref sig_draw, sig_idx20, sig_idx32; + { + D3D12_INDIRECT_ARGUMENT_DESC arg{}; + D3D12_COMMAND_SIGNATURE_DESC sig{}; + sig.NumArgumentDescs = 1; + sig.pArgumentDescs = &arg; + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; + sig.ByteStride = sizeof(D3D12_DRAW_ARGUMENTS); + EXPECT(SUCCEEDED(device->CreateCommandSignature(&sig, nullptr, IID_PPV_ARGS(&sig_draw.p)))); + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED; + sig.ByteStride = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); + EXPECT(SUCCEEDED(device->CreateCommandSignature(&sig, nullptr, IID_PPV_ARGS(&sig_idx20.p)))); + sig.ByteStride = 32; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&sig, nullptr, IID_PPV_ARGS(&sig_idx32.p)))); + } + + // The index buffer: for cell k and variant w, six indices 8k + 4w + {0 1 2 2 1 3} at slot 2k + w. + // Upload buffer 1 (CPU-written draw records at 64 after the index buffer's 1536 bytes ... see below). + Ref index_upload, args_cpu; + EXPECT(new_buffer(upload_heap, 4096, D3D12_RESOURCE_STATE_GENERIC_READ, index_upload)); + EXPECT(new_buffer(upload_heap, 4096, D3D12_RESOURCE_STATE_GENERIC_READ, args_cpu)); + std::uint8_t* mapped = nullptr; + EXPECT(SUCCEEDED(index_upload->Map(0, nullptr, reinterpret_cast(&mapped)))); + auto* indices = reinterpret_cast(mapped); + for (unsigned k = 0; k < 64; ++k) + for (unsigned w = 0; w < 2; ++w) { + const std::uint16_t b = std::uint16_t(8 * k + 4 * w), quad[6] = { + b, std::uint16_t(b + 1), std::uint16_t(b + 2), std::uint16_t(b + 2), std::uint16_t(b + 1), + std::uint16_t(b + 3)}; + std::memcpy(indices + 6 * (2 * k + w), quad, sizeof(quad)); + } + const D3D12_INDEX_BUFFER_VIEW ibv{index_upload->GetGPUVirtualAddress(), 128 * 6 * sizeof(std::uint16_t), + DXGI_FORMAT_R16_UINT}; + + // StartInstanceLocation: the shaders never read the instance index, so a non-zero start changes nothing + // in the pixels; it is there to run the records the way a game's culling pass writes them (with + // drawIndirectFirstInstance, which the device enables where it has it). + const auto first_instance = [&](unsigned r) { return d.draw_indirect_first_instance ? r + 1 : 0u; }; + Image want(64, 64); + // P1: CPU-written records in an upload buffer, argument offset 64, stride 16: strips of 4 vertices. + // Record r draws cell r, variant 1 for r = 5 and 12, with no instances at all for r % 4 == 3, and twice + // (InstanceCount 2) for r = 8. + EXPECT(SUCCEEDED(args_cpu->Map(0, nullptr, reinterpret_cast(&mapped)))); + std::memset(mapped, 0xA5, 4096); // bytes outside the records are never read + for (unsigned r = 0; r < 16; ++r) { + const unsigned w = (r == 5 || r == 12) ? 1 : 0; + const D3D12_DRAW_ARGUMENTS record{4, (r % 4 == 3) ? 0u : (r == 8 ? 2u : 1u), 8 * r + 4 * w, + first_instance(r)}; + std::memcpy(mapped + 64 + r * sizeof(record), &record, sizeof(record)); + if (record.InstanceCount) { paint_cell(want, r, w); ++cells_drawn; } + } + // P2..P5 records and the count words, built in one upload buffer and copied into placed default buffers. + // args2 (placed at 64 KiB): 20 indexed records of stride 32 at 96 for cells 16..35 (variant r % 2, none + // at r = 6), then 4 records at 736 for cells 44..47 (never drawn: count 0), then 6 at 864 for cells + // 48..53 (only the first two drawn: MaxCommandCount 2 against a count of 13). + // counts (placed at 128 KiB): 13 at 8, 0 at 12. + // args3 (placed at 192 KiB): 8 records of stride 20 at 12 for cells 36..43 (variant (r + 1) % 2). + Ref gpu_upload; + EXPECT(new_buffer(upload_heap, 8192, D3D12_RESOURCE_STATE_GENERIC_READ, gpu_upload)); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(gpu_upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memset(up, 0xA5, 8192); + const auto put_indexed = [&](std::uint8_t* at, unsigned cell, unsigned w, unsigned instances) { + const D3D12_DRAW_INDEXED_ARGUMENTS record{6, instances, 6 * (2 * cell + w), 0, first_instance(cell)}; + std::memcpy(at, &record, sizeof(record)); + }; + for (unsigned r = 0; r < 20; ++r) { + put_indexed(up + 96 + r * 32, 16 + r, r % 2, r == 6 ? 0 : 1); + if (r < 13 && r != 6) { paint_cell(want, 16 + r, r % 2); ++cells_drawn; } + } + for (unsigned r = 0; r < 4; ++r) put_indexed(up + 736 + r * 32, 44 + r, 0, 1); + for (unsigned r = 0; r < 6; ++r) put_indexed(up + 864 + r * 32, 48 + r, 1, 1); + paint_cell(want, 48, 1); + paint_cell(want, 49, 1); + cells_drawn += 2; + std::uint32_t* counts = reinterpret_cast(up + 4096); + counts[2] = 13; + counts[3] = 0; + for (unsigned r = 0; r < 8; ++r) { + put_indexed(up + 4096 + 256 + 12 + r * 20, 36 + r, (r + 1) % 2, 1); + paint_cell(want, 36 + r, (r + 1) % 2); + ++cells_drawn; + } + + const D3D12_HEAP_DESC heap_desc{256 * 1024, {D3D12_HEAP_TYPE_DEFAULT}, 64 * 1024, + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS}; + Ref heap; + EXPECT(SUCCEEDED(device->CreateHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + Ref args2, count_buffer, args3; + const auto placed = [&](UINT64 offset, UINT64 bytes, Ref& out) { + const auto desc2 = buffer_desc(bytes); + return SUCCEEDED(device->CreatePlacedResource(heap.p, offset, &desc2, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&out.p))); + }; + EXPECT(placed(64 * 1024, 4096, args2) && placed(128 * 1024, 256, count_buffer) && + placed(192 * 1024, 4096, args3)); + + Ref allocator; + Ref list; + EXPECT(new_list(allocator, list, pso.p)); + list->CopyBufferRegion(args2.p, 0, gpu_upload.p, 0, 2048); + list->CopyBufferRegion(count_buffer.p, 0, gpu_upload.p, 4096, 256); + list->CopyBufferRegion(args3.p, 0, gpu_upload.p, 4096 + 256, 256); + const D3D12_RESOURCE_BARRIER to_args[3] = { + transition(args2.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + transition(count_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + transition(args3.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT)}; + list->ResourceBarrier(3, to_args); + begin_target(list.p, cells_target); + list->SetGraphicsRootSignature(root.p); + set_target_state(list.p, cells_target); + list->IASetIndexBuffer(&ibv); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); + list->ExecuteIndirect(sig_draw.p, 16, args_cpu.p, 64, nullptr, 0); // P1 + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->ExecuteIndirect(sig_idx32.p, 20, args2.p, 96, count_buffer.p, 8); // P2: count 13 of 20 + list->ExecuteIndirect(sig_idx20.p, 8, args3.p, 12, nullptr, 0); // P3: no count buffer + list->ExecuteIndirect(sig_idx32.p, 4, args2.p, 736, count_buffer.p, 12); // P4: count 0 + list->ExecuteIndirect(sig_idx32.p, 2, args2.p, 864, count_buffer.p, 8); // P5: min(2, 13) + end_target(list.p, cells_target); + EXPECT(list->Close() == S_OK); + EXPECT(run({list.p})); + void* data = nullptr; + EXPECT(SUCCEEDED(cells_target.readback->Map(0, nullptr, &data))); + indirect_mismatches = compare("indirect", static_cast(data), cells_target.pitch, want); + } + + // ===== (b) multi-threaded recording ===== + { + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {0, 0, 8}; + param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + Ref root; + EXPECT(make_root(1, ¶m, root)); + const auto desc = pso_desc_of(root.p, vs_rect, ps_flat); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + + constexpr unsigned threads = 4, rounds = 8; + std::vector first_round_bytes; + for (unsigned round = 0; round < rounds; ++round) { + Ref allocators[threads]; + Ref lists[threads]; + std::atomic ready{0}; + std::atomic go{false}; + std::atomic failures{0}; + std::vector pool; + for (unsigned t = 0; t < threads; ++t) + pool.emplace_back([&, t] { + ready.fetch_add(1); + while (!go.load()) std::this_thread::yield(); // all four start recording together + if (!new_list(allocators[t], lists[t], pso.p)) { failures.fetch_add(1); return; } + ID3D12GraphicsCommandList* l = lists[t].p; + l->SetGraphicsRootSignature(root.p); + set_target_state(l, thread_target); + l->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); + for (const Rect& rect : worker_rects(round, t)) { + float constants[8]; + rect_constants(rect, constants); + l->SetGraphicsRoot32BitConstants(0, 8, constants, 0); + l->DrawInstanced(4, 1, 0, 0); + } + if (l->Close() != S_OK) failures.fetch_add(1); + }); + while (ready.load() < threads) std::this_thread::yield(); + go.store(true); + for (auto& thread : pool) thread.join(); + EXPECT(!failures.load()); + + Ref first_allocator, last_allocator; + Ref first, last; + EXPECT(new_list(first_allocator, first, nullptr) && new_list(last_allocator, last, nullptr)); + begin_target(first.p, thread_target); + EXPECT(first->Close() == S_OK); + end_target(last.p, thread_target); + EXPECT(last->Close() == S_OK); + // The clear list, the four workers (in thread order) and the readback list in one call. + EXPECT(run({first.p, lists[0].p, lists[1].p, lists[2].p, lists[3].p, last.p})); + Image want(64, 64); + for (unsigned t = 0; t < threads; ++t) + for (const Rect& rect : worker_rects(round, t)) { paint_rect(want, rect); ++thread_draws; } + void* data = nullptr; + EXPECT(SUCCEEDED(thread_target.readback->Map(0, nullptr, &data))); + thread_mismatches += compare("threads", static_cast(data), thread_target.pitch, want); + } + } + + // ===== (c) bindless-table pressure ===== + { + D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_count, 0, 0, 0}; + D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &srv_range}; + params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &sampler_range}; + params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {0, 0, 1}; + params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + Ref root; + EXPECT(make_root(3, params, root)); + const auto desc = pso_desc_of(root.p, vs_quad, ps_tex); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, texture_count, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap, sampler_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p)))); + const std::uint64_t srv_cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t srv_gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const std::uint64_t sampler_cpu = reinterpret_cast(slot(sampler_heap.p, 9))(sampler_heap.p); + const std::uint64_t sampler_gpu = reinterpret_cast(slot(sampler_heap.p, 10))(sampler_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(srv_cpu && sampler_cpu && srv_gpu >= 0x10000 && sampler_gpu >= 0x10000 && step >= 32); + EXPECT(srv_gpu < (1ull << 32) && sampler_gpu < (1ull << 32)); + + D3D12_SAMPLER_DESC sampler_desc{}; + sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler_desc.AddressU = sampler_desc.AddressV = sampler_desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler_desc.MaxAnisotropy = 1; + sampler_desc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; + sampler_desc.MaxLOD = D3D12_FLOAT32_MAX; + device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu)}); + + // 5120 textures of 2x2, 512 bytes apiece in the upload buffer (rows at the 256-byte pitch). + Ref upload; + EXPECT(new_buffer(upload_heap, std::uint64_t(texture_count) * 512, D3D12_RESOURCE_STATE_GENERIC_READ, upload)); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + D3D12_RESOURCE_DESC texture_desc{}; + texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture_desc.Width = texture_desc.Height = 2; + texture_desc.DepthOrArraySize = 1; + texture_desc.MipLevels = 1; + texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_desc.SampleDesc.Count = 1; + std::vector> textures(texture_count); + for (UINT i = 0; i < texture_count; ++i) { + for (unsigned t = 0; t < 4; ++t) { + const Pixel c = texel_colour(i, t); + std::memcpy(up + std::size_t(i) * 512 + (t / 2) * 256 + (t % 2) * 4, c.data(), 4); + } + if (FAILED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&textures[i].p)))) { + std::fprintf(stderr, "texture %u of %u could not be created\n", i, texture_count); + return 1; + } + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D = {0, 1, 0, 0.0f}; + device->CreateShaderResourceView(textures[i].p, &srv, + D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu + std::uint64_t(i) * step)}); + } + // The hash table: every T# has an entry and no two share an index. + std::set seen; + for (UINT i = 0; i < texture_count; ++i) { + std::uint32_t key[8]; + std::memcpy(key, reinterpret_cast(srv_cpu + std::uint64_t(i) * step), 32); + const std::uint32_t index = rt::d3d12::bindless_hash_lookup(device.p, key); + if (index) seen.insert(index); + } + distinct_indices = unsigned(seen.size()); + std::fprintf(stderr, "hash table: %u of %u T#s have distinct non-zero bindless indices\n", distinct_indices, + texture_count); + EXPECT(distinct_indices == texture_count); + + Ref allocator; + Ref list; + EXPECT(new_list(allocator, list, pso.p)); + for (UINT i = 0; i < texture_count; ++i) { + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = textures[i].p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = upload.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = {std::uint64_t(i) * 512, {DXGI_FORMAT_R8G8B8A8_UNORM, 2, 2, 1, 256}}; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + std::vector barriers; + for (UINT i = 0; i < texture_count; ++i) + barriers.push_back(transition(textures[i].p, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + list->ResourceBarrier(UINT(barriers.size()), barriers.data()); + begin_target(list.p, bindless_target); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p, sampler_heap.p}; + list->SetDescriptorHeaps(2, heaps); + set_target_state(list.p, bindless_target); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + Ref index_upload; + EXPECT(new_buffer(upload_heap, 256, D3D12_RESOURCE_STATE_GENERIC_READ, index_upload)); + std::uint8_t* index_data = nullptr; + EXPECT(SUCCEEDED(index_upload->Map(0, nullptr, reinterpret_cast(&index_data)))); + const std::uint16_t quad[6] = {0, 1, 2, 2, 1, 3}; + std::memcpy(index_data, quad, sizeof(quad)); + const D3D12_INDEX_BUFFER_VIEW ibv{index_upload->GetGPUVirtualAddress(), sizeof(quad), DXGI_FORMAT_R16_UINT}; + list->IASetIndexBuffer(&ibv); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu}); + list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu}); + Image want(bindless_w, bindless_h); + for (UINT p = 0; p < bindless_w * bindless_h; ++p) { + const UINT x = p % bindless_w, y = p / bindless_w, texture = scrambled(p); + const D3D12_RECT scissor{LONG(x), LONG(y), LONG(x + 1), LONG(y + 1)}; + list->RSSetScissorRects(1, &scissor); + const UINT offset = texture * step; + list->SetGraphicsRoot32BitConstants(2, 1, &offset, 0); + list->DrawIndexedInstanced(6, 1, 0, 0, 0); + const unsigned texel = (x >= bindless_w / 2 ? 1u : 0u) + (y >= bindless_h / 2 ? 2u : 0u); + want.at(x, y) = texel_colour(texture, texel); + } + bool last_used = false; + for (UINT p = 0; p < texture_count; ++p) last_used |= scrambled(p) == texture_count - 1; + EXPECT(last_used); + end_target(list.p, bindless_target); + EXPECT(list->Close() == S_OK); + EXPECT(run({list.p})); + void* data = nullptr; + EXPECT(SUCCEEDED(bindless_target.readback->Map(0, nullptr, &data))); + bindless_mismatches = compare("bindless", static_cast(data), bindless_target.pitch, want); + } + + // ===== (d) pipeline cache ===== + { + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {0, 0, 8}; + param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + Ref root; + EXPECT(make_root(1, ¶m, root)); + auto desc = pso_desc_of(root.p, vs_rect, ps_flat); + // A state nothing above used, so the first creation has nothing to be answered from: no alpha written + // (the target is cleared to alpha 1 and the shader writes 1, so the pixels do not change). + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0x7; + const auto before = rt::d3d12::pipeline_cache_stats(device.p); + Ref first_pso, second_pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&first_pso.p)))); + const auto after_first = rt::d3d12::pipeline_cache_stats(device.p); + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&second_pso.p)))); + const auto after_second = rt::d3d12::pipeline_cache_stats(device.p); + cache_available = after_second.available; + cache_first_created = after_first.created - before.created; + cache_second_created = after_second.created - after_first.created; + cache_second_hits = after_second.hits - after_first.hits; + cache_bytes_first = after_first.bytes; + cache_bytes_second = after_second.bytes; + std::fprintf(stderr, "pipeline cache: available %d; first creation %u pipeline(s), %u hit(s); second %u, %u " + "hit(s); cache data %zu -> %zu bytes (before: %zu)\n", + int(cache_available), cache_first_created, after_first.hits - before.hits, cache_second_created, + cache_second_hits, cache_bytes_first, cache_bytes_second, before.bytes); + EXPECT(first_pso.p != second_pso.p); + + // Both PSOs draw three overlapping rectangles, and the pixels are what the CPU says. + const Rect scene[3] = {{4, 4, 40, 30, 200, 30, 90}, {20, 16, 60, 58, 10, 220, 120}, {30, 2, 34, 62, 255, 255, 0}}; + Image want(64, 64); + for (const Rect& rect : scene) paint_rect(want, rect); + std::vector drawn[2]; + ID3D12PipelineState* psos[2] = {first_pso.p, second_pso.p}; + for (unsigned which = 0; which < 2; ++which) { + Ref allocator; + Ref list; + EXPECT(new_list(allocator, list, psos[which])); + begin_target(list.p, cache_target); + list->SetGraphicsRootSignature(root.p); + set_target_state(list.p, cache_target); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); + for (const Rect& rect : scene) { + float constants[8]; + rect_constants(rect, constants); + list->SetGraphicsRoot32BitConstants(0, 8, constants, 0); + list->DrawInstanced(4, 1, 0, 0); + } + end_target(list.p, cache_target); + EXPECT(list->Close() == S_OK); + EXPECT(run({list.p})); + void* data = nullptr; + EXPECT(SUCCEEDED(cache_target.readback->Map(0, nullptr, &data))); + cache_mismatches += compare(which ? "cache (second PSO)" : "cache (first PSO)", + static_cast(data), cache_target.pitch, want); + drawn[which].assign(static_cast(data), + static_cast(data) + std::size_t(cache_target.pitch) * 64); + } + EXPECT(drawn[0] == drawn[1]); + } + + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) >= 1); + } + + EXPECT(!indirect_mismatches); + EXPECT(!thread_mismatches); + EXPECT(!bindless_mismatches); + EXPECT(!cache_mismatches); + if (cache_available) { + EXPECT(cache_first_created >= 1); + EXPECT(cache_second_created == cache_first_created); + EXPECT(cache_second_hits == cache_second_created); // the second creation was answered by the cache + EXPECT(cache_bytes_second == cache_bytes_first); // and added nothing to it + } else { + std::printf("note: no VkPipelineCreationFeedback (Vulkan 1.3) or no VkPipelineCache: cache hits not checked\n"); + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("M5 (without mesh shaders): %u cells drawn by 5 ExecuteIndirect calls (draw and draw-indexed signatures, " + "CPU- and GPU-written arguments at offsets in placed buffers, count buffer, count 0 and count above " + "MaxCommandCount), %u rectangles recorded on 4 threads x 8 rounds, %u pixels each drawn from its own " + "texture out of %u SRVs (%u distinct hash-table indices), a PSO created twice (%u of %u creations " + "answered by the pipeline cache): every pixel matched the CPU reference (error 0)\n", + cells_drawn, thread_draws, bindless_w * bindless_h, texture_count, distinct_indices, cache_second_hits, + cache_second_created); + return 0; +} diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index ccf7be584d..e2436c9742 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -460,6 +460,7 @@ int main() { static std::vector offsets; ReplayFunctions vk{}; + vk.multi_draw_indirect = true; // one call takes all the records vk.draw_indirect = [](VkCommandBuffer, VkBuffer, VkDeviceSize offset, std::uint32_t, std::uint32_t) { offsets.push_back(offset); }; @@ -485,6 +486,21 @@ int main() { const std::vector expected{260, 264, 268, 516, 272, 520, 276, 296}; CHECK(offsets == expected); + // Without multiDrawIndirect each record is a call of its own. + { + const std::vector kept = offsets; // the later checks go on from these + ReplayFunctions single = vk; + single.multi_draw_indirect = false; + offsets.clear(); + CommandList one; + CHECK(one.execute_indirect({IndirectKind::draw, 16, 2, 1, 4, 0, 0})); + CHECK(one.execute_indirect({IndirectKind::draw_indexed, 20, 3, 1, 8, 0, 0})); + CHECK(one.close()); + CHECK(replay(one, VK_NULL_HANDLE, resolve, single) == ReplayResult::success); + CHECK((offsets == std::vector{260, 276, 264, 284, 304})); + offsets = kept; + } + // Reject invalid spans before invoking Vulkan, including after adding the backing-buffer base. const auto rejected = [&](const ExecuteIndirect& command) { CommandList invalid; diff --git a/runtime/test/shaders/ps_m5_flat.asm b/runtime/test/shaders/ps_m5_flat.asm new file mode 100644 index 0000000000..c924f6d689 --- /dev/null +++ b/runtime/test/shaders/ps_m5_flat.asm @@ -0,0 +1,11 @@ +; M5 pixel shader for the multi-threaded lists: a flat colour from root constants (the root signature of vs_m3.asm, +; [0], eight 32-bit constants). Run: d3d12_m5_world_test. +; User data: s5, s6, s7 = c0, c1, c2 (floats, k/255). mrt0 = (c0, c1, c2, 1.0) +; fssm-at: 0x10 +; fssm-data: 0x35534650 0x20535020 +v_mov_b32_e32 v2, s5 +v_mov_b32_e32 v3, s6 +v_mov_b32_e32 v4, s7 +v_mov_b32_e32 v5, 1.0 +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_m5_inst.asm b/runtime/test/shaders/ps_m5_inst.asm new file mode 100644 index 0000000000..a3b808c1b7 --- /dev/null +++ b/runtime/test/shaders/ps_m5_inst.asm @@ -0,0 +1,24 @@ +; M5 pixel shader for the indirect draws: a colour from the cell number and the variant the vertex shader passed. +; Run: d3d12_m5_world_test. +; attr0.xy = (k, variant), k = 0..63, variant 0 or 1 (constant over the quad; the +0.5 and the truncation take the +; interpolation's rounding error out) +; mrt0 = (4k, 4(63 - k), 128 * variant, 255) / 255 +; fssm-at: 0x10 +; fssm-data: 0x35535350 0x20535020 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_add_f32_e32 v2, 0.5, v2 +v_add_f32_e32 v3, 0.5, v3 +v_cvt_u32_f32_e32 v2, v2 +v_cvt_u32_f32_e32 v3, v3 +v_cvt_f32_u32_e32 v4, v2 +v_cvt_f32_u32_e32 v5, v3 +v_sub_f32_e32 v6, 0x427c0000, v4 +v_mul_f32_e32 v7, 0x3c808081, v4 +v_mul_f32_e32 v8, 0x3c808081, v6 +v_mul_f32_e32 v9, 0x3f008081, v5 +v_mov_b32_e32 v10, 1.0 +exp mrt0 v7, v8, v9, v10 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_m5_tex.asm b/runtime/test/shaders/ps_m5_tex.asm new file mode 100644 index 0000000000..66b4c3c55f --- /dev/null +++ b/runtime/test/shaders/ps_m5_tex.asm @@ -0,0 +1,19 @@ +; M5 pixel shader for the bindless-table pressure draws: samples the texture whose T# sits at a byte offset in the +; SRV table, the offset coming from a root constant. Run: d3d12_m5_world_test. +; User data from the root signature ([0] a table of SRVs, [1] a table of one sampler, [2] one 32-bit constant): +; s[0:1] = console VA of the SRV table's first slot; s[2:3] = console VA of the sampler table's slot +; s4 = byte offset of the slot (index * descriptor increment size) +; attr0.xy = (u, v), 0..1 over the quad. mrt0 = the texel under the pixel +; fssm-at: 0x10 +; fssm-data: 0x35535450 0x20535020 +s_load_dwordx8 s[8:15], s[0:1], s4 +s_load_dwordx4 s[16:19], s[2:3], 0x0 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/runtime/test/shaders/vs_m5.asm b/runtime/test/shaders/vs_m5.asm new file mode 100644 index 0000000000..c21712e30c --- /dev/null +++ b/runtime/test/shaders/vs_m5.asm @@ -0,0 +1,35 @@ +; M5 vertex shader: a quad from the vertex index, placed in an 8x8 grid of cells by the bits above the corner. Run: +; d3d12_m5_world_test (found by the SHA-256 of its FSSM program, as vs_m2 is). +; v0 = VertexIndex: the test draws triangle strips of vertices 8k + 4w + 0..3 and indexed lists 8k + 4w + {0 1 2 2 1 3} +; (base vertex 0), for cell k = 0..63 and variant w = 0, 1. Nothing here reads the instance index, so the result does +; not depend on whether StartInstanceLocation is part of it. +; corner u = v0 & 1, v = (v0 >> 1) & 1; variant w = (v0 >> 2) & 1; cell k = (v0 >> 3) & 63, cx = k & 7, cy = k >> 3 +; pos0 = (-1 + (cx + u) / 4, 1 - (cy + v) / 4, 0, 1): a cell is a quarter of the clip range per side, so every +; corner is a multiple of 1/4 and each operation is exact however it is fused +; param0 = (k, w, 0, 1) +; fssm-at: 0x10 +; fssm-data: 0x35534d56 0x20535620 +v_and_b32_e32 v1, 1, v0 +v_and_b32_e32 v2, 2, v0 +v_lshrrev_b32_e32 v7, 2, v0 +v_and_b32_e32 v7, 1, v7 +v_lshrrev_b32_e32 v12, 3, v0 +v_and_b32_e32 v12, 63, v12 +v_and_b32_e32 v8, 7, v12 +v_lshrrev_b32_e32 v9, 3, v12 +v_cvt_f32_u32_e32 v1, v1 +v_cvt_f32_u32_e32 v2, v2 +v_mul_f32_e32 v2, 0.5, v2 +v_cvt_f32_u32_e32 v8, v8 +v_cvt_f32_u32_e32 v9, v9 +v_cvt_f32_u32_e32 v7, v7 +v_cvt_f32_u32_e32 v12, v12 +v_fma_f32 v8, v8, 0.25, -1.0 +v_fma_f32 v9, v9, -0.25, 1.0 +v_fma_f32 v4, v1, 0.25, v8 +v_fma_f32 v5, v2, -0.25, v9 +v_mov_b32_e32 v6, 0 +v_mov_b32_e32 v10, 1.0 +exp pos0 v4, v5, v6, v10 done +exp param0 v12, v7, v6, v10 +s_endpgm diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 635a3107b5..52a647e736 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -95,6 +95,9 @@ class Device { // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; + bool multi_draw_indirect = false; // multiDrawIndirect enabled, where the device has it + bool draw_indirect_count = false; // drawIndirectCount (Vulkan 1.2) enabled, where the device has it + bool draw_indirect_first_instance = false; // drawIndirectFirstInstance enabled: indirect records may start at an instance bool shader_fma = false; // VK_KHR_shader_fma and shaderFmaFloat32 enabled (OpFmaKHR, rdna2spirv.py --fma khr) bool occlusion_query_precise = false; // occlusionQueryPrecise enabled bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled @@ -347,6 +350,8 @@ class Device { VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; + enable12.drawIndirectCount = features12.drawIndirectCount; // ExecuteIndirect with a count buffer + draw_indirect_count = features12.drawIndirectCount == VK_TRUE; buffer_device_address = request_buffer_device_address && features12.bufferDeviceAddress == VK_TRUE; enable12.bufferDeviceAddress = buffer_device_address; storage_buffer_8bit = features12.storageBuffer8BitAccess == VK_TRUE; @@ -380,6 +385,10 @@ class Device { bc = features.features.textureCompressionBC == VK_TRUE; enable.shaderSampledImageArrayDynamicIndexing = bindless; enable.shaderStorageImageArrayDynamicIndexing = bindless; + enable.multiDrawIndirect = features.features.multiDrawIndirect; // ExecuteIndirect: several commands per call + multi_draw_indirect = features.features.multiDrawIndirect == VK_TRUE; + enable.drawIndirectFirstInstance = features.features.drawIndirectFirstInstance; + draw_indirect_first_instance = features.features.drawIndirectFirstInstance == VK_TRUE; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 7209c364c3..197e2fa7dd 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -542,7 +542,9 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", - "ps_m3_post": "d3d12_m3_frame_test"} + "ps_m3_post": "d3d12_m3_frame_test", + "vs_m5": "d3d12_m5_world_test", "ps_m5_inst": "d3d12_m5_world_test", + "ps_m5_flat": "d3d12_m5_world_test", "ps_m5_tex": "d3d12_m5_world_test"} # Shaders a selected test draws with, built even when the filter leaves them out (#192). From 77d86d0c710a1aa30875d639096bfee733ec4471 Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:51:24 +0100 Subject: [PATCH 02/17] M5 review fixes: raw indirect flag, maxDrawIndirectCount chunking, feature flags, test leniency - A draw-kind ExecuteIndirect with no graphics state is unsupported at prepare unless it is marked raw (ExecuteIndirect::raw, set by the unit tests that wrap the call in rendering themselves). - Calls take at most VkPhysicalDeviceLimits::maxDrawIndirectCount records (ReplayFunctions, VulkanDeviceInfo). - VulkanDeviceInfo::draw_indirect_first_instance is recorded; the layer logs once when it is absent. - VulkanDeviceInfo::draw_indirect_count defaults to false. - d3d12_m5_world_test: without drawIndirectCount the count-buffer calls are left out; pipeline-cache checks only run when the driver returns valid creation feedback, and size equality only when both sizes are known. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.h | 11 ++++-- runtime/shims/d3d12_vulkan_device.cpp | 8 ++++- runtime/src/command_list.h | 4 +++ runtime/src/vulkan_backend.h | 3 +- runtime/src/vulkan_replay.h | 13 ++++--- runtime/test/d3d12_indirect_rt_test.cpp | 2 +- runtime/test/d3d12_m5_world_test.cpp | 45 ++++++++++++++++--------- runtime/test/d3d12_state_map_test.cpp | 12 +++---- runtime/test/vk_test_device.h | 2 ++ 9 files changed, 69 insertions(+), 31 deletions(-) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index ffa5a802f5..91e9e52ce8 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -93,9 +93,14 @@ struct VulkanDeviceInfo { // multiDrawIndirect is enabled: ExecuteIndirect hands all its commands to one vkCmdDraw*Indirect. Without it the // layer issues one call per command (a drawCount above 1 is invalid without the feature). bool multi_draw_indirect = false; - // drawIndirectCount (Vulkan 1.2) is enabled: ExecuteIndirect with a count buffer. True unless the creator says - // otherwise (it is the way callers that never set this behaved); without it such a call is unsupported. - bool draw_indirect_count = true; + // drawIndirectCount (Vulkan 1.2) is enabled: ExecuteIndirect with a count buffer. Without it such a call is + // unsupported. + bool draw_indirect_count = false; + // drawIndirectFirstInstance is enabled: indirect records may have a StartInstanceLocation other than 0. Without + // it such a record is invalid Vulkan (the layer cannot see inside the GPU buffer, so it only says so once). + bool draw_indirect_first_instance = false; + // VkPhysicalDeviceLimits::maxDrawIndirectCount (a call takes at most this many records); 0 means unknown, no cap. + std::uint32_t max_draw_indirect_count = 0; bool sampler_mirror_clamp_to_edge = false; bool sampler_filter_minmax = false; // VK_KHR_calibrated_timestamps or VK_EXT_calibrated_timestamps is enabled on `device` (QueueClock). diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 23ed4c699f..0b7549447a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3051,7 +3051,11 @@ class Device final info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address); - state_.context->set_indirect_features(info.multi_draw_indirect, info.draw_indirect_count); + state_.context->set_indirect_features(info.multi_draw_indirect, info.draw_indirect_count, + info.max_draw_indirect_count ? info.max_draw_indirect_count : UINT32_MAX); + if (!info.draw_indirect_first_instance) + std::fprintf(stderr, "[rt] d3d12: drawIndirectFirstInstance is not enabled: ExecuteIndirect records with " + "a StartInstanceLocation other than 0 are invalid\n"); if (info.buffer_device_address && state_.context->loaded() && !create_arena()) std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); if (info.conditional_rendering) { @@ -6065,6 +6069,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { info.multi_draw_indirect = chosen_features.multiDrawIndirect == VK_TRUE; info.draw_indirect_count = chosen12.drawIndirectCount == VK_TRUE; enable12.drawIndirectCount = info.draw_indirect_count; + info.draw_indirect_first_instance = chosen_features.drawIndirectFirstInstance == VK_TRUE; + info.max_draw_indirect_count = chosen.limits.maxDrawIndirectCount; info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; info.sampler_filter_minmax = chosen12.samplerFilterMinmax; enable12.runtimeDescriptorArray = info.bindless; diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index db4ce718ab..bbc56a350a 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -571,6 +571,10 @@ struct ExecuteIndirect { // binds the pipeline and the dynamic state as for a Draw, and issues the indirect draw. Null: the caller has set // all that up (a raw indirect call), as the unit tests of the indirect path do. std::shared_ptr state; + // A draw kind without `state` is a raw call that the caller has wrapped in rendering and bound a pipeline for + // (the unit tests of the indirect path do); only then does replay issue it as it is. Otherwise a draw kind with + // no state is unsupported: a bare vkCmdDraw*Indirect outside a render pass is invalid Vulkan. + bool raw = false; }; // Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 41a9c3099a..a22a8127f6 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -867,8 +867,9 @@ class VulkanContext { // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely. // The indirect-draw features enabled on the device (VulkanDeviceInfo::multi_draw_indirect / draw_indirect_count). - void set_indirect_features(bool multi_draw, bool draw_count) { + void set_indirect_features(bool multi_draw, bool draw_count, std::uint32_t max_draw_count = UINT32_MAX) { replay_.multi_draw_indirect = multi_draw; + replay_.max_draw_indirect_count = max_draw_count; if (!draw_count) replay_.draw_indirect_count = replay_.draw_indexed_indirect_count = nullptr; } diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 2109cf47de..01aef4a9da 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -784,6 +784,8 @@ struct ReplayFunctions { PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; // multiDrawIndirect: one vkCmdDraw*Indirect may take a drawCount above 1; without it each command is its own call. bool multi_draw_indirect = false; + // VkPhysicalDeviceLimits::maxDrawIndirectCount: a call takes at most this many records. + std::uint32_t max_draw_indirect_count = UINT32_MAX; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder @@ -1670,15 +1672,17 @@ inline void emit_indirect(const ReplayFunctions& vk, VkCommandBuffer command_buf return; } // Without multiDrawIndirect a call draws one command: loop over them. - const std::uint32_t per_call = vk.multi_draw_indirect ? ind.max_count : 1; + // and a call takes at most maxDrawIndirectCount records. + const std::uint32_t per_call = + vk.multi_draw_indirect ? std::max(1, std::min(ind.max_count, vk.max_draw_indirect_count)) : 1; if (ind.kind == IndirectKind::draw) { for (std::uint32_t k = 0; k < ind.max_count; k += per_call) - vk.draw_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, per_call, - ind.stride); + vk.draw_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, + std::min(per_call, ind.max_count - k), ind.stride); } else if (ind.kind == IndirectKind::draw_indexed) { for (std::uint32_t k = 0; k < ind.max_count; k += per_call) vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, - per_call, ind.stride); + std::min(per_call, ind.max_count - k), ind.stride); } else if (ind.kind == IndirectKind::dispatch) { for (std::uint32_t k = 0; k < ind.max_count; ++k) vk.dispatch_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride); @@ -2272,6 +2276,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) return ReplayResult::unsupported; } + if (ind->kind != IndirectKind::dispatch && !ind->state && !ind->raw) return ReplayResult::unsupported; // A draw with the list's graphics state: prepared as a Draw is (the argument and count buffers stay in // p.binding and p.source). if (ind->state) diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp index 1ed9a4d635..ef4a880910 100644 --- a/runtime/test/d3d12_indirect_rt_test.cpp +++ b/runtime/test/d3d12_indirect_rt_test.cpp @@ -498,7 +498,7 @@ int main() { leonida::CommandList ir; ir.execute_indirect({leonida::IndirectKind::draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u, rt::d3d12::resource_id(arg_buf), 0, rt::d3d12::resource_id(count_buf), - count_offset}); + count_offset, nullptr, true}); ir.close(); VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; diff --git a/runtime/test/d3d12_m5_world_test.cpp b/runtime/test/d3d12_m5_world_test.cpp index eb57865fc4..972970beca 100644 --- a/runtime/test/d3d12_m5_world_test.cpp +++ b/runtime/test/d3d12_m5_world_test.cpp @@ -157,9 +157,13 @@ int main() { std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); return 77; } - if (!d.multi_draw_indirect || !d.draw_indirect_count) - std::printf("note: multiDrawIndirect %d, drawIndirectCount %d: the layer's fallbacks are what runs\n", - int(d.multi_draw_indirect), int(d.draw_indirect_count)); + // Without multiDrawIndirect the layer issues one call per record, which is still checked. Without + // drawIndirectCount the calls that take a count buffer (P2, P4, P5) cannot run, and are left out. + const bool counts = d.draw_indirect_count; + if (!d.multi_draw_indirect) + std::printf("note: no multiDrawIndirect: the layer issues one call per record\n"); + if (!counts) + std::printf("note: no drawIndirectCount: the count-buffer calls (P2, P4, P5) are not run\n"); const std::filesystem::path root_dir = LEONIDA_TEST_M5_DIR; leonida::ShaderLibrary library; @@ -195,6 +199,8 @@ int main() { info.image_view_min_lod = d.image_view_min_lod; info.multi_draw_indirect = d.multi_draw_indirect; info.draw_indirect_count = d.draw_indirect_count; + info.draw_indirect_first_instance = d.draw_indirect_first_instance; + info.max_draw_indirect_count = d.max_draw_indirect_count; info.shader_dir = (root_dir / "spirv").string(); ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); @@ -398,13 +404,15 @@ int main() { }; for (unsigned r = 0; r < 20; ++r) { put_indexed(up + 96 + r * 32, 16 + r, r % 2, r == 6 ? 0 : 1); - if (r < 13 && r != 6) { paint_cell(want, 16 + r, r % 2); ++cells_drawn; } + if (counts && r < 13 && r != 6) { paint_cell(want, 16 + r, r % 2); ++cells_drawn; } } for (unsigned r = 0; r < 4; ++r) put_indexed(up + 736 + r * 32, 44 + r, 0, 1); for (unsigned r = 0; r < 6; ++r) put_indexed(up + 864 + r * 32, 48 + r, 1, 1); - paint_cell(want, 48, 1); - paint_cell(want, 49, 1); - cells_drawn += 2; + if (counts) { + paint_cell(want, 48, 1); + paint_cell(want, 49, 1); + cells_drawn += 2; + } std::uint32_t* counts = reinterpret_cast(up + 4096); counts[2] = 13; counts[3] = 0; @@ -445,10 +453,10 @@ int main() { list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); list->ExecuteIndirect(sig_draw.p, 16, args_cpu.p, 64, nullptr, 0); // P1 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - list->ExecuteIndirect(sig_idx32.p, 20, args2.p, 96, count_buffer.p, 8); // P2: count 13 of 20 + if (counts) list->ExecuteIndirect(sig_idx32.p, 20, args2.p, 96, count_buffer.p, 8); // P2: count 13 of 20 list->ExecuteIndirect(sig_idx20.p, 8, args3.p, 12, nullptr, 0); // P3: no count buffer - list->ExecuteIndirect(sig_idx32.p, 4, args2.p, 736, count_buffer.p, 12); // P4: count 0 - list->ExecuteIndirect(sig_idx32.p, 2, args2.p, 864, count_buffer.p, 8); // P5: min(2, 13) + if (counts) list->ExecuteIndirect(sig_idx32.p, 4, args2.p, 736, count_buffer.p, 12); // P4: count 0 + if (counts) list->ExecuteIndirect(sig_idx32.p, 2, args2.p, 864, count_buffer.p, 8); // P5: min(2, 13) end_target(list.p, cells_target); EXPECT(list->Close() == S_OK); EXPECT(run({list.p})); @@ -732,13 +740,20 @@ int main() { EXPECT(!thread_mismatches); EXPECT(!bindless_mismatches); EXPECT(!cache_mismatches); - if (cache_available) { - EXPECT(cache_first_created >= 1); + // The counters only move when the driver returns valid VkPipelineCreationFeedback (software ICDs may not); then + // only the pixels, compared above, are checked. + const bool feedback_valid = cache_available && cache_first_created >= 1 && cache_second_created >= 1; + if (feedback_valid) { EXPECT(cache_second_created == cache_first_created); - EXPECT(cache_second_hits == cache_second_created); // the second creation was answered by the cache - EXPECT(cache_bytes_second == cache_bytes_first); // and added nothing to it + EXPECT(!cache_second_hits || cache_second_hits == cache_second_created); + if (!cache_second_hits) // a driver that never sets the hit bit still shows a miss as growth of the cache + std::printf("note: the driver reported no application-cache hit for the second creation\n"); + if (cache_bytes_first && cache_bytes_second) { + EXPECT(cache_bytes_second == cache_bytes_first); // the second creation added nothing to the cache + } } else { - std::printf("note: no VkPipelineCreationFeedback (Vulkan 1.3) or no VkPipelineCache: cache hits not checked\n"); + std::printf("note: pipeline cache feedback unavailable (no Vulkan 1.3 feedback, no valid bits or no cache): " + "only the pixels were checked\n"); } if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index e2436c9742..57acd853e6 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -476,10 +476,10 @@ int main() { }; CommandList list; - CHECK(list.execute_indirect({IndirectKind::draw, 16, 2, 1, 4, 0, 0})); - CHECK(list.execute_indirect({IndirectKind::draw_indexed, 20, 2, 1, 8, 0, 0})); - CHECK(list.execute_indirect({IndirectKind::draw, 16, 2, 1, 12, 2, 4})); - CHECK(list.execute_indirect({IndirectKind::draw_indexed, 20, 2, 1, 16, 2, 8})); + CHECK(list.execute_indirect({IndirectKind::draw, 16, 2, 1, 4, 0, 0, nullptr, true})); + CHECK(list.execute_indirect({IndirectKind::draw_indexed, 20, 2, 1, 8, 0, 0, nullptr, true})); + CHECK(list.execute_indirect({IndirectKind::draw, 16, 2, 1, 12, 2, 4, nullptr, true})); + CHECK(list.execute_indirect({IndirectKind::draw_indexed, 20, 2, 1, 16, 2, 8, nullptr, true})); CHECK(list.execute_indirect({IndirectKind::dispatch, 20, 2, 1, 20, 0, 0})); CHECK(list.close()); CHECK(replay(list, VK_NULL_HANDLE, resolve, vk) == ReplayResult::success); @@ -493,8 +493,8 @@ int main() { single.multi_draw_indirect = false; offsets.clear(); CommandList one; - CHECK(one.execute_indirect({IndirectKind::draw, 16, 2, 1, 4, 0, 0})); - CHECK(one.execute_indirect({IndirectKind::draw_indexed, 20, 3, 1, 8, 0, 0})); + CHECK(one.execute_indirect({IndirectKind::draw, 16, 2, 1, 4, 0, 0, nullptr, true})); + CHECK(one.execute_indirect({IndirectKind::draw_indexed, 20, 3, 1, 8, 0, 0, nullptr, true})); CHECK(one.close()); CHECK(replay(one, VK_NULL_HANDLE, resolve, single) == ReplayResult::success); CHECK((offsets == std::vector{260, 276, 264, 284, 304})); diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 52a647e736..f529294da0 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -97,6 +97,7 @@ class Device { bool swapchain_maintenance1 = false; bool multi_draw_indirect = false; // multiDrawIndirect enabled, where the device has it bool draw_indirect_count = false; // drawIndirectCount (Vulkan 1.2) enabled, where the device has it + std::uint32_t max_draw_indirect_count = 0; // VkPhysicalDeviceLimits::maxDrawIndirectCount bool draw_indirect_first_instance = false; // drawIndirectFirstInstance enabled: indirect records may start at an instance bool shader_fma = false; // VK_KHR_shader_fma and shaderFmaFloat32 enabled (OpFmaKHR, rdna2spirv.py --fma khr) bool occlusion_query_precise = false; // occlusionQueryPrecise enabled @@ -389,6 +390,7 @@ class Device { multi_draw_indirect = features.features.multiDrawIndirect == VK_TRUE; enable.drawIndirectFirstInstance = features.features.drawIndirectFirstInstance; draw_indirect_first_instance = features.features.drawIndirectFirstInstance == VK_TRUE; + max_draw_indirect_count = chosen.limits.maxDrawIndirectCount; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; From 1ca74c02e3a1874f9f8758ea5e171690b727730a Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:58:09 +0100 Subject: [PATCH 03/17] emit_indirect: 64-bit chunk cursor advanced by the count each call drew The fixed-count loops added a full chunk to a 32-bit cursor, so a short final chunk could wrap it and restart at argument offset 0 (MaxCommandCount UINT32_MAX with maxDrawIndirectCount 0x80000000). Found by @Vonsek in review of #1865. d3d12_state_map now checks the calls (counts and offsets, not records) for both draw kinds with a huge count and for a limit that does not divide the count. Co-Authored-By: Claude Opus 5.5 --- runtime/src/vulkan_replay.h | 20 +++++++++++------ runtime/test/d3d12_state_map_test.cpp | 31 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 9a77c08429..17a5a6f481 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1833,18 +1833,24 @@ inline void emit_indirect(const ReplayFunctions& vk, VkCommandBuffer command_buf } // Without multiDrawIndirect a call draws one command: loop over them. // and a call takes at most maxDrawIndirectCount records. + // The cursor is 64 bits and advances by the count each call drew, so a short last call cannot wrap it. const std::uint32_t per_call = vk.multi_draw_indirect ? std::max(1, std::min(ind.max_count, vk.max_draw_indirect_count)) : 1; if (ind.kind == IndirectKind::draw) { - for (std::uint32_t k = 0; k < ind.max_count; k += per_call) - vk.draw_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, - std::min(per_call, ind.max_count - k), ind.stride); + for (std::uint64_t k = 0; k < ind.max_count;) { + const std::uint32_t n = std::uint32_t(std::min(per_call, ind.max_count - k)); + vk.draw_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, n, ind.stride); + k += n; + } } else if (ind.kind == IndirectKind::draw_indexed) { - for (std::uint32_t k = 0; k < ind.max_count; k += per_call) - vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, - std::min(per_call, ind.max_count - k), ind.stride); + for (std::uint64_t k = 0; k < ind.max_count;) { + const std::uint32_t n = std::uint32_t(std::min(per_call, ind.max_count - k)); + vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, n, + ind.stride); + k += n; + } } else if (ind.kind == IndirectKind::dispatch) { - for (std::uint32_t k = 0; k < ind.max_count; ++k) + for (std::uint64_t k = 0; k < ind.max_count; ++k) vk.dispatch_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride); } } diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 57acd853e6..87554c0d73 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -501,6 +501,37 @@ int main() { offsets = kept; } + // Chunking of one huge record count (found by @Vonsek in #1865): the calls are counted, not the records. With + // maxDrawIndirectCount 0x80000000 and MaxCommandCount UINT32_MAX there are two calls, 0x80000000 records and + // then the clipped 0x7fffffff, at 64-bit offsets, and the loop ends. Both draw kinds, and a limit that does not + // divide the count. + { + struct Call { VkDeviceSize offset; std::uint32_t count; }; + static std::vector calls; + ReplayFunctions huge{}; + huge.multi_draw_indirect = true; + huge.max_draw_indirect_count = 0x80000000u; + huge.draw_indirect = [](VkCommandBuffer, VkBuffer, VkDeviceSize offset, std::uint32_t count, + std::uint32_t) { calls.push_back({offset, count}); }; + huge.draw_indexed_indirect = huge.draw_indirect; + detail::Prepared prepared{}; + prepared.binding.buffer_offset = 256; + for (const IndirectKind kind : {IndirectKind::draw, IndirectKind::draw_indexed}) { + calls.clear(); + ExecuteIndirect command{kind, 20, UINT32_MAX, 1, 4, 0, 0, nullptr, true}; + detail::emit_indirect(huge, VK_NULL_HANDLE, prepared, command); + CHECK(calls.size() == 2); + CHECK(calls[0].offset == 260 && calls[0].count == 0x80000000u); + CHECK(calls[1].offset == 260 + 0x80000000ull * 20 && calls[1].count == 0x7fffffffu); + } + calls.clear(); + huge.max_draw_indirect_count = 1000; + ExecuteIndirect uneven{IndirectKind::draw, 16, 2500, 1, 0, 0, 0, nullptr, true}; + detail::emit_indirect(huge, VK_NULL_HANDLE, prepared, uneven); + CHECK(calls.size() == 3 && calls[0].count == 1000 && calls[1].count == 1000 && calls[2].count == 500); + CHECK(calls[2].offset == 256 + 2000ull * 16); + } + // Reject invalid spans before invoking Vulkan, including after adding the backing-buffer base. const auto rejected = [&](const ExecuteIndirect& command) { CommandList invalid; From e9ef1edbc5a1b25ea830acadbd284c3849636266 Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:09:51 +0100 Subject: [PATCH 04/17] d3d12_state_map: the chunking mock fails after 8 calls instead of growing without bound A cursor that wraps again now ends the loop with a failed check rather than appending until memory runs out. Checked by lowering the cap to 1: the check fails at the call. Suggested by @Vonsek in #1865. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_state_map_test.cpp | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 87554c0d73..db92f4d642 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -509,17 +509,31 @@ int main() { struct Call { VkDeviceSize offset; std::uint32_t count; }; static std::vector calls; ReplayFunctions huge{}; + detail::Prepared prepared{}; + prepared.binding.buffer_offset = 256; huge.multi_draw_indirect = true; huge.max_draw_indirect_count = 0x80000000u; + // More calls than any correct chunking needs end the loop by throwing, so a cursor that wraps again + // fails the test instead of running until memory is exhausted (@Vonsek's review of #1865). + struct TooManyCalls {}; huge.draw_indirect = [](VkCommandBuffer, VkBuffer, VkDeviceSize offset, std::uint32_t count, - std::uint32_t) { calls.push_back({offset, count}); }; + std::uint32_t) { + if (calls.size() >= 8) throw TooManyCalls{}; + calls.push_back({offset, count}); + }; + const auto emit_bounded = [&](const ExecuteIndirect& command) { + try { + detail::emit_indirect(huge, VK_NULL_HANDLE, prepared, command); + return true; + } catch (const TooManyCalls&) { + return false; + } + }; huge.draw_indexed_indirect = huge.draw_indirect; - detail::Prepared prepared{}; - prepared.binding.buffer_offset = 256; for (const IndirectKind kind : {IndirectKind::draw, IndirectKind::draw_indexed}) { calls.clear(); ExecuteIndirect command{kind, 20, UINT32_MAX, 1, 4, 0, 0, nullptr, true}; - detail::emit_indirect(huge, VK_NULL_HANDLE, prepared, command); + CHECK(emit_bounded(command)); CHECK(calls.size() == 2); CHECK(calls[0].offset == 260 && calls[0].count == 0x80000000u); CHECK(calls[1].offset == 260 + 0x80000000ull * 20 && calls[1].count == 0x7fffffffu); @@ -527,7 +541,7 @@ int main() { calls.clear(); huge.max_draw_indirect_count = 1000; ExecuteIndirect uneven{IndirectKind::draw, 16, 2500, 1, 0, 0, 0, nullptr, true}; - detail::emit_indirect(huge, VK_NULL_HANDLE, prepared, uneven); + CHECK(emit_bounded(uneven)); CHECK(calls.size() == 3 && calls[0].count == 1000 && calls[1].count == 1000 && calls[2].count == 500); CHECK(calls[2].offset == 256 + 2000ull * 16); } From 00a23e003ea4d8477a7e7081194e722c1acdadc2 Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:51:36 +0100 Subject: [PATCH 05/17] vulkan_backend.h: restore the line continuation after the merge Co-Authored-By: Claude Opus 5.5 --- runtime/src/vulkan_backend.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 0bac4487c9..1c9dd8968c 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -80,7 +80,8 @@ struct VulkanDeviceFunctions { X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ - X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \n X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) + X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER From dd0b40a4053f76a0222f5b09d113fd6ab9ef3a2e Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:22:39 +0100 Subject: [PATCH 06/17] d3d12_m5_world_test: the vertex and instance ids are zero-based now (main's translator subtracts BaseVertex/BaseInstance) After the round-41 merge the non-indexed records (P1) all drew cell 0: they chose their cell by StartVertexLocation, which the hardware-style zero-based v0 no longer carries. P1 now picks cells through the instance id (InstanceCount), indexed records still through the index values. The layer and the merge were fine; the test relied on an id semantic main changed. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- runtime/test/d3d12_m5_world_test.cpp | 20 +++++++++++--------- runtime/test/shaders/vs_m5.asm | 9 ++++++--- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0b13d29c05..dbbbbd7288 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2769,7 +2769,7 @@ M0–M2 do not need the executable. | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU). Formats, mips and arrays through a PSO: `d3d12_m2_formats_test` samples an 8×8 BC1 and an 8×8 BC7 texture with 4 mips each and an R8G8B8A8 2D array of 3 slices through the same path (every subresource uploaded at its `GetCopyableFootprints` layout, POINT samplers with `MinLOD = MaxLOD` pinning each level, a view from mip 1, two array views read by `ps_m2_array.asm`); all 12 cases match the CPU with error 0, validation clean on the RTX 4070 Ti SUPER, with no layer change needed | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker follows submission order, so the copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error; d3d12_queue_wait_test covers Wait-before-Signal without a resource), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | -| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met except mesh shaders (D3D-29, @Ryx69)** by `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 34 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, `StartIndexLocation`/`StartVertexLocation` picking the cell and a non-zero `StartInstanceLocation`. **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Still open for M5:** mesh shaders (D3D-29); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | +| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met except mesh shaders (D3D-29, @Ryx69)** by `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Still open for M5:** mesh shaders (D3D-29); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (42 pass `spirv-val`, four rules left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), SDR and HDR10 (PQ) planes converted to the swapchain, checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is clipped, not tone mapped. `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | diff --git a/runtime/test/d3d12_m5_world_test.cpp b/runtime/test/d3d12_m5_world_test.cpp index 972970beca..41880353d6 100644 --- a/runtime/test/d3d12_m5_world_test.cpp +++ b/runtime/test/d3d12_m5_world_test.cpp @@ -7,8 +7,10 @@ // records written by the CPU into an upload buffer, and by the GPU (CopyBufferRegion into default-heap buffers // placed at non-zero heap offsets, then a COPY_DEST -> INDIRECT_ARGUMENT barrier), argument offsets inside those // buffers, a count buffer (the draw count is the smaller of it and MaxCommandCount; a count of 0 draws nothing). -// Each record draws one cell of an 8x8 grid (vs_m5.asm places a quad from the vertex index, so StartVertexLocation -// or StartIndexLocation pick the cell; the colour says which cell and which variant). +// Each record draws cells of an 8x8 grid (vs_m5.asm places a quad from the vertex index and the instance id: +// the index values pick the cell of an indexed record, InstanceCount the cells of a non-indexed one; the colour +// says which cell and which variant). The ids are zero-based, so StartVertexLocation and StartInstanceLocation +// are not visible to the shaders. // (b) Multi-threaded recording. Four std::threads each create their own allocator and list and record 40 draws of // random rectangles (root constants) at once; the four lists run in one ExecuteCommandLists between a clear list and // a readback list. The rectangles overlap across the lists, so the list order shows in the pixels. Eight rounds of @@ -375,18 +377,18 @@ int main() { // drawIndirectFirstInstance, which the device enables where it has it). const auto first_instance = [&](unsigned r) { return d.draw_indirect_first_instance ? r + 1 : 0u; }; Image want(64, 64); - // P1: CPU-written records in an upload buffer, argument offset 64, stride 16: strips of 4 vertices. - // Record r draws cell r, variant 1 for r = 5 and 12, with no instances at all for r % 4 == 3, and twice - // (InstanceCount 2) for r = 8. + // P1: CPU-written records in an upload buffer, argument offset 64, stride 16: strips of 4 vertices, each + // record InstanceCount instances, which are cells 0..InstanceCount-1 (all variant 0). Most records are + // empty or small and the last one is the largest, so cells 0..12 are all painted only if the records + // after the first were drawn too, and an empty record draws nothing. EXPECT(SUCCEEDED(args_cpu->Map(0, nullptr, reinterpret_cast(&mapped)))); std::memset(mapped, 0xA5, 4096); // bytes outside the records are never read + static constexpr unsigned instances[16] = {2, 0, 0, 5, 0, 1, 0, 8, 0, 0, 3, 0, 0, 0, 6, 13}; for (unsigned r = 0; r < 16; ++r) { - const unsigned w = (r == 5 || r == 12) ? 1 : 0; - const D3D12_DRAW_ARGUMENTS record{4, (r % 4 == 3) ? 0u : (r == 8 ? 2u : 1u), 8 * r + 4 * w, - first_instance(r)}; + const D3D12_DRAW_ARGUMENTS record{4, instances[r], 0, 0}; std::memcpy(mapped + 64 + r * sizeof(record), &record, sizeof(record)); - if (record.InstanceCount) { paint_cell(want, r, w); ++cells_drawn; } } + for (unsigned k = 0; k < 13; ++k) { paint_cell(want, k, 0); ++cells_drawn; } // P2..P5 records and the count words, built in one upload buffer and copied into placed default buffers. // args2 (placed at 64 KiB): 20 indexed records of stride 32 at 96 for cells 16..35 (variant r % 2, none // at r = 6), then 4 records at 736 for cells 44..47 (never drawn: count 0), then 6 at 864 for cells diff --git a/runtime/test/shaders/vs_m5.asm b/runtime/test/shaders/vs_m5.asm index c21712e30c..a586711b9d 100644 --- a/runtime/test/shaders/vs_m5.asm +++ b/runtime/test/shaders/vs_m5.asm @@ -1,9 +1,11 @@ ; M5 vertex shader: a quad from the vertex index, placed in an 8x8 grid of cells by the bits above the corner. Run: ; d3d12_m5_world_test (found by the SHA-256 of its FSSM program, as vs_m2 is). ; v0 = VertexIndex: the test draws triangle strips of vertices 8k + 4w + 0..3 and indexed lists 8k + 4w + {0 1 2 2 1 3} -; (base vertex 0), for cell k = 0..63 and variant w = 0, 1. Nothing here reads the instance index, so the result does -; not depend on whether StartInstanceLocation is part of it. -; corner u = v0 & 1, v = (v0 >> 1) & 1; variant w = (v0 >> 2) & 1; cell k = (v0 >> 3) & 63, cx = k & 7, cy = k >> 3 +; (base vertex 0), for cell k = 0..63 and variant w = 0, 1. The vertex and instance ids are zero-based (the translator +; subtracts BaseVertex and BaseInstance, as the hardware's are), so a draw's first vertex or first instance does not +; show in them: indexed draws pick the cell through the index values, and instanced ones through the instance id. +; corner u = v0 & 1, v = (v0 >> 1) & 1; variant w = (v0 >> 2) & 1; +; cell k = ((v0 >> 3) + v3) & 63, cx = k & 7, cy = k >> 3 ; pos0 = (-1 + (cx + u) / 4, 1 - (cy + v) / 4, 0, 1): a cell is a quarter of the clip range per side, so every ; corner is a multiple of 1/4 and each operation is exact however it is fused ; param0 = (k, w, 0, 1) @@ -14,6 +16,7 @@ v_and_b32_e32 v2, 2, v0 v_lshrrev_b32_e32 v7, 2, v0 v_and_b32_e32 v7, 1, v7 v_lshrrev_b32_e32 v12, 3, v0 +v_add_nc_u32_e32 v12, v12, v3 v_and_b32_e32 v12, 63, v12 v_and_b32_e32 v8, 7, v12 v_lshrrev_b32_e32 v9, 3, v12 From e18b26bf99e774097907b7945f9b7b3758bf9940 Mon Sep 17 00:00:00 2001 From: lloyd Date: Sun, 22 Nov 2026 14:42:35 +0200 Subject: [PATCH 07/17] Runtime: mesh-shader PSOs from pipeline state streams and DispatchMesh (D3D-29) The device enables VK_EXT_mesh_shader (meshShader) where the GPU has it and reports MeshShaderTier 1 only then. ID3D12Device2::CreatePipelineState parses pipeline state streams in the d3dx12.h layout into the descriptions the existing PSO creators take, with the runtime's defaults for missing subobjects. Streams the PC runtime refuses are E_INVALIDARG; AS, depth bounds, split stencil masks and view instancing are E_NOTIMPL with a log. A mesh PSO is MS + PS with no vertex input or input assembly, and no dynamic topology or strides. Its output sizes and workgroup are checked against VkPhysicalDeviceMeshShaderPropertiesEXT. DispatchMesh records a Draw with mesh set and replays as vkCmdDrawMeshTasksEXT; a draw of the wrong kind for its pipeline fails with ReplayResult::invalid_draw. d3d12_mesh_test covers the refusals and checks a 2x2x1 and a 1x1x2 mesh grid plus a VS PSO from a stream, pixel by pixel. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 33 +++ runtime/CMakeLists.txt | 22 +- runtime/shims/d3d12_com.cpp | 15 + runtime/shims/d3d12_com.h | 4 + runtime/shims/d3d12_vulkan_device.cpp | 332 +++++++++++++++++++-- runtime/src/command_list.h | 14 +- runtime/src/shader_library.h | 6 + runtime/src/vulkan_backend.h | 10 +- runtime/src/vulkan_replay.h | 25 +- runtime/test/d3d12_mesh_test.cpp | 401 ++++++++++++++++++++++++++ runtime/test/glsl/ms_draw.mesh | 34 +++ runtime/test/replay_cpu_bench.cpp | 1 + runtime/test/vk_test_device.h | 17 ++ 13 files changed, 880 insertions(+), 34 deletions(-) create mode 100644 runtime/test/d3d12_mesh_test.cpp create mode 100644 runtime/test/glsl/ms_draw.mesh diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 8749bd331d..5b1d43b4b6 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2045,6 +2045,39 @@ Pipeline creation: **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. +**Implemented (D3D-29): pipeline state streams, mesh PSOs and `DispatchMesh`.** +- **Device:** `VK_EXT_mesh_shader` with `meshShader` is enabled where the GPU has it (`VulkanDeviceInfo::mesh_shader`). + `taskShader` is not enabled, since the corpus has no amplification shaders. `D3D12_OPTIONS7` reports + `MeshShaderTier` 1 only then; without the extension it reports `NOT_SUPPORTED` and mesh PSOs are `E_NOTIMPL`. +- **Streams:** `CreatePipelineState` parses the stream in the d3dx12.h layout: a subobject type, then its + description at that description's alignment, each subobject pointer-aligned. + - Every type up to `RASTERIZER2` is read. + - Missing subobjects take the runtime's defaults: depth test on with `LESS`, back-face culling, no blending, sample + mask `0xFFFFFFFF`, one sample. + - The stream becomes the same descriptions `CreateGraphicsPipelineState` and `CreateComputePipelineState` take, so + a VS stream builds the same PSO as the classic call. + - `E_INVALIDARG`, as on the PC runtime: a type given twice, an unknown type, a truncated stream, MS with VS, + tessellation or GS, CS with a graphics stage, or no stage at all. + - `E_NOTIMPL` with a log, for what is not built yet: an AS, a depth-bounds test, separate front and back stencil + masks, view instancing. + - `RASTERIZER1`/`2`'s float depth bias is truncated to the integer the PSO path takes, with a log. +- **Mesh PSO:** the MS (`ms` index entry by FSSM hash) and PS on the mesh stage. It has no vertex input or input + assembly; the input layout, topology type and strip cut are ignored, as D3D12 ignores them for mesh PSOs. Topology + and strides are not dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065/07066). Creation + is refused when the index's `max_vertices`/`max_primitives` or the workgroup size exceed the device's + `VkPhysicalDeviceMeshShaderPropertiesEXT`. +- **`DispatchMesh`:** recorded as a `Draw` with `mesh` set; the thread-group counts go in `count`/`instances`/`first`. + It takes the same state snapshot as `DrawInstanced`: render targets, root arguments, viewport, scissor, blend + factor, stencil references. Replay issues `vkCmdDrawMeshTasksEXT`. + - **Recording errors** (`Close` returns `E_INVALIDARG`): a grid above 65535 per count or 2^22 groups. + - **Not recorded:** an empty grid. + - **Execution error** (`ReplayResult::invalid_draw`): a mesh draw with a VS pipeline, or the reverse. +- **Tests:** `d3d12_mesh_test` checks the refusals and three draws pixel by pixel on an RX 9060 XT (RADV, under + Wine), validation-clean. + - **The three draws:** a 2×2×1 and a 1×1×2 mesh grid, plus a VS PSO from a stream. + - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open + question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 58153376e4..3bcd320591 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2487,8 +2487,28 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_stores_atomics_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_stores_atomics COMMAND d3d12_stores_atomics_test) set_tests_properties(d3d12_stores_atomics PROPERTIES SKIP_RETURN_CODE 77) + + # D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh (skips without VK_EXT_mesh_shader). + set(LEONIDA_TEST_MS ${CMAKE_CURRENT_BINARY_DIR}/generated/ms_draw.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_MS} + # Vulkan 1.2 (SPIR-V 1.5), the translator's target: 1.3 would emit LocalSizeId, which needs maintenance4. + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -o ${LEONIDA_TEST_MS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh + COMMENT "Compiling the mesh test shader ms_draw.mesh" + VERBATIM) + add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} + ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) + target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") + target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) + set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) else() - message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test and d3d12_set0_compute_test are not built") + message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") endif() # Native D3D12 SV_InnerCoverage reference; its HLSL is compiled at runtime, so glslang is not needed. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 55b523d96c..987dd2d647 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -90,6 +90,7 @@ const char* name(leonida::ReplayResult result) { case leonida::ReplayResult::invalid_copy: return "invalid copy or resolve"; case leonida::ReplayResult::invalid_query: return "invalid query"; case leonida::ReplayResult::invalid_indirect_arguments: return "invalid indirect argument or count buffer range"; + case leonida::ReplayResult::invalid_draw: return "draw kind does not match the pipeline (mesh or vertex)"; case leonida::ReplayResult::unsupported: return "unsupported"; } return "?"; @@ -433,6 +434,20 @@ class GraphicsCommandList final record_draw(true, indices, instances, first_index, base_vertex, first_instance); } + // ID3D12GraphicsCommandList6: a mesh draw. The bound graphics pipeline must have a mesh shader (checked at + // execution, where the pipeline is resolved). D3D12 caps each count at 65535 and their product at 2^22 + // (D3D12_MS_DISPATCH_MAX_THREAD_GROUPS_PER_GRID); a larger grid is a recording error. + void STDMETHODCALLTYPE DispatchMesh(UINT x, UINT y, UINT z) override { + d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh"); + if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); + if (!graphics_pipeline_ || !graphics_.layout) return check(false); + if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized + leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, + scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; + draw.mesh = true; + check(list_.draw(std::move(draw))); + } + void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { d3d12_trace::record("ID3D12GraphicsCommandList::ResourceBarrier"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index db5552b7f0..6212b9c885 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -169,6 +169,10 @@ struct VulkanDeviceInfo { // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it // unless LEONIDA_RT_AS=khr (docs/d3d12_vulkan.md 4.8); with it set, ray_tracing is not enabled. bool xdxr_acceleration_structures = false; + // VK_EXT_mesh_shader with its meshShader feature is enabled on `device` (taskShader is not needed: the game's + // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports + // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED. + bool mesh_shader = false; // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, // depthBiasClamp or dualSrcBlend are refused unless it is set here. VkPhysicalDeviceFeatures features{}; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1316fefaad..e074ce908b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -551,6 +551,10 @@ struct DeviceState { }; SubgroupFacts subgroups; std::once_flag subgroups_once; + // VkPhysicalDeviceMeshShaderPropertiesEXT, read on first use by a mesh PSO; zeros when it cannot be asked. + VkPhysicalDeviceMeshShaderPropertiesEXT mesh_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; + bool mesh_properties_read = false; + std::mutex mesh_properties_mutex; PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr; @@ -872,6 +876,20 @@ struct DeviceState { subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes; } + // The device's mesh-shader limits (output vertices and primitives, workgroup size), for mesh PSO creation. + const VkPhysicalDeviceMeshShaderPropertiesEXT& mesh_limits() { + std::lock_guard lock(mesh_properties_mutex); + if (mesh_properties_read) return mesh_properties; + mesh_properties_read = true; + const auto properties2 = reinterpret_cast( + info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); + if (!properties2 || !info.physical || !info.mesh_shader) return mesh_properties; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &mesh_properties}; + properties2(info.physical, &properties); + mesh_properties.pNext = nullptr; + return mesh_properties; + } + // Integer sampled images need not support multisampling. Pick a supported count for the // zero image in the corresponding set-0 bindings; one means that class is unavailable. VkSampleCountFlagBits ms_fallback_samples(VkFormat format) const { @@ -2802,6 +2820,192 @@ class XboxPipelineStateStubs : public ID3D12PipelineStateStubs { // A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the // translator's index, and the FSSM blob is copied into the arena as the shader's code base. +// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. +// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that +// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A +// subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face +// culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown +// type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log. +struct PipelineStream { + D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{}; + D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; + D3D12_SHADER_BYTECODE ms{}; + D3D12_SHADER_BYTECODE as{}; + bool has_cs = false; + bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS +}; + +HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out) { + if (!desc.pPipelineStateSubobjectStream || !desc.SizeInBytes) return E_INVALIDARG; + D3D12_GRAPHICS_PIPELINE_STATE_DESC& g = out.graphics; + for (auto& target : g.BlendState.RenderTarget) { + target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ZERO; + target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + target.LogicOp = D3D12_LOGIC_OP_NOOP; + target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + g.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + g.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; + g.RasterizerState.DepthClipEnable = TRUE; + g.DepthStencilState.DepthEnable = TRUE; + g.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + g.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + g.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + g.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + g.DepthStencilState.FrontFace = g.DepthStencilState.BackFace = { + D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; + g.SampleMask = UINT_MAX; + g.SampleDesc = {1, 0}; + + const auto* base = static_cast(desc.pPipelineStateSubobjectStream); + const std::size_t size = desc.SizeInBytes; + const auto round_up = [](std::size_t v, std::size_t a) { return (v + a - 1) / a * a; }; + std::uint64_t seen = 0; + std::size_t at = 0; + while (at < size) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; + if (size - at < sizeof(type)) return E_INVALIDARG; + std::memcpy(&type, base + at, sizeof(type)); + if (unsigned(type) >= 64 || (seen >> unsigned(type) & 1)) return E_INVALIDARG; + seen |= std::uint64_t(1) << unsigned(type); + bool ok = true; + const auto take = [&](auto& value) { + using T = std::remove_reference_t; + const std::size_t payload = round_up(at + sizeof(type), alignof(T)); + if (payload > size || size - payload < sizeof(T)) { + ok = false; + return; + } + std::memcpy(&value, base + payload, sizeof(T)); + at = round_up(payload + sizeof(T), sizeof(void*)); + }; + const auto stage = [&](D3D12_SHADER_BYTECODE& code) { + take(code); + out.has_graphics_stage = true; + }; + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: + take(g.pRootSignature); + out.compute.pRootSignature = g.pRootSignature; + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: stage(g.VS); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: stage(g.PS); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: stage(g.DS); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: stage(g.HS); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: stage(g.GS); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: stage(out.as); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: stage(out.ms); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + take(out.compute.CS); + out.has_cs = true; + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: take(g.StreamOutput); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: take(g.BlendState); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: take(g.SampleMask); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: take(g.RasterizerState); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: take(g.DepthStencilState); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: take(g.InputLayout); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: take(g.IBStripCutValue); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: take(g.PrimitiveTopologyType); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: { + D3D12_RT_FORMAT_ARRAY formats{}; + take(formats); + if (formats.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; + g.NumRenderTargets = formats.NumRenderTargets; + std::copy(std::begin(formats.RTFormats), std::end(formats.RTFormats), std::begin(g.RTVFormats)); + break; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: take(g.DSVFormat); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: take(g.SampleDesc); break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: + take(g.NodeMask); + out.compute.NodeMask = g.NodeMask; + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: + take(g.CachedPSO); + out.compute.CachedPSO = g.CachedPSO; + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: + take(g.Flags); + out.compute.Flags = g.Flags; + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { + D3D12_DEPTH_STENCIL_DESC1 d{}; + take(d); + if (ok && d.DepthBoundsTestEnable) { + log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); + return E_NOTIMPL; + } + g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, + d.StencilWriteMask, d.FrontFace, d.BackFace}; + break; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2: { + D3D12_DEPTH_STENCIL_DESC2 d{}; + take(d); + if (!ok) break; + if (d.DepthBoundsTestEnable) { + log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); + return E_NOTIMPL; + } + // Separate front and back stencil masks are not modelled (one read and one write mask per PSO). + if (d.StencilEnable && (d.FrontFace.StencilReadMask != d.BackFace.StencilReadMask || + d.FrontFace.StencilWriteMask != d.BackFace.StencilWriteMask)) { + log_once("separate front and back stencil masks are not supported yet; stream subobject", int(type)); + return E_NOTIMPL; + } + const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) { + return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc}; + }; + g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, + UINT8(d.FrontFace.StencilReadMask), UINT8(d.FrontFace.StencilWriteMask), + face(d.FrontFace), face(d.BackFace)}; + break; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2: { + // Their DepthBias is a float; the PSO path takes D3D12_RASTERIZER_DESC's integer one. + FLOAT bias = 0; + D3D12_RASTERIZER_DESC& r = g.RasterizerState; + if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1) { + D3D12_RASTERIZER_DESC1 d{}; + take(d); + r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, + d.DepthClipEnable, d.MultisampleEnable, d.AntialiasedLineEnable, d.ForcedSampleCount, + d.ConservativeRaster}; + bias = d.DepthBias; + } else { + D3D12_RASTERIZER_DESC2 d{}; + take(d); + r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, + d.DepthClipEnable, FALSE, FALSE, d.ForcedSampleCount, d.ConservativeRaster}; + bias = d.DepthBias; + } + r.DepthBias = INT(bias); + if (ok && FLOAT(r.DepthBias) != bias) log_once("a fractional depth bias is truncated; bias x1000", int(bias * 1000)); + break; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING: { + D3D12_VIEW_INSTANCING_DESC d{}; + take(d); + if (ok && d.ViewInstanceCount) { + log_once("view instancing is not supported yet; views", int(d.ViewInstanceCount)); + return E_NOTIMPL; + } + break; + } + default: + log_once("unknown pipeline state stream subobject type:", int(type)); + return E_INVALIDARG; + } + if (!ok) return E_INVALIDARG; + } + if (out.has_cs && out.has_graphics_stage) return E_INVALIDARG; // a compute stage with graphics stages + if (!out.has_cs && !out.has_graphics_stage) return E_INVALIDARG; + return S_OK; +} + class PipelineState final : public Child { @@ -2894,10 +3098,26 @@ class PipelineState final // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic, // set from the list's state at each draw. - HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { + // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead: + // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12 + // does for mesh PSOs), drawn by DispatchMesh. An AS (amplification shader) is refused: the game has none. + HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, + const D3D12_SHADER_BYTECODE* as = nullptr) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; - if (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength) return E_INVALIDARG; + const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; + if (as && as->pShaderBytecode && as->BytecodeLength) { + log_once("amplification shaders are not supported (the game has none); bytes", int(as->BytecodeLength)); + return E_NOTIMPL; + } + if (mesh && (desc.VS.BytecodeLength || desc.HS.BytecodeLength || desc.DS.BytecodeLength || + desc.GS.BytecodeLength || desc.StreamOutput.NumEntries)) + return E_INVALIDARG; // D3D12: a mesh PSO has no vertex, tessellation or geometry stage + if (!mesh && (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength)) return E_INVALIDARG; + if (mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT)) { + log_once("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1); + return E_NOTIMPL; + } if (!device_.arena.mapped) { log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); return E_NOTIMPL; @@ -2954,7 +3174,8 @@ class PipelineState final std::vector fssm; std::vector words; }; - Stage stages[3] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, + Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms} + : Stage{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. @@ -3008,6 +3229,26 @@ class PipelineState final uses_bindless = true; register_literal_samplers(device_, *stage.entry); } + if (stage.bit == VK_SHADER_STAGE_MESH_BIT_EXT) { + // The SPIR-V's output arrays are sized from PSV0 (the index's max_vertices / max_primitives); Vulkan + // has no per-pipeline limit to set, so a mesh shader beyond the device's is refused here + // (docs/d3d12_vulkan.md, "Pipelines"). + const VkPhysicalDeviceMeshShaderPropertiesEXT& limits = device_.mesh_limits(); + const auto& n = stage.entry->local_size; + if (stage.entry->max_vertices > limits.maxMeshOutputVertices || + stage.entry->max_primitives > limits.maxMeshOutputPrimitives || + n[0] > limits.maxMeshWorkGroupSize[0] || n[1] > limits.maxMeshWorkGroupSize[1] || + n[2] > limits.maxMeshWorkGroupSize[2] || + std::uint64_t(n[0]) * n[1] * n[2] > limits.maxMeshWorkGroupInvocations) { + std::fprintf(stderr, + "[rt] d3d12: %s needs %u vertices, %u primitives, %ux%ux%u threads; the device " + "allows %u, %u, %u invocations\n", + stage.entry->name.c_str(), stage.entry->max_vertices, stage.entry->max_primitives, + n[0], n[1], n[2], limits.maxMeshOutputVertices, limits.maxMeshOutputPrimitives, + limits.maxMeshWorkGroupInvocations); + return E_NOTIMPL; + } + } if (stage.entry->uses_code_base) { if (code_stage) { log_once("two stages read their code base; one push-constant slot holds one (question 14)", 0); @@ -3104,13 +3345,13 @@ class PipelineState final stage_infos.push_back(info); } - // Input layout -> vertex input, by semantic. + // Input layout -> vertex input, by semantic. A mesh pipeline has none. std::vector attributes; std::vector bindings; std::vector divisors; std::uint32_t divisor_slots = 0; UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {}; - for (UINT i = 0; i < desc.InputLayout.NumElements; ++i) { + for (UINT i = 0; !mesh && i < desc.InputLayout.NumElements; ++i) { const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; VkFormat format; @@ -3162,7 +3403,7 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (desc.PrimitiveTopologyType) { + switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; @@ -3170,13 +3411,15 @@ class PipelineState final log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); return E_INVALIDARG; } - if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && - desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF && - desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) { - log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue); - return E_INVALIDARG; + if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored + if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && + desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF && + desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) { + log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue); + return E_INVALIDARG; + } + graphics_.strip_cut = desc.IBStripCutValue; } - graphics_.strip_cut = desc.IBStripCutValue; const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF && @@ -3381,6 +3624,8 @@ class PipelineState final if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. + graphics_.mesh = mesh; + recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); recipe_.bindings = std::move(bindings); @@ -3526,6 +3771,7 @@ class PipelineState final private: // What a graphics pipeline is made from, so variants can be built at draw time. struct Recipe { + bool mesh = false; // no vertex input or input assembly state, and no dynamic topology or strides std::vector stages; // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{}; @@ -3594,15 +3840,25 @@ class PipelineState final VkPipelineColorBlendStateCreateInfo blend = r.blend; blend.attachmentCount = std::uint32_t(r.blends.size()); blend.pAttachments = r.blends.data(); + // A mesh pipeline takes neither the topology nor the strides as dynamic state + // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). + static constexpr VkDynamicState mesh_dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_STENCIL_REFERENCE, + VK_DYNAMIC_STATE_BLEND_CONSTANTS}; VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0); - dynamic.pDynamicStates = dynamic_states; + if (r.mesh) { + dynamic.dynamicStateCount = std::uint32_t(std::size(mesh_dynamic_states)); + dynamic.pDynamicStates = mesh_dynamic_states; + } else { + dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0); + dynamic.pDynamicStates = dynamic_states; + } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; info.stageCount = std::uint32_t(r.stages.size()); info.pStages = r.stages.data(); - info.pVertexInputState = &vertex_input; - info.pInputAssemblyState = &r.assembly; + info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity + info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; info.pRasterizationState = &raster; info.pMultisampleState = &multisample; @@ -5570,6 +5826,27 @@ class Device final return d3d12_trace::result(method, S_OK); } + // ID3D12Device2: a PSO from a pipeline state stream. A CS makes a compute PSO, an MS a mesh PSO, a VS the same + // graphics PSO CreateGraphicsPipelineState makes (parse_pipeline_stream). + HRESULT STDMETHODCALLTYPE CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, + void** out) override { + constexpr const char* method = "ID3D12Device2::CreatePipelineState"; + if (!out) return d3d12_trace::result(method, E_POINTER); + *out = nullptr; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + PipelineStream stream; + if (const HRESULT hr = parse_pipeline_stream(*desc, stream); FAILED(hr)) return d3d12_trace::result(method, hr); + auto* pipeline = new PipelineState(state_); + pipeline->attach_device(identity()); + const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) + : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as); + if (FAILED(hr)) { + pipeline->Release(); + return d3d12_trace::result(method, hr); + } + return d3d12_trace::result(method, hand_out(pipeline, riid, out)); + } + UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { return kDescriptorSize; } @@ -6847,7 +7124,11 @@ class Device final if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS7)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; - opts->MeshShaderTier = D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; + // Tier 1 is mesh PSOs and DispatchMesh, on VK_EXT_mesh_shader. Amplification shaders are part of the tier + // but refused at PSO creation (the game has none); OPTIONS9's mesh statistics and full-range render + // target array index stay FALSE. + opts->MeshShaderTier = + state_.info.mesh_shader ? D3D12_MESH_SHADER_TIER_1 : D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; opts->SamplerFeedbackTier = D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } @@ -8533,6 +8814,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { VkPhysicalDeviceAccelerationStructureFeaturesKHR as_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; + VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; { std::uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); @@ -8552,8 +8834,14 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { has_dho = true; } else if (!std::strcmp(e.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME)) { has_rq = true; + } else if (!std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; + vkGetPhysicalDeviceFeatures2(info.physical, &features); + info.mesh_shader = mesh_features.meshShader == VK_TRUE; } } + if (!info.mesh_shader) + std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { as_features.pNext = &rq_features; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; @@ -8582,7 +8870,16 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; enable_as.accelerationStructure = VK_TRUE; + // Only meshShader: the game has no amplification (task) shaders, and multiview and shading-rate mesh features + // are not used. + VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; + enable_mesh.meshShader = VK_TRUE; + void* ext_chain = nullptr; + if (info.mesh_shader) { + enable_mesh.pNext = ext_chain; + ext_chain = &enable_mesh; + } if (info.ray_tracing) { enable_rq.pNext = ext_chain; enable_as.pNext = &enable_rq; @@ -8956,6 +9253,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { // VK_KHR_swapchain requires VK_KHR_surface on the instance (VUID-vkCreateDevice-ppEnabledExtensionNames-01387). if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); + if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); if (info.ray_tracing) { device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 5c36d44e35..36fee95af4 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -414,9 +414,11 @@ struct DrawViews { std::uint32_t render_target_count = 8; }; -// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads -// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at -// the draw. resource 0 marks an unbound render-target slot or no depth buffer. +// DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: +// D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the +// list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw +// (DispatchMesh) takes its thread-group counts in count (x), instances (y) and first (z), and ignores the vertex +// and index buffers and the topology. // Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations // during command list recording (D3D-289). struct Draw { @@ -437,6 +439,7 @@ struct Draw { std::uint32_t first = 0; // first vertex or first index std::int32_t base_vertex = 0; std::uint32_t first_instance = 0; + bool mesh = false; }; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. @@ -738,10 +741,11 @@ class CommandList { return append(dispatch); } - // A draw with no vertices or instances does nothing in D3D12, and is not recorded. + // A draw with no vertices or instances, or a mesh draw with no thread groups, does nothing in D3D12, and is + // not recorded. bool draw(const Draw& draw) { if (!draw.pipeline) return false; - if (!draw.count || !draw.instances) return !closed_; + if (!draw.count || !draw.instances || (draw.mesh && !draw.first)) return !closed_; return append(draw); } bool draw(Draw&& draw) { diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 4cc35d58a7..c4cba63af2 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -714,6 +714,10 @@ struct ShaderEntry { // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). std::vector> literal_samplers; + // Mesh shaders: the output array sizes the SPIR-V declares (OutputVertices / OutputPrimitivesEXT), checked + // against the device's maxMeshOutputVertices / maxMeshOutputPrimitives when a pipeline is created. 0: not given. + std::uint32_t max_vertices = 0; + std::uint32_t max_primitives = 0; }; class ShaderLibrary { @@ -907,6 +911,8 @@ class ShaderLibrary { e.literal_samplers.push_back(words); } } + e.max_vertices = u32(meta.find("max_vertices")); + e.max_primitives = u32(meta.find("max_primitives")); if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); if (by_fspx && prefix == "fspx/") ++fspx_count_; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index dc042bf73f..66d6bb1548 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -96,16 +96,17 @@ struct VulkanDeviceFunctions { X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ - X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) \ + X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER - // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering) when the - // extension is not enabled, and the query functions are optional (a list that uses queries without them is - // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. + // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering, mesh + // shaders) when the extension is not enabled, and the query functions are optional (a list that uses queries + // without them is unsupported). The compute and descriptor functions are needed for normalized or summed + // occlusion results. bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { #define LEONIDA_VK_LOAD(name) name = reinterpret_cast(leonida::device_proc_or_khr(get, device, #name)); LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) @@ -956,6 +957,7 @@ class VulkanContext { replay_.set_stencil_reference = vk.vkCmdSetStencilReference; replay_.set_blend_constants = vk.vkCmdSetBlendConstants; replay_.draw = vk.vkCmdDraw; + replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled replay_.draw_indexed = vk.vkCmdDrawIndexed; replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { const auto it = graphics_pipelines_.find(id); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 49efd399df..a4c73f3186 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -758,6 +758,7 @@ struct GraphicsPipeline { std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) + bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth // and stencil. Null when it cannot be built. @@ -788,6 +789,7 @@ enum class ReplayResult { invalid_predication, invalid_query, invalid_indirect_arguments, + invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; @@ -843,6 +845,7 @@ struct ReplayFunctions { PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; PFN_vkCmdDraw draw = nullptr; + PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported PFN_vkCmdDrawIndexed draw_indexed = nullptr; std::function graphics_pipeline; // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is @@ -2068,6 +2071,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; + if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; p.graphics = pipeline; @@ -3974,12 +3979,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; vk.set_scissor(command_buffer, 0, 1, &scissor); - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); - vk.set_primitive_topology(command_buffer, topology); - const bool restart = draw->indexed && detail::strip_topology(topology) && - ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || - (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); - vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); + // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology + // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). + if (!draw->mesh) { + const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + vk.set_primitive_topology(command_buffer, topology); + const bool restart = draw->indexed && detail::strip_topology(topology) && + ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || + (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); + vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); + } vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); vk.set_blend_constants(command_buffer, draw->blend_factor.data()); @@ -3988,7 +3997,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], &d.vertex_sizes[slot], &d.vertex_strides[slot]); } - if (draw->indexed) { + if (draw->mesh) { + vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, draw->first_instance); diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp new file mode 100644 index 0000000000..77a4aefc62 --- /dev/null +++ b/runtime/test/d3d12_mesh_test.cpp @@ -0,0 +1,401 @@ +// D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh, through the Xbox-ABI proxy over the Vulkan +// device (docs/d3d12_vulkan.md section 5, "Pipelines"). +// - A device without VK_EXT_mesh_shader reports D3D12_MESH_SHADER_TIER_NOT_SUPPORTED and refuses a mesh PSO with +// E_NOTIMPL; that part runs on every GPU. The rest needs the extension (exit 77 without it). +// - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as +// d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime +// refuses (MS with VS, CS with PS, a subobject twice, an unknown type, a truncated stream) are E_INVALIDARG, and +// state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. +// - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; +// DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the +// Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the +// bottom-left quadrant (yellow). Each pixel is read back and compared. +// - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: +// invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. +// The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). +// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include + +#if !defined(LEONIDA_TEST_MS_SPV) || !defined(LEONIDA_TEST_PS_SPV) || !defined(LEONIDA_TEST_VS_FULLSCREEN_SPV) +#error "LEONIDA_TEST_MS_SPV, LEONIDA_TEST_PS_SPV and LEONIDA_TEST_VS_FULLSCREEN_SPV must name the compiled test shaders" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX + +namespace { + +// One pipeline state stream subobject as d3dx12.h declares it (CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT). +template +struct alignas(void*) Subobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type; + Inner inner; +}; +using RootSubobject = Subobject; +using VsSubobject = Subobject; +using PsSubobject = Subobject; +using CsSubobject = Subobject; +using AsSubobject = Subobject; +using MsSubobject = Subobject; +using TopologySubobject = Subobject; +using TargetsSubobject = Subobject; +using DepthStencil1Subobject = Subobject; +using MaskSubobject = Subobject; + +// Subobjects appended one after another: each is pointer-aligned and a multiple of the pointer size, so the bytes +// are what a struct of the same members would hold. +struct Stream { + std::vector bytes; + template + Stream& add(const S& subobject) { + static_assert(sizeof(S) % sizeof(void*) == 0); + const std::size_t at = bytes.size(); + bytes.resize(at + sizeof(S)); + std::memcpy(bytes.data() + at, &subobject, sizeof(S)); + return *this; + } + D3D12_PIPELINE_STATE_STREAM_DESC desc(std::size_t trim = 0) { return {bytes.size() - trim, bytes.data()}; } +}; + +D3D12_RT_FORMAT_ARRAY one_target() { + D3D12_RT_FORMAT_ARRAY formats{}; + formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + formats.NumRenderTargets = 1; + return formats; +} + +HRESULT create(ID3D12Device* device, Stream& stream, Ref& out, std::size_t trim = 0) { + Ref device2; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device2.p)))) return E_NOINTERFACE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc = stream.desc(trim); + out.reset(); + return device2->CreatePipelineState(&desc, IID_PPV_ARGS(&out.p)); +} + +D3D12_MESH_SHADER_TIER mesh_tier(ID3D12Device* device) { + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options, sizeof(options)))) + return D3D12_MESH_SHADER_TIER(-1); + return options.MeshShaderTier; +} + +} // namespace + +int main() { + vktest::Device d; + d.request_mesh_shader = true; + EXPECT(d.create()); + + const auto ms_program = fssm_program({0x4d530001, 0xbf810000}); + const auto ps_program = fssm_program({0x50530001, 0xbf810000}); + const auto vs_program = fssm_program({0x56530002, 0xbf810000}); + const auto ms_container = shader_container(ms_program), ps_container = shader_container(ps_program); + const auto vs_container = shader_container(vs_program); + const auto library = std::filesystem::temp_directory_path() / "leonida_mesh_test"; + std::filesystem::create_directories(library); + std::filesystem::copy_file(LEONIDA_TEST_MS_SPV, library / "ms_draw.spv", std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(LEONIDA_TEST_VS_FULLSCREEN_SPV, library / "vs_fullscreen.spv", + std::filesystem::copy_options::overwrite_existing); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"ms_draw\": {\"stage\": \"ms\", \"fssm_sha256\": \"" << leonida::sha256_hex(ms_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [32, 1, 1], " + "\"max_vertices\": 4, \"max_primitives\": 2},\n" + " \"vs_fullscreen\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"ps_draw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}"; + } + + const auto device_info = [&](bool mesh) { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.shader_dir = library.string(); + info.mesh_shader = mesh; + return info; + }; + const auto make_device = [&](bool mesh, Ref& device) { + ID3D12Device* inner = nullptr; + if (FAILED(rt::d3d12::create_vulkan_device(device_info(mesh), IID_PPV_ARGS(&inner)))) return false; + if (FAILED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))) + return false; + rt::d3d12::set_device_outer(inner, device.p); + return true; + }; + const auto root_signature = [&](ID3D12Device* device, Ref& root) { + // [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint), as in d3d12_draw_test. + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[1].Descriptor = {1, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(root_desc); + return !blob.empty() && + SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p))); + }; + const D3D12_SHADER_BYTECODE ms{ms_container.data(), ms_container.size()}; + const D3D12_SHADER_BYTECODE ps{ps_container.data(), ps_container.size()}; + const D3D12_SHADER_BYTECODE vs{vs_container.data(), vs_container.size()}; + + // Without the extension: no tier, and a mesh PSO is refused as not implemented. + { + Ref device; + Ref root; + EXPECT(make_device(false, device)); + EXPECT(root_signature(device.p, root)); + EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED); + Stream stream; + stream.add(RootSubobject{.inner = root.p}).add(MsSubobject{.inner = ms}).add(PsSubobject{.inner = ps}); + stream.add(TargetsSubobject{.inner = one_target()}); + Ref pso; + EXPECT(create(device.p, stream, pso) == E_NOTIMPL && !pso.p); + root.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + if (!d.mesh_shader) { + std::filesystem::remove_all(library); + std::printf("no VK_EXT_mesh_shader on this device: only the refusal without it was checked\n"); + return 77; + } + + constexpr UINT size = 64; + std::vector pixels(size * 256); + { + Ref device; + Ref root; + EXPECT(make_device(true, device)); + EXPECT(root_signature(device.p, root)); + EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_1); + + // The PSOs. Every other subobject takes its default: back-face culling, depth test on (no DSV here), no + // blending, all samples. + Ref mesh_pso, vs_pso, refused; + Stream mesh_stream; + mesh_stream.add(RootSubobject{.inner = root.p}).add(MsSubobject{.inner = ms}).add(PsSubobject{.inner = ps}); + mesh_stream.add(TargetsSubobject{.inner = one_target()}); + EXPECT(SUCCEEDED(create(device.p, mesh_stream, mesh_pso))); + Stream vs_stream; + vs_stream.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = vs}).add(PsSubobject{.inner = ps}); + vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}); + vs_stream.add(TargetsSubobject{.inner = one_target()}); + EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso))); + + // Streams the PC runtime refuses. + Stream bad = mesh_stream; + bad.add(VsSubobject{.inner = vs}); // a mesh shader and a vertex shader + EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); + bad = mesh_stream; + bad.add(PsSubobject{.inner = ps}); // the same subobject twice + EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); + bad = mesh_stream; + bad.add(CsSubobject{.inner = ps}); // compute with graphics stages + EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); + EXPECT(create(device.p, mesh_stream, refused, 4) == E_INVALIDARG && !refused.p); // truncated + bad = mesh_stream; + bad.add(Subobject{.inner = 0}); // 23 is no subobject type + EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); + Stream empty; + EXPECT(create(device.p, empty.add(MaskSubobject{.inner = UINT_MAX}), refused) == E_INVALIDARG && !refused.p); + // State the layer does not build yet. + bad = mesh_stream; + bad.add(AsSubobject{.inner = vs}); + EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); + bad = mesh_stream; + D3D12_DEPTH_STENCIL_DESC1 bounds{}; + bounds.DepthBoundsTestEnable = TRUE; + bad.add(DepthStencil1Subobject{.inner = bounds}); + EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref upload, readback, target; + const auto upload_desc = buffer_desc(4096); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(size * 256); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = size; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + + // Tints at 0 (red stays red), 256 (green) and 512 (white: yellow stays yellow); CBVs are 256-byte aligned. + const float tints[3][3] = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}}; + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + for (int i = 0; i < 3; ++i) std::memcpy(up + 256 * i, tints[i], sizeof(tints[i])); + const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress(); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref list6; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, mesh_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list6.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + D3D12_RESOURCE_BARRIER to_target = + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + const FLOAT blue[4] = {0, 0, 1, 1}; + list->ClearRenderTargetView(rtv, blue, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + const D3D12_VIEWPORT viewport{0, 0, float(size), float(size), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(size), LONG(size)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + + // Mesh draw 1: a 2x2 grid of quads, no offset, red -> the top-left quadrant. No topology was set: a mesh + // draw does not need one. An empty grid before it records nothing. + const float origin[2] = {0, 0}, down_right[2] = {1, -1}; + list->SetGraphicsRoot32BitConstants(0, 2, origin, 0); + list->SetGraphicsRootConstantBufferView(1, upload_va); + list6->DispatchMesh(0, 1, 1); + list6->DispatchMesh(2, 2, 1); + // Mesh draw 2: groups (0,0,0) and (0,0,1), columns 0 and 1 of row 0, moved by (1, -1), green -> the top half + // of the bottom-right quadrant. + list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0); + list->SetGraphicsRootConstantBufferView(1, upload_va + 256); + list6->DispatchMesh(1, 1, 2); + // The stream's VS PSO: a full-screen triangle through a viewport on the bottom-left quadrant, yellow. + const D3D12_VIEWPORT bottom_left{0, float(size / 2), float(size / 2), float(size / 2), 0, 1}; + list->RSSetViewports(1, &bottom_left); + list->SetPipelineState(vs_pso.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->SetGraphicsRootConstantBufferView(1, upload_va + 512); + list->DrawInstanced(3, 1, 0, 0); + + D3D12_RESOURCE_BARRIER to_copy = + transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, size, size, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(pixels.data(), mapped, pixels.size()); + + // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then + // DispatchMesh with the VS PSO. + for (const bool vertex_draw : {true, false}) { + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, vertex_draw ? mesh_pso.p + : vs_pso.p))); + list->SetGraphicsRootSignature(root.p); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if (vertex_draw) list->DrawInstanced(3, 1, 0, 0); + else list6->DispatchMesh(1, 1, 1); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::invalid_draw); + } + // A grid beyond D3D12's limits (65535 per count, 2^22 groups) is a recording error. + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_pso.p))); + list->SetGraphicsRootSignature(root.p); + list->RSSetViewports(1, &viewport); + list6->DispatchMesh(65536, 1, 1); + EXPECT(list->Close() == E_INVALIDARG); + EXPECT(SUCCEEDED(list->Reset(allocator.p, mesh_pso.p))); + list->SetGraphicsRootSignature(root.p); + list->RSSetViewports(1, &viewport); + list6->DispatchMesh(4096, 1025, 1); + EXPECT(list->Close() == E_INVALIDARG); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); + + for (auto* r : {&upload, &readback, &target}) r->reset(); + for (auto* p : {&mesh_pso, &vs_pso, &refused}) p->reset(); + root.reset(); + rtv_heap.reset(); + list6.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + std::filesystem::remove_all(library); + + unsigned mismatches = 0; + for (UINT row = 0; row < size; ++row) { + for (UINT col = 0; col < size; ++col) { + const bool top = row < size / 2, left = col < size / 2; + using Pixel = std::array; + const Pixel want = top && left ? Pixel{255, 0, 0, 255} + : !top && left ? Pixel{255, 255, 0, 255} + : !top && !left && row < size * 3 / 4 ? Pixel{0, 255, 0, 255} + : Pixel{0, 0, 255, 255}; + const std::uint8_t* got = pixels.data() + row * 256 + col * 4; + if (std::equal(want.begin(), want.end(), got)) continue; + if (mismatches++ < 6) + std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("D3D-29: mesh tier 1; mesh and VS PSOs from pipeline state streams (6 refused as invalid, 2 as not " + "implemented); DispatchMesh over X, Y and Z and a stream VS draw matched all %u pixels; wrong-kind " + "draws fail at execution, oversized grids at Close\n", + size * size); + return 0; +} diff --git a/runtime/test/glsl/ms_draw.mesh b/runtime/test/glsl/ms_draw.mesh new file mode 100644 index 0000000000..8bfd21785d --- /dev/null +++ b/runtime/test/glsl/ms_draw.mesh @@ -0,0 +1,34 @@ +#version 460 +// A mesh shader written to the translator's runtime contract (docs/design.md, "User data" and "Mesh shaders"), +// standing in for a translated one in d3d12_mesh_test. Each workgroup emits one quad (4 vertices, 2 triangles) on a +// 4x4 grid of clip-space cells: column = WorkgroupId.x + WorkgroupId.z, row = WorkgroupId.y, so all three +// DispatchMesh counts reach the shader. s0, s1 (root constants) move the quad in clip space; the colour is red. The +// corners are top-left, top-right, bottom-left, bottom-right and the triangles (0,1,2) and (2,1,3), clockwise in D3D +// screen space as in d3d12_draw_test, so they are front-facing with the default winding. +#extension GL_EXT_mesh_shader : require + +layout(local_size_x = 32) in; +layout(triangles, max_vertices = 4, max_primitives = 2) out; + +layout(location = 0) out vec4 out_color[]; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + SetMeshOutputsEXT(4, 2); + const uint i = gl_LocalInvocationIndex; + const float column = float(gl_WorkGroupID.x + gl_WorkGroupID.z), row = float(gl_WorkGroupID.y); + const vec2 offset = vec2(uintBitsToFloat(pc.s[0]), uintBitsToFloat(pc.s[1])); + if (i < 4) { + const vec2 corner = vec2(float(i & 1u), float(i >> 1)); + const vec2 top_left = vec2(-1.0 + 0.5 * column, 1.0 - 0.5 * row); + gl_MeshVerticesEXT[i].gl_Position = vec4(top_left + vec2(0.5, -0.5) * corner + offset, 0.0, 1.0); + out_color[i] = vec4(1.0, 0.0, 0.0, 1.0); + } + if (i == 0) gl_PrimitiveTriangleIndicesEXT[0] = uvec3(0, 1, 2); + if (i == 1) gl_PrimitiveTriangleIndicesEXT[1] = uvec3(2, 1, 3); +} diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp index a271d75d20..a3957d1669 100644 --- a/runtime/test/replay_cpu_bench.cpp +++ b/runtime/test/replay_cpu_bench.cpp @@ -493,6 +493,7 @@ const char* result_name(ReplayResult r) { case ReplayResult::invalid_predication: return "invalid_predication"; case ReplayResult::invalid_query: return "invalid_query"; case ReplayResult::invalid_indirect_arguments: return "invalid_indirect_arguments"; + case ReplayResult::invalid_draw: return "invalid_draw"; case ReplayResult::unsupported: return "unsupported"; } return "?"; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 114ca187f1..949e5abfba 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -116,6 +116,8 @@ class Device { bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available + bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available + bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. leonida::SubgroupSizeCaps subgroup; @@ -511,6 +513,20 @@ class Device { } } #endif + // VK_EXT_mesh_shader (meshShader only), for the tests that ask for it. + VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; + if (request_mesh_shader && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + mesh_shader = mesh_features.meshShader == VK_TRUE; + } + if (mesh_shader) { + mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; + mesh_features.meshShader = VK_TRUE; + *v13_.next() = &mesh_features; + } enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available enable.pipelineStatisticsQuery = features.features.pipelineStatisticsQuery; occlusion_query_precise = features.features.occlusionQueryPrecise == VK_TRUE; @@ -576,6 +592,7 @@ class Device { if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif if (custom_border_color) device_extensions.push_back(custom_border_color_name); + if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.data(); result = instance_fn("vkCreateDevice")(physical, &device_info, nullptr, &device); From c2376390a8248eb4274e80b75996220e9398eb8c Mon Sep 17 00:00:00 2001 From: lloyd Date: Sun, 22 Nov 2026 18:10:46 +0200 Subject: [PATCH 08/17] D3D-29: versioned depth-stencil/rasterizer subobjects count as duplicates; mesh test skips without Vulkan The stream parser keyed its duplicate check on the raw subobject type, so DEPTH_STENCIL with DEPTH_STENCIL1 (either order) or RASTERIZER with RASTERIZER2 was accepted; D3D12_PIPELINE_STATE_STREAM_DESC counts versions of one subobject as the same one. The check now uses the base type, while the payload still follows the original type. d3d12_mesh_test covers both mixed orders, RASTERIZER + RASTERIZER2, and each description alone. Reported by Vonsek in review. d3d12_mesh_test failed on a machine without a Vulkan device (the Windows CI runner) instead of exiting 77; it now skips there like d3d12_draw_test. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 13 ++++++-- runtime/test/d3d12_mesh_test.cpp | 46 +++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e074ce908b..4082d8b769 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2867,8 +2867,17 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; if (size - at < sizeof(type)) return E_INVALIDARG; std::memcpy(&type, base + at, sizeof(type)); - if (unsigned(type) >= 64 || (seen >> unsigned(type) & 1)) return E_INVALIDARG; - seen |= std::uint64_t(1) << unsigned(type); + // The versioned depth-stencil and rasterizer subobjects describe the same state as their base type, so the + // stream contract counts any two of one family as duplicates; the payload below still follows `type`. + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE family = type; + if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 || + type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2) + family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1 || + type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2) + family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; + if (unsigned(type) >= 64 || (seen >> unsigned(family) & 1)) return E_INVALIDARG; + seen |= std::uint64_t(1) << unsigned(family); bool ok = true; const auto take = [&](auto& value) { using T = std::remove_reference_t; diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 77a4aefc62..5fc6381703 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -4,7 +4,7 @@ // E_NOTIMPL; that part runs on every GPU. The rest needs the extension (exit 77 without it). // - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as // d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime -// refuses (MS with VS, CS with PS, a subobject twice, an unknown type, a truncated stream) are E_INVALIDARG, and +// refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and // state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. // - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; // DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the @@ -51,6 +51,9 @@ using MsSubobject = Subobject; using TargetsSubobject = Subobject; using DepthStencil1Subobject = Subobject; +using DepthStencilSubobject = Subobject; +using RasterizerSubobject = Subobject; +using Rasterizer2Subobject = Subobject; using MaskSubobject = Subobject; // Subobjects appended one after another: each is pointer-aligned and a multiple of the pointer size, so the bytes @@ -95,7 +98,12 @@ D3D12_MESH_SHADER_TIER mesh_tier(ID3D12Device* device) { int main() { vktest::Device d; d.request_mesh_shader = true; - EXPECT(d.create()); + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); const auto ms_program = fssm_program({0x4d530001, 0xbf810000}); const auto ps_program = fssm_program({0x50530001, 0xbf810000}); @@ -218,6 +226,38 @@ int main() { EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); Stream empty; EXPECT(create(device.p, empty.add(MaskSubobject{.inner = UINT_MAX}), refused) == E_INVALIDARG && !refused.p); + // Versions of one subobject count as the same subobject (D3D12_PIPELINE_STATE_STREAM_DESC): DEPTH_STENCIL with + // DEPTH_STENCIL1 in either order, and RASTERIZER with RASTERIZER2. Each description alone is accepted. + const D3D12_DEPTH_STENCIL_DESC depth{FALSE, D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_ALWAYS}; + const D3D12_DEPTH_STENCIL_DESC1 depth1{FALSE, D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_ALWAYS}; + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_SOLID; + raster.CullMode = D3D12_CULL_MODE_NONE; + raster.DepthClipEnable = TRUE; // D3D12's default; depth clamping is not built + D3D12_RASTERIZER_DESC2 raster2{}; + raster2.FillMode = D3D12_FILL_MODE_SOLID; + raster2.CullMode = D3D12_CULL_MODE_NONE; + raster2.DepthClipEnable = TRUE; // D3D12's default; depth clamping is not built + for (int order = 0; order < 2; ++order) { + bad = mesh_stream; + if (order == 0) bad.add(DepthStencilSubobject{.inner = depth}).add(DepthStencil1Subobject{.inner = depth1}); + else bad.add(DepthStencil1Subobject{.inner = depth1}).add(DepthStencilSubobject{.inner = depth}); + EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); + } + bad = mesh_stream; + bad.add(RasterizerSubobject{.inner = raster}).add(Rasterizer2Subobject{.inner = raster2}); + EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p); + for (int which = 0; which < 4; ++which) { + Stream one = mesh_stream; + if (which == 0) one.add(DepthStencilSubobject{.inner = depth}); + if (which == 1) one.add(DepthStencil1Subobject{.inner = depth1}); + if (which == 2) one.add(RasterizerSubobject{.inner = raster}); + if (which == 3) one.add(Rasterizer2Subobject{.inner = raster2}); + Ref accepted; + const HRESULT one_hr = create(device.p, one, accepted); + if (FAILED(one_hr)) std::fprintf(stderr, "single subobject %d: 0x%08lx\n", which, static_cast(one_hr)); + EXPECT(SUCCEEDED(one_hr)); + } // State the layer does not build yet. bad = mesh_stream; bad.add(AsSubobject{.inner = vs}); @@ -393,7 +433,7 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("D3D-29: mesh tier 1; mesh and VS PSOs from pipeline state streams (6 refused as invalid, 2 as not " + std::printf("D3D-29: mesh tier 1; mesh and VS PSOs from pipeline state streams (9 refused as invalid, 2 as not " "implemented); DispatchMesh over X, Y and Z and a stream VS draw matched all %u pixels; wrong-kind " "draws fail at execution, oversized grids at Close\n", size * size); From 7c6d99a231c3cc39386cd85f93fea478531135e2 Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:20:01 +0100 Subject: [PATCH 09/17] DispatchMesh in a bundle: record through defer, as DrawInstanced does main's bundles record their commands through defer() and replay them at ExecuteBundle. Without it, a DispatchMesh in a bundle went into the bundle's own command list and was never replayed. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 5412a8d10b..9f9fd9e4b1 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -440,12 +440,8 @@ class GraphicsCommandList final void STDMETHODCALLTYPE DispatchMesh(UINT x, UINT y, UINT z) override { d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh"); if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); - if (!graphics_pipeline_ || !graphics_.layout) return check(false); - if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, - scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; - draw.mesh = true; - check(list_.draw(std::move(draw))); + if (defer([=](GraphicsCommandList& l) { l.record_mesh_draw(x, y, z); }, true)) return; + record_mesh_draw(x, y, z); } void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { @@ -1203,6 +1199,16 @@ class GraphicsCommandList final return draw_views_; } + // A mesh draw needs a graphics pipeline and a graphics root signature; it has no topology or vertex input. + void record_mesh_draw(UINT x, UINT y, UINT z) { + if (!graphics_pipeline_ || !graphics_.layout) return check(false); + if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized + leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, scissor_, + blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; + draw.mesh = true; + check(list_.draw(std::move(draw))); + } + // A draw needs a graphics pipeline, a graphics root signature and a topology. void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); From 8fc39ab76232a6e4a969edec4314a414f95c258b Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:10:43 +0100 Subject: [PATCH 10/17] Runtime: ExecuteIndirect with DISPATCH_MESH signatures, and the M5 mesh gate with a translated mesh shader CreateCommandSignature takes DISPATCH_MESH where VK_EXT_mesh_shader is enabled (E_NOTIMPL without it). ExecuteIndirect records it with the state DispatchMesh takes, and replay issues vkCmdDrawMeshTasksIndirectEXT, or vkCmdDrawMeshTasksIndirectCountEXT with a count buffer, split by multiDrawIndirect and maxDrawIndirectCount as the draw kinds are. build.py makes the PSV0 container of a mesh shader whose header has a psv0: line, so translated mesh shaders can be layer-test fixtures. d3d12_m5_mesh_test draws ms_m5.asm (NGG wave64, 128 threads, the corpus's v5/s3 idioms) by DispatchMesh and by ExecuteIndirect, error 0. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 31 +- runtime/shims/d3d12_com.cpp | 20 +- runtime/shims/d3d12_vulkan_device.cpp | 6 + runtime/src/command_list.h | 3 +- runtime/src/vulkan_backend.h | 9 +- runtime/src/vulkan_replay.h | 22 +- runtime/test/d3d12_m5_mesh_test.cpp | 483 ++++++++++++++++++++++++++ runtime/test/shaders/build.py | 35 +- runtime/test/shaders/ms_m5.asm | 51 +++ runtime/test/shaders/ps_m5_mesh.asm | 14 + scripts/run_gpu_tests.py | 1 + 11 files changed, 659 insertions(+), 16 deletions(-) create mode 100644 runtime/test/d3d12_m5_mesh_test.cpp create mode 100644 runtime/test/shaders/ms_m5.asm create mode 100644 runtime/test/shaders/ps_m5_mesh.asm diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index d8e8df43bb..edd1c9ff32 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2118,6 +2118,35 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_m5_world_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m5_world COMMAND d3d12_m5_world_test) set_tests_properties(d3d12_m5_world PROPERTIES SKIP_RETURN_CODE 77) + # M5, the mesh part: ms_m5.asm (a translated NGG wave64 mesh shader; build.py makes its PSV0 container from the + # "psv0:" header) with ps_m5_mesh.asm, drawn by DispatchMesh and by ExecuteIndirect with DISPATCH_MESH + # signatures; vs_m3/ps_m5_flat make the VS PSO of the wrong-kind checks. Exits 77 without VK_EXT_mesh_shader. + set(LEONIDA_M5_MESH_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m5_mesh_shaders) + set(LEONIDA_M5_MESH_FILES ${LEONIDA_M5_MESH_DIR}/spirv/index.json ${LEONIDA_M5_MESH_DIR}/fssm/ms_m5.fssm + ${LEONIDA_M5_MESH_DIR}/fssm/ps_m5_mesh.fssm ${LEONIDA_M5_MESH_DIR}/fssm/vs_m3.fssm + ${LEONIDA_M5_MESH_DIR}/fssm/ps_m5_flat.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M5_MESH_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M5_MESH_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M5_MESH_DIR} ms_m5 ps_m5_mesh vs_m3 ps_m5_flat + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ms_m5.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m5_mesh.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m3.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m5_flat.asm + ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py + COMMENT "Translating ms_m5, ps_m5_mesh, vs_m3 and ps_m5_flat for the M5 mesh test" + VERBATIM) + add_executable(d3d12_m5_mesh_test test/d3d12_m5_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M5_MESH_FILES}) + target_link_libraries(d3d12_m5_mesh_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m5_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M5_MESH_DIR="${LEONIDA_M5_MESH_DIR}") + target_compile_options(d3d12_m5_mesh_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m5_mesh COMMAND d3d12_m5_mesh_test) + set_tests_properties(d3d12_m5_mesh PROPERTIES SKIP_RETURN_CODE 77) # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes @@ -2180,7 +2209,7 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_buffer_uav COMMAND d3d12_buffer_uav_test) set_tests_properties(d3d12_buffer_uav PROPERTIES SKIP_RETURN_CODE 77) else() - message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m2_formats_test, d3d12_m3_frame_test, d3d12_m4_compute_test, d3d12_buffer_uav_test and d3d12_m5_world_test are not built") + message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m2_formats_test, d3d12_m3_frame_test, d3d12_m4_compute_test, d3d12_buffer_uav_test, d3d12_m5_world_test and d3d12_m5_mesh_test are not built") endif() # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the # host runtime and WARP; run explicitly on a Vulkan GPU. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 9f9fd9e4b1..1f192b33d4 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -764,11 +764,13 @@ class GraphicsCommandList final // A draw takes the list's graphics state, as DrawInstanced does; with nothing to rasterize it is dropped. A // list with no pipeline, root signature or topology yet records the bare call (it closes, as on the PC // runtime; it is not a call replay can run). + // A DISPATCH_MESH signature takes the state DispatchMesh does: no topology, vertex or index buffers. + const bool mesh = kind == leonida::IndirectKind::dispatch_mesh; if (kind != leonida::IndirectKind::dispatch && max_command_count && graphics_pipeline_ && graphics_.layout && - topology_) { + (topology_ || mesh)) { if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; cmd.state = std::make_shared( - make_draw(kind == leonida::IndirectKind::draw_indexed, 0, 0, 0, 0, 0)); + mesh ? make_mesh_draw(0, 0, 0) : make_draw(kind == leonida::IndirectKind::draw_indexed, 0, 0, 0, 0, 0)); } cmd.kind = kind; cmd.stride = stride; @@ -1203,10 +1205,7 @@ class GraphicsCommandList final void record_mesh_draw(UINT x, UINT y, UINT z) { if (!graphics_pipeline_ || !graphics_.layout) return check(false); if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, scissor_, - blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; - draw.mesh = true; - check(list_.draw(std::move(draw))); + check(list_.draw(make_mesh_draw(x, y, z))); } // A draw needs a graphics pipeline, a graphics root signature and a topology. @@ -1218,6 +1217,15 @@ class GraphicsCommandList final check(list_.draw(make_draw(indexed, count, instances, first, base_vertex, first_instance))); } + // The list's graphics state as a mesh draw: no vertex input or input assembly; the group counts go in + // count/instances/first. + leonida::Draw make_mesh_draw(UINT x, UINT y, UINT z) { + leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, scissor_, + blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; + draw.mesh = true; + return draw; + } + // The list's graphics state as a draw (see record_draw for what has to be set). leonida::Draw make_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e47d7019b7..5d390ec220 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5568,6 +5568,12 @@ class Device final case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: kind = leonida::IndirectKind::draw; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: + // Replayed as vkCmdDrawMeshTasksIndirect(Count)EXT; without VK_EXT_mesh_shader there is no mesh PSO to + // run it with (the device reports MeshShaderTier NOT_SUPPORTED then). + if (!state_.info.mesh_shader || !state_.context->vk.vkCmdDrawMeshTasksIndirectEXT) return E_NOTIMPL; + kind = leonida::IndirectKind::dispatch_mesh; + break; default: return E_NOTIMPL; } return create_command_signature(kind, desc->ByteStride, riid, out, identity()); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 22febb8b6f..cdfb23ea80 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -587,6 +587,7 @@ enum class IndirectKind : std::uint8_t { draw = 0, draw_indexed = 1, dispatch = 2, + dispatch_mesh = 3, // D3D12_DISPATCH_MESH_ARGUMENTS, the same 12 bytes as VkDrawMeshTasksIndirectCommandEXT }; struct ExecuteIndirect { @@ -598,7 +599,7 @@ struct ExecuteIndirect { ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount std::uint64_t count_offset = 0; // The list's graphics state at the call (its count, instances and first fields are unused: the argument buffer - // holds them), for the draw kinds. Replay then makes the call a whole draw: it begins rendering into the targets, + // holds them), for the draw kinds and dispatch_mesh (whose state has `mesh` set, as DispatchMesh records it). Replay then makes the call a whole draw: it begins rendering into the targets, // binds the pipeline and the dynamic state as for a Draw, and issues the indirect draw. Null: the caller has set // all that up (a raw indirect call), as the unit tests of the indirect path do. std::shared_ptr state; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index da5cbe8cd5..3a5312010a 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -98,7 +98,7 @@ struct VulkanDeviceFunctions { X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ - X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) + X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER @@ -958,6 +958,8 @@ class VulkanContext { replay_.set_blend_constants = vk.vkCmdSetBlendConstants; replay_.draw = vk.vkCmdDraw; replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled + replay_.draw_mesh_tasks_indirect = vk.vkCmdDrawMeshTasksIndirectEXT; + replay_.draw_mesh_tasks_indirect_count = vk.vkCmdDrawMeshTasksIndirectCountEXT; replay_.draw_indexed = vk.vkCmdDrawIndexed; replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { const auto it = graphics_pipelines_.find(id); @@ -1229,7 +1231,10 @@ class VulkanContext { void set_indirect_features(bool multi_draw, bool draw_count, std::uint32_t max_draw_count = UINT32_MAX) { replay_.multi_draw_indirect = multi_draw; replay_.max_draw_indirect_count = max_draw_count; - if (!draw_count) replay_.draw_indirect_count = replay_.draw_indexed_indirect_count = nullptr; + if (!draw_count) { + replay_.draw_indirect_count = replay_.draw_indexed_indirect_count = nullptr; + replay_.draw_mesh_tasks_indirect_count = nullptr; + } } void set_heap_base(std::uint64_t heap_base) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 29543f2ecd..37ec4c1f53 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -886,6 +886,9 @@ struct ReplayFunctions { std::function prepare_counted_dispatch; std::function emit_counted_dispatch; + // VK_EXT_mesh_shader: DISPATCH_MESH signatures. The count variant also needs drawIndirectCount. + PFN_vkCmdDrawMeshTasksIndirectEXT draw_mesh_tasks_indirect = nullptr; + PFN_vkCmdDrawMeshTasksIndirectCountEXT draw_mesh_tasks_indirect_count = nullptr; // multiDrawIndirect: one vkCmdDraw*Indirect may take a drawCount above 1; without it each command is its own call. bool multi_draw_indirect = false; // VkPhysicalDeviceLimits::maxDrawIndirectCount: a call takes at most this many records. @@ -1533,6 +1536,7 @@ inline VkDeviceSize indirect_record_size(IndirectKind kind) { case IndirectKind::draw: return sizeof(VkDrawIndirectCommand); case IndirectKind::draw_indexed: return sizeof(VkDrawIndexedIndirectCommand); case IndirectKind::dispatch: return sizeof(VkDispatchIndirectCommand); + case IndirectKind::dispatch_mesh: return sizeof(VkDrawMeshTasksIndirectCommandEXT); } return 0; } @@ -2225,6 +2229,9 @@ inline void emit_indirect(const ReplayFunctions& vk, VkCommandBuffer command_buf } else if (ind.kind == IndirectKind::draw_indexed) { vk.draw_indexed_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, count, ind.max_count, ind.stride); + } else if (ind.kind == IndirectKind::dispatch_mesh) { + vk.draw_mesh_tasks_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, count, + ind.max_count, ind.stride); } return; } @@ -2246,6 +2253,15 @@ inline void emit_indirect(const ReplayFunctions& vk, VkCommandBuffer command_buf ind.stride); k += n; } + } else if (ind.kind == IndirectKind::dispatch_mesh) { + // multiDrawIndirect and maxDrawIndirectCount bound a mesh call's drawCount as they bound a draw's + // (VUID-vkCmdDrawMeshTasksIndirectEXT-drawCount-02718/02719). + for (std::uint64_t k = 0; k < ind.max_count;) { + const std::uint32_t n = std::uint32_t(std::min(per_call, ind.max_count - k)); + vk.draw_mesh_tasks_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind.stride, n, + ind.stride); + k += n; + } } else if (ind.kind == IndirectKind::dispatch) { for (std::uint64_t k = 0; k < ind.max_count; ++k) { if (ind.count_buffer) @@ -2992,13 +3008,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun ind->stride, ind->max_count, p.counted_dispatch)) return ReplayResult::unsupported; } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || - (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { + (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count) || + (ind->kind == IndirectKind::dispatch_mesh && !vk.draw_mesh_tasks_indirect_count)) { return ReplayResult::unsupported; } } else { if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || - (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) + (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect) || + (ind->kind == IndirectKind::dispatch_mesh && !vk.draw_mesh_tasks_indirect)) return ReplayResult::unsupported; } if (ind->kind != IndirectKind::dispatch && !ind->state && !ind->raw) return ReplayResult::unsupported; diff --git a/runtime/test/d3d12_m5_mesh_test.cpp b/runtime/test/d3d12_m5_mesh_test.cpp new file mode 100644 index 0000000000..f7811f57c6 --- /dev/null +++ b/runtime/test/d3d12_m5_mesh_test.cpp @@ -0,0 +1,483 @@ +// Milestone M5 (docs/d3d12_vulkan.md section 6), the mesh part: translated mesh shaders through the D3D12 API on the +// proxy, drawn by DispatchMesh and by ExecuteIndirect with DISPATCH_MESH command signatures, with every pixel compared +// with a CPU reference (error 0). The shaders are translator output (hand-written RDNA2 in test/shaders): ms_m5.asm, +// an NGG wave64 mesh shader of 128 threads written with the corpus's idioms (the group index from v5, the thread id +// from s3 and mbcnt, GS_ALLOC_REQ, one vertex and one primitive export per thread), and ps_m5_mesh.asm. Each mesh group +// draws one quad into cell (first cell + linear group index) of an 8x8 grid on a 64x64 target, in a colour from root +// constants; the mesh PSOs are built from pipeline state streams. +// +// (a) DispatchMesh: a 4x2x2 grid (all three counts reach the shader: 16 cells, so every group got its own index), a +// 3x1x1 grid and a 1x1x1 grid at other first cells and colours, and an empty grid that draws nothing. +// (b) ExecuteIndirect with DISPATCH_MESH signatures, with additive blending, so a cell's colour counts the records +// whose group count reached it, and each record's counts show in the pixels: +// I1 5 CPU-written records, stride 12, at argument offset 36, one of them empty; +// I2 4 records, stride 24, copied by the GPU into a default buffer (COPY_DEST -> INDIRECT_ARGUMENT) at offset +// 48, with a count buffer holding 3 (so the 4th record is not drawn); +// I3 a count of 0: nothing; +// I4 a count of 7 against MaxCommandCount 2: the first two records only; +// I5 20 records of one group each, without a count buffer: one call of 20 (or 20 calls without +// multiDrawIndirect). +// Without drawIndirectCount, I2..I4 are left out. +// (c) Refusals: a DISPATCH_MESH signature whose stride is below 12 is E_INVALIDARG; one on a device without +// VK_EXT_mesh_shader is E_NOTIMPL; a DISPATCH_MESH signature run with a VS PSO, and a DRAW signature with the mesh +// PSO, fail at execution (ReplayResult::invalid_draw). +// Needs VK_EXT_mesh_shader (exit 77 without it). No game data. Set LEONIDA_VK_VALIDATION=1 to run under +// VK_LAYER_KHRONOS_validation (0 errors required). +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M5_MESH_DIR +#error "LEONIDA_TEST_M5_MESH_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +// One pipeline state stream subobject as d3dx12.h declares it (CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT). +template +struct alignas(void*) Subobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type; + Inner inner; +}; +using RootSubobject = Subobject; +using MsSubobject = Subobject; +using VsSubobject = Subobject; +using PsSubobject = Subobject; +using TopologySubobject = Subobject; +using TargetsSubobject = Subobject; +using BlendSubobject = Subobject; +using DepthStencilSubobject = Subobject; +using RasterizerSubobject = Subobject; + +struct Stream { + std::vector bytes; + template + Stream& add(const S& subobject) { + static_assert(sizeof(S) % sizeof(void*) == 0); + const std::size_t at = bytes.size(); + bytes.resize(at + sizeof(S)); + std::memcpy(bytes.data() + at, &subobject, sizeof(S)); + return *this; + } +}; + +using Pixel = std::array; + +struct Image { + std::vector pixels; + explicit Image(Pixel fill) : pixels(64 * 64, fill) {} + Pixel& at(UINT x, UINT y) { return pixels[std::size_t(y) * 64 + x]; } + // Cell k of the 8x8 grid (cells past 63 are off the target). + template + void cell(unsigned k, F&& f) { + if (k >= 64) return; + for (UINT y = 0; y < 8; ++y) + for (UINT x = 0; x < 8; ++x) f(at((k & 7) * 8 + x, (k >> 3) * 8 + y)); + } +}; + +unsigned compare(const char* what, const std::uint8_t* got, UINT pitch, Image& want) { + unsigned mismatches = 0; + for (UINT y = 0; y < 64; ++y) + for (UINT x = 0; x < 64; ++x) { + const std::uint8_t* g = got + std::size_t(y) * pitch + x * 4; + const Pixel& w = want.at(x, y); + if (std::memcmp(g, w.data(), 4) == 0) continue; + if (mismatches++ < 6) + std::fprintf(stderr, "%s pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", what, x, y, g[0], g[1], + g[2], g[3], w[0], w[1], w[2], w[3]); + } + return mismatches; +} + +// The root constants of ms_m5.asm: s0 = the first cell, s1, s2 = red and green (k / 255). +struct Constants { + UINT first; + float r, g; +}; +Constants constants(UINT first, unsigned r, unsigned g) { return {first, float(r) / 255.0f, float(g) / 255.0f}; } + +} // namespace + +int main() { + vktest::Device d; + d.request_mesh_shader = true; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + + const std::filesystem::path root_dir = LEONIDA_TEST_M5_MESH_DIR; + leonida::ShaderLibrary library; + EXPECT(library.load((root_dir / "spirv").string())); + const auto container_of = [&](const char* name, const char* stage, std::vector& out) { + const auto program = read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); + if (program.size() < 4 || !library.find(stage, leonida::sha256_hex(program))) return false; + out = shader_container(program); + return true; + }; + std::vector ms_bytes, ps_bytes, vs_rect, ps_flat; + EXPECT(container_of("ms_m5", "ms", ms_bytes) && container_of("ps_m5_mesh", "ps", ps_bytes) && + container_of("vs_m3", "vs", vs_rect) && container_of("ps_m5_flat", "ps", ps_flat)); + const D3D12_SHADER_BYTECODE ms{ms_bytes.data(), ms_bytes.size()}, ps{ps_bytes.data(), ps_bytes.size()}; + + const auto device_info = [&](bool mesh) { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.multi_draw_indirect = d.multi_draw_indirect; + info.draw_indirect_count = d.draw_indirect_count; + info.max_draw_indirect_count = d.max_draw_indirect_count; + info.mesh_shader = mesh; + info.shader_dir = (root_dir / "spirv").string(); + return info; + }; + const auto make_device = [&](bool mesh, Ref& device) { + ID3D12Device* inner = nullptr; + if (FAILED(rt::d3d12::create_vulkan_device(device_info(mesh), IID_PPV_ARGS(&inner)))) return false; + if (FAILED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))) + return false; + rt::d3d12::set_device_outer(inner, device.p); + return true; + }; + const auto mesh_signature = [](ID3D12Device* device, UINT stride, Ref& out) { + D3D12_INDIRECT_ARGUMENT_DESC arg{}; + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const D3D12_COMMAND_SIGNATURE_DESC desc{stride, 1, &arg, 0}; + out.reset(); + return device->CreateCommandSignature(&desc, nullptr, IID_PPV_ARGS(&out.p)); + }; + + // (c) Without the extension, a DISPATCH_MESH signature is not implemented. + { + Ref device; + Ref sig; + EXPECT(make_device(false, device)); + EXPECT(mesh_signature(device.p, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), sig) == E_NOTIMPL && !sig.p); + } + if (!d.mesh_shader) { + std::printf("no VK_EXT_mesh_shader on this device: only the refusal without it was checked\n"); + return 77; + } + const bool counts = d.draw_indirect_count; + if (!d.multi_draw_indirect) std::printf("note: no multiDrawIndirect: the layer issues one call per record\n"); + if (!counts) std::printf("note: no drawIndirectCount: the count-buffer calls (I2, I3, I4) are not run\n"); + + unsigned direct_mismatches = 0, indirect_mismatches = 0, records_drawn = 0; + { + Ref device; + EXPECT(make_device(true, device)); + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + UINT64 fence_value = 0; + // Runs one list and waits; the replay result of the submission. + const auto run = [&](ID3D12GraphicsCommandList* list) { + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + const auto result = rt::d3d12::last_execute_result(queue.p); + ++fence_value; + if (FAILED(queue->Signal(fence.p, fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) + return leonida::ReplayResult::unsupported; + return result; + }; + const auto new_buffer = [&](const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes, D3D12_RESOURCE_STATES state, + Ref& out) { + const auto desc = buffer_desc(bytes); + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + + // [0] three 32-bit constants: s0..s2. + Ref root; + { + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {0, 0, 3}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(root_desc); + EXPECT(!blob.empty() && + SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); + } + + // The PSOs: the mesh one opaque and additive, from streams; a VS PSO (vs_m3 + ps_m5_flat) for (c). + D3D12_RT_FORMAT_ARRAY formats{}; + formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + formats.NumRenderTargets = 1; + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_SOLID; + raster.CullMode = D3D12_CULL_MODE_NONE; + raster.DepthClipEnable = TRUE; + const D3D12_DEPTH_STENCIL_DESC no_depth{FALSE, D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_ALWAYS}; + D3D12_BLEND_DESC opaque{}; + opaque.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + D3D12_BLEND_DESC additive = opaque; + additive.RenderTarget[0].BlendEnable = TRUE; + additive.RenderTarget[0].SrcBlend = additive.RenderTarget[0].DestBlend = D3D12_BLEND_ONE; + additive.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; + additive.RenderTarget[0].SrcBlendAlpha = additive.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; + additive.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; + Ref device2; + EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device2.p)))); + const auto stream_pso = [&](Stream& stream, Ref& out) { + const D3D12_PIPELINE_STATE_STREAM_DESC desc{stream.bytes.size(), stream.bytes.data()}; + return SUCCEEDED(device2->CreatePipelineState(&desc, IID_PPV_ARGS(&out.p))); + }; + Ref mesh_opaque, mesh_additive, vs_pso; + { + Stream s; + s.add(RootSubobject{.inner = root.p}).add(MsSubobject{.inner = ms}).add(PsSubobject{.inner = ps}); + s.add(TargetsSubobject{.inner = formats}).add(RasterizerSubobject{.inner = raster}); + s.add(DepthStencilSubobject{.inner = no_depth}); + Stream a = s; + s.add(BlendSubobject{.inner = opaque}); + a.add(BlendSubobject{.inner = additive}); + EXPECT(stream_pso(s, mesh_opaque) && stream_pso(a, mesh_additive)); + Stream v; + v.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = {vs_rect.data(), vs_rect.size()}}); + v.add(PsSubobject{.inner = {ps_flat.data(), ps_flat.size()}}); + v.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}); + v.add(TargetsSubobject{.inner = formats}).add(RasterizerSubobject{.inner = raster}); + v.add(DepthStencilSubobject{.inner = no_depth}).add(BlendSubobject{.inner = opaque}); + EXPECT(stream_pso(v, vs_pso)); + } + + // The target, its RTV and readback. + Ref target, readback; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = 64; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COPY_SOURCE, nullptr, + IID_PPV_ARGS(&target.p)))); + constexpr UINT pitch = 256; + EXPECT(new_buffer(readback_heap, pitch * 64, D3D12_RESOURCE_STATE_COPY_DEST, readback)); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + Ref allocator; + Ref list; + Ref list6; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list6.p)))); + // Reset, COPY_SOURCE -> RENDER_TARGET, a clear, the pipeline and the target state. + const auto begin = [&](ID3D12PipelineState* pso, const FLOAT (&clear)[4]) { + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, pso))) return false; + const auto barrier = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &barrier); + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + const D3D12_VIEWPORT viewport{0, 0, 64, 64, 0, 1}; + const D3D12_RECT scissor{0, 0, 64, 64}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + return true; + }; + const auto end = [&]() { + const auto barrier = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + return SUCCEEDED(list->Close()); + }; + const auto set_constants = [&](const Constants& c) { list->SetGraphicsRoot32BitConstants(0, 3, &c, 0); }; + const auto check = [&](const char* what, Image& want) { + std::uint8_t* mapped = nullptr; + const D3D12_RANGE range{0, pitch * 64}; + if (FAILED(readback->Map(0, &range, reinterpret_cast(&mapped)))) return 64u * 64u; + const unsigned bad = compare(what, mapped, pitch, want); + readback->Unmap(0, nullptr); + return bad; + }; + + // ===== (a) DispatchMesh ===== + { + const FLOAT grey[4] = {0.5f, 0.5f, 0.5f, 1.0f}; + Image want({128, 128, 128, 255}); + EXPECT(begin(mesh_opaque.p, grey)); + set_constants(constants(0, 200, 40)); + list6->DispatchMesh(4, 2, 2); + for (unsigned k = 0; k < 16; ++k) want.cell(k, [](Pixel& p) { p = {200, 40, 0, 255}; }); + set_constants(constants(20, 60, 220)); + list6->DispatchMesh(3, 1, 1); + for (unsigned k = 20; k < 23; ++k) want.cell(k, [](Pixel& p) { p = {60, 220, 0, 255}; }); + set_constants(constants(40, 255, 255)); + list6->DispatchMesh(0, 1, 1); // empty: nothing + set_constants(constants(63, 10, 250)); + list6->DispatchMesh(1, 1, 1); + want.cell(63, [](Pixel& p) { p = {10, 250, 0, 255}; }); + EXPECT(end()); + EXPECT(run(list.p) == leonida::ReplayResult::success); + direct_mismatches = check("DispatchMesh", want); + } + + // ===== (b) ExecuteIndirect with DISPATCH_MESH ===== + { + Ref sig12, sig24, refused; + EXPECT(SUCCEEDED(mesh_signature(device.p, 12, sig12)) && SUCCEEDED(mesh_signature(device.p, 24, sig24))); + EXPECT(mesh_signature(device.p, 8, refused) == E_INVALIDARG && !refused.p); // (c) stride below a record + + // The CPU-written records (I1, I4, I5) in an upload buffer; I2's records and the count words staged in a + // second one and copied into default buffers by the GPU. + Ref args_cpu, staging, args_gpu, count_gpu; + EXPECT(new_buffer(upload_heap, 4096, D3D12_RESOURCE_STATE_GENERIC_READ, args_cpu)); + EXPECT(new_buffer(upload_heap, 4096, D3D12_RESOURCE_STATE_GENERIC_READ, staging)); + EXPECT(new_buffer(default_heap, 1024, D3D12_RESOURCE_STATE_COPY_DEST, args_gpu)); + EXPECT(new_buffer(default_heap, 256, D3D12_RESOURCE_STATE_COPY_DEST, count_gpu)); + std::uint8_t* cpu = nullptr; + std::uint8_t* stage = nullptr; + EXPECT(SUCCEEDED(args_cpu->Map(0, nullptr, reinterpret_cast(&cpu)))); + EXPECT(SUCCEEDED(staging->Map(0, nullptr, reinterpret_cast(&stage)))); + std::memset(cpu, 0xA5, 4096); // bytes outside the records are never read + std::memset(stage, 0xA5, 4096); + const auto put = [](std::uint8_t* at, UINT x, UINT y, UINT z) { + const D3D12_DISPATCH_MESH_ARGUMENTS record{x, y, z}; + std::memcpy(at, &record, sizeof(record)); + }; + // Each call draws from its first cell with an increment of colour per record; cell first + j gets the + // increment once for each drawn record of more than j groups. + const FLOAT black[4] = {0, 0, 0, 1}; + Image want({0, 0, 0, 255}); + const auto expect_records = [&](UINT first, unsigned dr, unsigned dg, const std::vector& groups) { + for (const unsigned n : groups) { + for (unsigned j = 0; j < n; ++j) + want.cell(first + j, [&](Pixel& p) { + p[0] = std::uint8_t(std::min(255u, p[0] + dr)); + p[1] = std::uint8_t(std::min(255u, p[1] + dg)); + }); + ++records_drawn; + } + }; + // I1: offset 36, stride 12: 3, 0, 2, 4 and 1 groups (as 3x1x1, 0x5x1, 1x2x1, 2x1x2, 1x1x1). + put(cpu + 36, 3, 1, 1); + put(cpu + 48, 0, 5, 1); + put(cpu + 60, 1, 2, 1); + put(cpu + 72, 2, 1, 2); + put(cpu + 84, 1, 1, 1); + expect_records(0, 32, 0, {3, 0, 2, 4, 1}); + // I4: offset 256, stride 12, three records (1, 2 and 4 groups) under a count of 7 and MaxCommandCount 2. + put(cpu + 256, 1, 1, 1); + put(cpu + 268, 2, 1, 1); + put(cpu + 280, 4, 1, 1); + if (counts) expect_records(40, 0, 64, {1, 2}); + // I5: offset 512, stride 12, 20 records of one group each. + for (unsigned r = 0; r < 20; ++r) put(cpu + 512 + 12 * r, 1, 1, 1); + expect_records(48, 8, 8, std::vector(20, 1)); + // I2 (staged at 0, copied to args_gpu at 48): stride 24, 4, 3, 5 and 8 groups, the count 3 drops the 8. + put(stage + 0, 2, 2, 1); + put(stage + 24, 1, 1, 3); + put(stage + 48, 5, 1, 1); + put(stage + 72, 8, 1, 1); + if (counts) expect_records(16, 0, 32, {4, 3, 5}); + // The count words, staged at 2048: 3 (I2, copied to count_gpu at 16), 0 (I3, at 20), 7 (I4, at 24). + const std::uint32_t words[3] = {3, 0, 7}; + std::memcpy(stage + 2048, words, sizeof(words)); + + EXPECT(begin(mesh_additive.p, black)); + list->CopyBufferRegion(args_gpu.p, 48, staging.p, 0, 96); + list->CopyBufferRegion(count_gpu.p, 16, staging.p, 2048, 12); + const D3D12_RESOURCE_BARRIER to_args[2] = { + transition(args_gpu.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + transition(count_gpu.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT)}; + list->ResourceBarrier(2, to_args); + set_constants(constants(0, 32, 0)); + list->ExecuteIndirect(sig12.p, 5, args_cpu.p, 36, nullptr, 0); + if (counts) { + set_constants(constants(16, 0, 32)); + list->ExecuteIndirect(sig24.p, 4, args_gpu.p, 48, count_gpu.p, 16); + set_constants(constants(32, 255, 255)); + list->ExecuteIndirect(sig24.p, 4, args_gpu.p, 48, count_gpu.p, 20); // I3: a count of 0 + set_constants(constants(40, 0, 64)); + list->ExecuteIndirect(sig12.p, 2, args_cpu.p, 256, count_gpu.p, 24); + } + set_constants(constants(48, 8, 8)); + list->ExecuteIndirect(sig12.p, 20, args_cpu.p, 512, nullptr, 0); + EXPECT(end()); + const auto result = run(list.p); + if (result != leonida::ReplayResult::success) + std::fprintf(stderr, "indirect mesh replay: %d\n", int(result)); + EXPECT(result == leonida::ReplayResult::success); + indirect_mismatches = check("ExecuteIndirect DISPATCH_MESH", want); + + // ===== (c) a draw of the wrong kind fails at execution ===== + Ref sig_draw; + { + D3D12_INDIRECT_ARGUMENT_DESC arg{}; + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; + const D3D12_COMMAND_SIGNATURE_DESC desc{sizeof(D3D12_DRAW_ARGUMENTS), 1, &arg, 0}; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&desc, nullptr, IID_PPV_ARGS(&sig_draw.p)))); + } + EXPECT(begin(vs_pso.p, black)); // a DISPATCH_MESH signature with a VS PSO + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->ExecuteIndirect(sig12.p, 1, args_cpu.p, 36, nullptr, 0); + EXPECT(end()); + EXPECT(run(list.p) == leonida::ReplayResult::invalid_draw); + EXPECT(begin(mesh_opaque.p, black)); // a DRAW signature with the mesh PSO + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->ExecuteIndirect(sig_draw.p, 1, args_cpu.p, 512, nullptr, 0); + EXPECT(end()); + EXPECT(run(list.p) == leonida::ReplayResult::invalid_draw); + args_cpu->Unmap(0, nullptr); + staging->Unmap(0, nullptr); + } + } + + std::printf("mesh tier 1, translated wave64 mesh shader (128 threads): DispatchMesh 4x2x2, 3x1x1, 1x1x1 and an empty " + "grid, %u mismatched pixels; ExecuteIndirect DISPATCH_MESH, %u records drawn%s, %u mismatched pixels; " + "wrong-kind indirect draws fail at execution\n", + direct_mismatches, records_drawn, counts ? " (count buffers included)" : " (no count buffers)", + indirect_mismatches); + return direct_mismatches == 0 && indirect_mismatches == 0 ? 0 : 1; +} diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index b8dcdab0e0..6772abd961 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -13,8 +13,9 @@ SHA-256 goes into the index as fssm_sha256, which is what the layer looks a PSO's shader up by (the translator hashes /fssm/.fssm for the game's programs, and compute shaders here already). A test builds the shader container from that file. The words are also what a shader reads through s_getpc_b64 (the code base) at that offset. -The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this -doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container). +The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0: a mesh shader +whose header has "; psv0: THREADS MAX_VERTICES MAX_PRIMITIVES" gets one (triangles; ms_container), the others are not +built (scripts/run_gpu_tests.py makes theirs). Geometry shaders (gs_) get gs_tri's signatures (gs_container). The comment at the top of each .asm says which test program to run on the result and what it should print. With LEONIDA_FMA=khr (or glsl, or exact), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77), --fma glsl, or --fma exact @@ -66,6 +67,18 @@ def asm_mattr(path): CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} +def asm_psv0(path): + """(threads, max vertices, max primitives) of a mesh shader's "psv0" header comment, or None.""" + for ln in Path(path).read_text(encoding="utf-8").splitlines(): + s = ln.strip() + if s and not s.startswith(";"): + break + m = re.match(r";\s*psv0:\s*(\d+)\s+(\d+)\s+(\d+)\s*$", s) + if m: + return tuple(int(v) for v in m.groups()) + return None + + def asm_fssm_fields(path): """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" at, words = None, [] @@ -124,6 +137,18 @@ def gs_container(): + b"ISG1" + chunk + b"OSG1" + chunk) +def ms_container(threads, max_vertices, max_primitives): + # One PSV0 chunk, as scripts/run_gpu_tests.py's make_ms_psv0 lays it out: the mesh stage (13), triangles (2), the + # output counts and NumThreads (threads x 1 x 1), no group-shared bytes. + psv = bytearray(48) + struct.pack_into("> 7, as all 9,282 corpus mesh shaders do), the +; thread id from the wave index in s3[27:24] and mbcnt, GS_ALLOC_REQ with m0 = prims << 12 | verts, and one vertex +; and one primitive export per thread. Run: d3d12_m5_mesh_test (found by the SHA-256 of its FSSM program). +; psv0: 128 128 128 +; Each group draws one quad, 4 vertices and 2 triangles, into cell k of an 8x8 grid on a 64x64 target: +; L = v5 >> 7, the linear group index (x + X * (y + Y * z) of the DispatchMesh grid, as the translator numbers it) +; k = L + s0 (s0, a root constant: the first cell); column k & 7, row k >> 3 (cells k >= 64 are off the target) +; thread t < 4: vertex t at corner (t & 1, t >> 1) of the cell, pos0 = (col / 4 - 1, 1 - row / 4, 0, 1), and +; param0 = (s1, s2, 0, 1.0), the colour (root constants, floats); t = 0, 1: triangles (0, 1, 2) and (2, 1, 3) +; The user data are read from s0 as the layer packs root constants today (docs/d3d12_vulkan.md, section 3.5; the corpus +; reads mesh user data from s16, a base the layer does not apply yet). s3 is not user data here: it is the merged wave +; info, so a fourth root dword is out of a mesh shader's reach under that packing. Every value is exact (quarters). +; fssm-at: 0x10 +; fssm-data: 0x354d534d 0x20534d20 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_bfe_u32 s8, s3, 0x40018 +v_lshl_add_u32 v0, s8, 6, v0 +v_readfirstlane_b32 s9, v5 +s_lshr_b32 s9, s9, 7 +s_add_u32 s9, s9, s0 +s_and_b32 s10, s9, 7 +s_lshr_b32 s11, s9, 3 +v_and_b32_e32 v1, 1, v0 +v_lshrrev_b32_e32 v2, 1, v0 +v_and_b32_e32 v2, 1, v2 +v_add_nc_u32_e32 v1, s10, v1 +v_add_nc_u32_e32 v2, s11, v2 +v_cvt_f32_u32_e32 v1, v1 +v_cvt_f32_u32_e32 v2, v2 +v_mul_f32_e32 v1, 0x3e800000, v1 +v_add_f32_e32 v1, -1.0, v1 +v_mul_f32_e32 v2, 0xbe800000, v2 +v_add_f32_e32 v2, 1.0, v2 +v_mov_b32_e32 v3, s1 +v_mov_b32_e32 v4, s2 +v_mov_b32_e32 v6, 0 +v_mov_b32_e32 v7, 1.0 +v_mov_b32_e32 v8, 0 +v_mov_b32_e32 v10, 0x300402 +v_cmp_eq_u32_e32 vcc_lo, 1, v0 +v_cndmask_b32_e32 v9, 0x200400, v10, vcc_lo +s_mov_b32 m0, 0x2004 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +v_cmpx_gt_u32_e32 4, v0 +exp pos0 v1, v2, v8, v7 done +exp param0 v3, v4, v6, v7 +v_cmpx_gt_u32_e32 2, v0 +exp prim v9, off, off, off done +s_endpgm diff --git a/runtime/test/shaders/ps_m5_mesh.asm b/runtime/test/shaders/ps_m5_mesh.asm new file mode 100644 index 0000000000..aa03a4eb68 --- /dev/null +++ b/runtime/test/shaders/ps_m5_mesh.asm @@ -0,0 +1,14 @@ +; M5 pixel shader for the mesh draws: mrt0 = param0, the colour ms_m5.asm passes (constant over each quad, so the +; interpolation returns it exactly). Run: d3d12_m5_mesh_test. +; fssm-at: 0x10 +; fssm-data: 0x48534d50 0x20535020 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_interp_p1_f32_e32 v4, v0, attr0.z +v_interp_p2_f32_e32 v4, v1, attr0.z +v_interp_p1_f32_e32 v5, v0, attr0.w +v_interp_p2_f32_e32 v5, v1, attr0.w +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 9b749ec7e7..ecff5f345c 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -599,6 +599,7 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, "ps_m3_post": "d3d12_m3_frame_test", "ps_m3_query": "d3d12_m3_frame_test", "vs_m5": "d3d12_m5_world_test", "ps_m5_inst": "d3d12_m5_world_test", "ps_m5_flat": "d3d12_m5_world_test", "ps_m5_tex": "d3d12_m5_world_test", + "ms_m5": "d3d12_m5_mesh_test", "ps_m5_mesh": "d3d12_m5_mesh_test", "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test", "ps_live_width": "w64_graphics.py"} From 132e7807518ec0cba75d0cc2e13502d5e11f5cc0 Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:13:47 +0100 Subject: [PATCH 11/17] docs, tests: DISPATCH_MESH signatures and the M5 mesh gate; build.py mesh container test AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 25 ++++++++++++-- tests/test_shader_build_mesh.py | 59 +++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 tests/test_shader_build_mesh.py diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 94abe0fdfe..cc3b185984 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2081,6 +2081,24 @@ The trace will enumerate them. - **The three draws:** a 2×2×1 and a 1×1×2 mesh grid, plus a VS PSO from a stream. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +- **`ExecuteIndirect` with `DISPATCH_MESH` signatures:** `CreateCommandSignature` takes them where + `VK_EXT_mesh_shader` is enabled (`E_NOTIMPL` without it, as mesh PSOs are); `IndirectKind::dispatch_mesh`. + `D3D12_DISPATCH_MESH_ARGUMENTS` and `VkDrawMeshTasksIndirectCommandEXT` are the same three dwords, so the records + are read as they are. The call records the state `DispatchMesh` takes (no topology, vertex or index buffers) and + replays as a whole draw issuing `vkCmdDrawMeshTasksIndirectEXT`, or `vkCmdDrawMeshTasksIndirectCountEXT` with a + count buffer (which also needs `drawIndirectCount`; without it the call is `ReplayResult::unsupported`). As for the + draw kinds, a call takes at most `maxDrawIndirectCount` records, and one record without `multiDrawIndirect` + (VUID-vkCmdDrawMeshTasksIndirectEXT-drawCount-02718/02719). A record's group counts are GPU data, so D3D12's limits + (65535 per count, 2^22 groups) are not checked; counts past the device's `maxMeshWorkGroupCount` are undefined on + both APIs. A DISPATCH_MESH call with a VS PSO, or a draw signature with a mesh PSO, is `ReplayResult::invalid_draw`. +- **Translated mesh shaders through the layer:** `d3d12_m5_mesh_test` (section 6, M5) draws `ms_m5.asm`, an NGG + wave64 mesh shader of 128 threads written with the corpus's idioms (group index from `v5`, thread id from `s3` and + `mbcnt`, `GS_ALLOC_REQ`, per-thread exports), translated by `rdna2spirv.py` and run at required subgroup size 64. + `runtime/test/shaders/build.py` makes a mesh shader's PSV0 container from a `; psv0: THREADS MAX_VERTICES + MAX_PRIMITIVES` header line. Two things the census in section 3.5 raises and this layer does not do yet: root + arguments are packed from s0 for the mesh stage too, while the corpus reads mesh user data from s16; and s3 is the + merged wave info in the translator's mesh ABI, so a fourth root dword is out of a mesh shader's reach under the + s0 packing (`ms_m5.asm` reads s0..s2 only). ## 4. Object model mapping @@ -3226,8 +3244,9 @@ Not implemented yet: draw-indexed, dispatch and mesh-dispatch signatures map to `vkCmdDraw*Indirect`, `vkCmdDispatchIndirect` and `vkCmdDrawMeshTasksIndirectEXT`; use the `*Count` variants (`VK_KHR_draw_indirect_count`, core 1.2) when the `ExecuteIndirect` call supplies a count buffer. The draw kinds replay as whole draws (the list's graphics state at the - call is recorded with them, as for `DrawInstanced`); without `multiDrawIndirect` each record is its own call. - `d3d12_m5_world_test` runs them from CPU- and GPU-written records at offsets in placed buffers. + call is recorded with them, as for `DrawInstanced`; a mesh dispatch, as for `DispatchMesh`, section 3.6); without + `multiDrawIndirect` each record is its own call. `d3d12_m5_world_test` runs the draw kinds and + `d3d12_m5_mesh_test` the mesh kind from CPU- and GPU-written records at offsets in their buffers. - Signatures that change root constants, vertex/index buffers or descriptors per argument cannot be expressed by one Vulkan indirect call. Use a compute expansion pass that writes a Vulkan-shaped indirect buffer, or `VK_NV_device_generated_commands` on NVIDIA. Start with the simple signatures; the trace will show which @@ -3609,7 +3628,7 @@ M0–M2 do not need the executable. | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU). Formats, mips and arrays through a PSO: `d3d12_m2_formats_test` samples an 8×8 BC1 and an 8×8 BC7 texture with 4 mips each and an R8G8B8A8 2D array of 3 slices through the same path (every subresource uploaded at its `GetCopyableFootprints` layout, POINT samplers with `MinLOD = MaxLOD` pinning each level, a view from mip 1, two array views read by `ps_m2_array.asm`); all 12 cases match the CPU with error 0, validation clean on the RTX 4070 Ti SUPER, with no layer change needed | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; before the far rectangle, a single-output probe (`ps_m3_query.asm`) uses the same depth/stencil tests with color, depth and stencil writes disabled, inside `BeginQuery`/`EndQuery(OCCLUSION)`, and `ResolveQueryData` writes its sample count to a readback buffer. The actual far-rectangle draw still writes both render targets with depth/stencil writes enabled. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the single-output probe's occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames). The original version was validation clean (including synchronization validation) on the AMD Radeon 880M and the RTX 5070 Laptop; current probe/isolation results are recorded below. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one); and a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker followed submission order, so a copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error): such a batch is now held on the CPU until a Signal that satisfies its Wait has been submitted, and recorded in dependency order (section 4.4, "Wait before Signal across queues"; `d3d12_queue_handover_test`, every queue-type and submission order, exact against the host runtime). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | -| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met except mesh shaders (D3D-29, @Ryx69)** by `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Still open for M5:** mesh shaders (D3D-29); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | +| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met** by `d3d12_m5_world_test` and, for mesh shaders, `d3d12_m5_mesh_test` (below). `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Mesh shaders (`d3d12_m5_mesh_test`, on D3D-29's mesh PSOs):** a translated NGG wave64 mesh shader (`ms_m5.asm`, 128 threads, the corpus's `v5`/`s3` idioms) and `ps_m5_mesh.asm` in PSOs from pipeline state streams; `DispatchMesh` 4x2x2, 3x1x1, 1x1x1 and an empty grid; `ExecuteIndirect` with DISPATCH_MESH signatures (strides 12 and 24) under additive blending, so each cell counts the records whose group count reached it: 5 CPU-written records at offset 36 (one empty), 4 GPU-copied records at offset 48 under a count of 3, a count of 0, a count of 7 under `MaxCommandCount` 2, and 20 one-group records in one call; a DISPATCH_MESH call with a VS PSO and a DRAW call with the mesh PSO fail at execution. Every pixel against the CPU reference, error 0, validation clean, on an RX 9070 XT (AMD 26.11.2). **Still open for M5:** the mesh stage's user-data base (the corpus reads mesh user data from s16; the layer packs from s0, section 3.6); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), filtered and blended in linear light, SDR (sRGB or gamma 2.2) and HDR10 (PQ) planes converted to the swapchain, SDR white from Windows' setting when HDR10 is active (else 203 nits), checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha, tone map and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is tone mapped (identity below 0.8 of SDR white, Reinhard shoulder above, then clipped per channel). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | diff --git a/tests/test_shader_build_mesh.py b/tests/test_shader_build_mesh.py new file mode 100644 index 0000000000..6b5c72fd7b --- /dev/null +++ b/tests/test_shader_build_mesh.py @@ -0,0 +1,59 @@ +"""runtime/test/shaders/build.py: the PSV0 container of a mesh shader with a "psv0:" header. + +build.py used to skip every ms_ shader (it made no PSV0, which the translator reads a mesh shader's thread count and +output counts from). A mesh shader whose header has "; psv0: THREADS MAX_VERTICES MAX_PRIMITIVES" now gets one, so a +layer test (d3d12_m5_mesh_test) can use a translated mesh shader. The container must be the one +scripts/run_gpu_tests.py builds for its mesh fixtures (make_dxbc + make_ms_psv0), byte for byte. + +Standard library only; no llvm-mc, SPIR-V tools, GPU or game data. + + python -I tests/test_shader_build_mesh.py +""" +import importlib.util +import os +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BUILD = os.path.join(ROOT, "runtime", "test", "shaders", "build.py") +GPU_TESTS = os.path.join(ROOT, "scripts", "run_gpu_tests.py") + + +def load(path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class MeshContainerTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.build = load(BUILD, "shaders_build_mesh_under_test") + sys.path.insert(0, os.path.join(ROOT, "scripts")) + cls.gpu = load(GPU_TESTS, "run_gpu_tests_mesh_under_test") + + def test_container_matches_run_gpu_tests(self): + for threads, verts, prims in ((128, 128, 128), (128, 64, 64), (32, 3, 1)): + want = self.gpu.make_dxbc([(b"PSV0", self.gpu.make_ms_psv0(threads, verts, prims))]) + self.assertEqual(self.build.ms_container(threads, verts, prims), want) + + def test_psv0_header(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "ms_x.asm" + path.write_text("; a mesh shader\n; psv0: 128 64 32\n; fssm-at: 0x10\ns_endpgm\n", encoding="utf-8") + self.assertEqual(self.build.asm_psv0(path), (128, 64, 32)) + path.write_text("; a mesh shader\ns_endpgm\n; psv0: 128 64 32\n", encoding="utf-8") + self.assertIsNone(self.build.asm_psv0(path)) # only the header counts + + def test_the_m5_mesh_shader_is_built_and_the_old_fixtures_are_not(self): + here = os.path.dirname(BUILD) + self.assertEqual(self.build.asm_psv0(os.path.join(here, "ms_m5.asm")), (128, 128, 128)) + for name in ("ms_tri", "ms_v5_workgroup", "ms_clip"): # run_gpu_tests.py makes their containers + self.assertIsNone(self.build.asm_psv0(os.path.join(here, name + ".asm"))) + + +if __name__ == "__main__": + unittest.main() From 5cbe1c6c2b320e6cef408c3a19dd4cc6f190cf5e Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:15:23 +0100 Subject: [PATCH 12/17] command_list.h: rewrap the ExecuteIndirect state comment Co-Authored-By: Claude Opus 5.5 --- runtime/src/command_list.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index cdfb23ea80..4fb6507e40 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -599,8 +599,9 @@ struct ExecuteIndirect { ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount std::uint64_t count_offset = 0; // The list's graphics state at the call (its count, instances and first fields are unused: the argument buffer - // holds them), for the draw kinds and dispatch_mesh (whose state has `mesh` set, as DispatchMesh records it). Replay then makes the call a whole draw: it begins rendering into the targets, - // binds the pipeline and the dynamic state as for a Draw, and issues the indirect draw. Null: the caller has set + // holds them), for the draw kinds and dispatch_mesh (whose state has `mesh` set, as DispatchMesh records it). + // Replay then makes the call a whole draw: it begins rendering into the targets, binds the pipeline and the + // dynamic state as for a Draw, and issues the indirect draw. Null: the caller has set // all that up (a raw indirect call), as the unit tests of the indirect path do. std::shared_ptr state; // A draw kind without `state` is a raw call that the caller has wrapped in rendering and bound a pipeline for From 5944fec9611ef280b58edad45eec0e176f36bd4e Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:24:02 +0100 Subject: [PATCH 13/17] M5 mesh test: require 64-wide mesh subgroups, skip where unavailable; fallback-path ctest; run_gpu_tests reads the psv0 header - Pass the device's subgroup caps to the layer, so the wave64 mesh stage asks for 64; exit 77 where the device cannot run it 64-wide, or has fewer than 144 push-constant bytes. - --single-calls / --no-count-buffers turn multiDrawIndirect / drawIndirectCount off on the layer's device; registered as d3d12_m5_mesh_fallbacks. Without drawIndirectCount a count-buffer call must be ReplayResult::unsupported. - scripts/run_gpu_tests.py translates every .asm itself: give a mesh shader with a psv0: header its PSV0 there too (ms_m5 failed translation in the GPU suite without it). AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 3 +- runtime/test/d3d12_m5_mesh_test.cpp | 59 +++++++++++++++++++++++++---- scripts/run_gpu_tests.py | 17 +++++++++ tests/test_shader_build_mesh.py | 7 ++++ 4 files changed, 77 insertions(+), 9 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index edd1c9ff32..d3dbb3a334 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2146,7 +2146,8 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_M5_MESH_DIR="${LEONIDA_M5_MESH_DIR}") target_compile_options(d3d12_m5_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m5_mesh COMMAND d3d12_m5_mesh_test) - set_tests_properties(d3d12_m5_mesh PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_m5_mesh_fallbacks COMMAND d3d12_m5_mesh_test --single-calls --no-count-buffers) + set_tests_properties(d3d12_m5_mesh d3d12_m5_mesh_fallbacks PROPERTIES SKIP_RETURN_CODE 77) # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes diff --git a/runtime/test/d3d12_m5_mesh_test.cpp b/runtime/test/d3d12_m5_mesh_test.cpp index f7811f57c6..97041382eb 100644 --- a/runtime/test/d3d12_m5_mesh_test.cpp +++ b/runtime/test/d3d12_m5_mesh_test.cpp @@ -17,7 +17,9 @@ // I4 a count of 7 against MaxCommandCount 2: the first two records only; // I5 20 records of one group each, without a count buffer: one call of 20 (or 20 calls without // multiDrawIndirect). -// Without drawIndirectCount, I2..I4 are left out. +// Without drawIndirectCount, I2..I4 are left out, and a count-buffer call must fail as unsupported. +// --single-calls and --no-count-buffers turn multiDrawIndirect and drawIndirectCount off on the layer's device +// (registered as d3d12_m5_mesh_fallbacks), so those paths run on any GPU. // (c) Refusals: a DISPATCH_MESH signature whose stride is below 12 is E_INVALIDARG; one on a device without // VK_EXT_mesh_shader is E_NOTIMPL; a DISPATCH_MESH signature run with a VS PSO, and a DRAW signature with the mesh // PSO, fail at execution (ReplayResult::invalid_draw). @@ -121,7 +123,16 @@ Constants constants(UINT first, unsigned r, unsigned g) { return {first, float(r } // namespace -int main() { +int main(int argc, char** argv) { + bool single_calls = false, no_count_buffers = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--single-calls") == 0) single_calls = true; + else if (std::strcmp(argv[i], "--no-count-buffers") == 0) no_count_buffers = true; + else { + std::fprintf(stderr, "usage: d3d12_m5_mesh_test [--single-calls] [--no-count-buffers]\n"); + return 2; + } + } vktest::Device d; d.request_mesh_shader = true; const auto device_status = d.initialize(); @@ -151,10 +162,11 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; - info.multi_draw_indirect = d.multi_draw_indirect; - info.draw_indirect_count = d.draw_indirect_count; + info.multi_draw_indirect = d.multi_draw_indirect && !single_calls; + info.draw_indirect_count = d.draw_indirect_count && !no_count_buffers; info.max_draw_indirect_count = d.max_draw_indirect_count; info.mesh_shader = mesh; + info.subgroup = d.subgroup; // so the wave64 mesh stage asks for 64 where the device can require it info.shader_dir = (root_dir / "spirv").string(); return info; }; @@ -186,14 +198,20 @@ int main() { std::printf("no VK_EXT_mesh_shader on this device: only the refusal without it was checked\n"); return 77; } - const bool counts = d.draw_indirect_count; - if (!d.multi_draw_indirect) std::printf("note: no multiDrawIndirect: the layer issues one call per record\n"); + const bool counts = d.draw_indirect_count && !no_count_buffers; + if (!d.multi_draw_indirect || single_calls) std::printf("note: no multiDrawIndirect: the layer issues one call per record\n"); if (!counts) std::printf("note: no drawIndirectCount: the count-buffer calls (I2, I3, I4) are not run\n"); unsigned direct_mismatches = 0, indirect_mismatches = 0, records_drawn = 0; + const char* subgroup = "?"; { Ref device; EXPECT(make_device(true, device)); + if (rt::d3d12::device_push_constants_need_fallback(device.p)) { + std::printf("SKIP: the PSOs need 144 push-constant bytes and this GPU has %u\n", + rt::d3d12::device_max_push_constants_size(device.p)); + return 77; + } const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; @@ -267,6 +285,23 @@ int main() { s.add(BlendSubobject{.inner = opaque}); a.add(BlendSubobject{.inner = additive}); EXPECT(stream_pso(s, mesh_opaque) && stream_pso(a, mesh_additive)); + // ms_m5 is wave64 (not built with --wave64-emulate): it needs 64-wide subgroups in the mesh stage. + const auto* requests = rt::d3d12::pipeline_subgroup_requests(mesh_opaque.p); + EXPECT(requests); + for (const auto& request : *requests) { + if (request.stage != VK_SHADER_STAGE_MESH_BIT_EXT) continue; + switch (request.outcome) { + case leonida::SubgroupOutcome::required: subgroup = "required subgroup size 64"; break; + case leonida::SubgroupOutcome::device_fixed: subgroup = "the device's only subgroup size, 64"; break; + case leonida::SubgroupOutcome::device_default: subgroup = "the default subgroup size, 64"; break; + case leonida::SubgroupOutcome::emulated: subgroup = "wave64 emulation"; break; + default: + std::printf("SKIP: the wave64 mesh shader cannot run 64-wide here (subgroup sizes %u..%u, default " + "%u, requirable stages 0x%x)\n", d.subgroup.min_size, d.subgroup.max_size, + d.subgroup.default_size, unsigned(d.subgroup.required_stages)); + return 77; + } + } Stream v; v.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = {vs_rect.data(), vs_rect.size()}}); v.add(PsSubobject{.inner = {ps_flat.data(), ps_flat.size()}}); @@ -451,6 +486,14 @@ int main() { EXPECT(result == leonida::ReplayResult::success); indirect_mismatches = check("ExecuteIndirect DISPATCH_MESH", want); + // Without drawIndirectCount, a count-buffer call cannot be replayed. + if (!counts) { + EXPECT(begin(mesh_opaque.p, black)); + list->ExecuteIndirect(sig12.p, 2, args_cpu.p, 256, count_gpu.p, 24); + EXPECT(end()); + EXPECT(run(list.p) == leonida::ReplayResult::unsupported); + } + // ===== (c) a draw of the wrong kind fails at execution ===== Ref sig_draw; { @@ -474,10 +517,10 @@ int main() { } } - std::printf("mesh tier 1, translated wave64 mesh shader (128 threads): DispatchMesh 4x2x2, 3x1x1, 1x1x1 and an empty " + std::printf("mesh tier 1, translated wave64 mesh shader (128 threads, %s): DispatchMesh 4x2x2, 3x1x1, 1x1x1 and an empty " "grid, %u mismatched pixels; ExecuteIndirect DISPATCH_MESH, %u records drawn%s, %u mismatched pixels; " "wrong-kind indirect draws fail at execution\n", - direct_mismatches, records_drawn, counts ? " (count buffers included)" : " (no count buffers)", + subgroup, direct_mismatches, records_drawn, counts ? " (count buffers included)" : " (no count buffers)", indirect_mismatches); return direct_mismatches == 0 && indirect_mismatches == 0 ? 0 : 1; } diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index ecff5f345c..8463a7e0b5 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -91,6 +91,20 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_ return struct.pack(" None: """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" with open(asm_path, encoding="utf-8") as source: @@ -783,6 +797,9 @@ def run_suite(a, work: str) -> int: dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) elif name == "ms_v5_workgroup": dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) + elif name.startswith("ms_") and asm_psv0(os.path.join(SHADER_DIR, fname)): + # A layer-test mesh shader (ms_m5): its PSV0 from the "psv0:" header, as build.py makes it. + dxbc = make_dxbc([(b"PSV0", make_ms_psv0(*asm_psv0(os.path.join(SHADER_DIR, fname))))]) elif name == "ms_clip": dxbc = make_dxbc([ (b"PSV0", make_ms_psv0(128, 64, 64, 2)), diff --git a/tests/test_shader_build_mesh.py b/tests/test_shader_build_mesh.py index 6b5c72fd7b..aec945bf90 100644 --- a/tests/test_shader_build_mesh.py +++ b/tests/test_shader_build_mesh.py @@ -54,6 +54,13 @@ def test_the_m5_mesh_shader_is_built_and_the_old_fixtures_are_not(self): for name in ("ms_tri", "ms_v5_workgroup", "ms_clip"): # run_gpu_tests.py makes their containers self.assertIsNone(self.build.asm_psv0(os.path.join(here, name + ".asm"))) + def test_run_gpu_tests_reads_the_same_header(self): + # run_gpu_tests.py translates every .asm in the folder itself; without the header's PSV0 ms_m5 fails there. + here = os.path.dirname(BUILD) + for name in ("ms_m5", "ms_tri"): + path = os.path.join(here, name + ".asm") + self.assertEqual(self.gpu.asm_psv0(path), self.build.asm_psv0(path)) + if __name__ == "__main__": unittest.main() From b8c0e06012a9d9b3aa1bec74bcc0ee554e2505aa Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:25:10 +0100 Subject: [PATCH 14/17] docs: the M5 mesh row names the fallback run and the required subgroup size Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index cc3b185984..bdc3898b5b 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3628,7 +3628,7 @@ M0–M2 do not need the executable. | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU). Formats, mips and arrays through a PSO: `d3d12_m2_formats_test` samples an 8×8 BC1 and an 8×8 BC7 texture with 4 mips each and an R8G8B8A8 2D array of 3 slices through the same path (every subresource uploaded at its `GetCopyableFootprints` layout, POINT samplers with `MinLOD = MaxLOD` pinning each level, a view from mip 1, two array views read by `ps_m2_array.asm`); all 12 cases match the CPU with error 0, validation clean on the RTX 4070 Ti SUPER, with no layer change needed | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; before the far rectangle, a single-output probe (`ps_m3_query.asm`) uses the same depth/stencil tests with color, depth and stencil writes disabled, inside `BeginQuery`/`EndQuery(OCCLUSION)`, and `ResolveQueryData` writes its sample count to a readback buffer. The actual far-rectangle draw still writes both render targets with depth/stencil writes enabled. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the single-output probe's occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames). The original version was validation clean (including synchronization validation) on the AMD Radeon 880M and the RTX 5070 Laptop; current probe/isolation results are recorded below. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one); and a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker followed submission order, so a copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error): such a batch is now held on the CPU until a Signal that satisfies its Wait has been submitted, and recorded in dependency order (section 4.4, "Wait before Signal across queues"; `d3d12_queue_handover_test`, every queue-type and submission order, exact against the host runtime). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | -| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met** by `d3d12_m5_world_test` and, for mesh shaders, `d3d12_m5_mesh_test` (below). `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Mesh shaders (`d3d12_m5_mesh_test`, on D3D-29's mesh PSOs):** a translated NGG wave64 mesh shader (`ms_m5.asm`, 128 threads, the corpus's `v5`/`s3` idioms) and `ps_m5_mesh.asm` in PSOs from pipeline state streams; `DispatchMesh` 4x2x2, 3x1x1, 1x1x1 and an empty grid; `ExecuteIndirect` with DISPATCH_MESH signatures (strides 12 and 24) under additive blending, so each cell counts the records whose group count reached it: 5 CPU-written records at offset 36 (one empty), 4 GPU-copied records at offset 48 under a count of 3, a count of 0, a count of 7 under `MaxCommandCount` 2, and 20 one-group records in one call; a DISPATCH_MESH call with a VS PSO and a DRAW call with the mesh PSO fail at execution. Every pixel against the CPU reference, error 0, validation clean, on an RX 9070 XT (AMD 26.11.2). **Still open for M5:** the mesh stage's user-data base (the corpus reads mesh user data from s16; the layer packs from s0, section 3.6); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | +| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met** by `d3d12_m5_world_test` and, for mesh shaders, `d3d12_m5_mesh_test` (below). `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Mesh shaders (`d3d12_m5_mesh_test`, on D3D-29's mesh PSOs):** a translated NGG wave64 mesh shader (`ms_m5.asm`, 128 threads, the corpus's `v5`/`s3` idioms) and `ps_m5_mesh.asm` in PSOs from pipeline state streams; `DispatchMesh` 4x2x2, 3x1x1, 1x1x1 and an empty grid; `ExecuteIndirect` with DISPATCH_MESH signatures (strides 12 and 24) under additive blending, so each cell counts the records whose group count reached it: 5 CPU-written records at offset 36 (one empty), 4 GPU-copied records at offset 48 under a count of 3, a count of 0, a count of 7 under `MaxCommandCount` 2, and 20 one-group records in one call; a DISPATCH_MESH call with a VS PSO and a DRAW call with the mesh PSO fail at execution. `d3d12_m5_mesh_fallbacks` reruns it with `multiDrawIndirect` and `drawIndirectCount` off on the layer's device (one call per record; a count-buffer call is `unsupported`). Every pixel against the CPU reference, error 0, validation (with synchronization validation) clean, on an RX 9070 XT (AMD 26.11.2), the mesh stage at required subgroup size 64; the test exits 77 where the mesh stage cannot run 64-wide or the device has fewer than 144 push-constant bytes. **Still open for M5:** the mesh stage's user-data base (the corpus reads mesh user data from s16; the layer packs from s0, section 3.6); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), filtered and blended in linear light, SDR (sRGB or gamma 2.2) and HDR10 (PQ) planes converted to the swapchain, SDR white from Windows' setting when HDR10 is active (else 203 nits), checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha, tone map and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is tone mapped (identity below 0.8 of SDR white, Reinhard shoulder above, then clipped per channel). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | From b45b41df1f76a92c16173761e6b37880bb7d7c3d Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:07:48 +0100 Subject: [PATCH 15/17] Review fixes for the DISPATCH_MESH path and the M5 mesh test From two review passes (one adversarial): - CreateCommandSignature refuses DISPATCH_MESH after root arguments (E_NOTIMPL, as before this branch) instead of accepting it and reading the group counts from the record's first bytes. - CommandList::execute_indirect refuses a mesh dispatch without DispatchMesh's state, and a draw kind with it. - The test fails on validation errors, as its siblings do; asserts the mesh stage's subgroup request was found (and fails on an undecided one). - I5 runs at stride 24 without a count buffer, zero-padded, 1 to 4 groups per record; new d3d12_m5_mesh_chunks lowers the layer's maxDrawIndirectCount to 3 so the calls are split. Mutations caught: chunks that don't advance (chunks run), a stride hard-coded to 12 (both). - Docs and comments: one-argument signatures only; maxDrawIndirectCount applies without a count buffer; invalid_draw for a draw signature with a mesh PSO needs a topology; only a record's group total is visible; ms_m5 sends GS_ALLOC_REQ from every thread; whitespace restored. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 17 +++++--- runtime/CMakeLists.txt | 3 +- runtime/shims/d3d12_vulkan_device.cpp | 3 ++ runtime/src/command_list.h | 2 + runtime/test/d3d12_m5_mesh_test.cpp | 61 ++++++++++++++++++++++----- runtime/test/shaders/ms_m5.asm | 5 ++- 6 files changed, 71 insertions(+), 20 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index bdc3898b5b..2cb83b6ee1 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2082,18 +2082,23 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. - **`ExecuteIndirect` with `DISPATCH_MESH` signatures:** `CreateCommandSignature` takes them where - `VK_EXT_mesh_shader` is enabled (`E_NOTIMPL` without it, as mesh PSOs are); `IndirectKind::dispatch_mesh`. + `VK_EXT_mesh_shader` is enabled (`E_NOTIMPL` without it, as mesh PSOs are), with `DISPATCH_MESH` as the one + argument; root constants or views before it are `E_NOTIMPL` (not expanded, section 4.7); `IndirectKind::dispatch_mesh`. `D3D12_DISPATCH_MESH_ARGUMENTS` and `VkDrawMeshTasksIndirectCommandEXT` are the same three dwords, so the records are read as they are. The call records the state `DispatchMesh` takes (no topology, vertex or index buffers) and replays as a whole draw issuing `vkCmdDrawMeshTasksIndirectEXT`, or `vkCmdDrawMeshTasksIndirectCountEXT` with a count buffer (which also needs `drawIndirectCount`; without it the call is `ReplayResult::unsupported`). As for the - draw kinds, a call takes at most `maxDrawIndirectCount` records, and one record without `multiDrawIndirect` - (VUID-vkCmdDrawMeshTasksIndirectEXT-drawCount-02718/02719). A record's group counts are GPU data, so D3D12's limits + draw kinds, a call without a count buffer takes at most `maxDrawIndirectCount` records, and one record without + `multiDrawIndirect` (VUID-vkCmdDrawMeshTasksIndirectEXT-drawCount-02718/02719); with one, `MaxCommandCount` is the + call's `maxDrawCount` and the GPU-written count is not checked against the limit. A record's group counts are GPU data, so D3D12's limits (65535 per count, 2^22 groups) are not checked; counts past the device's `maxMeshWorkGroupCount` are undefined on - both APIs. A DISPATCH_MESH call with a VS PSO, or a draw signature with a mesh PSO, is `ReplayResult::invalid_draw`. + both APIs. A DISPATCH_MESH call with a VS PSO, or a draw signature with a mesh PSO and a topology set, is + `ReplayResult::invalid_draw`; a draw signature with no topology set records the bare call, which replay refuses as + `unsupported`, as for any draw signature without a topology. - **Translated mesh shaders through the layer:** `d3d12_m5_mesh_test` (section 6, M5) draws `ms_m5.asm`, an NGG wave64 mesh shader of 128 threads written with the corpus's idioms (group index from `v5`, thread id from `s3` and - `mbcnt`, `GS_ALLOC_REQ`, per-thread exports), translated by `rdna2spirv.py` and run at required subgroup size 64. + `mbcnt`, `GS_ALLOC_REQ`, per-thread exports), translated by `rdna2spirv.py`; the mesh stage asks for subgroup size 64 (required on the RX 9070 XT), and the test + exits 77 where it cannot run 64-wide. `runtime/test/shaders/build.py` makes a mesh shader's PSV0 container from a `; psv0: THREADS MAX_VERTICES MAX_PRIMITIVES` header line. Two things the census in section 3.5 raises and this layer does not do yet: root arguments are packed from s0 for the mesh stage too, while the corpus reads mesh user data from s16; and s3 is the @@ -3628,7 +3633,7 @@ M0–M2 do not need the executable. | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU). Formats, mips and arrays through a PSO: `d3d12_m2_formats_test` samples an 8×8 BC1 and an 8×8 BC7 texture with 4 mips each and an R8G8B8A8 2D array of 3 slices through the same path (every subresource uploaded at its `GetCopyableFootprints` layout, POINT samplers with `MinLOD = MaxLOD` pinning each level, a view from mip 1, two array views read by `ps_m2_array.asm`); all 12 cases match the CPU with error 0, validation clean on the RTX 4070 Ti SUPER, with no layer change needed | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; before the far rectangle, a single-output probe (`ps_m3_query.asm`) uses the same depth/stencil tests with color, depth and stencil writes disabled, inside `BeginQuery`/`EndQuery(OCCLUSION)`, and `ResolveQueryData` writes its sample count to a readback buffer. The actual far-rectangle draw still writes both render targets with depth/stencil writes enabled. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the single-output probe's occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames). The original version was validation clean (including synchronization validation) on the AMD Radeon 880M and the RTX 5070 Laptop; current probe/isolation results are recorded below. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one); and a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker followed submission order, so a copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error): such a batch is now held on the CPU until a Signal that satisfies its Wait has been submitted, and recorded in dependency order (section 4.4, "Wait before Signal across queues"; `d3d12_queue_handover_test`, every queue-type and submission order, exact against the host runtime). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | -| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met** by `d3d12_m5_world_test` and, for mesh shaders, `d3d12_m5_mesh_test` (below). `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Mesh shaders (`d3d12_m5_mesh_test`, on D3D-29's mesh PSOs):** a translated NGG wave64 mesh shader (`ms_m5.asm`, 128 threads, the corpus's `v5`/`s3` idioms) and `ps_m5_mesh.asm` in PSOs from pipeline state streams; `DispatchMesh` 4x2x2, 3x1x1, 1x1x1 and an empty grid; `ExecuteIndirect` with DISPATCH_MESH signatures (strides 12 and 24) under additive blending, so each cell counts the records whose group count reached it: 5 CPU-written records at offset 36 (one empty), 4 GPU-copied records at offset 48 under a count of 3, a count of 0, a count of 7 under `MaxCommandCount` 2, and 20 one-group records in one call; a DISPATCH_MESH call with a VS PSO and a DRAW call with the mesh PSO fail at execution. `d3d12_m5_mesh_fallbacks` reruns it with `multiDrawIndirect` and `drawIndirectCount` off on the layer's device (one call per record; a count-buffer call is `unsupported`). Every pixel against the CPU reference, error 0, validation (with synchronization validation) clean, on an RX 9070 XT (AMD 26.11.2), the mesh stage at required subgroup size 64; the test exits 77 where the mesh stage cannot run 64-wide or the device has fewer than 144 push-constant bytes. **Still open for M5:** the mesh stage's user-data base (the corpus reads mesh user data from s16; the layer packs from s0, section 3.6); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | +| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise **Synthetic part met** by `d3d12_m5_world_test` and, for mesh shaders, `d3d12_m5_mesh_test` (below). `d3d12_m5_world_test`: through the proxy, D3D12 API only, translator-output shaders (hand-written RDNA2: `vs_m5`, `ps_m5_inst`, `vs_m3`, `ps_m5_flat`, `vs_m2`, `ps_m5_tex`), every pixel against a CPU reference with error 0. **(a) `ExecuteIndirect` draws:** `CreateCommandSignature` for DRAW (stride 16) and DRAW_INDEXED (strides 20 and 32), five calls drawing 35 cells of an 8x8 grid from records the CPU wrote into an upload buffer and records the GPU copied (`CopyBufferRegion`, then COPY_DEST to INDIRECT_ARGUMENT) into default-heap buffers placed at 64, 128 and 192 KiB of a heap, argument offsets 12, 64, 96, 736 and 864 inside them, a count buffer (13 of 20; count 0 draws nothing; `MaxCommandCount` 2 under a count of 13 draws 2), records with `InstanceCount` 0 and 2, index values picking the cell of an indexed record, `InstanceCount` the cells of a non-indexed one (vertex and instance ids are zero-based since the translator subtracts BaseVertex and BaseInstance, so `StartVertexLocation` and `StartInstanceLocation` are not visible to a shader; a non-zero `StartInstanceLocation` is still passed in the indexed records). **(b) Multi-threaded lists:** four `std::thread`s each create an allocator and a list and record 40 draws of random rectangles (root constants) at once; the four lists run in one `ExecuteCommandLists` between a clear list and a readback list, eight rounds with different seeds (1280 rectangles), overlapping across lists so the list order shows. **(c) Bindless-table pressure:** a shader-visible heap of 5120 SRVs of 5120 distinct 2x2 textures in one descriptor table; each of the 5120 pixels of a 128x40 target is a draw (one-pixel scissor) whose root constant is the byte offset of a slot, which `ps_m5_tex.asm` `s_load`s the T# from (`s_load_dwordx8 s[8:15], s[0:1], s4`), visited in a scrambled order so the last slot and every other is used once; all 5120 T#s have distinct non-zero descriptor-hash-table entries. **(d) Pipeline cache:** the same PSO created twice; the layer's device-wide `VkPipelineCache` answers the second (`VkPipelineCreationFeedback` application-cache-hit bit: first creation 0 hits, second 1 of 1) and the cache's data does not grow (AMD 25232 and NVIDIA 72163 bytes either way); both PSOs draw identically. Validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Layer changes it needed:** `ExecuteIndirect` draws were never rendered by the COM layer (replay issued a bare `vkCmdDraw*Indirect` outside any render pass, with no pipeline bound; only a unit test that wrapped it by hand passed), so the call now carries the list's graphics state like a `Draw` and replays as one; `multiDrawIndirect`, `drawIndirectCount` and `drawIndirectFirstInstance` were never enabled on the layer's device (a record count above 1 or a count buffer was a validation error), now enabled where present (`VulkanDeviceInfo::multi_draw_indirect`, `draw_indirect_count`; one call per record without `multiDrawIndirect`); every pipeline was created with a null `VkPipelineCache`, now with one per device (`rt::d3d12::pipeline_cache_stats`). **Mesh shaders (`d3d12_m5_mesh_test`, on D3D-29's mesh PSOs):** a translated NGG wave64 mesh shader (`ms_m5.asm`, 128 threads, the corpus's `v5`/`s3` idioms) and `ps_m5_mesh.asm` in PSOs from pipeline state streams; `DispatchMesh` 4x2x2, 3x1x1, 1x1x1 and an empty grid; `ExecuteIndirect` with DISPATCH_MESH signatures (strides 12 and 24) under additive blending, so each cell counts the records whose group count reached it: 5 CPU-written records at offset 36 (one empty), 4 GPU-copied records at offset 48 under a count of 3, a count of 0, a count of 7 under `MaxCommandCount` 2, and 20 records of 1 to 4 groups at stride 24 in one call (`d3d12_m5_mesh_chunks` splits them into calls of 3 by lowering the layer's `maxDrawIndirectCount`); a signature with a root constant before DISPATCH_MESH is `E_NOTIMPL`; a DISPATCH_MESH call with a VS PSO and a DRAW call with the mesh PSO fail at execution. `d3d12_m5_mesh_fallbacks` reruns it with `multiDrawIndirect` and `drawIndirectCount` off on the layer's device (one call per record; a count-buffer call is `unsupported`). Every pixel against the CPU reference, error 0, validation (with synchronization validation) clean, on an RX 9070 XT (AMD 26.11.2), the mesh stage at required subgroup size 64; the test exits 77 where the mesh stage cannot run 64-wide or the device has fewer than 144 push-constant bytes. **Still open for M5:** the mesh stage's user-data base (the corpus reads mesh user data from s16; the layer packs from s0, section 3.6); command signatures with more than one argument (root constants, vertex/index buffers, descriptors per record) are not expanded (section 4.7: the last draw or dispatch argument names the kind and the rest is ignored, so such a signature draws from the wrong offsets); `ExecuteIndirect` with a dispatch kind has no graphics-style test here (M4); no `ID3D12PipelineLibrary` (`CreatePipelineLibrary`, `StorePipeline`, `LoadGraphicsPipeline`), no `CachedPSO` use, and the `VkPipelineCache` is not written to disk or seeded at boot; instance ids of indirect draws with a non-zero `StartInstanceLocation` (PR 436's zero-based ids) are not covered, as the test shaders do not read them; the pressure test uses a CPU-uniform index per draw (a per-lane index would need the waterfall loop a game shader has), 2D textures of one format, and one 5120-slot table; the game's own world frame needs the executable | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), filtered and blended in linear light, SDR (sRGB or gamma 2.2) and HDR10 (PQ) planes converted to the swapchain, SDR white from Windows' setting when HDR10 is active (else 203 nits), checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha, tone map and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is tone mapped (identity below 0.8 of SDR white, Reinhard shoulder above, then clipped per channel). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index d3dbb3a334..37d2e06dc5 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2147,7 +2147,8 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_m5_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m5_mesh COMMAND d3d12_m5_mesh_test) add_test(NAME d3d12_m5_mesh_fallbacks COMMAND d3d12_m5_mesh_test --single-calls --no-count-buffers) - set_tests_properties(d3d12_m5_mesh d3d12_m5_mesh_fallbacks PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_m5_mesh_chunks COMMAND d3d12_m5_mesh_test --max-draw-indirect-count 3) + set_tests_properties(d3d12_m5_mesh d3d12_m5_mesh_fallbacks d3d12_m5_mesh_chunks PROPERTIES SKIP_RETURN_CODE 77) # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 5d390ec220..890ec760ed 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5572,6 +5572,9 @@ class Device final // Replayed as vkCmdDrawMeshTasksIndirect(Count)EXT; without VK_EXT_mesh_shader there is no mesh PSO to // run it with (the device reports MeshShaderTier NOT_SUPPORTED then). if (!state_.info.mesh_shader || !state_.context->vk.vkCmdDrawMeshTasksIndirectEXT) return E_NOTIMPL; + // Root arguments or views before it would need the per-record expansion the draw kinds lack too + // (section 4.7); refuse rather than read the group counts from the record's first bytes. + if (desc->NumArgumentDescs != 1) return E_NOTIMPL; kind = leonida::IndirectKind::dispatch_mesh; break; default: return E_NOTIMPL; diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 4fb6507e40..214d51bf7e 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -884,6 +884,8 @@ class CommandList { bool execute_indirect(const ExecuteIndirect& indirect) { if (!indirect.argument_buffer || !indirect.stride) return false; if (indirect.state && (!indirect.state->pipeline || indirect.kind == IndirectKind::dispatch)) return false; + // A mesh dispatch carries DispatchMesh's state, a draw kind a draw's. + if (indirect.state && indirect.state->mesh != (indirect.kind == IndirectKind::dispatch_mesh)) return false; if (!indirect.max_count) return !closed_; // the PC runtime takes MaxCommandCount 0 as a no-op return append(indirect); } diff --git a/runtime/test/d3d12_m5_mesh_test.cpp b/runtime/test/d3d12_m5_mesh_test.cpp index 97041382eb..7ddec8d5dc 100644 --- a/runtime/test/d3d12_m5_mesh_test.cpp +++ b/runtime/test/d3d12_m5_mesh_test.cpp @@ -9,18 +9,23 @@ // (a) DispatchMesh: a 4x2x2 grid (all three counts reach the shader: 16 cells, so every group got its own index), a // 3x1x1 grid and a 1x1x1 grid at other first cells and colours, and an empty grid that draws nothing. // (b) ExecuteIndirect with DISPATCH_MESH signatures, with additive blending, so a cell's colour counts the records -// whose group count reached it, and each record's counts show in the pixels: +// whose group count reached it, so each record's group total shows in the pixels (the split of a total into X, +// Y and Z, and the order groups are numbered in, are not visible: a group sees only its linear index): // I1 5 CPU-written records, stride 12, at argument offset 36, one of them empty; // I2 4 records, stride 24, copied by the GPU into a default buffer (COPY_DEST -> INDIRECT_ARGUMENT) at offset // 48, with a count buffer holding 3 (so the 4th record is not drawn); // I3 a count of 0: nothing; // I4 a count of 7 against MaxCommandCount 2: the first two records only; -// I5 20 records of one group each, without a count buffer: one call of 20 (or 20 calls without -// multiDrawIndirect). +// I5 20 records of 1 to 4 groups, stride 24 with zeroed padding (a wrong stride would read empty records), +// without a count buffer: one call of 20, or calls of at most maxDrawIndirectCount records, or 20 calls +// without multiDrawIndirect. // Without drawIndirectCount, I2..I4 are left out, and a count-buffer call must fail as unsupported. // --single-calls and --no-count-buffers turn multiDrawIndirect and drawIndirectCount off on the layer's device -// (registered as d3d12_m5_mesh_fallbacks), so those paths run on any GPU. -// (c) Refusals: a DISPATCH_MESH signature whose stride is below 12 is E_INVALIDARG; one on a device without +// (registered as d3d12_m5_mesh_fallbacks), so those paths run on any GPU; --max-draw-indirect-count N lowers the +// layer's limit (d3d12_m5_mesh_chunks runs N = 3, so I5 is split into calls of 3 records at stride 24). The +// one-call-per-record split itself only shows as a validation error on a device without multiDrawIndirect. +// (c) Refusals: a DISPATCH_MESH signature whose stride is below 12 is E_INVALIDARG; one with a root constant before +// DISPATCH_MESH is E_NOTIMPL (multi-argument signatures are not expanded); one on a device without // VK_EXT_mesh_shader is E_NOTIMPL; a DISPATCH_MESH signature run with a VS PSO, and a DRAW signature with the mesh // PSO, fail at execution (ReplayResult::invalid_draw). // Needs VK_EXT_mesh_shader (exit 77 without it). No game data. Set LEONIDA_VK_VALIDATION=1 to run under @@ -32,6 +37,7 @@ #include "../src/shader_library.h" #include +#include #include #include #include @@ -125,11 +131,15 @@ Constants constants(UINT first, unsigned r, unsigned g) { return {first, float(r int main(int argc, char** argv) { bool single_calls = false, no_count_buffers = false; + std::uint32_t max_draw_count = 0; // 0: the device's maxDrawIndirectCount for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--single-calls") == 0) single_calls = true; else if (std::strcmp(argv[i], "--no-count-buffers") == 0) no_count_buffers = true; + else if (std::strcmp(argv[i], "--max-draw-indirect-count") == 0 && i + 1 < argc) + max_draw_count = std::uint32_t(std::strtoul(argv[++i], nullptr, 10)); else { - std::fprintf(stderr, "usage: d3d12_m5_mesh_test [--single-calls] [--no-count-buffers]\n"); + std::fprintf(stderr, "usage: d3d12_m5_mesh_test [--single-calls] [--no-count-buffers] " + "[--max-draw-indirect-count N]\n"); return 2; } } @@ -164,7 +174,8 @@ int main(int argc, char** argv) { info.buffer_device_address = true; info.multi_draw_indirect = d.multi_draw_indirect && !single_calls; info.draw_indirect_count = d.draw_indirect_count && !no_count_buffers; - info.max_draw_indirect_count = d.max_draw_indirect_count; + info.max_draw_indirect_count = + max_draw_count ? std::min(max_draw_count, d.max_draw_indirect_count) : d.max_draw_indirect_count; info.mesh_shader = mesh; info.subgroup = d.subgroup; // so the wave64 mesh stage asks for 64 where the device can require it info.shader_dir = (root_dir / "spirv").string(); @@ -288,13 +299,20 @@ int main(int argc, char** argv) { // ms_m5 is wave64 (not built with --wave64-emulate): it needs 64-wide subgroups in the mesh stage. const auto* requests = rt::d3d12::pipeline_subgroup_requests(mesh_opaque.p); EXPECT(requests); + bool mesh_request = false; for (const auto& request : *requests) { if (request.stage != VK_SHADER_STAGE_MESH_BIT_EXT) continue; + mesh_request = true; switch (request.outcome) { case leonida::SubgroupOutcome::required: subgroup = "required subgroup size 64"; break; case leonida::SubgroupOutcome::device_fixed: subgroup = "the device's only subgroup size, 64"; break; case leonida::SubgroupOutcome::device_default: subgroup = "the default subgroup size, 64"; break; case leonida::SubgroupOutcome::emulated: subgroup = "wave64 emulation"; break; + case leonida::SubgroupOutcome::unknown_device: + case leonida::SubgroupOutcome::unknown_stage: + std::fprintf(stderr, "the mesh stage's subgroup size was not decided (outcome %d)\n", + int(request.outcome)); + return 1; default: std::printf("SKIP: the wave64 mesh shader cannot run 64-wide here (subgroup sizes %u..%u, default " "%u, requirable stages 0x%x)\n", d.subgroup.min_size, d.subgroup.max_size, @@ -302,6 +320,7 @@ int main(int argc, char** argv) { return 77; } } + EXPECT(mesh_request); Stream v; v.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = {vs_rect.data(), vs_rect.size()}}); v.add(PsSubobject{.inner = {ps_flat.data(), ps_flat.size()}}); @@ -403,6 +422,15 @@ int main(int argc, char** argv) { Ref sig12, sig24, refused; EXPECT(SUCCEEDED(mesh_signature(device.p, 12, sig12)) && SUCCEEDED(mesh_signature(device.p, 24, sig24))); EXPECT(mesh_signature(device.p, 8, refused) == E_INVALIDARG && !refused.p); // (c) stride below a record + { // (c) a root constant before DISPATCH_MESH: not expanded, so refused rather than misread + D3D12_INDIRECT_ARGUMENT_DESC args[2] = {}; + args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT; + args[0].Constant = {0, 0, 1}; + args[1].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const D3D12_COMMAND_SIGNATURE_DESC desc{16, 2, args, 0}; + EXPECT(device->CreateCommandSignature(&desc, root.p, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && + !refused.p); + } // The CPU-written records (I1, I4, I5) in an upload buffer; I2's records and the count words staged in a // second one and copied into default buffers by the GPU. @@ -447,9 +475,16 @@ int main(int argc, char** argv) { put(cpu + 268, 2, 1, 1); put(cpu + 280, 4, 1, 1); if (counts) expect_records(40, 0, 64, {1, 2}); - // I5: offset 512, stride 12, 20 records of one group each. - for (unsigned r = 0; r < 20; ++r) put(cpu + 512 + 12 * r, 1, 1, 1); - expect_records(48, 8, 8, std::vector(20, 1)); + // I5: offset 512, stride 24, 20 records of 1 + r % 4 groups (as 1x1, then 2x1x1, 1x3x1, 2x1x2), each + // followed by 12 zero bytes: read at stride 12, half the records would be empty. + std::memset(cpu + 512, 0, 20 * 24); + std::vector i5; + for (unsigned r = 0; r < 20; ++r) { + static constexpr UINT shapes[4][3] = {{1, 1, 1}, {2, 1, 1}, {1, 3, 1}, {2, 1, 2}}; + put(cpu + 512 + 24 * r, shapes[r % 4][0], shapes[r % 4][1], shapes[r % 4][2]); + i5.push_back(1 + r % 4); + } + expect_records(48, 8, 8, i5); // I2 (staged at 0, copied to args_gpu at 48): stride 24, 4, 3, 5 and 8 groups, the count 3 drops the 8. put(stage + 0, 2, 2, 1); put(stage + 24, 1, 1, 3); @@ -478,7 +513,7 @@ int main(int argc, char** argv) { list->ExecuteIndirect(sig12.p, 2, args_cpu.p, 256, count_gpu.p, 24); } set_constants(constants(48, 8, 8)); - list->ExecuteIndirect(sig12.p, 20, args_cpu.p, 512, nullptr, 0); + list->ExecuteIndirect(sig24.p, 20, args_cpu.p, 512, nullptr, 0); EXPECT(end()); const auto result = run(list.p); if (result != leonida::ReplayResult::success) @@ -522,5 +557,9 @@ int main(int argc, char** argv) { "wrong-kind indirect draws fail at execution\n", subgroup, direct_mismatches, records_drawn, counts ? " (count buffers included)" : " (no count buffers)", indirect_mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } return direct_mismatches == 0 && indirect_mismatches == 0 ? 0 : 1; } diff --git a/runtime/test/shaders/ms_m5.asm b/runtime/test/shaders/ms_m5.asm index 90419991ed..46875c2f2d 100644 --- a/runtime/test/shaders/ms_m5.asm +++ b/runtime/test/shaders/ms_m5.asm @@ -1,7 +1,8 @@ ; M5 mesh shader (NGG, wave64, 128 threads = two waves), written with the corpus's mesh idioms (docs/design.md, "Mesh ; shaders"): the group index from v5 (v_readfirstlane_b32, then >> 7, as all 9,282 corpus mesh shaders do), the -; thread id from the wave index in s3[27:24] and mbcnt, GS_ALLOC_REQ with m0 = prims << 12 | verts, and one vertex -; and one primitive export per thread. Run: d3d12_m5_mesh_test (found by the SHA-256 of its FSSM program). +; thread id from the wave index in s3[27:24] and mbcnt, GS_ALLOC_REQ with m0 = prims << 12 | verts (sent by every +; thread with the same m0, as ms_tri.asm does; the corpus sends it from thread 0), and one vertex and one primitive +; export per thread. Run: d3d12_m5_mesh_test (found by the SHA-256 of its FSSM program). ; psv0: 128 128 128 ; Each group draws one quad, 4 vertices and 2 triangles, into cell k of an 8x8 grid on a 64x64 target: ; L = v5 >> 7, the linear group index (x + X * (y + Y * z) of the DispatchMesh grid, as the translator numbers it) From 340fad0b61cdd64d535b0c0c384e8744bef8aa84 Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:53:48 +0100 Subject: [PATCH 16/17] M5 mesh test: the fallback run covers every GPU that runs the test, not every GPU Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_m5_mesh_test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/test/d3d12_m5_mesh_test.cpp b/runtime/test/d3d12_m5_mesh_test.cpp index 7ddec8d5dc..8bd3745124 100644 --- a/runtime/test/d3d12_m5_mesh_test.cpp +++ b/runtime/test/d3d12_m5_mesh_test.cpp @@ -21,7 +21,8 @@ // without multiDrawIndirect. // Without drawIndirectCount, I2..I4 are left out, and a count-buffer call must fail as unsupported. // --single-calls and --no-count-buffers turn multiDrawIndirect and drawIndirectCount off on the layer's device -// (registered as d3d12_m5_mesh_fallbacks), so those paths run on any GPU; --max-draw-indirect-count N lowers the +// (registered as d3d12_m5_mesh_fallbacks), so those paths run on every GPU that runs this test (64-wide mesh +// subgroups), whatever its features; --max-draw-indirect-count N lowers the // layer's limit (d3d12_m5_mesh_chunks runs N = 3, so I5 is split into calls of 3 records at stride 24). The // one-call-per-record split itself only shows as a validation error on a device without multiDrawIndirect. // (c) Refusals: a DISPATCH_MESH signature whose stride is below 12 is E_INVALIDARG; one with a root constant before From f8b19786869859993e9cc8ea2972aeede740a0d2 Mon Sep 17 00:00:00 2001 From: zneel <14263028+zneel@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:43:27 +0100 Subject: [PATCH 17/17] M5 mesh test: skip before the mesh PSOs, an exact clear, first-instance caps; build.py psv0 error From review on #3777: - The wave64 skip is decided from the library entry and the device's subgroup caps (decide_subgroup_size, as the layer decides it) before any mesh PSO is created, so a device that cannot run ms_m5 skips even if its PSO creation would fail. The PSO's own mesh-stage request must match that prediction. (whattheflop) - The DispatchMesh part clears to 128/255 instead of 0.5: 0.5 is 127.5 in UNORM8 and some GPUs store 127. The emulated RTX 5070 / 5080 runs differed only there. (kacper-serewis, tedin7) - The layer's device info gets drawIndirectFirstInstance, as d3d12_m5_world_test does, which silences its "not enabled" log. (ddm-j) - build.py: an ms_ shader without a psv0 header raises a clear ValueError instead of a TypeError when translate_tests is called directly. (tupacfan04) AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_m5_mesh_test.cpp | 40 ++++++++++++++++++++--------- runtime/test/shaders/build.py | 5 +++- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/runtime/test/d3d12_m5_mesh_test.cpp b/runtime/test/d3d12_m5_mesh_test.cpp index 8bd3745124..1d052e2920 100644 --- a/runtime/test/d3d12_m5_mesh_test.cpp +++ b/runtime/test/d3d12_m5_mesh_test.cpp @@ -177,6 +177,7 @@ int main(int argc, char** argv) { info.draw_indirect_count = d.draw_indirect_count && !no_count_buffers; info.max_draw_indirect_count = max_draw_count ? std::min(max_draw_count, d.max_draw_indirect_count) : d.max_draw_indirect_count; + info.draw_indirect_first_instance = d.draw_indirect_first_instance; info.mesh_shader = mesh; info.subgroup = d.subgroup; // so the wave64 mesh stage asks for 64 where the device can require it info.shader_dir = (root_dir / "spirv").string(); @@ -210,6 +211,24 @@ int main(int argc, char** argv) { std::printf("no VK_EXT_mesh_shader on this device: only the refusal without it was checked\n"); return 77; } + // ms_m5 is wave64 (not built with --wave64-emulate): it needs 64-wide subgroups in the mesh stage. Decided from + // the library entry and the device's caps, as the layer decides it, so a device that cannot run it skips before + // any mesh PSO is created; the PSO's own request is checked against this below. + const leonida::ShaderEntry* ms_entry = + library.find("ms", leonida::sha256_hex(read_file(root_dir / "fssm" / "ms_m5.fssm"))); + EXPECT(ms_entry); + const leonida::SubgroupRequest ms_request = leonida::decide_subgroup_size(*ms_entry, d.subgroup); + if (ms_request.outcome == leonida::SubgroupOutcome::unknown_device || + ms_request.outcome == leonida::SubgroupOutcome::unknown_stage) { + std::fprintf(stderr, "the mesh stage's subgroup size was not decided (outcome %d)\n", int(ms_request.outcome)); + return 1; + } + if (ms_request.outcome == leonida::SubgroupOutcome::unavailable) { + std::printf("SKIP: the wave64 mesh shader cannot run 64-wide here (subgroup sizes %u..%u, default %u, " + "requirable stages 0x%x)\n", d.subgroup.min_size, d.subgroup.max_size, d.subgroup.default_size, + unsigned(d.subgroup.required_stages)); + return 77; + } const bool counts = d.draw_indirect_count && !no_count_buffers; if (!d.multi_draw_indirect || single_calls) std::printf("note: no multiDrawIndirect: the layer issues one call per record\n"); if (!counts) std::printf("note: no drawIndirectCount: the count-buffer calls (I2, I3, I4) are not run\n"); @@ -297,28 +316,24 @@ int main(int argc, char** argv) { s.add(BlendSubobject{.inner = opaque}); a.add(BlendSubobject{.inner = additive}); EXPECT(stream_pso(s, mesh_opaque) && stream_pso(a, mesh_additive)); - // ms_m5 is wave64 (not built with --wave64-emulate): it needs 64-wide subgroups in the mesh stage. + // The PSO's mesh-stage request must be the one decided above. const auto* requests = rt::d3d12::pipeline_subgroup_requests(mesh_opaque.p); EXPECT(requests); bool mesh_request = false; for (const auto& request : *requests) { if (request.stage != VK_SHADER_STAGE_MESH_BIT_EXT) continue; mesh_request = true; + if (request.outcome != ms_request.outcome) { + std::fprintf(stderr, "the mesh PSO's subgroup outcome %d is not the predicted %d\n", + int(request.outcome), int(ms_request.outcome)); + return 1; + } switch (request.outcome) { case leonida::SubgroupOutcome::required: subgroup = "required subgroup size 64"; break; case leonida::SubgroupOutcome::device_fixed: subgroup = "the device's only subgroup size, 64"; break; case leonida::SubgroupOutcome::device_default: subgroup = "the default subgroup size, 64"; break; case leonida::SubgroupOutcome::emulated: subgroup = "wave64 emulation"; break; - case leonida::SubgroupOutcome::unknown_device: - case leonida::SubgroupOutcome::unknown_stage: - std::fprintf(stderr, "the mesh stage's subgroup size was not decided (outcome %d)\n", - int(request.outcome)); - return 1; - default: - std::printf("SKIP: the wave64 mesh shader cannot run 64-wide here (subgroup sizes %u..%u, default " - "%u, requirable stages 0x%x)\n", d.subgroup.min_size, d.subgroup.max_size, - d.subgroup.default_size, unsigned(d.subgroup.required_stages)); - return 77; + default: return 1; // the unavailable and unknown outcomes returned before the PSOs } } EXPECT(mesh_request); @@ -399,7 +414,8 @@ int main(int argc, char** argv) { // ===== (a) DispatchMesh ===== { - const FLOAT grey[4] = {0.5f, 0.5f, 0.5f, 1.0f}; + // 128/255 exactly, so the UNORM store cannot round either way (0.5 is 127.5, stored as 127 on some GPUs). + const FLOAT grey[4] = {128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; Image want({128, 128, 128, 255}); EXPECT(begin(mesh_opaque.p, grey)); set_constants(constants(0, 200, 40)); diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 6772abd961..5bc6e6758b 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -187,7 +187,10 @@ def translate_tests(work, names): elif n.startswith("gs_"): (work / (n + ".dxbc")).write_bytes(gs_container()) elif n.startswith("ms_"): - (work / (n + ".dxbc")).write_bytes(ms_container(*asm_psv0(asm_path))) + psv0 = asm_psv0(asm_path) + if psv0 is None: # main() skips these; a direct caller gets a clear error, not a TypeError + raise ValueError(f"{n}: a mesh shader needs a '; psv0: threads vertices primitives' header") + (work / (n + ".dxbc")).write_bytes(ms_container(*psv0)) else: (work / (n + ".dxbc")).write_bytes(bytes(32)) # chunk count 0 cmd = [sys.executable, "-I", TRANSLATOR, disasm, "--out", spirv]