From c7d64a00aa38d368431673b09d5ebe56237ba5d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 20:25:47 +0100 Subject: [PATCH] Run LocalCast fusion through D3D12 compute --- docs/temporal-sdf-gaussian-field.md | 44 ++++- .../Render/AquariumApp.cs | 6 + .../Render/AquariumRenderPlan.cs | 34 ++++ src/Aquarium.Engine/Render/D3D12Renderer.cs | 153 +++++++++++++++++- .../Render/D3D12StructuredBuffer.cs | 29 +++- .../Features/D3D12GpuFusionSeedPacket.cs | 13 ++ .../Render/Shaders/D3D12LocalCastFusion.hlsl | 72 +++++++++ .../LocalCastGpuFusionMapper.cs | 73 +++++++++ src/Aquarium.LocalCast/LocalCastRuntime.cs | 10 +- .../LocalCastTemporalGaussianMapperTests.cs | 35 ++++ 10 files changed, 452 insertions(+), 17 deletions(-) create mode 100644 src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs create mode 100644 src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl create mode 100644 src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs diff --git a/docs/temporal-sdf-gaussian-field.md b/docs/temporal-sdf-gaussian-field.md index 3a6d8f5..6c3da85 100644 --- a/docs/temporal-sdf-gaussian-field.md +++ b/docs/temporal-sdf-gaussian-field.md @@ -34,9 +34,12 @@ diegetic scene content. `Aquarium.LocalCast` is the first concrete live client for this contract. It reads `localcast.visual.render_frame` from LocalCastBridge's typed CultCache -MessagePack document, maps every point claim into `TemporalGaussianObservation` -rows, and lets the accumulator own smoothing, history, and presentation delay. -It does not downsample the document in client space. +MessagePack document. The older CPU path can still map point claims into +`TemporalGaussianObservation` rows for accumulator smoothing, but the live +LocalCast path now prefers `AquariumGpuFusionField`: compact fusion seeds enter +the D3D12 backend, `D3D12LocalCastFusion.hlsl` dispatches over them, and the +compute shader writes the temporal Gaussian buffer consumed by the SDF Gaussian +draw. It does not downsample the document in client space. ## Invariants @@ -55,10 +58,37 @@ It does not downsample the document in client space. This cut deliberately claims million-slot ingestion, not a finished million-splat renderer architecture. The live D3D12 path can draw up to 1,048,576 temporal -Gaussians through instanced proxy quads and only uploads the active packet span. -The next scaling cut belongs to the Aquarium renderer: selected-cut residency, -tiled/bin dispatch, GPU accumulation, and clustered visibility. Do not push that -scheduler into LocalCastBridge. +Gaussians through instanced proxy quads, only uploads the active seed/packet +span, and now owns the GPU lowering step from LocalCast fusion seeds to Gaussian +packets. The next scaling cut belongs to the Aquarium renderer: packed camera +planes, selected-cut residency, tiled/bin dispatch, GPU accumulation, and +clustered visibility. Do not push that scheduler into LocalCastBridge. + +## GPU Fusion Spine + +The active GPU boundary is deliberately narrow: + +```text +LocalCast typed visual frame +-> AquariumGpuFusionSeed[] +-> D3D12 LocalCast fusion compute shader +-> RWStructuredBuffer +-> instanced SDF Gaussian draw +-> TAA/resolve +``` + +Ownership: + +- `AquariumGpuFusionField` is the renderer contract for GPU-owned fusion input. +- `LocalCastGpuFusionMapper` converts typed LocalCast point claims into compact + seeds without client downsampling. +- `D3D12LocalCastFusion.hlsl` owns the first compute lowering pass. +- `D3D12Renderer` owns UAV-capable temporal Gaussian storage, dispatch, and the + transition back to shader-resource state for the draw. + +Next cut: replace point-claim seeds with packed camera planes and Leap packed +maps so the compute shader performs stereo/flow/feature extraction directly on +GPU-resident sensor data. The first shader pass also uses camera-facing proxy planes to evaluate each kernel. True ray-integrated volume compositing, Gaussian depth sorting, and diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs b/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs index 3d093bf..a2d6606 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs @@ -138,6 +138,12 @@ public sealed class AquariumShaderBuilder(AquariumShaderManifest manifest) return this; } + public AquariumShaderBuilder LocalCastFusion(string path) + { + manifest.LocalCastFusion(path); + return this; + } + public AquariumShaderBuilder Include(string path) { manifest.Include(path); diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs b/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs index 1b72416..a11427e 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs @@ -29,6 +29,8 @@ public sealed class AquariumShaderManifest public string TemporalGaussianShader { get; private set; } = "D3D12TemporalGaussian.hlsl"; + public string LocalCastFusionShader { get; private set; } = "D3D12LocalCastFusion.hlsl"; + public string PostShader { get; private set; } = "D3D12Post.hlsl"; public string SdfCommonInclude { get; private set; } = "D3D12SdfCommon.hlsli"; @@ -67,6 +69,12 @@ public sealed class AquariumShaderManifest return this; } + public AquariumShaderManifest LocalCastFusion(string path) + { + LocalCastFusionShader = path; + return this; + } + public AquariumShaderManifest Post(string path) { PostShader = path; @@ -256,6 +264,30 @@ public readonly record struct AquariumTemporalSdfGaussian( float ShapePower, int FieldId); +public readonly record struct AquariumGpuFusionSeed( + string StableKey, + Vector3 Center, + Vector3 PreviousCenter, + Vector3 Velocity, + Vector3 Radii, + Vector4 ColorOpacity, + float Confidence, + float HistoryWeight, + float Falloff, + float ShapePower, + int FieldId); + +public sealed class AquariumGpuFusionField +{ + public static AquariumGpuFusionField Empty { get; } = new(); + + public IReadOnlyList Seeds { get; init; } = []; + + public float AccumulationWindowSeconds { get; init; } + + public float PresentationDelaySeconds { get; init; } +} + public sealed class AquariumTemporalGaussianField { public static AquariumTemporalGaussianField Empty { get; } = new(); @@ -282,4 +314,6 @@ public sealed class AquariumSceneState public IReadOnlyList SdfLights { get; init; } = []; public AquariumTemporalGaussianField TemporalGaussianField { get; init; } = AquariumTemporalGaussianField.Empty; + + public AquariumGpuFusionField GpuFusionField { get; init; } = AquariumGpuFusionField.Empty; } diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 14587c0..7c978bd 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -52,6 +52,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int RootStudioIrradiance = 11; private const int RootSdfObjects = 12; private const int RootTemporalGaussians = 13; + private const int RootFusionFrameConstants = 0; + private const int RootFusionSeeds = 1; + private const int RootFusionOutput = 2; private static readonly DebugUi.DebugUiOption[] RenderDebugOptions = [ new(0, "Final"), @@ -85,10 +88,12 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly FrameResources[] frames = new FrameResources[BackBufferCount]; private readonly ID3D12GraphicsCommandList commandList; private readonly ID3D12RootSignature fullscreenRootSignature; + private readonly ID3D12RootSignature localCastFusionRootSignature; private ID3D12PipelineState? heightFieldBasePipelineState; private ID3D12PipelineState? heightFieldBrushPipelineState; private ID3D12PipelineState? scenePipelineState; private ID3D12PipelineState? temporalGaussianPipelineState; + private ID3D12PipelineState? localCastFusionPipelineState; private ID3D12PipelineState?[] sdfProxyPipelineStates = []; private ID3D12PipelineState? bloomPrefilterPipelineState; private ID3D12PipelineState? bloomDownsamplePipelineState; @@ -126,13 +131,16 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12RenderTarget[] bloomScratchTargets = new D3D12RenderTarget[BloomLevelCount]; private readonly D3D12StructuredBuffer sdfLightBuffer; private readonly D3D12StructuredBuffer sdfObjectBuffer; + private readonly D3D12StructuredBuffer gpuFusionSeedBuffer; private readonly D3D12StructuredBuffer temporalGaussianBuffer; private readonly D3D12CubeTexture studioPmremTexture; private readonly D3D12CubeTexture studioIrradianceTexture; private readonly AquariumSdfLight[] sdfLights = new AquariumSdfLight[MaxSdfLightCount]; private readonly AquariumSdfObject[] sdfObjects = new AquariumSdfObject[MaxSdfObjectCount]; + private readonly D3D12GpuFusionSeedPacket[] gpuFusionSeeds = new D3D12GpuFusionSeedPacket[MaxTemporalGaussianCount]; private readonly D3D12TemporalGaussianPacket[] temporalGaussians = new D3D12TemporalGaussianPacket[MaxTemporalGaussianCount]; private int temporalGaussianCount; + private bool temporalGaussiansGpuGenerated; private Viewport viewport; private RawRect scissorRect; private int width; @@ -230,9 +238,11 @@ public sealed class D3D12Renderer : IAquariumRenderer CreateGraphRenderTargets(); sdfLightBuffer = new D3D12StructuredBuffer(device, MaxSdfLightCount, Marshal.SizeOf(), "Aquarium D3D12 Sdf Light Buffer"); sdfObjectBuffer = new D3D12StructuredBuffer(device, MaxSdfObjectCount, Marshal.SizeOf(), "Aquarium D3D12 Sdf Object Buffer"); - temporalGaussianBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 Temporal Gaussian Buffer"); + gpuFusionSeedBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 LocalCast GPU Fusion Seed Buffer"); + temporalGaussianBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 Temporal Gaussian Buffer", allowUnorderedAccess: true); resourceRegistry.Add("sdf-light-buffer", sdfLightBuffer); resourceRegistry.Add("sdf-object-buffer", sdfObjectBuffer); + resourceRegistry.Add("gpu-fusion-seed-buffer", gpuFusionSeedBuffer); resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); commandList.Name = "Aquarium D3D12 Graphics Command List"; @@ -249,6 +259,8 @@ public sealed class D3D12Renderer : IAquariumRenderer ReportStartupProgress(startupProgress, "Creating D3D12 render pipelines"); fullscreenRootSignature = CreateFullscreenRootSignature(); fullscreenRootSignature.Name = "Aquarium D3D12 Fullscreen Root Signature"; + localCastFusionRootSignature = CreateLocalCastFusionRootSignature(); + localCastFusionRootSignature.Name = "Aquarium D3D12 LocalCast Fusion Root Signature"; CaptureShaderWriteTimes(); StartPipelineBuild("initial"); viewport = new Viewport(0.0f, 0.0f, width, height); @@ -484,6 +496,12 @@ public sealed class D3D12Renderer : IAquariumRenderer } CopySceneState(frame.Scene); + var activeAccumulationWindow = frame.Scene.GpuFusionField.Seeds.Count > 0 + ? frame.Scene.GpuFusionField.AccumulationWindowSeconds + : frame.Scene.TemporalGaussianField.AccumulationWindowSeconds; + var activePresentationDelay = frame.Scene.GpuFusionField.Seeds.Count > 0 + ? frame.Scene.GpuFusionField.PresentationDelaySeconds + : frame.Scene.TemporalGaussianField.PresentationDelaySeconds; var frameConstants = frameResources.UploadRing.WriteConstant(new FrameConstants( new Vector2(width, height), frame.TimeSeconds, @@ -510,8 +528,8 @@ public sealed class D3D12Renderer : IAquariumRenderer new Vector4( temporalGaussianCount, MaxTemporalGaussianCount, - frame.Scene.TemporalGaussianField.AccumulationWindowSeconds, - frame.Scene.TemporalGaussianField.PresentationDelaySeconds))); + activeAccumulationWindow, + activePresentationDelay))); frameResources.FrameConstantsDescriptor = frameResources.TransientShaderDescriptors.Allocate(); device.CreateConstantBufferView( new ConstantBufferViewDescription(frameConstants.GpuVirtualAddress, frameConstants.SizeInBytes), @@ -526,8 +544,12 @@ public sealed class D3D12Renderer : IAquariumRenderer sdfLightBuffer.CreateShaderResourceView(device, frameResources.SdfLightDescriptor); frameResources.SdfObjectDescriptor = frameResources.TransientShaderDescriptors.Allocate(); sdfObjectBuffer.CreateShaderResourceView(device, frameResources.SdfObjectDescriptor); + frameResources.GpuFusionSeedDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + gpuFusionSeedBuffer.CreateShaderResourceView(device, frameResources.GpuFusionSeedDescriptor); frameResources.TemporalGaussianDescriptor = frameResources.TransientShaderDescriptors.Allocate(); temporalGaussianBuffer.CreateShaderResourceView(device, frameResources.TemporalGaussianDescriptor); + frameResources.TemporalGaussianUnorderedAccessDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + temporalGaussianBuffer.CreateUnorderedAccessView(device, frameResources.TemporalGaussianUnorderedAccessDescriptor); frameResources.StudioPmremDescriptor = frameResources.TransientShaderDescriptors.Allocate(); studioPmremTexture.CreateShaderResourceView(device, frameResources.StudioPmremDescriptor); frameResources.StudioIrradianceDescriptor = frameResources.TransientShaderDescriptors.Allocate(); @@ -569,6 +591,7 @@ public sealed class D3D12Renderer : IAquariumRenderer var recordCpuStart = Stopwatch.GetTimestamp(); commandList.BeginEvent("Aquarium D3D12 Frame"); UploadSceneStructuredResources(commandList, frameResources); + DispatchLocalCastGpuFusion(commandList, frameResources); RenderHeightField(commandList, frameResources); RenderSceneAndPresent(new D3D12PassContext(commandList, frameResources.BackBuffer, frameResources.BackBufferRenderTargetView.Cpu), frameResources); commandList.EndEvent(); @@ -698,6 +721,7 @@ public sealed class D3D12Renderer : IAquariumRenderer && heightFieldBrushPipelineState is not null && scenePipelineState is not null && temporalGaussianPipelineState is not null + && localCastFusionPipelineState is not null && sdfProxyPipelineStates.All(pipeline => pipeline is not null) && bloomPrefilterPipelineState is not null && bloomDownsamplePipelineState is not null @@ -735,8 +759,11 @@ public sealed class D3D12Renderer : IAquariumRenderer overlayDevice.Dispose(); DisposePipelineStates(); fullscreenRootSignature.Dispose(); + localCastFusionRootSignature.Dispose(); studioIrradianceTexture.Dispose(); studioPmremTexture.Dispose(); + temporalGaussianBuffer.Dispose(); + gpuFusionSeedBuffer.Dispose(); sdfObjectBuffer.Dispose(); sdfLightBuffer.Dispose(); DisposeBloomRenderTargets(); @@ -876,6 +903,8 @@ public sealed class D3D12Renderer : IAquariumRenderer scene.Name = "Aquarium D3D12 Scene Pipeline"; var temporalGaussian = CreateTemporalGaussianPipelineState(paths.TemporalGaussian); temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; + var localCastFusion = CreateLocalCastFusionPipelineState(paths.LocalCastFusion); + localCastFusion.Name = "Aquarium D3D12 LocalCast Fusion Compute Pipeline"; var sdfProxies = new ID3D12PipelineState[paths.SdfShaders.Count]; for (var index = 0; index < paths.SdfShaders.Count; index++) { @@ -899,6 +928,7 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrush, scene, temporalGaussian, + localCastFusion, sdfProxies, bloomPrefilter, bloomDownsample, @@ -1386,7 +1416,41 @@ public sealed class D3D12Renderer : IAquariumRenderer { sdfLightBuffer.Upload(activeCommandList, frameResources.UploadRing, sdfLights); sdfObjectBuffer.Upload(activeCommandList, frameResources.UploadRing, sdfObjects); - temporalGaussianBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians.AsSpan(0, temporalGaussianCount)); + if (temporalGaussiansGpuGenerated) + { + gpuFusionSeedBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, gpuFusionSeeds.AsSpan(0, temporalGaussianCount)); + } + else + { + temporalGaussianBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians.AsSpan(0, temporalGaussianCount)); + } + } + finally + { + activeCommandList.EndEvent(); + } + } + + private void DispatchLocalCastGpuFusion(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) + { + if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0) + { + return; + } + + activeCommandList.BeginEvent("LocalCast GPU Fusion"); + try + { + gpuFusionSeedBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + temporalGaussianBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); + activeCommandList.SetComputeRootSignature(localCastFusionRootSignature); + activeCommandList.SetPipelineState(localCastFusionPipelineState!); + activeCommandList.SetComputeRootDescriptorTable(RootFusionFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); + activeCommandList.SetComputeRootDescriptorTable(RootFusionSeeds, frameResources.GpuFusionSeedDescriptor.Gpu); + activeCommandList.SetComputeRootDescriptorTable(RootFusionOutput, frameResources.TemporalGaussianUnorderedAccessDescriptor.Gpu); + activeCommandList.Dispatch((uint)((temporalGaussianCount + 127) / 128), 1, 1); + temporalGaussianBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); } finally { @@ -1428,6 +1492,7 @@ public sealed class D3D12Renderer : IAquariumRenderer Array.Clear(sdfObjects); Array.Clear(sdfLights); temporalGaussianCount = 0; + temporalGaussiansGpuGenerated = false; heightFieldBrushConstants = D3D12HeightFieldBrushConstants.FromBrushes(scene.HeightFieldBrushes); var objectCount = Math.Min(scene.SdfObjects.Count, MaxSdfObjectCount); @@ -1442,6 +1507,18 @@ public sealed class D3D12Renderer : IAquariumRenderer sdfLights[index] = scene.SdfLights[index]; } + if (scene.GpuFusionField.Seeds.Count > 0) + { + var seedCount = Math.Min(scene.GpuFusionField.Seeds.Count, MaxTemporalGaussianCount); + temporalGaussianCount = seedCount; + temporalGaussiansGpuGenerated = true; + for (var index = 0; index < seedCount; index++) + { + gpuFusionSeeds[index] = ToGpuFusionSeedPacket(scene.GpuFusionField.Seeds[index]); + } + return; + } + var gaussianCount = Math.Min(scene.TemporalGaussianField.Gaussians.Count, MaxTemporalGaussianCount); temporalGaussianCount = gaussianCount; for (var index = 0; index < gaussianCount; index++) @@ -1450,6 +1527,17 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private static D3D12GpuFusionSeedPacket ToGpuFusionSeedPacket(AquariumGpuFusionSeed seed) + { + return new D3D12GpuFusionSeedPacket( + new Vector4(seed.Center, Math.Clamp(seed.HistoryWeight, 0.0f, 1.0f)), + new Vector4(seed.PreviousCenter, seed.FieldId), + new Vector4(seed.Velocity, Math.Clamp(seed.Confidence, 0.0f, 1.0f)), + new Vector4(Vector3.Max(seed.Radii, new Vector3(0.0001f)), MathF.Max(0.0001f, seed.Falloff)), + seed.ColorOpacity, + new Vector4(MathF.Max(0.0001f, seed.ShapePower), 0.0f, 0.0f, 0.0f)); + } + private static D3D12TemporalGaussianPacket ToTemporalGaussianPacket(AquariumTemporalSdfGaussian gaussian) { var orientation = gaussian.Orientation.LengthSquared() <= 0.000001f @@ -1691,6 +1779,7 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState!, scenePipelineState!, temporalGaussianPipelineState!, + localCastFusionPipelineState!, sdfProxyPipelineStates.Select(pipeline => pipeline!).ToArray(), bloomPrefilterPipelineState!, bloomDownsamplePipelineState!, @@ -1706,6 +1795,7 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState = pipelines.HeightFieldBrush; scenePipelineState = pipelines.Scene; temporalGaussianPipelineState = pipelines.TemporalGaussian; + localCastFusionPipelineState = pipelines.LocalCastFusion; for (var index = 0; index < sdfProxyPipelineStates.Length; index++) { sdfProxyPipelineStates[index] = pipelines.SdfProxies[index]; @@ -1724,6 +1814,7 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState = null; scenePipelineState = null; temporalGaussianPipelineState = null; + localCastFusionPipelineState = null; Array.Clear(sdfProxyPipelineStates); bloomPrefilterPipelineState = null; bloomDownsamplePipelineState = null; @@ -1917,6 +2008,39 @@ public sealed class D3D12Renderer : IAquariumRenderer return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); } + private ID3D12RootSignature CreateLocalCastFusionRootSignature() + { + var frameRange = new DescriptorRange( + DescriptorRangeType.ConstantBufferView, + 1, + 0, + 0, + D3D12.DescriptorRangeOffsetAppend); + var seedRange = new DescriptorRange( + DescriptorRangeType.ShaderResourceView, + 1, + 26, + 0, + D3D12.DescriptorRangeOffsetAppend); + var outputRange = new DescriptorRange( + DescriptorRangeType.UnorderedAccessView, + 1, + 0, + 0, + D3D12.DescriptorRangeOffsetAppend); + var rootParameters = new[] + { + new RootParameter(new RootDescriptorTable([frameRange]), ShaderVisibility.All), + new RootParameter(new RootDescriptorTable([seedRange]), ShaderVisibility.All), + new RootParameter(new RootDescriptorTable([outputRange]), ShaderVisibility.All), + }; + var description = new RootSignatureDescription( + RootSignatureFlags.None, + rootParameters, + []); + return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); + } + private FrameResources CreateFrameResources(int index) { var commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); @@ -1947,6 +2071,17 @@ public sealed class D3D12Renderer : IAquariumRenderer return CreateFullscreenPipelineState(path, "D3D12TemporalGaussianVS", "D3D12TemporalGaussianPS", [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], enableDepth: true); } + private ID3D12PipelineState CreateLocalCastFusionPipelineState(string path) + { + var computeShader = CompileShader(path, "D3D12LocalCastFusionCS", "cs_5_0"); + var description = new ComputePipelineStateDescription + { + RootSignature = localCastFusionRootSignature, + ComputeShader = computeShader, + }; + return device.CreateComputePipelineState(description); + } + private ID3D12PipelineState CreateBloomPrefilterPipelineState(string path) { return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomPrefilterPS", SceneHdrFormat); @@ -2134,6 +2269,7 @@ public sealed class D3D12Renderer : IAquariumRenderer string HeightField, string Scene, string TemporalGaussian, + string LocalCastFusion, string SdfCommon, string SdfProxy, IReadOnlyList SdfShaders, @@ -2141,7 +2277,7 @@ public sealed class D3D12Renderer : IAquariumRenderer IReadOnlyList Includes, string Post) { - public IReadOnlyList All { get; } = [HeightField, Scene, TemporalGaussian, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post]; + public IReadOnlyList All { get; } = [HeightField, Scene, TemporalGaussian, LocalCastFusion, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post]; public static D3D12ShaderPaths FromManifest(string root, AquariumShaderManifest manifest) { @@ -2153,6 +2289,7 @@ public sealed class D3D12Renderer : IAquariumRenderer shaderPath(manifest.HeightFieldShader), shaderPath(manifest.SceneShader), shaderPath(manifest.TemporalGaussianShader), + shaderPath(manifest.LocalCastFusionShader), shaderPath(manifest.SdfCommonInclude), shaderPath(manifest.SdfProxyInclude), manifest.SdfShaderPaths.Select(shaderPath).ToArray(), @@ -2167,6 +2304,7 @@ public sealed class D3D12Renderer : IAquariumRenderer ID3D12PipelineState HeightFieldBrush, ID3D12PipelineState Scene, ID3D12PipelineState TemporalGaussian, + ID3D12PipelineState LocalCastFusion, IReadOnlyList SdfProxies, ID3D12PipelineState BloomPrefilter, ID3D12PipelineState BloomDownsample, @@ -2181,6 +2319,7 @@ public sealed class D3D12Renderer : IAquariumRenderer BloomBlurHorizontal.Dispose(); BloomDownsample.Dispose(); BloomPrefilter.Dispose(); + LocalCastFusion.Dispose(); TemporalGaussian.Dispose(); foreach (var sdfProxy in SdfProxies) { @@ -2212,8 +2351,12 @@ public sealed class D3D12Renderer : IAquariumRenderer public D3D12DescriptorSlot SdfObjectDescriptor { get; set; } + public D3D12DescriptorSlot GpuFusionSeedDescriptor { get; set; } + public D3D12DescriptorSlot TemporalGaussianDescriptor { get; set; } + public D3D12DescriptorSlot TemporalGaussianUnorderedAccessDescriptor { get; set; } + public D3D12DescriptorSlot StudioPmremDescriptor { get; set; } public D3D12DescriptorSlot StudioIrradianceDescriptor { get; set; } diff --git a/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs b/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs index ea36893..633eb5a 100644 --- a/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs +++ b/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs @@ -9,14 +9,16 @@ internal sealed class D3D12StructuredBuffer : IDisposable private readonly int elementCount; private readonly int strideBytes; - public D3D12StructuredBuffer(ID3D12Device device, int elementCount, int strideBytes, string name) + public D3D12StructuredBuffer(ID3D12Device device, int elementCount, int strideBytes, string name, bool allowUnorderedAccess = false) { this.elementCount = elementCount; this.strideBytes = strideBytes; SizeBytes = elementCount * strideBytes; Resource = device.CreateCommittedResource( HeapType.Default, - ResourceDescription.Buffer((ulong)SizeBytes), + ResourceDescription.Buffer( + (ulong)SizeBytes, + allowUnorderedAccess ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None), ResourceStates.Common, null); Resource.Name = name; @@ -96,7 +98,28 @@ internal sealed class D3D12StructuredBuffer : IDisposable descriptor.Cpu); } - private void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) + public void CreateUnorderedAccessView(ID3D12Device device, D3D12DescriptorSlot descriptor) + { + device.CreateUnorderedAccessView( + Resource, + null, + new UnorderedAccessViewDescription + { + Format = Format.Unknown, + ViewDimension = UnorderedAccessViewDimension.Buffer, + Buffer = new BufferUnorderedAccessView + { + FirstElement = 0, + NumElements = (uint)elementCount, + StructureByteStride = (uint)strideBytes, + CounterOffsetInBytes = 0, + Flags = BufferUnorderedAccessViewFlags.None, + }, + }, + descriptor.Cpu); + } + + public void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) { if (State == nextState) { diff --git a/src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs b/src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs new file mode 100644 index 0000000..e481f28 --- /dev/null +++ b/src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs @@ -0,0 +1,13 @@ +using System.Numerics; +using System.Runtime.InteropServices; + +namespace Aquarium.Engine.Render.Features; + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct D3D12GpuFusionSeedPacket( + Vector4 CenterHistoryWeight, + Vector4 PreviousCenterFieldId, + Vector4 VelocityConfidence, + Vector4 RadiiFalloff, + Vector4 ColorOpacity, + Vector4 ShapePad); diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl new file mode 100644 index 0000000..0297ead --- /dev/null +++ b/src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl @@ -0,0 +1,72 @@ +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; +}; + +struct GpuFusionSeed +{ + float4 centerHistoryWeight; + float4 previousCenterFieldId; + float4 velocityConfidence; + float4 radiiFalloff; + float4 colorOpacity; + float4 shapePad; +}; + +struct TemporalGaussian +{ + float4 centerHistoryWeight; + float4 previousCenterFieldId; + float4 velocityConfidence; + float4 radiiFalloff; + float4 orientation; + float4 colorOpacity; + float4 shapePad; +}; + +StructuredBuffer fusionSeeds : register(t26); +RWStructuredBuffer temporalGaussiansOut : register(u0); + +[numthreads(128, 1, 1)] +void D3D12LocalCastFusionCS(uint3 dispatchThreadId : SV_DispatchThreadID) +{ + uint index = dispatchThreadId.x; + uint seedCount = (uint)temporalGaussianInfo.x; + if (index >= seedCount) + { + return; + } + + GpuFusionSeed seed = fusionSeeds[index]; + TemporalGaussian gaussian; + gaussian.centerHistoryWeight = seed.centerHistoryWeight; + gaussian.previousCenterFieldId = seed.previousCenterFieldId; + gaussian.velocityConfidence = seed.velocityConfidence; + gaussian.radiiFalloff = seed.radiiFalloff; + gaussian.orientation = float4(0.0, 0.0, 0.0, 1.0); + gaussian.colorOpacity = seed.colorOpacity; + gaussian.shapePad = seed.shapePad; + temporalGaussiansOut[index] = gaussian; +} diff --git a/src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs b/src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs new file mode 100644 index 0000000..8204388 --- /dev/null +++ b/src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs @@ -0,0 +1,73 @@ +using System.Numerics; +using Aquarium.Engine.Render; + +namespace Aquarium.LocalCast; + +public sealed class LocalCastGpuFusionMapper +{ + private const float NanosecondsToSeconds = 1.0f / 1_000_000_000.0f; + + public AquariumGpuFusionField Map(LocalCastVisualFrame frame) + { + var seeds = new AquariumGpuFusionSeed[frame.Points.Count]; + for (var index = 0; index < frame.Points.Count; index++) + { + seeds[index] = MapPoint(frame.Points[index], index); + } + + return new AquariumGpuFusionField + { + Seeds = seeds, + AccumulationWindowSeconds = 2.75f, + PresentationDelaySeconds = 0.35f, + }; + } + + private static AquariumGpuFusionSeed MapPoint(LocalCastVisualPoint point, int fieldId) + { + var confidence = Math.Clamp(point.Confidence, 0.0f, 1.0f); + var radius = Math.Clamp(point.RadiusMeters, 0.0015f, 0.09f); + var isLeap = point.StableKey.StartsWith("leap-motion:", StringComparison.Ordinal); + var isDense = point.StableKey.StartsWith("dense-rgb:", StringComparison.Ordinal); + var anisotropy = isLeap ? 0.62f : isDense ? 0.42f : 0.55f; + var radii = new Vector3(radius * 1.7f, radius * anisotropy, radius * 1.15f); + var opacity = Math.Clamp(point.ColorOpacity.W * (0.35f + confidence * 0.65f), 0.0f, 0.98f); + var color = new Vector4( + Math.Clamp(point.ColorOpacity.X, 0.0f, 1.0f), + Math.Clamp(point.ColorOpacity.Y, 0.0f, 1.0f), + Math.Clamp(point.ColorOpacity.Z, 0.0f, 1.0f), + opacity); + + return new AquariumGpuFusionSeed( + point.StableKey, + point.Position, + point.Position, + Vector3.Zero, + radii, + color, + confidence, + confidence, + isDense ? 5.5f : 4.2f, + isLeap ? 2.4f : 1.65f, + StableFieldId(point.StableKey, fieldId)); + } + + public float ToTimelineSeconds(long monotonicNs) + { + return monotonicNs * NanosecondsToSeconds; + } + + private static int StableFieldId(string key, int fallback) + { + unchecked + { + var hash = 17; + foreach (var ch in key) + { + hash = (hash * 31) + ch; + } + + return Math.Abs(hash == int.MinValue ? fallback : hash); + } + } +} diff --git a/src/Aquarium.LocalCast/LocalCastRuntime.cs b/src/Aquarium.LocalCast/LocalCastRuntime.cs index 4a378d7..27bf62c 100644 --- a/src/Aquarium.LocalCast/LocalCastRuntime.cs +++ b/src/Aquarium.LocalCast/LocalCastRuntime.cs @@ -15,7 +15,9 @@ public sealed class LocalCastRuntime : IAquariumRuntime presentationDelaySeconds: 0.35f, smoothing: 0.55f); private readonly LocalCastTemporalGaussianMapper mapper = new(); + private readonly LocalCastGpuFusionMapper gpuFusionMapper = new(); private readonly LocalCastVisualStateReader reader; + private AquariumGpuFusionField latestGpuFusionField = AquariumGpuFusionField.Empty; private float timeSeconds; private float sceneTimelineSeconds; private long lastFrameId = -1; @@ -57,7 +59,10 @@ public sealed class LocalCastRuntime : IAquariumRuntime { TraceHeightFieldSurface = false, UseStarfieldBackground = false, - TemporalGaussianField = temporalField, + TemporalGaussianField = ReferenceEquals(latestGpuFusionField, AquariumGpuFusionField.Empty) + ? temporalField + : AquariumTemporalGaussianField.Empty, + GpuFusionField = latestGpuFusionField, }; return new AquariumFrame( @@ -94,6 +99,7 @@ public sealed class LocalCastRuntime : IAquariumRuntime if (frame.FrameId != lastFrameId) { accumulator.Observe(mapper.Map(frame)); + latestGpuFusionField = gpuFusionMapper.Map(frame); lastFrameId = frame.FrameId; latestPointCount = frame.Points.Count; latestStatus = "live"; @@ -101,7 +107,7 @@ public sealed class LocalCastRuntime : IAquariumRuntime sceneTimelineSeconds = MathF.Max( sceneTimelineSeconds + Math.Max(deltaSeconds, 0.0f), - mapper.ToTimelineSeconds(frame.PresentTimeNs)); + gpuFusionMapper.ToTimelineSeconds(frame.PresentTimeNs)); } public void FlushState() diff --git a/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs b/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs index b75aee0..224014f 100644 --- a/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs +++ b/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs @@ -81,4 +81,39 @@ public sealed class LocalCastTemporalGaussianMapperTests Assert.Contains(observations, observation => observation.StableKey == "leap-motion:green:0:0"); Assert.Contains(observations, observation => observation.StableKey.StartsWith("room-rgb:", StringComparison.Ordinal)); } + + [Fact] + public void MapsVisualPointsToGpuFusionSeedsWithoutClientDownsampling() + { + var points = new List(); + for (var index = 0; index < 8192; index++) + { + points.Add(new LocalCastVisualPoint( + index % 2 == 0 ? $"dense-rgb:{index}" : $"leap-motion:green:{index}", + new Vector3(index * 0.0001f, 0.0f, 1.0f), + 0.006f, + new Vector4(0.4f, 0.7f, 1.0f, 0.85f), + 0.9f, + 1_000_000_000 + index)); + } + + var field = new LocalCastGpuFusionMapper().Map(new LocalCastVisualFrame + { + SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, + FrameId = 2, + CreatedMonotonicNs = 1_000_000_000, + SourceTimeMinNs = 1_000_000_000, + SourceTimeMaxNs = 1_000_010_000, + PresentTimeNs = 1_350_000_000, + AudioAlignmentTimeNs = 1_350_000_000, + SpoutSenderName = "LocalCastBridge Point Cloud", + TargetWidth = 1920, + TargetHeight = 1080, + Points = points, + }); + + Assert.Equal(8192, field.Seeds.Count); + Assert.Contains(field.Seeds, seed => seed.StableKey.StartsWith("dense-rgb:", StringComparison.Ordinal)); + Assert.Contains(field.Seeds, seed => seed.ShapePower > 2.0f); + } }