From ab02fd9a02a31a33dc283eb079c58a2735ce796e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 9 May 2026 12:59:40 +0100 Subject: [PATCH] Split D3D12 descriptors and registry --- docs/d3d12-best-practices-audit.md | 10 ++-- docs/d3d12-migration.md | 3 +- .../Render/D3D12DescriptorArena.cs | 17 +++++- src/Aquarium.Engine/Render/D3D12Renderer.cs | 58 ++++++++++++++----- .../Render/D3D12ResourceRegistry.cs | 54 +++++++++++++++++ src/Aquarium.Engine/Render/D3D12UploadRing.cs | 12 +++- state/evidence.jsonl | 1 + state/scratch.md | 10 +++- 8 files changed, 140 insertions(+), 25 deletions(-) create mode 100644 src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs diff --git a/docs/d3d12-best-practices-audit.md b/docs/d3d12-best-practices-audit.md index 24bc62b..5e121a6 100644 --- a/docs/d3d12-best-practices-audit.md +++ b/docs/d3d12-best-practices-audit.md @@ -23,6 +23,10 @@ smoke-pass helpers become permanent resource policy by accident. of raw assumed barriers. - D3D12 objects are named, and command-list events mark the frame, smoke pass, and copy pass for PIX/graphics diagnostics. +- Shader-visible descriptors are split into static and per-frame transient + arenas. Transient arenas reset only after the owning frame fence clears. +- D3D12 resources are registered by name, and capacity diagnostics report upload, + transient descriptor, static descriptor, and RTV usage. - The D3D12 smoke path exercises shader compilation, root signature, PSO, descriptor table, RTV binding, barriers, copy, and present. @@ -30,8 +34,8 @@ smoke-pass helpers become permanent resource policy by accident. - Committed resources are used directly. Replace with D3D12MA or placed-resource suballocation before the renderer owns many textures/buffers. -- Descriptor arena is fixed-size and not fence-reclaimed. It should split into - static descriptors and transient per-frame ranges. +- Descriptor arenas are still simple bump allocators. Add free lists or + descriptor-table paging only when real resource churn demands it. - Upload ring is per-frame and reset after fence wait. It is not yet a global transient allocator with suballocation statistics or overflow diagnostics. - Backbuffer state is assumed. Wrap swapchain buffers in state-tracked frame @@ -42,8 +46,6 @@ smoke-pass helpers become permanent resource policy by accident. ## Required Before Real Pass Migration -- A named D3D12 resource registry for render targets and buffers. -- Static and transient descriptor allocation APIs. - Upload ring capacity policy and overflow reporting for real frame data. - Debug names for D3D12 resources, descriptors by owner, and command lists. - Backbuffer state tracking and resize-safe recreation. diff --git a/docs/d3d12-migration.md b/docs/d3d12-migration.md index 1dd94d2..32bfeb0 100644 --- a/docs/d3d12-migration.md +++ b/docs/d3d12-migration.md @@ -27,8 +27,7 @@ has feature parity. 1. Keep D3D11 as the visual reference. 2. Move shared renderer contracts behind explicit backend-neutral types. -3. Replace the smoke-only resource code with a named resource registry, - static/transient descriptors, SRV/UAV creation, and an upload ring. +3. Add SRV/UAV creation paths and resize-safe resource recreation. 4. Add resize-safe recreation and capacity diagnostics while the backend is still small enough to make mistakes obvious. 5. Port the existing passes in visible order: grid height, froxel volume, scene, diff --git a/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs b/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs index 7168d13..b77f26f 100644 --- a/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs +++ b/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs @@ -11,6 +11,7 @@ internal sealed class D3D12DescriptorArena : IDisposable { Type = type; Capacity = capacity; + Name = name; Heap = device.CreateDescriptorHeap(new DescriptorHeapDescription(type, (uint)capacity, flags)); Heap.Name = name; descriptorSize = (int)device.GetDescriptorHandleIncrementSize(type); @@ -22,11 +23,15 @@ internal sealed class D3D12DescriptorArena : IDisposable public int Capacity { get; } + public int Used => used; + + public string Name { get; } + public D3D12DescriptorSlot Allocate() { if (used >= Capacity) { - throw new InvalidOperationException($"D3D12 {Type} descriptor arena exhausted ({Capacity} descriptors)."); + throw new InvalidOperationException($"D3D12 descriptor arena '{Name}' exhausted ({Capacity} {Type} descriptors)."); } var index = used++; @@ -35,6 +40,16 @@ internal sealed class D3D12DescriptorArena : IDisposable Heap.GetGPUDescriptorHandleForHeapStart() + (index * descriptorSize)); } + public void Reset() + { + used = 0; + } + + public string Describe() + { + return $"{Name}: {used}/{Capacity} {Type} descriptors"; + } + public void Dispose() { Heap.Dispose(); diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 80b5669..2b7fc93 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -19,8 +19,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly ID3D12Device device; private readonly ID3D12CommandQueue commandQueue; private readonly IDXGISwapChain3 swapChain; + private readonly D3D12ResourceRegistry resourceRegistry = new(); private readonly D3D12DescriptorArena renderTargetViewArena; - private readonly D3D12DescriptorArena shaderDescriptorArena; + private readonly D3D12DescriptorArena staticShaderDescriptorArena; private readonly D3D12RenderTarget smokeRenderTarget; private readonly FrameResources[] frames = new FrameResources[BackBufferCount]; private readonly ID3D12GraphicsCommandList commandList; @@ -68,8 +69,8 @@ public sealed class D3D12Renderer : IAquariumRenderer swapChain = swapChain1.QueryInterface(); frameIndex = (int)swapChain.CurrentBackBufferIndex; - renderTargetViewArena = new D3D12DescriptorArena(device, DescriptorHeapType.RenderTargetView, BackBufferCount + 1, DescriptorHeapFlags.None, "Aquarium D3D12 RTV Arena"); - shaderDescriptorArena = new D3D12DescriptorArena(device, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, BackBufferCount, DescriptorHeapFlags.ShaderVisible, "Aquarium D3D12 Shader Descriptor Arena"); + renderTargetViewArena = new D3D12DescriptorArena(device, DescriptorHeapType.RenderTargetView, 32, DescriptorHeapFlags.None, "Aquarium D3D12 RTV Arena"); + staticShaderDescriptorArena = new D3D12DescriptorArena(device, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, 64, DescriptorHeapFlags.ShaderVisible, "Aquarium D3D12 Static Shader Descriptor Arena"); for (var index = 0; index < frames.Length; index++) { frames[index] = CreateFrameResources(index); @@ -84,6 +85,7 @@ public sealed class D3D12Renderer : IAquariumRenderer renderTargetViewArena.Allocate(), new Color4(0.006f, 0.014f, 0.022f, 1.0f), "Aquarium D3D12 Smoke Target"); + resourceRegistry.Add("smoke-target", smokeRenderTarget); commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); commandList.Name = "Aquarium D3D12 Graphics Command List"; commandList.Close(); @@ -96,6 +98,7 @@ public sealed class D3D12Renderer : IAquariumRenderer scissorRect = new RawRect(0, 0, width, height); fence = device.CreateFence(0); fence.Name = "Aquarium D3D12 Frame Fence"; + Console.WriteLine($"D3D12 resource registry: {resourceRegistry.Describe()}"); Console.WriteLine("D3D12 device and swapchain created."); } @@ -136,6 +139,7 @@ public sealed class D3D12Renderer : IAquariumRenderer var frameResources = frames[frameIndex]; WaitForFrame(frameResources); frameResources.UploadRing.Reset(); + frameResources.TransientShaderDescriptors.Reset(); var smokeConstants = frameResources.UploadRing.WriteConstant(new SmokeConstants( new Vector4( 0.020f + settings.SceneExposure * 0.08f, @@ -143,9 +147,10 @@ public sealed class D3D12Renderer : IAquariumRenderer 0.066f + settings.BloomVeilIntensity * 1.2f, 1.0f), new Vector4(frame.TimeSeconds, RenderDebugMode, DebugUiVisible ? 1.0f : 0.0f, 0.0f))); + frameResources.SmokeConstantsDescriptor = frameResources.TransientShaderDescriptors.Allocate(); device.CreateConstantBufferView( new ConstantBufferViewDescription(smokeConstants.GpuVirtualAddress, smokeConstants.SizeInBytes), - frameResources.SmokeConstantsCpuDescriptor); + frameResources.SmokeConstantsDescriptor.Cpu); frameResources.CommandAllocator.Reset(); commandList.Reset(frameResources.CommandAllocator, null); @@ -157,6 +162,7 @@ public sealed class D3D12Renderer : IAquariumRenderer commandQueue.ExecuteCommandList(commandList); swapChain.Present(1, PresentFlags.None); SignalFrame(frameResources); + ReportCapacityOncePerSecond(frame.TimeSeconds, frameResources); frameIndex = (int)swapChain.CurrentBackBufferIndex; } @@ -173,7 +179,7 @@ public sealed class D3D12Renderer : IAquariumRenderer { frames[index].Dispose(); } - shaderDescriptorArena.Dispose(); + staticShaderDescriptorArena.Dispose(); renderTargetViewArena.Dispose(); swapChain.Dispose(); commandQueue.Dispose(); @@ -186,7 +192,9 @@ public sealed class D3D12Renderer : IAquariumRenderer for (var index = 0; index < frames.Length; index++) { var backBuffer = swapChain.GetBuffer((uint)index); - frames[index].BackBuffer = new D3D12TrackedResource(backBuffer, ResourceStates.Present, $"Aquarium D3D12 Backbuffer {index}", ownsResource: true); + var backBufferResource = new D3D12TrackedResource(backBuffer, ResourceStates.Present, $"Aquarium D3D12 Backbuffer {index}", ownsResource: true); + frames[index].BackBuffer = backBufferResource; + resourceRegistry.Add($"backbuffer-{index}", backBufferResource); frames[index].BackBufferRenderTargetView = renderTargetViewArena.Allocate(); device.CreateRenderTargetView(frames[index].BackBuffer.Resource, null, frames[index].BackBufferRenderTargetView.Cpu); } @@ -206,10 +214,10 @@ public sealed class D3D12Renderer : IAquariumRenderer { smokeRenderTarget.Transition(context.CommandList, ResourceStates.RenderTarget); context.CommandList.ClearRenderTargetView(smokeRenderTarget.RenderTargetView.Cpu, clearColor); - context.CommandList.SetDescriptorHeaps(shaderDescriptorArena.Heap); + context.CommandList.SetDescriptorHeaps(frames[frameIndex].TransientShaderDescriptors.Heap); context.CommandList.SetPipelineState(smokePipelineState); context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature); - context.CommandList.SetGraphicsRootDescriptorTable(0, frames[frameIndex].SmokeConstantsGpuDescriptor); + context.CommandList.SetGraphicsRootDescriptorTable(0, frames[frameIndex].SmokeConstantsDescriptor.Gpu); context.CommandList.RSSetViewports(viewport); context.CommandList.RSSetScissorRects(scissorRect); context.CommandList.OMSetRenderTargets(smokeRenderTarget.RenderTargetView.Cpu, null); @@ -242,6 +250,23 @@ public sealed class D3D12Renderer : IAquariumRenderer frameResources.FenceValue = signalValue; } + private float lastCapacityReportSecond = -1.0f; + + private void ReportCapacityOncePerSecond(float timeSeconds, FrameResources frameResources) + { + if (timeSeconds - lastCapacityReportSecond < 1.0f) + { + return; + } + + lastCapacityReportSecond = timeSeconds; + Console.WriteLine( + $"D3D12 capacity: {frameResources.UploadRing.Describe()}; " + + $"{frameResources.TransientShaderDescriptors.Describe()}; " + + $"{staticShaderDescriptorArena.Describe()}; " + + $"{renderTargetViewArena.Describe()}"); + } + private void WaitForFrame(FrameResources frameResources) { if (frameResources.FenceValue != 0 && fence.CompletedValue < frameResources.FenceValue) @@ -289,9 +314,14 @@ public sealed class D3D12Renderer : IAquariumRenderer var commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); commandAllocator.Name = $"Aquarium D3D12 Frame {index} Command Allocator"; var uploadRing = new D3D12UploadRing(device, 64 * 1024, $"Aquarium D3D12 Frame {index} Upload Ring"); - var constantBufferSlot = shaderDescriptorArena.Allocate(); + var transientDescriptors = new D3D12DescriptorArena( + device, + DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, + 64, + DescriptorHeapFlags.ShaderVisible, + $"Aquarium D3D12 Frame {index} Transient Shader Descriptor Arena"); - return new FrameResources(commandAllocator, uploadRing, constantBufferSlot.Cpu, constantBufferSlot.Gpu); + return new FrameResources(commandAllocator, uploadRing, transientDescriptors); } private ID3D12PipelineState CreateSmokePipelineState(string path) @@ -335,16 +365,15 @@ public sealed class D3D12Renderer : IAquariumRenderer private sealed class FrameResources( ID3D12CommandAllocator commandAllocator, D3D12UploadRing uploadRing, - CpuDescriptorHandle smokeConstantsCpuDescriptor, - GpuDescriptorHandle smokeConstantsGpuDescriptor) : IDisposable + D3D12DescriptorArena transientShaderDescriptors) : IDisposable { public ID3D12CommandAllocator CommandAllocator { get; } = commandAllocator; public D3D12UploadRing UploadRing { get; } = uploadRing; - public CpuDescriptorHandle SmokeConstantsCpuDescriptor { get; } = smokeConstantsCpuDescriptor; + public D3D12DescriptorArena TransientShaderDescriptors { get; } = transientShaderDescriptors; - public GpuDescriptorHandle SmokeConstantsGpuDescriptor { get; } = smokeConstantsGpuDescriptor; + public D3D12DescriptorSlot SmokeConstantsDescriptor { get; set; } public D3D12TrackedResource BackBuffer { get; set; } = null!; @@ -355,6 +384,7 @@ public sealed class D3D12Renderer : IAquariumRenderer public void Dispose() { BackBuffer.Dispose(); + TransientShaderDescriptors.Dispose(); UploadRing.Dispose(); CommandAllocator.Dispose(); } diff --git a/src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs b/src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs new file mode 100644 index 0000000..c82f5d2 --- /dev/null +++ b/src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs @@ -0,0 +1,54 @@ +using Vortice.Direct3D12; + +namespace Aquarium.Engine.Render; + +internal sealed class D3D12ResourceRegistry +{ + private readonly Dictionary trackedResources = new(StringComparer.Ordinal); + private readonly Dictionary renderTargets = new(StringComparer.Ordinal); + + public void Add(string name, D3D12TrackedResource resource) + { + if (!trackedResources.TryAdd(name, resource)) + { + throw new InvalidOperationException($"D3D12 resource already registered: {name}"); + } + } + + public void Add(string name, D3D12RenderTarget renderTarget) + { + if (!renderTargets.TryAdd(name, renderTarget)) + { + throw new InvalidOperationException($"D3D12 render target already registered: {name}"); + } + } + + public D3D12TrackedResource GetResource(string name) + { + return trackedResources.TryGetValue(name, out var resource) + ? resource + : throw new KeyNotFoundException($"D3D12 resource was not registered: {name}"); + } + + public D3D12RenderTarget GetRenderTarget(string name) + { + return renderTargets.TryGetValue(name, out var renderTarget) + ? renderTarget + : throw new KeyNotFoundException($"D3D12 render target was not registered: {name}"); + } + + public void RemoveResource(string name) + { + trackedResources.Remove(name); + } + + public void RemoveRenderTarget(string name) + { + renderTargets.Remove(name); + } + + public string Describe() + { + return $"resources={trackedResources.Count}, renderTargets={renderTargets.Count}"; + } +} diff --git a/src/Aquarium.Engine/Render/D3D12UploadRing.cs b/src/Aquarium.Engine/Render/D3D12UploadRing.cs index 2e4d32e..3d0c496 100644 --- a/src/Aquarium.Engine/Render/D3D12UploadRing.cs +++ b/src/Aquarium.Engine/Render/D3D12UploadRing.cs @@ -12,6 +12,7 @@ internal sealed unsafe class D3D12UploadRing : IDisposable public D3D12UploadRing(ID3D12Device device, int capacityBytes, string name) { CapacityBytes = Align256(capacityBytes); + Name = name; resource = device.CreateCommittedResource( HeapType.Upload, ResourceDescription.Buffer((ulong)CapacityBytes), @@ -23,6 +24,10 @@ internal sealed unsafe class D3D12UploadRing : IDisposable public int CapacityBytes { get; } + public int UsedBytes => cursor; + + public string Name { get; } + public ulong GpuVirtualAddress => resource.GPUVirtualAddress; public void Reset() @@ -36,7 +41,7 @@ internal sealed unsafe class D3D12UploadRing : IDisposable var size = Align256(Unsafe.SizeOf()); if (cursor + size > CapacityBytes) { - throw new InvalidOperationException($"D3D12 upload ring exhausted ({CapacityBytes} bytes)."); + throw new InvalidOperationException($"D3D12 upload ring '{Name}' exhausted ({cursor}/{CapacityBytes} bytes used, requested {size} bytes)."); } var offset = cursor; @@ -45,6 +50,11 @@ internal sealed unsafe class D3D12UploadRing : IDisposable return new D3D12UploadAllocation(GpuVirtualAddress + (ulong)offset, (uint)size); } + public string Describe() + { + return $"{Name}: {cursor}/{CapacityBytes} bytes"; + } + public void Dispose() { resource.Unmap(0, null); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 932a736..d01b1f6 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -66,3 +66,4 @@ {"area":"renderer/d3d12","lesson":"D3D12 now has reusable renderer-side primitives instead of smoke-pass-local plumbing: a descriptor arena, persistent mapped upload buffer, and default-heap render target with explicit state tracking. The smoke pass renders into the offscreen target and copies to the swapchain, proving render target lifetime and copy barriers before porting Aquarium scene/history/froxel textures.","files":["src/Aquarium.Engine/Aquarium.Engine.csproj","src/Aquarium.Engine/Render/D3D12DescriptorArena.cs","src/Aquarium.Engine/Render/D3D12UploadBuffer.cs","src/Aquarium.Engine/Render/D3D12RenderTarget.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/d3d12-migration.md","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","Aquarium.Engine.exe --headless --renderer d3d12 exited 0 with offscreen render target copy path"],"ts":"2026-05-09"} {"area":"renderer/d3d12","lesson":"D3D12 best-practice pass distilled Microsoft, NVIDIA, and AMD guidance. Current Aquarium D3D12 backend is acceptable bring-up scaffolding, but real pass migration should wait for a named resource registry, static/transient descriptor allocation, fence-reclaimed upload ring, debug names, PIX markers, and backbuffer state tracking. Committed resources and fixed arenas must not become production policy by inertia.","files":["research/d3d12/source-manifest.md","research/d3d12/synthesis.md","docs/d3d12-best-practices-audit.md","docs/d3d12-migration.md","state/scratch.md"],"verification":["Research sources reviewed via Microsoft Learn, DirectX Developer Blog, NVIDIA Technical Blog, and AMD GPUOpen","Current D3D12 helper code audited against descriptor, upload, barrier, memory, and fence guidance"],"ts":"2026-05-09"} {"area":"renderer/d3d12","lesson":"Full-ass D3D12 foundation pass added debug names, command-list events, tracked swapchain backbuffer states, and per-frame persistent-mapped upload rings. This moves current code closer to the researched doctrine: visible ownership, inspectable GPU captures, and fence-safe transient CPU-to-GPU data. Next remaining pre-pass work is static/transient descriptor separation, resource registry, resize-safe recreation, and capacity diagnostics.","files":["src/Aquarium.Engine/Render/D3D12TrackedResource.cs","src/Aquarium.Engine/Render/D3D12DescriptorArena.cs","src/Aquarium.Engine/Render/D3D12UploadRing.cs","src/Aquarium.Engine/Render/D3D12RenderTarget.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/d3d12-best-practices-audit.md","docs/d3d12-migration.md","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","Aquarium.Engine.exe --headless --renderer d3d12 exited 0 with tracked resources, events, and upload ring"],"ts":"2026-05-09"} +{"area":"renderer/d3d12","lesson":"D3D12 now separates static shader descriptors from per-frame transient descriptor arenas, resets transient descriptors only after frame fence wait, registers named resources, and reports capacity for upload ring, transient/static shader descriptors, and RTV descriptors. Keep arenas simple until real churn demands free lists; avoid exact-fit capacities that leave no room for immediate next resources.","files":["src/Aquarium.Engine/Render/D3D12DescriptorArena.cs","src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12UploadRing.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/d3d12-best-practices-audit.md","docs/d3d12-migration.md","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","Aquarium.Engine.exe --headless --renderer d3d12 exited 0 and printed resource registry plus capacity diagnostics"],"ts":"2026-05-09"} diff --git a/state/scratch.md b/state/scratch.md index 1bcc684..7ac6766 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -9,9 +9,8 @@ plus a shader-visible descriptor arena, per-frame upload constant buffers, renderer-owned offscreen render target, fullscreen root signature, and smoke-test PSO that draws a diagnostic fullscreen triangle into the offscreen target before copying to the swapchain. Next renderer work should generalize -this into a named resource registry, static/transient descriptor allocators, -SRV/UAV creation, resize-safe resource recreation, and capacity diagnostics -before building the stochastic transparent surface pipe. +this into SRV/UAV creation and resize-safe resource recreation before building +the stochastic transparent surface pipe. ## Hot Context @@ -245,3 +244,8 @@ before building the stochastic transparent surface pipe. and smoke/copy passes emit command-list events for PIX-style inspection, swapchain backbuffers are state-tracked resources, and per-frame constants are allocated from a persistent mapped upload ring after the frame fence wait. +- D3D12 descriptor/registry pass: shader-visible descriptors are split into + static and per-frame transient arenas. Transient descriptors reset after the + frame fence wait, named resources live in `D3D12ResourceRegistry`, and + one-second capacity diagnostics report upload ring, transient/static shader + descriptor, and RTV usage.