acdream/tests/AcDream.App.Tests/Rendering/Walk/WalkFrameDriverTranscriptTests.cs
Erik be81475cf9 fix(render): S3 chunk 1 round 1 — SC at DrawSortCell entry, the weather OC, real pins with mutation checks
Campaign OVERHAUL S3 chunk 1 fix round 1 (docs/research/2026-09-01-overhaul/
s3-walk-ownership-map.md §11.5), applied on top of 079483bb6 after the
three-lens review. G1-G10, each verified against source and (where the item
adds a pin) mutation-checked.

G1 — the flag-off integration test was vacuous: Collect_TranscriptFlagOff_
ProducesNoConsoleOutput drove ONE frame, and WalkOracleTrace.Parse
structurally discards the last (open) frame, so it passed whether or not
the flag gate worked. Now drives TWO frames and asserts BOTH that Parse
sees zero frames AND that no captured line starts with any of the ten
transcript-kind prefixes (F /P /LS/LC /SC /BLD /DI /DC /EC /OC ) — robust
to unrelated console noise from parallel test classes.

G2 — LC/SC computed LodCellId before testing the flag (~1,300 land-cell
turns/frame of division/modulo/checked-conversion work paid even when the
flag is off). Both OnLandCellTurn and the new OnSortCellTurn now guard the
LodCellId call itself, not just WalkTranscriptDump's internal check.

G3 — the flag-on round trip never exercised LC/SC/BLD (the T2 fixture's
stub 1x1 landscape has zero blocks). New
OutdoorRoot_TranscriptFlagOn_PrintsLandscapeThenLandCellThenSortCellThen
Building_InOrder drives RetailFrameWalk.DrawLandscape directly (the same
deterministic "CY-only" admission technique the existing outdoor LandCell
test uses) over a landscape with one block + one building, and asserts
LS < LC < SC < BLD by position, with the exact cell/building ids.

G4 — the parts/alpha-depth smoke tests asserted FL/PC (Flushes/
DrawCellsSamples) but never AM/PM (MeshAdds/PortalPolyDraws) for the
alpha-depth log, even though PD/DM were already asserted for the parts
log. Added the missing Assert.Contains for MeshAdds and PortalPolyDraws.

G5 — launch-options.md's side-effects column now states the flag off/on
costs explicitly ("one bool read per print site, nothing else" / "one
console line per walk turn, ≈600-800 lines per outdoor frame").

G6 — removed the "DI f4180108... no, a9b4013f" self-correction in
Oh_doorway_still_first_frame_diff's comment; added a one-line note on why
it and Oh_foundry_deep_... stay bespoke Facts rather than folding into the
Theory (no functional reason, just history).

G7 — SC printed from OnLandscapeCellTurn, which RetailFrameWalk.
DrawLandscape calls AFTER DrawBuilding — retail's own order is
LC -> SC -> BLD (terrace-edge.walk.log:2331-2333), not LC -> BLD -> SC.
Fixed by adding IWalkEventSink.OnSortCellTurn, fired at the DrawSortCell
entry point (same alwaysDrawObjects||cellInView gate, before DrawBuilding);
the driver moves its SC print there and OnLandscapeCellTurn no longer
prints one.

G8 — the trailing "OC <viewer land cell>" retail prints once per complete
outdoor frame is GameSky::Draw's weather branch calling
DrawObjCellForDummies(after_sky_cell) @0x005070da, not a walk turn.
RetailPViewPassExecutor.DrawLandscapeSliceLate now prints it at the point
it actually calls RenderWeather; PrintObjectCellTurn's doc, which denied
this line existed, is corrected. New
Oh_terrace_edge_outdoor_frame_ends_with_the_weather_ObjectCellTurn pins
this directly against the OH capture: every complete outdoor frame's last
event is an OC whose cell id equals that same frame's own P-line cell id.

G9 — "EC and OC counts are always exactly equal per pose" was false
(terrace-edge: 12 EC vs 16 OC, the extra 4 being G8's weather OC, which
has no EC counterpart). The visit-scoped/stamp-dedupe conclusion was
right; only the count claim needed fixing. Both doc sites corrected.

G10 — the conformance signature dropped LC/SC/EC/OC entirely, which is
how G7 shipped green: no test ever compared their placement. Recorder now
tracks LC/SC via the new OnLandCellTurn/OnSortCellTurn hooks and derives
EC/OC per DC from PView::DrawCells's own two reverse loops (shell
far-to-near, then object-list far-to-near) — a look-in flood's DC derives
them immediately, the interior root's OWN flood defers to
OnInteriorFloodDrawTurn (verified against cathedral-leak.walk.log:4,1328,
where the root DC's own EC/OC print last). WalkTraceReplayContext.
Signature8 applies the identical derivation to oracle frames and never
produces the trailing weather OC (G8's own dedicated pin covers that
separately, matching the spec's "exclude from the comparison, assert
separately" instruction). Used ONLY for the four OH-capture-rooted
conformance rows (the older FW0 fixtures predate the LC/SC/EC/OC
breakpoints and carry none of those lines).

Applying the eight-kind check surfaced a real, separate bug: WalkLandscape
DatBuilder never set WalkLandBlock.LandblockId, so every LC/SC token any
DAT-built world ever produced read landblockId=0 — latent because the old
four-kind signature filtered LC/SC out. Fixed (one field, test-fixture-
only, no production behavior change). With that fixed, three of the four
OH rows (terrace-edge, cathedral-arrival, foundry-deep) reproduce EXACTLY
at the eight-kind level. Oh_doorway_still_first_frame_diff still diverges
by one extra LC/SC pair (token index 165: replay draws LC:a9c90001|
SC:a9c90001 that retail never does) — a real WalkLandscape.CheckBlocks
visibility question at a ring-2/ring-3 LOD boundary, out of this round's
print-only scope, needing the retail oracle to resolve. Marked
[Trait("Status","KnownFailure")] with the exact position recorded in its
own doc comment, matching TowerAscent's existing pattern — the InstalledDat
lane now shows FOUR known failures (the pre-existing two #383 layout tests
+ TowerAscent, plus this new finding), not three; never weakened the pin
itself.

Mutation checks (all four restored after observing the failure):
- G1: forcing WalkTranscriptDump.Enabled true made
  Collect_TranscriptFlagOff_ProducesNoConsoleOutput fail with
  "Assert.DoesNotContain() Failure: Filter matched in collection ... Collection:
  [\"DI 00000100\", \"DC pv=00000000 ov=1 n=2: 00000100 00000101\", \"LS\", ...]".
- G3: deleting PrintLandCell's Console.WriteLine made the new outdoor test
  fail with "expected an LC line".
- G4: making MeshAddPattern unmatchable made all five
  Alpha_depth_log_parses_with_nonempty_samples rows fail with
  "Assert.Contains() Failure: Filter not matched in collection".
- G7/G10: moving OnSortCellTurn back after DrawBuilding made the
  terrace-edge conformance row fail with "walk diverged from retail
  (terrace-edge.walk)", first divergence exactly at its first building
  (f518002e): expected ...SC:f518002e|BLD:f518002e..., actual
  ...BLD:f518002e|SC:f518002e....

Gates: hermetic lane 6,816/0 (baseline 6,814 + G3's new test + G8's new
test); InstalledDat lane 244/4 known failures (two pre-existing #383
layout tests + TowerAscent + the new Oh_doorway_still_first_frame_diff
finding, documented above).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-03 11:49:42 +02:00

468 lines
22 KiB
C#

using System.Numerics;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Walk;
using AcDream.App.Tests.Rendering;
using AcDream.Core.Rendering;
namespace AcDream.App.Tests.Rendering.Walk;
/// <summary>
/// Campaign OVERHAUL S3 chunk 1 (§11.2): tests T1/T2 for the print-only walk
/// transcript emitter (<see cref="WalkTranscriptDump"/>, gated by
/// <see cref="RenderingDiagnostics.DumpWalkTranscriptEnabled"/>), plus the
/// §11.2 B4 offline signature-diff self-check. Reuses
/// <see cref="WalkFrameDriverTests"/>'s own private fixture types via the
/// shared <c>partial class</c> — the SAME minimal interior two-cell flood
/// (one exit view) that file's own
/// <c>RunFrame_InteriorFloodWithExitView_FreshDriverSkipsTheGatedClearThenDrawsSealsAndFloodCells</c>
/// test already exercises and proves correct; here only
/// <see cref="WalkFrameDriver.Collect"/> runs (no <c>Replay</c>/GPU
/// submission), since every transcript print fires synchronously during the
/// walk itself.
///
/// <para>
/// <see cref="RenderingDiagnostics.DumpWalkTranscriptEnabled"/> and
/// <see cref="Console.Out"/> are both process-wide mutable statics — joins
/// <see cref="CameraDiagnosticsCollection"/> for the SAME reason
/// <c>CornerFloodReplayTests</c>/<c>Issue181WallPressEquilibriumTests</c> do
/// (that collection's own doc comment, issue #251): interleaved
/// <c>Console.SetOut</c> redirection across parallel test classes can
/// restore a disposed <see cref="StringWriter"/> process-wide.
/// </para>
/// </summary>
[Collection(CameraDiagnosticsCollection.Name)]
public sealed partial class WalkFrameDriverTests
{
private static (WalkCell Cell1, WalkCell Cell2) BuildTranscriptFixtureCells(TestContext ctx)
{
var cell1 = new WalkCell
{
CellId = 0x100,
StabList = [0x101u],
Portals =
[
new WalkCellPortal
{
OtherCellId = 0x101, PolygonIndex = 0, PortalSide = 0, OtherPortalId = 0,
},
// The exit portal — raises ov to 1, so the flood draws the
// (empty, zero-block) landscape too, exercising LS.
new WalkCellPortal
{
OtherCellId = 0xFFFFFFFF, PolygonIndex = 1, PortalSide = 0, OtherPortalId = -1,
},
],
PortalPolygons = [Quad(-2f), Quad(-3f)],
};
var cell2 = new WalkCell
{
CellId = 0x101,
Portals = [new WalkCellPortal
{
OtherCellId = 0x100, PolygonIndex = 0, PortalSide = 1, OtherPortalId = 0,
}],
PortalPolygons = [Quad(-2f)],
};
ctx.Cells[cell1.CellId] = cell1;
ctx.Cells[cell2.CellId] = cell2;
return (cell1, cell2);
}
/// <summary>T1 (§11.3): the flag off — zero output, and the emitter's
/// own methods (the only code this chunk adds to the walk path)
/// allocate nothing. The walk itself is NOT independently zero-alloc
/// (e.g. <c>RetailFrameWalk.EmitDrawCells</c> allocates its cell-id
/// array on every call — pre-existing, unrelated to this chunk), so the
/// allocation bound below is scoped to <see cref="WalkTranscriptDump"/>
/// itself, matching B1's actual contract ("allocates nothing EXTRA").</summary>
[Fact]
public void TranscriptEmitter_FlagOff_EveryPrintMethodIsAZeroCostNoOp()
{
bool previous = RenderingDiagnostics.DumpWalkTranscriptEnabled;
RenderingDiagnostics.DumpWalkTranscriptEnabled = false;
TextWriter originalOut = Console.Out;
var capture = new StringWriter();
try
{
Console.SetOut(capture);
var cells = new List<uint> { 0x100u, 0x101u };
void Step()
{
WalkTranscriptDump.PrintFrameRoot(1, 0x100u, Vector3.Zero, Vector3.UnitY);
WalkTranscriptDump.PrintLandscape();
WalkTranscriptDump.PrintBuilding(0x100u);
WalkTranscriptDump.PrintDrawInside(0x100u);
WalkTranscriptDump.PrintDrawCells(outdoorPview: false, 1, cells);
WalkTranscriptDump.PrintLandCell(0xF4180001u);
WalkTranscriptDump.PrintSortCell(0xF4180001u);
WalkTranscriptDump.PrintEnvCellShell(0x101u);
WalkTranscriptDump.PrintObjectCellTurn(0x101u);
}
ZeroAllocationProbe.AssertAllocatesNothing(
"WalkTranscriptDump.Print* (flag off)", Step);
AssertNoTranscriptLines(capture);
}
finally
{
Console.SetOut(originalOut);
RenderingDiagnostics.DumpWalkTranscriptEnabled = previous;
}
}
/// <summary>T1's integration half: a full synthetic interior frame,
/// driven through the SAME <see cref="WalkFrameDriver.Collect"/> path
/// production uses, produces literally NO transcript output when the
/// flag is off. S3 chunk 1 fix round 1 (G1): TWO <c>Collect</c> calls,
/// not one — <see cref="WalkOracleTrace.Parse"/> structurally discards
/// the last (open) frame (its own class doc: the capture harness
/// detaches at the frame marker, so the final "F n" never records its
/// own draws), so a SINGLE-frame transcript parses to zero frames
/// whether or not the flag actually gated anything — a one-Collect-call
/// version of this test is vacuous (it would pass exactly as well with
/// the flag gate forced true). Two Collect calls give the parser a real
/// COMPLETE frame to see if the gate leaked (MUTATION CHECK: forcing
/// <c>RenderingDiagnostics.DumpWalkTranscriptEnabled</c> true right
/// after setting it false here makes <c>AssertNoTranscriptLines</c>
/// fail, both on the parsed-frame-count assertion and the prefix
/// scan).</summary>
[Fact]
public void Collect_TranscriptFlagOff_ProducesNoConsoleOutput()
{
bool previous = RenderingDiagnostics.DumpWalkTranscriptEnabled;
RenderingDiagnostics.DumpWalkTranscriptEnabled = false;
TextWriter originalOut = Console.Out;
var capture = new StringWriter();
try
{
Console.SetOut(capture);
using var fx = new DispatcherFixture();
var ctx = new TestContext();
(WalkCell cell1, _) = BuildTranscriptFixtureCells(ctx);
var landscape = new WalkLandscape { MidWidth = 1, Blocks = new WalkLandBlock?[1] };
var worldData = new FakeWorldData();
var leaf = new RecordingLeafRenderer(new List<string>());
using ClipFrame clipFrame = ClipFrame.NoClip();
var driver = new WalkFrameDriver(fx.Dispatcher, leaf, worldData, clipFrame: clipFrame);
var walk = new RetailFrameWalk();
driver.Collect(
walk, cell1.CellId, cell1, landscape, ctx, Matrix4x4.Identity, Vector3.Zero);
driver.Collect(
walk, cell1.CellId, cell1, landscape, ctx, Matrix4x4.Identity, Vector3.Zero);
AssertNoTranscriptLines(capture);
}
finally
{
Console.SetOut(originalOut);
RenderingDiagnostics.DumpWalkTranscriptEnabled = previous;
}
}
/// <summary>
/// The ten transcript line-kind prefixes <see cref="WalkTranscriptDump"/>
/// ever emits — <c>F </c>/<c>P </c>/<c>LS</c>/<c>LC </c>/<c>SC </c>/
/// <c>BLD </c>/<c>DI </c>/<c>DC </c>/<c>EC </c>/<c>OC </c> — matching
/// each print method's own exact <c>Console.WriteLine</c> format
/// (S3 chunk 1 fix round 1, G1).
/// </summary>
private static readonly string[] TranscriptLinePrefixes =
["F ", "P ", "LS", "LC ", "SC ", "BLD ", "DI ", "DC ", "EC ", "OC "];
/// <summary>
/// Asserts NONE of <see cref="WalkTranscriptDump"/>'s own line kinds
/// appear in <paramref name="capture"/> — robust to unrelated
/// <see cref="Console"/> noise from another test class running in
/// parallel (a real, observed hazard: xUnit runs distinct classes
/// concurrently by default, and <see cref="Console.Out"/> is a
/// process-wide static — see <c>CameraDiagnosticsCollection</c>'s own
/// doc comment, issue #251). A plain <c>Assert.Empty(capture.ToString())</c>
/// is NOT this robust: an unrelated class's unconditional
/// <c>Console.WriteLine</c> can land inside this test's redirect window
/// and fail it for a reason that has nothing to do with the transcript
/// flag. <see cref="WalkOracleTrace.Parse"/> only ever appends a frame
/// once it sees a well-formed <c>F &lt;n&gt;</c> marker line — arbitrary
/// unrelated text can never satisfy that regex, so a truly EMPTY parsed
/// frame list is exactly as strong a proof that THIS code printed
/// nothing, without being sensitive to what else shares the process
/// console. S3 chunk 1 fix round 1 (G1) adds a second, independent
/// check: no captured line starts with any of the ten transcript
/// prefixes — those exact tokens never begin an unrelated test class's
/// own console noise, so this stays robust to the SAME parallel hazard
/// while also catching a leak the parser's own drop-last-frame quirk
/// could otherwise hide (a caller that (mistakenly) drives only ONE
/// frame).
/// </summary>
private static void AssertNoTranscriptLines(StringWriter capture)
{
string[] lines = capture.ToString()
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(l => l.TrimEnd('\r'))
.ToArray();
Assert.Empty(WalkOracleTrace.Parse(lines));
Assert.DoesNotContain(
lines,
l => Array.Exists(
TranscriptLinePrefixes, p => l.StartsWith(p, StringComparison.Ordinal)));
}
/// <summary>T2 (§11.3): flag on, one synthetic interior frame — the
/// printed lines parse with the extended <see cref="WalkOracleTrace"/>
/// into the same events the driver recorded (emitter/parser round
/// trip). Asserted structurally (kinds, cell ids, counts) rather than
/// against a hand-predicted exact ordering, so the test does not
/// silently pin an assumption about traversal order it never
/// independently verified.</summary>
[Fact]
public void Collect_TranscriptFlagOn_PrintedLinesRoundTripThroughTheParser()
{
bool previous = RenderingDiagnostics.DumpWalkTranscriptEnabled;
RenderingDiagnostics.DumpWalkTranscriptEnabled = true;
TextWriter originalOut = Console.Out;
var capture = new StringWriter();
try
{
Console.SetOut(capture);
using var fx = new DispatcherFixture();
var ctx = new TestContext();
(WalkCell cell1, WalkCell cell2) = BuildTranscriptFixtureCells(ctx);
var landscape = new WalkLandscape { MidWidth = 1, Blocks = new WalkLandBlock?[1] };
var worldData = new FakeWorldData();
var leaf = new RecordingLeafRenderer(new List<string>());
using ClipFrame clipFrame = ClipFrame.NoClip();
var driver = new WalkFrameDriver(fx.Dispatcher, leaf, worldData, clipFrame: clipFrame);
var walk = new RetailFrameWalk();
// Two Collect calls: WalkOracleTrace.Parse (like every real
// capture) only flushes a frame once the NEXT "F n" marker
// appears — it deliberately drops the final in-progress frame
// (the detach-frame rule). One frame alone would parse to zero
// complete frames.
driver.Collect(
walk, cell1.CellId, cell1, landscape, ctx, Matrix4x4.Identity, Vector3.Zero);
driver.Collect(
walk, cell1.CellId, cell1, landscape, ctx, Matrix4x4.Identity, Vector3.Zero);
Console.Out.Flush();
string[] lines = capture.ToString()
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(l => l.TrimEnd('\r'))
.ToArray();
Assert.NotEmpty(lines);
IReadOnlyList<WalkOracleFrame> frames = WalkOracleTrace.Parse(lines);
WalkOracleFrame frame = Assert.Single(frames);
Assert.Equal(1, frame.Number);
Assert.NotNull(frame.Pose);
Assert.Equal(cell1.CellId, frame.Pose!.CellId);
Assert.Equal(cell1.CellId, frame.InteriorRootCell);
Assert.True(frame.HasLandscape);
WalkOracleEvent dc = Assert.Single(
frame.Events, e => e.Kind == WalkOracleEventKind.DrawCells);
Assert.Equal(1, dc.OutsideViewCount);
Assert.Equal(
new HashSet<uint> { cell1.CellId, cell2.CellId },
dc.Cells.ToHashSet());
// The interior root's own flood visits both cells for a shell
// AND an object-list turn — EC/OC pair, one line per cell, no
// dedupe (this is the interior root's OWN flood — the ONE case
// WalkTranscriptDump.PrintEnvCellShell's own doc comment (G9)
// still guarantees EC==OC count for; a look-in flood matches
// too, but G8's per-frame trailing weather OC does not, and
// never fires here since this fixture's landscape has zero
// blocks/buildings).
List<uint> ec = frame.Events
.Where(e => e.Kind == WalkOracleEventKind.EnvCellShell)
.Select(e => e.CellId!.Value).ToList();
List<uint> oc = frame.Events
.Where(e => e.Kind == WalkOracleEventKind.ObjectCellTurn)
.Select(e => e.CellId!.Value).ToList();
Assert.Equal(new HashSet<uint> { cell1.CellId, cell2.CellId }, ec.ToHashSet());
Assert.Equal(new HashSet<uint> { cell1.CellId, cell2.CellId }, oc.ToHashSet());
Assert.Equal(2, ec.Count);
Assert.Equal(2, oc.Count);
// No landblocks were published (the stub 1x1 landscape), so no
// LC/SC/BLD turns exist this frame — the transcript format and
// relative order for those three kinds is proven by
// OutdoorRoot_TranscriptFlagOn_PrintsLandscapeThenLandCellThenSortCellThenBuilding_InOrder
// below (S3 chunk 1 fix round 1, G3), and separately against
// real retail data by WalkOracleTraceTests.AllFixtures and
// WalkLandCellOrderTests.
Assert.DoesNotContain(frame.Events, e => e.Kind
is WalkOracleEventKind.LandCell or WalkOracleEventKind.SortCell
or WalkOracleEventKind.Building);
}
finally
{
Console.SetOut(originalOut);
RenderingDiagnostics.DumpWalkTranscriptEnabled = previous;
}
}
/// <summary>S3 chunk 1 fix round 1 (G3): the outdoor-root half T2 never
/// covered — the flag-on round trip above uses a stub 1x1 landscape with
/// zero blocks, so LC/SC/BLD never fire at all. Drives
/// <see cref="RetailFrameWalk.DrawLandscape"/> directly with the SAME
/// deterministic "CY-only" <see cref="OneDegenerateView"/> admission
/// technique <c>OutdoorRoot_LandCellPrecedesItsOwnCellsObjectTurn_ThenFlushesAtReplaysEnd</c>
/// uses (a real <see cref="RetailFrameWalk.WalkFrame"/> root's default
/// full-viewport view depends on this suite's synthetic ray caster,
/// which does not model screen geometry faithfully enough to predict
/// block/cell admission from — see that test's own doc comment), with a
/// building attached to the one admitted cell so BLD fires too. Checked
/// against the RAW captured lines directly (not
/// <see cref="WalkOracleTrace.Parse"/>) — this test only needs kind
/// presence and relative order, not a complete F/P-framed capture.
/// MUTATION CHECK: deleting <c>WalkTranscriptDump.PrintLandCell</c>'s
/// call site (or its body) makes the "expected an LC line" assertion
/// fail.</summary>
[Fact]
public void OutdoorRoot_TranscriptFlagOn_PrintsLandscapeThenLandCellThenSortCellThenBuilding_InOrder()
{
bool previous = RenderingDiagnostics.DumpWalkTranscriptEnabled;
RenderingDiagnostics.DumpWalkTranscriptEnabled = true;
TextWriter originalOut = Console.Out;
var capture = new StringWriter();
try
{
Console.SetOut(capture);
using var fx = new DispatcherFixture();
var leaf = new RecordingLeafRenderer(new List<string>());
leaf.CellsWithoutEmitters.UnionWith(CoarseLandscapeBuckets(0xF4180000u));
var ctx = new TestContext();
var driver = new WalkFrameDriver(fx.Dispatcher, leaf, new FakeWorldData());
var walk = new RetailFrameWalk();
var landscape = new WalkLandscape { MidWidth = 1, Blocks = new WalkLandBlock?[1] };
var block = new WalkLandBlock
{
LandblockId = 0xF4180000u, SideCellCount = 1, MaxZ = 10f, MinZ = 0f,
};
block.EnsureCellArrays();
block.CellBuildings[0] = new WalkBuilding { PositionCellId = 0xF4180000u };
landscape.Blocks[0] = block;
driver.BeginFrame(ctx, Matrix4x4.Identity, Vector3.Zero);
walk.DrawLandscape(landscape, OneDegenerateView(), ctx, driver);
driver.EndFrame();
Console.Out.Flush();
string[] lines = capture.ToString()
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(l => l.TrimEnd('\r'))
.ToArray();
int lsIndex = Array.IndexOf(lines, "LS");
int lcIndex = Array.FindIndex(
lines, l => l.StartsWith("LC ", StringComparison.Ordinal));
int scIndex = Array.FindIndex(
lines, l => l.StartsWith("SC ", StringComparison.Ordinal));
int bldIndex = Array.FindIndex(
lines, l => l.StartsWith("BLD ", StringComparison.Ordinal));
Assert.True(lsIndex >= 0, "expected an LS line");
Assert.True(lcIndex >= 0, "expected an LC line");
Assert.True(scIndex >= 0, "expected an SC line");
Assert.True(bldIndex >= 0, "expected a BLD line");
Assert.True(lsIndex < lcIndex, "LS must precede LC");
Assert.True(
lcIndex < scIndex,
"LC must precede SC — RenderDeviceD3D::DrawLandCell before DrawSortCell");
Assert.True(
scIndex < bldIndex,
"SC must precede BLD — S3 chunk 1 fix round 1 (G7): DrawSortCell entry, "
+ "before its own DrawBuilding call");
Assert.Equal("LC f4180001", lines[lcIndex]);
Assert.Equal("SC f4180001", lines[scIndex]);
Assert.Equal("BLD f4180000", lines[bldIndex]);
}
finally
{
Console.SetOut(originalOut);
RenderingDiagnostics.DumpWalkTranscriptEnabled = previous;
}
}
/// <summary>§11.2 B4: the offline signature diff, self-checked over a
/// synthetic pair — the SAME captured T2 transcript versus itself with
/// its own LAST event removed. Reuses <c>Collect_TranscriptFlagOn_…</c>'s
/// own capture rather than duplicating the walk drive.</summary>
[Fact]
public void SignatureDiff_ReportsTheExactRemovedEvent()
{
bool previous = RenderingDiagnostics.DumpWalkTranscriptEnabled;
RenderingDiagnostics.DumpWalkTranscriptEnabled = true;
TextWriter originalOut = Console.Out;
var capture = new StringWriter();
try
{
Console.SetOut(capture);
using var fx = new DispatcherFixture();
var ctx = new TestContext();
(WalkCell cell1, _) = BuildTranscriptFixtureCells(ctx);
var landscape = new WalkLandscape { MidWidth = 1, Blocks = new WalkLandBlock?[1] };
var worldData = new FakeWorldData();
var leaf = new RecordingLeafRenderer(new List<string>());
using ClipFrame clipFrame = ClipFrame.NoClip();
var driver = new WalkFrameDriver(fx.Dispatcher, leaf, worldData, clipFrame: clipFrame);
var walk = new RetailFrameWalk();
// Two Collect calls — see the round-trip test's own comment on
// why one alone parses to zero complete frames.
driver.Collect(
walk, cell1.CellId, cell1, landscape, ctx, Matrix4x4.Identity, Vector3.Zero);
driver.Collect(
walk, cell1.CellId, cell1, landscape, ctx, Matrix4x4.Identity, Vector3.Zero);
Console.Out.Flush();
string[] lines = capture.ToString()
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(l => l.TrimEnd('\r'))
.ToArray();
IReadOnlyList<WalkOracleFrame> expected = WalkOracleTrace.Parse(lines);
WalkOracleFrame expectedFrame = Assert.Single(expected);
Assert.NotEmpty(expectedFrame.Events);
// Self-vs-self (unmutated copy): no divergence at all.
IReadOnlyList<WalkOracleFrame> unchanged =
[expectedFrame with { Events = expectedFrame.Events.ToList() }];
Assert.Null(WalkTranscriptSignatureDiff.FirstDivergence(expected, unchanged));
// Self-vs-self-minus-one (the LAST event removed): the reported
// divergence is exact — same frame number, position exactly at
// the new (shorter) end, expected = the removed event's own
// signature string, actual = "<end of frame>".
int lastIndex = expectedFrame.Events.Count - 1;
List<WalkOracleEvent> truncated = expectedFrame.Events.Take(lastIndex).ToList();
IReadOnlyList<WalkOracleFrame> actual =
[expectedFrame with { Events = truncated }];
WalkTranscriptSignatureDiff.Divergence? divergence =
WalkTranscriptSignatureDiff.FirstDivergence(expected, actual);
Assert.NotNull(divergence);
Assert.Equal(expectedFrame.Number, divergence!.Value.FrameNumber);
Assert.Equal(lastIndex, divergence.Value.Position);
Assert.Equal("<end of frame>", divergence.Value.Actual);
Assert.NotEqual("<end of frame>", divergence.Value.Expected);
}
finally
{
Console.SetOut(originalOut);
RenderingDiagnostics.DumpWalkTranscriptEnabled = previous;
}
}
}