acdream/tests/AcDream.Core.Tests/Physics/TransitionCheckOtherCellsTests.cs
Erik 35b37dfb5f 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).
2026-05-23 15:11:49 +02:00

171 lines
6.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Numerics;
using DatReaderWriter.Enums;
using DatReaderWriter.Types;
using AcDream.Core.Physics;
using Xunit;
namespace AcDream.Core.Tests.Physics;
/// <summary>
/// Unit tests for the result-combine helper used by
/// <see cref="Transition.CheckOtherCells"/>. The iteration / per-cell
/// BSP-query parts are covered end-to-end by
/// <see cref="FindEnvCollisionsMultiCellTests"/>; this file pins the
/// retail-faithful halt semantics that
/// <c>acclient_2013_pseudo_c.txt:272739-272752</c> spells out.
/// </summary>
public class TransitionCheckOtherCellsTests
{
private static Transition MakeTransition(bool contactFlag = false)
{
var t = new Transition();
t.SpherePath.InitPath(Vector3.Zero, Vector3.Zero, cellId: 0xA9B40100u, sphereRadius: 0.48f);
t.ObjectInfo.State = contactFlag ? ObjectInfoState.Contact : ObjectInfoState.None;
// Pre-set CP fields to non-default so the Slid-clears-CP assertion
// can detect the clear.
t.CollisionInfo.ContactPlaneValid = true;
t.CollisionInfo.ContactPlaneIsWater = true;
return t;
}
[Fact]
public void OK_ContinuesIteration_DoesNotMutate()
{
var t = MakeTransition();
bool halt = t.ApplyOtherCellResult(TransitionState.OK, out var finalState);
Assert.False(halt);
Assert.Equal(TransitionState.OK, finalState);
Assert.True(t.CollisionInfo.ContactPlaneValid);
Assert.True(t.CollisionInfo.ContactPlaneIsWater);
Assert.False(t.CollisionInfo.CollidedWithEnvironment);
}
[Fact]
public void Collided_HaltsAndSetsCollidedWithEnvironment_WhenNotInContact()
{
var t = MakeTransition(contactFlag: false);
bool halt = t.ApplyOtherCellResult(TransitionState.Collided, out var finalState);
Assert.True(halt);
Assert.Equal(TransitionState.Collided, finalState);
Assert.True(t.CollisionInfo.CollidedWithEnvironment);
}
[Fact]
public void Collided_DoesNotSetCollidedWithEnvironment_WhenInContact()
{
// Retail oracle gating: the CollidedWithEnvironment flip mirrors
// the existing primary-cell behavior in FindEnvCollisions —
// skipped when ObjectInfo.State has Contact bit set.
var t = MakeTransition(contactFlag: true);
bool halt = t.ApplyOtherCellResult(TransitionState.Collided, out var finalState);
Assert.True(halt);
Assert.Equal(TransitionState.Collided, finalState);
Assert.False(t.CollisionInfo.CollidedWithEnvironment);
}
[Fact]
public void Adjusted_HaltsAndSetsCollidedWithEnvironment_WhenNotInContact()
{
var t = MakeTransition(contactFlag: false);
bool halt = t.ApplyOtherCellResult(TransitionState.Adjusted, out var finalState);
Assert.True(halt);
Assert.Equal(TransitionState.Adjusted, finalState);
Assert.True(t.CollisionInfo.CollidedWithEnvironment);
}
[Fact]
public void Slid_HaltsAndClearsContactPlaneFields()
{
// Retail oracle: acclient_2013_pseudo_c.txt:272746-272750
// case 4:
// this->collision_info.contact_plane_valid = 0;
// this->collision_info.contact_plane_is_water = 0;
// return result;
var t = MakeTransition();
Assert.True(t.CollisionInfo.ContactPlaneValid); // pre-condition
Assert.True(t.CollisionInfo.ContactPlaneIsWater); // pre-condition
bool halt = t.ApplyOtherCellResult(TransitionState.Slid, out var finalState);
Assert.True(halt);
Assert.Equal(TransitionState.Slid, finalState);
Assert.False(t.CollisionInfo.ContactPlaneValid);
Assert.False(t.CollisionInfo.ContactPlaneIsWater);
}
[Fact]
public void CheckOtherCells_CellWithNullBspRoot_IsSkippedNoCrash()
{
// Iteration safety: a CellPhysics in the candidate set with
// `BSP = null` (loaded for render but not physics) must be skipped,
// not crash. Matches the spec's R2 guard at design §Edge cases E2.
var cell = new CellPhysics
{
BSP = null, // <-- the guard target
WorldTransform = Matrix4x4.Identity,
InverseWorldTransform = Matrix4x4.Identity,
Resolved = new Dictionary<ushort, ResolvedPolygon>(),
};
var engine = new PhysicsEngine();
engine.DataCache = new PhysicsDataCache(); // PhysicsEngine has nullable DataCache
// FindEnvCollisions has terrain probes downstream; populate a
// minimal landblock so the cache + engine are coherent. The cell
// we test against doesn't need a real landblock entry.
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);
engine.DataCache.RegisterCellStructForTest(0xA9B40157u, cell);
var t = MakeTransition();
var cellSet = new HashSet<uint> { 0xA9B40157u };
// Call CheckOtherCells directly via the internal seam.
var result = t.CheckOtherCells(engine, Vector3.Zero, 0.48f, cellSet);
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);
}
}