< Summary

Information
Class: Gravitas.Colliders.LSPolygonCollider2D
Assembly: Gravitas
File(s): /home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/2D/Shapes/LSPolygonCollider2D.cs
Line coverage
100%
Covered lines: 158
Uncovered lines: 0
Coverable lines: 158
Total lines: 329
Line coverage: 100%
Branch coverage
100%
Covered branches: 52
Total branches: 52
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/2D/Shapes/LSPolygonCollider2D.cs

#LineLine coverage
 1//=======================================================================
 2// LSPolygonCollider2D.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;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12
 13namespace Gravitas.Colliders;
 14
 15/// <summary>
 16/// Pure 2D convex polygon collider with deterministic vertex ordering.
 17/// </summary>
 18public sealed class LSPolygonCollider2D : LSCollider2D, IConvexVertexSource2D
 19{
 20    private Vector2d[] _localVertices;
 21    private Vector2d[] _scaledLocalVertices;
 22    private Vector2d[] _scaledLocalVerticesScratch;
 23    private PolygonMassProperties2D _massProperties;
 24    private PolygonMassProperties2D _preparedMassProperties;
 25
 26    /// <summary>Creates a pure 2D convex polygon from authored local vertices.</summary>
 111827    public LSPolygonCollider2D(params Vector2d[] vertices)
 28    {
 111829        _localVertices = Array.Empty<Vector2d>();
 111830        _scaledLocalVertices = Array.Empty<Vector2d>();
 111831        _scaledLocalVerticesScratch = Array.Empty<Vector2d>();
 111832        SetLocalVertices(vertices, markDirty: true);
 111433    }
 34
 35    /// <summary>Creates a runtime convex polygon from an authored shape definition.</summary>
 11236    public LSPolygonCollider2D(ColliderShapeDefinition2D definition)
 37    {
 11238        definition.EnsureKind(ColliderShapeDefinition2DKind.ConvexPolygon);
 11239        Material = definition.Material;
 11240        _localVertices = Array.Empty<Vector2d>();
 11241        _scaledLocalVertices = Array.Empty<Vector2d>();
 11242        _scaledLocalVerticesScratch = Array.Empty<Vector2d>();
 11243        SetLocalVertices(definition.GetPolygonVerticesForRuntime(), markDirty: true);
 11244    }
 45
 46    /// <inheritdoc/>
 14237547    public override ColliderType2D Shape => ColliderType2D.ConvexPolygon;
 48
 49    /// <summary>Gets the polygon vertex count.</summary>
 26850    public int Count => _scaledLocalVertices.Length;
 51
 52    /// <summary>
 53    /// Gets the committed vertices in the collider's scaled local frame.
 54    /// </summary>
 1974155    internal ReadOnlySpan<Vector2d> ScaledLocalVertices => _scaledLocalVertices;
 56
 10534157    int IConvexVertexSource2D.VertexCount => _scaledLocalVertices.Length;
 58
 10092359    Fixed64 IConvexVertexSource2D.Rotation => Rotation;
 60
 61    /// <summary>
 62    /// Gets a world-space vertex when the conceptual point is representable.
 63    /// </summary>
 64    /// <exception cref="InvalidOperationException">
 65    /// Thrown when the conceptual vertex lies outside the fixed-point scalar
 66    /// domain. Use <see cref="TryGetWorldVertex(int, out Vector2d)"/> when
 67    /// querying geometry near a scalar boundary.
 68    /// </exception>
 69    public Vector2d GetWorldVertex(int index)
 70    {
 23871        if (TryGetWorldVertex(index, out Vector2d vertex))
 23672            return vertex;
 73
 274        throw new InvalidOperationException(
 275            "The polygon vertex is outside the representable coordinate range. Use TryGetWorldVertex.");
 76    }
 77
 78    /// <summary>
 79    /// Attempts to materialize a committed polygon vertex in world space
 80    /// without saturation.
 81    /// </summary>
 82    public bool TryGetWorldVertex(int index, out Vector2d vertex)
 83    {
 24484        ChronicleGuard.ThrowIfArrayIndexInvalid(
 24485            index,
 24486            _scaledLocalVertices.Length,
 24487            nameof(index));
 24488        return TryGetVertex(index, out vertex);
 89    }
 90
 91    /// <inheritdoc/>
 92    public override bool ContainsPoint(Vector2d point) =>
 184693        FixedConvex2dRelations.ContainsPoint(
 184694            point,
 184695            Center,
 184696            Rotation,
 184697            _scaledLocalVertices);
 98
 99    /// <inheritdoc/>
 100    public override Vector2d GetClosestPoint(Vector2d point)
 101    {
 4102        if (ContainsPoint(point))
 2103            return point;
 104
 2105        FixedPointAnchor2d anchor =
 2106            FixedConvex2dRelations.GetClosestPointAnchor(
 2107                point,
 2108                Center,
 2109                Rotation,
 2110                _scaledLocalVertices);
 2111        if (anchor.TryGetPoint(out Vector2d closest))
 112        {
 1113            return closest;
 114        }
 115
 1116        throw new InvalidOperationException(
 1117            "The closest polygon point is outside the Fixed64 coordinate domain.");
 118    }
 119
 120    /// <inheritdoc/>
 121    public override Vector2d GetSupportPoint(Vector2d direction)
 122    {
 6123        FixedPointAnchor2d anchor = FixedConvex2dRelations.GetSupportAnchor(
 6124            Center,
 6125            Rotation,
 6126            _scaledLocalVertices,
 6127            direction);
 6128        if (anchor.TryGetPoint(out Vector2d support))
 129        {
 4130            return support;
 131        }
 132
 2133        throw new InvalidOperationException(
 2134            "The polygon support point is outside the Fixed64 coordinate domain.");
 135    }
 136
 137    Vector2d IConvexVertexSource2D.GetScaledLocalVertexUnchecked(int index) =>
 84104138        _scaledLocalVertices[index];
 139
 140    FixedPointAnchor2d IConvexVertexSource2D.GetSupportAnchor(Vector2d direction) =>
 2141        FixedConvex2dRelations.GetSupportAnchor(
 2142            Center,
 2143            Rotation,
 2144            _scaledLocalVertices,
 2145            direction);
 146
 147    internal override ExactMassPoint2D CalculateLocalMassPoint()
 148    {
 13370149        return TransformRelativeMassPropertyPointExact(GetMassProperties().Centroid);
 150    }
 151
 152    internal override ExactMassPoint2D CalculatePreparedLocalMassPoint()
 153    {
 982154        return TransformPreparedPartMassPropertyPointExact(
 982155            _preparedMassProperties.Centroid);
 156    }
 157
 158    internal override ExactMassWeight CalculateAreaForMassProperties()
 159    {
 148160        return GetMassProperties().Weight;
 161    }
 162
 163    internal override ExactMassWeight CalculatePreparedAreaForMassProperties()
 164    {
 1964165        return _preparedMassProperties.Weight;
 166    }
 167
 168    internal override Fixed64 CalculateCenterOfMassMoment(Fixed64 mass)
 169    {
 1170        return GetMassProperties().CalculateMoment(mass);
 171    }
 172
 173    /// <inheritdoc/>
 174    public override Fixed64 CalculateMomentOfInertia(Fixed64 mass, Vector2d localReferencePoint)
 175    {
 13327176        if (mass <= Fixed64.Zero)
 1177            return Fixed64.Zero;
 178
 13326179        PolygonMassProperties2D properties = GetMassProperties();
 180        // Detached scaling may collapse area before shape admission. Retain the
 181        // base point-mass limit rather than dividing by a zero polygon weight.
 13326182        if (properties.Weight.IsZero)
 1183            return base.CalculateMomentOfInertia(mass, localReferencePoint);
 184
 13325185        ExactMassPoint2D point = TransformRelativeMassPropertyPointExact(properties.Centroid);
 13325186        ExactMassPoint2D reference = ExactMassPoint2D.FromPoint(localReferencePoint);
 13325187        Signed320 dx = WideArithmetic.SubtractSigned320(point.XNumerator, reference.XNumerator);
 13325188        Signed320 dy = WideArithmetic.SubtractSigned320(point.YNumerator, reference.YNumerator);
 13325189        if (dx.IsZero && dy.IsZero)
 13143190            return properties.CalculateMoment(mass);
 191
 182192        if (properties.TryCalculateMoment(mass, CompoundLocalRotation, dx, dy, out Fixed64 moment))
 178193            return moment;
 194
 4195        if (!point.TryGetPoint(out _))
 1196            throw new InvalidOperationException("The requested moment of inertia is outside the Fixed64 scalar domain.")
 3197        return Fixed64.MaxValue;
 198    }
 199
 200    internal Fixed64 GetCurrentGeometryReach()
 201    {
 9202        GetCurrentScaleFactors(out Vector2d ownerScale, out Vector2d partScale);
 9203        return GetCandidateGeometryReach(ownerScale, partScale);
 204    }
 205
 206    internal Fixed64 GetCandidateGeometryReach(Vector2d ownerScale, Vector2d partScale)
 207    {
 14208        Fixed64 reach = Fixed64.Zero;
 110209        for (int i = 0; i < _localVertices.Length; i++)
 210        {
 44211            Vector2d vertex = _localVertices[i];
 212            // Detached metadata can precede a compensating host scale; do not
 213            // publish or reject runtime geometry while measuring its enclosure.
 44214            if (!Fixed64.TryMultiplyDivide(vertex.X, ownerScale.X, partScale.X,
 44215                    Fixed64.One, out Fixed64 x)
 44216                || !Fixed64.TryMultiplyDivide(vertex.Y, ownerScale.Y, partScale.Y,
 44217                    Fixed64.One, out Fixed64 y)
 44218                || !new Vector2d(x, y).TryGetMagnitudeCeiling(out Fixed64 vertexReach))
 3219                return Fixed64.MaxValue;
 41220            reach = FixedMath.Max(reach, vertexReach);
 221        }
 11222        return reach;
 223    }
 224
 225    private protected override void PrepareShape(in ColliderShapeSnapshot2D snapshot)
 226    {
 15629227        Fixed64 reach = Fixed64.Zero;
 15629228        bool verticesChanged = !HasCommittedShape
 15629229            || _scaledLocalVertices.Length != _localVertices.Length;
 157118230        for (int i = 0; i < _localVertices.Length; i++)
 231        {
 62930232            Vector2d scaledVertex = ColliderScalePolicy.Scale(
 62930233                _localVertices[i],
 62930234                snapshot.OwnerScale,
 62930235                snapshot.PartScale);
 62930236            verticesChanged = verticesChanged || scaledVertex != _scaledLocalVertices[i];
 62930237            _scaledLocalVerticesScratch[i] = scaledVertex;
 62930238            reach = FixedMath.Max(reach, ColliderGeometryPolicy.Magnitude(scaledVertex));
 239        }
 240
 241        // Positive scaling can collapse a small edge through rounding. Validate
 242        // before publication, but reuse admission when only the pose changes.
 15629243        if (verticesChanged)
 244        {
 1199245            ValidateConvexPolygon(_scaledLocalVerticesScratch);
 1195246            _preparedMassProperties = PolygonMassProperties2D.Create(_scaledLocalVerticesScratch);
 247        }
 248        else
 249        {
 250            // Intrinsic integrals depend on effective geometry, not world pose.
 14430251            _preparedMassProperties = _massProperties;
 252        }
 253
 15625254        SetPreparedGeometryReach(reach);
 15625255        SetPreparedBounds(FixedBoundArea.FromRotatedOffsetsClippedToDomain(
 15625256            snapshot.Center,
 15625257            snapshot.Rotation,
 15625258            _scaledLocalVerticesScratch));
 15625259    }
 260
 261    private protected override void PublishShape()
 262    {
 15389263        Vector2d[] offsets = _scaledLocalVertices;
 15389264        if (offsets.Length != _scaledLocalVerticesScratch.Length)
 3265            offsets = new Vector2d[_scaledLocalVerticesScratch.Length];
 15389266        _scaledLocalVertices = _scaledLocalVerticesScratch;
 15389267        _scaledLocalVerticesScratch = offsets;
 15389268        _massProperties = _preparedMassProperties;
 15389269    }
 270
 271    /// <inheritdoc/>
 272    protected override void RecordShapeData(IChronicler chronicler)
 273    {
 8274        Vector2d[] vertices = _localVertices;
 8275        RecordValues.Look(chronicler, ref vertices, "Vertices", Array.Empty<Vector2d>());
 8276        if (chronicler.Mode == SerializationMode.Loading && vertices.Length > 0)
 5277            SetLocalVertices(vertices, markDirty: false);
 8278    }
 279
 280    private void SetLocalVertices(Vector2d[] vertices, bool markDirty)
 281    {
 1235282        ChronicleGuard.ThrowIfNull(vertices, nameof(vertices));
 1235283        ChronicleGuard.ThrowIfArgument(vertices.Length < 3, nameof(vertices), "2D polygon must contain at least three ve
 1234284        ValidateConvexPolygon(vertices);
 285
 1231286        if (_localVertices.Length != vertices.Length)
 287        {
 1229288            _localVertices = new Vector2d[vertices.Length];
 289            // A load may change vertex count. Retain committed query geometry
 290            // until the replacement has passed scaled admission and publishes.
 1229291            if (!HasCommittedShape)
 1226292                _scaledLocalVertices = new Vector2d[vertices.Length];
 1229293            _scaledLocalVerticesScratch = new Vector2d[vertices.Length];
 294        }
 295
 1231296        Array.Copy(vertices, _localVertices, vertices.Length);
 1231297        if (markDirty)
 1226298            MarkShapeDirty();
 1231299    }
 300
 301    internal static void ValidateConvexPolygon(Vector2d[] vertices)
 302    {
 2556303        ChronicleGuard.ThrowIfArgument(vertices.Length < 3, nameof(vertices), "2D polygon must contain at least three ve
 2556304        ChronicleGuard.ThrowIfArgument(
 2556305            !FixedConvex2dRelations.IsStrictlyConvex(vertices),
 2556306            nameof(vertices),
 2556307            "2D polygon vertices must form a strictly convex boundary.");
 2548308    }
 309
 26910310    internal PolygonMassProperties2D GetMassProperties() => HasCommittedShape
 26910311        ? _massProperties
 26910312        : PolygonMassProperties2D.Create(GetMassPropertyVertices());
 313
 314    private ReadOnlySpan<Vector2d> GetMassPropertyVertices()
 315    {
 259316        GetCurrentScaleFactors(
 259317            out Vector2d ownerScale,
 259318            out Vector2d partScale);
 2180319        for (int i = 0; i < _localVertices.Length; i++)
 320        {
 831321            _scaledLocalVerticesScratch[i] = ColliderScalePolicy.Scale(
 831322                _localVertices[i],
 831323                ownerScale,
 831324                partScale);
 325        }
 326
 259327        return _scaledLocalVerticesScratch;
 328    }
 329}