diff --git a/docs/d3d12-best-practices-audit.md b/docs/d3d12-best-practices-audit.md index 9b7c3dc..8781009 100644 --- a/docs/d3d12-best-practices-audit.md +++ b/docs/d3d12-best-practices-audit.md @@ -35,11 +35,15 @@ resource graph beyond smoke-pass scaffolding. plus a fixed body brush table feed a base field draw followed by one additive up-facing gravity quad per body. The target is scalar `R16_Float`: height is one value, and the format still supports the additive render-target blending - the brush pass needs. Mode `11` exposes it. + the brush pass needs. - D3D12 uploads the live froxel primitive table and field instance table into default-heap structured buffers each frame, using the upload ring only as the copy source. Their SRVs are created in the transient descriptor heap used by the consuming pass, avoiding impossible static+transient heap co-binding. +- D3D12 renders the first medium froxel atlas from the field instance buffer + into diagnostic and transport render targets. Mode `11` exposes froxel + density, so the debug path now follows the renderer being built rather than a + Grid-height bring-up convenience. - Renderer calls receive current window dimensions, and the D3D12 backend can recreate swapchain buffers plus dependent smoke resources on resize. - Resize waits for the GPU, disposes swapchain-dependent targets, rebuilds @@ -67,9 +71,9 @@ resource graph beyond smoke-pass scaffolding. - The offscreen smoke target copies to the swapchain. Keep this only if the real post-process graph needs it; otherwise present from the final render target path with no ornamental copy. -- The D3D11 and D3D12 field table builders are temporarily duplicated. Extract - them into one shared field ABI owner before the second backend starts to - drift. +- D3D11 and D3D12 field table builders are temporarily duplicated by design. + D3D11 is reference-only and will be removed after migration; do not pay DRY + tax merely to preserve it. ## Required Before Real Pass Migration diff --git a/docs/d3d12-migration.md b/docs/d3d12-migration.md index 7d5d00f..bab9eb1 100644 --- a/docs/d3d12-migration.md +++ b/docs/d3d12-migration.md @@ -22,13 +22,16 @@ has feature parity. - The first real migrated pass is the Grid height pass. D3D12 uploads Aquarium frame constants plus a fixed body brush table, renders a base Grid field, then draws one additive up-facing gravity quad per body into a 128x128 - scalar `R16_Float` Grid height target. Render debug mode `11` displays that - target. + scalar `R16_Float` Grid height target. - D3D12 now owns the first field-resource upload path: CPU-built froxel primitive ids and field instances upload through the per-frame upload ring, copy into default-heap structured buffers, and bind as transient SRVs for the diagnostic shader. This proves the backend can feed real Aquarium field data without reading directly from upload memory. +- The D3D12 medium pass renders a packed frustum froxel atlas into diagnostic + and transport render targets from the field instance buffer. Render debug mode + `11` now displays D3D12 froxel density, matching the future renderer path + rather than the temporary Grid-height bring-up view. - Resize waits for the GPU, releases swapchain-dependent resources, rebuilds static shader/RTV descriptor arenas, then recreates backbuffer views and dependent render targets. Descriptor exhaustion on resize is no longer a @@ -40,7 +43,7 @@ has feature parity. ## Migration Order -1. Keep D3D11 as the visual reference. +1. Keep D3D11 as the visual reference only. 2. Move shared renderer contracts behind explicit backend-neutral types. 3. Port the Grid height pass after preserving D3D11 as the reference output. 4. Keep capacity diagnostics loud while the backend is still small enough to diff --git a/docs/hlsl-renderer.md b/docs/hlsl-renderer.md index 468d5a2..dbba284 100644 --- a/docs/hlsl-renderer.md +++ b/docs/hlsl-renderer.md @@ -79,16 +79,14 @@ The D3D12 backend has begun migrating this order with a proper brush-based Grid height pass. It uploads the Aquarium frame constant buffer plus a fixed body brush table through the D3D12 upload ring, renders the base Grid field, then draws one additive up-facing gravity quad per body into a 128x128 -scalar `R16_Float` Grid height target. D3D12 render debug mode `11` displays -that target. D3D11 remains the visual reference until the full pass chain -reaches parity. +scalar `R16_Float` Grid height target. D3D11 remains the visual reference until +the full pass chain reaches parity. D3D12 also uploads the current froxel primitive id table and field instance -table into default-heap structured buffers every frame. The diagnostic smoke -shader reads both SRVs through the transient descriptor heap; this is only a -resource-path proof, not the migrated scene or medium pass yet. The D3D11 and -D3D12 table builders should be collapsed into one shared field ABI before more -field consumers are ported. +table into default-heap structured buffers every frame. The D3D12 medium pass +renders a packed frustum froxel atlas into diagnostic and transport render +targets from those field instances, and mode `11` displays the froxel density +target. The scene and resolve passes have not been migrated yet. The shader far distance is frame-derived, not a fixed constant. C# sends the distance from the camera to the Grid origin plus the Grid radius, which matches diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 422e86a..b14c5b9 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -15,6 +15,10 @@ public sealed class D3D12Renderer : IAquariumRenderer { private const int BackBufferCount = 2; private const int GridHeightTextureSize = 128; + private const int MediumFroxelDownscale = 8; + private const int MediumFroxelAtlasColumns = 8; + private const int MediumFroxelAtlasRows = 4; + private const Format MediumVolumeFormat = Format.R16G16B16A16_Float; private const Format GridHeightFormat = Format.R16_Float; private const int PlanetCount = 5; private const int GridHeightBrushCount = PlanetCount + 1; @@ -29,6 +33,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private const float FroxelMaxZ = 6.0f; private const string GridShaderRelativePath = "Render/Shaders/D3D12Grid.hlsl"; private const string SmokeShaderRelativePath = "Render/Shaders/D3D12Smoke.hlsl"; + private const string MediumShaderRelativePath = "Render/Shaders/D3D12Medium.hlsl"; private readonly IDXGIFactory4 factory; private readonly ID3D12Device device; @@ -43,11 +48,14 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly ID3D12PipelineState gridHeightBasePipelineState; private readonly ID3D12PipelineState gridHeightBrushPipelineState; private readonly ID3D12PipelineState smokePipelineState; + private readonly ID3D12PipelineState mediumVolumePipelineState; private readonly ID3D12PipelineState copyPipelineState; - private readonly ID3D12PipelineState gridHeightDebugPipelineState; + private readonly ID3D12PipelineState mediumDensityDebugPipelineState; private readonly ID3D12Fence fence; private readonly AutoResetEvent fenceEvent = new(false); private D3D12RenderTarget gridHeightRenderTarget; + private D3D12RenderTarget mediumVolumeRenderTarget; + private D3D12RenderTarget mediumTransportRenderTarget; private D3D12RenderTarget smokeRenderTarget; private D3D12RenderTarget diagnosticUavTarget; private readonly D3D12StructuredBuffer froxelPrimitiveBuffer; @@ -58,6 +66,10 @@ public sealed class D3D12Renderer : IAquariumRenderer private RawRect scissorRect; private int width; private int height; + private int mediumFroxelWidth; + private int mediumFroxelHeight; + private int mediumVolumeWidth; + private int mediumVolumeHeight; private ulong fenceValue; private int temporalFrameIndex; private int frameIndex; @@ -81,6 +93,7 @@ public sealed class D3D12Renderer : IAquariumRenderer ApplyGraphicsSettings(graphicsSettings ?? GraphicsSettings.Default); this.width = width; this.height = height; + UpdateMediumDimensions(); ReportStartupProgress(startupProgress, "Creating D3D12 device and swapchain"); factory = DXGI.CreateDXGIFactory2(false); @@ -113,6 +126,8 @@ public sealed class D3D12Renderer : IAquariumRenderer CreateRenderTargetViews(); gridHeightRenderTarget = CreateGridHeightRenderTarget(); + mediumVolumeRenderTarget = CreateMediumVolumeRenderTarget("medium-volume-target", "Aquarium D3D12 Medium Volume Target"); + mediumTransportRenderTarget = CreateMediumVolumeRenderTarget("medium-transport-target", "Aquarium D3D12 Medium Transport Target"); smokeRenderTarget = CreateSmokeRenderTarget(); diagnosticUavTarget = CreateDiagnosticUavTarget(); froxelPrimitiveBuffer = new D3D12StructuredBuffer(device, FroxelBufferElementCount, Marshal.SizeOf(), "Aquarium D3D12 Froxel Primitive Buffer"); @@ -127,16 +142,19 @@ public sealed class D3D12Renderer : IAquariumRenderer fullscreenRootSignature.Name = "Aquarium D3D12 Fullscreen Root Signature"; var gridShaderPath = Path.Combine(AppContext.BaseDirectory, GridShaderRelativePath); var smokeShaderPath = Path.Combine(AppContext.BaseDirectory, SmokeShaderRelativePath); + var mediumShaderPath = Path.Combine(AppContext.BaseDirectory, MediumShaderRelativePath); gridHeightBasePipelineState = CreateGridHeightBasePipelineState(gridShaderPath); gridHeightBasePipelineState.Name = "Aquarium D3D12 Grid Height Base Pipeline"; gridHeightBrushPipelineState = CreateGridHeightBrushPipelineState(gridShaderPath); gridHeightBrushPipelineState.Name = "Aquarium D3D12 Grid Height Brush Pipeline"; + mediumVolumePipelineState = CreateMediumVolumePipelineState(mediumShaderPath); + mediumVolumePipelineState.Name = "Aquarium D3D12 Medium Volume Pipeline"; smokePipelineState = CreateSmokePipelineState(smokeShaderPath); smokePipelineState.Name = "Aquarium D3D12 Smoke Pipeline"; copyPipelineState = CreateCopyPipelineState(smokeShaderPath); copyPipelineState.Name = "Aquarium D3D12 Copy Pipeline"; - gridHeightDebugPipelineState = CreateGridHeightDebugPipelineState(smokeShaderPath); - gridHeightDebugPipelineState.Name = "Aquarium D3D12 Grid Height Debug Pipeline"; + mediumDensityDebugPipelineState = CreateMediumDensityDebugPipelineState(smokeShaderPath); + mediumDensityDebugPipelineState.Name = "Aquarium D3D12 Medium Density Debug Pipeline"; viewport = new Viewport(0.0f, 0.0f, width, height); scissorRect = new RawRect(0, 0, width, height); fence = device.CreateFence(0); @@ -251,6 +269,15 @@ public sealed class D3D12Renderer : IAquariumRenderer commandList.BeginEvent("Aquarium D3D12 Frame"); UploadFieldResources(commandList, frameResources); RenderGridHeight(commandList, frameResources); + if (ShouldRenderMediumVolume()) + { + RenderMediumVolume(commandList, frameResources); + } + else + { + ClearMediumVolume(commandList); + } + ClearBackBuffer(new D3D12PassContext(commandList, frameResources.BackBuffer, frameResources.BackBufferRenderTargetView.Cpu), frame); commandList.EndEvent(); commandList.Close(); @@ -273,9 +300,10 @@ public sealed class D3D12Renderer : IAquariumRenderer fenceEvent.Dispose(); fence.Dispose(); commandList.Dispose(); - gridHeightDebugPipelineState.Dispose(); + mediumDensityDebugPipelineState.Dispose(); copyPipelineState.Dispose(); smokePipelineState.Dispose(); + mediumVolumePipelineState.Dispose(); gridHeightBrushPipelineState.Dispose(); gridHeightBasePipelineState.Dispose(); fullscreenRootSignature.Dispose(); @@ -283,6 +311,8 @@ public sealed class D3D12Renderer : IAquariumRenderer froxelPrimitiveBuffer.Dispose(); diagnosticUavTarget.Dispose(); smokeRenderTarget.Dispose(); + mediumTransportRenderTarget.Dispose(); + mediumVolumeRenderTarget.Dispose(); gridHeightRenderTarget.Dispose(); for (var index = 0; index < frames.Length; index++) { @@ -309,6 +339,14 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private void UpdateMediumDimensions() + { + mediumFroxelWidth = Math.Max(1, width / MediumFroxelDownscale); + mediumFroxelHeight = Math.Max(1, height / MediumFroxelDownscale); + mediumVolumeWidth = mediumFroxelWidth * MediumFroxelAtlasColumns; + mediumVolumeHeight = mediumFroxelHeight * MediumFroxelAtlasRows; + } + private void ResizeIfNeeded(int newWidth, int newHeight) { newWidth = Math.Max(1, newWidth); @@ -321,9 +359,13 @@ public sealed class D3D12Renderer : IAquariumRenderer WaitForGpu(); resourceRegistry.RemoveRenderTarget("diagnostic-uav-target"); resourceRegistry.RemoveRenderTarget("smoke-target"); + resourceRegistry.RemoveRenderTarget("medium-transport-target"); + resourceRegistry.RemoveRenderTarget("medium-volume-target"); resourceRegistry.RemoveRenderTarget("grid-height-target"); diagnosticUavTarget.Dispose(); smokeRenderTarget.Dispose(); + mediumTransportRenderTarget.Dispose(); + mediumVolumeRenderTarget.Dispose(); gridHeightRenderTarget.Dispose(); for (var index = 0; index < frames.Length; index++) { @@ -333,6 +375,7 @@ public sealed class D3D12Renderer : IAquariumRenderer width = newWidth; height = newHeight; + UpdateMediumDimensions(); renderTargetViewArena.Dispose(); staticShaderDescriptorArena.Dispose(); renderTargetViewArena = CreateRenderTargetViewArena(); @@ -342,6 +385,8 @@ public sealed class D3D12Renderer : IAquariumRenderer frameIndex = (int)swapChain.CurrentBackBufferIndex; CreateRenderTargetViews(); gridHeightRenderTarget = CreateGridHeightRenderTarget(); + mediumVolumeRenderTarget = CreateMediumVolumeRenderTarget("medium-volume-target", "Aquarium D3D12 Medium Volume Target"); + mediumTransportRenderTarget = CreateMediumVolumeRenderTarget("medium-transport-target", "Aquarium D3D12 Medium Transport Target"); smokeRenderTarget = CreateSmokeRenderTarget(); diagnosticUavTarget = CreateDiagnosticUavTarget(); viewport = new Viewport(0.0f, 0.0f, width, height); @@ -383,6 +428,23 @@ public sealed class D3D12Renderer : IAquariumRenderer return target; } + private D3D12RenderTarget CreateMediumVolumeRenderTarget(string registryName, string resourceName) + { + var target = new D3D12RenderTarget( + device, + mediumVolumeWidth, + mediumVolumeHeight, + MediumVolumeFormat, + renderTargetViewArena.Allocate(), + staticShaderDescriptorArena.Allocate(), + null, + false, + new Color4(0.0f, 0.0f, 0.0f, 1.0f), + resourceName); + resourceRegistry.Add(registryName, target); + return target; + } + private D3D12RenderTarget CreateDiagnosticUavTarget() { var target = new D3D12RenderTarget( @@ -436,11 +498,11 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.BeginEvent("Copy Smoke Target To Swapchain"); try { - var showGridHeight = RenderDebugMode == 11; - var sourceTarget = showGridHeight ? gridHeightRenderTarget : smokeRenderTarget; + var showMediumDensity = RenderDebugMode == 11; + var sourceTarget = showMediumDensity ? mediumVolumeRenderTarget : smokeRenderTarget; var sourceDescriptor = sourceTarget.ShaderResourceView ?? throw new InvalidOperationException($"{sourceTarget.Resource.Name} was created without an SRV."); - var presentPipelineState = showGridHeight ? gridHeightDebugPipelineState : copyPipelineState; + var presentPipelineState = showMediumDensity ? mediumDensityDebugPipelineState : copyPipelineState; smokeRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); sourceTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); context.BackBuffer.Transition(context.CommandList, ResourceStates.RenderTarget); @@ -504,6 +566,61 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private void RenderMediumVolume(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) + { + var mediumViewport = new Viewport(0.0f, 0.0f, mediumVolumeWidth, mediumVolumeHeight); + var mediumScissorRect = new RawRect(0, 0, mediumVolumeWidth, mediumVolumeHeight); + + activeCommandList.BeginEvent("Medium Volume Pass"); + try + { + mediumVolumeRenderTarget.Transition(activeCommandList, ResourceStates.RenderTarget); + mediumTransportRenderTarget.Transition(activeCommandList, ResourceStates.RenderTarget); + activeCommandList.ClearRenderTargetView(mediumVolumeRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 1.0f, 0.0f, 0.0f)); + activeCommandList.ClearRenderTargetView(mediumTransportRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); + activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); + activeCommandList.SetPipelineState(mediumVolumePipelineState); + activeCommandList.SetGraphicsRootSignature(fullscreenRootSignature); + activeCommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu); + activeCommandList.SetGraphicsRootDescriptorTable(5, frameResources.FieldInstanceDescriptor.Gpu); + activeCommandList.RSSetViewports(mediumViewport); + activeCommandList.RSSetScissorRects(mediumScissorRect); + activeCommandList.OMSetRenderTargets( + [ + mediumVolumeRenderTarget.RenderTargetView.Cpu, + mediumTransportRenderTarget.RenderTargetView.Cpu, + ], + null); + activeCommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); + activeCommandList.DrawInstanced(3, 1, 0, 0); + } + finally + { + activeCommandList.EndEvent(); + } + } + + private void ClearMediumVolume(ID3D12GraphicsCommandList activeCommandList) + { + activeCommandList.BeginEvent("Clear Medium Volume"); + try + { + mediumVolumeRenderTarget.Transition(activeCommandList, ResourceStates.RenderTarget); + mediumTransportRenderTarget.Transition(activeCommandList, ResourceStates.RenderTarget); + activeCommandList.ClearRenderTargetView(mediumVolumeRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 1.0f, 0.0f, 0.0f)); + activeCommandList.ClearRenderTargetView(mediumTransportRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); + } + finally + { + activeCommandList.EndEvent(); + } + } + + private bool ShouldRenderMediumVolume() + { + return settings.MediumCompositeIntensity > 0.001f || RenderDebugMode == 11; + } + private void BuildGridHeightBrushes(AquariumFrame frame) { SetGridHeightBrush( @@ -855,14 +972,23 @@ public sealed class D3D12Renderer : IAquariumRenderer return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12SmokePS", Format.B8G8R8A8_UNorm); } + private ID3D12PipelineState CreateMediumVolumePipelineState(string path) + { + return CreateFullscreenPipelineState( + path, + "FullscreenTriangleVS", + "MediumVolumePS", + [MediumVolumeFormat, MediumVolumeFormat]); + } + private ID3D12PipelineState CreateCopyPipelineState(string path) { return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12CopyPS", Format.B8G8R8A8_UNorm); } - private ID3D12PipelineState CreateGridHeightDebugPipelineState(string path) + private ID3D12PipelineState CreateMediumDensityDebugPipelineState(string path) { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12GridHeightDebugPS", Format.B8G8R8A8_UNorm); + return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12MediumDensityDebugPS", Format.B8G8R8A8_UNorm); } private ID3D12PipelineState CreateGridHeightBasePipelineState(string path) @@ -886,6 +1012,21 @@ public sealed class D3D12Renderer : IAquariumRenderer string pixelEntryPoint, Format renderTargetFormat, BlendDescription? blendDescription = null) + { + return CreateFullscreenPipelineState( + path, + vertexEntryPoint, + pixelEntryPoint, + [renderTargetFormat], + blendDescription); + } + + private ID3D12PipelineState CreateFullscreenPipelineState( + string path, + string vertexEntryPoint, + string pixelEntryPoint, + IReadOnlyList renderTargetFormats, + BlendDescription? blendDescription = null) { var vertexShader = CompileShader(path, vertexEntryPoint, "vs_5_0"); var pixelShader = CompileShader(path, pixelEntryPoint, "ps_5_0"); @@ -899,7 +1040,7 @@ public sealed class D3D12Renderer : IAquariumRenderer DepthStencilState = DepthStencilDescription.None, SampleMask = uint.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, - RenderTargetFormats = [renderTargetFormat], + RenderTargetFormats = renderTargetFormats.ToArray(), SampleDescription = new SampleDescription(1, 0), }; diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl new file mode 100644 index 0000000..fbfc879 --- /dev/null +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl @@ -0,0 +1,226 @@ +cbuffer AquariumFrame : register(b0) +{ + float2 resolution; + float timeSeconds; + float gridRadius; + float3 cameraPosition; + float farDistance; + float2 gridCenter; + float frameIndex; + float previousTimeSeconds; + float3 previousCameraPosition; + float previousGridRadius; + float2 previousGridCenter; + float2 jitterPixels; + float2 previousJitterPixels; + float renderDebugMode; + float exposure; + float bloomIntensity; + float bloomVeilIntensity; + float mediumCompositeIntensity; + float mediumDebugStep; + float3 presentationPadding; +}; + +struct FieldInstance +{ + float4 centerRadius; + float4 radiusAngle; + float4 fieldFlags; + float4 materialMedium; + float4 colorIntensity; + float4 mediumTerms; +}; + +StructuredBuffer fieldInstances : register(t12); + +static const int FIELD_INSTANCE_COUNT = 10; +static const int FIELD_FLAG_CLOUD = 2; +static const int MEDIUM_FROXEL_ATLAS_COLUMNS = 8; +static const int MEDIUM_FROXEL_ATLAS_ROWS = 4; +static const int MEDIUM_FROXEL_SLICE_COUNT = MEDIUM_FROXEL_ATLAS_COLUMNS * MEDIUM_FROXEL_ATLAS_ROWS; + +struct VertexOut +{ + float4 position : SV_Position; + float2 uv : TEXCOORD0; +}; + +struct MediumVolumeOut +{ + float4 diagnostic : SV_Target0; + float4 transport : SV_Target1; +}; + +VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) +{ + float2 uv = float2((vertexId << 1) & 2, vertexId & 2); + VertexOut output; + output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); + output.uv = uv; + return output; +} + +void cameraBasis(float3 camera, float2 center, out float3 forward, out float3 right, out float3 up) +{ + float3 target = float3(center, 0.0); + forward = normalize(target - camera); + right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); + up = cross(right, forward); +} + +float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float2 center) +{ + float2 ndc = ((pixel + jitter) * 2.0 - resolution) / resolution.y; + float3 forward; + float3 right; + float3 up; + cameraBasis(camera, center, forward, right, up); + return normalize(forward * 1.6 + right * ndc.x + up * ndc.y); +} + +float hash31(float3 p) +{ + p = frac(p * 0.1031); + p += dot(p, p.yzx + 33.33); + return frac((p.x + p.y) * p.z) * 2.0 - 1.0; +} + +float noised3(float3 x) +{ + float3 p = floor(x); + float3 w = frac(x); + float3 u = w * w * w * (w * (w * 6.0 - 15.0) + 10.0); + + float a = hash31(p + float3(0.0, 0.0, 0.0)); + float b = hash31(p + float3(1.0, 0.0, 0.0)); + float c = hash31(p + float3(0.0, 1.0, 0.0)); + float d = hash31(p + float3(1.0, 1.0, 0.0)); + float e = hash31(p + float3(0.0, 0.0, 1.0)); + float f = hash31(p + float3(1.0, 0.0, 1.0)); + float g = hash31(p + float3(0.0, 1.0, 1.0)); + float h = hash31(p + float3(1.0, 1.0, 1.0)); + + float k0 = a; + float k1 = b - a; + float k2 = c - a; + float k3 = e - a; + float k4 = a - b - c + d; + float k5 = a - c - e + g; + float k6 = a - b - e + f; + float k7 = -a + b + c - d + e - f - g + h; + + return k0 + + k1 * u.x + + k2 * u.y + + k3 * u.z + + k4 * u.x * u.y + + k5 * u.y * u.z + + k6 * u.z * u.x + + k7 * u.x * u.y * u.z; +} + +float fbm3(float3 p) +{ + float value = 0.0; + float amplitude = 0.5; + + [unroll] + for (int i = 0; i < 3; i++) + { + value += noised3(p) * amplitude; + p = p.yzx * 2.03 + float3(3.7, 1.9, 5.1); + amplitude *= 0.52; + } + + return clamp(value, -1.0, 1.0); +} + +float2 rotate2(float2 value, float angle) +{ + float s = sin(angle); + float c = cos(angle); + return float2(value.x * c - value.y * s, value.x * s + value.y * c); +} + +float ellipsoidSdf(float3 p, float3 radius) +{ + float3 safeRadius = max(radius, 0.001); + float normalizedDistance = length(p / safeRadius) - 1.0; + return normalizedDistance * min(safeRadius.x, min(safeRadius.y, safeRadius.z)); +} + +float fieldDistance(float3 p, FieldInstance field) +{ + float3 local = p - field.centerRadius.xyz; + local.xy = rotate2(local.xy, -field.radiusAngle.w); + return ellipsoidSdf(local, max(field.radiusAngle.xyz, 0.001)); +} + +float registeredMediumDensity(float3 p, out float3 scattering) +{ + float density = 0.0; + scattering = 0.0; + + [unroll] + for (int i = 0; i < FIELD_INSTANCE_COUNT; i++) + { + FieldInstance field = fieldInstances[i]; + if (((int)(field.fieldFlags.y + 0.5) & FIELD_FLAG_CLOUD) == 0) + { + continue; + } + + float distanceToField = fieldDistance(p, field); + float shell = smoothstep(0.0, 0.42, -distanceToField); + if (shell <= 0.0) + { + continue; + } + + float3 local = p - field.centerRadius.xyz; + local.xy = rotate2(local.xy, -field.radiusAngle.w); + local /= max(field.radiusAngle.xyz, 0.001); + float erosion = saturate(0.86 + fbm3(local * 3.4) * 0.14); + float core = 1.0 - smoothstep(0.80, 1.05, length(local)); + float fieldDensity = shell * core * erosion * field.mediumTerms.w; + density += fieldDensity; + scattering += field.colorIntensity.rgb * fieldDensity * field.mediumTerms.y; + } + + return saturate(density); +} + +float mediumSliceTravel(int sliceIndex) +{ + float t = ((float)sliceIndex + 0.5) / (float)MEDIUM_FROXEL_SLICE_COUNT; + return t * farDistance; +} + +MediumVolumeOut MediumVolumePS(VertexOut input) +{ + float2 atlasCoord = saturate(input.uv) * float2(MEDIUM_FROXEL_ATLAS_COLUMNS, MEDIUM_FROXEL_ATLAS_ROWS); + int2 tile = clamp((int2)floor(atlasCoord), int2(0, 0), int2(MEDIUM_FROXEL_ATLAS_COLUMNS - 1, MEDIUM_FROXEL_ATLAS_ROWS - 1)); + int sliceIndex = tile.x + tile.y * MEDIUM_FROXEL_ATLAS_COLUMNS; + float2 localUv = frac(atlasCoord); + float2 screenUv = float2(localUv.x, 1.0 - localUv.y); + float2 pixel = screenUv * resolution; + float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, gridCenter); + + float sliceLength = farDistance / (float)MEDIUM_FROXEL_SLICE_COUNT; + float travel = mediumSliceTravel(sliceIndex); + float3 p = cameraPosition + rayDirection * travel; + float3 scattering; + float density = registeredMediumDensity(p, scattering); + float extinction = density * 0.16; + float transmittance = exp(-extinction * sliceLength); + float3 inScattering = density > 0.001 + ? scattering * (1.0 - transmittance) / max(extinction, 0.001) + : 0.0; + + float sourceDebug = saturate(dot(inScattering, float3(0.2126, 0.7152, 0.0722)) * 0.65); + MediumVolumeOut output; + output.diagnostic = float4(saturate(density), saturate(transmittance), sourceDebug, 1.0); + output.transport = float4(inScattering, saturate(transmittance)); + return output; +} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl index b2c8d56..836f8b0 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl @@ -52,12 +52,15 @@ float4 D3D12CopyPS(VertexOut input) : SV_Target0 return sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0); } -float4 D3D12GridHeightDebugPS(VertexOut input) : SV_Target0 +float4 D3D12MediumDensityDebugPS(VertexOut input) : SV_Target0 { - float height = sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0).r; - float signedShape = saturate(abs(height) * 0.85); - float3 negative = float3(0.08, 0.34, 0.52); - float3 positive = float3(0.95, 0.62, 0.22); - float3 baseColor = height < 0.0 ? negative : positive; - return float4(baseColor * signedShape, 1.0); + float4 diagnostic = sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0); + float density = saturate(diagnostic.r); + float transmittance = saturate(diagnostic.g); + float source = saturate(diagnostic.b); + float3 clear = float3(0.006, 0.014, 0.022); + float3 fog = float3(0.18, 0.48, 0.68) * density; + fog += float3(0.95, 0.72, 0.36) * source; + fog *= lerp(0.45, 1.0, transmittance); + return float4(max(clear, fog), 1.0); } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 1ac04dc..95f5e5f 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -73,4 +73,5 @@ {"area":"renderer/d3d12","lesson":"The first real D3D12 pass migration exposed the Grid height target and frame-constant path, but its original fullscreen per-texel body loop was intentionally superseded by a brush-rendered pass. Keep temporal previous camera/Grid/time as renderer-level state; swapchain frame resources are allocator reuse buckets, not frame-history state.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl","docs/d3d12-migration.md","docs/d3d12-best-practices-audit.md","docs/hlsl-renderer.md","state/map.yaml","state/memory.json","state/scratch.md"],"verification":["dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=0 exited 0"],"ts":"2026-05-09"} {"area":"renderer/d3d12","lesson":"The D3D12 Grid height pass must be a real gravity brush pass, not a fullscreen shader loop over every body per texel. It renders a base field, uploads a small body brush constant table, and draws one additive up-facing quad per body into a 128x128 scalar R16_Float target. R32G32B32A32_Float is the wrong target format for additive blending here, and extra channels are waste unless the pass contract actually stores extra data. The root signature must expose frame constants to the vertex shader because the brush vertex shader performs the top-down Grid-space orthographic transform.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Grid.hlsl","docs/d3d12-migration.md","docs/d3d12-best-practices-audit.md","docs/hlsl-renderer.md","state/memory.json","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0","dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=0 exited 0"],"ts":"2026-05-09"} {"area":"renderer/d3d12","lesson":"A Grid height target is scalar. The D3D12 brush-rendered Grid height pass should use R16_Float and scalar pixel-shader outputs; four float channels were defensive waste after the R32G32B32A32_Float blend failure, not a real contract. Add channels only when the pass explicitly stores more than height.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Grid.hlsl","docs/d3d12-migration.md","docs/d3d12-best-practices-audit.md","docs/hlsl-renderer.md","state/memory.json","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0","dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=0 exited 0"],"ts":"2026-05-09"} -{"area":"renderer/d3d12","lesson":"D3D12 now has the first real Aquarium field data upload path: froxel primitive ids and field instances are built on CPU, uploaded through the per-frame upload ring, copied into default-heap structured buffers, and bound through transient SRV descriptors for a shader that actually reads them. Static and transient CBV/SRV/UAV heaps cannot be co-bound; pass-visible descriptor tables need to live in the active transient heap or be copied there. The table builders are temporarily duplicated from D3D11 and should be extracted into one shared field ABI owner before more consumers depend on them.","files":["src/Aquarium.Engine/Render/D3D12UploadRing.cs","src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs","src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl","docs/d3d12-migration.md","docs/d3d12-best-practices-audit.md","docs/hlsl-renderer.md","state/memory.json","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=0 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0","dotnet build Aquarium.Engine.slnx"],"ts":"2026-05-09"} +{"area":"renderer/d3d12","lesson":"D3D12 now has the first real Aquarium field data upload path: froxel primitive ids and field instances are built on CPU, uploaded through the per-frame upload ring, copied into default-heap structured buffers, and bound through transient SRV descriptors for a shader that actually reads them. Static and transient CBV/SRV/UAV heaps cannot be co-bound; pass-visible descriptor tables need to live in the active transient heap or be copied there. D3D11 is reference-only during migration, so duplicate table-building code is acceptable when it keeps the D3D12 path moving toward ownership.","files":["src/Aquarium.Engine/Render/D3D12UploadRing.cs","src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs","src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl","docs/d3d12-migration.md","docs/d3d12-best-practices-audit.md","docs/hlsl-renderer.md","state/memory.json","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=0 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0","dotnet build Aquarium.Engine.slnx"],"ts":"2026-05-09"} +{"area":"renderer/d3d12","lesson":"D3D12 now renders the first medium froxel atlas pass into diagnostic and transport render targets from the field instance structured buffer. Render debug mode 11 displays D3D12 froxel density, and the old D3D12 Grid-height debug PSO was removed instead of preserving stale bring-up scaffolding.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl","docs/d3d12-migration.md","docs/d3d12-best-practices-audit.md","docs/hlsl-renderer.md","state/map.yaml","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=0 exited 0"],"ts":"2026-05-09"} diff --git a/state/map.yaml b/state/map.yaml index d6c49ce..95a39f3 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -64,10 +64,10 @@ renderer_state: - Direct2D/DirectWrite debug UI panel with code-first controls bound to renderer state. - Global GraphicsSettings document feeding render debug, exposure, bloom intensity, bloom veil, and medium composite intensity. - First field instance structured buffer feeding a half-resolution registered medium diagnostic/transport pass. - - Parallel D3D12 scaffold behind IAquariumRenderer proving device/queue/swapchain, per-frame command allocators, fences, static/transient descriptor arenas, upload ring constants, RTV/SRV/UAV render targets, tracked barriers, command events, resize descriptor-arena rebuild, and the first migrated Grid height pass. + - Parallel D3D12 scaffold behind IAquariumRenderer proving device/queue/swapchain, per-frame command allocators, fences, static/transient descriptor arenas, upload ring constants, RTV/SRV/UAV render targets, structured field buffers, tracked barriers, command events, resize descriptor-arena rebuild, the migrated Grid height pass, and the first medium froxel atlas pass. - Splash screen with bundled app icon and GameCult typefaces. next: - - Port the froxel/field resource upload path into D3D12 without cloning smoke-pass-local policy. + - Port the D3D12 scene and resolve passes so the Grid, bodies, medium atlases, presentation controls, and debug views flow through one D3D12 frame graph. - Promote field instances from fixed renderer table to a CPU-owned registry with per-field debug controls. - Extend explicit renderer debug modes for hits, normals, depth, bins, and lighting. - Restore HDR scene target, gentle pre-tonemap bloom, and ACES as explicit passes. diff --git a/state/memory.json b/state/memory.json index 8240ed4..61847f8 100644 --- a/state/memory.json +++ b/state/memory.json @@ -18,7 +18,7 @@ "D3D12 is being added beside D3D11, not by mutating the reference renderer in place. Keep descriptor ownership explicit: static descriptors for long-lived SRV/UAV tables, per-frame transient descriptors reset only after fence wait, and whole-arena rebuilds on resize until real non-resize churn demands free lists. Resource capability flags are not descriptor ownership; do not burn static UAV descriptors just to allow a transient UAV view.", "D3D12 previous-frame camera/Grid/time state must be renderer-level temporal state, not per-swapchain-frame-resource state. The swapchain image index is an allocator/reuse index, not frame history.", "D3D12 Grid height must be brush-rendered, not a fullscreen per-texel loop over bodies. Use a top-down Grid-space orthographic brush pass: base field draw, then one additive up-facing quad per body into a scalar R16_Float height target. Height is one value; do not spend extra channels unless the pass contract actually gains more data. Do not use R32G32B32A32_Float for additive brush composition.", - "D3D12 field data should live in default-heap structured buffers, updated from the per-frame upload ring by CopyBufferRegion, then bound through transient SRV descriptors owned by the consuming pass. Do not make shaders read dynamic field tables straight from upload memory. Collapse D3D11 and D3D12 field table builders into one shared ABI owner before more consumers depend on them.", + "D3D12 field data should live in default-heap structured buffers, updated from the per-frame upload ring by CopyBufferRegion, then bound through transient SRV descriptors owned by the consuming pass. Do not make shaders read dynamic field tables straight from upload memory. D3D11 is reference-only during migration; do not pay DRY tax to preserve it.", "D3D12 pixel shader UAV registers share the output namespace. If a shader writes SV_Target0, bind the first manual UAV at u1, not u0.", "D3D12 shader routing must not inherit the D3D11 --shader-source override by accident. Backend-specific HLSL should compile from its copied output path unless an explicit backend-specific override exists.", "Use Vortice at the graphics API membrane. Keep CultMath as the CPU math grammar. Do not let third-party math opinions leak inward unless the conversion is explicit.", diff --git a/state/scratch.md b/state/scratch.md index 965aae9..69cb360 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -283,6 +283,10 @@ can start porting real passes while keeping D3D11 as the visual reference. and field instance table, uploads them through the per-frame upload ring, copies them into default-heap structured buffers, and binds transient SRVs to the diagnostic shader. This proves the real field data path without forcing - shaders to read directly from upload heap memory. The table-building code is - duplicated from D3D11 for this slice; extract it into one shared field ABI - owner before porting the next field consumer. + shaders to read directly from upload heap memory. The table-building code can + duplicate D3D11 during migration because D3D11 is reference-only and will be + removed after the D3D12 path owns the renderer. +- D3D12 medium froxel pass: D3D12 now renders diagnostic and transport froxel + atlases from the D3D12 field instance buffer. Render debug mode `11` displays + D3D12 froxel density; the temporary Grid-height debug view was cut rather + than left as stale bring-up scaffolding.