using System.Numerics; using AcDream.App.World; using AcDream.Core.Items; using AcDream.Core.Net; using AcDream.Core.Physics; using AcDream.Core.World; using DatReaderWriter.DBObjs; using DatReaderWriter.Types; namespace AcDream.App.Physics; /// /// Immutable input to the canonical shadow registry for one live object. /// Building is DAT/physics-only and therefore testable without a window or GL /// context; registration remains one explicit commit. /// internal sealed record LiveEntityCollisionRegistration( uint EntityId, uint SourceId, Vector3 EntityWorldPosition, Quaternion EntityWorldRotation, IReadOnlyList Shapes, uint State, EntityCollisionFlags Flags, float WorldOffsetX, float WorldOffsetY, uint LandblockId, uint SeedCellId); /// /// Ports the live-object collision-shape policy used by /// CPhysicsObj::FindObjCollisions (0x0050f050), which DISPATCHES /// rather than unions: every physics-BSP part, ELSE the Setup's CylSpheres, /// ELSE its Spheres, else nothing (AP-152). The gate itself lives in /// . /// /// /// A Setup that yields no shape produces no registration. Retail synthesizes /// nothing for a shapeless object: CPhysicsObj::FindObjCollisions /// (0x0050f050) walks CylSpheres or Spheres or the physics BSP, and when /// CPartArray::GetNumSphere returns zero it branches straight to the /// epilogue (0x0050f22f je 0x50f31b) returning the seeded /// OK_TS. CPartArray::GetRadius (0x005180a0) and /// GetHeight (0x005180b0) are absent from that function's entire call /// set — Setup.Radius/Height serve attack cones, /// cylinder_distance, and MoveTo, never collision geometry. /// internal sealed class LiveEntityCollisionBuilder { private readonly Func _physicsBspBounds; /// /// The dispatch gate, derived from so the /// two can never disagree (AP-156), and cached once so /// allocates no closure per call — Slice I1's 0 B/resolve budget. /// private readonly Func _hasPhysicsBsp; private readonly LiveEntityDefaultPoseResolver _defaultPose; public LiveEntityCollisionBuilder( PhysicsDataCache physicsData, LiveEntityDefaultPoseResolver defaultPose) : this( id => { FlatGfxObjCollisionAsset? asset = physicsData.GetFlatGfxObj(id); FlatPhysicsBsp? flat = asset?.PhysicsBsp; return flat is { RootIndex: >= 0 } ? ShadowPartGeometry.Create( flat.Nodes[flat.RootIndex].BoundingSphere, asset!.VisualBounds) : (ShadowPartGeometry?)null; }, defaultPose) { ArgumentNullException.ThrowIfNull(physicsData); } /// The part GfxObj's physics-BSP root /// bounding sphere AND its authored vertex-array box, or null when it has /// no physics BSP. ONE resolver answers every question the builder asks — /// "does this part dispatch as BSP?", "where and how big is its flood /// sphere?", and "what is its outdoor extent?" — so the dispatch gate and /// the emitted geometry cannot disagree, the sphere's radius cannot be /// carried while its origin is dropped (AP-156), and the outdoor extent /// walk cannot be left without a box (#334). internal LiveEntityCollisionBuilder( Func physicsBspBounds, LiveEntityDefaultPoseResolver defaultPose) { _physicsBspBounds = physicsBspBounds ?? throw new ArgumentNullException(nameof(physicsBspBounds)); _hasPhysicsBsp = id => _physicsBspBounds(id) is not null; _defaultPose = defaultPose ?? throw new ArgumentNullException(nameof(defaultPose)); } /// /// Resolves collision slot zero for every post-AnimPartChanged identity. /// This intentionally has no visual-LOD option or Setup-type input. /// public static uint[] ResolveEffectivePartIdentities( IReadOnlyList postAnimPartGfxObjIds, Func resolveSlotZero) { ArgumentNullException.ThrowIfNull(postAnimPartGfxObjIds); ArgumentNullException.ThrowIfNull(resolveSlotZero); var result = new uint[postAnimPartGfxObjIds.Count]; for (int i = 0; i < result.Length; i++) result[i] = resolveSlotZero(postAnimPartGfxObjIds[i]); return result; } public LiveEntityCollisionRegistration? Build( WorldEntity entity, Setup setup, IReadOnlyList effectivePartGfxObjIds, WorldSession.EntitySpawn spawn, LiveEntityRecord exactRecord, Vector3 worldOrigin, bool retainEmptyPayload = false) { ArgumentNullException.ThrowIfNull(entity); ArgumentNullException.ThrowIfNull(setup); ArgumentNullException.ThrowIfNull(effectivePartGfxObjIds); ArgumentNullException.ThrowIfNull(exactRecord); if (spawn.Position is not { } position) return null; if (spawn.Guid != exactRecord.ServerGuid || spawn.InstanceSequence != exactRecord.Generation || !ReferenceEquals(exactRecord.WorldEntity, entity)) { throw new InvalidOperationException( "Live collision construction requires the exact materialized record."); } float scale = spawn.ObjScale ?? 1f; IReadOnlyList? defaultPose = _defaultPose.Resolve( spawn.MotionTableId ?? 0u, setup.Parts.Count); // One resolver drives both the dispatch gate and the emitted BSP // geometry, and FromSetup applies the entity scale to radius and // center alike — there is no downstream substitution that could take // one and drop the other. IReadOnlyList shapes = ShadowShapeBuilder.FromSetup( setup, scale, _hasPhysicsBsp, partPoseOverride: defaultPose, effectivePartGfxObjIds: effectivePartGfxObjIds, physicsBspBounds: _physicsBspBounds); if (shapes.Count == 0 && !retainEmptyPayload) return null; EntityCollisionFlags flags = EntityCollisionFlags.HasWeenie; if (spawn.ObjectDescriptionFlags is { } descriptionFlags) flags |= EntityCollisionFlagsExt.FromPwdBitfield(descriptionFlags); if (spawn.ItemType == (uint)ItemType.Creature) flags |= EntityCollisionFlags.IsCreature; return new LiveEntityCollisionRegistration( entity.Id, entity.SourceGfxObjOrSetupId, entity.Position, entity.Rotation, shapes, (uint)exactRecord.FinalPhysicsState, flags, worldOrigin.X, worldOrigin.Y, position.LandblockId, position.LandblockId); } public static void Register( ShadowObjectRegistry registry, LiveEntityCollisionRegistration registration) { ArgumentNullException.ThrowIfNull(registry); ArgumentNullException.ThrowIfNull(registration); registry.RegisterMultiPart( registration.EntityId, registration.EntityWorldPosition, registration.EntityWorldRotation, registration.Shapes, registration.State, registration.Flags, registration.WorldOffsetX, registration.WorldOffsetY, registration.LandblockId, registration.SeedCellId, isStatic: false); if (!PhysicsDiagnostics.ProbeBuildingEnabled) return; int cylinders = 0; int bsps = 0; foreach (ShadowShape shape in registration.Shapes) { if (shape.CollisionType == ShadowCollisionType.Cylinder) cylinders++; else bsps++; } Console.WriteLine(FormattableString.Invariant( $"[entity-source] id=0x{registration.EntityId:X8} entityId=0x{registration.EntityId:X8} src=0x{registration.SourceId:X8} gfxObj=0x{registration.SourceId:X8} lb=0x{registration.LandblockId:X8} shapes=cyl{cylinders}+bsp{bsps} note=server-spawn-root state=0x{registration.State:X8} flags={registration.Flags}")); } /// /// Commits a retail ObjDesc part-array replacement. A shapeless result /// removes the prior payload; a shaped result replaces it without making /// a Hidden, parented, or cell-less object collide in world cells. /// public static void ReconcileAppearance( ShadowObjectRegistry registry, uint entityId, LiveEntityCollisionRegistration? registration, bool suspendIfNew) { ArgumentNullException.ThrowIfNull(registry); if (registration is null) return; if (registration.EntityId != entityId) throw new InvalidOperationException("Collision replacement belongs to a different live entity."); registry.ReplaceMultiPartPayload( registration.EntityId, registration.EntityWorldPosition, registration.EntityWorldRotation, registration.Shapes, registration.State, registration.Flags, registration.WorldOffsetX, registration.WorldOffsetY, registration.LandblockId, registration.SeedCellId, isStatic: false, suspendIfNew); } }