From 3a4c5cddcd3f3e984331ae2fc9d8e3a7ca56c315 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 9 Nov 2026 19:19:21 +0800 Subject: [PATCH 01/20] fix(d3d12): populate `dsv_readonly_flags` for render encoder Since `GetDepthStencilState()` on render pso will use it, and disable depth/stencil write if the planar is readonly. Signed-off-by: Feifan He --- src/d3d12/d3d12_command_list.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 2199b87c1..34197b636 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -427,6 +427,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChilddsv_planar_flags = dsv_planar_flags; + render->dsv_readonly_flags = AttachmentDesc.Flags; render_target_width = std::min(render_target_width, AttachmentDesc.Width); render_target_height = std::min(render_target_height, AttachmentDesc.Height); render_target_array_length = std::max(render_target_array_length, AttachmentDesc.RenderTargetArrayLength); From da316cf645fd85b2b0bf00217d08ca07d8d90893 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 9 Nov 2026 19:20:37 +0800 Subject: [PATCH 02/20] chore(d3d12): make `{Begin|End}Event` no-op Signed-off-by: Feifan He --- src/d3d12/d3d12_command_list.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 34197b636..b588c1e0e 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -1695,9 +1695,13 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild Date: Mon, 9 Nov 2026 19:32:34 +0800 Subject: [PATCH 03/20] feat(d3d12): introduce render encoder prepass Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 3 +++ src/d3d12/d3d12_command_allocator.hpp | 12 ++++++++++++ src/d3d12/d3d12_command_encoder.hpp | 2 ++ src/d3d12/d3d12_command_list.cpp | 3 +++ src/d3d12/d3d12_command_queue.cpp | 7 +++++++ 5 files changed, 27 insertions(+) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index b67a737f6..b6a241639 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -443,6 +443,9 @@ SimpleCommandContext::startRenderPass() { render->cmd_head.type = WMTRenderCommandNop; render->cmd_head.next.set(0); render->cmd_tail = (wmtcmd_base *)&render->cmd_head; + render->cmd_prepass_head.type = WMTComputeCommandNop; + render->cmd_prepass_head.next.set(0); + render->cmd_prepass_tail = (wmtcmd_base *)&render->cmd_prepass_head; render->dsv_planar_flags = 0; render->dsv_readonly_flags = 0; render->render_target_count = 0; diff --git a/src/d3d12/d3d12_command_allocator.hpp b/src/d3d12/d3d12_command_allocator.hpp index 482792a07..909ce19af 100644 --- a/src/d3d12/d3d12_command_allocator.hpp +++ b/src/d3d12/d3d12_command_allocator.hpp @@ -195,6 +195,18 @@ class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable + cmd_struct & + EncodeRenderPrepassCommand() { + assert(encoder_current->type == EncoderType::Render); + auto encoder = static_cast(encoder_current); + auto storage = (cmd_struct *)AllocateCPUHeap(sizeof(cmd_struct), 16); + encoder->cmd_prepass_tail->next.set(storage); + encoder->cmd_prepass_tail = (wmtcmd_base *)storage; + storage->next.set(nullptr); + return *storage; + } + template cmd_struct & EncodeBlitCommand() { diff --git a/src/d3d12/d3d12_command_encoder.hpp b/src/d3d12/d3d12_command_encoder.hpp index 1caf3bcdf..4548887b2 100644 --- a/src/d3d12/d3d12_command_encoder.hpp +++ b/src/d3d12/d3d12_command_encoder.hpp @@ -97,6 +97,8 @@ struct RenderEncoderData : EncoderData { uint32_t render_target_width; wmtcmd_render_nop cmd_head; wmtcmd_base *cmd_tail; + wmtcmd_compute_nop cmd_prepass_head; + wmtcmd_base *cmd_prepass_tail; uint8_t dsv_planar_flags; uint8_t dsv_readonly_flags; uint8_t render_target_count; diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index b588c1e0e..d5f5a42f5 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -381,6 +381,9 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildcmd_head.type = WMTRenderCommandNop; render->cmd_head.next.set(0); render->cmd_tail = (wmtcmd_base *)&render->cmd_head; + render->cmd_prepass_head.type = WMTComputeCommandNop; + render->cmd_prepass_head.next.set(0); + render->cmd_prepass_tail = (wmtcmd_base *)&render->cmd_prepass_head; render->dsv_planar_flags = 0; render->dsv_readonly_flags = 0; render->render_target_count = num_rtvs; diff --git a/src/d3d12/d3d12_command_queue.cpp b/src/d3d12/d3d12_command_queue.cpp index 57b0332cf..e36ba7bec 100644 --- a/src/d3d12/d3d12_command_queue.cpp +++ b/src/d3d12/d3d12_command_queue.cpp @@ -295,6 +295,13 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageablerender_target_width; render_pass_info.render_target_height = data->render_target_height; } + if (data->cmd_prepass_tail->type != WMTComputeCommandNop) { + auto encoder = cmdbuf.computeCommandEncoder(false); + encoder.waitForFence(fence_); + encoder.encodeCommands(&data->cmd_prepass_head); + encoder.updateFence(fence_); + encoder.endEncoding(); + } auto encoder = cmdbuf.renderCommandEncoder(render_pass_info); encoder.waitForFence(fence_, WMTRenderStageVertex); encoder.encodeCommands(&data->cmd_head); From e7be8ec7cc266dd2e61ba674b23bd0f227b9c43a Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 9 Nov 2026 19:42:44 +0800 Subject: [PATCH 04/20] refactor(d3d12): populate render icb in render prepass Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 30 ++++++++++++--------------- src/d3d12/d3d12_command_signature.cpp | 21 ++++--------------- src/d3d12/d3d12_device.hpp | 3 +-- 3 files changed, 18 insertions(+), 36 deletions(-) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index b6a241639..f0fbcb2b7 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -204,7 +204,7 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat auto &cmd_setpso_res = EncodeComputeCommand(); cmd_setpso_res.type = WMTComputeCommandSetPSO; - cmd_setpso_res.pso = pCmdSig->compute_resolver; + cmd_setpso_res.pso = pCmdSig->resolver; cmd_setpso_res.threadgroup_size = {1, 1, 1}; auto &cmd_argbuf_res = EncodeComputeCommand(); @@ -214,7 +214,7 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat cmd_argbuf_res.index = 30; auto &cmd_dispatch_res = EncodeComputeCommand(); - cmd_dispatch_res.type = WMTComputeCommandDispatch; + cmd_dispatch_res.type = WMTComputeCommandDispatchThreads; cmd_dispatch_res.size = {1, 1, 1}; auto &cmd_setpso = EncodeComputeCommand(); @@ -289,29 +289,25 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( * TODO: move these out? */ - auto &cmd_use_icb = EncodeRenderCommand(); - cmd_use_icb.type = WMTRenderCommandUseResource; - cmd_use_icb.stages = WMTRenderStageVertex; + auto &cmd_use_icb = EncodeRenderPrepassCommand(); + cmd_use_icb.type = WMTComputeCommandUseResource; cmd_use_icb.usage = WMTResourceUsageRead | WMTResourceUsageWrite; cmd_use_icb.resource = icb; - auto &cmd_setpso_res = EncodeRenderCommand(); - cmd_setpso_res.type = WMTRenderCommandSetPSO; - cmd_setpso_res.pso = pCmdSig->render_resolver; + auto &cmd_setpso_res = EncodeRenderPrepassCommand(); + cmd_setpso_res.type = WMTComputeCommandSetPSO; + cmd_setpso_res.pso = pCmdSig->resolver; + cmd_setpso_res.threadgroup_size = {32, 1, 1}; - auto &cmd_argbuf_res = EncodeRenderCommand(); - cmd_argbuf_res.type = WMTRenderCommandSetVertexBuffer; + auto &cmd_argbuf_res = EncodeRenderPrepassCommand(); + cmd_argbuf_res.type = WMTComputeCommandSetBuffer; cmd_argbuf_res.buffer = gpu_heap_buffer_; cmd_argbuf_res.offset = Offset; cmd_argbuf_res.index = 30; - auto &cmd_draw_res = EncodeRenderCommand(); - cmd_draw_res.type = WMTRenderCommandDraw; - cmd_draw_res.primitive_type = WMTPrimitiveTypePoint; - cmd_draw_res.vertex_start = 0; - cmd_draw_res.vertex_count = 1; - cmd_draw_res.base_instance = 0; - cmd_draw_res.instance_count = 1; + auto &cmd_draw_res = EncodeRenderPrepassCommand(); + cmd_draw_res.type = WMTComputeCommandDispatchThreads; + cmd_draw_res.size = {1, 1, 1}; auto &cmd_setpso = EncodeRenderCommand(); cmd_setpso.type = WMTRenderCommandSetPSO; diff --git a/src/d3d12/d3d12_command_signature.cpp b/src/d3d12/d3d12_command_signature.cpp index 0a046e28b..35502ff9a 100644 --- a/src/d3d12/d3d12_command_signature.cpp +++ b/src/d3d12/d3d12_command_signature.cpp @@ -175,15 +175,10 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12PageableGetMTLDevice().newComputePipelineState(function, err); - } else { - WMTRenderPipelineInfo info; - WMT::InitializeRenderPipelineInfo(info); - info.rasterization_enabled = false; - info.vertex_function = function; - render_resolver = device_->GetMTLDevice().newRenderPipelineState(info, err); - } + resolver = device_->GetMTLDevice().newComputePipelineState(function, err); if (err) { ERR("Failed to compile command signature resolve pso: ", err.description().getUTF8String()); diff --git a/src/d3d12/d3d12_device.hpp b/src/d3d12/d3d12_device.hpp index 0897a7d2e..d2172d2c2 100644 --- a/src/d3d12/d3d12_device.hpp +++ b/src/d3d12/d3d12_device.hpp @@ -115,8 +115,7 @@ class MTLD3D12CommandSignature : public ID3D12CommandSignature { UINT UpdateVertexBuffers : 1; UINT UpdateIndexBuffer : 1; - WMT::Reference render_resolver; - WMT::Reference compute_resolver; + WMT::Reference resolver; virtual void AddRefPrivate() = 0; virtual void ReleasePrivate() = 0; From 6913d64a7ceb3d9c85ce150e5d284f4ba24aa9ee Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 9 Nov 2026 20:00:51 +0800 Subject: [PATCH 05/20] refactor(d3d12): populate one indirect command per thread Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 4 ++-- src/d3d12/d3d12_command_signature.cpp | 11 +++-------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index f0fbcb2b7..675ae8721 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -215,7 +215,7 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat auto &cmd_dispatch_res = EncodeComputeCommand(); cmd_dispatch_res.type = WMTComputeCommandDispatchThreads; - cmd_dispatch_res.size = {1, 1, 1}; + cmd_dispatch_res.size = {MaxCount, 1, 1}; auto &cmd_setpso = EncodeComputeCommand(); cmd_setpso.type = WMTComputeCommandSetPSO; @@ -307,7 +307,7 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( auto &cmd_draw_res = EncodeRenderPrepassCommand(); cmd_draw_res.type = WMTComputeCommandDispatchThreads; - cmd_draw_res.size = {1, 1, 1}; + cmd_draw_res.size = {MaxCount, 1, 1}; auto &cmd_setpso = EncodeRenderCommand(); cmd_setpso.type = WMTRenderCommandSetPSO; diff --git a/src/d3d12/d3d12_command_signature.cpp b/src/d3d12/d3d12_command_signature.cpp index 35502ff9a..800d67811 100644 --- a/src/d3d12/d3d12_command_signature.cpp +++ b/src/d3d12/d3d12_command_signature.cpp @@ -175,14 +175,10 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable(" "command_data.argument_buffer + i * " << pDesc->ByteStride << ")[0];\n"; @@ -192,7 +188,7 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable= count) continue;\n"; + source << "if (i >= count) return;\n"; source << "device ulong * rootsig_qwords = command_data.rootsig_qwords + " "(i * command_data.rootsig_qwords_stride);\n"; if (!is_compute) @@ -311,8 +307,7 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable err; auto lib = device_->GetMTLDevice().newLibraryWithSource(source.view(), err); From a76bec74e4c42dcb2d0c0c52a9506f2d4b23747c Mon Sep 17 00:00:00 2001 From: Feifan He Date: Tue, 10 Nov 2026 17:37:07 +0800 Subject: [PATCH 06/20] feat(d3d12): implement `ExecuteIndirect()` for geometry & tessellation pipeline Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 32 +++++--- src/d3d12/d3d12_command_allocator.hpp | 18 ++++- src/d3d12/d3d12_command_list.cpp | 28 +++++-- src/d3d12/d3d12_command_signature.cpp | 110 +++++++++++++++++++++----- 4 files changed, 151 insertions(+), 37 deletions(-) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index 675ae8721..94e9d38fd 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -236,10 +236,14 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat IndirectRenderCommandData * MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( - MTLD3D12CommandSignature *pCmdSig, MTLD3D12GraphicsPipelineState *pPSO, size_t MaxCount + MTLD3D12CommandSignature *pCmdSig, MTLD3D12GraphicsPipelineState *pPSO, size_t MaxCount, + D3D12_PRIMITIVE_TOPOLOGY Topology ) { + bool use_emulated_mesh = pPSO->is_geometry || pPSO->is_tess; + bool encode_binding = + use_emulated_mesh || pCmdSig->UpdateVertexBuffers || pCmdSig->UpdateIndexBuffer || pCmdSig->UpdateRootArguments; WMTIndirectCommandBufferInfo info; - info.inherit_buffers = !(pCmdSig->UpdateVertexBuffers || pCmdSig->UpdateIndexBuffer || pCmdSig->UpdateRootArguments); + info.inherit_buffers = !encode_binding; info.inherit_pso = 1; info.inherit_cull_mode = 1; info.inherit_fill_mode = 1; @@ -250,12 +254,13 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( info.support_color_attachment_mapping = 0; info.support_dynamic_attribute_stride = 0; info.support_ray_tracing = 0; - info.type = pCmdSig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? WMTIndirectCommandTypeDrawIndexed - : WMTIndirectCommandTypeDraw; + info.type = use_emulated_mesh ? WMTIndirectCommandTypeDrawMeshThreadgroups + : pCmdSig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? WMTIndirectCommandTypeDrawIndexed + : WMTIndirectCommandTypeDraw; info.max_vertex_buffer_binding = 31; info.max_fragment_buffer_binding = 31; - info.max_object_buffer_binding = 0; - info.max_mesh_buffer_binding = 0; + info.max_object_buffer_binding = 31; + info.max_mesh_buffer_binding = 31; info.max_kernel_buffer_binding = 0; info.max_kernel_threadgroup_memory_binding = 0; info.max_object_threadgroup_memory_binding = 0; @@ -269,6 +274,12 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( data->cmd_buf = info.gpu_resource_id; data->max_count = MaxCount; + uint32_t cmd_flags = 0; + if (pPSO->is_geometry) + cmd_flags |= kIndirectRenderCommandFlagIsGeometry; + if (pPSO->is_tess) + cmd_flags |= kIndirectRenderCommandFlagIsTessellation; + data->flags = cmd_flags; { // populated outside @@ -282,13 +293,12 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( data->primitive_type = 0; data->index_buffer = 0; data->index_buffer_format = {}; + data->dyn_ib_args = 0; + data->vertex_increment_per_warp = 0; + data->vertex_per_warp = 0; } { - /** - * TODO: move these out? - */ - auto &cmd_use_icb = EncodeRenderPrepassCommand(); cmd_use_icb.type = WMTComputeCommandUseResource; cmd_use_icb.usage = WMTResourceUsageRead | WMTResourceUsageWrite; @@ -311,7 +321,7 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( auto &cmd_setpso = EncodeRenderCommand(); cmd_setpso.type = WMTRenderCommandSetPSO; - cmd_setpso.pso = pPSO->GetRenderPipelineVariant({} /* FIXME: value should not matter here until gs/ts */); + cmd_setpso.pso = pPSO->GetRenderPipelineVariant(Topology); } auto &cmd = EncodeRenderCommand(); diff --git a/src/d3d12/d3d12_command_allocator.hpp b/src/d3d12/d3d12_command_allocator.hpp index 909ce19af..81c5d83a5 100644 --- a/src/d3d12/d3d12_command_allocator.hpp +++ b/src/d3d12/d3d12_command_allocator.hpp @@ -52,6 +52,9 @@ struct IndirectComputeCommandData { uint32_t tgsize_z; }; +constexpr uint32_t kIndirectRenderCommandFlagIsGeometry = 1 << 0; +constexpr uint32_t kIndirectRenderCommandFlagIsTessellation = 1 << 1; + struct IndirectRenderCommandData { uint64_t cmd_buf; uint64_t max_count; @@ -65,6 +68,16 @@ struct IndirectRenderCommandData { uint64_t index_buffer; DXGI_FORMAT index_buffer_format; uint32_t vertex_argbuf_stride; + uint64_t dyn_ib_args; + uint32_t flags; + union { + uint32_t vertex_per_warp; + uint32_t control_point_count; + }; + union { + uint32_t vertex_increment_per_warp; + uint32_t threads_per_patch; + }; }; class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable { @@ -251,7 +264,10 @@ class MTLD3D12CommandAllocatorImpl : public MTLD3D12PageableUpdateRootArguments || sig->UpdateIndexBuffer || sig->UpdateVertexBuffers; + bool encode_binding = sig->UpdateRootArguments || sig->UpdateIndexBuffer || sig->UpdateVertexBuffers || + pso_graphics_->is_geometry || pso_graphics_->is_tess; DrawCallStatus status = PreDraw(encode_binding); if (status == DrawCallStatus::Invalid) return; - if (status != DrawCallStatus::Ordinary) { - IMPLEMENT_ME // TODO: (potential) emulated pipeline - } - auto cmd = allocator_->EncodeIndirectRenderCommand(sig, pso_graphics_.ptr(), MaxCommandCount); + auto cmd = allocator_->EncodeIndirectRenderCommand(sig, pso_graphics_.ptr(), MaxCommandCount, topology_); cmd->max_count_buffer = CountBufferAddress; cmd->argument_buffer = ArgBufferAddress; cmd->primitive_type = primitive_type; - cmd->index_buffer = index_buffer_address; - cmd->index_buffer_format = index_type == WMTIndexTypeUInt32 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; + if (sig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED) { + cmd->index_buffer = index_buffer_address; + cmd->index_buffer_format = index_type == WMTIndexTypeUInt32 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; + } else { + cmd->index_buffer = 0; + cmd->index_buffer_format = DXGI_FORMAT_UNKNOWN; + } + if (status == DrawCallStatus::Geometry) { + std::tie(cmd->vertex_per_warp, cmd->vertex_increment_per_warp) = get_gs_vertex_count(topology_); + } + if (status == DrawCallStatus::Tessellation) { + cmd->control_point_count = cp_count; + cmd->threads_per_patch = pso_graphics_->tess_threads_per_patch; + } + if (status != DrawCallStatus::Ordinary) { + auto [Unused, Offset] = allocator_->AllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS) * MaxCommandCount, 32); + cmd->dyn_ib_args = allocator_->gpu_heap_buffer_address_ + Offset; + } if (!encode_binding) return; cmd->rootsig_qwords = EncodeRootArgument(rootsig_graphics_.ptr(), rootarg_graphics_staging_, MaxCommandCount); diff --git a/src/d3d12/d3d12_command_signature.cpp b/src/d3d12/d3d12_command_signature.cpp index 800d67811..967ec395a 100644 --- a/src/d3d12/d3d12_command_signature.cpp +++ b/src/d3d12/d3d12_command_signature.cpp @@ -17,6 +17,7 @@ */ #include "com/com_pointer.hpp" +#include "d3d12_command_allocator.hpp" #include "d3d12_device.hpp" #include "d3d12_pageable.hpp" @@ -71,6 +72,16 @@ struct dxmt_vertex_buffer { uint length; }; +struct dxmt_dynamic_ib_arguments { + uint vertex_per_instance; + uint instance_count; + uint start_vertex; + uint base_vertex; + uint start_instance; + uint index_format; + device void * index_buffer; +}; + struct dxmt_render_command_data { command_buffer cmd_buf; ulong max_count; @@ -84,6 +95,10 @@ struct dxmt_render_command_data { device void * index_buffer; uint index_buffer_format; uint vertex_argbuf_stride; + device dxmt_dynamic_ib_arguments * dyn_ib_args; + uint flags; + uint mesh_arg1; + uint mesh_arg2; }; )"; @@ -191,19 +206,36 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable= count) return;\n"; source << "device ulong * rootsig_qwords = command_data.rootsig_qwords + " "(i * command_data.rootsig_qwords_stride);\n"; - if (!is_compute) + if (!is_compute) { source << "device dxmt_vertex_buffer * vertex_buffer = " "reinterpret_cast(command_data.vertex_buffer + " "(i * command_data.vertex_argbuf_stride));\n"; + source << "device dxmt_dynamic_ib_arguments * dyn_ib_args = &command_data.dyn_ib_args[i];\n"; + source << "bool is_geometry = command_data.flags & " << kIndirectRenderCommandFlagIsGeometry << ";\n"; + source << "bool is_tessellation = command_data.flags & " << kIndirectRenderCommandFlagIsTessellation << ";\n"; + source << "bool is_mesh_emulated = is_geometry || is_tessellation;\n"; + source << "if (is_mesh_emulated) {\n"; + source << "cmd.set_object_buffer(vertex_buffer," << SM50_BINDING_INDEX_VERTEX_BUFFER << ");\n"; + source << "cmd.set_object_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; + source << "cmd.set_object_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "cmd.set_object_buffer(dyn_ib_args," << SM50_BINDING_INDEX_DRAW_ARGUMENTS << ");\n"; + source << "cmd.set_mesh_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; + source << "cmd.set_mesh_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "cmd.set_fragment_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; + source << "cmd.set_fragment_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "} \n"; + } if (UpdateRootArguments || UpdateVertexBuffers || UpdateIndexBuffer) { if (!is_compute) { + source << "if (!is_mesh_emulated) {\n"; source << "cmd.set_vertex_buffer(vertex_buffer," << SM50_BINDING_INDEX_VERTEX_BUFFER << ");\n"; source << "cmd.set_vertex_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_vertex_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; source << "cmd.set_fragment_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_fragment_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "}\n"; } else { source << "cmd.set_kernel_buffer(rootsig_qwords, " << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_kernel_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; @@ -214,10 +246,32 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12PageablepArgumentDescs[i]; switch (arg.Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: { - source << "cmd.draw_primitives((primitive_type)command_data.primitive_type, " - "arg.draw.start_vertex_location, " - "arg.draw.vertex_count_per_instance, arg.draw.instance_count, " - "arg.draw.start_instance_location);\n"; + source + << "if (is_mesh_emulated) {\n" + " dyn_ib_args->vertex_per_instance = arg.draw.vertex_count_per_instance;\n" + " dyn_ib_args->instance_count = arg.draw.instance_count;\n" + " dyn_ib_args->start_vertex = arg.draw.start_vertex_location;\n" + " dyn_ib_args->base_vertex = 0;\n" + " dyn_ib_args->start_instance = arg.draw.start_instance_location;\n" + " dyn_ib_args->index_format = 0;\n" + " dyn_ib_args->index_buffer = 0;\n" + "}\n" + "if (is_geometry) {\n" + " uint warp_count = (arg.draw.vertex_count_per_instance - 1) / command_data.mesh_arg2 + 1;\n" + " cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw.instance_count, 1)," + " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n" + "} else if (is_tessellation) {\n" + " uint patch_per_instance = arg.draw.vertex_count_per_instance / command_data.mesh_arg1;\n" + " uint patch_per_group = 32 / command_data.mesh_arg2;\n" + " uint patch_per_object = (patch_per_instance - 1) / patch_per_group + 1;\n" + " cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw.instance_count, 1)," + " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n" + "} else {\n" + " cmd.draw_primitives((primitive_type)command_data.primitive_type," + " arg.draw.start_vertex_location," + " arg.draw.vertex_count_per_instance, arg.draw.instance_count," + " arg.draw.start_instance_location);\n" + "}\n"; break; } case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: { @@ -225,19 +279,39 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable(ib) + arg.draw_indexed.start_index_location, " - "arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location, " - "arg.draw_indexed.start_instance_location);\n"; - source << "} else {\n"; - source << "cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type, " - "arg.draw_indexed.index_count_per_instance, " - "reinterpret_cast(ib) + arg.draw_indexed.start_index_location, " - "arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location, " - "arg.draw_indexed.start_instance_location);\n"; - source << "}\n"; + source + << "if (is_mesh_emulated) {\n" + " dyn_ib_args->vertex_per_instance = arg.draw_indexed.index_count_per_instance;\n" + " dyn_ib_args->instance_count = arg.draw_indexed.instance_count;\n" + " dyn_ib_args->start_vertex = arg.draw_indexed.start_index_location;\n" + " dyn_ib_args->base_vertex = arg.draw_indexed.base_vertex_location;\n" + " dyn_ib_args->start_instance = arg.draw_indexed.start_instance_location;\n" + " dyn_ib_args->index_format = command_data.index_buffer_format;\n" + " dyn_ib_args->index_buffer = ib;\n" + "}\n" + "if (is_geometry) {\n" + " uint warp_count = (arg.draw_indexed.index_count_per_instance - 1) / command_data.mesh_arg2 + 1;\n" + " cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw_indexed.instance_count, 1), " + " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n" + "} else if (is_tessellation) {\n" + " uint patch_per_instance = arg.draw_indexed.index_count_per_instance / command_data.mesh_arg1;\n" + " uint patch_per_group = 32 / command_data.mesh_arg2;\n" + " uint patch_per_object = (patch_per_instance - 1) / patch_per_group + 1;\n" + " cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw_indexed.instance_count, 1), " + " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n" + "} else if (ib32bit) {\n" + " cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type," + " arg.draw_indexed.index_count_per_instance," + " reinterpret_cast(ib) + arg.draw_indexed.start_index_location," + " arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location," + " arg.draw_indexed.start_instance_location);\n" + "} else {\n" + " cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type," + " arg.draw_indexed.index_count_per_instance," + " reinterpret_cast(ib) + arg.draw_indexed.start_index_location," + " arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location," + " arg.draw_indexed.start_instance_location);\n" + "}\n"; break; } case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: { From 25b8f19c295f90b450b5e8b9ec3474d8fad8d5f0 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 16 Nov 2026 18:35:06 +0800 Subject: [PATCH 07/20] fix(dxmt): use 3d thread coordinate for kernel `cs_clear_texture3d_*` Signed-off-by: Feifan He --- src/dxmt/dxmt_command.metal | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/dxmt/dxmt_command.metal b/src/dxmt/dxmt_command.metal index 516f49e29..9525b1fb5 100644 --- a/src/dxmt/dxmt_command.metal +++ b/src/dxmt/dxmt_command.metal @@ -564,13 +564,10 @@ struct DXMTClearUintMetadata { [[kernel]] void cs_clear_texture3d_float( texture3d tex [[texture(0)]], constant DXMTClearFloatMetadata& meta [[buffer(1)]], - uint2 pos [[thread_position_in_grid]] + uint3 pos [[thread_position_in_grid]] ) { - auto depth = tex.get_depth(); - for (uint i = 0; i < depth; i++) { - uint2 final_pos = meta.offset + pos; - tex.write(meta.value, uint3(final_pos.x, final_pos.y, i)); - } + uint2 final_pos = meta.offset + pos.xy; + tex.write(meta.value, uint3(final_pos.x, final_pos.y, pos.z)); } [[kernel]] void cs_clear_texture2d_uint( @@ -592,13 +589,10 @@ struct DXMTClearUintMetadata { [[kernel]] void cs_clear_texture3d_uint( texture3d tex [[texture(0)]], constant DXMTClearUintMetadata& meta [[buffer(1)]], - uint2 pos [[thread_position_in_grid]] + uint3 pos [[thread_position_in_grid]] ) { - auto depth = tex.get_depth(); - for (uint i = 0; i < depth; i++) { - uint2 final_pos = meta.offset + pos; - tex.write(meta.value, uint3(final_pos.x, final_pos.y, i)); - } + uint2 final_pos = meta.offset + pos.xy; + tex.write(meta.value, uint3(final_pos.x, final_pos.y, pos.z)); } [[kernel]] void cs_clear_tbuffer_float( From 4f9ecbef00841de845b03efbbd0b136607818cd8 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 16 Nov 2026 20:13:44 +0800 Subject: [PATCH 08/20] fix(d3d12): bail out of invalid draw command early Signed-off-by: Feifan He --- src/d3d12/d3d12_command_list.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 6886c5abf..97c9248b9 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -625,6 +625,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild Date: Mon, 16 Nov 2026 20:26:06 +0800 Subject: [PATCH 09/20] feat(d3d12): implement indirect mesh draw fallback of `ExecuteIndirect()` for geometry & tessellation pipeline An unpleasant thing to introduce, but mesh ICB is not supported on M1 & M2. Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 131 ++++++++++++------------- src/d3d12/d3d12_command_list.cpp | 90 +++++++++++++++++ src/d3d12/d3d12_command_signature.cpp | 133 ++++++++++++++++---------- src/d3d12/d3d12_device.cpp | 2 + src/d3d12/d3d12_device.hpp | 2 + 5 files changed, 239 insertions(+), 119 deletions(-) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index 94e9d38fd..b384c1cc6 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -242,95 +242,90 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( bool use_emulated_mesh = pPSO->is_geometry || pPSO->is_tess; bool encode_binding = use_emulated_mesh || pCmdSig->UpdateVertexBuffers || pCmdSig->UpdateIndexBuffer || pCmdSig->UpdateRootArguments; - WMTIndirectCommandBufferInfo info; - info.inherit_buffers = !encode_binding; - info.inherit_pso = 1; - info.inherit_cull_mode = 1; - info.inherit_fill_mode = 1; - info.inherit_front_facing = 1; - info.inherit_depth_bias = 1; - info.inherit_depth_clip_mode = 1; - info.inherit_depth_stencil_state = 1; - info.support_color_attachment_mapping = 0; - info.support_dynamic_attribute_stride = 0; - info.support_ray_tracing = 0; - info.type = use_emulated_mesh ? WMTIndirectCommandTypeDrawMeshThreadgroups - : pCmdSig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? WMTIndirectCommandTypeDrawIndexed - : WMTIndirectCommandTypeDraw; - info.max_vertex_buffer_binding = 31; - info.max_fragment_buffer_binding = 31; - info.max_object_buffer_binding = 31; - info.max_mesh_buffer_binding = 31; - info.max_kernel_buffer_binding = 0; - info.max_kernel_threadgroup_memory_binding = 0; - info.max_object_threadgroup_memory_binding = 0; - info.gpu_resource_id = 0; - - auto icb = device_->GetMTLDevice().newIndirectCommandBuffer(info, MaxCount, WMTResourceStorageModePrivate); auto [Ptr, Offset] = AllocateGPUHeap(sizeof(IndirectRenderCommandData), 16); auto data = reinterpret_cast(Ptr); - data->cmd_buf = info.gpu_resource_id; - data->max_count = MaxCount; uint32_t cmd_flags = 0; if (pPSO->is_geometry) cmd_flags |= kIndirectRenderCommandFlagIsGeometry; if (pPSO->is_tess) cmd_flags |= kIndirectRenderCommandFlagIsTessellation; - data->flags = cmd_flags; - { - // populated outside - data->max_count_buffer = 0; - data->argument_buffer = 0; - data->rootsig_qwords = 0; - data->rootsig_qwords_stride = 0; - data->static_samplers = 0; - data->vertex_buffer = 0; - data->vertex_argbuf_stride = 0; - data->primitive_type = 0; - data->index_buffer = 0; - data->index_buffer_format = {}; - data->dyn_ib_args = 0; - data->vertex_increment_per_warp = 0; - data->vertex_per_warp = 0; - } + data->cmd_buf = 0; + data->max_count = MaxCount; + data->max_count_buffer = 0; + data->argument_buffer = 0; + data->rootsig_qwords = 0; + data->rootsig_qwords_stride = 0; + data->static_samplers = 0; + data->vertex_buffer = 0; + data->vertex_argbuf_stride = 0; + data->primitive_type = 0; + data->index_buffer = 0; + data->index_buffer_format = {}; + data->dyn_ib_args = 0; + data->flags = cmd_flags; + data->vertex_increment_per_warp = 0; + data->vertex_per_warp = 0; + + if (!use_emulated_mesh || device_->mesh_icb_supported) { + WMTIndirectCommandBufferInfo info; + info.inherit_buffers = !encode_binding; + info.inherit_pso = 1; + info.inherit_cull_mode = 1; + info.inherit_fill_mode = 1; + info.inherit_front_facing = 1; + info.inherit_depth_bias = 1; + info.inherit_depth_clip_mode = 1; + info.inherit_depth_stencil_state = 1; + info.support_color_attachment_mapping = 0; + info.support_dynamic_attribute_stride = 0; + info.support_ray_tracing = 0; + info.type = use_emulated_mesh ? WMTIndirectCommandTypeDrawMeshThreadgroups + : pCmdSig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? WMTIndirectCommandTypeDrawIndexed + : WMTIndirectCommandTypeDraw; + info.max_vertex_buffer_binding = 31; + info.max_fragment_buffer_binding = 31; + info.max_object_buffer_binding = 31; + info.max_mesh_buffer_binding = 31; + info.max_kernel_buffer_binding = 0; + info.max_kernel_threadgroup_memory_binding = 0; + info.max_object_threadgroup_memory_binding = 0; + info.gpu_resource_id = 0; + auto icb = device_->GetMTLDevice().newIndirectCommandBuffer(info, MaxCount, WMTResourceStorageModePrivate | WMTResourceHazardTrackingModeUntracked); + + data->cmd_buf = info.gpu_resource_id; - { auto &cmd_use_icb = EncodeRenderPrepassCommand(); cmd_use_icb.type = WMTComputeCommandUseResource; cmd_use_icb.usage = WMTResourceUsageRead | WMTResourceUsageWrite; cmd_use_icb.resource = icb; - auto &cmd_setpso_res = EncodeRenderPrepassCommand(); - cmd_setpso_res.type = WMTComputeCommandSetPSO; - cmd_setpso_res.pso = pCmdSig->resolver; - cmd_setpso_res.threadgroup_size = {32, 1, 1}; - - auto &cmd_argbuf_res = EncodeRenderPrepassCommand(); - cmd_argbuf_res.type = WMTComputeCommandSetBuffer; - cmd_argbuf_res.buffer = gpu_heap_buffer_; - cmd_argbuf_res.offset = Offset; - cmd_argbuf_res.index = 30; - - auto &cmd_draw_res = EncodeRenderPrepassCommand(); - cmd_draw_res.type = WMTComputeCommandDispatchThreads; - cmd_draw_res.size = {MaxCount, 1, 1}; + auto &cmd = EncodeRenderCommand(); + cmd.type = WMTRenderCommandExecuteCommandsInBuffer; + cmd.indirect_command_buffer = icb; + cmd.location = 0; + cmd.length = MaxCount; - auto &cmd_setpso = EncodeRenderCommand(); - cmd_setpso.type = WMTRenderCommandSetPSO; - cmd_setpso.pso = pPSO->GetRenderPipelineVariant(Topology); + icb_.push_back(std::move(icb)); } - auto &cmd = EncodeRenderCommand(); - cmd.type = WMTRenderCommandExecuteCommandsInBuffer; - cmd.indirect_command_buffer = icb; - cmd.location = 0; - cmd.length = MaxCount; + auto &cmd_setpso_res = EncodeRenderPrepassCommand(); + cmd_setpso_res.type = WMTComputeCommandSetPSO; + cmd_setpso_res.pso = pCmdSig->resolver; + cmd_setpso_res.threadgroup_size = {32, 1, 1}; - icb_.push_back(std::move(icb)); + auto &cmd_argbuf_res = EncodeRenderPrepassCommand(); + cmd_argbuf_res.type = WMTComputeCommandSetBuffer; + cmd_argbuf_res.buffer = gpu_heap_buffer_; + cmd_argbuf_res.offset = Offset; + cmd_argbuf_res.index = 30; + + auto &cmd_draw_res = EncodeRenderPrepassCommand(); + cmd_draw_res.type = WMTComputeCommandDispatchThreads; + cmd_draw_res.size = {MaxCount, 1, 1}; return data; } diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 97c9248b9..c471eb515 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -1772,6 +1772,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildthreads_per_patch = pso_graphics_->tess_threads_per_patch; } if (status != DrawCallStatus::Ordinary) { + if (!device_->mesh_icb_supported) + return ExecuteIndirectMeshUnroll(cmd, MaxCommandCount); auto [Unused, Offset] = allocator_->AllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS) * MaxCommandCount, 32); cmd->dyn_ib_args = allocator_->gpu_heap_buffer_address_ + Offset; } @@ -1787,6 +1789,94 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildvertex_argbuf_stride = VBStride; }; + void + ExecuteIndirectMeshUnroll(IndirectRenderCommandData *cmd, UINT MaxCommandCount) { + auto [_, IBArgOffset] = allocator_->AllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS) * MaxCommandCount, 32); + cmd->dyn_ib_args = allocator_->gpu_heap_buffer_address_ + IBArgOffset; + auto [__, DrawArgOffset] = allocator_->AllocateGPUHeap(sizeof(D3D12_DISPATCH_ARGUMENTS) * MaxCommandCount, 32); + cmd->static_samplers = allocator_->gpu_heap_buffer_address_ + DrawArgOffset; + auto RAOffset = EncodeRootArgument(rootsig_graphics_.ptr(), rootarg_graphics_staging_, MaxCommandCount); + cmd->rootsig_qwords = RAOffset; + cmd->rootsig_qwords += allocator_->gpu_heap_buffer_address_; + cmd->rootsig_qwords_stride = rootsig_graphics_->UploadQwords; + auto [VBOffset, VBStride] = PopulateVertexBufferTable(MaxCommandCount); + cmd->vertex_buffer = allocator_->gpu_heap_buffer_address_ + VBOffset; + cmd->vertex_argbuf_stride = VBStride; + + { + auto SSOffset = EncodeStaticSamplers(rootsig_graphics_.ptr()); + auto &cmd_fsargbuf = allocator_->EncodeRenderCommand(); + cmd_fsargbuf.type = WMTRenderCommandSetFragmentBuffer; + cmd_fsargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_fsargbuf.offset = SSOffset; + cmd_fsargbuf.index = SM50_BINDING_INDEX_STATIC_SAMPLERS; + auto &cmd_osargbuf = allocator_->EncodeRenderCommand(); + cmd_osargbuf.type = WMTRenderCommandSetObjectBuffer; + cmd_osargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_osargbuf.offset = SSOffset; + cmd_osargbuf.index = SM50_BINDING_INDEX_STATIC_SAMPLERS; + auto &cmd_msargbuf = allocator_->EncodeRenderCommand(); + cmd_msargbuf.type = WMTRenderCommandSetMeshBuffer; + cmd_msargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_msargbuf.offset = SSOffset; + cmd_msargbuf.index = SM50_BINDING_INDEX_STATIC_SAMPLERS; + } + + for (unsigned i = 0; i < MaxCommandCount; i++) { + + auto IBArgOffsetLocal = IBArgOffset + i * sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS); + auto VBOffsetLocal = VBOffset + i * VBStride; + auto RAOffsetLocal = RAOffset + i * sizeof(uint64_t) * rootsig_graphics_->UploadQwords; + + auto &cmd_osvb = allocator_->EncodeRenderCommand(); + cmd_osvb.type = WMTRenderCommandSetObjectBuffer; + cmd_osvb.buffer = allocator_->gpu_heap_buffer_; + cmd_osvb.offset = VBOffsetLocal; + cmd_osvb.index = SM50_BINDING_INDEX_VERTEX_BUFFER; + + auto &cmd_osdrawarg = allocator_->EncodeRenderCommand(); + cmd_osdrawarg.type = WMTRenderCommandSetObjectBuffer; + cmd_osdrawarg.buffer = allocator_->gpu_heap_buffer_; + cmd_osdrawarg.offset = IBArgOffsetLocal; + cmd_osdrawarg.index = SM50_BINDING_INDEX_DRAW_ARGUMENTS; + + auto &cmd_fsargbuf = allocator_->EncodeRenderCommand(); + cmd_fsargbuf.type = WMTRenderCommandSetFragmentBuffer; + cmd_fsargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_fsargbuf.offset = RAOffsetLocal; + cmd_fsargbuf.index = SM50_BINDING_INDEX_ROOT_ARGUMENTS; + auto &cmd_osargbuf = allocator_->EncodeRenderCommand(); + cmd_osargbuf.type = WMTRenderCommandSetObjectBuffer; + cmd_osargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_osargbuf.offset = RAOffsetLocal; + cmd_osargbuf.index = SM50_BINDING_INDEX_ROOT_ARGUMENTS; + auto &cmd_msargbuf = allocator_->EncodeRenderCommand(); + cmd_msargbuf.type = WMTRenderCommandSetMeshBuffer; + cmd_msargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_msargbuf.offset = RAOffsetLocal; + cmd_msargbuf.index = SM50_BINDING_INDEX_ROOT_ARGUMENTS; + + auto &cmd_mesh = allocator_->EncodeRenderCommand(); + cmd_mesh.type = WMTRenderCommandDrawMeshThreadgroupsIndirect; + cmd_mesh.indirect_args_buffer = allocator_->gpu_heap_buffer_; + cmd_mesh.indirect_args_offset = DrawArgOffset + i * sizeof(D3D12_DISPATCH_ARGUMENTS); + if (pso_graphics_->is_geometry) { + auto [vertex_per_warp, _] = get_gs_vertex_count(topology_); + cmd_mesh.object_threadgroup_size = {vertex_per_warp, 1, 1}; + cmd_mesh.mesh_threadgroup_size = {1, 1, 1}; + } else if (pso_graphics_->is_tess) { + auto PatchPerGroup = 32 / pso_graphics_->tess_threads_per_patch; + auto ThreadsPerPatch = pso_graphics_->tess_threads_per_patch; + cmd_mesh.object_threadgroup_size = {ThreadsPerPatch, PatchPerGroup, 1}; + cmd_mesh.mesh_threadgroup_size = {32, 1, 1}; + } else { + // unreachable + cmd_mesh.object_threadgroup_size = {0, 0, 0}; + cmd_mesh.mesh_threadgroup_size = {0, 0, 0}; + } + } + } + void STDMETHODCALLTYPE AtomicCopyBufferUINT( ID3D12Resource *pDstBuffer, UINT64 DstOffset, ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT Dependencies, diff --git a/src/d3d12/d3d12_command_signature.cpp b/src/d3d12/d3d12_command_signature.cpp index 967ec395a..ce756c736 100644 --- a/src/d3d12/d3d12_command_signature.cpp +++ b/src/d3d12/d3d12_command_signature.cpp @@ -116,6 +116,8 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageablemesh_icb_supported; + source << kSharedHeader; source << "struct __attribute__ ((packed)) d3d12_arguments {\n"; @@ -199,10 +201,20 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12PageableByteStride << ")[0];\n"; if (is_compute) { source << "compute_command cmd(command_data.cmd_buf, i);\n"; + source << "cmd.reset();\n"; } else { + source << "bool is_geometry = command_data.flags & " << kIndirectRenderCommandFlagIsGeometry << ";\n"; + source << "bool is_tessellation = command_data.flags & " << kIndirectRenderCommandFlagIsTessellation << ";\n"; + source << "bool is_mesh_emulated = is_geometry || is_tessellation;\n"; source << "render_command cmd(command_data.cmd_buf, i);\n"; + if (mesh_icb_supported) { + source << "cmd.reset();\n"; + } else { + source + << "auto device & mesh_args = reinterpret_cast(command_data.static_samplers)[i];\n"; + source << "if (!is_mesh_emulated) { cmd.reset(); } else { mesh_args = 0; }\n"; + } } - source << "cmd.reset();\n"; source << "if (i >= count) return;\n"; source << "device ulong * rootsig_qwords = command_data.rootsig_qwords + " "(i * command_data.rootsig_qwords_stride);\n"; @@ -211,10 +223,10 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable(command_data.vertex_buffer + " "(i * command_data.vertex_argbuf_stride));\n"; source << "device dxmt_dynamic_ib_arguments * dyn_ib_args = &command_data.dyn_ib_args[i];\n"; - source << "bool is_geometry = command_data.flags & " << kIndirectRenderCommandFlagIsGeometry << ";\n"; - source << "bool is_tessellation = command_data.flags & " << kIndirectRenderCommandFlagIsTessellation << ";\n"; - source << "bool is_mesh_emulated = is_geometry || is_tessellation;\n"; - source << "if (is_mesh_emulated) {\n"; + if (mesh_icb_supported) + source << "if (is_mesh_emulated) {\n"; + else + source << "if (0) {\n"; source << "cmd.set_object_buffer(vertex_buffer," << SM50_BINDING_INDEX_VERTEX_BUFFER << ");\n"; source << "cmd.set_object_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_object_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; @@ -246,32 +258,41 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12PageablepArgumentDescs[i]; switch (arg.Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: { - source - << "if (is_mesh_emulated) {\n" - " dyn_ib_args->vertex_per_instance = arg.draw.vertex_count_per_instance;\n" - " dyn_ib_args->instance_count = arg.draw.instance_count;\n" - " dyn_ib_args->start_vertex = arg.draw.start_vertex_location;\n" - " dyn_ib_args->base_vertex = 0;\n" - " dyn_ib_args->start_instance = arg.draw.start_instance_location;\n" - " dyn_ib_args->index_format = 0;\n" - " dyn_ib_args->index_buffer = 0;\n" - "}\n" - "if (is_geometry) {\n" - " uint warp_count = (arg.draw.vertex_count_per_instance - 1) / command_data.mesh_arg2 + 1;\n" - " cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw.instance_count, 1)," - " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n" - "} else if (is_tessellation) {\n" - " uint patch_per_instance = arg.draw.vertex_count_per_instance / command_data.mesh_arg1;\n" - " uint patch_per_group = 32 / command_data.mesh_arg2;\n" - " uint patch_per_object = (patch_per_instance - 1) / patch_per_group + 1;\n" - " cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw.instance_count, 1)," - " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n" - "} else {\n" - " cmd.draw_primitives((primitive_type)command_data.primitive_type," - " arg.draw.start_vertex_location," - " arg.draw.vertex_count_per_instance, arg.draw.instance_count," - " arg.draw.start_instance_location);\n" - "}\n"; + source << "if (is_mesh_emulated) {\n" + " dyn_ib_args->vertex_per_instance = arg.draw.vertex_count_per_instance;\n" + " dyn_ib_args->instance_count = arg.draw.instance_count;\n" + " dyn_ib_args->start_vertex = arg.draw.start_vertex_location;\n" + " dyn_ib_args->base_vertex = 0;\n" + " dyn_ib_args->start_instance = arg.draw.start_instance_location;\n" + " dyn_ib_args->index_format = 0;\n" + " dyn_ib_args->index_buffer = 0;\n" + "}\n" + "if (is_geometry) {\n" + " uint warp_count = arg.draw.vertex_count_per_instance" + " ? (arg.draw.vertex_count_per_instance - 1) / command_data.mesh_arg2 + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw.instance_count, 1)," + " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n"; + else + source << "mesh_args = uint3(warp_count, arg.draw.instance_count, 1);\n"; + source << "} else if (is_tessellation) {\n" + " uint patch_per_instance = arg.draw.vertex_count_per_instance / command_data.mesh_arg1;\n" + " uint patch_per_group = 32 / command_data.mesh_arg2;\n" + " uint patch_per_object = patch_per_instance" + " ? (patch_per_instance - 1) / patch_per_group + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw.instance_count, 1)," + " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n"; + else + source << "mesh_args = uint3(patch_per_object, arg.draw.instance_count, 1);\n"; + source << "} else {\n" + " cmd.draw_primitives((primitive_type)command_data.primitive_type," + " arg.draw.start_vertex_location," + " arg.draw.vertex_count_per_instance, arg.draw.instance_count," + " arg.draw.start_instance_location);\n" + "}\n"; break; } case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: { @@ -279,27 +300,37 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageablevertex_per_instance = arg.draw_indexed.index_count_per_instance;\n" + " dyn_ib_args->instance_count = arg.draw_indexed.instance_count;\n" + " dyn_ib_args->start_vertex = arg.draw_indexed.start_index_location;\n" + " dyn_ib_args->base_vertex = arg.draw_indexed.base_vertex_location;\n" + " dyn_ib_args->start_instance = arg.draw_indexed.start_instance_location;\n" + " dyn_ib_args->index_format = command_data.index_buffer_format;\n" + " dyn_ib_args->index_buffer = ib;\n" + "}\n" + "if (is_geometry) {\n" + " uint warp_count = arg.draw_indexed.index_count_per_instance" + " ? (arg.draw_indexed.index_count_per_instance - 1) / command_data.mesh_arg2 + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw_indexed.instance_count, 1), " + " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n"; + else + source << "mesh_args = uint3(warp_count, arg.draw_indexed.instance_count, 1);\n"; + source << "} else if (is_tessellation) {\n" + " uint patch_per_instance = arg.draw_indexed.index_count_per_instance / command_data.mesh_arg1;\n" + " uint patch_per_group = 32 / command_data.mesh_arg2;\n" + " uint patch_per_object = patch_per_instance" + " ? (patch_per_instance - 1) / patch_per_group + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw_indexed.instance_count, 1), " + " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n"; + else + source << "mesh_args = uint3(patch_per_object, arg.draw_indexed.instance_count, 1);\n"; source - << "if (is_mesh_emulated) {\n" - " dyn_ib_args->vertex_per_instance = arg.draw_indexed.index_count_per_instance;\n" - " dyn_ib_args->instance_count = arg.draw_indexed.instance_count;\n" - " dyn_ib_args->start_vertex = arg.draw_indexed.start_index_location;\n" - " dyn_ib_args->base_vertex = arg.draw_indexed.base_vertex_location;\n" - " dyn_ib_args->start_instance = arg.draw_indexed.start_instance_location;\n" - " dyn_ib_args->index_format = command_data.index_buffer_format;\n" - " dyn_ib_args->index_buffer = ib;\n" - "}\n" - "if (is_geometry) {\n" - " uint warp_count = (arg.draw_indexed.index_count_per_instance - 1) / command_data.mesh_arg2 + 1;\n" - " cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw_indexed.instance_count, 1), " - " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n" - "} else if (is_tessellation) {\n" - " uint patch_per_instance = arg.draw_indexed.index_count_per_instance / command_data.mesh_arg1;\n" - " uint patch_per_group = 32 / command_data.mesh_arg2;\n" - " uint patch_per_object = (patch_per_instance - 1) / patch_per_group + 1;\n" - " cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw_indexed.instance_count, 1), " - " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n" - "} else if (ib32bit) {\n" + << "} else if (ib32bit) {\n" " cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type," " arg.draw_indexed.index_count_per_instance," " reinterpret_cast(ib) + arg.draw_indexed.start_index_location," diff --git a/src/d3d12/d3d12_device.cpp b/src/d3d12/d3d12_device.cpp index 039c10658..4610f7285 100644 --- a/src/d3d12/d3d12_device.cpp +++ b/src/d3d12/d3d12_device.cpp @@ -71,6 +71,8 @@ class MTLD3D12DeviceImpl : public MTLD3D12Object> { info.depth_compare_function = WMTCompareFunctionAlways; default_depth_stencil_state = GetMTLDevice().newDepthStencilState(info); + mesh_icb_supported = GetMTLDevice().supportsFamily(WMTGPUFamilyApple9); + return S_OK; }; diff --git a/src/d3d12/d3d12_device.hpp b/src/d3d12/d3d12_device.hpp index d2172d2c2..c7ee9be66 100644 --- a/src/d3d12/d3d12_device.hpp +++ b/src/d3d12/d3d12_device.hpp @@ -193,6 +193,8 @@ class MTLD3D12Device : public ID3D12Device4 { EventListener event_listener; WMT::Reference default_depth_stencil_state; + + bool mesh_icb_supported; }; HRESULT From 569f44aa78159c57970a9397a2d2e1994d28f6cf Mon Sep 17 00:00:00 2001 From: Feifan He Date: Thu, 19 Nov 2026 17:16:23 +0800 Subject: [PATCH 10/20] refactor(d3d12): explicitly intialize `*EncoderData` data members Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 22 +-------- src/d3d12/d3d12_command_encoder.hpp | 66 +++++++++++++++++++-------- src/d3d12/d3d12_command_list.cpp | 24 +--------- 3 files changed, 51 insertions(+), 61 deletions(-) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index b384c1cc6..956654e4f 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -349,11 +349,7 @@ template <> void SimpleCommandContext::startComputePass() { ctx.InvalidateCurrentPass(); - auto compute = ctx.AllocatePass(); - compute->type = EncoderType::Compute; - compute->cmd_head.type = WMTComputeCommandNop; - compute->cmd_head.next.set(0); - compute->cmd_tail = (wmtcmd_base *)&compute->cmd_head; + ctx.AllocatePass(); } template <> @@ -439,21 +435,7 @@ template <> void SimpleCommandContext::startRenderPass() { ctx.InvalidateCurrentPass(); - auto render = ctx.AllocatePass(); - render->type = EncoderType::Render; - render->cmd_head.type = WMTRenderCommandNop; - render->cmd_head.next.set(0); - render->cmd_tail = (wmtcmd_base *)&render->cmd_head; - render->cmd_prepass_head.type = WMTComputeCommandNop; - render->cmd_prepass_head.next.set(0); - render->cmd_prepass_tail = (wmtcmd_base *)&render->cmd_prepass_head; - render->dsv_planar_flags = 0; - render->dsv_readonly_flags = 0; - render->render_target_count = 0; - render->render_target_width = 16384; - render->render_target_height = 16384; - render->render_target_array_length = 0; - render->default_raster_sample_count = 1; + ctx.AllocatePass(); } template <> diff --git a/src/d3d12/d3d12_command_encoder.hpp b/src/d3d12/d3d12_command_encoder.hpp index 4548887b2..1e2c725e1 100644 --- a/src/d3d12/d3d12_command_encoder.hpp +++ b/src/d3d12/d3d12_command_encoder.hpp @@ -35,7 +35,6 @@ enum class EncoderType { struct EncoderData { EncoderType type; EncoderData *next = nullptr; - uint64_t id; }; struct ClearEncoderData : EncoderData { @@ -44,13 +43,16 @@ struct ClearEncoderData : EncoderData { std::pair depth_stencil; }; TextureViewRef attachment; - unsigned clear_dsv; - unsigned array_length; - unsigned width; - unsigned height; - unsigned depth_plane; + unsigned clear_dsv = 0; + unsigned array_length = 0; + unsigned width = 0; + unsigned height = 0; + unsigned depth_plane = 0; - ClearEncoderData() {} + ClearEncoderData() { + type = EncoderType::Clear; + color = {0, 0, 0, 0}; + } }; struct RenderEncoderColorAttachmentData { @@ -88,37 +90,63 @@ struct RenderEncoderStencilAttachmentData { }; struct RenderEncoderData : EncoderData { - std::array colors; - RenderEncoderDepthAttachmentData depth; - RenderEncoderStencilAttachmentData stencil; - uint8_t default_raster_sample_count; - uint16_t render_target_array_length; - uint32_t render_target_height; - uint32_t render_target_width; + std::array colors{{}}; + RenderEncoderDepthAttachmentData depth{}; + RenderEncoderStencilAttachmentData stencil{}; + uint8_t default_raster_sample_count = 0; + uint16_t render_target_array_length = 0; + uint32_t render_target_height = 16384; + uint32_t render_target_width = 16384; wmtcmd_render_nop cmd_head; wmtcmd_base *cmd_tail; wmtcmd_compute_nop cmd_prepass_head; wmtcmd_base *cmd_prepass_tail; - uint8_t dsv_planar_flags; - uint8_t dsv_readonly_flags; - uint8_t render_target_count; + uint8_t dsv_planar_flags = 0; + uint8_t dsv_readonly_flags = 0; + uint8_t render_target_count = 0; bool use_visibility_result = 0; - bool use_tessellation = 0; - bool use_geometry = 0; + + RenderEncoderData() { + type = EncoderType::Render; + cmd_head.type = WMTRenderCommandNop; + cmd_head.next.set(nullptr); + cmd_tail = (wmtcmd_base *)&cmd_head; + cmd_prepass_head.type = WMTComputeCommandNop; + cmd_prepass_head.next.set(nullptr); + cmd_prepass_tail = (wmtcmd_base *)&cmd_prepass_head; + } }; struct BlitEncoderData : EncoderData { wmtcmd_blit_nop cmd_head; wmtcmd_base *cmd_tail; + + BlitEncoderData() { + type = EncoderType::Blit; + cmd_head.type = WMTBlitCommandNop; + cmd_head.next.set(0); + cmd_tail = (wmtcmd_base *)&cmd_head; + } }; struct ComputeEncoderData : EncoderData { wmtcmd_compute_nop cmd_head; wmtcmd_base *cmd_tail; + + ComputeEncoderData() { + type = EncoderType::Compute; + cmd_head.type = WMTComputeCommandNop; + cmd_head.next.set(0); + cmd_tail = (wmtcmd_base *)&cmd_head; + } }; struct ResolveEncoderData : EncoderData { TextureViewRef src; TextureViewRef dst; + + ResolveEncoderData() { + type = EncoderType::Resolve; + } }; }; // namespace dxmt diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index c471eb515..11115667d 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -377,15 +377,6 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); auto render = allocator_->AllocatePass(); - render->type = EncoderType::Render; - render->cmd_head.type = WMTRenderCommandNop; - render->cmd_head.next.set(0); - render->cmd_tail = (wmtcmd_base *)&render->cmd_head; - render->cmd_prepass_head.type = WMTComputeCommandNop; - render->cmd_prepass_head.next.set(0); - render->cmd_prepass_tail = (wmtcmd_base *)&render->cmd_prepass_head; - render->dsv_planar_flags = 0; - render->dsv_readonly_flags = 0; render->render_target_count = num_rtvs; unsigned render_target_width = 16384, render_target_height = 16384, render_target_array_length = 0; @@ -810,11 +801,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Compute) { allocator_->InvalidateCurrentPass(); - auto compute = allocator_->AllocatePass(); - compute->type = EncoderType::Compute; - compute->cmd_head.type = WMTComputeCommandNop; - compute->cmd_head.next.set(0); - compute->cmd_tail = (wmtcmd_base *)&compute->cmd_head; + allocator_->AllocatePass(); dirty_state_.set(DirtyState::ComputeRootArguments, DirtyState::ComputeRootSignature); dirty_state_.set(DirtyState::ComputePipelineState); } @@ -871,11 +858,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Blit) { allocator_->InvalidateCurrentPass(); - auto render = allocator_->AllocatePass(); - render->type = EncoderType::Blit; - render->cmd_head.type = WMTBlitCommandNop; - render->cmd_head.next.set(0); - render->cmd_tail = (wmtcmd_base *)&render->cmd_head; + allocator_->AllocatePass(); } return true; } @@ -1161,7 +1144,6 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); auto resolve = allocator_->AllocatePass(); - resolve->type = EncoderType::Resolve; MTL_DXGI_FORMAT_DESC format_desc; if (FAILED(MTLQueryDXGIFormat(device_->GetMTLDevice(), Format, format_desc))) { @@ -1513,7 +1495,6 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); auto encoder_info = allocator_->AllocatePass(); - encoder_info->type = EncoderType::Clear; encoder_info->clear_dsv = CheckedFlags; encoder_info->depth_stencil = {Depth, Stencil}; encoder_info->attachment = AttachmentDesc.Texture->view(AttachmentDesc.View); @@ -1553,7 +1534,6 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); auto encoder_info = allocator_->AllocatePass(); - encoder_info->type = EncoderType::Clear; encoder_info->clear_dsv = 0; encoder_info->color = {Color[0], Color[1], Color[2], Color[3]}; SanitizeRTVClearColor(AttachmentDesc.Texture->pixelFormat(AttachmentDesc.View), encoder_info->color); From c064ab1785c4f727d02b5f93973c9eab17e7c8c3 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Thu, 19 Nov 2026 17:51:24 +0800 Subject: [PATCH 11/20] refactor(d3d12): track pass boundary in command list Previously a pass is managed by command allocator, and it becomes awkward when we need to perform certain logic on pass start/end. `SimpleCommandContext` can also create a pass but that should be agnostic to command list, and the pass is transient. Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 2 - src/d3d12/d3d12_command_allocator.hpp | 4 +- src/d3d12/d3d12_command_list.cpp | 63 ++++++++++++++++++--------- 3 files changed, 44 insertions(+), 25 deletions(-) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index 956654e4f..cbf9a85de 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -348,7 +348,6 @@ SimpleCommandContext::getComputePipeline(std::stri template <> void SimpleCommandContext::startComputePass() { - ctx.InvalidateCurrentPass(); ctx.AllocatePass(); } @@ -434,7 +433,6 @@ SimpleCommandContext::getDefaultLibrary() { template <> void SimpleCommandContext::startRenderPass() { - ctx.InvalidateCurrentPass(); ctx.AllocatePass(); } diff --git a/src/d3d12/d3d12_command_allocator.hpp b/src/d3d12/d3d12_command_allocator.hpp index 81c5d83a5..8f92a670a 100644 --- a/src/d3d12/d3d12_command_allocator.hpp +++ b/src/d3d12/d3d12_command_allocator.hpp @@ -155,10 +155,9 @@ class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable T * AllocatePass() { + assert(!encoder_current); auto p = (new (AllocateCPUHeap(sizeof(T), alignof(T))) T()); encoder_current = p; return p; diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 11115667d..d2c2f402a 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -195,6 +195,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild allocator_; + EncoderType list_current_encoder_type_ = EncoderType::Null; + /* state */ Flags dirty_state_; @@ -325,6 +327,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild::max()) return E_FAIL; + EndCommandListPass(); return allocator_->EndRecord(&encoder_count); }; @@ -337,10 +340,31 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); + EndCommandListPass(); ResetState(pPipelineState); }; + void + EndCommandListPass() { + assert((list_current_encoder_type_ == EncoderType::Null) ^ !!allocator_->encoder_current); + assert(!allocator_->encoder_current || allocator_->encoder_current->type == list_current_encoder_type_); + + if (list_current_encoder_type_ != EncoderType::Null) { + list_current_encoder_type_ = EncoderType::Null; + allocator_->InvalidateCurrentPass(); + } + } + + template + EncoderDataType * + StartCommandListPass() { + if (list_current_encoder_type_ != EncoderType::Null) + EndCommandListPass(); + auto encoder = allocator_->AllocatePass(); + list_current_encoder_type_ = encoder->type; + return encoder; + } + std::tuple PopulateVertexBufferTable(uint32_t Count) { auto slot_mask = pso_graphics_ ? pso_graphics_->slot_mask : 0; @@ -373,10 +397,9 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Render) { + if (list_current_encoder_type_ != EncoderType::Render) { - allocator_->InvalidateCurrentPass(); - auto render = allocator_->AllocatePass(); + auto render = StartCommandListPass(); render->render_target_count = num_rtvs; unsigned render_target_width = 16384, render_target_height = 16384, render_target_array_length = 0; @@ -799,9 +822,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Compute) { - allocator_->InvalidateCurrentPass(); - allocator_->AllocatePass(); + if (list_current_encoder_type_ != EncoderType::Compute) { + StartCommandListPass(); dirty_state_.set(DirtyState::ComputeRootArguments, DirtyState::ComputeRootSignature); dirty_state_.set(DirtyState::ComputePipelineState); } @@ -856,9 +878,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Blit) { - allocator_->InvalidateCurrentPass(); - allocator_->AllocatePass(); + if (list_current_encoder_type_ != EncoderType::Blit) { + StartCommandListPass(); } return true; } @@ -1142,8 +1163,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); - auto resolve = allocator_->AllocatePass(); + auto resolve = StartCommandListPass(); MTL_DXGI_FORMAT_DESC format_desc; if (FAILED(MTLQueryDXGIFormat(device_->GetMTLDevice(), Format, format_desc))) { @@ -1176,7 +1196,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildsrc = src->view(src_view); resolve->dst = dst->view(dst_view); } - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); }; void STDMETHODCALLTYPE @@ -1455,7 +1475,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); + EndCommandListPass(); num_rtvs = NumRTV; for (unsigned i = 0; i < NumRTV; i++) { @@ -1479,6 +1499,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.begin(AttachmentDesc.Texture, AttachmentDesc.View, 0, CheckedFlags); for (unsigned i = 0; i < RectCount; i++) { auto rect = Rects[i]; @@ -1493,8 +1514,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.end(); return; } - allocator_->InvalidateCurrentPass(); - auto encoder_info = allocator_->AllocatePass(); + auto encoder_info = StartCommandListPass(); encoder_info->clear_dsv = CheckedFlags; encoder_info->depth_stencil = {Depth, Stencil}; encoder_info->attachment = AttachmentDesc.Texture->view(AttachmentDesc.View); @@ -1503,7 +1523,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildheight = AttachmentDesc.Height; encoder_info->depth_plane = 0; - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); }; void STDMETHODCALLTYPE @@ -1515,6 +1535,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.begin(AttachmentDesc.Texture, AttachmentDesc.View, AttachmentDesc.DepthPlane); for (unsigned i = 0; i < RectCount; i++) { auto rect = Rects[i]; @@ -1532,8 +1553,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.end(); return; } - allocator_->InvalidateCurrentPass(); - auto encoder_info = allocator_->AllocatePass(); + auto encoder_info = StartCommandListPass(); encoder_info->clear_dsv = 0; encoder_info->color = {Color[0], Color[1], Color[2], Color[3]}; SanitizeRTVClearColor(AttachmentDesc.Texture->pixelFormat(AttachmentDesc.View), encoder_info->color); @@ -1542,8 +1562,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildwidth = AttachmentDesc.Width; encoder_info->height = AttachmentDesc.Height; encoder_info->depth_plane = AttachmentDesc.DepthPlane; - - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); }; void STDMETHODCALLTYPE @@ -1555,6 +1574,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildGetDescriptor(Index); auto color = std::array({Values[0], Values[1], Values[2], Values[3]}); D3D12_RECT full_rect; + EndCommandListPass(); switch (Descriptor.type) { case ShaderVisibleDescriptorType::UAVBuffer: { allocator_->clear_uav_.begin(color, Descriptor.UAVBuffer.buffer); @@ -1609,6 +1629,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildGetDescriptor(Index); auto color = std::array({Values[0], Values[1], Values[2], Values[3]}); D3D12_RECT full_rect; + EndCommandListPass(); switch (Descriptor.type) { case ShaderVisibleDescriptorType::UAVBuffer: { allocator_->clear_uav_.begin(color, Descriptor.UAVBuffer.buffer); From 44ae9a62da8dedb63f50ec16ff0ac624438ef399 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 23 Nov 2026 17:54:35 +0800 Subject: [PATCH 12/20] feat(d3d12, dxmt): introduce occlusion query resolve encoder Signed-off-by: Feifan He --- src/d3d12/d3d12_command_allocator.cpp | 3 ++ src/d3d12/d3d12_command_encoder.hpp | 16 +++++++ src/d3d12/d3d12_command_list.cpp | 1 + src/d3d12/d3d12_command_queue.cpp | 60 +++++++++++++++++++++++++++ src/d3d12/d3d12_device.hpp | 1 + src/dxmt/dxmt_command.metal | 24 +++++++++++ 6 files changed, 105 insertions(+) diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index cbf9a85de..69c319ba3 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -134,6 +134,9 @@ MTLD3D12CommandAllocatorImpl::Reset() { case EncoderType::Resolve: reinterpret_cast(next)->~ResolveEncoderData(); break; + case EncoderType::OcclusionQueryResolve: + reinterpret_cast(next)->~OcclusionQueryResolveEncoderData(); + break; } next = next->next; } diff --git a/src/d3d12/d3d12_command_encoder.hpp b/src/d3d12/d3d12_command_encoder.hpp index 1e2c725e1..f7358976c 100644 --- a/src/d3d12/d3d12_command_encoder.hpp +++ b/src/d3d12/d3d12_command_encoder.hpp @@ -19,6 +19,7 @@ #pragma once #include "dxmt_texture.hpp" +#include "util_svector.hpp" #include namespace dxmt { @@ -30,6 +31,7 @@ enum class EncoderType { Blit, Compute, Resolve, + OcclusionQueryResolve, }; struct EncoderData { @@ -149,4 +151,18 @@ struct ResolveEncoderData : EncoderData { } }; +struct OcclusionQueryResolveInfo { + uint64_t visibility_offset_start; + uint64_t visibility_offset_end; + uint64_t resolve_dst; +}; + +struct OcclusionQueryResolveEncoderData : EncoderData { + small_vector info; + + OcclusionQueryResolveEncoderData() { + type = EncoderType::OcclusionQueryResolve; + } +}; + }; // namespace dxmt diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index d2c2f402a..688d7a9f7 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -293,6 +293,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild::max(); + visibility_result_count = 0; return allocator_->StartRecord(&entry); } diff --git a/src/d3d12/d3d12_command_queue.cpp b/src/d3d12/d3d12_command_queue.cpp index e36ba7bec..e8096474f 100644 --- a/src/d3d12/d3d12_command_queue.cpp +++ b/src/d3d12/d3d12_command_queue.cpp @@ -42,12 +42,15 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable queue_; WMT::Reference fence_; + WMT::Reference pso_occlusion_query_resolve_; + std::atomic_uint64_t inflight_cmdbuf_seq_ = 1; std::atomic_uint64_t inflight_cmdbuf_count_ = 0; std::atomic_uint64_t inflight_cmdbuf_stop_ = 0; struct InflightCommandBuffer { WMT::Reference cmdbuf{}; + small_vector, 1> visibility_buffers; HANDLE semaphore{}; }; @@ -141,6 +144,13 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable err; + auto occlusion_query_resolve_function = device_->GetLib().getLibrary().newFunction("cs_occlusion_query_resolve"); + pso_occlusion_query_resolve_ = metal_device.newComputePipelineState(occlusion_query_resolve_function, err); + + if (err || !pso_occlusion_query_resolve_) + return E_FAIL; + return S_OK; } @@ -203,6 +213,14 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable(ppCommandLists[i]); + WMT::Reference visibility_buffer; + if (pCommandList->visibility_result_count) { + WMTBufferInfo info; + info.length = pCommandList->visibility_result_count * sizeof(uint64_t); + info.memory.set(nullptr); + info.options = WMTResourceStorageModePrivate | WMTResourceHazardTrackingModeUntracked; + visibility_buffer = device_->GetMTLDevice().newBuffer(info); + } EncoderData *current = pCommandList->entry; while (current) { switch (current->type) { @@ -294,6 +312,8 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageablerender_target_array_length; render_pass_info.render_target_width = data->render_target_width; render_pass_info.render_target_height = data->render_target_height; + if (data->use_visibility_result) + render_pass_info.visibility_buffer = visibility_buffer; } if (data->cmd_prepass_tail->type != WMTComputeCommandNop) { auto encoder = cmdbuf.computeCommandEncoder(false); @@ -345,9 +365,49 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable(current); + auto encoder = cmdbuf.computeCommandEncoder(false); + encoder.waitForFence(fence_); + + { + wmtcmd_compute_setbytes cmd_setbytes; + cmd_setbytes.index = 0; + cmd_setbytes.bytes.set(data->info.data()); + cmd_setbytes.length = data->info.size() * sizeof(OcclusionQueryResolveInfo); + cmd_setbytes.type = WMTComputeCommandSetBytes; + + wmtcmd_compute_setbuffer cmd_setbuffer; + cmd_setbytes.next.set(&cmd_setbuffer); + cmd_setbuffer.type = WMTComputeCommandSetBuffer; + cmd_setbuffer.index = 1; + cmd_setbuffer.buffer = visibility_buffer; + cmd_setbuffer.offset = 0; + + wmtcmd_compute_setpso cmd_setpso; + cmd_setbuffer.next.set(&cmd_setpso); + cmd_setpso.type = WMTComputeCommandSetPSO; + cmd_setpso.threadgroup_size = {1, 1, 1}; + cmd_setpso.pso = pso_occlusion_query_resolve_; + + wmtcmd_compute_dispatch cmd_dispatch; + cmd_setpso.next.set(&cmd_dispatch); + cmd_dispatch.type = WMTComputeCommandDispatch; + cmd_dispatch.size = {data->info.size(), 1, 1}; + + cmd_dispatch.next.set(nullptr); + encoder.encodeCommands((wmtcmd_compute_nop *)&cmd_setbytes); + } + + encoder.updateFence(fence_); + encoder.endEncoding(); + break; + } } current = current->next; } + if (visibility_buffer) + scope.inflight.visibility_buffers.push_back(std::move(visibility_buffer)); } }; diff --git a/src/d3d12/d3d12_device.hpp b/src/d3d12/d3d12_device.hpp index c7ee9be66..9172326d4 100644 --- a/src/d3d12/d3d12_device.hpp +++ b/src/d3d12/d3d12_device.hpp @@ -44,6 +44,7 @@ class MTLD3D12GraphicsCommandList : public ID3D12GraphicsCommandList2 { public: EncoderData *entry; size_t encoder_count; + size_t visibility_result_count; }; class MTLD3D12CommandAllocator : public ID3D12CommandAllocator { diff --git a/src/dxmt/dxmt_command.metal b/src/dxmt/dxmt_command.metal index 9525b1fb5..c52a94959 100644 --- a/src/dxmt/dxmt_command.metal +++ b/src/dxmt/dxmt_command.metal @@ -647,3 +647,27 @@ struct DXMTClearUintMetadata { [[kernel]] void tile_barrier(ushort2 pos [[thread_position_in_threadgroup]]) { // empty } + +struct DXMTOcclusionQueryResolveInfo { + ulong visibility_offset_start; + ulong visibility_offset_end; + device ulong2 * resolve_dst; +}; + +[[kernel]] void cs_occlusion_query_resolve( + uint id [[threadgroup_position_in_grid]], + constant DXMTOcclusionQueryResolveInfo* infos [[buffer(0)]], + constant ulong* visibility_buffer [[buffer(1)]] +) { + constant auto& info = infos[id]; + if (info.visibility_offset_end <= info.visibility_offset_start) { + *info.resolve_dst = 0; + return; + } + ulong accum = 0; + for (auto i = info.visibility_offset_start; i < info.visibility_offset_end; i++) { + accum += visibility_buffer[i]; + } + *info.resolve_dst = ulong2(accum, !!accum); + return; +} \ No newline at end of file From 4920880a2bd049a30165933a02bc8b05bdeb0648 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 23 Nov 2026 18:00:19 +0800 Subject: [PATCH 13/20] feat(d3d12): allocate buffer for d3d12 query heap Signed-off-by: Feifan He --- src/d3d12/d3d12_device.hpp | 3 +++ src/d3d12/d3d12_query_heap.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/d3d12/d3d12_device.hpp b/src/d3d12/d3d12_device.hpp index 9172326d4..b714d2ea9 100644 --- a/src/d3d12/d3d12_device.hpp +++ b/src/d3d12/d3d12_device.hpp @@ -124,6 +124,9 @@ class MTLD3D12CommandSignature : public ID3D12CommandSignature { class MTLD3D12QueryHeap : public ID3D12QueryHeap { public: + WMT::Reference query_heap; + uint64_t query_heap_address; + size_t query_count; }; class MTLD3D12PipelineState : public ID3D12PipelineState { diff --git a/src/d3d12/d3d12_query_heap.cpp b/src/d3d12/d3d12_query_heap.cpp index 904c58f7b..75fef855b 100644 --- a/src/d3d12/d3d12_query_heap.cpp +++ b/src/d3d12/d3d12_query_heap.cpp @@ -27,9 +27,39 @@ class MTLD3D12QueryHeapImpl : public MTLD3D12Pageable { HRESULT Initialize(const D3D12_QUERY_HEAP_DESC *pDesc) { + query_count = pDesc->Count; + + /** + Two uint64_t are allocated for each occlusion query slot, one for binary occlusion. + We need to store both numerical and binary value because we implement `ResolveQueryData` as a blit, where + `D3D12_QUERY_TYPE` actually matters + */ + auto query_size = pDesc->Type == D3D12_QUERY_HEAP_TYPE_OCCLUSION ? sizeof(uint64_t) * 2 : sizeof(uint64_t); + + WMTBufferInfo info; + info.memory.set(nullptr); + info.length = query_size * query_count; + info.options = WMTResourceStorageModePrivate | WMTResourceHazardTrackingModeUntracked; + + query_heap = device_->GetMTLDevice().newBuffer(info); + + if (!query_heap) { + ERR("MTLD3D12QueryHeapImpl: failed to allocate query heap"); + return E_OUTOFMEMORY; + } + query_heap_address = info.gpu_address; + device_->RegisterResidency(query_heap); return S_OK; } + ~MTLD3D12QueryHeapImpl() { + if (query_heap) { + device_->UnregisterResidency(query_heap); + } + query_heap = {}; + query_heap_address = 0; + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { From 222725657479889b379c71d081bff666051d1358 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Mon, 23 Nov 2026 18:10:10 +0800 Subject: [PATCH 14/20] feat(d3d12): implement occlusion query Signed-off-by: Feifan He --- src/d3d12/d3d12_command_list.cpp | 122 ++++++++++++++++++++++++++-- src/d3d12/d3d12_occlusion_query.cpp | 105 ++++++++++++++++++++++++ src/d3d12/d3d12_occlusion_query.hpp | 41 ++++++++++ src/d3d12/meson.build | 1 + 4 files changed, 264 insertions(+), 5 deletions(-) create mode 100644 src/d3d12/d3d12_occlusion_query.cpp create mode 100644 src/d3d12/d3d12_occlusion_query.hpp diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 688d7a9f7..5d32bf51c 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -17,8 +17,10 @@ */ #include "d3d12_command_allocator.hpp" +#include "d3d12_occlusion_query.hpp" #include "com/com_pointer.hpp" #include "dxmt_format.hpp" +#include "dxmt_occlusion_query.hpp" namespace dxmt { @@ -233,6 +235,11 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild(pDevice) {} @@ -327,14 +334,26 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild::max()) - return E_FAIL; + return E_FAIL; // the command list has already been closed + + if (!occlusion_query_state_.Flush([this](auto info) { ResolveOcclusionQueryData(info); })) { + ERR("D3D12CommandList::Close(): exists outstanding `BeginQuery()` of occlusion queries"); + cmdlist_valid_ = false; + } + EndCommandListPass(); - return allocator_->EndRecord(&encoder_count); + visibility_result_count = vro_state_.reset(); + HRESULT hr = allocator_->EndRecord(&encoder_count); + if (!cmdlist_valid_) + return E_FAIL; + return hr; }; HRESULT STDMETHODCALLTYPE Reset(ID3D12CommandAllocator *pAllocator, ID3D12PipelineState *pInitialState) { if (encoder_count == std::numeric_limits::max()) + return E_FAIL; // still recording + if (!cmdlist_valid_) return E_FAIL; return Initialize(pAllocator, pInitialState); }; @@ -351,6 +370,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type == list_current_encoder_type_); if (list_current_encoder_type_ != EncoderType::Null) { + if (list_current_encoder_type_ == EncoderType::Render) + vro_state_.endEncoder(); list_current_encoder_type_ = EncoderType::Null; allocator_->InvalidateCurrentPass(); } @@ -363,6 +384,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildAllocatePass(); list_current_encoder_type_ = encoder->type; + if (list_current_encoder_type_ == EncoderType::Render) + vro_state_.beginEncoder(); return encoder; } @@ -650,6 +673,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildAllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS), 32); DXMT_DRAW_DYNAMIC_IB_ARGUMENTS *draw_argument = reinterpret_cast(Ptr); @@ -732,6 +756,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildAllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS), 32); DXMT_DRAW_DYNAMIC_IB_ARGUMENTS *draw_argument = reinterpret_cast(Ptr); @@ -1682,12 +1707,40 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild(pHeap), Index, vro_state_.getNextReadOffset() + )) { + ERR("D3D12CommandList::BeginQuery(): exists outstanding `BeginQuery()` of occlusion query at index ", Index); + cmdlist_valid_ = false; + } + break; + } + default: { + DEBUG("BeginQuery ", Type); + break; + } + } }; void STDMETHODCALLTYPE EndQuery(ID3D12QueryHeap *pHeap, D3D12_QUERY_TYPE Type, UINT Index) { - DEBUG("EndQuery"); + switch (Type) { + case D3D12_QUERY_TYPE_OCCLUSION: + case D3D12_QUERY_TYPE_BINARY_OCCLUSION: { + if (!occlusion_query_state_.End(static_cast(pHeap), Index, vro_state_.getNextReadOffset())) { + ERR("D3D12CommandList::EndQuery(): called without corresponding `BeginQuery()` at index ", Index); + cmdlist_valid_ = false; + } + break; + } + default: { + DEBUG("EndQuery ", Type); + break; + } + } }; void STDMETHODCALLTYPE @@ -1695,9 +1748,67 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild(pHeap); + OcclusionQueryResolveInfo info; + for (unsigned i = 0; i < QueryCount; i++) { + if (occlusion_query_state_.GetResolveInfo(heap, StartIndex + i, info)) { + if (~info.visibility_offset_start) + ResolveOcclusionQueryData(info); + } else { + ERR("D3D12CommandList::ResolveQueryData(): `BeginQuery()` without corresponding `EndQuery()` at index ", StartIndex + i); + cmdlist_valid_ = false; + } + } + + if (!PreBlit()) + return; + + auto Dst = static_cast(pDstBuffer); + for (unsigned i = 0; i < QueryCount; i++) { + auto &cmd_cp = allocator_->EncodeBlitCommand(); + cmd_cp.type = WMTBlitCommandCopyFromBufferToBuffer; + cmd_cp.src = heap->query_heap; + cmd_cp.dst = Dst->buffer->current()->buffer(); + cmd_cp.src_offset = sizeof(uint64_t) * ((StartIndex + i) * 2 + (Type == D3D12_QUERY_TYPE_BINARY_OCCLUSION)); + cmd_cp.dst_offset = AlignedDstBufferOffset + sizeof(uint64_t) * i; + cmd_cp.copy_length = sizeof(uint64_t); + } + + return; + } + DEBUG("ResolveQueryData ", Type); }; + void + BumpVisibilityResultOffset() { + assert(allocator_->encoder_current->type == EncoderType::Render); + auto encoder = static_cast(allocator_->encoder_current); + bool has_outstanding_query = occlusion_query_state_.HasOutstandingQuery(); + encoder->use_visibility_result = encoder->use_visibility_result || has_outstanding_query; + + uint64_t offset; + if (vro_state_.tryGetNextWriteOffset(has_outstanding_query, offset)) { + auto &cmd = allocator_->EncodeRenderCommand(); + cmd.type = WMTRenderCommandSetVisibilityMode; + if (~offset == 0) { + cmd.mode = WMTVisibilityResultModeDisabled; + cmd.offset = 0; + } else { + cmd.mode = WMTVisibilityResultModeCounting; + cmd.offset = offset * sizeof(uint64_t); + } + } + } + + void + ResolveOcclusionQueryData(OcclusionQueryResolveInfo const &info) { + if (list_current_encoder_type_ != EncoderType::OcclusionQueryResolve) + StartCommandListPass(); + auto encoder = static_cast(allocator_->encoder_current); + encoder->info.push_back(info); + } + void STDMETHODCALLTYPE SetPredication(ID3D12Resource *pBuffer, UINT64 AlignedBufferOffset, D3D12_PREDICATION_OP Op) { IMPLEMENT_ME }; @@ -1755,6 +1866,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildEncodeIndirectRenderCommand(sig, pso_graphics_.ptr(), MaxCommandCount, topology_); cmd->max_count_buffer = CountBufferAddress; cmd->argument_buffer = ArgBufferAddress; diff --git a/src/d3d12/d3d12_occlusion_query.cpp b/src/d3d12/d3d12_occlusion_query.cpp new file mode 100644 index 000000000..43d8f0320 --- /dev/null +++ b/src/d3d12/d3d12_occlusion_query.cpp @@ -0,0 +1,105 @@ +/* + * Copyright 2026 Feifan He for CodeWeavers + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include "d3d12_occlusion_query.hpp" + +namespace dxmt { + +bool +CommandListOcclusionQueryState::Begin(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset) { + + auto iter = queries_.find({pHeap, Index}); + if (iter != queries_.end()) { + auto &state = iter->second; + if (state.is_resolvable) { + DEBUG("BeginQuery: discarded unresolved data"); + state.is_resolvable = false; + state.offset_start = Offset; + return true; + } + // duplicated Begin() + return false; + } + OcclusionQueryState state; + state.offset_start = Offset; + state.offset_end = 0; + state.is_resolvable = false; + queries_.insert({{pHeap, Index}, state}); + return true; +} + +bool +CommandListOcclusionQueryState::End(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset) { + auto iter = queries_.find({pHeap, Index}); + if (iter == queries_.end()) { + // no Begin() + return false; + } + auto &state = iter->second; + state.offset_end = Offset; + state.is_resolvable = true; + return true; +} + +bool +CommandListOcclusionQueryState::GetResolveInfo( + MTLD3D12QueryHeap *pHeap, UINT Index, OcclusionQueryResolveInfo &InfoOut +) { + auto iter = queries_.find({pHeap, Index}); + if (iter == queries_.end()) { + InfoOut.visibility_offset_start = ~0ull; + InfoOut.visibility_offset_end = ~0ull; + InfoOut.resolve_dst = 0; + return true; + } + auto &state = iter->second; + if (state.is_resolvable) { + InfoOut.visibility_offset_start = state.offset_start; + InfoOut.visibility_offset_end = state.offset_end; + InfoOut.resolve_dst = pHeap->query_heap_address + Index * sizeof(uint64_t) * 2; + queries_.erase(iter); + return true; + } + // no End() + return false; +} + +bool +CommandListOcclusionQueryState::HasOutstandingQuery() { + return std::any_of(queries_.rbegin(), queries_.rend(), [](auto pair) { return !pair.second.is_resolvable; }); +} + +bool +CommandListOcclusionQueryState::Flush(std::function fn) { + std::erase_if(queries_, [fn = std::move(fn)](auto pair) { + auto &[heap, index] = pair.first; + auto &state = pair.second; + if (state.is_resolvable) { + OcclusionQueryResolveInfo InfoOut; + InfoOut.visibility_offset_start = state.offset_start; + InfoOut.visibility_offset_end = state.offset_end; + InfoOut.resolve_dst = heap->query_heap_address + index * sizeof(uint64_t) * 2; + fn(InfoOut); + return true; + } + return false; + }); + return queries_.size() == 0; +} + +} // namespace dxmt \ No newline at end of file diff --git a/src/d3d12/d3d12_occlusion_query.hpp b/src/d3d12/d3d12_occlusion_query.hpp new file mode 100644 index 000000000..491d0667c --- /dev/null +++ b/src/d3d12/d3d12_occlusion_query.hpp @@ -0,0 +1,41 @@ +/* + * Copyright 2026 Feifan He for CodeWeavers + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#pragma once +#include "d3d12_device.hpp" + +namespace dxmt { + +class CommandListOcclusionQueryState { + + struct OcclusionQueryState { + uint64_t offset_start = 0; + uint64_t offset_end = 0; + bool is_resolvable = false; + }; + + std::map, OcclusionQueryState> queries_; + +public: + bool Begin(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset); + bool End(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset); + bool GetResolveInfo(MTLD3D12QueryHeap *pHeap, UINT Index, OcclusionQueryResolveInfo &InfoOut); + bool HasOutstandingQuery(); + bool Flush(std::function fn); +}; +} // namespace dxmt diff --git a/src/d3d12/meson.build b/src/d3d12/meson.build index ce23ea65b..175fb703d 100644 --- a/src/d3d12/meson.build +++ b/src/d3d12/meson.build @@ -9,6 +9,7 @@ d3d12_src = [ 'd3d12_device.cpp', 'd3d12_fence.cpp', 'd3d12_heap.cpp', + 'd3d12_occlusion_query.cpp', 'd3d12_pipeline_compute.cpp', 'd3d12_pipeline_graphics.cpp', 'd3d12_query_heap.cpp', From 2198ae405e65cd7a65426658ff55e932a78d5069 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Tue, 24 Nov 2026 15:46:28 +0800 Subject: [PATCH 15/20] feat(d3d12): add `ID3D12Device5` stubs Signed-off-by: Feifan He --- src/d3d12/d3d12_device.cpp | 49 +++++++++++++++++++++++++++++++++++++- src/d3d12/d3d12_device.hpp | 2 +- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/d3d12/d3d12_device.cpp b/src/d3d12/d3d12_device.cpp index 4610f7285..ef399403e 100644 --- a/src/d3d12/d3d12_device.cpp +++ b/src/d3d12/d3d12_device.cpp @@ -106,7 +106,7 @@ class MTLD3D12DeviceImpl : public MTLD3D12Object> { if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12Device) || riid == __uuidof(ID3D12Device1) || riid == __uuidof(ID3D12Device2) || riid == __uuidof(ID3D12Device3) || - riid == __uuidof(ID3D12Device4)) { + riid == __uuidof(ID3D12Device4) || riid == __uuidof(ID3D12Device5)) { *ppvObject = ref(this); return S_OK; } @@ -1211,6 +1211,53 @@ class MTLD3D12DeviceImpl : public MTLD3D12Object> { return __ret; } + HRESULT STDMETHODCALLTYPE + CreateLifetimeTracker(ID3D12LifetimeOwner *pOwner, REFIID riid, void **ppTracker) { + return E_NOTIMPL; + } + + void STDMETHODCALLTYPE + RemoveDevice() {} + + HRESULT STDMETHODCALLTYPE + EnumerateMetaCommands(UINT *pCount, D3D12_META_COMMAND_DESC *pDescs) { + *pCount = 0; + return S_OK; + } + + HRESULT STDMETHODCALLTYPE + EnumerateMetaCommandParameters( + REFGUID id, D3D12_META_COMMAND_PARAMETER_STAGE Stage, UINT *pTotalSizeInBytes, UINT *pParameterCount, + D3D12_META_COMMAND_PARAMETER_DESC *pParameterDescs + ) { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE + CreateMetaCommand( + REFGUID id, UINT NodeMask, const void *pCreationParameters, SIZE_T SizeInBytes, REFIID riid, void **ppCommand + ) { + return DXGI_ERROR_UNSUPPORTED; + } + + HRESULT STDMETHODCALLTYPE + CreateStateObject(const D3D12_STATE_OBJECT_DESC *pDesc, REFIID riid, void **ppStateObject) { + return E_NOTIMPL; + } + + void STDMETHODCALLTYPE + GetRaytracingAccelerationStructurePrebuildInfo( + const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS *pDesc, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO *pInfo + ) {} + + D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS STDMETHODCALLTYPE + CheckDriverMatchingIdentifier( + D3D12_SERIALIZED_DATA_TYPE Type, const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER *pIdentifier + ) { + return D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED; + } + WMT::ResidencySet GetGlobalResidencySet() { return residency_set_; diff --git a/src/d3d12/d3d12_device.hpp b/src/d3d12/d3d12_device.hpp index b714d2ea9..b5ef8da5d 100644 --- a/src/d3d12/d3d12_device.hpp +++ b/src/d3d12/d3d12_device.hpp @@ -170,7 +170,7 @@ class MTLD3D12ComputePipelineState : public MTLD3D12PipelineState { virtual void ReleasePrivate() = 0; }; -class MTLD3D12Device : public ID3D12Device4 { +class MTLD3D12Device : public ID3D12Device5 { public: virtual WMT::Device GetMTLDevice() = 0; From 837753885df53b76a24e93179962dd4ebd618de9 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Wed, 25 Nov 2026 18:45:43 +0800 Subject: [PATCH 16/20] fix(airconv): set tessellation payload struct type packed So that `estimate_payload_size()` is accurate Signed-off-by: Feifan He --- src/airconv/airconv_public.h | 2 +- src/airconv/dxbc_converter_ts.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/airconv/airconv_public.h b/src/airconv/airconv_public.h index e8bf54aa6..bcce2ea4e 100644 --- a/src/airconv/airconv_public.h +++ b/src/airconv/airconv_public.h @@ -5,7 +5,7 @@ #ifndef __AIRCONV_H #define __AIRCONV_H -#define AIRCONV_VERSION 26 +#define AIRCONV_VERSION 27 #ifdef __cplusplus #include diff --git a/src/airconv/dxbc_converter_ts.cpp b/src/airconv/dxbc_converter_ts.cpp index 94a55c3a7..311d44e87 100644 --- a/src/airconv/dxbc_converter_ts.cpp +++ b/src/airconv/dxbc_converter_ts.cpp @@ -283,7 +283,7 @@ convert_dxbc_vertex_hull_shader( context, {hs_output_per_group_type, hs_pcout_per_group_scaler_type, types._int, llvm::ArrayType::get(types._int, max_workload_count * patch_per_group * size_workload_info / 4)}, - "payload" + "payload", true ); uint32_t payload_struct_size = module.getDataLayout().getTypeAllocSize(payload_struct_type); @@ -910,7 +910,7 @@ convert_dxbc_tesselator_domain_shader( context, {hs_output_per_group_type, hs_pcout_per_group_scaler_type, types._int, llvm::ArrayType::get(types._int, max_workload_count * patch_per_group * size_workload_info / 4)}, - "payload" + "payload", true ); uint32_t payload_struct_size = module.getDataLayout().getTypeAllocSize(payload_struct_type); From 583210c7b3e71a4f9441962940e91a93b0237a53 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Wed, 25 Nov 2026 18:48:26 +0800 Subject: [PATCH 17/20] fix(airconv): multiply max tessellation mesh workgroup count by `patch_per_group` Signed-off-by: Feifan He --- src/airconv/airconv_public.h | 2 +- src/airconv/dxbc_converter_ts.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/airconv/airconv_public.h b/src/airconv/airconv_public.h index bcce2ea4e..434bff510 100644 --- a/src/airconv/airconv_public.h +++ b/src/airconv/airconv_public.h @@ -5,7 +5,7 @@ #ifndef __AIRCONV_H #define __AIRCONV_H -#define AIRCONV_VERSION 27 +#define AIRCONV_VERSION 28 #ifdef __cplusplus #include diff --git a/src/airconv/dxbc_converter_ts.cpp b/src/airconv/dxbc_converter_ts.cpp index 311d44e87..e1a3717f5 100644 --- a/src/airconv/dxbc_converter_ts.cpp +++ b/src/airconv/dxbc_converter_ts.cpp @@ -275,7 +275,7 @@ convert_dxbc_vertex_hull_shader( uint32_t max_workload_count = get_max_potential_workload_count(factor_int, pHullStage); - func_signature.UseMaxMeshWorkgroupSize(max_workload_count); + func_signature.UseMaxMeshWorkgroupSize(max_workload_count * patch_per_group); constexpr uint32_t size_workload_info = sizeof(TessMeshWorkload); From b57b5fdffba074e5a5d6a6536d5a24234c542a9d Mon Sep 17 00:00:00 2001 From: Feifan He Date: Wed, 25 Nov 2026 18:49:43 +0800 Subject: [PATCH 18/20] fix(airconv): guard dxil hull control point phase execution by output control point count Signed-off-by: Feifan He --- src/airconv/airconv_public.h | 2 +- src/airconv/nt/dxil_converter_base.cpp | 18 +++++++++++++++++- src/airconv/nt/dxil_converter_base.hpp | 1 + 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/airconv/airconv_public.h b/src/airconv/airconv_public.h index 434bff510..938ed4b28 100644 --- a/src/airconv/airconv_public.h +++ b/src/airconv/airconv_public.h @@ -5,7 +5,7 @@ #ifndef __AIRCONV_H #define __AIRCONV_H -#define AIRCONV_VERSION 28 +#define AIRCONV_VERSION 29 #ifdef __cplusplus #include diff --git a/src/airconv/nt/dxil_converter_base.cpp b/src/airconv/nt/dxil_converter_base.cpp index 75076fadc..7e07088ab 100644 --- a/src/airconv/nt/dxil_converter_base.cpp +++ b/src/airconv/nt/dxil_converter_base.cpp @@ -48,8 +48,10 @@ Converter::Converter(EntryPoint const &entry, dxmt::dxbc::context &ctx) : air(ctx.air), entry(entry) { for (const auto &property : entry.properties) { - if (property.tag == EntryPropertyTag::HSState) + if (property.tag == EntryPropertyTag::HSState) { pcf_ = property.hs_state.patch_constant_function; + output_control_point_count_ = property.hs_state.output_control_point_count; + } } } @@ -135,6 +137,20 @@ Converter::Run(llvm::BasicBlock *ReturnBB) { return PCFStart; } + if (output_control_point_count_) { + auto cp_active = llvm::BasicBlock::Create(air.getContext(), "cp_active", ctx.function); + auto cp_end = llvm::BasicBlock::Create(air.getContext(), "cp_end", ctx.function); + ir.SetInsertPoint(cp_active); + auto is_active_control_point_thread = ctx.builder.CreateICmp( + llvm::CmpInst::ICMP_ULT, ctx.resource.thread_id_in_patch, ctx.builder.getInt32(output_control_point_count_) + ); + ir.CreateCondBr(is_active_control_point_thread, block_map_[&entry.function->getEntryBlock()], cp_end); + ir.SetInsertPoint(cp_end); + air.CreateBarrier(llvm::air::MemFlags::Threadgroup); + ir.CreateBr(pcf_ ? PCFStart : ReturnBB); + return cp_active; + } + return block_map_[&entry.function->getEntryBlock()]; } diff --git a/src/airconv/nt/dxil_converter_base.hpp b/src/airconv/nt/dxil_converter_base.hpp index 9df9b206a..f1516a812 100644 --- a/src/airconv/nt/dxil_converter_base.hpp +++ b/src/airconv/nt/dxil_converter_base.hpp @@ -42,6 +42,7 @@ class Converter { const EntryPoint &entry; const llvm::Function *pcf_ = nullptr; + uint32_t output_control_point_count_ = 0; llvm::DenseMap value_map_; llvm::DenseMap block_map_; llvm::DenseMap type_map_; From 5be53a7e151a8dfee9e4021fcd0caaa2fc8deb02 Mon Sep 17 00:00:00 2001 From: Feifan He Date: Wed, 25 Nov 2026 18:51:48 +0800 Subject: [PATCH 19/20] fix(airconv): correct the workload count estimation of quad domain The old one is underestimating Signed-off-by: Feifan He --- src/airconv/airconv_public.h | 2 +- src/airconv/dxbc_converter_ts.cpp | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/airconv/airconv_public.h b/src/airconv/airconv_public.h index 938ed4b28..6e60f527c 100644 --- a/src/airconv/airconv_public.h +++ b/src/airconv/airconv_public.h @@ -5,7 +5,7 @@ #ifndef __AIRCONV_H #define __AIRCONV_H -#define AIRCONV_VERSION 29 +#define AIRCONV_VERSION 30 #ifdef __cplusplus #include diff --git a/src/airconv/dxbc_converter_ts.cpp b/src/airconv/dxbc_converter_ts.cpp index e1a3717f5..0975af309 100644 --- a/src/airconv/dxbc_converter_ts.cpp +++ b/src/airconv/dxbc_converter_ts.cpp @@ -116,8 +116,7 @@ get_max_potential_workload_count(uint32_t max_tess_factor, SM50ShaderInternal *p case microsoft::D3D11_SB_TESSELLATOR_DOMAIN_TRI: return std::ceil((max_tess_factor - 1) / 4.0) * 3 + (max_tess_factor & 1); case microsoft::D3D11_SB_TESSELLATOR_DOMAIN_QUAD: - return std::ceil((max_tess_factor - 1) / 4.0) * 4 + (max_tess_factor & 1); - ; + return max_tess_factor + ((max_tess_factor & 1) == 0); } } From fb988d084b65869e4836674e9fe5aece57e71ead Mon Sep 17 00:00:00 2001 From: Feifan He Date: Wed, 25 Nov 2026 18:59:42 +0800 Subject: [PATCH 20/20] fix(d3d12): add object & mesh stages to render encoder waiting fence Signed-off-by: Feifan He --- src/d3d12/d3d12_command_queue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d3d12/d3d12_command_queue.cpp b/src/d3d12/d3d12_command_queue.cpp index e8096474f..744adcbe2 100644 --- a/src/d3d12/d3d12_command_queue.cpp +++ b/src/d3d12/d3d12_command_queue.cpp @@ -323,7 +323,7 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageablecmd_head); encoder.updateFence(fence_, WMTRenderStageFragment); encoder.endEncoding();