From db69e28d2c0b5c3810d4e93b0384ea108e8adf83 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 12 Jul 2026 20:53:20 +0100 Subject: [PATCH] Render Zyphos erosion from persistent GPU pages --- ...teless-planetary-erosion-rendering-plan.md | 43 +++--- .../Render/AquariumApp.cs | 12 ++ .../Render/AquariumRenderPlan.cs | 34 +++++ .../Lod/PlanetarySurfacePage.cs | 7 + src/Aquarium.Engine/Render/D3D12Renderer.cs | 140 +++++++++++++++++- .../Shaders/D3D12PlanetarySurfacePage.hlsl | 12 ++ .../D3D12PlanetarySurfacePageSummary.hlsl | 25 ++++ .../Render/Shaders/D3D12SdfProxy.hlsli | 6 +- .../Shaders/D3D12ZyphosPlanet.hlsl | 19 ++- .../Shaders/D3D12ZyphosTerrain.hlsli | 53 +++++++ .../ZyphosPlanetarySurfacePages.cs | 45 ++++++ src/Aquarium.Zyphos/ZyphosRenderPlan.cs | 4 + src/Aquarium.Zyphos/ZyphosRuntime.cs | 2 +- src/Aquarium.Zyphos/ZyphosSceneBuilder.cs | 15 ++ state/evidence.jsonl | 1 + state/map.yaml | 12 ++ .../Aquarium.Engine.Tests.csproj | 1 + .../D3D12PlanetarySurfacePageTests.cs | 86 +++++++++++ 18 files changed, 491 insertions(+), 26 deletions(-) create mode 100644 src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePage.hlsl create mode 100644 src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePageSummary.hlsl create mode 100644 src/Aquarium.Zyphos/ZyphosPlanetarySurfacePages.cs diff --git a/docs/stateless-planetary-erosion-rendering-plan.md b/docs/stateless-planetary-erosion-rendering-plan.md index 0ca7714..74601eb 100644 --- a/docs/stateless-planetary-erosion-rendering-plan.md +++ b/docs/stateless-planetary-erosion-rendering-plan.md @@ -34,7 +34,7 @@ parent/child residual transitions have not been built. | 2. CPU/GPU parity | Complete | Compute readback comparison over 2,052 samples | | 3. Physical bands | Complete | Wavelength selection, fractional terminal octave, unresolved bound | | 4. GPU pages | Complete | Spherical borders, sibling seam tests, GPU summary reduction | -| 5. Page-backed intersection | In progress | Persistent page generation and direct fallback boot; conservative live bounds remain | +| 5. Page-backed intersection | Complete | Persistent page and summary buffers, conservative bounds/steps, bracketed refinement, radial hit parity | | 6. Quadtree transitions | Not started | Parent/child residual ownership still to implement | | 7. Unified differentials/materials | Not started | Final composed derivative contract still to implement | | 8. Profiling/backend decision | Not started | No frame-time or memory-budget claim yet | @@ -59,11 +59,13 @@ planetary-scale rendering as a whole is complete. - **Forbidden writers:** face-local terrain noise, tile-local seeds, seam repair passes, renderer-only erosion logic, and caches that change terrain when evicted. -- **Shared path:** direct shader evaluation, CPU page baking, GPU page baking, +- **Shared path:** direct compute evaluation, CPU page baking, GPU page baking, reload, and LOD transitions evaluate the same field contract. - **Deletion line:** remove direct full-spectrum erosion from the repeated sphere-tracing loop once page-backed geometry proves equivalent. Keep direct - evaluation only as a bounded fallback and verification oracle. + evaluation as a verification oracle. The visible fallback is the nearest + resident ancestor band; the root fallback is the uneroded base field until a + root page is available. ## Invariants @@ -234,7 +236,8 @@ Exit: independently generated overlapping pages produce identical samples. - Add page lookup to the Zyphos intersection path. - Use min/max summaries for broad-phase culling and conservative stepping. - Add bracketed near-surface root refinement. -- Preserve direct evaluation as oracle and missing-page fallback. +- Preserve direct compute evaluation as the oracle. Use the nearest resident + ancestor, or the base field before root residency, as the visible fallback. - Remove repeated full-spectrum erosion from page-backed sphere tracing. Exit: direct and page-backed hits agree within declared page-filter error. @@ -298,24 +301,22 @@ Measure the actual visible path. ## Immediate next cut -Finish Phase 5 before expanding residency: +Phase 6 replaces the single camera-face page with a projected-error resident +quadtree: -1. Dispatch the existing GPU page-summary reduction into a persistent summary - buffer beside the live page. -2. Bind displacement bounds, unresolved error, and maximum slope to the planet - intersection shader. -3. Use those values for expanded-sphere culling and a sign-preserving - conservative distance bound. Keep the existing bracketed sign-change - refinement as the near-root authority. -4. Retain direct evaluation only as the missing-page fallback and verification - oracle. -5. Prove direct and page-backed hit agreement within the declared page-filter - error, then exercise page absence, arrival, eviction, and field-version - replacement as a timeline. - -Only after that gate should the resident set become a projected-error quadtree. -The next authority change is parent low-frequency terrain plus child residual -bands; it is not “more pages” with independent full-spectrum terrain. +1. Define one page identity containing field version, parameter identity, tile, + and represented wavelength band. +2. Keep all six root pages resident so the root fallback is stable across + camera-face changes. +3. Select a quadtree cut from projected geometric error and current residency; + requests do not become visible until their page and summary are complete. +4. Generate each child as only the newly resolvable residual band over its + parent's identical low-frequency field. +5. Blend residual weight during arrival and eviction. The parent remains the + terrain owner until the child reaches full weight, and no path blends two + independent full-spectrum heights. +6. Probe descent, lateral edge/corner crossing, teleport, reload, page arrival, + and eviction at transition midpoint as well as settled state. ## Sources diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs b/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs index 993d960..78da60f 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs @@ -156,6 +156,18 @@ public sealed class AquariumShaderBuilder(AquariumShaderManifest manifest) return this; } + public AquariumShaderBuilder PlanetarySurfacePage(string path) + { + manifest.PlanetarySurfacePage(path); + return this; + } + + public AquariumShaderBuilder PlanetarySurfacePageSummary(string path) + { + manifest.PlanetarySurfacePageSummary(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 afa5311..667f591 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs @@ -36,6 +36,10 @@ public sealed class AquariumShaderManifest public string FractalSplatRenderShader { get; private set; } = "D3D12FractalSplatRender.hlsl"; + public string PlanetarySurfacePageShader { get; private set; } = "D3D12PlanetarySurfacePage.hlsl"; + + public string PlanetarySurfacePageSummaryShader { get; private set; } = "D3D12PlanetarySurfacePageSummary.hlsl"; + public string PostShader { get; private set; } = "D3D12Post.hlsl"; public string SdfCommonInclude { get; private set; } = "D3D12SdfCommon.hlsli"; @@ -92,6 +96,18 @@ public sealed class AquariumShaderManifest return this; } + public AquariumShaderManifest PlanetarySurfacePage(string path) + { + PlanetarySurfacePageShader = path; + return this; + } + + public AquariumShaderManifest PlanetarySurfacePageSummary(string path) + { + PlanetarySurfacePageSummaryShader = path; + return this; + } + public AquariumShaderManifest Post(string path) { PostShader = path; @@ -499,6 +515,8 @@ public sealed class AquariumSceneState public AquariumFractalReservoirField FractalReservoirField { get; init; } = AquariumFractalReservoirField.Empty; + public AquariumPlanetarySurfacePageSet PlanetarySurfacePages { get; init; } = AquariumPlanetarySurfacePageSet.Empty; + public AquariumGpuSensorFrame GpuSensorFrame { get; init; } = AquariumGpuSensorFrame.Empty; public AquariumAcousticFieldFrame AcousticFieldFrame { get; init; } = AquariumAcousticFieldFrame.Empty; @@ -516,6 +534,22 @@ public sealed class AquariumSceneState public AquariumSplineFrame SplineFrame { get; init; } = AquariumSplineFrame.Empty; } +[StructLayout(LayoutKind.Sequential)] +public readonly record struct AquariumPlanetarySurfacePageInput(Vector4 DirectionRadius, Vector4 Sampling); + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct AquariumPlanetarySurfacePageMetadata(Vector4 Address, Vector4 Layout, Vector4 Bounds, Vector4 State); + +public sealed class AquariumPlanetarySurfacePageSet +{ + public static AquariumPlanetarySurfacePageSet Empty { get; } = new(); + public string GeneratorEntryPoint { get; init; } = "D3D12PlanetaryTerrainPageCS"; + public long Version { get; init; } + public IReadOnlyList Samples { get; init; } = []; + public AquariumPlanetarySurfacePageMetadata Metadata { get; init; } + public bool HasInput => Version > 0 && Samples.Count > 0; +} + public sealed class AquariumBokushoBrushFrame { public static AquariumBokushoBrushFrame Empty { get; } = new(); diff --git a/src/Aquarium.Engine.Fractal/Lod/PlanetarySurfacePage.cs b/src/Aquarium.Engine.Fractal/Lod/PlanetarySurfacePage.cs index 7657e6a..37f4a2e 100644 --- a/src/Aquarium.Engine.Fractal/Lod/PlanetarySurfacePage.cs +++ b/src/Aquarium.Engine.Fractal/Lod/PlanetarySurfacePage.cs @@ -31,6 +31,13 @@ public static class PlanetarySurfacePageSampling if ((uint)storageX >= request.StorageSize || (uint)storageY >= request.StorageSize) throw new ArgumentOutOfRangeException(); var localU = (storageX - request.BorderSize) / (double)(request.InteriorSize - 1); var localV = (storageY - request.BorderSize) / (double)(request.InteriorSize - 1); + return DirectionAtLocal(request, localU, localV); + } + + public static Vector3 DirectionAtLocal(PlanetarySurfacePageRequest request, double localU, double localV) + { + request.Validate(); + if (!double.IsFinite(localU) || !double.IsFinite(localV)) throw new ArgumentOutOfRangeException(); var count = request.Tile.AxisTileCount; var faceU = -1.0 + 2.0 * (request.Tile.X + localU) / count; var faceV = -1.0 + 2.0 * (request.Tile.Y + localV) / count; diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 5b2b252..d9401cb 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -95,6 +95,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int RootTubeFieldReplayManifest = 21; private const int RootTubeFieldReplaySources = 22; private const int RootSceneOverdraw = 23; + private const int RootPlanetarySurfacePage = 29; + private const int RootPlanetarySurfacePageMetadata = 30; + private const int RootPlanetarySurfacePageSummary = 31; private const int RootFusionFrameConstants = 0; private const int RootFusionSeeds = 1; private const int RootFusionSensorCameras = 2; @@ -208,6 +211,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly FrameResources[] frames = new FrameResources[BackBufferCount]; private readonly ID3D12GraphicsCommandList commandList; private readonly ID3D12RootSignature fullscreenRootSignature; + private readonly ID3D12RootSignature planetarySurfacePageRootSignature; private readonly ID3D12RootSignature gpuSensorFusionRootSignature; private readonly ID3D12RootSignature pointCloudRootSignature; private readonly ID3D12RootSignature fractalReservoirRootSignature; @@ -232,6 +236,8 @@ public sealed class D3D12Renderer : IAquariumRenderer private ID3D12PipelineState? fractalSdfReservoirPipelineState; private ID3D12PipelineState? fractalPbrReservoirPipelineState; private ID3D12PipelineState? fractalRadiosityReservoirPipelineState; + private ID3D12PipelineState? planetarySurfacePagePipelineState; + private ID3D12PipelineState? planetarySurfacePageSummaryPipelineState; private ID3D12PipelineState? tubeFieldComputePipelineState; private ID3D12PipelineState? tubeFieldRenderPipelineState; private ID3D12PipelineState? bokushoBrushPipelineState; @@ -311,6 +317,12 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12StructuredBuffer bokushoBrushStrokeBuffer; private readonly D3D12StructuredBuffer bokushoSourcePointBuffer; private readonly D3D12StructuredBuffer bokushoPageDensityBuffer; + private D3D12StructuredBuffer? planetarySurfacePageInputBuffer; + private D3D12StructuredBuffer? planetarySurfacePageOutputBuffer; + private D3D12StructuredBuffer? planetarySurfacePageMetadataBuffer; + private D3D12StructuredBuffer? planetarySurfacePageSummaryBuffer; + private AquariumPlanetarySurfacePageSet activePlanetarySurfacePages = AquariumPlanetarySurfacePageSet.Empty; + private long residentPlanetarySurfacePageVersion; private D3D12StructuredBuffer fieldReservoirCandidateBuffer = null!; private D3D12StructuredBuffer fieldReservoirLockBuffer = null!; private readonly List tubeFieldDrawBatches = []; @@ -582,6 +594,8 @@ public sealed class D3D12Renderer : IAquariumRenderer ReportStartupProgress(startupProgress, "Creating D3D12 render pipelines"); fullscreenRootSignature = CreateFullscreenRootSignature(); fullscreenRootSignature.Name = "Aquarium D3D12 Fullscreen Root Signature"; + planetarySurfacePageRootSignature = CreatePlanetarySurfacePageRootSignature(); + planetarySurfacePageRootSignature.Name = "Aquarium D3D12 Planetary Surface Page Root Signature"; gpuSensorFusionRootSignature = CreateGpuSensorFusionRootSignature(); gpuSensorFusionRootSignature.Name = "Aquarium D3D12 GPU Sensor Fusion Root Signature"; pointCloudRootSignature = CreatePointCloudRootSignature(); @@ -1326,6 +1340,7 @@ public sealed class D3D12Renderer : IAquariumRenderer EnsureFractalReservoirBuffers(activeFractalReservoirField); EnsureFractalProgramTransformBuffer(); EnsureBufferFieldProgramBuffers(); + EnsurePlanetarySurfacePageBuffers(); var activeGpuSensorInput = frame.Scene.GpuSensorFrame.HasInput; var activeAccumulationWindow = activeGpuSensorInput ? frame.Scene.GpuSensorFrame.AccumulationWindowSeconds @@ -1479,6 +1494,7 @@ public sealed class D3D12Renderer : IAquariumRenderer DispatchStereoDepth(commandList, frameResources); DispatchPointClouds(commandList, frameResources); DispatchFractalReservoirs(commandList, frameResources); + DispatchPlanetarySurfacePage(commandList, frameResources); DispatchTubeFields(commandList, frameResources); RenderHeightField(commandList, frameResources); RenderSceneAndPresent(passContext, frameResources); @@ -1673,6 +1689,8 @@ public sealed class D3D12Renderer : IAquariumRenderer && fractalSdfReservoirPipelineState is not null && fractalPbrReservoirPipelineState is not null && fractalRadiosityReservoirPipelineState is not null + && planetarySurfacePagePipelineState is not null + && planetarySurfacePageSummaryPipelineState is not null && tubeFieldComputePipelineState is not null && tubeFieldRenderPipelineState is not null && bokushoBrushPipelineState is not null @@ -1716,6 +1734,7 @@ public sealed class D3D12Renderer : IAquariumRenderer overlayDevice.Dispose(); DisposePipelineStates(); fullscreenRootSignature.Dispose(); + planetarySurfacePageRootSignature.Dispose(); gpuSensorFusionRootSignature.Dispose(); pointCloudRootSignature.Dispose(); fractalReservoirRootSignature.Dispose(); @@ -1742,6 +1761,10 @@ public sealed class D3D12Renderer : IAquariumRenderer bokushoBrushStrokeBuffer.Dispose(); bokushoSourcePointBuffer.Dispose(); bokushoPageDensityBuffer.Dispose(); + planetarySurfacePageMetadataBuffer?.Dispose(); + planetarySurfacePageSummaryBuffer?.Dispose(); + planetarySurfacePageOutputBuffer?.Dispose(); + planetarySurfacePageInputBuffer?.Dispose(); tubeFieldSegmentBuffer.Dispose(); tubeFieldIndexBuffer.Dispose(); tubeFieldVertexBuffer.Dispose(); @@ -2400,6 +2423,12 @@ public sealed class D3D12Renderer : IAquariumRenderer Step("fractal-radiosity-reservoir"); var fractalRadiosityReservoir = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12RadiosityReservoirCS"); fractalRadiosityReservoir.Name = "Aquarium D3D12 Fractal Radiosity Reservoir Compute Pipeline"; + Step("planetary-surface-page"); + var planetarySurfacePage = CreatePlanetarySurfacePagePipelineState(paths.PlanetarySurfacePage); + planetarySurfacePage.Name = "Aquarium D3D12 Planetary Surface Page Compute Pipeline"; + Step("planetary-surface-page-summary"); + var planetarySurfacePageSummary = CreatePlanetarySurfacePageSummaryPipelineState(paths.PlanetarySurfacePageSummary); + planetarySurfacePageSummary.Name = "Aquarium D3D12 Planetary Surface Page Summary Compute Pipeline"; Step("tube-field-compute"); var tubeFieldCompute = CreateTubeFieldComputePipelineState(paths.TubeField); tubeFieldCompute.Name = "Aquarium D3D12 TubeField Compute Pipeline"; @@ -2469,6 +2498,8 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalSdfReservoir, fractalPbrReservoir, fractalRadiosityReservoir, + planetarySurfacePage, + planetarySurfacePageSummary, tubeFieldCompute, tubeFieldRender, bokushoBrush, @@ -3740,6 +3771,12 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.SetGraphicsRootDescriptorTable(RootTemporalGaussians, frameResources.TemporalGaussianDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(RootCurrentReservoirGuide, frameResources.SceneReservoirGuideDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(RootBlueNoise, frameResources.BlueNoiseDescriptor.Gpu); + planetarySurfacePageOutputBuffer!.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + planetarySurfacePageMetadataBuffer!.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + planetarySurfacePageSummaryBuffer!.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + context.CommandList.SetGraphicsRootShaderResourceView(RootPlanetarySurfacePage, planetarySurfacePageOutputBuffer.Resource.GPUVirtualAddress); + context.CommandList.SetGraphicsRootShaderResourceView(RootPlanetarySurfacePageMetadata, planetarySurfacePageMetadataBuffer.Resource.GPUVirtualAddress); + context.CommandList.SetGraphicsRootShaderResourceView(RootPlanetarySurfacePageSummary, planetarySurfacePageSummaryBuffer!.Resource.GPUVirtualAddress); context.CommandList.SetGraphicsRootDescriptorTable(RootSceneOverdraw, frameResources.SceneOverdrawDescriptor.Gpu); context.CommandList.RSSetViewports(viewport); @@ -3859,6 +3896,55 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private void EnsurePlanetarySurfacePageBuffers() + { + var count = Math.Max(activePlanetarySurfacePages.Samples.Count, 1); + if (planetarySurfacePageInputBuffer?.ElementCount == count) return; + planetarySurfacePageMetadataBuffer?.Dispose(); planetarySurfacePageSummaryBuffer?.Dispose(); planetarySurfacePageOutputBuffer?.Dispose(); planetarySurfacePageInputBuffer?.Dispose(); + planetarySurfacePageInputBuffer = new D3D12StructuredBuffer(device, count, Marshal.SizeOf(), "Aquarium Planetary Page Inputs"); + planetarySurfacePageOutputBuffer = new D3D12StructuredBuffer(device, count, 32, "Aquarium Planetary Page Outputs", allowUnorderedAccess: true); + planetarySurfacePageMetadataBuffer = new D3D12StructuredBuffer(device, 1, Marshal.SizeOf(), "Aquarium Planetary Page Metadata"); + planetarySurfacePageSummaryBuffer = new D3D12StructuredBuffer(device, 1, 32, "Aquarium Planetary Page Summary", allowUnorderedAccess: true); + residentPlanetarySurfacePageVersion = 0; + } + + private void DispatchPlanetarySurfacePage(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) + { + if (planetarySurfacePageInputBuffer is null || planetarySurfacePageOutputBuffer is null || planetarySurfacePageMetadataBuffer is null || planetarySurfacePageSummaryBuffer is null) return; + if (!activePlanetarySurfacePages.HasInput) + { + if (residentPlanetarySurfacePageVersion != 0) + { + planetarySurfacePageMetadataBuffer.Upload(activeCommandList, frameResources.UploadRing, new[] { default(AquariumPlanetarySurfacePageMetadata) }); + residentPlanetarySurfacePageVersion = 0; + } + return; + } + if (residentPlanetarySurfacePageVersion == activePlanetarySurfacePages.Version) return; + var samples = activePlanetarySurfacePages.Samples as AquariumPlanetarySurfacePageInput[] ?? activePlanetarySurfacePages.Samples.ToArray(); + planetarySurfacePageInputBuffer.Upload(activeCommandList, frameResources.UploadRing, samples); + planetarySurfacePageMetadataBuffer.Upload(activeCommandList, frameResources.UploadRing, new[] { activePlanetarySurfacePages.Metadata }); + planetarySurfacePageOutputBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + activeCommandList.SetComputeRootSignature(planetarySurfacePageRootSignature); + activeCommandList.SetPipelineState(planetarySurfacePagePipelineState!); + activeCommandList.SetComputeRootShaderResourceView(0, planetarySurfacePageInputBuffer.Resource.GPUVirtualAddress); + activeCommandList.SetComputeRootUnorderedAccessView(1, planetarySurfacePageOutputBuffer.Resource.GPUVirtualAddress); + activeCommandList.SetComputeRoot32BitConstant(2, (uint)samples.Length, 0); + activeCommandList.Dispatch((uint)((samples.Length + 63) / 64), 1, 1); + activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(planetarySurfacePageOutputBuffer.Resource)); + planetarySurfacePageOutputBuffer.Transition(activeCommandList, ResourceStates.NonPixelShaderResource); + planetarySurfacePageSummaryBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + activeCommandList.SetPipelineState(planetarySurfacePageSummaryPipelineState!); + activeCommandList.SetComputeRootShaderResourceView(0, planetarySurfacePageOutputBuffer.Resource.GPUVirtualAddress); + activeCommandList.SetComputeRootUnorderedAccessView(1, planetarySurfacePageSummaryBuffer.Resource.GPUVirtualAddress); + activeCommandList.SetComputeRoot32BitConstant(2, (uint)samples.Length, 0); + activeCommandList.Dispatch(1, 1, 1); + activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(planetarySurfacePageSummaryBuffer.Resource)); + planetarySurfacePageSummaryBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + planetarySurfacePageOutputBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + residentPlanetarySurfacePageVersion = activePlanetarySurfacePages.Version; + } + private void DispatchFractalReservoirs(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { if (activePointCloudSurfaceReservoir) @@ -4744,6 +4830,9 @@ public sealed class D3D12Renderer : IAquariumRenderer activeBokushoBrushFrame = scene.BokushoBrushFrame.HasInput ? scene.BokushoBrushFrame.Normalized() : AquariumBokushoBrushFrame.Empty; + activePlanetarySurfacePages = scene.PlanetarySurfacePages.HasInput + ? scene.PlanetarySurfacePages + : AquariumPlanetarySurfacePageSet.Empty; activeTextureSplinePrograms = PackTextureSplinePrograms(activeBufferFieldFrame); activeTextureFieldSamples = FlattenTextureSamples(activeBufferFieldFrame); activeSplineFrame = MergeSplineFrames( @@ -5949,6 +6038,8 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalSdfReservoirPipelineState!, fractalPbrReservoirPipelineState!, fractalRadiosityReservoirPipelineState!, + planetarySurfacePagePipelineState!, + planetarySurfacePageSummaryPipelineState!, tubeFieldComputePipelineState!, tubeFieldRenderPipelineState!, bokushoBrushPipelineState!, @@ -5982,6 +6073,8 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalSdfReservoirPipelineState = pipelines.FractalSdfReservoir; fractalPbrReservoirPipelineState = pipelines.FractalPbrReservoir; fractalRadiosityReservoirPipelineState = pipelines.FractalRadiosityReservoir; + planetarySurfacePagePipelineState = pipelines.PlanetarySurfacePage; + planetarySurfacePageSummaryPipelineState = pipelines.PlanetarySurfacePageSummary; tubeFieldComputePipelineState = pipelines.TubeFieldCompute; tubeFieldRenderPipelineState = pipelines.TubeFieldRender; bokushoBrushPipelineState = pipelines.BokushoBrush; @@ -6017,6 +6110,8 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalSdfReservoirPipelineState = null; fractalPbrReservoirPipelineState = null; fractalRadiosityReservoirPipelineState = null; + planetarySurfacePagePipelineState = null; + planetarySurfacePageSummaryPipelineState = null; tubeFieldComputePipelineState = null; tubeFieldRenderPipelineState = null; bokushoBrushPipelineState = null; @@ -6228,6 +6323,9 @@ public sealed class D3D12Renderer : IAquariumRenderer new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(78, 0), ShaderVisibility.All), new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(79, 0), ShaderVisibility.All), new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(80, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(81, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(82, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(83, 0), ShaderVisibility.All), }; var staticSamplers = new[] { @@ -6253,6 +6351,18 @@ public sealed class D3D12Renderer : IAquariumRenderer return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); } + private ID3D12RootSignature CreatePlanetarySurfacePageRootSignature() + { + var parameters = new[] + { + new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(0, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(0, 0), ShaderVisibility.All), + new RootParameter(new RootConstants(0, 0, 1), ShaderVisibility.All), + }; + var description = new RootSignatureDescription(RootSignatureFlags.None, parameters, []); + return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); + } + private ID3D12RootSignature CreateGpuSensorFusionRootSignature() { var frameRange = new DescriptorRange( @@ -6668,6 +6778,26 @@ public sealed class D3D12Renderer : IAquariumRenderer return device.CreateComputePipelineState(description); } + private ID3D12PipelineState CreatePlanetarySurfacePagePipelineState(string path) + { + var shader = CompileShader(path, "D3D12ZyphosTerrainPageCS", "cs_5_0"); + return device.CreateComputePipelineState(new ComputePipelineStateDescription + { + RootSignature = planetarySurfacePageRootSignature, + ComputeShader = shader, + }); + } + + private ID3D12PipelineState CreatePlanetarySurfacePageSummaryPipelineState(string path) + { + var shader = CompileShader(path, "D3D12ZyphosTerrainPageSummaryCS", "cs_5_0"); + return device.CreateComputePipelineState(new ComputePipelineStateDescription + { + RootSignature = planetarySurfacePageRootSignature, + ComputeShader = shader, + }); + } + private ID3D12PipelineState CreateStereoDepthPipelineState(string path) { var computeShader = CompileShader(path, "D3D12PackedStereoDepthCS", "cs_5_0"); @@ -7226,6 +7356,8 @@ public sealed class D3D12Renderer : IAquariumRenderer string BokushoBrush, string FractalReservoir, string FractalSplatRender, + string PlanetarySurfacePage, + string PlanetarySurfacePageSummary, string SdfCommon, string SdfProxy, IReadOnlyList SdfShaders, @@ -7234,7 +7366,7 @@ public sealed class D3D12Renderer : IAquariumRenderer string Post, string ReservoirHistoryUpdate) { - public IReadOnlyList All { get; } = [HeightField, Scene, Spline, TemporalGaussian, GpuSensorFusion, StereoDepth, PointCloud, TubeField, BokushoBrush, FractalReservoir, FractalSplatRender, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post, ReservoirHistoryUpdate]; + public IReadOnlyList All { get; } = [HeightField, Scene, Spline, TemporalGaussian, GpuSensorFusion, StereoDepth, PointCloud, TubeField, BokushoBrush, FractalReservoir, FractalSplatRender, PlanetarySurfacePage, PlanetarySurfacePageSummary, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post, ReservoirHistoryUpdate]; public static D3D12ShaderPaths FromManifest(string root, AquariumShaderManifest manifest) { @@ -7254,6 +7386,8 @@ public sealed class D3D12Renderer : IAquariumRenderer shaderPath("D3D12BokushoBrush.hlsl"), shaderPath(manifest.FractalReservoirShader), shaderPath(manifest.FractalSplatRenderShader), + shaderPath(manifest.PlanetarySurfacePageShader), + shaderPath(manifest.PlanetarySurfacePageSummaryShader), shaderPath(manifest.SdfCommonInclude), shaderPath(manifest.SdfProxyInclude), manifest.SdfShaderPaths.Select(shaderPath).ToArray(), @@ -7280,6 +7414,8 @@ public sealed class D3D12Renderer : IAquariumRenderer ID3D12PipelineState FractalSdfReservoir, ID3D12PipelineState FractalPbrReservoir, ID3D12PipelineState FractalRadiosityReservoir, + ID3D12PipelineState PlanetarySurfacePage, + ID3D12PipelineState PlanetarySurfacePageSummary, ID3D12PipelineState TubeFieldCompute, ID3D12PipelineState TubeFieldRender, ID3D12PipelineState BokushoBrush, @@ -7307,6 +7443,8 @@ public sealed class D3D12Renderer : IAquariumRenderer BokushoPageClear.Dispose(); BokushoBrush.Dispose(); FractalRadiosityReservoir.Dispose(); + PlanetarySurfacePage.Dispose(); + PlanetarySurfacePageSummary.Dispose(); TubeFieldRender.Dispose(); TubeFieldCompute.Dispose(); PointCloudRender.Dispose(); diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePage.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePage.hlsl new file mode 100644 index 0000000..d883cf4 --- /dev/null +++ b/src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePage.hlsl @@ -0,0 +1,12 @@ +struct PageInput { float4 direction_radius; float4 sampling; }; +struct PageOutput { float4 height_gradient; float4 masks; }; +StructuredBuffer page_inputs : register(t0); +RWStructuredBuffer page_outputs : register(u0); +cbuffer PageConstants : register(b0) { uint page_sample_count; } +[numthreads(64,1,1)] +void D3D12ZyphosTerrainPageCS(uint3 id : SV_DispatchThreadID) +{ + if(id.x>=page_sample_count)return; + page_outputs[id.x].height_gradient=0; + page_outputs[id.x].masks=float4(0,0,0,1); +} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePageSummary.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePageSummary.hlsl new file mode 100644 index 0000000..da8dfae --- /dev/null +++ b/src/Aquarium.Engine/Render/Shaders/D3D12PlanetarySurfacePageSummary.hlsl @@ -0,0 +1,25 @@ +struct PageOutput { float4 height_gradient; float4 masks; }; +struct PageSummary { float4 bounds; float4 metadata; }; +StructuredBuffer summary_inputs : register(t0); +RWStructuredBuffer summary_outputs : register(u0); +cbuffer PageConstants : register(b0) { uint page_sample_count; } + +[numthreads(1,1,1)] +void D3D12ZyphosTerrainPageSummaryCS(uint3 id : SV_DispatchThreadID) +{ + if (id.x != 0 || page_sample_count == 0) return; + float minimum_height = 3.402823466e+38; + float maximum_height = -3.402823466e+38; + float maximum_slope = 0.0; + float maximum_unresolved = 0.0; + [loop] for (uint index = 0; index < page_sample_count; index++) + { + float4 sample = summary_inputs[index].height_gradient; + minimum_height = min(minimum_height, sample.x); + maximum_height = max(maximum_height, sample.x); + maximum_slope = max(maximum_slope, length(sample.yz)); + maximum_unresolved = max(maximum_unresolved, sample.w); + } + summary_outputs[0].bounds = float4(minimum_height, maximum_height, maximum_slope, maximum_unresolved); + summary_outputs[0].metadata = float4(page_sample_count, 0.0, 0.0, 1.0); +} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli b/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli index 2015be6..afec552 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli +++ b/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli @@ -14,6 +14,10 @@ #define SDF_TRACE_MAX_STEP_RADIUS_SCALE 0.012 #endif +#ifndef SDF_TRACE_BOUND_RADIUS +#define SDF_TRACE_BOUND_RADIUS(sdfObject) max((sdfObject).centerRadius.w * 1.42, 0.001) +#endif + float3 sdfNormal(float3 p, int sdfIndex) { float epsilon = 0.006; @@ -50,7 +54,7 @@ bool refineSdfHit(float3 origin, float3 direction, int sdfIndex, float lowTravel bool traceSdf(float3 origin, float3 direction, int sdfIndex, out float travel, out float3 normal, out SdfSurface surface, out float stepCount) { SdfObject sdfObject = sdfObjects[sdfIndex]; - float boundRadius = max(sdfObject.centerRadius.w * 1.42, 0.001); + float boundRadius = SDF_TRACE_BOUND_RADIUS(sdfObject); if (!traceSphere(origin, direction, sdfObject.centerRadius.xyz, boundRadius, travel)) { normal = 0.0; diff --git a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl index 6f265d9..cef15eb 100644 --- a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl +++ b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl @@ -216,8 +216,11 @@ float zyPebbleCluster(float3 dir) float zyTerrainOffset(float3 dir, SdfObject sdfObject) { float field = zySphericalField(dir); + float4 pageHeightGradient; float2 pageMasks; float sampleSpacing = max(viewRadius / max(resolution.y, 1.0) * 2.0, max(sdfObject.state.x, 0.001) / 8192.0); - float erosionHeight = zyAdvancedErosion(dir, field, max(sdfObject.state.x, 0.001), sampleSpacing).x; + float erosionHeight = zyTrySampleErosionPage(dir,pageHeightGradient,pageMasks) + ? pageHeightGradient.x + : 0.0; float seaLevel = sdfObject.state.z; float land = smoothstep(seaLevel - 0.04, seaLevel + 0.08, field); float mountain = pow(saturate(field - seaLevel), 1.65); @@ -234,7 +237,18 @@ float sdfDistance(float3 p, int sdfIndex) float planetRadius = max(sdfObject.state.x, 0.001); float3 local = p - sdfObject.centerRadius.xyz; float3 dir = zyPlanetDir(local, sdfObject); - return length(local) - (planetRadius + zyTerrainOffset(dir, sdfObject)); + float radialDistance = length(local) - (planetRadius + zyTerrainOffset(dir, sdfObject)); + return radialDistance * zyTerrainConservativeDistanceScale(dir); +} + +float zyPlanetTraceBoundRadius(SdfObject sdfObject) +{ + float legacyBound = max(sdfObject.centerRadius.w * 1.42, 0.001); + ZyPlanetPageSummary summary = zy_planet_page_summary[0]; + ZyPlanetPageMetadata metadata = zy_planet_page_metadata[0]; + if (metadata.state.x < 0.5 || summary.metadata.w < 0.5) return legacyBound; + float erosionExtent = max(abs(summary.bounds.x), abs(summary.bounds.y)) + max(summary.bounds.w, 0.0); + return max(legacyBound, max(sdfObject.state.x, 0.001) + erosionExtent); } SdfSurface sdfSurface(float3 p, int sdfIndex) @@ -301,4 +315,5 @@ float3 shadeSdf(float2 uv, float travel, float3 p, float3 normal, int sdfIndex, return shadeSdfPbr(p, normal, surface) * daylight + city + atmosphere + eclipseTint; } +#define SDF_TRACE_BOUND_RADIUS(sdfObject) zyPlanetTraceBoundRadius(sdfObject) #include "D3D12SdfProxy.hlsli" diff --git a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrain.hlsli b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrain.hlsli index 92fb583..34d6452 100644 --- a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrain.hlsli +++ b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrain.hlsli @@ -3,6 +3,59 @@ #include "CultMath/CultMath.hlsl" +struct ZyPlanetPageOutput { float4 height_gradient; float4 masks; }; +struct ZyPlanetPageMetadata { float4 address; float4 layout; float4 bounds; float4 state; }; +struct ZyPlanetPageSummary { float4 bounds; float4 metadata; }; +StructuredBuffer zy_planet_page : register(t81); +StructuredBuffer zy_planet_page_metadata : register(t82); +StructuredBuffer zy_planet_page_summary : register(t83); + +static const float ZY_TERRAIN_NON_EROSION_SLOPE_BOUND = 8.0; + +float2 zyTerrainCubeFaceUv(float3 dir, out float face) +{ + float3 a=abs(dir); + if(a.x>=a.y&&a.x>=a.z){if(dir.x>=0){face=0;return float2(-dir.z,dir.y)/a.x;}face=1;return float2(dir.z,dir.y)/a.x;} + if(a.y>=a.z){if(dir.y>=0){face=2;return float2(dir.x,-dir.z)/a.y;}face=3;return float2(dir.x,dir.z)/a.y;} + if(dir.z>=0){face=4;return dir.xy/a.z;}face=5;return float2(-dir.x,dir.y)/a.z; +} + +bool zyTrySampleErosionPage(float3 dir, out float4 heightGradient, out float2 masks) +{ + ZyPlanetPageMetadata metadata=zy_planet_page_metadata[0]; heightGradient=0; masks=0; + if(metadata.state.x<0.5)return false; + float face; float2 uv=zyTerrainCubeFaceUv(dir,face); if(abs(face-metadata.address.x)>0.25)return false; + float axisTiles=exp2(metadata.address.y); float2 local=(uv*0.5+0.5)*axisTiles-metadata.address.zw; + if(any(local<0.0)||any(local>1.0))return false; + float storage=metadata.layout.y, interior=metadata.layout.z, border=metadata.layout.w; + float2 texel=local*(interior-1.0)+border; float2 base=floor(texel); float2 fraction=frac(texel); + int2 p0=(int2)clamp(base,0.0,storage-1.0); int2 p1=min(p0+1,(int2)(storage-1.0)); + ZyPlanetPageOutput a=zy_planet_page[p0.y*(int)storage+p0.x], b=zy_planet_page[p0.y*(int)storage+p1.x]; + ZyPlanetPageOutput c=zy_planet_page[p1.y*(int)storage+p0.x], d=zy_planet_page[p1.y*(int)storage+p1.x]; + heightGradient=lerp(lerp(a.height_gradient,b.height_gradient,fraction.x),lerp(c.height_gradient,d.height_gradient,fraction.x),fraction.y); + masks=lerp(lerp(a.masks.xy,b.masks.xy,fraction.x),lerp(c.masks.xy,d.masks.xy,fraction.x),fraction.y); return true; +} + +bool zyTryGetErosionPageSummary(float3 dir, out ZyPlanetPageSummary summary) +{ + summary = zy_planet_page_summary[0]; + ZyPlanetPageMetadata metadata = zy_planet_page_metadata[0]; + if (metadata.state.x < 0.5 || summary.metadata.w < 0.5) return false; + float face; float2 uv = zyTerrainCubeFaceUv(dir, face); + if (abs(face - metadata.address.x) > 0.25) return false; + float axisTiles = exp2(metadata.address.y); + float2 local = (uv * 0.5 + 0.5) * axisTiles - metadata.address.zw; + return all(local >= 0.0) && all(local <= 1.0); +} + +float zyTerrainConservativeDistanceScale(float3 dir) +{ + ZyPlanetPageSummary summary; + float erosionSlope = zyTryGetErosionPageSummary(dir, summary) ? summary.bounds.z : 0.0; + float totalSlopeBound = ZY_TERRAIN_NON_EROSION_SLOPE_BOUND + max(erosionSlope, 0.0); + return rsqrt(1.0 + totalSlopeBound * totalSlopeBound); +} + float zySphericalField(float3 dir) { float latitude = asin(saturate(abs(dir.z)) * 2.0 - 1.0); diff --git a/src/Aquarium.Zyphos/ZyphosPlanetarySurfacePages.cs b/src/Aquarium.Zyphos/ZyphosPlanetarySurfacePages.cs new file mode 100644 index 0000000..3213297 --- /dev/null +++ b/src/Aquarium.Zyphos/ZyphosPlanetarySurfacePages.cs @@ -0,0 +1,45 @@ +using System.Numerics; +using Aquarium.Engine.Fractal; +using Aquarium.Engine.Fractal.Lod; +using Aquarium.Engine.Render; + +namespace Aquarium.Zyphos; + +internal static class ZyphosPlanetarySurfacePages +{ + private static readonly Dictionary Pages = []; + + public static AquariumPlanetarySurfacePageSet ForCamera(Vector3 cameraPosition) + { + var direction = Vector3.Normalize(cameraPosition - ZyphosUmbrosSystem.ZyphosCenter); + var face = DominantFace(direction); + if (Pages.TryGetValue(face, out var cached)) return cached; + var request = new PlanetarySurfacePageRequest(new CubeTileKey(face, 0, 0, 0), 17, 2); + var radius = ZyphosUmbrosSystem.ZyphosSurfaceRadius; + var spacing = PlanetarySurfacePageSampling.NominalAngularTexelSize(request) * radius; + var samples = new AquariumPlanetarySurfacePageInput[request.StorageSize * request.StorageSize]; + for (var y = 0; y < request.StorageSize; y++) for (var x = 0; x < request.StorageSize; x++) + { + var sampleDirection = PlanetarySurfacePageSampling.Direction(request, x, y); + samples[y * request.StorageSize + x] = new AquariumPlanetarySurfacePageInput(new Vector4(sampleDirection, radius), new Vector4(spacing, 0, 0, 0)); + } + var metadata = new AquariumPlanetarySurfacePageMetadata( + new Vector4((int)face, 0, 0, 0), + new Vector4(0, request.StorageSize, request.InteriorSize, request.BorderSize), + Vector4.Zero, + new Vector4(1, (int)face + 1, PlanetarySurfacePageSampling.AngularTexelSize(request), spacing)); + return Pages[face] = new AquariumPlanetarySurfacePageSet + { + GeneratorEntryPoint = "D3D12ZyphosTerrainPageCS", + Version = (int)face + 1, Samples = samples, Metadata = metadata, + }; + } + + private static CubeFace DominantFace(Vector3 d) + { + var a = Vector3.Abs(d); + if (a.X >= a.Y && a.X >= a.Z) return d.X >= 0 ? CubeFace.PositiveX : CubeFace.NegativeX; + if (a.Y >= a.Z) return d.Y >= 0 ? CubeFace.PositiveY : CubeFace.NegativeY; + return d.Z >= 0 ? CubeFace.PositiveZ : CubeFace.NegativeZ; + } +} diff --git a/src/Aquarium.Zyphos/ZyphosRenderPlan.cs b/src/Aquarium.Zyphos/ZyphosRenderPlan.cs index 528bd0d..ff0e4f8 100644 --- a/src/Aquarium.Zyphos/ZyphosRenderPlan.cs +++ b/src/Aquarium.Zyphos/ZyphosRenderPlan.cs @@ -14,6 +14,10 @@ public static class ZyphosRenderPlan var app = new AquariumApp(); app.Shaders .Core("D3D12HeightField.hlsl", "D3D12Scene.hlsl", "D3D12Post.hlsl") + .PlanetarySurfacePage("D3D12ZyphosTerrainPage.hlsl") + .PlanetarySurfacePageSummary("D3D12ZyphosTerrainPageSummary.hlsl") + .SdfShader("D3D12ZyphosPlanet.hlsl") + .SdfShader("D3D12ZyphosUmbros.hlsl") .SdfShader("D3D12ZyphosStar.hlsl"); var heightField = app.RenderTargets.Create("height-field") diff --git a/src/Aquarium.Zyphos/ZyphosRuntime.cs b/src/Aquarium.Zyphos/ZyphosRuntime.cs index 15defe8..3fa6658 100644 --- a/src/Aquarium.Zyphos/ZyphosRuntime.cs +++ b/src/Aquarium.Zyphos/ZyphosRuntime.cs @@ -70,7 +70,7 @@ public sealed class ZyphosRuntime : IAquariumRuntime shot.CameraTarget, timeSeconds, Vector2.Zero, - ZyphosSceneBuilder.Build(timeSeconds, previousTimeSeconds, fractalPlan)); + ZyphosSceneBuilder.Build(timeSeconds, previousTimeSeconds, shot.CameraPosition, fractalPlan)); } } diff --git a/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs b/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs index bacd53a..06f5b96 100644 --- a/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs +++ b/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs @@ -6,6 +6,9 @@ namespace Aquarium.Zyphos; public static class ZyphosSceneBuilder { public static AquariumSceneState Build(float timeSeconds, float previousTimeSeconds, ZyphosFractalRenderPlan fractalPlan) + => Build(timeSeconds, previousTimeSeconds, ZyphosUmbrosSystem.ZyphosCenter + Vector3.UnitZ * 12.0f, fractalPlan); + + public static AquariumSceneState Build(float timeSeconds, float previousTimeSeconds, Vector3 cameraPosition, ZyphosFractalRenderPlan fractalPlan) { return new AquariumSceneState { @@ -21,6 +24,7 @@ public static class ZyphosSceneBuilder PriorityFocus = fractalPlan.ReservoirPriorityFocus, ProgramTransforms = fractalPlan.GpuProgramTransforms, }, + PlanetarySurfacePages = ZyphosPlanetarySurfacePages.ForCamera(cameraPosition), SdfObjects = BuildSdfObjects(timeSeconds, previousTimeSeconds), SdfLights = BuildSdfLights(timeSeconds), }; @@ -29,10 +33,21 @@ public static class ZyphosSceneBuilder private static AquariumSdfObject[] BuildSdfObjects(float timeSeconds, float previousTimeSeconds) { var rotation = ZyphosUmbrosSystem.MutualPhase(timeSeconds); + var previousRotation = ZyphosUmbrosSystem.MutualPhase(previousTimeSeconds); + var umbrosCenter = ZyphosUmbrosSystem.UmbrosCenter(timeSeconds); + var previousUmbrosCenter = ZyphosUmbrosSystem.UmbrosCenter(previousTimeSeconds); var starCenter = ZyphosUmbrosSystem.PrimaryStarCenter(timeSeconds); var previousStarCenter = ZyphosUmbrosSystem.PrimaryStarCenter(previousTimeSeconds); var objects = new AquariumSdfObject[ZyphosRenderPlan.SdfObjectCount]; + objects[ZyphosRenderPlan.PlanetIndex] = new AquariumSdfObject( + new Vector4(ZyphosUmbrosSystem.ZyphosCenter, ZyphosUmbrosSystem.ZyphosBoundRadius), + new Vector4(ZyphosUmbrosSystem.ZyphosCenter, previousRotation), + new Vector4(ZyphosUmbrosSystem.ZyphosSurfaceRadius, rotation, ZyphosUmbrosSystem.SeaLevel, rotation)); + objects[ZyphosRenderPlan.UmbrosIndex] = new AquariumSdfObject( + new Vector4(umbrosCenter, ZyphosUmbrosSystem.UmbrosBoundRadius), + new Vector4(previousUmbrosCenter, 0.0f), + new Vector4(ZyphosUmbrosSystem.UmbrosSurfaceRadius, rotation, 0.0f, 0.0f)); objects[ZyphosRenderPlan.StarIndex] = new AquariumSdfObject( new Vector4(starCenter, ZyphosUmbrosSystem.PrimaryStarVisualRadius), new Vector4(previousStarCenter, 0.0f), diff --git a/state/evidence.jsonl b/state/evidence.jsonl index f97d7d2..1d05d0f 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -337,3 +337,4 @@ {"timestamp":"2026-07-12T21:00:00+01:00","topic":"erosion-physical-frequency-bands","lesson":"Planetary erosion LOD is now a filter over one world-space spectrum: CultMath selects active octaves from physical wavelength and sample spacing, fractionally weights the last resolvable octave, and reports omitted height. Zyphos uses that contract through smooth planet-space triplanar charts, so changing view footprint changes represented bands rather than switching terrain authorities.","files":["E:\\Projects\\CultMath\\src\\CultMath\\ErosionFrequencyBands.cs","E:\\Projects\\CultMath\\src\\CultMath\\AdvancedErosionFilter.cs","E:\\Projects\\CultMath\\shaders\\AdvancedErosionFilter.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl"],"source":"phase 3 of stateless planetary erosion rendering plan"} {"timestamp":"2026-07-12T21:35:00+01:00","topic":"planetary-page-boundary-authority","lesson":"Using each tile's locally measured angular texel size caused independently generated sibling pages to choose different erosion weights at the same shared boundary. Band selection now uses a level-global nominal angular footprint; local projection distortion remains summary evidence. GPU-generated sibling boundaries are identical and borders sample the spherical field without neighbor residency.","files":["src/Aquarium.Engine.Fractal/Lod/PlanetarySurfacePage.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrain.hlsli","src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrainPage.hlsl","tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs"],"source":"phase 4 cross-page GPU verification"} {"timestamp":"2026-07-12T22:00:00+01:00","topic":"planetary-page-summary-reduction","lesson":"Planetary erosion pages now reduce minimum/maximum displacement, maximum tangent slope, and maximum unresolved height through the GPU kernel and verify those results against CPU reduction. These summaries are the conservative evidence needed by later intersection and residency; they are not inferred from parameters.","files":["src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrainPageSummary.hlsl","tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs"],"source":"phase 4 GPU summary gate"} +{"timestamp":"2026-07-12T23:15:00+01:00","topic":"page-backed-planetary-intersection","lesson":"Planetary erosion rendering now generates a persistent D3D12 page and GPU summary, binds both to Zyphos SDF tracing, uses measured displacement/slope/unresolved evidence for bounds and conservative radial stepping, and retains the shared bracketed sign-change refiner. Compiling the previously unregistered planet proxy proved that advanced erosion cannot remain nested in the Shader Model 5 pixel trace; exact direct evaluation is therefore the CPU/compute oracle, while visible misses use the resident ancestor or base field. Zyphos now registers and publishes planet, Umbros, and star in matching object-index order.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosTerrain.hlsli","src/Aquarium.Zyphos/ZyphosRenderPlan.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs"],"source":"phase 5 compile, D3D12 summary, lifecycle, and direct-versus-page hit verification"} diff --git a/state/map.yaml b/state/map.yaml index f548045..bf6d85e 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -93,6 +93,18 @@ invariants: band selection. Per-tile projection distortion is summary evidence only; it may not change terrain at a shared boundary. Page borders evaluate the spherical field beyond tile bounds without reading neighbor residency. + - D3D12 owns persistent planetary page input, output, metadata, and summary + buffers. Client compute shaders generate the page and reduce min/max + displacement, maximum slope, and unresolved error before SDF proxies read + them at t81-t83. Zyphos registers planet, Umbros, and star proxies in object + index order and publishes all three SDF objects from one scene builder. + - Advanced erosion is not evaluated inside the pixel-shader sphere-trace + loop. Shader Model 5 cannot carry its nested dynamic octave loops there, + and doing so would multiply the full filter by every ray step. Missing + pages therefore lower to the nearest resident ancestor (the base field at + root); direct CultMath evaluation remains the CPU/compute verification + oracle. Page summaries expand broad-phase bounds and scale radial steps, + while the shared SDF proxy owns bracketed sign-change refinement. - The shared reservoir is a fractal domain reservoir, not a texel cache. Pixel rows are the current D3D12 execution projection of selected domain evidence. Area-domain contributors must carry selected subpixel or local diff --git a/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj b/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj index 1cdd582..e2fc1a1 100644 --- a/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj +++ b/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj @@ -21,6 +21,7 @@ + diff --git a/tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs b/tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs index 0fd4370..359de71 100644 --- a/tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs +++ b/tests/Aquarium.Engine.Tests/D3D12PlanetarySurfacePageTests.cs @@ -3,11 +3,62 @@ using System.Runtime.InteropServices; using Aquarium.Engine.Fractal; using Aquarium.Engine.Fractal.Lod; using Aquarium.Engine.Render; +using Aquarium.Zyphos; namespace Aquarium.Engine.Tests; public sealed class D3D12PlanetarySurfacePageTests { + [Fact] + public void ZyphosRegistersAndPublishesAllSdfAuthoritiesInIndexOrder() + { + var plan = ZyphosRenderPlan.Create(); + Assert.Equal( + new[] { "D3D12ZyphosPlanet.hlsl", "D3D12ZyphosUmbros.hlsl", "D3D12ZyphosStar.hlsl" }, + plan.Shaders.SdfShaderPaths.Select(Path.GetFileName)); + + var scene = ZyphosSceneBuilder.Build(1.0f, 0.5f, ZyphosUmbrosSystem.ZyphosCenter + Vector3.UnitZ * 12.0f, default); + Assert.Equal(ZyphosRenderPlan.SdfObjectCount, scene.SdfObjects.Count); + Assert.Equal(ZyphosUmbrosSystem.ZyphosBoundRadius, scene.SdfObjects[ZyphosRenderPlan.PlanetIndex].CenterRadius.W); + Assert.Equal(ZyphosUmbrosSystem.UmbrosBoundRadius, scene.SdfObjects[ZyphosRenderPlan.UmbrosIndex].CenterRadius.W); + Assert.Equal(ZyphosUmbrosSystem.PrimaryStarVisualRadius, scene.SdfObjects[ZyphosRenderPlan.StarIndex].CenterRadius.W); + } + + [Fact] + public void CameraFaceSelectionReusesResidentPageAndVersionsReplacement() + { + var center = ZyphosUmbrosSystem.ZyphosCenter; + var first = ZyphosSceneBuilder.Build(0.0f, 0.0f, center + Vector3.UnitZ * 12.0f, default).PlanetarySurfacePages; + var sameFace = ZyphosSceneBuilder.Build(0.0f, 0.0f, center + Vector3.Normalize(new Vector3(0.1f, 0.1f, 1.0f)) * 12.0f, default).PlanetarySurfacePages; + var replacement = ZyphosSceneBuilder.Build(0.0f, 0.0f, center + Vector3.UnitX * 12.0f, default).PlanetarySurfacePages; + + Assert.Same(first, sameFace); + Assert.NotEqual(first.Version, replacement.Version); + Assert.NotEqual(first.Metadata.Address.X, replacement.Metadata.Address.X); + } + + [Fact] + public void ZyphosPlanetaryProxyShadersCompileWithPageBindings() + { + var temporaryRoot = Path.Combine(Path.GetTempPath(), $"aquarium-zyphos-shaders-{Guid.NewGuid():N}"); + Directory.CreateDirectory(temporaryRoot); + try + { + CopyShaderTree(Path.Combine(RepositoryRoot(), "src", "Aquarium.Engine", "Render", "Shaders"), temporaryRoot); + CopyShaderTree(Path.Combine(RepositoryRoot(), "src", "Aquarium.Zyphos", "Shaders"), temporaryRoot); + CopyShaderTree(Path.GetFullPath(Path.Combine(RepositoryRoot(), "..", "CultMath", "shaders")), Path.Combine(temporaryRoot, "CultMath")); + foreach (var shaderName in new[] { "D3D12ZyphosPlanet.hlsl", "D3D12ZyphosUmbros.hlsl", "D3D12ZyphosStar.hlsl" }) + { + var bytecode = D3D12ShaderCompiler.Compile(Path.Combine(temporaryRoot, shaderName), "D3D12SdfProxyPS", "ps_5_0", skipOptimizationInDebug: false); + Assert.False(bytecode.IsEmpty); + } + } + finally + { + Directory.Delete(temporaryRoot, recursive: true); + } + } + [Fact] public void IndependentlyGeneratedSiblingPagesAgreeOnSharedBoundary() { @@ -35,6 +86,30 @@ public sealed class D3D12PlanetarySurfacePageTests Assert.Equal(min,summary.Bounds.X); Assert.Equal(max,summary.Bounds.Y); Assert.Equal(slope,summary.Bounds.Z); Assert.Equal(output.Max(s=>s.HeightGradient.W),summary.Bounds.W); } + [Fact] + public void PageBackedRadialHitsAgreeWithDirectOracleWithinDeclaredError() + { + var request=new PlanetarySurfacePageRequest(new CubeTileKey(CubeFace.PositiveZ,1,1,0),9,2); + var page=Generate(request); const float radius=8.4f,rayOriginRadius=12.0f; + var spacing=PlanetarySurfacePageSampling.NominalAngularTexelSize(request)*radius; + var points=new[]{new Vector2(0.08f,0.11f),new Vector2(0.37f,0.61f),new Vector2(0.52f,0.48f),new Vector2(0.79f,0.22f),new Vector2(0.91f,0.88f)}; + var directInput=points.Select(point=>new PageInput(new Vector4(PlanetarySurfacePageSampling.DirectionAtLocal(request,point.X,point.Y),radius),new Vector4(spacing,0,0,0))).ToArray(); + var direct=D3D12ComputeProbe.Run(ShaderPath(),"D3D12ZyphosTerrainPageCS",directInput); + float H(int px,int py)=>page[py*request.StorageSize+px].HeightGradient.X; + float Lerp(float a,float b,float t)=>a+(b-a)*t; + var maximumSlope=page.Max(s=>MathF.Sqrt(s.HeightGradient.Y*s.HeightGradient.Y+s.HeightGradient.Z*s.HeightGradient.Z)); + for(var index=0;indexPath.Combine(RepositoryRoot(),"src","Aquarium.Zyphos","Shaders","D3D12ZyphosTerrainPage.hlsl"); + private static void CopyShaderTree(string source, string destination) + { + foreach (var file in Directory.EnumerateFiles(source, "*.*", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(source, file); + var target = Path.Combine(destination, relative); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(file, target, overwrite: true); + } + } + private static string RepositoryRoot(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Fensalir.sln")))d=d.Parent;return d?.FullName??throw new InvalidOperationException();} [StructLayout(LayoutKind.Sequential)] private readonly record struct PageInput(Vector4 DirectionRadius,Vector4 Sampling); [StructLayout(LayoutKind.Sequential)] private readonly record struct PageOutput(Vector4 HeightGradient,Vector4 Masks);