diff --git a/docs/d3d12-migration.md b/docs/d3d12-migration.md index fa0011c..b24ac9e 100644 --- a/docs/d3d12-migration.md +++ b/docs/d3d12-migration.md @@ -44,8 +44,11 @@ has feature parity. - The D3D12 scene pass writes the first temporal diagnostic spine: color/travel, field id/normal metadata, and temporal control render targets. The present shader can inspect current temporal control in debug mode `5` and field - identity in debug mode `6`. History ping-pong and reprojection are still - pending; these targets are the buffers that make that work honest. + identity in debug mode `6`. Resolve now writes ping-pong history color, + metadata, and control targets, with previous-camera reprojection and + field/travel/normal/color/coverage/medium validation for opaque current scene + hits. Debug mode `3` shows history age and mode `4` shows history weight. + Grid/transparent-specific temporal reconstruction is still pending. - 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 diff --git a/docs/hlsl-renderer.md b/docs/hlsl-renderer.md index 4578e7d..f53f3cb 100644 --- a/docs/hlsl-renderer.md +++ b/docs/hlsl-renderer.md @@ -93,8 +93,12 @@ terminator. That binned Grid layer now carries cartesian gridlines, height isolines, and gradient-angle field lines. D3D12 also owns an HDR scene target and bloom/present pass. Its scene pass now writes color/travel, field-id/normal metadata, and temporal-control targets, with debug modes `5` -and `6` inspecting the current control and identity buffers. The full temporal -history ping-pong/reprojection and overlay/debug UI still need to move. +and `6` inspecting the current control and identity buffers. Its resolve pass +now writes ping-pong history color, metadata, and control targets and validates +opaque history with previous-camera reprojection plus field, travel, normal, +neighborhood color, coverage, and medium-continuity checks. Debug modes `3` and +`4` show history age and weight. Grid/transparent-specific reconstruction and +overlay/debug UI still need to move. 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 b371249..a2e9056 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -60,7 +60,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly ID3D12PipelineState bloomDownsamplePipelineState; private readonly ID3D12PipelineState bloomBlurHorizontalPipelineState; private readonly ID3D12PipelineState bloomBlurVerticalPipelineState; - private readonly ID3D12PipelineState presentPipelineState; + private readonly ID3D12PipelineState resolvePipelineState; private readonly ID3D12Fence fence; private readonly AutoResetEvent fenceEvent = new(false); private D3D12RenderTarget gridHeightRenderTarget; @@ -69,6 +69,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private D3D12RenderTarget sceneRenderTarget; private D3D12RenderTarget sceneMetadataRenderTarget; private D3D12RenderTarget sceneControlRenderTarget; + private readonly D3D12RenderTarget[] historyRenderTargets = new D3D12RenderTarget[2]; + private readonly D3D12RenderTarget[] historyMetadataRenderTargets = new D3D12RenderTarget[2]; + private readonly D3D12RenderTarget[] historyControlRenderTargets = new D3D12RenderTarget[2]; private readonly D3D12RenderTarget[] bloomRenderTargets = new D3D12RenderTarget[BloomLevelCount]; private readonly D3D12RenderTarget[] bloomScratchTargets = new D3D12RenderTarget[BloomLevelCount]; private readonly D3D12StructuredBuffer froxelPrimitiveBuffer; @@ -148,6 +151,7 @@ public sealed class D3D12Renderer : IAquariumRenderer sceneRenderTarget = CreateSceneRenderTarget(); sceneMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-metadata-target", "Aquarium D3D12 Scene Metadata Target"); sceneControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-control-target", "Aquarium D3D12 Scene Control Target"); + CreateHistoryRenderTargets(); CreateBloomRenderTargets(); froxelPrimitiveBuffer = new D3D12StructuredBuffer(device, FroxelBufferElementCount, Marshal.SizeOf(), "Aquarium D3D12 Froxel Primitive Buffer"); fieldInstanceBuffer = new D3D12StructuredBuffer(device, FieldInstanceCount, Marshal.SizeOf(), "Aquarium D3D12 Field Instance Buffer"); @@ -186,8 +190,8 @@ public sealed class D3D12Renderer : IAquariumRenderer bloomBlurHorizontalPipelineState.Name = "Aquarium D3D12 Bloom Blur Horizontal Pipeline"; bloomBlurVerticalPipelineState = CreateBloomBlurVerticalPipelineState(postShaderPath); bloomBlurVerticalPipelineState.Name = "Aquarium D3D12 Bloom Blur Vertical Pipeline"; - presentPipelineState = CreatePresentPipelineState(postShaderPath); - presentPipelineState.Name = "Aquarium D3D12 Present Pipeline"; + resolvePipelineState = CreateResolvePipelineState(postShaderPath); + resolvePipelineState.Name = "Aquarium D3D12 Resolve Pipeline"; viewport = new Viewport(0.0f, 0.0f, width, height); scissorRect = new RawRect(0, 0, width, height); fence = device.CreateFence(0); @@ -300,6 +304,13 @@ public sealed class D3D12Renderer : IAquariumRenderer sceneMetadataRenderTarget.CreateShaderResourceView(device, frameResources.SceneMetadataDescriptor); frameResources.SceneControlDescriptor = frameResources.TransientShaderDescriptors.Allocate(); sceneControlRenderTarget.CreateShaderResourceView(device, frameResources.SceneControlDescriptor); + var historyReadIndex = temporalFrameIndex & 1; + frameResources.HistoryDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + historyRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryDescriptor); + frameResources.HistoryMetadataDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + historyMetadataRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryMetadataDescriptor); + frameResources.HistoryControlDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + historyControlRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryControlDescriptor); for (var level = 0; level < BloomLevelCount; level++) { frameResources.BloomDescriptors[level] = frameResources.TransientShaderDescriptors.Allocate(); @@ -353,7 +364,7 @@ public sealed class D3D12Renderer : IAquariumRenderer fenceEvent.Dispose(); fence.Dispose(); commandList.Dispose(); - presentPipelineState.Dispose(); + resolvePipelineState.Dispose(); bloomBlurVerticalPipelineState.Dispose(); bloomBlurHorizontalPipelineState.Dispose(); bloomDownsamplePipelineState.Dispose(); @@ -369,6 +380,7 @@ public sealed class D3D12Renderer : IAquariumRenderer transparentSurfaceBuffer.Dispose(); transparentSurfaceIndexBuffer.Dispose(); DisposeBloomRenderTargets(); + DisposeHistoryRenderTargets(); sceneRenderTarget.Dispose(); sceneMetadataRenderTarget.Dispose(); sceneControlRenderTarget.Dispose(); @@ -419,6 +431,7 @@ public sealed class D3D12Renderer : IAquariumRenderer WaitForGpu(); RemoveBloomRenderTargets(); + RemoveHistoryRenderTargets(); resourceRegistry.RemoveRenderTarget("scene-hdr-target"); resourceRegistry.RemoveRenderTarget("scene-metadata-target"); resourceRegistry.RemoveRenderTarget("scene-control-target"); @@ -426,6 +439,7 @@ public sealed class D3D12Renderer : IAquariumRenderer resourceRegistry.RemoveRenderTarget("medium-volume-target"); resourceRegistry.RemoveRenderTarget("grid-height-target"); DisposeBloomRenderTargets(); + DisposeHistoryRenderTargets(); sceneRenderTarget.Dispose(); sceneMetadataRenderTarget.Dispose(); sceneControlRenderTarget.Dispose(); @@ -455,6 +469,7 @@ public sealed class D3D12Renderer : IAquariumRenderer sceneRenderTarget = CreateSceneRenderTarget(); sceneMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-metadata-target", "Aquarium D3D12 Scene Metadata Target"); sceneControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-control-target", "Aquarium D3D12 Scene Control Target"); + CreateHistoryRenderTargets(); CreateBloomRenderTargets(); viewport = new Viewport(0.0f, 0.0f, width, height); scissorRect = new RawRect(0, 0, width, height); @@ -504,6 +519,36 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private void CreateHistoryRenderTargets() + { + for (var index = 0; index < 2; index++) + { + historyRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-{index}", $"Aquarium D3D12 History {index}"); + historyMetadataRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-metadata-{index}", $"Aquarium D3D12 History Metadata {index}"); + historyControlRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-control-{index}", $"Aquarium D3D12 History Control {index}"); + } + } + + private void RemoveHistoryRenderTargets() + { + for (var index = 0; index < 2; index++) + { + resourceRegistry.RemoveRenderTarget($"history-{index}"); + resourceRegistry.RemoveRenderTarget($"history-metadata-{index}"); + resourceRegistry.RemoveRenderTarget($"history-control-{index}"); + } + } + + private void DisposeHistoryRenderTargets() + { + for (var index = 0; index < 2; index++) + { + historyRenderTargets[index]?.Dispose(); + historyMetadataRenderTargets[index]?.Dispose(); + historyControlRenderTargets[index]?.Dispose(); + } + } + private D3D12RenderTarget CreateBloomRenderTarget(int level, bool scratch) { var target = new D3D12RenderTarget( @@ -690,33 +735,62 @@ public sealed class D3D12Renderer : IAquariumRenderer try { var showMediumDensity = RenderDebugMode == 11; - var sourceTarget = showMediumDensity ? mediumVolumeRenderTarget : sceneRenderTarget; - var sourceDescriptor = showMediumDensity ? frameResources.MediumTargetsDescriptor : frameResources.SceneDescriptor; - var pipelineState = showMediumDensity ? mediumDensityDebugPipelineState : presentPipelineState; + var historyReadIndex = temporalFrameIndex & 1; + var historyWriteIndex = 1 - historyReadIndex; - sourceTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - if (!showMediumDensity) + if (showMediumDensity) { - sceneMetadataRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - sceneControlRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); + mediumVolumeRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); + context.BackBuffer.Transition(context.CommandList, ResourceStates.RenderTarget); + context.CommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); + context.CommandList.SetPipelineState(mediumDensityDebugPipelineState); + context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature); + context.CommandList.SetGraphicsRootDescriptorTable(1, frameResources.MediumTargetsDescriptor.Gpu); + context.CommandList.RSSetViewports(viewport); + context.CommandList.RSSetScissorRects(scissorRect); + context.CommandList.OMSetRenderTargets(context.RenderTargetView, null); + context.CommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); + context.CommandList.DrawInstanced(3, 1, 0, 0); + context.BackBuffer.Transition(context.CommandList, ResourceStates.Present); + return; } + sceneRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); + sceneMetadataRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); + sceneControlRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); + historyRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); + historyMetadataRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); + historyControlRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); + historyRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); + historyMetadataRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); + historyControlRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); + context.CommandList.ClearRenderTargetView(historyRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); + context.CommandList.ClearRenderTargetView(historyMetadataRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); + context.CommandList.ClearRenderTargetView(historyControlRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); + context.BackBuffer.Transition(context.CommandList, ResourceStates.RenderTarget); context.CommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); - context.CommandList.SetPipelineState(pipelineState); + context.CommandList.SetPipelineState(resolvePipelineState); context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature); context.CommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(1, sourceDescriptor.Gpu); - if (!showMediumDensity) - { - context.CommandList.SetGraphicsRootDescriptorTable(7, frameResources.BloomPresentationDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(8, frameResources.SceneMetadataDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(9, frameResources.SceneControlDescriptor.Gpu); - } + context.CommandList.SetGraphicsRootDescriptorTable(1, frameResources.SceneDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(7, frameResources.BloomPresentationDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(8, frameResources.SceneMetadataDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(9, frameResources.SceneControlDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(10, frameResources.HistoryDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(11, frameResources.HistoryMetadataDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(12, frameResources.HistoryControlDescriptor.Gpu); context.CommandList.RSSetViewports(viewport); context.CommandList.RSSetScissorRects(scissorRect); - context.CommandList.OMSetRenderTargets(context.RenderTargetView, null); + context.CommandList.OMSetRenderTargets( + [ + context.RenderTargetView, + historyRenderTargets[historyWriteIndex].RenderTargetView.Cpu, + historyMetadataRenderTargets[historyWriteIndex].RenderTargetView.Cpu, + historyControlRenderTargets[historyWriteIndex].RenderTargetView.Cpu, + ], + null); context.CommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); context.CommandList.DrawInstanced(3, 1, 0, 0); context.BackBuffer.Transition(context.CommandList, ResourceStates.Present); @@ -1238,6 +1312,24 @@ public sealed class D3D12Renderer : IAquariumRenderer 7, 0, D3D12.DescriptorRangeOffsetAppend); + var historyRange = new DescriptorRange( + DescriptorRangeType.ShaderResourceView, + 1, + 4, + 0, + D3D12.DescriptorRangeOffsetAppend); + var historyMetadataRange = new DescriptorRange( + DescriptorRangeType.ShaderResourceView, + 1, + 6, + 0, + D3D12.DescriptorRangeOffsetAppend); + var historyControlRange = new DescriptorRange( + DescriptorRangeType.ShaderResourceView, + 1, + 8, + 0, + D3D12.DescriptorRangeOffsetAppend); var rootParameters = new[] { new RootParameter(new RootDescriptorTable([constantBufferRange]), ShaderVisibility.All), @@ -1250,6 +1342,9 @@ public sealed class D3D12Renderer : IAquariumRenderer new RootParameter(new RootDescriptorTable([bloomRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([currentSceneMetadataRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([currentSceneControlRange]), ShaderVisibility.Pixel), + new RootParameter(new RootDescriptorTable([historyRange]), ShaderVisibility.Pixel), + new RootParameter(new RootDescriptorTable([historyMetadataRange]), ShaderVisibility.Pixel), + new RootParameter(new RootDescriptorTable([historyControlRange]), ShaderVisibility.Pixel), }; var staticSamplers = new[] { @@ -1316,9 +1411,13 @@ public sealed class D3D12Renderer : IAquariumRenderer return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomBlurVerticalPS", SceneHdrFormat); } - private ID3D12PipelineState CreatePresentPipelineState(string path) + private ID3D12PipelineState CreateResolvePipelineState(string path) { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12PresentPS", Format.B8G8R8A8_UNorm); + return CreateFullscreenPipelineState( + path, + "FullscreenTriangleVS", + "D3D12ResolvePS", + [Format.B8G8R8A8_UNorm, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat]); } private ID3D12PipelineState CreateGridHeightBasePipelineState(string path) @@ -1618,6 +1717,12 @@ public sealed class D3D12Renderer : IAquariumRenderer public D3D12DescriptorSlot SceneControlDescriptor { get; set; } + public D3D12DescriptorSlot HistoryDescriptor { get; set; } + + public D3D12DescriptorSlot HistoryMetadataDescriptor { get; set; } + + public D3D12DescriptorSlot HistoryControlDescriptor { get; set; } + public D3D12DescriptorSlot[] BloomDescriptors { get; } = new D3D12DescriptorSlot[BloomLevelCount]; public D3D12DescriptorSlot[] BloomScratchDescriptors { get; } = new D3D12DescriptorSlot[BloomLevelCount]; diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl index abbd479..79fdf74 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl @@ -23,8 +23,11 @@ cbuffer AquariumFrame : register(b0) }; Texture2D sourceTexture : register(t0); +Texture2D historyTexture : register(t4); Texture2D currentSceneMetadataTexture : register(t5); +Texture2D historyMetadataTexture : register(t6); Texture2D currentSceneControlTexture : register(t7); +Texture2D historyControlTexture : register(t8); Texture2D bloomTexture0 : register(t9); Texture2D bloomTexture1 : register(t10); Texture2D bloomTexture2 : register(t11); @@ -36,6 +39,21 @@ struct VertexOut float2 uv : TEXCOORD0; }; +struct ResolveOut +{ + float4 finalColor : SV_Target0; + float4 historyColor : SV_Target1; + float4 historyMetadata : SV_Target2; + float4 historyControl : SV_Target3; +}; + +static const float SUN_RADIUS = 1.12; +static const int PLANET_COUNT = 5; +static const float FIELD_ID_GRID = 1.0; +static const float FIELD_ID_SELF = 2.0; +static const float FIELD_ID_PLANET_BASE = 10.0; +static const float MAX_HISTORY_AGE = 32.0; + VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) { float2 uv = float2((vertexId << 1) & 2, vertexId & 2); @@ -89,6 +107,134 @@ float3 debugFieldIdColor(float fieldId) return float3(1.0, 0.0, 1.0); } +float hash21(float2 p) +{ + p = frac(p * float2(123.34, 456.21)); + p += dot(p, p + 45.32); + return frac(p.x * p.y); +} + +float planetRadius(int index) +{ + return lerp(0.34, 0.62, hash21(float2(index, 19.7))); +} + +float3 planetCenterAt(int index, float sampleTime) +{ + float f = (float)index; + float angle = f * 0.8975979 + sampleTime * (0.08 + 0.011 * f); + float radius = 4.1 + f * 0.77; + float2 xy = float2(cos(angle), sin(angle)) * radius; + return float3(xy, 1.15 + planetRadius(index) * 0.72); +} + +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); +} + +float3 temporalPreviousWorldPosition(float3 worldPosition, float fieldId) +{ + if (fieldId >= FIELD_ID_PLANET_BASE) + { + int planetIndex = clamp((int)round(fieldId - FIELD_ID_PLANET_BASE), 0, PLANET_COUNT - 1); + float3 currentCenter = planetCenterAt(planetIndex, timeSeconds); + float3 previousCenter = planetCenterAt(planetIndex, previousTimeSeconds); + return previousCenter + (worldPosition - currentCenter); + } + + return worldPosition; +} + +float2 projectWorldToPreviousHistoryUv(float3 worldPosition) +{ + float3 forward; + float3 right; + float3 up; + cameraBasis(previousCameraPosition, previousGridCenter, forward, right, up); + float3 delta = worldPosition - previousCameraPosition; + float z = max(dot(delta, forward), 0.0001); + float2 ndc = float2(dot(delta, right), dot(delta, up)) / z * 1.6; + float2 pixel = (ndc * resolution.y + resolution) * 0.5 - previousJitterPixels; + return float2(pixel.x / resolution.x, 1.0 - pixel.y / resolution.y); +} + +int2 pixelFromUv(float2 uv) +{ + return clamp((int2)floor(uv * resolution), int2(0, 0), (int2)resolution - int2(1, 1)); +} + +float4 loadCurrentMetadata(float2 uv) +{ + return currentSceneMetadataTexture.Load(int3(pixelFromUv(uv), 0)); +} + +float4 loadCurrentControl(float2 uv) +{ + return currentSceneControlTexture.Load(int3(pixelFromUv(uv), 0)); +} + +float4 loadHistoryColor(float2 uv) +{ + return historyTexture.Load(int3(pixelFromUv(uv), 0)); +} + +float4 loadHistoryMetadata(float2 uv) +{ + return historyMetadataTexture.Load(int3(pixelFromUv(uv), 0)); +} + +float4 loadHistoryControl(float2 uv) +{ + return historyControlTexture.Load(int3(pixelFromUv(uv), 0)); +} + +void currentNeighborhood(float2 uv, out float3 neighborhoodMin, out float3 neighborhoodMax) +{ + float2 texel = 1.0 / resolution; + neighborhoodMin = 100000.0; + neighborhoodMax = -100000.0; + + [unroll] + for (int y = -1; y <= 1; y++) + { + [unroll] + for (int x = -1; x <= 1; x++) + { + float3 sampleColor = sourceTexture.SampleLevel(sourceSampler, uv + float2(x, y) * texel, 0.0).rgb; + neighborhoodMin = min(neighborhoodMin, sampleColor); + neighborhoodMax = max(neighborhoodMax, sampleColor); + } + } +} + +float3 bloomColorAt(float2 uv) +{ + return bloomTexture0.SampleLevel(sourceSampler, uv, 0.0).rgb * 0.42 + + bloomTexture1.SampleLevel(sourceSampler, uv, 0.0).rgb * 0.34 + + bloomTexture2.SampleLevel(sourceSampler, uv, 0.0).rgb * 0.24; +} + +float3 presentColor(float3 scene, float2 uv) +{ + float3 bloom = bloomColorAt(uv); + float3 exposedScene = scene * max(exposure, 0.001); + return aces(exposedScene + bloom * bloomIntensity + luminance(bloom) * bloomVeilIntensity); +} + float4 D3D12BloomPrefilterPS(VertexOut input) : SV_Target0 { return float4(sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0).rgb * max(exposure, 0.001), 1.0); @@ -149,41 +295,113 @@ float4 D3D12BloomBlurVerticalPS(VertexOut input) : SV_Target0 return float4(color, 1.0); } -float4 D3D12PresentPS(VertexOut input) : SV_Target0 +ResolveOut D3D12ResolvePS(VertexOut input) { - float3 scene = sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0).rgb * max(exposure, 0.001); - float3 bloom = - bloomTexture0.SampleLevel(sourceSampler, input.uv, 0.0).rgb * 0.42 + - bloomTexture1.SampleLevel(sourceSampler, input.uv, 0.0).rgb * 0.34 + - bloomTexture2.SampleLevel(sourceSampler, input.uv, 0.0).rgb * 0.24; + float2 screenUv = float2(input.uv.x, 1.0 - input.uv.y); + float2 pixel = screenUv * resolution; + float4 current = sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0); + float currentTravel = current.a; + float3 currentColor = current.rgb; + float4 currentMetadata = loadCurrentMetadata(input.uv); + float4 currentControl = loadCurrentControl(input.uv); + float currentFieldId = currentMetadata.x; + float3 currentNormal = currentMetadata.yzw; + float currentReactive = saturate(currentControl.x); + float currentCoverage = saturate(currentControl.y); + float currentMediumOpacity = saturate(currentControl.z); + + float historyWeight = 0.0; + float historyAge = 0.0; + float3 historyColor = currentColor; + if (frameIndex > 0.5 && currentTravel <= farDistance && currentFieldId > 0.5) + { + float3 currentRay = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, gridCenter); + float3 worldPosition = cameraPosition + currentRay * currentTravel; + float3 previousWorldPosition = temporalPreviousWorldPosition(worldPosition, currentFieldId); + float2 previousUv = projectWorldToPreviousHistoryUv(previousWorldPosition); + + if (all(previousUv >= 0.0) && all(previousUv <= 1.0)) + { + float4 previousMetadata = loadHistoryMetadata(previousUv); + float4 previousControl = loadHistoryControl(previousUv); + float4 previous = historyTexture.SampleLevel(sourceSampler, previousUv, 0.0); + float previousFieldId = previousMetadata.x; + float previousTravel = previous.a; + float3 previousNormal = previousMetadata.yzw; + float previousCoverage = saturate(previousControl.y); + float previousMediumOpacity = saturate(previousControl.z); + float previousHistoryAge = max(previousControl.w, 0.0); + float expectedPreviousTravel = distance(previousCameraPosition, previousWorldPosition); + float travelDelta = abs(previousTravel - expectedPreviousTravel); + float travelTolerance = max(0.045, expectedPreviousTravel * 0.018); + float travelWeight = 1.0 - smoothstep(travelTolerance, travelTolerance * 4.0, travelDelta); + float fieldWeight = abs(previousFieldId - currentFieldId) < 0.001 ? 1.0 : 0.0; + float normalWeight = 0.0; + if (dot(previousNormal, previousNormal) > 0.01 && dot(currentNormal, currentNormal) > 0.01) + { + normalWeight = smoothstep(0.68, 0.96, dot(normalize(previousNormal), normalize(currentNormal))); + } + + float3 neighborhoodMin; + float3 neighborhoodMax; + currentNeighborhood(input.uv, neighborhoodMin, neighborhoodMax); + float3 clampedHistory = clamp(previous.rgb, neighborhoodMin, neighborhoodMax); + float colorDelta = length(clampedHistory - currentColor); + float colorWeight = 1.0 - smoothstep(0.18, 1.2, colorDelta); + float reactiveWeight = 1.0 - currentReactive; + float coverageWeight = smoothstep(0.02, 0.55, currentCoverage); + float coverageContinuityWeight = 1.0 - smoothstep(0.10, 0.50, abs(previousCoverage - currentCoverage)); + float mediumContinuityWeight = 1.0 - smoothstep(0.04, 0.35, abs(previousMediumOpacity - currentMediumOpacity)); + float historyConfidence = smoothstep(0.0, 6.0, previousHistoryAge); + float validationWeight = travelWeight * colorWeight * fieldWeight * normalWeight * reactiveWeight * coverageWeight * coverageContinuityWeight * mediumContinuityWeight; + + historyColor = clampedHistory; + historyWeight = 0.82 * lerp(0.35, 1.0, historyConfidence) * validationWeight; + historyAge = validationWeight > 0.01 ? min(previousHistoryAge + 1.0, MAX_HISTORY_AGE) : 0.0; + } + } + + float3 resolved = lerp(currentColor, historyColor, historyWeight); + float3 finalColor = presentColor(resolved, input.uv); if (renderDebugMode > 0.5 && renderDebugMode < 1.5) { - return float4(aces(scene), 1.0); + finalColor = aces(currentColor * max(exposure, 0.001)); } - - if (renderDebugMode >= 4.5 && renderDebugMode < 5.5) + else if (renderDebugMode >= 1.5 && renderDebugMode < 2.5) { - float4 control = currentSceneControlTexture.SampleLevel(sourceSampler, input.uv, 0.0); - return float4(saturate(control.xyz), 1.0); + finalColor = aces(historyColor * max(exposure, 0.001)); } - - if (renderDebugMode >= 5.5 && renderDebugMode < 6.5) + else if (renderDebugMode >= 2.5 && renderDebugMode < 3.5) { - float fieldId = currentSceneMetadataTexture.SampleLevel(sourceSampler, input.uv, 0.0).x; - return float4(debugFieldIdColor(fieldId), 1.0); + finalColor = (historyAge / MAX_HISTORY_AGE).xxx; } - - if (renderDebugMode >= 6.5 && renderDebugMode < 7.5) + else if (renderDebugMode >= 3.5 && renderDebugMode < 4.5) { - return float4(aces(bloom * bloomIntensity), 1.0); + finalColor = historyWeight.xxx; } - - if (renderDebugMode >= 7.5 && renderDebugMode < 8.5) + else if (renderDebugMode >= 4.5 && renderDebugMode < 5.5) { - float luma = luminance(scene); - return float4(luma.xxx, 1.0); + finalColor = saturate(currentControl.xyz); + } + else if (renderDebugMode >= 5.5 && renderDebugMode < 6.5) + { + finalColor = debugFieldIdColor(currentFieldId); + } + else if (renderDebugMode >= 6.5 && renderDebugMode < 7.5) + { + float3 bloom = bloomColorAt(input.uv); + finalColor = aces(bloom * bloomIntensity + luminance(bloom) * bloomVeilIntensity); + } + else if (renderDebugMode >= 7.5 && renderDebugMode < 8.5) + { + float luma = luminance(currentColor * max(exposure, 0.001)); + finalColor = luma.xxx; } - float3 presented = scene + bloom * bloomIntensity + luminance(bloom) * bloomVeilIntensity; - return float4(aces(presented), 1.0); + ResolveOut output; + output.finalColor = float4(finalColor, 1.0); + output.historyColor = float4(resolved, currentTravel); + output.historyMetadata = currentMetadata; + output.historyControl = float4(currentControl.xyz, historyAge); + return output; } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 3401a9d..8edf35d 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -80,3 +80,4 @@ {"area":"renderer/d3d12","lesson":"D3D12 presentation now mirrors the HDR doctrine: render scene-linear into an R16G16B16A16_Float scene target, build a three-level half/quarter/eighth bloom pyramid with firefly-safe downsample and separable blur scratch targets, then apply exposure, bloom/veil composite, and ACES only in the present pass. Debug mode 7 shows bloom contribution, mode 8 exposed luminance, and mode 11 remains a direct medium-density bypass.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","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=0 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=7 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0"],"ts":"2026-05-09"} {"area":"renderer/d3d12","lesson":"D3D12 Grid transparency now carries the richer Aetheria/Aquarium line vocabulary inside the transparent-surface froxel path: cartesian gridlines, height isolines, and gradient-angle field lines are evaluated from the Grid height target and integrated as binned transparent medium contribution, not as a revived alpha-blended surface path.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl","docs/d3d12-migration.md","docs/hlsl-renderer.md","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"],"ts":"2026-05-09"} {"area":"renderer/d3d12/temporal","lesson":"D3D12 now has the first temporal diagnostic spine: the scene pass writes color/travel, field-id/normal metadata, and temporal-control MRTs, and the present shader can inspect current control in debug mode 5 and field identity in debug mode 6. This is not TAA parity yet; history ping-pong, reprojection, validation, and age/weight outputs still need to be ported before temporal accumulation is real.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","docs/d3d12-migration.md","docs/hlsl-renderer.md","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=0 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=5 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=6 exited 0"],"ts":"2026-05-09"} +{"area":"renderer/d3d12/temporal","lesson":"D3D12 resolve now owns presentation and history output: it writes the swapchain plus ping-pong history color, metadata, and control targets. Opaque current scene hits reproject through previous camera/Grid state, remap orbiting planet hits to previous centers, and validate by field id, travel, normal, neighborhood color, coverage, and medium opacity before blending. Debug mode 3 shows history age and mode 4 history weight. Grid/transparent-specific temporal reconstruction remains pending.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","docs/d3d12-migration.md","docs/hlsl-renderer.md","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=0 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=3 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=4 exited 0",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 20 with AQUARIUM_RENDERER=d3d12 and AQUARIUM_RENDER_DEBUG_MODE=11 exited 0"],"ts":"2026-05-09"} diff --git a/state/scratch.md b/state/scratch.md index c200f44..2edaf4b 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -316,3 +316,10 @@ can start porting real passes while keeping D3D11 as the visual reference. mode 5 shows current control and mode 6 shows field identity. History ping-pong/reprojection is still pending; do not claim TAA parity until those buffers are written and validated. +- D3D12 temporal history pass: resolve now writes ping-pong color, metadata, + and control history targets and presents through the resolve shader. Opaque + current scene hits reproject through previous camera/Grid state, remap planet + hits to previous centers, and validate history by field id, travel, normal, + neighborhood color, coverage, and medium opacity. Debug mode 3 shows history + age and mode 4 shows history weight. Grid/transparent-specific temporal + reconstruction remains pending.