Keep grid resident across view tube slices

This commit is contained in:
Meta Vens 2026-05-09 22:02:05 +01:00
commit 29b4ee06a9
4 changed files with 27 additions and 89 deletions

View file

@ -27,8 +27,6 @@ public sealed class D3D12Renderer : IAquariumRenderer
private const int MediumFroxelAtlasColumns = 8;
private const int MediumFroxelAtlasRows = 4;
private const int MediumFroxelSliceCount = MediumFroxelAtlasColumns * MediumFroxelAtlasRows;
private const int GridBinRaySamplesPerAxis = 1;
private const int GridBinTravelSegments = MediumFroxelSliceCount;
private const int ViewFroxelPrimitiveSlotCount = 2;
private const Format MediumVolumeFormat = Format.R16G16B16A16_Float;
private const Format GridHeightFormat = Format.R16_Float;
@ -1321,109 +1319,47 @@ public sealed class D3D12Renderer : IAquariumRenderer
{
for (var x = 0; x < mediumFroxelWidth; x++)
{
var minTravel = float.PositiveInfinity;
var maxTravel = float.NegativeInfinity;
for (var sy = 0; sy < GridBinRaySamplesPerAxis; sy++)
{
for (var sx = 0; sx < GridBinRaySamplesPerAxis; sx++)
{
var sample = ScreenRayPixelForViewFroxelSample(x, y, sx, sy);
var direction = RayDirectionForPixel(sample, frame.CameraPosition, frame.Grid.Center);
if (!TryFindGridSurfaceTravel(frame, direction, farDistance, out var travel))
{
continue;
}
minTravel = MathF.Min(minTravel, travel);
maxTravel = MathF.Max(maxTravel, travel);
}
}
if (float.IsPositiveInfinity(minTravel))
if (!ViewFroxelTubeMaySeeGrid(frame, x, y, farDistance))
{
continue;
}
var slicePad = farDistance / MediumFroxelSliceCount;
AddGridSliceRangeToViewFroxels(x, y, minTravel - slicePad, maxTravel + slicePad, farDistance, surfaceId);
for (var slice = 0; slice < MediumFroxelSliceCount; slice++)
{
AddTransparentSurfaceToViewFroxel(ViewFroxelIndex(x, y, slice), surfaceId);
}
}
}
}
private bool TryFindGridSurfaceTravel(AquariumFrame frame, Vector3 direction, float farDistance, out float travel)
private bool ViewFroxelTubeMaySeeGrid(AquariumFrame frame, int x, int y, float farDistance)
{
travel = 0.0f;
var previousTravel = 0.0f;
var previousDistance = GridSurfaceDistanceAt(frame, direction, previousTravel);
const float epsilon = 0.002f;
if (MathF.Abs(previousDistance) <= epsilon)
var gridCenter = new Vector2(frame.Grid.Center.X, frame.Grid.Center.Y);
var expandedRadius = frame.Grid.Radius + MediumFroxelDownscale * 0.1f;
Span<Vector3> corners = stackalloc Vector3[8];
FillViewFroxelCorners(frame, x, y, 0, farDistance, corners);
if (AnyCornerInsideGridRadius(corners, gridCenter, expandedRadius))
{
return true;
}
for (var segment = 1; segment <= GridBinTravelSegments; segment++)
{
var currentTravel = (segment / (float)GridBinTravelSegments) * farDistance;
var currentDistance = GridSurfaceDistanceAt(frame, direction, currentTravel);
if (MathF.Abs(currentDistance) <= epsilon || previousDistance * currentDistance <= 0.0f)
{
var a = previousTravel;
var b = currentTravel;
var fa = previousDistance;
for (var i = 0; i < 6; i++)
{
var mid = (a + b) * 0.5f;
var fm = GridSurfaceDistanceAt(frame, direction, mid);
if (fa * fm <= 0.0f)
{
b = mid;
}
else
{
a = mid;
fa = fm;
}
}
FillViewFroxelCorners(frame, x, y, MediumFroxelSliceCount - 1, farDistance, corners);
return AnyCornerInsideGridRadius(corners, gridCenter, expandedRadius);
}
travel = (a + b) * 0.5f;
private static bool AnyCornerInsideGridRadius(ReadOnlySpan<Vector3> corners, Vector2 gridCenter, float radius)
{
foreach (var corner in corners)
{
if (Vector2.Distance(new Vector2(corner.X, corner.Y), gridCenter) <= radius)
{
return true;
}
previousTravel = currentTravel;
previousDistance = currentDistance;
}
return false;
}
private float GridSurfaceDistanceAt(AquariumFrame frame, Vector3 direction, float travel)
{
var p = frame.CameraPosition + direction * travel;
return p.Z - EvaluateGridHeight(frame, new Vector2(p.X, p.Y));
}
private void AddGridSliceRangeToViewFroxels(int x, int y, float minTravel, float maxTravel, float farDistance, int surfaceId)
{
var safeFarDistance = MathF.Max(farDistance, 0.001f);
var start = (int)MathF.Floor(Math.Clamp(minTravel / safeFarDistance, 0.0f, 0.99999f) * MediumFroxelSliceCount);
var end = (int)MathF.Floor(Math.Clamp(maxTravel / safeFarDistance, 0.0f, 0.99999f) * MediumFroxelSliceCount);
for (var slice = Math.Max(0, start); slice <= Math.Min(MediumFroxelSliceCount - 1, end); slice++)
{
AddTransparentSurfaceToViewFroxel(ViewFroxelIndex(x, y, slice), surfaceId);
}
}
private Vector2 ScreenRayPixelForViewFroxelSample(int x, int y, int sampleX, int sampleY)
{
var localX = (sampleX + 0.5f) / GridBinRaySamplesPerAxis;
var localY = (sampleY + 0.5f) / GridBinRaySamplesPerAxis;
var pixelX = (x + localX) * MediumFroxelDownscale;
var pixelY = height - ((y + localY) * MediumFroxelDownscale);
return new Vector2(
Math.Clamp(pixelX, 0.0f, MathF.Max(width - 1.0f, 0.0f)),
Math.Clamp(pixelY, 0.0f, MathF.Max(height - 1.0f, 0.0f)));
}
private bool TryProjectSphereToViewFroxelBounds(
AquariumFrame frame,
Vector3 center,

View file

@ -98,3 +98,4 @@
{"timestamp":"2026-05-09T21:38:12.8491911+01:00","topic":"d3d12-view-froxel-cpu-binning","lesson":"View-froxel CPU bootstrap binning now follows the intended conservative tests: Grid candidates require a sign crossing from heightfield-minus-worldZ over all eight cell corners, and sphere candidates use the froxel face planes expanded by radius. This removes the all-cells hammer while avoiding representative-ray chopping.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]}
{"timestamp":"2026-05-09T21:47:47.2476504+01:00","topic":"d3d12-view-froxel-binning-strip-failure","lesson":"A narrow horizontal visibility strip cannot be explained by curved Grid height misses alone. The failed corner-sign Grid test and froxel face-plane sphere test were still proxy tests for the wrong view-froxel shape. The current CPU bootstrap bins spheres with a conservative froxel bounding sphere and bins the Grid by solving actual height-sheet crossings per low-res screen tube, then marking crossed depth slice ranges.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]}
{"timestamp":"2026-05-09T22:05:11.0000000+01:00","topic":"d3d12-view-froxel-y-contract","lesson":"The repeated horizontal strip was caused by CPU view-froxel binning using raw top-left pixel Y while the D3D12 scene shader flips input UV Y before ray generation. CPU candidate producers must mirror the shader screen-ray pixel convention exactly. Spheres now use projected screen bounds plus travel slice ranges instead of brute-force per-froxel testing, reducing bootstrap CPU cost.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]}
{"timestamp":"2026-05-09T22:01:24.4341856+01:00","topic":"d3d12-grid-depth-residency","lesson":"Depth-sparse CPU binning for the Grid is the wrong bootstrap contract. At grazing angles the Grid is a global transparent height sheet and guessed crossing slice ranges produce sliced bands. Bin the Grid by low-res screen tube and write it to all depth slices for tubes that may see the Grid radius; the shader exact height-sheet intersection remains the authority for whether an event exists inside each interval.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]}

View file

@ -21,7 +21,7 @@
"D3D12 field data should live in default-heap structured buffers, updated from the per-frame upload ring by CopyBufferRegion, then bound through transient SRV descriptors owned by the consuming pass. Do not make shaders read dynamic field tables straight from upload memory. D3D11 is reference-only during migration; do not pay DRY tax to preserve it.",
"Transparent D3D12 surfaces must enter the same froxel/field candidate path as volumetrics, but not as pre-averaged froxel color. Grid line transparency is a scene-traversal transparent event: the CPU bins the Grid only into a conservative height slab, the shader brackets the height-sheet crossing inside the active ray interval, samples the height texture at the hit, evaluates cartesian lines/isolines/field lines there, composites without terminating, and keeps marching. Future transparent particles and billboard surfaces need the same candidate/event pipe with quad intersections and richer per-froxel event lists rather than alpha side channels or medium-atlas summaries.",
"D3D12 scene candidate discovery belongs in the view-froxel volume. At 720p the active tube is 160x90x32; primitive and transparent candidate ids are indexed by low-res screen cell and depth slice, then scene rays test exact solid/transparent intersections inside that slice interval. The CPU-filled view-froxel buffers are bootstrap only; the durable path should become GPU/raster binning so per-frame upload bandwidth does not become the next stupid tax.",
"CPU view-froxel binning must mirror the shader's screen-ray coordinate convention. D3D12 scene rays flip input UV Y before ray generation, so CPU binning must generate rays from the same flipped screen pixel Y or candidates appear only in a narrow horizontal strip. Until GPU/raster binning replaces the bootstrap, spheres use projected screen bounds plus travel slice ranges and the Grid bins per low-res screen tube by solving height-sheet crossings and marking crossed depth slices.",
"CPU view-froxel binning must mirror the shader's screen-ray coordinate convention. D3D12 scene rays flip input UV Y before ray generation, so CPU binning must generate rays from the same flipped screen pixel Y or candidates appear only in a narrow horizontal strip. Until GPU/raster binning replaces the bootstrap, spheres use projected screen bounds plus travel slice ranges. The Grid is a global transparent height sheet: bin it by screen tube, not guessed sparse depth residency; if a tube may see the Grid radius, write the Grid candidate to every depth slice and let the shader's exact height-sheet intersection reject non-events.",
"D3D12 pixel shader UAV registers share the output namespace. If a shader writes SV_Target0, bind the first manual UAV at u1, not u0.",
"D3D12 shader routing derives its editable source directory from --shader-source/AQUARIUM_SHADER_SOURCE, then watches D3D12Grid/Medium/Scene/Post/Smoke HLSL files directly. Shader/PSO builds run on a background task; startup presents a lightweight loading frame until the first pipeline set is ready, and hot reload keeps the previous pipeline set if compilation fails.",
"Use Vortice at the graphics API membrane. Keep CultMath as the CPU math grammar. Do not let third-party math opinions leak inward unless the conversion is explicit.",

View file

@ -15,12 +15,13 @@ volume. The repeated horizontal-strip failure was a CPU/GPU row-contract bug:
the scene shader flips screen Y before ray generation, while CPU binning used
raw top-left pixel Y. CPU binning now mirrors the shader's screen-ray pixel
convention. Solid spheres use projected screen bounds plus travel slice ranges
instead of brute-force testing every froxel, and the Grid bins per low-res
screen tube by solving height-sheet crossings and marking crossed depth slices.
The scene shader looks up solid and transparent candidate ids by
`(lowX, lowY, slice)` before doing exact intersection for that slice interval.
Next steel-plate step is replacing the CPU-filled candidate buffers with
GPU/raster binning passes.
instead of brute-force testing every froxel. The Grid no longer guesses sparse
depth residency: if a low-res screen tube may see the Grid radius, the Grid
candidate is written to every depth slice for that tube and the shader's exact
height-sheet intersection decides the visible event. The scene shader looks up
solid and transparent candidate ids by `(lowX, lowY, slice)` before doing exact
intersection for that slice interval. Next steel-plate step is replacing the
CPU-filled candidate buffers with GPU/raster binning passes.
## Hot Context