diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 9d44ed6..2523d10 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -134,6 +134,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly ID3D12RootSignature gpuSensorFusionRootSignature; private readonly ID3D12RootSignature fractalReservoirRootSignature; private readonly ID3D12RootSignature tubeFieldRootSignature; + private readonly ID3D12RootSignature tubeFieldRenderRootSignature; private readonly D3D12BlueNoiseTexture blueNoiseTexture; private ID3D12PipelineState? heightFieldBasePipelineState; private ID3D12PipelineState? heightFieldBrushPipelineState; @@ -148,6 +149,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private ID3D12PipelineState? fractalPbrReservoirPipelineState; private ID3D12PipelineState? fractalRadiosityReservoirPipelineState; private ID3D12PipelineState? tubeFieldComputePipelineState; + private ID3D12PipelineState? tubeFieldRenderPipelineState; private ID3D12PipelineState?[] sdfProxyPipelineStates = []; private ID3D12PipelineState? bloomPrefilterPipelineState; private ID3D12PipelineState? bloomDownsamplePipelineState; @@ -203,6 +205,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12StructuredBuffer tubeFieldVertexBuffer; private readonly D3D12StructuredBuffer tubeFieldIndexBuffer; private readonly D3D12StructuredBuffer tubeFieldStatsBuffer; + private readonly List tubeFieldDrawBatches = []; private readonly Dictionary externalSensorTextures = new(StringComparer.Ordinal); private D3D12TrackedResource? programOutputTexture; private IntPtr programOutputSharedHandle; @@ -352,7 +355,7 @@ public sealed class D3D12Renderer : IAquariumRenderer gpuFusionSeedBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Fusion Seed Buffer"); gpuFusionPointBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Fusion Native Point Buffer"); 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); + 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); tubeFieldStatsBuffer = new D3D12StructuredBuffer(device, 4, Marshal.SizeOf(), "Aquarium D3D12 TubeField Stats Buffer", allowUnorderedAccess: true); resourceRegistry.Add("sdf-light-buffer", sdfLightBuffer); @@ -389,6 +392,8 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalReservoirRootSignature.Name = "Aquarium D3D12 Fractal Reservoir Root Signature"; tubeFieldRootSignature = CreateTubeFieldRootSignature(); tubeFieldRootSignature.Name = "Aquarium D3D12 TubeField Root Signature"; + tubeFieldRenderRootSignature = CreateTubeFieldRenderRootSignature(); + tubeFieldRenderRootSignature.Name = "Aquarium D3D12 TubeField Render Root Signature"; CaptureShaderWriteTimes(); StartPipelineBuild("initial"); viewport = new Viewport(0.0f, 0.0f, width, height); @@ -921,6 +926,7 @@ public sealed class D3D12Renderer : IAquariumRenderer && fractalPbrReservoirPipelineState is not null && fractalRadiosityReservoirPipelineState is not null && tubeFieldComputePipelineState is not null + && tubeFieldRenderPipelineState is not null && sdfProxyPipelineStates.All(pipeline => pipeline is not null) && bloomPrefilterPipelineState is not null && bloomDownsamplePipelineState is not null @@ -961,6 +967,7 @@ public sealed class D3D12Renderer : IAquariumRenderer gpuSensorFusionRootSignature.Dispose(); fractalReservoirRootSignature.Dispose(); tubeFieldRootSignature.Dispose(); + tubeFieldRenderRootSignature.Dispose(); blueNoiseTexture.Dispose(); studioIrradianceTexture.Dispose(); studioPmremTexture.Dispose(); @@ -1212,6 +1219,8 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalRadiosityReservoir.Name = "Aquarium D3D12 Fractal Radiosity Reservoir Compute Pipeline"; var tubeFieldCompute = CreateTubeFieldComputePipelineState(paths.TubeField); tubeFieldCompute.Name = "Aquarium D3D12 TubeField Compute Pipeline"; + var tubeFieldRender = CreateTubeFieldRenderPipelineState(paths.TubeField); + tubeFieldRender.Name = "Aquarium D3D12 TubeField Render Pipeline"; var sdfProxies = new ID3D12PipelineState[paths.SdfShaders.Count]; for (var index = 0; index < paths.SdfShaders.Count; index++) { @@ -1244,6 +1253,7 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalPbrReservoir, fractalRadiosityReservoir, tubeFieldCompute, + tubeFieldRender, sdfProxies, bloomPrefilter, bloomDownsample, @@ -1761,7 +1771,7 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.DrawInstanced(6, (uint)visibleFractalSplatCount, 0, 0); } - RenderTubeFields(context.CommandList); + RenderTubeFields(context.CommandList, frameResources); RenderSplineSurfaceClaims(context.CommandList, frameResources); } finally @@ -1807,9 +1817,9 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.DrawInstanced((uint)vertices.Count, 1, 0, 0); } - private void RenderTubeFields(ID3D12GraphicsCommandList activeCommandList) + private void RenderTubeFields(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { - if (activeTubeFieldDrawIndexCount <= 0 || splinePipelineState is null) + if (activeTubeFieldDrawIndexCount <= 0 || tubeFieldRenderPipelineState is null || tubeFieldDrawBatches.Count == 0) { return; } @@ -1818,17 +1828,25 @@ public sealed class D3D12Renderer : IAquariumRenderer tubeFieldIndexBuffer.Transition(activeCommandList, ResourceStates.IndexBuffer); var vertexView = new VertexBufferView( tubeFieldVertexBuffer.Resource.GPUVirtualAddress, - (uint)(MaxTubeFieldVertices * Marshal.SizeOf()), - (uint)Marshal.SizeOf()); + (uint)(MaxTubeFieldVertices * Marshal.SizeOf()), + (uint)Marshal.SizeOf()); var indexView = new IndexBufferView( tubeFieldIndexBuffer.Resource.GPUVirtualAddress, (uint)(MaxTubeFieldIndices * Marshal.SizeOf()), Format.R32_UInt); - activeCommandList.SetPipelineState(splinePipelineState); + activeCommandList.SetPipelineState(tubeFieldRenderPipelineState); + activeCommandList.SetGraphicsRootSignature(tubeFieldRenderRootSignature); + activeCommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu); activeCommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); activeCommandList.IASetVertexBuffers(0, [vertexView]); activeCommandList.IASetIndexBuffer(indexView); - activeCommandList.DrawIndexedInstanced((uint)activeTubeFieldDrawIndexCount, 1, 0, 0, 0); + foreach (var batch in tubeFieldDrawBatches) + { + batch.Source.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + activeCommandList.SetGraphicsRootConstantBufferView(1, batch.ConstantsGpuVirtualAddress); + activeCommandList.SetGraphicsRootShaderResourceView(2, batch.Source.Resource.GPUVirtualAddress); + activeCommandList.DrawIndexedInstanced((uint)batch.IndexCount, 1, (uint)batch.StartIndex, 0, 0); + } } private static void AppendSplineSurfaceEnvelopeGeometry(List output, AquariumSpline3D spline) @@ -2228,6 +2246,7 @@ public sealed class D3D12Renderer : IAquariumRenderer activeTubeFieldDispatchedSegments = 0; activeTubeFieldRequestedSegments = 0; activeTubeFieldTruncatedSegments = 0; + tubeFieldDrawBatches.Clear(); if (tubeFieldComputePipelineState is null || activeFieldEvidenceFrame.TubeSplineLowerings.Count == 0) { return; @@ -2272,6 +2291,7 @@ public sealed class D3D12Renderer : IAquariumRenderer normalized.ColumnStep, 0.0f); var constantsUpload = frameResources.UploadRing.WriteConstant(constants); + var startIndex = segmentBase * 6; sourceBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); tubeFieldVertexBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); @@ -2291,6 +2311,11 @@ public sealed class D3D12Renderer : IAquariumRenderer segmentBase += dispatchSegments; activeTubeFieldDispatchedSegments += dispatchSegments; + tubeFieldDrawBatches.Add(new D3D12TubeFieldDrawBatch( + sourceBuffer, + constantsUpload.GpuVirtualAddress, + startIndex, + dispatchSegments * 6)); } activeTubeFieldDrawIndexCount = activeTubeFieldDispatchedSegments * 6; @@ -3139,6 +3164,7 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalPbrReservoirPipelineState!, fractalRadiosityReservoirPipelineState!, tubeFieldComputePipelineState!, + tubeFieldRenderPipelineState!, sdfProxyPipelineStates.Select(pipeline => pipeline!).ToArray(), bloomPrefilterPipelineState!, bloomDownsamplePipelineState!, @@ -3163,6 +3189,7 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalPbrReservoirPipelineState = pipelines.FractalPbrReservoir; fractalRadiosityReservoirPipelineState = pipelines.FractalRadiosityReservoir; tubeFieldComputePipelineState = pipelines.TubeFieldCompute; + tubeFieldRenderPipelineState = pipelines.TubeFieldRender; for (var index = 0; index < sdfProxyPipelineStates.Length; index++) { sdfProxyPipelineStates[index] = pipelines.SdfProxies[index]; @@ -3505,6 +3532,27 @@ public sealed class D3D12Renderer : IAquariumRenderer return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); } + private ID3D12RootSignature CreateTubeFieldRenderRootSignature() + { + var frameConstants = new DescriptorRange( + DescriptorRangeType.ConstantBufferView, + 1, + 0, + 0, + D3D12.DescriptorRangeOffsetAppend); + var rootParameters = new[] + { + new RootParameter(new RootDescriptorTable([frameConstants]), ShaderVisibility.All), + new RootParameter(RootParameterType.ConstantBufferView, new RootDescriptor(3, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(42, 0), ShaderVisibility.Pixel), + }; + var description = new RootSignatureDescription( + RootSignatureFlags.AllowInputAssemblerInputLayout, + rootParameters, + []); + return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); + } + private FrameResources CreateFrameResources(int index) { var commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); @@ -3640,6 +3688,56 @@ public sealed class D3D12Renderer : IAquariumRenderer return device.CreateComputePipelineState(description); } + private ID3D12PipelineState CreateTubeFieldRenderPipelineState(string path) + { + var vertexShader = CompileShader(path, "D3D12TubeFieldVS", "vs_5_0"); + var pixelShader = CompileShader(path, "D3D12TubeFieldPS", "ps_5_0"); + var blend = BlendDescription.Opaque; + for (var index = 1; index < 8; index++) + { + blend.RenderTarget[index] = new RenderTargetBlendDescription( + false, + false, + Blend.One, + Blend.Zero, + BlendOperation.Add, + Blend.One, + Blend.Zero, + BlendOperation.Add, + LogicOp.Noop, + index < 4 ? ColorWriteEnable.All : ColorWriteEnable.None); + } + + var description = new GraphicsPipelineStateDescription + { + RootSignature = tubeFieldRenderRootSignature, + VertexShader = vertexShader, + PixelShader = pixelShader, + BlendState = blend, + RasterizerState = RasterizerDescription.CullNone, + DepthStencilState = DepthStencilDescription.None, + SampleMask = uint.MaxValue, + PrimitiveTopologyType = PrimitiveTopologyType.Triangle, + InputLayout = new InputLayoutDescription( + [ + new InputElementDescription("POSITION", 0, Format.R32G32B32_Float, 0, 0), + new InputElementDescription("TEXCOORD", 0, Format.R32G32B32_Float, 12, 0), + new InputElementDescription("TEXCOORD", 1, Format.R32G32B32_Float, 24, 0), + new InputElementDescription("TEXCOORD", 2, Format.R32G32B32_Float, 36, 0), + new InputElementDescription("TEXCOORD", 3, Format.R32G32B32_Float, 48, 0), + new InputElementDescription("TEXCOORD", 4, Format.R32G32B32A32_Float, 60, 0), + new InputElementDescription("TEXCOORD", 5, Format.R32G32B32A32_Float, 76, 0), + new InputElementDescription("COLOR", 0, Format.R32G32B32A32_Float, 92, 0), + new InputElementDescription("TEXCOORD", 6, Format.R32G32B32A32_Float, 108, 0), + new InputElementDescription("TEXCOORD", 7, Format.R32G32B32A32_Float, 124, 0), + ]), + RenderTargetFormats = [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], + SampleDescription = new SampleDescription(1, 0), + }; + + return device.CreateGraphicsPipelineState(description); + } + private ID3D12PipelineState CreateBloomPrefilterPipelineState(string path) { return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomPrefilterPS", SceneHdrFormat); @@ -3792,7 +3890,7 @@ public sealed class D3D12Renderer : IAquariumRenderer } catch (Exception ex) { - throw new InvalidOperationException($"Failed to compile shader path={path} entry={entryPoint} profile={profile}.", ex); + throw new InvalidOperationException($"Failed to compile shader path={path} entry={entryPoint} profile={profile}: {ex.Message}", ex); } } @@ -3882,6 +3980,25 @@ public sealed class D3D12Renderer : IAquariumRenderer Vector4 Color, Vector4 Material); + [StructLayout(LayoutKind.Sequential)] + private readonly record struct D3D12TubeFieldVertex( + Vector3 Position, + Vector3 SegmentStart, + Vector3 SegmentEnd, + Vector3 Previous, + Vector3 Next, + Vector4 ShapeData, + Vector4 RadiusData, + Vector4 Color, + Vector4 Material, + Vector4 TubeData); + + private readonly record struct D3D12TubeFieldDrawBatch( + D3D12StructuredBuffer Source, + ulong ConstantsGpuVirtualAddress, + int StartIndex, + int IndexCount); + [StructLayout(LayoutKind.Sequential)] private readonly record struct D3D12TubeFieldConstants( Vector4 Shape, @@ -3952,6 +4069,7 @@ public sealed class D3D12Renderer : IAquariumRenderer ID3D12PipelineState FractalPbrReservoir, ID3D12PipelineState FractalRadiosityReservoir, ID3D12PipelineState TubeFieldCompute, + ID3D12PipelineState TubeFieldRender, IReadOnlyList SdfProxies, ID3D12PipelineState BloomPrefilter, ID3D12PipelineState BloomDownsample, @@ -3967,6 +4085,7 @@ public sealed class D3D12Renderer : IAquariumRenderer BloomDownsample.Dispose(); BloomPrefilter.Dispose(); FractalRadiosityReservoir.Dispose(); + TubeFieldRender.Dispose(); TubeFieldCompute.Dispose(); FractalPbrReservoir.Dispose(); FractalSdfReservoir.Dispose(); diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl index 4d47a64..4f8f1f5 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl @@ -9,6 +9,36 @@ struct TubeFieldVertex float4 radiusData; float4 color; float4 material; + float4 tubeData; +}; + +cbuffer AquariumFrame : register(b0) +{ + float2 resolution; + float timeSeconds; + float viewRadius; + float3 cameraPosition; + float farDistance; + float3 cameraTarget; + float sceneFlags; + float2 viewCenter; + float frameIndex; + float previousTimeSeconds; + float3 previousCameraPosition; + float previousViewRadius; + float3 previousCameraTarget; + float previousSceneFlags; + float2 previousViewCenter; + float2 jitterPixels; + float2 previousJitterPixels; + float renderDebugMode; + float exposure; + float bloomIntensity; + float bloomVeilIntensity; + float4 cursorWorlds; + float4 temporalGaussianInfo; + float4 cameraFrustumXy; + float4 cameraFrustumZ; }; cbuffer TubeFieldConstants : register(b3) @@ -112,7 +142,7 @@ float3 TubePoint(uint logicalColumn, float x) float3(0.0, value * tubeAmplitude.y, 0.0); } -TubeFieldVertex MakeTubeVertex(float3 position, float3 previous, float3 start, float3 end, float3 next, float side, float endpointT, float capSign, float value) +TubeFieldVertex MakeTubeVertex(float3 position, float3 previous, float3 start, float3 end, float3 next, float side, float endpointT, float capSign, float value, uint logicalColumn, float x0, float x1) { TubeFieldVertex vertex; float radius = max(tubeMaterial.x + value * tubeMaterial.y, 0.0001); @@ -126,6 +156,7 @@ TubeFieldVertex MakeTubeVertex(float3 position, float3 previous, float3 start, f vertex.radiusData = float4(radius, radius, tubeMaterial.w, 0.0); vertex.color = float4(rampColor, tubeMaterial.z); vertex.material = float4(max(value * value * tubeDispatch.x, 0.0), tubeMaterial.z, 0.55, 0.55); + vertex.tubeData = float4((float)logicalColumn, x0, x1, tubeDispatch.x); return vertex; } @@ -162,10 +193,10 @@ void D3D12TubeFieldExpandCS(uint3 dispatchThreadId : SV_DispatchThreadID) uint globalSegment = (uint)round(tubeDispatch.z) + localSegment; uint vertexBase = globalSegment * 4u; uint indexBase = globalSegment * 6u; - TubeFieldVertices[vertexBase + 0u] = MakeTubeVertex(start, previous, start, end, next, -1.0, 0.0, -1.0, v0); - TubeFieldVertices[vertexBase + 1u] = MakeTubeVertex(start, previous, start, end, next, 1.0, 0.0, -1.0, v0); - TubeFieldVertices[vertexBase + 2u] = MakeTubeVertex(end, previous, start, end, next, -1.0, 1.0, 1.0, v1); - TubeFieldVertices[vertexBase + 3u] = MakeTubeVertex(end, previous, start, end, next, 1.0, 1.0, 1.0, v1); + TubeFieldVertices[vertexBase + 0u] = MakeTubeVertex(start, previous, start, end, next, -1.0, 0.0, -1.0, v0, logicalColumn, x0, x1); + TubeFieldVertices[vertexBase + 1u] = MakeTubeVertex(start, previous, start, end, next, 1.0, 0.0, -1.0, v0, logicalColumn, x0, x1); + TubeFieldVertices[vertexBase + 2u] = MakeTubeVertex(end, previous, start, end, next, -1.0, 1.0, 1.0, v1, logicalColumn, x0, x1); + TubeFieldVertices[vertexBase + 3u] = MakeTubeVertex(end, previous, start, end, next, 1.0, 1.0, 1.0, v1, logicalColumn, x0, x1); TubeFieldIndices[indexBase + 0u] = vertexBase + 0u; TubeFieldIndices[indexBase + 1u] = vertexBase + 1u; TubeFieldIndices[indexBase + 2u] = vertexBase + 2u; @@ -174,3 +205,268 @@ void D3D12TubeFieldExpandCS(uint3 dispatchThreadId : SV_DispatchThreadID) TubeFieldIndices[indexBase + 5u] = vertexBase + 3u; TubeFieldStats[0] = globalSegment + 1u; } + +struct TubeFieldVertexIn +{ + float3 position : POSITION; + float3 segmentStart : TEXCOORD0; + float3 segmentEnd : TEXCOORD1; + float3 previousPoint : TEXCOORD2; + float3 nextPoint : TEXCOORD3; + float4 shapeData : TEXCOORD4; + float4 radiusData : TEXCOORD5; + float4 color : COLOR; + float4 material : TEXCOORD6; + float4 tubeData : TEXCOORD7; +}; + +struct TubeFieldVertexOut +{ + float4 position : SV_Position; + nointerpolation float2 segmentStartPx : TEXCOORD0; + nointerpolation float2 segmentEndPx : TEXCOORD1; + nointerpolation float2 previousPx : TEXCOORD2; + nointerpolation float2 nextPx : TEXCOORD3; + nointerpolation float2 segmentRadiusPx : TEXCOORD4; + nointerpolation float2 joinRadiusPx : TEXCOORD5; + nointerpolation float4 segmentValidity : TEXCOORD6; + float2 segmentUv : TEXCOORD7; + float4 color : COLOR; + float4 material : TEXCOORD8; + nointerpolation float feather : TEXCOORD9; + nointerpolation float2 segmentTravel : TEXCOORD10; + nointerpolation float4 tubeData : TEXCOORD11; +}; + +struct SceneOut +{ + float4 colorTravel : SV_Target0; + float4 metadata : SV_Target1; + float4 control : SV_Target2; + float4 reservoirGuide : SV_Target3; + float depth : SV_Depth; +}; + +void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) +{ + forward = normalize(target - camera); + float3 worldUp = abs(forward.y) > 0.96 ? float3(0.0, 0.0, 1.0) : float3(0.0, 1.0, 0.0); + right = normalize(cross(worldUp, forward)); + up = normalize(cross(forward, right)); +} + +float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float3 target) +{ + float2 uv = (pixel + jitter) / max(resolution, float2(1.0, 1.0)); + float2 ndc = uv * 2.0 - 1.0; + ndc.y = -ndc.y; + float3 forward; + float3 right; + float3 up; + cameraBasis(camera, target, forward, right, up); + float aspect = resolution.x / max(resolution.y, 1.0); + float halfHeight = max(viewRadius, 0.0001); + float halfWidth = halfHeight * aspect; + float3 targetPoint = target + right * ndc.x * halfWidth + up * ndc.y * halfHeight; + return normalize(targetPoint - camera); +} + +float4 projectCameraSpace(float3 view) +{ + float z = max(view.z, 0.0001); + float x = view.x / max(cameraFrustumXy.y * z, 0.0001); + float y = view.y / max(cameraFrustumXy.w * z, 0.0001); + float depth = saturate((z - cameraFrustumZ.x) / max(cameraFrustumZ.y - cameraFrustumZ.x, 0.0001)); + return float4(x, y, depth, 1.0); +} + +float2 ndcToPixel(float2 ndc) +{ + return float2((ndc.x * 0.5 + 0.5) * resolution.x, (1.0 - (ndc.y * 0.5 + 0.5)) * resolution.y); +} + +float2 pixelToNdc(float2 pixel) +{ + return float2(pixel.x / max(resolution.x, 1.0) * 2.0 - 1.0, 1.0 - pixel.y / max(resolution.y, 1.0) * 2.0); +} + +float splineRadiusToPixels(float radiusWorld, float viewDepth) +{ + float frustumHeight = max(cameraFrustumXy.w - cameraFrustumXy.z, 0.0001); + return max(radiusWorld * resolution.y / max(frustumHeight * max(viewDepth, 0.0001), 0.0001), 0.5); +} + +float3 worldToCameraSpace(float3 worldPoint, float3 right, float3 up, float3 forward) +{ + return float3( + dot(worldPoint - cameraPosition, right), + dot(worldPoint - cameraPosition, up), + dot(worldPoint - cameraPosition, forward)); +} + +float2 safeDirection(float2 value, float2 fallback) +{ + float lengthValue = length(value); + return lengthValue > 0.001 ? value / lengthValue : fallback; +} + +void capsuleDistancePx( + float2 samplePx, + float2 startPx, + float2 endPx, + float startRadiusPx, + float endRadiusPx, + out float sdf, + out float closestT, + out float radiusPx, + out float2 normalPx) +{ + float2 segment = endPx - startPx; + float segmentLength2 = max(dot(segment, segment), 0.0001); + closestT = saturate(dot(samplePx - startPx, segment) / segmentLength2); + float2 closest = startPx + segment * closestT; + radiusPx = lerp(startRadiusPx, endRadiusPx, closestT); + float2 normalPxRaw = samplePx - closest; + float normalPxLength = length(normalPxRaw); + float2 tangent = safeDirection(segment, float2(1.0, 0.0)); + normalPx = normalPxLength > 0.0001 ? normalPxRaw / normalPxLength : float2(-tangent.y, tangent.x); + sdf = normalPxLength - radiusPx; +} + +TubeFieldVertexOut D3D12TubeFieldVS(TubeFieldVertexIn input) +{ + float3 forward; + float3 right; + float3 up; + cameraBasis(cameraPosition, cameraTarget, forward, right, up); + + bool isEndVertex = input.shapeData.y > 0.5; + float endpointT = isEndVertex ? 1.0 : 0.0; + float3 startView = worldToCameraSpace(input.segmentStart, right, up, forward); + float3 endView = worldToCameraSpace(input.segmentEnd, right, up, forward); + float3 previousView = worldToCameraSpace(input.previousPoint, right, up, forward); + float3 nextView = worldToCameraSpace(input.nextPoint, right, up, forward); + float3 endpointView = worldToCameraSpace(input.position, right, up, forward); + float4 startClip = projectCameraSpace(startView); + float4 endClip = projectCameraSpace(endView); + float4 previousClip = projectCameraSpace(previousView); + float4 nextClip = projectCameraSpace(nextView); + float4 endpointClip = projectCameraSpace(endpointView); + + float2 startPx = ndcToPixel(startClip.xy); + float2 endPx = ndcToPixel(endClip.xy); + float2 previousPx = ndcToPixel(previousClip.xy); + float2 nextPx = ndcToPixel(nextClip.xy); + float2 endpointPx = ndcToPixel(endpointClip.xy); + float2 tangent = safeDirection(endPx - startPx, float2(1.0, 0.0)); + float startRadiusPx = splineRadiusToPixels(input.radiusData.x, startView.z); + float endRadiusPx = splineRadiusToPixels(input.radiusData.y, endView.z); + float previousRadiusPx = splineRadiusToPixels(input.radiusData.x, previousView.z); + float nextRadiusPx = splineRadiusToPixels(input.radiusData.y, nextView.z); + float endpointRadiusPx = lerp(startRadiusPx, endRadiusPx, endpointT); + float envelopeRadiusPx = endpointRadiusPx + max(2.0, endpointRadiusPx * max(input.radiusData.z, 0.0) + 1.5); + + float2 previousSegmentPx = startPx - previousPx; + float2 nextSegmentPx = nextPx - endPx; + bool hasPrevious = dot(previousSegmentPx, previousSegmentPx) > 0.0001; + bool hasNext = dot(nextSegmentPx, nextSegmentPx) > 0.0001; + float2 joinTangent = tangent; + if (!isEndVertex && hasPrevious) + { + joinTangent = safeDirection(tangent + safeDirection(previousSegmentPx, tangent), tangent); + } + else if (isEndVertex && hasNext) + { + joinTangent = safeDirection(tangent + safeDirection(nextSegmentPx, tangent), tangent); + } + + float2 joinNormal = float2(-joinTangent.y, joinTangent.x); + float2 expandedPx = endpointPx + joinNormal * input.shapeData.x * envelopeRadiusPx + tangent * input.shapeData.z * envelopeRadiusPx; + + TubeFieldVertexOut output; + output.position = float4(pixelToNdc(expandedPx), endpointClip.z, 1.0); + output.segmentStartPx = startPx; + output.segmentEndPx = endPx; + output.previousPx = previousPx; + output.nextPx = nextPx; + output.segmentRadiusPx = float2(startRadiusPx, endRadiusPx); + output.joinRadiusPx = float2(previousRadiusPx, nextRadiusPx); + output.segmentValidity = float4(hasPrevious ? 1.0 : 0.0, hasNext ? 1.0 : 0.0, endpointT, input.shapeData.x); + output.segmentUv = float2(endpointT, input.shapeData.x); + output.color = input.color; + output.material = input.material; + output.feather = input.radiusData.z; + output.segmentTravel = float2(startView.z, endView.z); + output.tubeData = input.tubeData; + return output; +} + +SceneOut D3D12TubeFieldPS(TubeFieldVertexOut input) +{ + float2 samplePx = input.position.xy; + float sdf; + float closestT; + float radiusPx; + float2 normalPx; + capsuleDistancePx(samplePx, input.segmentStartPx, input.segmentEndPx, input.segmentRadiusPx.x, input.segmentRadiusPx.y, sdf, closestT, radiusPx, normalPx); + + float previousSdf; + float previousT; + float previousRadius; + float2 previousNormal; + capsuleDistancePx(samplePx, input.previousPx, input.segmentStartPx, input.joinRadiusPx.x, input.segmentRadiusPx.x, previousSdf, previousT, previousRadius, previousNormal); + if (input.segmentValidity.x > 0.5 && previousSdf < sdf) + { + sdf = previousSdf; + closestT = 0.0; + radiusPx = previousRadius; + normalPx = previousNormal; + } + + float nextSdf; + float nextT; + float nextRadius; + float2 nextNormal; + capsuleDistancePx(samplePx, input.segmentEndPx, input.nextPx, input.segmentRadiusPx.y, input.joinRadiusPx.y, nextSdf, nextT, nextRadius, nextNormal); + if (input.segmentValidity.y > 0.5 && nextSdf < sdf) + { + sdf = nextSdf; + closestT = 1.0; + radiusPx = nextRadius; + normalPx = nextNormal; + } + + float aa = max(fwidth(sdf), max(0.75, radiusPx * max(input.feather, 0.0))); + float coverage = 1.0 - smoothstep(0.0, aa, sdf); + float sampleX = lerp(input.tubeData.y, input.tubeData.z, closestT); + float value = SampleCurve((uint)round(input.tubeData.x), sampleX); + float3 rampColor = lerp(float3(0.0, 0.0, 0.0), float3(1.0, 0.62, 0.18), value); + float3 ray = rayDirectionForPixel(samplePx, jitterPixels, cameraPosition, cameraTarget); + float3 forward; + float3 right; + float3 up; + cameraBasis(cameraPosition, cameraTarget, forward, right, up); + float rimBlend = saturate((sdf + radiusPx) / max(radiusPx, 0.0001)); + 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(input.material.z, 0.0001)); + float alphaFacing = pow(normalFacing, max(input.material.w, 0.0001)); + float claimCoverage = saturate(input.color.a * coverage * alphaFacing); + if (claimCoverage <= 0.004) + { + discard; + } + + float emission = value * value * max(input.tubeData.w, 0.0); + float3 color = rampColor * emission * glowFacing * claimCoverage; + float travel = lerp(input.segmentTravel.x, input.segmentTravel.y, closestT); + + SceneOut output; + output.colorTravel = float4(color, min(travel, farDistance + 1.0)); + output.metadata = float4(5100.0, sampleX, sdf, radiusPx); + output.control = float4(claimCoverage, coverage, saturate(radiusPx / 32.0), value); + output.reservoirGuide = float4(claimCoverage, 0.0, coverage, value); + output.depth = saturate(travel / max(farDistance, 0.0001)); + return output; +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index db5e040..e2632ea 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -236,3 +236,4 @@ {"lesson":"The corrected Mimir/Fensalir resource boundary is in-process engine ownership, not a cross-process payload authority. D3D12Renderer now owns a D3D12FieldResourceRegistry that resolves valid AquariumFieldResourceDeclaration rows into Fensalir-owned structured/curve buffer slots, reuses unchanged slots, recreates changed shape/access/version, and retires stale slots from the renderer resource registry. Duplicate resource keys are validation errors. Visible rendering is no longer blocked on ownership resolution for structured TubeField payloads; it is blocked on shader binding selected TubeField packets to the resolved slots, with texture, mesh, surface-page, and volume resolvers still future cuts. dotnet build Fensalir.sln --no-restore passed with 0 warnings; dotnet test tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj --no-restore passed with 16 tests.","timestamp":"2026-05-26T17:29:30+01:00","files":["src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs","state/map.yaml"],"source":"continued Mimir/Fensalir field resource boundary implementation","topic":"d3d12-field-resource-registry"} {"lesson":"Rendering-relevant field buffers must be GPU-resident early and stay GPU-resident. The TubeField contract now has an explicit AquariumFieldTubeSplineLowering/DSL command for interpreting a 2D rolling Float32 buffer as Catmull-Rom XY tubes with modulo column addressing, amplitude power/normalization, radius scaling, ramp texture path, and emission scale. D3D12FieldResourceRegistry no longer creates duplicate empty buffers for SharedGpu declarations: shared structured/curve resources must import by GPU handle or remain unsupported; allocation is only for Fensalir-owned GPU-resident producer slots. Visible TubeField rendering remains blocked on shader-side expansion/binding over the GPU slot, not CPU spline tessellation. Fensalir.sln builds cleanly; Aquarium.Engine.Tests passed with 17 tests.","timestamp":"2026-05-26T18:50:34+01:00","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs","src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs","tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs","state/map.yaml"],"source":"user clarified GPU-resident no-copy rendering buffer invariant","topic":"gpu-resident-tubefield-dsl"} {"lesson":"D3D12 TubeField now has a first GPU-only rendering path: resolved resource-backed 2D rolling float buffers bind as read-only GPU memory, a compute shader expands endpoint-clamped Catmull-Rom tube envelopes into fixed-budget vertex/index UAVs, byte-address sample loads honor declared stride, the existing spline SDF pipeline draws opaque tube field geometry, and capacity logs report requested/dispatched/truncated segment counts. This proves shader-side expansion/binding without CPU tessellation; per-pixel source-row material sampling, ramp texture binding, and indirect draw remain the next cuts.","timestamp":"2026-05-26T20:11:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","state/map.yaml"],"source":"continued GPU-resident TubeField implementation","topic":"d3d12-tubefield-compute-expansion"} +{"lesson":"TubeField rendering now has a dedicated D3D12 render pipeline rather than reusing generic spline material. Compute expansion records one draw batch per lowering, and the TubeField pixel shader binds the matching source buffer/constants and resamples the rolling buffer per pixel by column+spline coordinate with the cheap 5-tap path. The initial material is opaque field geometry with fallback black-to-warm ramp, squared normalized emission, and fake Fresnel center-bright/edge-dark shaping. Real ramp texture binding, indirect draw packets, and non-buffer resolvers remain open. Headless dev reload, Aquarium.Engine.Tests, Mimir build, and both Mimir Fensalir field smokes passed.","timestamp":"2026-05-26T20:22:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","state/map.yaml"],"source":"continued GPU-resident TubeField material implementation","topic":"d3d12-tubefield-pixel-material"} diff --git a/state/map.yaml b/state/map.yaml index e048fee..5270e24 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -82,14 +82,17 @@ next_actions: slots only when Fensalir is the producer. The TubeField DSL can now express a 2D rolling float buffer as Catmull-Rom XY tubes with modulo column addressing, amplitude power/normalization, radius, ramp texture path, and - emission scale. D3D12 now has the first shader-side TubeField expansion: - a compute pass binds the rolling sample buffer as read-only GPU memory, - emits fixed-budget vertex/index buffers with endpoint-clamped Catmull-Rom - tube envelopes, honors declared sample stride with byte-address loads, - dispatches the existing spline SDF draw, and reports requested/dispatched/ - truncated segment counts. The next cut is TubeField-specific material - shading that samples source rows per pixel, binds ramp textures with the - linear fallback, and eventually moves the draw to an indirect packet path. + emission scale. D3D12 now has a TubeField compute/render lowering: + compute binds the rolling sample buffer as read-only GPU memory, emits + fixed-budget vertex/index buffers with endpoint-clamped Catmull-Rom tube + envelopes, honors declared sample stride with byte-address loads, and + records one draw batch per lowering so the TubeField pixel shader can bind + the right source row/column and resample material per pixel with the cheap + 5-tap approximation. The first material is opaque field geometry with a + black-to-warm fallback ramp, squared normalized emission, fake Fresnel + center-bright/edge-dark shaping, and requested/dispatched/truncated segment + reporting. Remaining cuts are real ramp texture binding, indirect draw + packets, and texture/mesh/surface-page/volume resolvers. - 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.