Bin view froxels by crossing ranges

This commit is contained in:
Meta Vens 2026-05-09 21:48:28 +01:00
commit 3ce6a5ceae
4 changed files with 106 additions and 54 deletions

View file

@ -27,6 +27,8 @@ 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 = 3;
private const int GridBinTravelSegments = MediumFroxelSliceCount;
private const int ViewFroxelPrimitiveSlotCount = 2;
private const Format MediumVolumeFormat = Format.R16G16B16A16_Float;
private const Format GridHeightFormat = Format.R16_Float;
@ -1212,7 +1214,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
{
for (var x = 0; x < mediumFroxelWidth; x++)
{
if (ViewFroxelIntersectsSphere(frame, x, y, slice, farDistance, center, boundRadius))
if (ViewFroxelMayContainSphere(frame, x, y, slice, farDistance, center, boundRadius))
{
AddPrimitiveToViewFroxel(ViewFroxelIndex(x, y, slice), primitiveId);
}
@ -1303,20 +1305,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
new Vector4(2.0f, 10.0f, 0.055f, 0.090f),
new Vector4(0.30f, 0.90f, 0.82f, 0.24f));
var farDistance = FrameFarDistance(frame);
for (var slice = 0; slice < MediumFroxelSliceCount; slice++)
{
for (var y = 0; y < mediumFroxelHeight; y++)
{
for (var x = 0; x < mediumFroxelWidth; x++)
{
if (ViewFroxelCrossesGrid(frame, x, y, slice, farDistance))
{
AddTransparentSurfaceToViewFroxel(ViewFroxelIndex(x, y, slice), 0);
}
}
}
}
BinGridSurfaceIntoViewFroxels(frame, FrameFarDistance(frame), 0);
}
private void AddTransparentSurfaceToViewFroxel(int viewFroxelIndex, int surfaceId)
@ -1324,63 +1313,124 @@ public sealed class D3D12Renderer : IAquariumRenderer
AddIdToInt4Slots(transparentSurfaceIds, viewFroxelIndex, 1, surfaceId);
}
private bool ViewFroxelCrossesGrid(AquariumFrame frame, int x, int y, int slice, float farDistance)
private void BinGridSurfaceIntoViewFroxels(AquariumFrame frame, float farDistance, int surfaceId)
{
Span<Vector3> corners = stackalloc Vector3[8];
FillViewFroxelCorners(frame, x, y, slice, farDistance, corners);
var sawPositive = false;
var sawNegative = false;
const float epsilon = 0.025f;
foreach (var corner in corners)
for (var y = 0; y < mediumFroxelHeight; y++)
{
var signedDistance = EvaluateGridHeight(frame, new Vector2(corner.X, corner.Y)) - corner.Z;
sawPositive |= signedDistance >= -epsilon;
sawNegative |= signedDistance <= epsilon;
if (sawPositive && sawNegative)
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 = new Vector2(
(x + ((sx + 0.5f) / GridBinRaySamplesPerAxis)) * MediumFroxelDownscale,
(y + ((sy + 0.5f) / GridBinRaySamplesPerAxis)) * MediumFroxelDownscale);
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))
{
continue;
}
var slicePad = farDistance / MediumFroxelSliceCount;
AddGridSliceRangeToViewFroxels(x, y, minTravel - slicePad, maxTravel + slicePad, farDistance, surfaceId);
}
}
}
private bool TryFindGridSurfaceTravel(AquariumFrame frame, Vector3 direction, float farDistance, out float travel)
{
travel = 0.0f;
var previousTravel = 0.0f;
var previousDistance = GridSurfaceDistanceAt(frame, direction, previousTravel);
const float epsilon = 0.002f;
if (MathF.Abs(previousDistance) <= epsilon)
{
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;
}
}
travel = (a + b) * 0.5f;
return true;
}
previousTravel = currentTravel;
previousDistance = currentDistance;
}
return false;
}
private bool ViewFroxelIntersectsSphere(AquariumFrame frame, int x, int y, int slice, float farDistance, Vector3 center, float radius)
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 bool ViewFroxelMayContainSphere(AquariumFrame frame, int x, int y, int slice, float farDistance, Vector3 center, float radius)
{
Span<Vector3> corners = stackalloc Vector3[8];
FillViewFroxelCorners(frame, x, y, slice, farDistance, corners);
var inside = Vector3.Zero;
var froxelCenter = Vector3.Zero;
foreach (var corner in corners)
{
inside += corner;
froxelCenter += corner;
}
inside /= corners.Length;
return SphereInsidePlane(corners[0], corners[1], corners[3], inside, center, radius)
&& SphereInsidePlane(corners[4], corners[7], corners[5], inside, center, radius)
&& SphereInsidePlane(corners[0], corners[4], corners[1], inside, center, radius)
&& SphereInsidePlane(corners[2], corners[3], corners[6], inside, center, radius)
&& SphereInsidePlane(corners[0], corners[2], corners[4], inside, center, radius)
&& SphereInsidePlane(corners[1], corners[5], corners[3], inside, center, radius);
}
private static bool SphereInsidePlane(Vector3 a, Vector3 b, Vector3 c, Vector3 inside, Vector3 center, float radius)
{
var normal = Vector3.Cross(b - a, c - a);
var length = normal.Length();
if (length <= 0.000001f)
froxelCenter /= corners.Length;
var froxelRadius = 0.0f;
foreach (var corner in corners)
{
return true;
froxelRadius = MathF.Max(froxelRadius, Vector3.Distance(froxelCenter, corner));
}
normal /= length;
if (Vector3.Dot(normal, inside - a) < 0.0f)
{
normal = -normal;
}
return Vector3.Dot(normal, center - a) >= -radius;
return Vector3.Distance(froxelCenter, center) <= froxelRadius + radius;
}
private void FillViewFroxelCorners(AquariumFrame frame, int x, int y, int slice, float farDistance, Span<Vector3> corners)

View file

@ -96,3 +96,4 @@
{"timestamp":"2026-05-09T21:19:15.6975837+01:00","topic":"d3d12-view-froxel-all-candidates","lesson":"The D3D12 scene path must not keep a parallel world-space candidate broadphase. Solid primitives and transparent surfaces now both use view-froxel candidate buffers indexed by low-res screen cell and depth slice; the scene ray marches its assigned tube and tests candidates only inside each slice interval. CPU binning is temporary scaffolding until GPU/raster binning owns the producer side.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json","state/scratch.md"]}
{"timestamp":"2026-05-09T21:26:19.5181030+01:00","topic":"d3d12-conservative-view-froxel-bootstrap","lesson":"Representative-ray CPU binning is not conservative enough for view-froxel candidates; sampling only corners/center missed sub-cell silhouettes and chopped solids/Grid. Until GPU/raster binning owns the producer side, bootstrap candidate buffers should overfill and let exact per-slice intersection reject false positives.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json","state/scratch.md"]}
{"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"]}

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 be conservative until the real GPU/raster producer exists. The bootstrap bins the Grid by evaluating signed heightfield distance at the eight view-froxel corners and requiring a sign crossing, and bins spheres by testing the sphere center against the view-froxel face planes expanded by radius. Representative center/corner rays alone can miss sub-cell silhouettes and chop solids/Grid lines.",
"CPU view-froxel binning must be conservative until the real GPU/raster producer exists. Corner-sign Grid tests and planar froxel-face sphere tests produced a narrow horizontal strip, which means they were still proxy tests for the wrong shape. The bootstrap now bins spheres with a conservative froxel bounding sphere and bins the Grid per low-res screen tube by solving actual height-sheet crossings on a small ray stencil, then marking the crossed depth slice range. Representative center/corner rays alone can miss sub-cell silhouettes and chop solids/Grid lines.",
"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

@ -11,13 +11,14 @@ selectable only as temporary reference ballast until visible D3D12 use survives
the cut.
Current renderer correction: D3D12 scene candidates now live in the view-froxel
volume. CPU bootstrap code now bins sphere primitives by the view-froxel cell
face planes expanded by sphere radius, and bins the Grid by evaluating signed
heightfield distance at all eight view-froxel corners and requiring a crossing.
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.
volume. The corner-sign Grid test and face-plane sphere test produced the same
horizontal-strip failure as the earlier representative binning, so the current
CPU bootstrap bins solids with a conservative froxel bounding-sphere test and
bins the Grid per low-res screen tube by solving actual height-sheet crossings
on a 3x3 ray stencil, then marking the crossed depth slice range. 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