< Summary

Line coverage
100%
Covered lines: 478
Uncovered lines: 0
Coverable lines: 478
Total lines: 910
Line coverage: 100%
Branch coverage
100%
Covered branches: 270
Total branches: 270
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_World()100%11100%
File 1: get_ContactDependenciesChanged()100%88100%
File 1: get_CurrentSurfaceCollisionLayers()100%1414100%
File 1: BeginCollisionLayerUpdate()100%88100%
File 1: CompleteCollisionLayerUpdate(...)100%44100%
File 1: get_IsNotificationInProgress()100%11100%
File 1: get_HasContactTransition()100%11100%
File 1: get_LifetimeVersion()100%11100%
File 1: ReleaseEndpointsForPooling()100%11100%
File 1: Initialize(...)100%66100%
File 1: AssignPriority(...)100%22100%
File 1: ShouldFirstColliderLead(...)100%88100%
File 1: UpdateCollision()100%11100%
File 1: UpdateCollisionDeferred()100%11100%
File 1: UpdateCollision(...)100%1212100%
File 1: UpdateLastFrame()100%11100%
File 1: DeactivateAndPoolIfRequired()100%22100%
File 1: ProcessCollision(...)100%2222100%
File 1: WakeSleepingBodiesForCollision()100%88100%
File 1: NotifyCollidersOfContact()100%1818100%
File 1: EndNotification(...)100%22100%
File 1: NotifySeparation(...)100%66100%
File 1: ClearPendingNotificationState()100%11100%
File 1: HandleCullingIfNotColliding()100%22100%
File 1: TryRefreshRetainedContact()100%2626100%
File 1: RefreshPhysicalContactState()100%2222100%
File 1: WakeSleepingContactParticipants()100%44100%
File 1: CheckCollision(...)100%1414100%
File 1: IsCullStateInvalidated()100%66100%
File 1: BroadPhaseVersionChanged()100%22100%
File 1: RefreshBroadPhaseVersions()100%11100%
File 1: ShouldPerformCollisionCheck()100%11100%
File 1: BoundsOverlapInclusive(...)100%1010100%
File 1: CalculateCullScore()100%88100%
File 1: GetCullDistanceStep(...)100%11100%
File 1: Reset()100%11100%
File 1: StoreWarmStartImpulse(...)100%11100%
File 1: TryGetWarmStartImpulse(...)100%11100%
File 1: ClearWarmStart()100%11100%
File 1: InvalidateSurfaceContact(...)100%66100%
File 1: StoreWarmStartImpulse(...)100%11100%
File 1: TryGetWarmStartImpulse(...)100%11100%
File 1: RemoveWarmStartImpulse(...)100%11100%
File 1: RetainWarmStarts()100%11100%
File 1: Deactivate()100%1616100%
File 2: ContributeReplayHash(...)100%2020100%
File 2: ContributeManifoldReplayHash(...)100%66100%
File 2: WriteMaterial(...)100%11100%
File 2: ContributeWarmStartReplayHash(...)100%44100%
File 2: WriteGroupKey(...)100%11100%
File 2: WriteSource(...)100%44100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/CollisionHandling/Pairs/3D/CollisionPair.cs

#LineLine coverage
 1//=======================================================================
 2// CollisionPair.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 FixedMathSharp;
 11using Gravitas.Colliders;
 12using GridForge.Grids;
 13using GridForge.Grids.Topology;
 14using SwiftCollections;
 15
 16namespace Gravitas.CollisionHandling;
 17
 18
 19
 20/// <summary>
 21/// Owns deterministic 3D pair lifecycle, culling, contact, and notification state.
 22/// </summary>
 23/// <remarks>The service releases the collider endpoints when it returns a retired pair to the pool.</remarks>
 24/// <content>Owns contact groups, cached impulses and discrete response lifecycle.</content>
 25public partial class CollisionPair
 26{
 27    /// <summary>Stores the host-controlled pair diagnostic flag.</summary>
 310428    public bool Debug = true;
 29
 30    /// <summary>Gets whether this pooled pair currently represents two registered colliders.</summary>
 31    public bool Active { get; private set; }
 32
 33    private bool _isPooledForDeactivation;
 34
 35    /// <summary>Gets the world context that owns this pair.</summary>
 36    public GravitasWorldContext Context { get; private set; } = null!;
 37
 38    /// <summary>Gets the GridForge world owned by <see cref="Context"/>.</summary>
 186639    public GridWorld World => Context.World;
 40
 41    // stores order in which they come in
 42    /// <summary>Gets the first collider ID used to identify the pair.</summary>
 43    public int Id1 { get; private set; }
 44    /// <summary>Gets the second collider ID used to identify the pair.</summary>
 45    public int Id2 { get; private set; }
 46
 47    /// <summary>Gets the collider selected to lead narrow-phase dispatch.</summary>
 48    public LSCollider ColliderA { get; private set; } = null!;
 49    /// <summary>Gets the other collider in the pair.</summary>
 50    public LSCollider ColliderB { get; private set; } = null!;
 51
 52    /// <summary>Tracks the collision-service partition pass that last processed this pair.</summary>
 53    public uint PartitionVersion;
 54    /// <summary>Tracks reuse of this pooled pair instance.</summary>
 310455    public ushort PairVersion = 1;
 56
 57    /// <summary>Gets the last simulation frame in which this pair was updated.</summary>
 58    public long LastFrame { get; private set; }
 59    /// <summary>Gets the last simulation frame in which this pair had contact.</summary>
 60    public long LastCollidedFrame { get; private set; }
 61
 62    private Fixed64 _fastCollideDistance;
 63    private Fixed64 _fastDistance;
 64    /// <summary>Gets the narrow-phase dispatch type for this collider combination.</summary>
 65    public CollisionType CollisionType { get; private set; }
 310466    private bool _doPhysics = true;
 67
 68    /// <summary>Gets the remaining deferred updates before this pair is checked again.</summary>
 69    public short CullCounter { get; private set; }
 70    private bool _preventDistanceCull;
 71    private Fixed64 _fastDistanceOffset;
 72    private uint _lastColliderABroadPhaseVersion;
 73    private uint _lastColliderBBroadPhaseVersion;
 74
 75    private bool _isColliding;
 76    private bool _isCollidingChanged;
 77    private bool _notificationInProgress;
 78    private bool _separationPending;
 79    private bool _colliderANotified;
 80    private bool _colliderBNotified;
 81    private SolidBody? _pendingBodyA;
 82    private SolidBody? _pendingBodyB;
 83    private long _lifetimeVersion;
 84    private uint _lastColliderAContactDependencyVersion;
 85    private uint _lastColliderBContactDependencyVersion;
 86    private bool _surfaceContactChanged;
 87    private ulong? _surfaceCollisionLayers;
 88
 14706689    private bool ContactDependenciesChanged => _surfaceContactChanged
 14706690        || ColliderA.ContactDependencyVersion != _lastColliderAContactDependencyVersion
 14706691        || ColliderB.ContactDependencyVersion != _lastColliderBContactDependencyVersion
 14706692        || _surfaceCollisionLayers.HasValue && _surfaceCollisionLayers != CurrentSurfaceCollisionLayers;
 93
 94    private ulong? CurrentSurfaceCollisionLayers
 95    {
 96        get
 97        {
 19055498            if (ColliderA.IsTrigger || ColliderB.IsTrigger) return null;
 19048899            LSCollider? mover = ColliderA is LSMeshCollider { StaticSurface: not null } ? ColliderB
 190488100                : ColliderB is LSMeshCollider { StaticSurface: not null } ? ColliderA : null;
 190488101            return mover == null ? null : Context.Settings.GetCollisionLayerMask(default, mover.Layer, false, true);
 102        }
 103    }
 104
 105    internal (ulong? Layers, ContactManifold? Before) BeginCollisionLayerUpdate()
 106    {
 67395107        ulong? layers = CurrentSurfaceCollisionLayers;
 67395108        if (!_isColliding || !layers.HasValue || !_surfaceCollisionLayers.HasValue || layers == _surfaceCollisionLayers)
 67390109            return (layers, null);
 5110        ContactManifold before = Context.CollisionScratch.SurfaceContactSnapshot3D;
 5111        before.CopyFrom(Manifold, Manifold.LastUpdatedFrame);
 5112        return (layers, before);
 113    }
 114
 115    internal void CompleteCollisionLayerUpdate((ulong? Layers, ContactManifold? Before) previous)
 116    {
 67394117        if (previous.Before != null && !previous.Before.HasSameContacts(Manifold))
 118        {
 4119            ClearWarmStart(); WakeSleepingContactParticipants();
 120        }
 67394121        _surfaceCollisionLayers = previous.Layers;
 67394122    }
 123
 127124    internal bool IsNotificationInProgress => _notificationInProgress;
 125
 2427126    internal bool HasContactTransition => _isCollidingChanged;
 127
 197474128    internal long LifetimeVersion => _lifetimeVersion;
 129
 130    /// <summary>Gets the deterministic contact manifold owned by this pair.</summary>
 131    public ContactManifold Manifold { get; } = new();
 132
 133    private ContactWarmStartCache _warmStart;
 134
 135    internal ContactResponseSnapshot ResponseSnapshot;
 136
 6208137    internal CollisionPair(LSCollider c1, LSCollider c2) => Initialize(c1, c2);
 138
 139    internal void ReleaseEndpointsForPooling()
 140    {
 141        // A pending retirement token may still refer to this shell before it is reused.
 114142        _lifetimeVersion++;
 114143        ColliderA = ColliderB = null!;
 114144    }
 145
 146    /// <summary>
 147    /// Initializes the CollisionPair with the given colliders.
 148    /// </summary>
 149    /// <param name="c1">The first collider.</param>
 150    /// <param name="c2">The second collider.</param>
 151    internal void Initialize(LSCollider c1, LSCollider c2)
 152    {
 3129153        ChronicleGuard.ThrowIfNull(c1, nameof(c1));
 3129154        ChronicleGuard.ThrowIfNull(c2, nameof(c2));
 3129155        ChronicleGuard.ThrowIfArgument(c1 == c2, nameof(c2), "Cannot create a CollisionPair with the same collider.");
 3129156        GravitasWorldContext context = c1.Context;
 3129157        ChronicleGuard.ThrowIfArgument(
 3129158            !ReferenceEquals(context, c2.Context),
 3129159            nameof(c2),
 3129160            "Colliders must be in the same context to create a CollisionPair.");
 161
 3128162        Context = context;
 3128163        _lifetimeVersion++;
 164
 3128165        Reset();
 166
 3128167        AssignPriority(c1, c2);
 3128168        Id1 = ColliderA.Id;
 3128169        Id2 = ColliderB.Id;
 170
 3128171        CollisionType = ColliderSettings.GetCollisionType(ColliderA.Shape, ColliderB.Shape);
 172
 173        // Calculate the square of the sum of the radii of the bounding spheres
 3128174        _fastCollideDistance = ColliderA!.Bounds.Scope.Magnitude + ColliderB!.Bounds.Scope.Magnitude;
 3128175        _fastCollideDistance *= _fastCollideDistance;
 176
 3128177        _doPhysics = (ColliderA.Body != null || ColliderB.Body != null)
 3128178            && !ColliderA.IsTrigger && !ColliderB.IsTrigger;
 179
 180        // Immediately check collision. If collision distance is too large, do
 181        // not cull based on distance.
 3128182        CullCounter = 0;
 3128183        _preventDistanceCull = _fastCollideDistance > Context.Environment.CullFastDistanceMax;
 3128184        _fastDistanceOffset = Fixed64.FromRaw((int)_fastCollideDistance) + (Fixed64.One * 2) * (Fixed64.One * 2);
 185
 3128186        LastCollidedFrame = Context.FrameCount;
 3128187        RefreshBroadPhaseVersions();
 3128188        _lastColliderAContactDependencyVersion = ColliderA.ContactDependencyVersion;
 3128189        _lastColliderBContactDependencyVersion = ColliderB.ContactDependencyVersion;
 3128190        _surfaceContactChanged = false;
 3128191        PairVersion++;
 3128192        Active = true;
 3128193    }
 194
 195    /// <summary>Orders the colliders for stable narrow-phase dispatch.</summary>
 196    public void AssignPriority(LSCollider c1, LSCollider c2)
 197    {
 3128198        if (ShouldFirstColliderLead(c1, c2))
 199        {
 2766200            ColliderA = c1;
 2766201            ColliderB = c2;
 2766202            return;
 203        }
 204
 362205        ColliderA = c2;
 362206        ColliderB = c1;
 362207    }
 208
 209    private static bool ShouldFirstColliderLead(LSCollider c1, LSCollider c2)
 210    {
 3128211        if (c1.Priority != c2.Priority)
 1869212            return c1.Priority > c2.Priority;
 213
 1259214        if (c1.Body == null || c2.Body == null)
 744215            return true;
 216
 515217        if (c1.Body.LinearSpeed != c2.Body.LinearSpeed)
 123218            return c1.Body.LinearSpeed > c2.Body.LinearSpeed;
 219
 392220        return true;
 221    }
 222
 223    /// <summary>
 224    /// Checks and distributes collisions between colliders.
 225    /// Called by Partition Manager every fixed update if 2 colliders are on the same partion.
 226    /// </summary>
 27227    public void UpdateCollision() => UpdateCollision(CollisionResponseDispatchMode.Immediate);
 228
 92725229    internal void UpdateCollisionDeferred() => UpdateCollision(CollisionResponseDispatchMode.Deferred);
 230
 231    private void UpdateCollision(CollisionResponseDispatchMode responseMode)
 232    {
 92752233        if (!Active)
 1234            return;
 235
 92751236        UpdateLastFrame();
 92751237        DeactivateAndPoolIfRequired();
 238
 92751239        if (CullCounter > 0 && IsCullStateInvalidated())
 2364240            CullCounter = 0;
 241
 92751242        if (CullCounter <= 0)
 243        {
 92750244            ProcessCollision(responseMode);
 92750245            RefreshBroadPhaseVersions();
 92750246            if (_isCollidingChanged && !_isColliding)
 774247                Manifold.Reset();
 248
 92750249            HandleCullingIfNotColliding();
 92750250            return;
 251        }
 252
 1253        CullCounter--;  // Culled and one step closer to checking again.
 1254    }
 255
 92751256    private void UpdateLastFrame() => LastFrame = Context.FrameCount;
 257
 258    private void DeactivateAndPoolIfRequired()
 259    {
 92751260        if (_isPooledForDeactivation)
 91959261            return;
 262
 792263        Context.Physics.PoolForDeactivation(this);
 792264        _isPooledForDeactivation = true;
 792265    }
 266
 267    private void ProcessCollision(CollisionResponseDispatchMode responseMode)
 268    {
 92750269        bool contactChanged = RefreshPhysicalContactState();
 92750270        if (!ShouldPerformCollisionCheck())
 271        {
 33731272            if (_isColliding && _doPhysics)
 187273                WakeSleepingContactParticipants();
 33731274            _isCollidingChanged = _isColliding;
 33731275            _isColliding = false;
 33731276            Manifold.Reset();
 33731277            ClearWarmStart();
 33731278            return;
 279        }
 280
 59019281        bool result = CheckCollision(contactChanged);
 59019282        if (result)
 52814283            Context.Diagnostics.EmitContact(this, result);
 284
 59019285        if (result ^ _isColliding)
 286        {
 2025287            if (_isColliding && _doPhysics)
 585288                WakeSleepingContactParticipants();
 2025289            _isColliding = result;
 2025290            _isCollidingChanged = true;
 291        }
 292
 59019293        if (!result || !Manifold.HasContact)
 294        {
 12411295            ClearWarmStart();
 12411296            return;
 297        }
 298
 46608299        if (!_doPhysics)
 30300            return;
 301
 46578302        if (responseMode == CollisionResponseDispatchMode.Deferred)
 303        {
 46564304            Context.Physics.QueueDiscreteResponsePair(this);
 46564305            return;
 306        }
 307
 14308        WakeSleepingBodiesForCollision();
 14309        CollisionResponse.CalculateImpulse(this);
 14310    }
 311
 312    internal void WakeSleepingBodiesForCollision()
 313    {
 38461314        SolidBody? bodyA = ColliderA.Body;
 38461315        SolidBody? bodyB = ColliderB.Body;
 38461316        if (bodyA == null || bodyB == null)
 32449317            return;
 318
 6012319        bool bodyAAwake = bodyA.IsAwakeForCollision;
 6012320        bool bodyBAwake = bodyB.IsAwakeForCollision;
 321
 6012322        if (bodyA.IsSleeping && bodyBAwake)
 1323            bodyA.Wake();
 6012324        if (bodyB.IsSleeping && bodyAAwake)
 3325            bodyB.Wake();
 6012326    }
 327
 328    /// <summary>Raises contact or separation notifications for the current pair state.</summary>
 329    public void NotifyCollidersOfContact()
 330    {
 95650331        bool isColliding = _isColliding;
 95650332        bool isChanged = _isCollidingChanged;
 333
 95650334        var registrationA = new ColliderLifetimeToken(ColliderA);
 95650335        var registrationB = new ColliderLifetimeToken(ColliderB);
 95650336        LSCollider colliderA = registrationA.Collider;
 95650337        LSCollider colliderB = registrationB.Collider;
 95650338        SolidBody? bodyA = colliderA.Body;
 95650339        SolidBody? bodyB = colliderB.Body;
 95650340        bool isTriggerPair = colliderA.IsTrigger || colliderB.IsTrigger;
 95650341        bool shouldRaiseTriggerA = isTriggerPair && ColliderTriggerEventPolicy.ShouldRaise(colliderA, colliderB);
 95650342        bool shouldRaiseTriggerB = isTriggerPair && ColliderTriggerEventPolicy.ShouldRaise(colliderB, colliderA);
 95650343        _notificationInProgress = true;
 95650344        SwiftList<Exception>? notificationExceptions = null;
 345        try
 346        {
 95650347            if (isColliding)
 348            {
 54303349                bool notifyEnterA = isChanged && !_colliderANotified;
 54303350                _colliderANotified = true;
 54303351                colliderA.NotifyContact(
 54303352                    colliderB,
 54303353                    bodyB,
 54303354                    isColliding: true,
 54303355                    notifyEnterA,
 54303356                    allowInactive: false,
 54303357                    registrationA,
 54303358                    registrationB,
 54303359                    isTriggerPair,
 54303360                    shouldRaiseTriggerA);
 54300361                if (registrationA.IsActive && registrationB.IsActive && !_separationPending)
 362                {
 54292363                    bool notifyEnterB = isChanged && !_colliderBNotified;
 54292364                    _colliderBNotified = true;
 54292365                    colliderB.NotifyContact(
 54292366                        colliderA,
 54292367                        bodyA,
 54292368                        isColliding: true,
 54292369                        notifyEnterB,
 54292370                        allowInactive: false,
 54292371                        registrationB,
 54292372                        registrationA,
 54292373                        isTriggerPair,
 54292374                        shouldRaiseTriggerB);
 375                }
 376            }
 377            else
 378            {
 41347379                NotifySeparation(
 41347380                    registrationA,
 41347381                    registrationB,
 41347382                    bodyA,
 41347383                    bodyB,
 41347384                    isChanged,
 41347385                    isTriggerPair,
 41347386                    shouldRaiseTriggerA,
 41347387                    shouldRaiseTriggerB);
 388            }
 95640389        }
 10390        catch (Exception exception)
 391        {
 10392            CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 10393        }
 394
 395        try
 396        {
 95650397            EndNotification(
 95650398                registrationA,
 95650399                registrationB,
 95650400                isTriggerPair,
 95650401                shouldRaiseTriggerA,
 95650402                shouldRaiseTriggerB);
 95649403        }
 1404        catch (Exception exception)
 405        {
 1406            CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 1407        }
 408
 95650409        _isCollidingChanged &= _isColliding
 95650410            & !(_colliderANotified & _colliderBNotified);
 411
 95650412        CollisionNotificationExceptions.ThrowIfAny(notificationExceptions);
 95639413    }
 414
 415    private void EndNotification(
 416        in ColliderLifetimeToken registrationA,
 417        in ColliderLifetimeToken registrationB,
 418        bool isTriggerPair,
 419        bool shouldRaiseTriggerA,
 420        bool shouldRaiseTriggerB)
 421    {
 422        try
 423        {
 95650424            if (!_separationPending)
 95641425                return;
 426
 9427            SolidBody? bodyA = _pendingBodyA;
 9428            SolidBody? bodyB = _pendingBodyB;
 9429            ClearPendingNotificationState();
 9430            NotifySeparation(
 9431                registrationA,
 9432                registrationB,
 9433                bodyA,
 9434                bodyB,
 9435                isChanged: true,
 9436                isTriggerPair,
 9437                shouldRaiseTriggerA,
 9438                shouldRaiseTriggerB);
 8439        }
 440        finally
 441        {
 95650442            ClearPendingNotificationState();
 95650443            _notificationInProgress = false;
 95650444        }
 95649445    }
 446
 447    private void NotifySeparation(
 448        in ColliderLifetimeToken registrationA,
 449        in ColliderLifetimeToken registrationB,
 450        SolidBody? bodyA,
 451        SolidBody? bodyB,
 452        bool isChanged,
 453        bool isTriggerPair,
 454        bool shouldRaiseTriggerA,
 455        bool shouldRaiseTriggerB)
 456    {
 41356457        bool notifyA = _colliderANotified;
 41356458        bool notifyB = _colliderBNotified;
 41356459        _colliderANotified = false;
 41356460        _colliderBNotified = false;
 461
 41356462        SwiftList<Exception>? notificationExceptions = null;
 41356463        if (notifyA)
 464        {
 465            try
 466            {
 873467                registrationA.Collider.NotifyContact(
 873468                    registrationB.Collider,
 873469                    bodyB,
 873470                    isColliding: false,
 873471                    isChanged,
 873472                    allowInactive: true,
 873473                    registrationA,
 873474                    registrationB,
 873475                    isTriggerPair,
 873476                    shouldRaiseTriggerA);
 865477            }
 8478            catch (Exception exception)
 479            {
 8480                CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 8481            }
 482        }
 483
 41356484        if (notifyB && registrationB.IsCurrentLifetime)
 485        {
 486            try
 487            {
 862488                registrationB.Collider.NotifyContact(
 862489                    registrationA.Collider,
 862490                    bodyA,
 862491                    isColliding: false,
 862492                    isChanged,
 862493                    allowInactive: true,
 862494                    registrationB,
 862495                    registrationA,
 862496                    isTriggerPair,
 862497                    shouldRaiseTriggerB);
 861498            }
 1499            catch (Exception exception)
 500            {
 1501                CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 1502            }
 503        }
 504
 41356505        CollisionNotificationExceptions.ThrowIfAny(notificationExceptions);
 41348506    }
 507
 508    private void ClearPendingNotificationState()
 509    {
 98789510        _separationPending = false;
 98789511        _pendingBodyA = null;
 98789512        _pendingBodyB = null;
 98789513    }
 514
 515    private void HandleCullingIfNotColliding()
 516    {
 92750517        if (_isColliding)
 518        {
 52814519            LastCollidedFrame = Context.FrameCount;
 52814520            return;
 521        }
 522
 39936523        CalculateCullScore();
 39936524    }
 525
 526    internal bool TryRefreshRetainedContact()
 527    {
 98000528        if (!_isColliding)
 43682529            return true;
 54318530        bool joined = ColliderA is LSMeshCollider { StaticSurface: not null }
 54318531            || ColliderB is LSMeshCollider { StaticSurface: not null };
 54318532        bool contactChanged = RefreshPhysicalContactState();
 533        // A sleeping participant does not make a moved or reshaped support's old manifold valid.
 534        // The broad-phase pass already checked live eligibility this frame.
 535        // An overlap can legitimately leave its selected rows to another member.
 54318536        if (LastFrame != Context.FrameCount && (!Manifold.HasContact || joined)
 54318537            || contactChanged || BroadPhaseVersionChanged())
 538        {
 145539            if (!BoundsOverlapInclusive(ColliderA, ColliderB)
 145540                || !CollisionDetection.DoCollisionCheck(this))
 22541                return false;
 123542            RefreshBroadPhaseVersions();
 543        }
 544
 54296545        if (ColliderA.Body?.IsSleeping == true || ColliderB.Body?.IsSleeping == true)
 1558546            LastCollidedFrame = Context.FrameCount;
 54296547        return true;
 548    }
 549
 550    private bool RefreshPhysicalContactState()
 551    {
 147068552        bool doPhysics = (ColliderA.Body != null || ColliderB.Body != null)
 147068553            && !ColliderA.IsTrigger && !ColliderB.IsTrigger;
 147068554        bool contactChanged = _doPhysics != doPhysics || ContactDependenciesChanged;
 555        // A changed solid constraint can carry frictional load even if its new geometry still overlaps.
 147068556        if (_isColliding)
 557        {
 106467558            if (_doPhysics != doPhysics)
 559            {
 3560                ClearWarmStart();
 3561                WakeSleepingContactParticipants();
 562            }
 106464563            else if (_doPhysics)
 564            {
 106428565                if (ColliderB.ContactDependencyVersion != _lastColliderBContactDependencyVersion)
 409566                    ColliderA.Body?.WakeForContactChange();
 106428567                if (ColliderA.ContactDependencyVersion != _lastColliderAContactDependencyVersion)
 50568                    ColliderB.Body?.WakeForContactChange();
 569            }
 570        }
 147068571        _doPhysics = doPhysics;
 147068572        _lastColliderAContactDependencyVersion = ColliderA.ContactDependencyVersion;
 147068573        _lastColliderBContactDependencyVersion = ColliderB.ContactDependencyVersion;
 147068574        _surfaceContactChanged = false;
 147068575        return contactChanged;
 576    }
 577
 578    private void WakeSleepingContactParticipants()
 579    {
 957580        ColliderA.Body?.WakeForContactChange();
 957581        ColliderB.Body?.WakeForContactChange();
 836582    }
 583
 584    private bool CheckCollision(bool contactChanged)
 585    {
 586        // Child material overrides are manifold data and can change without a bounds publication.
 59019587        if (!contactChanged && !BroadPhaseVersionChanged() && _isColliding
 59019588            && ColliderA is not LSMeshCollider { StaticSurface: not null }
 59019589            && ColliderB is not LSMeshCollider { StaticSurface: not null })
 700590            return _isColliding;
 591
 58319592        return CollisionDetection.DoCollisionCheck(this);
 593    }
 594
 595    private bool IsCullStateInvalidated()
 596    {
 2365597        return ColliderA.PartitionChanged
 2365598            || ColliderB.PartitionChanged
 2365599            || BroadPhaseVersionChanged() || ContactDependenciesChanged;
 600    }
 601
 602    private bool BroadPhaseVersionChanged()
 603    {
 112791604        return ColliderA.BroadPhaseVersion != _lastColliderABroadPhaseVersion
 112791605            || ColliderB.BroadPhaseVersion != _lastColliderBBroadPhaseVersion;
 606    }
 607
 608    private void RefreshBroadPhaseVersions()
 609    {
 96001610        _lastColliderABroadPhaseVersion = ColliderA.BroadPhaseVersion;
 96001611        _lastColliderBBroadPhaseVersion = ColliderB.BroadPhaseVersion;
 96001612    }
 613
 614    private bool ShouldPerformCollisionCheck()
 615    {
 616        // Center distance remains a scheduling signal only. Canonical geometry
 617        // may extend beyond a scalar face while its conservative broad-phase
 618        // bounds are clipped to the representable domain, which can shorten
 619        // Bounds.Scope without shortening the physical shape.
 92750620        _fastDistance = Vector3d.DistanceSquared(ColliderA.Center, ColliderB.Center);
 621
 622        // Inclusive bounds overlap preserves zero-depth touching contacts for the manifold pass.
 92750623        return BoundsOverlapInclusive(ColliderA, ColliderB);
 624    }
 625
 626    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 627    internal static bool BoundsOverlapInclusive(LSCollider colliderA, LSCollider colliderB)
 628    {
 307574629        return colliderA.BoundsMin.X <= colliderB.BoundsMax.X
 307574630            && colliderA.BoundsMax.X >= colliderB.BoundsMin.X
 307574631            && colliderA.BoundsMin.Y <= colliderB.BoundsMax.Y
 307574632            && colliderA.BoundsMax.Y >= colliderB.BoundsMin.Y
 307574633            && colliderA.BoundsMin.Z <= colliderB.BoundsMax.Z
 307574634            && colliderA.BoundsMax.Z >= colliderB.BoundsMin.Z;
 635    }
 636
 637    private void CalculateCullScore()
 638    {
 39936639        int distanceScore = 0;
 39936640        int velocityScore = 0;
 39936641        if (!_preventDistanceCull)
 642        {
 1867643            int distanceMax = Context.Environment.CullDistanceMax;
 1867644            if (distanceMax > 0)
 645            {
 1866646                int step = GetCullDistanceStep(World!);
 1866647                distanceScore = Math.Clamp((int)(_fastDistance - _fastDistanceOffset) / step + Context.Collisions.CullDi
 648            }
 649
 1867650            int cullVelocityStep = Context.Environment.CullVelocityStep;
 1867651            if (cullVelocityStep > 0)
 1866652                velocityScore = Math.Clamp((int)(ColliderA.Velocity - ColliderB.Velocity).Magnitude / cullVelocityStep, 
 653        }
 654
 39936655        int timeScore = 0;
 39936656        int cullTimeStep = Context.Environment.CullTimeStep;
 39936657        if (cullTimeStep > 0)
 39935658            timeScore = (int)Math.Clamp((Context.FrameCount - LastCollidedFrame) / cullTimeStep, 0, Context.Environment.
 659
 39936660        CullCounter = (short)Math.Clamp(distanceScore + timeScore - velocityScore, 0, short.MaxValue);
 39936661    }
 662
 663    /// <summary>
 664    /// Defines the step value for distance-based culling. The score is increased
 665    /// when the distance between objects increases. Higher values make the culling more aggressive for distant objects.
 666    /// </summary>
 667    private int GetCullDistanceStep(GridWorld world)
 668    {
 1866669        int distanceMax = Context.Environment.CullDistanceMax;
 1866670        Fixed64 cellEdge = GridTopologyMetricUtility.GetRepresentativeCellEdge(world);
 1866671        int step = ((cellEdge + Fixed64.One * 2) * (cellEdge + Fixed64.One * 2) / distanceMax).CeilToInt();
 1866672        return Math.Max(1, step);
 673    }
 674
 675    /// <summary>Clears transient contact and notification state before reuse.</summary>
 676    public void Reset()
 677    {
 3130678        Manifold.Reset();
 3130679        ClearWarmStart();
 3130680        _isColliding = false;
 3130681        _surfaceCollisionLayers = null;
 3130682        _isCollidingChanged = false;
 3130683        _isPooledForDeactivation = false;
 3130684        _notificationInProgress = false;
 3130685        _colliderANotified = false;
 3130686        _colliderBNotified = false;
 3130687        ClearPendingNotificationState();
 3130688    }
 689
 690    internal void StoreWarmStartImpulse(
 691        ulong contactId,
 692        Vector3d normal,
 693        Fixed64 normalImpulse,
 694        Fixed64 tangentImpulse,
 695        Fixed64 secondaryTangentImpulse = default) =>
 58696        _warmStart.Set(contactId, normal, normalImpulse, tangentImpulse, secondaryTangentImpulse);
 697
 698    internal bool TryGetWarmStartImpulse(ulong contactId, out ContactWarmStartImpulse impulse) =>
 68699        _warmStart.TryGet(contactId, out impulse);
 700
 701    internal void ClearWarmStart()
 702    {
 49556703        _warmStart.Clear();
 49556704        ResponseSnapshot = default;
 49556705    }
 706
 707    internal void InvalidateSurfaceContact(LSCollider member, SwiftHashSet<int> suppliers)
 708    {
 308709        if (!Manifold.ReferencesSuppliers(suppliers, ColliderA == member, member.Id + 1)) return;
 114710        _surfaceContactChanged = true;
 114711        ClearWarmStart();
 209712        if (_isColliding && _doPhysics) WakeSleepingContactParticipants();
 114713    }
 714
 715    internal void StoreWarmStartImpulse(in ContactGroupKey group, ulong contactId,
 716        Vector3d normal, Fixed64 normalImpulse, Fixed64 tangentImpulse,
 717        Fixed64 secondaryTangentImpulse) =>
 603716718        _warmStart.Set(group, contactId, normal, normalImpulse, tangentImpulse, secondaryTangentImpulse);
 719
 720    internal bool TryGetWarmStartImpulse(in ContactGroupKey group, ulong contactId,
 714512721        out ContactWarmStartImpulse impulse) => _warmStart.TryGet(group, contactId, out impulse);
 722
 723    internal void RemoveWarmStartImpulse(in ContactGroupKey group, ulong contactId) =>
 13724        _warmStart.Remove(group, contactId);
 725
 115019726    internal void RetainWarmStarts() => _warmStart.Retain(Manifold);
 727
 728    /// <summary>
 729    /// Deactivates the CollisionPair.
 730    /// </summary>
 731    public void Deactivate()
 732    {
 139733        if (_isColliding && _doPhysics)
 85734            WakeSleepingContactParticipants();
 139735        bool notifySeparation = _isColliding || _colliderANotified || _colliderBNotified;
 139736        if (notifySeparation)
 737        {
 103738            _isColliding = false;
 103739            _isCollidingChanged = true;
 103740            if (_notificationInProgress)
 741            {
 9742                _separationPending = true;
 9743                _pendingBodyA = ColliderA.Body;
 9744                _pendingBodyB = ColliderB.Body;
 745            }
 746        }
 747
 139748        Manifold.Reset();
 139749        ClearWarmStart();
 139750        _isPooledForDeactivation = false;
 139751        Active = false;
 752
 139753        if (notifySeparation && !_notificationInProgress)
 94754            NotifyCollidersOfContact();
 134755    }
 756}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/CollisionHandling/Pairs/3D/CollisionPair.ReplayHash.cs

#LineLine coverage
 1//=======================================================================
 2// CollisionPair.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 Chronicler.Hashing;
 9using FixedMathSharp.Chronicler;
 10using Gravitas.Materials;
 11
 12namespace Gravitas.CollisionHandling;
 13
 14/// <content>Hashes 3D pair state, retained contacts, and warm-start impulses.</content>
 15public partial class CollisionPair
 16{
 17    internal void ContributeReplayHash(
 18        ref ChronicleHashWriter writer,
 19        GravitasReplayHashMode mode)
 20    {
 141521        writer.WriteSection("pair.3d", 4);
 22        // Only an existing contact depends on these stamps; loading may republish noncontact geometry.
 141523        writer.WriteBool(!_isColliding || _lastColliderAContactDependencyVersion == ColliderA.ContactDependencyVersion);
 141524        writer.WriteBool(!_isColliding || _lastColliderBContactDependencyVersion == ColliderB.ContactDependencyVersion);
 141525        writer.WriteBool(Active);
 141526        writer.WriteInt32(ColliderA.ReplayOrdinal);
 141527        writer.WriteInt32(ColliderB.ReplayOrdinal);
 141528        writer.WriteEnum(CollisionType);
 141529        writer.WriteUInt32(PartitionVersion);
 141530        writer.WriteInt32(PairVersion);
 141531        writer.WriteInt64(LastFrame);
 141532        writer.WriteInt64(LastCollidedFrame);
 141533        writer.WriteBool(_doPhysics);
 141534        writer.WriteInt32(CullCounter);
 141535        writer.WriteBool(_preventDistanceCull);
 141536        writer.WriteBool(_isColliding);
 141537        writer.WriteBool(_isCollidingChanged);
 141538        writer.WriteFixed64(_fastCollideDistance);
 141539        writer.WriteFixed64(_fastDistance);
 141540        writer.WriteFixed64(_fastDistanceOffset);
 41        // An unculled noncontact refreshes both stamps before using them; other pairs depend on freshness.
 141542        bool usesBroadPhaseCache = _isColliding || CullCounter > 0;
 141543        writer.WriteBool(!usesBroadPhaseCache || _lastColliderABroadPhaseVersion == ColliderA.BroadPhaseVersion);
 141544        writer.WriteBool(!usesBroadPhaseCache || _lastColliderBBroadPhaseVersion == ColliderB.BroadPhaseVersion);
 45        // Borrowed suppliers can stale a retained contact or distance-cull decision
 46        // without changing either endpoint. Fresh snapshots have no authoritative history.
 141547        if (usesBroadPhaseCache && (_surfaceContactChanged ||
 141548            _surfaceCollisionLayers.HasValue && _surfaceCollisionLayers != CurrentSurfaceCollisionLayers))
 549            writer.WriteSection("pair.3d.surface", 1);
 141550        ContributeManifoldReplayHash(ref writer, Context, Manifold);
 141551        ContributeWarmStartReplayHash(ref writer, _warmStart);
 52
 141553        if (mode != GravitasReplayHashMode.AuthoritativeWithSolverCaches)
 51154            return;
 55
 90456        writer.WriteSection("pair.3d.caches", 1);
 90457        writer.WriteBool(_isPooledForDeactivation);
 90458    }
 59
 60    internal static void ContributeManifoldReplayHash(
 61        ref ChronicleHashWriter writer,
 62        GravitasWorldContext context,
 63        ContactManifold manifold,
 64        string sectionName = "manifold.3d")
 65    {
 167266        writer.WriteSection(sectionName, 9);
 167267        writer.WriteInt64(manifold.LastUpdatedFrame);
 167268        writer.WriteInt32(manifold.Count);
 167269        writer.WriteInt32(manifold.GroupCount);
 760870        for (int groupIndex = 0; groupIndex < manifold.GroupCount; groupIndex++)
 71        {
 213272            ref ContactGroup group = ref manifold.GetGroup(groupIndex);
 213273            WriteGroupKey(ref writer, context, group.Key);
 213274            writer.WriteInt32(group.Count);
 1266875            for (int i = 0; i < group.Count; i++)
 76            {
 420277                ManifoldContact contact = group[i];
 420278                writer.WriteUInt64(contact.ContactId);
 420279                writer.WriteInt32(contact.FeatureNamespaceA);
 420280                writer.WriteVector3d(contact.AnchorA.Origin);
 420281                writer.WriteQuaternion(contact.AnchorA.Rotation);
 420282                writer.WriteVector3d(contact.AnchorA.LocalPoint);
 420283                writer.WriteVector3d(contact.AnchorA.LocalDisplacement);
 420284                writer.WriteUInt64(contact.AnchorA.GetLocalFeatureHash64());
 420285                writer.WriteInt32(contact.FeatureNamespaceB);
 420286                writer.WriteVector3d(contact.AnchorB.Origin);
 420287                writer.WriteQuaternion(contact.AnchorB.Rotation);
 420288                writer.WriteVector3d(contact.AnchorB.LocalPoint);
 420289                writer.WriteVector3d(contact.AnchorB.LocalDisplacement);
 420290                writer.WriteUInt64(contact.AnchorB.GetLocalFeatureHash64());
 420291                writer.WriteFixed64(contact.Depth);
 420292                writer.WriteBool(contact.DepthIsClamped);
 420293                writer.WriteVector3d(contact.Normal);
 420294                writer.WriteBool(contact.HasMaterialOverride);
 420295                if (contact.HasMaterialOverride)
 96                {
 360397                    WriteMaterial(ref writer, contact.MaterialA);
 360398                    WriteMaterial(ref writer, contact.MaterialB);
 99                }
 100            }
 101        }
 1672102    }
 103
 104    private static void WriteMaterial(ref ChronicleHashWriter writer, PhysicsMaterial material)
 105    {
 7206106        writer.WriteFixed64(material.StaticFriction);
 7206107        writer.WriteFixed64(material.DynamicFriction);
 7206108        writer.WriteFixed64(material.Restitution);
 7206109        writer.WriteEnum(material.FrictionCombine);
 7206110        writer.WriteEnum(material.RestitutionCombine);
 7206111    }
 112
 113    private void ContributeWarmStartReplayHash(
 114        ref ChronicleHashWriter writer,
 115        ContactWarmStartCache warmStart)
 116    {
 1415117        writer.WriteSection("warm-start.3d", 3);
 1415118        writer.WriteInt32(warmStart.Count);
 1415119        writer.WriteInt32(warmStart.GroupCount);
 6564120        for (int groupIndex = 0; groupIndex < warmStart.GroupCount; groupIndex++)
 121        {
 1867122            ContactWarmStartGroup group = warmStart.GetGroup(groupIndex);
 1867123            WriteGroupKey(ref writer, Context, group.Key);
 1867124            writer.WriteInt32(group.Count);
 11506125            for (int i = 0; i < group.Count; i++)
 126            {
 3886127                writer.WriteUInt64(group.GetContactId(i));
 3886128                ContactWarmStartImpulse impulse = group.GetImpulseUnchecked(i);
 3886129                writer.WriteVector3d(impulse.Normal);
 3886130                writer.WriteFixed64(impulse.NormalImpulse);
 3886131                writer.WriteFixed64(impulse.TangentImpulse);
 3886132                writer.WriteFixed64(impulse.SecondaryTangentImpulse);
 133            }
 134        }
 1415135    }
 136
 137    private static void WriteGroupKey(ref ChronicleHashWriter writer, GravitasWorldContext context, in ContactGroupKey g
 138    {
 3999139        writer.WriteInt32(group.NamespaceA);
 3999140        writer.WriteInt32(group.NamespaceB);
 3999141        writer.WriteInt32(group.SurfaceA);
 3999142        writer.WriteInt32(group.SurfaceB);
 3999143        writer.WriteInt32(group.Region);
 3999144        WriteSource(ref writer, context, group.SourceIdA);
 3999145        WriteSource(ref writer, context, group.SourceIdB);
 3999146    }
 147
 148    private static void WriteSource(ref ChronicleHashWriter writer, GravitasWorldContext context, int source)
 149    {
 150        // Runtime identity is available before hashing assigns live replay ordinals.
 7998151        writer.WriteInt32(source == 0 ? 0 : context.Physics.TryGetColliderById(source - 1, out var collider)
 7998152            ? collider!.ReplayOrdinal + 1 : -1);
 7998153    }
 154}

Methods/Properties

.ctor(Gravitas.Colliders.LSCollider,Gravitas.Colliders.LSCollider)
get_World()
get_ContactDependenciesChanged()
get_CurrentSurfaceCollisionLayers()
BeginCollisionLayerUpdate()
CompleteCollisionLayerUpdate(System.ValueTuple`2<System.Nullable`1<System.UInt64>,Gravitas.CollisionHandling.ContactManifold>)
get_IsNotificationInProgress()
get_HasContactTransition()
get_LifetimeVersion()
ReleaseEndpointsForPooling()
Initialize(Gravitas.Colliders.LSCollider,Gravitas.Colliders.LSCollider)
AssignPriority(Gravitas.Colliders.LSCollider,Gravitas.Colliders.LSCollider)
ShouldFirstColliderLead(Gravitas.Colliders.LSCollider,Gravitas.Colliders.LSCollider)
UpdateCollision()
UpdateCollisionDeferred()
UpdateCollision(Gravitas.CollisionHandling.CollisionResponseDispatchMode)
UpdateLastFrame()
DeactivateAndPoolIfRequired()
ProcessCollision(Gravitas.CollisionHandling.CollisionResponseDispatchMode)
WakeSleepingBodiesForCollision()
NotifyCollidersOfContact()
EndNotification(Gravitas.Colliders.ColliderLifetimeToken&,Gravitas.Colliders.ColliderLifetimeToken&,System.Boolean,System.Boolean,System.Boolean)
NotifySeparation(Gravitas.Colliders.ColliderLifetimeToken&,Gravitas.Colliders.ColliderLifetimeToken&,Gravitas.SolidBody,Gravitas.SolidBody,System.Boolean,System.Boolean,System.Boolean,System.Boolean)
ClearPendingNotificationState()
HandleCullingIfNotColliding()
TryRefreshRetainedContact()
RefreshPhysicalContactState()
WakeSleepingContactParticipants()
CheckCollision(System.Boolean)
IsCullStateInvalidated()
BroadPhaseVersionChanged()
RefreshBroadPhaseVersions()
ShouldPerformCollisionCheck()
BoundsOverlapInclusive(Gravitas.Colliders.LSCollider,Gravitas.Colliders.LSCollider)
CalculateCullScore()
GetCullDistanceStep(GridForge.Grids.GridWorld)
Reset()
StoreWarmStartImpulse(System.UInt64,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
TryGetWarmStartImpulse(System.UInt64,Gravitas.CollisionHandling.ContactWarmStartImpulse&)
ClearWarmStart()
InvalidateSurfaceContact(Gravitas.Colliders.LSCollider,SwiftCollections.SwiftHashSet`1<System.Int32>)
StoreWarmStartImpulse(Gravitas.CollisionHandling.ContactGroupKey&,System.UInt64,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
TryGetWarmStartImpulse(Gravitas.CollisionHandling.ContactGroupKey&,System.UInt64,Gravitas.CollisionHandling.ContactWarmStartImpulse&)
RemoveWarmStartImpulse(Gravitas.CollisionHandling.ContactGroupKey&,System.UInt64)
RetainWarmStarts()
Deactivate()
ContributeReplayHash(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.GravitasReplayHashMode)
ContributeManifoldReplayHash(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.GravitasWorldContext,Gravitas.CollisionHandling.ContactManifold,System.String)
WriteMaterial(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.Materials.PhysicsMaterial)
ContributeWarmStartReplayHash(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.CollisionHandling.ContactWarmStartCache)
WriteGroupKey(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.GravitasWorldContext,Gravitas.CollisionHandling.ContactGroupKey&)
WriteSource(Chronicler.Hashing.ChronicleHashWriter&,Gravitas.GravitasWorldContext,System.Int32)