< Summary

Line coverage
100%
Covered lines: 306
Uncovered lines: 0
Coverable lines: 306
Total lines: 799
Line coverage: 100%
Branch coverage
100%
Covered branches: 124
Total branches: 124
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: .cctor()100%11100%
File 1: .ctor(...)100%11100%
File 1: get_IsBetweenFixedSteps()100%44100%
File 1: EnterSimulationPhase()100%11100%
File 1: ExitSimulationPhase()100%11100%
File 1: ThrowIfFixedStepMutationNotAllowed()100%22100%
File 1: get_IsDisposed()100%11100%
File 1: get_VoxelSize()100%11100%
File 1: get_FrameRate()100%11100%
File 1: get_DeltaTime()100%11100%
File 1: get_InvDeltaTime()100%11100%
File 1: get_FrameCount()100%11100%
File 1: get_ElapsedTime()100%11100%
File 1: get_AccumulatedTime()100%11100%
File 1: get_ResetAccumulation()100%11100%
File 1: get_ResetAccumulationThisVisualize()100%11100%
File 1: get_LateSimulateToken()100%11100%
File 1: CaptureClockLifetime()100%11100%
File 1: ValidateClockLifetime(...)100%11100%
File 1: GetDeadlineFrame(...)100%11100%
File 1: get_ExpectedAccumulation()100%11100%
File 1: ComputeReplayHash(...)100%11100%
File 1: Attach(...)100%11100%
File 1: CreateOwned(...)100%11100%
File 1: Simulate()100%1616100%
File 1: LateSimulate()100%2020100%
File 1: ProcessQueuedContinuousCollisionHandoffs(...)100%2222100%
File 1: AdvanceLateSimulateToken()100%11100%
File 1: ThrowIfLateSimulateTokenExhausted()100%11100%
File 1: Visualize()100%66100%
File 1: LateVisualize()100%11100%
File 1: Reset()100%11100%
File 1: SetFrameRate(...)100%11100%
File 1: ApplySettings(...)100%22100%
File 1: ValidateMixedGeometry(...)100%44100%
File 1: GetFrameCountForDuration(...)100%11100%
File 1: RegisterOnSimulate(...)100%11100%
File 1: RegisterOnLateSimulate(...)100%11100%
File 1: RegisterOnVisualize(...)100%11100%
File 1: RegisterOnLateVisualize(...)100%11100%
File 1: RegisterOnReset(...)100%11100%
File 1: RegisterOnFrameRateChanged(...)100%11100%
File 1: Dispose()100%66100%
File 1: CreateRegistered(...)100%11100%
File 1: ThrowIfWorldOwned(...)100%11100%
File 1: ReleaseWorldOwnership(...)100%11100%
File 1: ThrowIfDisposed()100%11100%
File 2: OnQueryPartitionWorldChange(...)100%88100%
File 2: RefreshQueryPartitions()100%88100%
File 3: .ctor(...)100%11100%
File 3: ReserveSleepIslands()100%11100%
File 3: UpdateAutomaticSleep(...)100%2626100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Runtime/GravitasWorldContext.cs

#LineLine coverage
 1//=======================================================================
 2// GravitasWorldContext.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 Chronicler.Timing;
 11using FixedMathSharp;
 12using Gravitas.CollisionHandling;
 13using Gravitas.Diagnostics;
 14using Gravitas.Queries;
 15using Gravitas.Support;
 16using GridForge.Grids;
 17using GridForge.Grids.Topology;
 18using SwiftCollections;
 19
 20namespace Gravitas;
 21
 22/// <summary>
 23/// Owns Gravitas runtime state for one explicit <see cref="GridWorld"/>.
 24/// </summary>
 25/// <remarks>
 26/// Owns world lifetime, deterministic timing, physics registries, collision
 27/// partitioning, queries, coroutines, and lifecycle hooks for one simulation.
 28/// </remarks>
 29/// <content>Owns world lifetime, context services, configuration and the host lifecycle.</content>
 30public sealed partial class GravitasWorldContext : IDisposable
 31{
 132    private static readonly object _worldOwnershipLock = new();
 33
 134    private static readonly SwiftDictionary<GridWorld, GravitasWorldContext> _worldOwners = new();
 35
 1019136    private readonly GravitasClock _clock = new();
 37
 1019138    private readonly GravitasLifecycleHooks _hooks = new();
 39
 40    private readonly bool _ownsWorld;
 41
 42    private bool _disposed;
 43
 44    private long _lateSimulateToken;
 45
 46    private int _simulationPhaseDepth;
 47
 48    private bool _fixedStepOpen;
 49
 31224050    internal bool IsBetweenFixedSteps => !_disposed && !_fixedStepOpen && _simulationPhaseDepth == 0;
 51
 22915752    internal void EnterSimulationPhase() => _simulationPhaseDepth++;
 53
 22915754    internal void ExitSimulationPhase() => _simulationPhaseDepth--;
 55
 56    internal void ThrowIfFixedStepMutationNotAllowed()
 57    {
 1167958        ChronicleGuard.ThrowIfTrue(
 1167959            _fixedStepOpen || _simulationPhaseDepth > 0,
 1167960            nameof(GravitasWorldContext),
 1167961            "Authoritative body roles, static poses, and loaded state can change only outside the Simulate-to-LateSimula
 1164962    }
 63
 1019164    private GravitasWorldContext(GridWorld world, bool ownsWorld)
 65    {
 1019166        World = world;
 1019167        _ownsWorld = ownsWorld;
 1019168        Settings = PhysicsSettings.DefaultSettings();
 1019169        Environment = PhysicsEnvironment.Default(Settings.FrameRate);
 1019170        CollisionScratch = new CollisionSatScratch();
 1019171        Diagnostics = new GravitasDiagnosticSink(this);
 1019172        Constraints3D = new GravitasConstraint3DService(this);
 1019173        Constraints2D = new GravitasConstraint2DService(this);
 1019174        Collisions = new GravitasCollisionService(this);
 1019175        Collisions2D = new GravitasCollision2DService(this);
 1019176        Physics = new GravitasPhysicsService(this);
 1019177        Physics2D = new GravitasPhysics2DService(this);
 1019178        MixedCollisions = new GravitasMixedCollisionService(this);
 1019179        Query2D = new GravitasQuery2DService(this);
 1019180        Query3D = new GravitasQuery3DService(this);
 1019181        QueryMixed = new GravitasQueryMixedService(this);
 1019182        Coroutines = new GravitasCoroutineService(this);
 1019183        _observedGridChangeSequence = World.ChangeSequence;
 1019184        World.OnChangeCommitted += OnQueryPartitionWorldChange;
 1019185        Settings.Owner = this;
 1019186    }
 87
 88    /// <summary>
 89    /// Gets the explicit GridForge world owned or referenced by this context.
 90    /// </summary>
 91    public GridWorld World { get; }
 92
 93    /// <summary>
 94    /// Gets this context's world-local physics settings.
 95    /// </summary>
 96    public PhysicsSettings Settings { get; private set; }
 97
 98    /// <summary>
 99    /// Gets this context's world-local physical environment values.
 100    /// </summary>
 101    public PhysicsEnvironment Environment { get; }
 102
 103    /// <summary>
 104    /// Gets this context's world-local collision partitioning service.
 105    /// </summary>
 106    public GravitasCollisionService Collisions { get; }
 107
 108    /// <summary>
 109    /// Gets this context's world-local pure 2D collision partitioning service.
 110    /// </summary>
 111    public GravitasCollision2DService Collisions2D { get; }
 112
 113    /// <summary>
 114    /// Gets this context's world-local physics registration and pair service.
 115    /// </summary>
 116    public GravitasPhysicsService Physics { get; }
 117
 118    /// <summary>
 119    /// Gets this context's world-local pure 2D physics service.
 120    /// </summary>
 121    public GravitasPhysics2DService Physics2D { get; }
 122
 123    internal GravitasMixedCollisionService MixedCollisions { get; }
 124
 125    /// <summary>
 126    /// Gets this context's world-local pure 2D query service.
 127    /// </summary>
 128    public GravitasQuery2DService Query2D { get; }
 129
 130    /// <summary>
 131    /// Gets this context's world-local 3D query service.
 132    /// </summary>
 133    public GravitasQuery3DService Query3D { get; }
 134
 135    /// <summary>
 136    /// Gets this context's explicit mixed 3D/2D query service.
 137    /// </summary>
 138    public GravitasQueryMixedService QueryMixed { get; }
 139
 140    /// <summary>
 141    /// Gets this context's world-local lockstep coroutine service.
 142    /// </summary>
 143    public GravitasCoroutineService Coroutines { get; }
 144
 145    /// <summary>
 146    /// Gets this context's deterministic diagnostic sink.
 147    /// </summary>
 148    public GravitasDiagnosticSink Diagnostics { get; }
 149
 150    /// <summary>
 151    /// Gets this context's world-local 3D constraint and ragdoll service.
 152    /// </summary>
 153    public GravitasConstraint3DService Constraints3D { get; }
 154
 155    /// <summary>
 156    /// Gets this context's world-local pure 2D constraint and ragdoll service.
 157    /// </summary>
 158    public GravitasConstraint2DService Constraints2D { get; }
 159
 160    internal CollisionSatScratch CollisionScratch { get; }
 161
 162    /// <summary>
 163    /// Gets whether this context has been disposed.
 164    /// </summary>
 98165    public bool IsDisposed => _disposed;
 166
 167    /// <summary>
 168    /// Gets a representative grid cell edge for this context's world.
 169    /// </summary>
 170    public Fixed64 VoxelSize
 171    {
 172        get
 173        {
 7174            ThrowIfDisposed();
 7175            return GridTopologyMetricUtility.GetRepresentativeCellEdge(World);
 176        }
 177    }
 178
 179    /// <summary>
 180    /// Gets this context's fixed simulation frame rate.
 181    /// </summary>
 182    public int FrameRate
 183    {
 184        get
 185        {
 173199186            ThrowIfDisposed();
 173199187            return _clock.FrameRate;
 188        }
 189    }
 190
 191    /// <summary>
 192    /// Gets this context's fixed simulation time step.
 193    /// </summary>
 194    public Fixed64 DeltaTime
 195    {
 196        get
 197        {
 1689931198            ThrowIfDisposed();
 1689931199            return _clock.DeltaTime;
 200        }
 201    }
 202
 203    /// <summary>
 204    /// Gets the reciprocal of this context's fixed simulation time step.
 205    /// </summary>
 206    public Fixed64 InvDeltaTime
 207    {
 208        get
 209        {
 19262210            ThrowIfDisposed();
 19262211            return _clock.InvDeltaTime;
 212        }
 213    }
 214
 215    /// <summary>
 216    /// Gets this context's simulated frame count.
 217    /// </summary>
 218    public long FrameCount
 219    {
 220        get
 221        {
 926976222            ThrowIfDisposed();
 926976223            return _clock.FrameCount;
 224        }
 225    }
 226
 227    /// <summary>
 228    /// Gets elapsed simulation time, preserving the history of step-size changes.
 229    /// </summary>
 230    public ChronicleTimestamp ElapsedTime
 231    {
 232        get
 233        {
 8438234            ThrowIfDisposed();
 8438235            return _clock.ElapsedTime;
 236        }
 237    }
 238
 239    /// <summary>
 240    /// Gets this context's accumulated visualization time.
 241    /// </summary>
 242    public Fixed64 AccumulatedTime
 243    {
 244        get
 245        {
 1246            ThrowIfDisposed();
 1247            return _clock.AccumulatedTime;
 248        }
 249    }
 250
 251    /// <summary>
 252    /// Gets whether this context's visualization accumulation will reset on the next visualize call.
 253    /// </summary>
 254    public bool ResetAccumulation
 255    {
 256        get
 257        {
 7258            ThrowIfDisposed();
 7259            return _clock.ResetAccumulation;
 260        }
 261    }
 262
 263    internal bool ResetAccumulationThisVisualize
 264    {
 265        get
 266        {
 46267            ThrowIfDisposed();
 46268            return _clock.ResetAccumulationThisVisualize;
 269        }
 270    }
 271
 430743272    internal long LateSimulateToken => _lateSimulateToken;
 273
 274    internal object CaptureClockLifetime()
 275    {
 676276        ThrowIfDisposed();
 676277        return _clock.Lifetime;
 278    }
 279
 280    internal void ValidateClockLifetime(object lifetime)
 281    {
 1096282        ThrowIfDisposed();
 1093283        ChronicleGuard.ThrowIfTrue(!ReferenceEquals(lifetime, _clock.Lifetime),
 1093284            nameof(GravitasWorldContext), "The wait belongs to a previous simulation lifetime.");
 1090285    }
 286
 287    internal long GetDeadlineFrame(long framesFromNow)
 288    {
 457289        ThrowIfDisposed();
 457290        return _clock.GetDeadlineFrame(framesFromNow);
 291    }
 292
 293    /// <summary>
 294    /// Gets this context's visualization accumulation expressed in simulation frames.
 295    /// </summary>
 296    public Fixed64 ExpectedAccumulation
 297    {
 298        get
 299        {
 19300            ThrowIfDisposed();
 19301            return _clock.ExpectedAccumulation;
 302        }
 303    }
 304
 305    /// <summary>
 306    /// Computes a deterministic fixed-width hash of this context's replay-relevant physics state.
 307    /// </summary>
 308    /// <param name="mode">Selects whether diagnostic solver/cache state is included in addition to authoritative state.
 309    /// <returns>A deterministic hash suitable for lockstep replay conformance checks.</returns>
 310    /// <remarks>
 311    /// The hash includes context settings, environment values, body state, collider shape/filter state,
 312    /// retained pair/contact state, and continuation-affecting CCD handoff state. It excludes host object
 313    /// identity, delegates, diagnostics buffers, debug draw data, query scratch buffers, and visualization
 314    /// interpolation caches.
 315    /// </remarks>
 316    public ChronicleHash ComputeReplayHash(
 317        GravitasReplayHashMode mode = GravitasReplayHashMode.Authoritative)
 318    {
 3875319        ThrowIfDisposed();
 3875320        return GravitasReplayHashService.Compute(this, mode);
 321    }
 322
 323    /// <summary>
 324    /// Attaches a context to a host-owned <see cref="GridWorld"/>.
 325    /// </summary>
 326    /// <param name="world">The active world to bind.</param>
 327    /// <param name="takeOwnership">True when disposing this context should dispose the supplied world.</param>
 328    /// <returns>A context bound to <paramref name="world"/>.</returns>
 329    public static GravitasWorldContext Attach(GridWorld world, bool takeOwnership = false)
 330    {
 10331        ChronicleGuard.ThrowIfNull(world, nameof(world));
 9332        return CreateRegistered(world, takeOwnership);
 333    }
 334
 335    /// <summary>
 336    /// Creates a context with an owned <see cref="GridWorld"/>.
 337    /// </summary>
 338    /// <param name="spatialGridCellSize">Ordinary-grid spatial lookup cell size for the created world.</param>
 339    /// <returns>A context that owns its created world.</returns>
 340    public static GravitasWorldContext CreateOwned(
 341        int spatialGridCellSize = GridWorld.DefaultSpatialGridCellSize)
 342    {
 10185343        return CreateRegistered(
 10185344            new GridWorld(spatialGridCellSize),
 10185345            ownsWorld: true);
 346    }
 347
 348    /// <summary>
 349    /// Advances this context's deterministic simulation clock and ordered simulate hooks.
 350    /// </summary>
 351    /// <exception cref="InvalidOperationException">
 352    /// The frame counter or required late-simulation phase counter is exhausted.
 353    /// </exception>
 354    /// <exception cref="OverflowException">The next elapsed timestamp is unrepresentable.</exception>
 355    /// <remarks>Timing exhaustion rejects before this call changes world state.</remarks>
 356    public void Simulate()
 357    {
 70971358        ThrowIfDisposed();
 70971359        PhysicsRuntimeMode runtimeMode = Settings.RuntimeMode;
 70971360        if ((runtimeMode.Runs3D() && Physics.SimulatePhysics)
 70971361            || (runtimeMode.Runs2D() && Physics2D.SimulatePhysics)
 70971362            || runtimeMode.RunsMixedContacts())
 70968363            ThrowIfLateSimulateTokenExhausted();
 364        // Clock exhaustion must reject before opening the containing fixed step.
 70969365        _clock.Simulate();
 70967366        RefreshQueryPartitions();
 70967367        _fixedStepOpen = true;
 70967368        EnterSimulationPhase();
 369        try
 370        {
 70967371            if (runtimeMode.Runs3D())
 62982372                Physics.Simulate();
 70967373            if (runtimeMode.Runs2D())
 23868374                Physics2D.Simulate();
 70967375            if (runtimeMode.RunsMixedContacts())
 15810376                MixedCollisions.Simulate();
 377
 70967378            Coroutines.Simulate();
 70967379            _hooks.InvokeSimulate();
 70962380        }
 5381        catch
 382        {
 5383            _fixedStepOpen = false;
 5384            throw;
 385        }
 386        finally
 387        {
 70967388            ExitSimulationPhase();
 70967389        }
 70962390    }
 391
 392    /// <summary>
 393    /// Runs this context's late-simulation step.
 394    /// </summary>
 395    /// <exception cref="InvalidOperationException">
 396    /// The independent late-simulation phase counter is exhausted. Rejection occurs
 397    /// before this call changes world state.
 398    /// </exception>
 399    /// <exception cref="OverflowException">
 400    /// A body position cannot be represented. Earlier step work may already have advanced;
 401    /// stop and restore a known state before continuing.
 402    /// </exception>
 403    public void LateSimulate()
 404    {
 71317405        ThrowIfDisposed();
 71317406        PhysicsRuntimeMode runtimeMode = Settings.RuntimeMode;
 71317407        bool willRun3D = runtimeMode.Runs3D() && Physics.SimulatePhysics;
 71317408        bool willRun2D = runtimeMode.Runs2D() && Physics2D.SimulatePhysics;
 71317409        bool willRunMixed = runtimeMode.RunsMixedContacts();
 71317410        if (willRun3D || willRun2D || willRunMixed)
 71314411            AdvanceLateSimulateToken();
 71315412        RefreshQueryPartitions();
 71315413        _fixedStepOpen = true;
 71315414        EnterSimulationPhase();
 415        try
 416        {
 71315417            _clock.LateSimulate();
 71315418            if (willRun3D)
 63058419                Physics.PrepareContinuousCollisionFrame();
 71312420            if (willRun2D)
 24304421                Physics2D.PrepareContinuousCollisionFrame();
 71309422            bool ran3D = willRun3D
 71309423                && Physics.BeginLateSimulateBodies(continuousCollisionFramePrepared: true);
 71308424            bool ran2D = willRun2D
 71308425                && Physics2D.BeginLateSimulateBodies(continuousCollisionFramePrepared: true);
 71307426            ProcessQueuedContinuousCollisionHandoffs(ran3D, ran2D);
 71306427            if (ran3D)
 63051428                Physics.CompleteLateSimulatePhysicsStep(deferSleep: willRunMixed);
 71303429            if (ran2D)
 24299430                Physics2D.CompleteLateSimulatePhysicsStep(deferSleep: willRunMixed);
 71302431            if (willRunMixed)
 432            {
 15999433                MixedCollisions.LateSimulate();
 15999434                UpdateAutomaticSleep(ran3D, ran2D, mixed: true);
 435            }
 436
 71302437            _hooks.InvokeLateSimulate();
 71299438        }
 439        finally
 440        {
 71315441            ExitSimulationPhase();
 71315442            _fixedStepOpen = false;
 71315443        }
 71299444        Physics.PublishCollisionPositionStates();
 71299445        Physics2D.PublishCollisionPositionStates();
 71299446        RefreshQueryPartitions();
 71299447    }
 448
 449    private void ProcessQueuedContinuousCollisionHandoffs(bool runs3D, bool runs2D)
 450    {
 71307451        if (!runs3D && !runs2D)
 9452            return;
 453
 454        try
 455        {
 71298456            int iterationLimit = Settings.ContinuousCollisionMaxToiIterations;
 71298457            int remainingIterations = iterationLimit;
 142748458            for (int iteration = 0; iteration < iterationLimit && remainingIterations > 0; iteration++)
 459            {
 71367460                int processedIterations = 0;
 71367461                if (runs3D)
 462                {
 63113463                    int usedIterations = Physics.ProcessQueuedContinuousCollisionHandoffs(remainingIterations);
 63112464                    processedIterations += usedIterations;
 63112465                    remainingIterations -= usedIterations;
 466                }
 467
 71366468                if (remainingIterations > 0 && runs2D)
 469                {
 24350470                    int usedIterations = Physics2D.ProcessQueuedContinuousCollisionHandoffs(remainingIterations);
 24350471                    processedIterations += usedIterations;
 24350472                    remainingIterations -= usedIterations;
 473                }
 474
 71366475                if (processedIterations == 0)
 71290476                    return;
 477            }
 478
 7479            if (runs3D)
 6480                Physics.ProcessQueuedContinuousCollisionHandoffs(iterationBudget: 0);
 7481            if (runs2D)
 6482                Physics2D.ProcessQueuedContinuousCollisionHandoffs(iterationBudget: 0);
 7483        }
 1484        catch
 485        {
 1486            if (runs3D)
 1487                Physics.AbortContinuousCollisionHandoffFrame();
 1488            if (runs2D)
 1489                Physics2D.AbortContinuousCollisionHandoffFrame();
 1490            throw;
 491        }
 71297492    }
 493
 494    internal void AdvanceLateSimulateToken()
 495    {
 71667496        ThrowIfLateSimulateTokenExhausted();
 71665497        _lateSimulateToken++;
 71665498    }
 499
 500    private void ThrowIfLateSimulateTokenExhausted() =>
 142635501        ChronicleGuard.ThrowIfTrue(_lateSimulateToken == long.MaxValue,
 142635502            nameof(GravitasWorldContext), "The late-simulation phase counter is exhausted.");
 503
 504    /// <summary>
 505    /// Runs this context's visualization accumulation step.
 506    /// </summary>
 507    public void Visualize()
 508    {
 49509        ThrowIfDisposed();
 49510        _clock.Visualize();
 49511        PhysicsRuntimeMode runtimeMode = Settings.RuntimeMode;
 49512        if (runtimeMode.Runs3D())
 38513            Physics.Visualize();
 49514        if (runtimeMode.Runs2D())
 22515            Physics2D.Visualize();
 49516        if (runtimeMode.RunsMixedContacts())
 6517            MixedCollisions.Visualize();
 518
 49519        _hooks.InvokeVisualize();
 49520    }
 521
 522    /// <summary>
 523    /// Runs this context's host-owned late-visualization hook phase.
 524    /// </summary>
 525    public void LateVisualize()
 526    {
 35527        ThrowIfDisposed();
 35528        _hooks.InvokeLateVisualize();
 35529    }
 530
 531    /// <summary>
 532    /// Resets this context's deterministic clock and context-local lifecycle hooks.
 533    /// </summary>
 534    public void Reset()
 535    {
 113536        ThrowIfDisposed();
 113537        _lateSimulateToken = 0;
 113538        _clock.Reset();
 113539        Constraints3D.Reset();
 113540        Constraints2D.Reset();
 113541        Collisions.Reset();
 113542        Collisions2D.Reset();
 113543        Physics.Reset();
 113544        Physics2D.Reset();
 113545        MixedCollisions.Reset();
 113546        Query2D.Reset();
 113547        Query3D.Reset();
 113548        QueryMixed.Reset();
 113549        Coroutines.Reset();
 113550        Diagnostics.Reset();
 113551        _hooks.InvokeReset();
 113552    }
 553
 554    /// <summary>
 555    /// Updates this context's fixed simulation frame rate.
 556    /// </summary>
 557    /// <param name="frameRate">The new frame rate. Must be within the supported physics settings range.</param>
 558    public void SetFrameRate(int frameRate)
 559    {
 3315560        ThrowIfDisposed();
 3315561        Settings.SetFrameRate(frameRate);
 3314562        _clock.SetFrameRate(frameRate);
 3314563        _hooks.InvokeFrameRateChanged();
 3314564    }
 565
 566    /// <summary>
 567    /// Applies context-local settings and synchronizes frame-derived clock state.
 568    /// </summary>
 569    /// <param name="settings">The settings instance to own.</param>
 570    public void ApplySettings(PhysicsSettings settings)
 571    {
 916572        ThrowIfDisposed();
 916573        ChronicleGuard.ThrowIfNull(settings, nameof(settings));
 916574        ChronicleGuard.ThrowIfTrue(settings.Owner != null && !ReferenceEquals(settings.Owner, this),
 916575            nameof(settings), "Physics settings are already owned by another context.");
 915576        ValidateMixedGeometry(settings.RuntimeMode, settings.Mixed2DHalfThickness);
 912577        Settings.Owner = null;
 912578        Settings = settings;
 912579        settings.Owner = this;
 912580        _clock.SetFrameRate(settings.FrameRate);
 912581        _hooks.InvokeFrameRateChanged();
 912582    }
 583
 584    internal void ValidateMixedGeometry(PhysicsRuntimeMode mode, Fixed64 halfThickness)
 585    {
 6883586        ThrowIfFixedStepMutationNotAllowed();
 6880587        if (!mode.RunsMixedContacts())
 2859588            return;
 8052589        for (int i = 0; i < Physics2D.ColliderCount; i++)
 11590            Physics2D.GetColliderByServiceIndex(i).ValidateMixedGeometry(halfThickness);
 4015591    }
 592
 593    /// <summary>
 594    /// Counts complete steps in a duration using the current fixed step size.
 595    /// </summary>
 596    /// <param name="duration">A nonnegative duration in seconds.</param>
 597    /// <returns>The complete-step count, rounded down using exact raw-unit division.</returns>
 598    /// <remarks>This is not a historical timestamp-to-frame lookup.</remarks>
 599    public long GetFrameCountForDuration(Fixed64 duration)
 600    {
 216601        ThrowIfDisposed();
 216602        return _clock.GetFrameCountForDuration(duration);
 603    }
 604
 605    internal IDisposable RegisterOnSimulate(string owner, int order, Action callback)
 606    {
 18607        ThrowIfDisposed();
 18608        return _hooks.RegisterOnSimulate(owner, order, callback);
 609    }
 610
 611    internal IDisposable RegisterOnLateSimulate(string owner, int order, Action callback)
 612    {
 11613        ThrowIfDisposed();
 11614        return _hooks.RegisterOnLateSimulate(owner, order, callback);
 615    }
 616
 617    internal IDisposable RegisterOnVisualize(string owner, int order, Action callback)
 618    {
 1619        ThrowIfDisposed();
 1620        return _hooks.RegisterOnVisualize(owner, order, callback);
 621    }
 622
 623    internal IDisposable RegisterOnLateVisualize(string owner, int order, Action callback)
 624    {
 1625        ThrowIfDisposed();
 1626        return _hooks.RegisterOnLateVisualize(owner, order, callback);
 627    }
 628
 629    internal IDisposable RegisterOnReset(string owner, int order, Action callback)
 630    {
 2631        ThrowIfDisposed();
 2632        return _hooks.RegisterOnReset(owner, order, callback);
 633    }
 634
 635    internal IDisposable RegisterOnFrameRateChanged(string owner, int order, Action callback)
 636    {
 2637        ThrowIfDisposed();
 2638        return _hooks.RegisterOnFrameRateChanged(owner, order, callback);
 639    }
 640
 641    /// <inheritdoc/>
 642    public void Dispose()
 643    {
 10204644        lock (_worldOwnershipLock)
 645        {
 10204646            if (_disposed)
 13647                return;
 648
 10191649            Constraints3D.Reset();
 10191650            Constraints2D.Reset();
 10191651            Physics.ReleaseStaticSurfaces();
 10191652            Physics2D.ReleaseStaticSurfaces();
 10191653            World.OnChangeCommitted -= OnQueryPartitionWorldChange;
 10191654            Settings.Owner = null;
 10191655            _disposed = true;
 656            try
 657            {
 10191658                Coroutines.Deactivate();
 10191659            }
 660            finally
 661            {
 662                try
 663                {
 10191664                    if (_ownsWorld && World.IsActive)
 10186665                        World.Dispose();
 10191666                }
 667                finally
 668                {
 10191669                    ReleaseWorldOwnership(this);
 10191670                }
 10191671            }
 672        }
 10204673    }
 674
 675    private static GravitasWorldContext CreateRegistered(GridWorld world, bool ownsWorld)
 676    {
 10194677        lock (_worldOwnershipLock)
 678        {
 10194679            ChronicleGuard.ThrowIfTrue(
 10194680                !world.IsActive,
 10194681                nameof(GravitasWorldContext),
 10194682                "GravitasWorldContext requires an active GridWorld.");
 10193683            ThrowIfWorldOwned(world);
 10191684            GravitasWorldContext context = new(world, ownsWorld);
 10191685            _worldOwners[world] = context;
 10191686            return context;
 687        }
 10191688    }
 689
 690    private static void ThrowIfWorldOwned(GridWorld world)
 691    {
 10193692        ChronicleGuard.ThrowIfTrue(
 10193693            _worldOwners.ContainsKey(world),
 10193694            nameof(GravitasWorldContext),
 10193695            "GridWorld is already attached to an active GravitasWorldContext.");
 10191696    }
 697
 698    private static void ReleaseWorldOwnership(GravitasWorldContext context)
 699    {
 10191700        _worldOwners.Remove(context.World);
 10191701    }
 702
 703    internal void ThrowIfDisposed()
 704    {
 2972970705        ChronicleGuard.ThrowIfDisposed(_disposed, nameof(GravitasWorldContext));
 2972961706        ChronicleGuard.ThrowIfTrue(
 2972961707            !World.IsActive,
 2972961708            nameof(GravitasWorldContext),
 2972961709            "GravitasWorldContext is bound to an inactive GridWorld.");
 2972961710    }
 711}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Runtime/GravitasWorldContext.QueryPartitions.cs

#LineLine coverage
 1//=======================================================================
 2// GravitasWorldContext.QueryPartitions.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 GridForge.Grids;
 9
 10namespace Gravitas;
 11
 12/// <content>Reconciles physical grid membership at stable sampling boundaries.</content>
 13public sealed partial class GravitasWorldContext
 14{
 15    private ulong _observedGridChangeSequence;
 16    private bool _queryPartitionTopologyChanged;
 17
 18    private void OnQueryPartitionWorldChange(GridEventInfo change)
 19    {
 898020        _observedGridChangeSequence = change.ChangeSequence;
 898021        if (change.ChangeKind is GridEventKind.GridAdded or GridEventKind.GridRemoved
 898022            or GridEventKind.GridChanged or GridEventKind.SparseVoxelAdded
 898023            or GridEventKind.SparseVoxelRemoved or GridEventKind.WorldReset)
 24        {
 897825            _queryPartitionTopologyChanged = Physics.ColliderCount > 0 || Physics2D.ColliderCount > 0;
 26        }
 898027    }
 28
 29    internal bool RefreshQueryPartitions()
 30    {
 31224031        if (!IsBetweenFixedSteps || !World.IsActive
 31224032            || _observedGridChangeSequence != World.ChangeSequence)
 33        {
 14307734            return false;
 35        }
 36
 16916337        if (_queryPartitionTopologyChanged)
 38        {
 39            // Registration scans occur once per physical topology batch, never per
 40            // ordinary query, obstacle event, or unchanged simulation frame.
 2441            Collisions.RebuildPartitionsAfterWorldChange();
 2442            Collisions2D.RebuildPartitionsAfterWorldChange();
 2443            _queryPartitionTopologyChanged = false;
 44        }
 45
 16916346        Collisions2D.RefreshDeferredColliderPartitions();
 16916347        return true;
 48    }
 49}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Runtime/GravitasWorldContext.Sleep.cs

#LineLine coverage
 1//=======================================================================
 2// GravitasWorldContext.Sleep.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
 8namespace Gravitas;
 9
 10/// <content>Coordinates automatic sleep after all participating response phases.</content>
 11public sealed partial class GravitasWorldContext
 12{
 1019113    private readonly SleepIslands _sleepIslands = new();
 14
 15    internal void ReserveSleepIslands() =>
 1228116        _sleepIslands.Reserve(checked(Physics.BodySlotCount + Physics2D.BodySlotCount));
 17
 18    internal void UpdateAutomaticSleep(bool ran3D, bool ran2D, bool mixed = false)
 19    {
 7138620        bool ready3D = ran3D && Physics.AdvanceSleepCounters();
 7138621        bool ready2D = ran2D && Physics2D.AdvanceSleepCounters();
 7138622        if (!ready3D && !ready2D)
 7087423            return;
 24
 25        // Only rebuild connectivity on a candidate frame. Current retained
 26        // contacts include sleeping edges and reflect response-time removals.
 51227        int planarOffset = ran3D || mixed ? Physics.BodySlotCount : 0;
 51228        int planarSlots = ran2D || mixed ? Physics2D.BodySlotCount : 0;
 51229        _sleepIslands.Begin(checked(planarOffset + planarSlots));
 77830        if (ran3D) Physics.JoinSleepIslands(_sleepIslands);
 76531        if (ran2D) Physics2D.JoinSleepIslands(_sleepIslands, planarOffset);
 53332        if (mixed) MixedCollisions.JoinSleepIslands(_sleepIslands, planarOffset);
 33
 78534        if (ran3D || mixed) Physics.BlockUnreadySleepIslands(_sleepIslands, ran3D);
 77235        if (ran2D || mixed) Physics2D.BlockUnreadySleepIslands(_sleepIslands, planarOffset, ran2D);
 77636        if (ready3D) Physics.SleepReadyIslands(_sleepIslands);
 76437        if (ready2D) Physics2D.SleepReadyIslands(_sleepIslands, planarOffset);
 51238    }
 39}

Methods/Properties

.cctor()
.ctor(GridForge.Grids.GridWorld,System.Boolean)
get_IsBetweenFixedSteps()
EnterSimulationPhase()
ExitSimulationPhase()
ThrowIfFixedStepMutationNotAllowed()
get_IsDisposed()
get_VoxelSize()
get_FrameRate()
get_DeltaTime()
get_InvDeltaTime()
get_FrameCount()
get_ElapsedTime()
get_AccumulatedTime()
get_ResetAccumulation()
get_ResetAccumulationThisVisualize()
get_LateSimulateToken()
CaptureClockLifetime()
ValidateClockLifetime(System.Object)
GetDeadlineFrame(System.Int64)
get_ExpectedAccumulation()
ComputeReplayHash(Gravitas.GravitasReplayHashMode)
Attach(GridForge.Grids.GridWorld,System.Boolean)
CreateOwned(System.Int32)
Simulate()
LateSimulate()
ProcessQueuedContinuousCollisionHandoffs(System.Boolean,System.Boolean)
AdvanceLateSimulateToken()
ThrowIfLateSimulateTokenExhausted()
Visualize()
LateVisualize()
Reset()
SetFrameRate(System.Int32)
ApplySettings(Gravitas.PhysicsSettings)
ValidateMixedGeometry(Gravitas.PhysicsRuntimeMode,FixedMathSharp.Fixed64)
GetFrameCountForDuration(FixedMathSharp.Fixed64)
RegisterOnSimulate(System.String,System.Int32,System.Action)
RegisterOnLateSimulate(System.String,System.Int32,System.Action)
RegisterOnVisualize(System.String,System.Int32,System.Action)
RegisterOnLateVisualize(System.String,System.Int32,System.Action)
RegisterOnReset(System.String,System.Int32,System.Action)
RegisterOnFrameRateChanged(System.String,System.Int32,System.Action)
Dispose()
CreateRegistered(GridForge.Grids.GridWorld,System.Boolean)
ThrowIfWorldOwned(GridForge.Grids.GridWorld)
ReleaseWorldOwnership(Gravitas.GravitasWorldContext)
ThrowIfDisposed()
OnQueryPartitionWorldChange(GridForge.Grids.GridEventInfo)
RefreshQueryPartitions()
.ctor(GridForge.Grids.GridWorld,System.Boolean)
ReserveSleepIslands()
UpdateAutomaticSleep(System.Boolean,System.Boolean,System.Boolean)