diff --git a/docs/temporal-spatial-evidence-reservoir.md b/docs/temporal-spatial-evidence-reservoir.md index ecb405d..01191b0 100644 --- a/docs/temporal-spatial-evidence-reservoir.md +++ b/docs/temporal-spatial-evidence-reservoir.md @@ -2,40 +2,83 @@ ## Objective -Aquarium owns resolved temporal spatial evidence. Producers may capture raw -camera frames, audio blocks, point claims, SDF probes, or calibration events, but -the shared stable-key history, delayed presentation, smoothing, confidence -weighting, expiry, and backend lowering belong to the Aquarium reservoir stack. +Aquarium owns the shared temporal evidence machine for two customers: -This serves both current customers: +- fractal rendering, where SDF/detail/path candidates need bounded reuse across + pixels, frames, and nested domains; +- Mimir/LocalCast sensor fusion, where camera and microphone features need a + delayed coherence window before the resolved field is rendered. -- fractal rendering: SDF probes and selected-cut packets need bounded, - confidence-weighted detail that converges while the camera moves; -- Mimir/LocalCast sensor fusion: cameras and microphones need a delayed - coherence window before the resolved field is rendered. +The old stable-key accumulator was useful, but it was not ReSTIR. The live +architecture now splits the problem into a small resampled-importance core, a +spatial evidence track layer, typed lowerings, renderer passes, and TAA history. -## Pipeline +## Research Spine + +- NVIDIA ReSTIR DI repeatedly resamples candidate light samples, then applies + spatial and temporal resampling to share useful samples across nearby pixels + and frames. The paper reports equal-error speedups of 6-60x, with biased + variants reaching 35-65x in its tested direct-lighting workloads. + Source: https://research.nvidia.com/labs/rtr/publication/bitterli2020spatiotemporal/ +- ReSTIR GI applies the same screen-space spatiotemporal reuse idea to + multi-bounce indirect paths and reports 9.3x-166x MSE improvement at one + sample per pixel in tested scenes. + Source: https://research.nvidia.com/publication/2021-06_restir-gi-path-resampling-real-time-path-tracing +- GRIS generalizes RIS/ReSTIR to correlated samples, unknown PDFs, varied + domains, and shift mappings. That is the important part for Aquarium: + fractal domains and sensor-fusion samples are not all light samples. + Source: https://research.nvidia.com/labs/rtr/publication/lin2022generalized/ +- RTXDI's integration docs make the pass boundary concrete: acquire initial + samples, store reservoir data, validate temporal reuse through reprojection, + validate spatial reuse against nearby surfaces, shift candidate paths between + domains, then shade/denoise from the final reservoir. + Sources: + https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirGI.md + https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirPT.md + +## Pipeline Map ```text -raw producer samples --> typed producer adapter --> TemporalSpatialEvidenceObservation --> TemporalSpatialEvidenceReservoir --> TemporalSpatialEvidenceSample snapshot +producer observations +-> candidate generator +-> target evaluator +-> ResampledImportanceReservoir +-> temporal reuse pass +-> spatial/domain reuse pass +-> validation + shift mapping +-> TemporalSpatialEvidenceReservoir track layer when stable fields are needed -> TemporalSpatialEvidenceLowering -> backend packet stream --> D3D12 render/fusion/TAA +-> renderer/fusion passes +-> TAA guide/history buffers ``` ## Ownership -Raw sample reservoirs own capture-time retention only. LocalCastBridge's native -rolling reservoir is allowed to keep time-ordered camera/audio/sample handles, -typed views, latest-for-sensor lookup, and provenance filtering. It must not own -resolved spatial confidence, smoothed motion, render packet lowering, or TAA -history. +`ResampledImportanceReservoir` owns RIS/ReSTIR-style candidate math: -`TemporalSpatialEvidenceReservoir` owns stable spatial tracks: +- one selected representative sample; +- summed importance weight of accepted candidates; +- number of source candidates represented by the reservoir; +- selected sample target value; +- final contribution weight `weightSum / (candidateCount * selectedTarget)`. + +Candidate generators own proposal distributions. A fractal renderer may propose +SDF probe candidates from projected error, node bounds, blue-noise screen tiles, +or resident children. Mimir may propose visual/audio feature candidates from +sensor confidence and calibration state. The reservoir does not know these +domains; it only receives target and source-PDF values. + +Reuse passes own validity and shift mapping. A sample may be reused only when +the target domain can explain it. For pixels this means depth/normal/material +compatibility, motion vectors, conservative visibility, and disocclusion tests. +For fractal domains it means matching domain ancestry, bounded local-frame +error, resident payload compatibility, and conservative SDF bounds. For sensor +fusion it means time delay, calibration confidence, modality agreement, and +feature reprojection error. + +`TemporalSpatialEvidenceReservoir` owns stable resolved spatial tracks after +candidate selection when the output is a field with persistent identity: - stable key identity; - accumulation window and presentation delay; @@ -45,52 +88,77 @@ history. - expiry; - max-track eviction by confidence and age. -`TemporalSpatialEvidenceLowering` owns packet conversions. Current lowerings: +`TemporalSpatialEvidenceLowering` owns packet conversion. Consumers do not pack +payload vectors by private convention when a lowering helper exists. -- `TemporalGaussianObservation` -> evidence observation; -- evidence sample -> `AquariumTemporalSdfGaussian`; -- `AquariumGpuFusionSeed` -> evidence observation; -- evidence sample -> `AquariumGpuFusionSeed`. - -Adapters own domain-specific interpretation before the reservoir. For example, -LocalCast may decide how a visual point maps to radii, color, falloff, and -shape power, but it then hands the result to the shared lowering path. - -Renderer passes own backend packet layout and GPU execution. TAA owns pixel -history validation, not producer identity or stable-key accumulation. +TAA owns pixel history validation and temporal guide buffers. It may consume +reservoir confidence, sample age, domain id, motion, and temporal-detail lanes, +but it does not own producer identity or stable spatial evidence. ## Invariants -- Stable-key spatial history has one owner: `TemporalSpatialEvidenceReservoir`. -- Consumers do not privately implement track dictionaries, smoothing, expiry, or - max-count eviction for resolved spatial evidence. -- Payload vectors are not ad hoc folklore. If a backend needs packed payload - fields, add or use a named lowering helper. -- Raw retention and resolved evidence are separate layers. Do not collapse - LocalCastBridge's raw rolling reservoir into Aquarium's resolved evidence - reservoir. -- Conservative bounds remain safety authority. Learned scoring or stochastic - sampling may prioritize work, but it must not replace bounds used for render - correctness. +- Reservoir math is a pure, testable core before it becomes HLSL. +- A reservoir is not a dictionary of tracks. A track layer may use reservoirs, + but it does not replace candidate resampling. +- Reuse is invalid until a pass proves the shift/validation contract for the + source and target domains. +- Conservative bounds remain the safety authority. Learned or stochastic + priority may decide what to refresh first; it must not replace SDF bounds, + visibility bounds, or calibration bounds. +- CPU, GPU, RAM, and SSD budgets are inputs to candidate generation and + residency. They are not hidden side effects of renderer convenience code. +- Consumer repos do not grow parallel stable-key temporal caches. -## Current Consumers +## Current State -`TemporalGaussianAccumulator` is a compatibility facade. It maps Gaussian -observations through `TemporalSpatialEvidenceLowering`, stores them in the -shared reservoir, and lowers snapshots back to `AquariumTemporalSdfGaussian`. +Built: -`LocalCastGpuFusionAccumulator` is also a facade. It maps LocalCast fallback -GPU fusion seeds into shared evidence observations and lowers snapshots back to -`AquariumGpuFusionSeed`. +- `ResampledImportanceCandidate` stores a sample, target value, source + PDF, and represented candidate count. +- `ResampledImportanceReservoir` accepts candidates by weight + proportional to `target / sourcePdf`, merges reservoirs, preserves represented + candidate count, and exposes the RIS contribution weight. +- `TemporalSpatialEvidenceReservoir` remains the stable track layer used by + temporal Gaussian fields and LocalCast fallback GPU fusion. +- `FractalContributionCache` remains the node-summary LOD estimator. It should + become a candidate generator feeding the resampling core rather than a + separate claim to temporal-reservoir theory. -`FractalContributionCache` is adjacent, not yet unified: it owns selected-cut -contribution estimates for authored fractal nodes. Future SDF probe evidence -should enter the shared reservoir when probe results become spatial samples; -node-summary scoring remains a separate LOD planning authority. +Not built yet: + +- GPU reservoir buffers; +- temporal reprojection validation for fractal/SDF reservoirs; +- spatial neighbor reuse for fractal/SDF reservoirs; +- GRIS-style domain shift mappings for nested `.aquageo` domains; +- TAA guide-buffer weaving of reservoir confidence, age, and domain validity; +- SSD/RAM residency queues driven by reservoir contribution estimates. + +## Implementation Roadmap + +1. Keep the CPU reservoir core pure and exhaustive under unit tests. +2. Add typed reservoir samples for fractal SDF probes: domain key, local frame, + bound radius, target contribution, source PDF, payload handle, and material + delta. +3. Turn `FractalContributionCache` into a candidate generator that refreshes + nodes under CPU budget and submits candidates to the reservoir core. +4. Add temporal reuse for fractal probes using camera motion, domain ancestry, + local-frame error, and conservative bounds. +5. Add spatial reuse across screen tiles and quadtree neighbors. +6. Lower selected reservoirs into GPU brush/SDF packets and expose debug views + for weight sum, selected target, candidate count, confidence, age, and + invalidation reason. +7. Weave reservoir confidence and temporal detail into TAA guide buffers so the + history filter can distinguish stable reused evidence from fresh stochastic + noise. +8. Add Mimir-facing candidate adapters only after the fractal path proves the + contract: modality features are candidates, not a second reservoir system. +9. Port the pure core to HLSL and add CPU/GPU parity fixtures. +10. Add residency scheduling: hot selected reservoirs keep GPU packets resident, + warm reservoirs keep RAM payloads, cold reservoirs fall to SSD handles. ## Cut Line -Do not build a second temporal spatial evidence cache in a client repo. If a -consumer needs different sample semantics, add a producer adapter and a named -lowering helper. If it needs different retention semantics, extend the shared -reservoir only after stating the invariant the new behavior protects. +If a new subsystem stores temporal candidates, it must state whether it owns raw +producer retention, resampled candidate selection, stable resolved tracks, +packet lowering, or TAA history. If it cannot name that authority, it is not an +architecture. It is a decorative leak. diff --git a/research/rendering/fractal-brush-implementation-roadmap.md b/research/rendering/fractal-brush-implementation-roadmap.md index 3a82cea..e8a21ac 100644 --- a/research/rendering/fractal-brush-implementation-roadmap.md +++ b/research/rendering/fractal-brush-implementation-roadmap.md @@ -303,36 +303,78 @@ Cut line: ## Phase 6: Probabilistic Online Updates -Goal: refresh contribution estimates under budget and converge. +Goal: refresh contribution estimates under budget and converge without +pretending an online smoother is ReSTIR. + +Research authority: + +- ReSTIR DI: candidate generation plus temporal and spatial reservoir reuse for + real-time direct lighting. + https://research.nvidia.com/labs/rtr/publication/bitterli2020spatiotemporal/ +- ReSTIR GI: path reservoirs for indirect lighting, with final shading fed by a + selected reservoir sample. + https://research.nvidia.com/publication/2021-06_restir-gi-path-resampling-real-time-path-tracing +- GRIS: the generalized theory for correlated samples, unknown PDFs, varied + domains, and shift mappings. This is the fractal/SDF/sensor-fusion door. + https://research.nvidia.com/labs/rtr/publication/lin2022generalized/ +- RTXDI integration docs: initial sampling, temporal reprojection, spatial + reuse, validation, shift mapping, reservoir buffers, and denoiser guide + buffers. + https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirGI.md + https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirPT.md Tasks: +- [x] Add pure `ResampledImportanceReservoir` core with selected + sample, target, weight sum, represented candidate count, merge, and + contribution weight. - [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. +- [ ] Convert contribution-cache refresh into a candidate generator that submits + weighted candidates to the resampled-importance core. +- [ ] Add fractal SDF probe candidate records: domain key, local frame, bound, + projected contribution target, source PDF, payload handle, and material delta. +- [ ] Add temporal reuse validation: camera motion, domain ancestry, local-frame + error, bounds, and disocclusion/material compatibility. +- [ ] Add spatial reuse validation across screen tiles and cube-sphere neighbor + domains. +- [ ] Feed reservoir confidence, selected target, candidate count, sample age, + and invalidation reason into TAA guide/history buffers. - [ ] Add confidence decay and stale uncertainty growth. - [ ] Add fake contribution probe. - [ ] Add convergence telemetry. -- [ ] Add debug channels: uncertainty, sample age, update probability. +- [ ] Add debug channels: uncertainty, sample age, update probability, + reservoir weight sum, selected target, candidate count, reuse validity. Tests: +- [x] reservoir accepts candidates proportional to target/source PDF; +- [x] reservoir merge preserves represented candidate count and weight sum; +- [x] invalid zero-weight candidates do not corrupt reservoir state; - deterministic RNG fixture repeats schedule; - visible nodes keep nonzero update probability; - near-threshold nodes keep nonzero update probability; - stale wrong score recovers after observations; - fixed camera path converges within tolerance; +- temporal reuse rejects mismatched domain ancestry; +- spatial reuse rejects invalid local-frame shifts; +- TAA history confidence drops when reservoir validity changes; - update cost respects budget. Exit gate: -- cache updates only a bounded subset per frame while selected cuts converge. +- cache updates only a bounded subset per frame while selected cuts converge, + and the selected detail path is driven by tested reservoir math rather than a + frozen score table. Cut line: -- No neural predictor until this estimator fails with captured telemetry. +- No neural predictor until the ReSTIR/GRIS-shaped reservoir pipeline fails + with captured telemetry. No consumer-owned temporal cache unless it clearly + owns raw capture retention rather than resolved evidence. ## Phase 7: Residency Simulation diff --git a/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs b/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs new file mode 100644 index 0000000..7e9d2e5 --- /dev/null +++ b/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs @@ -0,0 +1,21 @@ +namespace Aquarium.Engine.Fractal.Temporal; + +public readonly record struct ResampledImportanceCandidate( + TSample Sample, + float Target, + float SourcePdf, + int CandidateCount = 1) +{ + public float ImportanceWeight + { + get + { + if (!float.IsFinite(Target) || !float.IsFinite(SourcePdf) || Target <= 0.0f || SourcePdf <= 0.0f) + { + return 0.0f; + } + + return Target / SourcePdf; + } + } +} diff --git a/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs b/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs new file mode 100644 index 0000000..4d9bc08 --- /dev/null +++ b/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs @@ -0,0 +1,110 @@ +namespace Aquarium.Engine.Fractal.Temporal; + +public sealed class ResampledImportanceReservoir +{ + private const float Epsilon = 1.0e-8f; + + private TSample selectedSample = default!; + + public bool HasSample { get; private set; } + + public TSample SelectedSample + { + get + { + if (!HasSample) + { + throw new InvalidOperationException("The reservoir does not contain a selected sample."); + } + + return selectedSample; + } + } + + public float SelectedTarget { get; private set; } + + public float WeightSum { get; private set; } + + public int CandidateCount { get; private set; } + + public float ContributionWeight + { + get + { + if (!HasSample || CandidateCount <= 0 || SelectedTarget <= Epsilon) + { + return 0.0f; + } + + return WeightSum / (CandidateCount * SelectedTarget); + } + } + + public bool Add(ResampledImportanceCandidate candidate, double randomUnit) + { + return AddWeightedSample( + candidate.Sample, + candidate.Target, + candidate.ImportanceWeight, + candidate.CandidateCount, + randomUnit); + } + + public bool Merge(ResampledImportanceReservoir other, double randomUnit) + { + if (other is null) + { + throw new ArgumentNullException(nameof(other)); + } + + if (!other.HasSample) + { + return false; + } + + return AddWeightedSample( + other.SelectedSample, + other.SelectedTarget, + other.WeightSum, + other.CandidateCount, + randomUnit); + } + + private bool AddWeightedSample( + TSample sample, + float target, + float weightSum, + int candidateCount, + double randomUnit) + { + if (candidateCount <= 0 || !float.IsFinite(target) || target <= 0.0f || !float.IsFinite(weightSum) || weightSum <= 0.0f) + { + return false; + } + + if (!double.IsFinite(randomUnit) || randomUnit < 0.0 || randomUnit >= 1.0) + { + throw new ArgumentOutOfRangeException(nameof(randomUnit), "Reservoir random value must be in [0, 1)."); + } + + var previousWeightSum = WeightSum; + var nextWeightSum = previousWeightSum + weightSum; + if (!float.IsFinite(nextWeightSum) || nextWeightSum <= 0.0f) + { + return false; + } + + WeightSum = nextWeightSum; + CandidateCount = checked(CandidateCount + candidateCount); + + if (!HasSample || randomUnit < weightSum / nextWeightSum) + { + selectedSample = sample; + SelectedTarget = target; + HasSample = true; + return true; + } + + return false; + } +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index a84e5ea..76da81c 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -158,3 +158,4 @@ {"timestamp":"2026-05-19T15:46:00+01:00","topic":"temporal-reservoir-ownership-contract","lesson":"The temporal spatial evidence reservoir now has an explicit architecture contract. Raw sample reservoirs keep capture-time handles and ordering; Aquarium's `TemporalSpatialEvidenceReservoir` owns stable resolved spatial history; `TemporalSpatialEvidenceLowering` owns backend packet conversion; TAA owns pixel history. This prevents consumer repos from growing parallel half-reservoirs while preserving LocalCastBridge's lower-level raw rolling reservoir authority.","files":["docs/temporal-spatial-evidence-reservoir.md","state/map.yaml","state/memory.json"],"source":"user made Aquarium responsible for resolving temporal reservoir sampling architecturally across consumer repos"} {"timestamp":"2026-05-19T16:11:00+01:00","topic":"zyphos-budgeted-fractal-geometry","lesson":"Authored fractal packets now affect Zyphos traced planet geometry, but only through a hard-budgeted top-influence subset. Selected height brushes are sorted by abs(amplitude)*max(radius), `sdfDistance` samples the first four, and `sdfSurface` still evaluates the full selected packet table for material/detail. A 12-brush geometry loop was tested and cut after pushing the live frame to about 33 ms; the four-brush budget returns the live view to about 16.4 ms after shader pipelines are ready.","files":["src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"runtime proof after moving authored fractal packet evaluation into the hot SDF distance path"} {"timestamp":"2026-05-19T16:27:00+01:00","topic":"zyphos-fractal-domain-debug-mode","lesson":"Render debug mode 11 now exposes a client fractal-domain view. Zyphos colors cube faces, draws an 8x8 tile grid, and overlays authored brush material influence so face/tile/material packet mapping can be inspected from the renderer instead of inferred from final beauty shading.","files":["src/Aquarium.Engine.Contracts/GraphicsSettings.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"roadmap called for face/tile/LOD/cache debug modes; this is the first renderer-visible face/tile/material influence slice"} +{"timestamp":"2026-05-19T17:35:00+01:00","topic":"restir-reservoir-core","lesson":"The previous stable-key temporal smoother was not ReSTIR. Aquarium now treats `ResampledImportanceReservoir` as the RIS/ReSTIR math authority: selected sample, target value, weight sum, represented candidate count, merge, and contribution weight. `TemporalSpatialEvidenceReservoir` is a stable resolved-track layer, while fractal contribution scoring should become a candidate generator feeding reservoir resampling with temporal/spatial/domain validation and TAA guide-buffer integration.","files":["src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs","src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs","tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs","docs/temporal-spatial-evidence-reservoir.md","research/rendering/fractal-brush-implementation-roadmap.md","state/map.yaml","state/memory.json"],"source":"user corrected the architecture toward NVIDIA ReSTIR/GRIS rather than invented spatiotemporal reservoir sampling"} diff --git a/state/map.yaml b/state/map.yaml index ec74003..0f28c6c 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -114,7 +114,7 @@ renderer_state: - Aquarium owns the temporal SDF Gaussian field renderer boundary: clients can publish `AquariumTemporalGaussianField`, `TemporalGaussianAccumulator` can buffer stable keyed observations in world space, and D3D12 lowers those packets into an instanced compact-kernel splat pass that writes normal scene color/travel/metadata/control targets. - Temporal Gaussian accumulation now lowers through `TemporalSpatialEvidenceReservoir`, a renderer-agnostic stable-key reservoir for confidence-weighted spatial samples with presentation delay, smoothing, velocity prediction, expiry, and max-track eviction. Gaussian splats are one lowering; fractal SDF probe evidence and Mimir sensor-fusion features should use the same reservoir shape when they need delayed coherence solving. - LocalCast fallback GPU fusion history delegates to `TemporalSpatialEvidenceReservoir`. `LocalCastGpuFusionAccumulator` is now an adapter that maps LocalCast stable seeds into shared evidence observations and back into GPU fusion seeds; it does not own a parallel temporal sampling algorithm. - - The temporal reservoir ownership contract lives in docs/temporal-spatial-evidence-reservoir.md. Raw producer reservoirs own capture-time retention; Aquarium's temporal spatial evidence reservoir owns stable resolved spatial history; lowerings own backend packet conversion; TAA owns pixel history validation. + - The temporal reservoir ownership contract lives in docs/temporal-spatial-evidence-reservoir.md. `ResampledImportanceReservoir` owns RIS/ReSTIR-style candidate selection math: selected sample, target value, weight sum, represented candidate count, merge, and contribution weight. Raw producer reservoirs own capture-time retention; Aquarium's temporal spatial evidence track layer owns stable resolved spatial history; lowerings own backend packet conversion; TAA owns pixel history validation. - Isolated Epiphany agent preview renders run through the real D3D12 renderer from src/Aquarium.Epiphany.AgentPreview; preview isolation is owned by a preview-only scene shader, while the engine exposes only final-frame PNG capture. - Zyphos is the first nontrivial non-Epiphany client: a planetary-scale demo with spherical-domain terrain, atmospheric rim lighting, night-side glints, fixed-sky Umbros, and first-pass eclipse cadence. - Zyphos/Umbros render-scale binary constants live in src/Aquarium.Zyphos/ZyphosUmbrosSystem.cs: Umbros is modeled as a 0.9-radius mutually tidally locked twin at 8 Zyphos radii, while the dim primary star phase moves through the Zyphos-local frame. diff --git a/state/memory.json b/state/memory.json index 5cbc53b..87b19a2 100644 --- a/state/memory.json +++ b/state/memory.json @@ -83,13 +83,13 @@ "Temporal Gaussian splats lower through TemporalSpatialEvidenceReservoir: stable keyed observations become delayed, smoothed, confidence-weighted tracks with velocity prediction, expiry, and max-track eviction before backend packet lowering. Treat Gaussian fields, fractal SDF probes, and Mimir sensor-fusion features as different evidence producers for this reservoir shape, not separate accumulator folklore.", "LocalCastGpuFusionAccumulator must remain a thin adapter over TemporalSpatialEvidenceReservoir. LocalCast may own mapping from visual points/seeds into evidence payloads, but it must not grow a second stable-key history, smoothing, expiry, or sample-budget algorithm.", "TemporalSpatialEvidenceLowering owns conversion between shared evidence samples and backend packets such as TemporalGaussianObservation, AquariumTemporalSdfGaussian, and AquariumGpuFusionSeed. Consumers should not pack Payload0/Payload1 by private convention when a lowering helper exists.", - "The temporal reservoir ownership contract lives in docs/temporal-spatial-evidence-reservoir.md: raw producer reservoirs own capture-time retention; Aquarium's TemporalSpatialEvidenceReservoir owns stable resolved spatial history; lowerings own backend packet conversion; TAA owns pixel history validation. Do not let consumer repos build parallel stable-key spatial evidence caches.", + "The temporal reservoir ownership contract lives in docs/temporal-spatial-evidence-reservoir.md: ResampledImportanceReservoir owns RIS/ReSTIR-style candidate selection math; raw producer reservoirs own capture-time retention; Aquarium's temporal spatial evidence track layer owns stable resolved spatial history; lowerings own backend packet conversion; TAA owns pixel history validation. Do not let consumer repos build parallel stable-key spatial evidence caches.", "Zyphos fractal stress data should keep authored topology richer than the first renderer backend: both Zyphos and Umbros expose lat/long, surface, object-scale, and cube-tile domains in `.aquageo`, with explicit continent/forest/tree/leaf/coast/pebble and crater/boulder/pebble recursion. The current D3D12 height-field stress table uploads 64 shaped 2D brushes and the SDF planet shaders carry separate cheap bounded quadtree-style relief.", "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.", "Zyphos traced planet geometry may sample only a hard-budgeted top-influence subset of authored fractal brush packets in `sdfDistance`; the current proven budget is four brushes after sorting selected packets by abs(amplitude)*max(radius). A 12-brush distance loop was tested and rejected because it pushed the live frame to about 33 ms; the four-brush loop returns the live view to about 16.4 ms while full packet richness remains available to post-hit material/detail.", "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.", + "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. It should evolve into a candidate generator feeding ResampledImportanceReservoir, not pretend the estimator alone is spatiotemporal reservoir sampling. 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." diff --git a/tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs new file mode 100644 index 0000000..89a7793 --- /dev/null +++ b/tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs @@ -0,0 +1,60 @@ +using Aquarium.Engine.Fractal.Temporal; + +namespace Aquarium.Engine.Fractal.Tests; + +public sealed class ResampledImportanceReservoirTests +{ + [Fact] + public void ReservoirSelectsCandidateWithProbabilityProportionalToImportanceWeight() + { + var reservoir = new ResampledImportanceReservoir(); + + Assert.True(reservoir.Add(new ResampledImportanceCandidate("dim", 1.0f, 1.0f), randomUnit: 0.0)); + Assert.True(reservoir.Add(new ResampledImportanceCandidate("bright", 9.0f, 1.0f), randomUnit: 0.5)); + + Assert.Equal("bright", reservoir.SelectedSample); + Assert.Equal(10.0f, reservoir.WeightSum); + Assert.Equal(2, reservoir.CandidateCount); + Assert.InRange(reservoir.ContributionWeight, 0.55f, 0.56f); + } + + [Fact] + public void ReservoirRejectsInvalidOrZeroWeightCandidates() + { + var reservoir = new ResampledImportanceReservoir(); + + Assert.False(reservoir.Add(new ResampledImportanceCandidate("zero-target", 0.0f, 1.0f), randomUnit: 0.0)); + Assert.False(reservoir.Add(new ResampledImportanceCandidate("zero-pdf", 1.0f, 0.0f), randomUnit: 0.0)); + + Assert.False(reservoir.HasSample); + Assert.Equal(0.0f, reservoir.WeightSum); + Assert.Equal(0, reservoir.CandidateCount); + } + + [Fact] + public void ReservoirMergeCarriesSourceCandidateCountAndWeightSum() + { + var left = new ResampledImportanceReservoir(); + var right = new ResampledImportanceReservoir(); + + Assert.True(left.Add(new ResampledImportanceCandidate("left-a", 2.0f, 1.0f), randomUnit: 0.0)); + Assert.False(left.Add(new ResampledImportanceCandidate("left-b", 1.0f, 1.0f), randomUnit: 0.99)); + Assert.True(right.Add(new ResampledImportanceCandidate("right", 6.0f, 1.0f, 4), randomUnit: 0.0)); + + Assert.True(left.Merge(right, randomUnit: 0.25)); + + Assert.Equal("right", left.SelectedSample); + Assert.Equal(9.0f, left.WeightSum); + Assert.Equal(6, left.CandidateCount); + Assert.InRange(left.ContributionWeight, 0.24f, 0.26f); + } + + [Fact] + public void ReservoirRejectsOutOfRangeRandomUnits() + { + var reservoir = new ResampledImportanceReservoir(); + + Assert.Throws( + () => reservoir.Add(new ResampledImportanceCandidate("sample", 1.0f, 1.0f), randomUnit: 1.0)); + } +}