From 285c7735b63d79a63b93844f18f1740dc7cb0e5d Mon Sep 17 00:00:00 2001 From: requiemsnkrp <317543573+requiemsnkrp@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:54:10 +0100 Subject: [PATCH] Replay: a draw skips the binds and sets still bound from the last draw (D3D-393) emit kept no memory of what it had bound, so every draw bound its pipeline, set 0 and 144 bytes of push constants, set viewport, scissor, topology, primitive restart, both stencil references and blend constants, and bound its vertex and index buffers: 16-17 Vulkan calls per draw. detail::BoundDrawState remembers what the command buffer holds and a draw records only what differs. It carries across the per-draw rendering scopes (Vulkan keeps bound state for the command buffer's life; begin/end rendering, barriers, transfers and vkCmdClearAttachments leave it alone). It forgets: - the vertex strides when a pipeline without vertex input is bound (its static stride state invalidates them; VUID-vkCmdDraw-pStrides-04913 without the re-bind); - set 0 and push constants when the push-constant stages differ (layout compatibility); - everything at a command that binds or runs a helper (dispatch, indirect dispatch, predicate capture, predicated or depth24 copy, query resolve, acceleration structures, any command kind added later: keeps_draw_state lists the ones that keep it), and at the start of every emit. replay_cpu_bench (no-op entry points, median of 7 runs): 16 -> 7 calls per draw, 17 -> 8 per indexed draw, frame 8.30 -> 4.65 calls per command; emit 136.0 -> 138.2 ns per draw (the skipped calls are no-ops there). On an RTX 3060's driver the eight dynamic-state and push calls a repeated draw no longer records cost ~101 ns per draw to record (scratch recorder, not committed). replay_draw_state_test counts the calls for each rule with mocks. d3d12_draw_state_test renders 6 scenarios (state changing and kept from draw to draw; clears, a copy, a barrier, a dispatch, a binary-occlusion resolve, a bundle and a pipeline without vertex input between draws) on the layer, the default adapter and WARP: same grids, and every pixel byte-identical to main's output; validation and synchronization validation clean. ctest 173/173 (171 before plus the two new tests); d3d12_|vk_|replay_ with LEONIDA_VK_VALIDATION=1: 89/89. AI-assisted. --- docs/d3d12_vulkan.md | 24 + runtime/CMakeLists.txt | 21 + runtime/src/vulkan_replay.h | 181 +++++- runtime/test/d3d12_draw_state_test.cpp | 702 ++++++++++++++++++++++++ runtime/test/replay_draw_state_test.cpp | 504 +++++++++++++++++ 5 files changed, 1414 insertions(+), 18 deletions(-) create mode 100644 runtime/test/d3d12_draw_state_test.cpp create mode 100644 runtime/test/replay_draw_state_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9de1527b94..a5c00c611c 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -770,6 +770,30 @@ The compute path, end to end: dynamic-rendering scope. Its layer count is the smallest layer count of the bound views. - **Viewport:** it is flipped (negative height), because translated vertex shaders write D3D clip coordinates; front-face winding then matches D3D12's. + - **Unchanged state** (D3D-393): a draw skips each bind and set whose value an earlier draw of the same list left + bound: the pipeline, set 0, the push constants (compared as their 144 bytes), viewport, scissor, topology, + primitive restart, both stencil references, blend constants, each vertex-buffer slot and the index buffer + (`detail::BoundDrawState`). Vulkan keeps bound state for the life of the command buffer, per bind point, and a + rendering scope's begin and end, a barrier, a transfer or `vkCmdClearAttachments` leave it alone, so it carries + from one draw's scope to the next. What does disturb it: + - Binding a pipeline replaces the state it does not declare dynamic. Every PSO declares the six dynamic states a + draw sets, and the vertex-input stride when it has vertex bindings, so only a PSO without vertex input makes + the vertex buffers bind again after it (the strides they were bound with are invalid then). + - Set 0 and push constants stay valid across layouts compatible for them. Every graphics layout has one + push-constant range, `{push_stages, 0, 144}`, and set 0 is the device's one bindless set, so both are keyed on + the stage flags as well as the value. + - A command that binds, or runs a helper that does, forgets everything: a dispatch, direct or indirect (it pushes + constants with a layout not compatible for push constants with the graphics ones), `SetPredication` on a buffer + (the capture dispatch), a copy through the predicated-copy or depth24 pass, `ResolveQueryData`, the + acceleration-structure commands, and any command kind added later (`detail::keeps_draw_state` names the ones + that keep the state). Each list starts with nothing known, since the caller may record anything between two + lists. + + In `replay_cpu_bench` a draw goes from 16 Vulkan calls to 7 (indexed: 17 to 8), and the frame from 8.30 calls + per command to 4.65. `replay_draw_state_test` counts the calls for each rule with mocks; `d3d12_draw_state_test` + renders draws that change and keep state around clears, a copy, a dispatch, a query resolve, a bundle and a + pipeline without vertex input, on the layer and on the host's D3D12 (default adapter and WARP); without the + re-bind after that pipeline, the validation layer reports `VUID-vkCmdDraw-pStrides-04913`. - Only the first viewport and scissor are used, and primitive restart is not modelled yet. **Resources and heaps:** diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 9dc2a7b66c..b1bf484a1a 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2099,6 +2099,19 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_bundle_forbidden_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_bundle_forbidden COMMAND d3d12_bundle_forbidden_test) set_tests_properties(d3d12_bundle_forbidden PROPERTIES SKIP_RETURN_CODE 77) + # Draw state the replay keeps from one draw to the next or sets again (D3D-393), against the host runtime and + # WARP: state changes between draws, clears, a copy, a dispatch, a query resolve, a bundle and a pipeline + # without vertex input. + add_executable(d3d12_draw_state_test test/d3d12_draw_state_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} + ${LEONIDA_TEST_CS} ${LEONIDA_TEST_VS_FULLSCREEN}) + target_link_libraries(d3d12_draw_state_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_draw_state_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") + target_compile_options(d3d12_draw_state_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_draw_state COMMAND d3d12_draw_state_test) + set_tests_properties(d3d12_draw_state 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") endif() @@ -2287,6 +2300,14 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_query_edges COMMAND replay_query_edges_test) + # Draw state still bound from the last draw is not set again, and is forgotten where it may be disturbed + # (D3D-393), with CPU mocks (no GPU or game data). + add_executable(replay_draw_state_test test/replay_draw_state_test.cpp) + target_link_libraries(replay_draw_state_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_draw_state_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_draw_state COMMAND replay_draw_state_test) # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h). add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp) target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers) diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index d5effb8308..2be77fd76c 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -743,12 +744,17 @@ struct ComputePipeline { // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it // reads. code_base: as for compute (one per pipeline; two stages that both read theirs are refused, question 14). +// Its dynamic state is what a draw sets: viewport, scissor, primitive topology, primitive restart, stencil reference +// and blend constants, and the vertex-input binding stride when vertex_slots is not 0. emit keeps that state from +// one draw to the next across pipeline binds (detail::BoundDrawState). struct GraphicsPipeline { VkPipeline pipeline = VK_NULL_HANDLE; VkPipelineLayout layout = VK_NULL_HANDLE; - VkShaderStageFlags push_stages = 0; // the layout's push-constant range; vkCmdPushConstants must name the same + // The layout's one push-constant range: these stages, the whole ShaderUserData. vkCmdPushConstants must name the + // same, and layouts with the same stages are compatible for push constants. + VkShaderStageFlags push_stages = 0; std::uint64_t code_base = 0; - VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every draw; null: none + VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound before a draw; null: none std::vector color_formats; // by render-target slot VkFormat depth_format = VK_FORMAT_UNDEFINED; VkImageAspectFlags depth_aspects = 0; @@ -2100,6 +2106,84 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf if (tracker) tracker->set(a.id, range, layout); } +// The draw state emit last recorded in the command buffer (D3D-393). A draw skips each bind and set whose value is +// still bound: pipeline, set 0, push constants, the dynamic state, each vertex-buffer slot and the index buffer. +// Vulkan keeps all of it for the life of the command buffer, per bind point; vkCmdBeginRendering and +// vkCmdEndRendering, barriers, transfers and vkCmdClearAttachments leave it alone, so it carries over from one +// draw's rendering scope to the next. What disturbs it, and what is done about it: +// - A graphics pipeline bind replaces the state the pipeline does not declare dynamic. Every pipeline declares +// the dynamic state a draw sets (GraphicsPipeline), so that survives pipeline changes, except the vertex-input +// stride, which a pipeline without vertex slots leaves static: binding one invalidates the strides the buffers +// were bound with, and every slot is bound again after it. +// - Set 0 stays bound across pipelines whose layouts are compatible for set 0 (the same set layout, as the set is +// the same, and the same push-constant range), and push constants across layouts compatible for push constants +// (the same range): both are keyed on push_stages as well as the values. +// - Everything else that may bind: a dispatch (it pushes with a compute layout, not compatible for push constants +// with the graphics ones; a pipeline, set and push constants of the compute bind point should leave the graphics +// ones alone, but nothing is assumed there), a helper the device records (counted dispatch, predicate capture, +// predicated copy, depth24 conversion, query resolves and sums, XDXR), and whatever the caller records between +// two lists. keeps_draw_state names the commands that bind nothing; any other one makes emit forget everything, +// and every emit starts with nothing known. +struct BoundDrawState { + VkPipeline pipeline = VK_NULL_HANDLE; + VkDescriptorSet set = VK_NULL_HANDLE; // set 0, bound with a layout whose push-constant stages are set_stages + VkShaderStageFlags set_stages = 0; + bool pushed = false; + VkShaderStageFlags push_stages = 0; + ShaderUserData push{}; + bool dynamic = false; // the values below are set + VkViewport viewport{}; + VkRect2D scissor{}; + VkPrimitiveTopology topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; + VkBool32 restart = VK_FALSE; + std::uint32_t stencil_front = 0, stencil_back = 0; + std::array blend{}; + std::uint32_t vertex_slots = 0; // bit per slot whose binding below is bound, stride included + std::array vertex_buffers{}; + std::array vertex_offsets{}, vertex_sizes{}, vertex_strides{}; + VkBuffer index_buffer = VK_NULL_HANDLE; // null: none known + VkDeviceSize index_offset = 0; + VkIndexType index_type = VK_INDEX_TYPE_UINT16; + + void forget() { + pipeline = VK_NULL_HANDLE; + set = VK_NULL_HANDLE; + pushed = false; + dynamic = false; + vertex_slots = 0; + index_buffer = VK_NULL_HANDLE; + } +}; + +// Whether a command other than a draw leaves BoundDrawState as it is: it records only barriers, transfers, clears +// (vkCmdClearAttachments neither uses nor sets bound state), resolves, labels, query begins and ends, indirect draws, +// or the end of conditional rendering. Commands that bind or run a helper do not, nor does any kind not named here. +inline bool keeps_draw_state(const Command& command, const Prepared& p) { + return std::visit( + [&](const auto& c) { + using T = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v) + return true; + else if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v) + return p.predicated_copy.empty() && !p.has_depth24; // or a helper dispatch runs + else if constexpr (std::is_same_v) + return !c.buffer; // a new predicate is captured by a helper dispatch + else if constexpr (std::is_same_v) + return c.kind != IndirectKind::dispatch; + else + return false; + }, + command); +} + } // namespace detail // Destination and source of a copy or resolve command. @@ -3106,9 +3190,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); }; + // What earlier draws of this list left bound; the caller may record anything before the list, so nothing yet. + detail::BoundDrawState bound; + for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; const auto& p = prepared.commands[i]; + if (!std::holds_alternative(command) && !detail::keeps_draw_state(command, p)) bound.forget(); if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); continue; @@ -3772,41 +3860,98 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.pStencilAttachment = &depth; vk.begin_rendering(command_buffer, &rendering); + // Each bind or set is skipped when its value is still bound (detail::BoundDrawState). + if (bound.pipeline != d.pipeline) { + vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, d.pipeline); + bound.pipeline = d.pipeline; + if (!graphics.vertex_slots) bound.vertex_slots = 0; // its static strides replace the bound ones + } + if (graphics.bindless_set && + (bound.set != graphics.bindless_set || bound.set_stages != graphics.push_stages)) { + vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.layout, 0, 1, + &graphics.bindless_set, 0, nullptr); + bound.set = graphics.bindless_set; + bound.set_stages = graphics.push_stages; + } ShaderUserData data{}; std::copy(draw->user_data.begin(), draw->user_data.end(), data.s); data.heap_base = vk.heap_base; data.code_base = graphics.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, d.pipeline); - if (graphics.bindless_set) - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.layout, 0, 1, - &graphics.bindless_set, 0, nullptr); - vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); + if (!bound.pushed || bound.push_stages != graphics.push_stages || + std::memcmp(&bound.push, &data, sizeof(data)) != 0) { + vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); + bound.pushed = true; + bound.push_stages = graphics.push_stages; + bound.push = 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; const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; - vk.set_viewport(command_buffer, 0, 1, &viewport); const Rect& s = draw->scissor; const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, {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); - 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()); + const VkBool32 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_TRUE + : VK_FALSE; + // Values compare as bytes: a NaN matches itself, and -0 and +0 differ, so a skip never changes a value. + const bool known = bound.dynamic; + if (!known || std::memcmp(&bound.viewport, &viewport, sizeof(viewport)) != 0) { + vk.set_viewport(command_buffer, 0, 1, &viewport); + bound.viewport = viewport; + } + if (!known || std::memcmp(&bound.scissor, &scissor, sizeof(scissor)) != 0) { + vk.set_scissor(command_buffer, 0, 1, &scissor); + bound.scissor = scissor; + } + if (!known || bound.topology != topology) { + vk.set_primitive_topology(command_buffer, topology); + bound.topology = topology; + } + if (!known || bound.restart != restart) { + vk.set_primitive_restart_enable(command_buffer, restart); + bound.restart = restart; + } + if (!known || bound.stencil_front != draw->stencil_front) { + vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); + bound.stencil_front = draw->stencil_front; + } + if (!known || bound.stencil_back != draw->stencil_back) { + vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); + bound.stencil_back = draw->stencil_back; + } + if (!known || std::memcmp(bound.blend.data(), draw->blend_factor.data(), sizeof(bound.blend)) != 0) { + vk.set_blend_constants(command_buffer, draw->blend_factor.data()); + bound.blend = draw->blend_factor; + } + bound.dynamic = true; for (std::uint32_t slot = 0; slot < d.vertex_buffers.size(); ++slot) { if (!d.vertex_buffers[slot]) continue; + if ((bound.vertex_slots & (1u << slot)) && bound.vertex_buffers[slot] == d.vertex_buffers[slot] && + bound.vertex_offsets[slot] == d.vertex_offsets[slot] && + bound.vertex_sizes[slot] == d.vertex_sizes[slot] && + bound.vertex_strides[slot] == d.vertex_strides[slot]) + continue; vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], &d.vertex_sizes[slot], &d.vertex_strides[slot]); + bound.vertex_slots |= 1u << slot; + bound.vertex_buffers[slot] = d.vertex_buffers[slot]; + bound.vertex_offsets[slot] = d.vertex_offsets[slot]; + bound.vertex_sizes[slot] = d.vertex_sizes[slot]; + bound.vertex_strides[slot] = d.vertex_strides[slot]; } if (draw->indexed) { - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + if (bound.index_buffer != d.index_buffer || bound.index_offset != d.index_offset || + bound.index_type != d.index_type) { + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + bound.index_buffer = d.index_buffer; + bound.index_offset = d.index_offset; + bound.index_type = d.index_type; + } vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, draw->first_instance); } else { diff --git a/runtime/test/d3d12_draw_state_test.cpp b/runtime/test/d3d12_draw_state_test.cpp new file mode 100644 index 0000000000..175a0d87f1 --- /dev/null +++ b/runtime/test/d3d12_draw_state_test.cpp @@ -0,0 +1,702 @@ +// D3D-393: the replay skips a draw's bind or set when the same value is still bound in the command buffer and forgets +// what is bound where a command may disturb it (src/vulkan_replay.h, detail::BoundDrawState). These scenarios make +// each skip and each forgetting visible: every draw changes some state (pipeline, root arguments, viewport, scissor, +// vertex and index buffers, topology, blend factor, root signature) and keeps the rest, and between draws come clears +// (whole-view, and rectangles in a rendering scope of their own), a copy and a barrier, which keep the bound state; a +// compute dispatch and a binary-occlusion resolve, whose dispatches bind their own pipeline and push constants; a +// bundle; and a pipeline without vertex input, after which the vertex buffers must be bound again (their strides are +// invalid, which the validation layer reports). A draw that kept a stale value, or lost one it should have kept, +// lands in another cell or colour. +// The same scenarios run on the layer (a Vulkan device, the shaders d3d12_bundle_test and d3d12_draw_test use, and +// cs_user_data.comp) and on Windows' own D3D12 (HLSL from D3DCompile, the default adapter and WARP); each is read +// back as an 8x8 grid of letters: B blue (the clear), R, G, Y the draw's colour, C a green-only write over blue, K +// black (a cleared rectangle). The expected grids are what both host adapters produced; the layer is held to them, +// and so are the hosts. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation with synchronization +// validation: any error fails the test. No game data. +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "host_wine.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) || !defined(LEONIDA_TEST_CS_SPV) || \ + !defined(LEONIDA_TEST_VS_FULLSCREEN_SPV) +#error "the LEONIDA_TEST_*_SPV macros must name the compiled test shaders" +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +#define REQUIRE(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; + +namespace { + +constexpr UINT target_px = 64; +constexpr UINT grid_cells = 8; + +struct Vertex { + float x, y; + std::uint8_t r, g, b, a; +}; + +// Upload-heap layout, in bytes. +constexpr UINT64 vb_quad = 0; // the viewport's top-left quarter as a strip: (-1,1) (0,1) (-1,0) (0,0) +constexpr UINT64 vb_other = 64; // the same shape in the bottom-left quarter +constexpr UINT64 ib_quad = 128; // 0 1 2 2 1 3: both triangles of the quad as a list +constexpr UINT64 ib_flip = 144; // 3 1 2 0: as a list, only the lower-right half; as a strip, the whole quad +constexpr UINT64 tint_red = 256; // (1, 0, 1): the red vertices stay red +constexpr UINT64 tint_green = 512; // (0, 1, 0) +constexpr UINT64 tint_yellow = 768; // (1, 1, 1) + +constexpr auto strip = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; +constexpr auto tlist = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; + +#define BLANK "BBBBBBBB" + +using Recorder = std::function; + +struct Shaders { + std::vector vs, ps, cs, fs; // fs: a vertex shader without inputs, one viewport-sized triangle +}; + +struct Rig { + ID3D12Device* device = nullptr; + // root1: two constants (an offset, s0 s1) and a CBV (the tint). root2 adds a third constant: another layout. + // croot: two constants and a root UAV, for the compute pipeline. + Ref root1, root2, croot; + // a: all channels; b: green and alpha only; a2: a on root2; f: the output times the blend factor; fs: no vertex + // input, a yellow triangle over the whole viewport; cs: compute. + Ref pso_a, pso_b, pso_a2, pso_f, pso_fs, cs; + Ref queue; + Ref fence; + Ref upload, target, readback, results, uav; + Ref rtv_heap; + Ref queries; + D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; + D3D12_GPU_VIRTUAL_ADDRESS upload_va = 0; + UINT64 fence_value = 0; + std::vector> bundle_allocators; + std::vector> bundles; + Shaders shaders; + + bool make_root(UINT count, Ref& root) { + D3D12_ROOT_PARAMETER params[3] = {}; + 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}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {2, 0, 1}; + 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_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + const auto blob = serialize_root_signature(root_desc); + CHECK(!blob.empty()); + CHECK(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); + return true; + } + + bool make_pso(ID3D12RootSignature* root, UINT8 write_mask, bool blend_factor, Ref& pso, + bool fullscreen = false) { + static const D3D12_INPUT_ELEMENT_DESC elements[2] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}}; + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.VS = fullscreen ? D3D12_SHADER_BYTECODE{shaders.fs.data(), shaders.fs.size()} + : D3D12_SHADER_BYTECODE{shaders.vs.data(), shaders.vs.size()}; + desc.PS = {shaders.ps.data(), shaders.ps.size()}; + auto& blend = desc.BlendState.RenderTarget[0]; + blend.RenderTargetWriteMask = write_mask; + if (blend_factor) { // colour = output * blend factor, alpha = output alpha + blend.BlendEnable = TRUE; + blend.SrcBlend = D3D12_BLEND_BLEND_FACTOR; + blend.DestBlend = D3D12_BLEND_ZERO; + blend.BlendOp = D3D12_BLEND_OP_ADD; + blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlendAlpha = D3D12_BLEND_ZERO; + blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + } + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.InputLayout = fullscreen ? D3D12_INPUT_LAYOUT_DESC{nullptr, 0} : D3D12_INPUT_LAYOUT_DESC{elements, 2}; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + CHECK(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + return true; + } + + bool init(ID3D12Device* d, const Shaders& s) { + device = d; + shaders = s; + CHECK(make_root(2, root1) && make_root(3, root2)); + constexpr UINT8 all = D3D12_COLOR_WRITE_ENABLE_ALL; + CHECK(make_pso(root1.p, all, false, pso_a)); + CHECK(make_pso(root1.p, D3D12_COLOR_WRITE_ENABLE_GREEN | D3D12_COLOR_WRITE_ENABLE_ALPHA, false, pso_b)); + CHECK(make_pso(root2.p, all, false, pso_a2)); + CHECK(make_pso(root1.p, all, true, pso_f)); + CHECK(make_pso(root1.p, all, false, pso_fs, true)); + { + 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_UAV; + params[1].Descriptor = {0, 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); + CHECK(!blob.empty()); + CHECK(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&croot.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = croot.p; + desc.CS = {shaders.cs.data(), shaders.cs.size()}; + CHECK(SUCCEEDED(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&cs.p)))); + } + + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + auto buffer = buffer_desc(4096); + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&results.p)))); + buffer = buffer_desc(4096, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&uav.p)))); + buffer = buffer_desc(target_px * 256); + CHECK(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = target_px; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture.SampleDesc.Count = 1; + texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&target.p)))); + const Vertex quad[4] = {{-1, 1, 255, 0, 0, 255}, {0, 1, 255, 0, 0, 255}, {-1, 0, 255, 0, 0, 255}, + {0, 0, 255, 0, 0, 255}}; + const Vertex other[4] = {{-1, 0, 255, 0, 0, 255}, {0, 0, 255, 0, 0, 255}, {-1, -1, 255, 0, 0, 255}, + {0, -1, 255, 0, 0, 255}}; + const std::uint16_t list[6] = {0, 1, 2, 2, 1, 3}; + const std::uint16_t flip[4] = {3, 1, 2, 0}; + const float tints[3][3] = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}}; + std::uint8_t* up = nullptr; + CHECK(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memset(up, 0, 4096); + std::memcpy(up + vb_quad, quad, sizeof(quad)); + std::memcpy(up + vb_other, other, sizeof(other)); + std::memcpy(up + ib_quad, list, sizeof(list)); + std::memcpy(up + ib_flip, flip, sizeof(flip)); + std::memcpy(up + tint_red, tints[0], sizeof(tints[0])); + std::memcpy(up + tint_green, tints[1], sizeof(tints[1])); + std::memcpy(up + tint_yellow, tints[2], sizeof(tints[2])); + upload->Unmap(0, nullptr); + upload_va = upload->GetGPUVirtualAddress(); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.p, nullptr, rtv); + const D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 0}; + CHECK(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&queries.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + return true; + } + + // A closed bundle created with `initial` as its pipeline state, kept alive until the rig goes. + template + ID3D12GraphicsCommandList* bundle(ID3D12PipelineState* initial, F&& record) { + bundle_allocators.emplace_back(); + bundles.emplace_back(); + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, + IID_PPV_ARGS(&bundle_allocators.back().p))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocators.back().p, initial, + IID_PPV_ARGS(&bundles.back().p)))) + return nullptr; + record(bundles.back().p); + if (FAILED(bundles.back()->Close())) return nullptr; + return bundles.back().p; + } + + // A viewport of size x size pixels at (x, y): the quad fills its top-left quarter, a cell when size is 16, an + // offset of 1 moves it by size / 2 pixels, and what an offset moves out of the viewport is clipped. + void viewport(ID3D12GraphicsCommandList* list, float x, float y, float size) { + const D3D12_VIEWPORT v{x, y, size, size, 0, 1}; + list->RSSetViewports(1, &v); + } + void scissor(ID3D12GraphicsCommandList* list, LONG right) { + const D3D12_RECT rect{0, 0, right, LONG(target_px)}; + list->RSSetScissorRects(1, &rect); + } + void vertices(ID3D12GraphicsCommandList* list, UINT64 offset) { + const D3D12_VERTEX_BUFFER_VIEW view{upload_va + offset, 4 * sizeof(Vertex), sizeof(Vertex)}; + list->IASetVertexBuffers(0, 1, &view); + } + void indices(ID3D12GraphicsCommandList* list, UINT64 offset, UINT count) { + const D3D12_INDEX_BUFFER_VIEW view{upload_va + offset, count * 2, DXGI_FORMAT_R16_UINT}; + list->IASetIndexBuffer(&view); + } + void offset(ID3D12GraphicsCommandList* list, float x, float y) { + const float xy[2] = {x, y}; + list->SetGraphicsRoot32BitConstants(0, 2, xy, 0); + } + void tint(ID3D12GraphicsCommandList* list, UINT64 which) { + list->SetGraphicsRootConstantBufferView(1, upload_va + which); + } + // The first draw's state: pso_a, root1, a strip of vb_quad, no offset, red, a cell-sized viewport at (0, 0). + void start(ID3D12GraphicsCommandList* list, float size = 16) { + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + scissor(list, LONG(target_px)); + viewport(list, 0, 0, size); + list->SetGraphicsRootSignature(root1.p); + list->SetPipelineState(pso_a.p); + list->IASetPrimitiveTopology(strip); + vertices(list, vb_quad); + offset(list, 0, 0); + tint(list, tint_red); + } + // A compute dispatch whose root constants, if a draw read them, would move it by (1, -1). + void dispatch(ID3D12GraphicsCommandList* list) { + const float constants[2] = {1, -1}; + list->SetComputeRootSignature(croot.p); + list->SetComputeRoot32BitConstants(0, 2, constants, 0); + list->SetComputeRootUnorderedAccessView(1, uav->GetGPUVirtualAddress()); + list->SetPipelineState(cs.p); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER written{}; // the next dispatch writes the same words + written.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + written.UAV.pResource = uav.p; + list->ResourceBarrier(1, &written); + } + // Clears `cell` (column, row) black. + void clear_cell(ID3D12GraphicsCommandList* list, LONG column, LONG row) { + const FLOAT black[4] = {0, 0, 0, 1}; + const D3D12_RECT rect{column * 8, row * 8, column * 8 + 8, row * 8 + 8}; + list->ClearRenderTargetView(rtv, black, 1, &rect); + } + + // Clears the target blue, runs `record` on a direct list and reads the target back as letters. + bool render(const Recorder& record, std::string& out, HRESULT& close) { + Ref allocator; + Ref list; + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.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); + record(*this, list.p); + 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{}, src{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, target_px, target_px, 1, 256}}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + close = list->Close(); + if (FAILED(close)) return true; // reported by the caller + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); + const std::uint8_t* pixels = nullptr; + const HRESULT mapped = readback->Map(0, nullptr, const_cast(reinterpret_cast(&pixels))); + if (FAILED(mapped)) { + char text[96]; + std::snprintf(text, sizeof(text), "Map 0x%08lx, device removed 0x%08lx", static_cast(mapped), + static_cast(device->GetDeviceRemovedReason())); + out = text; + return true; + } + out.clear(); + for (UINT row = 0; row < grid_cells; ++row) { + for (UINT column = 0; column < grid_cells; ++column) { + // Pixel (3, 3) of the cell: inside the upper-left half of a cell-sized quad, outside the lower-right. + const std::uint8_t* p = pixels + (row * 8 + 3) * 256 + (column * 8 + 3) * 4; + char letter = '?'; + if (p[3] == 255) { + if (p[0] == 0 && p[1] == 0 && p[2] == 255) letter = 'B'; + else if (p[0] == 255 && p[1] == 0 && p[2] == 0) letter = 'R'; + else if (p[0] == 0 && p[1] == 255 && p[2] == 0) letter = 'G'; + else if (p[0] == 255 && p[1] == 255 && p[2] == 0) letter = 'Y'; + else if (p[0] == 0 && p[1] == 255 && p[2] == 255) letter = 'C'; + else if (p[0] == 0 && p[1] == 0 && p[2] == 0) letter = 'K'; + } + out += letter; + } + if (row + 1 < grid_cells) out += ' '; + } + readback->Unmap(0, nullptr); + return true; + } +}; + +struct Scenario { + const char* name; + Recorder record; + const char* expected; // null: print only +}; + +std::vector scenarios() { + std::vector s; + // Draw by draw; each comment names what changed and the cell (column, row) the quad lands in. + s.push_back({"draw to draw: each draw changes some state and keeps the rest", + [](Rig& r, ID3D12GraphicsCommandList* l) { + r.start(l); + l->DrawInstanced(4, 1, 0, 0); // (0, 0) R + r.offset(l, 1, 0); + l->DrawInstanced(4, 1, 0, 0); // root constants: (1, 0) R + r.tint(l, tint_green); + l->DrawInstanced(4, 1, 0, 0); // root CBV: (1, 0) G + r.viewport(l, 16, 0, 16); + l->DrawInstanced(4, 1, 0, 0); // viewport: (3, 0) G + r.vertices(l, vb_other); + l->DrawInstanced(4, 1, 0, 0); // vertex buffer: (3, 1) G + l->SetPipelineState(r.pso_b.p); + r.tint(l, tint_yellow); + r.vertices(l, vb_quad); + r.viewport(l, 32, 16, 16); + l->DrawInstanced(4, 1, 0, 0); // pipeline, CBV, vertex buffer, viewport: (5, 2) C + l->SetPipelineState(r.pso_a.p); + l->DrawInstanced(4, 1, 0, 0); // pipeline: (5, 2) Y + r.scissor(l, 32); + r.viewport(l, 32, 24, 16); + l->DrawInstanced(4, 1, 0, 0); // scissor, viewport: (5, 3) cut away + r.scissor(l, LONG(target_px)); + l->DrawInstanced(4, 1, 0, 0); // scissor: (5, 3) Y + r.indices(l, ib_flip, 4); + r.viewport(l, 48, 32, 16); + l->DrawIndexedInstanced(4, 1, 0, 0, 0); // indexed strip: (7, 4) Y + l->IASetPrimitiveTopology(tlist); + r.viewport(l, 48, 40, 16); + l->DrawIndexedInstanced(4, 1, 0, 0, 0); // topology: a list, (7, 5) only the lower-right half + r.indices(l, ib_quad, 6); + r.viewport(l, 48, 48, 16); + l->DrawIndexedInstanced(6, 1, 0, 0, 0); // index buffer: (7, 6) Y + l->SetPipelineState(r.pso_f.p); + const FLOAT red[4] = {1, 0, 0, 1}, green[4] = {0, 1, 0, 1}; + l->OMSetBlendFactor(red); + r.viewport(l, 0, 32, 16); + l->DrawIndexedInstanced(6, 1, 0, 0, 0); // pipeline, blend factor, viewport: (1, 4) R + l->OMSetBlendFactor(green); + r.viewport(l, 0, 40, 16); + l->DrawIndexedInstanced(6, 1, 0, 0, 0); // blend factor, viewport: (1, 5) G + r.viewport(l, 0, 48, 16); + l->DrawIndexedInstanced(6, 1, 0, 0, 0); // viewport: (1, 6) G + l->SetGraphicsRootSignature(r.root2.p); // the arguments go: the same values again + l->SetPipelineState(r.pso_a2.p); + r.offset(l, 1, 0); + r.tint(l, tint_yellow); + const UINT zero = 0; + l->SetGraphicsRoot32BitConstants(2, 1, &zero, 0); + r.viewport(l, 16, 48, 16); + l->DrawIndexedInstanced(6, 1, 0, 0, 0); // root signature, pipeline, viewport: (3, 6) Y + }, + "RGBGBBBB BBBGBBBB BBBBBYBB BBBBBYBB BRBBBBBY BGBBBBBB BGBYBBBY " BLANK}); + // The quad covers 2x2 cells here. Clears, a copy and a barrier bind nothing: the draws after them set nothing, + // and must still draw. + s.push_back({"clears, a copy and a barrier between draws keep the state", + [](Rig& r, ID3D12GraphicsCommandList* l) { + r.start(l, 32); + l->DrawInstanced(4, 1, 0, 0); + const FLOAT blue[4] = {0, 0, 1, 1}; + l->ClearRenderTargetView(r.rtv, blue, 0, nullptr); + l->CopyBufferRegion(r.results.p, 0, r.upload.p, 0, 256); + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + l->ResourceBarrier(1, &uav); + l->DrawInstanced(4, 1, 0, 0); + r.clear_cell(l, 0, 0); + l->DrawInstanced(4, 1, 0, 0); + r.clear_cell(l, 1, 1); + }, + "RRBBBBBB RKBBBBBB " BLANK " " BLANK " " BLANK " " BLANK " " BLANK " " BLANK}); + // A dispatch binds a compute pipeline and pushes its own constants: (1, -1) would move the draw two cells right + // and down. The draw after it, with the same root arguments, must still draw where its own say. + s.push_back({"a compute dispatch between draws", + [](Rig& r, ID3D12GraphicsCommandList* l) { + r.start(l, 32); + l->SetPipelineState(r.pso_b.p); + r.tint(l, tint_yellow); + l->DrawInstanced(4, 1, 0, 0); // (0..1, 0..1) C + r.dispatch(l); + l->SetPipelineState(r.pso_a.p); + l->DrawInstanced(4, 1, 0, 0); // the same arguments: (0..1, 0..1) Y + r.dispatch(l); + l->SetPipelineState(r.pso_a.p); + r.viewport(l, 32, 32, 32); + l->DrawInstanced(4, 1, 0, 0); // the same pipeline and arguments: (4..5, 4..5) Y + }, + "YYBBBBBB YYBBBBBB " BLANK " " BLANK " BBBBYYBB BBBBYYBB " BLANK " " BLANK}); + // A binary-occlusion resolve runs a dispatch of the layer's own between the two draws. + s.push_back({"a binary-occlusion resolve between draws", + [](Rig& r, ID3D12GraphicsCommandList* l) { + r.start(l, 32); + l->SetPipelineState(r.pso_b.p); + r.tint(l, tint_yellow); + l->BeginQuery(r.queries.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 0); + l->DrawInstanced(4, 1, 0, 0); // (0..1, 0..1) C + l->EndQuery(r.queries.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 0); + l->ResolveQueryData(r.queries.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 0, 1, r.results.p, 0); + l->SetPipelineState(r.pso_a.p); + l->DrawInstanced(4, 1, 0, 0); // (0..1, 0..1) Y + r.viewport(l, 32, 32, 32); + l->DrawInstanced(4, 1, 0, 0); // (4..5, 4..5) Y + }, + "YYBBBBBB YYBBBBBB " BLANK " " BLANK " BBBBYYBB BBBBYYBB " BLANK " " BLANK}); + // A bundle's draw runs on the parent's root arguments and viewport with its own pipeline, and hands that back. + s.push_back({"a bundle between draws", + [](Rig& r, ID3D12GraphicsCommandList* l) { + auto* b = r.bundle(r.pso_b.p, [](ID3D12GraphicsCommandList* b) { + b->IASetPrimitiveTopology(strip); + b->DrawInstanced(4, 1, 0, 0); + }); + r.start(l); + r.tint(l, tint_yellow); + l->DrawInstanced(4, 1, 0, 0); // (0, 0) Y + r.offset(l, 1, 0); + if (b) l->ExecuteBundle(b); // (1, 0) C + r.viewport(l, 16, 0, 16); + l->DrawInstanced(4, 1, 0, 0); // pso_b, handed back; viewport: (3, 0) C + l->SetPipelineState(r.pso_a.p); + r.viewport(l, 32, 0, 16); + l->DrawInstanced(4, 1, 0, 0); // pipeline, viewport: (5, 0) Y + }, + "YCBCBYBB " BLANK " " BLANK " " BLANK " " BLANK " " BLANK " " BLANK " " BLANK}); + // A pipeline without vertex input leaves the vertex strides static: binding it invalidates the ones the vertex + // buffer was bound with, so the next draw with vertex input binds the unchanged buffer again. + s.push_back({"a pipeline without vertex input between draws", + [](Rig& r, ID3D12GraphicsCommandList* l) { + r.start(l); + l->DrawInstanced(4, 1, 0, 0); // (0, 0) R + l->SetPipelineState(r.pso_fs.p); + r.tint(l, tint_green); + r.viewport(l, 16, 0, 16); + l->DrawInstanced(3, 1, 0, 0); // the whole viewport: (2..3, 0..1) G + l->SetPipelineState(r.pso_a.p); + r.viewport(l, 32, 0, 16); + l->DrawInstanced(4, 1, 0, 0); // the same vertex buffer: (4, 0) G + }, + "RBGGGBBB BBGGBBBB " BLANK " " BLANK " " BLANK " " BLANK " " BLANK " " BLANK}); + return s; +} + +bool compile_hlsl(const char* source, const char* entry, const char* profile, std::vector& out) { + const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto compile = compiler ? reinterpret_cast(GetProcAddress(compiler, "D3DCompile")) : nullptr; + if (!compile) return false; + ID3DBlob* blob = nullptr; + ID3DBlob* errors = nullptr; + const HRESULT hr = compile(source, std::strlen(source), "draw_state.hlsl", nullptr, nullptr, entry, profile, 0, 0, + &blob, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + if (errors) errors->Release(); + if (FAILED(hr) || !blob) return false; + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + return true; +} + +// The layer's shaders, for the host: test/glsl/vs_draw.vert and ps_draw.frag (s0, s1 offset the vertex, the root CBV +// tints), vs_fullscreen.vert, and a compute shader that, like cs_user_data.comp, writes base + step * i into the +// root UAV. +constexpr char hlsl[] = + "cbuffer Offset : register(b0) { float2 offset; };\n" + "cbuffer Tint : register(b1) { float3 tint; };\n" + "struct V { float4 position : SV_Position; float4 color : COLOR; };\n" + "V vs(float2 position : POSITION, float4 color : COLOR) {\n" + " V v; v.position = float4(position + offset, 0, 1); v.color = color; return v; }\n" + "float4 ps(V v) : SV_Target { return float4(v.color.r * tint.x, tint.y, v.color.b * tint.z, 1); }\n" + "V fs(uint id : SV_VertexID) {\n" + " V v; v.position = float4(float2(id & 2, (id << 1) & 2) * 2 - 1, 0, 1); v.color = float4(1, 1, 0, 1);\n" + " return v; }\n" + "cbuffer Step : register(b0) { uint base; uint step; };\n" + "RWByteAddressBuffer result : register(u0);\n" + "[numthreads(64, 1, 1)] void cs(uint3 id : SV_DispatchThreadID) { result.Store(id.x * 4, base + step * id.x); }\n"; + +// Runs every scenario and stores the grids; false on a harness failure. A host scenario gets a device of its own. +bool run_all(ID3D12Device* shared, bool own_device, IDXGIAdapter* adapter, const Shaders& shaders, + const std::vector& list, std::vector& grids, std::vector& closes) { + for (const Scenario& scenario : list) { + Rig rig; + Ref own; + if (own_device) D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&own.p)); + ID3D12Device* device = own_device ? own.p : shared; + if (!device || !rig.init(device, shaders)) { + grids.push_back("device unusable"); + closes.push_back(E_FAIL); + continue; + } + std::string grid_text; + HRESULT close = S_OK; + if (!rig.render(scenario.record, grid_text, close)) return false; + grids.push_back(grid_text); + closes.push_back(close); + } + return true; +} + +} // namespace + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + vktest::Device vk; + const auto device_status = vk.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + REQUIRE(device_status == vktest::DeviceStatus::ready); + const auto list = scenarios(); + + // Layer shaders: FSSM-shaped containers found by hash in a translator-style index. + const auto vs_program = fssm_program({0x56530101, 0xbf810000}); + const auto ps_program = fssm_program({0x50530101, 0xbf810000}); + const auto cs_program = fssm_program({0x43530101, 0xbf810000}); + const auto fs_program = fssm_program({0x46530101, 0xbf810000}); + const Shaders layer_shaders{shader_container(vs_program), shader_container(ps_program), + shader_container(cs_program), shader_container(fs_program)}; + const testfiles::ScratchDir scratch("leonida_draw_state_test"); + const auto& library = scratch.path(); + REQUIRE(testfiles::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv")); + REQUIRE(testfiles::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv")); + REQUIRE(testfiles::copy_file(LEONIDA_TEST_CS_SPV, library / "cs_user_data.spv")); + REQUIRE(testfiles::copy_file(LEONIDA_TEST_VS_FULLSCREEN_SPV, library / "vs_fullscreen.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [" + "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, " + "\"system_value\": 0, \"component_type\": \"float\"}, " + "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, " + "\"system_value\": 0, \"component_type\": \"float\"}]},\n" + " \"vs_fullscreen\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fs_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]},\n" + " \"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false}}"; + } + const unsigned errors_before = vk.validation_errors(); + std::vector layer_grids; + std::vector layer_closes; + { + 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; + info.buffer_device_address = true; + info.subgroup = vk.subgroup; + info.shader_dir = library.string(); + Ref ours; + REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); + REQUIRE(run_all(ours.p, false, nullptr, layer_shaders, list, layer_grids, layer_closes)); + } + + // The host: Windows' D3D12 on the default adapter and on WARP. + Shaders host_shaders; + const bool wine = hostwine::host_is_wine(); + const bool compiled = !wine && compile_hlsl(hlsl, "vs", "vs_5_0", host_shaders.vs) && + compile_hlsl(hlsl, "ps", "ps_5_0", host_shaders.ps) && + compile_hlsl(hlsl, "cs", "cs_5_0", host_shaders.cs) && + compile_hlsl(hlsl, "fs", "vs_5_0", host_shaders.fs); + struct HostRun { + const char* name = ""; + bool ran = false; + std::vector grids; + std::vector closes; + } hosts[2]; + hosts[0].name = "the default adapter"; + hosts[1].name = "WARP"; + if (compiled) { + Ref factory; + REQUIRE(SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))); + for (int i = 0; i < 2; ++i) { + Ref adapter; + Ref host; + if (i == 1 && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; + if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; + REQUIRE(run_all(nullptr, true, adapter.p, host_shaders, list, hosts[i].grids, hosts[i].closes)); + hosts[i].ran = true; + } + } else if (!wine) { + std::fprintf(stderr, "no HLSL compiler: the host is not run\n"); + } + + unsigned failures = 0, compared = 0; + const auto verdict = [&](const char* who, const Scenario& scenario, const std::string& grid, HRESULT close) { + if (grid == scenario.expected && close == S_OK) return; + std::fprintf(stderr, "FAIL %s on %s: Close 0x%08lx\n got %s\n expected %s\n", scenario.name, who, + static_cast(close), grid.c_str(), scenario.expected); + ++failures; + }; + for (std::size_t i = 0; i < list.size(); ++i) { + if (!list[i].expected) { + std::printf("%s | layer %s", list[i].name, layer_grids[i].c_str()); + for (const auto& host : hosts) + if (host.ran) std::printf(" | %s %s", host.name, host.grids[i].c_str()); + std::printf("\n"); + ++failures; + continue; + } + verdict("the layer", list[i], layer_grids[i], layer_closes[i]); + for (const auto& host : hosts) { + if (!host.ran) continue; + verdict(host.name, list[i], host.grids[i], host.closes[i]); + ++compared; + } + } + const unsigned validation_errors = vk.validation_errors() - errors_before; + if (validation_errors) { + std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors); + ++failures; + } + if (!hosts[0].ran && !hosts[1].ran && !wine) + std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); + std::printf("draw state: %zu scenarios on the layer, %u host comparisons, %u failures\n", list.size(), compared, + failures); + return failures ? 1 : 0; +} diff --git a/runtime/test/replay_draw_state_test.cpp b/runtime/test/replay_draw_state_test.cpp new file mode 100644 index 0000000000..de13d846c0 --- /dev/null +++ b/runtime/test/replay_draw_state_test.cpp @@ -0,0 +1,504 @@ +// D3D-393: emit skips a draw's bind or set when the same value is still bound in the command buffer, and forgets what +// is bound at every command that may disturb it (detail::BoundDrawState). Every Vulkan entry point is a mock that +// counts its calls. The lists change one piece of state at a time, switch between pipelines whose layouts are and +// are not compatible for set 0 and push constants and to one without vertex input, and put between two draws a +// dispatch, an indirect dispatch, a predicate capture and a query resolve (helpers that bind), and barriers, clears, +// a copy, a marker, a query and an indirect draw (commands that bind nothing); a bundle's draws, and a list emitted +// twice into one command buffer. No Vulkan loader, GPU, shaders or game data. +#include "../src/vulkan_replay.h" + +#include +#include +#include +#include +#include + +namespace { + +using namespace leonida; + +struct Calls { + unsigned graphics_pipeline = 0, compute_pipeline = 0; + unsigned graphics_set = 0, compute_set = 0; + unsigned graphics_push = 0, compute_push = 0; + unsigned viewport = 0, scissor = 0, topology = 0, restart = 0, stencil_front = 0, stencil_back = 0, blend = 0; + unsigned vertex = 0, index = 0; + unsigned draws = 0, dispatches = 0, scopes = 0, helpers = 0; +}; +Calls g; + +VKAPI_ATTR void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint point, VkPipeline) { + ++(point == VK_PIPELINE_BIND_POINT_GRAPHICS ? g.graphics_pipeline : g.compute_pipeline); +} +VKAPI_ATTR void VKAPI_CALL bind_sets(VkCommandBuffer, VkPipelineBindPoint point, VkPipelineLayout, std::uint32_t, + std::uint32_t, const VkDescriptorSet*, std::uint32_t, const std::uint32_t*) { + ++(point == VK_PIPELINE_BIND_POINT_GRAPHICS ? g.graphics_set : g.compute_set); +} +VKAPI_ATTR void VKAPI_CALL push(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags stages, std::uint32_t, + std::uint32_t, const void*) { + ++(stages == VK_SHADER_STAGE_COMPUTE_BIT ? g.compute_push : g.graphics_push); +} +VKAPI_ATTR void VKAPI_CALL viewport(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) { ++g.viewport; } +VKAPI_ATTR void VKAPI_CALL scissor(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) { ++g.scissor; } +VKAPI_ATTR void VKAPI_CALL topology(VkCommandBuffer, VkPrimitiveTopology) { ++g.topology; } +VKAPI_ATTR void VKAPI_CALL restart(VkCommandBuffer, VkBool32) { ++g.restart; } +VKAPI_ATTR void VKAPI_CALL stencil(VkCommandBuffer, VkStencilFaceFlags face, std::uint32_t) { + ++(face == VK_STENCIL_FACE_FRONT_BIT ? g.stencil_front : g.stencil_back); +} +VKAPI_ATTR void VKAPI_CALL blend(VkCommandBuffer, const float*) { ++g.blend; } +VKAPI_ATTR void VKAPI_CALL vertex(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, const VkDeviceSize*, + const VkDeviceSize*, const VkDeviceSize*) { + ++g.vertex; +} +VKAPI_ATTR void VKAPI_CALL index(VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) { ++g.index; } +VKAPI_ATTR void VKAPI_CALL draw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { + ++g.draws; +} +VKAPI_ATTR void VKAPI_CALL draw_indexed(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, + std::uint32_t) { + ++g.draws; +} +VKAPI_ATTR void VKAPI_CALL dispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { ++g.dispatches; } +VKAPI_ATTR void VKAPI_CALL dispatch_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize) { ++g.dispatches; } +VKAPI_ATTR void VKAPI_CALL begin_rendering(VkCommandBuffer, const VkRenderingInfo*) { ++g.scopes; } + +// Any other vkCmd* signature: a no-op. +template +struct Nop; +template +struct Nop { + static R VKAPI_CALL call(A...) { + if constexpr (!std::is_void_v) return R{}; + } +}; +template +PFN nop() { + return &Nop>::call; +} + +template +H handle(std::uintptr_t value) { + return reinterpret_cast(value); +} + +enum : ResourceId { color = 1, upload, predicate, results }; +constexpr QueryHeapId occlusion_heap = 100; +constexpr std::uint64_t geometry = 0x100000000ull; // a 1 MiB vertex and index arena + +// p1: two vertex slots, set 0, VS+FS push constants. p2: the same with another layout handle (compatible for set 0 +// and push constants). p3: no vertex input and no set 0. p4: another push-constant range (incompatible). p5: p1 with +// a 32-bit strip cut. +enum : std::uintptr_t { p1 = 0x7001, p2, p3, p4, p5, compute = 0x7100 }; + +struct Rig { + std::unordered_map resources; + std::unordered_map pipelines; + ComputePipeline cs; + QueryPool queries; + ReplayFunctions vk; + + Rig() { + ResourceBinding image{}; + image.image = handle(0x1001); + image.format = VK_FORMAT_R8G8B8A8_UNORM; + image.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + image.width = image.height = 64; + image.depth = image.mip_levels = image.array_layers = image.samples = 1; + image.color_attachment = true; + resources[color] = image; + for (const ResourceId id : {upload, predicate, results}) { + ResourceBinding b{}; + b.buffer = handle(0x2000 + id); + b.size = 1 << 20; + resources[id] = b; + } + queries = {handle(0x3000), d3d12_query_heap::occlusion, 16, false, std::vector(16)}; + + const VkDescriptorSet set0 = handle(0x5000); + const VkShaderStageFlags vs_fs = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + const auto pipeline = [&](std::uintptr_t id, VkShaderStageFlags stages, VkDescriptorSet set, + std::uint32_t vertex_slots, std::uint32_t strip_cut) { + GraphicsPipeline& p = pipelines[id]; + p.pipeline = handle(0x6000 + id); + p.layout = handle(0x8000 + id); + p.push_stages = stages; + p.bindless_set = set; + p.color_formats = {VK_FORMAT_R8G8B8A8_UNORM}; + p.vertex_slots = vertex_slots; + p.strip_cut = strip_cut; + }; + pipeline(p1, vs_fs, set0, 0b11, 0); + pipeline(p2, vs_fs, set0, 0b11, 0); + pipeline(p3, vs_fs, VK_NULL_HANDLE, 0, 0); + pipeline(p4, vs_fs | VK_SHADER_STAGE_GEOMETRY_BIT, set0, 0b11, 0); + pipeline(p5, vs_fs, set0, 0b11, 2); + cs = {handle(0x6100), handle(0x8100), 0, set0}; + + vk.pipeline_barrier = nop(); + vk.clear_color_image = nop(); + vk.clear_depth_stencil_image = nop(); + vk.pipeline_barrier2 = nop(); + vk.begin_rendering = begin_rendering; + vk.end_rendering = nop(); + vk.clear_attachments = nop(); + vk.copy_buffer = nop(); + vk.copy_buffer_to_image = nop(); + vk.copy_image_to_buffer = nop(); + vk.copy_image = nop(); + vk.resolve_image = nop(); + vk.fill_buffer = nop(); + vk.update_buffer = nop(); + vk.begin_conditional_rendering = nop(); + vk.end_conditional_rendering = nop(); + vk.prepare_predicate = [](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { + out = {source, offset, handle(0x2100), 0, VK_NULL_HANDLE}; + return true; + }; + vk.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) { ++g.helpers; }; + vk.reset_query_pool = nop(); + vk.begin_query = nop(); + vk.end_query = nop(); + vk.write_timestamp = nop(); + vk.copy_query_pool_results = nop(); + vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, + VkDeviceSize) { ++g.helpers; }; + vk.query_pool = [this](QueryHeapId id) { return id == occlusion_heap ? &queries : nullptr; }; + vk.insert_label = nop(); + vk.begin_label = nop(); + vk.end_label = nop(); + vk.draw_indirect = nop(); + vk.draw_indexed_indirect = nop(); + vk.dispatch_indirect = dispatch_indirect; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { + return handle(0x4000); + }; + vk.bind_pipeline = bind_pipeline; + vk.push_constants = push; + vk.bind_descriptor_sets = bind_sets; + vk.dispatch = dispatch; + vk.compute_pipeline = [this](std::uintptr_t id) { return id == compute ? &cs : nullptr; }; + vk.bind_vertex_buffers2 = vertex; + vk.bind_index_buffer = index; + vk.set_viewport = viewport; + vk.set_scissor = scissor; + vk.set_primitive_topology = topology; + vk.set_primitive_restart_enable = restart; + vk.set_stencil_reference = stencil; + vk.set_blend_constants = blend; + vk.draw = draw; + vk.draw_indexed = draw_indexed; + vk.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { + const auto it = pipelines.find(id); + return it == pipelines.end() ? nullptr : &it->second; + }; + vk.buffer_at = [](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + if (va < geometry || va >= geometry + (1 << 20)) return false; + buffer = handle(0x2200); + offset = va - geometry; + size = std::min(size, geometry + (1 << 20) - va); + return true; + }; + vk.zero_buffer = handle(0x2300); + vk.zero_size = 65536; + } + + const ResourceBinding* resolve(ResourceId id) const { + const auto it = resources.find(id); + return it == resources.end() ? nullptr : &it->second; + } +}; + +// A draw's state; each field is one piece the draw sets. +struct Spec { + std::uintptr_t pipeline = p1; + std::uint32_t s0 = 0; + float viewport_x = 0; + std::int32_t scissor_right = 64; + std::uint32_t topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST + std::uint32_t stencil_front = 0, stencil_back = 0; + float blend = 1; + std::uint64_t vertex1 = geometry + 4096; // slot 1; slot 0 is always at `geometry` + bool indexed = true; + std::uint64_t index = geometry + 8192; + std::uint32_t index_format = 57; // DXGI_FORMAT_R16_UINT +}; + +Draw make(const Spec& s) { + Draw d{}; + d.pipeline = s.pipeline; + d.user_data[0] = s.s0; + auto views = std::make_shared(); + views->render_targets[0] = {color, 0, 0, 1}; + views->render_target_count = 1; + views->vertex_buffers[0] = {geometry, 4096, 12}; + views->vertex_buffers[1] = {s.vertex1, 4096, 8}; + d.views = std::move(views); + d.index = {s.index, 4096, s.index_format}; + d.topology = s.topology; + d.viewport = {s.viewport_x, 0, 64, 64, 0, 1}; + d.scissor = {0, 0, s.scissor_right, 64}; + d.blend_factor = {s.blend, 1, 1, 1}; + d.stencil_front = s.stencil_front; + d.stencil_back = s.stencil_back; + d.indexed = s.indexed; + d.count = 3; + d.instances = 1; + return d; +} + +int failures = 0; + +// Replays `list` (closed here) and compares every count with `want`. +void check(const char* name, Rig& rig, CommandList& list, const Calls& want, int emits = 1) { + g = {}; + if (!list.close()) { + std::fprintf(stderr, "FAIL %s: the list did not close\n", name); + ++failures; + return; + } + const auto resolve = [&rig](ResourceId id) { return rig.resolve(id); }; + PreparedList prepared; + if (const auto r = prepare(list, resolve, rig.vk, prepared); r != ReplayResult::success) { + std::fprintf(stderr, "FAIL %s: prepare returned %d\n", name, int(r)); + ++failures; + return; + } + QueryReplay queries; + if (queries.plan(prepared) != ReplayResult::success) { + std::fprintf(stderr, "FAIL %s: the queries were not planned\n", name); + ++failures; + return; + } + for (int i = 0; i < emits; ++i) emit(prepared, handle(0x10), rig.vk); + queries.commit(); + bool ok = true; + const auto field = [&](const char* what, unsigned got, unsigned expected) { + if (got == expected) return; + std::fprintf(stderr, "FAIL %s: %s %u, expected %u\n", name, what, got, expected); + ok = false; + }; + field("graphics pipeline binds", g.graphics_pipeline, want.graphics_pipeline); + field("compute pipeline binds", g.compute_pipeline, want.compute_pipeline); + field("graphics set binds", g.graphics_set, want.graphics_set); + field("compute set binds", g.compute_set, want.compute_set); + field("graphics pushes", g.graphics_push, want.graphics_push); + field("compute pushes", g.compute_push, want.compute_push); + field("viewports", g.viewport, want.viewport); + field("scissors", g.scissor, want.scissor); + field("topologies", g.topology, want.topology); + field("primitive restarts", g.restart, want.restart); + field("front stencil references", g.stencil_front, want.stencil_front); + field("back stencil references", g.stencil_back, want.stencil_back); + field("blend constants", g.blend, want.blend); + field("vertex-buffer binds", g.vertex, want.vertex); + field("index-buffer binds", g.index, want.index); + field("draws", g.draws, want.draws); + field("dispatches", g.dispatches, want.dispatches); + field("rendering scopes", g.scopes, want.scopes); + field("helpers", g.helpers, want.helpers); + if (!ok) ++failures; +} + +// The counts of `draws` draws that set every piece once: what the first draw of a list costs. +Calls once(unsigned draws) { + Calls c; + c.graphics_pipeline = c.graphics_set = c.graphics_push = 1; + c.viewport = c.scissor = c.topology = c.restart = c.stencil_front = c.stencil_back = c.blend = 1; + c.vertex = 2; + c.index = 1; + c.draws = c.scopes = draws; + return c; +} + +} // namespace + +int main() { + Rig rig; + const Spec base; + // The same draw three times: the second and third set nothing. + { + CommandList l; + for (int i = 0; i < 3; ++i) l.draw(make(base)); + check("unchanged", rig, l, once(3)); + } + // Each draw changes one more piece than the one before: only that piece is set again. + { + CommandList l; + Spec s = base; + l.draw(make(s)); + s.s0 = 1; // push constants + l.draw(make(s)); + s.viewport_x = 8; + l.draw(make(s)); + s.scissor_right = 32; + l.draw(make(s)); + s.topology = 5; // strip; restart stays off (no strip cut) + l.draw(make(s)); + s.stencil_front = 1; + l.draw(make(s)); + s.stencil_back = 2; + l.draw(make(s)); + s.blend = 0.5f; + l.draw(make(s)); + s.vertex1 = geometry + 12288; // slot 1 only + l.draw(make(s)); + s.index = geometry + 16384; + l.draw(make(s)); + s.index_format = 42; // DXGI_FORMAT_R32_UINT + l.draw(make(s)); + s.pipeline = p5; // a 32-bit strip cut: restart on + l.draw(make(s)); + Calls want = once(12); + want.graphics_pipeline = want.graphics_push = want.viewport = want.scissor = want.topology = want.restart = + want.stencil_front = want.stencil_back = want.blend = 2; + want.vertex = 3; + want.index = 3; + check("one change at a time", rig, l, want); + } + // Set 0 and push constants stay across a layout compatible for them (p2), not across another push range (p4). + { + CommandList l; + for (const std::uintptr_t p : {p1, p2, p4, p1}) { + Spec s = base; + s.pipeline = p; + l.draw(make(s)); + } + Calls want = once(4); + want.graphics_pipeline = 4; + want.graphics_set = want.graphics_push = 3; + check("layouts", rig, l, want); + } + // A pipeline without vertex input leaves the strides static: the vertex buffers are bound again after it. Set 0 + // stays bound through it. + { + CommandList l; + for (const std::uintptr_t p : {p1, p3, p1}) { + Spec s = base; + s.pipeline = p; + l.draw(make(s)); + } + Calls want = once(3); + want.graphics_pipeline = 3; + want.vertex = 4; + check("no vertex input", rig, l, want); + } + // A dispatch, direct or indirect, binds a compute pipeline, set 0 and push constants: everything is set again. + { + CommandList l; + l.draw(make(base)); + l.dispatch({compute, {}, 1, 1, 1}); + l.draw(make(base)); + ExecuteIndirect indirect; + indirect.kind = IndirectKind::dispatch; + indirect.stride = 12; + indirect.max_count = 1; + indirect.argument_buffer = upload; + indirect.pipeline = compute; + l.execute_indirect(indirect); + l.draw(make(base)); + Calls want = once(3); + want.graphics_pipeline = want.graphics_set = want.graphics_push = 3; + want.viewport = want.scissor = want.topology = want.restart = want.stencil_front = want.stencil_back = + want.blend = 3; + want.vertex = 6; + want.index = 3; + want.compute_pipeline = want.compute_set = want.compute_push = 2; + want.dispatches = 2; + check("dispatches", rig, l, want); + } + // Barriers, clears (one in a rendering scope of its own), a copy, a marker, a query and an indirect draw bind + // nothing: the draw after them sets nothing. + { + CommandList l; + l.draw(make(base)); + l.transition({upload, all_subresources, d3d12_state::copy_source, d3d12_state::copy_dest}); + l.barrier(BufferBarrier{d3d12_sync::copy, d3d12_sync::pixel_shading, d3d12_access::copy_dest, + d3d12_access::shader_resource, upload}); + const Rect rect{0, 0, 16, 16}; + l.clear_render_target({color, 0, 0, 1}, {0, 0, 0, 1}, {&rect, 1}); + l.clear_render_target({color, 0, 0, 1}, {0, 0, 0, 1}); + l.copy_buffer({results, 0, upload, 0, 256}); + l.marker(DebugMarker::Kind::set, "between"); + l.begin_query({occlusion_heap, d3d12_query::occlusion, 0}); + l.end_query({occlusion_heap, d3d12_query::occlusion, 0}); + ExecuteIndirect indirect; + indirect.kind = IndirectKind::draw; + indirect.stride = 16; + indirect.max_count = 1; + indirect.argument_buffer = upload; + l.execute_indirect(indirect); + l.draw(make(base)); + Calls want = once(2); + want.scopes = 3; + check("commands that bind nothing", rig, l, want); + } + // SetPredication on a buffer captures the predicate with a helper dispatch; turning it off runs nothing. + { + CommandList l; + l.draw(make(base)); + l.set_predication({predicate, 0, d3d12_predication::equal_zero}); + l.draw(make(base)); + l.set_predication({0, 0, 0}); + l.draw(make(base)); + Calls want = once(3); + want.graphics_pipeline = want.graphics_set = want.graphics_push = 2; + want.viewport = want.scissor = want.topology = want.restart = want.stencil_front = want.stencil_back = + want.blend = 2; + want.vertex = 4; + want.index = 2; + want.helpers = 1; + check("predication", rig, l, want); + } + // A binary-occlusion resolve runs a helper dispatch. + { + CommandList l; + l.begin_query({occlusion_heap, d3d12_query::binary_occlusion, 1}); + l.draw(make(base)); + l.end_query({occlusion_heap, d3d12_query::binary_occlusion, 1}); + l.resolve_queries({occlusion_heap, d3d12_query::binary_occlusion, 1, 1, results, 0}); + l.draw(make(base)); + Calls want = once(2); + want.graphics_pipeline = want.graphics_set = want.graphics_push = 2; + want.viewport = want.scissor = want.topology = want.restart = want.stencil_front = want.stencil_back = + want.blend = 2; + want.vertex = 4; + want.index = 2; + want.helpers = 1; + check("query resolve", rig, l, want); + } + // An index buffer stays bound through a draw that reads none. + { + CommandList l; + Spec plain = base; + plain.indexed = false; + l.draw(make(base)); + l.draw(make(plain)); + l.draw(make(base)); + check("non-indexed between indexed", rig, l, once(3)); + } + // A bundle's draws are the parent's (flattened): the same state is not set again across it. + { + CommandList bundle, l; + bundle.draw(make(base)); + bundle.close(); + l.draw(make(base)); + l.execute_bundle(bundle); + l.draw(make(base)); + check("bundle", rig, l, once(3)); + } + // Each emit starts with nothing known, even into the command buffer the last one wrote. + { + CommandList l; + l.draw(make(base)); + l.draw(make(base)); + Calls want = once(4); + want.graphics_pipeline = want.graphics_set = want.graphics_push = 2; + want.viewport = want.scissor = want.topology = want.restart = want.stencil_front = want.stencil_back = + want.blend = 2; + want.vertex = 4; + want.index = 2; + check("two emits", rig, l, want, 2); + } + std::printf("replay draw state: %s\n", failures ? "FAILED" : "ok"); + return failures ? 1 : 0; +}