Make fractal contribution cache live

This commit is contained in:
Meta Vens 2026-05-19 13:51:56 +01:00
commit 4174457fe7
6 changed files with 164 additions and 43 deletions

View file

@ -310,6 +310,8 @@ Tasks:
- [x] Add estimator state: mean, variance/uncertainty, confidence, sample count, sample age.
- [x] Add stochastic scheduler with deterministic random source.
- [x] Add exploration budget.
- [x] Add live contribution cache that observes only scheduled nodes each frame
and feeds the next resource plan.
- [ ] Add confidence decay and stale uncertainty growth.
- [ ] Add fake contribution probe.
- [ ] Add convergence telemetry.
@ -374,6 +376,8 @@ Tasks:
- [x] Feed planet shader from tile-local cube-face domains for post-hit
material/detail evaluation.
- [x] Route Zyphos render-plan construction through the resource budget planner.
- [x] Update Zyphos contribution cache every render-plan request while reusing
compiled brush packets for equivalent selected cuts.
- [ ] Feed traced planet geometry from selected-cut/resident tile packets.
- [ ] Add face/tile/LOD/cache debug modes.
- [ ] Remove or quarantine old spherical noise path as baseline fixture.

View file

@ -0,0 +1,62 @@
using Aquarium.Engine.Fractal;
namespace Aquarium.Engine.Fractal.Lod;
public sealed class FractalContributionCache
{
private readonly FractalContributionTable table = new();
private uint frameIndex;
public FractalResourcePlan PlanFrame(
IReadOnlyList<AquariumFractalSummary> summaries,
Func<AquariumFractalSummary, float> projectedPixelsPerWorldUnit,
FractalResourceBudget budget,
IFractalRandom random,
IFractalPayloadStore payloadStore)
{
ArgumentNullException.ThrowIfNull(summaries);
ArgumentNullException.ThrowIfNull(projectedPixelsPerWorldUnit);
ArgumentNullException.ThrowIfNull(random);
ArgumentNullException.ThrowIfNull(payloadStore);
frameIndex++;
var states = new AquariumContributionState[summaries.Count];
var scores = new Dictionary<string, float>(StringComparer.Ordinal);
for (var index = 0; index < summaries.Count; index++)
{
var summary = summaries[index];
states[index] = table.GetOrCreate(summary.NodeKey);
scores[summary.NodeKey.Value] = FractalProjectedErrorScorer.Score(summary, projectedPixelsPerWorldUnit(summary));
}
var plan = FractalResourceBudgetPlanner.Plan(
summaries,
states,
projectedPixelsPerWorldUnit,
state => scores.TryGetValue(state.NodeKey.Value, out var score) ? score : 0.0f,
budget,
random,
payloadStore,
frameIndex);
var resident = plan.Residency.ResidentNodes.Select(key => key.Value).ToHashSet(StringComparer.Ordinal);
foreach (var nodeKey in plan.UpdateNodes)
{
if (!scores.TryGetValue(nodeKey.Value, out var observedScore))
{
continue;
}
var state = table.GetOrCreate(nodeKey);
table.Store(FractalContributionEstimator.Observe(state, observedScore, frameIndex, resident.Contains(nodeKey.Value)));
}
return plan;
}
public bool TryGet(AquariumFractalKey nodeKey, out AquariumContributionState state)
{
return table.TryGet(nodeKey, out state);
}
}

View file

@ -14,18 +14,11 @@ public static class ZyphosFractalTerrain
private static readonly Lazy<string> PatchSource = new(() => File.ReadAllText(PatchPath));
private static readonly Lazy<FractalOwnershipTree> Tree = new(() => FractalDslCompiler.Compile(PatchSource.Value));
private static readonly Lazy<AquariumFractalSummary[]> Summaries = new(() => FractalSummaryBuilder.Build(Tree.Value));
private static readonly Lazy<AquariumContributionState[]> ContributionStates = new(() => Summaries.Value.Select(summary => new AquariumContributionState(
summary.NodeKey,
MeanContribution: 0.0f,
Variance: MathF.Max(summary.MaxHeightError, 0.001f),
Confidence: 0.0f,
SampleCount: 0,
LastSampledFrame: 0,
Resident: true)).ToArray());
private static readonly Lazy<AquariumSelectedCut[]> SelectedCut = new(() => FractalSelectedCutBuilder.Build(Summaries.Value, _ => 8.0f, maxEstimatedCost: 64.0f));
private static readonly Lazy<AquariumHeightFieldBrush[]> Brushes = new(() => FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, SelectedCut.Value));
private static readonly FractalContributionCache ContributionCache = new();
private static readonly object PlanCacheLock = new();
private static readonly Dictionary<int, ZyphosFractalRenderPlan> PlanCache = [];
private static readonly Dictionary<string, AquariumHeightFieldBrush[]> BrushCache = [];
private static readonly FractalResourceBudget DefaultBudget = new(
MaxCpuUpdates: 2,
MaxGpuEstimatedCost: 64.0f,
@ -48,39 +41,41 @@ public static class ZyphosFractalTerrain
{
var pixelsPerWorld = Math.Clamp(72.0f / MathF.Max(shot.EffectiveDistance, 0.001f), 0.25f, 48.0f);
var bucket = (int)Math.Clamp(MathF.Round(pixelsPerWorld * 16.0f), 4.0f, 768.0f);
var bucketPixelsPerWorld = bucket / 16.0f;
FractalResourcePlan resourcePlan;
lock (PlanCacheLock)
{
if (PlanCache.TryGetValue(bucket, out var cached))
resourcePlan = ContributionCache.PlanFrame(
Summaries.Value,
_ => bucketPixelsPerWorld,
DefaultBudget,
new FractalXorShiftRandom((uint)bucket ^ 0x9E3779B9u),
ResidentFractalPayloadStore.Instance);
}
var selectedCut = resourcePlan.SelectedCut;
var cutKey = CutCacheKey(selectedCut);
AquariumHeightFieldBrush[] brushes;
lock (PlanCacheLock)
{
if (!BrushCache.TryGetValue(cutKey, out brushes!))
{
return cached;
brushes = FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, selectedCut);
BrushCache[cutKey] = brushes;
}
}
var bucketPixelsPerWorld = bucket / 16.0f;
var resourcePlan = FractalResourceBudgetPlanner.Plan(
Summaries.Value,
ContributionStates.Value,
_ => bucketPixelsPerWorld,
state => ScoreForState(state, bucketPixelsPerWorld),
DefaultBudget,
new FractalXorShiftRandom((uint)bucket ^ 0x9E3779B9u),
ResidentFractalPayloadStore.Instance,
frameIndex: (uint)bucket);
var selectedCut = resourcePlan.SelectedCut;
var brushes = FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, selectedCut);
var plan = new ZyphosFractalRenderPlan(
return new ZyphosFractalRenderPlan(
brushes,
selectedCut,
resourcePlan,
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 / {bucketPixelsPerWorld:0.00} px-wu");
}
lock (PlanCacheLock)
{
PlanCache[bucket] = plan;
}
return plan;
private static string CutCacheKey(IReadOnlyList<AquariumSelectedCut> selectedCut)
{
return string.Join("|", selectedCut.Select(cut => cut.NodeKey.Value));
}
public static string Summary =>
@ -119,19 +114,6 @@ public static class ZyphosFractalTerrain
return string.Join(Environment.NewLine, lines);
}
private static float ScoreForState(AquariumContributionState state, float pixelsPerWorld)
{
foreach (var summary in Summaries.Value)
{
if (summary.NodeKey == state.NodeKey)
{
return FractalProjectedErrorScorer.Score(summary, pixelsPerWorld);
}
}
return 0.0f;
}
private sealed class ResidentFractalPayloadStore : IFractalPayloadStore
{
public static ResidentFractalPayloadStore Instance { get; } = new();

View file

@ -152,3 +152,4 @@
{"timestamp":"2026-05-19T13:38:00+01:00","topic":"fractal-resource-budget-and-flame-dsl","lesson":"The fractal DSL now has a compact `flame` primitive for deterministic curled recursive brush emission, and Zyphos exercises it in a leaf microdetail domain without exceeding the 64-brush stress table. Fractal render planning now coordinates CPU stochastic update count, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request budget before packet compilation. This budget vocabulary should remain compatible with Mimir-style sensor fusion because both pipelines accumulate confidence-weighted spatial samples into temporal reservoirs before rendering a resolved field.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudget.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","tests/Aquarium.Engine.Fractal.Tests/FractalResourceBudgetPlannerTests.cs"],"source":"user demanded full fractal SDF rendering and noted Mimir sensor fusion shares the same temporal spatial evidence shape"}
{"timestamp":"2026-05-19T14:04:00+01:00","topic":"temporal-spatial-evidence-reservoir","lesson":"Temporal Gaussian accumulation now uses `TemporalSpatialEvidenceReservoir`, which owns stable-keyed spatial tracks, smoothing, delayed presentation, velocity prediction, confidence-weighted history, expiry, and max-track eviction. This pulls the common reservoir shape out from under Gaussian rendering so fractal SDF probes and Mimir sensor-fusion features can converge through the same evidence machinery before backend lowering.","files":["src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceObservation.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs","tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceReservoirTests.cs","docs/temporal-sdf-gaussian-field.md"],"source":"user pointed out fractal rendering and Mimir sensor fusion both accumulate surface/volume confidence into temporal reservoirs"}
{"timestamp":"2026-05-19T14:20:00+01:00","topic":"zyphos-fractal-resource-observability","lesson":"Zyphos exposes `zyphos-fractal-plan`, a command-level dump of the current fractal selected cut and resource plan. Keep this kind of budget/cut observability alongside renderer work: pixels alone are not enough to validate stochastic LOD, residency, or cache behavior.","files":["src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"third implementation slice after adding resource planning; the machine needs to explain itself without screenshot divination"}
{"timestamp":"2026-05-19T14:43:00+01:00","topic":"fractal-contribution-cache-live-loop","lesson":"Fractal contribution planning now has a live cache loop. `FractalContributionCache` builds a resource plan from current summaries and cached states, stochastically observes only budgeted update nodes, updates estimator confidence, and lets Zyphos reuse compiled brush packets by selected-cut key instead of freezing the whole render plan by camera bucket. Static plan caches are not acceptable for stochastic LOD because they stop learning.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs"],"source":"follow-up after resource observability revealed the old bucket plan cache prevented continual cache updates"}

View file

@ -85,6 +85,7 @@
"The `.aquageo` compiler must preserve each tile declaration as its own ownership-tree node. Collapsing every claim under the final tile makes the authored multi-domain world a lie even if the brush count looks impressive.",
"Zyphos passes cube-tile domain metadata through height brush packets and binds those packets into the SDF pass. The planet shader may use authored brush packets for post-hit material/detail evaluation; traced geometry must wait for selected-cut/resident packet policy so SDF distance loops do not evaluate every brush at every step.",
"Temporal resolve has a cache-facing detail lane: SdfSurface.temporalDetail writes through scene-control.z into history-control.z, and D3D12Post reduces history confidence when current and previous temporal detail disagree. Use this lane for stochastic fractal/cache stability signals, not as geometry authority.",
"FractalContributionCache is the live cache loop: each frame builds a resource plan from current summaries and cached states, stochastically observes only budgeted update nodes, stores mean/variance/confidence/sample age through FractalContributionEstimator, and lets backend packet compilation stay cached by selected-cut key. Do not replace this with a static plan cache that stops learning after the first camera bucket.",
"Zyphos camera distance limits belong to the selected spatial domain, not one global planetary clamp. Leaf/pebble domains must be able to zoom below whole-body distances, and the parent star must be a visible SDF body when it is also the primary light source.",
"The consolidated fractal brush architecture lives in research/rendering/fractal-brush-architecture-plan.md. Its pipeline is client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence. Its credibility depends on module boundaries and tests: contracts, pure CPU fractal core, D3D12 backend, client adapters, mock payload/probe/random/clock seams, shader parity tests, and deterministic performance fixtures.",
"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."

View file

@ -0,0 +1,71 @@
using System.Numerics;
using Aquarium.Engine.Fractal;
using Aquarium.Engine.Fractal.Lod;
namespace Aquarium.Engine.Fractal.Tests;
public sealed class FractalContributionCacheTests
{
[Fact]
public void CacheUpdatesOnlyBudgetedNodesEachFrame()
{
var cache = new FractalContributionCache();
var summaries = new[]
{
Summary("node/a", maxHeightError: 2.0f),
Summary("node/b", maxHeightError: 1.0f),
Summary("node/c", maxHeightError: 0.5f),
};
var plan = cache.PlanFrame(
summaries,
_ => 4.0f,
new FractalResourceBudget(MaxCpuUpdates: 1, MaxGpuEstimatedCost: 8.0f, MaxResidentPayloads: 8, MaxSsdRequests: 0),
new TestFractalRandom(0.01, 0.01, 0.01),
new ResidentStore());
Assert.Single(plan.UpdateNodes);
Assert.True(cache.TryGet(plan.UpdateNodes[0], out var updated));
Assert.Equal(1, updated.SampleCount);
Assert.True(updated.Confidence > 0.0f);
}
[Fact]
public void CacheConfidenceConvergesAcrossRepeatedFrames()
{
var cache = new FractalContributionCache();
var summary = Summary("node/a", maxHeightError: 2.0f);
var budget = new FractalResourceBudget(MaxCpuUpdates: 1, MaxGpuEstimatedCost: 4.0f, MaxResidentPayloads: 4, MaxSsdRequests: 0);
cache.PlanFrame([summary], _ => 4.0f, budget, new TestFractalRandom(0.01), new ResidentStore());
cache.PlanFrame([summary], _ => 4.0f, budget, new TestFractalRandom(0.01), new ResidentStore());
Assert.True(cache.TryGet(summary.NodeKey, out var state));
Assert.Equal(2, state.SampleCount);
Assert.True(state.Confidence > 0.1f);
Assert.True(state.Resident);
}
private static AquariumFractalSummary Summary(string key, float maxHeightError)
{
return new AquariumFractalSummary(
new AquariumFractalKey(key),
Vector4.Zero,
maxHeightError,
MaxMaterialDelta: 0.0f,
EstimatedCost: 1.0f,
DescendantCount: 1);
}
private sealed class ResidentStore : IFractalPayloadStore
{
public bool IsResident(AquariumFractalKey nodeKey)
{
return true;
}
public void Request(AquariumFractalKey nodeKey)
{
}
}
}