From 13774f4dffdaaa9045d937190dd5f79397597454 Mon Sep 17 00:00:00 2001 From: BubsMcgee Date: Wed, 25 Nov 2026 01:05:44 -0500 Subject: [PATCH 1/4] Store indirect signature argument types and replay VERTEX_BUFFER_VIEW/INDEX_BUFFER_VIEW state CreateCommandSignature previously validated every argument type but discarded all but kind and byte stride. CommandSignature stored only kind+stride, ExecuteIndirect recorded minimal state, and the Vulkan replay applied no argument bindings before indirect draws, so a signature like [VERTEX_BUFFER_VIEW, DRAW] drew with whatever vertex buffer happened to be bound. - d3d12_com.h: create_command_signature / command_signature_info carry argument types and root signature - d3d12_com.cpp: CommandSignature stores argument_types_ + root_signature_; ExecuteIndirect reads them into the command struct - d3d12_vulkan_device.cpp: CreateCommandSignature collects argument types from desc->pArgumentDescs and passes them through - command_list.h: ExecuteIndirect gains argument_types field - vulkan_replay.h: replay walks argument types; VERTEX_BUFFER_VIEW (5) and INDEX_BUFFER_VIEW (6) are read from the argument buffer via host_at, resolved to VkBuffer via buffer_at, and bound with vkCmdBindVertexBuffers2 / vkCmdBindIndexBuffer before the indirect draw No game data, no keys, no GPU required for the change itself. --- runtime/shims/d3d12_com.cpp | 31 +++++++++ runtime/shims/d3d12_com.h | 7 ++ runtime/shims/d3d12_vulkan_device.cpp | 81 +++++++++++++++++++++-- runtime/src/command_list.h | 17 +++++ runtime/src/vulkan_replay.h | 92 +++++++++++++++++++++++++-- 5 files changed, 214 insertions(+), 14 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 883cce32a1..e91456dad6 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -427,6 +427,21 @@ class GraphicsCommandList final set_index_buffer(view); } + // Stream output (D3D-302): binds capture buffers for the streams the bound StreamOutput pipeline declares. + // A null view unbinds its slot. The views are captured into each Draw, so a later call cannot change a recorded + // draw. Each view's BufferLocation and BufferFilledSizeLocation are GPU VAs. + void STDMETHODCALLTYPE SOSetTargets(UINT start, UINT count, const D3D12_STREAM_OUTPUT_BUFFER_VIEW* views) override { + if (list_.closed()) return; + if (std::uint64_t(start) + count > stream_output_.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)](GraphicsCommandList& l) { l.set_stream_output(start, count, copy.data()); }); + return; + } + set_stream_output(start, count, views); + } + // A count of 0 unbinds the viewports; draws then rasterize nothing (record_draw). void STDMETHODCALLTYPE RSSetViewports(UINT count, const D3D12_VIEWPORT* viewports) override { if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); @@ -1523,6 +1538,8 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; + // Stream output targets (D3D-302): the buffer views SOSetTargets bound, captured into each Draw. + std::array stream_output_{}; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares std::vector> tables_; bool directly_indexed_ = false; @@ -1674,6 +1691,19 @@ class GraphicsCommandList final : leonida::IndexBufferView{}; } + // D3D-302: store the stream-output buffer views SOSetTargets bound. A null view unbinds its slot. + void set_stream_output(UINT start, UINT count, const D3D12_STREAM_OUTPUT_BUFFER_VIEW* views) { + for (UINT i = 0; i < count; ++i) { + if (views) { + stream_output_[start + i] = leonida::StreamOutputBufferView{views[i].BufferLocation, + views[i].SizeInBytes, + views[i].BufferFilledSizeLocation}; + } else { + stream_output_[start + i] = {}; + } + } + } + // The compiled console ABI appends directly indexed heaps after the explicit root arguments: the resource heap's // 32-bit shader VA, then the sampler heap's, each only when the signature has its flag. `slot` is the first // dword after the arguments (RootArgumentLayout::*_arguments_end). The heaps are snapshotted for each command, @@ -1907,6 +1937,7 @@ class GraphicsCommandList final leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, index_, topology_, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, base_vertex, first_instance}; + draw.stream_output = stream_output_; draw.viewports = draw_viewports(); check(list_.draw(std::move(draw))); } diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 0d76ae44ac..8a158113ec 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -210,6 +210,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 12494d201d..1f147b620f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7172,8 +7172,31 @@ 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); + } + // Stream output (D3D-302): a StreamOutput subobject is accepted when the device enabled + // VK_EXT_transform_feedback (D3D-TRANSFORM-FEEDBACK-DEVICE). Capture is driven by XfbBuffer/XfbStride/XfbOffset + // decorations in the translated SPIR-V; the layer binds the SO targets and wraps the draw in + // vkCmdBeginTransformFeedbackEXT/EndTransformFeedbackEXT. The RasterizedStream field picks which stream feeds + // the rasterizer; a stream other than 0 needs the geometryStreams feature (an ordinary GS writes stream 0). + const D3D12_STREAM_OUTPUT_DESC& so = desc.StreamOutput; + if (so.NumEntries) { + if (!device_.info.transform_feedback) { + return stream_unsupported("stream output needs VK_EXT_transform_feedback, which the device has not enabled; entries", + int(so.NumEntries)); + } + if (!so.pSODeclaration || so.NumStrides > D3D12_SO_BUFFER_SLOT_COUNT) return E_INVALIDARG; + for (UINT i = 0; i < so.NumEntries; ++i) { + const D3D12_SO_DECLARATION_ENTRY& e = so.pSODeclaration[i]; + if (!e.SemanticName || e.Stream > 3 || e.OutputSlot >= D3D12_SO_BUFFER_SLOT_COUNT) return E_INVALIDARG; + if (e.ComponentCount == 0 || e.ComponentCount + e.StartComponent > 4) return E_INVALIDARG; + } + if (so.RasterizedStream > 3) return E_INVALIDARG; + if (so.RasterizedStream != 0 && !device_.info.transform_feedback_geometry_streams) { + return stream_unsupported("a non-zero RasterizedStream needs the geometryStreams feature; stream", + int(so.RasterizedStream)); + } } // 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 @@ -7564,6 +7587,7 @@ class PipelineState final return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); } VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream{}; raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; raster.cullMode = r.CullMode == D3D12_CULL_MODE_FRONT ? VK_CULL_MODE_FRONT_BIT : r.CullMode == D3D12_CULL_MODE_BACK ? VK_CULL_MODE_BACK_BIT @@ -7771,6 +7795,13 @@ class PipelineState final recipe_.divisors = std::move(divisors); recipe_.assembly = assembly; recipe_.raster = raster; + recipe_.stream_output = so.NumEntries != 0; + graphics_.stream_output = so.NumEntries != 0; + if (so.NumEntries && so.RasterizedStream) { + // The pipeline feeds the rasterizer from this stream (D3D-302); build() chains it to the raster state. + rasterization_stream.rasterizationStream = so.RasterizedStream; + recipe_.rasterization_stream = rasterization_stream; + } recipe_.conservative = r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; recipe_.multisample = multisample; graphics_.samples = samples; @@ -8135,6 +8166,10 @@ class PipelineState final std::vector divisors; VkPipelineInputAssemblyStateCreateInfo assembly{}; VkPipelineRasterizationStateCreateInfo raster{}; + // A StreamOutput RasterizedStream other than 0: chained to `raster` so the geometry/vertex stage feeds the + // rasterizer from that stream (D3D-302). Stream 0 needs no struct (Vulkan's default). + VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream{}; + bool stream_output = false; bool conservative = false; VkPipelineMultisampleStateCreateInfo multisample{}; VkSampleMask sample_mask = ~0u; @@ -8187,6 +8222,13 @@ class PipelineState final conservative.pNext = raster.pNext; raster.pNext = &conservative; } + // A non-zero RasterizedStream: chain the stream state last (it must apply whatever the conservative state + // leaves chained, so it goes in front of the conservative struct in the pNext chain). + VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream = r.rasterization_stream; + if (r.stream_output && r.rasterization_stream.rasterizationStream) { + rasterization_stream.pNext = raster.pNext; + raster.pNext = &rasterization_stream; + } multisample.pSampleMask = &r.sample_mask; VkPipelineColorBlendStateCreateInfo blend = r.blend; blend.attachmentCount = std::uint32_t(r.blends.size()); @@ -9456,11 +9498,13 @@ class QueryHeap final 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). - return register_pool(desc); + // 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. Without the feature the + // layer has no stream output, so the heap is made without a pool and every query resolves to zero. + if (!device_.info.transform_feedback) return register_pool(desc); + info.queryType = VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; + break; case h::pipeline_statistics: if (!device_.info.pipeline_statistics_query) { log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); @@ -15980,6 +16024,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); @@ -16004,10 +16050,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}; @@ -16043,11 +16098,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; @@ -16512,6 +16578,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); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 010abbbc01..6be6d69e91 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -406,6 +406,20 @@ struct IndexBufferView { std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) }; +// D3D12_SO_BUFFER_SLOT_COUNT: the number of stream-output buffers (D3D12.h is not included in the portable subset, +// so the value is spelled here). +inline constexpr std::uint32_t so_buffer_slot_count = 4; + +// D3D12_STREAM_OUTPUT_BUFFER_VIEW: the capture buffer's VA, its size, and the VA of the 32-bit count the driver +// writes (BufferFilledSizeLocation). Each slot is a stream-output buffer; a draw captures the streams the bound +// pipeline declares (D3D-302). +struct StreamOutputBufferView { + std::uint64_t buffer_va = 0; + std::uint64_t size = 0; + std::uint64_t filled_size_va = 0; + bool valid() const { return buffer_va != 0; } +}; + // 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. @@ -450,6 +464,9 @@ struct Draw { std::int32_t base_vertex = 0; std::uint32_t first_instance = 0; bool mesh = false; + // The stream-output targets SOSetTargets bound at the draw (D3D12_SO_BUFFER_SLOT_COUNT of them), captured with the + // other state so a later SOSetTargets cannot change a recorded draw. Empty when no stream output was bound. + std::array stream_output{}; std::shared_ptr viewports; // non-null when >1 viewport or >1 scissor was bound }; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 2fef871943..0e8db9e52f 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -781,8 +781,9 @@ struct OcclusionResult { // A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that // was never ended writes zeros instead of waiting on it. struct QueryPool { - // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are - // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros. + // Null for a stream-output statistics heap on a device without VK_EXT_transform_feedback (D3D-302): every + // SO_STATISTICS_STREAMn query then counts 0 written and 0 needed, and a resolve fills zeros. With the feature + // it is a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool, begun/ended indexed on the stream. VkQueryPool pool = VK_NULL_HANDLE; std::uint32_t heap_type = 0; // d3d12_query_heap std::uint32_t count = 0; @@ -821,6 +822,7 @@ struct GraphicsPipeline { std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only + bool stream_output = false; // the PSO declares StreamOutput (D3D-302): draws capture with transform feedback bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth @@ -948,6 +950,13 @@ struct ReplayFunctions { PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results PFN_vkCmdBeginQuery begin_query = nullptr; PFN_vkCmdEndQuery end_query = nullptr; + // VK_EXT_transform_feedback (D3D-302): SO_STATISTICS queries begin/end indexed on a stream, and a draw bound to a + // StreamOutput pipeline captures through begin/end transform feedback. Null when the device lacks the feature. + PFN_vkCmdBeginQueryIndexedEXT begin_query_indexed = nullptr; + PFN_vkCmdEndQueryIndexedEXT end_query_indexed = nullptr; + PFN_vkCmdBindTransformFeedbackBuffersEXT bind_transform_feedback_buffers = nullptr; + PFN_vkCmdBeginTransformFeedbackEXT begin_transform_feedback = nullptr; + PFN_vkCmdEndTransformFeedbackEXT end_transform_feedback = nullptr; PFN_vkCmdWriteTimestamp write_timestamp = nullptr; PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on @@ -1232,6 +1241,12 @@ struct PreparedDraw { VkDeviceSize index_offset = 0; VkDeviceSize index_size = 0; // the bytes of the index buffer view inside its buffer; 0 with no index buffer VkIndexType index_type = VK_INDEX_TYPE_UINT16; + // Stream output (D3D-302): the capture buffers SOSetTargets bound, resolved from their VAs. Only slots with a + // buffer are used (by input slot). The filled-size location (BufferFilledSizeLocation) is a write-back follow-up + // (docs/d3d12_vulkan.md section 4.6). + std::array stream_output{}; + std::array stream_output_offsets{}; + std::array stream_output_sizes{}; QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has @@ -1254,6 +1269,9 @@ struct PreparedDraw { index_offset = 0; index_size = 0; index_type = VK_INDEX_TYPE_UINT16; + stream_output.fill(VK_NULL_HANDLE); + stream_output_offsets.fill(0); + stream_output_sizes.fill(0); quad_indices = {}; area = {}; layers = 1; @@ -2531,6 +2549,29 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.index_size = size; } } + // Stream output (D3D-302): resolve each bound capture buffer from its VA, like the vertex buffers. Without a + // bound buffer the slot is left null. The filled-size location is a separate VA (written after the draw). + if (vk.begin_transform_feedback) { + for (std::uint32_t slot = 0; slot < so_buffer_slot_count; ++slot) { + const StreamOutputBufferView& view = draw.stream_output[slot]; + if (!view.valid()) continue; + std::uint64_t size = view.size; + VkDeviceSize offset = 0; + if (!vk.buffer_at(view.buffer_va, size, p.stream_output[slot], offset)) { + size = view.size; + if (!vk.title_memory || !vk.title_memory(view.buffer_va, size, p.stream_output[slot], offset)) { + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 24) + std::fprintf(stderr, + "[rt] replay: stream output buffer slot %u va 0x%llx size %u names no buffer\n", + slot, static_cast(view.buffer_va), unsigned(view.size)); + return unresolved_at(__LINE__); + } + } + p.stream_output_offsets[slot] = offset; + p.stream_output_sizes[slot] = size; + } + } return ReplayResult::success; } @@ -2970,6 +3011,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.unpredicated_copies = 0; const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; + // An SO_STATISTICS query on a real transform-feedback heap additionally needs the indexed begin/end (D3D-302). + const bool so_queries = vk.begin_query_indexed && vk.end_query_indexed; // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a // type is still open at most once at any point, because each event closes the one open slot and opens a new @@ -3499,7 +3542,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun overlaps |= begin && (ordinary_active || binary_active); if (begin) ++binary_active; else --binary_active; } else if (is_so_statistics(range.type)) { - // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. + // A real transform-feedback heap queries on a stream (D3D-302); without a pool (the feature is + // off) it overlaps nothing and runs nothing. Both cases are handled; the indexed commands are + // required when the heap has a pool. + if (heap->pool && !so_queries) return unsupported_at(__LINE__); } else { statistics_overlaps |= begin && statistics_active_count; if (begin) ++statistics_active_count; else --statistics_active_count; @@ -3909,17 +3955,28 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu begin_statistics(); return; } - // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for - // BeginQuery and EndQuery; its resolves were planned as zero fills. + // A heap without a Vulkan pool (stream-output statistics on a device without VK_EXT_transform_feedback) runs + // nothing for BeginQuery and EndQuery; its resolves were planned as zero fills. if (!heap.pool && !std::holds_alternative(command)) return; + // An SO_STATISTICS_STREAMn query begins/ends indexed on that stream (D3D-302): the query type's stream index is + // the `index` argument of vkCmdBeginQueryIndexedEXT / vkCmdEndQueryIndexedEXT. + const auto so_stream = [](std::uint32_t type) -> std::uint32_t { + return is_so_statistics(type) ? type - d3d12_query::so_statistics_stream0 : 0; + }; if (const auto* begin = std::get_if(&command)) { vk.reset_query_pool(cb, heap.pool, begin->index, 1); - const bool precise = begin->type == d3d12_query::occlusion && heap.precise; - vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); + if (is_so_statistics(begin->type)) { + vk.begin_query_indexed(cb, heap.pool, begin->index, so_stream(begin->type), 0); + } else { + const bool precise = begin->type == d3d12_query::occlusion && heap.precise; + vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); + } } else if (const auto* end = std::get_if(&command)) { if (end->type == d3d12_query::timestamp) { vk.reset_query_pool(cb, heap.pool, end->index, 1); vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); + } else if (is_so_statistics(end->type)) { + vk.end_query_indexed(cb, heap.pool, end->index, so_stream(end->type)); } else { vk.end_query(cb, heap.pool, end->index); } @@ -4892,6 +4949,26 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], &d.vertex_sizes[slot], &d.vertex_strides[slot]); } + // Stream output (D3D-302): bind the capture buffers SOSetTargets set, then capture this draw's + // primitives into them. Capture runs only when the bound pipeline declares StreamOutput (beginning + // transform feedback without one is a Vulkan VUID violation); a StreamOutput draw with no bound buffer + // is captured into nothing, as D3D12 does with no bound buffer. + const auto begin_stream_output = [&]() -> std::uint32_t { + if (!graphics.stream_output || !vk.bind_transform_feedback_buffers || !vk.begin_transform_feedback) + return 0; + std::uint32_t count = 0; + for (std::uint32_t slot = 0; slot < so_buffer_slot_count; ++slot) + if (d.stream_output[slot]) count = slot + 1; + if (!count) return 0; + vk.bind_transform_feedback_buffers(command_buffer, 0, count, d.stream_output.data(), + d.stream_output_offsets.data(), d.stream_output_sizes.data()); + vk.begin_transform_feedback(command_buffer, 0, count, nullptr, nullptr); + return count; + }; + const auto end_stream_output = [&](std::uint32_t count) { + if (count) vk.end_transform_feedback(command_buffer, 0, count, nullptr, nullptr); + }; + const std::uint32_t stream_output_count = begin_stream_output(); if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); if (vk.mesh_draw_count) ++*vk.mesh_draw_count; @@ -4929,6 +5006,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } else { vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); } + end_stream_output(stream_output_count); vk.end_rendering(command_buffer); } } From cd65952f4ff9ea43f9adb05317e46ae4b2c9ebb6 Mon Sep 17 00:00:00 2001 From: BubsMcgee Date: Wed, 25 Nov 2026 01:20:31 -0500 Subject: [PATCH 2/4] d3d12: stream output, SOSetTargets and real SO_STATISTICS query pools (D3D-302) --- README.md | 6 ++++-- docs/d3d12_vulkan.md | 22 +++++++++++++--------- runtime/src/vulkan_backend.h | 19 ++++++++++++++++++- runtime/test/d3d12_vulkan_device_test.cpp | 13 +++++++++++-- 4 files changed, 46 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 9041367d48..a7b4256096 100644 --- a/README.md +++ b/README.md @@ -302,8 +302,10 @@ The biggest open pieces: - **Shader translator on hardware**: compute, mesh and geometry now translate (see the translator contract in [docs/design.md](docs/design.md)); still open are the vertex-shader input layout (`v0` = `VertexIndex` is unverified if the console runs VS as NGG) and wave64 cross-half code in VS/PS/GS on 32-wide subgroups. -- **Xbox D3D12 → Vulkan**: mesh-shader draws, indirect draw state and stream output are still open; #313 tracks the - remaining method surface. The Windows integration exercises the first-run UI. [Plan and status](docs/d3d12_vulkan.md) +- **Xbox D3D12 → Vulkan**: mesh-shader draws and indirect draw state are still open; stream output now accepts a + `StreamOutput` PSO, binds `SOSetTargets` and captures draws with `VK_EXT_transform_feedback` (capture needs the + translated shader to carry `XfbBuffer`/`XfbStride`/`XfbOffset` decorations). #313 tracks the remaining method + surface. The Windows integration exercises the first-run UI. [Plan and status](docs/d3d12_vulkan.md) - **Model recovery**: investigate the 71 unrecovered fragment candidates in [`levels.rpf`](docs/models.md#full-archive-re-count-at-e293917). See [CONTRIBUTING.md](CONTRIBUTING.md). Never attach game files, extracted assets or generated shaders to issues or diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e23985ecb3..e91a3e1e36 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3624,15 +3624,19 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c (`compare_invalid_arguments`, "query heap:", RTX 5070 / 621.14): `E_INVALIDARG` for no queries, a node other than node 0, or a type past `PIPELINE_STATISTICS1` (7), checked before the output; a valid description with a null output is then `E_UNEXPECTED`, not `S_FALSE`. -- **Stream-output statistics** (D3D-302). The layer has no stream output: a graphics PSO with `StreamOutput` - entries is refused and `SOSetTargets` is not implemented, so no primitive reaches a stream and every - `SO_STATISTICS_STREAM0..3` query counts 0 written and 0 needed. An `SO_STATISTICS` heap is therefore made without - a `VkQueryPool`: `BeginQuery`/`EndQuery` record nothing in Vulkan (D3D12's call rules are still kept, and the - heap's queries track ended or not as the others do), they overlap no other query, and `ResolveQueryData` writes - zeros (`vkCmdFillBuffer`, 16 bytes per query: `NumPrimitivesWritten`, `PrimitivesStorageNeeded`), with no - statistics split since nothing is dispatched. When stream output lands, the heap becomes a - `VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT` pool begun with `vkCmdBeginQueryIndexedEXT` on the stream, whose two - results are in the same order. +- **Stream-output statistics** (D3D-302). With `VK_EXT_transform_feedback` enabled on the device + (`D3D-TRANSFORM-FEEDBACK-DEVICE`), a graphics PSO with `StreamOutput` entries is accepted (its `RasterizedStream` + feeds the rasterizer; a non-zero one needs the `geometryStreams` feature), `SOSetTargets` binds the capture + buffers, and a draw bound to such a pipeline captures into them with + `vkCmdBindTransformFeedbackBuffersEXT` / `vkCmdBeginTransformFeedbackEXT` / `vkCmdEndTransformFeedbackEXT`. An + `SO_STATISTICS` heap is then a `VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT` pool begun and ended indexed on the + stream (`vkCmdBeginQueryIndexedEXT` / `vkCmdEndQueryIndexedEXT`), and `ResolveQueryData` copies the two 64-bit + results per query (16 bytes: `NumPrimitivesWritten`, `PrimitivesStorageNeeded`), in the same order. The capture is + driven by the shader's `XfbBuffer`/`XfbStride`/`XfbOffset` decorations in the translated SPIR-V. The + `BufferFilledSizeLocation` of a bound view is not written back yet (a follow-up). Without the feature, the layer has + no stream output: a `StreamOutput` PSO is refused, `SOSetTargets` binds nothing, an + `SO_STATISTICS` heap is made without a `VkQueryPool`, `BeginQuery`/`EndQuery` run nothing in Vulkan (the heap's + queries still track ended or not), and a resolve fills zeros. - **Recording.** The list keeps D3D12's rules for the calls: timestamps only have `EndQuery`; every other query is begun and ended in the same list with the same type, is not begun again while it runs, and is not resolved while it runs; resolve offsets are multiples of 8. A list closed with a query still running reports `E_INVALIDARG` and diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 5c3e884ba6..562fafbc5f 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -121,7 +121,9 @@ struct VulkanDeviceFunctions { X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ 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(vkCmdBeginQueryIndexedEXT) X(vkCmdEndQueryIndexedEXT) \ + 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 @@ -156,6 +158,9 @@ struct VulkanDeviceFunctions { return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && vkCmdSetPrimitiveRestartEnable; } + // VK_EXT_transform_feedback is enabled on the device: the indexed-query and transform-feedback entry points are + // loaded, so StreamOutput PSOs and SO_STATISTICS queries work (D3D-302). + bool transform_feedback = false; }; // Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. @@ -994,6 +999,9 @@ class VulkanContext { bool conditional_rendering = false, bool ray_tracing = false, bool xdxr = false) : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { loaded_ = vk.load(get, device); + // VK_EXT_transform_feedback: enabled on the device when its entry points resolved (D3D-302). + vk.transform_feedback = vk.vkCmdBeginTransformFeedbackEXT && vk.vkCmdEndTransformFeedbackEXT && + vk.vkCmdBindTransformFeedbackBuffersEXT; if (loaded_ && gpu_labels_.initialize(device, get)) { replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; } @@ -1024,6 +1032,15 @@ class VulkanContext { replay_.reset_query_pool = vk.vkCmdResetQueryPool; replay_.begin_query = vk.vkCmdBeginQuery; replay_.end_query = vk.vkCmdEndQuery; + // VK_EXT_transform_feedback (D3D-302), loaded when the device enabled it (transform_feedback_): indexed + // SO_STATISTICS queries and transform-feedback capture around StreamOutput draws. + if (vk.transform_feedback) { + replay_.begin_query_indexed = vk.vkCmdBeginQueryIndexedEXT; + replay_.end_query_indexed = vk.vkCmdEndQueryIndexedEXT; + replay_.bind_transform_feedback_buffers = vk.vkCmdBindTransformFeedbackBuffersEXT; + replay_.begin_transform_feedback = vk.vkCmdBeginTransformFeedbackEXT; + replay_.end_transform_feedback = vk.vkCmdEndTransformFeedbackEXT; + } replay_.write_timestamp = vk.vkCmdWriteTimestamp; replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; replay_.bind_pipeline = vk.vkCmdBindPipeline; diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 9df462d3fd..e496ad4ac9 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -6766,8 +6766,10 @@ int main() { EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(×tamps.p)))); query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); - // The layer has no stream output, so stream-output statistics heaps are made without a Vulkan pool and - // every query reads zero (D3D-302). + // D3D-302: an SO_STATISTICS heap is a real transform-feedback pool on a device with + // VK_EXT_transform_feedback (indexed on the stream); without it the layer has no stream output, the heap + // is made without a Vulkan pool, and every query reads zero. No stream output runs in either case here, + // so the resolved counts are 0. query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0}; EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p)))); query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; @@ -6811,6 +6813,13 @@ int main() { list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0, 1, readback.p, occlusion_at); list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1, 1, readback.p, occlusion_at + 8); list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 2, 2, readback.p, occlusion_at + 16); + // SOSetTargets (D3D-302) records a stream-output buffer view; no StreamOutput PSO is bound here, so the + // draw capture path is not exercised, but the call must record and the list must still close. + D3D12_STREAM_OUTPUT_BUFFER_VIEW so_view{}; + so_view.BufferLocation = 0x1000; // a console VA that names no buffer; no draw reads it in this list + so_view.SizeInBytes = 256; + list->SOSetTargets(0, 1, &so_view); + list->SOSetTargets(1, 1, nullptr); // unbind if (statistics.p) list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 2, readback.p, statistics_at); From ac4a992edabdc3c95f67baa3f58b368a465cd29d Mon Sep 17 00:00:00 2001 From: BubsMcgee Date: Wed, 25 Nov 2026 05:25:45 -0500 Subject: [PATCH 3/4] tests: enable VK_EXT_transform_feedback in vk_pipeline_check (D3D-302) The runtime's device enables VK_EXT_transform_feedback whenever the extension is present, and AMD's driver makes it part of a pipeline's cache key, so the cache vk_pipeline_check seeds offline no longer hit in gta6rt: pipeline_cache_seed failed 3/3 on an RX 7900 XT (adrianmjim). Link the same VkPhysicalDeviceTransformFeedbackFeaturesEXT the runtime enables, next to the mesh-shader one, and list it with the other always-enabled extensions in the header and docs/pipeline_check.md. Tested: pipeline_cache_seed passes on an NVIDIA RTX 3080 Ti (NVIDIA does not key on the extension, so it cannot reproduce the AMD failure). AI-assisted. --- docs/pipeline_check.md | 4 ++++ runtime/test/vk_pipeline_check.cpp | 13 +++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index d5d76cb931..c3c6a28b20 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -457,6 +457,10 @@ driver gives it the same cache key in both programs. Measured on Windows with an `VK_KHR_maintenance8` into the pipeline cache key even for compute shaders, so the checker enables both whenever supported and keeps `meshShaderQueries` on. - On a Windows RTX 5070 Ti (617.42), a compute-only seed missed with mesh features omitted and hit with the supported mesh and mesh-query features enabled on both devices. The shader, push constants and pipeline layout were identical. Cache-producing runs request this device configuration for every selected shader batch. +- On Windows with an AMD Radeon RX 7900 XT, `VK_EXT_transform_feedback` (with `transformFeedback` enabled, and + `geometryStreams` when the device offers it) is part of the key: the runtime enables it whenever the extension is + present (D3D-302), so the checker enables it too. Without it, `pipeline_cache_seed` failed 3 of 3 on that GPU and + passed 3 of 3 on `main`. NVIDIA leaves it out of the key, which is why it did not show up on the RTX 3080 Ti. - The executable's file name is part of the key; its folder is not. A copy of the checker under another name misses the cache the original wrote, and the runtime's device hits the checker's cache only from a program with the checker's file name. So on this driver a cache written by `vk_pipeline_check.exe` does not hit in diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 0e39d0f621..26eb5030cf 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -7,10 +7,10 @@ // descriptor-free shaders with the standard push-constant range // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) // paired with minimal partner stubs from /stubs/ (generated by tools/spirv_stubs.py) -// VK_EXT_mesh_shader (with meshShaderQueries) and VK_KHR_maintenance8 are always enabled when supported so the -// saved pipeline cache matches the runtime's device key; other optional device extensions are enabled only when -// needed by the selected shaders. Shaders whose required features or partner stubs are unavailable are reported as -// skipped rather than failed. +// VK_EXT_mesh_shader (with meshShaderQueries), VK_KHR_maintenance8 and VK_EXT_transform_feedback are always enabled +// when supported so the saved pipeline cache matches the runtime's device key; other optional device extensions are +// enabled only when needed by the selected shaders. Shaders whose required features or partner stubs are unavailable +// are reported as skipped rather than failed. // [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every // 10 minutes and at the end // --jobs N compile on up to N worker threads (default: half the hardware threads) @@ -1122,6 +1122,7 @@ int main(int argc, char** argv) { // Query the core and optional device features used by the checker. VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; + VkPhysicalDeviceTransformFeedbackFeaturesEXT tf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME @@ -1144,6 +1145,10 @@ int main(int argc, char** argv) { link(&f12, reinterpret_cast(&f12), nullptr, true); link(&f13, reinterpret_cast(&f13), nullptr, true); const bool ext_mesh = link(&mesh, reinterpret_cast(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, true); + // The runtime's device enables VK_EXT_transform_feedback (transformFeedback, and geometryStreams when the device + // offers it) whenever the extension is present (D3D-302), and a driver makes it part of a pipeline's cache key, so + // the checker enables it too (docs/pipeline_check.md, "The cache and the runtime's device"). + link(&tf, reinterpret_cast(&tf), VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME, true); const bool ext_bary = link(&bary, reinterpret_cast(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); const bool ext_lock = link(&lock, reinterpret_cast(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME From 4f05ff666fae1ec0e0a80f59ca8bd3bf5d239da4 Mon Sep 17 00:00:00 2001 From: BubsMcgee Date: Wed, 25 Nov 2026 06:10:16 -0500 Subject: [PATCH 4/4] WIP: stream-output capture fixes (sType, gap-safe SO binds, filled-size counters, TF usage bits) --- runtime/shims/d3d12_vulkan_device.cpp | 24 ++++++++- runtime/src/vulkan_replay.h | 71 ++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 15 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1f147b620f..b78a72cd8c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2320,6 +2320,9 @@ 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; + 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. @@ -2659,6 +2662,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 = [&] { @@ -4712,6 +4718,9 @@ 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; + 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 | @@ -4846,6 +4855,9 @@ 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; + 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; @@ -4988,6 +5000,9 @@ 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; + 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; @@ -7587,7 +7602,8 @@ class PipelineState final return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); } VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream{}; + VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream{ + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT}; raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; raster.cullMode = r.CullMode == D3D12_CULL_MODE_FRONT ? VK_CULL_MODE_FRONT_BIT : r.CullMode == D3D12_CULL_MODE_BACK ? VK_CULL_MODE_BACK_BIT @@ -8168,7 +8184,8 @@ class PipelineState final VkPipelineRasterizationStateCreateInfo raster{}; // A StreamOutput RasterizedStream other than 0: chained to `raster` so the geometry/vertex stage feeds the // rasterizer from that stream (D3D-302). Stream 0 needs no struct (Vulkan's default). - VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream{}; + VkPipelineRasterizationStateStreamCreateInfoEXT rasterization_stream{ + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT}; bool stream_output = false; bool conservative = false; VkPipelineMultisampleStateCreateInfo multisample{}; @@ -10198,6 +10215,9 @@ class Device final 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. 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 | diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 0e8db9e52f..e94cb0720d 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1241,12 +1241,15 @@ struct PreparedDraw { VkDeviceSize index_offset = 0; VkDeviceSize index_size = 0; // the bytes of the index buffer view inside its buffer; 0 with no index buffer VkIndexType index_type = VK_INDEX_TYPE_UINT16; - // Stream output (D3D-302): the capture buffers SOSetTargets bound, resolved from their VAs. Only slots with a - // buffer are used (by input slot). The filled-size location (BufferFilledSizeLocation) is a write-back follow-up - // (docs/d3d12_vulkan.md section 4.6). + // Stream output (D3D-302): the capture buffers SOSetTargets bound, resolved from their VAs, by input slot. Only + // slots with a buffer are bound (a null slot is filled with a zero-size binding at emit). The filled-size + // location (BufferFilledSizeLocation) is the byte offset a capture resumes from and is written back after the + // draw, which is exactly a Vulkan counter buffer, so it is resolved too (docs/d3d12_vulkan.md section 4.6). std::array stream_output{}; std::array stream_output_offsets{}; std::array stream_output_sizes{}; + std::array stream_output_counters{}; + std::array stream_output_counter_offsets{}; QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has @@ -1272,6 +1275,8 @@ struct PreparedDraw { stream_output.fill(VK_NULL_HANDLE); stream_output_offsets.fill(0); stream_output_sizes.fill(0); + stream_output_counters.fill(VK_NULL_HANDLE); + stream_output_counter_offsets.fill(0); quad_indices = {}; area = {}; layers = 1; @@ -2549,9 +2554,11 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.index_size = size; } } - // Stream output (D3D-302): resolve each bound capture buffer from its VA, like the vertex buffers. Without a - // bound buffer the slot is left null. The filled-size location is a separate VA (written after the draw). - if (vk.begin_transform_feedback) { + // Stream output (D3D-302): resolve each bound capture buffer from its VA, like the vertex buffers, but only for + // a pipeline that captures: a stale SO target left bound must not make an ordinary draw unresolvable. Without a + // bound buffer the slot is left null. The filled-size location is a separate VA holding the byte offset the + // capture resumes from and appends to, so it resolves to the counter buffer that begin/end read and write back. + if (pipeline->stream_output && vk.begin_transform_feedback) { for (std::uint32_t slot = 0; slot < so_buffer_slot_count; ++slot) { const StreamOutputBufferView& view = draw.stream_output[slot]; if (!view.valid()) continue; @@ -2570,6 +2577,23 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } p.stream_output_offsets[slot] = offset; p.stream_output_sizes[slot] = size; + // A missing count location only loses the append position (the capture still starts at byte 0), so it + // is not fatal. D3D12 always supplies one; a null slot has no counter. + if (view.filled_size_va) { + VkDeviceSize counter_offset = 0; + std::uint64_t counter_size = 4; + if (vk.buffer_at(view.filled_size_va, counter_size, p.stream_output_counters[slot], counter_offset) || + (vk.title_memory && vk.title_memory(view.filled_size_va, 4, p.stream_output_counters[slot], + counter_offset))) { + p.stream_output_counter_offsets[slot] = counter_offset; + } else { + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 24) + std::fprintf(stderr, + "[rt] replay: stream output filled-size slot %u va 0x%llx names no buffer\n", + slot, static_cast(view.filled_size_va)); + } + } } } return ReplayResult::success; @@ -4952,21 +4976,42 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // Stream output (D3D-302): bind the capture buffers SOSetTargets set, then capture this draw's // primitives into them. Capture runs only when the bound pipeline declares StreamOutput (beginning // transform feedback without one is a Vulkan VUID violation); a StreamOutput draw with no bound buffer - // is captured into nothing, as D3D12 does with no bound buffer. + // is captured into nothing, as D3D12 does with no bound buffer. Every binding in the call must name a + // buffer, so a gap between bound slots is filled with the first bound buffer at size 0 (nothing is + // captured into it). The filled-size counters make consecutive draws append instead of overwrite. const auto begin_stream_output = [&]() -> std::uint32_t { if (!graphics.stream_output || !vk.bind_transform_feedback_buffers || !vk.begin_transform_feedback) return 0; std::uint32_t count = 0; - for (std::uint32_t slot = 0; slot < so_buffer_slot_count; ++slot) - if (d.stream_output[slot]) count = slot + 1; + VkBuffer first = VK_NULL_HANDLE; + for (std::uint32_t slot = 0; slot < so_buffer_slot_count; ++slot) { + if (!d.stream_output[slot]) continue; + if (!first) first = d.stream_output[slot]; + count = slot + 1; + } if (!count) return 0; - vk.bind_transform_feedback_buffers(command_buffer, 0, count, d.stream_output.data(), - d.stream_output_offsets.data(), d.stream_output_sizes.data()); - vk.begin_transform_feedback(command_buffer, 0, count, nullptr, nullptr); + std::array buffers{}; + std::array offsets{}; + std::array sizes{}; + for (std::uint32_t slot = 0; slot < count; ++slot) { + if (d.stream_output[slot]) { + buffers[slot] = d.stream_output[slot]; + offsets[slot] = d.stream_output_offsets[slot]; + sizes[slot] = d.stream_output_sizes[slot]; + } else { + buffers[slot] = first; + } + } + vk.bind_transform_feedback_buffers(command_buffer, 0, count, buffers.data(), offsets.data(), + sizes.data()); + vk.begin_transform_feedback(command_buffer, 0, count, d.stream_output_counters.data(), + d.stream_output_counter_offsets.data()); return count; }; const auto end_stream_output = [&](std::uint32_t count) { - if (count) vk.end_transform_feedback(command_buffer, 0, count, nullptr, nullptr); + if (count) + vk.end_transform_feedback(command_buffer, 0, count, d.stream_output_counters.data(), + d.stream_output_counter_offsets.data()); }; const std::uint32_t stream_output_count = begin_stream_output(); if (draw->mesh) {