acdream/tests/AcDream.Core.Tests/Physics/ShadowShapeBuilderTests.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

260 lines
10 KiB
C#

using System;
using System.Linq;
using System.Numerics;
using AcDream.Core.Physics;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Enums;
using DatReaderWriter.Types;
using Xunit;
namespace AcDream.Core.Tests.Physics;
public class ShadowShapeBuilderTests
{
/// <summary>
/// Synthetic Setup mirroring live dump of 0x020019FF (cottage door)
/// captured 2026-05-24: 0 cylSpheres, 1 sphere (r=0.100, origin=(0,0,0.018)),
/// 3 parts (0x010044B5 + 0x010044B6 + 0x010044B6), setup.Radius=0.141,
/// setup.Height=0.200. PlacementFrames[Default] has identity transforms
/// for all 3 parts.
/// </summary>
private static Setup CreateDoorSetup()
{
var setup = new Setup
{
Radius = 0.141f,
Height = 0.200f,
StepUpHeight = 0.090f,
StepDownHeight = 0.090f,
Parts = { 0x010044B5u, 0x010044B6u, 0x010044B6u },
Spheres =
{
new Sphere { Radius = 0.100f, Origin = new Vector3(0f, 0f, 0.018f) }
},
PlacementFrames =
{
[Placement.Default] = new AnimationFrame(3)
{
Frames =
{
new Frame { Origin = Vector3.Zero, Orientation = Quaternion.Identity },
new Frame { Origin = Vector3.Zero, Orientation = Quaternion.Identity },
new Frame { Origin = Vector3.Zero, Orientation = Quaternion.Identity }
}
}
}
};
return setup;
}
/// <summary>
/// AP-152, corrected 2026-08-06 (was <c>FromSetup_DoorSetup_ProducesFourShapes</c>,
/// which pinned the additive emission as intended).
///
/// <para>
/// Retail dispatches EXCLUSIVELY and BSP wins.
/// <c>CPhysicsObj::FindObjCollisions</c> @0x0050f050 tests
/// <c>HAS_PHYSICS_BSP_PS</c> first (<c>0x0050f165
/// test dword [esi+0xa8],0x10000</c> / <c>0x0050f16f je 0x50f1a2</c>) and
/// leaves the BSP branch through the UNCONDITIONAL
/// <c>0x0050f19d jmp 0x50f2b0</c>, which is past both the CylSphere loop
/// (0x50f1a2) and the Sphere loop (0x50f21d).
/// <c>CPhysicsObj::calc_cross_cells</c> @0x00515230 tests the same flag at
/// 0x00515285 and routes to <c>find_bbox_cell_list</c> @0x00510fc0.
/// So the cottage door's 0.100 m base Sphere is neither tested for
/// collision nor used for cell membership — only the three slab BSP parts.
/// </para>
/// </summary>
[Fact]
public void FromSetup_DoorSetup_EmitsBspPartsOnly()
{
var setup = CreateDoorSetup();
Func<uint, bool> hasBsp = id => id == 0x010044B5u || id == 0x010044B6u;
var shapes = ShadowShapeBuilder.FromSetup(setup, entScale: 1.0f, hasBsp);
Assert.Equal(3, shapes.Count);
Assert.All(shapes, s => Assert.Equal(ShadowCollisionType.BSP, s.CollisionType));
Assert.DoesNotContain(shapes, s => s.CollisionType == ShadowCollisionType.Sphere);
Assert.DoesNotContain(shapes, s => s.CollisionType == ShadowCollisionType.Cylinder);
}
/// <summary>
/// AP-152, re-hosted 2026-08-06 on <c>hasPhysicsBsp: _ => false</c> — the
/// DAT-real configuration for the 3,605 Sphere-only Setups. The fact
/// itself is unchanged and still live: a Setup Sphere emits a TRUE
/// <see cref="ShadowCollisionType.Sphere"/> (not a height-capped
/// Cylinder), passing its local offset and radius through.
/// <c>ShadowCollisionType.Sphere</c> is produced at exactly one site in
/// <c>src/</c>, and it is the premise of the whole CSphere family port.
/// Retail: <c>CSphere::intersects_sphere</c> @0x00537A80 uses 3-D
/// distance, so there is no height cap.
/// </summary>
[Fact]
public void FromSetup_DoorSetup_SphereAtExpectedLocalOffset()
{
var setup = CreateDoorSetup();
var shapes = ShadowShapeBuilder.FromSetup(setup, 1.0f, _ => false);
var sphereShape = Assert.Single(shapes);
Assert.Equal(ShadowCollisionType.Sphere, sphereShape.CollisionType);
Assert.Equal(0f, sphereShape.LocalPosition.X, 4);
Assert.Equal(0f, sphereShape.LocalPosition.Y, 4);
Assert.Equal(0.018f, sphereShape.LocalPosition.Z, 4);
Assert.Equal(0.100f, sphereShape.Radius, 4);
// CylHeight must be 0 — spheres have no height cap.
Assert.Equal(0f, sphereShape.CylHeight, 4);
}
/// <summary>
/// AP-152 trap 1. The step-0 dispatch gate and the step-3 emission must
/// read the SAME part identities. If the gate read <c>setup.Parts</c>
/// while step 3 read the installed <c>AnimPartChanged</c> replacements,
/// a swap could suppress the primitives while step 3 emitted nothing —
/// <c>LiveEntityCollisionBuilder.Build</c> would then return null and the
/// entity's collision would disappear entirely.
/// </summary>
[Fact]
public void FromSetup_DispatchGateReadsTheEffectivePartIdentities()
{
const uint basePart = 0x010044B5u;
const uint replacementWithBsp = 0x0100AA01u;
var setup = new Setup
{
Parts = { basePart },
CylSpheres = { new CylSphere { Radius = 0.4f, Height = 1.2f, Origin = Vector3.Zero } },
};
Func<uint, bool> hasBsp = id => id == replacementWithBsp;
var swapped = ShadowShapeBuilder.FromSetup(
setup, 1.0f, hasBsp, effectivePartGfxObjIds: [replacementWithBsp]);
var unswapped = ShadowShapeBuilder.FromSetup(setup, 1.0f, hasBsp);
// Replacement carries the BSP -> BSP wins, the CylSphere is suppressed.
ShadowShape swappedShape = Assert.Single(swapped);
Assert.Equal(ShadowCollisionType.BSP, swappedShape.CollisionType);
Assert.Equal(replacementWithBsp, swappedShape.GfxObjId);
// Base identity has no BSP -> no BSP shape exists, so the CylSphere
// must survive. A gate reading setup.Parts would agree here and
// disagree above; a gate reading nothing at all would disagree here.
ShadowShape unswappedShape = Assert.Single(unswapped);
Assert.Equal(ShadowCollisionType.Cylinder, unswappedShape.CollisionType);
Assert.Equal(0.4f, unswappedShape.Radius, 4);
}
[Fact]
public void FromSetup_PartWithoutBsp_SkipsBspShape()
{
var setup = CreateDoorSetup();
Func<uint, bool> hasBsp = id => id == 0x010044B5u;
var shapes = ShadowShapeBuilder.FromSetup(setup, 1.0f, hasBsp);
int bspCount = 0;
foreach (var s in shapes)
if (s.CollisionType == ShadowCollisionType.BSP) bspCount++;
Assert.Equal(1, bspCount);
}
[Fact]
public void FromSetup_EffectivePartIdentitiesControlPhysicsBspSelection()
{
const uint replacementWithBsp = 0x0100AA01u;
const uint replacementWithoutBsp = 0x0100AA02u;
var setup = new Setup
{
Parts = { 0x010044B5u, 0x010044B6u },
};
var shapes = ShadowShapeBuilder.FromSetup(
setup,
entScale: 1f,
hasPhysicsBsp: id => id == replacementWithBsp,
effectivePartGfxObjIds: [replacementWithBsp, replacementWithoutBsp]);
ShadowShape shape = Assert.Single(shapes);
Assert.Equal(replacementWithBsp, shape.GfxObjId);
}
[Fact]
public void FromSetup_CreatureWithCylSpheres_OnlyEmitsCylinders()
{
var setup = new Setup
{
Parts = { 0x02000001u },
CylSpheres =
{
new CylSphere { Radius = 0.40f, Height = 1.20f, Origin = new Vector3(0, 0, 0.6f) }
},
Spheres =
{
new Sphere { Radius = 0.50f, Origin = new Vector3(0, 0, 0.7f) }
}
};
var shapes = ShadowShapeBuilder.FromSetup(setup, 1.0f, _ => false);
Assert.Single(shapes);
Assert.Equal(ShadowCollisionType.Cylinder, shapes[0].CollisionType);
Assert.Equal(0.40f, shapes[0].Radius, 3);
Assert.Equal(1.20f, shapes[0].CylHeight, 3);
}
/// <summary>
/// Corrected 2026-08-06 (AP-152 §11.5). This test used to run
/// <c>CreateDoorSetup()</c> — which has ZERO CylSpheres — and then assert
/// radius/offset scaling inside
/// <c>if (s.CollisionType == ShadowCollisionType.Cylinder)</c>. That
/// branch had been unreachable since Setup Spheres started emitting
/// <see cref="ShadowCollisionType.Sphere"/> (2026-06-24), so the only
/// assertion that ever executed was <c>Scale == 2.0f</c>: the name
/// promised radius and offset scaling and pinned neither. Both primitive
/// kinds are now asserted unconditionally, on fixtures that actually
/// emit them.
/// </summary>
[Fact]
public void FromSetup_ScaleFactor_MultipliesAllRadiiAndOffsets()
{
var sphereShape = Assert.Single(
ShadowShapeBuilder.FromSetup(CreateDoorSetup(), entScale: 2.0f, _ => false));
Assert.Equal(ShadowCollisionType.Sphere, sphereShape.CollisionType);
Assert.Equal(2.0f, sphereShape.Scale, 3);
Assert.Equal(0.200f, sphereShape.Radius, 3); // 0.100 * 2
Assert.Equal(0.036f, sphereShape.LocalPosition.Z, 3); // 0.018 * 2
var cylSetup = new Setup
{
CylSpheres =
{
new CylSphere { Radius = 0.40f, Height = 1.20f, Origin = new Vector3(0.1f, 0.2f, 0.6f) }
}
};
var cylShape = Assert.Single(
ShadowShapeBuilder.FromSetup(cylSetup, entScale: 2.0f, _ => false));
Assert.Equal(ShadowCollisionType.Cylinder, cylShape.CollisionType);
Assert.Equal(2.0f, cylShape.Scale, 3);
Assert.Equal(0.800f, cylShape.Radius, 3); // 0.40 * 2
Assert.Equal(2.400f, cylShape.CylHeight, 3); // 1.20 * 2
Assert.Equal(0.200f, cylShape.LocalPosition.X, 3);
Assert.Equal(0.400f, cylShape.LocalPosition.Y, 3);
Assert.Equal(1.200f, cylShape.LocalPosition.Z, 3);
}
[Fact]
public void FromSetup_EmptySetup_ReturnsEmptyList()
{
var setup = new Setup();
var shapes = ShadowShapeBuilder.FromSetup(setup, 1.0f, _ => true);
Assert.Empty(shapes);
}
[Fact]
public void FromSetup_NullSetup_Throws()
{
Assert.Throws<ArgumentNullException>(
() => ShadowShapeBuilder.FromSetup(null!, 1.0f, _ => true));
}
}