acdream/tests/AcDream.App.Tests/Rendering/ClipFrameLayoutTests.cs
Erik 7df0b94c9f fix(render): S3 chunk 4 round 2 — draw-gate condition pinned, scissor and terrain-clip stacks deleted, one outside-view slice constructor
Round-1 three-lens FAIL at d60ca4ea0 found: the K2 fix was right in
production but nothing pinned the draw side (restoring the pre-fix gate
left every lane green); a stale "still ends an active scissor" comment
asserted a mechanism the same round had already deleted; the sky.vert
comment claimed retail clips the sky when it draws unclipped; the K6
pin ran through ClipFrameAssembler.Assemble, which has zero production
callers, so it proved nothing about the producer that actually runs.
This round closes L1-L9.

L1 (BLOCKING) — draw-side weather-gate pin. Added
RetailPViewPassExecutorTests.DrawLandscapeDynamicsPhase_GatesDrawWeatherOnceOnWalkDriverWeatherTurnFired:
reads DrawLandscapeDynamicsPhase's compiled call graph and asserts (a)
the call immediately before DrawWeatherOnce is
WalkFrameDriver.get_WeatherTurnFired and (b) exactly one
brfalse/brfalse.s branch sits between that call and the draw, jumping
forward past it. Three mutations, each shown failing:

  M1 (restore `if (clipAssembly.OutsideViewSlices.Length != 0)`):
    Assert.Equal() Failure: Values differ
    Expected: typeof(AcDream.App.Rendering.Walk.WalkFrameDriver)
    Actual:   typeof(AcDream.App.Rendering.ClipFrameAssembly)

  M2 (drop the gate, unconditional call):
    Assert.Equal() Failure: Values differ
    Expected: typeof(AcDream.App.Rendering.Walk.WalkFrameDriver)
    Actual:   typeof(AcDream.App.Rendering.RetailPViewPassExecutor)

  M3 (invert to `if (!walkDriver.WeatherTurnFired)`):
    Assert.Single() Failure: The collection did not contain any matching items
    Expected:   (predicate expression)
    Collection: [CompiledBranch { Offset = 7, OpCode = brfalse.s, TargetOffset = 17 }, CompiledBranch { Offset = 24, OpCode = brtrue.s, TargetOffset = 33 }]

Corrected WalkFrameDriverTranscriptTests.cs's doc comment (the
Collect_WeatherTurnFiredMatchesThePrintedOcLineExactly block): it pins
the print half and the flag only, and now names the real draw-side pin
instead of falsely claiming to double as one.

L2 (MAJOR) — scissor stack deleted, K4 comment corrected. Deleted
IWorldPassSurface.BeginScissor/EndScissor and their RhiWorldPassSurface
bodies, the scissor call inside ClearInteriorDepth, NdcScissorRect.cs +
NdcScissorRectTests.cs (BeginScissor had zero remaining callers, and
RhiWorldPassSurface.BeginScissor was NdcScissorRect.ToPixels' only
production caller). This left RhiWorldPassSurface's 4th constructor
parameter (IRetailPViewFramebufferSource) and RetailPViewPassExecutor.cs's
RetailPViewFramebufferSize/IRetailPViewFramebufferSource/
SilkRetailPViewFramebufferSource types entirely dead (framebuffer size
was needed only for the scissor's NDC-to-pixel conversion) — removed
them and their one call site in FrameRootComposition.cs. Rewrote
RetailPViewPassExecutor.cs's K4 comment: it no longer asserts a live
scissor mechanism; it states that VulkanGpuPassEncoder's constructor
sets the full-attachment scissor once, at pass begin
(VulkanGpuPassEncoder.cs:87), and nothing narrows it after that. KEPT
per the round-1 verdict: ScissorFallbacks, OutsidePlaneCount,
OutsideViewNdcAabb, HasOutsideView, OutdoorVisible, OutdoorSlot,
ClipViewSlice.NdcAabb (the >8-edge zero-plane slice case the punch fans
still consume) and the VulkanViewportMapping.ScissorToVulkan pass-begin
path (IGpuPassEncoder.SetScissor stays). Also deleted
ClipFrameAssembly.TerrainMode/TerrainScissorNdcAabb and their writers
in ClipFrameAssembler.cs (both Assemble and ReassembleOutsideViewFromWalk);
OutsidePlaneCount's formula reduces to `outsideHasScissorFallback ? 0 :
outsideMaxPlaneCount` without needing the deleted TerrainClipMode
comparison (a scissor-fallback slice can only exist when outdoorVisible
is already true, so the three original cases collapse identically).
Deleted the two "terrain=" / "outMode=" diagnostic reads in
WorldRenderDiagnostics.cs (:345, :409) and the now-vestigial
EmitClipRouteProbe "ubo: n=..." segment that read ClipFrame's deleted
terrain bytes.

DEVIATION from L2's literal text: kept the TerrainClipMode enum type
itself — WorldSceneRenderer.cs's flat-world safety path (explicitly
"out of this chunk's scope" per K4's own round-1 comment) still uses it
for an unrelated "did the flat terrain draw" diagnostic flag, with its
own WorldSceneDiagnosticsController/WorldRenderDiagnostics/test
consumers. Deleting the type would require rewriting files outside
every round's declared file list. Reworded its doc comment to state
this plainly.

L3 (MAJOR, completes K3) — dead TerrainClip UBO deleted from the sky
and terrain shaders. Deleted the block, both gl_ClipDistance loops, and
the gl_PerVertex redeclaration (nothing else needs it) from sky.vert,
terrain_modern.vert, terrain_atmospheric.vert. Recompiled via
tools/compile-shaders.ps1 (glslc via the Vulkan SDK, managed shaderc
fallback also runs) — 24/24 pairs compiled; only sky.vert.spv,
terrain_atmospheric.vert.spv and terrain_modern.vert.spv changed.
Re-pinned VulkanShaderManifestTests.cs's frozen retail-oracle hashes
for sky.vert.spv (7d67a9e3624d198b370d402b5c12e4ce925bf9b8e646ef5123636a86d5985ab5)
and terrain_modern.vert.spv (8a73d89ef0e51e550327b9ff8c24857e309103b1d491030cf0d4d8594b45068c)
with dated comments, matching the existing re-pin convention.

Deleted WorldFrameSectionBinding.BindTerrainClip and
WorldFrameSections.TerrainClip (+ its Reset) with its two callers
(SkyRenderer.Rhi.cs:258, TerrainModernRenderer.Rhi.cs:259). DEVIATION
from L3's literal text: kept the shared Zeroed(...) helper in
WorldPassScope.cs — it is also called by BindSceneLighting and
BindClipRegions, both of which stay; deleting it would have broken
those two live bindings. Deleted IWorldPassSurface.BindTerrainClip
(no-op interface method + RhiWorldPassSurface body) and
WorldScenePassExecutor.cs's two calls to it (:121, :235).

Deleted ClipFrame's _terrainBytes field, TerrainBytes/TerrainBytesForTest
properties, Reset's Array.Clear(_terrainBytes), and the stale
header/K3 comment paragraphs. DEVIATION from L3's literal text: kept
ClipFrame.TerrainUboBytes and ClipFrame.TerrainClipUboBinding —
PortalDepthMaskRenderer.Rhi.cs (:140, :187) is a live production
consumer of both constants for the KEPT exit-seal/punch-fan clip block,
which was never in scope for deletion (portal_depth.vert's own
TerrainClip UBO declaration is the KEEP block, untouched). Reworded
both constants' doc comments (ClipFrame.cs, VulkanPipelineLayouts.cs's
UniformTerrainClip) to say only the portal-depth clip block uses
binding 2 now, and corrected the two GpuBindingModel.cs comments that
explained why terrain-tiling/sky-params bindings are 3/4 by naming "the
terrain clip block". Updated VulkanShaderDescriptorContractTests.cs's
TerrainVertexShaderDeclaresItsClipBlockInTheUniformSet (renamed
TerrainVertexShaderDeclaresOnlySceneLightingInTheUniformSet):
terrain_modern.vert's uniform set is now {SceneLighting} only. Deleted
ClipFrameLayoutTests.NoClip_TerrainBytes_Count0_AllZeros and its K3
comment; corrected the class doc comment and LayoutConstants_MatchShaderStruct's
"terrain UBO"/binding-contract comments to describe the portal-depth
consumer instead.

REQUIRED L3 fact (declared-but-never-bound dynamic uniform binding):
VulkanFrameBindings's constructor seeds EVERY declared uniform binding
(0..UniformBindingCount-1, including binding 2) with the shared dummy
buffer's range before any renderer runs (VulkanFrameBindings.cs:128-130,
`_arena.SeedUniform(binding, dummy.Handle.Handle, dummyUniformRange)`
in a loop over every binding) — "Every binding is always bound, whether
a renderer uses it or not... unused ones point at a shared dummy range"
(VulkanFrameBindings.cs:27-31). So after this round, when the sky or
terrain pipeline draws, set 1's shared descriptor layout still declares
binding 2 (portal_depth.vert's own declaration keeps
IsDeclaredUniformBinding(2) true), and its descriptor still points at a
valid (dummy) range from that seed — vkCmdBindDescriptorSets stays
legal even though neither shader statically uses binding 2 any more.
No SPIR-V-side change was needed to keep this legal.

L4 (MAJOR) — one outside-view slice constructor. Extracted
ClipFrameAssembler.AppendOutsideSlice (frame, ViewPolygon,
outsideSlicesList, ref maxPlaneCount, ref hasScissorFallback, ref
scissorFallbacks) — the exact ClipPlaneSet.From/AppendSlot/
ClipViewSlice-construction body — and call it from both Assemble's
outside_view loop and ReassembleOutsideViewFromWalk's outside_view
loop. Rewrote ClipFrameLayoutTests's K6 pin
(ClipViewSlicePlanes_PunchFanPath_EqualsCpuViewPolygonEdgePlanes_ForASyntheticView):
builds a synthetic WalkPortalView from pixel-space points (the
WalkCopyViewTests pattern) via a trivial IWalkRayCaster, runs
BeginWalkFrame(frame, outdoorRoot: false) then
ReassembleOutsideViewFromWalk(assembly, walkView, 640, 480), and reads
assembly.OutsideViewSlices[0].Planes — the exact production pair
RetailPViewPassExecutor.cs's BeginWalkFrame call and
RetailPViewRenderer.cs's ReassembleOutsideViewFromWalk call make.
Mutation (perturbed planes[0].W inside the shared helper, right after
`planes = cps.PlaneArray;`):

  edge 0 midpoint (-0.3,0.10000001) should lie ~on its OWN GPU plane; the closest plane was only 0.5251073 away

The pin's own source contains no `Assemble(` call — grep-checked by
extracting the method body and searching it for the literal text; no
match.

L5 — shader comments corrected. sky.vert/terrain_modern.vert/
terrain_atmospheric.vert now state retail draws the sky once
(LScape::draw @0x00506330 -> GameSky::Draw(sky,0) @0x0050633c, before
draw_check_blocks) and the landscape is view-culled per cell, never
GPU-clipped (RenderDeviceD3D::DrawBlock @0x005a17c0). The "Phase W
Stage 4"/"U.3 default" clip narratives are deleted along with the
blocks they described.

L6 — grep sweep. `grep -rn "<token>" src tests docs/architecture`
returns nothing for SetTerrainClip, BeginDoorwayScissor,
BindTerrainClip, TerrainBytes, "active scissor", and NdcScissorRect —
confirmed after this commit (docs/plans and docs/research keep the
historical record, untouched). TerrainClipMode is the one deliberate
exception (see the L2 deviation note above); every one of its 9
remaining hits is a live, non-stale reference (the enum declaration,
WorldSceneRenderer's flat-path local, or their diagnostic/test
plumbing), not a stale mention of a deleted mechanism.

L7 — Issue130DoorwayStripTests. Deleted AnySliceAdmitsScissor,
worstScissorGapPx and its PIN 1 assertion, the header's scissor
sentences, and the scissorGap half of MeasureTopEdgeGap (dropped the
fbW parameter it alone needed). Rewrote the header: the scissor
mechanism is retired (the sky and landscape draw unclipped; aperture
exactness comes from the depth clear, the exit seals and the interior
repaint). The remaining plane-gap half (the canary PIN,
`worstPlaneGapPx <= 1.2f`) still pins something production reads:
AnySliceAdmitsPlanes walks slice.Planes from the SAME ProjectToClip ->
ClipToRegion -> ClipPlaneSet.From pipeline
RetailPViewPassExecutor.DrawWalkPunchFan reads through
clipAssembly.OutsideViewSlices[activeViewIndex].Planes — so the test
was kept, not deleted.

L8 — DrawWalkSky loop-shape pin. Added
DrawWalkSky_RenderSkyCallSiteHasNoEnclosingBackwardBranch (same
backward-branch-span shape as K1's DrawWeatherOnce pin), plus a note in
both pins that CompiledCallGraph.ReadBranches does not decode a
compiled switch jump table, but no C# loop construct compiles to one.
Mutation (wrapped the RenderSky call in `for (int i = 0; i < 2; i++)`):

  Assert.DoesNotContain() Failure: Filter matched in collection
  Collection: [..., CompiledBranch { Offset = 20, OpCode = brtrue.s, TargetOffset = 25 }, CompiledBranch { Offset = 23, OpCode = br.s, TargetOffset = 66 }, CompiledBranch { Offset = 72, OpCode = blt.s, TargetOffset = 13 }, CompiledBranch { Offset = 80, OpCode = brfalse.s, TargetOffset = 116 }, CompiledBranch { Offset = 88, OpCode = brfalse.s, TargetOffset = 116 }]

(the Offset=72 -> TargetOffset=13 entry is the injected loop's backward
branch spanning the call).

L9 — this message.

Gates: dotnet build 0 warnings / 0 errors. Hermetic filter
(Lane!=InstalledDat&...&Status!=KnownFailure): 6827 passed, 0 failed.
InstalledDat lane against a real DAT directory: 244 passed, 4 failed —
exactly the four known failures (LayoutImporterMediaBearingChildSweepTests
+ LayoutImporterInvisibleSweepTests, both #383; TowerAscentReplayTests,
KnownFailure; WalkTraceConformanceTests.Oh_doorway_still_first_frame_diff,
#458 KnownFailure). No register row added (every deletion here removes
an acdream-only rule; the KEEP items already had their equivalence
pins from round 1). No new flag/probe.

OWED: the lead's ACDREAM_DEVTOOLS=1 four-pose visual self-gate against
the running client is not run by this agent — CLAUDE.md and this
task's own instructions forbid launching the graphical client from
here; that visual/validation-layer pass remains the user's to run
before this round is accepted.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-03 16:18:27 +02:00

352 lines
16 KiB
C#

using System.Numerics;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Walk;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Phase U.3: CPU-side proof that <see cref="ClipFrame"/> packs the mesh SSBO
/// clip-region table in the EXACT std430 byte layout mesh_modern.vert reads. A
/// silent layout drift here would mis-clip at U.4 with no build error — these
/// tests are the gate that catches it.
///
/// Layout under test (mesh CellClip, std430):
/// offset 0 : uint count
/// offset 4 : uint _p0 (pad)
/// offset 8 : uint _p1 (pad)
/// offset 12 : uint _p2 (pad)
/// offset 16 : vec4 planes[0] (16-byte vec4 stride)
/// ...
/// offset 16 + i*16 : vec4 planes[i]
/// stride 144 bytes per slot.
///
/// <see cref="ClipFrame.TerrainUboBytes"/>/<see cref="ClipFrame.TerrainClipUboBinding"/>
/// share this file only because they happen to reuse the identical std140
/// 144-byte shape for a DIFFERENT, still-live consumer — see their own doc
/// comments (S3 chunk 4 fix round 2, L3).
/// </summary>
public class ClipFrameLayoutTests
{
private static float ReadFloat(System.ReadOnlySpan<byte> b, int offset)
=> System.BitConverter.ToSingle(b.Slice(offset, 4));
private static uint ReadUInt(System.ReadOnlySpan<byte> b, int offset)
=> System.BitConverter.ToUInt32(b.Slice(offset, 4));
private static int ReadInt(System.ReadOnlySpan<byte> b, int offset)
=> System.BitConverter.ToInt32(b.Slice(offset, 4));
[Fact]
public void LayoutConstants_MatchShaderStruct()
{
// CellClip: 16 (count + 3 pad uints) + 8*16 (vec4 planes) = 144.
Assert.Equal(144, ClipFrame.CellClipStrideBytes);
Assert.Equal(16, ClipFrame.CellClipPlanesOffset);
Assert.Equal(8, ClipFrame.MaxPlanes);
Assert.Equal(144, ClipFrame.TerrainUboBytes);
// Binding contract: mesh clip regions on SSBO binding=2, PortalDepthMaskRenderer's
// exit-seal/punch-fan clip block on UBO binding=2. The mesh side's binding
// index moved off ClipFrame at Campaign V slice V11 — the RHI arm addresses
// it through GpuBindingModel.StorageClipRegions instead of a raw GL binding
// constant (see ClipFrame's BeginFrame doc comment); the portal-depth UBO
// binding is still genuinely shared, so it stays.
Assert.Equal(2u, GpuBindingModel.StorageClipRegions);
Assert.Equal(2u, ClipFrame.TerrainClipUboBinding);
}
[Fact]
public void NoClip_HasExactlyOneSlot_AllZeros_Count0()
{
var frame = ClipFrame.NoClip();
Assert.Equal(1, frame.SlotCount);
var bytes = frame.RegionBytesForTest;
Assert.Equal(ClipFrame.CellClipStrideBytes, bytes.Length); // 144 — exactly one slot
// count == 0 ⇒ shader passes every plane (no-clip).
Assert.Equal(0u, ReadUInt(bytes, 0));
// Every byte of the reserved no-clip slot is zero.
foreach (var b in bytes)
Assert.Equal(0, b);
}
[Fact]
public void AppendSlot_WritesCountAndPlanes_AtStd430Offsets()
{
var frame = ClipFrame.NoClip();
// Three distinct planes so each lands at a verifiable offset.
var p0 = new Vector4(1f, 0f, 0f, 0.5f);
var p1 = new Vector4(0f, 1f, 0f, 0.25f);
var p2 = new Vector4(-1f, 0f, 0f, -0.75f);
int slot = frame.AppendSlot(new[] { p0, p1, p2 });
Assert.Equal(1, slot); // slot 0 is the reserved no-clip; this is slot 1
Assert.Equal(2, frame.SlotCount);
var bytes = frame.RegionBytesForTest;
Assert.Equal(2 * ClipFrame.CellClipStrideBytes, bytes.Length); // two slots now
int baseOff = slot * ClipFrame.CellClipStrideBytes; // 144
// count == 3 at offset 0 of the slot; the 3 pad uints stay zero.
Assert.Equal(3u, ReadUInt(bytes, baseOff + 0));
Assert.Equal(0u, ReadUInt(bytes, baseOff + 4));
Assert.Equal(0u, ReadUInt(bytes, baseOff + 8));
Assert.Equal(0u, ReadUInt(bytes, baseOff + 12));
// planes[0..2] at offset 16, 32, 48 (vec4 stride 16).
AssertPlaneAt(bytes, baseOff + 16, p0);
AssertPlaneAt(bytes, baseOff + 32, p1);
AssertPlaneAt(bytes, baseOff + 48, p2);
// Slot 0 (the reserved no-clip) is untouched: still count 0.
Assert.Equal(0u, ReadUInt(bytes, 0));
}
[Fact]
public void GetSlotPlanes_BorrowsTheExactPackedClipRegion()
{
using ClipFrame frame = ClipFrame.NoClip();
Vector4[] expected =
[
new(1f, 2f, 3f, 4f),
new(-5f, 6f, -7f, 8f),
];
int slot = frame.AppendSlot(expected);
ReadOnlySpan<Vector4> actual = frame.GetSlotPlanes(checked((uint)slot));
Assert.Equal(expected.Length, actual.Length);
Assert.Equal(expected[0], actual[0]);
Assert.Equal(expected[1], actual[1]);
Assert.Equal(0, frame.GetSlotPlanes(0).Length);
}
[Fact]
public void AppendSlot_EmptyPlaneList_PacksNoClipSlot_Count0()
{
var frame = ClipFrame.NoClip();
int slot = frame.AppendSlot(System.ReadOnlySpan<Vector4>.Empty);
Assert.Equal(1, slot);
var bytes = frame.RegionBytesForTest;
Assert.Equal(0u, ReadUInt(bytes, slot * ClipFrame.CellClipStrideBytes)); // count 0
}
[Fact]
public void AppendSlot_ClampsToEightPlanes()
{
var frame = ClipFrame.NoClip();
var planes = new Vector4[12];
for (int i = 0; i < planes.Length; i++)
planes[i] = new Vector4(i, 0f, 0f, 0f);
int slot = frame.AppendSlot(planes);
var bytes = frame.RegionBytesForTest;
// Only MaxPlanes (8) are recorded in the count.
Assert.Equal((uint)ClipFrame.MaxPlanes, ReadUInt(bytes, slot * ClipFrame.CellClipStrideBytes));
}
[Fact]
public void AppendSlot_FromClipPlaneSet_AxisAlignedSquare_PacksFourPlanes()
{
// A unit square in NDC → ClipPlaneSet with 4 convex planes.
var cv = new CellView();
cv.Add(new ViewPolygon(new[]
{
new Vector2(-0.5f, -0.5f), new Vector2(0.5f, -0.5f),
new Vector2(0.5f, 0.5f), new Vector2(-0.5f, 0.5f),
}));
var cps = ClipPlaneSet.From(cv);
Assert.Equal(4, cps.Count);
var frame = ClipFrame.NoClip();
int slot = frame.AppendSlot(cps);
var bytes = frame.RegionBytesForTest;
int baseOff = slot * ClipFrame.CellClipStrideBytes;
Assert.Equal(4u, ReadUInt(bytes, baseOff + 0));
// Each packed plane must match the ClipPlaneSet's plane bit-for-bit.
for (int i = 0; i < 4; i++)
AssertPlaneAt(bytes, baseOff + ClipFrame.CellClipPlanesOffset + i * 16, cps.Planes[i]);
}
// S3 chunk 4 fix round 2 (L3): the walk's screen-space clip gate and its
// own std140 layout pin are deleted outright — no shader declares that
// block any more, so there is nothing left to pack or pin.
private static void AssertPlaneAt(System.ReadOnlySpan<byte> bytes, int offset, Vector4 expected)
{
Assert.Equal(expected.X, ReadFloat(bytes, offset + 0), 6);
Assert.Equal(expected.Y, ReadFloat(bytes, offset + 4), 6);
Assert.Equal(expected.Z, ReadFloat(bytes, offset + 8), 6);
Assert.Equal(expected.W, ReadFloat(bytes, offset + 12), 6);
}
// ── S3 chunk 4 (§10.2 KEEP): CPU/GPU clip-plane equivalence pins ────────
//
// Grepped first (per the chunk 4 contract): ClipPlaneSetTests.cs pins
// sign correctness (inside >= 0, just-outside < 0 on SOME plane) and
// AppendSlot_FromClipPlaneSet_AxisAlignedSquare_PacksFourPlanes pins
// bit-exact GPU packing of ClipPlaneSet's own output — neither asks
// whether a point ON an edge has ~0 distance under the planes actually
// read back through each KEEP item's real production accessor. These
// two tests close that gap, one per KEEP item (exit seals, punch fans).
/// <summary>
/// KEEP item 1 — exit seals: <c>RetailPViewPassExecutor.DrawExitPortalMask</c>
/// reads its clip planes through <c>WalkFrameDriver.
/// InteriorFloodViewClipPlanesAt</c> → <see cref="ClipFrame.GetSlotPlanes"/>,
/// the packed-byte round trip <c>ClipFrameAssembler.Assemble</c> builds
/// via <see cref="ClipFrame.AppendSlot(ClipPlaneSet)"/>. For a synthetic
/// quad "view" (a stand-in for one live portal view), every edge
/// midpoint has near-zero signed distance under the GPU-read-back
/// planes AND non-negative distance under every plane (retail's
/// <c>polyClipFinish</c> keeps the whole convex region, never clips a
/// point that sits ON the boundary) — proving the bytes
/// <c>InteriorFloodViewClipPlanesAt</c> hands the seal leaf really are
/// the CPU view polygon's own edge planes, not merely SOME bytes that
/// happen to round-trip.
/// </summary>
[Fact]
public void GetSlotPlanes_ExitSealPath_EqualsCpuViewPolygonEdgePlanes_ForASyntheticView()
{
Vector2[] verts =
[
new(-1f, -0.5f), new(1f, -0.5f), new(1f, 0.5f), new(-1f, 0.5f),
];
var cv = new CellView();
cv.Add(new ViewPolygon(verts));
ClipPlaneSet cps = ClipPlaneSet.From(cv);
Assert.Equal(4, cps.Count);
// The EXACT production path: ClipFrameAssembler.Assemble packs the
// ClipPlaneSet into a slot; the seal leaf reads it back through
// ClipFrame.GetSlotPlanes (WalkFrameDriver.InteriorFloodViewClipPlanesAt).
var frame = ClipFrame.NoClip();
int slot = frame.AppendSlot(cps);
ReadOnlySpan<Vector4> gpuPlanes = frame.GetSlotPlanes(checked((uint)slot));
Assert.Equal(4, gpuPlanes.Length);
AssertEveryEdgeMidpointLiesOnSomeGpuPlane(verts, gpuPlanes);
}
/// <summary>
/// KEEP item 2 — punch fans: <c>RetailPViewPassExecutor.DrawWalkPunchFan</c>
/// reads its clip planes through <c>clipAssembly.OutsideViewSlices
/// [activeViewIndex].Planes</c> — <see cref="ClipViewSlice"/>'s
/// <c>Planes</c> field. S3 chunk 4 fix round 2 (L4): a prior round's pin
/// here built the slice through <c>ClipFrameAssembler.Assemble</c> — but
/// <c>Assemble</c> has ZERO production callers (it exists only for
/// isolated research/replay tests, per this file's own class header);
/// production builds an interior root's outside-view slices through
/// <c>BeginWalkFrame</c> + <c>ReassembleOutsideViewFromWalk</c>
/// (<c>RetailPViewPassExecutor.cs</c>'s <c>BeginWalkFrame</c> call,
/// <c>RetailPViewRenderer.cs</c>'s <c>ReassembleOutsideViewFromWalk</c>
/// call), so a pin through <c>Assemble</c> proves nothing about the code
/// that actually runs. This pin now drives that EXACT pair: a synthetic
/// <see cref="WalkPortalView"/> holding one pixel-space polygon (built
/// the way <c>WalkCopyViewTests</c> builds views), fed through
/// <c>BeginWalkFrame(frame, outdoorRoot: false)</c> then
/// <c>ReassembleOutsideViewFromWalk</c> — both of which now call the
/// SAME shared <c>ClipFrameAssembler.AppendOutsideSlice</c> helper
/// <c>Assemble</c> would have (L4's own de-duplication), so this pin
/// exercises the helper through the producer that actually runs.
/// MUTATION: perturbing <c>planes[0].W</c> INSIDE that shared helper (the
/// one place both producers pack a plane) breaks this pin — see the
/// commit body for the recorded failing assertion text. The pin's own
/// source contains no <c>Assemble(</c> call (grep-checked in the commit
/// body). Same non-axis-aligned synthetic polygon as before, kept
/// distinct from the exit-seal pin's input.
/// </summary>
[Fact]
public void ClipViewSlicePlanes_PunchFanPath_EqualsCpuViewPolygonEdgePlanes_ForASyntheticView()
{
const float ViewportWidth = 640f, ViewportHeight = 480f;
Vector2[] verts =
[
new(0f, 0.6f), new(-0.6f, -0.4f), new(0.5f, -0.5f), new(0.7f, 0.2f),
];
// Pixel-space points (origin top-left, +Y down) that ReassembleOutsideViewFromWalk's
// own inverse transform (px = (ndc+1)*W/2, py = (1-ndc)*H/2) maps back to `verts`.
var pixelPoints = new WalkScreenPoint[verts.Length];
for (int i = 0; i < verts.Length; i++)
{
float px = (verts[i].X + 1f) * ViewportWidth / 2f;
float py = (1f - verts[i].Y) * ViewportHeight / 2f;
pixelPoints[i] = new WalkScreenPoint(px, py, 0f, 1f);
}
var walkView = new WalkPortalView();
Assert.True(WalkCopyView.Append(
walkView, pixelPoints, new SyntheticRayCaster(), Vector3.Zero));
// The EXACT production pair: BeginWalkFrame seeds an interior root's
// empty outside-view assembly; ReassembleOutsideViewFromWalk (the
// walk's real producer) fills it from the walk's own pixel-space
// view — the same two calls RetailPViewPassExecutor.cs and
// RetailPViewRenderer.cs make.
ClipFrameAssembly assembly = ClipFrameAssembler.BeginWalkFrame(
ClipFrame.NoClip(), outdoorRoot: false);
ClipFrameAssembler.ReassembleOutsideViewFromWalk(
assembly, walkView, ViewportWidth, ViewportHeight);
ClipViewSlice slice = Assert.Single(assembly.OutsideViewSlices);
Assert.True(slice.Planes.Length >= 3);
AssertEveryEdgeMidpointLiesOnSomeGpuPlane(verts, slice.Planes);
}
/// <summary>Trivial ray caster: only <c>WalkPortalView</c>'s stored pixel
/// points feed <see cref="ClipFrameAssembler.ReassembleOutsideViewFromWalk"/>
/// (via NDC conversion); the per-vertex plane a ray caster would seed is
/// unused by that path, so any non-degenerate direction works.</summary>
private sealed class SyntheticRayCaster : IWalkRayCaster
{
public Vector3 RayThrough(float screenX, float screenY) =>
Vector3.Normalize(new Vector3(screenX, screenY, 1000f));
}
/// <summary>
/// CPU/GPU equivalence: a point on a convex polygon's edge must sit
/// (a) non-negative under EVERY plane (still inside-or-on the region —
/// no plane clips it away) and (b) within <paramref name="verts"/>'s
/// own floating-point tolerance of ZERO under at least one plane (that
/// edge's own plane). MUTATION: perturbing any one GPU plane's offset
/// or normal after it left <see cref="ClipPlaneSet.From(CellView)"/>
/// (a packing/binding bug) breaks either (a) for a nearby edge or (b)
/// for its own edge, failing the corresponding assertion below.
/// </summary>
private static void AssertEveryEdgeMidpointLiesOnSomeGpuPlane(
Vector2[] verts, ReadOnlySpan<Vector4> gpuPlanes)
{
const float eps = 1e-4f;
for (int i = 0; i < verts.Length; i++)
{
Vector2 a = verts[i];
Vector2 b = verts[(i + 1) % verts.Length];
Vector2 mid = (a + b) / 2f;
var clip = new Vector4(mid.X, mid.Y, 0f, 1f);
float minAbsDistance = float.PositiveInfinity;
foreach (Vector4 plane in gpuPlanes)
{
float distance = Vector4.Dot(plane, clip);
Assert.True(
distance >= -eps,
$"edge {i} midpoint ({mid.X},{mid.Y}) must be inside-or-on every "
+ $"GPU plane; plane {plane} gave distance {distance}");
minAbsDistance = MathF.Min(minAbsDistance, MathF.Abs(distance));
}
Assert.True(
minAbsDistance < eps,
$"edge {i} midpoint ({mid.X},{mid.Y}) should lie ~on its OWN GPU plane; "
+ $"the closest plane was only {minAbsDistance} away");
}
}
}