< Summary

Information
Class: Gravitas.Colliders.LSCompoundCollider2D
Assembly: Gravitas
File(s): /home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Compound/LSCompoundCollider2D.cs
Line coverage
100%
Covered lines: 201
Uncovered lines: 0
Coverable lines: 201
Total lines: 405
Line coverage: 100%
Branch coverage
100%
Covered branches: 84
Total branches: 84
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/Colliders/Compound/LSCompoundCollider2D.cs

#LineLine coverage
 1//=======================================================================
 2// LSCompoundCollider2D.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 FixedMathSharp.Geometry;
 12using Gravitas.CollisionHandling;
 13using Gravitas.Materials;
 14
 15namespace Gravitas.Colliders;
 16
 17/// <summary>
 18/// Represents one pure 2D collider identity whose collision shape is composed
 19/// from deterministic internal primitive and convex-polygon parts.
 20/// </summary>
 21public sealed class LSCompoundCollider2D : LSCollider2D
 22{
 23    private readonly CompoundColliderPart2D[] _parts;
 24    private readonly LSCollider2D[] _partColliders;
 25    private readonly ExactMassPoint2D[] _massPointScratch;
 26    private readonly ExactMassWeight[] _massWeightScratch;
 28827    private readonly ContactManifold2D _partManifoldScratch = new();
 28    private bool _hasMassPropertyCenter;
 29    private Vector2d _massPropertyOwnerScale;
 30    private Vector2d _massPropertyOffset;
 31    private bool _massPropertyCommitted;
 32    private Vector2d _massPropertyCenter;
 33    private bool _hasMomentGeometry;
 34    private Vector2d _momentReferencePoint;
 35    private Signed576 _momentGeometry;
 36    private Signed704 _momentDenominator;
 37
 38    /// <summary>Creates a runtime compound collider from authored pure 2D parts.</summary>
 28839    public LSCompoundCollider2D(params CompoundColliderPart2D[] parts)
 40    {
 28841        ChronicleGuard.ThrowIfNull(parts, nameof(parts));
 28842        ChronicleGuard.ThrowIfArgument(parts.Length == 0, nameof(parts), "2D compound collider must contain at least one
 43
 152644        for (int i = 0; i < parts.Length; i++)
 47745            ValidatePart(parts[i]);
 46
 28647        _parts = new CompoundColliderPart2D[parts.Length];
 28648        _partColliders = new LSCollider2D[parts.Length];
 28649        _massPointScratch = new ExactMassPoint2D[parts.Length];
 28650        _massWeightScratch = new ExactMassWeight[parts.Length];
 152451        for (int i = 0; i < parts.Length; i++)
 52        {
 47653            _parts[i] = parts[i];
 47654            _partColliders[i] = MaterializePartCollider(parts[i]);
 47655            _partColliders[i].ReserveCompoundPart(this, parts[i].LocalRotation, parts[i].LocalScale);
 56        }
 28657    }
 58
 59    /// <inheritdoc/>
 125460    public override ColliderType2D Shape => ColliderType2D.Compound;
 61
 62    /// <inheritdoc/>
 7963    public override int Priority => ColliderSettings2D.GetPriority(Shape);
 64
 65    /// <summary>
 66    /// Gets the radius of a circle that conservatively contains the current
 67    /// aggregate shape.
 68    /// </summary>
 69    public Fixed64 ScaledRadius
 70    {
 71        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 72        get
 73        {
 2674            return HasCommittedShape
 2675                ? CanonicalCenteredProxyRadius
 2676                : ColliderCanonicalBounds2D.GetCurrentCompoundCenteredProxyRadius(this);
 77        }
 78    }
 79
 80    /// <summary>Gets the authored parts in stable source order.</summary>
 5581    public ReadOnlySpan<CompoundColliderPart2D> Parts => _parts;
 82
 83    /// <summary>Gets the number of authored compound parts.</summary>
 84    public int PartCount
 85    {
 86        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1130487        get => _parts.Length;
 88    }
 89
 90    /// <summary>Gets the stable runtime part identifier for a source-order index.</summary>
 91    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 92    public int GetPartId(int index)
 93    {
 294        ChronicleGuard.ThrowIfArrayIndexInvalid(index, _parts.Length, nameof(index));
 295        return index;
 96    }
 97
 98    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 99    internal LSCollider2D GetPartCollider(int index)
 100    {
 7312101        ChronicleGuard.ThrowIfArrayIndexInvalid(index, _parts.Length, nameof(index));
 7312102        return _partColliders[index];
 103    }
 104
 132105    internal ContactManifold2D PartManifoldScratch => _partManifoldScratch;
 106
 107    /// <inheritdoc/>
 108    public override bool ContainsPoint(Vector2d point)
 109    {
 1268110        for (int i = 0; i < _partColliders.Length; i++)
 111        {
 424112            if (_partColliders[i].ContainsPoint(point))
 3113                return true;
 114        }
 115
 210116        return false;
 117    }
 118
 119    /// <inheritdoc/>
 120    public override Vector2d GetClosestPoint(Vector2d point)
 121    {
 5122        _ = TryGetClosestBoundaryAnchor(
 5123            point,
 5124            out FixedPointAnchor2d anchor);
 5125        if (anchor.TryGetPoint(out Vector2d closest))
 126        {
 4127            return closest;
 128        }
 129
 1130        throw new InvalidOperationException(
 1131            "The closest compound surface point is outside the Fixed64 coordinate domain.");
 132    }
 133
 134    /// <inheritdoc/>
 135    public override Vector2d GetSupportPoint(Vector2d direction)
 136    {
 4137        Vector2d bestPoint = _partColliders[0].GetSupportPoint(direction);
 4138        Fixed64 bestProjection = Vector2d.Dot(bestPoint, direction);
 12139        for (int i = 1; i < _partColliders.Length; i++)
 140        {
 2141            Vector2d candidate = _partColliders[i].GetSupportPoint(direction);
 2142            Fixed64 projection = Vector2d.Dot(candidate, direction);
 2143            if (projection <= bestProjection)
 144                continue;
 145
 1146            bestProjection = projection;
 1147            bestPoint = candidate;
 148        }
 149
 4150        return bestPoint;
 151    }
 152
 153    internal override ExactMassPoint2D CalculateLocalMassPoint()
 154    {
 1360155        GetCurrentScaleFactors(out Vector2d ownerScale, out _);
 1360156        return _hasMassPropertyCenter
 1360157            && ownerScale == _massPropertyOwnerScale
 1360158            && LocalOffset == _massPropertyOffset
 1360159            && HasCommittedShape == _massPropertyCommitted
 1360160            ? ExactMassPoint2D.FromPoint(_massPropertyCenter)
 1360161            : CalculateAggregateMassPoint(usePrepared: false);
 162    }
 163
 164    internal override ExactMassPoint2D CalculatePreparedLocalMassPoint() =>
 1431165        CalculateAggregateMassPoint(usePrepared: true);
 166
 167    private ExactMassPoint2D CalculateAggregateMassPoint(bool usePrepared)
 168    {
 1767169        bool hasPositiveWeight = false;
 8234170        for (int i = 0; i < _partColliders.Length; i++)
 171        {
 2350172            LSCollider2D partCollider = _partColliders[i];
 2350173            ExactMassWeight weight = usePrepared
 2350174                ? partCollider.CalculatePreparedAreaForMassProperties()
 2350175                : partCollider.CalculateAreaForMassProperties();
 2350176            _massPointScratch[i] = usePrepared
 2350177                ? partCollider.CalculatePreparedLocalMassPoint()
 2350178                : partCollider.CalculateLocalMassPoint();
 2350179            _massWeightScratch[i] = weight;
 2350180            hasPositiveWeight |= !weight.IsZero;
 181        }
 182
 1767183        if (!hasPositiveWeight)
 184        {
 24185            for (int i = 0; i < _massWeightScratch.Length; i++)
 8186                _massWeightScratch[i] = ExactMassWeight.One;
 187        }
 188
 1767189        if (!ExactMassPoint2D.TryGetWeightedAverage(
 1767190            _massPointScratch,
 1767191            _massWeightScratch,
 1767192            out Vector2d center))
 193        {
 2194            throw new InvalidOperationException(
 2195                usePrepared
 2196                    ? "Prepared 2D compound mass-property point is outside the Fixed64 coordinate domain."
 2197                    : "The 2D compound collider's center of mass is outside the Fixed64 coordinate domain.");
 198        }
 1765199        return ExactMassPoint2D.FromPoint(center);
 200    }
 201
 202    internal override ExactMassWeight CalculateAreaForMassProperties() =>
 2203        CalculateAggregateMassWeight(usePrepared: false);
 204
 205    internal override ExactMassWeight CalculatePreparedAreaForMassProperties() =>
 1430206        CalculateAggregateMassWeight(usePrepared: true);
 207
 208    private ExactMassWeight CalculateAggregateMassWeight(bool usePrepared)
 209    {
 1432210        ExactMassWeight totalWeight = ExactMassWeight.Zero;
 6442211        for (int i = 0; i < _partColliders.Length; i++)
 212        {
 1789213            ExactMassWeight weight = usePrepared
 1789214                ? _partColliders[i].CalculatePreparedAreaForMassProperties()
 1789215                : _partColliders[i].CalculateAreaForMassProperties();
 1789216            totalWeight = totalWeight.Add(weight);
 217        }
 218
 1432219        return totalWeight;
 220    }
 221
 222    internal override Fixed64 CalculateCenterOfMassMoment(Fixed64 mass)
 223    {
 1181224        EnsureMassPropertyCenter();
 1181225        return CalculateMomentAboutReference(mass, _massPropertyCenter);
 226    }
 227
 228    /// <inheritdoc/>
 229    public override Fixed64 CalculateMomentOfInertia(Fixed64 mass, Vector2d localReferencePoint)
 230    {
 1218231        if (mass <= Fixed64.Zero)
 2232            return Fixed64.Zero;
 1216233        EnsureMassPropertyCenter();
 1216234        return localReferencePoint == _massPropertyCenter
 1216235            ? CalculateCenterOfMassMoment(mass)
 1216236            : CalculateMomentAboutReference(mass, localReferencePoint);
 237    }
 238
 239    private void EnsureMassPropertyCenter()
 240    {
 2397241        GetCurrentScaleFactors(out Vector2d ownerScale, out _);
 2397242        if (_hasMassPropertyCenter && ownerScale == _massPropertyOwnerScale
 2397243            && LocalOffset == _massPropertyOffset && HasCommittedShape == _massPropertyCommitted)
 2227244            return;
 245
 170246        _hasMassPropertyCenter = false;
 170247        _massPropertyCenter = CalculateLocalCenterOfMassOffset();
 170248        _massPropertyOwnerScale = ownerScale;
 170249        _massPropertyOffset = LocalOffset;
 170250        _massPropertyCommitted = HasCommittedShape;
 170251        _hasMomentGeometry = false;
 170252        _hasMassPropertyCenter = true;
 170253    }
 254
 255    private Fixed64 CalculateMomentAboutReference(Fixed64 mass, Vector2d referencePoint)
 256    {
 1216257        if (!_hasMomentGeometry || referencePoint != _momentReferencePoint)
 197258            CacheMomentGeometry(referencePoint);
 259
 1216260        Signed704 numerator = WideArithmetic.MultiplySigned576ToSigned704(
 1216261            _momentGeometry, Signed320.ExtendValue(Signed192.Raw(mass)));
 1216262        if (!Fixed64.TryGetSignedRawRatio(numerator, _momentDenominator, out Fixed64 moment))
 263        {
 3264            throw new InvalidOperationException(
 3265                "The 2D compound collider's moment of inertia is outside the Fixed64 scalar domain.");
 266        }
 1213267        return moment;
 268    }
 269
 270    private void CacheMomentGeometry(Vector2d referencePoint)
 271    {
 197272        ExactMassWeight totalWeight = ExactMassWeight.Zero;
 1020273        for (int i = 0; i < _partColliders.Length; i++)
 274        {
 313275            ExactMassWeight weight = _partColliders[i].CalculateAreaForMassProperties();
 313276            _massWeightScratch[i] = weight;
 313277            totalWeight = totalWeight.Add(weight);
 278        }
 279
 197280        if (totalWeight.IsZero)
 281        {
 16282            for (int i = 0; i < _partColliders.Length; i++)
 283            {
 5284                _massWeightScratch[i] = ExactMassWeight.One;
 5285                totalWeight = totalWeight.Add(ExactMassWeight.One);
 286            }
 287        }
 288
 197289        ExactMassPoint2D reference = ExactMassPoint2D.FromPoint(referencePoint);
 197290        Signed576 geometry = default;
 1020291        for (int i = 0; i < _partColliders.Length; i++)
 292        {
 313293            LSCollider2D part = _partColliders[i];
 313294            ExactMassWeight weight = _massWeightScratch[i];
 313295            if (weight.IsZero)
 296                continue;
 312297            ExactMassPoint2D point = part.CalculateLocalMassPoint();
 312298            Signed320 dx = WideArithmetic.SubtractSigned320(point.XNumerator, reference.XNumerator);
 312299            Signed320 dy = WideArithmetic.SubtractSigned320(point.YNumerator, reference.YNumerator);
 312300            Signed320 squaredDistance = Signed320.NarrowValue(WideArithmetic.AddSigned576(
 312301                WideArithmetic.MultiplySigned320(dx, dx), WideArithmetic.MultiplySigned320(dy, dy)));
 312302            Signed576 parallelAxis = WideArithmetic.MultiplySigned576(
 312303                WideArithmetic.MultiplySigned320(squaredDistance, weight.Numerator), 60);
 312304            Signed576 intrinsic = WideArithmetic.MultiplySigned576(
 312305                CompoundMomentMath2D.GetWeightedMoment(part, weight, _parts[i].LocalRotation, dx, dy,
 312306                    out Signed576 firstMomentContribution), Signed192.One);
 312307            geometry = WideArithmetic.AddSigned576(geometry, WideArithmetic.AddSigned576(intrinsic, parallelAxis));
 312308            geometry = WideArithmetic.AddSigned576(geometry, firstMomentContribution);
 309        }
 310        // Semantic points retain Q64 coordinates. Their squared offsets and
 311        // weighted intrinsic moments share Q256; only the final parent moment rounds.
 197312        _momentGeometry = geometry;
 197313        _momentDenominator = Signed704.ExtendValue(WideArithmetic.MultiplySigned576(
 197314            WideArithmetic.MultiplySigned576(Signed576.ExtendValue(totalWeight.Numerator),
 197315                Signed192.One, Signed192.One, Signed192.One, Signed192.One), 60));
 197316        _momentReferencePoint = referencePoint;
 197317        _hasMomentGeometry = true;
 197318    }
 319
 320    internal Fixed64 GetMutationGeometryReach(LSCollider2D changed, Vector2d ownerScale,
 321        Fixed64 candidateIntrinsic, Vector2d candidateOffset)
 322    {
 11323        Fixed64 reach = Fixed64.Zero;
 44324        for (int i = 0; i < _parts.Length; i++)
 325        {
 11326            LSCollider2D part = _partColliders[i];
 11327            bool replaced = ReferenceEquals(part, changed);
 11328            Fixed64 intrinsic = replaced ? candidateIntrinsic
 11329                : part.GetCandidateGeometryReach(ownerScale, _parts[i].LocalScale);
 11330            reach = FixedMath.Max(reach, ColliderGeometryPolicy.Add(
 11331                ColliderGeometryPolicy.Attachment(replaced ? candidateOffset : part.LocalOffset, ownerScale),
 11332                intrinsic));
 333        }
 11334        return reach;
 335    }
 336
 337    private protected override void PrepareShape(in ColliderShapeSnapshot2D snapshot)
 338    {
 1437339        Vector2d min = Vector2d.Zero;
 1437340        Vector2d max = Vector2d.Zero;
 341
 1437342        Fixed64 reach = Fixed64.Zero;
 6450343        for (int i = 0; i < _parts.Length; i++)
 344        {
 1794345            CompoundColliderPart2D part = _parts[i];
 1794346            LSCollider2D partCollider = _partColliders[i];
 1794347            partCollider.PrepareCompoundPart(
 1794348                snapshot,
 1794349                part.LocalRotation,
 1794350                part.LocalScale,
 1794351                PreparedContext);
 1788352            reach = FixedMath.Max(reach, ColliderGeometryPolicy.Add(
 1788353                partCollider.PreparedAttachmentReach,
 1788354                partCollider.PreparedGeometryReach));
 355
 1788356            Vector2d partMin = partCollider.PreparedShapeBounds.Min;
 1788357            Vector2d partMax = partCollider.PreparedShapeBounds.Max;
 1788358            if (i == 0)
 359            {
 1432360                min = partMin;
 1432361                max = partMax;
 1432362                continue;
 363            }
 364
 356365            min = new Vector2d(FixedMath.Min(min.X, partMin.X), FixedMath.Min(min.Y, partMin.Y));
 356366            max = new Vector2d(FixedMath.Max(max.X, partMax.X), FixedMath.Max(max.Y, partMax.Y));
 367        }
 368
 1431369        _ = CalculatePreparedLocalMassPoint();
 1430370        _ = CalculatePreparedAreaForMassProperties();
 1430371        SetPreparedGeometryReach(reach);
 1430372        SetPreparedBounds(FixedBoundArea.FromMinMax(min, max));
 1430373    }
 374
 375    private protected override void PublishShape()
 376    {
 6406377        for (int i = 0; i < _parts.Length; i++)
 378        {
 1778379            CompoundColliderPart2D part = _parts[i];
 1778380            _partColliders[i].PublishCompoundPart(
 1778381                part.LocalRotation,
 1778382                part.LocalScale,
 1778383                PreparedContext);
 384        }
 1425385    }
 386
 387    private static LSCollider2D MaterializePartCollider(CompoundColliderPart2D part)
 388    {
 476389        LSCollider2D collider = part.Shape.CreateRuntimeCollider();
 476390        collider.LocalOffset = part.LocalOffset;
 476391        collider.Material = part.ResolveMaterial(PhysicsMaterial.Default);
 476392        return collider;
 393    }
 394
 395    /// <inheritdoc/>
 396    protected override void OnMaterialChanged()
 397    {
 114398        for (int i = 0; i < _parts.Length; i++)
 35399            _partColliders[i].Material = _parts[i].ResolveMaterial(Material);
 22400    }
 401
 402    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 403    private static void ValidatePart(CompoundColliderPart2D part) =>
 477404        ChronicleGuard.ThrowIfArgument(part.IsDefault, nameof(part), "2D compound collider part cannot be default.");
 405}