From c99f26559a4cca1866da4891a3cfb27cd5236c3e Mon Sep 17 00:00:00 2001 From: Miici0 Date: Tue, 24 Nov 2026 21:40:33 +0100 Subject: [PATCH 1/3] d3d12_vulkan_device: detect and enable VK_EXT_transform_feedback Foundation for D3D-302 (stream output): read the physical device's transformFeedback/geometryStreams features where the extension is present, record them on VulkanDeviceInfo, and enable them on the logical device when supported, exactly the same pattern the existing VK_EXT_mesh_shader detection/enable code already follows. Device-capability plumbing only: no behaviour changes yet. A graphics PSO declaring StreamOutput is still refused and SOSetTargets is still not implemented, same as before this commit. Confirmed VK_EXT_transform_feedback is available (4 streams, 4 buffers) on an NVIDIA GeForce RTX 4070 SUPER, driver 621.24. Co-Authored-By: Claude Sonnet 5 --- runtime/shims/d3d12_com.h | 7 +++++++ runtime/shims/d3d12_vulkan_device.cpp | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index c0ff3cf8da..b320fb88c9 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -178,6 +178,13 @@ struct VulkanDeviceInfo { // VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so the clipping invocations of a mesh // segment come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Without it they read 0. bool mesh_shader_queries = false; + // VK_EXT_transform_feedback with its transformFeedback feature is enabled on `device` (D3D-302): a graphics PSO + // that declares StreamOutput is accepted, SOSetTargets binds real buffers, and draws between them are captured + // with vkCmdBeginTransformFeedbackEXT/EndTransformFeedbackEXT. Without it, StreamOutput PSOs stay refused. + bool transform_feedback = false; + // VK_EXT_transform_feedback's geometryStreams feature is enabled: a StreamOutput RasterizedStream other than the + // vertex/geometry shader's stream 0 can be rasterized. Without it, only RasterizedStream 0 is accepted. + bool transform_feedback_geometry_streams = false; // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, // depthBiasClamp or dualSrcBlend are refused unless it is set here. VkPhysicalDeviceFeatures features{}; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 97ed334a11..b7fc1dfa0a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -9476,6 +9476,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; + VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; { std::uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); @@ -9500,10 +9502,19 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin vkGetPhysicalDeviceFeatures2(info.physical, &features); info.mesh_shader = mesh_features.meshShader == VK_TRUE; info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; + } else if (!std::strcmp(e.extensionName, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, + &transform_feedback_features}; + vkGetPhysicalDeviceFeatures2(info.physical, &features); + info.transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE; + info.transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE; } } if (!info.mesh_shader) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); + if (!info.transform_feedback) + std::fprintf(stderr, + "[rt] d3d12: the GPU has no VK_EXT_transform_feedback: StreamOutput PSOs are unsupported\n"); if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { as_features.pNext = &rq_features; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; @@ -9539,11 +9550,22 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; + // D3D-302: StreamOutput PSOs, SOSetTargets and real SO_STATISTICS queries need transformFeedback; geometryStreams + // is only requested when the device already offers it (RasterizedStream != 0 is the one thing it gates). + VkPhysicalDeviceTransformFeedbackFeaturesEXT enable_transform_feedback{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; + enable_transform_feedback.transformFeedback = VK_TRUE; + enable_transform_feedback.geometryStreams = info.transform_feedback_geometry_streams ? VK_TRUE : VK_FALSE; + void* ext_chain = nullptr; if (info.mesh_shader) { enable_mesh.pNext = ext_chain; ext_chain = &enable_mesh; } + if (info.transform_feedback) { + enable_transform_feedback.pNext = ext_chain; + ext_chain = &enable_transform_feedback; + } if (info.ray_tracing) { enable_rq.pNext = ext_chain; enable_as.pNext = &enable_rq; @@ -9932,6 +9954,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); + if (info.transform_feedback) device_extensions.push_back(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME); if (info.ray_tracing) { device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); From 9fc0789e2e6ec165eae3cff1ab0be7da633e9890 Mon Sep 17 00:00:00 2001 From: Miici0 Date: Wed, 25 Nov 2026 14:43:00 +0100 Subject: [PATCH 2/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 ### Tested 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 | 5 + runtime/shims/d3d12_vulkan_device.cpp | 43 ++++- runtime/src/command_list.h | 9 + runtime/src/vulkan_backend.h | 7 +- runtime/src/vulkan_replay.h | 76 ++++++++ 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, 447 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 3b334c7133..8f8171a721 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2887,6 +2887,33 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_pso_validation COMMAND d3d12_pso_validation_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 4f4904e965..1c1f2f684d 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -399,6 +399,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; @@ -1263,6 +1279,7 @@ class GraphicsCommandList final D3D12_GPU_VIRTUAL_ADDRESS sampler_base_ = 0; std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; + std::array so_buffers_{}; leonida::IndexBufferView index_{}; leonida::Viewport viewport_{}; leonida::Rect scissor_{}; @@ -1365,6 +1382,7 @@ class GraphicsCommandList final sampler_base_ = 0; topology_ = 0; vertex_buffers_ = {}; + so_buffers_ = {}; index_ = {}; viewport_ = {}; scissor_ = {}; @@ -1384,6 +1402,14 @@ class GraphicsCommandList final : leonida::VertexBufferView{}; } + 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) { index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} : leonida::IndexBufferView{}; @@ -1401,6 +1427,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 b320fb88c9..5320283434 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -185,6 +185,11 @@ struct VulkanDeviceInfo { // VK_EXT_transform_feedback's geometryStreams feature is enabled: a StreamOutput RasterizedStream other than the // vertex/geometry shader's stream 0 can be rasterized. Without it, only RasterizedStream 0 is accepted. bool transform_feedback_geometry_streams = 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; + std::uint32_t max_transform_feedback_streams = 0; // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, // depthBiasClamp or dualSrcBlend are refused unless it is set here. VkPhysicalDeviceFeatures features{}; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index b7fc1dfa0a..cd5a7d613d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3448,10 +3448,28 @@ 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) { - log_once("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); + if (desc.HS.BytecodeLength || desc.DS.BytecodeLength) { + log_once("graphics pipeline stage not supported yet (hull/domain):", 0); return E_NOTIMPL; } + // 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 // be its input primitive, as D3D12 requires. @@ -3936,6 +3954,9 @@ class PipelineState final // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; + 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); @@ -4943,10 +4964,12 @@ class QueryHeap final info.queryType = VK_QUERY_TYPE_TIMESTAMP; break; case h::so_statistics: - // The layer has no stream output: a graphics PSO with StreamOutput entries is refused (E_NOTIMPL) and - // SOSetTargets is not implemented, so no primitive ever reaches a stream and every query of this heap - // counts 0 written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills zeros. When stream - // output lands, this becomes a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool (D3D-302). + // D3D-302: StreamOutput PSOs and SOSetTargets now capture real primitives (prepare_draw, + // vulkan_replay.h), but this heap's counters are not wired to that yet: every query still counts 0 + // written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills + // zeros. Follow-up: a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool with the indexed + // vkCmdBeginQueryIndexedEXT/EndQueryIndexedEXT commands, read back through the counter buffers + // SOSetTargets' BufferFilledSizeLocation already resolves. return register_pool(desc); case h::pipeline_statistics: if (!device_.info.pipeline_statistics_query) { @@ -9508,6 +9531,14 @@ 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; + if (info.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}; + vkGetPhysicalDeviceProperties2(info.physical, &props); + info.max_transform_feedback_buffers = tf_props.maxTransformFeedbackBuffers; + info.max_transform_feedback_streams = tf_props.maxTransformFeedbackStreams; + } } } if (!info.mesh_shader) diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7c5c09e0ac..c87ddcf1c2 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -405,12 +405,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 a959942561..f98ad54bf3 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -107,7 +107,8 @@ struct VulkanDeviceFunctions { X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ - X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) + X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) X(vkCmdBindTransformFeedbackBuffersEXT) \ + X(vkCmdBeginTransformFeedbackEXT) X(vkCmdEndTransformFeedbackEXT) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER @@ -994,6 +995,10 @@ class VulkanContext { replay_.draw = vk.vkCmdDraw; replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled 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 d5a73b909d..d9b713ebae 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -779,6 +779,11 @@ struct GraphicsPipeline { static constexpr std::uint32_t unbound_depth = 1u << 8; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + // 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. @@ -861,6 +866,10 @@ struct ReplayFunctions { PFN_vkCmdDraw draw = nullptr; PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported 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; // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all @@ -1076,6 +1085,15 @@ struct PreparedDraw { VkIndexType index_type = VK_INDEX_TYPE_UINT16; VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has + // 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() { @@ -1092,6 +1110,11 @@ struct PreparedDraw { index_type = VK_INDEX_TYPE_UINT16; area = {}; layers = 1; + so_buffers.clear(); + so_offsets.clear(); + so_sizes.clear(); + so_counter_buffers.clear(); + so_counter_offsets.clear(); } }; @@ -2224,6 +2247,42 @@ 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; } + // 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) { + std::uint64_t counter_size = sizeof(std::uint64_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 (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -4272,6 +4331,18 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_vertex_buffers2(command_buffer, slot, 1, &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 both must be + // inside the render pass this draw is already in (VUID-vkCmdBeginTransformFeedbackEXT-None-02365). + 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 (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->indexed) { @@ -4281,6 +4352,11 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } 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()); + } vk.end_rendering(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 678d369e28..1e01945df4 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -119,6 +119,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; @@ -533,6 +539,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; @@ -610,6 +642,7 @@ class Device { #endif if (custom_border_color) device_extensions.push_back(custom_border_color_name); if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_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 e045ccce33116f138137b2a15c916c581fd6ea33 Mon Sep 17 00:00:00 2001 From: Miici0 Date: Wed, 25 Nov 2026 16:06:15 +0100 Subject: [PATCH 3/3] d3d12: support StreamOutput RasterizedStream other than 0 (D3D-302) Builds on D3D-STREAMOUTPUT-RUNTIME (#1884), which refused any RasterizedStream other than 0. Two more cases now work: - D3D12_SO_NO_RASTERIZED_STREAM (no stream reaches the rasterizer): rasterizerDiscardEnable on the pipeline's rasterization state. Needs no extra Vulkan feature; still captures everything via transform feedback. - An explicit non-default stream index: VkPipelineRasterizationStateStream- CreateInfoEXT chained into the rasterization state, gated on the geometryStreams feature (detected/enabled by #1236) and the index being below the device's maxTransformFeedbackStreams. The pipeline-creation refusal and the Recipe/build() rasterization-state wiring are both updated; replay is unaffected (capture is per XFB buffer slot, not per rasterized stream). ### Tested d3d12_stream_output_test.cpp now runs its capture check twice: once at RasterizedStream 0 (as before) and once at D3D12_SO_NO_RASTERIZED_STREAM. Both capture all 3 vertices correctly, 0 mismatches, on real hardware. (An explicit non-zero stream index needs a multi-stream geometry shader to exercise meaningfully, which this PR does not add; the code path is implemented per the Vulkan spec but not independently tested here.) Full ctest (runtime/build, RelWithDebInfo): same pattern as #1884, only the pre-existing d3d12_execute_indirect_validation failure (#1066, unrelated). No regressions. GPU: NVIDIA GeForce RTX 4070 SUPER, driver 621.24, Windows 11 26300.9974. Co-Authored-By: Claude Sonnet 5 --- runtime/shims/d3d12_vulkan_device.cpp | 34 +++- runtime/src/vulkan_replay.h | 9 +- runtime/test/d3d12_stream_output_test.cpp | 225 ++++++++++++---------- 3 files changed, 159 insertions(+), 109 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index cd5a7d613d..bbe4caefe0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3465,9 +3465,17 @@ class PipelineState final 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; + // D3D12_SO_NO_RASTERIZED_STREAM (no stream is rasterized) needs only rasterizerDiscardEnable, always + // available. A real, non-default stream index needs picking which stream the rasterizer reads + // (VkPipelineRasterizationStateStreamCreateInfoEXT), which needs the geometryStreams feature. + if (stream_output_desc.RasterizedStream != 0 && + stream_output_desc.RasterizedStream != D3D12_SO_NO_RASTERIZED_STREAM) { + if (stream_output_desc.RasterizedStream >= device_.info.max_transform_feedback_streams) + return E_INVALIDARG; + if (!device_.info.transform_feedback_geometry_streams) { + log_once("a non-zero RasterizedStream needs the Vulkan geometryStreams feature; stage", 1); + return E_NOTIMPL; + } } } // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes @@ -3954,9 +3962,11 @@ class PipelineState final // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; - if (stream_output) + if (stream_output) { graphics_.so_strides.assign(stream_output_desc.pBufferStrides, stream_output_desc.pBufferStrides + stream_output_desc.NumStrides); + recipe_.so_rasterized_stream = stream_output_desc.RasterizedStream; + } recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); @@ -4115,6 +4125,10 @@ class PipelineState final VkPipelineInputAssemblyStateCreateInfo assembly{}; VkPipelineRasterizationStateCreateInfo raster{}; bool conservative = false; + // D3D12_STREAM_OUTPUT_DESC::RasterizedStream (D3D-302): 0 (the default, needs nothing extra here), + // D3D12_SO_NO_RASTERIZED_STREAM (rasterizerDiscardEnable), or a real stream index + // (VkPipelineRasterizationStateStreamCreateInfoEXT, needs geometryStreams). + std::uint32_t so_rasterized_stream = 0; VkPipelineMultisampleStateCreateInfo multisample{}; VkSampleMask sample_mask = ~0u; VkPipelineDepthStencilStateCreateInfo depth{}; @@ -4170,6 +4184,18 @@ class PipelineState final conservative.pNext = raster.pNext; raster.pNext = &conservative; } + // D3D-302: D3D12_SO_NO_RASTERIZED_STREAM (no stream reaches the rasterizer) is rasterizerDiscardEnable; a + // real non-zero stream picks which one does (create_graphics already refused this device_.info without + // geometryStreams). + VkPipelineRasterizationStateStreamCreateInfoEXT raster_stream{ + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT}; + if (r.so_rasterized_stream == D3D12_SO_NO_RASTERIZED_STREAM) { + raster.rasterizerDiscardEnable = VK_TRUE; + } else if (r.so_rasterized_stream != 0) { + raster_stream.rasterizationStream = r.so_rasterized_stream; + raster_stream.pNext = raster.pNext; + raster.pNext = &raster_stream; + } multisample.pSampleMask = &r.sample_mask; VkPipelineColorBlendStateCreateInfo blend = r.blend; blend.attachmentCount = std::uint32_t(r.blends.size()); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index d9b713ebae..a2304828d0 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -779,10 +779,11 @@ struct GraphicsPipeline { static constexpr std::uint32_t unbound_depth = 1u << 8; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count - // 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 + // D3D12_STREAM_OUTPUT_DESC buffer strides, kept to capture and wrap draws with this pipeline bound (D3D-302). + // Empty: the PSO declared no StreamOutput, same as before this was tracked at all. RasterizedStream only + // matters at pipeline creation (which stream the rasterizer reads, Device::build's so_rasterized_stream); a + // draw's capture itself is per XFB buffer slot and does not depend on it. + std::vector so_strides; // by buffer slot, NumStrides entries bool has_stream_output() const { return !so_strides.empty(); } }; diff --git a/runtime/test/d3d12_stream_output_test.cpp b/runtime/test/d3d12_stream_output_test.cpp index 0390af183d..f485867d64 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. +// back and every vertex's 16 bytes are checked against that constant, for RasterizedStream 0 (the ordinary case) +// and D3D12_SO_NO_RASTERIZED_STREAM (capture-only, rasterizerDiscardEnable): both must still capture correctly. +// No game data; needs VK_EXT_transform_feedback. #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -16,9 +18,123 @@ #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ } while (0) +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) using namespace d3d12test; +namespace { + +// Builds a StreamOutput PSO with the given RasterizedStream, draws 3 vertices through it, and checks that the +// buffer SOSetTargets bound captured 3 copies of vs_stream_output.vert's fixed vec4 (1, 2, 3, 4). +bool run_case(ID3D12Device* device, ID3D12RootSignature* root, D3D12_CPU_DESCRIPTOR_HANDLE rtv, + const std::vector& vs_container, const std::vector& ps_container, + UINT width, UINT height, UINT rasterized_stream, const char* label) { + 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; + 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 = rasterized_stream; + 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; + CHECK(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; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + 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; + CHECK(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; + CHECK(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; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + CHECK(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); + 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); + CHECK(SUCCEEDED(list->Close())); + + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + const HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CHECK(ev != nullptr); + const bool done = SUCCEEDED(fence->SetEventOnCompletion(1, ev)) && WaitForSingleObject(ev, 20000) == WAIT_OBJECT_0; + CloseHandle(ev); + CHECK(done); + + void* mapped = nullptr; + CHECK(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, "%s: vertex %d component %d: got %f, expected %f\n", label, vertex, component, + double(got), double(expected[component])); + ++mismatches; + } + } + } + const D3D12_RANGE no_write{0, 0}; + so_readback->Unmap(0, &no_write); + CHECK(mismatches == 0); + std::printf("stream_output %s: 3 vertices captured, %d mismatches\n", label, mismatches); + return true; +} + +} // namespace + int main() { vktest::Device vk; vk.request_transform_feedback = true; @@ -101,107 +217,14 @@ int main() { 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); + // RasterizedStream 0: the ordinary case (also exercised by d3d12_m2_textured_test-style draws elsewhere, but + // not with StreamOutput). + EXPECT(run_case(device.p, root.p, rtv, vs_container, ps_container, width, height, 0, "RasterizedStream=0")); + // D3D12_SO_NO_RASTERIZED_STREAM: capture-only (rasterizerDiscardEnable). Must still capture every vertex; + // only the (unchecked) render target's contents should differ. + EXPECT(run_case(device.p, root.p, rtv, vs_container, ps_container, width, height, + D3D12_SO_NO_RASTERIZED_STREAM, "NO_RASTERIZED_STREAM")); - std::printf("stream_output: 3 vertices captured through SOSetTargets + a StreamOutput PSO, %d mismatches\n", - mismatches); std::filesystem::remove_all(fixture); return 0; }