From 21f07a063ba0000cfeb8717075d28809056b3561 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:45:10 +0100 Subject: [PATCH 01/13] d3d12: draw the console's rectangle lists (17, PSO type 19) and quad lists (19) as triangles A rectangle list is three corners; the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage. A quad list is four vertices per quad. Vulkan has neither. A PSO with topology type 19 was refused (E_INVALIDARG) and the two list topologies drew as a plain triangle list. Rectangle list: the PSO becomes a triangle-list pipeline with a generated geometry stage (src/rect_list_geometry.h), built from the vertex shader's own SPIR-V outputs, that emits the strip v1 v2 v3 v4. Quad list: one triangle fan per quad (0 1 2, 0 2 3), drawn with the index values 4q..4q+3 so the translated vertex id (VertexIndex - BaseVertex) is right; non-indexed draws read a shared 0, 1, 2, ... buffer reserved in the arena. Facts from xvalkyrie (GPL-3.0, commit 53af7df77c10); no code copied. --- docs/d3d12_vulkan.md | 8 +- runtime/CMakeLists.txt | 9 + runtime/shims/d3d12_vulkan_device.cpp | 45 +++- runtime/src/rect_list_geometry.h | 214 ++++++++++++++++ runtime/src/vulkan_backend.h | 8 + runtime/src/vulkan_replay.h | 29 +++ runtime/test/d3d12_rect_list_test.cpp | 341 ++++++++++++++++++++++++++ 7 files changed, 649 insertions(+), 5 deletions(-) create mode 100644 runtime/src/rect_list_geometry.h create mode 100644 runtime/test/d3d12_rect_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..51a3a4a9ed 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -169,7 +169,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -2118,6 +2118,12 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..c422368d05 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2428,6 +2428,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..f6f7b50046 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,6 +18,7 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -65,7 +66,9 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the @@ -3460,6 +3463,14 @@ class PipelineState final log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); return E_NOTIMPL; } + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; + } if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); return E_INVALIDARG; @@ -3640,6 +3651,26 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return E_NOTIMPL; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -3714,7 +3745,8 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; @@ -5448,7 +5480,11 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + { + auto* iota = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5459,7 +5495,8 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); return true; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..ee7d69905c --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,214 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for +// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the +// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's +// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value +// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather +// than computed, so it cannot turn into a NaN. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, + op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), t_bool = id(), + t_v4bool = id(), t_v4uint = id(), c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_v4bool, t_bool, 4}); + emit(globals, op_type_vector, {t_v4uint, t_uint, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three corners, and the fourth. The fourth is v2 + v3 - v1, except where all three corners + // have the same bits (a flat value), where it is v1. + struct Corners { std::uint32_t v[4]; }; + std::vector corners; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + Corners c{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + c.v[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, c.v[k], ptr}); + } + const std::uint32_t sum = id(), diff = id(); + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + if (v.is_position) { + c.v[3] = diff; + } else { + const std::uint32_t b0 = id(), b1 = id(), b2 = id(), e1 = id(), e2 = id(), same = id(), pick = id(); + emit(body, op_bitcast, {t_v4uint, b0, c.v[0]}); + emit(body, op_bitcast, {t_v4uint, b1, c.v[1]}); + emit(body, op_bitcast, {t_v4uint, b2, c.v[2]}); + emit(body, op_iequal, {t_v4bool, e1, b1, b0}); + emit(body, op_iequal, {t_v4bool, e2, b2, b0}); + emit(body, op_logical_and, {t_v4bool, same, e1, e2}); + emit(body, op_select, {t_v4, pick, same, c.v[0], diff}); + c.v[3] = pick; + } + corners.push_back(c); + } + // The strip v1, v2, v3, v4. + for (int k = 0; k < 4; ++k) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {19}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 4}); // OutputVertices 4 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe89..c049698582 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1268,6 +1268,14 @@ class VulkanContext { replay_.zero_size = size; } + // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..9a1f0f404e 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -869,6 +870,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::functionzero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -2227,6 +2235,11 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three + // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), + // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -4207,6 +4220,22 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->topology == topology_quad_list) { + // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index + // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an + // indexed draw reads them from the application's index buffer, a non-indexed one from the + // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as + // VertexIndex is first + i for a plain draw. + const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there + if (generated) + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + else + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + for (std::uint32_t quad = 0; quad < quads; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, + vertex_offset, draw->first_instance); } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..05b90a81c8 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,341 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + 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 root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[2] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; + for (unsigned i = 0; i < 2; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " + "%u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, + target_extent * target_extent); + return 0; +} From 0688b839baf12e7a80795744c908a6ee3e4fdcc1 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:48:05 +0100 Subject: [PATCH 02/13] d3d12: rectangle list stage emits (v1 v2 v4) (v1 v4 v3) with capability Geometry, log cut-off quads (review fixes) --- docs/d3d12_vulkan.md | 2 +- runtime/src/rect_list_geometry.h | 57 ++++++++++++-------------------- runtime/src/vulkan_replay.h | 11 +++++- 3 files changed, 33 insertions(+), 37 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 51a3a4a9ed..9db4505959 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2122,7 +2122,7 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index ee7d69905c..335e4db00e 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -11,11 +11,10 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the -// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's -// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value -// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather -// than computed, so it cannot turn into a NaN. +// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of +// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. // // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. @@ -40,11 +39,10 @@ constexpr std::uint32_t topology_type_rect_list = 19; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { enum : std::uint32_t { - op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, - op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, - op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, op_capability = 17, op_memory_model = 14, op_execution_mode = 16, deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, storage_input = 1, storage_output = 3 @@ -113,17 +111,14 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; const std::uint32_t cs[3] = {c0, c1, c2}; @@ -170,32 +164,25 @@ inline std::vector rect_list_geometry(const std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; - emit(out, op_capability, {19}); // Geometry + emit(out, op_capability, {2}); // Geometry emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" entry.insert(entry.end(), io_vars.begin(), io_vars.end()); @@ -204,7 +191,7 @@ inline std::vector rect_list_geometry(const std::vector #include #include +#include #include #include #include @@ -4231,8 +4232,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); else vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. + const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; + const std::uint32_t quads = std::min(wanted, room); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + // All the instances of a quad are drawn together (a split by instance would zero the translated + // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad + // by quad, not instance by instance: only overlapping blended instances can tell. for (std::uint32_t quad = 0; quad < quads; ++quad) vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, vertex_offset, draw->first_instance); From abe64d495b0a22a78ccf9106f1980c2f550778e0 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:11:37 +0100 Subject: [PATCH 03/13] d3d12: quad lists draw as triangle-list indices (0 1 2) (0 2 3) so flat inputs use the first quad vertex, and the PSO topology type is read as raw bits Taken from the follow-up patch of @matheuskshn (930e78a2, tested by them on an RTX 4070 Ti: replay_quad_list_test fails the two non-indexed cases on a6b31d51 and passes with it). Re-run here: replay_quad_list_test and d3d12_rect_list_test exit 0 on the pod (Wine, RTX 4090). --- docs/d3d12_vulkan.md | 7 +- runtime/CMakeLists.txt | 6 ++ runtime/shims/d3d12_vulkan_device.cpp | 28 ++++--- runtime/src/rect_list_geometry.h | 2 + runtime/src/vulkan_backend.h | 2 +- runtime/src/vulkan_replay.h | 54 ++++++------ runtime/test/replay_quad_list_test.cpp | 110 +++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 41 deletions(-) create mode 100644 runtime/test/replay_quad_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9db4505959..6ecc34081d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2122,7 +2122,12 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. +- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern + `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance + order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still + read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking + vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type + is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index c422368d05..be338e70d3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3257,6 +3257,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f6f7b50046..945d10512b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -67,7 +67,8 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); @@ -3066,7 +3067,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -3466,13 +3468,15 @@ class PipelineState final // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. - const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -3746,12 +3750,12 @@ class PipelineState final } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. - switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -3773,7 +3777,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return E_NOTIMPL; } @@ -5481,9 +5485,11 @@ class Device final } arena.mapped = static_cast(mapped); std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read - { - auto* iota = reinterpret_cast(arena.mapped + kZeroPage); - for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 335e4db00e..86826317c6 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -22,6 +22,7 @@ // Plain word editing, standard library only. #include +#include #include #include #include @@ -35,6 +36,7 @@ namespace leonida { constexpr std::uint32_t topology_rect_list = 17; constexpr std::uint32_t topology_quad_list = 19; constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index c049698582..02fdad1a09 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1268,7 +1268,7 @@ class VulkanContext { replay_.zero_size = size; } - // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); replay_.quad_indices = buffer; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 49554653ce..f9dfb6b030 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -871,7 +871,7 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; - // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. VkBuffer quad_indices = VK_NULL_HANDLE; VkDeviceSize quad_indices_offset = 0; std::uint32_t quad_index_count = 0; @@ -2199,7 +2199,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } - // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) return ReplayResult::unresolved_resource; if (draw.indexed) { @@ -2236,9 +2236,8 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three - // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), - // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; + // emit() overrides non-indexed quads to a triangle list backed by the shared indices. case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; @@ -4204,7 +4203,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : 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) || @@ -4222,29 +4222,27 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->topology == topology_quad_list) { - // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index - // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an - // indexed draw reads them from the application's index buffer, a non-indexed one from the - // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as - // VertexIndex is first + i for a plain draw. - const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there - if (generated) - vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); - else + if (draw->indexed) { + // Indexed quads still read their vertices from the application's index buffer, one fan per quad. vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. - const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; - const std::uint32_t quads = std::min(wanted, room); - if (quads < wanted) - std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", - wanted, quads); - const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; - // All the instances of a quad are drawn together (a split by instance would zero the translated - // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad - // by quad, not instance by instance: only overlapping blended instances can tell. - for (std::uint32_t quad = 0; quad < quads; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, - vertex_offset, draw->first_instance); + for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, + draw->base_vertex, draw->first_instance); + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..15b0c7e781 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,110 @@ +// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans +// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +#include "../src/vulkan_replay.h" + +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + }; + + vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + + GraphicsPipeline graphics{}; + const auto collect = [&](const Draw& draw) { + calls.clear(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + draw.indexed = true; + draw.count = 8; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; + const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; + ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, + "indexed quads use the application's index buffer and base vertex"); + return ok ? 0 : 1; +} From e3c22cc24693eb654be1bbea7cca32ebc62fd8b7 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:19:02 +0100 Subject: [PATCH 04/13] d3d12: rect_list_geometry records that packed f16 attributes cannot be told apart from float outputs on the vertex side (comment only) --- runtime/src/rect_list_geometry.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 86826317c6..15d7368d34 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -92,6 +92,10 @@ inline std::vector rect_list_geometry(const std::vector Date: Mon, 23 Nov 2026 21:52:35 +0100 Subject: [PATCH 05/13] d3d12: rectangle list geometry picks the right-angle corner per rectangle (the vertex opposite the longest screen edge) instead of assuming the first; tests for the corner at the second and third vertex and for a non-right triangle --- runtime/src/rect_list_geometry.h | 85 +++++++++++++++++++++----- runtime/test/d3d12_rect_list_test.cpp | 86 +++++++++++++++++++++++---- 2 files changed, 144 insertions(+), 27 deletions(-) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 15d7368d34..69b52f7e7f 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -2,8 +2,10 @@ // Console rectangle lists on Vulkan, which has no such primitive. // -// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for -// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its +// neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: +// the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest +// screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline // whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in // its backlog); no code is taken from it. // @@ -11,8 +13,8 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of -// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of +// (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), // and so is the stage's Position; the generated stage reads and writes exactly those. // @@ -44,7 +46,9 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; + std::vector> loaded; const std::uint32_t cs[3] = {c0, c1, c2}; for (const Var& v : vars) { - Corners c{}; + std::array three{}; for (int k = 0; k < 3; ++k) { const std::uint32_t ptr = id(); - c.v[k] = id(); + three[k] = id(); emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); - emit(body, op_load, {t_v4, c.v[k], ptr}); + emit(body, op_load, {t_v4, three[k], ptr}); } + loaded.push_back(three); + } + // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; + // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain + // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right + // triangle gets the same rule, so the choice is at least consistent. + std::uint32_t screen[3][2]; + for (int k = 0; k < 3; ++k) { + const std::uint32_t x = id(), y = id(), w = id(); + emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); + emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); + emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); + screen[k][0] = id(); + screen[k][1] = id(); + emit(body, op_fdiv, {t_float, screen[k][0], x, w}); + emit(body, op_fdiv, {t_float, screen[k][1], y, w}); + } + const auto squared_edge = [&](int a, int b) { + const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); + emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); + emit(body, op_fmul, {t_float, xx, dx, dx}); + emit(body, op_fmul, {t_float, yy, dy, dy}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); + const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); + emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); + emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); + emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner + emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); + emit(body, op_logical_not, {t_bool, not_first, at_first}); + emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 + const std::uint32_t first4 = id(), second4 = id(); + emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); + emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); + // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding + // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. + for (const auto& three : loaded) { + Corners c{}; + const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { + const std::uint32_t inner = id(), outer = id(); + emit(body, op_select, {t_v4, inner, second4, second, third}); + emit(body, op_select, {t_v4, outer, first4, first, inner}); + return outer; + }; + c.v[0] = pick(three[0], three[1], three[2]); + c.v[1] = pick(three[1], three[2], three[0]); + c.v[2] = pick(three[2], three[0], three[1]); const std::uint32_t sum = id(), diff = id(); emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); c.v[3] = diff; corners.push_back(c); } - // Two triangles, (v1, v2, v4) and (v1, v4, v3): the diagonal is v1 to v4, so both start at v1 and a flat input - // (which Vulkan takes from a triangle's first vertex) is v1's over the whole rectangle. The attributes are + // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input + // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are // affine over the parallelogram, so the split does not change any interpolated value. const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; for (const auto& triangle : triangles) { diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp index 05b90a81c8..5ab5611163 100644 --- a/runtime/test/d3d12_rect_list_test.cpp +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -7,6 +7,10 @@ // v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth // corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane // through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frames 3 to 5, rectangle lists whose right angle is at the second vertex, at the third vertex, and a triangle with +// no right angle at all. The layer takes the right-angle corner as the vertex opposite the longest screen edge, so +// the first two must cover all 64x64 pixels on the colour plane too (the retail boot's full-screen draw has its +// right angle at the second vertex); the third only has to draw something and not fail. // frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners // in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. // Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 @@ -86,12 +90,19 @@ int main() { // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; - const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + const Vertex vertices[20] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), - vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; - static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2), + // vertices 11..13: right angle at the second vertex; 14..16: at the third; 17..19: none + vertex(-1, 1, ca), vertex(1, 1, cb), vertex(1, -1, cc), + vertex(-1, 1, ca), vertex(1, -1, cb), vertex(-1, -1, cc), + vertex(-1, 1, ca), vertex(0.5f, 0.75f, cb), vertex(-0.25f, -1, cc)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 640); + const Vertex* const corner_cases[2] = {&vertices[11], &vertices[14]}; - std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent), + second_pixels(target_extent * target_extent), third_pixels(target_extent * target_extent), + skew_pixels(target_extent * target_extent); { rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = d.instance_proc; @@ -172,8 +183,9 @@ int main() { EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); std::memcpy(up, vertices, sizeof(vertices)); - // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + // V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners, slots 2 to 4 + // the three more rectangles. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); @@ -183,9 +195,12 @@ int main() { EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); EXPECT(buffer_va >= 0x10000); - const std::array vsharps[2] = {make_vsharp(buffer_va, 3), - make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; - for (unsigned i = 0; i < 2; ++i) + const std::array vsharps[5] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8), + make_vsharp(buffer_va + 11 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 14 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 17 * sizeof(Vertex), 3)}; + for (unsigned i = 0; i < 5; ++i) std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; @@ -263,6 +278,9 @@ int main() { }; EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + EXPECT(render_frame(3, rect_pso.p, rect_list, 2, 3, second_pixels) == 0); + EXPECT(render_frame(4, rect_pso.p, rect_list, 3, 3, third_pixels) == 0); + EXPECT(render_frame(5, rect_pso.p, rect_list, 4, 3, skew_pixels) == 0); for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); rect_pso.reset(); quad_pso.reset(); @@ -312,6 +330,46 @@ int main() { } EXPECT(covered == target_extent * target_extent); + // Right angle at the second and at the third vertex: the plane through the three drawn corners, everywhere. + const std::vector* const corner_pixels[2] = {&second_pixels, &third_pixels}; + const char* const corner_names[2] = {"second", "third"}; + unsigned corner_covered[2] = {0, 0}; + float corner_worst = 0.0f; + for (int which = 0; which < 2; ++which) { + const Vertex* t = corner_cases[which]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const Pixel& got = (*corner_pixels[which])[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (t[0].color[c] + s * (t[1].color[c] - t[0].color[c]) + + r * (t[2].color[c] - t[0].color[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + corner_worst = std::fmax(corner_worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + corner_covered[which] += pixel_ok; + } + } + if (corner_covered[which] != target_extent * target_extent) { + std::fprintf(stderr, "rect list with the right angle at the %s vertex: %u of %u pixels on the plane\n", + corner_names[which], corner_covered[which], target_extent * target_extent); + return 1; + } + } + // Not a right triangle: any consistent corner, but it must draw (some pixel differs from the clear colour). + const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; + unsigned skew_drawn = 0; + for (const Pixel& p : skew_pixels) skew_drawn += std::memcmp(&p, &clear_pixel, sizeof(Pixel)) != 0; + EXPECT(skew_drawn > 0); + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; @@ -333,9 +391,11 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " - "%u of %u pixels exact\n", - covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, - target_extent * target_extent); + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; right angle at " + "the second vertex %u and at the third %u of %u (worst error %g); no right angle: %u pixels drawn; " + "quad list: %u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), corner_covered[0], corner_covered[1], + target_extent * target_extent, double(corner_worst), skew_drawn, + target_extent * target_extent - quad_wrong, target_extent * target_extent); return 0; } From ee9db97988cb8c8ee36ab835becffb3b9e1d6bae Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:53:37 +0100 Subject: [PATCH 06/13] d3d12: rect list test: every pixel well inside a non-right triangle is drawn; geometry notes edges are measured in NDC --- runtime/src/rect_list_geometry.h | 4 ++++ runtime/test/d3d12_rect_list_test.cpp | 28 +++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 69b52f7e7f..e90173095d 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -18,6 +18,10 @@ // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), // and so is the stage's Position; the generated stage reads and writes exactly those. // +// The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the +// usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a +// different corner than the pixel-space right angle. +// // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. // diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp index 5ab5611163..a6d4d25b85 100644 --- a/runtime/test/d3d12_rect_list_test.cpp +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -364,11 +364,31 @@ int main() { return 1; } } - // Not a right triangle: any consistent corner, but it must draw (some pixel differs from the clear colour). + // Not a right triangle: any consistent corner is fine, but every corner choice makes a parallelogram that holds the + // drawn triangle, so each pixel well inside the triangle must be drawn (not the clear colour). const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; - unsigned skew_drawn = 0; - for (const Pixel& p : skew_pixels) skew_drawn += std::memcmp(&p, &clear_pixel, sizeof(Pixel)) != 0; - EXPECT(skew_drawn > 0); + unsigned skew_drawn = 0, skew_inside = 0, skew_missing = 0; + { + const Vertex* t = &vertices[17]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const bool drawn = std::memcmp(&skew_pixels[row * target_extent + col], &clear_pixel, sizeof(Pixel)) != 0; + skew_drawn += drawn; + if (s > 0.02f && r > 0.02f && s + r < 0.98f) { + ++skew_inside; + skew_missing += !drawn; + } + } + } + } + EXPECT(skew_inside > 1000 && skew_missing == 0); // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; From 8311d8918c3d6ec5cafbfbb6577aad69c6d1a06b Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:08:20 -0500 Subject: [PATCH 07/13] d3d12: the quad list index counts are 32-bit constants, not narrowed from size_t (C4267) std::array::size() is a size_t, and the two constants made from it are 32-bit. MSVC warned once in d3d12_vulkan_device.cpp and once in every file that includes vulkan_replay.h: 124 C4267 warnings in a Windows build of the runtime and its tests. The values (6 indices for a quad) are unchanged. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/src/vulkan_replay.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 945d10512b..bf5c58d40a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -67,7 +67,7 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index f9dfb6b030..5ffa65c95f 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -4231,7 +4231,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } else { // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. - constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + constexpr auto indices_per_quad = std::uint32_t(quad_triangle_indices.size()); const std::uint32_t wanted = draw->count / 4; const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); if (quads < wanted) From 7739895421f52326ab9523690848ec105e99e2e5 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:08:57 -0500 Subject: [PATCH 08/13] vulkan_scratch: the chunks can take usage beyond transfer source and destination ScratchBuffers creates every chunk as a transfer source and destination, which is all the staged copies need. Its owner can now add usage flags: the expanded indices of indexed quad lists (next commit) live in the same scratch, as an index buffer that a compute pass writes through its device address. The default is unchanged. vulkan_scratch_test checks the usage a chunk is created with, with and without the flags. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- runtime/src/vulkan_scratch.h | 9 ++++++--- runtime/test/vulkan_scratch_test.cpp | 26 +++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd7..c12d909e66 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -3,6 +3,8 @@ // it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour // copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own // scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24. +// The chunks are transfer sources and destinations; `extra_usage` adds what another user needs (the expanded indices +// of quad lists, quad_index_expand.h: an index buffer written through its device address). #pragma once #ifndef VK_NO_PROTOTYPES @@ -23,8 +25,8 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0) + : device_(device), allocate_(std::move(allocate)), extra_usage_(extra_usage) { loaded_ = vk_.load(get, device); } @@ -148,7 +150,7 @@ class ScratchBuffers { bool make_chunk(std::uint64_t size, Chunk& out) { VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | extra_usage_; if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); @@ -172,6 +174,7 @@ class ScratchBuffers { VkDevice device_; Allocate allocate_; + VkBufferUsageFlags extra_usage_ = 0; Functions vk_; bool loaded_ = false; Batch current_; // handed out, not yet submitted diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp index 8ca6a819a3..1d8e20d552 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp @@ -1,5 +1,6 @@ // Unit tests for ScratchBuffers (runtime/src/vulkan_scratch.h). CPU-only, no Vulkan instance and no GPU: -// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, and spare cap. +// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, spare cap, +// and the usage a chunk is created with. #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES #endif @@ -37,6 +38,7 @@ struct FakeVulkan { int free_memory_calls = 0; int wait_idle_calls = 0; int get_counter_calls = 0; + VkBufferUsageFlags last_usage = 0; // of the last chunk created VkResult create_buffer_result = VK_SUCCESS; VkResult bind_result = VK_SUCCESS; @@ -55,6 +57,7 @@ VKAPI_ATTR VkResult VKAPI_CALL fake_create_buffer( if (g_vk->create_buffer_result != VK_SUCCESS) return g_vk->create_buffer_result; const std::uintptr_t id = g_vk->next_buffer++; g_vk->live_buffers[id] = info->size; + g_vk->last_usage = info->usage; *out = make_handle(id); return VK_SUCCESS; } @@ -289,6 +292,27 @@ int main() { EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); } + // A chunk is a transfer source and destination, plus whatever usage the owner asks for (the expanded indices of + // quad lists are an index buffer written through its device address). + { + FakeVulkan vk; + g_vk = &vk; + constexpr VkBufferUsageFlags transfer = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + constexpr VkBufferUsageFlags extra = + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer buf = VK_NULL_HANDLE; + VkDeviceSize off = 0; + { + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); + EXPECT(scratch.get(256, buf, off) && vk.last_usage == transfer); + } + { + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate, extra); + EXPECT(scratch.get(256, buf, off) && vk.last_usage == (transfer | extra)); + } + EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); + } + std::printf("vulkan_scratch: all checks passed\n"); return 0; } From a9fb8058aa14d7686c6af11d1b14064924fe50d2 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:09:17 -0500 Subject: [PATCH 09/13] d3d12: indexed quad lists draw from triangle indices a compute pass expands on the GPU (OLD-9940) An indexed quad list was one triangle fan per quad over the application's index buffer. That is wrong in two ways, both measured on #207 (RTX 4070 Ti there, RTX 4070 SUPER here): - A fan's triangles are (v1 v2 v0) and (v2 v3 v0), and Vulkan takes a flat input from a triangle's first vertex. So a quad showed its second and third vertex, never its first: a quad with a red first vertex came out black and blue, 0 of 4096 pixels red. - One draw per quad runs every instance of quad 0 before quad 1. D3D12 draws instance by instance, so where instances overlap the wrong one ended on top (2048 of 4096 pixels). Neither can be fixed inside that scheme (VK_EXT_provoking_vertex cannot name a fan's hub either), so the indices are rewritten: a compute pass (quad_index_expand.comp) reads the application's index buffer on the GPU and writes (i0 i1 i2) (i0 i2 i3) for each quad as 32-bit indices into copy scratch, and the draw is one indexed triangle list over that scratch with the application's instance count, base vertex and first instance. Both triangles start at the quad's first vertex, like the non-indexed path. - The host never reads the indices: a copy or a shader earlier in the list can have written them. The pass runs before the draw's rendering scope, between a barrier for those writes and one for its own, and between two segments of an active pipeline-statistics query, as the other helper dispatches do (D3D-162). - 16-bit and 32-bit indices, read as whole words, so a 16-bit view at an address of 2 modulo 4 works. Index values are copied as they are: VertexIndex - BaseVertex is still the application's index. - The strip-cut values are ordinary indices, as in every list topology. An index past the view reads 0, as in D3D12, and the pass reads nothing past the view. A draw's last one to three indices are dropped. - It needs bufferDeviceAddress. Without it, or inside a statistics query that cannot be split, the list is refused as unsupported. - vulkan_topology(19) is a triangle list for both paths; nothing draws a fan any more (MoltenVK has no fans). replay_quad_list_test replays indexed draws through prepare() and the real expander on a recording device: one dispatch before the rendering scope and one draw in it, the push constants for both index sizes, the view's end, the split of a draw larger than one dispatch, the refusals, and the order inside a statistics query. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- runtime/shims/d3d12_vulkan_device.cpp | 15 +- runtime/src/quad_index_expand.comp | 44 ++++ runtime/src/quad_index_expand.h | 182 ++++++++++++++ runtime/src/quad_index_expand_spv.h | 148 +++++++++++ runtime/src/vulkan_backend.h | 29 ++- runtime/src/vulkan_replay.h | 97 ++++++-- runtime/test/replay_quad_list_test.cpp | 328 +++++++++++++++++++++++-- 7 files changed, 802 insertions(+), 41 deletions(-) create mode 100644 runtime/src/quad_index_expand.comp create mode 100644 runtime/src/quad_index_expand.h create mode 100644 runtime/src/quad_index_expand_spv.h diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index bf5c58d40a..b88a372e70 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5190,16 +5190,23 @@ class Device final if (info.host_pointer_alignment) state_.get_host_pointer_properties = reinterpret_cast( get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); - // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. - state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { - return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); + // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. With buffer + // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): + // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. + const bool index_scratch = info.buffer_device_address; + state_.context->enable_copy_scratch( + get_device, + [this, index_scratch](const VkMemoryRequirements& requirements) { + return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); + }, + index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); + state_.context->configure_quad_indices(get_device, props.limits); } } // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of diff --git a/runtime/src/quad_index_expand.comp b/runtime/src/quad_index_expand.comp new file mode 100644 index 0000000000..697cf7665d --- /dev/null +++ b/runtime/src/quad_index_expand.comp @@ -0,0 +1,44 @@ +// Expand the index buffer of a console quad list into triangle-list indices without reading it on the CPU +// (quad_index_expand.h). Each quad (i0 i1 i2 i3) becomes (i0 i1 i2) (i0 i2 i3) as six 32-bit indices: both +// triangles start at the quad's first vertex, the one a flat input is taken from. +#version 460 +#extension GL_EXT_buffer_reference : require +layout(local_size_x = 64) in; +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { + uint data[]; +}; +layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer WordsOut { + uint data[]; +}; +layout(push_constant) uniform Params { + WordsIn source; // the 4-byte aligned word that holds this dispatch's first index + WordsOut triangles; // six words for each quad of this dispatch + uint first_half; // 16-bit indices: 1 when the first index is the high half of its word + uint index_bits; // 16 or 32 + uint limit; // how many of this dispatch's indices the index buffer view holds; the rest read 0 + uint quads; +} p; + +uint index_at(uint i) { + if (i >= p.limit) return 0u; + if (p.index_bits == 32u) return p.source.data[i]; + const uint slot = i + p.first_half; + return (p.source.data[slot >> 1u] >> ((slot & 1u) * 16u)) & 0xffffu; +} + +void main() { + const uint quad = gl_GlobalInvocationID.x; + if (quad >= p.quads) return; + const uint first = quad * 4u; + const uint i0 = index_at(first); + const uint i1 = index_at(first + 1u); + const uint i2 = index_at(first + 2u); + const uint i3 = index_at(first + 3u); + const uint target = quad * 6u; + p.triangles.data[target] = i0; + p.triangles.data[target + 1u] = i1; + p.triangles.data[target + 2u] = i2; + p.triangles.data[target + 3u] = i0; + p.triangles.data[target + 4u] = i2; + p.triangles.data[target + 5u] = i3; +} diff --git a/runtime/src/quad_index_expand.h b/runtime/src/quad_index_expand.h new file mode 100644 index 0000000000..3c539a5406 --- /dev/null +++ b/runtime/src/quad_index_expand.h @@ -0,0 +1,182 @@ +// Indexed console quad lists (D3D_PRIMITIVE_TOPOLOGY 19) on Vulkan, which has no quad primitive. +// +// A quad is four indices and Vulkan can only draw it as triangles. A triangle fan per quad reads the application's +// index buffer in place, but gets two things wrong: a fan takes a flat input from each triangle's own first vertex +// (the quad's second and third), where the quad takes it from its first, and one draw per quad runs every instance +// of quad 0 before quad 1, where D3D12 draws instance by instance (visible when instances overlap). So the indices +// are rewritten instead: a compute pass (quad_index_expand.comp) reads the application's index buffer on the GPU and +// writes (i0 i1 i2) (i0 i2 i3) for each quad as 32-bit indices into scratch that lives until the submission +// completes (vulkan_scratch.h), and the draw is one indexed triangle list over that scratch with the application's +// instance count, base vertex and first instance. Both triangles start at the quad's first vertex, so a flat input +// is the first vertex's over the whole quad, and one draw keeps D3D12's instance order. +// +// The indices are read on the GPU, never on the host: an index buffer can be written by a copy or a shader earlier +// in the same list. Index values are copied as they are (a 16-bit index is zero-extended), so VertexIndex - +// BaseVertex is still the application's index. That includes the strip-cut value: 0xFFFF and 0xFFFFFFFF are +// ordinary indices in a quad list, as in every list topology (the replay enables primitive restart for strips only), +// and 0xFFFF stays vertex 65535 after the widening. An index past the end of the index buffer view reads 0, as +// D3D12 defines it, and a draw's last one to three indices that do not make a quad are dropped. +// +// Needs bufferDeviceAddress (the pass reads and writes through device addresses, no descriptors) and scratch with +// INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage. Non-indexed quad lists do not come here: they draw from a shared +// constant index buffer (ReplayFunctions::quad_indices). +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include "quad_index_expand_spv.h" + +namespace leonida { + +// One indexed quad-list draw's expansion. `buffer` is null for a draw that needs none. +struct QuadIndexExpansion { + VkBuffer buffer = VK_NULL_HANDLE; // the triangle-list indices, 32-bit: six for each quad + VkDeviceSize offset = 0; + VkDeviceAddress source = 0; // the 4-byte aligned word that holds the draw's first index + VkDeviceAddress triangles = 0; // `buffer` + `offset` + std::uint64_t readable = 0; // indices from the draw's first one that the index buffer view holds + std::uint32_t first_half = 0; // 16-bit indices: 1 when the first index is the high half of its word + std::uint32_t index_bits = 0; // 16 or 32 + std::uint32_t quads = 0; +}; + +class QuadIndexExpander { +public: + static constexpr std::uint32_t indices_per_quad = 6; + // vkCmdDrawIndexed counts the expanded indices in 32 bits. + static constexpr std::uint32_t max_quads = UINT32_MAX / indices_per_quad; + // The scratch bytes `quads` quads expand into. + static constexpr VkDeviceSize bytes(std::uint32_t quads) { + return VkDeviceSize(quads) * indices_per_quad * sizeof(std::uint32_t); + } + + QuadIndexExpander(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) + : get_(get), device_(device), limits_(limits) {} + ~QuadIndexExpander() { + if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); + if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + } + QuadIndexExpander(const QuadIndexExpander&) = delete; + QuadIndexExpander& operator=(const QuadIndexExpander&) = delete; + + // `quads` quads from the indices at `index_offset` in `indices` (the draw's first index), of which the view holds + // `readable`, into bytes(quads) of `scratch` at `scratch_offset`. The pipeline is made on the first call; the + // caller serializes calls. False, with `out` cleared, when the draw cannot be expanded. + bool prepare(VkBuffer indices, VkDeviceSize index_offset, VkIndexType type, std::uint64_t readable, + std::uint32_t quads, VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + out = {}; + const std::uint32_t index_bytes = type == VK_INDEX_TYPE_UINT16 ? 2 : type == VK_INDEX_TYPE_UINT32 ? 4 : 0; + if (!indices || !scratch || !index_bytes || !quads || quads > max_quads || index_offset % index_bytes || + scratch_offset % sizeof(std::uint32_t) || !limits_.maxComputeWorkGroupCount[0] || !make_pipeline()) + return false; + const auto address = fn("vkGetBufferDeviceAddress"); + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = indices; + const VkDeviceAddress source = address(device_, &info); + info.buffer = scratch; + const VkDeviceAddress target = address(device_, &info); + if (!source || !target || index_offset > UINT64_MAX - source || scratch_offset > UINT64_MAX - target || + (source % sizeof(std::uint32_t)) || (target % sizeof(std::uint32_t))) + return false; + out.buffer = scratch; + out.offset = scratch_offset; + // The shader reads whole words: a 16-bit index at an address of 2 modulo 4 is the high half of its word. + out.source = (source + index_offset) & ~VkDeviceAddress(3); + out.first_half = std::uint32_t((index_offset & 3) / 2); + out.triangles = target + scratch_offset; + out.readable = readable; + out.index_bits = index_bytes * 8; + out.quads = quads; + return true; + } + + // Records the pass: outside a render pass, before the draw that binds job.buffer as its index buffer. + void emit(VkCommandBuffer cb, const QuadIndexExpansion& job) const { + const auto barrier = fn("vkCmdPipelineBarrier"); + // Whatever wrote the application's indices earlier in the command buffer (a copy, a shader) is visible. + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 1, &before, 0, nullptr, 0, nullptr); + fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + struct Push { + VkDeviceAddress source, triangles; + std::uint32_t first_half, index_bits, limit, quads; + }; + static_assert(sizeof(Push) == push_bytes); + // A dispatch indexes its quads and their indices in 32 bits: 4 * quad + 4 and 6 * quad + 5 must fit. + constexpr VkDeviceSize index_limit = 1u << 28; + const VkDeviceSize chunk_limit = + std::min(VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * group_size, index_limit); + for (VkDeviceSize first = 0; first < job.quads;) { + const std::uint32_t quads = std::uint32_t(std::min(chunk_limit, job.quads - first)); + const VkDeviceSize first_index = first * 4; + // 16-bit indices: `first_index` is even, so the chunk starts at the same half of a word as the draw. + const VkDeviceSize source_bytes = first_index * (job.index_bits / 8); + const std::uint64_t left = job.readable > first_index ? job.readable - first_index : 0; + const Push push{job.source + source_bytes, job.triangles + first * indices_per_quad * 4, + job.first_half, job.index_bits, std::uint32_t(std::min(left, UINT32_MAX)), + quads}; + fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, + sizeof(push), &push); + fn("vkCmdDispatch")(cb, (quads - 1u) / group_size + 1u, 1, 1); + first += quads; + } + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_INDEX_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + 0, 1, &after, 0, nullptr, 0, nullptr); + } + +private: + static constexpr std::uint32_t group_size = 64; // local_size_x of quad_index_expand.comp + static constexpr std::uint32_t push_bytes = 32; + template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + bool make_pipeline() { + if (pipeline_) return true; + for (const char* name : {"vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule", + "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", + "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkShaderModule module = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = sizeof(quad_index_expand_spirv); + shader.pCode = quad_index_expand_spirv; + bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")( + device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + return false; + } + layout_ = layout; + pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceLimits limits_; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; +}; +} // namespace leonida diff --git a/runtime/src/quad_index_expand_spv.h b/runtime/src/quad_index_expand_spv.h new file mode 100644 index 0000000000..c7bb4b5c5f --- /dev/null +++ b/runtime/src/quad_index_expand_spv.h @@ -0,0 +1,148 @@ +// Generated with glslang 16.6.0: glslangValidator -V --target-env vulkan1.2 -Os --spirv-val quad_index_expand.comp +#pragma once +#include +namespace leonida { +inline constexpr std::uint32_t quad_index_expand_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000149u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, + 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000015u, + 0x0000004au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, + 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, + 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, 0x0000000fu, 0x61726150u, + 0x0000736du, 0x00050006u, 0x0000000fu, 0x00000000u, 0x72756f73u, 0x00006563u, 0x00060006u, 0x0000000fu, + 0x00000001u, 0x61697274u, 0x656c676eu, 0x00000073u, 0x00060006u, 0x0000000fu, 0x00000002u, 0x73726966u, + 0x61685f74u, 0x0000666cu, 0x00060006u, 0x0000000fu, 0x00000003u, 0x65646e69u, 0x69625f78u, 0x00007374u, + 0x00050006u, 0x0000000fu, 0x00000004u, 0x696d696cu, 0x00000074u, 0x00050006u, 0x0000000fu, 0x00000005u, + 0x64617571u, 0x00000073u, 0x00040005u, 0x00000011u, 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000011u, + 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, 0x00000013u, 0x64726f57u, 0x74754f73u, 0x00000000u, + 0x00050006u, 0x00000013u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00030005u, 0x00000015u, 0x00000070u, + 0x00080005u, 0x0000004au, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, + 0x00030047u, 0x0000000fu, 0x00000002u, 0x00050048u, 0x0000000fu, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00050048u, 0x0000000fu, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x0000000fu, 0x00000002u, + 0x00000023u, 0x00000010u, 0x00050048u, 0x0000000fu, 0x00000003u, 0x00000023u, 0x00000014u, 0x00050048u, + 0x0000000fu, 0x00000004u, 0x00000023u, 0x00000018u, 0x00050048u, 0x0000000fu, 0x00000005u, 0x00000023u, + 0x0000001cu, 0x00040047u, 0x00000010u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000011u, 0x00000002u, + 0x00040048u, 0x00000011u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000011u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x00000012u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000013u, 0x00000002u, + 0x00040048u, 0x00000013u, 0x00000000u, 0x00000019u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x0000004au, 0x0000000bu, 0x0000001cu, 0x00040047u, 0x0000009au, 0x0000000bu, + 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, + 0x00000020u, 0x00000000u, 0x00030027u, 0x0000000du, 0x000014e5u, 0x00030027u, 0x0000000eu, 0x000014e5u, + 0x0008001eu, 0x0000000fu, 0x0000000du, 0x0000000eu, 0x00000006u, 0x00000006u, 0x00000006u, 0x00000006u, + 0x0003001du, 0x00000010u, 0x00000006u, 0x0003001eu, 0x00000011u, 0x00000010u, 0x00040020u, 0x0000000du, + 0x000014e5u, 0x00000011u, 0x0003001du, 0x00000012u, 0x00000006u, 0x0003001eu, 0x00000013u, 0x00000012u, + 0x00040020u, 0x0000000eu, 0x000014e5u, 0x00000013u, 0x00040020u, 0x00000014u, 0x00000009u, 0x0000000fu, + 0x0004003bu, 0x00000014u, 0x00000015u, 0x00000009u, 0x00040015u, 0x00000016u, 0x00000020u, 0x00000001u, + 0x0004002bu, 0x00000016u, 0x00000017u, 0x00000004u, 0x00040020u, 0x00000018u, 0x00000009u, 0x00000006u, + 0x00020014u, 0x0000001bu, 0x0004002bu, 0x00000006u, 0x0000001fu, 0x00000000u, 0x0004002bu, 0x00000016u, + 0x00000021u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000024u, 0x00000020u, 0x0004002bu, 0x00000016u, + 0x00000028u, 0x00000000u, 0x00040020u, 0x00000029u, 0x00000009u, 0x0000000du, 0x00040020u, 0x0000002du, + 0x000014e5u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x00000033u, 0x00000002u, 0x0004002bu, 0x00000006u, + 0x0000003au, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000040u, 0x00000010u, 0x0004002bu, 0x00000006u, + 0x00000043u, 0x0000ffffu, 0x00040017u, 0x00000048u, 0x00000006u, 0x00000003u, 0x00040020u, 0x00000049u, + 0x00000001u, 0x00000048u, 0x0004003bu, 0x00000049u, 0x0000004au, 0x00000001u, 0x00040020u, 0x0000004bu, + 0x00000001u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x0000004fu, 0x00000005u, 0x0004002bu, 0x00000006u, + 0x00000058u, 0x00000004u, 0x0004002bu, 0x00000006u, 0x00000065u, 0x00000002u, 0x0004002bu, 0x00000006u, + 0x0000006bu, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000071u, 0x00000006u, 0x0004002bu, 0x00000016u, + 0x00000073u, 0x00000001u, 0x00040020u, 0x00000074u, 0x00000009u, 0x0000000eu, 0x0004002bu, 0x00000006u, + 0x00000095u, 0x00000005u, 0x0004002bu, 0x00000006u, 0x00000099u, 0x00000040u, 0x0006002cu, 0x00000048u, + 0x0000009au, 0x00000099u, 0x0000003au, 0x0000003au, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, + 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x0000009bu, 0x00000000u, 0x000300fbu, 0x0000001fu, + 0x0000009cu, 0x000200f8u, 0x0000009cu, 0x00050041u, 0x0000004bu, 0x0000004cu, 0x0000004au, 0x0000001fu, + 0x0004003du, 0x00000006u, 0x0000004du, 0x0000004cu, 0x00050041u, 0x00000018u, 0x00000050u, 0x00000015u, + 0x0000004fu, 0x0004003du, 0x00000006u, 0x00000051u, 0x00000050u, 0x000500aeu, 0x0000001bu, 0x00000052u, + 0x0000004du, 0x00000051u, 0x000300f7u, 0x00000054u, 0x00000000u, 0x000400fau, 0x00000052u, 0x00000053u, + 0x00000054u, 0x000200f8u, 0x00000053u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x00000054u, 0x00050084u, + 0x00000006u, 0x00000059u, 0x0000004du, 0x00000058u, 0x000300f7u, 0x000000cbu, 0x00000000u, 0x000300fbu, + 0x0000001fu, 0x000000abu, 0x000200f8u, 0x000000abu, 0x00050041u, 0x00000018u, 0x000000adu, 0x00000015u, + 0x00000017u, 0x0004003du, 0x00000006u, 0x000000aeu, 0x000000adu, 0x000500aeu, 0x0000001bu, 0x000000afu, + 0x00000059u, 0x000000aeu, 0x000300f7u, 0x000000b1u, 0x00000000u, 0x000400fau, 0x000000afu, 0x000000b0u, + 0x000000b1u, 0x000200f8u, 0x000000b0u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000b1u, 0x00050041u, + 0x00000018u, 0x000000b2u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x000000b2u, + 0x000500aau, 0x0000001bu, 0x000000b4u, 0x000000b3u, 0x00000024u, 0x000300f7u, 0x000000bbu, 0x00000000u, + 0x000400fau, 0x000000b4u, 0x000000b5u, 0x000000bbu, 0x000200f8u, 0x000000b5u, 0x00050041u, 0x00000029u, + 0x000000b6u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000b7u, 0x000000b6u, 0x00060041u, + 0x0000002du, 0x000000b9u, 0x000000b7u, 0x00000028u, 0x00000059u, 0x0006003du, 0x00000006u, 0x000000bau, + 0x000000b9u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000bbu, 0x00050041u, + 0x00000018u, 0x000000bdu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000beu, 0x000000bdu, + 0x00050080u, 0x00000006u, 0x000000bfu, 0x00000059u, 0x000000beu, 0x00050041u, 0x00000029u, 0x000000c0u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000c1u, 0x000000c0u, 0x000500c2u, 0x00000006u, + 0x000000c3u, 0x000000bfu, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000c4u, 0x000000c1u, 0x00000028u, + 0x000000c3u, 0x0006003du, 0x00000006u, 0x000000c5u, 0x000000c4u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x000000c7u, 0x000000bfu, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000c8u, 0x000000c7u, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000c9u, 0x000000c5u, 0x000000c8u, 0x000500c7u, 0x00000006u, + 0x000000cau, 0x000000c9u, 0x00000043u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000cbu, 0x000900f5u, + 0x00000006u, 0x00000142u, 0x0000001fu, 0x000000b0u, 0x000000bau, 0x000000b5u, 0x000000cau, 0x000000bbu, + 0x00050080u, 0x00000006u, 0x00000060u, 0x00000059u, 0x0000003au, 0x000300f7u, 0x000000f2u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x000500aeu, 0x0000001bu, 0x000000d6u, + 0x00000060u, 0x000000aeu, 0x000300f7u, 0x000000d8u, 0x00000000u, 0x000400fau, 0x000000d6u, 0x000000d7u, + 0x000000d8u, 0x000200f8u, 0x000000d7u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000d8u, 0x00050041u, + 0x00000018u, 0x000000d9u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000dau, 0x000000d9u, + 0x000500aau, 0x0000001bu, 0x000000dbu, 0x000000dau, 0x00000024u, 0x000300f7u, 0x000000e2u, 0x00000000u, + 0x000400fau, 0x000000dbu, 0x000000dcu, 0x000000e2u, 0x000200f8u, 0x000000dcu, 0x00050041u, 0x00000029u, + 0x000000ddu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000deu, 0x000000ddu, 0x00060041u, + 0x0000002du, 0x000000e0u, 0x000000deu, 0x00000028u, 0x00000060u, 0x0006003du, 0x00000006u, 0x000000e1u, + 0x000000e0u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000e2u, 0x00050041u, + 0x00000018u, 0x000000e4u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000e5u, 0x000000e4u, + 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000060u, 0x000000e5u, 0x00050041u, 0x00000029u, 0x000000e7u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000e8u, 0x000000e7u, 0x000500c2u, 0x00000006u, + 0x000000eau, 0x000000e6u, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000ebu, 0x000000e8u, 0x00000028u, + 0x000000eau, 0x0006003du, 0x00000006u, 0x000000ecu, 0x000000ebu, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x000000eeu, 0x000000e6u, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000efu, 0x000000eeu, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000f0u, 0x000000ecu, 0x000000efu, 0x000500c7u, 0x00000006u, + 0x000000f1u, 0x000000f0u, 0x00000043u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000f2u, 0x000900f5u, + 0x00000006u, 0x00000144u, 0x0000001fu, 0x000000d7u, 0x000000e1u, 0x000000dcu, 0x000000f1u, 0x000000e2u, + 0x00050080u, 0x00000006u, 0x00000066u, 0x00000059u, 0x00000065u, 0x000300f7u, 0x00000119u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x000000f9u, 0x000200f8u, 0x000000f9u, 0x000500aeu, 0x0000001bu, 0x000000fdu, + 0x00000066u, 0x000000aeu, 0x000300f7u, 0x000000ffu, 0x00000000u, 0x000400fau, 0x000000fdu, 0x000000feu, + 0x000000ffu, 0x000200f8u, 0x000000feu, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x000000ffu, 0x00050041u, + 0x00000018u, 0x00000100u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000101u, 0x00000100u, + 0x000500aau, 0x0000001bu, 0x00000102u, 0x00000101u, 0x00000024u, 0x000300f7u, 0x00000109u, 0x00000000u, + 0x000400fau, 0x00000102u, 0x00000103u, 0x00000109u, 0x000200f8u, 0x00000103u, 0x00050041u, 0x00000029u, + 0x00000104u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000105u, 0x00000104u, 0x00060041u, + 0x0000002du, 0x00000107u, 0x00000105u, 0x00000028u, 0x00000066u, 0x0006003du, 0x00000006u, 0x00000108u, + 0x00000107u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000109u, 0x00050041u, + 0x00000018u, 0x0000010bu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x0000010cu, 0x0000010bu, + 0x00050080u, 0x00000006u, 0x0000010du, 0x00000066u, 0x0000010cu, 0x00050041u, 0x00000029u, 0x0000010eu, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000010fu, 0x0000010eu, 0x000500c2u, 0x00000006u, + 0x00000111u, 0x0000010du, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000112u, 0x0000010fu, 0x00000028u, + 0x00000111u, 0x0006003du, 0x00000006u, 0x00000113u, 0x00000112u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x00000115u, 0x0000010du, 0x0000003au, 0x00050084u, 0x00000006u, 0x00000116u, 0x00000115u, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x00000117u, 0x00000113u, 0x00000116u, 0x000500c7u, 0x00000006u, + 0x00000118u, 0x00000117u, 0x00000043u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000119u, 0x000900f5u, + 0x00000006u, 0x00000146u, 0x0000001fu, 0x000000feu, 0x00000108u, 0x00000103u, 0x00000118u, 0x00000109u, + 0x00050080u, 0x00000006u, 0x0000006cu, 0x00000059u, 0x0000006bu, 0x000300f7u, 0x00000140u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x00000120u, 0x000200f8u, 0x00000120u, 0x000500aeu, 0x0000001bu, 0x00000124u, + 0x0000006cu, 0x000000aeu, 0x000300f7u, 0x00000126u, 0x00000000u, 0x000400fau, 0x00000124u, 0x00000125u, + 0x00000126u, 0x000200f8u, 0x00000125u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000126u, 0x00050041u, + 0x00000018u, 0x00000127u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000128u, 0x00000127u, + 0x000500aau, 0x0000001bu, 0x00000129u, 0x00000128u, 0x00000024u, 0x000300f7u, 0x00000130u, 0x00000000u, + 0x000400fau, 0x00000129u, 0x0000012au, 0x00000130u, 0x000200f8u, 0x0000012au, 0x00050041u, 0x00000029u, + 0x0000012bu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000012cu, 0x0000012bu, 0x00060041u, + 0x0000002du, 0x0000012eu, 0x0000012cu, 0x00000028u, 0x0000006cu, 0x0006003du, 0x00000006u, 0x0000012fu, + 0x0000012eu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000130u, 0x00050041u, + 0x00000018u, 0x00000132u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x00000133u, 0x00000132u, + 0x00050080u, 0x00000006u, 0x00000134u, 0x0000006cu, 0x00000133u, 0x00050041u, 0x00000029u, 0x00000135u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000136u, 0x00000135u, 0x000500c2u, 0x00000006u, + 0x00000138u, 0x00000134u, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000139u, 0x00000136u, 0x00000028u, + 0x00000138u, 0x0006003du, 0x00000006u, 0x0000013au, 0x00000139u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x0000013cu, 0x00000134u, 0x0000003au, 0x00050084u, 0x00000006u, 0x0000013du, 0x0000013cu, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x0000013eu, 0x0000013au, 0x0000013du, 0x000500c7u, 0x00000006u, + 0x0000013fu, 0x0000013eu, 0x00000043u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000140u, 0x000900f5u, + 0x00000006u, 0x00000148u, 0x0000001fu, 0x00000125u, 0x0000012fu, 0x0000012au, 0x0000013fu, 0x00000130u, + 0x00050084u, 0x00000006u, 0x00000072u, 0x0000004du, 0x00000071u, 0x00050041u, 0x00000074u, 0x00000075u, + 0x00000015u, 0x00000073u, 0x0004003du, 0x0000000eu, 0x00000076u, 0x00000075u, 0x00060041u, 0x0000002du, + 0x00000079u, 0x00000076u, 0x00000028u, 0x00000072u, 0x0005003eu, 0x00000079u, 0x00000142u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x0000007du, 0x00000072u, 0x0000003au, 0x00060041u, 0x0000002du, + 0x0000007fu, 0x00000076u, 0x00000028u, 0x0000007du, 0x0005003eu, 0x0000007fu, 0x00000144u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000083u, 0x00000072u, 0x00000065u, 0x00060041u, 0x0000002du, + 0x00000085u, 0x00000076u, 0x00000028u, 0x00000083u, 0x0005003eu, 0x00000085u, 0x00000146u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000089u, 0x00000072u, 0x0000006bu, 0x00060041u, 0x0000002du, + 0x0000008bu, 0x00000076u, 0x00000028u, 0x00000089u, 0x0005003eu, 0x0000008bu, 0x00000142u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x0000008fu, 0x00000072u, 0x00000058u, 0x00060041u, 0x0000002du, + 0x00000091u, 0x00000076u, 0x00000028u, 0x0000008fu, 0x0005003eu, 0x00000091u, 0x00000146u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000096u, 0x00000072u, 0x00000095u, 0x00060041u, 0x0000002du, + 0x00000098u, 0x00000076u, 0x00000028u, 0x00000096u, 0x0005003eu, 0x00000098u, 0x00000148u, 0x00000002u, + 0x00000004u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x0000009bu, 0x000100fdu, 0x00010038u, +}; +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 02fdad1a09..a041825c2a 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1116,6 +1116,13 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); counted_dispatch_ = std::make_unique(get, device_, memory, limits); } + // Indexed quad lists are drawn from triangle indices a compute pass writes into the copy scratch + // (quad_index_expand.h). Call only with bufferDeviceAddress enabled and after an enable_copy_scratch whose chunks + // have INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage on memory allocated with a device address. + void configure_quad_indices(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { + std::unique_lock lock(resource_mutex_); + quad_indices_ = std::make_unique(get, device_, limits); + } VkDevice device() const { return device_; } // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets @@ -1413,10 +1420,12 @@ class VulkanContext { } // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from - // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { + // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer + // usage, for configure_quad_indices. + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + VkBufferUsageFlags extra_usage = 0) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), extra_usage); if (!scratch_->loaded()) scratch_.reset(); } @@ -1723,6 +1732,7 @@ class VulkanContext { std::unique_ptr predicate_reducer_; std::unique_ptr predicated_copier_; std::unique_ptr counted_dispatch_; + std::unique_ptr quad_indices_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; DebugLabelFunctions labels_; @@ -2379,6 +2389,19 @@ class VulkanQueue : private QueueHolds::Holder { context_.counted_dispatch_->emit(cb, job); }; } + if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { + replay.prepare_quad_indices = [this, &tracker_lock]( + VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, + VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, + scratch_offset, out); + }; + replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { + context_.quad_indices_->emit(cb, job); + }; + } if (context_.depth24_ && !transfer_only) { replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, std::vector& parts) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 5ffa65c95f..3225cffeb3 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "quad_index_expand.h" #include "rect_list_geometry.h" #include "uav_clear.h" @@ -904,6 +905,14 @@ struct ReplayFunctions { std::function prepare_counted_dispatch; std::function emit_counted_dispatch; + // An indexed quad list draws from triangle-list indices that a compute prepass writes from the application's + // index buffer (quad_index_expand.h): the index buffer and the offset of the draw's first index, the index type, + // how many indices from there the view holds, the quads, and QuadIndexExpander::bytes(quads) of `copy_scratch`. + // That scratch must be usable as an index buffer and through its device address. Without both such a draw is + // unsupported. + std::function prepare_quad_indices; + std::function emit_quad_indices; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan @@ -947,7 +956,8 @@ struct ReplayFunctions { std::function&)> depth24_prepare; // whole copy in, dispatches out std::function depth24_run; // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour - // copies go through it, image to buffer to image. Without it such a copy is unsupported. + // copies go through it, image to buffer to image. Without it such a copy is unsupported. The expanded indices of + // an indexed quad list are written there too (prepare_quad_indices). std::function copy_scratch; // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. std::function query_pool; @@ -1070,7 +1080,9 @@ struct PreparedDraw { std::vector vertex_offsets, vertex_sizes, vertex_strides; VkBuffer index_buffer = VK_NULL_HANDLE; VkDeviceSize index_offset = 0; + VkDeviceSize index_size = 0; // the bytes of the index buffer view inside its buffer; 0 with no index buffer VkIndexType index_type = VK_INDEX_TYPE_UINT16; + QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has @@ -1086,7 +1098,9 @@ struct PreparedDraw { vertex_strides.clear(); index_buffer = VK_NULL_HANDLE; index_offset = 0; + index_size = 0; index_type = VK_INDEX_TYPE_UINT16; + quad_indices = {}; area = {}; layers = 1; } @@ -2214,11 +2228,36 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct std::uint64_t size = draw.index.size; if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) return ReplayResult::unresolved_resource; + p.index_size = size; } } return ReplayResult::success; } +// An indexed quad list (D3D_PRIMITIVE_TOPOLOGY 19): the scratch and the compute job that turn the application's +// indices into triangle-list indices (quad_index_expand.h). `p` is the draw as prepare_draw left it. A draw of +// fewer than four indices has no quad and needs nothing. +inline ReplayResult prepare_quad_indices(const Draw& draw, const ReplayFunctions& vk, PreparedDraw& p) { + const std::uint32_t quads = draw.count / 4; + if (!quads) return ReplayResult::success; + if (!vk.prepare_quad_indices || !vk.emit_quad_indices || !vk.copy_scratch || + quads > QuadIndexExpander::max_quads) + return ReplayResult::unsupported; + // The indices from the draw's first one that the view holds; the pass reads the rest as 0, like D3D12. With no + // index buffer (the zero page) that is all of them. + const std::uint32_t index_bytes = p.index_type == VK_INDEX_TYPE_UINT16 ? 2 : 4; + const std::uint64_t in_view = p.index_size / index_bytes; + const std::uint64_t readable = in_view > draw.first ? in_view - draw.first : 0; + const VkDeviceSize first = readable ? p.index_offset + VkDeviceSize(draw.first) * index_bytes : p.index_offset; + VkBuffer scratch = VK_NULL_HANDLE; + VkDeviceSize scratch_offset = 0; + if (!vk.copy_scratch(QuadIndexExpander::bytes(quads), scratch, scratch_offset) || + !vk.prepare_quad_indices(p.index_buffer, first, p.index_type, readable, quads, scratch, scratch_offset, + p.quad_indices)) + return ReplayResult::unsupported; + return ReplayResult::success; +} + inline bool strip_topology(VkPrimitiveTopology topology) { return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY || @@ -2236,10 +2275,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; - // emit() overrides non-indexed quads to a triangle list backed by the shared indices. + // Rectangles draw as triangle lists through a geometry stage, quads as triangle lists through indices: the + // shared ones for a non-indexed draw, the application's own, expanded, for an indexed one (emit). case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -2354,6 +2393,16 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) { return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; } +// True for a command that records a compute dispatch of the layer's own before the application's work: a predicate +// capture, a predicated copy, a depth24 or rgb96 conversion, the count clamp of an ExecuteIndirect dispatch, or the +// index expansion of an indexed quad list (which is also a draw). +inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) { + const auto& p = out.commands[i]; + if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect) + return true; + return std::holds_alternative(out.list->commands()[i]) && out.draws[p.draw].quad_indices.buffer; +} + // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. @@ -2373,8 +2422,7 @@ inline void plan_statistics_segments(PreparedList& out) { const auto commands = out.list->commands(); for (std::size_t i = 0; i < out.commands.size(); ++i) { auto& p = out.commands[i]; - if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { + if (begin && has_helper_dispatch(out, i)) { inner.push_back({&p.statistics_end, &p.statistics_begin, -1}); splits = true; } @@ -2459,13 +2507,12 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { query = &out.queries[next_query++]; if (!query) { // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical - // segment before it and open a new one after, the way resolves do. - if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { + // segment before it and open a new one after, the way resolves do. An indexed quad list is a helper and + // a draw: the new segment is the one its draw runs in, and its kind is recorded below. + if (!active.empty() && has_helper_dispatch(out, i)) { p.statistics_end = current; current = open(); p.statistics_begin = current; - continue; } // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291). int draw = -1; @@ -3163,6 +3210,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun p.draw = std::uint32_t(out.draw_count++); if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) return r; + if (draw->indexed && !draw->mesh && draw->topology == topology_quad_list) { + // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. + if (statistics_active && !statistics_helpers && draw->count >= 4) return ReplayResult::unsupported; + if (const auto r = detail::prepare_quad_indices(*draw, vk, prepared_draw); r != ReplayResult::success) + return r; + } } } if (ordinary_active || binary_active) return ReplayResult::invalid_query; @@ -3455,9 +3508,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk); }; // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the - // draw's own rendering scope begins. + // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the + // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside + // the predicate, which skips it together with its draw. if (std::holds_alternative(command) || std::holds_alternative(command)) { end_statistics(); + if (std::holds_alternative(command) && prepared.draws[p.draw].quad_indices.buffer) + vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); begin_statistics(); } if (const auto* predication = std::get_if(&command)) { @@ -4203,8 +4260,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed - ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); + 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) || @@ -4223,11 +4279,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->topology == topology_quad_list) { if (draw->indexed) { - // Indexed quads still read their vertices from the application's index buffer, one fan per quad. - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, - draw->base_vertex, draw->first_instance); + // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) + // for each quad of the application's indices from draw->first on: one draw, so instances run + // in D3D12's order, flat inputs come from each quad's first vertex, and VertexIndex - BaseVertex + // is still the application's index. A draw of fewer than four indices has no quad. + const QuadIndexExpansion& quads = d.quad_indices; + if (quads.buffer) { + vk.bind_index_buffer(command_buffer, quads.buffer, quads.offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads.quads * QuadIndexExpander::indices_per_quad, + draw->instances, 0, draw->base_vertex, draw->first_instance); + } } else { // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp index 15b0c7e781..0557a3e577 100644 --- a/runtime/test/replay_quad_list_test.cpp +++ b/runtime/test/replay_quad_list_test.cpp @@ -1,9 +1,18 @@ -// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans -// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +// Quad lists are triangle-list draws. A switch back to Vulkan triangle fans changes the provoking vertex for flat +// attributes and the order of overlapping blended instances. +// - Without an index buffer: one draw over the shared triangle indices. +// - With one: one compute dispatch that expands the application's indices into scratch (src/quad_index_expand.h), +// then one draw over that scratch. The dispatch runs before the draw's rendering scope and outside a +// pipeline-statistics query, reads no index past the view, and a draw with more quads than one dispatch may +// cover is split into several. +// No GPU: the Vulkan calls are recorded. #include "../src/vulkan_replay.h" #include #include +#include +#include +#include #include namespace { @@ -20,27 +29,129 @@ struct DrawCall { bool operator==(const DrawCall&) const = default; }; +// What quad_index_expand.comp reads from its push constants. +struct Push { + VkDeviceAddress source, triangles; + std::uint32_t first_half, index_bits, limit, quads; + bool operator==(const Push&) const = default; +}; + +struct Barrier { + VkPipelineStageFlags src_stages, dst_stages; + VkAccessFlags src_access, dst_access; + bool operator==(const Barrier&) const = default; +}; + DrawCall recorded{}; std::vector calls; +std::vector pushes; +std::vector dispatches; // group counts +std::vector barriers; +std::vector events; // the order of everything recorded +std::vector scratch_requests; + +template +T handle(std::uintptr_t n) { + return reinterpret_cast(n); +} bool check(bool condition, const char* description) { if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); return condition; } + +// The device the expander sees: every buffer's address is 0x1000 times its handle. +VKAPI_ATTR VkDeviceAddress VKAPI_CALL device_address(VkDevice, const VkBufferDeviceAddressInfo* info) { + return VkDeviceAddress(reinterpret_cast(info->buffer)) * 0x1000; +} +VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice, const VkShaderModuleCreateInfo* info, + const VkAllocationCallbacks*, VkShaderModule* out) { + *out = handle(20); + return info->codeSize && info->pCode[0] == 0x07230203u ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; +} +VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL create_layout(VkDevice, const VkPipelineLayoutCreateInfo* info, + const VkAllocationCallbacks*, VkPipelineLayout* out) { + *out = handle(21); + return info->pushConstantRangeCount == 1 && info->pPushConstantRanges[0].size == sizeof(Push) + ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; +} +VKAPI_ATTR void VKAPI_CALL destroy_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, std::uint32_t, + const VkComputePipelineCreateInfo*, const VkAllocationCallbacks*, + VkPipeline* out) { + *out = handle(22); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {} +VKAPI_ATTR void VKAPI_CALL cmd_barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst, + VkDependencyFlags, std::uint32_t count, const VkMemoryBarrier* memory, + std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, + const VkImageMemoryBarrier*) { + barriers.push_back({src, dst, count == 1 ? memory->srcAccessMask : 0, count == 1 ? memory->dstAccessMask : 0}); + events.push_back("barrier"); +} +VKAPI_ATTR void VKAPI_CALL cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint point, VkPipeline) { + events.push_back(point == VK_PIPELINE_BIND_POINT_COMPUTE ? "bind_compute" : "bind_graphics"); +} +VKAPI_ATTR void VKAPI_CALL cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags stages, + std::uint32_t, std::uint32_t size, const void* values) { + if (stages != VK_SHADER_STAGE_COMPUTE_BIT || size != sizeof(Push)) return; // the draw's own user data + std::memcpy(&pushes.emplace_back(), values, sizeof(Push)); +} +VKAPI_ATTR void VKAPI_CALL cmd_dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t y, std::uint32_t z) { + dispatches.push_back(y == 1 && z == 1 ? x : 0); + events.push_back("dispatch"); +} +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice, const char* name) { +#define PROC(vk_name, function) \ + if (std::strcmp(name, vk_name) == 0) return reinterpret_cast(function) + PROC("vkGetBufferDeviceAddress", device_address); + PROC("vkCreateShaderModule", create_module); + PROC("vkDestroyShaderModule", destroy_module); + PROC("vkCreatePipelineLayout", create_layout); + PROC("vkDestroyPipelineLayout", destroy_layout); + PROC("vkCreateComputePipelines", create_pipelines); + PROC("vkDestroyPipeline", destroy_pipeline); + PROC("vkCmdPipelineBarrier", cmd_barrier); + PROC("vkCmdBindPipeline", cmd_bind_pipeline); + PROC("vkCmdPushConstants", cmd_push_constants); + PROC("vkCmdDispatch", cmd_dispatch); +#undef PROC + return nullptr; +} + +VKAPI_ATTR void VKAPI_CALL begin_query(VkCommandBuffer, VkQueryPool, std::uint32_t index, VkQueryControlFlags) { + events.push_back("begin_query " + std::to_string(index)); +} +VKAPI_ATTR void VKAPI_CALL end_query(VkCommandBuffer, VkQueryPool, std::uint32_t index) { + events.push_back("end_query " + std::to_string(index)); +} +VKAPI_ATTR void VKAPI_CALL destroy_query_pool(VkDevice, VkQueryPool, const VkAllocationCallbacks*) {} + +void reset() { + calls.clear(); + pushes.clear(); + dispatches.clear(); + barriers.clear(); + events.clear(); + scratch_requests.clear(); +} } int main() { using namespace leonida; ReplayFunctions vk{}; - vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; - vk.end_rendering = +[](VkCommandBuffer) {}; - vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; - vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, - std::uint32_t, const void*) {}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) { events.push_back("begin_rendering"); }; + vk.end_rendering = +[](VkCommandBuffer) { events.push_back("end_rendering"); }; + vk.bind_pipeline = cmd_bind_pipeline; + vk.push_constants = cmd_push_constants; vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; - vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32 enable) { + if (enable) events.push_back("primitive_restart"); + }; vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { @@ -56,16 +167,19 @@ int main() { recorded.base_vertex = base; recorded.first_instance = first_instance; calls.push_back(recorded); + events.push_back("draw_indexed"); }; - vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices = handle(1); vk.quad_indices_offset = 64; vk.quad_index_count = 12; - const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + const auto app_buffer = handle(2); GraphicsPipeline graphics{}; + graphics.pipeline = handle(3); + graphics.strip_cut = 1; // 0xFFFF cuts strips: it must not make a quad list restart const auto collect = [&](const Draw& draw) { - calls.clear(); + reset(); CommandList list; if (!list.draw(draw) || !list.close()) return false; PreparedList prepared; @@ -92,19 +206,201 @@ int main() { 12, 2, 0, 13, 7}; bool ok = check(collect(draw) && calls == std::vector{triangles}, "non-indexed quads use one triangle-list draw and preserve draw bases"); + ok &= check(dispatches.empty(), "non-indexed quads need no index expansion"); draw.count = 13; ok &= check(collect(draw) && calls == std::vector{triangles}, "a draw is limited to whole quads in the generated index buffer"); draw.count = 3; ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + // Indexed quads, through prepare(): the real expander on the recording device above. + VkPhysicalDeviceLimits limits{}; + limits.maxComputeWorkGroupCount[0] = 65535; + QuadIndexExpander expander(device_proc, handle(9), limits); + const auto scratch = handle(5), zero_page = handle(6); + constexpr VkDeviceSize scratch_offset = 512; + std::uint64_t app_bytes = 64; // the application's buffer past the view's start + vk.graphics_pipeline = [&](std::uintptr_t) -> const GraphicsPipeline* { return &graphics; }; + vk.buffer_at = [&](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + buffer = app_buffer; + offset = va; // the console VA is the offset in this test + size = std::min(size, app_bytes); + return true; + }; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return VkImageView{}; }; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, + const VkDeviceSize*, const VkDeviceSize*, const VkDeviceSize*) {}; + vk.draw = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.zero_buffer = zero_page; + vk.zero_size = 65536; + vk.copy_scratch = [&](VkDeviceSize bytes, VkBuffer& buffer, VkDeviceSize& offset) { + scratch_requests.push_back(bytes); + buffer = scratch; + offset = scratch_offset; + return true; + }; + const auto wire = [](ReplayFunctions& functions, QuadIndexExpander& to) { + functions.prepare_quad_indices = [&to](VkBuffer indices, VkDeviceSize offset, VkIndexType type, + std::uint64_t readable, std::uint32_t quads, VkBuffer target, + VkDeviceSize target_offset, QuadIndexExpansion& out) { + return to.prepare(indices, offset, type, readable, quads, target, target_offset, out); + }; + functions.emit_quad_indices = [&to](VkCommandBuffer cb, const QuadIndexExpansion& job) { to.emit(cb, job); }; + }; + wire(vk, expander); + const auto resolve = [](ResourceId) -> const ResourceBinding* { return nullptr; }; + const auto run = [&](const Draw& indexed, const ReplayFunctions& functions) { + reset(); + CommandList list; + if (!list.draw(indexed) || !list.close()) return ReplayResult::list_open; + PreparedList prepared; + const auto result = prepare(list, resolve, functions, prepared); + if (result == ReplayResult::success) emit(prepared, VK_NULL_HANDLE, functions); + return result; + }; + + constexpr VkDeviceAddress app_address = 2 * 0x1000, scratch_address = 5 * 0x1000 + scratch_offset; + const Barrier before{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT}; + const Barrier after{VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT}; + const std::vector one_dispatch_one_draw{ + "barrier", "bind_compute", "dispatch", "barrier", "begin_rendering", "bind_graphics", "draw_indexed", + "end_rendering"}; + + // 16-bit indices: two quads and a ninth index, from index 5 of a view at byte 32 (the first index is at byte 42, + // the high half of the word at 40). The view holds 32 indices, 27 of them from index 5 on. draw.indexed = true; - draw.count = 8; + draw.index = {32, 64, 57}; // DXGI_FORMAT_R16_UINT + draw.count = 9; draw.first = 5; draw.base_vertex = -2; - const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; - const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; - ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, - "indexed quads use the application's index buffer and base vertex"); + const DrawCall expanded{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, scratch, scratch_offset, VK_INDEX_TYPE_UINT32, + 12, 2, 0, -2, 7}; + ok &= check(run(draw, vk) == ReplayResult::success && events == one_dispatch_one_draw, + "indexed quads are one dispatch before the rendering scope and one draw inside it"); + ok &= check(calls == std::vector{expanded}, + "indexed quads draw the expanded indices once, with the draw's instances and bases"); + ok &= check(dispatches == std::vector{1} && scratch_requests == std::vector{48}, + "two quads are one work group and 48 bytes of scratch"); + ok &= check(pushes == std::vector{Push{app_address + 40, scratch_address, 1, 16, 27, 2}}, + "16-bit indices are read from the word that holds the first one, up to the view's end"); + ok &= check(barriers == std::vector{before, after}, + "earlier writes are visible to the pass, and its indices to the draw"); + + // 32-bit indices through a view of six: the last two of the second quad read 0. + draw.index = {64, 24, 42}; // DXGI_FORMAT_R32_UINT + draw.count = 8; + draw.first = 0; + ok &= check(run(draw, vk) == ReplayResult::success && events == one_dispatch_one_draw && + pushes == std::vector{Push{app_address + 64, scratch_address, 0, 32, 6, 2}}, + "32-bit indices past the view are not read"); + // A view that runs past its buffer ends where the buffer does. + draw.index = {64, 4096, 42}; + app_bytes = 20; + ok &= check(run(draw, vk) == ReplayResult::success && pushes.size() == 1 && pushes[0].limit == 5, + "a view is cut at the end of its buffer"); + app_bytes = 64; + // The first index past the view, and no index buffer at all: every index reads 0. + draw.index = {64, 24, 42}; + draw.first = 6; + ok &= check(run(draw, vk) == ReplayResult::success && calls.size() == 1 && pushes.size() == 1 && + pushes[0].limit == 0 && pushes[0].source == app_address + 64, + "a draw that starts past the view reads no index"); + draw.index = {0, 0, 57}; + draw.first = 0; + ok &= check(run(draw, vk) == ReplayResult::success && calls.size() == 1 && pushes.size() == 1 && + pushes[0].limit == 0 && pushes[0].source == 6 * 0x1000, + "without an index buffer every index reads 0"); + + // Fewer than four indices: nothing to expand, nothing to draw. + draw.index = {32, 64, 57}; + draw.count = 3; + ok &= check(run(draw, vk) == ReplayResult::success && calls.empty() && dispatches.empty() && + scratch_requests.empty(), + "an incomplete indexed quad needs no scratch and emits no draw"); + + // What cannot be expanded is refused when the list is prepared. + draw.count = 8; + { + ReplayFunctions without = vk; + without.prepare_quad_indices = {}; + ok &= check(run(draw, without) == ReplayResult::unsupported && events.empty(), + "indexed quads are unsupported without the expander"); + without = vk; + without.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; + ok &= check(run(draw, without) == ReplayResult::unsupported && events.empty(), + "indexed quads are unsupported without scratch"); + Draw odd = draw; + odd.index = {33, 64, 57}; + ok &= check(run(odd, vk) == ReplayResult::unsupported && events.empty(), + "16-bit indices at an odd address are refused"); + Draw huge = draw; + huge.count = UINT32_MAX; // 6 indices for each quad would not fit vkCmdDrawIndexed's count + ok &= check(run(huge, vk) == ReplayResult::unsupported && scratch_requests.empty(), + "a draw whose expanded index count overflows 32 bits is refused before taking scratch"); + } + + // More quads than one dispatch may cover: 300 quads with two work groups (128 quads) for each dispatch. Every + // dispatch starts 512 indices (1024 bytes) and 128 * 24 bytes of scratch after the one before, and the view's + // 1000 indices from the first one run out in the second. + { + VkPhysicalDeviceLimits small{}; + small.maxComputeWorkGroupCount[0] = 2; + QuadIndexExpander chunked(device_proc, handle(9), small); + ReplayFunctions split = vk; + wire(split, chunked); + Draw many = draw; + many.index = {32, 2010, 57}; + many.count = 1200; + many.first = 5; + app_bytes = 4096; + const std::vector want{{app_address + 40, scratch_address, 1, 16, 1000, 128}, + {app_address + 40 + 1024, scratch_address + 128 * 24, 1, 16, 488, 128}, + {app_address + 40 + 2048, scratch_address + 256 * 24, 1, 16, 0, 44}}; + ok &= check(run(many, split) == ReplayResult::success && pushes == want && + dispatches == std::vector{2, 2, 1}, + "a large draw is expanded by several dispatches that continue where the last one stopped"); + ok &= check(calls.size() == 1 && calls[0].count == 1800 && scratch_requests == std::vector{7200}, + "a large draw is still one draw over one piece of scratch"); + app_bytes = 64; + } + + // Inside a pipeline-statistics query the dispatch must not be counted (CSInvocations): the query's segment ends + // before it and a new one begins after it, for the draw. Without a segment pool the list is refused. + { + QueryPool heap{handle(7), d3d12_query_heap::pipeline_statistics, 1, false, {false}, {}}; + ReplayFunctions queries = vk; + queries.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}; + queries.begin_query = begin_query; + queries.end_query = end_query; + queries.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool, std::uint32_t) {}; + queries.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, + VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}; + queries.fill_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}; + queries.query_pool = [&](QueryHeapId) { return &heap; }; + reset(); + CommandList list; + ok &= check(list.begin_query({6, d3d12_query::pipeline_statistics, 0}) && list.draw(draw) && + list.end_query({6, d3d12_query::pipeline_statistics, 0}) && list.close(), + "record a quad draw inside a statistics query"); + PreparedList prepared; + ok &= check(prepare(list, resolve, queries, prepared) == ReplayResult::unsupported && + scratch_requests.empty(), + "without a segment pool the expansion inside a statistics query is refused before its scratch"); + ok &= check(prepare(list, resolve, queries, prepared, true) == ReplayResult::success && + prepared.statistics_segment_count == 2, + "the expansion splits the statistics query in two segments"); + auto pool = std::make_shared(); + pool->pool = handle(8); + pool->destroy = destroy_query_pool; + QueryReplay plan; + ok &= check(plan.plan(prepared, {}, 0, true, pool, 4) == ReplayResult::success, "plan the split query"); + emit(prepared, VK_NULL_HANDLE, queries); + const std::vector want{ + "begin_query 4", "end_query 4", "barrier", "bind_compute", "dispatch", "barrier", "begin_query 5", + "begin_rendering", "bind_graphics", "draw_indexed", "end_rendering", "end_query 5"}; + ok &= check(events == want, "the dispatch runs between the query's two segments, the draw in the second"); + } return ok ? 0 : 1; } From 6ce66cf219c9036195f3abe429fa4893867057ca Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:09:40 -0500 Subject: [PATCH 10/13] d3d12: GPU test for indexed quad lists: both index sizes, a base vertex, flat inputs, overlapping instances (d3d12_quad_index) d3d12_rect_list draws its quads without an index buffer, so it could not see what #207's review measured on indexed ones. d3d12_quad_index_test draws six 64x64 frames through DrawIndexedInstanced with IASetPrimitiveTopology(19) and compares every pixel bit for bit: 0 non-indexed control 1 16-bit indices, a quad whose corners all differ: the first vertex's colour everywhere 2 32-bit indices from StartIndexLocation 3 3 16-bit indices from StartIndexLocation 5 (an address of 2 modulo 4), BaseVertexLocation 3 4 two quads and two instances whose quads overlap: the later instance on top 5 a view that ends inside the second quad: its last two indices read 0 The index buffer is in a DEFAULT heap and filled by a copy in the first list, so only the GPU can read it. Two translated fixtures, like vs_m15 and ps_m15: vs_quad_inst.asm reads the instance id (v3) to move and recolour each later instance, ps_quad_flat.asm reads its colour with v_interp_mov, which makes the input Flat. RTX 4070 SUPER (621.24), Windows 11, LEONIDA_VK_VALIDATION=1: on the six commits of #207: frames 1, 2, 3 and 5 match in 0 of 4096 pixels (black and blue, the second and third vertex), frame 4 in 2048, frame 0 in 4096; exit 1 with the expansion: 4096 of 4096 in all six, 0 validation errors run_gpu_tests.py lists the two fixtures as run by this test, and docs/testing.md names the test (and d3d12_rect_list) among those that need llvm-mc and the SPIR-V tools. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- docs/testing.md | 6 +- runtime/CMakeLists.txt | 25 ++ runtime/test/d3d12_quad_index_test.cpp | 341 +++++++++++++++++++++++++ runtime/test/shaders/ps_quad_flat.asm | 15 ++ runtime/test/shaders/vs_quad_inst.asm | 28 ++ scripts/run_gpu_tests.py | 3 +- 6 files changed, 414 insertions(+), 4 deletions(-) create mode 100644 runtime/test/d3d12_quad_index_test.cpp create mode 100644 runtime/test/shaders/ps_quad_flat.asm create mode 100644 runtime/test/shaders/vs_quad_inst.asm diff --git a/docs/testing.md b/docs/testing.md index 743d7b6406..29a075548d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -55,9 +55,9 @@ This page collects the setup steps and the problems testers have run into so far ## Build the test programs -On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_m2_textured`, -`d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and `d3d12_buffer_uav` when it finds `llvm-mc`, -`spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. +On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_rect_list`, +`d3d12_quad_index`, `d3d12_m2_textured`, `d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and +`d3d12_buffer_uav` when it finds `llvm-mc`, `spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. Without `glslangValidator`, other tests are also omitted, including `d3d12_compute`, `d3d12_draw`, `d3d12_set0_compute` and `d3d12_mesh`; some registered tests run only part of their checks. These tests can be **absent**, not reported as skipped, when their build prerequisites are missing, so a passing `ctest` percentage diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index be338e70d3..b7acb791d0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2437,6 +2437,31 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # Indexed quad lists (src/quad_index_expand.h): a vertex shader that reads the instance id and a pixel shader + # with a flat colour input, translated like vs_m15 and ps_m15. + set(LEONIDA_QUAD_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/quad_shaders) + set(LEONIDA_QUAD_FILES ${LEONIDA_QUAD_DIR}/spirv/index.json ${LEONIDA_QUAD_DIR}/fssm/vs_quad_inst.fssm + ${LEONIDA_QUAD_DIR}/fssm/ps_quad_flat.fssm) + add_custom_command( + OUTPUT ${LEONIDA_QUAD_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_QUAD_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_QUAD_DIR} vs_quad_inst ps_quad_flat + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_quad_inst.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_quad_flat.asm + COMMENT "Translating vs_quad_inst and ps_quad_flat for the indexed quad list test" + VERBATIM) + add_executable(d3d12_quad_index_test test/d3d12_quad_index_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_QUAD_FILES}) + target_link_libraries(d3d12_quad_index_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_quad_index_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_QUAD_DIR="${LEONIDA_QUAD_DIR}") + target_compile_options(d3d12_quad_index_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_quad_index COMMAND d3d12_quad_index_test) + set_tests_properties(d3d12_quad_index PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) diff --git a/runtime/test/d3d12_quad_index_test.cpp b/runtime/test/d3d12_quad_index_test.cpp new file mode 100644 index 0000000000..2d41f52189 --- /dev/null +++ b/runtime/test/d3d12_quad_index_test.cpp @@ -0,0 +1,341 @@ +// Indexed console quad lists (IASetPrimitiveTopology(19) with DrawIndexedInstanced) through the D3D12-on-Vulkan +// layer (src/quad_index_expand.h). +// +// Built like d3d12_rect_list_test.cpp, with two translated shaders of its own: vs_quad_inst (vertex fetch through a +// V#, each instance after the first moved by a root constant and its red and green swapped) and ps_quad_flat (the +// colour as a Flat input, so a quad shows the colour of the vertex it takes flat inputs from: its first). Vertices +// 0..3 and 4..7 are full-screen quads with a different colour at every corner; 8..11 and 12..15 are the left and the +// right half of the target, red at every corner. The index buffer is in a DEFAULT heap and is written by a copy in +// the first command list, so nothing but the GPU can read it when the draw is recorded. Six 64x64 frames: +// frame 0, control: a non-indexed quad, DrawInstanced(4) over vertices 0..3. Red (vertex 0) everywhere. +// frame 1: 16-bit indices 0 1 2 3. Red everywhere; a triangle fan shows vertices 1 and 2 (black and blue). +// frame 2: 32-bit indices 7 4 5 6 from StartIndexLocation 3. Green (vertex 7) everywhere. +// frame 3: 16-bit indices 0 1 2 3 from StartIndexLocation 5 (an address of 2 modulo 4) with BaseVertexLocation 3. +// The translated vertex shader's vertex id is the index without the base vertex, so this is frame 1 again; the +// base added into the indices would fetch vertices 3..6 instead (white). +// frame 4: two quads (left half, right half) and two instances; instance 1 is green and one half to the right, so +// its first quad lands on instance 0's second. D3D12 draws instance by instance: the right half ends green. +// Drawn quad by quad, instance 0's second quad comes last and leaves it red. +// frame 5: eight 16-bit indices, 0 1 2 3 and 7 4 5 6, through a view that ends after the sixth. The last two read +// 0 (D3D12: an index outside the view), which makes the second quad empty: red everywhere. Read past the view, +// the second quad covers the target in green. +// Every pixel is compared, bit for bit. LEONIDA_VK_VALIDATION=1 runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_QUAD_DIR +#error "LEONIDA_TEST_QUAD_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_quad_inst.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +constexpr Pixel red = {1, 0, 0, 1}, green = {0, 1, 0, 1}, blue = {0, 0, 1, 1}, black = {0, 0, 0, 1}, + white = {1, 1, 1, 1}; + +Vertex vertex(float x, float y, const Pixel& c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +struct Frame { + const char* name; + DXGI_FORMAT index_format; // DXGI_FORMAT_UNKNOWN: DrawInstanced + UINT view_offset, view_bytes; // the index buffer view, in the index buffer + UINT count, instances, start; + INT base_vertex; + Pixel left, right; // what the left and the right half of the target must hold +}; + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + const std::filesystem::path root_dir = LEONIDA_TEST_QUAD_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_quad_inst.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_quad_flat.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() >= 4); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + const Vertex vertices[16] = { + vertex(-1, 1, red), vertex(1, 1, black), vertex(1, -1, blue), vertex(-1, -1, white), + vertex(-1, 1, black), vertex(1, 1, blue), vertex(1, -1, white), vertex(-1, -1, green), + vertex(-1, 1, red), vertex(0, 1, red), vertex(0, -1, red), vertex(-1, -1, red), + vertex(0, 1, red), vertex(1, 1, red), vertex(1, -1, red), vertex(0, -1, red)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 512); + // Index 15 fills the gaps: a draw that starts at the wrong index shows it. + const std::uint16_t indices16[28] = {0, 1, 2, 3, 15, 0, 1, 2, 3, 15, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, + 0, 1, 2, 3, 7, 4, 5, 6}; + const std::uint32_t indices32[7] = {15, 15, 15, 7, 4, 5, 6}; + constexpr UINT indices32_offset = 64, index_bytes = 128; + static_assert(sizeof(indices16) <= indices32_offset && indices32_offset + sizeof(indices32) <= index_bytes); + const Frame frames[] = { + {"non-indexed (control)", DXGI_FORMAT_UNKNOWN, 0, 0, 4, 1, 0, 0, red, red}, + {"16-bit indices", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 4, 1, 0, 0, red, red}, + {"32-bit indices, first index 3", DXGI_FORMAT_R32_UINT, indices32_offset, sizeof(indices32), 4, 1, 3, 0, + green, green}, + {"16-bit indices, first index 5, base vertex 3", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 4, 1, 5, 3, + red, red}, + {"two overlapping instances", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 8, 2, 10, 0, red, green}, + {"view ends inside the second quad", DXGI_FORMAT_R16_UINT, 20 * sizeof(std::uint16_t), + 6 * sizeof(std::uint16_t), 8, 1, 0, 0, red, red}, + }; + constexpr std::size_t frame_count = std::size(frames); + std::vector pixels[frame_count]; + for (auto& p : pixels) p.resize(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + 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 root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; // quads use the triangle type + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, index_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto ib_desc = buffer_desc(index_bytes); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&index_buffer.p)))); + constexpr UINT upload_indices = 512; // where the index bytes sit in the upload buffer + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + std::memset(up + upload_indices, 0xee, index_bytes); // an index read from a gap is far out of the V# + std::memcpy(up + upload_indices, indices16, sizeof(indices16)); + std::memcpy(up + upload_indices + indices32_offset, indices32, sizeof(indices32)); + + // One V# over the sixteen vertices. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + const std::uint64_t index_va = index_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000 && index_va >= 0x10000 && index_va % 4 == 0); + leonida::gfx10::Buffer vsharp; + vsharp.address = buffer_va; + vsharp.stride = 32; + vsharp.num_records = std::uint32_t(std::size(vertices)); + vsharp.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + vsharp.oob_select = leonida::gfx10::OobSelect::structured; + const std::array vsharp_words = leonida::gfx10::encode(vsharp); + std::memcpy(reinterpret_cast(cpu), vsharp_words.data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + // The copies that fill the vertex and index buffers are in the first frame's list, before its draw. + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + list->CopyBufferRegion(index_buffer.p, 0, upload.p, upload_indices, index_bytes); + D3D12_RESOURCE_BARRIER barriers[3] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(index_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(3, barriers); + + const auto render_frame = [&](UINT64 number, const Frame& frame, std::vector& out) -> int { + if (number > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(quad_list); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {1, 0, 0, 0}; // each later instance: half the target to the right + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + if (frame.index_format == DXGI_FORMAT_UNKNOWN) { + list->DrawInstanced(frame.count, frame.instances, frame.start, 0); + } else { + const D3D12_INDEX_BUFFER_VIEW view{index_va + frame.view_offset, frame.view_bytes, frame.index_format}; + list->IASetIndexBuffer(&view); + list->DrawIndexedInstanced(frame.count, frame.instances, frame.start, frame.base_vertex, 0); + } + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, number))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(number, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + for (std::size_t i = 0; i < frame_count; ++i) EXPECT(render_frame(i + 1, frames[i], pixels[i]) == 0); + for (auto* r : {&vertex_buffer, &index_buffer, &upload, &readback, &target}) r->reset(); + pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + constexpr unsigned all = target_extent * target_extent; + bool ok = true; + for (std::size_t i = 0; i < frame_count; ++i) { + unsigned exact = 0, reported = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const Pixel& want = col < target_extent / 2 ? frames[i].left : frames[i].right; + const Pixel& got = pixels[i][row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) { + ++exact; + } else if (reported++ < 2) { + std::fprintf(stderr, "frame %zu (%s) pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", i, + frames[i].name, col, row, got[0], got[1], got[2], got[3], want[0], want[1], + want[2], want[3]); + } + } + } + std::printf("frame %zu, %s: %u of %u pixels exact\n", i, frames[i].name, exact, all); + ok = ok && exact == all; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + if (!ok) return 1; + std::printf("indexed quad lists: %zu frames of %u pixels exact\n", frame_count, all); + return 0; +} diff --git a/runtime/test/shaders/ps_quad_flat.asm b/runtime/test/shaders/ps_quad_flat.asm new file mode 100644 index 0000000000..ae84247241 --- /dev/null +++ b/runtime/test/shaders/ps_quad_flat.asm @@ -0,0 +1,15 @@ +; Pixel shader for the indexed quad-list test: param0 (a colour) read only with v_interp_mov, so the input is Flat +; and every pixel of a primitive gets the provoking vertex's colour, unscaled. Run: d3d12_quad_index_test, with +; vs_quad_inst. +; mrt0 = param0 of the primitive's provoking vertex +; A quad list takes it from the quad's first vertex. The test's quads have a different colour at each corner, so +; a quad drawn from any other vertex shows that vertex's colour instead; the colours are 0 and 1, exact in the float +; render target. +; fssm-at: 0x10 +; fssm-data: 0x44415551 0x20535020 +v_interp_mov_f32_e32 v2, p0, attr0.x +v_interp_mov_f32_e32 v3, p0, attr0.y +v_interp_mov_f32_e32 v4, p0, attr0.z +v_interp_mov_f32_e32 v5, p0, attr0.w +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/vs_quad_inst.asm b/runtime/test/shaders/vs_quad_inst.asm new file mode 100644 index 0000000000..48adac14af --- /dev/null +++ b/runtime/test/shaders/vs_quad_inst.asm @@ -0,0 +1,28 @@ +; Vertex shader for the indexed quad-list test: vs_m15's vertex fetch through a V#, plus the instance id. Run: +; d3d12_quad_index_test (through a D3D12 graphics PSO found by the SHA-256 of its FSSM program), with ps_quad_flat. +; +; User data, from the root signature [0] descriptor table, [1] four 32-bit constants (docs/d3d12_vulkan.md 3.5): +; s[0:1] = console VA of the table's first slot: the 16 bytes of a V# (base VA, stride 32) +; s2, s3 = the clip-space offset (x, y) of each instance after the first, as floats +; v0 = the vertex id and v3 = the instance id, both zero-based as on the hardware (vs_base_ids.asm): in an indexed +; draw v0 is the index the application wrote, without the draw's base vertex. +; Vertex record, 32 bytes: position xyzw at 0, colour rgba at 16 (both float). +; pos0 = (position.x + instance * s2, position.y + instance * s3, position.z, position.w) +; param0 = colour for instance 0, colour.grba (red and green swapped) for every later instance +; The test draws red quads with two instances: instance 0 stays red, instance 1 is green and one offset further on. +; fssm-at: 0x10 +; fssm-data: 0x44415551 0x20535620 +s_load_dwordx4 s[8:11], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +buffer_load_dwordx4 v[8:11], v0, s[8:11], 0 idxen offset:16 +s_waitcnt vmcnt(0) +v_cvt_f32_u32_e32 v12, v3 +v_fma_f32 v4, v12, s2, v4 +v_fma_f32 v5, v12, s3, v5 +v_cmp_ne_u32_e32 vcc_lo, 0, v3 +v_cndmask_b32_e32 v13, v8, v9, vcc_lo +v_cndmask_b32_e32 v14, v9, v8, vcc_lo +exp pos0 v4, v5, v6, v7 done +exp param0 v13, v14, v10, v11 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index a075c876a4..ae5f064249 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -659,7 +659,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test", "ps_live_width": "w64_graphics.py", - "ps_heap_index": "d3d12_heap_index_test"} + "ps_heap_index": "d3d12_heap_index_test", + "ps_quad_flat": "d3d12_quad_index_test", "vs_quad_inst": "d3d12_quad_index_test"} # Shaders a selected test draws with, built even when the filter leaves them out (#192). From a60f66ee95b2bd9c08f7fa7fe2a624fc400c09eb Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:09:40 -0500 Subject: [PATCH 11/13] docs: d3d12_vulkan: how quad lists are drawn, indexed ones through the index expansion The quad list entry of "Console rectangle and quad lists" described the fan per quad and its two faults. It now describes both paths as one triangle-list draw, the compute pass for indexed draws and where it runs, what it does with the base vertex, the strip-cut values and indices past the view, what it needs, the measurement that replaced the fans, and what is still not covered (ExecuteIndirect draws, which record no topology). AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- docs/d3d12_vulkan.md | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6ecc34081d..7ff1303e13 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2120,14 +2120,37 @@ The trace will enumerate them. ### Console rectangle and quad lists -The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact; `d3d12_quad_index_test` for indexed quads). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern - `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance - order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still - read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking - vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type - is the ordinary triangle type. +- **Quad list**: one triangle-list draw whose indices are `i0 i1 i2, i0 i2 i3` for each quad. Both triangles start + at the quad's first vertex, the one Vulkan takes flat inputs from, and one draw keeps D3D12's instance order + (instance by instance, not quad by quad). The PSO type is the ordinary triangle type. + - **Non-indexed**: a shared index buffer in the arena holds the pattern `0 1 2, 0 2 3` for 16384 quads (a draw + with more is cut off there, with a log line). The draw's first vertex becomes the vertex offset. + - **Indexed**: a compute pass (`src/quad_index_expand.comp`, run by `src/quad_index_expand.h`) reads the + application's index buffer on the GPU and writes the six 32-bit indices of each quad into copy scratch + (`src/vulkan_scratch.h`); the draw binds that scratch with the application's instance count, base vertex and + first instance. The host never reads the indices: a copy or a shader earlier in the same list can have written + them. The pass runs before the draw's rendering scope, after a barrier that makes earlier writes visible to it + and before one that makes its indices visible to the draw, and between two segments of an active + pipeline-statistics query so that `CSInvocations` does not count it (as for the other helper dispatches, + D3D-162). + - Index values are copied as they are, a 16-bit one zero-extended, so `VertexIndex - BaseVertex` is still the + application's index in a translated vertex shader. + - The strip-cut values `0xFFFF` and `0xFFFFFFFF` are ordinary indices, as in every list topology: the replay + enables primitive restart for strips only. What the console does with one inside a quad is not measured. + - An index past the end of the index buffer view reads 0, as in D3D12; the pass never reads past the view. + A draw's last one to three indices that do not make a quad are dropped. + - Needs `bufferDeviceAddress` (the pass uses device addresses, no descriptors). Without it, and inside a + statistics query that cannot be split, the list fails as unsupported instead of drawing something else. + - **Why not a triangle fan per quad** (the first version of the indexed path): a fan takes a flat input from + each triangle's own first vertex, the quad's second and third, and a draw per quad runs every instance of one + quad before the next quad. `d3d12_quad_index_test` shows both on an RTX 4070 SUPER: a quad with a red first + vertex came out black and blue (0 of 4096 pixels red), and of two overlapping instances the first one's + second quad ended on top (2048 of 4096 pixels right). With the expansion all six frames are exact: 16-bit and + 32-bit indices, a first index at an address of 2 modulo 4, a base vertex, two instances, and a view that ends + inside the second quad. + - **Not covered**: quad and rectangle lists through `ExecuteIndirect`, whose draws do not record a topology. ## 4. Object model mapping From 2bd97967bacf41b9c3cb02f729a8fad8b3c33696 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:49:48 -0500 Subject: [PATCH 12/13] d3d12: align standalone shader-addressable quad index buffers --- docs/d3d12_vulkan.md | 10 +++++---- runtime/shims/d3d12_vulkan_device.cpp | 26 +++++++++++++++--------- runtime/test/d3d12_quad_index_test.cpp | 28 +++++++++++++++++++++----- 3 files changed, 45 insertions(+), 19 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 7ff1303e13..e777fce430 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2139,17 +2139,19 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv application's index in a translated vertex shader. - The strip-cut values `0xFFFF` and `0xFFFFFFFF` are ordinary indices, as in every list topology: the replay enables primitive restart for strips only. What the console does with one inside a quad is not measured. - - An index past the end of the index buffer view reads 0, as in D3D12; the pass never reads past the view. - A draw's last one to three indices that do not make a quad are dropped. + - An index past the end of the index buffer view reads 0, as in D3D12. The pass reads a 16-bit index from its + aligned 32-bit word, so standalone shader-addressable Vulkan buffers round their backing size up to a word. + The D3D buffer size and view bounds are unchanged. A draw's last one to three indices that do not make a quad + are dropped. - Needs `bufferDeviceAddress` (the pass uses device addresses, no descriptors). Without it, and inside a statistics query that cannot be split, the list fails as unsupported instead of drawing something else. - **Why not a triangle fan per quad** (the first version of the indexed path): a fan takes a flat input from each triangle's own first vertex, the quad's second and third, and a draw per quad runs every instance of one quad before the next quad. `d3d12_quad_index_test` shows both on an RTX 4070 SUPER: a quad with a red first vertex came out black and blue (0 of 4096 pixels red), and of two overlapping instances the first one's - second quad ended on top (2048 of 4096 pixels right). With the expansion all six frames are exact: 16-bit and + second quad ended on top (2048 of 4096 pixels right). With the expansion the seven test frames cover 16-bit and 32-bit indices, a first index at an address of 2 modulo 4, a base vertex, two instances, and a view that ends - inside the second quad. + inside the second quad, plus a 16-bit draw that reaches the end of a standalone upload buffer. - **Not covered**: quad and rectangle lists through `ExecuteIndirect`, whose draws do not record a topology. ## 4. Object model mapping diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index b88a372e70..a952bcbc3b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -72,6 +72,11 @@ constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); +// Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. +UINT64 align_up(UINT64 value, UINT64 to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered // to standard DXIL, whose baseline is 6.0. Answering the driver's own maximum would tell the game it can hand this @@ -1895,7 +1900,9 @@ class Resource final const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = desc_.Width; + // The indexed quad pass loads 16-bit indices from aligned 32-bit words. Keep the final word inside the + // Vulkan buffer while the D3D resource and views still use desc_.Width. + info.size = addressable || need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | @@ -1933,7 +1940,7 @@ class Resource final if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; - std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed + std::memset(mapped_, 0, std::size_t(info.size)); // committed resources and private padding start zeroed } if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; @@ -1986,13 +1993,17 @@ class Resource final if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; const auto start = reinterpret_cast(address); if (!address || !desc_.Width || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + // Apply the same backing size rule to imports. The committed-range check and Vulkan bind requirements + // below cover the padding as well. The import never initializes or writes the caller's padding. + const VkDeviceSize backing_size = need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; // The import starts at the page that holds `address`, and the buffer is bound at the offset inside it: the // title places small buffers inside a page too (a 16-byte UAV at a 64-byte-aligned address on an RTX 5090, // found in review), which an import of `address` itself would refuse. const std::uintptr_t base = start & ~static_cast(alignment - 1); void* const base_address = reinterpret_cast(base); const VkDeviceSize offset = start - base; - const VkDeviceSize bytes = (offset + desc_.Width + alignment - 1) & ~(alignment - 1); + const VkDeviceSize bytes = align_up(offset + backing_size, alignment); // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback @@ -2018,11 +2029,10 @@ class Resource final at = region_end - base; } if (!importable) return E_NOTIMPL; - const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; - info.size = desc_.Width; + info.size = backing_size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | @@ -2040,7 +2050,7 @@ class Resource final return E_NOTIMPL; const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; // An offset off the buffer's own alignment cannot be bound: the fallback answers. - if (!types || (offset % requirements.alignment) || bytes < offset + requirements.size) return E_NOTIMPL; + if (!types || (offset % requirements.alignment) || requirements.size > bytes - offset) return E_NOTIMPL; VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = base_address; @@ -8329,10 +8339,6 @@ class Device final static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; - // Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. - static UINT64 align_up(UINT64 value, UINT64 to) { - return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; - } // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and diff --git a/runtime/test/d3d12_quad_index_test.cpp b/runtime/test/d3d12_quad_index_test.cpp index 2d41f52189..03ce0a0eec 100644 --- a/runtime/test/d3d12_quad_index_test.cpp +++ b/runtime/test/d3d12_quad_index_test.cpp @@ -5,8 +5,8 @@ // V#, each instance after the first moved by a root constant and its red and green swapped) and ps_quad_flat (the // colour as a Flat input, so a quad shows the colour of the vertex it takes flat inputs from: its first). Vertices // 0..3 and 4..7 are full-screen quads with a different colour at every corner; 8..11 and 12..15 are the left and the -// right half of the target, red at every corner. The index buffer is in a DEFAULT heap and is written by a copy in -// the first command list, so nothing but the GPU can read it when the draw is recorded. Six 64x64 frames: +// right half of the target, red at every corner. Most cases use a DEFAULT heap index buffer written by a copy in +// the first command list, so nothing but the GPU can read it when the draw is recorded. Seven 64x64 frames: // frame 0, control: a non-indexed quad, DrawInstanced(4) over vertices 0..3. Red (vertex 0) everywhere. // frame 1: 16-bit indices 0 1 2 3. Red everywhere; a triangle fan shows vertices 1 and 2 (black and blue). // frame 2: 32-bit indices 7 4 5 6 from StartIndexLocation 3. Green (vertex 7) everywhere. @@ -19,6 +19,8 @@ // frame 5: eight 16-bit indices, 0 1 2 3 and 7 4 5 6, through a view that ends after the sixth. The last two read // 0 (D3D12: an index outside the view), which makes the second quad empty: red everywhere. Read past the view, // the second quad covers the target in green. +// frame 6: a standalone 10-byte UPLOAD index buffer, first index 1. All four 16-bit indices are readable, with +// the last one at the end of the resource. The backing buffer must accommodate the full word load. // Every pixel is compared, bit for bit. LEONIDA_VK_VALIDATION=1 runs it under the validation layer. #include "vk_test_device.h" #include "d3d12_test_shaders.h" @@ -72,6 +74,7 @@ struct Frame { UINT count, instances, start; INT base_vertex; Pixel left, right; // what the left and the right half of the target must hold + bool use_upload_indices = false; }; } // namespace @@ -97,6 +100,7 @@ int main() { const std::uint16_t indices16[28] = {0, 1, 2, 3, 15, 0, 1, 2, 3, 15, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, 0, 1, 2, 3, 7, 4, 5, 6}; const std::uint32_t indices32[7] = {15, 15, 15, 7, 4, 5, 6}; + const std::uint16_t upload_indices16[] = {15, 0, 1, 2, 3}; constexpr UINT indices32_offset = 64, index_bytes = 128; static_assert(sizeof(indices16) <= indices32_offset && indices32_offset + sizeof(indices32) <= index_bytes); const Frame frames[] = { @@ -109,6 +113,8 @@ int main() { {"two overlapping instances", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 8, 2, 10, 0, red, green}, {"view ends inside the second quad", DXGI_FORMAT_R16_UINT, 20 * sizeof(std::uint16_t), 6 * sizeof(std::uint16_t), 8, 1, 0, 0, red, red}, + {"16-bit indices at the end of an upload buffer", DXGI_FORMAT_R16_UINT, 0, + sizeof(upload_indices16), 4, 1, 1, 0, red, red, true}, }; constexpr std::size_t frame_count = std::size(frames); std::vector pixels[frame_count]; @@ -164,7 +170,7 @@ int main() { const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - Ref vertex_buffer, index_buffer, upload, readback, target; + Ref vertex_buffer, index_buffer, upload_index_buffer, upload, readback, target; const auto vb_desc = buffer_desc(sizeof(vertices)); EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, @@ -173,6 +179,15 @@ int main() { EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&index_buffer.p)))); + const auto upload_ib_desc = buffer_desc(sizeof(upload_indices16)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_ib_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload_index_buffer.p)))); + EXPECT(upload_index_buffer->GetDesc().Width == sizeof(upload_indices16)); + void* index_map = nullptr; + EXPECT(SUCCEEDED(upload_index_buffer->Map(0, nullptr, &index_map))); + std::memcpy(index_map, upload_indices16, sizeof(upload_indices16)); + upload_index_buffer->Unmap(0, nullptr); constexpr UINT upload_indices = 512; // where the index bytes sit in the upload buffer const auto upload_desc = buffer_desc(1024); EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, @@ -209,7 +224,9 @@ int main() { EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); const std::uint64_t index_va = index_buffer->GetGPUVirtualAddress(); + const std::uint64_t upload_index_va = upload_index_buffer->GetGPUVirtualAddress(); EXPECT(buffer_va >= 0x10000 && index_va >= 0x10000 && index_va % 4 == 0); + EXPECT(upload_index_va && upload_index_va % 4 == 0); leonida::gfx10::Buffer vsharp; vsharp.address = buffer_va; vsharp.stride = 32; @@ -271,7 +288,8 @@ int main() { if (frame.index_format == DXGI_FORMAT_UNKNOWN) { list->DrawInstanced(frame.count, frame.instances, frame.start, 0); } else { - const D3D12_INDEX_BUFFER_VIEW view{index_va + frame.view_offset, frame.view_bytes, frame.index_format}; + const std::uint64_t frame_index_va = frame.use_upload_indices ? upload_index_va : index_va; + const D3D12_INDEX_BUFFER_VIEW view{frame_index_va + frame.view_offset, frame.view_bytes, frame.index_format}; list->IASetIndexBuffer(&view); list->DrawIndexedInstanced(frame.count, frame.instances, frame.start, frame.base_vertex, 0); } @@ -299,7 +317,7 @@ int main() { return 0; }; for (std::size_t i = 0; i < frame_count; ++i) EXPECT(render_frame(i + 1, frames[i], pixels[i]) == 0); - for (auto* r : {&vertex_buffer, &index_buffer, &upload, &readback, &target}) r->reset(); + for (auto* r : {&vertex_buffer, &index_buffer, &upload_index_buffer, &upload, &readback, &target}) r->reset(); pso.reset(); root.reset(); srv_heap.reset(); From 6aa8eb11c66e66cf38a8f789c76bf7c7200a842d Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:21:07 -0500 Subject: [PATCH 13/13] d3d12: check prepared draw index before query planning --- runtime/src/vulkan_replay.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 3225cffeb3..7b6613d502 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -2400,7 +2400,8 @@ inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) { const auto& p = out.commands[i]; if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect) return true; - return std::holds_alternative(out.list->commands()[i]) && out.draws[p.draw].quad_indices.buffer; + return std::holds_alternative(out.list->commands()[i]) && p.draw < out.draws.size() && + out.draws[p.draw].quad_indices.buffer; } // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and