diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..f84c7a52e2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -179,7 +179,7 @@ The command-list surface maps to the IR as follows: | `DiscardResource` / `WriteBufferImmediate` / `AtomicCopyBufferUINT(64)` | discard, immediate-write and atomic-copy commands (section 4.2) | | `BeginQuery` / `EndQuery` / `ResolveQueryData` | query commands | | `ExecuteIndirect` | command; signature + argument buffer | -| `BeginRenderPass` / `EndRenderPass` | rendering scope | +| `BeginRenderPass` / `EndRenderPass` | target binding, clears and resolves on the list's own commands (Tier 0 emulation, section 4.3) | | `ExecuteBundle` | play the bundle's state calls and draws on this list, copy its state-free commands in order | The IR is the place to add the trace, validation and "unsupported call" reporting. It also lets the layer replay a @@ -2702,11 +2702,23 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a The access itself is never dropped, so the dependency still covers everything the application named, over a slightly larger scope. -- Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic - rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve - targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with - the same attachments and `LOAD`/`STORE`. If the game does not use render passes, build a rendering scope per draw - from the bound RTVs/DSV and let explicit `Clear*View` calls do the clears. +- Render passes (D3D-27): `BeginRenderPass`/`EndRenderPass` are emulated on the list's own commands, as the PC + runtime does for a driver at `RenderPassesTier` 0 (the tier the device reports, and WARP's): `BeginRenderPass` + binds the pass's render targets and depth/stencil view as `OMSetRenderTargets` would and records a clear for each + `CLEAR` beginning access (colour targets one by one, the depth and stencil planes together with their own flags + and values); `EndRenderPass` records a `ResolveSubresourceRegion` for each subresource of each `RESOLVE` ending + access (colour, depth or stencil). `DISCARD`, `PRESERVE`, the `PRESERVE_LOCAL_*` forms and `NO_ACCESS` record + nothing, which each of them allows. A `SUSPENDING_PASS` keeps its ending accesses for the pass that resumes it, and + a `RESUMING_PASS` does not run its beginning accesses again. Draws inside a pass are ordinary draws, each in its + own dynamic-rendering scope (section 3.2), so the emulation needs no Vulkan render pass object; a native mapping + to `vkCmdBeginRendering` load/store ops would save the separate clear and resolve, not change the result. The + recording rules are WARP's, measured on Windows 11 26200 (Close's verdict, not its code): no nesting, no + `EndRenderPass` without a pass, at most 8 targets, direct lists only (a bundle fails), Close fails while a pass is + open but not while one is suspended, copies, resolves, `Clear*View`, `DiscardResource` and `OMSetRenderTargets` + fail inside a pass while barriers do not, and the pass after a suspended one must be a `RESUMING_PASS` with no + command recorded in between (a barrier counts). `d3d12_render_pass_test` holds 6 data cases (byte for byte after + readback) and 26 Close cases to WARP; RTX 5080 (NVIDIA 621.14), Vulkan validation clean. Not covered: draws inside + a pass (the test has no shaders), and what the targets bound after `EndRenderPass` are (they stay bound here). ### 4.4 Fences, queues and frames in flight @@ -3735,7 +3747,7 @@ M0–M2 do not need the executable. | **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders most of them declare bindings, which M2 (pipelines bind set 0) lets through. **M1.5 (D3D-53) met with translator output** by `d3d12_translated_draw_test`: see below | | **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) | | **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 | +| **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 by this test (their accesses and recording rules are, by `d3d12_render_pass_test`, section 4.3), 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 | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..4012dc45fd 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3077,6 +3077,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_clear_formats COMMAND d3d12_clear_formats_test) set_tests_properties(d3d12_clear_formats PROPERTIES SKIP_RETURN_CODE 77) + # Render passes (BeginRenderPass/EndRenderPass, D3D-27) against WARP: accesses, resolves, suspend/resume and + # the recording rules Close reports (needs a Vulkan GPU and Microsoft's WARP; exit 77 without either). + add_executable(d3d12_render_pass_test test/d3d12_render_pass_test.cpp) + target_link_libraries(d3d12_render_pass_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_render_pass_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_render_pass_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_render_pass COMMAND d3d12_render_pass_test) + set_tests_properties(d3d12_render_pass PROPERTIES SKIP_RETURN_CODE 77) + # SetDescriptorHeaps validation, Reset/ClearState/bundle parity, lifetime pinning, direct-index flags. add_executable(d3d12_set_descriptor_heaps_test test/d3d12_set_descriptor_heaps_test.cpp) target_link_libraries(d3d12_set_descriptor_heaps_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..51e474a9c6 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -217,6 +217,7 @@ class GraphicsCommandList final HRESULT STDMETHODCALLTYPE Close() override { constexpr auto method = "ID3D12GraphicsCommandList::Close"; if (list_.queries_open()) invalid_ = true; + if (in_render_pass_) invalid_ = true; // a pass begun and not ended (WARP: E_FAIL); a suspended one is fine if (!list_.close()) return d3d12_trace::result(method, E_FAIL); stop_recording(); return d3d12_trace::result(method, invalid_ ? E_INVALIDARG : S_OK); @@ -233,6 +234,8 @@ class GraphicsCommandList final if (!list_.reset()) return d3d12_trace::result(method, E_FAIL); // D3D12 resets only closed lists record_into(command_allocator); invalid_ = false; + in_render_pass_ = pass_suspended_ = false; + pass_resolves_.clear(); calls_.clear(); release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default @@ -436,6 +439,90 @@ class GraphicsCommandList final void STDMETHODCALLTYPE OMSetRenderTargets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); + if (in_render_pass_) return check(false); // a render pass binds its own targets (WARP) + bind_targets(count, targets, single_range, depth); + } + + // ID3D12GraphicsCommandList4 render passes (D3D-27; docs/d3d12_vulkan.md section 4.3, "Render passes"), emulated + // on the list's own commands as the PC runtime does for a driver at RenderPassesTier 0: BeginRenderPass binds the + // pass's targets and runs its CLEAR beginning accesses, EndRenderPass runs its RESOLVE ending accesses. DISCARD, + // PRESERVE (and the PRESERVE_LOCAL forms) and NO_ACCESS leave the contents as they are, which every one of them + // allows. A SUSPENDING pass keeps its ending accesses for the pass that resumes it, and a RESUMING pass does not + // run its beginning accesses again. The recording rules are WARP's, measured by d3d12_render_pass_test: no + // nesting, no End without a Begin, at most 8 targets, direct lists only, Close fails while a pass is open, + // copies, resolves, clears, DiscardResource and OMSetRenderTargets fail inside a pass (barriers do not), and a + // pass that follows a suspended one must resume it with no command recorded in between. + void STDMETHODCALLTYPE BeginRenderPass(UINT count, const D3D12_RENDER_PASS_RENDER_TARGET_DESC* targets, + const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* depth, + D3D12_RENDER_PASS_FLAGS flags) override { + d3d12_trace::record("ID3D12GraphicsCommandList4::BeginRenderPass"); + if (list_.closed()) return; + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); + if (in_render_pass_ || count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT || (count && !targets)) + return check(false); + const bool resuming = (flags & D3D12_RENDER_PASS_FLAG_RESUMING_PASS) != 0; + if (pass_suspended_) { + if (!resuming || list_.commands().size() != suspended_at_) check(false); + pass_suspended_ = false; + } + in_render_pass_ = true; + pass_flags_ = flags; + pass_resolves_.clear(); + + std::array handles{}; + for (UINT i = 0; i < count; ++i) handles[i] = targets[i].cpuDescriptor; + const D3D12_CPU_DESCRIPTOR_HANDLE ds = depth ? depth->cpuDescriptor : D3D12_CPU_DESCRIPTOR_HANDLE{}; + bind_targets(count, handles.data(), FALSE, ds.ptr ? &ds : nullptr); + + for (UINT i = 0; i < count; ++i) keep_resolve(targets[i].EndingAccess); + if (depth) { + keep_resolve(depth->DepthEndingAccess); + keep_resolve(depth->StencilEndingAccess); + } + if (resuming) return; // the suspended pass ran these already + + for (UINT i = 0; i < count; ++i) { + const auto& access = targets[i].BeginningAccess; + if (access.Type != D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR || !handles[i].ptr) continue; + const FLOAT* color = access.Clear.ClearValue.Color; + check(list_.clear_render_target(*reinterpret_cast(handles[i].ptr), + {color[0], color[1], color[2], color[3]}, {})); + } + if (ds.ptr) { + UINT clear = 0; + if (depth->DepthBeginningAccess.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR) + clear |= D3D12_CLEAR_FLAG_DEPTH; + if (depth->StencilBeginningAccess.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR) + clear |= D3D12_CLEAR_FLAG_STENCIL; + if (clear) + check(list_.clear_depth_stencil(*reinterpret_cast(ds.ptr), clear, + depth->DepthBeginningAccess.Clear.ClearValue.DepthStencil.Depth, + depth->StencilBeginningAccess.Clear.ClearValue.DepthStencil.Stencil, + {})); + } + } + + void STDMETHODCALLTYPE EndRenderPass() override { + d3d12_trace::record("ID3D12GraphicsCommandList4::EndRenderPass"); + if (list_.closed()) return; + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT || !in_render_pass_) return check(false); + in_render_pass_ = false; + if (pass_flags_ & D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS) { + pass_suspended_ = true; + suspended_at_ = list_.commands().size(); + return; // the resuming pass ends with these accesses + } + for (PassResolve& resolve : pass_resolves_) { + for (auto& where : resolve.where) + resolve_region(resolve.dst, where.DstSubresource, where.DstX, where.DstY, resolve.src, + where.SrcSubresource, &where.SrcRect, resolve.format, resolve.mode); + } + pass_resolves_.clear(); + } + +private: + void bind_targets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, + const D3D12_CPU_DESCRIPTOR_HANDLE* depth) { if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); render_targets_.fill({}); render_target_count_ = count; @@ -447,6 +534,25 @@ class GraphicsCommandList final depth_ = depth && depth->ptr ? *reinterpret_cast(depth->ptr) : leonida::TargetView{}; } + // A RESOLVE ending access, copied at BeginRenderPass (the caller's arrays need not outlive the call) and run by + // EndRenderPass. PreserveResolveSource changes nothing here: the source keeps its contents either way. + struct PassResolve { + ID3D12Resource* src; + ID3D12Resource* dst; + DXGI_FORMAT format; + D3D12_RESOLVE_MODE mode; + std::vector where; + }; + void keep_resolve(const D3D12_RENDER_PASS_ENDING_ACCESS& access) { + if (access.Type != D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE) return; + const auto& r = access.Resolve; + if (!r.pSrcResource || !r.pDstResource || (r.SubresourceCount && !r.pSubresourceParameters)) + return check(false); + pass_resolves_.push_back({r.pSrcResource, r.pDstResource, r.Format, r.ResolveMode, + {r.pSubresourceParameters, r.pSubresourceParameters + r.SubresourceCount}}); + } + +public: void STDMETHODCALLTYPE OMSetBlendFactor(const FLOAT factor[4]) override { if (list_.closed()) return; const std::array value = factor ? std::array{factor[0], factor[1], factor[2], factor[3]} @@ -557,6 +663,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE CopyBufferRegion(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, UINT64 src_offset, UINT64 bytes) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyBufferRegion"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); check(list_.copy_buffer({resource_id(dst), dst_offset, resource_id(src), src_offset, bytes})); } @@ -565,6 +672,7 @@ class GraphicsCommandList final const D3D12_TILE_REGION_SIZE* size, ID3D12Resource* linear, UINT64 linear_offset, D3D12_TILE_COPY_FLAGS flags) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyTiles"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) const auto direction = flags & ~D3D12_TILE_COPY_FLAG_NO_HAZARD; const bool to_linear = direction == D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER; const auto grid = tile_grid(tiled); @@ -612,6 +720,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE CopyTextureRegion(const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyTextureRegion"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!dst || !src) return check(false); leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; @@ -621,6 +730,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyResource"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (dst && dst == src) { // A self-copy on a DEFAULT heap is a no-op, but an UPLOAD/READBACK resource still cannot @@ -637,6 +747,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE ResolveSubresource(ID3D12Resource* dst, UINT dst_subresource, ID3D12Resource* src, UINT src_subresource, DXGI_FORMAT format) override { d3d12_trace::record("ID3D12GraphicsCommandList::ResolveSubresource"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); const auto integer_color = [](ID3D12Resource* resource) { if (!resource) return false; @@ -655,6 +766,13 @@ class GraphicsCommandList final ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { d3d12_trace::record("ID3D12GraphicsCommandList1::ResolveSubresourceRegion"); + if (in_render_pass_) return check(false); + resolve_region(dst, dst_subresource, x, y, src, src_subresource, rect, format, mode); + } + + // ResolveSubresourceRegion without the trace line; a render pass's RESOLVE ending access runs through it too. + void resolve_region(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, ID3D12Resource* src, + UINT src_subresource, const D3D12_RECT* rect, DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) { if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); leonida::ResolveRegion region{x, y, std::nullopt}; if (mode != D3D12_RESOLVE_MODE_AVERAGE || !color_resolve_format_matches(format, dst, src)) { @@ -696,6 +814,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE view, const FLOAT color[4], UINT count, const D3D12_RECT* rects) override { d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); check(list_.clear_render_target(*reinterpret_cast(view.ptr), @@ -706,6 +825,7 @@ class GraphicsCommandList final FLOAT depth, UINT8 stencil, UINT count, const D3D12_RECT* rects) override { d3d12_trace::record("ID3D12GraphicsCommandList::ClearDepthStencilView"); + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr) return check(false); check(list_.clear_depth_stencil(*reinterpret_cast(view.ptr), u(flags), depth, @@ -714,6 +834,7 @@ class GraphicsCommandList final // A null region discards the whole resource. Not allowed in a bundle. void STDMETHODCALLTYPE DiscardResource(ID3D12Resource* resource, const D3D12_DISCARD_REGION* region) override { + if (in_render_pass_) return check(false); // not inside a render pass (WARP) if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!region) return check(list_.discard({resource_id(resource), 0, 0, false, true})); if (region->NumRects && !region->pRects) return check(false); @@ -1251,6 +1372,13 @@ class GraphicsCommandList final CommandAllocator* allocator_ = nullptr; // referenced while the list is open leonida::CommandList list_; bool invalid_ = false; + // Render passes (BeginRenderPass). pass_suspended_: the last pass ended with SUSPENDING_PASS, at suspended_at_ + // recorded commands; the next pass must resume it with nothing recorded in between. + bool in_render_pass_ = false; + D3D12_RENDER_PASS_FLAGS pass_flags_ = D3D12_RENDER_PASS_FLAG_NONE; + std::vector pass_resolves_; + bool pass_suspended_ = false; + std::size_t suspended_at_ = 0; UINT front_stencil_ref_ = 0; UINT back_stencil_ref_ = 0; RootState compute_; diff --git a/runtime/test/d3d12_render_pass_test.cpp b/runtime/test/d3d12_render_pass_test.cpp new file mode 100644 index 0000000000..ac79024743 --- /dev/null +++ b/runtime/test/d3d12_render_pass_test.cpp @@ -0,0 +1,608 @@ +// D3D12 render passes (ID3D12GraphicsCommandList4::BeginRenderPass / EndRenderPass, D3D-27) on the layer, compared +// with Windows' own D3D12 over WARP (no debug layer). Two groups: +// data each case records a render pass whose beginning and ending accesses write the targets (CLEAR on colour, +// depth and stencil separately, PRESERVE, a RESOLVE ending into a region and into the whole texture, +// SUSPENDING/RESUMING), runs it, copies every plane into a readback buffer and compares the bytes with WARP. +// close each case records a few calls on a fresh list and only closes it; the layer is held to WARP's verdict +// (Close succeeds or fails; both codes are printed, as in d3d12_close_parity_test). +// The layer emulates render passes on its own commands (RenderPassesTier 0), which is what the PC runtime does for a +// driver at tier 0, so WARP is the reference for both the bytes and the recording rules. No game data or shaders. +// Needs a Vulkan GPU (exit 77 without one) and Microsoft's WARP (exit 77 under Wine, whose host D3D12 is vkd3d). +#include "vk_test_device.h" +#include "host_wine.h" +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#include +#include +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, " line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { +// Owns one reference. Movable, not copyable, so a vector of them can grow without releasing twice. +template +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(Ref&& other) noexcept : p(other.p) { other.p = nullptr; } + Ref& operator=(Ref&&) = delete; + Ref(const Ref&) = delete; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; +struct Event { + HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); + ~Event() { if (handle) CloseHandle(handle); } +}; + +constexpr UINT kWidth = 5, kHeight = 3; // odd sizes expose a wrong treatment of footprint padding +constexpr DXGI_FORMAT kRgba = DXGI_FORMAT_R8G8B8A8_UNORM; +constexpr DXGI_FORMAT kFloat = DXGI_FORMAT_R32_FLOAT; +constexpr DXGI_FORMAT kDepth = DXGI_FORMAT_D24_UNORM_S8_UINT; + +D3D12_RESOURCE_DESC texture_desc(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, UINT samples = 1) { + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = kWidth; + texture.Height = kHeight; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = format; + texture.SampleDesc.Count = samples; + texture.Flags = flags; + return texture; +} + +void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* image, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = image; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; + barrier.Transition.StateAfter = after; + list->ResourceBarrier(1, &barrier); +} + +// One subresource copied into a readback buffer, read after the list has run. +struct Plane { + Ref buffer; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; + UINT64 total = 0; + unsigned bytes = 0; // per texel in this plane +}; + +// Everything one case creates on one device: a direct queue and list, the textures and their views. +struct Scene { + ID3D12Device* device = nullptr; + Ref queue; + Ref allocator; + Ref list; + Ref list4; + Ref fence; + Ref rtv_heap, dsv_heap; + UINT rtv_size = 0; + std::vector> textures; + std::vector planes; + + bool create(ID3D12Device* d, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) { + device = d; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list4.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC rtv{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 9, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC dsv{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&rtv, IID_PPV_ARGS(&rtv_heap.p)))); + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&dsv, IID_PPV_ARGS(&dsv_heap.p)))); + rtv_size = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + textures.reserve(16); + return true; + } + D3D12_CPU_DESCRIPTOR_HANDLE rtv(UINT slot) const { + D3D12_CPU_DESCRIPTOR_HANDLE handle = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T(slot) * rtv_size; + return handle; + } + D3D12_CPU_DESCRIPTOR_HANDLE dsv() const { return dsv_heap->GetCPUDescriptorHandleForHeapStart(); } + + // A texture in `state`; a render target gets an RTV in `slot`, a depth texture the one DSV. + ID3D12Resource* texture(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state, + UINT samples = 1, int slot = -1) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + const D3D12_RESOURCE_DESC desc = texture_desc(format, flags, samples); + textures.emplace_back(); + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&textures.back().p)))) + return nullptr; + ID3D12Resource* resource = textures.back().p; + if (slot >= 0) device->CreateRenderTargetView(resource, nullptr, rtv(UINT(slot))); + if (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) device->CreateDepthStencilView(resource, nullptr, dsv()); + return resource; + } + + // Records the copy of one subresource of a 1-sample texture (in COPY_SOURCE) into a new readback buffer. + bool copy_out(ID3D12Resource* image, DXGI_FORMAT format, UINT subresource, unsigned bytes) { + planes.emplace_back(); + Plane& plane = planes.back(); + plane.bytes = bytes; + const D3D12_RESOURCE_DESC texture = texture_desc(format, D3D12_RESOURCE_FLAG_NONE); + device->GetCopyableFootprints(&texture, subresource, 1, 0, &plane.placed, nullptr, nullptr, &plane.total); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = plane.total; + buffer.Height = buffer.SampleDesc.Count = 1; + buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_READBACK; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&plane.buffer.p)))); + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = image; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = subresource; + dst.pResource = plane.buffer.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = plane.placed; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + return true; + } + + // Runs the list and reads every plane back, tightly packed. + bool execute(std::vector>& out) { + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + Event event; + CHECK(event.handle); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); + CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); + for (Plane& plane : planes) { + void* mapped = nullptr; + const D3D12_RANGE range{0, SIZE_T(plane.total)}; + CHECK(SUCCEEDED(plane.buffer->Map(0, &range, &mapped)) && mapped); + std::vector pixels(std::size_t(kWidth) * kHeight * plane.bytes); + for (UINT y = 0; y < kHeight; ++y) + std::memcpy(pixels.data() + std::size_t(y) * kWidth * plane.bytes, + static_cast(mapped) + std::size_t(y) * plane.placed.Footprint.RowPitch, + std::size_t(kWidth) * plane.bytes); + const D3D12_RANGE none{}; + plane.buffer->Unmap(0, &none); + out.push_back(std::move(pixels)); + } + return true; + } +}; + +D3D12_RENDER_PASS_BEGINNING_ACCESS begin_clear(DXGI_FORMAT format, const std::array& color) { + D3D12_RENDER_PASS_BEGINNING_ACCESS access{}; + access.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR; + access.Clear.ClearValue.Format = format; + std::memcpy(access.Clear.ClearValue.Color, color.data(), sizeof(float) * 4); + return access; +} +D3D12_RENDER_PASS_BEGINNING_ACCESS begin_clear_depth(float depth, UINT8 stencil) { + D3D12_RENDER_PASS_BEGINNING_ACCESS access{}; + access.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR; + access.Clear.ClearValue.Format = kDepth; + access.Clear.ClearValue.DepthStencil = {depth, stencil}; + return access; +} +D3D12_RENDER_PASS_BEGINNING_ACCESS begin(D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE type) { + D3D12_RENDER_PASS_BEGINNING_ACCESS access{}; + access.Type = type; + return access; +} +D3D12_RENDER_PASS_ENDING_ACCESS end(D3D12_RENDER_PASS_ENDING_ACCESS_TYPE type) { + D3D12_RENDER_PASS_ENDING_ACCESS access{}; + access.Type = type; + return access; +} +D3D12_RENDER_PASS_RENDER_TARGET_DESC target(D3D12_CPU_DESCRIPTOR_HANDLE handle, + const D3D12_RENDER_PASS_BEGINNING_ACCESS& first, + const D3D12_RENDER_PASS_ENDING_ACCESS& last) { + return {handle, first, last}; +} +const auto kPreserve = begin(D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE); +const auto kKeep = end(D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE); + +constexpr std::array kBefore{0.25f, 0.5f, 0.75f, 1.0f}; +constexpr std::array kCleared{1.0f, 0.0f, 0.5f, 0.25f}; +constexpr std::array kSecond{0.0f, 1.0f, 0.125f, 0.5f}; +constexpr std::array kFloatBefore{-3.5f, 0, 0, 0}; + +// ---- data cases --------------------------------------------------------------------------------------------------- + +// Colour target 0 is cleared by the pass, colour target 1 keeps what a clear before the pass wrote; the depth plane +// is cleared by the pass while the stencil plane keeps its value, or the other way round. +bool colour_and_depth(Scene& s, bool clear_depth_plane) { + ID3D12Resource* rt0 = s.texture(kRgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, 1, 0); + ID3D12Resource* rt1 = s.texture(kFloat, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, 1, 1); + ID3D12Resource* ds = s.texture(kDepth, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + CHECK(rt0 && rt1 && ds); + s.list->ClearRenderTargetView(s.rtv(0), kBefore.data(), 0, nullptr); + s.list->ClearRenderTargetView(s.rtv(1), kFloatBefore.data(), 0, nullptr); + s.list->ClearDepthStencilView(s.dsv(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.5f, 7, 0, nullptr); + const D3D12_RENDER_PASS_RENDER_TARGET_DESC targets[] = { + target(s.rtv(0), begin_clear(kRgba, kCleared), kKeep), + target(s.rtv(1), kPreserve, kKeep), + }; + D3D12_RENDER_PASS_DEPTH_STENCIL_DESC depth{}; + depth.cpuDescriptor = s.dsv(); + depth.DepthBeginningAccess = clear_depth_plane ? begin_clear_depth(0.25f, 0x5A) : kPreserve; + depth.StencilBeginningAccess = clear_depth_plane ? kPreserve : begin_clear_depth(0.0f, 0xA5); + depth.DepthEndingAccess = depth.StencilEndingAccess = kKeep; + s.list4->BeginRenderPass(2, targets, &depth, D3D12_RENDER_PASS_FLAG_NONE); + s.list4->EndRenderPass(); + transition(s.list.p, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition(s.list.p, rt1, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition(s.list.p, ds, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + return s.copy_out(rt0, kRgba, 0, 4) && s.copy_out(rt1, kFloat, 0, 4) && s.copy_out(ds, kDepth, 0, 4) && + s.copy_out(ds, kDepth, 1, 1); +} +bool depth_cleared(Scene& s) { return colour_and_depth(s, true); } +bool stencil_cleared(Scene& s) { return colour_and_depth(s, false); } + +// Two passes on the same target in one list: the second pass's clear is the one left. +bool two_passes(Scene& s) { + ID3D12Resource* rt = s.texture(kRgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, 1, 0); + CHECK(rt); + const auto first = target(s.rtv(0), begin_clear(kRgba, kCleared), kKeep); + const auto second = target(s.rtv(0), begin_clear(kRgba, kSecond), kKeep); + s.list4->BeginRenderPass(1, &first, nullptr, D3D12_RENDER_PASS_FLAG_NONE); + s.list4->EndRenderPass(); + s.list4->BeginRenderPass(1, &second, nullptr, D3D12_RENDER_PASS_FLAG_NONE); + s.list4->EndRenderPass(); + transition(s.list.p, rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + return s.copy_out(rt, kRgba, 0, 4); +} + +// A suspended pass resumed later in the list: what each pass's beginning access leaves. +bool suspend_resume(Scene& s) { + ID3D12Resource* rt = s.texture(kRgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, 1, 0); + CHECK(rt); + const auto first = target(s.rtv(0), begin_clear(kRgba, kCleared), kKeep); + const auto second = target(s.rtv(0), begin_clear(kRgba, kSecond), kKeep); + s.list4->BeginRenderPass(1, &first, nullptr, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + s.list4->EndRenderPass(); + s.list4->BeginRenderPass(1, &second, nullptr, D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + s.list4->EndRenderPass(); + transition(s.list.p, rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + return s.copy_out(rt, kRgba, 0, 4); +} + +// A 4-sample target cleared by the pass and resolved by its ending access into a 1-sample texture: into a region +// (source rectangle and destination offset), or the whole texture. +bool resolve(Scene& s, bool region) { + ID3D12Resource* msaa = s.texture(kRgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, 4, 0); + ID3D12Resource* dst = s.texture(kRgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, 1, 1); + CHECK(msaa && dst); + s.list->ClearRenderTargetView(s.rtv(1), kBefore.data(), 0, nullptr); + transition(s.list.p, dst, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_DEST); + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS where{}; + if (region) { + where.DstX = 1; + where.DstY = 1; + where.SrcRect = {0, 0, 3, 2}; + } else { + where.SrcRect = {0, 0, LONG(kWidth), LONG(kHeight)}; + } + D3D12_RENDER_PASS_ENDING_ACCESS last{}; + last.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE; + last.Resolve.pSrcResource = msaa; + last.Resolve.pDstResource = dst; + last.Resolve.SubresourceCount = 1; + last.Resolve.pSubresourceParameters = &where; + last.Resolve.Format = kRgba; + last.Resolve.ResolveMode = D3D12_RESOLVE_MODE_AVERAGE; + last.Resolve.PreserveResolveSource = region ? FALSE : TRUE; + const auto desc = target(s.rtv(0), begin_clear(kRgba, kCleared), last); + s.list4->BeginRenderPass(1, &desc, nullptr, D3D12_RENDER_PASS_FLAG_NONE); + s.list4->EndRenderPass(); + transition(s.list.p, dst, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + return s.copy_out(dst, kRgba, 0, 4); +} +bool resolve_region(Scene& s) { return resolve(s, true); } +bool resolve_whole(Scene& s) { return resolve(s, false); } + +struct DataCase { + const char* name; + bool (*record)(Scene&); +}; +const DataCase kDataCases[] = { + {"colour CLEAR + PRESERVE, depth CLEAR, stencil PRESERVE", depth_cleared}, + {"colour CLEAR + PRESERVE, depth PRESERVE, stencil CLEAR", stencil_cleared}, + {"two passes on one target", two_passes}, + {"SUSPENDING then RESUMING pass", suspend_resume}, + {"RESOLVE ending into a region", resolve_region}, + {"RESOLVE ending into the whole texture", resolve_whole}, +}; + +// Close's result and every plane, or false when the device could not set the case up. +bool run_data(ID3D12Device* device, const DataCase& c, HRESULT& closed, std::vector>& out) { + Scene s; + CHECK(s.create(device)); + CHECK(c.record(s)); + closed = s.list->Close(); + if (FAILED(closed)) return true; // nothing to run + return s.execute(out); +} + +// ---- close cases -------------------------------------------------------------------------------------------------- + +struct CloseScene { + Scene s; + ID3D12Resource* rt = nullptr; + ID3D12Resource* other = nullptr; + ID3D12Resource* depth = nullptr; + ID3D12Resource* buffer = nullptr; + ID3D12Resource* buffer2 = nullptr; + D3D12_RENDER_PASS_RENDER_TARGET_DESC desc{}; + + ID3D12Resource* make_buffer() { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC desc_buffer{}; + desc_buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc_buffer.Width = 256; + desc_buffer.Height = desc_buffer.SampleDesc.Count = 1; + desc_buffer.DepthOrArraySize = desc_buffer.MipLevels = 1; + desc_buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + s.textures.emplace_back(); + if (FAILED(s.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc_buffer, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&s.textures.back().p)))) + return nullptr; + return s.textures.back().p; + } +}; + +using Recorder = std::function; +struct CloseCase { + const char* name; + Recorder record; + bool bundle = false; +}; + +void pass(CloseScene& c, D3D12_RENDER_PASS_FLAGS flags = D3D12_RENDER_PASS_FLAG_NONE) { + c.s.list4->BeginRenderPass(1, &c.desc, nullptr, flags); +} + +const CloseCase kCloseCases[] = { + {"Begin, End", [](CloseScene& c) { pass(c); c.s.list4->EndRenderPass(); }}, + {"Begin without End", [](CloseScene& c) { pass(c); }}, + {"End without Begin", [](CloseScene& c) { c.s.list4->EndRenderPass(); }}, + {"Begin, Begin, End", [](CloseScene& c) { pass(c); pass(c); c.s.list4->EndRenderPass(); }}, + {"Begin, End, End", [](CloseScene& c) { pass(c); c.s.list4->EndRenderPass(); c.s.list4->EndRenderPass(); }}, + {"Begin with 9 render targets", [](CloseScene& c) { + D3D12_RENDER_PASS_RENDER_TARGET_DESC nine[9]; + for (auto& t : nine) t = c.desc; + c.s.list4->BeginRenderPass(9, nine, nullptr, D3D12_RENDER_PASS_FLAG_NONE); + c.s.list4->EndRenderPass(); + }}, + {"Begin with no targets, End", [](CloseScene& c) { + c.s.list4->BeginRenderPass(0, nullptr, nullptr, D3D12_RENDER_PASS_FLAG_NONE); + c.s.list4->EndRenderPass(); + }}, + {"OMSetRenderTargets inside a pass", [](CloseScene& c) { + pass(c); + const auto handle = c.s.rtv(0); + c.s.list->OMSetRenderTargets(1, &handle, FALSE, nullptr); + c.s.list4->EndRenderPass(); + }}, + {"ClearRenderTargetView inside a pass", [](CloseScene& c) { + pass(c); + c.s.list->ClearRenderTargetView(c.s.rtv(0), kBefore.data(), 0, nullptr); + c.s.list4->EndRenderPass(); + }}, + {"ResourceBarrier inside a pass", [](CloseScene& c) { + pass(c); + transition(c.s.list.p, c.other, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + c.s.list4->EndRenderPass(); + }}, + {"CopyResource inside a pass", [](CloseScene& c) { + pass(c); + c.s.list->CopyResource(c.other, c.rt); + c.s.list4->EndRenderPass(); + }}, + {"CopyTextureRegion inside a pass", [](CloseScene& c) { + pass(c); + D3D12_TEXTURE_COPY_LOCATION dst{}, src{}; + dst.pResource = c.other; + src.pResource = c.rt; + dst.Type = src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + c.s.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + c.s.list4->EndRenderPass(); + }}, + {"ClearDepthStencilView inside a pass", [](CloseScene& c) { + pass(c); + c.s.list->ClearDepthStencilView(c.s.dsv(), D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + c.s.list4->EndRenderPass(); + }}, + {"CopyBufferRegion inside a pass", [](CloseScene& c) { + pass(c); + c.s.list->CopyBufferRegion(c.buffer2, 0, c.buffer, 0, 256); + c.s.list4->EndRenderPass(); + }}, + {"ResolveSubresourceRegion inside a pass", [](CloseScene& c) { + pass(c); + ID3D12GraphicsCommandList1* list1 = nullptr; + if (SUCCEEDED(c.s.list->QueryInterface(IID_PPV_ARGS(&list1)))) { + list1->ResolveSubresourceRegion(c.other, 0, 0, 0, c.rt, 0, nullptr, kRgba, D3D12_RESOLVE_MODE_AVERAGE); + list1->Release(); + } + c.s.list4->EndRenderPass(); + }}, + {"DiscardResource inside a pass", [](CloseScene& c) { + pass(c); + c.s.list->DiscardResource(c.rt, nullptr); + c.s.list4->EndRenderPass(); + }}, + {"ResolveSubresource inside a pass", [](CloseScene& c) { + pass(c); + c.s.list->ResolveSubresource(c.other, 0, c.rt, 0, kRgba); + c.s.list4->EndRenderPass(); + }}, + {"ResourceBarrier between SUSPENDING and RESUMING", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + c.s.list4->EndRenderPass(); + transition(c.s.list.p, c.other, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + pass(c, D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + c.s.list4->EndRenderPass(); + }}, + {"SUSPENDING, then a pass that does not resume", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + c.s.list4->EndRenderPass(); + pass(c); + c.s.list4->EndRenderPass(); + }}, + {"SUSPENDING, then OMSetRenderTargets", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + c.s.list4->EndRenderPass(); + const auto handle = c.s.rtv(0); + c.s.list->OMSetRenderTargets(1, &handle, FALSE, nullptr); + }}, + {"a copy after a pass ends", [](CloseScene& c) { + pass(c); + c.s.list4->EndRenderPass(); + c.s.list->CopyResource(c.other, c.rt); + }}, + {"Begin, End, Reset-free second pass with RESUMING and SUSPENDING", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + c.s.list4->EndRenderPass(); + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS | D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + c.s.list4->EndRenderPass(); + pass(c, D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + c.s.list4->EndRenderPass(); + }}, + {"RESUMING with no suspended pass", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + c.s.list4->EndRenderPass(); + }}, + {"SUSPENDING and never resumed", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + c.s.list4->EndRenderPass(); + }}, + {"SUSPENDING, a copy, RESUMING", [](CloseScene& c) { + pass(c, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + c.s.list4->EndRenderPass(); + c.s.list->CopyResource(c.other, c.rt); + pass(c, D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + c.s.list4->EndRenderPass(); + }}, + {"Begin, End in a bundle", [](CloseScene& c) { pass(c); c.s.list4->EndRenderPass(); }, true}, +}; + +HRESULT run_close(ID3D12Device* device, const CloseCase& c) { + CloseScene scene; + const auto type = c.bundle ? D3D12_COMMAND_LIST_TYPE_BUNDLE : D3D12_COMMAND_LIST_TYPE_DIRECT; + if (!scene.s.create(device, type)) return E_UNEXPECTED; + scene.rt = scene.s.texture(kRgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET, 1, 0); + scene.other = scene.s.texture(kRgba, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON); + scene.depth = scene.s.texture(kDepth, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + scene.buffer = scene.make_buffer(); + scene.buffer2 = scene.make_buffer(); + if (!scene.rt || !scene.other || !scene.depth || !scene.buffer || !scene.buffer2) return E_UNEXPECTED; + scene.desc = target(scene.s.rtv(0), begin_clear(kRgba, kCleared), kKeep); + c.record(scene); + return scene.s.list->Close(); +} + +void report(const char* name, std::size_t plane, const std::vector& actual, + const std::vector& expected) { + for (std::size_t b = 0; b < actual.size() && b < expected.size(); ++b) { + if (actual[b] != expected[b]) { + std::printf("DIFF %s: plane %zu byte %zu: layer %02x, WARP %02x\n", name, plane, b, unsigned(actual[b]), + unsigned(expected[b])); + return; + } + } + std::printf("DIFF %s: plane %zu sizes %zu and %zu\n", name, plane, actual.size(), expected.size()); +} +} // namespace + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); // every line reaches the log, even if a case crashes the process + if (hostwine::host_is_wine()) return 77; // the reference is Microsoft's runtime over WARP + vktest::Device vk; + const auto device_status = vk.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + const unsigned errors_before = vk.validation_errors(); + unsigned matched = 0, differ = 0; + { + Ref ours, host; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; + Ref factory; + Ref warp; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || + FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || + FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { + std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); + return 1; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS5 options{}; + if (SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &options, sizeof(options)))) + std::printf("WARP RenderPassesTier %d\n", int(options.RenderPassesTier)); + + for (const DataCase& c : kDataCases) { + HRESULT want_close = E_UNEXPECTED, got_close = E_UNEXPECTED; + std::vector> expected, actual; + if (!run_data(host.p, c, want_close, expected)) { + std::printf("SKIP %s: WARP could not set it up\n", c.name); + continue; + } + const bool ran = run_data(ours.p, c, got_close, actual); + bool same = ran && SUCCEEDED(want_close) == SUCCEEDED(got_close) && actual.size() == expected.size(); + if (!ran) std::printf("FAIL %s: the layer could not set it up\n", c.name); + else if (SUCCEEDED(want_close) != SUCCEEDED(got_close)) + std::printf("DIFF %s: Close layer 0x%08lx, WARP 0x%08lx\n", c.name, unsigned long(got_close), + unsigned long(want_close)); + for (std::size_t p = 0; same && p < expected.size(); ++p) { + if (actual[p] != expected[p]) { + report(c.name, p, actual[p], expected[p]); + same = false; + } + } + if (same) { + ++matched; + std::printf("ok %s (%zu planes)\n", c.name, expected.size()); + } else { + ++differ; + } + } + for (const CloseCase& c : kCloseCases) { + const HRESULT want = run_close(host.p, c); + const HRESULT got = run_close(ours.p, c); + const bool same = SUCCEEDED(want) == SUCCEEDED(got); + std::printf("%s Close after %s: layer 0x%08lx, WARP 0x%08lx\n", same ? "ok " : "DIFF", c.name, + unsigned long(got), unsigned long(want)); + if (same) ++matched; + else ++differ; + } + } // Destroy the D3D12 objects before checking the Vulkan validation counter. + std::printf("render passes: %u matched WARP, %u differ\n", matched, differ); + if (differ) return 1; + if (vk.validation_errors() != errors_before) return 1; + return 0; +}