< Summary

Line coverage
100%
Covered lines: 131
Uncovered lines: 0
Coverable lines: 131
Total lines: 385
Line coverage: 100%
Branch coverage
100%
Covered branches: 46
Total branches: 46
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Settings/PhysicsSettings.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsSettings.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 System.Runtime.InteropServices;
 11using FixedMathSharp;
 12using Gravitas.Support;
 13using SwiftCollections;
 14
 15namespace Gravitas;
 16
 17/// <summary>
 18/// Stores context-local configuration for deterministic physics simulation.
 19/// </summary>
 20/// <content>Owns validated settings, their context binding and registered-layer defaults.</content>
 21public sealed partial class PhysicsSettings
 22{
 23    internal GravitasWorldContext? Owner;
 24
 25    /// <summary>
 26    /// Default fixed-step frame rate in simulation frames per second.
 27    /// </summary>
 28    public const int DefaultFrameRate = 32;
 29
 30    /// <summary>
 31    /// Maximum supported fixed-step frame rate.
 32    /// </summary>
 33    /// <remarks>
 34    /// Higher values quantize <see cref="GravitasWorldContext.DeltaTime"/> at or below
 35    /// <see cref="Fixed64.Epsilon"/>, which would make integration and CCD degeneracy
 36    /// checks disagree about whether a step has meaningful duration.
 37    /// </remarks>
 38    public const int MaxResolvableFrameRate = (int)(FixedMath.ONE_L / (FixedMath.DEFAULT_TOLERANCE_L + 1));
 39
 40    /// <summary>
 41    /// Maximum number of physics layers represented by a layer mask.
 42    /// </summary>
 43    public const int MaxLayers = 32;
 44
 45    /// <summary>
 46    /// Default number of frames an empty partition remains retained for reuse.
 47    /// </summary>
 48    public const int DefaultRetainedPartitionTimeToKillFrames = DefaultFrameRate * 10;
 49
 50    /// <summary>
 51    /// Default maximum number of retained partitions checked per retirement sweep.
 52    /// </summary>
 53    public const int DefaultRetainedPartitionRetirementSweepBudget = 64;
 54
 55    /// <summary>
 56    /// Default maximum same-frame time-of-impact iterations for continuous collision.
 57    /// </summary>
 58    public const int DefaultContinuousCollisionMaxToiIterations = 4;
 59
 60    /// <summary>
 61    /// Default projected-impulse iteration count for discrete 3D constraint islands.
 62    /// </summary>
 63    public const int DefaultDiscreteSolverIterations = 6;
 64
 65    /// <summary>
 66    /// Default closing-speed threshold below which restitution is disabled.
 67    /// </summary>
 168    public static readonly Fixed64 DefaultRestitutionVelocityThreshold = (Fixed64)0.25f;
 69
 70    /// <summary>
 71    /// Default Y-axis half-thickness for 2D colliders embedded in mixed queries and contacts.
 72    /// </summary>
 173    public static readonly Fixed64 DefaultMixed2DHalfThickness = Fixed64.Half;
 74
 75    /// <summary>
 76    /// Default include mask used for ground and support checks.
 77    /// </summary>
 178    public static readonly PhysicsLayerMask DefaultGroundCheckLayerMask = PhysicsLayerMask.FromLayer(new PhysicsLayer(0)
 79
 80    /// <summary>
 81    /// Gets the fixed-step frame rate in simulation frames per second.
 82    /// </summary>
 83    public int FrameRate { get; private set; }
 84
 85    private readonly bool[,] _collisionMatrix;
 86
 87    /// <summary>
 88    /// Gets the layer-to-layer physical collision enablement matrix.
 89    /// </summary>
 303666990    public bool[,] CollisionMatrix => _collisionMatrix;
 91
 92    // Raw matrix edits have no setter notification. Retained joined contacts
 93    // need the exact eligible-layer bits, including enabled out-of-table layers.
 94    internal ulong GetCollisionLayerMask(PhysicsLayer row, PhysicsLayer column,
 95        bool watchRow, bool watchColumn)
 96    {
 19529097        ulong mask = 0;
 39058098        int rows = _collisionMatrix.GetLength(0), columns = _collisionMatrix.GetLength(1);
 99        // CLR rectangular arrays are contiguous in row-major order. Read the
 100        // same cells with one-dimensional bounds checks; empty tables enable all layers.
 195290101        ReadOnlySpan<bool> cells = _collisionMatrix.Length == 0 ? default
 195290102            : MemoryMarshal.CreateReadOnlySpan(ref _collisionMatrix[0, 0], _collisionMatrix.Length);
 195290103        if (watchRow)
 104        {
 17827105            uint enabled = uint.MaxValue;
 17827106            if (row.Index < rows)
 107            {
 17651108                ReadOnlySpan<bool> values = cells.Slice(row.Index * columns, Math.Min(columns, MaxLayers));
 73118109                for (int layer = 0; layer < values.Length; layer++)
 19707110                    if (!values[layer]) enabled &= ~(1u << layer);
 111            }
 17827112            mask = enabled;
 113        }
 195290114        if (watchColumn)
 115        {
 177463116            uint enabled = uint.MaxValue;
 177463117            if (column.Index < columns)
 363142118                for (int layer = 0; layer < Math.Min(rows, MaxLayers); layer++)
 92170119                    if (!cells[layer * columns + column.Index]) enabled &= ~(1u << layer);
 177463120            mask |= (ulong)enabled << MaxLayers;
 121        }
 195290122        return mask;
 123    }
 124
 125    /// <summary>
 126    /// Gets or sets whether reusable runtime collision objects are pooled.
 127    /// </summary>
 128    public bool PoolingEnabled { get; set; } = true;
 129
 130    /// <summary>
 131    /// Gets or sets the include mask used for ground and support checks.
 132    /// </summary>
 133    public PhysicsLayerMask GroundCheckLayerMask { get; set; }
 134
 11133135    private int _retainedPartitionTimeToKillFrames = DefaultRetainedPartitionTimeToKillFrames;
 11133136    private int _retainedPartitionRetirementSweepBudget = DefaultRetainedPartitionRetirementSweepBudget;
 11133137    private ContinuousCollisionMode _defaultContinuousCollisionMode = ContinuousCollisionMode.Discrete;
 11133138    private int _continuousCollisionMaxToiIterations = DefaultContinuousCollisionMaxToiIterations;
 11133139    private int _discreteSolverIterations = DefaultDiscreteSolverIterations;
 11133140    private Fixed64 _restitutionVelocityThreshold = DefaultRestitutionVelocityThreshold;
 11133141    private PhysicsRuntimeMode _runtimeMode = PhysicsRuntimeMode.ThreeD;
 11133142    private Fixed64 _mixed2DHalfThickness = DefaultMixed2DHalfThickness;
 143
 144    /// <summary>
 145    /// Gets or sets how many simulation frames an empty voxel partition should stay attached for fast reuse.
 146    /// A value of zero retires eligible partitions on the next retirement sweep.
 147    /// </summary>
 148    public int RetainedPartitionTimeToKillFrames
 149    {
 107252150        get => _retainedPartitionTimeToKillFrames;
 151        set
 152        {
 35153            ChronicleGuard.ThrowIfNegative(value, nameof(value));
 35154            _retainedPartitionTimeToKillFrames = value;
 35155        }
 156    }
 157
 158    /// <summary>
 159    /// Gets or sets the maximum retained partitions checked for retirement during one collision distribution step.
 160    /// A value of zero disables retirement sweeps.
 161    /// </summary>
 162    public int RetainedPartitionRetirementSweepBudget
 163    {
 107252164        get => _retainedPartitionRetirementSweepBudget;
 165        set
 166        {
 41167            ChronicleGuard.ThrowIfNegative(value, nameof(value));
 41168            _retainedPartitionRetirementSweepBudget = value;
 41169        }
 170    }
 171
 172    /// <summary>
 173    /// Gets or sets the default tunneling policy used by bodies configured to inherit from the context.
 174    /// A context default of <see cref="ContinuousCollisionMode.Inherit"/> resolves to
 175    /// <see cref="ContinuousCollisionMode.Discrete"/>.
 176    /// </summary>
 177    /// <exception cref="ArgumentOutOfRangeException">The value is not a declared continuous-collision mode.</exception>
 178    public ContinuousCollisionMode DefaultContinuousCollisionMode
 179    {
 165925180        get => _defaultContinuousCollisionMode;
 181        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 182        set
 183        {
 40184            value.ThrowIfInvalid(nameof(value));
 36185            _defaultContinuousCollisionMode = value;
 36186        }
 187    }
 188
 189    /// <summary>
 190    /// Gets or sets the maximum same-frame continuous-collision TOI iterations one body or handoff queue may consume.
 191    /// </summary>
 192    public int ContinuousCollisionMaxToiIterations
 193    {
 79666194        get => _continuousCollisionMaxToiIterations;
 195        set
 196        {
 113197            ChronicleGuard.ThrowIfNegativeOrZero(value, nameof(value));
 111198            _continuousCollisionMaxToiIterations = value;
 111199        }
 200    }
 201
 202    /// <summary>
 203    /// Gets or sets the bounded projected-impulse iteration count used for 3D discrete
 204    /// contact and joint constraint islands. Multipoint 3D pairs use this budget
 205    /// even when alone; a single contact row uses the direct one-pass path.
 206    /// </summary>
 207    public int DiscreteSolverIterations
 208    {
 34510209        get => _discreteSolverIterations;
 210        set
 211        {
 283212            ChronicleGuard.ThrowIfNegativeOrZero(value, nameof(value));
 281213            _discreteSolverIterations = value;
 281214        }
 215    }
 216
 217    /// <summary>
 218    /// Gets or sets the closing speed at or below which contact response uses zero restitution.
 219    /// </summary>
 220    public Fixed64 RestitutionVelocityThreshold
 221    {
 422710222        get => _restitutionVelocityThreshold;
 223        set
 224        {
 80225            ChronicleGuard.ThrowIfArgument(
 80226                value < Fixed64.Zero,
 80227                nameof(value),
 80228                "Restitution velocity threshold cannot be negative.");
 79229            _restitutionVelocityThreshold = value;
 79230        }
 231    }
 232
 233    /// <summary>
 234    /// Gets or sets the default half-thickness used when pure 2D colliders are embedded into mixed 2D/3D contacts.
 235    /// </summary>
 236    public Fixed64 Mixed2DHalfThickness
 237    {
 70720238        get => _mixed2DHalfThickness;
 239        set
 240        {
 79241            ChronicleGuard.ThrowIfArgument(
 79242                value <= Fixed64.Zero,
 79243                nameof(value),
 79244                "Mixed 2D half-thickness must be greater than zero.");
 77245            if (_mixed2DHalfThickness == value)
 7246                return;
 70247            Owner?.ValidateMixedGeometry(_runtimeMode, value);
 68248            _mixed2DHalfThickness = value;
 68249        }
 250    }
 251
 252    /// <summary>
 253    /// Gets or sets which dimensional physics service this context should advance.
 254    /// </summary>
 255    public PhysicsRuntimeMode RuntimeMode
 256    {
 354941257        get => _runtimeMode;
 258        set
 259        {
 6173260            ChronicleGuard.ThrowIfArgument(
 6173261                !value.IsValid(),
 6173262                nameof(value),
 6173263                "Physics runtime mode must be TwoD, ThreeD, Both, or Mixed.");
 6168264            if (_runtimeMode == value)
 196265                return;
 5972266            Owner?.ValidateMixedGeometry(value, _mixed2DHalfThickness);
 5968267            _runtimeMode = value;
 5968268        }
 269    }
 270
 271    /// <summary>
 272    /// Creates physics settings, using registered-layer defaults for omitted values.
 273    /// </summary>
 11133274    public PhysicsSettings(
 11133275        int? frameRate,
 11133276        bool[,]? collisionMatrix,
 11133277        PhysicsLayerMask? groundCheckLayerMask = null)
 278    {
 11133279        SetFrameRate(frameRate ?? DefaultFrameRate);
 11132280        _collisionMatrix = collisionMatrix ?? GetRegisteredCollisionMatrix();
 11132281        GroundCheckLayerMask = groundCheckLayerMask ?? DefaultGroundCheckLayerMask;
 11132282    }
 283
 284    /// <summary>
 285    /// Sets the fixed-step frame rate after validating its representable range.
 286    /// </summary>
 287    public void SetFrameRate(int frameRate)
 288    {
 14449289        ThrowIfInvalidFrameRate(frameRate);
 14446290        FrameRate = frameRate;
 14446291    }
 292
 293    internal static void ThrowIfInvalidFrameRate(int frameRate)
 294    {
 28868295        ChronicleGuard.ThrowIfNegativeOrZero(frameRate, nameof(frameRate));
 28868296        if (frameRate > MaxResolvableFrameRate)
 297        {
 4298            throw new ArgumentOutOfRangeException(
 4299                nameof(frameRate),
 4300                frameRate,
 4301                $"Frame rate cannot exceed {MaxResolvableFrameRate}.");
 302        }
 28864303    }
 304
 305    /// <summary>
 306    /// Creates settings with default values and the currently registered layer matrix.
 307    /// </summary>
 308    public static PhysicsSettings DefaultSettings()
 309    {
 10203310        bool[,] collisionMatrix = GetRegisteredCollisionMatrix();
 10203311        return new PhysicsSettings(DefaultFrameRate, collisionMatrix);
 312    }
 313
 314    /// <summary>
 315    /// Creates a fully enabled square collision matrix sized to the registered layer names.
 316    /// </summary>
 317    public static bool[,] GetRegisteredCollisionMatrix()
 318    {
 10994319        SwiftList<string> layersList = new();
 320
 725604321        for (int i = 0; i < MaxLayers; ++i)
 322        {
 351808323            string? layerName = PhysicsLayer.LayerToName(i);
 324            // Check if the layer has a name
 351808325            if (!string.IsNullOrEmpty(layerName))
 5075326                layersList.Add(layerName);
 327        }
 328
 10994329        string[] layerNames = layersList.ToArray();
 10994330        int numberOfLayers = layerNames.Length;
 331
 10994332        if (numberOfLayers == 0)
 5921333            return new bool[0, 0];
 334
 5073335        bool[,] collisionMatrix = new bool[numberOfLayers, numberOfLayers];
 20296336        for (int i = 0; i < numberOfLayers; ++i)
 20308337            for (int j = 0; j < numberOfLayers; ++j)
 5079338                collisionMatrix[i, j] = true;
 339
 5073340        return collisionMatrix;
 341    }
 342}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Settings/PhysicsSettings.ReplayHash.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsSettings.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;
 10
 11namespace Gravitas;
 12
 13/// <content>
 14/// Contributes physics settings to deterministic replay hashes.
 15/// </content>
 16public sealed partial class PhysicsSettings
 17{
 18    internal void ContributeReplayHash(ref ChronicleHashWriter writer)
 19    {
 389020        writer.WriteSection("settings", 1);
 389021        writer.WriteInt32(FrameRate);
 389022        writer.WriteBool(PoolingEnabled);
 389023        writer.WritePhysicsLayerMask(GroundCheckLayerMask);
 389024        writer.WriteInt32(RetainedPartitionTimeToKillFrames);
 389025        writer.WriteInt32(RetainedPartitionRetirementSweepBudget);
 389026        writer.WriteEnum(DefaultContinuousCollisionMode);
 389027        writer.WriteInt32(ContinuousCollisionMaxToiIterations);
 389028        writer.WriteInt32(DiscreteSolverIterations);
 389029        writer.WriteFixed64(RestitutionVelocityThreshold);
 389030        writer.WriteFixed64(Mixed2DHalfThickness);
 389031        writer.WriteEnum(RuntimeMode);
 32
 389033        int rows = _collisionMatrix.GetLength(0);
 389034        int columns = _collisionMatrix.GetLength(1);
 389035        writer.WriteInt32(rows);
 389036        writer.WriteInt32(columns);
 1082037        for (int row = 0; row < rows; row++)
 38        {
 613839            for (int column = 0; column < columns; column++)
 154940                writer.WriteBool(_collisionMatrix[row, column]);
 41        }
 389042    }
 43}