From 65c580fde83827872aa6a8eeaee96d60956a00ed Mon Sep 17 00:00:00 2001 From: Miici0 Date: Wed, 25 Nov 2026 14:43:00 +0100 Subject: [PATCH 1/3] d3d12: accept StreamOutput PSOs, implement SOSetTargets, capture draws via VK_EXT_transform_feedback Builds on D3D-TRANSFORM-FEEDBACK-DEVICE (the device-capability plumbing): a graphics PSO that declares StreamOutput is now accepted instead of refused (the common case only: RasterizedStream 0, NumStrides within the device's maxTransformFeedbackBuffers), SOSetTargets stores the bound buffers on the command list the same way IASetVertexBuffers does, and a draw with a pipeline that has StreamOutput and every declared buffer slot bound wraps itself in vkCmdBindTransformFeedbackBuffersEXT + vkCmdBeginTransformFeedbackEXT / vkCmdEndTransformFeedbackEXT, writing real captured data. Not done, left as follow-up: - RasterizedStream other than 0 (needs VkPipelineRasterizationStateStreamCreateInfoEXT / rasterizerDiscardEnable at pipeline creation) - SO_STATISTICS queries (still stubbed to 0; the real wiring is VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT with the indexed vkCmdBeginQueryIndexedEXT/EndQueryIndexedEXT commands) - Matching a real translated game shader's output semantics to StreamOutput buffer slots, which needs patching Xfb decorations into its SPIR-V at PSO creation time (the translator runs before any PSO exists, so it cannot know this ahead of time) - this PR's own test uses a hand-written GLSL shader with the decorations already in place, not a translated one New test d3d12_stream_output_test.cpp: a StreamOutput PSO with a hand-written vertex shader (runtime/test/glsl/vs_stream_output.vert, Xfb-decorated, writes the fixed vec4 (1,2,3,4)) draws 3 vertices; the buffer SOSetTargets bound is read back and every vertex's 16 bytes are checked against that constant. 0 mismatches on real hardware. Full ctest run (runtime/build, RelWithDebInfo): 307/308 pass (one more test than main, the new one); the only failure is the pre-existing d3d12_execute_indirect_validation (#504, fixed by the separate PR #1066, unrelated to this change). No regressions. GPU: NVIDIA GeForce RTX 4070 SUPER, driver 621.24, Windows 11 26300.9974. Co-Authored-By: Claude Sonnet 5 --- runtime/CMakeLists.txt | 27 +++ runtime/shims/d3d12_com.cpp | 27 +++ runtime/shims/d3d12_com.h | 4 + runtime/shims/d3d12_vulkan_device.cpp | 34 +++- runtime/src/command_list.h | 9 + runtime/src/vulkan_backend.h | 7 +- runtime/src/vulkan_replay.h | 81 +++++++++ runtime/test/d3d12_stream_output_test.cpp | 207 ++++++++++++++++++++++ runtime/test/glsl/ps_stream_output.frag | 9 + runtime/test/glsl/vs_stream_output.vert | 11 ++ runtime/test/vk_test_device.h | 33 ++++ 11 files changed, 442 insertions(+), 7 deletions(-) create mode 100644 runtime/test/d3d12_stream_output_test.cpp create mode 100644 runtime/test/glsl/ps_stream_output.frag create mode 100644 runtime/test/glsl/vs_stream_output.vert diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 58b9561847..215a01dc8f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4558,6 +4558,33 @@ if(TARGET Vulkan::Headers) # the thread (d3d12_compile_teardown_test). set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # D3D-302: a StreamOutput PSO and SOSetTargets actually capture a draw's output, read back and checked + # against the shader's fixed vec4. The PS just needs a valid render target to rasterize into (its own + # output colour is not checked), so it is its own trivial shader rather than ps_draw's CBV-reading one. + set(LEONIDA_TEST_VS_STREAM_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_stream_output.spv) + set(LEONIDA_TEST_PS_STREAM_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_stream_output.spv) + foreach(pair "vs_stream_output.vert;${LEONIDA_TEST_VS_STREAM_OUTPUT}" + "ps_stream_output.frag;${LEONIDA_TEST_PS_STREAM_OUTPUT}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command( + OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling the stream-output test shader ${source}" + VERBATIM) + endforeach() + add_executable(d3d12_stream_output_test test/d3d12_stream_output_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_VS_STREAM_OUTPUT} ${LEONIDA_TEST_PS_STREAM_OUTPUT}) + target_link_libraries(d3d12_stream_output_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_stream_output_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_STREAM_OUTPUT_SPV="${LEONIDA_TEST_VS_STREAM_OUTPUT}" + LEONIDA_TEST_PS_STREAM_OUTPUT_SPV="${LEONIDA_TEST_PS_STREAM_OUTPUT}") + target_compile_options(d3d12_stream_output_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_stream_output COMMAND d3d12_stream_output_test) + set_tests_properties(d3d12_stream_output PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 5ae879e04d..5401c9eed6 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -476,6 +476,22 @@ class GraphicsCommandList final set_vertex_buffers(start, count, views); } + // D3D-302. Unlike vertex buffers, an unbound slot inside [start, start+count) stays unbound (no zero-page + // fallback): the pipeline's StreamOutput declaration says how many slots it needs, and prepare_draw treats any + // of those left unbound as "stream output not active for this draw" rather than inventing a destination. + void STDMETHODCALLTYPE SOSetTargets(UINT start, UINT count, const D3D12_STREAM_OUTPUT_BUFFER_VIEW* views) override { + if (std::uint64_t(start) + count > so_buffers_.size()) return check(false); + if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) { + std::vector copy; + if (views) copy.assign(views, views + count); + defer([=, copy = std::move(copy), bound = views != nullptr](GraphicsCommandList& l) { + l.set_so_targets(start, count, bound ? copy.data() : nullptr); + }); + return; + } + set_so_targets(start, count, views); + } + void STDMETHODCALLTYPE IASetIndexBuffer(const D3D12_INDEX_BUFFER_VIEW* view) override { if (list_->closed()) return; const std::optional copy = view ? std::optional(*view) : std::nullopt; @@ -1839,6 +1855,7 @@ class GraphicsCommandList final std::uint64_t console_high_base_ = 0; // the console heap table_high_[2] is for std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; + std::array so_buffers_{}; leonida::IndexBufferView index_{}; void note_write_va(std::uint64_t va, std::uint64_t bytes) { if (va && bytes) write_ranges_.emplace_back(va, bytes); @@ -2117,6 +2134,7 @@ class GraphicsCommandList final direct_cbv_table_recorded_ = false; topology_ = 0; vertex_buffers_ = {}; + so_buffers_ = {}; index_ = {}; viewport_ = {}; scissor_ = {}; @@ -2185,6 +2203,14 @@ class GraphicsCommandList final } } + void set_so_targets(UINT start, UINT count, const D3D12_STREAM_OUTPUT_BUFFER_VIEW* views) { + if (count) draw_views_stale_ = true; + for (UINT i = 0; i < count; ++i) + so_buffers_[start + i] = views ? leonida::SOBufferView{views[i].BufferLocation, views[i].SizeInBytes, + views[i].BufferFilledSizeLocation} + : leonida::SOBufferView{}; + } + void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { const std::uint64_t va = view ? leonida::title_gpu_views::to_host_view(view->BufferLocation, view->SizeInBytes) : 0; @@ -2325,6 +2351,7 @@ class GraphicsCommandList final auto views = std::make_shared(); views->render_targets = render_targets_; views->vertex_buffers = vertex_buffers_; + views->so_buffers = so_buffers_; views->render_target_count = render_target_count_; draw_views_ = std::move(views); draw_views_stale_ = false; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 79752e5141..a1e13c0ad7 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -258,6 +258,10 @@ struct VulkanDeviceInfo { // VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT query. Without it an SO_STATISTICS heap is made without a pool and // every SO_STATISTICS query resolves zero, even when the transformFeedback feature is enabled. bool transform_feedback_queries = false; + // VkPhysicalDeviceTransformFeedbackPropertiesEXT limits, read when VK_EXT_transform_feedback is enabled: a + // StreamOutput PSO's NumStrides must not exceed max_transform_feedback_buffers, and a non-default + // RasterizedStream must be below max_transform_feedback_streams. Both 0 when the extension is not enabled. + std::uint32_t max_transform_feedback_buffers = 0; // The device's maxTransformFeedbackStreams property: an SO_STATISTICS_STREAMn query runs only for n below it. // Streams from this count up (to the D3D12 maximum of four) run nothing and resolve zero. std::uint32_t max_transform_feedback_streams = 0; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 9eca923131..3e0b62bb85 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18148,8 +18148,26 @@ class PipelineState final if (rt0.BlendEnable && rt0.LogicOpEnable) return E_INVALIDARG; if (rt0.LogicOpEnable && unsigned(rt0.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; } - if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.StreamOutput.NumEntries) { - return stream_unsupported("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); + if (desc.HS.BytecodeLength || desc.DS.BytecodeLength) { + return stream_unsupported("graphics pipeline stage not supported yet (hull/domain):", 0); + } + // D3D-302: the plumbing only covers the common case (one rasterized stream, the default stream 0). A + // RasterizedStream other than 0 (an explicit stream, or D3D12_SO_NO_RASTERIZED_STREAM for capture-only) + // needs VkPipelineRasterizationStateStreamCreateInfoEXT / rasterizerDiscardEnable at pipeline creation, + // which is follow-up work; refuse it cleanly instead of silently rasterizing the wrong stream. + const D3D12_STREAM_OUTPUT_DESC& stream_output_desc = desc.StreamOutput; + const bool stream_output = stream_output_desc.NumEntries > 0; + if (stream_output) { + if (!device_.info.transform_feedback || !vk.vkCmdBeginTransformFeedbackEXT) { + log_once("StreamOutput PSOs need VK_EXT_transform_feedback, which the device has not enabled; stage", + 1); + return E_NOTIMPL; + } + if (stream_output_desc.NumStrides > device_.info.max_transform_feedback_buffers) return E_INVALIDARG; + if (stream_output_desc.RasterizedStream != 0) { + log_once("StreamOutput with a RasterizedStream other than 0 is not supported yet; stage", 1); + return E_NOTIMPL; + } } // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes // triangles and emits a triangle strip. It needs the geometryShader feature, and the PSO's topology type must @@ -18932,6 +18950,9 @@ class PipelineState final graphics_.stencil_writes = depth.stencilTestEnable != VK_FALSE && (stencil_face_writes(depth.front) || stencil_face_writes(depth.back)); + if (stream_output) + graphics_.so_strides.assign(stream_output_desc.pBufferStrides, + stream_output_desc.pBufferStrides + stream_output_desc.NumStrides); recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); @@ -21591,9 +21612,9 @@ class QueryHeap final case h::so_statistics: // D3D-302: with VK_EXT_transform_feedback enabled, an SO_STATISTICS heap is a real transform-feedback // pool whose queries begin/end on a stream (vkCmdBeginQueryIndexedEXT); a resolve copies 16 bytes per - // query (NumPrimitivesWritten, PrimitivesStorageNeeded), in the same order. StreamOutput PSOs are still - // refused and SOSetTargets is still not implemented, so no primitive reaches a stream yet and every - // query counts 0. The pool needs the transformFeedbackQueries property and at least one stream; without + // query (NumPrimitivesWritten, PrimitivesStorageNeeded), in the same order. StreamOutput PSOs and + // SOSetTargets now capture real primitives (prepare_draw, vulkan_replay.h), so this pool counts what + // they wrote. The pool needs the transformFeedbackQueries property and at least one stream; without // them (or without the feature) the heap is made without a pool and every query resolves to zero. if (!device_.info.transform_feedback || !device_.info.transform_feedback_queries || !device_.info.max_transform_feedback_streams) @@ -31565,11 +31586,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin vkGetPhysicalDeviceFeatures2(info.physical, &features); info.transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE; info.transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE; - // D3D-302: the queries and the stream count are properties, not features. + // D3D-302: the queries, buffer count and stream count are properties, not features. VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &transform_feedback_properties}; vkGetPhysicalDeviceProperties2(info.physical, &properties); info.transform_feedback_queries = transform_feedback_properties.transformFeedbackQueries == VK_TRUE; + info.max_transform_feedback_buffers = transform_feedback_properties.maxTransformFeedbackBuffers; info.max_transform_feedback_streams = transform_feedback_properties.maxTransformFeedbackStreams; } } diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 6aa0689466..57f3ae60c3 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -413,12 +413,21 @@ struct IndexBufferView { std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) }; +// D3D12_STREAM_OUTPUT_BUFFER_VIEW: console VAs, resolved to buffers at replay. filled_size_va is where the GPU +// keeps the running byte count written so far (D3D12_STREAM_OUTPUT_BUFFER_VIEW::BufferFilledSizeLocation); 0: unset. +struct SOBufferView { + std::uint64_t va; + std::uint64_t size; + std::uint64_t filled_size_va; +}; + // The views a draw captured, at the D3D12 maxima. Kept by value because the CPU descriptor slots and the bound // views can change after the draw is recorded, and out of line because the command variant is sized by its largest // member: inline they made every recorded command, barriers included, 976 bytes. struct DrawViews { std::array render_targets{}; std::array vertex_buffers{}; // by input slot + std::array so_buffers{}; // by SOSetTargets slot (D3D12_SO_BUFFER_SLOT_COUNT) std::uint32_t render_target_count = 8; }; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index db6c9ae26d..3c83cd78ee 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -132,7 +132,8 @@ struct VulkanDeviceFunctions { X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ - X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ + X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) X(vkCmdBindTransformFeedbackBuffersEXT) \ + X(vkCmdBeginTransformFeedbackEXT) X(vkCmdEndTransformFeedbackEXT) \ X(vkCmdBeginQueryIndexedEXT) X(vkCmdEndQueryIndexedEXT) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) @@ -1237,6 +1238,10 @@ class VulkanContext { replay_.draw_mesh_tasks_indirect = vk.vkCmdDrawMeshTasksIndirectEXT; replay_.draw_mesh_tasks_indirect_count = vk.vkCmdDrawMeshTasksIndirectCountEXT; replay_.draw_indexed = vk.vkCmdDrawIndexed; + // null unless VK_EXT_transform_feedback is enabled (D3D-302) + replay_.bind_transform_feedback_buffers = vk.vkCmdBindTransformFeedbackBuffersEXT; + replay_.begin_transform_feedback = vk.vkCmdBeginTransformFeedbackEXT; + replay_.end_transform_feedback = vk.vkCmdEndTransformFeedbackEXT; replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { const auto it = graphics_pipelines_.find(id); return it == graphics_pipelines_.end() ? nullptr : &it->second; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 16f029335c..bb44a039d4 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -950,6 +950,11 @@ struct GraphicsPipeline { bool writes_buffer = true; // false only when every stage's shader metadata proves no buffer/global/flat write bool depth_writes = true; // false when PSO disables depth test or uses DepthWriteMask == ZERO bool stencil_writes = true; // false when PSO disables stencil writes (StencilEnable == FALSE, writeMask == 0, or all KEEP) + // D3D12_STREAM_OUTPUT_DESC, kept to capture and wrap draws with this pipeline bound (D3D-302). Empty + // so_strides: the PSO declared no StreamOutput, same as before this was tracked at all. + std::vector so_strides; // by buffer slot, NumStrides entries + std::uint32_t so_rasterized_stream = 0; // D3D12_SO_NO_RASTERIZED_STREAM: no stream is rasterized + bool has_stream_output() const { return !so_strides.empty(); } }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -1281,6 +1286,10 @@ struct ReplayFunctions { PFN_vkCmdDrawMeshTasksIndirectEXT draw_mesh_tasks_indirect = nullptr; PFN_vkCmdDrawMeshTasksIndirectCountEXT draw_mesh_tasks_indirect_count = nullptr; PFN_vkCmdDrawIndexed draw_indexed = nullptr; + // VK_EXT_transform_feedback (D3D-302); null: StreamOutput pipelines are unsupported (create_graphics refuses them). + PFN_vkCmdBindTransformFeedbackBuffersEXT bind_transform_feedback_buffers = nullptr; + PFN_vkCmdBeginTransformFeedbackEXT begin_transform_feedback = nullptr; + PFN_vkCmdEndTransformFeedbackEXT end_transform_feedback = nullptr; std::function graphics_pipeline; // Called during emit when a draw or dispatch whose pipeline has `writes_buffer == true` (or a legacy indirect // command without pipeline metadata) is emitted. Null: nobody is told. @@ -1655,6 +1664,15 @@ struct PreparedDraw { // skip_unresolved in prepare). bool skipped = false; bool sample_masked = false; // true when `pipeline` is a sample_masked twin using graphics->masked_layout (148 B push) + // D3D-302: graphics->so_strides.size() entries when the pipeline declares StreamOutput, else empty. A slot + // with no bound SOSetTargets buffer resolves to VK_NULL_HANDLE, which vkCmdBindTransformFeedbackBuffersEXT + // refuses (VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-parameter), so the draw is unsupported instead. + std::vector so_buffers; + std::vector so_offsets, so_sizes; + // The counter (BufferFilledSizeLocation) for each so_buffers entry, or VK_NULL_HANDLE: Begin starts that + // stream's running count at 0 instead of resuming it, and End does not write one back. + std::vector so_counter_buffers; + std::vector so_counter_offsets; // Back to a new draw's state, keeping the vectors' storage. void reset() { @@ -1680,6 +1698,11 @@ struct PreparedDraw { indirect_count_offset = 0; area = {}; layers = 1; + so_buffers.clear(); + so_offsets.clear(); + so_sizes.clear(); + so_counter_buffers.clear(); + so_counter_offsets.clear(); } }; @@ -3300,6 +3323,45 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R // 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 unresolved_at(__LINE__); + // D3D-302: resolve this draw's bound StreamOutput targets. The pipeline's so_strides.size() names how many + // buffer slots its declaration uses. Assumption, with no device to check it against (docs/d3d12_vulkan.md + // D3D-302): if any of those slots has no SOSetTargets buffer currently bound, stream output stays inactive + // for this draw (an ordinary draw, not a refusal) rather than failing it. + if (!pipeline->so_strides.empty()) { + const std::size_t count = pipeline->so_strides.size(); + std::vector so_buffers(count, VK_NULL_HANDLE); + std::vector so_offsets(count, 0), so_sizes(count, 0); + std::vector so_counters(count, VK_NULL_HANDLE); + std::vector so_counter_offsets(count, 0); + bool all_bound = true; + for (std::size_t slot = 0; slot < count && all_bound; ++slot) { + const bool bound = draw.views && slot < draw.views->so_buffers.size() && draw.views->so_buffers[slot].va; + if (!bound) { + all_bound = false; + break; + } + const SOBufferView& view = draw.views->so_buffers[slot]; + std::uint64_t size = view.size; + if (!vk.buffer_at(view.va, size, so_buffers[slot], so_offsets[slot])) + return ReplayResult::unresolved_resource; + so_sizes[slot] = size; + if (view.filled_size_va) { + // D3D12_STREAM_OUTPUT_BUFFER_VIEW::BufferFilledSizeLocation points to a UINT (32 bits), not a + // UINT64 (BubsMcgee, #1884): a wider span here could make buffer_at refuse a real 4-byte + // counter buffer looking for 4 more bytes than it has. + std::uint64_t counter_size = sizeof(std::uint32_t); + if (!vk.buffer_at(view.filled_size_va, counter_size, so_counters[slot], so_counter_offsets[slot])) + return ReplayResult::unresolved_resource; + } + } + if (all_bound) { + p.so_buffers = std::move(so_buffers); + p.so_offsets = std::move(so_offsets); + p.so_sizes = std::move(so_sizes); + p.so_counter_buffers = std::move(so_counters); + p.so_counter_offsets = std::move(so_counter_offsets); + } + } if (draw.indexed) { if (arguments && (!draw.index.va || (draw.index.format != 57 && draw.index.format != 42) || draw.index.size < (draw.index.format == 57 ? 2u : 4u) || @@ -6108,6 +6170,20 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ cache.bind_vertex_buffer(command_buffer, vk, slot, d.vertex_buffers[slot], d.vertex_offsets[slot], d.vertex_sizes[slot], d.vertex_strides[slot]); } + // D3D-302: active only when every buffer slot the pipeline's StreamOutput declares is currently bound + // (prepare_draw leaves d.so_buffers empty otherwise). Bind must run before Begin, and the pair wraps + // only this draw, every path below (indirect, mesh, quad-list, indexed, plain): the rendering scope can + // stay open across draws, and transform feedback must not be active when it ends or when the next draw + // binds its pipeline (VUID-vkCmdBindPipeline-None-02323). + const bool stream_output = !d.so_buffers.empty() && vk.bind_transform_feedback_buffers && + vk.begin_transform_feedback && vk.end_transform_feedback; + if (stream_output) { + const auto count = std::uint32_t(d.so_buffers.size()); + vk.bind_transform_feedback_buffers(command_buffer, 0, count, d.so_buffers.data(), d.so_offsets.data(), + d.so_sizes.data()); + vk.begin_transform_feedback(command_buffer, 0, count, d.so_counter_buffers.data(), + d.so_counter_offsets.data()); + } if (raster.arguments) { indirect_stats::note(indirect_stats::Event::emitted); const auto& arg = *raster.arguments; @@ -6180,6 +6256,11 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } else { vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); } + if (stream_output) { + const auto count = std::uint32_t(d.so_buffers.size()); + vk.end_transform_feedback(command_buffer, 0, count, d.so_counter_buffers.data(), + d.so_counter_offsets.data()); + } if constexpr (Checkpoints) { if (checkpoints->submission.markers) end_scope(); checkpoints->drawn(command_buffer); diff --git a/runtime/test/d3d12_stream_output_test.cpp b/runtime/test/d3d12_stream_output_test.cpp new file mode 100644 index 0000000000..0390af183d --- /dev/null +++ b/runtime/test/d3d12_stream_output_test.cpp @@ -0,0 +1,207 @@ +// D3D-302: a StreamOutput PSO and SOSetTargets actually capture a draw's vertex output on the Vulkan-backed +// device. vs_stream_output.vert writes the fixed vec4 (1, 2, 3, 4) to an Xfb-decorated output (buffer 0, stride +// 16 bytes); the PSO declares one matching StreamOutput buffer slot. After a 3-vertex draw, the buffer is read +// back and every vertex's 16 bytes are checked against that constant. No game data; needs VK_EXT_transform_feedback. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; + +int main() { + vktest::Device vk; + vk.request_transform_feedback = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(status == vktest::DeviceStatus::ready); + if (!vk.transform_feedback) { + std::fprintf(stderr, "SKIP: no VK_EXT_transform_feedback on this device\n"); + return 77; + } + + // Shader programs and the index that maps their hashes to the compiled test modules (fssm_sha256 is a + // lookup key the test controls on both sides; it has no relation to the real shader bytes). + const auto vs_program = fssm_program({0x56530302u, 0x00000001u}); + const auto ps_program = fssm_program({0x50530302u, 0x00000001u}); + const auto vs_container = shader_container(vs_program); + const auto ps_container = shader_container(ps_program); + const auto fixture = std::filesystem::temp_directory_path() / + ("leonida_stream_output_test_" + std::to_string(GetCurrentProcessId())); + std::filesystem::create_directories(fixture); + std::filesystem::copy_file(LEONIDA_TEST_VS_STREAM_OUTPUT_SPV, fixture / "vs_stream_output.spv", + std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(LEONIDA_TEST_PS_STREAM_OUTPUT_SPV, fixture / "ps_stream_output.spv", + std::filesystem::copy_options::overwrite_existing); + { + std::ofstream index(fixture / "index.json", std::ios::binary); + index << "{\"vs_stream_output\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 0, \"input_signature\": []},\n" + " \"ps_stream_output\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 0, \"outputs\": [0]}}"; + } + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = true; + info.subgroup = vk.subgroup; + info.shader_dir = fixture.string(); + info.transform_feedback = vk.transform_feedback; + info.transform_feedback_geometry_streams = vk.transform_feedback_geometry_streams; + info.max_transform_feedback_buffers = vk.max_transform_feedback_buffers; + info.max_transform_feedback_streams = vk.max_transform_feedback_streams; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + + // Empty root signature: neither shader reads a root parameter. + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {0, nullptr, 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)))); + + constexpr UINT width = 64, height = 64; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = width; + rt_desc.Height = height; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Ref target; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&target.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.p, nullptr, rtv); + + // One StreamOutput buffer slot, stride 16 bytes (one vec4), matching the shader's Xfb decoration. + const UINT stride = 16; + const D3D12_SO_DECLARATION_ENTRY so_entry{0, "OUT", 0, 0, 4, 0}; + 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.StreamOutput.pSODeclaration = &so_entry; + pso_desc.StreamOutput.NumEntries = 1; + pso_desc.StreamOutput.pBufferStrides = &stride; + pso_desc.StreamOutput.NumStrides = 1; + pso_desc.StreamOutput.RasterizedStream = 0; + 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; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pso_desc.SampleDesc.Count = 1; + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + + // The SO buffer (DEFAULT heap, created directly in STREAM_OUT state) and a READBACK copy of it. + constexpr UINT64 so_bytes = 256; + D3D12_RESOURCE_DESC buf_desc{}; + buf_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buf_desc.Width = so_bytes; + buf_desc.Height = 1; + buf_desc.DepthOrArraySize = 1; + buf_desc.MipLevels = 1; + buf_desc.SampleDesc.Count = 1; + buf_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref so_buffer; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &buf_desc, + D3D12_RESOURCE_STATE_STREAM_OUT, nullptr, + IID_PPV_ARGS(&so_buffer.p)))); + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref so_readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buf_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&so_readback.p)))); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + 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)))); + + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(width), LONG(height)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->SetGraphicsRootSignature(root.p); + list->SetPipelineState(pso.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_STREAM_OUTPUT_BUFFER_VIEW so_view{so_buffer->GetGPUVirtualAddress(), so_bytes, 0}; + list->SOSetTargets(0, 1, &so_view); + list->DrawInstanced(3, 1, 0, 0); + const auto to_copy_src = transition(so_buffer.p, D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy_src); + list->CopyBufferRegion(so_readback.p, 0, so_buffer.p, 0, so_bytes); + EXPECT(SUCCEEDED(list->Close())); + + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + const HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(ev != nullptr); + const bool done = SUCCEEDED(fence->SetEventOnCompletion(1, ev)) && WaitForSingleObject(ev, 20000) == WAIT_OBJECT_0; + CloseHandle(ev); + EXPECT(done); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(so_readback->Map(0, nullptr, &mapped)) && mapped); + const auto* floats = static_cast(mapped); + int mismatches = 0; + for (int vertex = 0; vertex < 3; ++vertex) { + const float expected[4] = {1.0f, 2.0f, 3.0f, 4.0f}; + for (int component = 0; component < 4; ++component) { + const float got = floats[vertex * 4 + component]; + if (got != expected[component]) { + std::fprintf(stderr, "vertex %d component %d: got %f, expected %f\n", vertex, component, + double(got), double(expected[component])); + ++mismatches; + } + } + } + const D3D12_RANGE no_write{0, 0}; + so_readback->Unmap(0, &no_write); + EXPECT(mismatches == 0); + + std::printf("stream_output: 3 vertices captured through SOSetTargets + a StreamOutput PSO, %d mismatches\n", + mismatches); + std::filesystem::remove_all(fixture); + return 0; +} diff --git a/runtime/test/glsl/ps_stream_output.frag b/runtime/test/glsl/ps_stream_output.frag new file mode 100644 index 0000000000..761c7f47e0 --- /dev/null +++ b/runtime/test/glsl/ps_stream_output.frag @@ -0,0 +1,9 @@ +#version 460 +// Trivial pixel shader for d3d12_stream_output_test (D3D-302): a render target is still needed so the draw has a +// valid area/layer count to rasterize into, but its colour is never checked. + +layout(location = 0) out vec4 target; + +void main() { + target = vec4(1.0, 0.0, 0.0, 1.0); +} diff --git a/runtime/test/glsl/vs_stream_output.vert b/runtime/test/glsl/vs_stream_output.vert new file mode 100644 index 0000000000..0c80b98c86 --- /dev/null +++ b/runtime/test/glsl/vs_stream_output.vert @@ -0,0 +1,11 @@ +#version 460 +// Minimal vertex shader for d3d12_stream_output_test (D3D-302): writes the fixed vec4 (1, 2, 3, 4) to both its +// Xfb-captured output (buffer 0, offset 0, stride 16 bytes: one vec4) and gl_Position. The rasterized output is +// unused by the test; only the captured buffer's contents, read back after the draw, are checked. + +layout(location = 0, xfb_buffer = 0, xfb_offset = 0, xfb_stride = 16) out vec4 out_val; + +void main() { + out_val = vec4(1.0, 2.0, 3.0, 4.0); + gl_Position = out_val; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 96357d3256..90f58fca38 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -139,6 +139,12 @@ class Device { bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled bool mesh_shader_queries = false; // the meshShaderQueries feature is enabled on the device + // set before create(): enable VK_EXT_transform_feedback (D3D-302) where available + bool request_transform_feedback = false; + bool transform_feedback = false; // VK_EXT_transform_feedback and transformFeedback are enabled + bool transform_feedback_geometry_streams = false; // the geometryStreams feature is enabled on the device + std::uint32_t max_transform_feedback_buffers = 0; // VkPhysicalDeviceTransformFeedbackPropertiesEXT; 0: disabled + std::uint32_t max_transform_feedback_streams = 0; bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. leonida::SubgroupSizeCaps subgroup; @@ -655,6 +661,32 @@ class Device { mesh_features.meshShaderQueries = mesh_shader_queries ? VK_TRUE : VK_FALSE; *v13_.next() = &mesh_features; } + // VK_EXT_transform_feedback (D3D-302), for the tests that ask for it. + VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; + if (request_transform_feedback && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &transform_feedback_features}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE; + transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE; + if (transform_feedback) { + VkPhysicalDeviceTransformFeedbackPropertiesEXT tf_props{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &tf_props}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &props); + max_transform_feedback_buffers = tf_props.maxTransformFeedbackBuffers; + max_transform_feedback_streams = tf_props.maxTransformFeedbackStreams; + } + } + if (transform_feedback) { + transform_feedback_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT, + *v13_.next()}; + transform_feedback_features.transformFeedback = VK_TRUE; + transform_feedback_features.geometryStreams = transform_feedback_geometry_streams ? VK_TRUE : VK_FALSE; + *v13_.next() = &transform_feedback_features; + } enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available enable.pipelineStatisticsQuery = features.features.pipelineStatisticsQuery; occlusion_query_precise = features.features.occlusionQueryPrecise == VK_TRUE; @@ -823,6 +855,7 @@ class Device { return std::strcmp(e.extensionName, VK_AMD_BUFFER_MARKER_EXTENSION_NAME) == 0; }); if (buffer_marker) device_extensions.push_back(VK_AMD_BUFFER_MARKER_EXTENSION_NAME); + if (transform_feedback) device_extensions.push_back(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.data(); result = instance_fn("vkCreateDevice")(physical, &device_info, nullptr, &device); From 79ad1c0e94c6c73ecf6d16c99df1ff4983b25357 Mon Sep 17 00:00:00 2001 From: Miici0 Date: Mon, 30 Nov 2026 14:42:13 +0100 Subject: [PATCH 2/3] d3d12_vulkan_device: give transform-feedback buffers their Vulkan usage bits BubsMcgee's review on #1884: vkCmdBindTransformFeedbackBuffersEXT requires every bound buffer (and the counter buffers Begin/End take) to have been created with VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT and VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT (VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-02360). NVIDIA does not enforce this, so the test passed on the 4070 SUPER without it; stricter drivers (and the Khronos validation layer) catch it. Added at the six buffer creation sites that gate VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT the same way, behind the matching transform_feedback flag. Co-Authored-By: Claude Sonnet 5 --- runtime/shims/d3d12_vulkan_device.cpp | 33 ++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 3e0b62bb85..f1b8c50132 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6087,6 +6087,12 @@ struct DeviceState { VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + // D3D-302 (BubsMcgee): a buffer bound to vkCmdBindTransformFeedbackBuffersEXT or passed as a counter + // buffer must have been created with these usage bits (VUID-vkCmdBindTransformFeedbackBuffersEXT- + // pBuffers-02360); NVIDIA does not enforce it, stricter drivers do. + if (info.transform_feedback) + result.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT | + VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT; // D3D12 reserved buffers are visible to DIRECT, COPY and COMPUTE queues without exposing Vulkan // queue-family ownership. Their tile bindings and accesses may use distinct families, so match the // CONCURRENT sharing policy used for ordinary buffers and the GPU address arena. @@ -10259,6 +10265,9 @@ struct DeviceState { create.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + if (info.transform_feedback) + create.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT | + VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT; share(create); if (vk.vkCreateBuffer(info.device, &create, nullptr, &heap.buffer) != VK_SUCCESS) return false; const auto fail = [&] { @@ -14664,6 +14673,12 @@ class Resource final VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + // D3D-302 (BubsMcgee): a resource bound through SOSetTargets, or as its counter, needs these usage bits + // at creation (VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-02360); not enforced on NVIDIA, is on + // stricter drivers. + if (device_.info.transform_feedback) + info.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT | + VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT; if (addressable || need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (device_.info.ray_tracing) { info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | @@ -14816,6 +14831,12 @@ class Resource final VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + // D3D-302 (BubsMcgee): a resource bound through SOSetTargets, or as its counter, needs these usage bits + // at creation (VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-02360); not enforced on NVIDIA, is on + // stricter drivers. + if (device_.info.transform_feedback) + info.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT | + VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT; if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; @@ -15019,6 +15040,12 @@ class Resource final VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + // D3D-302 (BubsMcgee): a resource bound through SOSetTargets, or as its counter, needs these usage bits + // at creation (VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-02360); not enforced on NVIDIA, is on + // stricter drivers. + if (device_.info.transform_feedback) + info.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT | + VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT; if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; @@ -22941,8 +22968,12 @@ class Device final VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - // Default-heap buffers live here, and any of them can be a SetPredication buffer. + // Default-heap buffers live here, and any of them can be a SetPredication buffer or a SOSetTargets + // buffer/counter (D3D-302, BubsMcgee): both need their own usage bit at creation. if (state_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (state_.info.transform_feedback) + info.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT | + VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT; // With ray tracing, AS result, scratch and build-input buffers are default-heap ranges of the arena. if (state_.info.ray_tracing) info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | From 6de8bf43b939fcd64e41929926339376472dbbd1 Mon Sep 17 00:00:00 2001 From: Miici0 Date: Mon, 30 Nov 2026 16:11:44 +0100 Subject: [PATCH 3/3] d3d12_stream_output_test: exercise the BufferFilledSize counter, fail on validation errors BubsMcgee's review on #1884: the test passed BufferFilledSizeLocation = 0, so the counter path was never exercised. A second draw now captures through a zeroed 4-byte counter (a D3D12 UINT); both buffers must hold the 3 vertices and the counter must read the bytes written. It reads 48 (3 x 16) on an RTX 4070 SUPER, so the position Vulkan's counter buffer records is the same quantity as D3D12's filled size, in bytes, and binding BufferFilledSizeLocation as the Vulkan counter needs no conversion. The test also fails on any validation error when run with LEONIDA_VK_VALIDATION=1, as in BubsMcgee's fixed branch. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_stream_output_test.cpp | 106 +++++++++++++++++----- 1 file changed, 85 insertions(+), 21 deletions(-) diff --git a/runtime/test/d3d12_stream_output_test.cpp b/runtime/test/d3d12_stream_output_test.cpp index 0390af183d..883c7c82fc 100644 --- a/runtime/test/d3d12_stream_output_test.cpp +++ b/runtime/test/d3d12_stream_output_test.cpp @@ -1,7 +1,9 @@ // D3D-302: a StreamOutput PSO and SOSetTargets actually capture a draw's vertex output on the Vulkan-backed // device. vs_stream_output.vert writes the fixed vec4 (1, 2, 3, 4) to an Xfb-decorated output (buffer 0, stride -// 16 bytes); the PSO declares one matching StreamOutput buffer slot. After a 3-vertex draw, the buffer is read -// back and every vertex's 16 bytes are checked against that constant. No game data; needs VK_EXT_transform_feedback. +// 16 bytes); the PSO declares one matching StreamOutput buffer slot. Two 3-vertex draws: one with no +// BufferFilledSizeLocation, one with a zeroed 4-byte counter. Both buffers are read back and every vertex's 16 bytes +// checked against that constant, and the counter must hold the bytes written. Run with LEONIDA_VK_VALIDATION=1 the +// test also fails on any validation error. No game data; needs VK_EXT_transform_feedback. #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -145,6 +147,35 @@ int main() { D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&so_readback.p)))); + // The second draw's SO buffer and its BufferFilledSizeLocation: a 4-byte counter (a D3D12 UINT), zeroed by a + // copy before the draw because vkCmdBeginTransformFeedbackEXT resumes from the value it holds. + Ref counted_buffer, counted_readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &buf_desc, + D3D12_RESOURCE_STATE_STREAM_OUT, nullptr, + IID_PPV_ARGS(&counted_buffer.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buf_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&counted_readback.p)))); + D3D12_RESOURCE_DESC counter_desc = buf_desc; + counter_desc.Width = sizeof(std::uint32_t); + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + Ref counter, counter_zero, counter_readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &counter_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&counter.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &counter_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&counter_zero.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &counter_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&counter_readback.p)))); + { + void* zero = nullptr; + EXPECT(SUCCEEDED(counter_zero->Map(0, nullptr, &zero)) && zero); + std::memset(zero, 0, sizeof(std::uint32_t)); + counter_zero->Unmap(0, nullptr); + } + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; Ref queue; Ref allocator; @@ -156,6 +187,10 @@ int main() { IID_PPV_ARGS(&list.p)))); EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + list->CopyBufferRegion(counter.p, 0, counter_zero.p, 0, sizeof(std::uint32_t)); + const auto counter_to_so = transition(counter.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_STREAM_OUT); + list->ResourceBarrier(1, &counter_to_so); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1}; const D3D12_RECT scissor{0, 0, LONG(width), LONG(height)}; @@ -167,9 +202,18 @@ int main() { const D3D12_STREAM_OUTPUT_BUFFER_VIEW so_view{so_buffer->GetGPUVirtualAddress(), so_bytes, 0}; list->SOSetTargets(0, 1, &so_view); list->DrawInstanced(3, 1, 0, 0); - const auto to_copy_src = transition(so_buffer.p, D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_copy_src); + const D3D12_STREAM_OUTPUT_BUFFER_VIEW counted_view{counted_buffer->GetGPUVirtualAddress(), so_bytes, + counter->GetGPUVirtualAddress()}; + list->SOSetTargets(0, 1, &counted_view); + list->DrawInstanced(3, 1, 0, 0); + const D3D12_RESOURCE_BARRIER to_copy_src[] = { + transition(so_buffer.p, D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(counted_buffer.p, D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(counter.p, D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + list->ResourceBarrier(UINT(std::size(to_copy_src)), to_copy_src); list->CopyBufferRegion(so_readback.p, 0, so_buffer.p, 0, so_bytes); + list->CopyBufferRegion(counted_readback.p, 0, counted_buffer.p, 0, so_bytes); + list->CopyBufferRegion(counter_readback.p, 0, counter.p, 0, sizeof(std::uint32_t)); EXPECT(SUCCEEDED(list->Close())); ID3D12CommandList* lists[] = {list.p}; @@ -181,27 +225,47 @@ int main() { CloseHandle(ev); EXPECT(done); - void* mapped = nullptr; - EXPECT(SUCCEEDED(so_readback->Map(0, nullptr, &mapped)) && mapped); - const auto* floats = static_cast(mapped); - int mismatches = 0; - for (int vertex = 0; vertex < 3; ++vertex) { - const float expected[4] = {1.0f, 2.0f, 3.0f, 4.0f}; - for (int component = 0; component < 4; ++component) { - const float got = floats[vertex * 4 + component]; - if (got != expected[component]) { - std::fprintf(stderr, "vertex %d component %d: got %f, expected %f\n", vertex, component, - double(got), double(expected[component])); - ++mismatches; + const D3D12_RANGE no_write{0, 0}; + // Mismatched components of the 3 captured vertices against the shader's constant (1, 2, 3, 4); -1: no map. + const auto mismatches = [&](ID3D12Resource* readback, const char* label) { + void* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, &mapped)) || !mapped) return -1; + const auto* floats = static_cast(mapped); + int count = 0; + for (int vertex = 0; vertex < 3; ++vertex) { + const float expected[4] = {1.0f, 2.0f, 3.0f, 4.0f}; + for (int component = 0; component < 4; ++component) { + const float got = floats[vertex * 4 + component]; + if (got != expected[component]) { + std::fprintf(stderr, "%s: vertex %d component %d: got %f, expected %f\n", label, vertex, + component, double(got), double(expected[component])); + ++count; + } } } + readback->Unmap(0, &no_write); + return count; + }; + EXPECT(mismatches(so_readback.p, "no counter") == 0); + EXPECT(mismatches(counted_readback.p, "counter") == 0); + + // D3D12's filled size is in bytes; the value Vulkan's counter buffer records must be the same quantity. + std::uint32_t filled = 0; + { + void* mapped = nullptr; + EXPECT(SUCCEEDED(counter_readback->Map(0, nullptr, &mapped)) && mapped); + std::memcpy(&filled, mapped, sizeof(filled)); + counter_readback->Unmap(0, &no_write); } - const D3D12_RANGE no_write{0, 0}; - so_readback->Unmap(0, &no_write); - EXPECT(mismatches == 0); + if (filled != 3 * stride) std::fprintf(stderr, "BufferFilledSize: got %u, expected %u\n", filled, 3 * stride); + EXPECT(filled == 3 * stride); - std::printf("stream_output: 3 vertices captured through SOSetTargets + a StreamOutput PSO, %d mismatches\n", - mismatches); + if (vk.validation_errors()) { + std::fprintf(stderr, "%u Vulkan validation errors\n", vk.validation_errors()); + return 1; + } + std::printf("stream_output: 3 vertices captured with and without a BufferFilledSize counter (%u bytes), " + "0 mismatches\n", filled); std::filesystem::remove_all(fixture); return 0; }