diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 45d4b4be47..77f86bc9c1 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -514,8 +514,20 @@ What is implemented (all of it testable without the game): operation inherits the graphics state of its command list. The Vulkan replay snapshots the same pipeline, root data, render targets, IA bindings and raster state as a direct draw, then reads the records on the GPU inside that draw's rendering scope. A padded stride is supported; it is not evidence that a signature is simple. - A compound graphics signature still emits no draw, but its written VB/IB and root bindings are reset for the - next command, even if no record is interpreted. Untouched slots and previously recorded draws retain their state. + A compound graphics signature (root or IA arguments before its DRAW) is expanded on the CPU into the calls its + records stand for: each record's vertex buffer views, index buffer view, root constants and root CBVs are + applied in the signature's argument order, then its DRAW or DRAW_INDEXED is recorded, so the draw reads the + bindings the argument buffer names instead of the ones the list had bound. The expansion needs the record bytes + on the CPU, so only a buffer whose memory the CPU can map (an upload or readback heap in practice) is replayed, + for the argument bytes and for the count buffer's DWORD alike. Those bytes are read when the call is *recorded*, + not when the list executes, so an application that rewrites the argument buffer between recording and execution - + a ring buffer filled just before `ExecuteCommandLists`, or a list reused with a new buffer - replays the records + that were there at record time; a count the GPU writes (a `CopyBufferRegion` into the count buffer, say) is not + seen, and the call replays the count that was there when it was recorded. Keeping the buffer referenced and expanding at + replay would match the runtime's timing; until then, fill the buffer before recording. A device-local + buffer, which the GPU may have written, still draws nothing. In both cases every binding the signature writes is + reset after the call, even if no record is interpreted, as the D3D12 runtime does; untouched slots and previously + recorded draws retain their state. See the [D3D12 state-leakage contract](https://microsoft.github.io/DirectX-Specs/d3d/IndirectDrawing.html#state-leakage). Fixed- and GPU-counted batches use the device's enabled indirect features and limits. The current graphics path covers triangle lists on direct command lists. A bundle can defer a single operation with no count @@ -523,8 +535,8 @@ What is implemented (all of it testable without the game): direct parent's state at that call. Count buffers and compound signatures remain invalid in bundles. `d3d12_bundle_indirect_warp` and `d3d12_bundle_indirect_layer` compare DRAW and DRAW_INDEXED against direct pixels with two different parent bindings; the layer fixture also checks marker order and captured views. - Compound graphics signatures, non-unit instance divisors - and unsupported capabilities stay guarded. A GPU-counted draw currently requires + A compound graphics signature whose record bytes are not host-mappable stays guarded, as do + non-unit instance divisors and unsupported capabilities. A GPU-counted draw currently requires `maxDrawIndirectCount == UINT32_MAX`: Vulkan also limits the raw counter value, not just the caller's maximum. To omit indirect graphics without changing direct drawing or compute, set `LEONIDA_INDIRECT_DRAWS=off` before starting the process. This applies to the Vulkan-backed D3D12 @@ -1304,6 +1316,9 @@ and any validation error fails them. `d3d12_stateful_indirect_counted_pixels`: positive D3D12-to-Vulkan graphics tests. Compare every readback pixel with both a direct-draw reference and a known pattern for each draw kind; the counted variant fills its argument and count buffers by GPU copy before use. +- `d3d12_compound_indirect_pixels`: a compound signature whose two records carry two vertex buffer views, the + index buffer view, two root constants and a root CBV each. The picture must match the same calls made by hand + and must not match the state the list had bound before the indirect call. - `d3d12_indirect_rt_test`: validates `ID3D12Device::CreateCommandSignature` + `ExecuteIndirect` with a GPU `CountBuffer` (`vkCmdDrawIndirectCount`, `count = 0` skipped and `count = 1` rendered), a draw whose record asks for four billion instances (clamped on the GPU, section 4.7), and a native Vulkan counted-draw reference over the @@ -5340,3 +5355,4 @@ The public Xbox graphics index retrieved for this document lists interfaces up t `ID3D12GraphicsCommandList7`; the shipped DLL names `Device11` and `CommandList8`, which the index does not cover. This is why the layer targets the Windows SDK's newer public chain rather than assuming the Xbox public index is complete. + diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f8edc3508e..312bcdf552 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3999,13 +3999,16 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_stateful_indirect_pixels COMMAND d3d12_draw_test --stateful-indirect-pixels) add_test(NAME d3d12_stateful_indirect_multi_pixels COMMAND d3d12_draw_test --stateful-indirect-multi-pixels) add_test(NAME d3d12_stateful_indirect_counted_pixels COMMAND d3d12_draw_test --stateful-indirect-counted-pixels) + # A compound signature whose records carry their own state (two vertex buffer views, the index buffer, root + # constants and a root CBV): the picture must come from the argument buffer, not from what the list had bound. + add_test(NAME d3d12_compound_indirect_pixels COMMAND d3d12_draw_test --compound-indirect-pixels) # A device without robust indexed views can still validate each ordinary DRAW pixel oracle. add_test(NAME d3d12_stateful_indirect_nonindexed_pixels COMMAND d3d12_draw_test --stateful-indirect-pixels --nonindexed-only) add_test(NAME d3d12_stateful_indirect_nonindexed_multi_pixels COMMAND d3d12_draw_test --stateful-indirect-multi-pixels --nonindexed-only) add_test(NAME d3d12_stateful_indirect_nonindexed_counted_pixels COMMAND d3d12_draw_test --stateful-indirect-counted-pixels --nonindexed-only) set_tests_properties(d3d12_stateful_indirect_pixels d3d12_stateful_indirect_multi_pixels d3d12_stateful_indirect_counted_pixels d3d12_stateful_indirect_nonindexed_pixels d3d12_stateful_indirect_nonindexed_multi_pixels - d3d12_stateful_indirect_nonindexed_counted_pixels PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + d3d12_stateful_indirect_nonindexed_counted_pixels d3d12_compound_indirect_pixels PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) add_test(NAME d3d12_title_index_window COMMAND d3d12_draw_test --title-index-window) add_test(NAME d3d12_title_vertex_window COMMAND d3d12_draw_test --title-vertex-window) # LEONIDA_STUB_PIPELINES: a pipeline with no translated shader is a no-op stub when the switch is on. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4a61ffadbc..e7ce3683ab 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1036,9 +1036,17 @@ class GraphicsCommandList final } if (!terminal_only && (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed)) { if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); - // Compound draw emission is not yet supported. Reset the written bindings even if no - // records execute. Bundle nesting and prefixes were already rejected above for bundles. - leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::compound); + // A compound graphics signature binds state per record (vertex and index buffer views, root constants, + // root views) before its DRAW. Vulkan has no indirect call that rebinds state, so the record list is + // expanded into the calls it stands for (docs/d3d12_vulkan.md 4.7). Only a host-visible argument and + // count buffer can be expanded: a device-local one may be GPU-written, and that list keeps the + // reset-only path. Bundle nesting and prefixes were already rejected above for bundles. + if (!expand_compound_indirect(*sig, max_command_count, argument_buffer, argument_buffer_offset, + count_buffer, count_buffer_offset)) + leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, + leonida::indirect_stats::compound); + // State leakage, as the D3D12 runtime does it: every binding the signature writes is reset after the + // call, even when no record ran. if (!list_.closed()) reset_indirect_graphics_bindings(sig->graphics_writes()); return; } @@ -1820,6 +1828,125 @@ class GraphicsCommandList final set_pipeline(state); } + // A compound graphics signature writes state in every record and then draws with it. Neither Vulkan's indirect + // draws nor the replay's per-draw state snapshot can carry that, so each record is expanded here into the state + // calls the application could have made and the draw they precede; the record layout is packed in the signature's + // argument order (D3D12 Indirect Drawing, "Indirect Argument Buffer Structures"). Expansion needs the bytes on the + // CPU, which only a host-visible argument and count buffer give. False means no record was expanded: the caller + // keeps the reset-only path, which is all a device-local (potentially GPU-written) list can get. + bool expand_compound_indirect(const CommandSignature& sig, UINT max_command_count, ID3D12Resource* argument_buffer, + UINT64 argument_buffer_offset, ID3D12Resource* count_buffer, + UINT64 count_buffer_offset) { + const bool indexed = sig.kind() == leonida::IndirectKind::draw_indexed; + // The same prerequisites a direct draw needs; a record list that cannot draw records nothing. + if (!graphics_pipeline_ || !graphics_.layout || !topology_) return false; + void* base = nullptr; + if (FAILED(argument_buffer->Map(0, nullptr, &base)) || !base) return false; + // Every argument is checked before the first record is recorded, so a shape this code cannot decode leaves + // the list as it was instead of expanding part of it. A creation-valid signature passes all of these. + for (const auto& arg : sig.graphics_writes()) { + switch (arg.Type) { + case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: + if (arg.VertexBuffer.Slot >= vertex_buffers_.size()) return false; + break; + case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: + case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: + case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: + case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: + case compat::kIndirectArgumentIncrementingConstant: break; + case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: + if (!arg.Constant.Num32BitValuesToSet || arg.Constant.Num32BitValuesToSet > D3D12_MAX_ROOT_COST) + return false; + break; + default: return false; // creation excludes every other non-terminal argument + } + } + UINT records = max_command_count; + if (count_buffer) { + void* counts = nullptr; + if (count_buffer_offset % sizeof(std::uint32_t) || + count_buffer_offset + sizeof(std::uint32_t) > count_buffer->GetDesc().Width || + FAILED(count_buffer->Map(0, nullptr, &counts)) || !counts) + return false; + std::uint32_t gpu_count = 0; + std::memcpy(&gpu_count, static_cast(counts) + count_buffer_offset, sizeof gpu_count); + records = std::min(records, gpu_count); // D3D12Core: min(MaxCommandCount, the buffer's uint32) + } + const auto* base_bytes = static_cast(base); + for (UINT record = 0; record < records; ++record) { + const std::uint8_t* cursor = base_bytes + argument_buffer_offset + std::uint64_t(record) * sig.stride(); + const auto take = [&cursor](std::size_t bytes) { + const std::uint8_t* at = cursor; + cursor += bytes; + return at; + }; + // Bounds are the caller's: packed_size <= stride and the last record's packed bytes fit the buffer. + for (const auto& arg : sig.graphics_writes()) { + switch (arg.Type) { + case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: { + D3D12_VERTEX_BUFFER_VIEW view{}; + std::memcpy(&view, take(sizeof view), sizeof view); + set_vertex_buffers(arg.VertexBuffer.Slot, 1, &view); + break; + } + case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: { + D3D12_INDEX_BUFFER_VIEW view{}; + std::memcpy(&view, take(sizeof view), sizeof view); + set_index_buffer(&view); + break; + } + case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: { + const UINT count = arg.Constant.Num32BitValuesToSet; + std::array words{}; + std::memcpy(words.data(), take(sizeof(std::uint32_t) * count), sizeof(std::uint32_t) * count); + constants(graphics_, arg.Constant.RootParameterIndex, count, words.data(), + arg.Constant.DestOffsetIn32BitValues); + break; + } + case compat::kIndirectArgumentIncrementingConstant: { + // Tier 1.1: the argument occupies no record bytes; the value is the record's index. + constants(graphics_, arg.Constant.RootParameterIndex, 1, &record, + arg.Constant.DestOffsetIn32BitValues); + break; + } + case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: + case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: + case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: { + D3D12_GPU_VIRTUAL_ADDRESS va = 0; + std::memcpy(&va, take(sizeof va), sizeof va); + const UINT index = arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW + ? arg.ConstantBufferView.RootParameterIndex + : arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW + ? arg.ShaderResourceView.RootParameterIndex + : arg.UnorderedAccessView.RootParameterIndex; + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + break; + } + default: return false; // creation excludes every other non-terminal argument + } + } + // The record's terminal operation, with the state above already in effect. + if (indexed) { + D3D12_DRAW_INDEXED_ARGUMENTS draw{}; + std::memcpy(&draw, cursor, sizeof draw); + if (!(index_.va && index_.size && + (index_.format == DXGI_FORMAT_R16_UINT || index_.format == DXGI_FORMAT_R32_UINT))) { + leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, + leonida::indirect_stats::index_view); + continue; + } + record_draw(true, draw.IndexCountPerInstance, draw.InstanceCount, draw.StartIndexLocation, + draw.BaseVertexLocation, draw.StartInstanceLocation); + } else { + D3D12_DRAW_ARGUMENTS draw{}; + std::memcpy(&draw, cursor, sizeof draw); + record_draw(false, draw.VertexCountPerInstance, draw.InstanceCount, draw.StartVertexLocation, 0, + draw.StartInstanceLocation); + } + } + return true; + } + void reset_indirect_graphics_bindings(std::span writes) { static constexpr std::array zeros{}; for (const auto& arg : writes) { diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index ffbfbf718d..3bf5a8a82e 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -80,12 +80,17 @@ static_assert(offsetof(Vertex, wrong_color) == 16); // Positive-only offscreen variant, sharing the translated-shader fixture, root signature and PSO description. int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* root, D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, bool multi, bool counted, bool nonindexed_only); +// The compound-signature variant: its records carry their own vertex and index buffer views and root arguments. +int check_compound_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* root, + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc); int main(int argc, char** argv) { const bool nonindexed_only = argc == 3 && std::strcmp(argv[2], "--nonindexed-only") == 0; const bool indirect_mode = argc == 2 || nonindexed_only; const bool multi_pixels = indirect_mode && std::strcmp(argv[1], "--stateful-indirect-multi-pixels") == 0; const bool count_pixels = indirect_mode && std::strcmp(argv[1], "--stateful-indirect-counted-pixels") == 0; + // Compound signatures need no indirect draw feature: every record is expanded into ordinary draws. + const bool compound_pixels = indirect_mode && std::strcmp(argv[1], "--compound-indirect-pixels") == 0; const bool indirect_pixels = multi_pixels || count_pixels || (indirect_mode && std::strcmp(argv[1], "--stateful-indirect-pixels") == 0); if (argc > 2 && !(nonindexed_only && indirect_pixels)) return 1; @@ -249,6 +254,11 @@ int main(int argc, char** argv) { EXPECT(d.validation_errors() == 0); return result; } + if (compound_pixels) { + const int result = check_compound_indirect_pixels(device.p, root.p, pso_desc); + EXPECT(d.validation_errors() == 0); + return result; + } Ref pso, unfed, mrt, instanced, refused, xor_pso, fullscreen; EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); pso_desc.InputLayout = {elements, 1}; // COLOR missing: D3D12 rejects a layout that leaves an input unfed diff --git a/runtime/test/d3d12_stateful_indirect_pixels.cpp b/runtime/test/d3d12_stateful_indirect_pixels.cpp index 7672c13a46..8292e7a281 100644 --- a/runtime/test/d3d12_stateful_indirect_pixels.cpp +++ b/runtime/test/d3d12_stateful_indirect_pixels.cpp @@ -1,5 +1,6 @@ // Positive graphics replay only: the direct and indirect submissions each draw into a fresh offscreen target. // The quadrant depends on the indexed vertices; red requires firstInstance=1. No title, presentation or display. +// The compound-signature fixture below spends its own offscreen targets the same way. #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -17,6 +18,15 @@ using namespace d3d12test; } \ } while (0) +// The same, for a helper that answers false and leaves the failure to its caller. +#define CHECK_IN(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "indirect pixels line %d: %s\n", __LINE__, #x); \ + return false; \ + } \ + } while (0) + int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* root, D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, bool multi, bool counted, bool nonindexed_only) { constexpr UINT side = 64, pitch = side * 4; @@ -122,14 +132,23 @@ int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* ro CHECK(kind == leonida::IndirectKind::draw && stride == 48 && terminal_only == !compound); } } - // Record-only: an unsupported compound draw still resets its written bindings. Nothing from - // this list is submitted. The ordinary draws either side expose the two immutable state snapshots. - for (UINT scenario = 0; !multi && !counted && scenario < 3; ++scenario) { + // Record-only, nothing from these lists is submitted. A compound record is expanded into the state calls and the + // draw it stands for, and every binding it wrote is reset afterwards (D3D12's state-leakage rule). A record list + // the CPU cannot read keeps the reset only. The ordinary draws either side expose the two state snapshots. + for (UINT scenario = 0; !multi && !counted && scenario < 4; ++scenario) { Ref allocator; Ref list; + Ref gpu_args; 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, pso.p, IID_PPV_ARGS(&list.p)))); + // Scenario 3: the same records in a device-local buffer. The CPU cannot read it and the GPU may have written + // it, so the layer may not expand it: nothing is drawn and only the written bindings are reset. + if (scenario == 3) { + const auto gpu_desc = buffer_desc(2048); + CHECK(SUCCEEDED(device->CreateCommittedResource(&def_heap, {}, &gpu_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&gpu_args.p)))); + } Ref compound; { D3D12_INDIRECT_ARGUMENT_DESC members[5]{}; @@ -156,14 +175,15 @@ int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* ro list->DrawInstanced(3, 1, 0, 0); // The two packed records fit exactly, without trailing padding. Fixed zero and GPU count zero // have the same postcondition. The count DWORD at offset zero is separate from the records. - list->ExecuteIndirect(compound.p, scenario == 1 ? 0 : 2, args.p, compound_at, + list->ExecuteIndirect(compound.p, scenario == 1 ? 0 : 2, scenario == 3 ? gpu_args.p : args.p, compound_at, scenario == 2 ? args.p : nullptr, 0); list->DrawInstanced(3, 1, 0, 0); CHECK(list->Close() == S_OK); std::vector recorded; - CHECK(rt::d3d12::recorded_commands(list.p, recorded) && recorded.size() == 2); - const auto* before = std::get_if(&recorded[0]); - const auto* after = std::get_if(&recorded[1]); + // Scenario 0 draws the two readable records; 1 has no record, 2 a GPU count of zero, 3 an unreadable list. + CHECK(rt::d3d12::recorded_commands(list.p, recorded) && recorded.size() == (scenario == 0 ? 4u : 2u)); + const auto* before = std::get_if(&recorded.front()); + const auto* after = std::get_if(&recorded.back()); CHECK(before && after && before->views && after->views && before->views != after->views); CHECK(before->views->vertex_buffers[5].va == va && after->views->vertex_buffers[5].va == 0); CHECK(after->views->vertex_buffers[0].va == va && after->views->vertex_buffers[1].va == va + 1024); @@ -178,6 +198,23 @@ int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* ro auto expected_words = before->user_data; expected_words[c0 + 1] = expected_words[view] = expected_words[view + 1] = 0; CHECK(after->user_data == expected_words); + if (scenario == 0) { + // The two expanded records carry the state the argument buffer names: slot 5 and the index buffer come + // from the record, and its single root constant lands in the second of the list's two words. + for (std::size_t i = 1; i <= 2; ++i) { + const auto* record = std::get_if(&recorded[i]); + const auto& expected = indexed_draw[i - 1]; + CHECK(record && record->indexed && record->count == expected.IndexCountPerInstance && + record->instances == expected.InstanceCount && record->first == expected.StartIndexLocation && + record->base_vertex == expected.BaseVertexLocation && + record->first_instance == expected.StartInstanceLocation); + CHECK(record->views && record->views->vertex_buffers[5].va == va); + CHECK(record->index.va == ib.BufferLocation); + // The record sets the second dword of the pair (DestOffsetIn32BitValues 1): the first keeps the value + // the list already had. + CHECK(record->user_data[c0] == 37 && record->user_data[c0 + 1] == 0); + } + } if (scenario == 0) { // Recording check only, never submitted: omit the last DWORD of the compound record. CHECK(SUCCEEDED(list->Reset(allocator.p, pso.p))); @@ -320,3 +357,206 @@ int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* ro } return 0; } + +// A compound graphics signature: every record writes its own state (two root constants, a root CBV, both vertex +// buffer slots and the index buffer) and then draws. The picture must come from the record, never from what the list +// had bound when ExecuteIndirect was recorded. Two records place the same indexed quad at two clip-space offsets, so a +// layer that applies one record's state to both of them, or none at all, cannot match the same calls made by hand. +int check_compound_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* root, + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc) { + constexpr UINT side = 64, pitch = side * 4; + using Image = std::array; + // Indices 2..7 with base vertex 1 select vertices 7, 8, 9, 9, 8 and 12: the unit square of the top-right quadrant. + constexpr float xy[][2] = { + {0, 0}, {-1, 1}, {0, 1}, {-1, 0}, {-1, 0}, {0, 1}, {0, 0}, // the left square, which this record does not draw + {0, 1}, {1, 1}, {0, 0}, {0, 0}, {1, 1}, {1, 0} // the right square: the record's own vertices + }; + // The same vertices half a unit lower, for the buffer the list has bound before the call: an ignored record draws + // those instead. Only translated, so the winding that culling tests is the one the reference draws with. + constexpr float xy_decoy[][2] = { + {0, -0.5f}, {-1, 0.5f}, {0, 0.5f}, {-1, -0.5f}, {-1, -0.5f}, {0, 0.5f}, {0, -0.5f}, + {0, 0.5f}, {1, 0.5f}, {0, -0.5f}, {0, -0.5f}, {1, 0.5f}, {1, -0.5f} + }; + constexpr std::uint16_t indices[] = {0, 0, 6, 7, 8, 8, 7, 11, 0, 1, 2, 2, 1, 5}; + constexpr std::uint16_t decoy_indices[] = {0, 0, 0, 1, 2, 3, 4, 5}; + constexpr std::uint8_t colors[][4] = {{0, 255, 0, 255}, {255, 0, 0, 255}, {255, 0, 255, 255}}; + constexpr float record_tint[3] = {0, 1, 0}, decoy_tint[3] = {1, 0, 1}; // a root CBV each: green, then magenta + constexpr float record_offset[2][2] = {{-0.5f, 0}, {0.5f, 0}}, decoy_offset[2] = {0.25f, 0.25f}; + constexpr float blue[]{0, 0, 1, 1}; + constexpr UINT record_count = 2, stride = 96, arguments_at = 512; + const std::array layout{ + {{"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1}}}; + desc.InputLayout = {layout.data(), UINT(layout.size())}; + Ref pso; + CHECK(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, read_heap{D3D12_HEAP_TYPE_READBACK}, + def_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto upload_desc = buffer_desc(2048), rb_desc = buffer_desc(sizeof(Image)); + Ref input, arguments; + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, {}, &upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&input.p)))); + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, {}, &upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&arguments.p)))); + std::uint8_t* data{}; + CHECK(SUCCEEDED(input->Map(0, nullptr, reinterpret_cast(&data)))); + std::memcpy(data, xy, sizeof(xy)); + std::memcpy(data + 256, indices, sizeof(indices)); + std::memcpy(data + 512, record_tint, sizeof(record_tint)); + std::memcpy(data + 768, decoy_tint, sizeof(decoy_tint)); + std::memcpy(data + 1024, colors, sizeof(colors)); + std::memcpy(data + 1280, xy_decoy, sizeof(xy_decoy)); + std::memcpy(data + 1536, decoy_indices, sizeof(decoy_indices)); + input->Unmap(0, nullptr); + const auto va = input->GetGPUVirtualAddress(); + const D3D12_VERTEX_BUFFER_VIEW record_views[] = {{va, sizeof(xy), sizeof(xy[0])}, + {va + 1024, sizeof(colors), sizeof(colors[0])}}; + const D3D12_VERTEX_BUFFER_VIEW decoy_views[] = {{va + 1280, sizeof(xy_decoy), sizeof(xy_decoy[0])}, + {va + 1024, sizeof(colors), sizeof(colors[0])}}; + const D3D12_INDEX_BUFFER_VIEW record_index{va + 256, sizeof(indices), DXGI_FORMAT_R16_UINT}; + const D3D12_INDEX_BUFFER_VIEW decoy_index{va + 1536, sizeof(decoy_indices), DXGI_FORMAT_R16_UINT}; + const D3D12_GPU_VIRTUAL_ADDRESS record_cbv = va + 512; + const D3D12_DRAW_INDEXED_ARGUMENTS draw{6, 1, 2, 1, 0}; // six indices, base vertex 1, instance 0 + CHECK(SUCCEEDED(arguments->Map(0, nullptr, reinterpret_cast(&data)))); + std::memset(data, 0, 2048); + for (UINT i = 0; i < record_count; ++i) { + // One record, packed in the signature's argument order: two constants, the root CBV, both vertex buffer + // views, the index buffer view, then the draw. ByteStride pads each record to 96. + std::uint8_t* record = data + arguments_at + i * stride; + std::memcpy(record, record_offset[i], sizeof(record_offset[i])); + std::memcpy(record + 8, &record_cbv, sizeof(record_cbv)); + std::memcpy(record + 16, &record_views[0], sizeof(record_views[0])); + std::memcpy(record + 32, &record_views[1], sizeof(record_views[1])); + std::memcpy(record + 48, &record_index, sizeof(record_index)); + std::memcpy(record + 64, &draw, sizeof(draw)); + } + arguments->Unmap(0, nullptr); + D3D12_INDIRECT_ARGUMENT_DESC members[6]{}; + members[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT; + members[0].Constant = {0, 0, 2}; + members[1].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW; + members[1].ConstantBufferView.RootParameterIndex = 1; + members[2].Type = D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW; + members[2].VertexBuffer.Slot = 0; + members[3].Type = D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW; + members[3].VertexBuffer.Slot = 1; + members[4].Type = D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW; + members[5].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{stride, 6, members, 0}; + Ref compound; + CHECK(SUCCEEDED(device->CreateCommandSignature(&signature_desc, root, IID_PPV_ARGS(&compound.p)))); + auto kind = leonida::IndirectKind::dispatch; + UINT byte_stride = 0; + bool terminal_only = true; + CHECK(rt::d3d12::command_signature_info(compound.p, kind, byte_stride, terminal_only)); + CHECK(kind == leonida::IndirectKind::draw_indexed && byte_stride == stride && !terminal_only); + + const D3D12_VIEWPORT viewport{0, 0, float(side), float(side), 0, 1}; + const D3D12_RECT scissor{0, 0, side, side}; + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = tex.Height = side; + tex.DepthOrArraySize = tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void*); + // mode 0: the record list through ExecuteIndirect. mode 1: the calls a record stands for. mode 2: those calls + // with only the state the list had bound before the indirect call. + const auto render = [&](UINT mode, Image& image) -> bool { + Ref target, readback; + Ref heap; + Ref allocator; + Ref list; + Ref fence; + CHECK_IN(SUCCEEDED(device->CreateCommittedResource(&def_heap, {}, &tex, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&target.p)))); + CHECK_IN(SUCCEEDED(device->CreateCommittedResource(&read_heap, {}, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)))); + CHECK_IN(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(heap.p, 9))(heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + CHECK_IN(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK_IN(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + CHECK_IN(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + auto b = transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &b); + list->ClearRenderTargetView(rtv, blue, 0, nullptr); + list->SetGraphicsRootSignature(root); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + // What the list has bound before the call: a mirrored vertex buffer, another index buffer and the other root + // arguments. No record may draw with any of it. + list->IASetVertexBuffers(0, 2, decoy_views); + list->IASetIndexBuffer(&decoy_index); + list->SetGraphicsRoot32BitConstants(0, 2, decoy_offset, 0); + list->SetGraphicsRootConstantBufferView(1, va + 768); + if (mode == 0) { + list->ExecuteIndirect(compound.p, record_count, arguments.p, arguments_at, nullptr, 0); + } else { + for (UINT i = 0; i < record_count; ++i) { + if (mode == 1) { + list->IASetVertexBuffers(0, 2, record_views); + list->IASetIndexBuffer(&record_index); + list->SetGraphicsRoot32BitConstants(0, 2, record_offset[i], 0); + list->SetGraphicsRootConstantBufferView(1, record_cbv); + } + list->DrawIndexedInstanced(draw.IndexCountPerInstance, draw.InstanceCount, draw.StartIndexLocation, + draw.BaseVertexLocation, draw.StartInstanceLocation); + } + } + b = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b); + D3D12_TEXTURE_COPY_LOCATION dst{}, src{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {tex.Format, side, side, 1, pitch}}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + CHECK_IN(list->Close() == S_OK); + ID3D12CommandList* lists[]{list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK_IN(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + CHECK_IN(SUCCEEDED(queue->Signal(fence.p, 1))); + CHECK_IN(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + void* mapped{}; + CHECK_IN(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(image.data(), mapped, image.size()); + readback->Unmap(0, nullptr); + return true; + }; + Image indirect_image{}, reference{}, decoy_image{}; + CHECK(render(0, indirect_image)); + CHECK(render(1, reference)); + CHECK(render(2, decoy_image)); + constexpr std::uint8_t clear[4] = {0, 0, 255, 255}; + const auto lit = [&clear](const Image& image) { + unsigned count = 0; + for (std::size_t i = 0; i < image.size(); i += 4) count += std::memcmp(image.data() + i, clear, 4) != 0; + return count; + }; + unsigned wrong = 0; + for (std::size_t i = 0; i < reference.size(); i += 4) + wrong += std::memcmp(reference.data() + i, indirect_image.data() + i, 4) != 0; + std::printf("compound DRAW_INDEXED x%u (two vertex buffer views, the index buffer, two root constants and a root " + "CBV per record): %u lit pixels, %u/4096 RGBA pixel mismatches against the same calls made by hand; " + "the indirect list alone lights %u and the state the list had bound alone lights %u\n", + record_count, lit(reference), wrong, lit(indirect_image), lit(decoy_image)); + // The record list must draw (a layer that only resets leaves the clear colour), must not use what the list had + // bound, and must match the calls it stands for pixel for pixel. + CHECK(lit(reference) > 0 && lit(decoy_image) > 0); + CHECK(!wrong); + CHECK(indirect_image != decoy_image); + return 0; +} +