diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 8749bd331d..92e332f358 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2041,10 +2041,117 @@ Pipeline creation: serialized size and bytes are each device's own (the host's empty library is 900 bytes, the layer's 16). - Not compared: the calls the host runtime faults on (`Serialize(nullptr, n)`, `StorePipeline` with a null PSO, `Load*` with a null name or description); the layer answers `E_INVALIDARG` for each. + **Pipeline cache:** the device's `VkPipelineCache` is passed to every graphics and compute pipeline it creates + (the draw-time variants of a graphics PSO included), and with Vulkan 1.3 the layer 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:** 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 then. Without the extension it reports 1 where the index has `--mesh-compute` mesh shaders and + the device can run them (below), and `NOT_SUPPORTED` otherwise, with mesh PSOs `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. +- **`ExecuteIndirect` with `DISPATCH_MESH` signatures:** `CreateCommandSignature` takes them where + `VK_EXT_mesh_shader` is enabled, or without it where the mesh PSOs are `--mesh-compute` ones (mesh tier 1 through + the fallback, below; `E_NOTIMPL` otherwise, 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 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 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. +- **Mesh shaders without `VK_EXT_mesh_shader`** (RDNA1, NVIDIA Pascal, Intel UHD): through the translator's + `--mesh-compute` (docs/design.md, "Mesh shaders as compute"). + - **PSO:** the MS entry must have a `mesh_compute` layout (`E_NOTIMPL` with a log otherwise). Its module becomes a + compute pipeline, with the device's set 0 where it declares bindings and its translated subgroup size. The + graphics pipeline gets, in place of the mesh stage, the vertex shader `runtime/src/mesh_compute_vs.h` builds + from the layout (the module `tools/mesh_compute_vs.py` writes, instruction for instruction): a vertex pipeline + with input assembly and no vertex input. Both layouts take the 152-byte block, the output address in dwords + 36..37. + - **Refused with `E_NOTIMPL` and a log**, and the tier hidden where any `--mesh-compute` mesh shader would be: + - a device under 152 bytes of push constants; + - a Direct queue family without `VK_QUEUE_COMPUTE_BIT` (the dispatch is recorded on that queue; + VUID-vkCmdDispatch-commandBuffer-02707); + - a mesh shader whose subgroup size the compute stage can't be guaranteed: it must be emulated + (`--wave64-emulate`), required by the stage, or the device's only size. A size that is only the default could + change its subgroup operations' results; + - a PS that reads a param's `--f16-interp-fallback` halves where the layout doesn't export them (reading some of + the exported params' halves is fine). Per-pipeline pairing is not built. + - **`DispatchMesh`:** groups × `slot_bytes` of the queue's scratch (`vulkan_scratch.h`, device-local, with a + device address, alive until the submission completes), then `vkCmdDispatch` with the counts, a compute-write → + vertex-read barrier, and in the draw's rendering scope a triangle-list `vkCmdDraw(groups × max_primitives × 3)`. + A draw whose vertex count does not fit in 32 bits is `ReplayResult::unsupported`. + - **`ExecuteIndirect` with `DISPATCH_MESH`:** the group counts are GPU data, so the draw's vertex count is too. A + prepass (`runtime/src/mesh_indirect_prepare.comp`, run by `vulkan_mesh_indirect.h`) reads each record, and the + count when there is a count buffer, and writes a `VkDispatchIndirectCommand` (the record's three counts) and a + `VkDrawIndirectCommand` (groups × `max_primitives` × 3 vertices, computed in 64 bits) into a private buffer the + batch keeps until the submission completes. The replay then issues, per record, `vkCmdDispatchIndirect` of the + mesh-as-compute pipeline, a compute-write → vertex-read barrier, and in the rendering scope `vkCmdDrawIndirect`, + each record writing and reading its own region of slots (the mesh-as-compute module flattens its slot index from + `NumWorkgroups`, which the indirect dispatch fills). No `drawIndirectCount` or `multiDrawIndirect` is needed. + - **Limit:** the regions are sized on the CPU before the counts exist: a 64 MiB budget per call + (`mesh_indirect_budget`), split evenly over `MaxCommandCount` records, at most 2^22 groups each. A record past + the count, an empty grid, or one with more groups than its region holds, or whose vertex count does not fit in + 32 bits, dispatches and draws nothing; the last two set a status word the batch logs when the submission + retires ("dropped records"). A call whose records don't get one slot each is `ReplayResult::unsupported`. + - **Test:** `d3d12_m5_mesh_test --mesh-compute` (`d3d12_m5_mesh_compute`, and `_single` without + `multiDrawIndirect`) runs M5's DispatchMesh and ExecuteIndirect cases on a layer device without the extension, + with `ms_m5` translated with `--mesh-compute --wave64-emulate` (`build.py`'s `LEONIDA_MESH_COMPUTE=1`): count + buffers, a count of 0, a count above `MaxCommandCount`, stride 24, GPU-written arguments, every pixel exact. On an + NVIDIA GeForce GTX 1050 Ti (Pascal, no `VK_EXT_mesh_shader`, driver 580.196.07, Linux, Wine 10.0): 30 records, + 0 mismatched pixels in both runs. + - **Test:** `d3d12_mesh_compute_test` makes the layer's device without the extension on any GPU and draws + `test/glsl/ms_draw_compute.comp`, `ms_draw.mesh` written to the `--mesh-compute` contract: tier 1, a stream PSO, + `DispatchMesh` over X, Y and Z, every pixel checked; a mesh shader without a layout is refused, f16 halves read + where exported link and elsewhere are refused, and devices with 144 push-constant bytes or unguaranteed subgroup + sizes hide the tier and refuse the PSO (an emulated mesh shader is still created). +- **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`; 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 + 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 | D3D12 / Xbox object | Vulkan / layer object | Notes | @@ -3188,7 +3295,10 @@ 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`; 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 @@ -3570,7 +3680,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 | +| **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/docs/design.md b/docs/design.md index b8a153d430..af4944c8f9 100644 --- a/docs/design.md +++ b/docs/design.md @@ -307,7 +307,7 @@ How the generated SPIR-V expects the runtime to work: | Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. | | Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | -| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | +| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The D3D12 layer turns a `DispatchMesh` on a device without the extension into that dispatch, a barrier and the draw, with the vertex shader built from the layout at PSO creation (`runtime/src/mesh_compute_vs.h`; docs/d3d12_vulkan.md, "Mesh shaders without `VK_EXT_mesh_shader`"). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | | Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | | Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py`; all 185 hand-written GPU test shaders pass `spirv-val` with the flag (109 of them read the tail) with set-0 bindings unchanged. The GPU harnesses and the D3D12 layer that bind the block are the follow-ups. | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 58153376e4..6c86b2028a 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -815,6 +815,21 @@ if(BUILD_TESTING) add_test(NAME shader_library COMMAND shader_library_test) add_executable(spirv_f16_halves_test test/spirv_f16_halves_test.cpp) add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test) + # The vertex shader that draws --mesh-compute slots (mesh_compute_vs.h). The test writes its modules to a folder; + # where the Vulkan SDK's spirv-val is found, each is validated after it. + add_executable(mesh_compute_vs_test test/mesh_compute_vs_test.cpp) + set(LEONIDA_MESH_VS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/mesh_compute_vs) + file(MAKE_DIRECTORY ${LEONIDA_MESH_VS_DIR}) + add_test(NAME mesh_compute_vs COMMAND mesh_compute_vs_test ${LEONIDA_MESH_VS_DIR}) + find_program(LEONIDA_SPIRV_VAL spirv-val HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if(LEONIDA_SPIRV_VAL) + set_tests_properties(mesh_compute_vs PROPERTIES FIXTURES_SETUP mesh_compute_vs_modules) + foreach(module small corpus distances f16) + add_test(NAME mesh_compute_vs_val_${module} + COMMAND ${LEONIDA_SPIRV_VAL} --target-env vulkan1.2 ${LEONIDA_MESH_VS_DIR}/${module}.spv) + set_tests_properties(mesh_compute_vs_val_${module} PROPERTIES FIXTURES_REQUIRED mesh_compute_vs_modules) + endforeach() + endif() # Optional: skips unless LEONIDA_SHADERS names a translated work folder (/shaders/spirv). add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) @@ -2086,6 +2101,108 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_m3_first_pass COMMAND d3d12_m3_frame_test --first-pass-only) set_tests_properties(d3d12_m3_frame d3d12_m3_first_pass 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) + # 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 + ${LEONIDA_M5_MESH_DIR}/fssm/cs_m5_args.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}" + LEONIDA_USER_DATA_SHIFT=4 + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M5_MESH_DIR} ms_m5 ps_m5_mesh vs_m3 ps_m5_flat cs_m5_args + 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}/test/shaders/cs_m5_args.asm + ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py + # LEONIDA_USER_DATA_SHIFT=4 shifts cs_m5_args only (the cs_ fixtures): a D3D12 compute PSO gets its root + # arguments from s4 (D3D-448), as for the M4 shaders. + COMMENT "Translating ms_m5, ps_m5_mesh, vs_m3 and ps_m5_flat for the M5 mesh test" + VERBATIM) + # The same shaders translated with --mesh-compute and --wave64-emulate: the test's --mesh-compute mode runs the + # same draws on a device without VK_EXT_mesh_shader (the layer's own device is created without it, so every + # GPU runs it), DispatchMesh through the mesh-as-compute pass and ExecuteIndirect(DISPATCH_MESH) through the + # prepass of vulkan_mesh_indirect.h. + set(LEONIDA_M5_MESH_COMPUTE_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m5_mesh_compute_shaders) + set(LEONIDA_M5_MESH_COMPUTE_FILES ${LEONIDA_M5_MESH_COMPUTE_DIR}/spirv/index.json + ${LEONIDA_M5_MESH_COMPUTE_DIR}/fssm/ms_m5.fssm + ${LEONIDA_M5_MESH_COMPUTE_DIR}/fssm/ps_m5_mesh.fssm + ${LEONIDA_M5_MESH_COMPUTE_DIR}/fssm/vs_m3.fssm + ${LEONIDA_M5_MESH_COMPUTE_DIR}/fssm/ps_m5_flat.fssm + ${LEONIDA_M5_MESH_COMPUTE_DIR}/fssm/cs_m5_args.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M5_MESH_COMPUTE_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M5_MESH_COMPUTE_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + "LEONIDA_MESH_COMPUTE=1" "LEONIDA_W64_EMULATE=1" + LEONIDA_USER_DATA_SHIFT=4 + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M5_MESH_COMPUTE_DIR} ms_m5 ps_m5_mesh vs_m3 ps_m5_flat cs_m5_args + 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}/test/shaders/cs_m5_args.asm + ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py + COMMENT "Translating ms_m5, ps_m5_mesh, vs_m3 and ps_m5_flat with --mesh-compute 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} + ${LEONIDA_M5_MESH_COMPUTE_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}" + LEONIDA_TEST_M5_MESH_COMPUTE_DIR="${LEONIDA_M5_MESH_COMPUTE_DIR}") + 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) + add_test(NAME d3d12_m5_mesh_chunks COMMAND d3d12_m5_mesh_test --max-draw-indirect-count 3) + add_test(NAME d3d12_m5_mesh_compute COMMAND d3d12_m5_mesh_test --mesh-compute) + add_test(NAME d3d12_m5_mesh_compute_single COMMAND d3d12_m5_mesh_test --mesh-compute --single-calls) + set_tests_properties(d3d12_m5_mesh d3d12_m5_mesh_fallbacks d3d12_m5_mesh_chunks d3d12_m5_mesh_compute + d3d12_m5_mesh_compute_single 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 @@ -2148,7 +2265,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 and d3d12_buffer_uav_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. @@ -2487,8 +2604,47 @@ 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) + # Mesh PSOs and DispatchMesh without VK_EXT_mesh_shader, through --mesh-compute (runs on every GPU: the layer's + # device is made without the extension). + set(LEONIDA_TEST_MS_COMPUTE ${CMAKE_CURRENT_BINARY_DIR}/generated/ms_draw_compute.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_MS_COMPUTE} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -o ${LEONIDA_TEST_MS_COMPUTE} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw_compute.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw_compute.comp + COMMENT "Compiling the --mesh-compute test shader ms_draw_compute.comp" + VERBATIM) + add_executable(d3d12_mesh_compute_test test/d3d12_mesh_compute_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_MS_COMPUTE} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_mesh_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_mesh_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_MS_COMPUTE_SPV="${LEONIDA_TEST_MS_COMPUTE}" + LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_mesh_compute_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_mesh_compute COMMAND d3d12_mesh_compute_test) + set_tests_properties(d3d12_mesh_compute 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, d3d12_mesh_test and d3d12_mesh_compute_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..1f192b33d4 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,16 @@ 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 (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 { d3d12_trace::record("ID3D12GraphicsCommandList::ResourceBarrier"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); @@ -750,6 +761,17 @@ 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). + // 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_ || mesh)) { + if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; + cmd.state = std::make_shared( + 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; cmd.max_count = max_command_count; @@ -1179,16 +1201,37 @@ 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 + check(list_.draw(make_mesh_draw(x, y, z))); + } + // 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); // 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, draw_views(), depth_, index_, topology_, viewport_, - scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, - first, base_vertex, first_instance}; - check(list_.draw(std::move(draw))); + 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) { + return {graphics_pipeline_, graphics_.data, draw_views(), depth_, 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 db5552b7f0..dcb619c2ea 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -103,6 +103,17 @@ 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. 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). @@ -169,6 +180,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{}; @@ -262,6 +277,18 @@ 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); + // The free indices of that set's 2D image and sampler arrays: how many more distinct 2D T#s and S#s // CreateShaderResourceView and CreateSampler can register before they log that the array is full. Zeros when // `device` has no such set. For tests. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1316fefaad..2f800a154f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -28,6 +28,7 @@ #include "../src/shader_library.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" +#include "../src/mesh_compute_vs.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/vulkan13_features.h" @@ -551,6 +552,13 @@ 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; + // Whether the Direct queue's family has VK_QUEUE_COMPUTE_BIT, read on first use by a --mesh-compute mesh PSO. + bool direct_computes = false; + bool direct_computes_read = false; PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr; @@ -721,6 +729,42 @@ struct DeviceState { } } + // Every pipeline the device creates goes through pipeline_cache() (docs/d3d12_vulkan.md section 3.6): a PSO + // created a second time from the same shaders and state is satisfied from it. With Vulkan 1.3 every creation also + // asks for VkPipelineCreationFeedback, which is how the layer counts the creations the cache answered. + 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}; + + // The size of the cache's data in bytes, 0 without a cache. + std::size_t pipeline_cache_bytes() { + const VkPipelineCache cache = pipeline_cache(); + 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(), 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; @@ -872,6 +916,54 @@ 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; + } + + // Whether the Direct queue's family can record vkCmdDispatch, as a --mesh-compute mesh draw does on that queue + // (VUID-vkCmdDispatch-commandBuffer-02707). The device is picked for VK_QUEUE_GRAPHICS_BIT only, and a family + // may have graphics without compute. False when it cannot be asked. + bool direct_family_computes() { + std::lock_guard lock(mesh_properties_mutex); + if (direct_computes_read) return direct_computes; + direct_computes_read = true; + const auto queue_families = reinterpret_cast( + info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties") + : nullptr); + if (!queue_families || !info.physical) return direct_computes; + std::uint32_t count = 0; + queue_families(info.physical, &count, nullptr); + std::vector queues(count); + queue_families(info.physical, &count, queues.data()); + direct_computes = info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT); + return direct_computes; + } + + // Whether a --mesh-compute mesh shader runs here at the subgroup size it was translated for, guaranteed: it is + // emulated (exact on any size), the compute stage requires the size, or that size is the device's only one. A + // size that is only the default, or cannot be had, could change the result of its subgroup operations. + bool mesh_compute_subgroup_guaranteed(const leonida::ShaderEntry& entry) const { + leonida::ShaderEntry as_compute; // what decide_subgroup_size reads, for the compute stage + as_compute.stage = "cs"; + as_compute.wave64 = entry.wave64; + as_compute.subgroup_size = entry.subgroup_size; + as_compute.wave64_exchange = entry.wave64_exchange; + as_compute.local_size = entry.local_size; + const leonida::SubgroupOutcome outcome = leonida::decide_subgroup_size(as_compute, info.subgroup).outcome; + return outcome == leonida::SubgroupOutcome::emulated || outcome == leonida::SubgroupOutcome::required || + outcome == leonida::SubgroupOutcome::device_fixed; + } + // 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 +2894,201 @@ 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)); + // 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; + 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 { @@ -2820,6 +3107,8 @@ class PipelineState final if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); + if (graphics_.mesh_compute.pipeline) vk.vkDestroyPipeline(dev, graphics_.mesh_compute.pipeline, nullptr); + if (graphics_.mesh_compute.layout) vk.vkDestroyPipelineLayout(dev, graphics_.mesh_compute.layout, nullptr); for (VkShaderModule module : modules_) vk.vkDestroyShaderModule(dev, module, nullptr); if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); } @@ -2894,10 +3183,39 @@ 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; + // Without VK_EXT_mesh_shader a mesh PSO runs through --mesh-compute (rdna2spirv.py, #1053): the mesh shader + // as a compute pipeline writing one output slot per workgroup, drawn by a vertex shader built here + // (mesh_compute_vs.h). Its MS entry must be such a module (checked below), and both take 152 bytes of push + // constants. The dispatch is recorded on the Direct queue, whose family must then have compute. + const bool mesh_compute = mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT); + if (mesh_compute && device_.info.max_push_constants_size && + device_.info.max_push_constants_size < sizeof(leonida::MeshComputeUserData)) { + log_once("--mesh-compute PSOs need 152 bytes of push constants; maxPushConstantsSize", + int(device_.info.max_push_constants_size)); + return E_NOTIMPL; + } + if (mesh_compute && !device_.direct_family_computes()) { + log_once("--mesh-compute PSOs dispatch on the Direct queue, whose family has no VK_QUEUE_COMPUTE_BIT; " + "family", + int(device_.info.queue_family)); + return E_NOTIMPL; + } if (!device_.arena.mapped) { log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); return E_NOTIMPL; @@ -2954,7 +3272,11 @@ class PipelineState final std::vector fssm; std::vector words; }; - Stage stages[3] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, + // --mesh-compute: the MS entry is looked up as "ms", and its Vulkan stage is the vertex shader drawing its + // slots. + const VkShaderStageFlagBits ms_bit = mesh_compute ? VK_SHADER_STAGE_VERTEX_BIT : VK_SHADER_STAGE_MESH_BIT_EXT; + Stage stages[3] = {mesh ? Stage{"ms", ms_bit, *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. @@ -2991,7 +3313,7 @@ class PipelineState final const std::string hash = leonida::sha256_hex(stage.fssm); // Containers with the same program can differ in their input signature or bindings: a VS must have its // inputs fed by this input layout (else the layout check below reports it). - const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT; + const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !mesh; stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { return !vertex || layout_feeds(e, desc.InputLayout); }); @@ -3008,6 +3330,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); @@ -3037,7 +3379,51 @@ class PipelineState final if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } - if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && !ps_stage.entry->f16_halves.empty()) { + // --mesh-compute: the MS module becomes the compute pipeline (create_mesh_compute, below), and stages[0] the + // vertex shader that draws its slots. That shader exports each param's decoded halves where the layout says, + // so a PS reading halves must read each of them there (a subset is fine: the rest go unread). Moving them per + // pipeline, as tools/mesh_compute_vs.py's pair_f16_halves does, is not built yet. + std::vector mesh_compute_words; + if (mesh_compute) { + const leonida::ShaderEntry& ms_entry = *vs_stage.entry; + if (!ms_entry.mesh_compute) { + std::fprintf(stderr, "[rt] d3d12: %s: mesh-shader PSOs need VK_EXT_mesh_shader, which the device has " + "not enabled, or mesh shaders translated with --mesh-compute\n", + ms_entry.name.c_str()); + return E_NOTIMPL; + } + // Its subgroup operations are exact only at the size it was translated for: refused where the compute + // stage cannot be guaranteed that size (the tier is hidden there too). --wave64-emulate makes a wave64 + // mesh shader exact on any size. + if (!device_.mesh_compute_subgroup_guaranteed(ms_entry)) { + std::fprintf(stderr, "[rt] d3d12: %s: this device cannot guarantee the %u-wide subgroups it was " + "translated for in a compute pipeline (translate it with --wave64-emulate)\n", + ms_entry.name.c_str(), + ms_entry.subgroup_size ? ms_entry.subgroup_size : (ms_entry.wave64 ? 64u : 32u)); + return E_NOTIMPL; + } + if (ps_stage.entry) { + const auto& exported = ms_entry.mesh_compute->f16_halves; + for (const auto& [param, halves] : ps_stage.entry->f16_halves) { + const auto it = exported.find(param); + if (it != exported.end() && it->second == halves) continue; + std::fprintf(stderr, "[rt] d3d12: %s reads param %u's f16 halves where %s's mesh_compute layout " + "does not export them (per-pipeline pairing not built yet)\n", + ps_stage.entry->name.c_str(), param, ms_entry.name.c_str()); + return E_NOTIMPL; + } + } + std::string vs_error; + std::vector vs_words = leonida::mesh_compute_vs(*ms_entry.mesh_compute, &vs_error); + if (vs_words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s: %s\n", ms_entry.name.c_str(), vs_error.c_str()); + return E_NOTIMPL; + } + mesh_compute_words = std::move(vs_stage.words); + vs_stage.words = std::move(vs_words); + } + if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && !mesh_compute && + !ps_stage.entry->f16_halves.empty()) { std::string link_error; if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, &link_error)) { @@ -3085,7 +3471,10 @@ class PipelineState final info.stage = stage.bit; info.module = module; info.pName = "main"; - subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); + // The --mesh-compute vertex shader uses no subgroup operation: it asks for no size (the MS entry's + // size is the compute pipeline's). + if (!(mesh_compute && &stage == &vs_stage)) + subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth @@ -3104,13 +3493,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 +3551,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 +3559,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 && @@ -3367,7 +3758,9 @@ class PipelineState final for (const Stage& stage : stages) if (stage.bit != VK_SHADER_STAGE_GEOMETRY_BIT || device_.info.features.geometryShader) graphics_.push_stages |= stage.bit; - const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)}; + const VkPushConstantRange push{graphics_.push_stages, 0, + static_cast(mesh_compute ? sizeof(leonida::MeshComputeUserData) + : sizeof(leonida::ShaderUserData))}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; @@ -3379,8 +3772,15 @@ class PipelineState final graphics_.bindless_set = device_.bindless->set(); } if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; + if (mesh_compute) { + if (const HRESULT hr = create_mesh_compute(*vs_stage.entry, mesh_compute_words); FAILED(hr)) return hr; + } // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. + // A --mesh-compute pipeline is still a mesh PSO to D3D12 (DispatchMesh draws it), and a vertex pipeline to + // Vulkan: input assembly (triangle lists, set at the draw) and no vertex input. + graphics_.mesh = mesh; + recipe_.mesh = mesh && !mesh_compute; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); recipe_.bindings = std::move(bindings); @@ -3412,6 +3812,68 @@ class PipelineState final return S_OK; } + // A --mesh-compute mesh PSO's compute half (create_graphics): the MS module as a compute pipeline that writes the + // workgroups' output slots, with the 152-byte push-constant block (the output address in dwords 36..37), the + // device's set 0 where the module declares bindings, and the subgroup size the shader was translated for. + HRESULT create_mesh_compute(const leonida::ShaderEntry& entry, const std::vector& words) { + auto& vk = device_.context->vk; + const VkDevice dev = device_.info.device; + // SHADER-309, as for compute PSOs: workgroup memory over the device's limit is refused here. + if (entry.lds_bytes && device_.info.get_instance_proc) { + if (const auto get_props = reinterpret_cast( + device_.info.get_instance_proc(device_.info.instance, "vkGetPhysicalDeviceProperties"))) { + VkPhysicalDeviceProperties props{}; + get_props(device_.info.physical, &props); + if (entry.lds_bytes > props.limits.maxComputeSharedMemorySize) { + std::fprintf(stderr, + "[rt] d3d12: %s declares %u bytes of workgroup memory, over the device's " + "maxComputeSharedMemorySize %u\n", + entry.name.c_str(), unsigned(entry.lds_bytes), + unsigned(props.limits.maxComputeSharedMemorySize)); + return E_NOTIMPL; + } + } + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + auto& mc = graphics_.mesh_compute; + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::MeshComputeUserData)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; + if (entry.binding_count) { // create_graphics checked that the device has its bindless set + set0_layout = device_.bindless->layout(); + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = &set0_layout; + mc.bindless_set = device_.bindless->set(); + } + if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &mc.layout) != VK_SUCCESS) return E_FAIL; + VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline_info.stage.module = module; + pipeline_info.stage.pName = "main"; + leonida::ShaderEntry as_compute = entry; // its subgroup size is decided for the compute stage + as_compute.stage = "cs"; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; + subgroup_size_for(as_compute, required_size, pipeline_info.stage); + pipeline_info.layout = mc.layout; + if (device_.create_pipeline( + [&](VkPipelineCache cache, const VkComputePipelineCreateInfo& create) { + return vk.vkCreateComputePipelines(dev, cache, 1, &create, nullptr, &mc.pipeline); + }, + pipeline_info) != VK_SUCCESS) + return E_FAIL; + mc.slot_bytes = entry.mesh_compute->slot_bytes; + mc.max_primitives = entry.mesh_compute->max_primitives; + return S_OK; + } + HRESULT create_compute(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; @@ -3505,8 +3967,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, device_.pipeline_cache(), 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. The @@ -3526,6 +3991,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 +4060,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; @@ -3611,8 +4087,12 @@ class PipelineState final info.pDynamicState = &dynamic; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 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; } @@ -4471,6 +4951,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; @@ -4546,6 +5031,11 @@ class Device final return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; }); } + 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) { @@ -4569,10 +5059,16 @@ class Device final } } if (info.host_image_copy) load_host_image_copy(get_device); - // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. - state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { - return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); + // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. With buffer + // device addresses the same scratch holds --mesh-compute mesh draws' output slots (vulkan_replay.h). + const bool scratch_addresses = info.buffer_device_address; + state_.context->enable_copy_scratch( + get_device, + [this, scratch_addresses](const VkMemoryRequirements& requirements) { + return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, + scratch_addresses); + }, + scratch_addresses); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { @@ -4920,6 +5416,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; } @@ -5208,6 +5705,21 @@ class Device final identity())); } + // Mesh tier 1 without VK_EXT_mesh_shader: the translated mesh shaders are --mesh-compute ones and the device can + // run them all as create_graphics does (buffer device addresses, 152 bytes of push constants, compute on the + // Direct queue's family, each one's subgroup size guaranteed). CheckFeatureSupport reports the tier from this and + // CreateCommandSignature accepts DISPATCH_MESH on it, so the two can't disagree. + bool mesh_compute_tier() { + const leonida::ShaderLibrary* library = state_.library(); + const std::uint32_t push_limit = state_.info.max_push_constants_size; + return !state_.info.mesh_shader && library && library->mesh_compute_count() && + state_.info.buffer_device_address && + (!push_limit || push_limit >= sizeof(leonida::MeshComputeUserData)) && + state_.direct_family_computes() && + library->all_mesh_compute( + [this](const leonida::ShaderEntry& e) { return state_.mesh_compute_subgroup_guaranteed(e); }); + } + HRESULT STDMETHODCALLTYPE CreateCommandSignature(const D3D12_COMMAND_SIGNATURE_DESC* desc, ID3D12RootSignature* root_signature, REFIID riid, void** out) override { @@ -5249,6 +5761,18 @@ 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, or without VK_EXT_mesh_shader, where the mesh PSOs are + // --mesh-compute ones (mesh_compute_tier), as the mesh-as-compute pass and the slot draw per record, with + // their indirect commands written on the GPU (vulkan_mesh_indirect.h). Without either, the device reports + // MeshShaderTier NOT_SUPPORTED and there is no mesh PSO to run it with. + if (!(state_.info.mesh_shader && state_.context->vk.vkCmdDrawMeshTasksIndirectEXT) && !mesh_compute_tier()) + 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; } return create_command_signature(kind, desc->ByteStride, riid, out, identity()); @@ -5570,6 +6094,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 +7392,13 @@ 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, or without it where the translated mesh + // shaders are --mesh-compute ones and the device can run them all as create_graphics does: buffer device + // addresses, 152 bytes of push constants, compute on the Direct queue's family, and each one's subgroup + // size guaranteed. 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 || mesh_compute_tier() ? 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); } @@ -8164,6 +8715,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() != VK_NULL_HANDLE; + stats.created = state.pipelines_created; + stats.hits = state.pipeline_cache_hits; + stats.bytes = state.pipeline_cache_bytes(); + return stats; +} + BindlessRoom bindless_room(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); if (!set) return {}; @@ -8533,6 +9098,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 +9118,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 +9154,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; @@ -8618,6 +9199,12 @@ 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.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; @@ -8691,6 +9278,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; @@ -8956,6 +9545,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..214d51bf7e 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -414,9 +415,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 +440,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. @@ -583,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 { @@ -593,6 +598,16 @@ 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 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 + // (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; // kind == dispatch: the compute pipeline and root arguments in effect, as Dispatch records them, so the dispatches // run that pipeline with those arguments whatever the command buffer had bound. A pipeline of 0 leaves the binding // as it is. @@ -738,10 +753,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) { @@ -867,6 +883,9 @@ 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/src/mesh_compute_vs.h b/runtime/src/mesh_compute_vs.h new file mode 100644 index 0000000000..dbc6c8e78d --- /dev/null +++ b/runtime/src/mesh_compute_vs.h @@ -0,0 +1,311 @@ +#pragma once + +// The vertex shader that draws what a `--mesh-compute` mesh shader wrote (rdna2spirv.py, #1053). +// +// On a device without VK_EXT_mesh_shader, `rdna2spirv.py --mesh-compute` turns each mesh shader into a compute shader +// with the same workgroup size. Each workgroup writes its vertex and primitive counts, its vertices and its +// primitives into a slot of an output buffer whose device address is in push-constant dwords 36..37 (the entry's +// "mesh_compute" layout, MeshComputeLayout). This header builds the vertex shader that draws the slots, the module +// tools/mesh_compute_vs.py writes for the GPU tests, instruction for instruction: +// - the draw is non-indexed, vkCmdDraw(groups * max_primitives * 3): vertex v is workgroup v / (3 * max_primitives), +// primitive (v / 3) % max_primitives, corner v % 3; +// - a primitive past the workgroup's count, or one marked culled, puts the same position outside the clip volume at +// all three corners, so it is clipped away; +// - otherwise the corner's vertex index (clamped to max_vertices - 1) selects the vertex whose position, clip and +// cull distances and params go out, at the mesh shader's locations, so the pixel shader is unchanged; with +// --f16-interp-fallback each f16_halves param's halves also go out decoded to f32 at their two locations. +// +// Pure C++20 stdlib, no Vulkan or Windows headers required. + +#include "shader_library.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +namespace mesh_vs_detail { + +constexpr std::uint16_t kOpExtension = 10, kOpExtInstImport = 11, kOpExtInst = 12, kOpMemoryModel = 14, + kOpEntryPoint = 15, kOpCapability = 17, kOpTypeVoid = 19, kOpTypeBool = 20, kOpTypeInt = 21, + kOpTypeFloat = 22, kOpTypeVector = 23, kOpTypeArray = 28, kOpTypeRuntimeArray = 29, + kOpTypeStruct = 30, kOpTypePointer = 32, kOpTypeFunction = 33, kOpConstant = 43, + kOpConstantComposite = 44, kOpFunction = 54, kOpFunctionEnd = 56, kOpVariable = 59, + kOpLoad = 61, kOpStore = 62, kOpAccessChain = 65, kOpDecorate = 71, kOpMemberDecorate = 72, + kOpCompositeConstruct = 80, kOpCompositeExtract = 81, kOpCopyObject = 83, kOpUConvert = 113, + kOpConvertUToPtr = 120, kOpBitcast = 124, kOpIAdd = 128, kOpIMul = 132, kOpUDiv = 134, + kOpUMod = 137, kOpLogicalAnd = 167, kOpLogicalNot = 168, kOpSelect = 169, kOpINotEqual = 171, + kOpULessThan = 176, kOpShiftLeftLogical = 196, kOpBitwiseOr = 197, kOpLabel = 248, + kOpReturn = 253; +constexpr std::uint32_t kCapShader = 1, kCapInt64 = 11, kCapClipDistance = 32, kCapCullDistance = 33, + kCapPhysicalStorageBufferAddresses = 5347; +constexpr std::uint32_t kAddressingPhysicalStorageBuffer64 = 5348, kMemoryGlsl450 = 1, kExecModelVertex = 0; +constexpr std::uint32_t kDecBlock = 2, kDecArrayStride = 6, kDecBuiltIn = 11, kDecLocation = 30, kDecOffset = 35; +constexpr std::uint32_t kBuiltInPosition = 0, kBuiltInClipDistance = 3, kBuiltInCullDistance = 4, + kBuiltInVertexIndex = 42; +constexpr std::uint32_t kStorageInput = 1, kStorageOutput = 3, kStoragePushConstant = 9, + kStoragePhysicalStorageBuffer = 5349; +constexpr std::uint32_t kMemoryAligned = 2; +constexpr std::uint32_t kGlslUMin = 38, kGlslUnpackHalf2x16 = 62; +constexpr std::uint32_t kUserSgprs = 32; // s0..s31, then heap base, code base and the output address + +inline void op(std::vector& w, std::uint16_t opcode, std::initializer_list operands) { + w.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode); + w.insert(w.end(), operands.begin(), operands.end()); +} + +inline void op(std::vector& w, std::uint16_t opcode, const std::vector& operands) { + w.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode); + w.insert(w.end(), operands.begin(), operands.end()); +} + +// A literal string's words: UTF-8, nul-terminated, padded with zeros to a whole word. +inline std::vector literal(std::string_view s) { + std::vector w(s.size() / 4 + 1, 0); + for (std::size_t i = 0; i < s.size(); ++i) w[i / 4] |= std::uint32_t(std::uint8_t(s[i])) << (8 * (i % 4)); + return w; +} + +} // namespace mesh_vs_detail + +// The vertex shader's SPIR-V words for this layout, or empty with *error set: a layout without vertices or +// primitives, one whose address is in the --pc-tail-ubo block, an f16_halves param that is not a layout param, or +// a half location that collides with another output. +inline std::vector mesh_compute_vs(const MeshComputeLayout& lay, std::string* error = nullptr) { + using namespace mesh_vs_detail; + const auto fail = [&](const std::string& why) { + if (error) *error = why; + return std::vector{}; + }; + const std::uint32_t maxv = lay.max_vertices, maxp = lay.max_primitives, clip = lay.clip_count, + cull = lay.cull_count; + if (!maxv || !maxp || !lay.slot_bytes) return fail("mesh_compute: a layout without vertices or primitives"); + if (lay.address_in_pc_tail) + return fail("mesh_compute: the output address is in the --pc-tail-ubo block, which this vertex shader does " + "not read"); + if (clip > 8 || cull > 8) return fail("mesh_compute: more than 8 clip or cull distances"); + std::set used( // output locations: the params, then each half's two + [&] { std::set s; for (const auto& [loc, off] : lay.params) s.insert(loc); return s; }()); + std::vector half_locations; + for (const auto& [loc, h] : lay.f16_halves) { + if (!lay.params.count(loc)) + return fail("mesh_compute: f16_halves param " + std::to_string(loc) + " is not in the layout's params"); + if (h[0] == h[1]) return fail("mesh_compute: f16_halves param " + std::to_string(loc) + " has one location"); + for (const std::uint32_t hloc : h) { + if (!used.insert(hloc).second) + return fail("mesh_compute: f16_halves location " + std::to_string(hloc) + + " collides with another output"); + half_locations.push_back(hloc); + } + } + + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + // Types, the push-constant block, globals: fixed ids. Constants get theirs as the body asks for them. + const std::uint32_t glsl = id(), t_void = id(), t_fn = id(), t_bool = id(), t_uint = id(), t_int = id(), + t_ulong = id(), t_float = id(), t_v4 = id(), t_v2 = id(), n_ud = id(), arr_ud = id(), + t_pc = id(), p_pc = id(), p_pc_uint = id(), rt_uint = id(), p_psb_uint = id(), + p_in_int = id(), p_out_v4 = id(), f1 = id(), f2 = id(), outside = id(); + const std::uint32_t arr_clip = clip ? id() : 0, p_out_clip = clip ? id() : 0; + const std::uint32_t arr_cull = cull ? id() : 0, p_out_cull = cull ? id() : 0; + const std::uint32_t vertex_index = id(), pc = id(), out_pos = id(); + const std::uint32_t out_clip = clip ? id() : 0, out_cull = cull ? id() : 0; + std::map out_at; // output location -> variable + for (const auto& [loc, off] : lay.params) out_at[loc] = id(); + for (const std::uint32_t hloc : half_locations) out_at[hloc] = id(); + const std::uint32_t fn_main = id(), entry = id(); + + std::map uints, ulongs; // value -> constant id, emitted sorted by value + const auto c = [&](std::uint32_t v) { + auto [it, added] = uints.try_emplace(v, 0); + if (added) it->second = id(); + return it->second; + }; + const auto cl = [&](std::uint32_t v) { + auto [it, added] = ulongs.try_emplace(v, 0); + if (added) it->second = id(); + return it->second; + }; + + std::vector body; + const auto value = [&](std::uint16_t opcode, std::uint32_t type, std::initializer_list operands) { + const std::uint32_t r = id(); + std::vector all{type, r}; + all.insert(all.end(), operands.begin(), operands.end()); + op(body, opcode, all); + return r; + }; + // The uint at slot byte offset `off` from the ulong address `base`. + const auto load_word = [&](std::uint32_t base, std::uint32_t off) { + const std::uint32_t a = off ? value(kOpIAdd, t_ulong, {base, cl(off)}) : value(kOpCopyObject, t_ulong, {base}); + const std::uint32_t p = value(kOpConvertUToPtr, p_psb_uint, {a}); + return value(kOpLoad, t_uint, {p, kMemoryAligned, 4}); + }; + const auto load_floats = [&](std::uint32_t base, std::uint32_t off, std::uint32_t count) { + std::vector out; + for (std::uint32_t i = 0; i < count; ++i) + out.push_back(value(kOpBitcast, t_float, {load_word(base, off + 4 * i)})); + return out; + }; + const auto construct = [&](std::uint32_t type, const std::vector& parts) { + const std::uint32_t r = id(); + std::vector all{type, r}; + all.insert(all.end(), parts.begin(), parts.end()); + op(body, kOpCompositeConstruct, all); + return r; + }; + + for (const std::uint32_t v : {0u, 1u, 3u, 5u, 6u}) c(v); // as the Python module declares them + if (clip) c(clip); + if (cull) c(cull); + const std::uint32_t vid = value(kOpLoad, t_int, {vertex_index}); + const std::uint32_t vidu = value(kOpBitcast, t_uint, {vid}); + const std::uint32_t per = value(kOpCopyObject, t_uint, {c(3 * maxp)}); + const std::uint32_t wg = value(kOpUDiv, t_uint, {vidu, per}); + const std::uint32_t rem = value(kOpUMod, t_uint, {vidu, per}); + const std::uint32_t prim = value(kOpUDiv, t_uint, {rem, c(3)}); + const std::uint32_t corner = value(kOpUMod, t_uint, {rem, c(3)}); + const std::uint32_t alo_p = value(kOpAccessChain, p_pc_uint, {pc, c(5)}); + const std::uint32_t ahi_p = value(kOpAccessChain, p_pc_uint, {pc, c(6)}); + const std::uint32_t alo = value(kOpLoad, t_uint, {alo_p}); + const std::uint32_t ahi = value(kOpLoad, t_uint, {ahi_p}); + const std::uint32_t alo64 = value(kOpUConvert, t_ulong, {alo}); + const std::uint32_t ahi64 = value(kOpUConvert, t_ulong, {ahi}); + const std::uint32_t ahis = value(kOpShiftLeftLogical, t_ulong, {ahi64, cl(32)}); + const std::uint32_t addr = value(kOpBitwiseOr, t_ulong, {ahis, alo64}); + const std::uint32_t wg64 = value(kOpUConvert, t_ulong, {wg}); + const std::uint32_t soff = value(kOpIMul, t_ulong, {wg64, cl(lay.slot_bytes)}); + const std::uint32_t slot = value(kOpIAdd, t_ulong, {addr, soff}); + const std::uint32_t pcount = load_word(slot, 4); + const std::uint32_t inrange = value(kOpULessThan, t_bool, {prim, pcount}); + const std::uint32_t pofs = value(kOpIMul, t_uint, {prim, c(lay.primitive_stride)}); + const std::uint32_t pofs64 = value(kOpUConvert, t_ulong, {pofs}); + const std::uint32_t pbase0 = value(kOpIAdd, t_ulong, {slot, cl(lay.primitives)}); + const std::uint32_t pbase = value(kOpIAdd, t_ulong, {pbase0, pofs64}); + const std::uint32_t cofs = value(kOpIMul, t_uint, {corner, c(4)}); + const std::uint32_t cofs64 = value(kOpUConvert, t_ulong, {cofs}); + const std::uint32_t iaddr = value(kOpIAdd, t_ulong, {pbase, cofs64}); + const std::uint32_t iptr = value(kOpConvertUToPtr, p_psb_uint, {iaddr}); + const std::uint32_t idx0 = value(kOpLoad, t_uint, {iptr, kMemoryAligned, 4}); + const std::uint32_t idx = value(kOpExtInst, t_uint, {glsl, kGlslUMin, idx0, c(maxv - 1)}); + const std::uint32_t culled_w = load_word(pbase, 12); + const std::uint32_t culled = value(kOpINotEqual, t_bool, {culled_w, c(0)}); + const std::uint32_t notculled = value(kOpLogicalNot, t_bool, {culled}); + const std::uint32_t valid = value(kOpLogicalAnd, t_bool, {inrange, notculled}); + const std::uint32_t vofs = value(kOpIMul, t_uint, {idx, c(lay.vertex_stride)}); + const std::uint32_t vofs64 = value(kOpUConvert, t_ulong, {vofs}); + const std::uint32_t vbase0 = value(kOpIAdd, t_ulong, {slot, cl(lay.vertices)}); + const std::uint32_t vbase = value(kOpIAdd, t_ulong, {vbase0, vofs64}); + const std::uint32_t pos = construct(t_v4, load_floats(vbase, 0, 4)); + const std::uint32_t pos_out = value(kOpSelect, t_v4, {valid, pos, outside}); + op(body, kOpStore, {out_pos, pos_out}); + if (clip) op(body, kOpStore, {out_clip, construct(arr_clip, load_floats(vbase, lay.clip_offset, clip))}); + if (cull) op(body, kOpStore, {out_cull, construct(arr_cull, load_floats(vbase, lay.cull_offset, cull))}); + for (const auto& [loc, off] : lay.params) + op(body, kOpStore, {out_at[loc], construct(t_v4, load_floats(vbase, off, 4))}); + for (const auto& [loc, h] : lay.f16_halves) { // each channel's two f16 halves decoded to f32 + std::vector parts[2]; + for (std::uint32_t i = 0; i < 4; ++i) { + const std::uint32_t w = load_word(vbase, lay.params.at(loc) + 4 * i); + const std::uint32_t h2 = value(kOpExtInst, t_v2, {glsl, kGlslUnpackHalf2x16, w}); + for (std::uint32_t half = 0; half < 2; ++half) + parts[half].push_back(value(kOpCompositeExtract, t_float, {h2, half})); + } + for (std::uint32_t half = 0; half < 2; ++half) + op(body, kOpStore, {out_at[h[half]], construct(t_v4, parts[half])}); + } + op(body, kOpReturn, {}); + op(body, kOpFunctionEnd, {}); + + // The module, in the order the Python one has it. + std::vector w{0x07230203u, 0x00010500u, 0, 0, 0}; // SPIR-V 1.5; bound set at the end + for (const std::uint32_t cap : {kCapShader, kCapInt64, kCapPhysicalStorageBufferAddresses}) + op(w, kOpCapability, {cap}); + if (clip) op(w, kOpCapability, {kCapClipDistance}); + if (cull) op(w, kOpCapability, {kCapCullDistance}); + op(w, kOpExtension, literal("SPV_KHR_physical_storage_buffer")); + { + std::vector import{glsl}; + const auto name = literal("GLSL.std.450"); + import.insert(import.end(), name.begin(), name.end()); + op(w, kOpExtInstImport, import); + } + op(w, kOpMemoryModel, {kAddressingPhysicalStorageBuffer64, kMemoryGlsl450}); + // Output order: position, distances, the params, then the halves' locations in f16_halves order. + std::vector output_order{out_pos}; + if (clip) output_order.push_back(out_clip); + if (cull) output_order.push_back(out_cull); + std::vector located; // locations in declaration order + for (const auto& [loc, off] : lay.params) located.push_back(loc); + located.insert(located.end(), half_locations.begin(), half_locations.end()); + for (const std::uint32_t loc : located) output_order.push_back(out_at[loc]); + { + std::vector ep{kExecModelVertex, fn_main}; + const auto name = literal("main"); + ep.insert(ep.end(), name.begin(), name.end()); + ep.push_back(vertex_index); + ep.push_back(pc); + ep.insert(ep.end(), output_order.begin(), output_order.end()); + op(w, kOpEntryPoint, ep); + } + op(w, kOpDecorate, {vertex_index, kDecBuiltIn, kBuiltInVertexIndex}); + op(w, kOpDecorate, {out_pos, kDecBuiltIn, kBuiltInPosition}); + if (clip) op(w, kOpDecorate, {out_clip, kDecBuiltIn, kBuiltInClipDistance}); + if (cull) op(w, kOpDecorate, {out_cull, kDecBuiltIn, kBuiltInCullDistance}); + for (const std::uint32_t loc : located) op(w, kOpDecorate, {out_at[loc], kDecLocation, loc}); + op(w, kOpDecorate, {arr_ud, kDecArrayStride, 4}); + op(w, kOpDecorate, {t_pc, kDecBlock}); + op(w, kOpMemberDecorate, {t_pc, 0, kDecOffset, 0}); + for (std::uint32_t k = 1; k <= 6; ++k) + op(w, kOpMemberDecorate, {t_pc, k, kDecOffset, 4 * kUserSgprs + 4 * (k - 1)}); + op(w, kOpDecorate, {rt_uint, kDecArrayStride, 4}); + op(w, kOpTypeVoid, {t_void}); + op(w, kOpTypeFunction, {t_fn, t_void}); + op(w, kOpTypeBool, {t_bool}); + op(w, kOpTypeInt, {t_uint, 32, 0}); + op(w, kOpTypeInt, {t_int, 32, 1}); + op(w, kOpTypeInt, {t_ulong, 64, 0}); + op(w, kOpTypeFloat, {t_float, 32}); + op(w, kOpTypeVector, {t_v4, t_float, 4}); + op(w, kOpTypeVector, {t_v2, t_float, 2}); + for (const auto& [v, cid] : uints) op(w, kOpConstant, {t_uint, cid, v}); + for (const auto& [v, cid] : ulongs) op(w, kOpConstant, {t_ulong, cid, v, 0}); // low word, then high + op(w, kOpConstant, {t_uint, n_ud, kUserSgprs}); + op(w, kOpTypeArray, {arr_ud, t_uint, n_ud}); + op(w, kOpTypeStruct, {t_pc, arr_ud, t_uint, t_uint, t_uint, t_uint, t_uint, t_uint}); + op(w, kOpTypePointer, {p_pc, kStoragePushConstant, t_pc}); + op(w, kOpTypePointer, {p_pc_uint, kStoragePushConstant, t_uint}); + op(w, kOpTypeRuntimeArray, {rt_uint, t_uint}); + op(w, kOpTypePointer, {p_psb_uint, kStoragePhysicalStorageBuffer, t_uint}); + op(w, kOpTypePointer, {p_in_int, kStorageInput, t_int}); + op(w, kOpTypePointer, {p_out_v4, kStorageOutput, t_v4}); + op(w, kOpConstant, {t_float, f1, 0x3f800000u}); + op(w, kOpConstant, {t_float, f2, 0x40000000u}); + op(w, kOpConstantComposite, {t_v4, outside, f2, f2, f2, f1}); + if (clip) { + op(w, kOpTypeArray, {arr_clip, t_float, c(clip)}); + op(w, kOpTypePointer, {p_out_clip, kStorageOutput, arr_clip}); + } + if (cull) { + op(w, kOpTypeArray, {arr_cull, t_float, c(cull)}); + op(w, kOpTypePointer, {p_out_cull, kStorageOutput, arr_cull}); + } + op(w, kOpVariable, {p_in_int, vertex_index, kStorageInput}); + op(w, kOpVariable, {p_pc, pc, kStoragePushConstant}); + op(w, kOpVariable, {p_out_v4, out_pos, kStorageOutput}); + if (clip) op(w, kOpVariable, {p_out_clip, out_clip, kStorageOutput}); + if (cull) op(w, kOpVariable, {p_out_cull, out_cull, kStorageOutput}); + for (const std::uint32_t loc : located) op(w, kOpVariable, {p_out_v4, out_at[loc], kStorageOutput}); + op(w, kOpFunction, {t_void, fn_main, 0 /* None */, t_fn}); + op(w, kOpLabel, {entry}); + w.insert(w.end(), body.begin(), body.end()); + w[3] = next; + return w; +} + +} // namespace leonida diff --git a/runtime/src/mesh_indirect_prepare.comp b/runtime/src/mesh_indirect_prepare.comp new file mode 100644 index 0000000000..753b530927 --- /dev/null +++ b/runtime/src/mesh_indirect_prepare.comp @@ -0,0 +1,61 @@ +// ExecuteIndirect(DISPATCH_MESH) without VK_EXT_mesh_shader (--mesh-compute): turn each GPU-written +// D3D12_DISPATCH_MESH_ARGUMENTS record (three uints) into the two indirect commands the fallback records, without +// reading the arguments on the CPU: +// dispatch[k]: a VkDispatchIndirectCommand for the mesh shader running as compute (one output slot per group), +// draw[k]: a VkDrawIndirectCommand for mesh_compute_vs.h, three vertices for every primitive a group may write. +// A record past the GPU count (when there is a count buffer), with an empty grid, or with more groups than its +// output region holds (capacity_groups), or whose vertex count does not fit in 32 bits, gets zero groups and zero +// vertices; the last two also set bit 0 of the status word so the host can report the dropped work. +#version 460 +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_shader_explicit_arithmetic_types_int64 : require +layout(local_size_x = 64) in; +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { + uint data[]; +}; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer WordsOut { + uint data[]; +}; +layout(push_constant) uniform Params { + WordsIn arguments; // the first record + WordsIn count; // the count word; ignored when has_count is 0 + WordsOut dispatch_out; // records * 3 words + WordsOut draw_out; // records * 4 words + WordsOut status; // one word, bit 0: some record was dropped + uint stride_words; + uint records; + uint capacity_groups; + uint max_primitives; + uint has_count; +} p; + +void main() { + const uint k = gl_GlobalInvocationID.x; + if (k >= p.records) return; + uint x = 0u, y = 0u, z = 0u, vertices = 0u; + if (p.has_count == 0u || k < p.count.data[0]) { + // The record's address in 64 bits: k * stride can pass 2^32 words with a large ByteStride (D3D12 allows + // any multiple of 4), where a 32-bit word index would wrap and read an earlier record. + WordsIn record = WordsIn(uint64_t(p.arguments) + uint64_t(k) * uint64_t(p.stride_words) * 4ul); + x = record.data[0]; + y = record.data[1]; + z = record.data[2]; + const uint64_t groups = uint64_t(x) * uint64_t(y) * uint64_t(z); + const uint64_t verts = groups * uint64_t(p.max_primitives) * 3ul; + if (groups == 0ul) { + x = y = z = 0u; + } else if (groups > uint64_t(p.capacity_groups) || verts > 0xFFFFFFFFul) { + x = y = z = 0u; + atomicOr(p.status.data[0], 1u); + } else { + vertices = uint(verts); + } + } + p.dispatch_out.data[k * 3u] = x; + p.dispatch_out.data[k * 3u + 1u] = y; + p.dispatch_out.data[k * 3u + 2u] = z; + p.draw_out.data[k * 4u] = vertices; + p.draw_out.data[k * 4u + 1u] = vertices != 0u ? 1u : 0u; + p.draw_out.data[k * 4u + 2u] = 0u; + p.draw_out.data[k * 4u + 3u] = 0u; +} diff --git a/runtime/src/mesh_indirect_prepare_spv.h b/runtime/src/mesh_indirect_prepare_spv.h new file mode 100644 index 0000000000..64669b6513 --- /dev/null +++ b/runtime/src/mesh_indirect_prepare_spv.h @@ -0,0 +1,134 @@ +// Generated with glslangValidator -V --target-env vulkan1.2 -Os --spirv-val mesh_indirect_prepare.comp +#pragma once +#include +namespace leonida { +inline constexpr std::uint32_t mesh_indirect_prepare_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x000000d4u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x0000000bu, 0x00020011u, 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, + 0x00000000u, 0x0003000eu, 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, + 0x00000000u, 0x0000000bu, 0x00000019u, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, + 0x00000001u, 0x00030003u, 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, + 0x65725f72u, 0x65726566u, 0x0065636eu, 0x000d0004u, 0x455f4c47u, 0x735f5458u, 0x65646168u, 0x78655f72u, + 0x63696c70u, 0x615f7469u, 0x68746972u, 0x6974656du, 0x79745f63u, 0x5f736570u, 0x36746e69u, 0x00000034u, + 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00080005u, 0x0000000bu, 0x475f6c67u, 0x61626f6cu, + 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x00000013u, 0x61726150u, 0x0000736du, + 0x00060006u, 0x00000013u, 0x00000000u, 0x75677261u, 0x746e656du, 0x00000073u, 0x00050006u, 0x00000013u, + 0x00000001u, 0x6e756f63u, 0x00000074u, 0x00070006u, 0x00000013u, 0x00000002u, 0x70736964u, 0x68637461u, + 0x74756f5fu, 0x00000000u, 0x00060006u, 0x00000013u, 0x00000003u, 0x77617264u, 0x74756f5fu, 0x00000000u, + 0x00050006u, 0x00000013u, 0x00000004u, 0x74617473u, 0x00007375u, 0x00070006u, 0x00000013u, 0x00000005u, + 0x69727473u, 0x775f6564u, 0x7364726fu, 0x00000000u, 0x00050006u, 0x00000013u, 0x00000006u, 0x6f636572u, + 0x00736472u, 0x00070006u, 0x00000013u, 0x00000007u, 0x61706163u, 0x79746963u, 0x6f72675fu, 0x00737075u, + 0x00070006u, 0x00000013u, 0x00000008u, 0x5f78616du, 0x6d697270u, 0x76697469u, 0x00007365u, 0x00060006u, + 0x00000013u, 0x00000009u, 0x5f736168u, 0x6e756f63u, 0x00000074u, 0x00040005u, 0x00000015u, 0x64726f57u, + 0x006e4973u, 0x00050006u, 0x00000015u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, 0x00000017u, + 0x64726f57u, 0x74754f73u, 0x00000000u, 0x00050006u, 0x00000017u, 0x00000000u, 0x61746164u, 0x00000000u, + 0x00030005u, 0x00000019u, 0x00000070u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, 0x00030047u, + 0x00000013u, 0x00000002u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, + 0x00000013u, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x00000013u, 0x00000002u, 0x00000023u, + 0x00000010u, 0x00050048u, 0x00000013u, 0x00000003u, 0x00000023u, 0x00000018u, 0x00050048u, 0x00000013u, + 0x00000004u, 0x00000023u, 0x00000020u, 0x00050048u, 0x00000013u, 0x00000005u, 0x00000023u, 0x00000028u, + 0x00050048u, 0x00000013u, 0x00000006u, 0x00000023u, 0x0000002cu, 0x00050048u, 0x00000013u, 0x00000007u, + 0x00000023u, 0x00000030u, 0x00050048u, 0x00000013u, 0x00000008u, 0x00000023u, 0x00000034u, 0x00050048u, + 0x00000013u, 0x00000009u, 0x00000023u, 0x00000038u, 0x00040047u, 0x00000014u, 0x00000006u, 0x00000004u, + 0x00030047u, 0x00000015u, 0x00000002u, 0x00040048u, 0x00000015u, 0x00000000u, 0x00000018u, 0x00050048u, + 0x00000015u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000016u, 0x00000006u, 0x00000004u, + 0x00030047u, 0x00000017u, 0x00000002u, 0x00050048u, 0x00000017u, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00040047u, 0x000000bau, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, + 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, + 0x00000003u, 0x00040020u, 0x0000000au, 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, + 0x00000001u, 0x0004002bu, 0x00000006u, 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, + 0x00000006u, 0x00030027u, 0x00000011u, 0x000014e5u, 0x00030027u, 0x00000012u, 0x000014e5u, 0x000c001eu, + 0x00000013u, 0x00000011u, 0x00000011u, 0x00000012u, 0x00000012u, 0x00000012u, 0x00000006u, 0x00000006u, + 0x00000006u, 0x00000006u, 0x00000006u, 0x0003001du, 0x00000014u, 0x00000006u, 0x0003001eu, 0x00000015u, + 0x00000014u, 0x00040020u, 0x00000011u, 0x000014e5u, 0x00000015u, 0x0003001du, 0x00000016u, 0x00000006u, + 0x0003001eu, 0x00000017u, 0x00000016u, 0x00040020u, 0x00000012u, 0x000014e5u, 0x00000017u, 0x00040020u, + 0x00000018u, 0x00000009u, 0x00000013u, 0x0004003bu, 0x00000018u, 0x00000019u, 0x00000009u, 0x00040015u, + 0x0000001au, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000001au, 0x0000001bu, 0x00000006u, 0x00040020u, + 0x0000001cu, 0x00000009u, 0x00000006u, 0x00020014u, 0x0000001fu, 0x0004002bu, 0x0000001au, 0x00000028u, + 0x00000009u, 0x0004002bu, 0x0000001au, 0x00000030u, 0x00000001u, 0x00040020u, 0x00000031u, 0x00000009u, + 0x00000011u, 0x0004002bu, 0x0000001au, 0x00000034u, 0x00000000u, 0x00040020u, 0x00000035u, 0x000014e5u, + 0x00000006u, 0x00040015u, 0x00000040u, 0x00000040u, 0x00000000u, 0x0004002bu, 0x0000001au, 0x00000044u, + 0x00000005u, 0x0005002bu, 0x00000040u, 0x00000049u, 0x00000004u, 0x00000000u, 0x0004002bu, 0x0000001au, + 0x00000054u, 0x00000002u, 0x0004002bu, 0x0000001au, 0x00000063u, 0x00000008u, 0x0005002bu, 0x00000040u, + 0x00000068u, 0x00000003u, 0x00000000u, 0x0005002bu, 0x00000040u, 0x0000006bu, 0x00000000u, 0x00000000u, + 0x0004002bu, 0x0000001au, 0x00000071u, 0x00000007u, 0x0005002bu, 0x00000040u, 0x00000077u, 0xffffffffu, + 0x00000000u, 0x0004002bu, 0x0000001au, 0x0000007cu, 0x00000004u, 0x00040020u, 0x0000007du, 0x00000009u, + 0x00000012u, 0x0004002bu, 0x00000006u, 0x00000081u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000089u, + 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000098u, 0x00000002u, 0x0004002bu, 0x0000001au, 0x0000009cu, + 0x00000003u, 0x0004002bu, 0x00000006u, 0x000000a0u, 0x00000004u, 0x0004002bu, 0x00000006u, 0x000000b9u, + 0x00000040u, 0x0006002cu, 0x00000009u, 0x000000bau, 0x000000b9u, 0x00000081u, 0x00000081u, 0x00050036u, + 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x000000bbu, + 0x00000000u, 0x000300fbu, 0x0000000cu, 0x000000bcu, 0x000200f8u, 0x000000bcu, 0x00050041u, 0x0000000du, + 0x0000000eu, 0x0000000bu, 0x0000000cu, 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, + 0x0000001cu, 0x0000001du, 0x00000019u, 0x0000001bu, 0x0004003du, 0x00000006u, 0x0000001eu, 0x0000001du, + 0x000500aeu, 0x0000001fu, 0x00000020u, 0x0000000fu, 0x0000001eu, 0x000300f7u, 0x00000022u, 0x00000000u, + 0x000400fau, 0x00000020u, 0x00000021u, 0x00000022u, 0x000200f8u, 0x00000021u, 0x000200f9u, 0x000000bbu, + 0x000200f8u, 0x00000022u, 0x00050041u, 0x0000001cu, 0x00000029u, 0x00000019u, 0x00000028u, 0x0004003du, + 0x00000006u, 0x0000002au, 0x00000029u, 0x000500aau, 0x0000001fu, 0x0000002bu, 0x0000002au, 0x0000000cu, + 0x000400a8u, 0x0000001fu, 0x0000002cu, 0x0000002bu, 0x000300f7u, 0x0000002eu, 0x00000000u, 0x000400fau, + 0x0000002cu, 0x0000002du, 0x0000002eu, 0x000200f8u, 0x0000002du, 0x00050041u, 0x00000031u, 0x00000032u, + 0x00000019u, 0x00000030u, 0x0004003du, 0x00000011u, 0x00000033u, 0x00000032u, 0x00060041u, 0x00000035u, + 0x00000036u, 0x00000033u, 0x00000034u, 0x00000034u, 0x0006003du, 0x00000006u, 0x00000037u, 0x00000036u, + 0x00000002u, 0x00000004u, 0x000500b0u, 0x0000001fu, 0x00000038u, 0x0000000fu, 0x00000037u, 0x000200f9u, + 0x0000002eu, 0x000200f8u, 0x0000002eu, 0x000700f5u, 0x0000001fu, 0x00000039u, 0x0000002bu, 0x00000022u, + 0x00000038u, 0x0000002du, 0x000300f7u, 0x0000003bu, 0x00000000u, 0x000400fau, 0x00000039u, 0x0000003au, + 0x0000003bu, 0x000200f8u, 0x0000003au, 0x00050041u, 0x00000031u, 0x0000003eu, 0x00000019u, 0x00000034u, + 0x0004003du, 0x00000011u, 0x0000003fu, 0x0000003eu, 0x00040075u, 0x00000040u, 0x00000041u, 0x0000003fu, + 0x00040071u, 0x00000040u, 0x00000043u, 0x0000000fu, 0x00050041u, 0x0000001cu, 0x00000045u, 0x00000019u, + 0x00000044u, 0x0004003du, 0x00000006u, 0x00000046u, 0x00000045u, 0x00040071u, 0x00000040u, 0x00000047u, + 0x00000046u, 0x00050084u, 0x00000040u, 0x00000048u, 0x00000043u, 0x00000047u, 0x00050084u, 0x00000040u, + 0x0000004au, 0x00000048u, 0x00000049u, 0x00050080u, 0x00000040u, 0x0000004bu, 0x00000041u, 0x0000004au, + 0x00040078u, 0x00000011u, 0x0000004cu, 0x0000004bu, 0x00060041u, 0x00000035u, 0x0000004eu, 0x0000004cu, + 0x00000034u, 0x00000034u, 0x0006003du, 0x00000006u, 0x0000004fu, 0x0000004eu, 0x00000002u, 0x00000004u, + 0x00060041u, 0x00000035u, 0x00000051u, 0x0000004cu, 0x00000034u, 0x00000030u, 0x0006003du, 0x00000006u, + 0x00000052u, 0x00000051u, 0x00000002u, 0x00000004u, 0x00060041u, 0x00000035u, 0x00000055u, 0x0000004cu, + 0x00000034u, 0x00000054u, 0x0006003du, 0x00000006u, 0x00000056u, 0x00000055u, 0x00000002u, 0x00000004u, + 0x00040071u, 0x00000040u, 0x0000005au, 0x0000004fu, 0x00040071u, 0x00000040u, 0x0000005cu, 0x00000052u, + 0x00050084u, 0x00000040u, 0x0000005du, 0x0000005au, 0x0000005cu, 0x00040071u, 0x00000040u, 0x0000005fu, + 0x00000056u, 0x00050084u, 0x00000040u, 0x00000060u, 0x0000005du, 0x0000005fu, 0x00050041u, 0x0000001cu, + 0x00000064u, 0x00000019u, 0x00000063u, 0x0004003du, 0x00000006u, 0x00000065u, 0x00000064u, 0x00040071u, + 0x00000040u, 0x00000066u, 0x00000065u, 0x00050084u, 0x00000040u, 0x00000067u, 0x00000060u, 0x00000066u, + 0x00050084u, 0x00000040u, 0x00000069u, 0x00000067u, 0x00000068u, 0x000500aau, 0x0000001fu, 0x0000006cu, + 0x00000060u, 0x0000006bu, 0x000300f7u, 0x0000006eu, 0x00000000u, 0x000400fau, 0x0000006cu, 0x0000006du, + 0x0000006fu, 0x000200f8u, 0x0000006du, 0x000200f9u, 0x0000006eu, 0x000200f8u, 0x0000006fu, 0x00050041u, + 0x0000001cu, 0x00000072u, 0x00000019u, 0x00000071u, 0x0004003du, 0x00000006u, 0x00000073u, 0x00000072u, + 0x00040071u, 0x00000040u, 0x00000074u, 0x00000073u, 0x000500acu, 0x0000001fu, 0x00000075u, 0x00000060u, + 0x00000074u, 0x000500acu, 0x0000001fu, 0x00000078u, 0x00000069u, 0x00000077u, 0x000500a6u, 0x0000001fu, + 0x00000079u, 0x00000075u, 0x00000078u, 0x000300f7u, 0x0000007bu, 0x00000000u, 0x000400fau, 0x00000079u, + 0x0000007au, 0x00000083u, 0x000200f8u, 0x0000007au, 0x00050041u, 0x0000007du, 0x0000007eu, 0x00000019u, + 0x0000007cu, 0x0004003du, 0x00000012u, 0x0000007fu, 0x0000007eu, 0x00060041u, 0x00000035u, 0x00000080u, + 0x0000007fu, 0x00000034u, 0x00000034u, 0x000700f1u, 0x00000006u, 0x00000082u, 0x00000080u, 0x00000081u, + 0x0000000cu, 0x00000081u, 0x000200f9u, 0x0000007bu, 0x000200f8u, 0x00000083u, 0x00040071u, 0x00000006u, + 0x00000085u, 0x00000069u, 0x000200f9u, 0x0000007bu, 0x000200f8u, 0x0000007bu, 0x000700f5u, 0x00000006u, + 0x000000d0u, 0x0000000cu, 0x0000007au, 0x00000085u, 0x00000083u, 0x000600a9u, 0x00000006u, 0x000000d1u, + 0x00000079u, 0x0000000cu, 0x00000056u, 0x000600a9u, 0x00000006u, 0x000000d2u, 0x00000079u, 0x0000000cu, + 0x00000052u, 0x000600a9u, 0x00000006u, 0x000000d3u, 0x00000079u, 0x0000000cu, 0x0000004fu, 0x000200f9u, + 0x0000006eu, 0x000200f8u, 0x0000006eu, 0x000700f5u, 0x00000006u, 0x000000cfu, 0x0000000cu, 0x0000006du, + 0x000000d0u, 0x0000007bu, 0x000700f5u, 0x00000006u, 0x000000cbu, 0x0000000cu, 0x0000006du, 0x000000d1u, + 0x0000007bu, 0x000700f5u, 0x00000006u, 0x000000c7u, 0x0000000cu, 0x0000006du, 0x000000d2u, 0x0000007bu, + 0x000700f5u, 0x00000006u, 0x000000c3u, 0x0000000cu, 0x0000006du, 0x000000d3u, 0x0000007bu, 0x000200f9u, + 0x0000003bu, 0x000200f8u, 0x0000003bu, 0x000700f5u, 0x00000006u, 0x000000cdu, 0x0000000cu, 0x0000002eu, + 0x000000cfu, 0x0000006eu, 0x000700f5u, 0x00000006u, 0x000000c9u, 0x0000000cu, 0x0000002eu, 0x000000cbu, + 0x0000006eu, 0x000700f5u, 0x00000006u, 0x000000c5u, 0x0000000cu, 0x0000002eu, 0x000000c7u, 0x0000006eu, + 0x000700f5u, 0x00000006u, 0x000000c1u, 0x0000000cu, 0x0000002eu, 0x000000c3u, 0x0000006eu, 0x00050041u, + 0x0000007du, 0x00000086u, 0x00000019u, 0x00000054u, 0x0004003du, 0x00000012u, 0x00000087u, 0x00000086u, + 0x00050084u, 0x00000006u, 0x0000008au, 0x0000000fu, 0x00000089u, 0x00060041u, 0x00000035u, 0x0000008cu, + 0x00000087u, 0x00000034u, 0x0000008au, 0x0005003eu, 0x0000008cu, 0x000000c1u, 0x00000002u, 0x00000004u, + 0x00050080u, 0x00000006u, 0x00000091u, 0x0000008au, 0x00000081u, 0x00060041u, 0x00000035u, 0x00000093u, + 0x00000087u, 0x00000034u, 0x00000091u, 0x0005003eu, 0x00000093u, 0x000000c5u, 0x00000002u, 0x00000004u, + 0x00050080u, 0x00000006u, 0x00000099u, 0x0000008au, 0x00000098u, 0x00060041u, 0x00000035u, 0x0000009bu, + 0x00000087u, 0x00000034u, 0x00000099u, 0x0005003eu, 0x0000009bu, 0x000000c9u, 0x00000002u, 0x00000004u, + 0x00050041u, 0x0000007du, 0x0000009du, 0x00000019u, 0x0000009cu, 0x0004003du, 0x00000012u, 0x0000009eu, + 0x0000009du, 0x00050084u, 0x00000006u, 0x000000a1u, 0x0000000fu, 0x000000a0u, 0x00060041u, 0x00000035u, + 0x000000a3u, 0x0000009eu, 0x00000034u, 0x000000a1u, 0x0005003eu, 0x000000a3u, 0x000000cdu, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x000000a8u, 0x000000a1u, 0x00000081u, 0x000500abu, 0x0000001fu, + 0x000000aau, 0x000000cdu, 0x0000000cu, 0x000600a9u, 0x00000006u, 0x000000abu, 0x000000aau, 0x00000081u, + 0x0000000cu, 0x00060041u, 0x00000035u, 0x000000acu, 0x0000009eu, 0x00000034u, 0x000000a8u, 0x0005003eu, + 0x000000acu, 0x000000abu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x000000b1u, 0x000000a1u, + 0x00000098u, 0x00060041u, 0x00000035u, 0x000000b2u, 0x0000009eu, 0x00000034u, 0x000000b1u, 0x0005003eu, + 0x000000b2u, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x000000b7u, 0x000000a1u, + 0x00000089u, 0x00060041u, 0x00000035u, 0x000000b8u, 0x0000009eu, 0x00000034u, 0x000000b7u, 0x0005003eu, + 0x000000b8u, 0x0000000cu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000bbu, 0x000200f8u, 0x000000bbu, + 0x000100fdu, 0x00010038u, +}; +} // namespace leonida diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 4cc35d58a7..c31e87369a 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -685,6 +686,28 @@ struct SignatureElement { std::string component_type; // "float", "uint", "sint" }; +// A `--mesh-compute` mesh shader's output slot (index.json "mesh_compute", rdna2spirv.mesh_compute_layout): the +// compute shader writes one slot per workgroup, the vertex shader mesh_compute_vs.h builds draws them. Byte offsets. +struct MeshComputeLayout { + std::uint32_t slot_bytes = 0; + std::uint32_t vertices = 0; // the first vertex, after the header (vertex count, primitive count) + std::uint32_t vertex_stride = 0; + std::uint32_t primitives = 0; // the first primitive: three vertex indices, then 1 if culled + std::uint32_t primitive_stride = 0; + std::uint32_t max_vertices = 0; + std::uint32_t max_primitives = 0; + std::uint32_t clip_count = 0; // distances, at clip_offset / cull_offset in each vertex + std::uint32_t clip_offset = 0; + std::uint32_t cull_count = 0; + std::uint32_t cull_offset = 0; + std::map params; // output location -> vec4 offset in each vertex + // --f16-interp-fallback: param location -> {low_half_location, high_half_location} the halves go out at. + std::map> f16_halves; + std::uint32_t push_constant_bytes = 0; // 152: the output address in dwords 36..37 + // Under --pc-tail-ubo the address is in the uniform tail block instead, which mesh_compute_vs.h does not read. + bool address_in_pc_tail = false; +}; + struct ShaderEntry { std::string name; std::string stage; // "vs", "ps", "cs", "ms", "gs" @@ -714,6 +737,12 @@ 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; + // A mesh shader translated with --mesh-compute: a compute module writing this slot layout (unset otherwise). + std::optional mesh_compute; }; class ShaderLibrary { @@ -746,6 +775,16 @@ class ShaderLibrary { // Entries loaded from /fspx/index.json. A corpus of RPF containers never reaches these: their programs // come from FidelityFX DLLs, so callers comparing reached entries with size() must leave them out. std::size_t fspx_size() const { return fspx_count_; } + // Mesh-shader entries translated with --mesh-compute (a "mesh_compute" layout). + std::size_t mesh_compute_count() const { return mesh_compute_count_; } + // Whether `ok` holds for every such entry (true when there are none). + template + bool all_mesh_compute(Predicate&& ok) const { + for (const auto& [key, list] : entries_) + for (const ShaderEntry& e : list) + if (e.stage == "ms" && e.mesh_compute && !ok(e)) return false; + return true; + } // The first entry for this program. Two containers can hold the same FSSM program with different input // signatures; `candidates` returns all of them. @@ -811,6 +850,41 @@ class ShaderLibrary { return n >= 0 && n <= 4294967295.0 ? std::uint32_t(n) : 0; } + // An index entry's "mesh_compute" object. Keys of "params" and "f16_halves" are decimal locations; entries + // that are not are skipped, as for the entry's own f16_halves. + static MeshComputeLayout mesh_compute_layout(const Json& m) { + MeshComputeLayout l; + l.slot_bytes = u32(m.find("slot_bytes")); + l.vertices = u32(m.find("vertices")); + l.vertex_stride = u32(m.find("vertex_stride")); + l.primitives = u32(m.find("primitives")); + l.primitive_stride = u32(m.find("primitive_stride")); + l.max_vertices = u32(m.find("max_vertices")); + l.max_primitives = u32(m.find("max_primitives")); + l.clip_count = u32(m.find("clip_count")); + l.clip_offset = u32(m.find("clip_offset")); + l.cull_count = u32(m.find("cull_count")); + l.cull_offset = u32(m.find("cull_offset")); + l.push_constant_bytes = u32(m.find("push_constant_bytes")); + if (const Json* t = m.find("pc_tail_address_dwords"); t && t->kind == Json::Kind::array) + l.address_in_pc_tail = true; + const auto location = [](const std::string& key, std::uint32_t& out) { + char* end = nullptr; + const unsigned long n = std::strtoul(key.c_str(), &end, 10); + if (key.empty() || !end || *end != '\0') return false; + out = std::uint32_t(n); + return true; + }; + if (const Json* p = m.find("params"); p && p->kind == Json::Kind::object) + for (const auto& [key, val] : p->object) + if (std::uint32_t loc; location(key, loc)) l.params[loc] = u32(&val); + if (const Json* h = m.find("f16_halves"); h && h->kind == Json::Kind::object) + for (const auto& [key, val] : h->object) + if (std::uint32_t loc; location(key, loc) && val.kind == Json::Kind::array && val.array.size() == 2) + l.f16_halves[loc] = {u32(&val.array[0]), u32(&val.array[1])}; + return l; + } + using LookupKey = std::pair; struct KeyLess { using is_transparent = void; @@ -848,6 +922,7 @@ class ShaderLibrary { fspx_entries_.clear(); count_ = 0; fspx_count_ = 0; + mesh_compute_count_ = 0; } for (const auto& [name, meta] : root.object) { const Json* hash = meta.find("fssm_sha256"); @@ -907,6 +982,12 @@ 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 (const Json* m = meta.find("mesh_compute"); m && m->kind == Json::Kind::object) { + e.mesh_compute = mesh_compute_layout(*m); + if (e.stage == "ms") ++mesh_compute_count_; + } 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_; @@ -918,6 +999,7 @@ class ShaderLibrary { std::filesystem::path dir_; std::size_t count_ = 0; std::size_t fspx_count_ = 0; + std::size_t mesh_compute_count_ = 0; // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. Entries entries_; Entries fspx_entries_; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index dc042bf73f..d54dfa834d 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -95,17 +95,18 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 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(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 - // 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,9 @@ 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_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); @@ -1093,6 +1097,9 @@ class VulkanContext { const VkPhysicalDeviceLimits& limits) { std::unique_lock lock(resource_mutex_); counted_dispatch_ = std::make_unique(get, device_, memory, limits); + // The ExecuteIndirect(DISPATCH_MESH) prepass for --mesh-compute PSOs: the same requirement, and it builds + // its pipeline on first use, so devices with VK_EXT_mesh_shader never create it. + mesh_indirect_ = std::make_unique(get, device_, memory); } VkDevice device() const { return device_; } @@ -1223,6 +1230,16 @@ 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, 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; + replay_.draw_mesh_tasks_indirect_count = nullptr; + } + } + void set_heap_base(std::uint64_t heap_base) { std::unique_lock lock(resource_mutex_); replay_.heap_base = heap_base; @@ -1373,10 +1390,13 @@ class VulkanContext { } // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from - // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { + // `allocate`. Without this such a copy is refused as unsupported. With `device_address` (the allocation must then + // carry VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT) the same scratch also takes the output of --mesh-compute mesh + // shaders, by address. + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + bool device_address = false) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), device_address); if (!scratch_->loaded()) scratch_.reset(); } @@ -1674,6 +1694,7 @@ class VulkanContext { std::unique_ptr predicate_reducer_; std::unique_ptr predicated_copier_; std::unique_ptr counted_dispatch_; + std::unique_ptr mesh_indirect_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; DebugLabelFunctions labels_; @@ -2204,6 +2225,7 @@ class VulkanQueue : private QueueHolds::Holder { std::unique_ptr batch; std::unique_ptr copy_batch; std::unique_ptr counted_batch; + std::unique_ptr mesh_indirect_batch; if (captures) { if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) return ReplayResult::unsupported; @@ -2240,6 +2262,14 @@ class VulkanQueue : private QueueHolds::Holder { } return context_.scratch_->get(bytes, buffer, offset); }; + replay.mesh_output = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkDeviceAddress& address) { + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!scratch_guard.active) { + context_.scratch_->collect(); + scratch_guard.active = true; + } + return context_.scratch_->get_address(bytes, address); + }; } if (kind_ != QueueKind::copy && context_.counted_dispatch_) { replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( @@ -2254,6 +2284,21 @@ class VulkanQueue : private QueueHolds::Holder { context_.counted_dispatch_->emit(cb, job); }; } + if (kind_ == QueueKind::direct && context_.mesh_indirect_) { + replay.prepare_mesh_indirect = [this, &tracker_lock, &mesh_indirect_batch]( + VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, + std::uint32_t stride, std::uint32_t records, std::uint32_t capacity, std::uint32_t max_primitives, + VkDeviceAddress output, VkDeviceSize region_bytes, MeshIndirect& out) { + // As the counted dispatch: lazy pipeline creation shared across queues, serialized here. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!mesh_indirect_batch) mesh_indirect_batch = context_.mesh_indirect_->batch(); + return mesh_indirect_batch->prepare(args, args_offset, count, count_offset, stride, records, capacity, + max_primitives, output, region_bytes, out); + }; + replay.emit_mesh_indirect = [this](VkCommandBuffer cb, const MeshIndirect& job) { + context_.mesh_indirect_->emit(cb, job); + }; + } if (context_.depth24_ && !transfer_only) { replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, std::vector& parts) { @@ -2519,6 +2564,7 @@ class VulkanQueue : private QueueHolds::Holder { slot->predicate = std::move(batch); slot->predicated_copy = std::move(copy_batch); slot->counted_dispatch = std::move(counted_batch); + slot->mesh_indirect = std::move(mesh_indirect_batch); queries.commit(); slot->segments = std::move(queries.retained); } else { @@ -2752,6 +2798,7 @@ class VulkanQueue : private QueueHolds::Holder { std::vector events; // order_timestamp_copy's, reset and reused once the slot completes std::unique_ptr predicated_copy; std::unique_ptr counted_dispatch; + std::unique_ptr mesh_indirect; // logs dropped records when the slot completes std::unique_ptr predicate; // retained until this slot completes std::vector khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime }; @@ -2972,6 +3019,7 @@ class VulkanQueue : private QueueHolds::Holder { reuse->predicate.reset(); reuse->predicated_copy.reset(); reuse->counted_dispatch.reset(); + reuse->mesh_indirect.reset(); reuse->ticket = UINT64_MAX; // in use until submitted return reuse; } diff --git a/runtime/src/vulkan_mesh_indirect.h b/runtime/src/vulkan_mesh_indirect.h new file mode 100644 index 0000000000..70c271252d --- /dev/null +++ b/runtime/src/vulkan_mesh_indirect.h @@ -0,0 +1,272 @@ +// ExecuteIndirect(DISPATCH_MESH) without VK_EXT_mesh_shader, for --mesh-compute PSOs. +// The direct path (DispatchMesh) knows the group counts on the CPU: it dispatches the mesh shader as compute, one +// output slot per workgroup, then draws groups * max_primitives * 3 vertices with mesh_compute_vs.h. Here the counts +// are GPU data, so a prepass (mesh_indirect_prepare.comp) turns each record into a VkDispatchIndirectCommand and a +// VkDrawIndirectCommand in a private buffer, and the replay issues one indirect dispatch and one indirect draw per +// record, each record writing its own region of output slots. A region holds capacity_groups slots, fixed when the +// call is prepared; a record with more groups is dropped (zero groups, zero vertices) and the batch logs it when +// its submission retires, instead of writing past the region. +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include +#include +#include +#include +#include "mesh_indirect_prepare_spv.h" + +namespace leonida { + +// The output slots of one ExecuteIndirect call: records * capacity_groups * slot_bytes bytes at most. A budget, not +// a measurement: 64 MiB keeps a call with a few hundred records at a useful capacity without holding a large share +// of a small GPU's memory. +inline constexpr VkDeviceSize mesh_indirect_budget = VkDeviceSize(64) << 20; +// D3D12 caps a DispatchMesh grid at 2^22 thread groups in all. +inline constexpr std::uint32_t mesh_indirect_max_groups = 1u << 22; + +// Groups each record's region holds, or 0 when not even one slot per record fits the budget. +inline std::uint32_t mesh_indirect_capacity(std::uint32_t records, std::uint32_t slot_bytes, + VkDeviceSize budget = mesh_indirect_budget) { + if (!records || !slot_bytes) return 0; + const VkDeviceSize per_record = budget / records / slot_bytes; + return std::uint32_t(std::min(per_record, mesh_indirect_max_groups)); +} + +struct MeshIndirect { + VkBuffer commands = VK_NULL_HANDLE; // records VkDispatchIndirectCommands, then records VkDrawIndirectCommands + VkDeviceSize draw_offset = 0; // where the draw commands start in `commands` + VkDeviceAddress arguments = 0, count = 0, dispatch_out = 0, draw_out = 0, status = 0; + std::uint32_t stride = 0, records = 0, capacity_groups = 0, max_primitives = 0; + bool has_count = false; + VkDeviceAddress output = 0; // record k's slots start at output + k * region_bytes + VkDeviceSize region_bytes = 0; // capacity_groups * slot_bytes +}; + +class MeshIndirectPreparer { +public: + MeshIndirectPreparer(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory) + : get_(get), device_(device), memory_(memory) {} + ~MeshIndirectPreparer() { + if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); + if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + } + MeshIndirectPreparer(const MeshIndirectPreparer&) = delete; + MeshIndirectPreparer& operator=(const MeshIndirectPreparer&) = delete; + + // Retained by the command-buffer slot until its submission's timeline ticket completes; then it reads the status + // words its prepasses wrote and logs dropped records once per batch. + struct Batch { + MeshIndirectPreparer& owner; + struct Allocation { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + const std::uint32_t* status = nullptr; // mapped, for the status allocation only + }; + std::vector allocations; + explicit Batch(MeshIndirectPreparer& value) : owner(value) {} + ~Batch() { + bool dropped = false; + for (auto& a : allocations) { + if (a.status && (*a.status & 1u)) dropped = true; + if (a.status) owner.fn("vkUnmapMemory")(owner.device_, a.memory); + if (a.buffer) owner.fn("vkDestroyBuffer")(owner.device_, a.buffer, nullptr); + if (a.memory) owner.fn("vkFreeMemory")(owner.device_, a.memory, nullptr); + } + if (dropped) + std::fprintf(stderr, "[rt] d3d12: ExecuteIndirect(DISPATCH_MESH) through --mesh-compute dropped records " + "with more thread groups than their output region holds\n"); + } + Batch(const Batch&) = delete; + Batch& operator=(const Batch&) = delete; + + // count == VK_NULL_HANDLE: no count buffer. `output` and `region_bytes` are the caller's (the replay's mesh + // output scratch); this allocates the command and status buffers. + bool prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, VkDeviceSize count_offset, + std::uint32_t stride, std::uint32_t records, std::uint32_t capacity_groups, + std::uint32_t max_primitives, VkDeviceAddress output, VkDeviceSize region_bytes, + MeshIndirect& out) { + out = {}; + if (!arguments || !stride || stride % 4 || !records || !capacity_groups || !max_primitives || !output || + !owner.make_pipeline()) + return false; + constexpr VkDeviceSize dispatch_bytes = 3 * sizeof(std::uint32_t), draw_bytes = 4 * sizeof(std::uint32_t); + if (VkDeviceSize(records) > std::numeric_limits::max() / (dispatch_bytes + draw_bytes)) + return false; + // The draw commands start 16-byte aligned after the dispatch commands. + const VkDeviceSize draw_offset = (VkDeviceSize(records) * dispatch_bytes + 15) & ~VkDeviceSize(15); + const VkDeviceSize bytes = draw_offset + VkDeviceSize(records) * draw_bytes; + Allocation* commands = allocate(bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, false); + if (!commands) return false; + const VkBuffer command_buffer = commands->buffer; + Allocation* status = allocate(sizeof(std::uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + true); + if (!status) return false; + const VkBuffer status_buffer = status->buffer; + const auto address = owner.fn("vkGetBufferDeviceAddress"); + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = arguments; + const VkDeviceAddress args_va = address(owner.device_, &info); + VkDeviceAddress count_va = 0; + if (count) { + info.buffer = count; + count_va = address(owner.device_, &info); + if (!count_va || count_offset > UINT64_MAX - count_va) return false; + } + info.buffer = command_buffer; + const VkDeviceAddress commands_va = address(owner.device_, &info); + info.buffer = status_buffer; + const VkDeviceAddress status_va = address(owner.device_, &info); + if (!args_va || !commands_va || !status_va || argument_offset > UINT64_MAX - args_va) return false; + out.commands = command_buffer; + out.draw_offset = draw_offset; + out.arguments = args_va + argument_offset; + out.count = count ? count_va + count_offset : 0; + out.dispatch_out = commands_va; + out.draw_out = commands_va + draw_offset; + out.status = status_va; + out.stride = stride; + out.records = records; + out.capacity_groups = capacity_groups; + out.max_primitives = max_primitives; + out.has_count = count != VK_NULL_HANDLE; + out.output = output; + out.region_bytes = region_bytes; + return true; + } + + private: + // A buffer with its own memory, pushed to `allocations` before anything can fail so the batch frees it. + Allocation* allocate(VkDeviceSize bytes, VkBufferUsageFlags usage, VkMemoryPropertyFlags wanted, bool map) { + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = bytes; + info.usage = usage; + Allocation a{}; + if (owner.fn("vkCreateBuffer")(owner.device_, &info, nullptr, &a.buffer) != VK_SUCCESS) + return nullptr; + allocations.push_back(a); + Allocation& slot = allocations.back(); + VkMemoryRequirements requirements{}; + owner.fn("vkGetBufferMemoryRequirements")(owner.device_, slot.buffer, + &requirements); + std::uint32_t memory_type = UINT32_MAX; + for (std::uint32_t i = 0; i < owner.memory_.memoryTypeCount; ++i) { + if (!(requirements.memoryTypeBits & (1u << i))) continue; + const VkMemoryPropertyFlags flags = owner.memory_.memoryTypes[i].propertyFlags; + if ((flags & wanted) == wanted) { + memory_type = i; + break; + } + // Device-local is a preference for the commands; host visibility is a requirement for the status. + if (!map && memory_type == UINT32_MAX) memory_type = i; + } + if (memory_type == UINT32_MAX) return nullptr; + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = memory_type; + if (owner.fn("vkAllocateMemory")(owner.device_, &allocation, nullptr, &slot.memory) != + VK_SUCCESS || + owner.fn("vkBindBufferMemory")(owner.device_, slot.buffer, slot.memory, 0) != + VK_SUCCESS) + return nullptr; + if (map) { + void* mapped = nullptr; + if (owner.fn("vkMapMemory")(owner.device_, slot.memory, 0, VK_WHOLE_SIZE, 0, + &mapped) != VK_SUCCESS) + return nullptr; + *static_cast(mapped) = 0; // host-coherent: visible to the prepass's atomicOr + slot.status = static_cast(mapped); + } + return &slot; + } + }; + + std::unique_ptr batch() { return std::make_unique(*this); } + + // The prepass, outside any rendering scope: reads the records (and the count) after earlier writes, writes the + // indirect commands, and makes them visible to the indirect dispatches and draws that follow. + void emit(VkCommandBuffer cb, const MeshIndirect& job) const { + const auto barrier = fn("vkCmdPipelineBarrier"); + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, + 0, nullptr); + fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + const Push push{job.arguments, job.count, job.dispatch_out, job.draw_out, job.status, + job.stride / 4, job.records, job.capacity_groups, job.max_primitives, + job.has_count ? 1u : 0u}; + fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), + &push); + fn("vkCmdDispatch")(cb, (job.records + 63u) / 64u, 1, 1); + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, 0, 1, &after, 0, + nullptr, 0, nullptr); + } + +private: + struct Push { + VkDeviceAddress arguments, count, dispatch_out, draw_out, status; + std::uint32_t stride_words, records, capacity_groups, max_primitives, has_count; + }; + static_assert(sizeof(Push) == 60 || sizeof(Push) == 64); + + template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + bool make_pipeline() { + if (pipeline_) return true; + for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", + "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkMapMemory", "vkUnmapMemory", + "vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout", + "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", "vkCmdPipelineBarrier", + "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkShaderModule module = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = sizeof(mesh_indirect_prepare_spirv); + shader.pCode = mesh_indirect_prepare_spirv; + bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, std::uint32_t(sizeof(Push))}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == + VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, + nullptr, &pipeline) == VK_SUCCESS; + if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + return false; + } + layout_ = layout; + pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceMemoryProperties memory_; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; +}; +} // namespace leonida diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 49efd399df..816f131e31 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -38,6 +38,7 @@ #include "vulkan_predicate.h" #include "vulkan_predicated_copy.h" #include "vulkan_indirect_dispatch_count.h" +#include "vulkan_mesh_indirect.h" #include #include @@ -758,12 +759,23 @@ 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. static constexpr std::uint32_t unbound_depth = 1u << 8; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + // A mesh PSO on a device without VK_EXT_mesh_shader (`--mesh-compute`): `mesh` is still set (DispatchMesh draws + // it), the mesh shader runs as this compute pipeline writing one output slot per workgroup, and `pipeline`, + // whose vertex shader is mesh_compute_vs.h's, draws the slots. Both take MeshComputeUserData. Null otherwise. + struct MeshCompute { + VkPipeline pipeline = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of `layout`; null: none + std::uint32_t slot_bytes = 0; + std::uint32_t max_primitives = 0; + } mesh_compute; }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -774,6 +786,13 @@ struct ShaderUserData { }; static_assert(sizeof(ShaderUserData) == 144); +// --mesh-compute modules and their vertex shader add the output buffer's address (dwords 36..37): 152 bytes. +struct MeshComputeUserData { + ShaderUserData user; + std::uint64_t output; +}; +static_assert(sizeof(MeshComputeUserData) == 152); + // A host read of a small CPU-written input either succeeds, names no VA, or names GPU-written memory. The last is a // capability limit, not bad contents: DEFAULT and READBACK bytes may still be stale while replay prepares a command. enum class HostReadStatus { ok, absent, not_cpu_written }; @@ -788,6 +807,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 +863,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 @@ -883,6 +904,20 @@ struct ReplayFunctions { std::function prepare_counted_dispatch; std::function emit_counted_dispatch; + // A DISPATCH_MESH signature on a --mesh-compute PSO (no VK_EXT_mesh_shader): the prepass that turns each record + // into an indirect dispatch and an indirect draw (vulkan_mesh_indirect.h). Arguments: the argument buffer and + // offset, the count buffer (null: none) and offset, stride, records, capacity_groups, max_primitives, the slots' + // address and region bytes. Its buffers are owned by the queue's timeline-retained batch. + std::function prepare_mesh_indirect; + std::function emit_mesh_indirect; + // 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. + std::uint32_t max_draw_indirect_count = UINT32_MAX; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan @@ -924,6 +959,9 @@ struct ReplayFunctions { // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour // copies go through it, image to buffer to image. Without it such a copy is unsupported. std::function copy_scratch; + // `bytes` of the same scratch by device address: a --mesh-compute mesh draw's output slots + // (GraphicsPipeline::mesh_compute). Without it such a draw is unsupported. + std::function mesh_output; // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. std::function query_pool; bool separate_depth_stencil_layouts = false; // must match the LayoutTracker, if one is used @@ -1035,11 +1073,21 @@ struct PreparedDraw { VkIndexType index_type = VK_INDEX_TYPE_UINT16; VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has + // A --mesh-compute mesh draw (mesh_compute): for DispatchMesh its workgroups and where their output slots are; + // for ExecuteIndirect(DISPATCH_MESH) the prepared indirect commands (mesh_indirect.records != 0) instead. + bool mesh_compute = false; + std::uint64_t mesh_groups = 0; + VkDeviceAddress mesh_output = 0; + MeshIndirect mesh_indirect; // Back to a new draw's state, keeping the vectors' storage. void reset() { graphics = nullptr; pipeline = VK_NULL_HANDLE; + mesh_compute = false; + mesh_groups = 0; + mesh_output = 0; + mesh_indirect = {}; colors.clear(); depth = {}; vertex_buffers.clear(); @@ -1526,6 +1574,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; } @@ -2059,7 +2108,8 @@ namespace detail { // Resolves a draw's pipeline, attachments and buffers. Attachment views take the pipeline's formats, so a // typeless texture is viewed as the format the pipeline renders. template -ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunctions& vk, PreparedDraw& p) { +ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunctions& vk, PreparedDraw& p, + bool indirect = false) { if (!vk.graphics_pipeline || !vk.buffer_at || !vk.image_view || !vk.begin_rendering || !vk.end_rendering || !vk.bind_vertex_buffers2 || !vk.bind_index_buffer || !vk.set_viewport || !vk.set_scissor || !vk.set_primitive_topology || !vk.set_primitive_restart_enable || !vk.set_stencil_reference || @@ -2068,8 +2118,25 @@ 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; + const GraphicsPipeline::MeshCompute& mc = pipeline->mesh_compute; + if (draw.mesh && !mc.pipeline && !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; + if (draw.mesh && mc.pipeline) { + // --mesh-compute: the workgroups' output slots, written by the dispatch and read by the draw that follows. + // DispatchMesh's counts are in count, instances and first. The draw's vertex count must fit in 32 bits. + // ExecuteIndirect's counts are GPU data: its caller reserves the slots and prepares the indirect commands. + if (!vk.dispatch || !vk.pipeline_barrier || !vk.mesh_output || (mc.bindless_set && !vk.bind_descriptor_sets)) + return ReplayResult::unsupported; + p.mesh_compute = true; + if (!indirect) { + const std::uint64_t groups = std::uint64_t(draw.count) * draw.instances * draw.first; + if (!groups || groups * mc.max_primitives * 3 > UINT32_MAX) return ReplayResult::unsupported; + if (!vk.mesh_output(groups * mc.slot_bytes, p.mesh_output)) return ReplayResult::unsupported; + p.mesh_groups = groups; + } + } p.graphics = pipeline; p.pipeline = pipeline->pipeline; p.area = {UINT32_MAX, UINT32_MAX}; @@ -2196,6 +2263,70 @@ 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. A dispatch with a count +// buffer reads the clamped copy the counted-dispatch prepass wrote (p.counted_dispatch), emitted before this. +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 && ind.kind != IndirectKind::dispatch) { + 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::dispatch_mesh) { + vk.draw_mesh_tasks_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. + // 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::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::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_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) + vk.dispatch_indirect(command_buffer, p.counted_dispatch.indirect, + p.counted_dispatch.offset + VkDeviceSize(k) * 12); + else + 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, const PreparedDraw::Attachment& a, VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, @@ -2915,13 +3046,25 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun const VkDeviceSize bytes = VkDeviceSize(ind->max_count - 1) * ind->stride + record_size; if (!detail::indirect_range(p.binding, ind->argument_offset, bytes)) return ReplayResult::invalid_indirect_arguments; + // DISPATCH_MESH on a --mesh-compute PSO: no mesh draw call runs it, the prepass below and the + // mesh-as-compute pass do (vulkan_mesh_indirect.h), so the mesh-shader entry points are not needed. + // A pipeline of the wrong kind (a VS PSO under DISPATCH_MESH, a mesh PSO under DRAW) is an invalid draw on + // every device, before any check of the entry points the right kind would need. + const GraphicsPipeline* state_pipeline = + ind->state && vk.graphics_pipeline ? vk.graphics_pipeline(ind->state->pipeline) : nullptr; + if (state_pipeline && state_pipeline->pipeline && state_pipeline->mesh != ind->state->mesh) + return ReplayResult::invalid_draw; + const GraphicsPipeline* mesh_pipeline = ind->kind == IndirectKind::dispatch_mesh ? state_pipeline : nullptr; + const bool mesh_compute = mesh_pipeline && mesh_pipeline->mesh_compute.pipeline; if (ind->count_buffer) { const ResourceBinding* cnt = resolve(ind->count_buffer); if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; - if (ind->kind == IndirectKind::dispatch) { + if (mesh_compute) { + // The prepass reads the count itself. + } else if (ind->kind == IndirectKind::dispatch) { // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch // and replace commands past min(count, max_count) with zero-group dispatches. if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch || @@ -2931,15 +3074,47 @@ 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 { + } else if (!mesh_compute) { 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; + // 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 (out.draw_count == out.draws.size()) out.draws.emplace_back(); + auto& prepared_draw = out.draws[out.draw_count]; + prepared_draw.reset(); + p.draw = std::uint32_t(out.draw_count++); + if (const auto r = detail::prepare_draw(*ind->state, resolve, vk, prepared_draw, true); + r != ReplayResult::success) + return r; + if (mesh_compute) { + // Each record gets a region of capacity_groups output slots; the prepass zeroes a record that + // would need more (mesh_indirect_capacity), and the draw count per record is written there too. + const GraphicsPipeline::MeshCompute& mc = mesh_pipeline->mesh_compute; + const std::uint32_t capacity = mesh_indirect_capacity(ind->max_count, mc.slot_bytes); + if (!capacity || !vk.prepare_mesh_indirect || !vk.emit_mesh_indirect || !vk.dispatch_indirect || + !vk.draw_indirect || (statistics_active && !statistics_helpers)) + return ReplayResult::unsupported; + const VkDeviceSize region = VkDeviceSize(capacity) * mc.slot_bytes; + VkDeviceAddress slots = 0; + if (!vk.mesh_output(region * ind->max_count, slots) || + !vk.prepare_mesh_indirect(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, + ind->count_buffer ? p.source.buffer : VK_NULL_HANDLE, + ind->count_buffer ? p.source.buffer_offset + ind->count_offset : 0, + ind->stride, ind->max_count, capacity, mc.max_primitives, slots, + region, prepared_draw.mesh_indirect)) + return ReplayResult::unsupported; + } + } if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); @@ -3791,51 +3966,27 @@ 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 && ind->kind != IndirectKind::dispatch) { - 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) { - if (ind->count_buffer) { - // No D3D12 query must count this internal compute pass as an application dispatch. - end_statistics(); - vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); - begin_statistics(); - } - if (ind->pipeline) { - ShaderUserData data{}; - std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = p.pipeline.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); - if (p.pipeline.bindless_set) { - const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, - 1, &set0, 0, nullptr); - } - vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), - &data); - } - for (std::uint32_t k = 0; k < ind->max_count; ++k) { - vk.dispatch_indirect(command_buffer, - ind->count_buffer ? p.counted_dispatch.indirect : p.binding.buffer, - (ind->count_buffer ? p.counted_dispatch.offset + VkDeviceSize(k) * 12 - : arguments + VkDeviceSize(k) * ind->stride)); - } + } else if (const auto* ind = std::get_if(&command); ind && !ind->state) { + if (ind->kind == IndirectKind::dispatch && ind->count_buffer) { + // No D3D12 query must count this internal compute pass as an application dispatch. + end_statistics(); + vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); + begin_statistics(); + } + if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments recorded + ShaderUserData data{}; + std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); + data.heap_base = vk.heap_base; + data.code_base = p.pipeline.code_base; + vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); + if (p.pipeline.bindless_set) { + const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; + vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, 1, + &set0, 0, nullptr); } + vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); } + detail::emit_indirect(vk, command_buffer, p, *ind); } else if (const auto* xdxr_build = std::get_if(&command); xdxr_build && vk.xdxr_record) { vk.xdxr_record(command_buffer, *xdxr_build); @@ -3912,8 +4063,48 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } 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)) { const detail::PreparedDraw& d = prepared.draws[p.draw]; + MeshComputeUserData mesh_data{}; // a --mesh-compute draw's push constants, for the dispatch and the draw + const MeshIndirect& mesh_indirect = d.mesh_indirect; // records != 0: ExecuteIndirect(DISPATCH_MESH) + if (d.mesh_compute) { + // The mesh shader as compute: one output slot per workgroup, then a barrier so the vertex shader + // that draws the slots sees them. Outside the draw's rendering scope, which opens below. + const GraphicsPipeline::MeshCompute& mc = d.graphics->mesh_compute; + std::copy(draw->user_data.begin(), draw->user_data.end(), mesh_data.user.s); + mesh_data.user.heap_base = vk.heap_base; + mesh_data.user.code_base = d.graphics->code_base; + mesh_data.output = d.mesh_output; + if (mesh_indirect.records) { + // The prepass writes every record's dispatch and draw commands; no D3D12 query counts it. + end_statistics(); + vk.emit_mesh_indirect(command_buffer, mesh_indirect); + begin_statistics(); + } + vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, mc.pipeline); + if (mc.bindless_set) + vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, mc.layout, 0, 1, + &mc.bindless_set, 0, nullptr); + if (mesh_indirect.records) { + // One indirect dispatch per record, each writing its own region of slots (a dropped record + // dispatches zero groups). + for (std::uint32_t k = 0; k < mesh_indirect.records; ++k) { + mesh_data.output = mesh_indirect.output + VkDeviceSize(k) * mesh_indirect.region_bytes; + vk.push_constants(command_buffer, mc.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, + sizeof(mesh_data), &mesh_data); + vk.dispatch_indirect(command_buffer, mesh_indirect.commands, VkDeviceSize(k) * 12); + } + } else { + vk.push_constants(command_buffer, mc.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(mesh_data), + &mesh_data); + vk.dispatch(command_buffer, draw->count, draw->instances, draw->first); + } + VkMemoryBarrier written{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + written.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + written.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + vk.pipeline_barrier(command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, 1, &written, 0, nullptr, 0, nullptr); + } constexpr VkAccessFlags color_access = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; constexpr VkAccessFlags depth_access = @@ -3963,7 +4154,11 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.layout, 0, 1, &set0, 0, nullptr); } - vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); + if (d.mesh_compute) + vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(mesh_data), + &mesh_data); + else + vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the // image upright, and winding as D3D12 sees it. const Viewport& v = draw->viewport; @@ -3974,12 +4169,18 @@ 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). + // A --mesh-compute draw is a vertex pipeline that draws triangle lists. + if (!draw->mesh || d.mesh_compute) { + const VkPrimitiveTopology topology = + d.mesh_compute ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); + vk.set_primitive_topology(command_buffer, topology); + const bool restart = draw->indexed && !draw->mesh && 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,8 +4189,26 @@ 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) { - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + if (draw->indexed) vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + if (std::get_if(&command) && mesh_indirect.records) { + // One indirect draw per record from the prepass's commands, each reading its record's slots. + for (std::uint32_t k = 0; k < mesh_indirect.records; ++k) { + mesh_data.output = mesh_indirect.output + VkDeviceSize(k) * mesh_indirect.region_bytes; + vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(mesh_data), + &mesh_data); + vk.draw_indirect(command_buffer, mesh_indirect.commands, + mesh_indirect.draw_offset + VkDeviceSize(k) * 16, 1, 16); + } + } else if (const auto* indirect = std::get_if(&command)) { + detail::emit_indirect(vk, command_buffer, p, *indirect); // the arguments hold the counts + } else if (draw->mesh && d.mesh_groups) { + // Three vertices for every primitive a workgroup may write (mesh_compute_vs.h); prepare_draw checked + // that the count fits in 32 bits. + vk.draw(command_buffer, + std::uint32_t(d.mesh_groups * graphics.mesh_compute.max_primitives * 3), 1, 0, 0); + } else if (draw->mesh) { + vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } 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/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd7..2cdf338b99 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -23,9 +23,15 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) + // With `device_address`, the chunks are storage buffers with a device address too (the allocation must then + // carry VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT), and `get_address` hands out scratch by address: the output of + // --mesh-compute mesh shaders goes there (vulkan_replay.h). + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, bool device_address = false) : device_(device), allocate_(std::move(allocate)) { loaded_ = vk_.load(get, device); + if (device_address) + get_buffer_address_ = + reinterpret_cast(get(device, "vkGetBufferDeviceAddress")); } ~ScratchBuffers() { @@ -69,6 +75,17 @@ class ScratchBuffers { return true; } + // `bytes` of scratch for the next submission by device address; false without device addresses. + bool get_address(std::uint64_t bytes, VkDeviceAddress& address) { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + if (!get_buffer_address_ || !get(bytes, buffer, offset)) return false; + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = buffer; + address = get_buffer_address_(device_, &info) + offset; + return true; + } + // The chunks handed out since the last call belong to a submission that `timeline` reaches `ticket` for // (ticket 0: nothing was submitted, they are free once `collect` runs). void retire(VkSemaphore timeline, std::uint64_t ticket) { @@ -149,6 +166,8 @@ class ScratchBuffers { VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + if (get_buffer_address_) + info.usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); @@ -174,6 +193,7 @@ class ScratchBuffers { Allocate allocate_; Functions vk_; bool loaded_ = false; + PFN_vkGetBufferDeviceAddress get_buffer_address_ = nullptr; // set: chunks have device addresses Batch current_; // handed out, not yet submitted std::vector retired_; // submitted, waiting for the GPU std::vector spare_; // finished chunks kept for reuse diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp index 251cab0862..60365d6afc 100644 --- a/runtime/test/d3d12_indirect_rt_test.cpp +++ b/runtime/test/d3d12_indirect_rt_test.cpp @@ -506,7 +506,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_mesh_test.cpp b/runtime/test/d3d12_m5_mesh_test.cpp new file mode 100644 index 0000000000..cab985e3ed --- /dev/null +++ b/runtime/test/d3d12_m5_mesh_test.cpp @@ -0,0 +1,694 @@ +// 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, 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 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 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 +// 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 +// VK_LAYER_KHRONOS_validation (0 errors required). +// +// --mesh-compute runs (a) and (b) without VK_EXT_mesh_shader on any GPU: the shaders translated with --mesh-compute +// and --wave64-emulate (LEONIDA_TEST_M5_MESH_COMPUTE_DIR) and a layer device created without the extension, so +// DispatchMesh is the mesh-as-compute pass and its slot draw, and ExecuteIndirect(DISPATCH_MESH) the prepass that +// writes each record's indirect dispatch and draw on the GPU (vulkan_mesh_indirect.h). Count buffers need no +// drawIndirectCount there (the prepass reads the count), so I2..I4 always run. The same CPU reference, error 0. +#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 + +#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 +#ifndef LEONIDA_TEST_M5_MESH_COMPUTE_DIR +#error "LEONIDA_TEST_M5_MESH_COMPUTE_DIR must name the folder build.py wrote with LEONIDA_MESH_COMPUTE=1" +#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(int argc, char** argv) { + bool single_calls = false, no_count_buffers = false, mesh_compute = 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], "--mesh-compute") == 0) mesh_compute = 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] [--mesh-compute] " + "[--max-draw-indirect-count N]\n"); + return 2; + } + } + 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 = mesh_compute ? LEONIDA_TEST_M5_MESH_COMPUTE_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 && !single_calls; + 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(); + 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, unless the mesh shaders are + // --mesh-compute ones (mesh tier 1 through the mesh-as-compute pass): then it is, on the same device. + { + Ref device; + Ref sig; + EXPECT(make_device(false, device)); + if (mesh_compute) { + EXPECT(SUCCEEDED(mesh_signature(device.p, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), sig)) && sig.p); + } else { + EXPECT(mesh_signature(device.p, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), sig) == E_NOTIMPL && !sig.p); + } + } + if (!mesh_compute && !d.mesh_shader) { + 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. Under --mesh-compute the mesh + // shader is an emulated-wave64 compute module: the layer checks its subgroup size at PSO creation. + const leonida::ShaderEntry* ms_entry = + library.find("ms", leonida::sha256_hex(read_file(root_dir / "fssm" / "ms_m5.fssm"))); + EXPECT(ms_entry); + leonida::SubgroupRequest ms_request{}; + if (!mesh_compute) { + 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 = mesh_compute || (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; + unsigned computed_mismatches = 0, computed_records = 0; // (d), with count buffers only + const char* subgroup = "?"; + { + Ref device; + EXPECT(make_device(!mesh_compute, 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}; + 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)); + // The PSO's mesh-stage request must be the one decided above (a --mesh-compute PSO has no mesh stage). + const auto* requests = rt::d3d12::pipeline_subgroup_requests(mesh_opaque.p); + EXPECT(requests); + bool mesh_request = mesh_compute; + if (mesh_compute) subgroup = "--mesh-compute, wave64 emulation"; + 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; + default: return 1; // the unavailable and unknown outcomes returned before the PSOs + } + } + 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()}}); + 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 ===== + { + // 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)); + 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 + { // (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. + 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 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); + 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(sig24.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); + + // ===== (d) arguments a compute shader writes in the same list (a GPU-culling pass) ===== + // cs_m5_args writes N = 8 records { 1 + (k & 3), 1, 1 } and the count 6 into two UAV buffers; after a + // transition to INDIRECT_ARGUMENT the next command reads them. Only the barrier orders the dispatch's + // writes before the reads (the prepass's under --mesh-compute, the indirect draw's natively). + if (counts) { + std::vector cs_bytes; + EXPECT(container_of("cs_m5_args", "cs", cs_bytes)); + Ref cs_root; + { + // [0] four 32-bit constants (s0..s3), [1] a table of two raw UAVs (s[4:5]). + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 4}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + 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); + EXPECT(!blob.empty() && SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), + IID_PPV_ARGS(&cs_root.p)))); + } + D3D12_COMPUTE_PIPELINE_STATE_DESC cs_desc{}; + cs_desc.pRootSignature = cs_root.p; + cs_desc.CS = {cs_bytes.data(), cs_bytes.size()}; + Ref cs_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&cs_desc, IID_PPV_ARGS(&cs_pso.p)))); + const auto uav_buffer = [&](Ref& out) { + const auto desc = buffer_desc(256, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + return SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p))); + }; + Ref records_cs, count_cs; + EXPECT(uav_buffer(records_cs) && uav_buffer(count_cs)); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu && step == 32); // the shader steps 32 bytes a slot + D3D12_UNORDERED_ACCESS_VIEW_DESC raw{}; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + raw.Buffer.NumElements = 64; + raw.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(records_cs.p, nullptr, &raw, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu)}); + device->CreateUnorderedAccessView(count_cs.p, nullptr, &raw, + D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + step)}); + + constexpr UINT written = 8, count = 6; + Image want_cs({0, 0, 0, 255}); + for (unsigned k = 0; k < count; ++k) // record k: 1 + (k & 3) groups from cell 0 + for (unsigned j = 0; j < 1 + (k & 3); ++j) + want_cs.cell(j, [](Pixel& p) { + p[0] = std::uint8_t(std::min(255u, p[0] + 16u)); + p[1] = std::uint8_t(std::min(255u, p[1] + 24u)); + }); + EXPECT(begin(mesh_additive.p, black)); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(cs_root.p); + list->SetPipelineState(cs_pso.p); + const std::uint32_t cs_constants[4] = {written, count, 0, 0}; + list->SetComputeRoot32BitConstants(0, 4, cs_constants, 0); + list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + const D3D12_RESOURCE_BARRIER to_indirect[2] = { + transition(records_cs.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + transition(count_cs.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT)}; + list->ResourceBarrier(2, to_indirect); + list->SetPipelineState(mesh_additive.p); // the graphics root signature and constants stay + set_constants(constants(0, 16, 24)); + list->ExecuteIndirect(sig12.p, written, records_cs.p, 0, count_cs.p, 0); + EXPECT(end()); + const auto computed = run(list.p); + if (computed != leonida::ReplayResult::success) + std::fprintf(stderr, "compute-written indirect mesh replay: %d\n", int(computed)); + EXPECT(computed == leonida::ReplayResult::success); + computed_mismatches = check("compute-written DISPATCH_MESH", want_cs); + computed_records = count; + } + + // 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; + { + 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%s, 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; compute-written records: %u drawn, %u mismatched pixels; wrong-kind indirect draws fail at " + "execution\n", + mesh_compute ? " without VK_EXT_mesh_shader" : "", subgroup, direct_mismatches, records_drawn, + counts ? " (count buffers included)" : " (no count buffers)", indirect_mismatches, computed_records, + computed_mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + return direct_mismatches == 0 && indirect_mismatches == 0 && computed_mismatches == 0 ? 0 : 1; +} diff --git a/runtime/test/d3d12_m5_world_test.cpp b/runtime/test/d3d12_m5_world_test.cpp new file mode 100644 index 0000000000..41880353d6 --- /dev/null +++ b/runtime/test/d3d12_m5_world_test.cpp @@ -0,0 +1,772 @@ +// 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 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 +// 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; + } + // 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; + 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.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)))); + 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, 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 D3D12_DRAW_ARGUMENTS record{4, instances[r], 0, 0}; + std::memcpy(mapped + 64 + r * sizeof(record), &record, sizeof(record)); + } + 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 + // 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 (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); + 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; + 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); + 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 + 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})); + 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); + // 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_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: 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()); + 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_mesh_compute_test.cpp b/runtime/test/d3d12_mesh_compute_test.cpp new file mode 100644 index 0000000000..c57483b285 --- /dev/null +++ b/runtime/test/d3d12_mesh_compute_test.cpp @@ -0,0 +1,413 @@ +// Mesh PSOs and DispatchMesh on a device without VK_EXT_mesh_shader, through `--mesh-compute` (docs/d3d12_vulkan.md, +// "Mesh shaders without VK_EXT_mesh_shader"). The layer's device is made without the extension on every GPU, so this +// runs everywhere d3d12_draw_test does. The mesh shader is test/glsl/ms_draw_compute.comp: d3d12_mesh_test's quad +// shader written to the --mesh-compute contract (a compute shader writing one output slot per workgroup), with the +// index entry's "mesh_compute" layout. The layer builds the vertex shader that draws the slots (mesh_compute_vs.h). +// - MeshShaderTier is 1 (the index has --mesh-compute mesh shaders), and an MS + PS PSO from a pipeline state +// stream is created. A mesh shader without a mesh_compute layout is still refused (E_NOTIMPL). +// - Draws, as in d3d12_mesh_test: an empty grid records nothing; 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 X, Y and Z counts each reach the slot index. The rest stays blue. +// Each pixel is read back and compared. +// - A vertex draw with the mesh PSO fails at execution (ReplayResult::invalid_draw). +// - A PS reading the f16 halves of some of the layout's params at its locations links; one reading them elsewhere +// is refused. +// - Where a --mesh-compute PSO can't be run as built, the tier is NOT_SUPPORTED and the PSO is refused: a device +// with 144 bytes of push constants (enough for every other pipeline, not for the 152-byte block), and one whose +// subgroup sizes can't be required, where the 32-wide mesh shader would only get its size as the default. A +// mesh shader translated with --wave64-emulate, exact on any size, is still created there. +// Shaders: test/glsl/ms_draw_compute.comp, ps_draw.frag. 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 "../src/subgroup_size.h" + +#include +#include + +#if !defined(LEONIDA_TEST_MS_COMPUTE_SPV) || !defined(LEONIDA_TEST_PS_SPV) +#error "LEONIDA_TEST_MS_COMPUTE_SPV and LEONIDA_TEST_PS_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 PsSubobject = Subobject; +using MsSubobject = Subobject; +using TargetsSubobject = 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; + } +}; + +HRESULT create(ID3D12Device* device, ID3D12RootSignature* root, const D3D12_SHADER_BYTECODE& ms, + const D3D12_SHADER_BYTECODE& ps, Ref& out) { + D3D12_RT_FORMAT_ARRAY formats{}; + formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + formats.NumRenderTargets = 1; + Stream stream; + stream.add(RootSubobject{.inner = root}).add(MsSubobject{.inner = ms}).add(PsSubobject{.inner = ps}); + stream.add(TargetsSubobject{.inner = formats}); + Ref device2; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device2.p)))) return E_NOINTERFACE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{stream.bytes.size(), stream.bytes.data()}; + 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; + 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); + + // One FSSM program per index entry; the entries share the two compiled modules. + const auto program = [](std::uint32_t tag) { return fssm_program({tag, 0xbf810000}); }; + const auto ms_program = program(0x4d530001), ms_plain_program = program(0x4d530002), + ms_halves_program = program(0x4d530003), ms_emulated_program = program(0x4d530004), + ps_program = program(0x50530001), ps_half_program = program(0x50530002), + ps_half_elsewhere_program = program(0x50530003); + const auto ms_container = shader_container(ms_program), ms_plain_container = shader_container(ms_plain_program), + ms_halves_container = shader_container(ms_halves_program), + ms_emulated_container = shader_container(ms_emulated_program), + ps_container = shader_container(ps_program), ps_half_container = shader_container(ps_half_program), + ps_half_elsewhere_container = shader_container(ps_half_elsewhere_program); + const auto library = std::filesystem::temp_directory_path() / "leonida_mesh_compute_test"; + std::filesystem::create_directories(library); + const auto overwrite = std::filesystem::copy_options::overwrite_existing; + for (const char* name : {"ms_draw_compute", "ms_plain", "ms_halves", "ms_emulated"}) + std::filesystem::copy_file(LEONIDA_TEST_MS_COMPUTE_SPV, library / (std::string(name) + ".spv"), overwrite); + for (const char* name : {"ps_draw", "ps_half", "ps_half_elsewhere"}) + std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / (std::string(name) + ".spv"), overwrite); + { + // ms_draw_compute's layout is rdna2spirv.mesh_compute_layout(4, 2, 0, 0, [0]). ms_plain has the same module + // but no layout, as a mesh shader translated without --mesh-compute has. ms_halves's layout (only created, + // never drawn) exports the halves of params 0 and 1, as --f16-interp-fallback does; ps_half reads param 0's + // at the same locations, ps_half_elsewhere at others. ms_emulated is ms_draw_compute translated with + // --wave64-emulate as far as the index says. + const std::string layout = + "\"mesh_compute\": {\"slot_bytes\": 176, \"vertices\": 16, \"vertex_stride\": 32, \"primitives\": 144, " + "\"primitive_stride\": 16, \"max_vertices\": 4, \"max_primitives\": 2, \"clip_count\": 0, " + "\"clip_offset\": 16, \"cull_count\": 0, \"cull_offset\": 16, \"params\": {\"0\": 16}, " + "\"push_constant_bytes\": 152, \"address_dwords\": [36, 37]}"; + const std::string halves_layout = + "\"mesh_compute\": {\"slot_bytes\": 240, \"vertices\": 16, \"vertex_stride\": 48, \"primitives\": 208, " + "\"primitive_stride\": 16, \"max_vertices\": 4, \"max_primitives\": 2, \"clip_count\": 0, " + "\"clip_offset\": 16, \"cull_count\": 0, \"cull_offset\": 16, \"params\": {\"0\": 16, \"1\": 32}, " + "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27]}, \"push_constant_bytes\": 152, " + "\"address_dwords\": [36, 37]}"; + const auto ms = [&](const char* name, const std::vector& p, const std::string& extra) { + return "\"" + std::string(name) + "\": {\"stage\": \"ms\", \"fssm_sha256\": \"" + leonida::sha256_hex(p) + + "\", \"bindings\": [], \"push_constant_bytes\": 152, \"local_size\": [32, 1, 1], " + "\"max_vertices\": 4, \"max_primitives\": 2" + extra + "}"; + }; + const auto ps = [&](const char* name, const std::vector& p, const std::string& extra) { + return "\"" + std::string(name) + "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" + leonida::sha256_hex(p) + + "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [0], \"outputs\": [0]" + extra + + "}"; + }; + std::ofstream index(library / "index.json", std::ios::binary); + index << "{" << ms("ms_draw_compute", ms_program, ", " + layout) << ",\n" + << ms("ms_plain", ms_plain_program, "") << ",\n" + << ms("ms_halves", ms_halves_program, ", " + halves_layout) << ",\n" + << ms("ms_emulated", ms_emulated_program, + ", \"wave64\": true, \"subgroup_size\": null, \"wave64_exchange\": \"workgroup\", " + layout) + << ",\n" + << ps("ps_draw", ps_program, "") << ",\n" + << ps("ps_half", ps_half_program, ", \"f16_halves\": {\"0\": [28, 29]}") << ",\n" + << ps("ps_half_elsewhere", ps_half_elsewhere_program, ", \"f16_halves\": {\"0\": [20, 21]}") << "}"; + } + const D3D12_SHADER_BYTECODE ms{ms_container.data(), ms_container.size()}; + const D3D12_SHADER_BYTECODE ms_plain{ms_plain_container.data(), ms_plain_container.size()}; + const D3D12_SHADER_BYTECODE ms_halves{ms_halves_container.data(), ms_halves_container.size()}; + const D3D12_SHADER_BYTECODE ms_emulated{ms_emulated_container.data(), ms_emulated_container.size()}; + const D3D12_SHADER_BYTECODE ps{ps_container.data(), ps_container.size()}; + const D3D12_SHADER_BYTECODE ps_half{ps_half_container.data(), ps_half_container.size()}; + const D3D12_SHADER_BYTECODE ps_half_elsewhere{ps_half_elsewhere_container.data(), + ps_half_elsewhere_container.size()}; + + // The layer's device, always without VK_EXT_mesh_shader, with the GPU's subgroup sizes unless changed. + const auto device_info = [&] { + 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.subgroup = d.subgroup; + info.shader_dir = library.string(); + info.mesh_shader = false; // as on a GPU without VK_EXT_mesh_shader, whatever this one has + return info; + }; + const auto make_device = [&](const rt::d3d12::VulkanDeviceInfo& info, Ref& device) { + ID3D12Device* inner = nullptr; + if (FAILED(rt::d3d12::create_vulkan_device(info, 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; + }; + // [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint), as in d3d12_mesh_test. + const auto make_root = [&](ID3D12Device* device, Ref& root) { + 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))); + }; + + // Where a --mesh-compute PSO can't run as built: no tier, and the PSO refused. + { + // 144 bytes of push constants: every other pipeline fits, the 152-byte block doesn't. + auto info = device_info(); + info.max_push_constants_size = 144; + Ref device; + Ref root; + Ref refused; + EXPECT(make_device(info, device) && make_root(device.p, root)); + EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED); + EXPECT(create(device.p, root.p, ms, ps, refused) == E_NOTIMPL && !refused.p); + root.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + { + // Subgroup sizes 32 to 64 that can't be required, 32 by default: the 32-wide mesh shader would only get its + // size by default. The emulated one is exact on any size. + auto info = device_info(); + info.subgroup = {}; + info.subgroup.min_size = 32; + info.subgroup.max_size = 64; + info.subgroup.default_size = 32; + info.subgroup.max_compute_workgroup_subgroups = 32; + Ref device; + Ref root; + Ref refused, emulated; + EXPECT(make_device(info, device) && make_root(device.p, root)); + EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED); + EXPECT(create(device.p, root.p, ms, ps, refused) == E_NOTIMPL && !refused.p); + EXPECT(SUCCEEDED(create(device.p, root.p, ms_emulated, ps, emulated))); + emulated.reset(); + root.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + // The GPU's own sizes must guarantee 32 for compute (required, or its only size) for the rest. + { + leonida::ShaderEntry cs; + cs.stage = "cs"; + cs.local_size = {32, 1, 1}; + const auto outcome = leonida::decide_subgroup_size(cs, d.subgroup).outcome; + if (outcome != leonida::SubgroupOutcome::required && outcome != leonida::SubgroupOutcome::device_fixed) { + std::filesystem::remove_all(library); + std::printf("SKIP: this GPU can't require 32-wide compute subgroups; only the refusals were checked\n"); + return 77; + } + } + + constexpr UINT size = 64; + std::vector pixels(size * 256); + { + Ref device; + Ref root; + EXPECT(make_device(device_info(), device) && make_root(device.p, root)); + EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_1); + + Ref mesh_pso, refused, halves_pso; + EXPECT(SUCCEEDED(create(device.p, root.p, ms, ps, mesh_pso))); + EXPECT(create(device.p, root.p, ms_plain, ps, refused) == E_NOTIMPL && !refused.p); + // f16 halves: param 0's where the layout exports them (param 1's go unread) links; elsewhere is refused. + EXPECT(SUCCEEDED(create(device.p, root.p, ms_halves, ps_half, halves_pso))); + EXPECT(create(device.p, root.p, ms_halves, ps_half_elsewhere, refused) == E_NOTIMPL && !refused.p); + halves_pso.reset(); + + 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) and 256 (green); CBVs are 256-byte aligned. + const float tints[2][3] = {{1, 0, 1}, {0, 1, 0}}; + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + for (int i = 0; i < 2; ++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, after an empty grid. + 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); + 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()); + + // A vertex draw with the mesh PSO fails at execution. + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_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); + list->DrawInstanced(3, 1, 0, 0); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::invalid_draw); + 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, &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 && 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("mesh compute: without VK_EXT_mesh_shader, mesh tier 1 through --mesh-compute; a stream MS + PS PSO " + "drew DispatchMesh over X, Y and Z (each slot a workgroup's quad) and matched all %u pixels; a mesh " + "shader without a mesh_compute layout refused; f16 halves read where exported linked, elsewhere " + "refused; no tier and the PSO refused at 144 push-constant bytes and with unguaranteed subgroup " + "sizes (an emulated mesh shader still created); a vertex draw with the mesh PSO fails at " + "execution\n", + size * size); + return 0; +} diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp new file mode 100644 index 0000000000..5fc6381703 --- /dev/null +++ b/runtime/test/d3d12_mesh_test.cpp @@ -0,0 +1,441 @@ +// 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 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 +// 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 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 +// 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; + 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}); + 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); + // 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}); + 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 (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); + return 0; +} diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index d7466b781b..c9f0d7d953 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -582,6 +582,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); }; @@ -597,16 +598,76 @@ 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); 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, 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})); + 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{}; + 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) { + 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; + for (const IndirectKind kind : {IndirectKind::draw, IndirectKind::draw_indexed}) { + calls.clear(); + ExecuteIndirect command{kind, 20, UINT32_MAX, 1, 4, 0, 0, nullptr, true}; + 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); + } + calls.clear(); + huge.max_draw_indirect_count = 1000; + ExecuteIndirect uneven{IndirectKind::draw, 16, 2500, 1, 0, 0, 0, nullptr, true}; + 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); + } + // 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/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/glsl/ms_draw_compute.comp b/runtime/test/glsl/ms_draw_compute.comp new file mode 100644 index 0000000000..9ef9159377 --- /dev/null +++ b/runtime/test/glsl/ms_draw_compute.comp @@ -0,0 +1,63 @@ +#version 460 +// test/glsl/ms_draw.mesh written to the `rdna2spirv.py --mesh-compute` contract instead (docs/design.md, "Mesh shaders +// as compute"), standing in for a translated mesh shader in d3d12_mesh_compute_test. Each workgroup writes one slot of +// the output buffer whose address is in push-constant dwords 36..37: slot = (x + y*nx + z*nx*ny) * 176 bytes. A slot +// is the layout rdna2spirv.mesh_compute_layout gives 4 vertices, 2 primitives and one param at location 0: a 16-byte +// header (vertex count, primitive count), 4 vertices of 32 bytes (position, then the colour), then 2 primitives of 16 +// bytes (three vertex indices, then 1 if culled). The quad is ms_draw.mesh's: column = x + z, row = y on a 4x4 grid of +// clip-space cells, moved by s0, s1 (root constants), red, triangles (0,1,2) and (2,1,3). +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require + +layout(local_size_x = 32) in; + +layout(buffer_reference, std430, buffer_reference_align = 16) buffer Slot { + uint words[]; +}; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; + uvec2 output_address; +} pc; + +const uint slot_bytes = 176u, vertices = 16u, vertex_stride = 32u, primitives = 144u; + +uvec2 add64(uvec2 a, uint b) { + uint carry; + const uint low = uaddCarry(a.x, b, carry); + return uvec2(low, a.y + carry); +} + +void main() { + const uvec3 n = gl_NumWorkGroups, g = gl_WorkGroupID; + const uint group = g.x + g.y * n.x + g.z * n.x * n.y; + Slot slot = Slot(add64(pc.output_address, group * slot_bytes)); + const uint i = gl_LocalInvocationIndex; + if (i == 0) { + slot.words[0] = 4u; // vertices + slot.words[1] = 2u; // primitives + } + if (i < 4) { + const float column = float(g.x + g.z), row = float(g.y); + const vec2 offset = vec2(uintBitsToFloat(pc.s[0]), uintBitsToFloat(pc.s[1])); + 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); + const vec4 position = vec4(top_left + vec2(0.5, -0.5) * corner + offset, 0.0, 1.0); + const vec4 colour = vec4(1.0, 0.0, 0.0, 1.0); + const uint at = (vertices + i * vertex_stride) / 4u; + for (uint c = 0; c < 4; ++c) { + slot.words[at + c] = floatBitsToUint(position[c]); + slot.words[at + 4u + c] = floatBitsToUint(colour[c]); + } + } + if (i < 2) { + const uvec3 corners = i == 0 ? uvec3(0, 1, 2) : uvec3(2, 1, 3); + const uint at = (primitives + i * 16u) / 4u; + slot.words[at] = corners.x; + slot.words[at + 1u] = corners.y; + slot.words[at + 2u] = corners.z; + slot.words[at + 3u] = 0u; // not culled + } +} diff --git a/runtime/test/mesh_compute_vs_test.cpp b/runtime/test/mesh_compute_vs_test.cpp new file mode 100644 index 0000000000..9b40ca6e92 --- /dev/null +++ b/runtime/test/mesh_compute_vs_test.cpp @@ -0,0 +1,150 @@ +// Pure-CPU tests for runtime/src/mesh_compute_vs.h, the vertex shader that draws a --mesh-compute mesh shader's slots: +// - layouts built as rdna2spirv.mesh_compute_layout builds them: one small, one like the corpus's (128/128 outputs, +// 18 params, 3 clip distances), one with clip and cull distances, one with --f16-interp-fallback halves; +// - the module's interface: a Vertex entry point reading VertexIndex and the 152-byte push-constant block, Position, +// the distance arrays and each param location out, then each half's two locations; +// - refusals: no vertices, the address in the --pc-tail-ubo block, an f16_halves param that is not a layout param, +// a half location that collides with another output. +// With a folder as the first argument it writes the modules there, for the spirv-val tests CMake adds. +// No GPU or game files required. +#include "../src/mesh_compute_vs.h" +#include "../src/spirv_f16_halves.h" + +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \ +} while (0) + +namespace { + +using namespace leonida; +using namespace leonida::mesh_vs_detail; + +// rdna2spirv.mesh_compute_layout, for the default push-constant layout. +MeshComputeLayout layout(std::uint32_t maxv, std::uint32_t maxp, std::uint32_t clip, std::uint32_t cull, + const std::vector& params) { + const std::uint32_t clip_vec4 = (clip + 3) / 4, cull_vec4 = (cull + 3) / 4; + MeshComputeLayout l; + l.vertex_stride = 16 * (1 + clip_vec4 + cull_vec4 + std::uint32_t(params.size())); + l.vertices = 16; + l.primitives = l.vertices + maxv * l.vertex_stride; + l.slot_bytes = l.primitives + maxp * 16; + l.primitive_stride = 16; + l.max_vertices = maxv; + l.max_primitives = maxp; + l.clip_count = clip; + l.clip_offset = 16; + l.cull_count = cull; + l.cull_offset = 16 * (1 + clip_vec4); + for (std::size_t k = 0; k < params.size(); ++k) + l.params[params[k]] = 16 * (1 + clip_vec4 + cull_vec4 + std::uint32_t(k)); + l.push_constant_bytes = 4 * 32 + 24; + return l; +} + +struct Summary { + bool ok = false; + std::uint32_t model = ~0u, interface_count = 0; + std::set capabilities, builtins, locations; + std::uint32_t push_constant_vars = 0; +}; + +Summary summarize(const std::vector& words) { + Summary s; + spirv_detail::Module m; + if (words.size() < 5 || words[1] != 0x00010500u || !m.parse(words)) return s; + for (const auto& inst : m.insts) { + const auto& w = inst.words; + switch (inst.opcode) { + case kOpCapability: s.capabilities.insert(w[1]); break; + case kOpEntryPoint: { + s.model = w[1]; + std::size_t i = 3; // past the name's words: its last word holds the terminating nul + while (i < w.size() && (w[i] >> 24) != 0) ++i; + s.interface_count = std::uint32_t(w.size() - (i + 1)); + break; + } + case kOpDecorate: + if (w[2] == kDecBuiltIn) s.builtins.insert(w[3]); + if (w[2] == kDecLocation) s.locations.insert(w[3]); + break; + case kOpVariable: + if (w[3] == kStoragePushConstant) ++s.push_constant_vars; + break; + default: break; + } + } + s.ok = true; + return s; +} + +bool write(const std::string& dir, const char* name, const std::vector& words) { + std::ofstream f(dir + "/" + name + ".spv", std::ios::binary); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); + return bool(f); +} + +} // namespace + +int main(int argc, char** argv) { + // Small: 4 vertices, 2 primitives, two params. + const auto small = mesh_compute_vs(layout(4, 2, 0, 0, {0, 2})); + const Summary s = summarize(small); + CHECK(s.ok && s.model == kExecModelVertex); + CHECK((s.capabilities == std::set{kCapShader, kCapInt64, kCapPhysicalStorageBufferAddresses})); + CHECK((s.builtins == std::set{kBuiltInVertexIndex, kBuiltInPosition})); + CHECK((s.locations == std::set{0, 2})); + CHECK(s.interface_count == 2 + 1 + 2); // VertexIndex, the push constants, Position, two params + CHECK(s.push_constant_vars == 1); + + // Like the corpus: 128 vertices and primitives, 18 params, 3 clip distances. + std::vector eighteen; + for (std::uint32_t n = 0; n < 18; ++n) eighteen.push_back(n); + const auto corpus = mesh_compute_vs(layout(128, 128, 3, 0, eighteen)); + const Summary c = summarize(corpus); + CHECK(c.ok && c.capabilities.count(kCapClipDistance) && !c.capabilities.count(kCapCullDistance)); + CHECK(c.builtins.count(kBuiltInClipDistance) && c.locations.size() == 18); + + // Clip and cull distances together. + const auto distances = mesh_compute_vs(layout(8, 4, 2, 5, {1})); + const Summary d = summarize(distances); + CHECK(d.ok && d.builtins.count(kBuiltInClipDistance) && d.builtins.count(kBuiltInCullDistance)); + CHECK(d.interface_count == 2 + 1 + 2 + 1); + + // --f16-interp-fallback: param 1's halves go out at 28 and 29 as well. + MeshComputeLayout halves = layout(4, 2, 0, 0, {0, 1}); + halves.f16_halves[1] = {28, 29}; + const auto f16 = mesh_compute_vs(halves); + const Summary h = summarize(f16); + CHECK(h.ok && (h.locations == std::set{0, 1, 28, 29}) && h.interface_count == 2 + 1 + 4); + + // Refusals. + std::string error; + CHECK(mesh_compute_vs(MeshComputeLayout{}, &error).empty() && error.find("without vertices") != std::string::npos); + MeshComputeLayout tail = layout(4, 2, 0, 0, {0}); + tail.address_in_pc_tail = true; + CHECK(mesh_compute_vs(tail, &error).empty() && error.find("pc-tail-ubo") != std::string::npos); + MeshComputeLayout stray = layout(4, 2, 0, 0, {0}); + stray.f16_halves[3] = {20, 21}; + CHECK(mesh_compute_vs(stray, &error).empty() && error.find("not in the layout") != std::string::npos); + MeshComputeLayout collide = layout(4, 2, 0, 0, {0, 1}); + collide.f16_halves[1] = {0, 29}; + CHECK(mesh_compute_vs(collide, &error).empty() && error.find("collides") != std::string::npos); + + if (argc > 1) { + CHECK(write(argv[1], "small", small)); + CHECK(write(argv[1], "corpus", corpus)); + CHECK(write(argv[1], "distances", distances)); + CHECK(write(argv[1], "f16", f16)); + } + std::printf("mesh_compute_vs: interfaces of four layouts (small, corpus-like, clip+cull, f16 halves) and the " + "refusals as expected\n"); + return 0; +} 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/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 6a0ffb62b7..737ff0c686 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -368,6 +368,11 @@ int main() { "\"subgroup_size\": 64},\n" " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " "\"subgroup_size\": null, \"wave64_exchange\": \"workgroup\", \"lds_bytes\": 33332},\n" + " \"ms_compute\": {\"stage\": \"ms\", \"fssm_sha256\": \"" << hash2 << "\", \"mesh_compute\": {" + "\"slot_bytes\": 4816, \"vertices\": 16, \"vertex_stride\": 48, \"primitives\": 6160, " + "\"primitive_stride\": 16, \"max_vertices\": 128, \"max_primitives\": 128, \"clip_count\": 3, " + "\"clip_offset\": 16, \"cull_count\": 0, \"cull_offset\": 32, \"params\": {\"0\": 32, \"x\": 1}, " + "\"f16_halves\": {\"0\": [28, 29]}, \"push_constant_bytes\": 152}},\n" " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}"; std::ofstream spv(dir / "cs_test.spv", std::ios::binary); const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; @@ -375,7 +380,7 @@ int main() { } ShaderLibrary library; std::string error; - CHECK(library.load(dir.string(), &error) && library.size() == 6); + CHECK(library.load(dir.string(), &error) && library.size() == 7); const ShaderEntry* vs = library.find("vs", hash); CHECK(vs && vs->input_signature.size() == 2 && vs->input_signature[0].semantic == "COLOR"); CHECK(vs->input_signature[1].register_index == 2 && vs->input_signature[1].system_value == 6 && @@ -399,6 +404,15 @@ int main() { CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144); CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64); CHECK(!library.find("ms", hash)); // no mesh shader with this hash + // A --mesh-compute mesh shader's slot layout; a param key that is not a location is skipped. + const ShaderEntry* ms = library.find("ms", hash2); + CHECK(ms && ms->mesh_compute && library.mesh_compute_count() == 1); + const MeshComputeLayout& lay = *ms->mesh_compute; + CHECK(lay.slot_bytes == 4816 && lay.vertices == 16 && lay.vertex_stride == 48 && lay.primitives == 6160); + CHECK(lay.max_vertices == 128 && lay.max_primitives == 128 && lay.clip_count == 3 && lay.cull_offset == 32); + CHECK(lay.params.size() == 1 && lay.params.at(0) == 32 && lay.push_constant_bytes == 152); + CHECK(lay.f16_halves.size() == 1 && lay.f16_halves.at(0)[0] == 28 && !lay.address_in_pc_tail); + CHECK(!library.find("ps", hash)->mesh_compute); // The subgroup fields of the index (wave64 / subgroup_size / wave64_exchange): absent, native and emulated. CHECK(!entry->subgroup_size && entry->wave64_exchange.empty() && !entry->emulated()); const ShaderEntry* native = library.find("ps", hash2); diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index b8dcdab0e0..426e172030 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 (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) +; 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_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_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/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..a586711b9d --- /dev/null +++ b/runtime/test/shaders/vs_m5.asm @@ -0,0 +1,38 @@ +; 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. 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) +; 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_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 +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 114ca187f1..e5b7e40034 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -109,6 +109,10 @@ 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 + 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 bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled @@ -116,6 +120,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; @@ -374,6 +380,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; @@ -428,6 +436,11 @@ 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; + max_draw_indirect_count = chosen.limits.maxDrawIndirectCount; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses @@ -511,6 +524,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 +603,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); diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index ca358a5142..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: @@ -597,6 +611,9 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", "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"} @@ -780,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 new file mode 100644 index 0000000000..aec945bf90 --- /dev/null +++ b/tests/test_shader_build_mesh.py @@ -0,0 +1,66 @@ +"""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"))) + + 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()