acdream/tests/AcDream.Core.Tests/Physics/ShadowObjectRegistryMultiPartTests.cs
Erik 4abd1b5eb7 fix(physics): AP-152 — dispatch collision shapes BSP-first, at emission and at the cell flood
The register row predicted "catching or stopping on a doorway sill". That
symptom could not have been occurring. `Transition.BspOnlyDispatch`
(TransitionTypes.cs:1348, landed 2026-05-25 as A6.P7) already skipped both
primitive branches (:3911, :3954) whenever the target's wire PhysicsState
carries HAS_PHYSICS_BSP_PS, and ACE sets that bit from CSetup.HasPhysicsBSP
for every affected Setup. The extra primitive was never tested for collision.

The live defect was CELL MEMBERSHIP. The same shape list feeds
`ShadowObjectRegistry.BuildFloodSpheres`, which had no such guard and
preferred Cylinders over everything whenever any Cylinder existed — retail's
SECOND priority applied ahead of its first. For the 73 CylSphere+BSP Setups
acdream therefore flooded shadow cells from the cylinder and never from the
slab: an object absent from cells it physically occupies, which is the
#98 / #168 symptom class, not the door-collision class the row named.

Retail, re-disassembled from the PDB-paired binary (v11.4186, CodeView GUID
9e847e2f-777c-4bd9-886c-22256bb87f32, check_exe_pdb.py MATCH) rather than
taken from Binary Ninja, which drops flag tests:

  CPhysicsObj::FindObjCollisions @0x0050f050
    0x0050f165  test dword [esi+0xa8], 0x10000
    0x0050f16f  je   0x50f1a2        ; clear -> primitive dispatch
    0x0050f18d  call 0x518180        ; CPartArray::FindObjCollisions
    0x0050f19d  jmp  0x50f2b0        ; UNCONDITIONAL, past BOTH primitive loops
                                     ; (CylSphere 0x50f1a2, Sphere 0x50f21d)
    0x0050f1d6  jae  0x50f317        ; CylSphere loop exhausted -> RETURN
    0x0050f22f  je   0x50f31b        ; zero Spheres -> RETURN seeded OK_TS

  CPhysicsObj::calc_cross_cells @0x00515230
    0x00515285  test dword [esi+0xa8], 0x10000
    0x0051528f  jne  0x515305 -> CPhysicsObj::find_bbox_cell_list @0x00510fc0
    0x005152d1  call 0x52b9f0        ; cylsphere branch, below the jump
    0x005152fb  call 0x52b990        ; sorting-sphere branch, below the jump

Priority at both consumers: BSP -> CylSphere -> Sphere -> nothing. BSP wins.
Every address above was resolved back to its symbol by exact lookup in
named-retail/symbols.json.

Changes:

* `ShadowShapeBuilder.FromSetup` gains a step-0 dispatch gate. Steps 1 and 2
  are skipped entirely when any part's EFFECTIVE GfxObj carries a physics
  BSP. The gate and step 3 now share one `EffectivePartGfxObjId` helper, so
  they cannot read different identities — a gate on `setup.Parts` would,
  after an ObjDesc swap, suppress the primitives while step 3 emitted
  nothing and `Build` returned null, deleting the entity's collision.
  Emission order is unchanged. This also removes acdream's undeclared
  reliance on the server sending the flag: the gate is derived from the
  parts, exactly as CPartArray::CacheHasPhysicsBSP @0x00518110 derives it.

* `ShadowObjectRegistry.BuildFloodSpheres` now applies calc_cross_cells'
  own order: BSP, else Cylinder, else everything. Given the gate above this
  is a no-op for every shape list acdream produces (FromSetup is now
  exclusive; both landblock-static publishers already emit homogeneous
  lists), so the measured membership delta remains attributable to the
  gate alone. It is kept for the same reason BspOnlyDispatch is kept: retail
  genuinely dispatches here, and it guards a future additive producer.

`Transition.BspOnlyDispatch` is deliberately untouched.

Register: AP-152 RETIRED with its four false statements corrected — the risk
statement (the symptom was already inert); "small and centred at the part
origin" (max primitive is 6.714 m, and 0x0200086E's sphere origin is
(0.759, 0.165, 5.842)); the cottage door's "~14 cm base Sphere" (it is
0.100 m; 0.141 is Setup.Radius, which AP-22 proved is never collision
geometry); and naming one pinning test where two existed. AP-153/154/155
filed: retail's dispatch flag is cached once at InitPartArrayObject+0x7e
where acdream's gate is live; the query-time guard takes a client-derived
flag off the wire; and the static publishers emit Setup Spheres as
height-capped Cylinders while BuildFloodSpheres approximates retail's
bounding box with bounding spheres.

Tests. Both pinning tests corrected, neither deleted:
`FromSetup_DoorSetup_ProducesFourShapes` -> `..._EmitsBspPartsOnly`;
`FromSetup_DoorSetup_SphereAtExpectedLocalOffset` re-hosted on
`_ => false`, the DAT-real configuration for the 3,605 Sphere-only Setups.
`FromSetup_ScaleFactor_MultipliesAllRadiiAndOffsets` was the campaign's
eighth green test covering nothing — its assertions sat inside
`if (CollisionType == Cylinder)` on a fixture with zero CylSpheres, so only
`Scale == 2.0f` ever ran. Proved empirically: with the sphere radius scale
deleted, the old body passes and the corrected body fails. Three new facts:
the effective-identity gate, the App-layer CylSphere+BSP registration (no
App fixture combined the two before), and the flood-set dispatch. One new
installed-DAT sweep pins 172 affected Setups (73 CylSphere+BSP, 99
Sphere+BSP) behind external bucket controls, re-measured independently and
agreeing exactly with the filing commit's separate sweep.

All eight sabotages run and reported; every discriminating fact reddens in
the intended direction and only there. Clean Release build after deleting
every bin/obj: 0 errors. Complete suite 11,203 passed / 4 skipped / 0
failed, +5 on the 11,198 baseline at ec29a732 — exactly the five added
facts, no new skips.

Blast radius, corrected: the FromSetup half is graphical-only (its sole
production caller is LiveEntityCollisionBuilder in AcDream.App, which
AcDream.Headless cannot reference — Headless -> Runtime -> Core/Content).
The BuildFloodSpheres half lives in AcDream.Core and DOES execute in
Headless via LandblockPhysicsContentBuilder, but is behaviour-neutral there
because both of that builder's registrations pass homogeneous lists.
Headless suite green at 89/89.

NOT yet gated live: this changes shadow-cell membership for 22 Setups used
by 151 Door weenies and 38 stationary props. Needs a connected session.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-06 14:51:36 +02:00

329 lines
14 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using AcDream.Core.Physics;
using Xunit;
namespace AcDream.Core.Tests.Physics;
public class ShadowObjectRegistryMultiPartTests
{
private const uint LbId = 0xA9B40000u;
private const float OffX = 0f;
private const float OffY = 0f;
private static IReadOnlyList<ShadowShape> DoorShapes() => new[]
{
new ShadowShape(
GfxObjId: 0u,
LocalPosition: new Vector3(0f, 0f, 0.018f),
LocalRotation: Quaternion.Identity,
Scale: 1.0f,
CollisionType: ShadowCollisionType.Cylinder,
Radius: 0.100f,
CylHeight: 0.200f),
new ShadowShape(
GfxObjId: 0x010044B5u,
LocalPosition: Vector3.Zero,
LocalRotation: Quaternion.Identity,
Scale: 1.0f,
CollisionType: ShadowCollisionType.BSP,
Radius: 2.0f,
CylHeight: 0f),
new ShadowShape(
GfxObjId: 0x010044B6u,
LocalPosition: Vector3.Zero,
LocalRotation: Quaternion.Identity,
Scale: 1.0f,
CollisionType: ShadowCollisionType.BSP,
Radius: 2.0f,
CylHeight: 0f),
new ShadowShape(
GfxObjId: 0x010044B6u,
LocalPosition: Vector3.Zero,
LocalRotation: Quaternion.Identity,
Scale: 1.0f,
CollisionType: ShadowCollisionType.BSP,
Radius: 2.0f,
CylHeight: 0f)
};
[Fact]
public void RegisterMultiPart_FourShapes_AllShareEntityId()
{
var reg = new ShadowObjectRegistry();
const uint doorEntityId = 0x000F4244u;
reg.RegisterMultiPart(
entityId: doorEntityId,
entityWorldPos: new Vector3(132.6f, 17.1f, 94.08f),
entityWorldRot: Quaternion.Identity,
shapes: DoorShapes(),
state: 0x10008u,
flags: EntityCollisionFlags.None,
worldOffsetX: OffX,
worldOffsetY: OffY,
landblockId: LbId);
int found = 0;
foreach (var entry in reg.AllEntriesForDebug())
{
if (entry.EntityId == doorEntityId) found++;
}
Assert.True(found >= 4,
$"Expected at least 4 entries for door entity (one per shape); found {found}");
}
[Fact]
public void RegisterMultiPart_EmptyShapeList_NoOp()
{
var reg = new ShadowObjectRegistry();
reg.RegisterMultiPart(
entityId: 0x1u,
entityWorldPos: Vector3.Zero,
entityWorldRot: Quaternion.Identity,
shapes: System.Array.Empty<ShadowShape>(),
state: 0u,
flags: EntityCollisionFlags.None,
worldOffsetX: OffX, worldOffsetY: OffY, landblockId: LbId);
Assert.Equal(0, reg.TotalRegistered);
}
[Fact]
public void Deregister_RemovesAllParts()
{
var reg = new ShadowObjectRegistry();
const uint doorEntityId = 0x000F4244u;
reg.RegisterMultiPart(doorEntityId, new Vector3(132.6f, 17.1f, 94.08f),
Quaternion.Identity, DoorShapes(), 0x10008u,
EntityCollisionFlags.None, OffX, OffY, LbId);
reg.Deregister(doorEntityId);
Assert.Equal(0, reg.TotalRegistered);
foreach (var entry in reg.AllEntriesForDebug())
Assert.NotEqual(doorEntityId, entry.EntityId);
}
[Fact]
public void UpdatePhysicsState_PropagatesEtherealToAllParts()
{
var reg = new ShadowObjectRegistry();
const uint doorEntityId = 0x000F4244u;
reg.RegisterMultiPart(doorEntityId, new Vector3(132.6f, 17.1f, 94.08f),
Quaternion.Identity, DoorShapes(), 0x10008u,
EntityCollisionFlags.None, OffX, OffY, LbId);
reg.UpdatePhysicsState(doorEntityId, 0x1000Cu); // 0x10008 | 0x4
int updated = 0;
foreach (var entry in reg.AllEntriesForDebug())
{
if (entry.EntityId != doorEntityId) continue;
Assert.Equal(0x1000Cu, entry.State);
updated++;
}
Assert.True(updated >= 4, $"Expected all parts updated, only {updated} were");
}
[Fact]
public void RegisterMultiPart_PartsAcrossMultipleCells_AllCellsListed()
{
var reg = new ShadowObjectRegistry();
// Two shapes 30m apart in X — must span two outdoor 24m cells.
var shapes = new[]
{
new ShadowShape(0u, new Vector3( 0f, 0f, 0f), Quaternion.Identity, 1f,
ShadowCollisionType.Cylinder, 1f, 2f),
new ShadowShape(0u, new Vector3(30f, 0f, 0f), Quaternion.Identity, 1f,
ShadowCollisionType.Cylinder, 1f, 2f),
};
reg.RegisterMultiPart(0x1u, new Vector3(12f, 12f, 50f), Quaternion.Identity,
shapes, 0u, EntityCollisionFlags.None, OffX, OffY, LbId);
// Part 1 at world (12, 12) → cell (0,0) = LbId | 1
// Part 2 at world (42, 12) → cell (1,0) = LbId | 9
var entriesIn1 = reg.GetObjectsInCell(LbId | 1u);
var entriesIn9 = reg.GetObjectsInCell(LbId | 9u);
Assert.Contains(entriesIn1, e => e.EntityId == 0x1u);
Assert.Contains(entriesIn9, e => e.EntityId == 0x1u);
}
[Fact]
public void Register_SingleShapeCompat_Unchanged()
{
var reg = new ShadowObjectRegistry();
reg.Register(42u, 0x01000001u, new Vector3(12f, 12f, 50f),
Quaternion.Identity, 1f, OffX, OffY, LbId);
Assert.Equal(1, reg.TotalRegistered);
Assert.Single(reg.GetObjectsInCell(LbId | 1u),
e => e.EntityId == 42u);
}
[Fact]
public void UpdatePosition_MovesAllPartsWithEntity()
{
var reg = new ShadowObjectRegistry();
const uint movingEntityId = 0xA1u;
var shapes = new[]
{
new ShadowShape(0u, new Vector3(0f, 0f, 0f), Quaternion.Identity, 1f,
ShadowCollisionType.Cylinder, 0.5f, 1f),
new ShadowShape(0u, new Vector3(1f, 0f, 0f), Quaternion.Identity, 1f,
ShadowCollisionType.Cylinder, 0.5f, 1f),
};
reg.RegisterMultiPart(movingEntityId, new Vector3(10f, 10f, 50f),
Quaternion.Identity, shapes, 0u,
EntityCollisionFlags.None, OffX, OffY, LbId);
// Move entity to (50, 10, 50). Parts should be at (50, 10, 50) and (51, 10, 50).
reg.UpdatePosition(movingEntityId,
new Vector3(50f, 10f, 50f), Quaternion.Identity,
OffX, OffY, LbId);
Vector3 expectedPart0 = new(50f, 10f, 50f);
Vector3 expectedPart1 = new(51f, 10f, 50f);
var atNew = reg.AllEntriesForDebug().Where(e => e.EntityId == movingEntityId).ToList();
Assert.Equal(2, atNew.Count);
bool found0 = atNew.Any(e => Vector3.Distance(e.Position, expectedPart0) < 0.01f);
bool found1 = atNew.Any(e => Vector3.Distance(e.Position, expectedPart1) < 0.01f);
Assert.True(found0 && found1,
"Expected both parts at new world positions (50, 10, 50) and (51, 10, 50)");
}
[Fact]
public void Deregister_ClearsEntityShapesCache_NoStaleUpdatePositionRebuild()
{
// A6.P4 door fix (2026-05-24) regression: after Deregister, a stray
// UpdatePosition with the same entityId must NOT resurrect the entity
// via the _entityShapes path. The Deregister cleanup added in Task 4
// (which folded Task 6 into the multi-part registration commit) clears
// _entityShapes[entityId] alongside the cell-list cleanup.
var reg = new ShadowObjectRegistry();
const uint doorEntityId = 0x000F4244u;
reg.RegisterMultiPart(doorEntityId, new Vector3(132.6f, 17.1f, 94.08f),
Quaternion.Identity, DoorShapes(), 0x10008u,
EntityCollisionFlags.None, OffX, OffY, LbId);
reg.Deregister(doorEntityId);
// Stray UpdatePosition should be a no-op now (no entry to find AND
// no _entityShapes entry to rebuild from).
reg.UpdatePosition(doorEntityId, new Vector3(200f, 200f, 50f),
Quaternion.Identity, OffX, OffY, LbId);
Assert.Equal(0, reg.TotalRegistered);
}
// ---------------------------------------------------------------------
// AP-152 — cross-cell dispatch. CPhysicsObj::calc_cross_cells @0x00515230
// tests HAS_PHYSICS_BSP_PS at 0x00515285 and routes a BSP-bearing object
// to CPhysicsObj::find_bbox_cell_list @0x00510fc0 through
// 0x0051528f jne 0x515305. The cylsphere branch (0x005152d1
// CObjCell::find_cell_list @0x0052b9f0) and the sorting-sphere branch
// (0x005152fb ... @0x0052b990) are BOTH below that jump and unreachable
// from it. BuildFloodSpheres used to prefer Cylinders over everything
// whenever any Cylinder was present, which is retail's SECOND priority
// applied ahead of its first.
// ---------------------------------------------------------------------
/// <summary>Cells of the landblock that hold at least one row for owner.</summary>
private static List<uint> OutdoorCellsHolding(ShadowObjectRegistry reg, uint ownerId)
{
var cells = new List<uint>();
for (uint index = 1u; index <= 64u; index++)
{
uint cellId = LbId | index;
if (reg.GetObjectsInCell(cellId).Any(e => e.EntityId == ownerId))
cells.Add(cellId);
}
return cells;
}
private static ShadowShape Cyl(float radius) => new(
GfxObjId: 0u, LocalPosition: Vector3.Zero, LocalRotation: Quaternion.Identity,
Scale: 1f, CollisionType: ShadowCollisionType.Cylinder,
Radius: radius, CylHeight: radius * 2f);
private static ShadowShape Bsp(float radius) => new(
GfxObjId: 0x010044B5u, LocalPosition: Vector3.Zero, LocalRotation: Quaternion.Identity,
Scale: 1f, CollisionType: ShadowCollisionType.BSP,
Radius: radius, CylHeight: 0f);
private static List<uint> FloodCellsFor(params ShadowShape[] shapes)
{
var reg = new ShadowObjectRegistry();
const uint ownerId = 0xBEEF01u;
// Centre of the landblock's cell (1,1) so a 14 m footprint stays
// inside the block's own 8x8 outdoor grid on every side.
reg.RegisterMultiPart(
ownerId, new Vector3(36f, 36f, 50f), Quaternion.Identity,
shapes, 0x10008u, EntityCollisionFlags.None, OffX, OffY, LbId);
return OutdoorCellsHolding(reg, ownerId);
}
[Fact]
public void BuildFloodSpheres_BspBearingOwner_FloodsFromBspNotFromCylinder()
{
List<uint> cylinderOnly = FloodCellsFor(Cyl(0.5f));
List<uint> bspOnly = FloodCellsFor(Bsp(14f));
List<uint> mixed = FloodCellsFor(Cyl(0.5f), Bsp(14f));
// Controls: the two footprints must actually differ, or the fact below
// is satisfiable by any dispatch rule at all.
Assert.Equal([LbId | 10u], cylinderOnly);
Assert.True(bspOnly.Count > 1,
$"BSP footprint control failed: expected >1 cell, got {bspOnly.Count}");
// The fact: a mixed list floods from the BSP shapes, exactly as if the
// cylinder were not there. Retail 0x0051528f.
Assert.Equal(bspOnly, mixed);
Assert.NotEqual(cylinderOnly, mixed);
}
/// <summary>
/// The AP-152 delta end-to-end: a CylSphere+BSP Setup (73 of the 172
/// affected installed Setups are this shape) registered through the
/// production builder. Before the fix the emitted list carried both, and
/// BuildFloodSpheres' cylinder preference confined the owner to the
/// cylinder's cell while its slab BSP reached further — an object absent
/// from shadow cells it physically occupies, the #98 / #168 symptom class.
/// </summary>
[Fact]
public void FromSetup_CylSphereAndBspSetup_FloodsTheBspFootprint()
{
const uint part = 0x010044B5u;
var setup = new DatReaderWriter.DBObjs.Setup
{
Parts = { part },
CylSpheres = { new DatReaderWriter.Types.CylSphere
{ Radius = 0.5f, Height = 1f, Origin = Vector3.Zero } },
};
IReadOnlyList<ShadowShape> raw =
ShadowShapeBuilder.FromSetup(setup, entScale: 1f, hasPhysicsBsp: id => id == part);
// Production substitutes the real BSP bounding radius at registration
// time (LiveEntityCollisionBuilder.Build); 14 m stands in for a slab
// wide enough to leave its own landcell.
var shapes = raw.Select(s => s.CollisionType == ShadowCollisionType.BSP
? s with { Radius = 14f }
: s).ToList();
ShadowShape only = Assert.Single(shapes);
Assert.Equal(ShadowCollisionType.BSP, only.CollisionType);
var reg = new ShadowObjectRegistry();
const uint ownerId = 0xBEEF02u;
reg.RegisterMultiPart(
ownerId, new Vector3(36f, 36f, 50f), Quaternion.Identity,
shapes, 0x10008u, EntityCollisionFlags.None, OffX, OffY, LbId);
List<uint> cells = OutdoorCellsHolding(reg, ownerId);
Assert.Contains(LbId | 10u, cells);
Assert.True(cells.Count > 1,
$"Expected the slab footprint to span more than its own landcell; got {cells.Count}");
}
}