From 99ad2fa885ee7e0b7a725dd982ea95f014b5c2d3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 29 May 2026 01:50:07 +0100 Subject: [PATCH] Promote TubeField reservoir candidates to columns --- src/Aquarium.Engine/Render/D3D12Renderer.cs | 144 +++++--- .../Render/Shaders/D3D12TubeField.hlsl | 327 +++++++++++------- state/evidence.jsonl | 1 + state/map.yaml | 26 +- 4 files changed, 300 insertions(+), 198 deletions(-) diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 272acfd..74aa935 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -39,9 +39,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int GpuSensorSamplesPerTexture = 131_072; private const int MaxTemporalGaussianCount = 1_048_576; private const int MaxVisibleFractalSplatCount = 524_288; - private const int MaxTubeFieldSegments = 65_536; - private const int MaxTubeFieldVertices = MaxTubeFieldSegments * 4; - private const int MaxTubeFieldIndices = MaxTubeFieldSegments * 6; + private const int MaxTubeFieldColumns = 65_536; + private const int MaxTubeFieldVertices = MaxTubeFieldColumns * 4; + private const int MaxTubeFieldIndices = MaxTubeFieldColumns * 6; private const int MaxTubeFieldDrawBatches = 4_096; private const int TubeFieldRestirTileSize = 16; private const int TubeFieldRestirMaxTileSegments = 128; @@ -129,6 +129,8 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int RootTubeFieldRestirWriteReservoirs = 9; private const int RootTubeFieldRestirFieldCandidates = 10; private const int RootTubeFieldRestirTileCountsRead = 11; + private const int RootTubeFieldRestirRamp = 12; + private const int RootTubeFieldRestirSource = 13; private static readonly DebugUi.DebugUiOption[] RenderDebugOptions = [ new(0, "Final"), @@ -259,7 +261,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private D3D12StructuredBuffer? bufferFieldTextureSampleBuffer; private readonly D3D12StructuredBuffer tubeFieldVertexBuffer; private readonly D3D12StructuredBuffer tubeFieldIndexBuffer; - private readonly D3D12StructuredBuffer tubeFieldSegmentBuffer; + private readonly D3D12StructuredBuffer tubeFieldColumnBuffer; private D3D12StructuredBuffer tubeFieldRestirTileCountBuffer = null!; private D3D12StructuredBuffer tubeFieldRestirTileSegmentBuffer = null!; private D3D12StructuredBuffer tubeFieldRestirScratchReservoirBuffer = null!; @@ -314,9 +316,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private AquariumFieldLoweringPlan activeFieldLoweringPlan = AquariumFieldLoweringPlan.Empty; private D3D12FieldResourceStats activeFieldResourceStats = D3D12FieldResourceStats.Empty; private int activeTubeFieldDrawIndexCount; - private int activeTubeFieldDispatchedSegments; - private int activeTubeFieldRequestedSegments; - private int activeTubeFieldTruncatedSegments; + private int activeTubeFieldDispatchedColumns; + private int activeTubeFieldRequestedColumns; + private int activeTubeFieldTruncatedColumns; private int activeTubeFieldIndirectDrawCount; private int activeTubeFieldSkippedDrawBatches; private int activeTubeFieldUnplannedLowerings; @@ -453,7 +455,7 @@ public sealed class D3D12Renderer : IAquariumRenderer temporalGaussianBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 Temporal Gaussian Buffer", allowUnorderedAccess: true); tubeFieldVertexBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldVertices, Marshal.SizeOf(), "Aquarium D3D12 TubeField Vertex Buffer", allowUnorderedAccess: true); tubeFieldIndexBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldIndices, Marshal.SizeOf(), "Aquarium D3D12 TubeField Index Buffer", allowUnorderedAccess: true); - tubeFieldSegmentBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldSegments, Marshal.SizeOf(), "Aquarium D3D12 TubeField Segment Buffer", allowUnorderedAccess: true); + tubeFieldColumnBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldColumns, Marshal.SizeOf(), "Aquarium D3D12 TubeField Column Buffer", allowUnorderedAccess: true); tubeFieldStatsBuffer = new D3D12StructuredBuffer(device, 4, Marshal.SizeOf(), "Aquarium D3D12 TubeField Stats Buffer", allowUnorderedAccess: true); tubeFieldDrawArgumentBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldDrawBatches * GeneratedMeshDrawArgumentUIntCount, Marshal.SizeOf(), "Aquarium D3D12 TubeField Indirect Draw Arguments", allowUnorderedAccess: true); CreateTubeFieldRestirBuffers(); @@ -467,7 +469,7 @@ public sealed class D3D12Renderer : IAquariumRenderer resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); resourceRegistry.Add("tube-field-vertex-buffer", tubeFieldVertexBuffer); resourceRegistry.Add("tube-field-index-buffer", tubeFieldIndexBuffer); - resourceRegistry.Add("tube-field-segment-buffer", tubeFieldSegmentBuffer); + resourceRegistry.Add("tube-field-column-buffer", tubeFieldColumnBuffer); resourceRegistry.Add("tube-field-stats-buffer", tubeFieldStatsBuffer); resourceRegistry.Add("tube-field-indirect-draw-arguments", tubeFieldDrawArgumentBuffer); commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); @@ -648,7 +650,7 @@ public sealed class D3D12Renderer : IAquariumRenderer $"candidates {activeFieldEvidenceFrame.Candidates.Count} / packets {activeFieldEvidenceFrame.BackendPackets.Count} / " + $"planned {activeFieldLoweringPlan.Packets.Count} / deferred {activeFieldLoweringPlan.DeferredRequests.Count} / errors {errorCount}" + (activeFieldEvidenceFrame.TubeSplineLowerings.Count > 0 - ? $" / tube requested {activeTubeFieldRequestedSegments} dispatched {activeTubeFieldDispatchedSegments} truncated {activeTubeFieldTruncatedSegments} invalid {activeTubeFieldInvalidColumns} uploads {activeFieldResourceUploadCount} skipped {activeFieldResourceUploadSkippedCount} unplanned {activeTubeFieldUnplannedLowerings}" + ? $" / tube columns requested {activeTubeFieldRequestedColumns} dispatched {activeTubeFieldDispatchedColumns} truncated {activeTubeFieldTruncatedColumns} invalid {activeTubeFieldInvalidColumns} uploads {activeFieldResourceUploadCount} skipped {activeFieldResourceUploadSkippedCount} unplanned {activeTubeFieldUnplannedLowerings}" : string.Empty); } @@ -1227,7 +1229,7 @@ public sealed class D3D12Renderer : IAquariumRenderer DisposeTubeFieldRestirBuffers(); tubeFieldStatsBuffer.Dispose(); tubeFieldDrawArgumentBuffer.Dispose(); - tubeFieldSegmentBuffer.Dispose(); + tubeFieldColumnBuffer.Dispose(); tubeFieldIndexBuffer.Dispose(); tubeFieldVertexBuffer.Dispose(); fieldReservoirLockBuffer.Dispose(); @@ -2758,7 +2760,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private void DispatchTubeFieldRestir(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { - if (activeTubeFieldDispatchedSegments <= 0 || + if (activeTubeFieldDispatchedColumns <= 0 || tubeFieldDrawBatches.Count == 0 || tubeFieldRestirClearTilesPipelineState is null || tubeFieldRestirClearReservoirsPipelineState is null || @@ -2776,6 +2778,13 @@ public sealed class D3D12Renderer : IAquariumRenderer var tileCount = TubeFieldRestirTileCount(); activeCommandList.SetComputeRootSignature(tubeFieldRestirRootSignature); activeCommandList.SetComputeRootDescriptorTable(RootTubeFieldRestirFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); + var restirRamp = ResolveTubeFieldRamp(activeCommandList, tubeFieldDrawBatches[0].RampResourceKey); + restirRamp.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + var restirRampDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + restirRamp.CreateShaderResourceView(device, restirRampDescriptor); + activeCommandList.SetComputeRootDescriptorTable(RootTubeFieldRestirRamp, restirRampDescriptor.Gpu); + tubeFieldDrawBatches[0].Source.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldRestirSource, tubeFieldDrawBatches[0].Source.Resource.GPUVirtualAddress); BindTubeFieldRestirCommon(activeCommandList, previousReservoir, tubeFieldRestirScratchReservoirBuffer, currentReservoir, currentReservoir); currentReservoir.Transition(activeCommandList, ResourceStates.UnorderedAccess); @@ -2797,7 +2806,7 @@ public sealed class D3D12Renderer : IAquariumRenderer Vector4.Zero, Vector4.Zero, Vector4.Zero, - new Vector4(0.0f, 0.0f, 0.0f, activeTubeFieldDispatchedSegments), + new Vector4(0.0f, 0.0f, 0.0f, activeTubeFieldDispatchedColumns), Vector4.Zero, Vector3.Zero, 0.0f, @@ -2815,9 +2824,9 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldRestirTileCountBuffer.Resource)); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldRestirTileSegmentBuffer.Resource)); - tubeFieldSegmentBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + tubeFieldColumnBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); activeCommandList.SetPipelineState(tubeFieldRestirBinSegmentsPipelineState); - activeCommandList.Dispatch((uint)((activeTubeFieldDispatchedSegments + 255) / 256), 1, 1); + activeCommandList.Dispatch((uint)((activeTubeFieldDispatchedColumns + 255) / 256), 1, 1); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldRestirTileCountBuffer.Resource)); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldRestirTileSegmentBuffer.Resource)); @@ -2858,7 +2867,7 @@ public sealed class D3D12Renderer : IAquariumRenderer D3D12StructuredBuffer initialReservoir, D3D12StructuredBuffer writeReservoir) { - activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldRestirSegments, tubeFieldSegmentBuffer.Resource.GPUVirtualAddress); + activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldRestirSegments, tubeFieldColumnBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldRestirTileSegmentsRead, tubeFieldRestirTileSegmentBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldRestirPreviousReservoirs, previousReservoir.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldRestirReadReservoirs, readReservoir.Resource.GPUVirtualAddress); @@ -3308,9 +3317,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private void DispatchTubeFields(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { activeTubeFieldDrawIndexCount = 0; - activeTubeFieldDispatchedSegments = 0; - activeTubeFieldRequestedSegments = 0; - activeTubeFieldTruncatedSegments = 0; + activeTubeFieldDispatchedColumns = 0; + activeTubeFieldRequestedColumns = 0; + activeTubeFieldTruncatedColumns = 0; activeTubeFieldIndirectDrawCount = 0; activeTubeFieldSkippedDrawBatches = 0; activeTubeFieldUnplannedLowerings = 0; @@ -3362,22 +3371,22 @@ public sealed class D3D12Renderer : IAquariumRenderer } normalized = normalized with { ColumnCount = validColumnCount }; - var requestedSegments = checked(Math.Max(0, normalized.Width - 1) * Math.Max(1, normalized.CatmullRomSubdivisions) * Math.Max(1, normalized.ColumnCount)); - activeTubeFieldRequestedSegments += requestedSegments; - var remainingSegments = MaxTubeFieldSegments - segmentBase; - if (remainingSegments <= 0) + var requestedColumns = Math.Max(1, normalized.ColumnCount); + activeTubeFieldRequestedColumns += requestedColumns; + var remainingColumns = MaxTubeFieldColumns - segmentBase; + if (remainingColumns <= 0) { - activeTubeFieldTruncatedSegments += requestedSegments; + activeTubeFieldTruncatedColumns += requestedColumns; continue; } - var dispatchSegments = Math.Min(requestedSegments, remainingSegments); - if (dispatchSegments <= 0) + var dispatchColumns = Math.Min(requestedColumns, remainingColumns); + if (dispatchColumns <= 0) { continue; } - activeTubeFieldTruncatedSegments += requestedSegments - dispatchSegments; + activeTubeFieldTruncatedColumns += requestedColumns - dispatchColumns; var startIndex = segmentBase * 6; var fieldId = StableFieldId(lowering.ClaimKey, 5100.0f, 4096); var constants = new D3D12TubeFieldConstants( @@ -3385,7 +3394,7 @@ public sealed class D3D12Renderer : IAquariumRenderer new Vector4(normalized.ColumnCount, normalized.ColumnStride, normalized.RollingModulo, normalized.RollingOffset), new Vector4(normalized.AmplitudePower, normalized.AmplitudeScale, normalized.NormalizeMin, normalized.NormalizeMax), new Vector4(normalized.BaseRadius, normalized.RadiusScale, normalized.Alpha, normalized.Feather), - new Vector4(normalized.EmissionScale, normalized.CatmullRomSubdivisions, segmentBase, dispatchSegments), + new Vector4(normalized.EmissionScale, normalized.CatmullRomSubdivisions, segmentBase, dispatchColumns), new Vector4(tubeFieldDrawBatches.Count * GeneratedMeshDrawArgumentUIntCount, startIndex, fieldId, 0.0f), normalized.Origin, 0.0f, @@ -3408,22 +3417,22 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldIndices, tubeFieldIndexBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldStats, tubeFieldStatsBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldDrawArguments, tubeFieldDrawArgumentBuffer.Resource.GPUVirtualAddress); - tubeFieldSegmentBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldSegments, tubeFieldSegmentBuffer.Resource.GPUVirtualAddress); + tubeFieldColumnBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldSegments, tubeFieldColumnBuffer.Resource.GPUVirtualAddress); var ramp = ResolveTubeFieldRamp(activeCommandList, normalized.RampResourceKey); ramp.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); var rampDescriptor = frameResources.TransientShaderDescriptors.Allocate(); ramp.CreateShaderResourceView(device, rampDescriptor); activeCommandList.SetComputeRootDescriptorTable(RootTubeFieldRamp, rampDescriptor.Gpu); - activeCommandList.Dispatch((uint)((dispatchSegments + 255) / 256), 1, 1); + activeCommandList.Dispatch((uint)((dispatchColumns + 255) / 256), 1, 1); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldVertexBuffer.Resource)); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldIndexBuffer.Resource)); - activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldSegmentBuffer.Resource)); + activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldColumnBuffer.Resource)); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldStatsBuffer.Resource)); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(tubeFieldDrawArgumentBuffer.Resource)); - segmentBase += dispatchSegments; - activeTubeFieldDispatchedSegments += dispatchSegments; + segmentBase += dispatchColumns; + activeTubeFieldDispatchedColumns += dispatchColumns; activeTubeFieldIndirectDrawCount++; tubeFieldDrawBatches.Add(new D3D12TubeFieldDrawBatch( sourceBuffer, @@ -3432,7 +3441,7 @@ public sealed class D3D12Renderer : IAquariumRenderer tubeFieldDrawBatches.Count * GeneratedMeshDrawArgumentBytes)); } - activeTubeFieldDrawIndexCount = activeTubeFieldDispatchedSegments * 6; + activeTubeFieldDrawIndexCount = 0; } private HashSet PlannedTubeFieldClaimKeys() @@ -4159,9 +4168,9 @@ public sealed class D3D12Renderer : IAquariumRenderer { Console.WriteLine( $"D3D12 tube fields: lowerings {activeFieldEvidenceFrame.TubeSplineLowerings.Count:N0}; " + - $"segments requested {activeTubeFieldRequestedSegments:N0}; " + - $"dispatched {activeTubeFieldDispatchedSegments:N0}; " + - $"truncated {activeTubeFieldTruncatedSegments:N0}; " + + $"columns requested {activeTubeFieldRequestedColumns:N0}; " + + $"dispatched {activeTubeFieldDispatchedColumns:N0}; " + + $"truncated {activeTubeFieldTruncatedColumns:N0}; " + $"indirect draws {activeTubeFieldIndirectDrawCount:N0}; " + $"skipped draw batches {activeTubeFieldSkippedDrawBatches:N0}; " + $"unplanned lowerings {activeTubeFieldUnplannedLowerings:N0}; " + @@ -4169,7 +4178,7 @@ public sealed class D3D12Renderer : IAquariumRenderer $"resource uploads {activeFieldResourceUploadCount:N0}; " + $"skipped uploads {activeFieldResourceUploadSkippedCount:N0}; " + $"index draw count {activeTubeFieldDrawIndexCount:N0}; " + - $"budget {MaxTubeFieldSegments:N0}"); + $"budget {MaxTubeFieldColumns:N0}"); } if (accumulatedTimingFrames > 0) @@ -4318,11 +4327,11 @@ public sealed class D3D12Renderer : IAquariumRenderer var error = task.Exception?.GetBaseException() ?? new InvalidOperationException("D3D12 shader pipeline build was canceled."); if (PipelinesReady) { - Console.Error.WriteLine($"D3D12 shader hot reload failed; keeping previous pipelines. {error.Message}"); + Console.Error.WriteLine($"D3D12 shader hot reload failed; keeping previous pipelines. {error}"); } else { - Console.Error.WriteLine($"D3D12 initial shader pipeline build failed; retrying after source change. {error.Message}"); + Console.Error.WriteLine($"D3D12 initial shader pipeline build failed; retrying after source change. {error}"); } shaderReloadFailureReported = true; @@ -4788,6 +4797,12 @@ public sealed class D3D12Renderer : IAquariumRenderer 0, 0, D3D12.DescriptorRangeOffsetAppend); + var rampTexture = new DescriptorRange( + DescriptorRangeType.ShaderResourceView, + 1, + 43, + 0, + D3D12.DescriptorRangeOffsetAppend); var rootParameters = new[] { new RootParameter(new RootDescriptorTable([frameConstants]), ShaderVisibility.All), @@ -4802,11 +4817,30 @@ public sealed class D3D12Renderer : IAquariumRenderer new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(20, 0), ShaderVisibility.All), new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(21, 0), ShaderVisibility.All), new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(50, 0), ShaderVisibility.All), + new RootParameter(new RootDescriptorTable([rampTexture]), ShaderVisibility.All), + new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(42, 0), ShaderVisibility.All), + }; + var staticSamplers = new[] + { + new StaticSamplerDescription( + 0, + Filter.MinMagMipLinear, + TextureAddressMode.Clamp, + TextureAddressMode.Clamp, + TextureAddressMode.Clamp, + 0.0f, + 1, + ComparisonFunction.Never, + StaticBorderColor.TransparentBlack, + 0.0f, + float.MaxValue, + ShaderVisibility.All, + 0), }; var description = new RootSignatureDescription( RootSignatureFlags.None, rootParameters, - []); + staticSamplers); return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); } @@ -5025,7 +5059,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private ID3D12PipelineState CreateTubeFieldRestirPipelineState(string path, string entryPoint) { - var computeShader = CompileShader(path, entryPoint, "cs_5_0"); + var computeShader = CompileShader(path, entryPoint, "cs_5_0", skipOptimizationInDebug: false); var description = new ComputePipelineStateDescription { RootSignature = tubeFieldRestirRootSignature, @@ -5250,11 +5284,15 @@ public sealed class D3D12Renderer : IAquariumRenderer } } - private static ReadOnlyMemory CompileShader(string path, string entryPoint, string profile) + private static ReadOnlyMemory CompileShader(string path, string entryPoint, string profile, bool skipOptimizationInDebug = true) { var shaderFlags = ShaderFlags.EnableStrictness; #if DEBUG - shaderFlags |= ShaderFlags.Debug | ShaderFlags.SkipOptimization; + shaderFlags |= ShaderFlags.Debug; + if (skipOptimizationInDebug) + { + shaderFlags |= ShaderFlags.SkipOptimization; + } #endif var source = ExpandShaderIncludes(path, []); @@ -5368,15 +5406,15 @@ public sealed class D3D12Renderer : IAquariumRenderer Vector4 TubeData); [StructLayout(LayoutKind.Sequential)] - private readonly record struct D3D12TubeFieldSegment( - Vector4 PreviousRadius, - Vector4 StartRadius, - Vector4 EndFeather, - Vector4 NextAlpha, - Vector4 Color0, - Vector4 Color1, + private readonly record struct D3D12TubeFieldColumn( + Vector4 Shape, + Vector4 Columns, + Vector4 Amplitude, Vector4 Material, - Vector4 TubeData); + Vector4 DispatchDraw, + Vector4 OriginField, + Vector4 AxisStepEmission, + Vector4 ColumnStep); private readonly record struct D3D12TubeFieldDrawBatch( D3D12StructuredBuffer Source, diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl index be9e521..91722af 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl @@ -24,6 +24,18 @@ struct TubeFieldSegment float4 tubeData; }; +struct TubeFieldColumn +{ + float4 shape; + float4 columns; + float4 amplitude; + float4 material; + float4 dispatchDraw; + float4 originField; + float4 axisStepEmission; + float4 columnStep; +}; + struct FieldReservoirCandidate { float4 colorTravel; @@ -96,9 +108,9 @@ RWStructuredBuffer TubeFieldVertices : register(u10); RWStructuredBuffer TubeFieldIndices : register(u11); RWStructuredBuffer TubeFieldStats : register(u12); RWStructuredBuffer TubeFieldDrawArguments : register(u13); -RWStructuredBuffer TubeFieldSegments : register(u16); +RWStructuredBuffer TubeFieldColumns : register(u16); -StructuredBuffer RestirSegments : register(t46); +StructuredBuffer RestirColumns : register(t46); StructuredBuffer RestirTileSegmentsRead : register(t47); StructuredBuffer RestirPreviousReservoirs : register(t48); StructuredBuffer RestirReadReservoirs : register(t49); @@ -114,9 +126,7 @@ static const uint TubeFieldRestirMaxTileSegments = 128u; static const uint TubeFieldRestirSpatialTileLanes = 16u; static const uint TubeFieldRestirDepthLanesPerSpatialLane = 1u; static const uint TubeFieldRestirResidentTileCandidates = TubeFieldRestirSpatialTileLanes * TubeFieldRestirDepthLanesPerSpatialLane; -static const uint TubeFieldRestirInitialCandidateCount = TubeFieldRestirResidentTileCandidates; static const uint TubeFieldRestirSpatialCandidateCount = 4u; -static const uint TubeFieldRestirExportCandidateCount = TubeFieldRestirResidentTileCandidates; static const uint FieldReservoirSlotsPerPixel = 4u; RWStructuredBuffer FieldReservoirCandidates : register(u14); @@ -148,6 +158,26 @@ uint SampleAddress(uint logicalColumn, uint sampleIndex) return (physicalColumn * width + min(sampleIndex, width - 1u)) * strideBytes; } +uint ColumnSampleAddress(TubeFieldColumn column, uint sampleIndex) +{ + uint width = max((uint)round(column.shape.x), 1u); + uint height = max((uint)round(column.shape.y), 1u); + uint firstColumn = (uint)max(round(column.shape.w), 0.0); + uint columnStride = max((uint)round(column.columns.y), 1u); + uint rollingModulo = (uint)max(round(column.columns.z), 0.0); + int rollingOffset = (int)round(column.columns.w); + uint logicalColumn = (uint)max(round(column.dispatchDraw.x), 0.0); + uint physicalColumn = firstColumn + logicalColumn * columnStride; + if (rollingModulo > 0u) + { + physicalColumn = PositiveModulo((int)physicalColumn + rollingOffset, rollingModulo); + } + + physicalColumn = min(physicalColumn, height - 1u); + uint strideBytes = max((uint)round(column.shape.z), 4u); + return (physicalColumn * width + min(sampleIndex, width - 1u)) * strideBytes; +} + float RawSample(uint logicalColumn, int sampleIndex) { uint width = max((uint)round(tubeShape.x), 1u); @@ -155,6 +185,13 @@ float RawSample(uint logicalColumn, int sampleIndex) return asfloat(TubeFieldSamples.Load(SampleAddress(logicalColumn, clamped))); } +float RawColumnSample(TubeFieldColumn column, int sampleIndex) +{ + uint width = max((uint)round(column.shape.x), 1u); + uint clamped = (uint)clamp(sampleIndex, 0, (int)width - 1); + return asfloat(TubeFieldSamples.Load(ColumnSampleAddress(column, clamped))); +} + float FilteredSample(uint logicalColumn, float x) { int center = (int)floor(x + 0.5); @@ -166,12 +203,29 @@ float FilteredSample(uint logicalColumn, float x) return (s0 + s4 + 4.0 * (s1 + s3) + 6.0 * s2) / 16.0; } +float FilteredColumnSample(TubeFieldColumn column, float x) +{ + int center = (int)floor(x + 0.5); + float s0 = RawColumnSample(column, center - 2); + float s1 = RawColumnSample(column, center - 1); + float s2 = RawColumnSample(column, center); + float s3 = RawColumnSample(column, center + 1); + float s4 = RawColumnSample(column, center + 2); + return (s0 + s4 + 4.0 * (s1 + s3) + 6.0 * s2) / 16.0; +} + float NormalizedSample(uint logicalColumn, float x) { float value = FilteredSample(logicalColumn, x); return saturate((value - tubeAmplitude.z) / max(tubeAmplitude.w - tubeAmplitude.z, 0.0001)); } +float NormalizedColumnSample(TubeFieldColumn column, float x) +{ + float value = FilteredColumnSample(column, x); + return saturate((value - column.amplitude.z) / max(column.amplitude.w - column.amplitude.z, 0.0001)); +} + float Catmull(float p0, float p1, float p2, float p3, float t) { float t2 = t * t; @@ -193,11 +247,27 @@ float SampleCurve(uint logicalColumn, float x) return saturate(Catmull(p0, p1, p2, p3, t)); } +float SampleColumnCurve(TubeFieldColumn column, float x) +{ + int i1 = (int)floor(x); + float t = frac(x); + float p0 = NormalizedColumnSample(column, (float)(i1 - 1)); + float p1 = NormalizedColumnSample(column, (float)i1); + float p2 = NormalizedColumnSample(column, (float)(i1 + 1)); + float p3 = NormalizedColumnSample(column, (float)(i1 + 2)); + return saturate(Catmull(p0, p1, p2, p3, t)); +} + float SampleAmplitudeCurve(uint logicalColumn, float x) { return pow(SampleCurve(logicalColumn, x), max(tubeAmplitude.x, 0.0001)); } +float SampleColumnAmplitudeCurve(TubeFieldColumn column, float x) +{ + return pow(SampleColumnCurve(column, x), max(column.amplitude.x, 0.0001)); +} + float3 TubePoint(uint logicalColumn, float x) { float value = SampleAmplitudeCurve(logicalColumn, x); @@ -207,6 +277,14 @@ float3 TubePoint(uint logicalColumn, float x) float3(0.0, value * tubeAmplitude.y, 0.0); } +float3 TubeColumnPoint(TubeFieldColumn column, float x) +{ + float value = SampleColumnAmplitudeCurve(column, x); + return column.originField.xyz + + column.axisStepEmission.xyz * x + + float3(0.0, value * column.amplitude.y, 0.0); +} + TubeFieldVertex MakeTubeVertex(float3 position, float3 previous, float3 start, float3 end, float3 next, float side, float endpointT, float capSign, float v0, float v1, float3 rampColor, uint logicalColumn, float x0, float x1) { TubeFieldVertex vertex; @@ -244,60 +322,35 @@ TubeFieldSegment MakeTubeSegment(float3 previous, float3 start, float3 end, floa [numthreads(256, 1, 1)] void D3D12TubeFieldExpandCS(uint3 dispatchThreadId : SV_DispatchThreadID) { - uint localSegment = dispatchThreadId.x; - uint dispatchSegments = (uint)round(tubeDispatch.w); - if (localSegment == 0u) + uint localColumn = dispatchThreadId.x; + uint dispatchColumns = (uint)round(tubeDispatch.w); + if (localColumn == 0u) { uint argumentBase = (uint)round(tubeDraw.x); - TubeFieldDrawArguments[argumentBase + 0u] = dispatchSegments * 6u; + TubeFieldDrawArguments[argumentBase + 0u] = 0u; TubeFieldDrawArguments[argumentBase + 1u] = 1u; TubeFieldDrawArguments[argumentBase + 2u] = (uint)round(tubeDraw.y); TubeFieldDrawArguments[argumentBase + 3u] = 0u; TubeFieldDrawArguments[argumentBase + 4u] = 0u; } - if (localSegment >= dispatchSegments) + if (localColumn >= dispatchColumns) { return; } - uint width = max((uint)round(tubeShape.x), 2u); - uint subdivisions = max((uint)round(tubeDispatch.y), 1u); - uint piecesPerColumn = (width - 1u) * subdivisions; - uint logicalColumn = localSegment / max(piecesPerColumn, 1u); - uint pieceInColumn = localSegment % max(piecesPerColumn, 1u); - uint sourceSegment = pieceInColumn / subdivisions; - uint subdivision = pieceInColumn % subdivisions; - float t0 = (float)subdivision / (float)subdivisions; - float t1 = (float)(subdivision + 1u) / (float)subdivisions; - float x0 = (float)sourceSegment + t0; - float x1 = (float)sourceSegment + t1; - float xPrev = max(0.0, x0 - 1.0 / (float)subdivisions); - float xNext = min((float)(width - 1u), x1 + 1.0 / (float)subdivisions); - float v0 = SampleCurve(logicalColumn, x0); - float v1 = SampleCurve(logicalColumn, x1); - float3 rampColor0 = TubeFieldRamp.SampleLevel(TubeFieldRampSampler, float2(saturate(v0), 0.5), 0.0).rgb; - float3 rampColor1 = TubeFieldRamp.SampleLevel(TubeFieldRampSampler, float2(saturate(v1), 0.5), 0.0).rgb; - float3 previous = TubePoint(logicalColumn, xPrev); - float3 start = TubePoint(logicalColumn, x0); - float3 end = TubePoint(logicalColumn, x1); - float3 next = TubePoint(logicalColumn, xNext); - - uint globalSegment = (uint)round(tubeDispatch.z) + localSegment; - uint vertexBase = globalSegment * 4u; - uint indexBase = globalSegment * 6u; - TubeFieldSegments[globalSegment] = MakeTubeSegment(previous, start, end, next, v0, v1, rampColor0, rampColor1, logicalColumn, x0, x1); - TubeFieldVertices[vertexBase + 0u] = MakeTubeVertex(start, previous, start, end, next, -1.0, 0.0, -1.0, v0, v1, rampColor0, logicalColumn, x0, x1); - TubeFieldVertices[vertexBase + 1u] = MakeTubeVertex(start, previous, start, end, next, 1.0, 0.0, -1.0, v0, v1, rampColor0, logicalColumn, x0, x1); - TubeFieldVertices[vertexBase + 2u] = MakeTubeVertex(end, previous, start, end, next, -1.0, 1.0, 1.0, v0, v1, rampColor1, logicalColumn, x0, x1); - TubeFieldVertices[vertexBase + 3u] = MakeTubeVertex(end, previous, start, end, next, 1.0, 1.0, 1.0, v0, v1, rampColor1, logicalColumn, x0, x1); - TubeFieldIndices[indexBase + 0u] = vertexBase + 0u; - TubeFieldIndices[indexBase + 1u] = vertexBase + 1u; - TubeFieldIndices[indexBase + 2u] = vertexBase + 2u; - TubeFieldIndices[indexBase + 3u] = vertexBase + 2u; - TubeFieldIndices[indexBase + 4u] = vertexBase + 1u; - TubeFieldIndices[indexBase + 5u] = vertexBase + 3u; - TubeFieldStats[0] = globalSegment + 1u; + uint globalColumn = (uint)round(tubeDispatch.z) + localColumn; + TubeFieldColumn column; + column.shape = tubeShape; + column.columns = tubeColumns; + column.amplitude = tubeAmplitude; + column.material = tubeMaterial; + column.dispatchDraw = float4((float)localColumn, max(tubeDispatch.x, 0.0), tubeDraw.z, tubeDispatch.y); + column.originField = float4(tubeOrigin + tubeColumnStep * (float)localColumn, tubeDraw.z); + column.axisStepEmission = float4(tubeAxisStep, max(tubeDispatch.x, 0.0)); + column.columnStep = float4(tubeColumnStep, 0.0); + TubeFieldColumns[globalColumn] = column; + TubeFieldStats[0] = globalColumn + 1u; } struct TubeFieldVertexIn @@ -766,41 +819,58 @@ float4 projectWorldToPixelAndDepth(float3 worldPoint) return float4(ndcToPixel(projected.xy), projected.z, view.z); } -bool evaluateTubeFieldSegmentCandidate(uint segmentIndex, float2 pixel, out TubeFieldReservoir candidate, out float targetPdf) +bool evaluateTubeFieldColumnCandidate(uint columnIndex, float2 pixel, out TubeFieldReservoir candidate, out float targetPdf) { candidate = emptyTubeFieldReservoir(); targetPdf = 0.0; - TubeFieldSegment segment = RestirSegments[segmentIndex]; - float4 startProjected = projectWorldToPixelAndDepth(segment.startRadius.xyz); - float4 endProjected = projectWorldToPixelAndDepth(segment.endFeather.xyz); + TubeFieldColumn column = RestirColumns[columnIndex]; + uint width = max((uint)round(column.shape.x), 2u); + float xMax = (float)(width - 1u); + float4 startProjected = projectWorldToPixelAndDepth(TubeColumnPoint(column, 0.0)); + float4 endProjected = projectWorldToPixelAndDepth(TubeColumnPoint(column, xMax)); if (!finite4(startProjected) || !finite4(endProjected)) { return false; } - float startRadiusPx = splineRadiusToPixels(segment.startRadius.w, startProjected.w); - float endRadiusPx = splineRadiusToPixels(segment.endFeather.w, endProjected.w); - if (!finite1(startRadiusPx) || !finite1(endRadiusPx)) - { - return false; - } - float sdf; float closestT; float radiusPx; float2 normalPx; - capsuleDistancePx(pixel, startProjected.xy, endProjected.xy, startRadiusPx, endRadiusPx, sdf, closestT, radiusPx, normalPx); + float2 axisPx = endProjected.xy - startProjected.xy; + float axisLength2 = max(dot(axisPx, axisPx), 0.0001); + float xCenter = saturate(dot(pixel - startProjected.xy, axisPx) / axisLength2) * xMax; + float sampleStep = max(0.5, xMax / 32.0); + float x0 = clamp(xCenter - sampleStep, 0.0, xMax); + float x1 = clamp(xCenter + sampleStep, 0.0, xMax); + float v0 = SampleColumnCurve(column, x0); + float v1 = SampleColumnCurve(column, x1); + float3 p0 = TubeColumnPoint(column, x0); + float3 p1 = TubeColumnPoint(column, x1); + float4 projected0 = projectWorldToPixelAndDepth(p0); + float4 projected1 = projectWorldToPixelAndDepth(p1); + if (!finite4(projected0) || !finite4(projected1)) + { + return false; + } - float aa = max(0.75, radiusPx * max(segment.material.w, 0.0)); + float r0 = splineRadiusToPixels(max(column.material.x + v0 * column.material.y, 0.0001), projected0.w); + float r1 = splineRadiusToPixels(max(column.material.x + v1 * column.material.y, 0.0001), projected1.w); + float localT; + capsuleDistancePx(pixel, projected0.xy, projected1.xy, r0, r1, sdf, localT, radiusPx, normalPx); + closestT = saturate(lerp(x0, x1, localT) / max(xMax, 0.0001)); + + float aa = max(0.75, radiusPx * max(column.material.w, 0.0)); float coverage = 1.0 - smoothstep(0.0, aa, sdf); - float alpha = saturate(segment.material.y * coverage); + float alpha = saturate(column.material.z * coverage); if (!finite1(sdf) || !finite1(radiusPx) || !finite2(normalPx) || alpha <= 0.004) { return false; } - float value = lerp(segment.color0.w, segment.color1.w, closestT); - float3 emissionColor = lerp(segment.color0.rgb, segment.color1.rgb, closestT); + float x = closestT * xMax; + float value = SampleColumnCurve(column, x); + float3 emissionColor = TubeFieldRamp.SampleLevel(TubeFieldRampSampler, float2(saturate(value), 0.5), 0.0).rgb; float3 ray = rayDirectionForPixel(pixel, float2(0.0, 0.0), cameraPosition, cameraTarget); float3 forward; float3 right; @@ -810,7 +880,7 @@ bool evaluateTubeFieldSegmentCandidate(uint segmentIndex, float2 pixel, out Tube float frontBlend = sqrt(saturate(1.0 - rimBlend * rimBlend)); float3 tubeNormal = normalize(((right * normalPx.x) - (up * normalPx.y)) * rimBlend - ray * frontBlend); float normalFacing = saturate(-dot(ray, tubeNormal)); - float glowFacing = pow(normalFacing, max(segment.material.z, 0.0001)); + float glowFacing = pow(normalFacing, 4.0); float alphaFacing = 1.0; float claimCoverage = saturate(alpha * alphaFacing); if (claimCoverage <= 0.004) @@ -818,22 +888,22 @@ bool evaluateTubeFieldSegmentCandidate(uint segmentIndex, float2 pixel, out Tube return false; } - float emission = value * value * max(segment.material.x, 0.0); + float emission = value * value * max(column.dispatchDraw.y, 0.0); float3 color = emissionColor * emission * glowFacing * claimCoverage; - float travel = lerp(startProjected.w, endProjected.w, closestT); - float3 worldPosition = lerp(segment.startRadius.xyz, segment.endFeather.xyz, closestT); + float3 worldPosition = TubeColumnPoint(column, x); + float travel = distance(cameraPosition, worldPosition); if (!finite3(color) || !finite3(worldPosition) || !finite1(travel) || !finite3(tubeNormal)) { return false; } candidate.colorTravel = float4(color, min(travel, farDistance + 1.0)); - candidate.metadata = float4(segment.tubeData.w, tubeNormal); + candidate.metadata = float4(column.originField.w, tubeNormal); candidate.control = float4(claimCoverage, coverage, saturate(radiusPx / 32.0), value); candidate.reservoirGuide = float4(claimCoverage, 0.0, coverage, value); candidate.statistics = float4(1.0, 1.0, 1.0, 0.0); candidate.sampleData = float4(worldPosition, closestT); - candidate.sampleKey = uint4(segmentIndex, 0u, 0u, 0u); + candidate.sampleKey = uint4(columnIndex, 0u, 0u, 0u); targetPdf = max(0.0001, claimCoverage * (0.05 + dot(color, float3(0.2126, 0.7152, 0.0722)))); return true; } @@ -851,7 +921,7 @@ bool shiftTubeFieldReservoirToPixel( return false; } - if (!evaluateTubeFieldSegmentCandidate(source.sampleKey.x, pixel + 0.5 + jitterPixels, shifted, shiftedTargetPdf)) + if (!evaluateTubeFieldColumnCandidate(source.sampleKey.x, pixel + 0.5 + jitterPixels, shifted, shiftedTargetPdf)) { return false; } @@ -978,17 +1048,19 @@ void D3D12TubeFieldRestirClearReservoirsCS(uint3 dispatchThreadId : SV_DispatchT [numthreads(256, 1, 1)] void D3D12TubeFieldRestirBinSegmentsCS(uint3 dispatchThreadId : SV_DispatchThreadID) { - uint localSegment = dispatchThreadId.x; - uint dispatchSegments = (uint)round(tubeDispatch.w); - if (localSegment >= dispatchSegments) + uint localColumn = dispatchThreadId.x; + uint dispatchColumns = (uint)round(tubeDispatch.w); + if (localColumn >= dispatchColumns) { return; } - uint segmentIndex = (uint)round(tubeDispatch.z) + localSegment; - TubeFieldSegment segment = RestirSegments[segmentIndex]; - float4 startProjected = projectWorldToPixelAndDepth(segment.startRadius.xyz); - float4 endProjected = projectWorldToPixelAndDepth(segment.endFeather.xyz); + uint columnIndex = (uint)round(tubeDispatch.z) + localColumn; + TubeFieldColumn column = RestirColumns[columnIndex]; + uint width = max((uint)round(column.shape.x), 2u); + float xMax = (float)(width - 1u); + float4 startProjected = projectWorldToPixelAndDepth(TubeColumnPoint(column, 0.0)); + float4 endProjected = projectWorldToPixelAndDepth(TubeColumnPoint(column, xMax)); if (!finite4(startProjected) || !finite4(endProjected)) { return; @@ -999,9 +1071,13 @@ void D3D12TubeFieldRestirBinSegmentsCS(uint3 dispatchThreadId : SV_DispatchThrea return; } + float startValue = SampleColumnCurve(column, 0.0); + float endValue = SampleColumnCurve(column, xMax); float radiusPx = max( - splineRadiusToPixels(segment.startRadius.w, startProjected.w), - splineRadiusToPixels(segment.endFeather.w, endProjected.w)); + splineRadiusToPixels(max(column.material.x + startValue * column.material.y, 0.0001), startProjected.w), + splineRadiusToPixels(max(column.material.x + endValue * column.material.y, 0.0001), endProjected.w)); + float2 minProjected = min(startProjected.xy, endProjected.xy); + float2 maxProjected = max(startProjected.xy, endProjected.xy); radiusPx = min(radiusPx, 256.0); float segmentTravel = min(startProjected.w, endProjected.w); if (!finite1(radiusPx) || !finite1(segmentTravel)) @@ -1009,8 +1085,8 @@ void D3D12TubeFieldRestirBinSegmentsCS(uint3 dispatchThreadId : SV_DispatchThrea return; } - float2 minPx = floor((min(startProjected.xy, endProjected.xy) - radiusPx * 1.5) / TubeFieldRestirTileSize); - float2 maxPx = floor((max(startProjected.xy, endProjected.xy) + radiusPx * 1.5) / TubeFieldRestirTileSize); + float2 minPx = floor((minProjected - radiusPx * 1.5) / TubeFieldRestirTileSize); + float2 maxPx = floor((maxProjected + radiusPx * 1.5) / TubeFieldRestirTileSize); if (!finite2(minPx) || !finite2(maxPx)) { return; @@ -1038,18 +1114,16 @@ void D3D12TubeFieldRestirBinSegmentsCS(uint3 dispatchThreadId : SV_DispatchThrea uint tileIndex = tileY * tileDims.x + tileX; uint slot; InterlockedAdd(RestirTileCounts[tileIndex], 1u, slot); - float2 tileOrigin = float2(tileX, tileY) * (float)TubeFieldRestirTileSize; - float2 tileCenter = tileOrigin + (float)TubeFieldRestirTileSize * 0.5; - float2 segmentPx = endProjected.xy - startProjected.xy; - float segmentLength2 = max(dot(segmentPx, segmentPx), 0.0001); - float tileT = saturate(dot(tileCenter - startProjected.xy, segmentPx) / segmentLength2); - float2 tilePoint = lerp(startProjected.xy, endProjected.xy, tileT); - float2 localTilePoint = saturate((tilePoint - tileOrigin) / (float)TubeFieldRestirTileSize); - uint laneX = min((uint)floor(localTilePoint.x * 4.0), 3u); - uint laneY = min((uint)floor(localTilePoint.y * 4.0), 3u); - uint spatialLane = laneY * 4u + laneX; - uint packed = packRestirTileSegment(segmentIndex, segmentTravel); - insertRestirTileSegment(tileIndex, spatialLane, packed); + uint packed = packRestirTileSegment(columnIndex, segmentTravel); + [unroll(4)] + for (uint laneY = 0u; laneY < 4u; laneY++) + { + [unroll(4)] + for (uint laneX = 0u; laneX < 4u; laneX++) + { + insertRestirTileSegment(tileIndex, laneY * 4u + laneX, packed); + } + } } } } @@ -1077,23 +1151,18 @@ void D3D12TubeFieldRestirInitialCS(uint3 dispatchThreadId : SV_DispatchThreadID) } uint count = TubeFieldRestirResidentTileCandidates; - float invSourcePdf = (float)count; - uint proposalCount = min(count, TubeFieldRestirInitialCandidateCount); - for (uint index = 0u; index < proposalCount; index++) + uint2 localPixelInTile = pixel - tile * TubeFieldRestirTileSize; + uint laneX = min(localPixelInTile.x / 4u, 3u); + uint laneY = min(localPixelInTile.y / 4u, 3u); + uint candidateSlot = min(laneY * 4u + laneX, count - 1u); + uint columnIndex; + if (unpackRestirTileSegment(RestirTileSegmentsRead[tileIndex * TubeFieldRestirMaxTileSegments + candidateSlot], columnIndex)) { - uint candidateSlot = index; - uint segmentIndex; - if (!unpackRestirTileSegment(RestirTileSegmentsRead[tileIndex * TubeFieldRestirMaxTileSegments + candidateSlot], segmentIndex)) - { - continue; - } - TubeFieldReservoir candidate; float targetPdf; - if (evaluateTubeFieldSegmentCandidate(segmentIndex, (float2)pixel + 0.5 + jitterPixels, candidate, targetPdf)) + if (evaluateTubeFieldColumnCandidate(columnIndex, (float2)pixel + 0.5 + jitterPixels, candidate, targetPdf)) { - float randomValue = restirRandom01(pixelIndex * 1664525u + index * 1013904223u + (uint)frameIndex * 977u); - restirStreamCandidate(reservoir, candidate, targetPdf, invSourcePdf, randomValue); + restirStreamCandidate(reservoir, candidate, targetPdf, (float)count, restirRandom01(pixelIndex * 1664525u + (uint)frameIndex * 977u)); } } @@ -1172,7 +1241,7 @@ void D3D12TubeFieldRestirSpatialResolveCS(uint3 dispatchThreadId : SV_DispatchTh int2(2, -4) }; - [unroll] + [unroll(4)] for (uint sampleIndex = 0u; sampleIndex < TubeFieldRestirSpatialCandidateCount; sampleIndex++) { uint offsetIndex = wangHash(pixelIndex * 9781u + sampleIndex * 6271u + (uint)frameIndex * 1709u) & 15u; @@ -1218,31 +1287,31 @@ void D3D12TubeFieldRestirSpatialResolveCS(uint3 dispatchThreadId : SV_DispatchTh uint2 tile = min(pixel / TubeFieldRestirTileSize, tileDims - 1u); uint tileIndex = tile.y * tileDims.x + tile.x; uint touchedSegmentCount = RestirTileCountsRead[tileIndex]; - uint count = touchedSegmentCount > 0u ? TubeFieldRestirResidentTileCandidates : 0u; - uint exportProposalCount = min(count, TubeFieldRestirExportCandidateCount); - for (uint index = 0u; index < exportProposalCount; index++) + if (touchedSegmentCount > 0u) { - uint candidateSlot = index; - uint segmentIndex; - if (!unpackRestirTileSegment(RestirTileSegmentsRead[tileIndex * TubeFieldRestirMaxTileSegments + candidateSlot], segmentIndex)) + uint count = TubeFieldRestirResidentTileCandidates; + uint2 localPixelInTile = pixel - tile * TubeFieldRestirTileSize; + uint laneX = min(localPixelInTile.x / 4u, 3u); + uint laneY = min(localPixelInTile.y / 4u, 3u); + uint candidateSlot = min(laneY * 4u + laneX, count - 1u); + uint columnIndex; + if (unpackRestirTileSegment(RestirTileSegmentsRead[tileIndex * TubeFieldRestirMaxTileSegments + candidateSlot], columnIndex)) { - continue; - } - - TubeFieldReservoir candidate; - float targetPdf; - if (evaluateTubeFieldSegmentCandidate(segmentIndex, (float2)pixel + 0.5 + jitterPixels, candidate, targetPdf)) - { - insertTubeFieldExportCandidate( - candidate, - export0, - export1, - export2, - export3, - priority0, - priority1, - priority2, - priority3); + TubeFieldReservoir candidate; + float targetPdf; + if (evaluateTubeFieldColumnCandidate(columnIndex, (float2)pixel + 0.5 + jitterPixels, candidate, targetPdf)) + { + insertTubeFieldExportCandidate( + candidate, + export0, + export1, + export2, + export3, + priority0, + priority1, + priority2, + priority3); + } } } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index d09d27c..a0218c8 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -276,3 +276,4 @@ {"lesson":"Reservoir history update and reuse moved out of the presentation pixel shader into a shared D3D12 compute pass. The pass reads canonical scene lanes, shared field candidate rows, and ping-ponged structured history rows; writes the next four history rows per pixel; and emits a resolved HDR field texture consumed by bloom and final presentation. The presentation shader no longer writes reservoir history, so it cannot become a hidden TAA owner. Fensalir and Mimir builds passed, the Mimir spectrum upload smoke passed, and a synthetic spectrum headless capture rendered through the compute-owned reservoir path.","timestamp":"2026-05-28T17:05:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","docs/temporal-spatial-evidence-reservoir.md","docs/perfect-machine-architecture.md","state/map.yaml"],"source":"user selected full structured-buffer reservoir path","topic":"reservoir-history-compute-owner"} {"lesson":"TubeField ReSTIR reuse no longer imports neighbor-pixel coverage directly. Temporal and spatial reuse now re-evaluate a shifted reservoir's selected segment at the receiving pixel before combination, and TubeField exports the four best deterministic current pixel candidates into the shared field-reservoir rows. This removes the wrong stochastic authority from opaque primary visibility, though the spectrum dashboard still reads visually busy because it draws many age-column tubes through generated segment proxies. Verified with Fensalir/Mimir builds, --mimir-spectrum-upload-smoke, and headless capture artifacts/runtime/reservoir-deterministic-top4-spectrum.png.","timestamp":"2026-05-28T17:35:00+01:00","files":["src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","state/map.yaml","state/evidence.jsonl"],"source":"noisy reservoir smoke diagnosis","topic":"tubefield-shifted-reuse-top4-export"} {"lesson":"The many-spline TubeField quality path stays on cheap segmented proxies. Segment continuity now fixes data ownership inside that model: every generated proxy vertex carries the same start/end radius pair, and the compute segment packet stores true start/end radii plus feather/alpha separately. ReSTIR candidate evaluation and tile binning now use the true end radius instead of silently reusing the start radius, reducing join disagreement without spline-wide SDF evaluation. Verified with Fensalir/Mimir builds, --mimir-spectrum-upload-smoke, and headless capture artifacts/runtime/tubefield-cheap-continuity-spectrum.png.","timestamp":"2026-05-28T17:55:00+01:00","files":["src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","state/map.yaml","state/evidence.jsonl"],"source":"user chose many-hundreds-splines cheap segment continuity path","topic":"tubefield-cheap-segment-continuity"} +{"lesson":"TubeField candidate authority has moved from generated segment packets to rolling-buffer column packets. D3D12TubeFieldExpandCS now emits one GPU-resident TubeFieldColumn per logical spectrum column and zeroes generated-mesh draw args; ReSTIR tile binning and candidate evaluation sample the source buffer directly as Catmull-Rom spline SDF evidence, with ramp sampling bound in the ReSTIR root signature. Debug builds compile TubeField ReSTIR shaders with optimization enabled because SkipOptimization can make the compiler unroll the column evaluator into failure. Verified with Mimir.App build and headless synthetic spectrum capture artifacts/runtime/mimir-column-packet-final-headless.png at about 60 FPS after warmup.","timestamp":"2026-05-29T01:46:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","state/map.yaml","state/evidence.jsonl"],"source":"user selected spline/column packets as TubeField reservoir authority","topic":"tubefield-column-packet-restir-authority"} diff --git a/state/map.yaml b/state/map.yaml index 9241ccb..de2c9f9 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -212,22 +212,16 @@ next_actions: remaining coherence cut is to make every non-debug contributor inject explicit field candidates instead of entering as the single legacy scene-candidate input. - TubeField reservoir ownership has been rebuilt into the first ReSTIR-shaped - compute path: TubeField expansion emits reusable segment records with baked - material endpoints, segments are binned into screen tiles once per frame, - pixel-owned reservoirs stream a small proposal set, temporal reuse - reprojects previous reservoirs, and spatial reuse samples neighbor - reservoirs only after re-evaluating the selected segment at the receiving - pixel. TubeField exports the four best deterministic current pixel - candidates into the shared field-reservoir candidate rows so opaque primary - visibility is not a single stochastic winner. The cheap segment model now - keeps a consistent start/end radius pair across each generated proxy and - stores the true end radius in the compute segment packet, so adjacent - capsules agree at joins without a heavier spline-wide SDF search. The old TubeField raster path - remains compiled as a - diagnostic/generated-mesh reference, but the live scene path calls the - compute ReSTIR export instead of letting raster fragments arbitrate - visibility with locks. + TubeField reservoir ownership now uses spline/column packets as the + candidate authority rather than generated mesh segments. TubeField expansion + writes one GPU-resident column packet per rolling-buffer column, tile binning + files those columns into screen-space lanes, pixel-owned reservoirs evaluate + a local Catmull-Rom SDF sample directly from the source buffer, temporal + reuse reprojects previous column samples, and spatial reuse re-evaluates the + selected column at the receiving pixel before combination. The shared field + reservoir remains the only final contribution path. Generated vertex/index + output is currently zeroed for the live path and retained only as a + diagnostic/generated-mesh reference. - Move any remaining client-only Epiphany state found here back to `E:\Projects\Aquarium-Engine`. - Keep Mimir app/adapters out of this repo; Fensalir may expose generic sensor-fusion contracts only. - Package contracts/host deliberately before replacing sibling source references in client repos.