< Summary

Line coverage
100%
Covered lines: 1149
Uncovered lines: 0
Coverable lines: 1149
Total lines: 2346
Line coverage: 100%
Branch coverage
100%
Covered branches: 428
Total branches: 428
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .ctor()100%11100%
File 1: get_IsActive()100%11100%
File 1: set_IsActive(...)100%1818100%
File 1: get_IsTrigger()100%11100%
File 1: set_IsTrigger(...)100%11100%
File 1: get_Id()100%11100%
File 1: get_ReplayOrdinal()100%11100%
File 1: get_LifetimeVersion()100%11100%
File 1: get_IsDeactivationInProgress()100%11100%
File 1: get_ServiceRefreshIndex()100%11100%
File 1: get_AgentOrNull()100%11100%
File 1: get_Context()100%11100%
File 1: get_Body()100%11100%
File 1: get_IsStatic()100%22100%
File 1: get_RequiresServiceSideRefresh()100%22100%
File 1: get_RuntimeShapeVersion()100%11100%
File 1: get_HasHostBinding()100%11100%
File 1: get_CompoundOwner()100%11100%
File 1: get_Position()100%66100%
File 1: set_Position(...)100%22100%
File 1: get_Rotation()100%22100%
File 1: set_Rotation(...)100%22100%
File 1: get_Velocity()100%22100%
File 1: get_World()100%11100%
File 1: get_Transform()100%1212100%
File 1: get_Layer()100%11100%
File 1: set_Layer(...)100%44100%
File 1: get_IgnoredCollisionLayers()100%11100%
File 1: set_IgnoredCollisionLayers(...)100%44100%
File 1: get_Material()100%11100%
File 1: set_Material(...)100%44100%
File 1: get_IsPartitioned()100%11100%
File 1: get_PartitionChanged()100%11100%
File 1: set_PartitionChanged(...)100%11100%
File 1: get_BroadPhaseVersion()100%11100%
File 1: get_LocalOffset()100%11100%
File 1: set_LocalOffset(...)100%22100%
File 1: get_Radius()100%11100%
File 1: set_Radius(...)100%22100%
File 1: get_ScaledRadius()100%11100%
File 1: get_ScaledRadiusSqr()100%11100%
File 1: get_Size()100%11100%
File 1: set_Size(...)100%22100%
File 1: get_LocalScale()100%11100%
File 1: TryGetLocalScale(...)100%22100%
File 1: get_ScaledOffset()100%11100%
File 1: TryGetScaledOffset(...)100%11100%
File 1: get_Center()100%22100%
File 1: get_Bounds()100%11100%
File 1: get_BoundsMin()100%11100%
File 1: get_BoundsMax()100%11100%
File 1: get_PartitionCoordinates()100%11100%
File 1: get_PartitionKind()100%11100%
File 1: get_IsMixedPartitioned()100%11100%
File 1: get_MixedPartitionCoordinates()100%11100%
File 1: get_MixedPartitionKind()100%11100%
File 1: get_RaycastVersion()100%11100%
File 1: set_RaycastVersion(...)100%11100%
File 1: get_CircleQueryVersion()100%11100%
File 1: set_CircleQueryVersion(...)100%11100%
File 1: get_IsChild()100%11100%
File 1: get_IsParent()100%11100%
File 1: get_ParentId()100%11100%
File 1: get_Parent3D()100%11100%
File 1: get_Parent2D()100%11100%
File 1: get_TopParent3D()100%11100%
File 1: get_TopParent2D()100%11100%
File 1: get_HierarchyChildCount()100%11100%
File 1: get_HierarchyKey()100%22100%
File 1: get_ParentKey()100%11100%
File 1: get_TopParentKey()100%11100%
File 1: get_HierarchyState()100%11100%
File 1: Gravitas.Colliders.IColliderHierarchyNode.get_HierarchyKey()100%11100%
File 1: Gravitas.Colliders.IColliderHierarchyNode.get_HierarchyParent()100%11100%
File 1: Initialize(...)100%11100%
File 1: InitializeWithNoBody(...)100%44100%
File 1: PreflightBodyInitialization(...)100%11100%
File 1: PreflightInitialization(...)100%11100%
File 1: InitCore(...)100%11100%
File 1: OnBeforeInitialize(...)100%11100%
File 1: OnInitialize()100%11100%
File 1: ValidateCurrentRuntimeTransform()100%11100%
File 1: InitialPartition()100%11100%
File 1: RepartitionCommittedShape()100%44100%
File 1: Simulate()100%11100%
File 1: Simulate(...)100%88100%
File 1: UpdatePartition()100%44100%
File 1: SetBodylessWorldPose(...)100%1010100%
File 1: SetParent(...)100%44100%
File 1: SetParent(...)100%44100%
File 1: ClearParent()100%44100%
File 1: IsSibling(...)100%11100%
File 1: ExcludesMixedCollisionWith(...)100%11100%
File 1: RebuildRuntimeShapeState(...)100%2020100%
File 1: RebuildRuntimeShapeOnly(...)100%11100%
File 1: MarkShapeDirty()100%44100%
File 1: MarkBroadPhaseChanged()100%11100%
File 1: OnRadiusChanged()100%11100%
File 1: OnMaterialChanged()100%11100%
File 1: NormalizeSize(...)100%11100%
File 1: ValidateSize(...)100%44100%
File 1: GetClosestSurfaceAnchor(...)100%11100%
File 1: TryGetPlanarSurfaceNormal(...)100%11100%
File 1: IsPositionInBounds(...)100%1010100%
File 1: Gravitas.Colliders.IColliderHierarchyNode.AddChild(...)100%11100%
File 1: Gravitas.Colliders.IColliderHierarchyNode.RemoveChild(...)100%11100%
File 1: Gravitas.Colliders.IColliderHierarchyNode.ClearParentReference()100%44100%
File 1: Gravitas.Colliders.IColliderHierarchyNode.TryGetHierarchyColliderByKey(...)100%1212100%
File 1: SetPhysicsState(...)100%11100%
File 1: SetServiceIndex(...)100%11100%
File 1: SetReplayOrdinal(...)100%11100%
File 1: SetServiceRefreshIndex(...)100%11100%
File 1: ClearServiceRefreshIndex()100%11100%
File 1: ClearPhysicsState()100%11100%
File 1: Gravitas.Colliders.IPhysicsColliderRegistryItem.SetRegistryState(...)100%11100%
File 1: Gravitas.Colliders.IPhysicsColliderRegistryItem.get_ServiceIndex()100%11100%
File 1: Gravitas.Colliders.IPhysicsColliderRegistryItem.get_ReplayOrder()100%11100%
File 1: Gravitas.Colliders.IPhysicsColliderRegistryItem.SetRegistryServiceIndex(...)100%11100%
File 1: Gravitas.Colliders.IPhysicsColliderRegistryItem.SetRegistryReplayOrdinal(...)100%11100%
File 1: Gravitas.Colliders.IPhysicsColliderRegistryItem.ClearRegistryState()100%11100%
File 1: GetOrCreateMixedPartitionCoordinates()100%22100%
File 1: MatchesPartitionGridBounds(...)100%66100%
File 1: MarkUnpartitioned()100%11100%
File 1: ClearPartitionCoordinates()100%11100%
File 1: MatchesMixedPartitionGridBounds(...)100%66100%
File 1: MarkMixedPartitioned(...)100%11100%
File 1: MarkMixedUnpartitioned()100%11100%
File 1: ClearMixedPartitionCoordinates()100%11100%
File 1: IgnoresCollisionLayer(...)100%11100%
File 2: get_CollisionPairCount()100%11100%
File 2: get_CollisionPairHolderCount()100%11100%
File 2: get_CollisionPairs()100%11100%
File 2: get_CollisionPairHolders()100%11100%
File 2: NotifyContact(...)100%22100%
File 2: NotifyContact(...)100%5050100%
File 2: NotifyMixedContact(...)100%11100%
File 2: NotifyMixedContact(...)100%4646100%
File 3: ValidateGeometryMutation(...)100%1212100%
File 3: GetCandidateGeometryReach(...)100%1212100%
File 4: GetFrontalArea(...)100%11100%
File 4: CalculateLocalCenterOfMassOffset()100%11100%
File 4: CalculateLocalMassPoint()100%11100%
File 4: CalculatePreparedLocalMassPoint()100%11100%
File 4: get_SupportsMassProperties()100%11100%
File 4: CalculateInertiaTensor(...)100%66100%
File 4: TransformRelativeMassPropertyPointExact(...)100%22100%
File 4: TransformPreparedRelativeMassPropertyPointExact(...)100%22100%
File 4: get_CompoundLocalRotation()100%11100%
File 5: ContributeReplayHash(...)100%22100%
File 5: ContributeShapeReplayHash(...)100%1818100%
File 5: WriteReplayHierarchyKey(...)100%22100%
File 5: TryResolveReplayHierarchyOrdinal(...)100%66100%
File 5: ContributeCompoundPartReplayHash(...)100%22100%
File 5: ContributeShapeDefinitionReplayHash(...)100%66100%
File 5: WriteMaterial(...)100%11100%
File 6: SetPreviousGridBounds()100%11100%
File 6: TryGetCollisionPair(...)100%11100%
File 6: TryAddCollisionPair(...)100%11100%
File 6: TryRemoveCollisionPair(...)100%11100%
File 6: TryAddCollisionPairHolder(...)100%11100%
File 6: TryRemoveCollisionPairHolder(...)100%11100%
File 6: ClearCollisionPairState()100%11100%
File 6: ClearRuntimeRelationships()100%11100%
File 6: Deactivate()100%22100%
File 6: DeactivateRuntimeRegistration()100%22100%
File 6: ClearBindingState()100%11100%
File 6: ClearChildParentReferences()100%66100%
File 6: BindContext(...)100%22100%
File 6: ReserveCompoundPart(...)100%22100%
File 6: ThrowIfCompoundPartLifecycle(...)100%11100%
File 6: SetTrigger(...)100%88100%
File 6: ThrowIfCannotEnableTrigger(...)100%11100%
File 6: ThrowIfTriggerWouldAttachToBody(...)100%11100%
File 6: ThrowIfLoadedTriggerHasBody(...)100%22100%
File 6: TryGetBoundContext(...)100%11100%
File 7: RecordData(...)100%22100%
File 7: ApplyLoadedState()100%1212100%
File 8: .ctor()100%11100%
File 8: get_HasCommittedShape()100%11100%
File 8: get_PreparedGeometryReach()100%11100%
File 8: get_PreparedAttachmentReach()100%11100%
File 8: get_PreparedContext()100%11100%
File 8: get_PreparedShapeBounds()100%11100%
File 8: get_CanonicalCenteredProxyRadius()100%11100%
File 8: get_CanonicalPivotProxyRadius()100%11100%
File 8: get_CanonicalGroundProbeRadius()100%11100%
File 8: get_CanonicalCenter()100%11100%
File 8: get_CanonicalRotation()100%11100%
File 8: TryGetCommittedOwnerScale(...)100%22100%
File 8: GetCurrentOwnerScale()100%44100%
File 8: GetCurrentPartScale()100%44100%
File 8: GetCurrentShapeScales(...)100%11100%
File 8: TryGetCurrentScaledOffset(...)100%22100%
File 8: GetCurrentScaledOffset()100%11100%
File 8: GetCurrentScaledRadius()100%11100%
File 8: CreateStandaloneSnapshot(...)100%22100%
File 8: CaptureShapeSnapshot()100%22100%
File 8: CreateCompoundPartSnapshot(...)100%11100%
File 8: PrepareRuntimeShape(...)100%44100%
File 8: MarkContactDependencyChanged(...)100%88100%
File 8: PublishPreparedShape(...)100%66100%
File 8: TryPrepareBodyPose(...)100%11100%
File 8: PublishPreparedBodyPose()100%11100%
File 8: PublishPreparedExplicitBodyPose(...)100%44100%
File 8: PrepareDetachedBodyReconfigurationCandidate(...)100%11100%
File 8: MatchesCommittedReconfigurationCandidate(...)100%11100%
File 8: PrepareBodyReconfiguration(...)100%11100%
File 8: PublishPreparedBodyReconfiguration(...)100%11100%
File 8: PrepareStandaloneInitialization(...)100%11100%
File 8: PrepareCompoundPart(...)100%22100%
File 8: PublishCompoundPart(...)100%11100%
File 8: SetPreparedGeometryReach(...)100%11100%
File 8: SetPreparedBounds(...)100%11100%
File 8: ValidateShapeCandidate(...)100%11100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using System.Runtime.CompilerServices;
 10using Chronicler;
 11using FixedMathSharp;
 12using FixedMathSharp.Geometry;
 13using Gravitas.CollisionHandling;
 14using Gravitas.Materials;
 15using Gravitas.Queries;
 16using Gravitas.Support;
 17using GridForge.Grids;
 18using GridForge.Spatial;
 19using SwiftCollections;
 20
 21namespace Gravitas.Colliders;
 22
 23/// <summary>
 24/// Common runtime type for the closed set of Gravitas-owned 3D collider
 25/// shapes. Use <see cref="ColliderShapeDefinition.CreateCollider"/> when
 26/// constructing from engine-adapter shape data.
 27/// </summary>
 28public abstract partial class LSCollider : IRecordable, IColliderHierarchyNode, IPhysicsColliderRegistryItem
 29{
 2951630    internal LSCollider() { }
 31
 32    #region Fields and Properties
 33
 34    /// <summary>Controls collider debug diagnostics.</summary>
 35    protected bool _debug;
 36    /// <summary>Controls collider shape debug drawing.</summary>
 37    protected bool _drawShape;
 38    private bool _drawPartitions;
 39    private bool _drawBoundingBox;
 40
 1475841    private bool _active = true;
 42    private bool _deactivationInProgress;
 43    /// <summary>Gets or sets whether this collider participates in runtime physics.</summary>
 44    public bool IsActive
 45    {
 46        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 637788047        get => _active;
 48        set
 49        {
 2050            ThrowIfCompoundPartLifecycle(nameof(IsActive));
 51
 2052            if (_active == value)
 253                return;
 54
 1855            if (_context == null || _id < 0)
 56            {
 257                _active = value;
 258                return;
 59            }
 60
 1661            if (value)
 62            {
 563                RebuildRuntimeShapeState();
 564                _active = true;
 565                InitialPartition();
 566                if (_context.Settings.RuntimeMode.RunsMixedContacts())
 367                    _context.MixedCollisions.Refresh3DColliderPartition(this);
 568                return;
 69            }
 70
 1171            _active = false;
 1372            if (this is LSMeshCollider mesh) mesh.StaticSurface?.Remove(mesh);
 1173            if (IsPartitioned)
 1074                _context.Collisions.ClearPartitionedObject(this, force: true);
 75
 1176            if (IsMixedPartitioned)
 77            {
 378                _context.MixedCollisions.ClearPartitioned3DCollider(this, force: true);
 379                MarkMixedUnpartitioned();
 380                ClearMixedPartitionCoordinates();
 81            }
 1182        }
 83    }
 84
 85    private bool _isTrigger;
 86
 87    /// <summary>
 88    /// Gets or sets whether this bodyless collider is a trigger volume.
 89    /// Trigger volumes raise trigger enter/stay/exit callbacks for valid overlap
 90    /// pairs and never apply physical response.
 91    /// </summary>
 92    public bool IsTrigger
 93    {
 94        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 178916095        get => _isTrigger;
 10496        set => SetTrigger(value);
 97    }
 98
 1475899    private int _id = -1;
 100    /// <summary>Gets the context-local runtime collider identifier.</summary>
 49674104101    public int Id => _id;
 102
 14758103    private int _serviceIndex = -1;
 104
 14758105    private int _replayOrder = -1;
 106
 14758107    private int _replayOrdinal = -1;
 20978108    internal int ReplayOrdinal => _replayOrdinal;
 109
 110    private long _lifetimeVersion;
 1232319111    internal long LifetimeVersion => _lifetimeVersion;
 112
 6040065113    internal bool IsDeactivationInProgress => _deactivationInProgress;
 114
 14758115    private int _serviceRefreshIndex = -1;
 7966116    internal int ServiceRefreshIndex => _serviceRefreshIndex;
 117
 118    private IMatterAgent? _agent;
 361573119    internal IMatterAgent? AgentOrNull => _agent;
 120
 121    private GravitasWorldContext? _context;
 122    /// <summary>Gets the world context to which this collider is bound.</summary>
 123    public GravitasWorldContext Context
 124    {
 125        get
 126        {
 1131035127            ChronicleGuard.ThrowIfTrue(
 1131035128                _context == null,
 1131035129                nameof(LSCollider),
 1131035130                "Collider is not bound to a GravitasWorldContext.");
 1131033131            return _context!;
 132        }
 133    }
 134
 135    private SolidBody? _body;
 136    /// <summary>Gets the owning 3D body, or <see langword="null"/> for a bodyless collider.</summary>
 13054805137    public SolidBody? Body => _body;
 138
 139    /// <summary>
 140    /// Gets whether this collider is bodyless or belongs to an explicit static
 141    /// body role.
 142    /// </summary>
 682677143    public bool IsStatic => _body == null || _body.IsStatic;
 144
 13328145    internal bool RequiresServiceSideRefresh => _body == null || _body.DynamicId < 0;
 146
 147    private LSCompoundCollider? _compoundOwner;
 14758148    private FixedQuaternion _compoundLocalRotation = FixedQuaternion.Identity;
 14758149    private Vector3d _compoundLocalScale = Vector3d.One;
 150
 14758151    private readonly ColliderRuntimeShapeState<ColliderShapeSnapshot> _runtimeShapeState = new();
 152    private ColliderPartitionState _partitionState;
 153    private ColliderPartitionState _mixedPartitionState;
 154    private ColliderQueryState _queryState;
 155    private ColliderPairState<CollisionPair> _pairState;
 156    private ColliderHierarchyState _hierarchyState;
 157
 96166158    internal uint RuntimeShapeVersion => _runtimeShapeState.RuntimeVersion;
 159
 14203160    internal bool HasHostBinding => _agent != null;
 161
 126510162    internal LSCompoundCollider? CompoundOwner => _compoundOwner;
 163
 164    /// <summary>Gets the runtime world position, or sets it for a bodyless collider.</summary>
 165    public Vector3d Position
 166    {
 11425167        get => _compoundOwner?.Center
 11425168            ?? Body?.Position3d
 11425169            ?? _agent?.Transform.WorldPosition
 11425170            ?? throw new InvalidOperationException("Collider has no body or static transform.");
 171        set
 172        {
 331173            ChronicleGuard.ThrowIfTrue(
 331174                _compoundOwner != null,
 331175                nameof(Position),
 331176                "Compound collider parts inherit position from their owning compound collider.");
 330177            ChronicleGuard.ThrowIfTrue(
 330178                _agent == null,
 330179                nameof(Position),
 330180                "Collider is not bound to a static transform.");
 329181            ChronicleGuard.ThrowIfTrue(
 329182                _body != null,
 329183                nameof(Position),
 329184                "Body-owned collider positions must be changed through their SolidBody.");
 185
 328186            if (_agent.Transform.WorldPosition == value)
 3187                return;
 325188            SetBodylessWorldPose(value, default, setRotation: false, nameof(Position));
 322189        }
 190    }
 191
 192    /// <summary>Gets the committed world rotation, or sets it for a bodyless collider.</summary>
 193    public FixedQuaternion Rotation
 194    {
 798549195        get => _hasCommittedShape
 798549196            ? _committedRotation
 798549197            : throw new InvalidOperationException(
 798549198                "Collider has no committed runtime shape.");
 199        set
 200        {
 13201            ChronicleGuard.ThrowIfTrue(
 13202                _compoundOwner != null,
 13203                nameof(Rotation),
 13204                "Compound collider parts inherit rotation from their owning compound collider.");
 12205            ChronicleGuard.ThrowIfTrue(
 12206                _agent == null,
 12207                nameof(Rotation),
 12208                "Collider is not bound to a static transform.");
 11209            ChronicleGuard.ThrowIfTrue(
 11210                _body != null,
 11211                nameof(Rotation),
 11212                "Body-owned collider rotations must be changed through their SolidBody.");
 213
 10214            if (_agent.Transform.WorldRotation == value)
 1215                return;
 9216            SetBodylessWorldPose(default, value, setRotation: true, nameof(Rotation));
 7217        }
 218    }
 219
 220    /// <summary>Gets the owning body's linear velocity, or zero for a bodyless collider.</summary>
 3734221    public Vector3d Velocity => Body?.LinearVelocity ?? Vector3d.Zero;
 222
 223    /// <summary>Gets the GridForge world owned by this collider's context.</summary>
 6224    public GridWorld World => Context.World;
 225
 226    /// <summary>Gets the transform that supplies this collider's runtime pose.</summary>
 1213227    public FixedTransform Transform => _compoundOwner?.Transform
 1213228        ?? Body?.PositionTransform
 1213229        ?? _agent?.Transform
 1213230        ?? throw new InvalidOperationException("Collider has no body or static transform.");
 231
 232    private PhysicsLayer _layer = new();
 14758233    private PhysicsLayerMask _ignoredCollisionLayers = PhysicsLayerMask.None;
 234
 235    /// <summary>Gets or sets the single physics layer used for collision and query filtering.</summary>
 236    public PhysicsLayer Layer
 237    {
 238        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 11956207239        get => _layer;
 240        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 241        set
 242        {
 273243            if (_layer == value) return;
 171244            _layer = value;
 171245            MarkContactDependencyChanged();
 171246            _body?.Wake();
 9247        }
 248    }
 249
 250    /// <summary>
 251    /// Gets or sets physical layers this collider ignores for collider-to-collider
 252    /// interactions. Public queries continue to use the caller's query mask.
 253    /// </summary>
 254    public PhysicsLayerMask IgnoredCollisionLayers
 255    {
 256        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 10257        get => _ignoredCollisionLayers;
 258        set
 259        {
 47260            if (_ignoredCollisionLayers == value)
 2261                return;
 262
 45263            _ignoredCollisionLayers = value;
 45264            MarkContactDependencyChanged();
 45265            _body?.Wake();
 32266        }
 267    }
 268
 14758269    private PhysicsMaterial _material = PhysicsMaterial.Default;
 270
 271    /// <summary>
 272    /// Gets or sets the deterministic surface material used by collision
 273    /// response for this collider.
 274    /// </summary>
 275    public PhysicsMaterial Material
 276    {
 277        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 526496278        get => _material;
 279        set
 280        {
 5876281            if (_material == value)
 2141282                return;
 283
 3735284            _material = value;
 3735285            MarkContactDependencyChanged(surfaceNeighborsChanged: false);
 3735286            OnMaterialChanged();
 3735287            _body?.Wake();
 680288        }
 289    }
 290
 291    /// <summary>Gets whether this collider currently has 3D broad-phase partition membership.</summary>
 299593292    public bool IsPartitioned => _partitionState.IsPartitioned;
 293
 294    /// <summary>
 295    /// Used for preventing culling for the first frame this object is added to a new partition node.
 296    /// </summary>
 297    public bool PartitionChanged
 298    {
 299        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 3863300        get => _partitionState.PartitionChanged;
 301        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 289272302        set => _partitionState.PartitionChanged = value;
 303    }
 304
 472947305    internal uint BroadPhaseVersion => _partitionState.BroadPhaseVersion;
 306
 307    /// <summary>
 308    /// Center of collider in local space, used for calculating bounds and offsets. Should be set in the Setup method of
 309    /// </summary>
 310    protected Vector3d _offset;
 311
 312    /// <summary>
 313    /// Gets or sets the unscaled local center offset used by bounds and shape-derived state.
 314    /// </summary>
 315    public Vector3d LocalOffset
 316    {
 317        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 125520318        get => _offset;
 319        set
 320        {
 969321            if (_offset == value)
 367322                return;
 323
 602324            ValidateGeometryMutation(value, _size, _radius);
 596325            _offset = value;
 596326            MarkShapeDirty();
 596327        }
 328    }
 329
 330    /// <summary>Gets the runtime 3D shape family.</summary>
 331    public abstract ColliderType Shape { get; }
 332    /// <summary>Gets the deterministic narrow-phase ordering priority.</summary>
 333    public abstract int Priority { get; }
 334
 335    /// <summary>Stores the unscaled radius for radius-based collider shapes.</summary>
 14758336    protected Fixed64 _radius = Fixed64.Half;
 337
 338    /// <summary>
 339    /// Gets or sets the unscaled shape radius used by radius-based colliders.
 340    /// </summary>
 341    public Fixed64 Radius
 342    {
 343        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 338344        get => _radius;
 345        set
 346        {
 3142347            ChronicleGuard.ThrowIfArgument(
 3142348                value <= Fixed64.Zero,
 3142349                nameof(value),
 3142350                "Collider radius must be greater than zero.");
 351
 3142352            if (_radius == value)
 1430353                return;
 354
 1712355            ValidateGeometryMutation(_offset, _size, value);
 1706356            _radius = value;
 1706357            OnRadiusChanged();
 1706358            MarkShapeDirty();
 1706359        }
 360    }
 361
 362    /// <summary>
 363    /// Gets the bounding circle radius.
 364    /// For boxes, this is half of the diagonal length of the cube
 365    /// </summary>
 366    /// <value>The radius.</value>
 5367    public virtual Fixed64 ScaledRadius => GetCurrentScaledRadius();
 368
 369    /// <summary>Gets the squared scaled bounding radius.</summary>
 21370    public Fixed64 ScaledRadiusSqr => ScaledRadius * ScaledRadius;
 371
 372    /// <summary>Stores the unscaled local collider size.</summary>
 14758373    protected Vector3d _size = Vector3d.One;
 374
 375    /// <summary>
 376    /// Gets or sets the unscaled local size used when rebuilding collider bounds.
 377    /// </summary>
 378    public Vector3d Size
 379    {
 380        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 184381        get => _size;
 382        set
 383        {
 4096384            ValidateSize(value);
 4090385            Vector3d normalizedSize = NormalizeSize(value);
 4090386            if (_size == normalizedSize)
 1381387                return;
 388
 2709389            ValidateGeometryMutation(_offset, normalizedSize, _radius);
 2705390            _size = normalizedSize;
 2705391            MarkShapeDirty();
 2705392        }
 393    }
 394
 395    /// <summary>Gets the committed shape-specific measure used as the frontal-area fallback.</summary>
 396    public virtual Fixed64 Area { get; protected set; } = Fixed64.Zero;
 397
 398    #region Grid & Partition Bounds
 399
 400    /// <summary>Gets the combined owner and compound-part scale.</summary>
 401    public virtual Vector3d LocalScale
 402    {
 403        get
 404        {
 3405            bool representable = TryGetLocalScale(out Vector3d scale);
 3406            ChronicleGuard.ThrowIfTrue(
 3407                !representable,
 3408                nameof(LocalScale),
 3409                "The combined 3D collider scale is outside the Fixed64 coordinate domain.");
 2410            return scale;
 411        }
 412    }
 413
 414    /// <summary>
 415    /// Attempts to materialize the combined owner and compound-part scale.
 416    /// Shape preparation retains those factors separately and does not require
 417    /// their product to be representable.
 418    /// </summary>
 419    public bool TryGetLocalScale(out Vector3d scale)
 420    {
 6421        GetCurrentShapeScales(
 6422            out Vector3d ownerScale,
 6423            out Vector3d partScale);
 424
 6425        bool representable = Fixed64.TryMultiplyDivide(
 6426                ownerScale.X,
 6427                partScale.X,
 6428                Fixed64.One,
 6429                out Fixed64 x)
 6430            & Fixed64.TryMultiplyDivide(
 6431                ownerScale.Y,
 6432                partScale.Y,
 6433                Fixed64.One,
 6434                out Fixed64 y)
 6435            & Fixed64.TryMultiplyDivide(
 6436                ownerScale.Z,
 6437                partScale.Z,
 6438                Fixed64.One,
 6439                out Fixed64 z);
 6440        scale = representable ? new Vector3d(x, y, z) : default;
 6441        return representable;
 442    }
 443
 444    /// <summary>
 445    /// Gets the component-scaled local offset.
 446    /// </summary>
 447    /// <exception cref="InvalidOperationException">
 448    /// The scaled offset itself is outside the Fixed64 coordinate domain. The
 449    /// collider may still have a representable world center through exact
 450    /// transform cancellation.
 451    /// </exception>
 12452    public Vector3d ScaledOffset => GetCurrentScaledOffset();
 453
 454    /// <summary>
 455    /// Attempts to materialize the component-scaled local offset independently
 456    /// from the collider's complete world transform.
 457    /// </summary>
 458    public bool TryGetScaledOffset(out Vector3d scaledOffset) =>
 2459        TryGetCurrentScaledOffset(out scaledOffset);
 460
 461    /// <summary>
 462    /// Bodies position in world space + collider offset (center) value
 463    /// </summary>
 2348113464    public Vector3d Center => _hasCommittedShape
 2348113465        ? _committedCenter
 2348113466        : throw new InvalidOperationException(
 2348113467            "Collider has no committed runtime shape.");
 468
 469    /// <summary>Stores the committed world-space axis-aligned bounds.</summary>
 470    protected FixedBoundBox _bounds;
 471    /// <summary>Gets the committed world-space axis-aligned bounds.</summary>
 442040472    public FixedBoundBox Bounds => _bounds;
 473    /// <summary>Gets the minimum corner of <see cref="Bounds"/>.</summary>
 26972895474    public Vector3d BoundsMin => _bounds.Min;
 475    /// <summary>Gets the maximum corner of <see cref="Bounds"/>.</summary>
 25904472476    public Vector3d BoundsMax => _bounds.Max;
 477
 3163478    internal SwiftList<WorldVoxelIndex>? PartitionCoordinates => _partitionState.Coordinates;
 479
 149887480    internal int PartitionKind => _partitionState.LastPartitionKind;
 481
 19516482    internal bool IsMixedPartitioned => _mixedPartitionState.IsPartitioned;
 483
 11011484    internal SwiftList<WorldVoxelIndex>? MixedPartitionCoordinates => _mixedPartitionState.Coordinates;
 485
 26753486    internal int MixedPartitionKind => _mixedPartitionState.LastPartitionKind;
 487
 488    #endregion
 489
 490    internal uint RaycastVersion
 491    {
 492        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 438752493        get => _queryState.RaycastVersion;
 494        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 25454495        set => _queryState.RaycastVersion = value;
 496    }
 497
 498    internal uint CircleQueryVersion
 499    {
 500        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 38518501        get => _queryState.CircleQueryVersion;
 502        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1040503        set => _queryState.CircleQueryVersion = value;
 504    }
 505
 506    /// <summary>Gets whether this collider has a hierarchy parent.</summary>
 2507    public bool IsChild => _hierarchyState.IsChild;
 508    /// <summary>Gets whether this collider is configured as or currently owns a hierarchy parent.</summary>
 4509    public bool IsParent => _hierarchyState.IsParent;
 510    /// <summary>Gets the context-local identifier of the parent collider, or -1 when unparented.</summary>
 9511    public int ParentId => ParentKey.Id;
 512    /// <summary>Gets the 3D parent collider, when the parent belongs to the 3D runtime.</summary>
 8513    public LSCollider? Parent3D => _hierarchyState.Parent as LSCollider;
 514    /// <summary>Gets the 2D parent collider, when the parent belongs to the 2D runtime.</summary>
 4515    public LSCollider2D? Parent2D => _hierarchyState.Parent as LSCollider2D;
 136799516    internal LSCollider? TopParent3D => _hierarchyState.TopParent as LSCollider;
 1517    internal LSCollider2D? TopParent2D => _hierarchyState.TopParent as LSCollider2D;
 11101518    internal int HierarchyChildCount => _hierarchyState.ChildCount;
 5353081519    internal ColliderHierarchyKey HierarchyKey => Id >= 0 ? ColliderHierarchyKey.Create3D(Id) : ColliderHierarchyKey.Non
 11104520    internal ColliderHierarchyKey ParentKey => _hierarchyState.ParentKey;
 11092521    internal ColliderHierarchyKey TopParentKey => _hierarchyState.TopParentKey;
 1522    internal ColliderHierarchyState HierarchyState => _hierarchyState;
 168523    ColliderHierarchyKey IColliderHierarchyNode.HierarchyKey => HierarchyKey;
 54524    IColliderHierarchyNode? IColliderHierarchyNode.HierarchyParent => _hierarchyState.Parent;
 525
 526    #endregion
 527
 528    internal void Initialize(SolidBody body)
 529    {
 8417530        _body = body;
 8417531        InitCore(body.Agent);
 8417532    }
 533
 534    /// <summary>Binds and registers this collider as a bodyless runtime collider.</summary>
 535    public void InitializeWithNoBody(IMatterAgent agent)
 536    {
 4866537        ThrowIfCompoundPartLifecycle(nameof(InitializeWithNoBody));
 4866538        ChronicleGuard.ThrowIfNull(agent, nameof(agent));
 4866539        ChronicleGuard.ThrowIfArgument(
 4866540            Id >= 0 || (HasHostBinding && !ReferenceEquals(_agent, agent)),
 4866541            nameof(agent),
 4866542            "Collider is already registered or bound to another host agent.");
 4864543        PreflightInitialization(agent);
 4824544        InitCore(agent);
 4824545    }
 546
 547    internal void PreflightBodyInitialization(
 548        SolidBody body,
 549        Vector3d requestedPosition,
 550        FixedQuaternion requestedRotation)
 551    {
 8426552        ThrowIfCompoundPartLifecycle(nameof(Initialize));
 8426553        ChronicleGuard.ThrowIfNull(body, nameof(body));
 8426554        ThrowIfTriggerWouldAttachToBody(nameof(Initialize));
 8425555        PreflightInitialization(
 8425556            body.Agent,
 8425557            useRequestedPose: true,
 8425558            requestedPosition,
 8425559            requestedRotation);
 8416560    }
 561
 562    private void PreflightInitialization(
 563        IMatterAgent agent,
 564        bool useRequestedPose = false,
 565        Vector3d requestedPosition = default,
 566        FixedQuaternion requestedRotation = default)
 567    {
 13289568        ChronicleGuard.ThrowIfNull(agent, nameof(agent));
 13289569        OnBeforeInitialize(agent);
 13289570        PrepareStandaloneInitialization(
 13289571            agent,
 13289572            useRequestedPose,
 13289573            requestedPosition,
 13289574            requestedRotation);
 13240575    }
 576
 577    private void InitCore(IMatterAgent agent)
 578    {
 13241579        _lifetimeVersion++;
 580
 13241581        _queryState.Reset();
 582
 13241583        _agent = agent;
 13241584        _active = true;
 13241585        _deactivationInProgress = false;
 13241586        BindContext(agent.Context);
 13241587        ContactDependencyVersion = 0;
 13241588        PublishPreparedShape();
 13241589        Context.Physics.AssimilateCollider(this);
 13241590        _hierarchyState.Initialize(_agent.IsParent);
 13241591        OnInitialize();
 592
 13241593        _partitionState.SetPreviousGridBounds(Vector3d.Zero, Vector3d.Zero);
 594
 13241595        InitialPartition();
 13241596    }
 597
 598    /// <summary>Validates or prepares derived shape state before runtime registration.</summary>
 13289599    protected virtual void OnBeforeInitialize(IMatterAgent agent) { }
 600
 601    /// <summary>Runs derived initialization after runtime registration.</summary>
 13241602    protected virtual void OnInitialize() { }
 603
 604    internal void ValidateCurrentRuntimeTransform()
 605    {
 691606        ColliderShapeSnapshot snapshot = CaptureShapeSnapshot();
 688607        PrepareRuntimeShape(
 688608            snapshot,
 688609            includeBodyAttachment: true);
 688610    }
 611
 612    private void InitialPartition()
 613    {
 13857614        RebuildRuntimeShapeState();
 13856615        RepartitionCommittedShape();
 13856616    }
 617
 618    internal void RepartitionCommittedShape()
 619    {
 13872620        if (!IsActive)
 1621            return;
 622
 13871623        _partitionState.Coordinates ??= new();
 13871624        SwiftList<WorldVoxelIndex> partitionCoordinates = _partitionState.Coordinates!;
 13871625        Context.Collisions.PartitionObject(this, ref partitionCoordinates);
 13871626        _partitionState.Coordinates = partitionCoordinates;
 13871627        SetPreviousGridBounds();
 13871628        _partitionState.MarkPartitioned();
 13871629        MarkBroadPhaseChanged();
 13871630    }
 631
 632    /// <summary>Refreshes bodyless collider shape and broad-phase state for one simulation step.</summary>
 236357633    public void Simulate() => Simulate(skipUnchangedMassProperties: false);
 634
 635    internal void Simulate(bool skipUnchangedMassProperties)
 636    {
 289718637        ThrowIfCompoundPartLifecycle(nameof(Simulate));
 289717638        if (!IsActive)
 3639            return;
 640
 289714641        if (!IsPartitioned)
 642        {
 461643            InitialPartition();
 460644            return;
 645        }
 646
 289253647        bool refreshPartition = RebuildRuntimeShapeState(skipUnchangedMassProperties: skipUnchangedMassProperties)
 289253648            || Context.Collisions.IsPartitionRefreshRequired(this);
 289244649        PartitionChanged = false;
 289244650        if (refreshPartition)
 129281651            UpdatePartition();
 289244652    }
 653
 654    private void UpdatePartition()
 655    {
 129541656        MarkBroadPhaseChanged();
 657
 129541658        if (!Context.Collisions.IsPartitionRefreshRequired(this))
 59659            return;
 660
 129482661        SwiftList<WorldVoxelIndex> partitionCoordinates = _partitionState.Coordinates!;
 129482662        bool partitioned = Context.Collisions.PartitionObject(this, ref partitionCoordinates);
 129482663        _partitionState.Coordinates = partitionCoordinates;
 129482664        if (!partitioned)
 817665            return;
 666
 128665667        SetPreviousGridBounds();
 668
 128665669        _partitionState.MarkPartitioned();
 128665670    }
 671
 672    private void SetBodylessWorldPose(
 673        Vector3d position,
 674        FixedQuaternion rotation,
 675        bool setRotation,
 676        string operation)
 677    {
 334678        GravitasWorldContext context = _context!;
 334679        context.ThrowIfFixedStepMutationNotAllowed();
 333680        FixedTransform transform = _agent!.Transform;
 333681        Vector3d localPosition = transform.LocalPosition;
 333682        FixedQuaternion localRotation = transform.LocalRotation;
 333683        bool transformed = setRotation
 333684            ? transform.TrySetWorldPose(transform.WorldPosition, rotation)
 333685            : transform.TrySetWorldPosition(position);
 333686        ChronicleGuard.ThrowIfTrue(
 333687            !transformed,
 333688            operation,
 333689            setRotation
 333690                ? "Static collider transform cannot represent the requested world rotation."
 333691                : "Static collider transform cannot represent the requested world position.");
 692
 693        try
 694        {
 331695            RebuildRuntimeShapeState();
 329696        }
 2697        catch
 698        {
 2699            transform.LocalPosition = localPosition;
 2700            transform.LocalRotation = localRotation;
 2701            throw;
 702        }
 703
 329704        if (!IsActive)
 1705            return;
 706
 328707        if (IsPartitioned)
 182708            UpdatePartition();
 709        else
 146710            InitialPartition();
 711
 328712        if (context.Settings.RuntimeMode.RunsMixedContacts())
 8713            context.MixedCollisions.Refresh3DColliderPartition(this);
 328714    }
 715
 716    /// <summary>Assigns a 3D hierarchy parent used for collision exclusion.</summary>
 717    public void SetParent(LSCollider parent)
 718    {
 31719        ThrowIfCompoundPartLifecycle(nameof(SetParent));
 31720        if (_hierarchyState.SetParent(this, parent))
 721        {
 26722            MarkContactDependencyChanged();
 26723            _body?.Wake();
 724        }
 26725    }
 726
 727    /// <summary>Assigns a 2D hierarchy parent used for mixed collision exclusion.</summary>
 728    public void SetParent(LSCollider2D parent)
 729    {
 9730        ThrowIfCompoundPartLifecycle(nameof(SetParent));
 9731        if (_hierarchyState.SetParent(this, parent))
 732        {
 8733            MarkContactDependencyChanged();
 8734            _body?.Wake();
 735        }
 4736    }
 737
 738    /// <summary>Removes this collider from its current hierarchy parent.</summary>
 739    public void ClearParent()
 740    {
 456741        ThrowIfCompoundPartLifecycle(nameof(ClearParent));
 456742        if (_hierarchyState.ClearParent(this))
 743        {
 5744            MarkContactDependencyChanged();
 5745            _body?.Wake();
 746        }
 455747    }
 748
 749    /// <summary>Gets whether hierarchy rules exclude collision with another 3D collider.</summary>
 750    public bool IsSibling(LSCollider other)
 751    {
 2490152752        return _hierarchyState.ExcludesCollisionWith(other._hierarchyState, HierarchyKey, other.HierarchyKey);
 753    }
 754
 755    internal bool ExcludesMixedCollisionWith(LSCollider2D other) =>
 361510756        _hierarchyState.ExcludesCollisionWith(other.HierarchyState, HierarchyKey, other.HierarchyKey);
 757
 758    private bool RebuildRuntimeShapeState(bool refreshMassProperties = true, bool geometryOnly = false,
 759        bool skipUnchangedMassProperties = false)
 760    {
 422860761        ColliderShapeSnapshot snapshot = CaptureShapeSnapshot();
 762        // CCD needs pending geometry, not an extra pose-only publication that
 763        // would advance runtime versions and disturb retained solver caches.
 422851764        if (geometryOnly && !_runtimeShapeState.IsDirty && snapshot.OwnerScale == _committedOwnerScale)
 74429765            return false;
 348422766        if (!_runtimeShapeState.ShouldRebuild(snapshot))
 212466767            return false;
 768
 135956769        bool contactDependencyChanged = _runtimeShapeState.IsDirty
 135956770            || snapshot.OwnerScale != _committedOwnerScale || _body?.IsDynamic != true;
 135956771        PrepareRuntimeShape(
 135956772            snapshot,
 135956773            includeBodyAttachment:
 135956774                _body != null);
 135949775        PublishPreparedShape(contactDependencyChanged);
 135949776        if (refreshMassProperties && (!skipUnchangedMassProperties || contactDependencyChanged))
 68381777            _body?.RefreshMassPropertiesFromColliderShape();
 135949778        return true;
 779    }
 780
 781    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 782    internal bool RebuildRuntimeShapeOnly(bool refreshMassProperties = true, bool geometryOnly = false) =>
 119320783        RebuildRuntimeShapeState(refreshMassProperties, geometryOnly);
 784
 785    /// <summary>Marks derived runtime shape state for deterministic rebuilding.</summary>
 786    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 787    protected void MarkShapeDirty()
 788    {
 5008789        _runtimeShapeState.MarkDirty();
 5008790        if (_compoundOwner != null)
 791        {
 1792            _compoundOwner.MarkShapeDirty();
 1793            return;
 794        }
 795
 5007796        _body?.Wake();
 48797    }
 798
 799    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 143412800    private void MarkBroadPhaseChanged() => _partitionState.MarkBroadPhaseChanged();
 801
 802    /// <summary>Updates derived authored dimensions after <see cref="Radius"/> changes.</summary>
 2803    protected virtual void OnRadiusChanged() { }
 804
 805    /// <summary>Updates derived material state after <see cref="Material"/> changes.</summary>
 3604806    protected virtual void OnMaterialChanged() { }
 807
 808    /// <summary>Normalizes an authored size for the derived shape.</summary>
 1129809    protected virtual Vector3d NormalizeSize(Vector3d value) => value;
 810
 811    private static void ValidateSize(Vector3d value)
 812    {
 4096813        ChronicleGuard.ThrowIfArgument(
 4096814            value.X <= Fixed64.Zero || value.Y <= Fixed64.Zero || value.Z <= Fixed64.Zero,
 4096815            nameof(value),
 4096816            "Collider size components must be greater than zero.");
 4090817    }
 818
 819    /// <summary>
 820    /// Gets the point on this collider's surface nearest to a world-space point.
 821    /// </summary>
 822    /// <param name="other"></param>
 823    /// <returns></returns>
 824    public abstract Vector3d ClosestPointOnSurface(Vector3d other);
 825
 826    /// <summary>
 827    /// The direction pointing outward from the surface of the collider at the point
 828    /// </summary>
 829    /// <param name="point"></param>
 830    /// <returns></returns>
 831    public abstract Vector3d GetNormalAtPoint(Vector3d point);
 832
 833    /// <summary>
 834    /// Returns the semantic closest surface feature without requiring its
 835    /// world point or distance to fit in one <see cref="Fixed64"/> vector.
 836    /// </summary>
 837    internal abstract FixedPointAnchor GetClosestSurfaceAnchor(
 838        Vector3d point,
 839        out Vector3d normal);
 840
 841    /// <summary>
 842    /// Retains exact primitive-solid containment alongside the selected feature.
 843    /// The default preserves surface-only query semantics.
 844    /// </summary>
 845    internal virtual FixedPointAnchor GetClosestSurfaceAnchor(
 846        Vector3d point, out Vector3d normal, out bool contained)
 847    {
 2848        contained = false;
 2849        return GetClosestSurfaceAnchor(point, out normal);
 850    }
 851
 852    /// <summary>
 853    /// Tries to resolve a normal that is invariant across the planar surface
 854    /// feature containing <paramref name="point"/>. A successful result must
 855    /// be a nonzero outward normal.
 856    /// </summary>
 857    internal virtual bool TryGetPlanarSurfaceNormal(Vector3d point, out Vector3d normal)
 858    {
 1473859        normal = Vector3d.Zero;
 1473860        return false;
 861    }
 862
 863    /// <summary>
 864    /// Checks if position is in the padded bounds of the collider, used for broad phase collision detection
 865    /// </summary>
 866    /// <param name="cellPadding">The topology cell edge used to conservatively pad the bounds.</param>
 867    /// <param name="position">The position to check</param>
 868    /// <returns>True if position within bounds</returns>
 869    public bool IsPositionInBounds(Fixed64 cellPadding, Vector3d position)
 870    {
 9626848871        return position.X + cellPadding >= BoundsMin.X
 9626848872            && position.X - cellPadding <= BoundsMax.X
 9626848873            && position.Y + cellPadding >= BoundsMin.Y
 9626848874            && position.Y - cellPadding <= BoundsMax.Y
 9626848875            && position.Z + cellPadding >= BoundsMin.Z
 9626848876            && position.Z - cellPadding <= BoundsMax.Z;
 877    }
 878
 879    /// <summary>
 880    /// Checks if this object overlaps the line formed by p1 and p2
 881    /// </summary>
 882    /// <param name="worker">The prepared ray-axis worker for the owning query service.</param>
 883    /// <param name="outputIntersectionPoints"></param>
 884    /// <returns></returns>
 885    public abstract bool ColliderOverlapsRay(RaycastSegmentWorker worker, ref SwiftList<Vector3d> outputIntersectionPoin
 886
 887    void IColliderHierarchyNode.AddChild(ColliderHierarchyKey key)
 888    {
 37889        ThrowIfCompoundPartLifecycle(nameof(IColliderHierarchyNode.AddChild));
 37890        _hierarchyState.AddChild(key);
 37891    }
 892
 893    void IColliderHierarchyNode.RemoveChild(ColliderHierarchyKey key)
 894    {
 6895        ThrowIfCompoundPartLifecycle(nameof(IColliderHierarchyNode.RemoveChild));
 6896        _hierarchyState.RemoveChild(key);
 6897    }
 898
 899    void IColliderHierarchyNode.ClearParentReference()
 900    {
 5901        if (_hierarchyState.ClearParentReference())
 902        {
 4903            MarkContactDependencyChanged();
 4904            _body?.Wake();
 905        }
 4906    }
 907
 908    bool IColliderHierarchyNode.TryGetHierarchyColliderByKey(ColliderHierarchyKey key, out IColliderHierarchyNode? colli
 909    {
 12910        collider = null;
 12911        if (!key.IsValid || _context == null)
 1912            return false;
 913
 11914        if (key.Is3D && _context.Physics.TryGetColliderById(key.Id, out LSCollider? collider3D))
 915        {
 4916            collider = collider3D;
 4917            return true;
 918        }
 919
 7920        if (key.Is2D && _context.Physics2D.TryGetColliderById(key.Id, out LSCollider2D? collider2D))
 921        {
 5922            collider = collider2D;
 5923            return true;
 924        }
 925
 2926        return false;
 927    }
 928
 929    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 930    internal void SetPhysicsState(int id, int serviceIndex, int replayOrder)
 931    {
 13254932        ChronicleGuard.ThrowIfNegative(id, nameof(id));
 13254933        ChronicleGuard.ThrowIfNegative(serviceIndex, nameof(serviceIndex));
 13254934        ChronicleGuard.ThrowIfNegative(replayOrder, nameof(replayOrder));
 13254935        _id = id;
 13254936        _serviceIndex = serviceIndex;
 13254937        _replayOrder = replayOrder;
 13254938        _replayOrdinal = -1;
 13254939    }
 940
 941    internal void SetServiceIndex(int serviceIndex)
 942    {
 125943        ChronicleGuard.ThrowIfNegative(serviceIndex, nameof(serviceIndex));
 125944        _serviceIndex = serviceIndex;
 125945    }
 946
 947    internal void SetReplayOrdinal(int replayOrdinal)
 948    {
 23043949        ChronicleGuard.ThrowIfNegative(replayOrdinal, nameof(replayOrdinal));
 23043950        _replayOrdinal = replayOrdinal;
 23043951    }
 952
 953    internal void SetServiceRefreshIndex(int serviceRefreshIndex)
 954    {
 5876955        ChronicleGuard.ThrowIfNegative(serviceRefreshIndex, nameof(serviceRefreshIndex));
 5876956        _serviceRefreshIndex = serviceRefreshIndex;
 5876957    }
 958
 959    internal void ClearServiceRefreshIndex()
 960    {
 7964961        _serviceRefreshIndex = -1;
 7964962    }
 963
 964    internal void ClearPhysicsState()
 965    {
 550966        _partitionState.MarkUnpartitioned();
 550967        _partitionState.ClearCoordinates();
 550968        _mixedPartitionState.MarkUnpartitioned();
 550969        _mixedPartitionState.ClearCoordinates();
 550970        _pairState.ClearCollisionPairs();
 550971        _pairState.ClearCollisionPairHolders();
 550972        _id = -1;
 550973        _serviceIndex = -1;
 550974        _replayOrder = -1;
 550975        _replayOrdinal = -1;
 550976        _serviceRefreshIndex = -1;
 550977    }
 978
 979    void IPhysicsColliderRegistryItem.SetRegistryState(int id, int serviceIndex, int replayOrder) =>
 13254980        SetPhysicsState(id, serviceIndex, replayOrder);
 981
 451982    int IPhysicsColliderRegistryItem.ServiceIndex => _serviceIndex;
 983
 141279984    int IPhysicsColliderRegistryItem.ReplayOrder => _replayOrder;
 985
 986    void IPhysicsColliderRegistryItem.SetRegistryServiceIndex(int serviceIndex) =>
 125987        SetServiceIndex(serviceIndex);
 988
 989    void IPhysicsColliderRegistryItem.SetRegistryReplayOrdinal(int replayOrdinal) =>
 23043990        SetReplayOrdinal(replayOrdinal);
 991
 550992    void IPhysicsColliderRegistryItem.ClearRegistryState() => ClearPhysicsState();
 993
 994    internal SwiftList<WorldVoxelIndex> GetOrCreateMixedPartitionCoordinates()
 995    {
 20604996        _mixedPartitionState.Coordinates ??= new();
 20604997        return _mixedPartitionState.Coordinates;
 998    }
 999
 1000    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1001    internal bool MatchesPartitionGridBounds(Vector3d min, Vector3d max, int partitionKind) =>
 3065041002        _partitionState.IsPartitioned
 3065041003        && _partitionState.LastGridBoundsMin == min
 3065041004        && _partitionState.LastGridBoundsMax == max
 3065041005        && _partitionState.LastPartitionKind == partitionKind;
 1006
 1007    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 35861008    internal void MarkUnpartitioned() => _partitionState.MarkUnpartitioned();
 1009
 1010    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 4881011    internal void ClearPartitionCoordinates() => _partitionState.ClearCoordinates();
 1012
 1013    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1014    internal bool MatchesMixedPartitionGridBounds(Vector3d min, Vector3d max, int partitionKind) =>
 310411015        _mixedPartitionState.IsPartitioned
 310411016        && _mixedPartitionState.LastGridBoundsMin == min
 310411017        && _mixedPartitionState.LastGridBoundsMax == max
 310411018        && _mixedPartitionState.LastPartitionKind == partitionKind;
 1019
 1020    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1021    internal void MarkMixedPartitioned(Vector3d min, Vector3d max, int partitionKind)
 1022    {
 205291023        _mixedPartitionState.SetPreviousGridBounds(min, max, partitionKind);
 205291024        _mixedPartitionState.MarkPartitioned();
 205291025    }
 1026
 1027    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1681028    internal void MarkMixedUnpartitioned() => _mixedPartitionState.MarkUnpartitioned();
 1029
 1030    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 931031    internal void ClearMixedPartitionCoordinates() => _mixedPartitionState.ClearCoordinates();
 1032
 1033    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 56537861034    internal bool IgnoresCollisionLayer(PhysicsLayer layer) => _ignoredCollisionLayers.Includes(layer);
 1035}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.Events.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.Events.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using Gravitas.CollisionHandling;
 9using SwiftCollections;
 10
 11namespace Gravitas.Colliders;
 12
 13/// <content>Exposes collision pair state and dispatches 3D and mixed contact notifications.</content>
 14public abstract partial class LSCollider
 15{
 617016    internal int CollisionPairCount => _pairState.CollisionPairCount;
 17
 617018    internal int CollisionPairHolderCount => _pairState.CollisionPairHolderCount;
 19
 532520    internal SwiftDictionary<int, CollisionPair>? CollisionPairs => _pairState.CollisionPairs;
 21
 532522    internal SwiftHashSet<int>? CollisionPairHolders => _pairState.CollisionPairHolders;
 23
 24
 25    /// <summary>Raised while this collider is touching another collider that owns a 3D body.</summary>
 26    public event BodyCollisionFunc? OnContact;
 27    /// <summary>Raised on the first simulation frame this collider touches another 3D body.</summary>
 28    public event BodyCollisionFunc? OnContactEnter;
 29    /// <summary>Raised when this collider stops touching another 3D body.</summary>
 30    public event BodyCollisionFunc? OnContactExit;
 31
 32
 33
 34    /// <summary>
 35    /// Raised on the first simulation frame this collider participates in a valid trigger pair.
 36    /// </summary>
 37    public event TriggerCollisionFunc? OnTriggerEnter;
 38
 39    /// <summary>
 40    /// Raised each simulation frame this collider participates in an overlapped valid trigger pair.
 41    /// </summary>
 42    public event TriggerCollisionFunc? OnTriggerStay;
 43
 44    /// <summary>
 45    /// Raised when this collider stops participating in a valid trigger pair.
 46    /// </summary>
 47    public event TriggerCollisionFunc? OnTriggerExit;
 48
 49
 50    /// <summary>Raised while this collider has a physical mixed contact with a 2D collider.</summary>
 51    public event MixedCollisionFunc? OnMixedContact;
 52    /// <summary>Raised when this collider begins a physical mixed contact with a 2D collider.</summary>
 53    public event MixedCollisionFunc? OnMixedContactEnter;
 54    /// <summary>Raised when this collider ends a physical mixed contact with a 2D collider.</summary>
 55    public event MixedCollisionFunc? OnMixedContactExit;
 56
 57    /// <summary>
 58    /// Raised on the first mixed 3D/2D simulation frame this collider participates in a valid trigger pair.
 59    /// </summary>
 60    public event MixedCollisionFunc? OnMixedTriggerEnter;
 61
 62    /// <summary>
 63    /// Raised each mixed 3D/2D simulation frame this collider participates in an overlapped valid trigger pair.
 64    /// </summary>
 65    public event MixedCollisionFunc? OnMixedTriggerStay;
 66
 67    /// <summary>
 68    /// Raised when this collider stops participating in a valid mixed 3D/2D trigger pair.
 69    /// </summary>
 70    public event MixedCollisionFunc? OnMixedTriggerExit;
 71
 72    internal void NotifyContact(LSCollider other, bool isColliding, bool isChanged) =>
 2173        NotifyContact(
 2174            other,
 2175            other.Body,
 2176            isColliding,
 2177            isChanged,
 2178            allowInactive: false,
 2179            new ColliderLifetimeToken(this),
 2180            new ColliderLifetimeToken(other),
 2181            IsTrigger || other.IsTrigger,
 2182            ColliderTriggerEventPolicy.ShouldRaise(this, other));
 83
 84    internal void NotifyContact(
 85        LSCollider other,
 86        SolidBody? otherBody,
 87        bool isColliding,
 88        bool isChanged,
 89        bool allowInactive,
 90        in ColliderLifetimeToken registration,
 91        in ColliderLifetimeToken otherRegistration,
 92        bool isTriggerPair,
 93        bool shouldRaiseTrigger)
 94    {
 11035195        if (isColliding
 11035196            ? !registration.IsActive || !otherRegistration.IsActive
 11035197            : allowInactive ? !registration.IsCurrentLifetime : !registration.IsActive)
 98        {
 299            return;
 100        }
 101
 110349102        if (isColliding)
 103        {
 108608104            if (isTriggerPair)
 105            {
 61106                if (shouldRaiseTrigger)
 107                {
 58108                    if (isChanged)
 109                    {
 50110                        OnTriggerEnter?.Invoke(other);
 49111                        if (!registration.IsActive || !otherRegistration.IsActive)
 2112                            return;
 113                    }
 114
 55115                    OnTriggerStay?.Invoke(other);
 116                }
 117
 15118                return;
 119            }
 120
 108547121            if (isChanged && otherBody != null)
 122            {
 1726123                OnContactEnter?.Invoke(otherBody);
 1724124                if (!registration.IsActive || !otherRegistration.IsActive)
 5125                    return;
 126            }
 127
 108540128            if (otherBody != null)
 64315129                OnContact?.Invoke(otherBody);
 130
 44665131            return;
 132        }
 133
 1741134        if (!isChanged)
 1135            return;
 136
 1740137        if (isTriggerPair)
 138        {
 40139            if (shouldRaiseTrigger)
 38140                OnTriggerExit?.Invoke(other);
 141
 21142            return;
 143        }
 144
 1700145        if (otherBody != null)
 998146            OnContactExit?.Invoke(otherBody);
 897147    }
 148
 149    internal void NotifyMixedContact(LSCollider2D other, bool isColliding, bool isChanged, bool isTriggerPair) =>
 14150        NotifyMixedContact(
 14151            other,
 14152            isColliding,
 14153            isChanged,
 14154            isTriggerPair,
 14155            allowInactive: false,
 14156            new ColliderLifetimeToken(this),
 14157            new ColliderLifetimeToken2D(other),
 14158            ColliderTriggerEventPolicy.ShouldRaise(this, other));
 159
 160    internal void NotifyMixedContact(
 161        LSCollider2D other,
 162        bool isColliding,
 163        bool isChanged,
 164        bool isTriggerPair,
 165        bool allowInactive,
 166        in ColliderLifetimeToken registration,
 167        in ColliderLifetimeToken2D otherRegistration,
 168        bool shouldRaiseTrigger)
 169    {
 16302170        if (isColliding
 16302171            ? !registration.IsActive || !otherRegistration.IsActive
 16302172            : allowInactive
 16302173                ? !registration.IsCurrentLifetime || !otherRegistration.IsCurrentLifetime
 16302174                : !registration.IsActive)
 175        {
 2176            return;
 177        }
 178
 16300179        if (isColliding)
 180        {
 16109181            if (isTriggerPair)
 182            {
 139183                if (shouldRaiseTrigger)
 184                {
 134185                    if (isChanged)
 186                    {
 59187                        OnMixedTriggerEnter?.Invoke(other);
 59188                        if (!registration.IsActive || !otherRegistration.IsActive)
 8189                            return;
 190                    }
 191
 126192                    OnMixedTriggerStay?.Invoke(other);
 193                }
 194
 16195                return;
 196            }
 197
 15970198            if (isChanged)
 199            {
 628200                OnMixedContactEnter?.Invoke(other);
 627201                if (!registration.IsActive || !otherRegistration.IsActive)
 3202                    return;
 203            }
 204
 15966205            OnMixedContact?.Invoke(other);
 118206            return;
 207        }
 208
 191209        if (!isChanged)
 1210            return;
 211
 190212        if (isTriggerPair)
 213        {
 23214            if (shouldRaiseTrigger)
 21215                OnMixedTriggerExit?.Invoke(other);
 216
 18217            return;
 218        }
 219
 167220        OnMixedContactExit?.Invoke(other);
 64221    }
 222}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.GeometryAdmission.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.GeometryAdmission.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using FixedMathSharp;
 9
 10namespace Gravitas.Colliders;
 11
 12/// <content>Preflights authored mutations before changing shape state or waking an owner.</content>
 13public abstract partial class LSCollider
 14{
 15    private void ValidateGeometryMutation(Vector3d offset, Vector3d size, Fixed64 radius)
 16    {
 502317        LSCollider root = _compoundOwner ?? this;
 502318        if (root._agent == null)
 493419            return; // Detached authoring may be compensated by a later host or part scale.
 20
 8921        Vector3d ownerScale = ColliderScalePolicy.CaptureScale(root._agent.Transform);
 8922        var candidate = new ColliderShapeSnapshot(default, default, ownerScale,
 8923            _compoundOwner == null ? Vector3d.One : _compoundLocalScale, offset, size, radius);
 8924        Fixed64 reach = root is LSCompoundCollider compound
 8925            ? compound.GetMutationGeometryReach(this, candidate)
 8926            : GetCandidateGeometryReach(candidate);
 8927        if (root._body != null)
 6128            reach = ColliderGeometryPolicy.Add(ColliderGeometryPolicy.Attachment(
 6129                ReferenceEquals(root, this) ? offset : root._offset, ownerScale), reach);
 8930        ColliderGeometryPolicy.ValidateReach(reach, nameof(candidate));
 7331    }
 32
 33    internal Fixed64 GetCandidateGeometryReach(in ColliderShapeSnapshot snapshot)
 34    {
 8935        switch (this)
 36        {
 37            case LSSphereCollider:
 4238                Vector3d radii = ColliderScalePolicy.ScalePositive(
 4239                    Vector3d.One * snapshot.Radius, snapshot.OwnerScale, snapshot.PartScale, Fixed64.One);
 4240                return FixedMath.Max(radii.X, FixedMath.Max(radii.Y, radii.Z));
 41            case LSCapsuleCollider:
 842                LSCapsuleCollider.GetScaledGeometry(snapshot, out Fixed64 radius, out Fixed64 length);
 843                return ColliderGeometryPolicy.Capsule(radius, length);
 44            case LSCuboidCollider:
 2045                return ColliderGeometryPolicy.Magnitude(ColliderScalePolicy.ScalePositive(
 2046                    snapshot.Size, snapshot.OwnerScale, snapshot.PartScale, Fixed64.Two));
 47            case LSConeCollider:
 48            case LSCylinderCollider:
 1349                return ColliderGeometryPolicy.FiniteAxis(FixedMath.Max(
 1350                    ColliderScalePolicy.ScalePositive(snapshot.Radius, snapshot.OwnerScale.X, snapshot.PartScale.X),
 1351                    ColliderScalePolicy.ScalePositive(snapshot.Radius, snapshot.OwnerScale.Z, snapshot.PartScale.Z)),
 1352                    ColliderScalePolicy.ScalePositive(snapshot.Size.Y, snapshot.OwnerScale.Y, snapshot.PartScale.Y));
 53            case LSMeshCollider mesh:
 554                return mesh.GeometryMesh.GetScaledLocalRadius(snapshot.OwnerScale, snapshot.PartScale);
 55            default:
 156                return Fixed64.MaxValue;
 57        }
 58    }
 59}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.MassProperties.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.MassProperties.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System.Runtime.CompilerServices;
 9using FixedMathSharp;
 10
 11namespace Gravitas.Colliders;
 12
 13/// <content>Derives frontal area, center of mass, and inertia inputs from collider geometry.</content>
 14public abstract partial class LSCollider
 15{
 16    /// <summary>Gets the frontal-area estimate for a world-space direction; the base implementation returns <see cref="
 10817    public virtual Fixed64 GetFrontalArea(Vector3d direction) => Area;
 18
 19    /// <summary>
 20    /// Calculates the body-local center of mass offset implied by this collider's current shape state.
 21    /// </summary>
 22    public virtual Vector3d CalculateLocalCenterOfMassOffset()
 23    {
 8558024        ExactMassPoint3D point = CalculateLocalMassPoint();
 8557925        ChronicleGuard.ThrowIfTrue(
 8557926            !point.TryGetPoint(out Vector3d center),
 8557927            nameof(CalculateLocalCenterOfMassOffset),
 8557928            "The collider's body-local center of mass is outside the Fixed64 coordinate domain.");
 8557829        return center;
 30    }
 31
 32    internal virtual ExactMassPoint3D CalculateLocalMassPoint() =>
 8556133        TransformRelativeMassPropertyPointExact(Vector3d.Zero);
 34
 35    internal virtual ExactMassPoint3D CalculatePreparedLocalMassPoint() =>
 1523736        TransformPreparedRelativeMassPropertyPointExact(Vector3d.Zero);
 37
 38    /// <summary>
 39    /// Calculates the deterministic relative measure used to distribute mass
 40    /// when this shape is owned by a compound collider.
 41    /// </summary>
 42    /// <remarks>
 43    /// Solid shapes return volume. Explicit surface-approximation shapes may
 44    /// return a documented shell measure instead.
 45    /// </remarks>
 46    internal abstract ExactMassWeight CalculateMassPropertyWeight();
 47
 48    internal abstract ExactMassWeight CalculatePreparedMassPropertyWeight();
 49
 25450    internal virtual bool SupportsMassProperties => true;
 51
 52    /// <summary>Calculates inertia for a mass about a body-local reference point.</summary>
 53    public virtual Fixed3x3 CalculateInertiaTensor(
 54        Fixed64 mass,
 55        Vector3d localCenterOfMassOffset)
 56    {
 2588057        if (mass <= Fixed64.Zero)
 158            return Fixed3x3.Zero;
 59
 2587960        Fixed3x3 centerTensor =
 2587961            CalculateCenterOfMassInertiaTensor(mass);
 2587962        ExactMassPoint3D massPoint = CalculateLocalMassPoint();
 2587963        if (massPoint.TryAddParallelAxisTensor(
 2587964                centerTensor,
 2587965                mass,
 2587966                localCenterOfMassOffset,
 2587967                out Fixed3x3 tensor))
 68        {
 2586869            return tensor;
 70        }
 71
 72        // Explicit body center overrides historically use the collider's
 73        // saturating public tensor contract. Semantic child centers have no
 74        // scalar fallback and must remain checked.
 1175        if (!massPoint.TryGetPoint(out Vector3d center))
 76        {
 177            ChronicleGuard.ThrowIfTrue(
 178                true,
 179                nameof(localCenterOfMassOffset),
 180                "The requested inertia tensor is outside the Fixed64 scalar domain.");
 81        }
 82
 1083        return InertiaTensorMath.AddParallelAxisTensor(
 1084            centerTensor,
 1085            mass,
 1086            localCenterOfMassOffset - center);
 87    }
 88
 89    internal abstract Fixed3x3 CalculateCenterOfMassInertiaTensor(
 90        Fixed64 mass);
 91
 92    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 93    internal ExactMassPoint3D TransformRelativeMassPropertyPointExact(
 94        Vector3d partRelativePoint) =>
 10281695        _compoundOwner == null
 10281696            ? ExactMassPoint3D.CreateScaledLocalComposition(
 10281697                LocalOffset,
 10281698                GetCurrentOwnerScale(),
 10281699                Vector3d.Zero,
 102816100                Vector3d.One,
 102816101                partRelativePoint,
 102816102                FixedQuaternion.Identity)
 102816103            : ExactMassPoint3D.CreateScaledLocalComposition(
 102816104                _compoundOwner.LocalOffset,
 102816105                GetCurrentOwnerScale(),
 102816106                LocalOffset,
 102816107                GetCurrentOwnerScale(),
 102816108                partRelativePoint,
 102816109                _compoundLocalRotation);
 110
 111    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 112    internal ExactMassPoint3D TransformPreparedRelativeMassPropertyPointExact(
 113        Vector3d partRelativePoint) =>
 38593114        _compoundOwner == null
 38593115            ? ExactMassPoint3D.CreateScaledLocalComposition(
 38593116                _preparedSnapshot.LocalOffset,
 38593117                _preparedSnapshot.OwnerScale,
 38593118                Vector3d.Zero,
 38593119                Vector3d.One,
 38593120                partRelativePoint,
 38593121                FixedQuaternion.Identity)
 38593122            : ExactMassPoint3D.CreateScaledLocalComposition(
 38593123                _compoundOwner._preparedSnapshot.LocalOffset,
 38593124                _preparedSnapshot.OwnerScale,
 38593125                _preparedSnapshot.LocalOffset,
 38593126                _preparedSnapshot.OwnerScale,
 38593127                partRelativePoint,
 38593128                _preparedCompoundLocalRotation);
 129
 313130    internal FixedQuaternion CompoundLocalRotation => _compoundLocalRotation;
 131}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.ReplayHash.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.ReplayHash.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using Chronicler.Hashing;
 10using FixedMathSharp.Chronicler;
 11using Gravitas.Materials;
 12
 13namespace Gravitas.Colliders;
 14
 15/// <content>Writes authoritative 3D collider state and hierarchy references in replay order.</content>
 16public abstract partial class LSCollider
 17{
 18    internal void ContributeReplayHash(
 19        ref ChronicleHashWriter writer,
 20        GravitasReplayHashMode mode)
 21    {
 1109222        writer.WriteSection("collider.3d", 4);
 1109223        writer.WriteInt32(_replayOrdinal);
 1109224        writer.WriteBool(_active);
 1109225        writer.WriteBool(_isTrigger);
 1109226        writer.WritePhysicsLayer(_layer);
 1109227        writer.WritePhysicsLayerMask(_ignoredCollisionLayers);
 1109228        WriteMaterial(ref writer, _material);
 1109229        writer.WriteEnum(Shape);
 1109230        writer.WriteInt32(Priority);
 1109231        writer.WriteVector3d(_offset);
 1109232        writer.WriteFixed64(_radius);
 1109233        writer.WriteVector3d(_size);
 1109234        writer.WriteVector3d(Position);
 1109235        writer.WriteQuaternion(Rotation);
 1109236        writer.WriteVector3d(_committedOwnerScale);
 1109237        writer.WriteVector3d(_committedPartScale);
 1109238        writer.WriteVector3d(Center);
 1109239        writer.WriteInt32(HierarchyChildCount);
 1109240        WriteReplayHierarchyKey(ref writer, HierarchyKey);
 1109241        WriteReplayHierarchyKey(ref writer, ParentKey);
 1109242        WriteReplayHierarchyKey(ref writer, TopParentKey);
 43
 1109244        ContributeShapeReplayHash(ref writer);
 45
 1109246        if (mode != GravitasReplayHashMode.AuthoritativeWithSolverCaches)
 503047            return;
 48
 606249        writer.WriteSection("collider.3d.caches", 1);
 606250        writer.WriteVector3d(BoundsMin);
 606251        writer.WriteVector3d(BoundsMax);
 606252        writer.WriteUInt32(RuntimeShapeVersion);
 606253        writer.WriteBool(IsPartitioned);
 606254        writer.WriteBool(IsMixedPartitioned);
 606255        writer.WriteInt32(PartitionKind);
 606256        writer.WriteInt32(MixedPartitionKind);
 606257        writer.WriteUInt32(BroadPhaseVersion);
 606258        writer.WriteUInt32(RaycastVersion);
 606259        writer.WriteUInt32(CircleQueryVersion);
 606260        writer.WriteInt32(CollisionPairCount);
 606261        writer.WriteInt32(CollisionPairHolderCount);
 606262    }
 63
 64    private void ContributeShapeReplayHash(ref ChronicleHashWriter writer)
 65    {
 1109266        writer.WriteSection("collider.3d.shape", 3);
 1109267        switch (this)
 68        {
 69            case LSCapsuleCollider capsule:
 25570                writer.WriteVector3d(capsule.Center);
 25571                writer.WriteFixed64(capsule.AxisLength);
 25572                writer.WriteFixed64(capsule.ScaledRadius);
 25573                break;
 74
 75            case LSCylinderCollider cylinder:
 13776                writer.WriteVector3d(cylinder.Center);
 13777                writer.WriteFixed64(cylinder.Height);
 13778                writer.WriteFixed64(cylinder.ScaledRadius);
 13779                break;
 80
 81            case LSConeCollider cone:
 24082                writer.WriteVector3d(cone.Center);
 24083                writer.WriteFixed64(cone.Height);
 24084                writer.WriteFixed64(cone.ScaledRadius);
 24085                break;
 86
 87            case LSCuboidCollider cuboid:
 43888                writer.WriteVector3d(cuboid.OrientedBox.Center);
 43889                writer.WriteQuaternion(cuboid.OrientedBox.Orientation);
 43890                writer.WriteVector3d(cuboid.OrientedBox.HalfExtents);
 43891                break;
 92
 93            case LSMeshCollider mesh:
 560694                writer.WriteEnum(mesh.Mode);
 560695                writer.WriteEnum(mesh.InertiaPolicy);
 560696                writer.WriteInt32(mesh.Mesh.VertexCount);
 6035297                for (int i = 0; i < mesh.Mesh.LocalVertices.Length; i++)
 2457098                    writer.WriteVector3d(mesh.Mesh.LocalVertices[i]);
 560699                writer.WriteInt32(mesh.Mesh.Triangles.Length);
 110260100                for (int i = 0; i < mesh.Mesh.Triangles.Length; i++)
 49524101                    writer.WriteInt32(mesh.Mesh.Triangles[i]);
 5606102                break;
 103
 104            case LSCompoundCollider compound:
 127105                writer.WriteInt32(compound.PartCount);
 127106                ReadOnlySpan<CompoundColliderPart> parts = compound.Parts;
 630107                for (int i = 0; i < parts.Length; i++)
 188108                    ContributeCompoundPartReplayHash(ref writer, parts[i]);
 127109                break;
 110
 111            default:
 4289112                writer.WriteFixed64(Area);
 113                break;
 114        }
 4289115    }
 116
 117    private void WriteReplayHierarchyKey(ref ChronicleHashWriter writer, ColliderHierarchyKey key)
 118    {
 33276119        if (!TryResolveReplayHierarchyOrdinal(key, out int replayOrdinal))
 120        {
 22174121            writer.WriteUInt64(0UL);
 22174122            return;
 123        }
 124
 11102125        writer.WriteUInt64(((ulong)key.Dimension << 32) | (uint)replayOrdinal);
 11102126    }
 127
 128    private bool TryResolveReplayHierarchyOrdinal(ColliderHierarchyKey key, out int replayOrdinal)
 129    {
 33276130        replayOrdinal = -1;
 33276131        if (!key.IsValid || _context == null)
 22170132            return false;
 133
 11106134        if (key.Is3D)
 135        {
 11094136            _context.Physics.TryGetColliderById(key.Id, out LSCollider? collider);
 11094137            replayOrdinal = collider!.ReplayOrdinal;
 11094138            return replayOrdinal >= 0;
 139        }
 140
 12141        _context.Physics2D.TryGetColliderById(key.Id, out LSCollider2D? collider2D);
 12142        replayOrdinal = collider2D!.ReplayOrdinal;
 12143        return replayOrdinal >= 0;
 144    }
 145
 146    private static void ContributeCompoundPartReplayHash(
 147        ref ChronicleHashWriter writer,
 148        CompoundColliderPart part)
 149    {
 188150        writer.WriteVector3d(part.LocalOffset);
 188151        writer.WriteQuaternion(part.LocalRotation);
 188152        writer.WriteVector3d(part.LocalScale);
 188153        writer.WriteBool(part.HasMaterial);
 188154        if (part.TryGetMaterial(out PhysicsMaterial material))
 31155            WriteMaterial(ref writer, material);
 188156        ContributeShapeDefinitionReplayHash(ref writer, part.Shape);
 188157    }
 158
 159    private static void ContributeShapeDefinitionReplayHash(
 160        ref ChronicleHashWriter writer,
 161        ColliderShapeDefinition definition)
 162    {
 188163        writer.WriteEnum(definition.Kind);
 188164        writer.WriteBool(definition.HasMaterial);
 188165        if (definition.HasMaterial)
 20166            WriteMaterial(ref writer, definition.Material);
 188167        writer.WriteFixed64(definition.Radius);
 188168        writer.WriteFixed64(definition.Height);
 188169        writer.WriteVector3d(definition.Size);
 188170        writer.WriteEnum(definition.MeshInertiaPolicy);
 188171        writer.WriteInt32(definition.MeshVertexCount);
 712172        for (int i = 0; i < definition.MeshVertexCount; i++)
 168173            writer.WriteVector3d(definition.GetMeshVertex(i));
 188174        writer.WriteInt32(definition.MeshTriangleIndexCount);
 1528175        for (int i = 0; i < definition.MeshTriangleIndexCount; i++)
 576176            writer.WriteInt32(definition.GetMeshTriangleIndex(i));
 188177    }
 178
 179    private static void WriteMaterial(ref ChronicleHashWriter writer, PhysicsMaterial material)
 180    {
 11143181        writer.WriteFixed64(material.StaticFriction);
 11143182        writer.WriteFixed64(material.DynamicFriction);
 11143183        writer.WriteFixed64(material.Restitution);
 11143184        writer.WriteEnum(material.FrictionCombine);
 11143185        writer.WriteEnum(material.RestitutionCombine);
 11143186    }
 187}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.RuntimeLifecycle.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.RuntimeLifecycle.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System.Runtime.CompilerServices;
 9using FixedMathSharp;
 10using Gravitas.CollisionHandling;
 11using SwiftCollections;
 12
 13namespace Gravitas.Colliders;
 14
 15/// <content>Manages runtime binding, pair bookkeeping, compound part ownership, and deactivation.</content>
 16public abstract partial class LSCollider
 17{
 18    /// <summary>Records the current bounds and partition role for broad-phase refresh checks.</summary>
 19    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 20    public void SetPreviousGridBounds() =>
 14253621        _partitionState.SetPreviousGridBounds(BoundsMin, BoundsMax, Context.Collisions.ResolvePartitionKind(this));
 22
 23    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 24    internal bool TryGetCollisionPair(int otherId, out CollisionPair? collisionPair) =>
 301998025        _pairState.TryGetCollisionPair(otherId, out collisionPair);
 26
 27    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 28    internal bool TryAddCollisionPair(int otherId, CollisionPair collisionPair) =>
 82729        _pairState.TryAddCollisionPair(otherId, collisionPair);
 30
 31    internal bool TryRemoveCollisionPair(int otherId) =>
 13532        _pairState.TryRemoveCollisionPair(otherId, out _);
 33
 82634    internal bool TryAddCollisionPairHolder(int otherId) => _pairState.TryAddCollisionPairHolder(otherId);
 35
 13536    internal bool TryRemoveCollisionPairHolder(int otherId) => _pairState.TryRemoveCollisionPairHolder(otherId);
 37
 38    internal void ClearCollisionPairState()
 39    {
 45140        _pairState.ClearCollisionPairs();
 45141        _pairState.ClearCollisionPairHolders();
 45142    }
 43
 44    internal void ClearRuntimeRelationships()
 45    {
 45146        ClearChildParentReferences();
 45147        ClearParent();
 45148    }
 49
 50    /// <summary>Unregisters this collider, or deactivates its owning body.</summary>
 51    public void Deactivate()
 52    {
 30953        ThrowIfCompoundPartLifecycle(nameof(Deactivate));
 30954        if (_body != null)
 55        {
 2456            _body.Deactivate();
 2457            return;
 58        }
 59
 28560        DeactivateRuntimeRegistration();
 28561    }
 62
 63    internal void DeactivateRuntimeRegistration()
 64    {
 45365        _deactivationInProgress = true;
 66        try
 67        {
 45368            if (_id >= 0)
 45069                Context.Physics.DessimilateCollider(this);
 70
 45271            _active = false;
 45272            ClearBindingState();
 45273        }
 74        finally
 75        {
 45376            _deactivationInProgress = false;
 45377        }
 45278    }
 79
 80    private void ClearBindingState()
 81    {
 45282        _body = null;
 45283        _agent = null;
 45284        _context = null;
 45285        _preparedContext = null;
 45286    }
 87
 88    private void ClearChildParentReferences()
 89    {
 45190        SwiftHashSet<ulong>? children = _hierarchyState.Children;
 45191        if (children == null)
 44692            return;
 93
 2494        foreach (ulong childPackedKey in children)
 95        {
 796            ColliderHierarchyKey childKey = ColliderHierarchyKey.FromPacked(childPackedKey);
 797            if (((IColliderHierarchyNode)this).TryGetHierarchyColliderByKey(childKey, out IColliderHierarchyNode? child)
 798                child!.ClearParentReference();
 99        }
 100
 5101        _hierarchyState.ClearChildren();
 5102    }
 103
 104    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 105    internal void BindContext(GravitasWorldContext context)
 106    {
 34897107        ChronicleGuard.ThrowIfNull(context, nameof(context));
 34897108        ChronicleGuard.ThrowIfArgument(
 34897109            _context != null && !ReferenceEquals(_context, context),
 34897110            nameof(context),
 34897111            "Collider is already bound to a different GravitasWorldContext.");
 34897112        _context = context;
 34897113    }
 114
 115    internal void ReserveCompoundPart(
 116        LSCompoundCollider owner,
 117        FixedQuaternion localRotation,
 118        Vector3d localScale)
 119    {
 800120        ChronicleGuard.ThrowIfNull(owner, nameof(owner));
 800121        ChronicleGuard.ThrowIfArgument(
 800122            HasHostBinding,
 800123            nameof(owner),
 800124            "Compound collider parts cannot be initialized as standalone colliders.");
 799125        ChronicleGuard.ThrowIfArgument(
 799126            _compoundOwner != null && !ReferenceEquals(_compoundOwner, owner),
 799127            nameof(owner),
 799128            "Compound collider part is already owned by another compound collider.");
 129
 798130        _compoundOwner = owner;
 798131        _compoundLocalRotation = localRotation;
 798132        _compoundLocalScale = localScale;
 798133    }
 134
 135    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 136    private void ThrowIfCompoundPartLifecycle(string operation)
 137    {
 303878138        ChronicleGuard.ThrowIfTrue(
 303878139            _compoundOwner != null,
 303878140            operation,
 303878141            "Compound collider parts are geometry owned by LSCompoundCollider and cannot run standalone lifecycle operat
 303877142    }
 143
 144    private void SetTrigger(bool value)
 145    {
 104146        if (_isTrigger == value)
 17147            return;
 148
 87149        if (value)
 84150            ThrowIfCannotEnableTrigger(nameof(IsTrigger));
 151
 86152        _isTrigger = value;
 102153        if (this is LSMeshCollider mesh) mesh.StaticSurface?.Invalidate(changed: mesh);
 79154    }
 155
 156    private void ThrowIfCannotEnableTrigger(string operation)
 157    {
 84158        ChronicleGuard.ThrowIfArgument(
 84159            _body != null,
 84160            operation,
 84161            "Trigger colliders must be initialized without a SolidBody. Use InitializeWithNoBody for trigger volumes.");
 83162        ChronicleGuard.ThrowIfArgument(
 83163            _compoundOwner != null,
 83164            operation,
 83165            "Compound collider parts are not trigger identities. Set IsTrigger on the owning compound collider.");
 83166    }
 167
 168    private void ThrowIfTriggerWouldAttachToBody(string operation)
 169    {
 8426170        ChronicleGuard.ThrowIfArgument(
 8426171            _isTrigger,
 8426172            operation,
 8426173            "Trigger colliders must be initialized without a SolidBody. Use InitializeWithNoBody for trigger volumes.");
 8425174    }
 175
 176    private void ThrowIfLoadedTriggerHasBody(string operation)
 177    {
 105178        ChronicleGuard.ThrowIfArgument(
 105179            _isTrigger && _body != null,
 105180            operation,
 105181            "Loaded trigger state is invalid for a collider attached to a SolidBody.");
 103182    }
 183
 184    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 185    internal bool TryGetBoundContext(out GravitasWorldContext? context)
 186    {
 17836187        context = _context;
 17836188        return context != null;
 189    }
 190}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.Serialization.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.Serialization.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using Chronicler;
 9using FixedMathSharp;
 10using Gravitas.Materials;
 11using Gravitas.Support;
 12
 13namespace Gravitas.Colliders;
 14
 15/// <content>Records authoritative collider state and applies loaded values to the existing collider.</content>
 16public abstract partial class LSCollider
 17{
 18    /// <inheritdoc/>
 19    public void RecordData(IChronicler chronicler)
 20    {
 18921        RecordValues.Look(chronicler, ref _debug, "Debug", false);
 18922        RecordValues.Look(chronicler, ref _drawShape, "DrawShape", false);
 18923        RecordValues.Look(chronicler, ref _drawPartitions, "DrawPartitions", false);
 18924        RecordValues.Look(chronicler, ref _drawBoundingBox, "DrawBoundingBox", false);
 18925        RecordValues.Look(chronicler, ref _active, "Active", true);
 18926        RecordValues.Look(chronicler, ref _layer, "Layer", new());
 18927        RecordValues.Look(chronicler, ref _ignoredCollisionLayers, "IgnoredCollisionLayers", PhysicsLayerMask.None);
 18928        RecordValues.Look(chronicler, ref _material, "Material", PhysicsMaterial.Default);
 18929        RecordValues.Look(chronicler, ref _isTrigger, "IsTrigger", false);
 18930        RecordValues.Look(chronicler, ref _offset, "Offset", Vector3d.Zero);
 18931        RecordValues.Look(chronicler, ref _radius, "Radius", Fixed64.Half);
 18932        RecordValues.Look(chronicler, ref _size, "Size", Vector3d.One);
 33
 18934        if (chronicler.Mode == SerializationMode.Loading)
 35        {
 10536            ThrowIfLoadedTriggerHasBody(nameof(IsTrigger));
 10337            ApplyLoadedState();
 38        }
 18539    }
 40
 41    private void ApplyLoadedState()
 42    {
 10343        _runtimeShapeState.MarkDirty();
 10344        if (_context == null)
 945            return;
 46
 9447        RebuildRuntimeShapeState();
 48
 9249        if (!_active)
 50        {
 1051            if (IsPartitioned)
 652                _context.Collisions.ClearPartitionedObject(this, force: true);
 53
 1054            if (IsMixedPartitioned)
 255                _context.MixedCollisions.ClearPartitioned3DCollider(this, force: true);
 1056            return;
 57        }
 58
 8259        if (IsPartitioned)
 7860            UpdatePartition();
 61        else
 462            InitialPartition();
 8263        if (_context.Settings.RuntimeMode.RunsMixedContacts())
 964            _context.MixedCollisions.Refresh3DColliderPartition(this);
 8265    }
 66}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/3D/LSCollider.ShapeTransaction.cs

#LineLine coverage
 1//=======================================================================
 2// LSCollider.ShapeTransaction.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using FixedMathSharp;
 9using FixedMathSharp.Geometry;
 10
 11namespace Gravitas.Colliders;
 12
 13/// <content>Prepares and commits 3D shape changes while retaining the last committed geometry for readers.</content>
 14public abstract partial class LSCollider
 15{
 16    private Vector3d _committedCenter;
 1475817    private FixedQuaternion _committedRotation = FixedQuaternion.Identity;
 1475818    private Vector3d _committedOwnerScale = Vector3d.One;
 1475819    private Vector3d _committedPartScale = Vector3d.One;
 20    private bool _hasCommittedShape;
 21
 22    /// <summary>Gets whether this collider has committed runtime shape state.</summary>
 203763823    protected bool HasCommittedShape => _hasCommittedShape;
 24
 25    private ColliderShapeSnapshot _preparedSnapshot;
 26    private FixedBoundBox _preparedBounds;
 1475827    private Fixed64 _canonicalCenteredProxyRadius = Fixed64.MaxValue;
 1475828    private Fixed64 _canonicalPivotProxyRadius = Fixed64.MaxValue;
 29    private Fixed64 _preparedAttachmentReach;
 1475830    private Fixed64 _preparedGeometryReach = Fixed64.MaxValue;
 31
 2073432    internal Fixed64 PreparedGeometryReach => _preparedGeometryReach;
 2073333    internal Fixed64 PreparedAttachmentReach => _preparedAttachmentReach;
 34    private Fixed64 _canonicalGroundProbeRadius;
 35    private GravitasWorldContext? _preparedContext;
 1475836    private FixedQuaternion _preparedCompoundLocalRotation = FixedQuaternion.Identity;
 37
 4146738    private protected GravitasWorldContext PreparedContext => _preparedContext!;
 39
 4146640    internal FixedBoundBox PreparedShapeBounds => _preparedBounds;
 41
 42    internal Fixed64 CanonicalCenteredProxyRadius =>
 10504643        _canonicalCenteredProxyRadius;
 44
 11943845    internal Fixed64 CanonicalPivotProxyRadius => _canonicalPivotProxyRadius;
 46
 47    internal Fixed64 CanonicalGroundProbeRadius =>
 1445848        _canonicalGroundProbeRadius;
 49
 13612150    internal Vector3d CanonicalCenter => _committedCenter;
 51
 6483452    internal FixedQuaternion CanonicalRotation => _committedRotation;
 53
 54    internal bool TryGetCommittedOwnerScale(out Vector3d scale)
 55    {
 44056        if (_hasCommittedShape)
 57        {
 43658            scale = _committedOwnerScale;
 43659            return true;
 60        }
 61
 462        scale = default;
 463        return false;
 64    }
 65
 66    private Vector3d GetCurrentOwnerScale()
 67    {
 11971768        if (_hasCommittedShape)
 11764869            return _committedOwnerScale;
 206970        if (_compoundOwner != null)
 29771            return _compoundOwner.GetCurrentOwnerScale();
 177272        return Vector3d.One;
 73    }
 74
 75    private Vector3d GetCurrentPartScale() =>
 1585276        _hasCommittedShape
 1585277            ? _committedPartScale
 1585278            : _compoundOwner == null
 1585279                ? Vector3d.One
 1585280                : _compoundLocalScale;
 81
 82    internal void GetCurrentShapeScales(
 83        out Vector3d ownerScale,
 84        out Vector3d partScale)
 85    {
 1581086        ownerScale = GetCurrentOwnerScale();
 1581087        partScale = GetCurrentPartScale();
 1581088    }
 89
 90    internal bool TryGetCurrentScaledOffset(out Vector3d scaledOffset)
 91    {
 2492        Vector3d ownerScale = GetCurrentOwnerScale();
 2493        bool representable = Fixed64.TryMultiplyDivide(
 2494                _offset.X,
 2495                ownerScale.X,
 2496                Fixed64.One,
 2497                out Fixed64 x)
 2498            & Fixed64.TryMultiplyDivide(
 2499                _offset.Y,
 24100                ownerScale.Y,
 24101                Fixed64.One,
 24102                out Fixed64 y)
 24103            & Fixed64.TryMultiplyDivide(
 24104                _offset.Z,
 24105                ownerScale.Z,
 24106                Fixed64.One,
 24107                out Fixed64 z);
 24108        scaledOffset = representable
 24109            ? new Vector3d(x, y, z)
 24110            : default;
 24111        return representable;
 112    }
 113
 114    internal Vector3d GetCurrentScaledOffset()
 115    {
 12116        bool representable =
 12117            TryGetCurrentScaledOffset(out Vector3d scaledOffset);
 12118        ChronicleGuard.ThrowIfTrue(
 12119            !representable,
 12120            nameof(ScaledOffset),
 12121            "The scaled collider offset is outside the Fixed64 coordinate domain.");
 12122        return scaledOffset;
 123    }
 124
 125    internal Fixed64 GetCurrentScaledRadius()
 126    {
 42127        Vector3d ownerScale = GetCurrentOwnerScale();
 42128        Vector3d partScale = GetCurrentPartScale();
 42129        return FixedMath.Max(
 42130            ColliderScalePolicy.ScalePositive(
 42131                _radius,
 42132                ownerScale.X,
 42133                partScale.X),
 42134            FixedMath.Max(
 42135                ColliderScalePolicy.ScalePositive(
 42136                    _radius,
 42137                    ownerScale.Y,
 42138                    partScale.Y),
 42139                ColliderScalePolicy.ScalePositive(
 42140                    _radius,
 42141                    ownerScale.Z,
 42142                    partScale.Z)));
 143    }
 144
 145    private ColliderShapeSnapshot CreateStandaloneSnapshot(
 146        IMatterAgent agent,
 147        bool useRequestedPose,
 148        Vector3d requestedPosition,
 149        FixedQuaternion requestedRotation)
 150    {
 151        Vector3d ownerScale;
 152        Vector3d center;
 153        Vector3d poseOrigin;
 154        FixedQuaternion rotation;
 446785155        if (useRequestedPose)
 156        {
 306670157            ownerScale = ColliderScalePolicy.CaptureScale(agent.Transform);
 306662158            poseOrigin = requestedPosition;
 306662159            rotation = requestedRotation;
 306662160            ChronicleGuard.ThrowIfArgument(
 306662161                !rotation.TryTransformScaledPoint(
 306662162                    requestedPosition,
 306662163                    _offset,
 306662164                    ownerScale,
 306662165                    out center),
 306662166                nameof(requestedPosition),
 306662167                "Collider center must be representable after applying the requested body pose.");
 168        }
 169        else
 170        {
 140115171            ownerScale = ColliderScalePolicy.Capture(
 140115172                agent.Transform,
 140115173                out Fixed4x4 worldMatrix,
 140115174                out FixedQuaternion matrixRotation);
 140095175            poseOrigin = worldMatrix.Translation;
 140095176            rotation = matrixRotation;
 140095177            ChronicleGuard.ThrowIfArgument(
 140095178                !Fixed4x4.TryTransformAffinePoint(worldMatrix, _offset, out center),
 140095179                nameof(agent),
 140095180                "Collider center must be representable after applying the host transform.");
 181        }
 182
 446752183        return new ColliderShapeSnapshot(
 446752184            center,
 446752185            rotation,
 446752186            ownerScale,
 446752187            Vector3d.One,
 446752188            _offset,
 446752189            _size,
 446752190            _radius,
 446752191            poseOrigin,
 446752192            rotation);
 193    }
 194
 195    private ColliderShapeSnapshot CaptureShapeSnapshot()
 196    {
 423551197        IMatterAgent agent = _agent!;
 423551198        return _body == null
 423551199            ? CreateStandaloneSnapshot(
 423551200                agent,
 423551201                useRequestedPose: false,
 423551202                default,
 423551203                default)
 423551204            : CreateStandaloneSnapshot(
 423551205                agent,
 423551206                useRequestedPose: true,
 423551207                _body.Position3d,
 423551208                _body.Rotation);
 209    }
 210
 211    private ColliderShapeSnapshot CreateCompoundPartSnapshot(
 212        in ColliderShapeSnapshot ownerSnapshot,
 213        FixedQuaternion localRotation,
 214        Vector3d localScale)
 215    {
 20739216        ColliderScalePolicy.Validate(localScale);
 20739217        ChronicleGuard.ThrowIfArgument(
 20739218            !ownerSnapshot.Rotation.TryTransformScaledPoint(
 20739219                ownerSnapshot.Center,
 20739220                _offset,
 20739221                ownerSnapshot.OwnerScale,
 20739222                out Vector3d center),
 20739223            nameof(ownerSnapshot),
 20739224            "Compound collider center must be representable after applying its scaled local offset.");
 20739225        FixedQuaternion rotation = (ownerSnapshot.Rotation * localRotation).Normalized;
 20739226        return new ColliderShapeSnapshot(
 20739227            center,
 20739228            rotation,
 20739229            ownerSnapshot.OwnerScale,
 20739230            localScale,
 20739231            _offset,
 20739232            _size,
 20739233            _radius,
 20739234            ownerSnapshot.Center,
 20739235            ownerSnapshot.Rotation);
 236    }
 237
 238    private void PrepareRuntimeShape(
 239        in ColliderShapeSnapshot snapshot,
 240        bool includeBodyAttachment)
 241    {
 180726242        _preparedContext ??= _context;
 180726243        ValidateShapeCandidate(snapshot);
 180726244        _preparedSnapshot = snapshot;
 180726245        _preparedGeometryReach = Fixed64.MaxValue;
 180726246        PrepareShape(snapshot);
 180704247        _preparedAttachmentReach = ColliderGeometryPolicy.Attachment(snapshot.LocalOffset, snapshot.OwnerScale);
 180704248        Fixed64 completeReach = _preparedGeometryReach;
 180704249        if (includeBodyAttachment)
 154650250            completeReach = ColliderGeometryPolicy.Add(
 154650251                _preparedAttachmentReach, completeReach);
 180704252        ColliderGeometryPolicy.ValidateReach(completeReach, nameof(snapshot));
 180676253    }
 254
 255    // Broad-phase geometry also advances for accepted dynamic solver poses; those are not new contact stimuli.
 256    internal uint ContactDependencyVersion { get; private set; }
 257
 258    internal void MarkContactDependencyChanged(bool notifySurface = true, bool surfaceNeighborsChanged = true)
 259    {
 7191260        LSCollider owner = this;
 7319261        while (owner._compoundOwner != null)
 128262            owner = owner._compoundOwner;
 7191263        owner.ContactDependencyVersion++;
 7191264        if (notifySurface && owner is LSMeshCollider mesh)
 1196265            mesh.StaticSurface?.Invalidate(changed: mesh, includeNeighbors: surfaceNeighborsChanged);
 6008266    }
 267
 268    private void PublishPreparedShape(bool contactDependencyChanged = true)
 269    {
 179968270        _committedCenter = _preparedSnapshot.Center;
 179968271        _committedRotation = _preparedSnapshot.Rotation;
 179968272        _committedOwnerScale = _preparedSnapshot.OwnerScale;
 179968273        _committedPartScale = _preparedSnapshot.PartScale;
 179968274        _bounds = _preparedBounds;
 179968275        PublishShape();
 276        Fixed64 intrinsic;
 179968277        if (this is LSCompoundCollider compound)
 20164278            _canonicalCenteredProxyRadius = ColliderCanonicalBounds.GetCompoundCenteredProxyRadius(compound, out intrins
 279        else
 280        {
 159804281            _canonicalCenteredProxyRadius = _preparedGeometryReach;
 159804282            intrinsic = this is LSSphereCollider ? _canonicalCenteredProxyRadius
 159804283                : ColliderGeometryPolicy.RotatedReach(_canonicalCenteredProxyRadius, planar: false);
 284        }
 179968285        _canonicalPivotProxyRadius = ColliderGeometryPolicy.Add(
 179968286            ColliderGeometryPolicy.RotatedReach(_preparedAttachmentReach, planar: false), intrinsic);
 179968287        _canonicalGroundProbeRadius =
 179968288            ColliderCanonicalBounds.GetGroundProbeRadius(this);
 179968289        _runtimeShapeState.Commit(_preparedSnapshot);
 179968290        _hasCommittedShape = true;
 179968291        if (contactDependencyChanged)
 58608292            ContactDependencyVersion++;
 179968293    }
 294
 295    internal bool TryPrepareBodyPose(
 296        Vector3d position,
 297        FixedQuaternion rotation)
 298    {
 299        try
 300        {
 9749301            ColliderShapeSnapshot snapshot = CreateStandaloneSnapshot(
 9749302                _agent!,
 9749303                useRequestedPose: true,
 9749304                position,
 9749305                rotation);
 9742306            PrepareRuntimeShape(
 9742307                snapshot,
 9742308                includeBodyAttachment: true);
 9740309            return true;
 310        }
 8311        catch (System.ArgumentException)
 312        {
 8313            return false;
 314        }
 1315        catch (System.InvalidOperationException)
 316        {
 1317            return false;
 318        }
 9749319    }
 320
 321    internal void PublishPreparedBodyPose()
 322    {
 757323        PublishPreparedShape(contactDependencyChanged: false);
 757324    }
 325
 326    internal void PublishPreparedExplicitBodyPose(bool poseChanged)
 327    {
 8966328        PublishPreparedShape(contactDependencyChanged: poseChanged || _runtimeShapeState.IsDirty
 8966329            || _preparedSnapshot.OwnerScale != _committedOwnerScale);
 8966330        _body!.RefreshMassPropertiesFromColliderShape();
 8966331    }
 332
 333    internal void PrepareDetachedBodyReconfigurationCandidate(
 334        SolidBody body,
 335        Vector3d localOffset,
 336        Vector3d position,
 337        FixedQuaternion rotation)
 338    {
 196339        _body = body;
 196340        _agent = body.Agent;
 196341        _context = body.Context;
 196342        _offset = localOffset;
 196343        PrepareStandaloneInitialization(
 196344            body.Agent,
 196345            useRequestedPose: true,
 196346            position,
 196347            rotation);
 195348        PublishPreparedShape();
 195349    }
 350
 351    internal bool MatchesCommittedReconfigurationCandidate(LSCollider candidate) =>
 2352        !_runtimeShapeState.ShouldRebuild(candidate._preparedSnapshot);
 353
 354    internal void PrepareBodyReconfiguration(
 355        ColliderShapeDefinition definition,
 356        Vector3d localOffset,
 357        Vector3d position,
 358        FixedQuaternion rotation)
 359    {
 130360        Vector3d ownerScale = ColliderScalePolicy.CaptureScale(_agent!.Transform);
 130361        ChronicleGuard.ThrowIfArgument(
 130362            !rotation.TryTransformScaledPoint(
 130363                position,
 130364                localOffset,
 130365                ownerScale,
 130366                out Vector3d center),
 130367            nameof(position),
 130368            "Collider center must be representable after applying the requested body pose.");
 130369        var snapshot = new ColliderShapeSnapshot(
 130370            center,
 130371            rotation,
 130372            ownerScale,
 130373            Vector3d.One,
 130374            localOffset,
 130375            definition.Size,
 130376            definition.Radius,
 130377            position,
 130378            rotation);
 130379        PrepareRuntimeShape(
 130380            snapshot,
 130381            includeBodyAttachment: true);
 130382    }
 383
 384    internal void PublishPreparedBodyReconfiguration(
 385        ColliderShapeDefinition definition,
 386        Vector3d localOffset)
 387    {
 130388        _offset = localOffset;
 130389        _radius = definition.Radius;
 130390        _size = definition.Size;
 130391        PublishPreparedShape();
 130392        _body!.RefreshMassPropertiesFromColliderShape();
 130393    }
 394
 395    private void PrepareStandaloneInitialization(
 396        IMatterAgent agent,
 397        bool useRequestedPose,
 398        Vector3d requestedPosition,
 399        FixedQuaternion requestedRotation)
 400    {
 13485401        ColliderShapeSnapshot snapshot = CreateStandaloneSnapshot(
 13485402            agent,
 13485403            useRequestedPose,
 13485404            requestedPosition,
 13485405            requestedRotation);
 13471406        _preparedContext = agent.Context;
 13471407        PrepareRuntimeShape(
 13471408            snapshot,
 13471409            includeBodyAttachment: useRequestedPose);
 13435410    }
 411
 412    internal void PrepareCompoundPart(
 413        in ColliderShapeSnapshot ownerSnapshot,
 414        FixedQuaternion localRotation,
 415        Vector3d localScale,
 416        GravitasWorldContext context)
 417    {
 20739418        ChronicleGuard.ThrowIfArgument(
 20739419            _context != null && !ReferenceEquals(_context, context),
 20739420            nameof(context),
 20739421            "Compound collider part is already bound to a different GravitasWorldContext.");
 20739422        ColliderShapeSnapshot snapshot = CreateCompoundPartSnapshot(
 20739423            ownerSnapshot,
 20739424            localRotation,
 20739425            localScale);
 20739426        _preparedContext = context;
 20739427        _preparedCompoundLocalRotation = localRotation;
 20739428        PrepareRuntimeShape(
 20739429            snapshot,
 20739430            includeBodyAttachment: false);
 20734431    }
 432
 433    internal void PublishCompoundPart(
 434        FixedQuaternion localRotation,
 435        Vector3d localScale,
 436        GravitasWorldContext context)
 437    {
 20730438        _compoundLocalRotation = localRotation;
 20730439        _compoundLocalScale = localScale;
 20730440        _context = context;
 20730441        PublishPreparedShape();
 20730442    }
 443
 444    private protected void SetPreparedGeometryReach(Fixed64 reach) =>
 180705445        _preparedGeometryReach = reach;
 446
 447    /// <summary>Sets the bounds for the shape transaction being prepared.</summary>
 448    protected void SetPreparedBounds(FixedBoundBox bounds) =>
 180704449        _preparedBounds = bounds;
 450
 180726451    private protected virtual void ValidateShapeCandidate(in ColliderShapeSnapshot snapshot) { }
 452
 453    private protected abstract void PrepareShape(in ColliderShapeSnapshot snapshot);
 454
 455    private protected abstract void PublishShape();
 456}

Methods/Properties

.ctor()
get_IsActive()
set_IsActive(System.Boolean)
get_IsTrigger()
set_IsTrigger(System.Boolean)
get_Id()
get_ReplayOrdinal()
get_LifetimeVersion()
get_IsDeactivationInProgress()
get_ServiceRefreshIndex()
get_AgentOrNull()
get_Context()
get_Body()
get_IsStatic()
get_RequiresServiceSideRefresh()
get_RuntimeShapeVersion()
get_HasHostBinding()
get_CompoundOwner()
get_Position()
set_Position(FixedMathSharp.Vector3d)
get_Rotation()
set_Rotation(FixedMathSharp.FixedQuaternion)
get_Velocity()
get_World()
get_Transform()
get_Layer()
set_Layer(Gravitas.Support.PhysicsLayer)
get_IgnoredCollisionLayers()
set_IgnoredCollisionLayers(Gravitas.Support.PhysicsLayerMask)
get_Material()
set_Material(Gravitas.Materials.PhysicsMaterial)
get_IsPartitioned()
get_PartitionChanged()
set_PartitionChanged(System.Boolean)
get_BroadPhaseVersion()
get_LocalOffset()
set_LocalOffset(FixedMathSharp.Vector3d)
get_Radius()
set_Radius(FixedMathSharp.Fixed64)
get_ScaledRadius()
get_ScaledRadiusSqr()
get_Size()
set_Size(FixedMathSharp.Vector3d)
get_LocalScale()
TryGetLocalScale(FixedMathSharp.Vector3d&)
get_ScaledOffset()
TryGetScaledOffset(FixedMathSharp.Vector3d&)
get_Center()
get_Bounds()
get_BoundsMin()
get_BoundsMax()
get_PartitionCoordinates()
get_PartitionKind()
get_IsMixedPartitioned()
get_MixedPartitionCoordinates()
get_MixedPartitionKind()
get_RaycastVersion()
set_RaycastVersion(System.UInt32)
get_CircleQueryVersion()
set_CircleQueryVersion(System.UInt32)
get_IsChild()
get_IsParent()
get_ParentId()
get_Parent3D()
get_Parent2D()
get_TopParent3D()
get_TopParent2D()
get_HierarchyChildCount()
get_HierarchyKey()
get_ParentKey()
get_TopParentKey()
get_HierarchyState()
Gravitas.Colliders.IColliderHierarchyNode.get_HierarchyKey()
Gravitas.Colliders.IColliderHierarchyNode.get_HierarchyParent()
Initialize(Gravitas.SolidBody)
InitializeWithNoBody(Gravitas.IMatterAgent)
PreflightBodyInitialization(Gravitas.SolidBody,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
PreflightInitialization(Gravitas.IMatterAgent,System.Boolean,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
InitCore(Gravitas.IMatterAgent)
OnBeforeInitialize(Gravitas.IMatterAgent)
OnInitialize()
ValidateCurrentRuntimeTransform()
InitialPartition()
RepartitionCommittedShape()
Simulate()
Simulate(System.Boolean)
UpdatePartition()
SetBodylessWorldPose(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,System.Boolean,System.String)
SetParent(Gravitas.Colliders.LSCollider)
SetParent(Gravitas.Colliders.LSCollider2D)
ClearParent()
IsSibling(Gravitas.Colliders.LSCollider)
ExcludesMixedCollisionWith(Gravitas.Colliders.LSCollider2D)
RebuildRuntimeShapeState(System.Boolean,System.Boolean,System.Boolean)
RebuildRuntimeShapeOnly(System.Boolean,System.Boolean)
MarkShapeDirty()
MarkBroadPhaseChanged()
OnRadiusChanged()
OnMaterialChanged()
NormalizeSize(FixedMathSharp.Vector3d)
ValidateSize(FixedMathSharp.Vector3d)
GetClosestSurfaceAnchor(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&,System.Boolean&)
TryGetPlanarSurfaceNormal(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
IsPositionInBounds(FixedMathSharp.Fixed64,FixedMathSharp.Vector3d)
Gravitas.Colliders.IColliderHierarchyNode.AddChild(Gravitas.Colliders.ColliderHierarchyKey)
Gravitas.Colliders.IColliderHierarchyNode.RemoveChild(Gravitas.Colliders.ColliderHierarchyKey)
Gravitas.Colliders.IColliderHierarchyNode.ClearParentReference()
Gravitas.Colliders.IColliderHierarchyNode.TryGetHierarchyColliderByKey(Gravitas.Colliders.ColliderHierarchyKey,Gravitas.Colliders.IColliderHierarchyNode&)
SetPhysicsState(System.Int32,System.Int32,System.Int32)
SetServiceIndex(System.Int32)
SetReplayOrdinal(System.Int32)
SetServiceRefreshIndex(System.Int32)
ClearServiceRefreshIndex()
ClearPhysicsState()
Gravitas.Colliders.IPhysicsColliderRegistryItem.SetRegistryState(System.Int32,System.Int32,System.Int32)
Gravitas.Colliders.IPhysicsColliderRegistryItem.get_ServiceIndex()
Gravitas.Colliders.IPhysicsColliderRegistryItem.get_ReplayOrder()
Gravitas.Colliders.IPhysicsColliderRegistryItem.SetRegistryServiceIndex(System.Int32)
Gravitas.Colliders.IPhysicsColliderRegistryItem.SetRegistryReplayOrdinal(System.Int32)
Gravitas.Colliders.IPhysicsColliderRegistryItem.ClearRegistryState()
GetOrCreateMixedPartitionCoordinates()
MatchesPartitionGridBounds(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32)
MarkUnpartitioned()
ClearPartitionCoordinates()
MatchesMixedPartitionGridBounds(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32)
MarkMixedPartitioned(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32)
MarkMixedUnpartitioned()
ClearMixedPartitionCoordinates()
IgnoresCollisionLayer(Gravitas.Support.PhysicsLayer)
get_CollisionPairCount()
get_CollisionPairHolderCount()
get_CollisionPairs()
get_CollisionPairHolders()
NotifyContact(Gravitas.Colliders.LSCollider,System.Boolean,System.Boolean)
NotifyContact(Gravitas.Colliders.LSCollider,Gravitas.SolidBody,System.Boolean,System.Boolean,System.Boolean,Gravitas.Colliders.ColliderLifetimeToken&,Gravitas.Colliders.ColliderLifetimeToken&,System.Boolean,System.Boolean)
NotifyMixedContact(Gravitas.Colliders.LSCollider2D,System.Boolean,System.Boolean,System.Boolean)
NotifyMixedContact(Gravitas.Colliders.LSCollider2D,System.Boolean,System.Boolean,System.Boolean,System.Boolean,Gravitas.Colliders.ColliderLifetimeToken&,Gravitas.Colliders.ColliderLifetimeToken2D&,System.Boolean)
ValidateGeometryMutation(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64)
GetCandidateGeometryReach(Gravitas.Colliders.ColliderShapeSnapshot&)
GetFrontalArea(FixedMathSharp.Vector3d)
CalculateLocalCenterOfMassOffset()
CalculateLocalMassPoint()
CalculatePreparedLocalMassPoint()
get_SupportsMassProperties()
CalculateInertiaTensor(FixedMathSharp.Fixed64,FixedMathSharp.Vector3d)
TransformRelativeMassPropertyPointExact(FixedMathSharp.Vector3d)
TransformPreparedRelativeMassPropertyPointExact(FixedMathSharp.Vector3d)
get_CompoundLocalRotation()
ContributeReplayHash(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.GravitasReplayHashMode)
ContributeShapeReplayHash(Chronicler.Hashing.ChronicleHashWriter&)
WriteReplayHierarchyKey(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.Colliders.ColliderHierarchyKey)
TryResolveReplayHierarchyOrdinal(Gravitas.Colliders.ColliderHierarchyKey,System.Int32&)
ContributeCompoundPartReplayHash(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.Colliders.CompoundColliderPart)
ContributeShapeDefinitionReplayHash(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.Colliders.ColliderShapeDefinition)
WriteMaterial(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.Materials.PhysicsMaterial)
SetPreviousGridBounds()
TryGetCollisionPair(System.Int32,Gravitas.CollisionHandling.CollisionPair&)
TryAddCollisionPair(System.Int32,Gravitas.CollisionHandling.CollisionPair)
TryRemoveCollisionPair(System.Int32)
TryAddCollisionPairHolder(System.Int32)
TryRemoveCollisionPairHolder(System.Int32)
ClearCollisionPairState()
ClearRuntimeRelationships()
Deactivate()
DeactivateRuntimeRegistration()
ClearBindingState()
ClearChildParentReferences()
BindContext(Gravitas.GravitasWorldContext)
ReserveCompoundPart(Gravitas.Colliders.LSCompoundCollider,FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d)
ThrowIfCompoundPartLifecycle(System.String)
SetTrigger(System.Boolean)
ThrowIfCannotEnableTrigger(System.String)
ThrowIfTriggerWouldAttachToBody(System.String)
ThrowIfLoadedTriggerHasBody(System.String)
TryGetBoundContext(Gravitas.GravitasWorldContext&)
RecordData(Chronicler.IChronicler)
ApplyLoadedState()
.ctor()
get_HasCommittedShape()
get_PreparedGeometryReach()
get_PreparedAttachmentReach()
get_PreparedContext()
get_PreparedShapeBounds()
get_CanonicalCenteredProxyRadius()
get_CanonicalPivotProxyRadius()
get_CanonicalGroundProbeRadius()
get_CanonicalCenter()
get_CanonicalRotation()
TryGetCommittedOwnerScale(FixedMathSharp.Vector3d&)
GetCurrentOwnerScale()
GetCurrentPartScale()
GetCurrentShapeScales(FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
TryGetCurrentScaledOffset(FixedMathSharp.Vector3d&)
GetCurrentScaledOffset()
GetCurrentScaledRadius()
CreateStandaloneSnapshot(Gravitas.IMatterAgent,System.Boolean,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
CaptureShapeSnapshot()
CreateCompoundPartSnapshot(Gravitas.Colliders.ColliderShapeSnapshot&,FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d)
PrepareRuntimeShape(Gravitas.Colliders.ColliderShapeSnapshot&,System.Boolean)
MarkContactDependencyChanged(System.Boolean,System.Boolean)
PublishPreparedShape(System.Boolean)
TryPrepareBodyPose(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
PublishPreparedBodyPose()
PublishPreparedExplicitBodyPose(System.Boolean)
PrepareDetachedBodyReconfigurationCandidate(Gravitas.SolidBody,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
MatchesCommittedReconfigurationCandidate(Gravitas.Colliders.LSCollider)
PrepareBodyReconfiguration(Gravitas.Colliders.ColliderShapeDefinition,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
PublishPreparedBodyReconfiguration(Gravitas.Colliders.ColliderShapeDefinition,FixedMathSharp.Vector3d)
PrepareStandaloneInitialization(Gravitas.IMatterAgent,System.Boolean,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
PrepareCompoundPart(Gravitas.Colliders.ColliderShapeSnapshot&,FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d,Gravitas.GravitasWorldContext)
PublishCompoundPart(FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d,Gravitas.GravitasWorldContext)
SetPreparedGeometryReach(FixedMathSharp.Fixed64)
SetPreparedBounds(FixedMathSharp.Geometry.FixedBoundBox)
ValidateShapeCandidate(System.Runtime.InteropServices.InAttribute))