< Summary

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

#LineLine coverage
 1//=======================================================================
 2// LSCapsuleCollider2D.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 Chronicler;
 11using FixedMathSharp;
 12using FixedMathSharp.Geometry;
 13
 14namespace Gravitas.Colliders;
 15
 16/// <summary>
 17/// Pure 2D capsule collider whose local center segment follows local 2D Y.
 18/// </summary>
 19public sealed class LSCapsuleCollider2D : LSCollider2D
 20{
 21    // Retain the fixed coefficient's rounding before bringing the cap moment
 22    // to the rectangle's common divisor of twelve.
 123    private static readonly Fixed64 CapCrossFactor =
 124        ((Fixed64)4 / ((Fixed64)3 * Fixed64.Pi)) * (Fixed64)12;
 25
 26    private Fixed64 _radius;
 27    private Fixed64 _height;
 28    private Fixed64 _scaledRadius;
 29    private Fixed64 _axisLength;
 30    private Fixed64 _preparedRadius;
 31    private Fixed64 _preparedAxisLength;
 32    private Vector2d _preparedAxis;
 33
 34    /// <summary>Creates a pure 2D capsule with authored dimensions.</summary>
 98235    public LSCapsuleCollider2D(Fixed64 radius, Fixed64 height)
 36    {
 98237        ValidateDimensions(radius, height);
 98138        _radius = radius;
 98139        _height = height;
 98140        MarkShapeDirty();
 98141    }
 42
 43    /// <summary>Creates a runtime capsule from an authored shape definition.</summary>
 9444    public LSCapsuleCollider2D(ColliderShapeDefinition2D definition)
 45    {
 9446        definition.EnsureKind(ColliderShapeDefinition2DKind.Capsule);
 9447        Material = definition.Material;
 9448        Fixed64 radius = definition.Radius;
 9449        Fixed64 height = definition.Size.Y;
 9450        ValidateDimensions(radius, height);
 9451        _radius = radius;
 9452        _height = height;
 9453        MarkShapeDirty();
 9454    }
 55
 56    /// <inheritdoc/>
 4494057    public override ColliderType2D Shape => ColliderType2D.Capsule;
 58
 59    /// <summary>
 60    /// Gets or sets the unscaled semicircle radius.
 61    /// </summary>
 62    public Fixed64 Radius
 63    {
 64        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 16765        get => _radius;
 66        set
 67        {
 768            ValidateDimensions(value, _height);
 569            if (_radius == value)
 370                return;
 71
 272            ValidateGeometryMutation(radius: value);
 273            _radius = value;
 274            MarkShapeDirty();
 275        }
 76    }
 77
 78    /// <summary>
 79    /// Gets or sets the unscaled full end-to-end capsule height.
 80    /// </summary>
 81    public Fixed64 Height
 82    {
 83        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 10984        get => _height;
 85        set
 86        {
 887            ValidateDimensions(_radius, value);
 788            if (_height == value)
 389                return;
 90
 491            ValidateGeometryMutation(height: value);
 392            _height = value;
 393            MarkShapeDirty();
 394        }
 95    }
 96
 97    /// <summary>
 98    /// Gets the radius after compound/local scaling.
 99    /// </summary>
 100    public Fixed64 ScaledRadius
 101    {
 102        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 103        get
 104        {
 20341105            GetMassPropertyGeometry(
 20341106                out Fixed64 radius,
 20341107                out _);
 20341108            return radius;
 109        }
 110    }
 111
 112    /// <summary>
 113    /// Gets the derived normalized world-space direction of the capsule's
 114    /// conceptual center axis. Exact geometry remains authoritative in the
 115    /// collider's planar rigid frame.
 116    /// </summary>
 117    public Vector2d WorldAxis { get; private set; } = Vector2d.Forward;
 118
 119    /// <summary>
 120    /// Gets the full length of the conceptual center axis.
 121    /// </summary>
 122    public Fixed64 AxisLength
 123    {
 124        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 125        get
 126        {
 39802127            if (HasCommittedShape)
 39800128                return _axisLength;
 129
 2130            GetMassPropertyGeometry(
 2131                out _,
 2132                out Fixed64 axisLength);
 2133            return axisLength;
 134        }
 135    }
 136
 137    /// <inheritdoc/>
 138    public override bool ContainsPoint(Vector2d point)
 847139        => FixedSegment2d.ContainsPointInCenteredCapsule(
 847140            point,
 847141            Center,
 847142            Rotation,
 847143            AxisLength,
 847144            ScaledRadius,
 847145            Fixed64.Zero,
 847146            strict: false);
 147
 148    /// <inheritdoc/>
 149    public override Vector2d GetClosestPoint(Vector2d point)
 150    {
 4151        Vector2d direction = FixedSegment2d.GetDirectionFromCenteredAxis(
 4152            point,
 4153            Center,
 4154            Rotation,
 4155            AxisLength);
 4156        if (direction == Vector2d.Zero)
 3157            direction = Rotate(Vector2d.Right, Rotation).Normalized;
 4158        if (FixedSegment2d.TryGetSurfacePointOnCenteredCapsule(
 4159                point,
 4160                Center,
 4161                Rotation,
 4162                AxisLength,
 4163                ScaledRadius,
 4164                direction,
 4165                out Vector2d surfacePoint))
 2166            return surfacePoint;
 167
 2168        throw new InvalidOperationException("The closest capsule surface point is outside the Fixed64 coordinate domain.
 169    }
 170
 171    internal Vector2d GetNormalFromCenteredAxis(Vector2d point)
 172    {
 1130173        Vector2d direction = FixedSegment2d.GetDirectionFromCenteredAxis(
 1130174            point,
 1130175            Center,
 1130176            Rotation,
 1130177            AxisLength);
 1130178        return direction != Vector2d.Zero
 1130179            ? direction
 1130180            : Rotate(Vector2d.Right, Rotation).Normalized;
 181    }
 182
 183    internal bool TryGetSurfacePointFromCenteredAxis(
 184        Vector2d point,
 185        Vector2d normal,
 186        out Vector2d surfacePoint) =>
 2187        TryGetSurfacePoint(point, normal, out surfacePoint);
 188
 189    /// <inheritdoc/>
 190    public override Vector2d GetSupportPoint(Vector2d direction)
 191    {
 263192        if (TryGetSupportPoint(direction, out Vector2d support))
 262193            return support;
 194
 1195        throw new InvalidOperationException("The capsule support point is outside the Fixed64 coordinate domain.");
 196    }
 197
 198    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 199    internal bool TryGetSupportPoint(Vector2d direction, out Vector2d support)
 200    {
 263201        Vector2d supportDirection = direction == Vector2d.Zero
 263202            ? Rotate(Vector2d.Right, Rotation)
 263203            : direction;
 263204        return FixedSegment2d.TryGetCenteredCapsuleSupport(
 263205            Center,
 263206            Rotation,
 263207            AxisLength,
 263208            ScaledRadius,
 263209            supportDirection,
 263210            out support);
 211    }
 212
 213    private bool TryGetSurfacePoint(
 214        Vector2d point,
 215        Vector2d worldNormal,
 216        out Vector2d surfacePoint) =>
 2217        FixedSegment2d.TryGetSurfacePointOnCenteredCapsule(
 2218            point,
 2219            Center,
 2220            Rotation,
 2221            AxisLength,
 2222            ScaledRadius,
 2223            worldNormal,
 2224            out surfacePoint);
 225
 226    internal override ExactMassWeight CalculateAreaForMassProperties()
 227    {
 65228        GetMassPropertyGeometry(
 65229            out Fixed64 radius,
 65230            out Fixed64 cylinderLength);
 65231        return GetRectangleWeight(radius, cylinderLength)
 65232            .Add(GetCircleWeight(radius));
 233    }
 234
 235    internal override ExactMassWeight CalculatePreparedAreaForMassProperties() =>
 364236        GetRectangleWeight(_preparedRadius, _preparedAxisLength)
 364237            .Add(GetCircleWeight(_preparedRadius));
 238
 239    internal override Fixed64 CalculateCenterOfMassMoment(Fixed64 mass)
 240    {
 4577241        GetMassPropertyGeometry(
 4577242            out Fixed64 radius,
 4577243            out Fixed64 cylinderLength);
 4577244        return CalculateCenteredMoment(mass, radius, cylinderLength);
 245    }
 246
 247    private protected override void PrepareShape(in ColliderShapeSnapshot2D snapshot)
 248    {
 5657249        GetScaledGeometry(_radius, _height, snapshot.OwnerScale, snapshot.PartScale,
 5657250            out _preparedRadius, out _preparedAxisLength);
 5655251        SetPreparedGeometryReach(ColliderGeometryPolicy.Capsule(_preparedRadius, _preparedAxisLength));
 5655252        _preparedAxis = Rotate(Vector2d.Forward, snapshot.Rotation).Normalized;
 5655253        SetPreparedBounds(FixedBoundArea.FromCenteredRotatedCapsuleClippedToDomain(
 5655254            snapshot.Center,
 5655255            snapshot.Rotation,
 5655256            _preparedAxisLength,
 5655257            _preparedRadius));
 5655258    }
 259
 260    internal static void GetScaledGeometry(Fixed64 authoredRadius, Fixed64 authoredHeight,
 261        Vector2d ownerScale, Vector2d partScale, out Fixed64 radius, out Fixed64 axisLength)
 262    {
 5668263        Fixed64 radiusX = ColliderScalePolicy.ScalePositive(
 5668264            authoredRadius,
 5668265            ownerScale.X,
 5668266            partScale.X);
 5668267        Fixed64 radiusY = ColliderScalePolicy.ScalePositive(
 5668268            authoredRadius,
 5668269            ownerScale.Y,
 5668270            partScale.Y);
 5668271        radius = FixedMath.Max(radiusX, radiusY);
 5668272        ChronicleGuard.ThrowIfArgument(
 5668273            !HasValidScaledDimensions(
 5668274                authoredRadius,
 5668275                authoredHeight,
 5668276                ownerScale,
 5668277                partScale),
 5668278            nameof(authoredHeight),
 5668279            "Scaled 2D capsule height must be at least the capsule diameter.");
 5666280        ChronicleGuard.ThrowIfArgument(
 5666281            !Fixed64.TryMultiplySubtractClamped(
 5666282                authoredHeight,
 5666283                ownerScale.Y,
 5666284                partScale.Y,
 5666285                Fixed64.One,
 5666286                authoredRadius,
 5666287                Fixed64.Two,
 5666288                ownerScale.X,
 5666289                partScale.X,
 5666290                out Fixed64 axisLengthX)
 5666291            | !Fixed64.TryMultiplySubtractClamped(
 5666292                authoredHeight,
 5666293                ownerScale.Y,
 5666294                partScale.Y,
 5666295                Fixed64.One,
 5666296                authoredRadius,
 5666297                Fixed64.Two,
 5666298                ownerScale.Y,
 5666299                partScale.Y,
 5666300                out Fixed64 axisLengthY),
 5666301            nameof(authoredHeight),
 5666302            "Scaled 2D capsule center-axis length must be representable.");
 5666303        axisLength = FixedMath.Min(axisLengthX, axisLengthY);
 5666304    }
 305
 306    private protected override void PublishShape()
 307    {
 5655308        _scaledRadius = _preparedRadius;
 5655309        _axisLength = _preparedAxisLength;
 5655310        WorldAxis = _preparedAxis;
 5655311    }
 312
 313    internal void CopyPreparedReconfiguration(LSCapsuleCollider2D candidate)
 314    {
 22315        _radius = candidate._radius;
 22316        _height = candidate._height;
 22317        _preparedRadius = candidate._preparedRadius;
 22318        _preparedAxisLength = candidate._preparedAxisLength;
 22319        _preparedAxis = candidate._preparedAxis;
 22320    }
 321
 322    /// <inheritdoc/>
 323    protected override void RecordShapeData(IChronicler chronicler)
 324    {
 4325        Fixed64 radius = _radius;
 4326        Fixed64 height = _height;
 4327        RecordValues.Look(chronicler, ref radius, "Radius", Fixed64.Half);
 4328        RecordValues.Look(chronicler, ref height, "Height", Fixed64.One);
 4329        if (chronicler.Mode == SerializationMode.Loading)
 330        {
 2331            ValidateDimensions(radius, height);
 2332            _radius = radius;
 2333            _height = height;
 334        }
 4335    }
 336
 337    internal void GetMassPropertyGeometry(
 338        out Fixed64 radius,
 339        out Fixed64 axisLength)
 340    {
 25006341        if (HasCommittedShape)
 342        {
 23912343            radius = _scaledRadius;
 23912344            axisLength = _axisLength;
 23912345            return;
 346        }
 347
 1094348        GetCurrentScaleFactors(
 1094349            out Vector2d ownerScale,
 1094350            out Vector2d partScale);
 1094351        Fixed64 radiusX = ColliderScalePolicy.Scale(
 1094352            _radius,
 1094353            ownerScale.X,
 1094354            partScale.X);
 1094355        Fixed64 radiusY = ColliderScalePolicy.Scale(
 1094356            _radius,
 1094357            ownerScale.Y,
 1094358            partScale.Y);
 1094359        radius = FixedMath.Max(radiusX, radiusY);
 1094360        ChronicleGuard.ThrowIfTrue(
 1094361            !HasValidScaledDimensions(
 1094362                _radius,
 1094363                _height,
 1094364                ownerScale,
 1094365                partScale),
 1094366            nameof(CalculateAreaForMassProperties),
 1094367            "Scaled 2D capsule height must be at least the capsule diameter.");
 1094368        bool representable = Fixed64.TryMultiplySubtractClamped(
 1094369                _height,
 1094370                ownerScale.Y,
 1094371                partScale.Y,
 1094372                Fixed64.One,
 1094373                _radius,
 1094374                Fixed64.Two,
 1094375                ownerScale.X,
 1094376                partScale.X,
 1094377                out Fixed64 axisLengthX)
 1094378            & Fixed64.TryMultiplySubtractClamped(
 1094379                _height,
 1094380                ownerScale.Y,
 1094381                partScale.Y,
 1094382                Fixed64.One,
 1094383                _radius,
 1094384                Fixed64.Two,
 1094385                ownerScale.Y,
 1094386                partScale.Y,
 1094387                out Fixed64 axisLengthY);
 1094388        ChronicleGuard.ThrowIfTrue(
 1094389            !representable,
 1094390            nameof(CalculateAreaForMassProperties),
 1094391            "Scaled 2D capsule center-axis length must be representable.");
 1094392        axisLength = FixedMath.Min(axisLengthX, axisLengthY);
 1094393    }
 394
 395    private static Fixed64 CalculateCenteredMoment(Fixed64 mass, Fixed64 radius, Fixed64 cylinderLength)
 396    {
 4577397        if (cylinderLength <= Fixed64.Epsilon)
 1335398            return ExactMassProperties.InertiaMoment(mass,
 1335399                ExactMassProperties.InertiaGeometryTerm(Fixed64.Half, radius, radius));
 400
 3242401        if (radius == Fixed64.Zero)
 2402            return Fixed64.TryMultiplyDivide(mass, cylinderLength, cylinderLength, (Fixed64)12, out Fixed64 rodMoment)
 2403                ? rodMoment : Fixed64.MaxValue;
 404
 405        // Cancelling the common radius leaves exact linear area weights.
 3240406        Signed192 rectangleWeight = Fixed64.GetExactRawProduct(Fixed64.Two, cylinderLength);
 3240407        Signed192 capWeight = Fixed64.GetExactRawProduct(Fixed64.Pi, radius);
 3240408        GetCenteredMomentGeometry(radius, cylinderLength,
 3240409            out Signed192 rectangleGeometry, out Signed192 capGeometry);
 3240410        return ExactMassProperties.InertiaWeightedMoment(
 3240411            mass, rectangleGeometry, rectangleWeight, capGeometry, capWeight, divisor: 12);
 412    }
 413
 414    /// <summary>Gets exact Q96 rectangle and paired-cap geometry with common divisor twelve.</summary>
 415    internal static void GetCenteredMomentGeometry(Fixed64 radius, Fixed64 cylinderLength,
 416        out Signed192 rectangleGeometry, out Signed192 capGeometry)
 417    {
 3253418        rectangleGeometry = WideArithmetic.AddSigned192(
 3253419            ExactMassProperties.InertiaGeometryTerm((Fixed64)4, radius, radius),
 3253420            ExactMassProperties.InertiaGeometryTerm(Fixed64.One, cylinderLength, cylinderLength));
 421
 422        // Combining both caps cancels their centroid-square terms and retains
 423        // odd raw mass: Ic = mc*(r^2/2 + L^2/4 + 4Lr/(3*pi)).
 3253424        capGeometry = WideArithmetic.AddSigned192(
 3253425            ExactMassProperties.InertiaGeometryTerm((Fixed64)6, radius, radius),
 3253426            WideArithmetic.AddSigned192(
 3253427                ExactMassProperties.InertiaGeometryTerm((Fixed64)3, cylinderLength, cylinderLength),
 3253428                ExactMassProperties.InertiaGeometryTerm(CapCrossFactor, cylinderLength, radius)));
 3253429    }
 430
 431    private static ExactMassWeight GetRectangleWeight(
 432        Fixed64 radius,
 433        Fixed64 cylinderLength) =>
 429434        ExactMassWeight.FromProduct(
 429435            Fixed64.Two,
 429436            radius,
 429437            cylinderLength);
 438
 439    private static ExactMassWeight GetCircleWeight(Fixed64 radius) =>
 429440        ExactMassWeight.FromProduct(
 429441            Fixed64.Pi,
 429442            radius,
 429443            radius);
 444
 445    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 446    private static void ValidateDimensions(Fixed64 radius, Fixed64 height)
 447    {
 1093448        ChronicleGuard.ThrowIfArgument(radius <= Fixed64.Zero, nameof(radius), "2D capsule radius must be greater than z
 1092449        ChronicleGuard.ThrowIfArgument(
 1092450            Fixed64.CompareProducts(
 1092451                height,
 1092452                Fixed64.One,
 1092453                radius,
 1092454                Fixed64.Two) < 0,
 1092455            nameof(height),
 1092456            "2D capsule height must be at least the capsule diameter.");
 1089457    }
 458
 459    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 460    private static bool HasValidScaledDimensions(
 461        Fixed64 radius,
 462        Fixed64 height,
 463        Vector2d ownerScale,
 464        Vector2d partScale) =>
 6762465        Fixed64.CompareProducts(
 6762466            height,
 6762467            ownerScale.Y,
 6762468            partScale.Y,
 6762469            Fixed64.One,
 6762470            radius,
 6762471            Fixed64.Two,
 6762472            ownerScale.X,
 6762473            partScale.X) >= 0
 6762474        & Fixed64.CompareProducts(
 6762475            height,
 6762476            ownerScale.Y,
 6762477            partScale.Y,
 6762478            Fixed64.One,
 6762479            radius,
 6762480            Fixed64.Two,
 6762481            ownerScale.Y,
 6762482            partScale.Y) >= 0;
 483}

Methods/Properties

.cctor()
.ctor(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
.ctor(Gravitas.Colliders.ColliderShapeDefinition2D)
get_Shape()
get_Radius()
set_Radius(FixedMathSharp.Fixed64)
get_Height()
set_Height(FixedMathSharp.Fixed64)
get_ScaledRadius()
get_AxisLength()
ContainsPoint(FixedMathSharp.Vector2d)
GetClosestPoint(FixedMathSharp.Vector2d)
GetNormalFromCenteredAxis(FixedMathSharp.Vector2d)
TryGetSurfacePointFromCenteredAxis(FixedMathSharp.Vector2d,FixedMathSharp.Vector2d,FixedMathSharp.Vector2d&)
GetSupportPoint(FixedMathSharp.Vector2d)
TryGetSupportPoint(FixedMathSharp.Vector2d,FixedMathSharp.Vector2d&)
TryGetSurfacePoint(FixedMathSharp.Vector2d,FixedMathSharp.Vector2d,FixedMathSharp.Vector2d&)
CalculateAreaForMassProperties()
CalculatePreparedAreaForMassProperties()
CalculateCenterOfMassMoment(FixedMathSharp.Fixed64)
PrepareShape(System.Runtime.InteropServices.InAttribute))
GetScaledGeometry(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Vector2d,FixedMathSharp.Vector2d,FixedMathSharp.Fixed64&,FixedMathSharp.Fixed64&)
PublishShape()
CopyPreparedReconfiguration(Gravitas.Colliders.LSCapsuleCollider2D)
RecordShapeData(Chronicler.IChronicler)
GetMassPropertyGeometry(FixedMathSharp.Fixed64&,FixedMathSharp.Fixed64&)
CalculateCenteredMoment(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
GetCenteredMomentGeometry(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Signed192&,FixedMathSharp.Signed192&)
GetRectangleWeight(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
GetCircleWeight(FixedMathSharp.Fixed64)
ValidateDimensions(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
HasValidScaledDimensions(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Vector2d,FixedMathSharp.Vector2d)