diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 84bf3b3..1f9f853 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -33,7 +33,6 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int PlanetCount = 5; private const int GridHeightBrushCount = PlanetCount + 1; private const int FieldInstanceCount = PlanetCount + 5; - private const int TransparentSurfaceCount = 1; private const float GridTransparentMinZ = -1.85f; private const float GridTransparentMaxZ = 0.45f; private const int BloomLevelCount = 3; @@ -101,12 +100,8 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12RenderTarget[] bloomScratchTargets = new D3D12RenderTarget[BloomLevelCount]; private D3D12StructuredBuffer froxelPrimitiveBuffer; private readonly D3D12StructuredBuffer fieldInstanceBuffer; - private D3D12StructuredBuffer transparentSurfaceIndexBuffer; - private readonly D3D12StructuredBuffer transparentSurfaceBuffer; private Int4[] froxelPrimitiveIds = []; private readonly FieldInstanceGpu[] fieldInstances = new FieldInstanceGpu[FieldInstanceCount]; - private Int4[] transparentSurfaceIds = []; - private readonly TransparentSurfaceGpu[] transparentSurfaces = new TransparentSurfaceGpu[TransparentSurfaceCount]; private readonly GridHeightBrushCpu[] gridHeightBrushes = new GridHeightBrushCpu[GridHeightBrushCount]; private Viewport viewport; private RawRect scissorRect; @@ -200,12 +195,8 @@ public sealed class D3D12Renderer : IAquariumRenderer CreateBloomRenderTargets(); froxelPrimitiveBuffer = CreateViewFroxelPrimitiveBuffer(); fieldInstanceBuffer = new D3D12StructuredBuffer(device, FieldInstanceCount, Marshal.SizeOf(), "Aquarium D3D12 Field Instance Buffer"); - transparentSurfaceIndexBuffer = CreateTransparentSurfaceIndexBuffer(); - transparentSurfaceBuffer = new D3D12StructuredBuffer(device, TransparentSurfaceCount, Marshal.SizeOf(), "Aquarium D3D12 Transparent Surface Buffer"); resourceRegistry.Add("froxel-primitive-buffer", froxelPrimitiveBuffer); resourceRegistry.Add("field-instance-buffer", fieldInstanceBuffer); - resourceRegistry.Add("transparent-surface-index-buffer", transparentSurfaceIndexBuffer); - resourceRegistry.Add("transparent-surface-buffer", transparentSurfaceBuffer); commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); commandList.Name = "Aquarium D3D12 Graphics Command List"; commandList.Close(); @@ -302,7 +293,6 @@ public sealed class D3D12Renderer : IAquariumRenderer BuildGridHeightBrushes(frame); BuildFroxelPrimitiveTable(frame); BuildFieldInstanceTable(frame); - BuildTransparentSurfaceTable(frame); var frameConstants = frameResources.UploadRing.WriteConstant(new FrameConstants( new Vector2(width, height), frame.TimeSeconds, @@ -344,10 +334,6 @@ public sealed class D3D12Renderer : IAquariumRenderer mediumVolumeRenderTarget.CreateShaderResourceView(device, frameResources.MediumTargetsDescriptor); frameResources.MediumTransportDescriptor = frameResources.TransientShaderDescriptors.Allocate(); mediumTransportRenderTarget.CreateShaderResourceView(device, frameResources.MediumTransportDescriptor); - frameResources.TransparentSurfaceIndexDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - transparentSurfaceIndexBuffer.CreateShaderResourceView(device, frameResources.TransparentSurfaceIndexDescriptor); - frameResources.TransparentSurfaceDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - transparentSurfaceBuffer.CreateShaderResourceView(device, frameResources.TransparentSurfaceDescriptor); frameResources.SceneDescriptor = frameResources.TransientShaderDescriptors.Allocate(); sceneRenderTarget.CreateShaderResourceView(device, frameResources.SceneDescriptor); frameResources.SceneMetadataDescriptor = frameResources.TransientShaderDescriptors.Allocate(); @@ -482,8 +468,6 @@ public sealed class D3D12Renderer : IAquariumRenderer fullscreenRootSignature.Dispose(); fieldInstanceBuffer.Dispose(); froxelPrimitiveBuffer.Dispose(); - transparentSurfaceBuffer.Dispose(); - transparentSurfaceIndexBuffer.Dispose(); DisposeBloomRenderTargets(); DisposeHistoryRenderTargets(); sceneRenderTarget.Dispose(); @@ -591,8 +575,6 @@ public sealed class D3D12Renderer : IAquariumRenderer private int ViewFroxelCount => mediumFroxelWidth * mediumFroxelHeight * MediumFroxelSliceCount; - private int TransparentSurfaceBufferElementCount => ViewFroxelCount; - private D3D12StructuredBuffer CreateViewFroxelPrimitiveBuffer() { froxelPrimitiveIds = new Int4[ViewFroxelCount * ViewFroxelPrimitiveSlotCount]; @@ -603,16 +585,6 @@ public sealed class D3D12Renderer : IAquariumRenderer "Aquarium D3D12 View-Froxel Primitive Buffer"); } - private D3D12StructuredBuffer CreateTransparentSurfaceIndexBuffer() - { - transparentSurfaceIds = new Int4[TransparentSurfaceBufferElementCount]; - return new D3D12StructuredBuffer( - device, - TransparentSurfaceBufferElementCount, - Marshal.SizeOf(), - "Aquarium D3D12 View-Froxel Transparent Surface Index Buffer"); - } - private D3D12PipelineSet CreatePipelineSet(D3D12ShaderPaths paths) { var gridHeightBase = CreateGridHeightBasePipelineState(paths.Grid); @@ -670,7 +642,6 @@ public sealed class D3D12Renderer : IAquariumRenderer resourceRegistry.RemoveRenderTarget("medium-volume-target"); resourceRegistry.RemoveRenderTarget("grid-height-target"); resourceRegistry.RemoveStructuredBuffer("froxel-primitive-buffer"); - resourceRegistry.RemoveStructuredBuffer("transparent-surface-index-buffer"); DisposeBloomRenderTargets(); DisposeHistoryRenderTargets(); sceneRenderTarget.Dispose(); @@ -680,7 +651,6 @@ public sealed class D3D12Renderer : IAquariumRenderer mediumVolumeRenderTarget.Dispose(); gridHeightRenderTarget.Dispose(); froxelPrimitiveBuffer.Dispose(); - transparentSurfaceIndexBuffer.Dispose(); for (var index = 0; index < frames.Length; index++) { resourceRegistry.RemoveResource($"backbuffer-{index}"); @@ -703,9 +673,7 @@ public sealed class D3D12Renderer : IAquariumRenderer mediumVolumeRenderTarget = CreateMediumVolumeRenderTarget("medium-volume-target", "Aquarium D3D12 Medium Volume Target"); mediumTransportRenderTarget = CreateMediumVolumeRenderTarget("medium-transport-target", "Aquarium D3D12 Medium Transport Target"); froxelPrimitiveBuffer = CreateViewFroxelPrimitiveBuffer(); - transparentSurfaceIndexBuffer = CreateTransparentSurfaceIndexBuffer(); resourceRegistry.Add("froxel-primitive-buffer", froxelPrimitiveBuffer); - resourceRegistry.Add("transparent-surface-index-buffer", transparentSurfaceIndexBuffer); sceneRenderTarget = CreateSceneRenderTarget(); sceneMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-metadata-target", "Aquarium D3D12 Scene Metadata Target"); sceneControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-control-target", "Aquarium D3D12 Scene Control Target"); @@ -882,7 +850,6 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.SetGraphicsRootDescriptorTable(3, frameResources.FroxelPrimitiveDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(4, frameResources.FieldInstanceDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(5, frameResources.MediumTargetsDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(6, frameResources.TransparentSurfaceIndexDescriptor.Gpu); context.CommandList.RSSetViewports(viewport); context.CommandList.RSSetScissorRects(scissorRect); context.CommandList.OMSetRenderTargets( @@ -1015,12 +982,12 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(1, frameResources.SceneDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(4, frameResources.FieldInstanceDescriptor.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.SetGraphicsRootDescriptorTable(6, frameResources.BloomPresentationDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(7, frameResources.SceneMetadataDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(8, frameResources.SceneControlDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(9, frameResources.HistoryDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(10, frameResources.HistoryMetadataDescriptor.Gpu); + context.CommandList.SetGraphicsRootDescriptorTable(11, frameResources.HistoryControlDescriptor.Gpu); context.CommandList.RSSetViewports(viewport); context.CommandList.RSSetScissorRects(scissorRect); @@ -1048,8 +1015,6 @@ public sealed class D3D12Renderer : IAquariumRenderer { froxelPrimitiveBuffer.Upload(activeCommandList, frameResources.UploadRing, froxelPrimitiveIds); fieldInstanceBuffer.Upload(activeCommandList, frameResources.UploadRing, fieldInstances); - transparentSurfaceIndexBuffer.Upload(activeCommandList, frameResources.UploadRing, transparentSurfaceIds); - transparentSurfaceBuffer.Upload(activeCommandList, frameResources.UploadRing, transparentSurfaces); } finally { @@ -1292,74 +1257,6 @@ public sealed class D3D12Renderer : IAquariumRenderer medium: new Vector4(0.190f, 0.130f, 0.0f, 1.20f)); } - private void BuildTransparentSurfaceTable(AquariumFrame frame) - { - for (var i = 0; i < transparentSurfaceIds.Length; i++) - { - transparentSurfaceIds[i] = new Int4(-1, -1, -1, -1); - } - - transparentSurfaces[0] = new TransparentSurfaceGpu( - new Vector4(frame.Grid.Center.X, frame.Grid.Center.Y, 0.0f, MathF.Max(frame.Grid.Radius, 0.001f)), - new Vector4(1.0f, 0.42f, 0.24f, 0.075f), - new Vector4(2.0f, 10.0f, 0.055f, 0.090f), - new Vector4(0.30f, 0.90f, 0.82f, 0.24f)); - - BinGridSurfaceIntoViewFroxels(frame, FrameFarDistance(frame), 0); - } - - private void AddTransparentSurfaceToViewFroxel(int viewFroxelIndex, int surfaceId) - { - AddIdToInt4Slots(transparentSurfaceIds, viewFroxelIndex, 1, surfaceId); - } - - private void BinGridSurfaceIntoViewFroxels(AquariumFrame frame, float farDistance, int surfaceId) - { - for (var y = 0; y < mediumFroxelHeight; y++) - { - for (var x = 0; x < mediumFroxelWidth; x++) - { - if (!ViewFroxelTubeMaySeeGrid(frame, x, y, farDistance)) - { - continue; - } - - for (var slice = 0; slice < MediumFroxelSliceCount; slice++) - { - AddTransparentSurfaceToViewFroxel(ViewFroxelIndex(x, y, slice), surfaceId); - } - } - } - } - - private bool ViewFroxelTubeMaySeeGrid(AquariumFrame frame, int x, int y, float farDistance) - { - var gridCenter = new Vector2(frame.Grid.Center.X, frame.Grid.Center.Y); - var expandedRadius = frame.Grid.Radius + MediumFroxelDownscale * 0.1f; - Span corners = stackalloc Vector3[8]; - FillViewFroxelCorners(frame, x, y, 0, farDistance, corners); - if (AnyCornerInsideGridRadius(corners, gridCenter, expandedRadius)) - { - return true; - } - - FillViewFroxelCorners(frame, x, y, MediumFroxelSliceCount - 1, farDistance, corners); - return AnyCornerInsideGridRadius(corners, gridCenter, expandedRadius); - } - - private static bool AnyCornerInsideGridRadius(ReadOnlySpan corners, Vector2 gridCenter, float radius) - { - foreach (var corner in corners) - { - if (Vector2.Distance(new Vector2(corner.X, corner.Y), gridCenter) <= radius) - { - return true; - } - } - - return false; - } - private bool TryProjectSphereToViewFroxelBounds( AquariumFrame frame, Vector3 center, @@ -1852,12 +1749,6 @@ public sealed class D3D12Renderer : IAquariumRenderer 13, 0, D3D12.DescriptorRangeOffsetAppend); - var transparentSurfaceRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 2, - 15, - 0, - D3D12.DescriptorRangeOffsetAppend); var bloomRange = new DescriptorRange( DescriptorRangeType.ShaderResourceView, BloomLevelCount, @@ -1902,7 +1793,6 @@ public sealed class D3D12Renderer : IAquariumRenderer new RootParameter(new RootDescriptorTable([froxelPrimitiveRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([fieldInstanceRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([mediumTargetRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([transparentSurfaceRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([bloomRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([currentSceneMetadataRange]), ShaderVisibility.Pixel), new RootParameter(new RootDescriptorTable([currentSceneControlRange]), ShaderVisibility.Pixel), @@ -2254,13 +2144,6 @@ public sealed class D3D12Renderer : IAquariumRenderer } } - [StructLayout(LayoutKind.Sequential)] - private readonly record struct TransparentSurfaceGpu( - Vector4 CenterRadius, - Vector4 KindDensity, - Vector4 LineParams, - Vector4 ColorScatter); - private sealed record D3D12ShaderPaths( string Grid, string Smoke, @@ -2333,10 +2216,6 @@ public sealed class D3D12Renderer : IAquariumRenderer public D3D12DescriptorSlot MediumTransportDescriptor { get; set; } - public D3D12DescriptorSlot TransparentSurfaceIndexDescriptor { get; set; } - - public D3D12DescriptorSlot TransparentSurfaceDescriptor { get; set; } - public D3D12DescriptorSlot SceneDescriptor { get; set; } public D3D12DescriptorSlot SceneMetadataDescriptor { get; set; } diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl index 5bb046c..cceaea4 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl @@ -64,7 +64,6 @@ 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_MEDIUM = 3.0; -static const float FIELD_ID_TRANSPARENT_EVENT = 4.0; static const float FIELD_ID_PLANET_BASE = 10.0; static const float MAX_HISTORY_AGE = 32.0; static const int FIELD_INSTANCE_COUNT = 10; @@ -117,11 +116,6 @@ float3 debugFieldIdColor(float fieldId) return float3(0.28, 0.72, 1.0); } - if (abs(fieldId - FIELD_ID_TRANSPARENT_EVENT) < 0.25) - { - return float3(0.20, 1.0, 0.74); - } - if (fieldId >= 10.0) { float phase = frac((fieldId - 10.0) * 0.37); @@ -468,9 +462,9 @@ ResolveOut D3D12ResolvePS(VertexOut input) float currentReactive = saturate(currentControl.x); float currentCoverage = saturate(currentControl.y); float currentMediumOpacity = saturate(currentControl.z); + bool currentIsGrid = abs(currentFieldId - FIELD_ID_GRID) < 0.25; bool currentIsMedium = abs(currentFieldId - FIELD_ID_MEDIUM) < 0.25; - bool currentIsTransparentEvent = abs(currentFieldId - FIELD_ID_TRANSPARENT_EVENT) < 0.25; - bool currentIsDistributed = currentIsMedium || currentIsTransparentEvent; + bool currentIsDistributed = currentIsMedium || currentIsGrid; float historyWeight = 0.0; float historyAge = 0.0; @@ -522,8 +516,8 @@ ResolveOut D3D12ResolvePS(VertexOut input) float validationWeight = travelWeight * colorWeight * fieldWeight * normalWeight * reactiveWeight * coverageWeight * coverageContinuityWeight * mediumContinuityWeight; historyColor = clampedHistory; - float maxHistoryWeight = currentIsTransparentEvent ? 0.90 : currentIsMedium ? 0.88 : 0.82; - float freshHistoryScale = currentIsDistributed ? 0.48 : 0.35; + float maxHistoryWeight = currentIsGrid ? 0.90 : currentIsMedium ? 0.88 : 0.82; + float freshHistoryScale = currentIsGrid ? 0.58 : currentIsDistributed ? 0.48 : 0.35; historyWeight = maxHistoryWeight * lerp(freshHistoryScale, 1.0, historyConfidence) * validationWeight; historyAge = validationWeight > 0.01 ? min(previousHistoryAge + 1.0, MAX_HISTORY_AGE) : 0.0; } diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl index f931ac5..0d40b3c 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl @@ -28,23 +28,11 @@ Texture2D mediumVolumeTexture : register(t13); Texture2D mediumTransportTexture : register(t14); SamplerState gridSampler : register(s0); -struct TransparentSurface -{ - float4 centerRadius; - float4 kindDensity; - float4 lineParams; - float4 colorScatter; -}; - -StructuredBuffer transparentSurfaceIds : register(t15); -StructuredBuffer transparentSurfaces : register(t16); - static const int PLANET_COUNT = 5; static const float SUN_RADIUS = 1.12; static const float FIELD_ID_GRID = 1.0; static const float FIELD_ID_SELF = 2.0; static const float FIELD_ID_MEDIUM = 3.0; -static const float FIELD_ID_TRANSPARENT_EVENT = 4.0; static const float FIELD_ID_PLANET_BASE = 10.0; static const int MEDIUM_FROXEL_ATLAS_COLUMNS = 8; static const int MEDIUM_FROXEL_ATLAS_ROWS = 4; @@ -54,6 +42,10 @@ static const int VIEW_FROXEL_PRIMITIVE_SLOT_COUNT = 2; static const float PI = 3.14159265359; static const float GRID_HEIGHT_TEXEL_COUNT = 128.0; static const float TERRAIN_ISOLINE_SPACING = 0.12; +static const float GRID_MINOR_CELL = 2.0; +static const float GRID_MAJOR_CELL = 10.0; +static const float3 GRID_COLOR = float3(0.30, 0.90, 0.82); +static const float GRID_ALPHA_SCALE = 0.24; struct VertexOut { @@ -77,16 +69,6 @@ struct SolidHit int primitiveId; }; -struct TransparentEvent -{ - bool hit; - float travel; - float3 color; - float alpha; - float coverage; - int surfaceId; -}; - struct RayMarchResult { float3 color; @@ -114,6 +96,13 @@ float hash21(float2 p) return frac(p.x * p.y); } +float stochasticTransparency(float2 screenUv, float alpha) +{ + float frameSeed = frac(frameIndex * 0.754877666); + float dither = frac(hash21(screenUv * resolution + frameIndex.xx * float2(17.0, 43.0)) + frameSeed); + return alpha - dither - 0.001 * (1.0 - ceil(alpha)); +} + void cameraBasis(float3 camera, float2 center, out float3 forward, out float3 right, out float3 up) { float3 target = float3(center, 0.0); @@ -177,6 +166,12 @@ float2 terrainGradient(float2 p) return float2(hRight - hLeft, hUp - hDown) / (texelWorld * 2.0); } +float3 terrainNormal(float3 p) +{ + float2 gradient = terrainGradient(p.xy); + return normalize(float3(-gradient.x, -gradient.y, 1.0)); +} + float lineDistance(float2 p, float cell) { float2 centered = abs(frac(p / cell + 0.5) - 0.5) * cell; @@ -307,150 +302,68 @@ float gridSurfaceDistanceAt(float3 origin, float3 direction, float travel) return p.z - terrainHeight(p.xy); } -bool bracketGridSurfaceInterval(float3 origin, float3 direction, float startTravel, float endTravel, out float bracketStart, out float bracketEnd) +bool traceGridSurfaceDirect(float3 origin, float3 direction, float intervalStart, float intervalEnd, out float3 hitPosition, out float travel) { - bracketStart = startTravel; - bracketEnd = endTravel; - float midTravel = (startTravel + endTravel) * 0.5; - float startDistance = gridSurfaceDistanceAt(origin, direction, startTravel); - float midDistance = gridSurfaceDistanceAt(origin, direction, midTravel); - float endDistance = gridSurfaceDistanceAt(origin, direction, endTravel); - float epsilon = 0.002; + travel = max(intervalStart, 0.0); + float previousTravel = travel; + hitPosition = origin + direction * travel; + float previousGap = hitPosition.z - terrainHeight(hitPosition.xy); + float radius = max(gridRadius, 0.001); - if (abs(startDistance) <= epsilon) + [loop] + for (int stepIndex = 0; stepIndex < 96; stepIndex++) { - bracketEnd = midTravel; - return true; - } + hitPosition = origin + direction * travel; + float2 local = (hitPosition.xy - gridCenter) / radius; + if (length(local) > 1.08 && hitPosition.z < 4.0) + { + return false; + } - if (startDistance * midDistance <= 0.0) - { - bracketEnd = midTravel; - return true; - } + float gap = hitPosition.z - terrainHeight(hitPosition.xy); + float hitEpsilon = max(0.002, travel * 0.00035); + if (length(local) <= 1.0 && (abs(gap) <= hitEpsilon || (previousGap > 0.0 && gap <= 0.0))) + { + float alpha = previousGap / max(previousGap - gap, 0.0001); + travel = lerp(previousTravel, travel, saturate(alpha)); + hitPosition = origin + direction * travel; + return travel > intervalStart && travel < intervalEnd && travel < farDistance; + } - if (abs(midDistance) <= epsilon) - { - bracketStart = midTravel; - bracketEnd = endTravel; - return true; - } - - if (midDistance * endDistance <= 0.0) - { - bracketStart = midTravel; - return true; + float2 slope = terrainGradient(hitPosition.xy); + float terrainRate = abs(direction.z - dot(slope, direction.xy)); + float terrainStep = gap > 0.0 ? gap / max(terrainRate, 0.22) : 0.026; + terrainStep = min(terrainStep * 0.62, max(gridRadius * 0.08, 0.026)); + previousTravel = travel; + previousGap = gap; + travel += max(terrainStep, 0.026); + if (travel > intervalEnd || travel > farDistance) + { + return false; + } } return false; } -bool traceGridSurface(float3 origin, float3 direction, float intervalStart, float intervalEnd, TransparentSurface surface, out float travel) -{ - travel = farDistance + 1.0; - if (intervalEnd <= intervalStart || intervalStart >= farDistance) - { - return false; - } - - float bracketStart; - float bracketEnd; - if (!bracketGridSurfaceInterval(origin, direction, max(intervalStart, 0.0), min(intervalEnd, farDistance), bracketStart, bracketEnd)) - { - return false; - } - - float t = (bracketStart + bracketEnd) * 0.5; - [unroll] - for (int i = 0; i < 6; i++) - { - float mid = (bracketStart + bracketEnd) * 0.5; - float startDistance = gridSurfaceDistanceAt(origin, direction, bracketStart); - float midDistance = gridSurfaceDistanceAt(origin, direction, mid); - if (startDistance * midDistance <= 0.0) - { - bracketEnd = mid; - } - else - { - bracketStart = mid; - } - - t = (bracketStart + bracketEnd) * 0.5; - } - - float3 p = origin + direction * t; - float radius = max(surface.centerRadius.w, 0.001); - float2 local = (p.xy - surface.centerRadius.xy) / radius; - if (t <= intervalStart || t >= intervalEnd || t >= farDistance || length(local) > 1.0) - { - return false; - } - - travel = t; - return true; -} - -float3 gridEventColor(float3 p, TransparentSurface surface, out float alpha) +float3 gridEventColor(float3 p, out float alpha) { float height = terrainHeight(p.xy); float2 gradient = terrainGradient(p.xy); float2 footprint = max(abs(ddx(p.xy)), abs(ddy(p.xy))); float pixelWidth = max(max(footprint.x, footprint.y), 0.006); - float minor = lineMaskFromDistance(lineDistance(p.xy, surface.lineParams.x), pixelWidth * 0.56, pixelWidth * 1.35); - float major = lineMaskFromDistance(lineDistance(p.xy, surface.lineParams.y), pixelWidth * 0.88, pixelWidth * 1.60); + float minor = lineMaskFromDistance(lineDistance(p.xy, GRID_MINOR_CELL), pixelWidth * 0.56, pixelWidth * 1.35); + float major = lineMaskFromDistance(lineDistance(p.xy, GRID_MAJOR_CELL), pixelWidth * 0.88, pixelWidth * 1.60); float contour = isolineMask(height, max(pixelWidth * 0.52, 0.010)) * smoothstep(0.025, 0.25, length(gradient)); float fieldLine = fieldLineMask(gradient, max(pixelWidth * 0.90, 0.016)); float support = saturate(minor * 0.38 + major * 0.92 + contour * 0.28 + fieldLine * 0.18); - float3 color = surface.colorScatter.rgb * (minor * 0.30 + major * 0.74); + float3 color = GRID_COLOR * (minor * 0.30 + major * 0.74); color += float3(0.98, 1.0, 0.78) * contour * 0.16; color += float3(0.36, 0.92, 1.0) * fieldLine * 0.12; - alpha = saturate(support * surface.colorScatter.w); + alpha = saturate(support * GRID_ALPHA_SCALE); return color; } -void considerTransparentSurfaceEvent(float3 origin, float3 direction, int surfaceId, uint consumedSurfaceMask, float intervalStart, float intervalEnd, inout TransparentEvent nearest) -{ - if (surfaceId < 0) - { - return; - } - - uint surfaceBit = 1u << (uint)min(surfaceId, 31); - if ((consumedSurfaceMask & surfaceBit) != 0u) - { - return; - } - - TransparentSurface surface = transparentSurfaces[surfaceId]; - float travel; - if (!traceGridSurface(origin, direction, intervalStart, min(intervalEnd, nearest.travel), surface, travel)) - { - return; - } - - nearest.hit = true; - nearest.travel = travel; - nearest.color = 0.0; - nearest.alpha = 1.0; - nearest.coverage = 1.0; - nearest.surfaceId = surfaceId; -} - -void considerFroxelTransparentEvents(float3 origin, float3 direction, int froxelIndex, uint consumedSurfaceMask, float intervalStart, float intervalEnd, inout TransparentEvent nearest) -{ - if (froxelIndex < 0) - { - return; - } - - int4 ids = transparentSurfaceIds[froxelIndex]; - considerTransparentSurfaceEvent(origin, direction, ids.x, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - considerTransparentSurfaceEvent(origin, direction, ids.y, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - considerTransparentSurfaceEvent(origin, direction, ids.z, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - considerTransparentSurfaceEvent(origin, direction, ids.w, consumedSurfaceMask, intervalStart, intervalEnd, nearest); -} - float2 mediumAtlasUv(float2 uv, int sliceIndex) { int tileX = sliceIndex % MEDIUM_FROXEL_ATLAS_COLUMNS; @@ -482,26 +395,6 @@ int viewFroxelIndexForUvSlice(float2 uv, int sliceIndex) return cell.x + cell.y * width + sliceIndex * width * height; } -TransparentEvent nearestViewFroxelTransparentEvent(float2 uv, float3 origin, float3 direction, int sliceIndex, uint consumedSurfaceMask) -{ - float intervalStart = mediumSliceStartTravel(sliceIndex); - float intervalEnd = min(mediumSliceEndTravel(sliceIndex), farDistance); - TransparentEvent nearest; - nearest.hit = false; - nearest.travel = intervalEnd; - nearest.color = 0.0; - nearest.alpha = 0.0; - nearest.coverage = 0.0; - nearest.surfaceId = -1; - - int4 ids = transparentSurfaceIds[viewFroxelIndexForUvSlice(uv, sliceIndex)]; - considerTransparentSurfaceEvent(origin, direction, ids.x, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - considerTransparentSurfaceEvent(origin, direction, ids.y, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - considerTransparentSurfaceEvent(origin, direction, ids.z, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - considerTransparentSurfaceEvent(origin, direction, ids.w, consumedSurfaceMask, intervalStart, intervalEnd, nearest); - return nearest; -} - SolidHit nearestViewFroxelSolidHit(float2 uv, float3 origin, float3 direction, int sliceIndex) { float intervalStart = mediumSliceStartTravel(sliceIndex); @@ -585,7 +478,7 @@ void integrateMediumRange( } } -RayMarchResult traverseRay(float2 uv, float3 origin, float3 direction) +RayMarchResult traverseRay(float2 uv, float2 screenUv, float3 origin, float3 direction) { RayMarchResult result; result.color = float3(0.001, 0.003, 0.004); @@ -600,8 +493,6 @@ RayMarchResult traverseRay(float2 uv, float3 origin, float3 direction) float3 inScattering = 0.0; float densityTravelSum = 0.0; float densitySum = 0.0; - float eventTravelSum = 0.0; - float eventSupportSum = 0.0; float densityAccumulation = 0.0; SolidHit nearestSolid; @@ -610,13 +501,6 @@ RayMarchResult traverseRay(float2 uv, float3 origin, float3 direction) nearestSolid.normal = 0.0; nearestSolid.fieldId = 0.0; nearestSolid.primitiveId = -1; - TransparentEvent nearestTransparent; - nearestTransparent.hit = false; - nearestTransparent.travel = farDistance; - nearestTransparent.color = 0.0; - nearestTransparent.alpha = 0.0; - nearestTransparent.coverage = 0.0; - nearestTransparent.surfaceId = -1; [loop] for (int sliceIndex = 0; sliceIndex < MEDIUM_FROXEL_SLICE_COUNT; sliceIndex++) { @@ -625,44 +509,52 @@ RayMarchResult traverseRay(float2 uv, float3 origin, float3 direction) { nearestSolid = cellSolid; } - - TransparentEvent cellTransparent = nearestViewFroxelTransparentEvent(uv, origin, direction, sliceIndex, 0u); - if (cellTransparent.hit && cellTransparent.travel < nearestTransparent.travel) - { - nearestTransparent = cellTransparent; - } - } - - if (nearestTransparent.hit) - { - float3 transparentPosition = origin + direction * nearestTransparent.travel; - float transparentAlpha; - float3 transparentColor = gridEventColor(transparentPosition, transparentSurfaces[nearestTransparent.surfaceId], transparentAlpha); - if (transparentAlpha <= 0.001) - { - nearestTransparent.hit = false; - } - else - { - nearestTransparent.color = transparentColor; - nearestTransparent.alpha = transparentAlpha; - nearestTransparent.coverage = transparentAlpha; - } } float stopTravel = nearestSolid.hit ? nearestSolid.travel : farDistance; - if (nearestTransparent.hit && nearestTransparent.travel < stopTravel) + float3 gridPosition; + float gridTravel; + bool gridHit = traceGridSurfaceDirect(origin, direction, 0.0, stopTravel, gridPosition, gridTravel); + float gridAlpha = 0.0; + float3 gridColor = 0.0; + if (gridHit) { - integrateMediumRange(uv, 0.0, nearestTransparent.travel, transmittance, inScattering, densityAccumulation, densityTravelSum, densitySum); - inScattering += transmittance * nearestTransparent.color * nearestTransparent.alpha; - transmittance *= 1.0 - nearestTransparent.alpha; - eventTravelSum += nearestTransparent.coverage * nearestTransparent.travel; - eventSupportSum += nearestTransparent.coverage; - integrateMediumRange(uv, nearestTransparent.travel, stopTravel, transmittance, inScattering, densityAccumulation, densityTravelSum, densitySum); + gridColor = gridEventColor(gridPosition, gridAlpha); + gridHit = gridAlpha > 0.001; } - else + + float gridTransmittance = 1.0; + float3 gridInScattering = 0.0; + float gridDensityAccumulation = 0.0; + float gridDensityTravelSum = 0.0; + float gridDensitySum = 0.0; + if (gridHit) { - integrateMediumRange(uv, 0.0, stopTravel, transmittance, inScattering, densityAccumulation, densityTravelSum, densitySum); + integrateMediumRange(uv, 0.0, gridTravel, gridTransmittance, gridInScattering, gridDensityAccumulation, gridDensityTravelSum, gridDensitySum); + } + + integrateMediumRange(uv, 0.0, stopTravel, transmittance, inScattering, densityAccumulation, densityTravelSum, densitySum); + + if (gridHit && stochasticTransparency(screenUv, gridAlpha) > 0.0) + { + result.color = gridColor * gridTransmittance + gridInScattering; + result.travel = gridTravel; + result.fieldId = FIELD_ID_GRID; + result.normal = terrainNormal(gridPosition); + result.coverage = gridAlpha; + result.mediumOpacity = saturate(1.0 - gridTransmittance); + result.densityMean = saturate(gridDensityAccumulation / (float)MEDIUM_FROXEL_SLICE_COUNT); + return result; + } + + if (gridHit) + { + result.travel = gridTravel; + result.fieldId = FIELD_ID_GRID; + result.normal = terrainNormal(gridPosition); + result.coverage = gridAlpha; + result.mediumOpacity = saturate(1.0 - gridTransmittance); + result.densityMean = saturate(gridDensityAccumulation / (float)MEDIUM_FROXEL_SLICE_COUNT); } if (nearestSolid.hit) @@ -670,32 +562,30 @@ RayMarchResult traverseRay(float2 uv, float3 origin, float3 direction) float3 p = origin + direction * nearestSolid.travel; float3 bodyColor = shadeBody(p, nearestSolid.normal, nearestSolid.primitiveId); result.color = bodyColor * transmittance + inScattering; - result.travel = nearestSolid.travel; - result.fieldId = nearestSolid.fieldId; - result.normal = nearestSolid.normal; - result.coverage = 1.0; - result.mediumOpacity = saturate(1.0 - transmittance); - result.densityMean = saturate(densityAccumulation / (float)MEDIUM_FROXEL_SLICE_COUNT); + if (!gridHit) + { + result.travel = nearestSolid.travel; + result.fieldId = nearestSolid.fieldId; + result.normal = nearestSolid.normal; + result.coverage = 1.0; + result.mediumOpacity = saturate(1.0 - transmittance); + result.densityMean = saturate(densityAccumulation / (float)MEDIUM_FROXEL_SLICE_COUNT); + } return result; } result.color = result.color * transmittance + inScattering; - result.mediumOpacity = saturate(1.0 - transmittance); - result.densityMean = saturate(densityAccumulation / (float)MEDIUM_FROXEL_SLICE_COUNT); - float transparentEventSupport = saturate(eventSupportSum / (float)MEDIUM_FROXEL_SLICE_COUNT * 4.0); - if (transparentEventSupport > 0.010) + if (!gridHit) { - result.fieldId = FIELD_ID_TRANSPARENT_EVENT; - result.normal = -direction; - result.coverage = transparentEventSupport; - result.travel = eventSupportSum > 0.0001 ? min(eventTravelSum / eventSupportSum, farDistance) : farDistance; - } - else if (result.mediumOpacity > 0.015) - { - result.fieldId = FIELD_ID_MEDIUM; - result.normal = -direction; - result.coverage = saturate(max(result.mediumOpacity, result.densityMean * 4.0)); - result.travel = densitySum > 0.0001 ? min(densityTravelSum / densitySum, farDistance) : farDistance; + result.mediumOpacity = saturate(1.0 - transmittance); + result.densityMean = saturate(densityAccumulation / (float)MEDIUM_FROXEL_SLICE_COUNT); + if (result.mediumOpacity > 0.015) + { + result.fieldId = FIELD_ID_MEDIUM; + result.normal = -direction; + result.coverage = saturate(max(result.mediumOpacity, result.densityMean * 4.0)); + result.travel = densitySum > 0.0001 ? min(densityTravelSum / densitySum, farDistance) : farDistance; + } } return result; @@ -722,7 +612,7 @@ SceneOut D3D12ScenePS(VertexOut input) float2 pixel = screenUv * resolution; float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, gridCenter); - RayMarchResult result = traverseRay(input.uv, cameraPosition, rayDirection); + RayMarchResult result = traverseRay(input.uv, screenUv, cameraPosition, rayDirection); if (renderDebugMode >= 10.5 && renderDebugMode < 11.5) { diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 6c5e046..683afde 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -99,3 +99,4 @@ {"timestamp":"2026-05-09T21:47:47.2476504+01:00","topic":"d3d12-view-froxel-binning-strip-failure","lesson":"A narrow horizontal visibility strip cannot be explained by curved Grid height misses alone. The failed corner-sign Grid test and froxel face-plane sphere test were still proxy tests for the wrong view-froxel shape. The current CPU bootstrap bins spheres with a conservative froxel bounding sphere and bins the Grid by solving actual height-sheet crossings per low-res screen tube, then marking crossed depth slice ranges.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]} {"timestamp":"2026-05-09T22:05:11.0000000+01:00","topic":"d3d12-view-froxel-y-contract","lesson":"The repeated horizontal strip was caused by CPU view-froxel binning using raw top-left pixel Y while the D3D12 scene shader flips input UV Y before ray generation. CPU candidate producers must mirror the shader screen-ray pixel convention exactly. Spheres now use projected screen bounds plus travel slice ranges instead of brute-force per-froxel testing, reducing bootstrap CPU cost.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]} {"timestamp":"2026-05-09T22:01:24.4341856+01:00","topic":"d3d12-grid-depth-residency","lesson":"Depth-sparse CPU binning for the Grid is the wrong bootstrap contract. At grazing angles the Grid is a global transparent height sheet and guessed crossing slice ranges produce sliced bands. Bin the Grid by low-res screen tube and write it to all depth slices for tubes that may see the Grid radius; the shader exact height-sheet intersection remains the authority for whether an event exists inside each interval.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]} +{"timestamp":"2026-05-09T22:18:03.0000000+01:00","topic":"d3d12-grid-stochastic-retreat","lesson":"The D3D12 transparent froxel candidate experiment made the Grid angle-dependent, spiky, and brittle. The Grid should follow the proven D3D11 contract: trace it directly as a stochastic surface before the nearest solid, write Grid identity/travel/normal/coverage for TAA, and do not leave dead transparent-surface binning code in the renderer. Git is the archive.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","state/memory.json","state/scratch.md"]} diff --git a/state/memory.json b/state/memory.json index d71f2a7..a40a272 100644 --- a/state/memory.json +++ b/state/memory.json @@ -19,9 +19,8 @@ "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. D3D11 is reference-only during migration; do not pay DRY tax to preserve it.", - "Transparent D3D12 surfaces must enter the same froxel/field candidate path as volumetrics, but not as pre-averaged froxel color. Grid line transparency is a scene-traversal transparent event: the CPU bins the Grid only into a conservative height slab, the shader brackets the height-sheet crossing inside the active ray interval, samples the height texture at the hit, evaluates cartesian lines/isolines/field lines there, composites without terminating, and keeps marching. Future transparent particles and billboard surfaces need the same candidate/event pipe with quad intersections and richer per-froxel event lists rather than alpha side channels or medium-atlas summaries.", - "D3D12 scene candidate discovery belongs in the view-froxel volume. At 720p the active tube is 160x90x32; primitive and transparent candidate ids are indexed by low-res screen cell and depth slice, then scene rays test exact solid/transparent intersections inside that slice interval. The CPU-filled view-froxel buffers are bootstrap only; the durable path should become GPU/raster binning so per-frame upload bandwidth does not become the next stupid tax.", - "CPU view-froxel binning must mirror the shader's screen-ray coordinate convention. D3D12 scene rays flip input UV Y before ray generation, so CPU binning must generate rays from the same flipped screen pixel Y or candidates appear only in a narrow horizontal strip. Until GPU/raster binning replaces the bootstrap, spheres use projected screen bounds plus travel slice ranges. The Grid is a global transparent height sheet: bin it by screen tube, not guessed sparse depth residency; if a tube may see the Grid radius, write the Grid candidate to every depth slice and let the shader's exact height-sheet intersection reject non-events.", + "Do not put the D3D12 Grid through transparent froxel candidate/event traversal. The one-pass transparent binning experiment made the Grid angle-dependent and brittle. The live Grid contract is direct scene tracing as a stochastic surface before the nearest solid, writing Grid identity/travel/normal/coverage for TAA accumulation. Git holds the old experiment; runtime code should stay lean.", + "D3D12 solid scene candidate discovery belongs in the view-froxel volume. At 720p the active tube is 160x90x32; primitive ids are indexed by low-res screen cell and depth slice, then scene rays test exact solid intersections inside that slice interval. The CPU-filled view-froxel buffers are bootstrap only; the durable path should become GPU/raster binning so per-frame upload bandwidth does not become the next stupid tax.", "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 derives its editable source directory from --shader-source/AQUARIUM_SHADER_SOURCE, then watches D3D12Grid/Medium/Scene/Post/Smoke HLSL files directly. Shader/PSO builds run on a background task; startup presents a lightweight loading frame until the first pipeline set is ready, and hot reload keeps the previous pipeline set if compilation fails.", "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 d27867d..cb40160 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -4,24 +4,20 @@ D3D12 parity push. The host now defaults to D3D12 unless `--renderer` or `AQUARIUM_RENDERER` says otherwise. D3D12 owns the visible scene path: -Grid-height brushes, field/froxel uploads, medium diagnostic/transport/event +Grid-height brushes, field/froxel uploads, medium diagnostic/transport atlases, scene HDR, bloom, temporal resolve/history, debug modes, and DirectWrite debug UI through a narrow D3D11On12 overlay bridge. D3D11 remains selectable only as temporary reference ballast until visible D3D12 use survives the cut. -Current renderer correction: D3D12 scene candidates now live in the view-froxel -volume. The repeated horizontal-strip failure was a CPU/GPU row-contract bug: -the scene shader flips screen Y before ray generation, while CPU binning used -raw top-left pixel Y. CPU binning now mirrors the shader's screen-ray pixel -convention. Solid spheres use projected screen bounds plus travel slice ranges -instead of brute-force testing every froxel. The Grid no longer guesses sparse -depth residency: if a low-res screen tube may see the Grid radius, the Grid -candidate is written to every depth slice for that tube and the shader's exact -height-sheet intersection decides the visible event. The scene shader looks up -solid and transparent candidate ids by `(lowX, lowY, slice)` before doing exact -intersection for that slice interval. Next steel-plate step is replacing the -CPU-filled candidate buffers with GPU/raster binning passes. +Current renderer correction: the D3D12 Grid has been removed from the +transparent/froxel candidate experiment. The Grid now traces directly in the +scene shader as a stochastic surface before the nearest solid, writes Grid +identity/travel/normal/coverage for temporal support, and relies on TAA to +accumulate coverage noise. Solid spheres still use view-froxel projected bounds +for empty-space skipping; transparent surface candidate buffers, descriptors, +root parameters, shader structs, and event traversal were cut rather than left +as dead scaffolding. ## Hot Context