chore(phys): A6.P3 #98 triage — revert neg-poly + bldg-check experiments

Triage step from the plan at C:\Users\erikn\.claude\plans\
i-did-some-work-sharded-acorn.md. Four sessions on issue #98 left the
worktree dirty with ~1352 LOC of mixed work. This commit splits the
work into "keep" (defensible + diagnostic) and "drop" (failed
experiments), then commits the keep set with the drops removed.

Plan asked for three commits (diag / fix / revert); consolidated to one
because the diagnostic emits in TransitionTypes.cs are tightly
interleaved with the multi-sphere CellTransit calls and the CellId
switch. Hunk-level splitting in those files for marginal bisect
granularity didn't justify the misclick risk.

Reverted entirely (failed experiments per slice 7 handoff):
- src/AcDream.Core/Physics/PhysicsDataCache.cs — neg-poly storage
  fields (Stippling, PosSurface, NegSurface, HasNegativeSide,
  IsNegativeSide, NegativeSide).
- src/AcDream.Core/Physics/ShadowObjectRegistry.cs — isBuilding flag
  propagation through Register / ShadowEntry.
- tests/AcDream.Core.Tests/Physics/BSPQueryTests.cs — 165 lines of
  PolygonWithNegativeSide_* tests.
- tests/AcDream.Core.Tests/Physics/ShadowObjectRegistryTests.cs —
  isBuilding propagation tests.
- src/AcDream.Core/World/WorldEntity.cs — IsLandblockBuilding field
  (no consumer once ShadowObjectRegistry.isBuilding is gone).
- src/AcDream.Core/World/LandblockLoader.cs — IsLandblockBuilding=true
  setter on building entities (kept BuildBuildingTerrainCells).
- src/AcDream.App/Rendering/GameWindow.cs — isBuilding: arg passed to
  ShadowObjects.Register.
- src/AcDream.Core/Physics/BSPQuery.cs — TryAdjustWalkableSide /
  IsWalkableAt helpers, their callers, the Path 5 / Path 6 neg-poly
  branch split, the BldgCheck-tied clearCell conditional, and the
  neg-poly ResolveCellPolygons writes.
- src/AcDream.Core/Physics/PhysicsDiagnostics.cs — neg-poly fields
  in the poly-dump format.
- src/AcDream.Core/Physics/TransitionTypes.cs — SpherePath.BldgCheck +
  SpherePath.HitsInteriorCell fields and every consumer, the
  savedBldgCheck try/finally around FindCollisions, and the neg-poly
  format additions to the dump-on-error helper.
- src/AcDream.Core/Physics/CellTransit.cs — FindCellSet overloads
  with hitsInteriorCell out-param and the BuildCellSetAndPickContaining
  out-param threading.

Kept (defensible correctness fixes + diagnostic infrastructure):
- src/AcDream.App/Rendering/GameWindow.cs — render-vs-physics cell
  origin split: the 0.02m render lift no longer leaks into physics
  BSP caching. lb.BuildingTerrainCells threaded into LandblockMesh.Build.
- src/AcDream.Core/World/LoadedLandblock.cs — BuildingTerrainCells
  record field.
- src/AcDream.Core/World/LandblockLoader.cs — BuildBuildingTerrainCells
  (cy*8+cx from LandBlockInfo.Buildings).
- src/AcDream.Core/Terrain/LandblockMesh.cs — hiddenTerrainCells
  param that collapses owned-cell triangles to a zero-area degenerate.
- src/AcDream.App/Streaming/{GpuWorldState,LandblockStreamer}.cs —
  mechanical BuildingTerrainCells threading through LoadedLandblock
  reconstructions.
- src/AcDream.Core/Physics/CellTransit.cs — multi-sphere
  FindTransitCellsSphere variant + multi-sphere AddAllOutsideCells +
  FindCellSet(IReadOnlyList<Sphere>, …) overload + the
  BSPQuery.SphereIntersectsCellBsp call for loaded neighbours. Matches
  retail CObjCell::find_cell_list / CEnvCell::find_transit_cells.
- src/AcDream.Core/Physics/TransitionTypes.cs — multi-sphere FindCellSet
  call site, retail-faithful CellId switch after CheckOtherCells, the
  outdoor-landcell terrain-walkable fallback in CheckOtherCells, and
  the full diagnostic suite ([step-walk], [walkable-nearest],
  [issue98-walkable-detail], [cell-set-summary], LastBspHitPoly
  emits).
- src/AcDream.Core/Physics/PhysicsDiagnostics.cs — ProbeStepWalkEnabled
  gate (ACDREAM_PROBE_STEP_WALK=1) + LogStepWalk helper + FormatVector
  / FormatPlane utilities. All emit-gated.
- src/AcDream.Core/Physics/BSPQuery.cs — diagnostic emits to
  LastBspHitPoly at four sites in SphereIntersectsPolyInternal /
  the placement adjustment path.
- Test files for the kept work: CellTransitFindCellSetTests,
  CellTransitFindTransitCellsSphereTests, PhysicsDiagnosticsTests,
  TransitionCheckOtherCellsTests, LandblockMeshTests,
  LandblockLoaderTests.

Verification:
- dotnet build: green, 0 errors, 3 pre-existing warnings.
- dotnet test: 1156 passed + 8 failed (baseline was 1148 + 8 pre-
  existing; the +8 passing are the new tests for the kept defensible
  work). Same 8 pre-existing failures, no new regressions.

Backup of pre-triage worktree state in stash@{0}.

A6.P3 #98 is still open; this is the apparatus-prep step, not a fix.
Next: cell-dump probe (Step 2 of the plan).
This commit is contained in:
Erik 2026-05-23 15:11:49 +02:00
parent 111aa3e59d
commit 35b37dfb5f
16 changed files with 930 additions and 58 deletions

View file

@ -134,4 +134,43 @@ public class CellTransitFindCellSetTests
Assert.Equal(0xA9B40001u, containing);
Assert.True(cellSet.Count >= 2, $"Expected ≥2 cells in set (primary + east neighbour), got {cellSet.Count}");
}
[Fact]
public void IndoorSeed_ExitPortalTouchedOnlyBySecondSphere_AddsOutdoorLandcell()
{
// Retail CObjCell::find_cell_list passes every SPHEREPATH sphere into
// CEnvCell::find_transit_cells. When any sphere straddles an outdoor
// exit portal, CLandCell::add_all_outside_cells runs for the whole
// sphere array.
uint lbPrefix = 0xA9B40000u;
float lbX = ((lbPrefix >> 24) & 0xFFu) * 192f;
float lbY = ((lbPrefix >> 16) & 0xFFu) * 192f;
var cellTransform = Matrix4x4.CreateTranslation(new Vector3(lbX, lbY, 0f));
var exitCell = MakeCellWithPortalAtRightWall(
cellTransform,
otherCellId: 0xFFFF,
flags: 0);
var cache = new PhysicsDataCache();
cache.RegisterCellStructForTest(0xA9B40100u, exitCell);
var spheres = new[]
{
// Foot sphere is not near the exit portal plane at local x=2.5.
new Sphere { Origin = new Vector3(lbX + 0.0f, lbY + 12.0f, 2.5f), Radius = 0.5f },
// Head sphere reaches the exit portal plane and should trigger
// outdoor landcell expansion.
new Sphere { Origin = new Vector3(lbX + 2.0f, lbY + 12.0f, 3.2f), Radius = 0.5f },
};
uint containing = CellTransit.FindCellSet(
cache, spheres, spheres.Length,
currentCellId: 0xA9B40100u,
out var cellSet);
Assert.Equal(0xA9B40100u, containing);
Assert.Contains(0xA9B40100u, cellSet);
Assert.Contains(0xA9B40001u, cellSet);
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Numerics;
using DatReaderWriter.Types;
using AcDream.Core.Physics;
using Xunit;
@ -7,6 +8,20 @@ namespace AcDream.Core.Tests.Physics;
public class CellTransitFindTransitCellsSphereTests
{
private static CellBSPTree SinglePlaneCellBsp()
{
var leaf = new CellBSPNode { Type = DatReaderWriter.Enums.BSPNodeType.Leaf };
return new CellBSPTree
{
Root = new CellBSPNode
{
// Local x >= 0 is inside this synthetic cell.
SplittingPlane = new Plane(new Vector3(1f, 0f, 0f), 0f),
PosNode = leaf,
}
};
}
private static CellPhysics MakeCellWithPortalAtRightWall(
Matrix4x4 worldTransform, uint otherCellId, ushort flags)
{
@ -88,6 +103,77 @@ public class CellTransitFindTransitCellsSphereTests
Assert.DoesNotContain(0xA9B40101u, candidates);
}
[Fact]
public void LoadedNeighbor_SphereIntersectsNeighborCellBsp_AddsEvenWhenPortalHintWouldReject()
{
// Retail CEnvCell::find_transit_cells uses the loaded neighbour's
// CellBSP sphere-overlap test. The portal-plane side test is only
// an unloaded-cell hint. flags=2 makes the old heuristic reject
// this world position even though the sphere overlaps cell B.
var cellA = MakeCellWithPortalAtRightWall(Matrix4x4.Identity, otherCellId: 0x0101, flags: 2);
var cellBT = Matrix4x4.CreateTranslation(new Vector3(5f, 0f, 0f));
Matrix4x4.Invert(cellBT, out var cellBInv);
var cellB = new CellPhysics
{
WorldTransform = cellBT,
InverseWorldTransform = cellBInv,
Resolved = new Dictionary<ushort, ResolvedPolygon>(),
CellBSP = SinglePlaneCellBsp(),
};
var cache = new PhysicsDataCache();
cache.RegisterCellStructForTest(0xA9B40100u, cellA);
cache.RegisterCellStructForTest(0xA9B40101u, cellB);
// Cell B local center is x=-0.25, radius=0.5, so the sphere
// straddles x=0 and intersects the cell volume.
var worldSphereCenter = new Vector3(4.75f, 0f, 2.5f);
var candidates = new HashSet<uint>();
CellTransit.FindTransitCellsSphere(
cache, cellA, currentCellId: 0xA9B40100u,
worldSphereCenter, sphereRadius: 0.5f, candidates, out bool exitOutside);
Assert.Contains(0xA9B40101u, candidates);
Assert.False(exitOutside);
}
[Fact]
public void LoadedNeighbor_SphereOutsideNeighborCellBsp_DoesNotUsePortalHintFallback()
{
// With a loaded neighbour, retail trusts sphere_intersects_cell.
// This guards against adding the neighbour merely because the
// current-cell portal plane would have accepted the sphere.
var cellA = MakeCellWithPortalAtRightWall(Matrix4x4.Identity, otherCellId: 0x0101, flags: 0);
var cellBT = Matrix4x4.CreateTranslation(new Vector3(5f, 0f, 0f));
Matrix4x4.Invert(cellBT, out var cellBInv);
var cellB = new CellPhysics
{
WorldTransform = cellBT,
InverseWorldTransform = cellBInv,
Resolved = new Dictionary<ushort, ResolvedPolygon>(),
CellBSP = SinglePlaneCellBsp(),
};
var cache = new PhysicsDataCache();
cache.RegisterCellStructForTest(0xA9B40100u, cellA);
cache.RegisterCellStructForTest(0xA9B40101u, cellB);
// Current portal-plane heuristic would add this (near x=2.5), but
// in cell B local space x=-1.95 with radius=0.5 is fully outside.
var worldSphereCenter = new Vector3(3.05f, 0f, 2.5f);
var candidates = new HashSet<uint>();
CellTransit.FindTransitCellsSphere(
cache, cellA, currentCellId: 0xA9B40100u,
worldSphereCenter, sphereRadius: 0.5f, candidates, out bool exitOutside);
Assert.DoesNotContain(0xA9B40101u, candidates);
Assert.False(exitOutside);
}
[Fact]
public void ExitPortal_SphereStraddlesPortalPlane_FlagsCheckOutside()
{
@ -105,4 +191,29 @@ public class CellTransitFindTransitCellsSphereTests
Assert.True(exitOutside);
}
[Fact]
public void ExitPortal_SecondSphereStraddlesPortalPlane_FlagsCheckOutside()
{
// Retail passes the whole SPHEREPATH global_sphere array into
// CEnvCell::find_transit_cells. The head sphere can be the one that
// overlaps an exit portal while the foot sphere is still clear.
var exitCell = MakeCellWithPortalAtRightWall(Matrix4x4.Identity, otherCellId: 0xFFFF, flags: 0);
var cache = new PhysicsDataCache();
cache.RegisterCellStructForTest(0xA9B40100u, exitCell);
var spheres = new[]
{
new Sphere { Origin = new Vector3(0.0f, 0f, 2.5f), Radius = 0.5f },
new Sphere { Origin = new Vector3(2.0f, 0f, 3.2f), Radius = 0.5f },
};
var candidates = new HashSet<uint>();
CellTransit.FindTransitCellsSphere(
cache, exitCell, currentCellId: 0xA9B40100u,
spheres, spheres.Length, candidates, out bool exitOutside);
Assert.True(exitOutside);
}
}

View file

@ -118,4 +118,27 @@ public class PhysicsDiagnosticsTests
PhysicsDiagnostics.ProbePushBackEnabled = initial;
}
}
// -----------------------------------------------------------------------
// ProbeStepWalkEnabled - flag gates the [step-walk] emission path.
// A6.P3 issue #98 (2026-05-23).
// -----------------------------------------------------------------------
[Fact]
public void ProbeStepWalk_StaticApi_Roundtrip()
{
bool initial = PhysicsDiagnostics.ProbeStepWalkEnabled;
try
{
PhysicsDiagnostics.ProbeStepWalkEnabled = true;
Assert.True(PhysicsDiagnostics.ProbeStepWalkEnabled);
PhysicsDiagnostics.ProbeStepWalkEnabled = false;
Assert.False(PhysicsDiagnostics.ProbeStepWalkEnabled);
}
finally
{
PhysicsDiagnostics.ProbeStepWalkEnabled = initial;
}
}
}

View file

@ -139,4 +139,33 @@ public class TransitionCheckOtherCellsTests
Assert.Equal(TransitionState.OK, result);
}
[Fact]
public void CheckOtherCells_OutdoorLandcellCandidate_UsesTerrainWalkable()
{
var engine = new PhysicsEngine();
engine.DataCache = new PhysicsDataCache();
var heights = new byte[81];
Array.Fill(heights, (byte)0);
var ht = new float[256];
for (int i = 0; i < 256; i++) ht[i] = i * 1.0f;
engine.AddLandblock(0xA9B4FFFFu, new TerrainSurface(heights, ht),
Array.Empty<CellSurface>(), Array.Empty<PortalPlane>(),
worldOffsetX: 0f, worldOffsetY: 0f);
var t = MakeTransition(contactFlag: true);
t.SpherePath.InitPath(new Vector3(10f, 10f, -0.28f), new Vector3(10f, 10f, -0.28f),
cellId: 0xA9B40147u, sphereRadius: 0.48f);
var footCenter = new Vector3(10f, 10f, 0.20f);
var cellSet = new HashSet<uint> { 0xA9B40001u };
var result = t.CheckOtherCells(engine, footCenter, 0.48f, cellSet);
Assert.Equal(TransitionState.Adjusted, result);
Assert.True(t.CollisionInfo.ContactPlaneValid);
Assert.Equal(0xA9B40001u, t.CollisionInfo.ContactPlaneCellId);
Assert.True(t.SpherePath.CheckPos.Z > -0.28f);
}
}

View file

@ -54,6 +54,35 @@ public class LandblockMeshTests
Assert.Equal(128 * 3, mesh.Indices.Length);
}
[Fact]
public void Build_HiddenTerrainCell_PreservesCountsAndDegeneratesOnlyThatCell()
{
var block = BuildFlatLandBlock();
var cache = new Dictionary<uint, SurfaceInfo>();
int hiddenCell = (3 * LandblockMesh.CellsPerSide) + 5;
var mesh = LandblockMesh.Build(
block,
0,
0,
IdentityHeightTable,
MakeContext(),
cache,
new HashSet<int> { hiddenCell });
Assert.Equal(LandblockMesh.VerticesPerLandblock, mesh.Vertices.Length);
Assert.Equal(LandblockMesh.VerticesPerLandblock, mesh.Indices.Length);
int hiddenBase = hiddenCell * LandblockMesh.VerticesPerCell;
for (int i = 0; i < LandblockMesh.VerticesPerCell; i++)
Assert.Equal((uint)hiddenBase, mesh.Indices[hiddenBase + i]);
int visibleCell = hiddenCell + 1;
int visibleBase = visibleCell * LandblockMesh.VerticesPerCell;
for (int i = 0; i < LandblockMesh.VerticesPerCell; i++)
Assert.Equal((uint)(visibleBase + i), mesh.Indices[visibleBase + i]);
}
[Fact]
public void Build_Vertices_CoverExactly192x192WorldUnits()
{

View file

@ -117,6 +117,35 @@ public class LandblockLoaderTests
Assert.Empty(entities);
}
[Fact]
public void BuildBuildingTerrainCells_UsesBuildingsOnlyAndMapsToMeshCellIndex()
{
var info = new LandBlockInfo
{
Objects =
{
new Stab
{
Id = 0x02000001u,
Frame = new Frame { Origin = new Vector3(120, 72, 0) },
},
},
Buildings =
{
new BuildingInfo
{
ModelId = 0x020000AAu,
Frame = new Frame { Origin = new Vector3(141.5f, 7.2f, 94f) },
},
},
};
var cells = LandblockLoader.BuildBuildingTerrainCells(info);
Assert.Single(cells);
Assert.Contains(5, cells); // cy=0, cx=5 => mesh index cy * 8 + cx.
}
[Fact]
public void BuildEntitiesFromInfo_WithLandblockId_NamespacesIdsForGlobalUniqueness()
{