acdream/src/AcDream.Core/Physics/ShadowShape.cs
Erik 13fcf38138 fix(physics): port retail's find_bbox_cell_list outdoor extent walk (#334)
acdream had never implemented retail's SECOND cell-membership algorithm.
CPhysicsObj::calc_cross_cells @0x00515230 tests HAS_PHYSICS_BSP_PS at
0x00515285 and jumps (0x0051528f jne 0x515305) to find_bbox_cell_list
@0x00510fc0 for a BSP-bearing object; everything below that jump is the
OTHER algorithm, CObjCell::find_cell_list, and that is all we had. Every
object, BSP-bearing or not, was routed through it.

That path's outdoor expansion is a HARD CAP of one cell in each direction.
CellTransit.AddAllOutsideCells computes minRad = radius, maxRad = 24 - radius
and adds at most the eight neighbours of the sphere's own cell, so for any
radius >= 12 m both boundary tests are unconditionally true and the result is
exactly 3x3. Widening the radius or adding a second sphere is mechanically
incapable of adding a tenth cell. The user's live probe measured the
consequence directly: standing inside a Neftet formation, inCell=2 exempt=2
reached=0 -- the geometry was not a candidate at all.

The port. AddAllOutsideCellsFromParts is CLandCell::add_all_outside_cells
@0x00533360 plus add_cell_block @0x005331d0: base landcell from the FIRST
part's own adjust_to_outside, baseX/baseY within-block, each part's authored
CGfxObj::gfx_bound_box re-fit through all eight corners
(BBox::LocalToGlobal @0x005b2120), floor(v / square_length) where
square_length = 0x7c920c = 24.0f, four accumulators seeded to zero, ONE
rectangle unioned across all parts, FILLED, in GLOBAL lcoords so it crosses
landblocks freely, clamped only to [0, 0x7f8).
BuildShadowCellSetFromParts is find_bbox_cell_list's worklist.
RegisterMultiPart dispatches on the same flag retail does, and
BuildFloodSpheres' BSP arm is deleted rather than left unreachable.

Disassembled from the PDB-paired 2013-09-06 binary, not read from Binary
Ninja: BN mis-renders four separate constructs inside add_all_outside_cells
alone -- a dropped `and eax,0xffff` on baseX, a neg/sbb/and select shown as
identically zero, a wrong get_landcell argument, and both x87 flag tests as
`unimplemented {test ah}`.

ShadowPartGeometry pairs the BSP root sphere with the authored box so no
resolver can answer one and leave the other call site to synthesize a
substitute -- the AP-156 invariant applied a second time, since that split is
what produced AP-156 and then this. The box comes from
FlatGfxObjVisualBounds, already computed by exactly CGfxObj::init_end's
algorithm and already in the prepared package: no bake change, no DAT re-read.

Cost, measured over the installed DATs before any code was written: 1,258
physics-BSP GfxObjs, cells/object p50 4, p90 4, p99 12, max 49. The port is
CHEAPER than the old 3x3 = 9 for 98.97% of them. Row totals (shapes x cells)
over all 1,031 landblocks with BSP owners fall 97,173 -> 15,607 (0.161x);
dense Arwic 0xC6A9 falls 342 -> 43. One landblock more than doubles.

Precondition confirmed before pinning any expected cell set: 0x010046D8's box
is 96 m x 96 m about cell (2,2) = 0x87640013, which independently corroborates
the 3x3-centred-there diagnosis, and its rectangle does contain 0x87640011 and
0x87640019 -- the two cells the probe measured empty.

Register: AP-156's outdoor half CLOSED and its risk column CORRECTED (it read
"extra broadphase candidates, never a missed one", which generalised the indoor
direction to the whole row and is why #334 sat inside it unnoticed). AP-159 +
issue #335 file the unported indoor arm; AD-49 records the seed-time rectangle.
Issue #336 files a fourth load-sensitive test flake seen once during the gate.

Ten tests, every one sabotage-verified in both directions across eight
mutations (dispatch, 8-corner refit, floor-vs-truncation, union-vs-per-part,
map clamp, adjust guard, landblock clamp, box-path-for-everything). The
strongest is an installed-DAT replay of the user's own probe evidence.
Suite 11,208 -> 11,218 passed / 4 skipped / 0 failed; the +10 is exactly the
new tests.

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

205 lines
8.3 KiB
C#

using System.Numerics;
namespace AcDream.Core.Physics;
/// <summary>
/// One collision-bearing shape attached to a logical PhysicsObj.
/// The set is a DISPATCH, not a union (AP-152): a BSP door emits one shape
/// per physics-BSP part and no primitive; a primitive-only object emits its
/// CylSpheres, else its Spheres; a simple item zero. Positions and rotations are
/// LOCAL to the entity's origin so <see cref="ShadowObjectRegistry.UpdatePosition"/>
/// can re-transform them when the entity moves.
///
/// <para>
/// Retail anchor: <c>CPhysicsPart</c> + <c>CPhysicsPart::find_obj_collisions</c>
/// at <c>acclient_2013_pseudo_c.txt:275045-275055</c>. Each part stores its
/// own transform and dispatches per-part collision to its GfxObj.
/// </para>
///
/// <para>
/// CONSTRUCTION IS BY FACTORY ONLY (<see cref="Bsp"/>, <see cref="Cylinder"/>,
/// <see cref="Sphere"/>) and the constructor is private. That is the AP-156
/// invariant expressed at the type rather than only at the producer: a BSP
/// shape's radius, its bounding-sphere CENTRE, and its authored bounding BOX
/// arrive as one <see cref="ShadowPartGeometry"/> value and are scaled together
/// inside <see cref="Bsp"/>, so no call site — present or future — can take one
/// while dropping another. Those splits are exactly what produced AP-156 (the
/// centre dropped) and #334 (the box never resolved at all); with a public
/// positional constructor a new BSP producer could reintroduce either silently
/// and green.
/// </para>
/// </summary>
public readonly record struct ShadowShape
{
private ShadowShape(
uint gfxObjId,
Vector3 localPosition,
Quaternion localRotation,
float scale,
ShadowCollisionType collisionType,
float radius,
float cylHeight,
Vector3 boundsCenter,
Vector3 localBoundsMin,
Vector3 localBoundsMax)
{
GfxObjId = gfxObjId;
LocalPosition = localPosition;
LocalRotation = localRotation;
Scale = scale;
CollisionType = collisionType;
Radius = radius;
CylHeight = cylHeight;
BoundsCenter = boundsCenter;
LocalBoundsMin = localBoundsMin;
LocalBoundsMax = localBoundsMax;
}
/// <summary>Source GfxObj id, for the BSP walk and for diagnostics.</summary>
public uint GfxObjId { get; }
/// <summary>Part placement in the entity's own frame, entity-scaled.</summary>
public Vector3 LocalPosition { get; }
/// <summary>Part orientation in the entity's own frame.</summary>
public Quaternion LocalRotation { get; }
/// <summary>The entity (or part) scale already applied to the geometry.</summary>
public float Scale { get; }
public ShadowCollisionType CollisionType { get; }
/// <summary>Collision radius, entity-scaled.</summary>
public float Radius { get; }
/// <summary>Cylinder height, entity-scaled; 0 for BSP and Sphere.</summary>
public float CylHeight { get; }
/// <summary>
/// Center of the shape's bounding sphere IN THE SHAPE'S OWN LOCAL FRAME —
/// the frame <see cref="LocalRotation"/> rotates out of and
/// <see cref="Radius"/> is measured in — already multiplied by the entity
/// scale, like <see cref="LocalPosition"/> and <see cref="Radius"/>.
/// <c>Zero</c> for Cylinder/Sphere shapes, whose
/// <see cref="LocalPosition"/> already IS their center.
///
/// <para>
/// BSP shapes need it because a GfxObj's physics BSP is authored in the
/// GfxObj's own coordinates and its root bounding sphere is frequently NOT
/// centered on that origin (376 of the 973 physics-BSP parts in the
/// installed <c>client_portal.dat</c> sit further from it than half their
/// own radius; worst 20.762 m on a 27.708 m sphere, gfx 0x010036DD).
/// <see cref="ShadowObjectRegistry.RegisterMultiPart"/>'s flood needs the
/// sphere's real position, not the part origin's.
/// </para>
///
/// <para>
/// Retail anchor: <c>CGfxObj::physics_sphere</c> (<c>[gfxobj+0x74]</c>) is
/// assigned <c>BSPTREE::GetSphere(physics_bsp)</c> @0x005397e0
/// (<c>mov eax,[ecx]; add eax,4</c> — the root <c>BSPNODE</c>'s
/// <c>CSphere sphere</c>, past its 4-byte vftable), so retail's per-part
/// flood sphere IS the BSP root bounding sphere, origin included.
/// <c>CEnvCell::find_transit_cells</c> @0x0052cae0 — the part-array overload
/// reached from <c>CPhysicsObj::find_bbox_cell_list</c> @0x00510fc0 via
/// <c>CPartArray::calc_cross_cells_static</c> @0x00518160's
/// <c>[vtbl+0x7c]</c> dispatch — loads that sphere at
/// <c>0x0052cb36 mov esi,[ecx+0x74]</c>, transforms its CENTER through the
/// part's own <c>Position</c> at <c>[part+0x30]</c>
/// (<c>0x0052cb4c add eax,0x30</c> / <c>0x0052cb5a call Position::localtolocal</c>),
/// and only then reads the radius at <c>0x0052cb65 fadd [esi+0xc]</c>.
/// </para>
/// </summary>
public Vector3 BoundsCenter { get; }
/// <summary>
/// The shape's AXIS-ALIGNED BOX in the same local frame as
/// <see cref="BoundsCenter"/>, already entity-scaled. For a BSP shape this
/// is retail's <c>CGfxObj::gfx_bound_box</c> — the AABB of the GfxObj's
/// vertex array, which <c>CPhysicsPart::GetBoundingBox</c> @0x0050d600
/// returns and which <c>CLandCell::add_all_outside_cells</c> @0x00533360
/// divides by <c>square_length</c> to build the outdoor cell rectangle
/// (#334). Primitive shapes carry their own radius/height box; they never
/// reach that path, because <c>CPhysicsObj::calc_cross_cells</c>
/// @0x00515230 routes only <c>HAS_PHYSICS_BSP_PS</c> objects to
/// <c>find_bbox_cell_list</c>.
/// </summary>
public Vector3 LocalBoundsMin { get; }
/// <inheritdoc cref="LocalBoundsMin"/>
public Vector3 LocalBoundsMax { get; }
/// <summary>
/// One physics-BSP part. <paramref name="localGeometry"/> carries the part
/// GfxObj's physics-BSP ROOT bounding sphere AND its vertex-array box in
/// the GfxObj's OWN frame, unscaled — retail's
/// <c>CGfxObj::physics_sphere</c> and <c>CGfxObj::gfx_bound_box</c>.
/// Sphere radius, sphere centre, and both box corners are scaled together
/// here, which is the whole point of taking them as one value: retail
/// reads the sphere for the indoor portal reject and the box for the
/// outdoor extent walk, and a producer that supplied one without the
/// other would silently force a substitute at the other call site
/// (AP-156, then #334).
/// </summary>
public static ShadowShape Bsp(
uint gfxObjId,
Vector3 localPosition,
Quaternion localRotation,
float scale,
ShadowPartGeometry localGeometry)
=> new(
gfxObjId,
localPosition,
localRotation,
scale,
ShadowCollisionType.BSP,
localGeometry.Sphere.Radius * scale,
0f,
localGeometry.Sphere.Origin * scale,
localGeometry.BoxMin * scale,
localGeometry.BoxMax * scale);
/// <summary>
/// One Setup CylSphere. <paramref name="localPosition"/> already IS the
/// shape's centre, so it carries no separate bounds centre.
/// </summary>
public static ShadowShape Cylinder(
uint gfxObjId,
Vector3 localPosition,
Quaternion localRotation,
float scale,
float radius,
float cylHeight)
=> new(
gfxObjId,
localPosition,
localRotation,
scale,
ShadowCollisionType.Cylinder,
radius,
cylHeight,
Vector3.Zero,
new Vector3(-radius, -radius, 0f),
new Vector3(radius, radius, cylHeight));
/// <summary>
/// One Setup Sphere. <paramref name="localPosition"/> already IS the
/// shape's centre, so it carries no separate bounds centre.
/// </summary>
public static ShadowShape Sphere(
uint gfxObjId,
Vector3 localPosition,
Quaternion localRotation,
float scale,
float radius)
=> new(
gfxObjId,
localPosition,
localRotation,
scale,
ShadowCollisionType.Sphere,
radius,
0f,
Vector3.Zero,
new Vector3(-radius),
new Vector3(radius));
}