From b9ceb9c20e0aa7b1b6c195fac2ee3959a655db95 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 19 May 2026 20:34:42 +0100 Subject: [PATCH] Add CPU fractal surface page rasterizer --- docs/perfect-machine-architecture.md | 6 +- .../fractal-brush-implementation-roadmap.md | 2 + .../Brushes/FractalBrushEnvelope2D.cs | 6 + .../Lod/FractalSurfacePagePayload.cs | 20 +++ .../Lod/FractalSurfacePageRasterizer.cs | 157 ++++++++++++++++++ src/Aquarium.Zyphos/ZyphosFractalTerrain.cs | 28 +++- state/evidence.jsonl | 1 + state/map.yaml | 1 + state/memory.json | 1 + .../FractalBrushEnvelope2DTests.cs | 10 ++ .../FractalSurfacePageRasterizerTests.cs | 101 +++++++++++ .../ZyphosFractalTerrainTests.cs | 5 +- 12 files changed, 334 insertions(+), 4 deletions(-) create mode 100644 src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs create mode 100644 src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs create mode 100644 tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs diff --git a/docs/perfect-machine-architecture.md b/docs/perfect-machine-architecture.md index bc6b368..53b6749 100644 --- a/docs/perfect-machine-architecture.md +++ b/docs/perfect-machine-architecture.md @@ -518,8 +518,10 @@ turns a selected IFS cut into stable page metadata, and the Zyphos render plan now exposes height, 2D signed-distance, material, and confidence pages beside its structural probe reservoir. `FractalSurfacePageResidencyPlanner` adds a mockable page-store boundary with byte-budgeted resident, missing, requested, -and evicted page decisions. The real page store, atlas, and D3D12 lowering -remain open. +and evicted page decisions. `FractalSurfacePageRasterizer` now lowers resident +pages to CPU height, 2D signed-distance support, material, and confidence +sample payloads using the same shaped brush envelope math as the live brush +compiler. The real page store, atlas, and D3D12 lowering remain open. ### Phase F: 3D SDF Splat Backend diff --git a/research/rendering/fractal-brush-implementation-roadmap.md b/research/rendering/fractal-brush-implementation-roadmap.md index ca28cbe..92c9fa2 100644 --- a/research/rendering/fractal-brush-implementation-roadmap.md +++ b/research/rendering/fractal-brush-implementation-roadmap.md @@ -406,6 +406,8 @@ Tasks: page metadata. - [x] Add mockable surface page store boundary with resident/request/evict decisions under a byte budget. +- [x] Add CPU surface page rasterizer for resident height, 2D signed-distance, + material, and confidence pages. - [x] Add fake payload store with resident/missing states. - [x] Add child request queue. - [x] Add score/cost eviction policy. diff --git a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs b/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs index 9edf268..33d524a 100644 --- a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs +++ b/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs @@ -80,6 +80,12 @@ public readonly record struct FractalBrushEnvelope2D return NormalizedRadiusSquared(point) <= 1.0; } + public double SignedSupportDistanceEstimate(Vector2 point) + { + var normalizedRadius = Math.Sqrt(NormalizedRadiusSquared(point)); + return (normalizedRadius - 1.0) * Math.Min(RadiusX, RadiusY); + } + public FractalBrushEnvelopeBounds2D AxisAlignedBounds() { var cos = Math.Cos(RotationRadians); diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs new file mode 100644 index 0000000..103c139 --- /dev/null +++ b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs @@ -0,0 +1,20 @@ +namespace Aquarium.Engine.Fractal.Lod; + +public sealed class FractalSurfacePagePayload +{ + public FractalSurfacePagePayload(AquariumFractalSurfacePage page, float[] samples) + { + ArgumentNullException.ThrowIfNull(samples); + if (samples.Length != page.Width * page.Height) + { + throw new ArgumentException("Surface page sample count must match page dimensions.", nameof(samples)); + } + + Page = page; + Samples = samples; + } + + public AquariumFractalSurfacePage Page { get; } + + public float[] Samples { get; } +} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs new file mode 100644 index 0000000..3260921 --- /dev/null +++ b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs @@ -0,0 +1,157 @@ +using System.Numerics; +using Aquarium.Engine.Fractal.Brushes; +using Aquarium.Engine.Fractal.Grammar; + +namespace Aquarium.Engine.Fractal.Lod; + +public static class FractalSurfacePageRasterizer +{ + public static FractalSurfacePagePayload Rasterize(FractalOwnershipTree tree, AquariumFractalSurfacePage page) + { + ArgumentNullException.ThrowIfNull(tree); + if (page.Width <= 0 || page.Height <= 0) + { + throw new ArgumentOutOfRangeException(nameof(page), "Surface page dimensions must be positive."); + } + + var node = tree.Nodes.FirstOrDefault(candidate => candidate.Key == page.Key.NodeKey); + if (node.Key.Value is null) + { + throw new ArgumentException($"Surface page node {page.Key.NodeKey} does not exist in the ownership tree.", nameof(page)); + } + + var claims = ClaimsForNode(tree, node); + var samples = new float[page.Width * page.Height]; + for (var y = 0; y < page.Height; y++) + { + for (var x = 0; x < page.Width; x++) + { + var point = SamplePoint(page, x, y); + samples[(y * page.Width) + x] = Evaluate(page.Key.Kind, claims, point); + } + } + + return new FractalSurfacePagePayload(page, samples); + } + + private static AquariumBrushClaim[] ClaimsForNode(FractalOwnershipTree tree, AquariumFractalNode node) + { + if (node.ClaimCount <= 0) + { + return []; + } + + var claims = new AquariumBrushClaim[node.ClaimCount]; + for (var index = 0; index < node.ClaimCount; index++) + { + claims[index] = tree.Claims[node.FirstClaimIndex + index]; + } + + return claims; + } + + private static Vector2 SamplePoint(AquariumFractalSurfacePage page, int x, int y) + { + var u = page.Width == 1 ? 0.5f : x / (float)(page.Width - 1); + var v = page.Height == 1 ? 0.5f : y / (float)(page.Height - 1); + return new Vector2( + Lerp(page.BoundsMinMax.X, page.BoundsMinMax.Z, u), + Lerp(page.BoundsMinMax.Y, page.BoundsMinMax.W, v)); + } + + private static float Lerp(float a, float b, float t) + { + return a + ((b - a) * t); + } + + private static float Evaluate(AquariumFractalSurfacePageKind kind, IReadOnlyList claims, Vector2 point) + { + return kind switch + { + AquariumFractalSurfacePageKind.Height => EvaluateHeight(claims, point), + AquariumFractalSurfacePageKind.SignedDistance2D => EvaluateSignedDistance(claims, point), + AquariumFractalSurfacePageKind.Material => EvaluateMaterial(claims, point), + AquariumFractalSurfacePageKind.Confidence => EvaluateConfidence(claims, point), + _ => 0.0f, + }; + } + + private static float EvaluateHeight(IReadOnlyList claims, Vector2 point) + { + var value = 0.0; + foreach (var claim in claims) + { + value += Envelope(claim).Evaluate(point) * claim.Amplitude; + } + + return (float)value; + } + + private static float EvaluateSignedDistance(IReadOnlyList claims, Vector2 point) + { + if (claims.Count == 0) + { + return float.PositiveInfinity; + } + + var distance = double.PositiveInfinity; + foreach (var claim in claims) + { + distance = Math.Min(distance, Envelope(claim).SignedSupportDistanceEstimate(point)); + } + + return (float)distance; + } + + private static float EvaluateMaterial(IReadOnlyList claims, Vector2 point) + { + var weighted = 0.0; + var weightSum = 0.0; + foreach (var claim in claims) + { + var weight = Envelope(claim).Evaluate(point); + if (weight <= 0.0) + { + continue; + } + + weighted += weight * StableMaterialValue(claim); + weightSum += weight; + } + + return weightSum <= 0.0 ? 0.0f : (float)(weighted / weightSum); + } + + private static float EvaluateConfidence(IReadOnlyList claims, Vector2 point) + { + var confidence = 0.0; + foreach (var claim in claims) + { + confidence += Envelope(claim).Evaluate(point); + } + + return (float)Math.Clamp(confidence, 0.0, 1.0); + } + + private static double StableMaterialValue(AquariumBrushClaim claim) + { + var hash = (uint)claim.Seed * 747796405u; + foreach (var ch in claim.Tags) + { + hash = (hash * 16777619u) ^ ch; + } + + return (hash & 0xFFFFu) / 65535.0; + } + + private static FractalBrushEnvelope2D Envelope(AquariumBrushClaim claim) + { + return new FractalBrushEnvelope2D( + claim.Center, + claim.Radii.X, + claim.Radii.Y, + claim.RotationRadians, + claim.Falloff, + claim.ShapePower); + } +} diff --git a/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs b/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs index a3c976f..c644ace 100644 --- a/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs +++ b/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs @@ -22,6 +22,7 @@ public static class ZyphosFractalTerrain private static readonly FractalContributionCache ContributionCache = new(); private static readonly object PlanCacheLock = new(); private static readonly Dictionary BrushCache = []; + private static readonly Dictionary SurfacePagePayloadCache = []; private static readonly FractalResourceBudget DefaultBudget = new( MaxCpuUpdates: 2, MaxGpuEstimatedCost: 64.0f, @@ -76,6 +77,7 @@ public static class ZyphosFractalTerrain ResidentSurfacePageStore.Instance, MaxResidentSurfacePageBytes, MaxSurfacePageRequests); + var surfacePagePayloads = BuildSurfacePagePayloads(surfacePageResidency.ResidentPages); var cutKey = CutCacheKey(selectedCut); AquariumHeightFieldBrush[] brushes; lock (PlanCacheLock) @@ -94,8 +96,9 @@ public static class ZyphosFractalTerrain structuralProbeReservoir, surfacePages, surfacePageResidency, + surfacePagePayloads, bucketPixelsPerWorld, - $"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {resourcePlan.UpdateNodes.Length}/{DefaultBudget.MaxCpuUpdates} cpu updates / {resourcePlan.GpuEstimatedCost:0.0}/{DefaultBudget.MaxGpuEstimatedCost:0.0} gpu cost / {resourcePlan.Residency.ResidentNodes.Count}/{DefaultBudget.MaxResidentPayloads} resident / {resourcePlan.Residency.RequestedNodes.Count}/{DefaultBudget.MaxSsdRequests} ssd requests / {(structuralProbeReservoir.HasSample ? structuralProbeReservoir.CandidateCount : 0)} probe candidates / {surfacePageResidency.ResidentPages.Count}/{surfacePages.Length} surface pages / {bucketPixelsPerWorld:0.00} px-wu"); + $"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {resourcePlan.UpdateNodes.Length}/{DefaultBudget.MaxCpuUpdates} cpu updates / {resourcePlan.GpuEstimatedCost:0.0}/{DefaultBudget.MaxGpuEstimatedCost:0.0} gpu cost / {resourcePlan.Residency.ResidentNodes.Count}/{DefaultBudget.MaxResidentPayloads} resident / {resourcePlan.Residency.RequestedNodes.Count}/{DefaultBudget.MaxSsdRequests} ssd requests / {(structuralProbeReservoir.HasSample ? structuralProbeReservoir.CandidateCount : 0)} probe candidates / {surfacePagePayloads.Length}/{surfacePages.Length} surface payloads / {bucketPixelsPerWorld:0.00} px-wu"); } private static AquariumFractalSurfacePage[] PlanSurfacePages(IReadOnlyList selectedCut) @@ -111,6 +114,27 @@ public static class ZyphosFractalTerrain .ToArray(); } + private static FractalSurfacePagePayload[] BuildSurfacePagePayloads(IReadOnlyList residentPages) + { + var payloads = new FractalSurfacePagePayload[residentPages.Count]; + lock (PlanCacheLock) + { + for (var index = 0; index < residentPages.Count; index++) + { + var page = residentPages[index]; + if (!SurfacePagePayloadCache.TryGetValue(page.Key.Value, out var payload)) + { + payload = FractalSurfacePageRasterizer.Rasterize(Tree.Value, page); + SurfacePagePayloadCache[page.Key.Value] = payload; + } + + payloads[index] = payload; + } + } + + return payloads; + } + private static string CutCacheKey(IReadOnlyList selectedCut) { return string.Join("|", selectedCut.Select(cut => cut.NodeKey.Value)); @@ -148,6 +172,7 @@ public static class ZyphosFractalTerrain $" structuralProbeWeight: {plan.StructuralProbeReservoir.WeightSum:0.000} candidates={plan.StructuralProbeReservoir.CandidateCount} contributionWeight={plan.StructuralProbeReservoir.ContributionWeight:0.000}", $" surfacePages: {plan.SurfacePages.Length} {SurfacePageDimension}x{SurfacePageDimension}", $" surfacePageResident: {plan.SurfacePageResidency.ResidentPages.Count}/{plan.SurfacePages.Length} bytes={plan.SurfacePageResidency.ResidentBytes}/{MaxResidentSurfacePageBytes}", + $" surfacePagePayloads: {plan.SurfacePagePayloads.Length}", $" surfacePageRequests: {plan.SurfacePageResidency.RequestedPages.Count}/{MaxSurfacePageRequests}", $" surfacePageEvictions: {plan.SurfacePageResidency.EvictedPages.Count}", "selected:", @@ -210,5 +235,6 @@ public readonly record struct ZyphosFractalRenderPlan( FractalProbeReservoirSnapshot StructuralProbeReservoir, AquariumFractalSurfacePage[] SurfacePages, FractalSurfacePageResidencyPlan SurfacePageResidency, + FractalSurfacePagePayload[] SurfacePagePayloads, float PixelsPerWorld, string Summary); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 9a06498..68f3607 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -172,3 +172,4 @@ {"timestamp":"2026-05-19T22:31:00+01:00","topic":"fractal-surface-page-planner","lesson":"Phase E now has a CPU page-planning boundary. `FractalSurfacePagePlanner` lowers selected IFS cuts into stable height, 2D signed-distance, material, and confidence page metadata; `ZyphosFractalRenderPlan` carries those pages beside brushes, resource planning, and structural probe reservoirs. This proves page identity and inspection before adding a page store, eviction policy, D3D12 atlas, or GPU lowering.","files":["src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePlanner.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePagePlannerTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E CPU page planning"} {"timestamp":"2026-05-19T22:48:00+01:00","topic":"fractal-residency-eviction-policy","lesson":"Residency planning now has an explicit score-per-cost eviction decision. `FractalResidencyPlanner` can receive node summaries, retain resident payloads with the best contribution per estimated cost under RAM budget, place evicted residents on summary fallback, and report evicted node keys without mutating a real store. This keeps eviction testable until a page/payload store owns storage changes.","files":["src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase D/E residency pressure slice"} {"timestamp":"2026-05-19T23:10:00+01:00","topic":"fractal-surface-page-residency","lesson":"Surface page residency now has a separate mockable boundary from node payload residency. `IFractalSurfacePageStore` owns page-key resident/request/evict calls, and `FractalSurfacePageResidencyPlanner` turns planned pages into resident, missing, requested, evicted, and resident-byte rows using a max-error-per-byte heuristic. Zyphos carries this page residency plan for inspection before any real atlas or SSD-backed page store exists.","files":["src/Aquarium.Engine.Fractal/Lod/IFractalSurfacePageStore.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageResidencyPlannerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E page-store boundary slice"} +{"timestamp":"2026-05-19T23:35:00+01:00","topic":"fractal-surface-page-rasterizer","lesson":"Resident surface pages now produce CPU payloads instead of only metadata. `FractalSurfacePageRasterizer` lowers ownership-tree claims into height, 2D signed-distance support, material, and confidence sample arrays using `FractalBrushEnvelope2D`; Zyphos caches resident page payloads by stable page key. This gives Phase E a renderer-agnostic payload producer before D3D12 atlas/upload work begins.","files":["src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E CPU page payload slice"} diff --git a/state/map.yaml b/state/map.yaml index 1a724fd..6b26fd3 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -139,6 +139,7 @@ renderer_state: - The Perfect Machine architecture lives in docs/perfect-machine-architecture.md. It is the current waterfall design authority for fast 2D SDF splats, 3D SDF splats, 2D-projected-to-3D surface splats, IFS `.aquageo` structural probes, Mimir-style camera/audio evidence candidates, ReSTIR/GRIS reservoir reuse, heuristic occupancy graph updates, resource-tier residency, and TAA guide-buffer integration. - Fractal surface page planning now has a CPU boundary: FractalSurfacePagePlanner lowers selected IFS cuts into stable height, 2D signed-distance, material, and confidence page metadata; ZyphosFractalRenderPlan exposes these pages, while the live D3D12 page store and atlas remain future work. - Surface page residency has its own mockable store boundary: IFractalSurfacePageStore plus FractalSurfacePageResidencyPlanner produce resident, missing, requested, evicted, and byte-budget rows for planned pages without collapsing page cache policy into node payload residency. + - Resident surface pages can now be rasterized on CPU through FractalSurfacePageRasterizer into height, 2D signed-distance support, material, and confidence sample payloads using the same shaped brush envelope math as the brush compiler. Zyphos caches those payloads by page key; D3D12 upload remains future work. - The actionable fractal brush implementation roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md and is the execution authority for the first pass. - Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them. - D3D11 scene renderer, runtime volumetrics, cloud/fog research, medium/froxel render targets, and the SDF-field renderer plan are shelved and removed from live repo state. diff --git a/state/memory.json b/state/memory.json index 9484316..5b90fa0 100644 --- a/state/memory.json +++ b/state/memory.json @@ -103,6 +103,7 @@ "AquariumFractalSurfacePageKey and AquariumFractalSurfacePage are the renderer-agnostic page contracts for Phase E: height, SignedDistance2D, material, and confidence surface pages carry stable domain/node/kind/mip keys, bounds, dimensions, payload handles, and max error before any D3D12 page store exists.", "FractalSurfacePagePlanner lowers selected IFS cuts into stable surface page metadata without renderer dependencies. ZyphosFractalRenderPlan now exposes height, SignedDistance2D, material, and confidence pages beside brushes, resource plans, and structural probe reservoirs; the actual page store, eviction, atlas, and D3D12 lowering are still open.", "FractalSurfacePageResidencyPlanner is the renderer-agnostic page-store policy boundary: it asks IFractalSurfacePageStore about page-key residency, keeps best max-error-per-byte resident pages under a byte budget, requests highest-value missing pages, and reports evictions. Zyphos carries this page residency plan, but real storage and D3D12 atlas mutation remain future work.", + "FractalSurfacePageRasterizer lowers resident planned pages into CPU sample payloads using the shared FractalBrushEnvelope2D math: height sums amplitudes, SignedDistance2D uses a cheap signed support-distance estimate, material uses deterministic weighted claim tags/seeds, and confidence accumulates clamped envelope coverage. Zyphos caches resident page payloads by page key before any GPU atlas exists.", "The actionable fractal brush roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md. Start with the first work packet: add Aquarium.Engine.Fractal and tests, cube-face/tile key types, identity and tangent projection candidates, an area distortion sampler, face-edge tests, and a projection report before touching recursive detail." ], "text_and_ui": [ diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs index 819cb2f..1a4d9b7 100644 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs +++ b/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs @@ -24,6 +24,16 @@ public sealed class FractalBrushEnvelope2DTests Assert.False(envelope.Contains(new Vector2(1.5f, 0.0f))); } + [Fact] + public void SignedSupportDistanceIsNegativeInsideAndPositiveOutside() + { + var envelope = new FractalBrushEnvelope2D(Vector2.Zero, 2.0, 1.0, 0.0, falloff: 4.0); + + Assert.True(envelope.SignedSupportDistanceEstimate(Vector2.Zero) < 0.0); + Assert.Equal(0.0, envelope.SignedSupportDistanceEstimate(new Vector2(2.0f, 0.0f)), 12); + Assert.True(envelope.SignedSupportDistanceEstimate(new Vector2(3.0f, 0.0f)) > 0.0); + } + [Fact] public void RoundEnvelopeIsRotationInvariant() { diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs new file mode 100644 index 0000000..87698a4 --- /dev/null +++ b/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs @@ -0,0 +1,101 @@ +using System.Numerics; +using Aquarium.Engine.Fractal; +using Aquarium.Engine.Fractal.Grammar; +using Aquarium.Engine.Fractal.Lod; + +namespace Aquarium.Engine.Fractal.Tests; + +public sealed class FractalSurfacePageRasterizerTests +{ + [Fact] + public void RasterizerLowersHeightPageFromShapedBrushClaims() + { + var domainKey = new AquariumFractalKey("domain/tile"); + var rootKey = new AquariumFractalKey("domain/tile/root"); + var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 2.0f)); + var page = Page(domainKey, rootKey, AquariumFractalSurfacePageKind.Height, width: 3, height: 3); + + var payload = FractalSurfacePageRasterizer.Rasterize(tree, page); + + Assert.Equal(0.0f, payload.Samples[0]); + Assert.Equal(2.0f, payload.Samples[4], 5); + } + + [Fact] + public void RasterizerLowersSignedDistancePageFromBrushSupport() + { + var domainKey = new AquariumFractalKey("domain/tile"); + var rootKey = new AquariumFractalKey("domain/tile/root"); + var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 1.0f)); + var page = Page(domainKey, rootKey, AquariumFractalSurfacePageKind.SignedDistance2D, width: 3, height: 3); + + var payload = FractalSurfacePageRasterizer.Rasterize(tree, page); + + Assert.True(payload.Samples[4] < 0.0f); + Assert.Equal(0.0f, payload.Samples[1], 5); + } + + [Fact] + public void RasterizerLowersConfidencePageFromEnvelopeCoverage() + { + var domainKey = new AquariumFractalKey("domain/tile"); + var rootKey = new AquariumFractalKey("domain/tile/root"); + var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 1.0f)); + var page = Page(domainKey, rootKey, AquariumFractalSurfacePageKind.Confidence, width: 3, height: 3); + + var payload = FractalSurfacePageRasterizer.Rasterize(tree, page); + + Assert.Equal(1.0f, payload.Samples[4], 5); + Assert.Equal(0.0f, payload.Samples[0]); + } + + [Fact] + public void RasterizerRejectsUnknownPageNode() + { + var domainKey = new AquariumFractalKey("domain/tile"); + var rootKey = new AquariumFractalKey("domain/tile/root"); + var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 1.0f)); + var page = Page(domainKey, new AquariumFractalKey("domain/tile/missing"), AquariumFractalSurfacePageKind.Height, width: 3, height: 3); + + Assert.Throws(() => FractalSurfacePageRasterizer.Rasterize(tree, page)); + } + + private static FractalOwnershipTree Tree(AquariumFractalKey domainKey, AquariumFractalKey rootKey, AquariumBrushClaim claim) + { + var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); + return FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [claim]); + } + + private static AquariumBrushClaim Claim(string key, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, float amplitude) + { + return new AquariumBrushClaim( + new AquariumFractalKey(key), + domainKey, + nodeKey, + AquariumFractalPayloadKind.Height, + Vector2.Zero, + Vector2.One, + RotationRadians: 0.0f, + Falloff: 4.0f, + ShapePower: 1.0f, + Amplitude: amplitude, + Seed: 13, + Tags: "raster"); + } + + private static AquariumFractalSurfacePage Page( + AquariumFractalKey domainKey, + AquariumFractalKey nodeKey, + AquariumFractalSurfacePageKind kind, + int width, + int height) + { + return new AquariumFractalSurfacePage( + new AquariumFractalSurfacePageKey(domainKey, nodeKey, kind, mipLevel: 0), + new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), + width, + height, + PayloadHandle: 0, + MaxError: 1.0f); + } +} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs index 321e807..2f7fef4 100644 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs +++ b/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs @@ -53,7 +53,7 @@ public sealed class ZyphosFractalTerrainTests Assert.Contains("gpu cost", near.Summary, StringComparison.Ordinal); Assert.Contains("resident", near.Summary, StringComparison.Ordinal); Assert.Contains("probe candidates", near.Summary, StringComparison.Ordinal); - Assert.Contains("surface pages", near.Summary, StringComparison.Ordinal); + Assert.Contains("surface payloads", near.Summary, StringComparison.Ordinal); Assert.True(near.StructuralProbeReservoir.HasSample); Assert.True(near.StructuralProbeReservoir.CandidateCount > 0); Assert.True(near.StructuralProbeReservoir.WeightSum > 0.0f); @@ -62,6 +62,8 @@ public sealed class ZyphosFractalTerrainTests Assert.True(near.SurfacePageResidency.ResidentPages.Count <= near.SurfacePages.Length); Assert.True(near.SurfacePageResidency.ResidentBytes <= 2L * 1024L * 1024L); Assert.True(near.SurfacePageResidency.RequestedPages.Count <= 8); + Assert.Equal(near.SurfacePageResidency.ResidentPages.Count, near.SurfacePagePayloads.Length); + Assert.All(near.SurfacePagePayloads, payload => Assert.Equal(payload.Page.Width * payload.Page.Height, payload.Samples.Length)); Assert.All(near.SurfacePages, page => { Assert.Equal(128, page.Width); @@ -89,6 +91,7 @@ public sealed class ZyphosFractalTerrainTests Assert.Contains("structuralProbeWeight:", dump, StringComparison.Ordinal); Assert.Contains("surfacePages:", dump, StringComparison.Ordinal); Assert.Contains("surfacePageResident:", dump, StringComparison.Ordinal); + Assert.Contains("surfacePagePayloads:", dump, StringComparison.Ordinal); Assert.Contains("surfacePageRequests:", dump, StringComparison.Ordinal); Assert.Contains("surfacePageEvictions:", dump, StringComparison.Ordinal); Assert.Contains("selected:", dump, StringComparison.Ordinal);