< Summary

Line coverage
100%
Covered lines: 470
Uncovered lines: 0
Coverable lines: 470
Total lines: 821
Line coverage: 100%
Branch coverage
100%
Covered branches: 358
Total branches: 358
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: .ctor()100%11100%
File 1: get_SelectionWords()100%11100%
File 1: SelectBanks(...)100%11100%
File 1: Build(...)100%11100%
File 1: Build(...)100%2222100%
File 1: Reserve(...)100%44100%
File 1: Gather(...)100%3232100%
File 1: VisitSource(...)100%44100%
File 1: FindRegion(...)100%1414100%
File 1: AdmitPoint(...)100%2424100%
File 1: TryGetSamplingPoint(...)100%22100%
File 1: BorrowWinner(...)100%11100%
File 1: ReduceSamples(...)100%1212100%
File 1: GetSeed(...)100%1212100%
File 1: RetainPoint(...)100%44100%
File 1: BorrowPoint(...)100%11100%
File 1: .ctor(...)100%11100%
File 1: CompareToPoint(...)100%11100%
File 1: ComparePoints(...)100%22100%
File 1: GetNormal(...)100%11100%
File 1: GetOrientation(...)100%11100%
File 1: GetSampleCount(...)100%11100%
File 1: TryGetSample(...)100%66100%
File 1: TryCreateContact(...)100%11100%
File 1: ValidateRegion(...)100%22100%
File 1: .ctor(...)100%11100%
File 2: ReleaseJoined()100%11100%
File 2: BuildJoined(...)100%5050100%
File 2: GetBoundaryFrame(...)100%44100%
File 2: GetBoundaryOrientation(...)100%44100%
File 2: GetJoinedBoundary(...)100%44100%
File 2: IsJoinedSpan(...)100%11100%
File 2: GetJoinedEndpointFan(...)100%11100%
File 2: AppendJoinedBoundaries(...)100%88100%
File 2: TryGatherContainedJoinedSupport(...)100%2626100%
File 2: JoinFiniteSpans(...)100%1616100%
File 2: JoinAtPoint(...)100%88100%
File 2: VisitJoinedSource(...)100%11100%
File 2: AdmitJoinedPoint(...)100%1616100%
File 2: KeepJoinedPoint(...)100%3030100%
File 2: GetJoinedRegionFrame(...)100%11100%
File 2: RetainJoinedPoint(...)100%44100%
File 2: CompareJoinedWitness(...)100%22100%
File 2: CompareJoinedPoints(...)100%11100%
File 2: ReduceJoinedSamples(...)100%3232100%
File 2: TryGetJoinedSample(...)100%1414100%
File 2: .ctor(...)100%11100%
File 2: .ctor(...)100%11100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/CollisionHandling/Detection/3D/Mesh/FaceRegions/MeshCapsuleFaceRegions.cs

#LineLine coverage
 1//=======================================================================
 2// MeshCapsuleFaceRegions.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.Collections.Generic;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12using Gravitas.Colliders;
 13using SwiftCollections;
 14
 15namespace Gravitas.CollisionHandling;
 16
 17/// <summary>Retains each admitted capsule section's exact face direction and finite sample coverage.</summary>
 18/// <content>Single-member gathering, exact point storage and final sample access.</content>
 19internal sealed partial class MeshCapsuleFaceRegions
 20{
 1076921    private ulong[] _values = Array.Empty<ulong>();
 1076922    private int[] _signs = Array.Empty<int>();
 1076923    private sbyte[] _valueSigns = Array.Empty<sbyte>();
 1076924    private CapsulePlaneRaySelectionMetadata[] _winners = Array.Empty<CapsulePlaneRaySelectionMetadata>();
 2153825    private int[] _orientations = Array.Empty<int>(), _counts = Array.Empty<int>();
 1076926    private Sample[] _samples = Array.Empty<Sample>();
 2153827    private readonly SwiftList<Sample> _events = new(), _pool = new();
 1076928    private ulong[] _pointValues = Array.Empty<ulong>();
 1076929    private int[] _pointSigns = Array.Empty<int>();
 1076930    private readonly SwiftList<PointStorage> _points = new();
 31    private int _pointWordCount;
 32    private readonly CapsulePlaneRayEventVisitor _visitor;
 33    private readonly IComparer<Sample> _pointComparer;
 34    private CapsulePlaneRayFrame _frame;
 2153835    private int _fieldWords = CapsulePlaneRaySelection.FieldWords, _rootWords = CapsulePlaneRaySelection.RootWords,
 1076936        _valueWords = CapsulePlaneRayValue.PolynomialWords;
 24704037    private int SelectionWords => CapsulePlaneRaySelection.GetStorageWords(_fieldWords, _rootWords, _valueWords);
 38
 39    private void SelectBanks(in CapsulePlaneRayFrame frame)
 7838440    { _fieldWords = frame.FieldWords; _rootWords = frame.RootWords; _valueWords = frame.ValueWords; }
 41    private Vector3d _normal, _meshOrigin, _center;
 42    private FixedQuaternion _meshRotation, _rotation;
 43    private PhysicsMesh? _gatherMesh;
 44    private MeshSurfaceConnectivity? _gatherConnectivity;
 45    private int _gatherSurface;
 46    private int _sourceRegion;
 47    private int _fixedOrientation;
 48    private bool _containsSection, _usesConvexFan;
 49
 1076950    internal MeshCapsuleFaceRegions()
 51    {
 1076952        _visitor = AdmitPoint;
 1076953        _pointComparer = Comparer<Sample>.Create(ComparePoints);
 1076954    }
 55
 56    internal int RegionCount { get; private set; }
 57    internal bool HasBoundaryIntersection { get; private set; }
 58
 59    internal void Build(PhysicsMesh mesh, int surfaceTriangle, Vector3d center,
 60        FixedQuaternion rotation, Fixed64 coreLength, Fixed64 radius, MeshSurfaceConnectivity connectivity)
 61    {
 7162        var finite = new CapsuleFiniteSectionFrame(mesh.GeometryFrame, center, rotation, coreLength, radius);
 7163        Build(mesh, surfaceTriangle, finite, center, rotation, connectivity);
 7164    }
 65
 66    internal void Build(PhysicsMesh mesh, int surfaceTriangle, in CapsuleFiniteSectionFrame finite,
 67        Vector3d center, FixedQuaternion rotation, MeshSurfaceConnectivity connectivity)
 68    {
 1317769        if (_joined != null) _joined.Active = false;
 1317670        RegionCount = connectivity.RegionCount;
 1317671        HasBoundaryIntersection = false;
 1318172        if (RegionCount == 0) return;
 1317173        mesh.GetGeometryTriangleVertices(surfaceTriangle, out Vector3d a, out Vector3d b, out Vector3d c);
 1317174        _frame = new CapsulePlaneRayFrame(new FixedTriangle(a, b, c), mesh.GeometryFrame, finite);
 2634275        SelectBanks(_frame); Reserve(RegionCount);
 76        // Sphere and axial rays share one radial height H(q): their signed
 77        // exits are H(q) +/- the plane offset, so every region chooses alike.
 1317178        _fixedOrientation = finite.Length == Fixed64.Zero || _frame.Normal.X.IsZero && _frame.Normal.Z.IsZero
 1317179            ? (_frame.PlaneConstant.Sign >= 0 ? 1 : -1) : 0;
 1317180        _normal = _frame.GetWorldNormal(mesh.Rotation);
 1317181        _meshOrigin = _frame.Finite.ShapeFrame.HasExactScale ? center : mesh.Origin;
 1317182        _meshRotation = _frame.Finite.ShapeFrame.HasExactScale ? rotation : mesh.Rotation;
 2634283        _center = center; _rotation = rotation;
 1317184        Array.Clear(_winners, 0, 2 * RegionCount);
 3951385        _events.FastClear(); _points.FastClear(); _pointWordCount = 0;
 1317186        Gather(mesh, surfaceTriangle, connectivity);
 87        // Exact rigid transforms preserve the physical metric. Rounding once
 88        // in authored coordinates also keeps finite mesh anchors representable.
 1317189        var metrics = new WidePlaneMetrics(new FixedTriangle(a, b, c), FixedQuaternion.Identity);
 5503490        for (int region = 0; region < RegionCount; region++)
 91        {
 2864992            if (_fixedOrientation != 0) _orientations[region] = _fixedOrientation;
 93            else
 94            {
 4395                var positive = BorrowWinner(2 * region);
 4396                var negative = BorrowWinner(2 * region + 1);
 97                System.Diagnostics.Debug.Assert(positive.HasValue && negative.HasValue);
 4398                _orientations[region] = positive.CompareDepth(negative) <= 0 ? 1 : -1;
 99            }
 14346100            ReduceSamples(region, metrics);
 101        }
 13171102    }
 103
 104    private void Reserve(int count)
 105    {
 19596106        if (_counts.Length < count)
 107        {
 405108            int capacity = Math.Max(count, 2 * _counts.Length);
 810109            Array.Resize(ref _counts, capacity); Array.Resize(ref _orientations, capacity);
 405110            Array.Resize(ref _samples, capacity * ContactManifold.MaxContactsPerGroup);
 405111            Array.Resize(ref _winners, 2 * capacity);
 405112            Array.Resize(ref _signs, 2 * capacity * CapsulePlaneRaySelection.SignCount);
 405113            Array.Resize(ref _valueSigns, 2 * capacity * CapsulePlaneRaySelection.ValueSignCount);
 114        }
 19596115        if (_values.Length < 2 * _counts.Length * SelectionWords)
 406116            Array.Resize(ref _values, 2 * _counts.Length * SelectionWords);
 19596117    }
 118
 119    private void Gather(PhysicsMesh mesh, int surfaceTriangle, MeshSurfaceConnectivity connectivity)
 120    {
 39513121        _gatherMesh = mesh; _gatherConnectivity = connectivity; _gatherSurface = surfaceTriangle;
 122        try
 123        {
 13171124            ReadOnlySpan<int> boundary = mesh.GetCanonicalSurfaceBoundaryVertexPairs(surfaceTriangle);
 13171125            ReadOnlySpan<Vector3d> vertices = mesh.GeometryVertices;
 13171126            int first = 0;
 115679127            for (; first < boundary.Length; first += 2)
 51638128                if (_frame.Finite.IntersectsSegment(new FixedSegment(vertices[boundary[first]],
 51638129                    vertices[boundary[first + 1]]))) break;
 13171130            HasBoundaryIntersection = first < boundary.Length;
 13171131            ReadOnlySpan<int> corners = mesh.GetConvexCoplanarPatchCornerVertexIndices(surfaceTriangle);
 132            // A connected convex section with an admitted point cannot leave
 133            // the filled domain without meeting its complete true boundary.
 13171134            _containsSection = RegionCount == 1 && !HasBoundaryIntersection;
 13171135            _usesConvexFan = !_containsSection && RegionCount == 1 && !corners.IsEmpty
 13171136                && corners.Length - 2 < connectivity.TriangleIndices.Length
 13171137                && connectivity.IsCompleteSingleRegion(mesh);
 13171138            if (_containsSection && _fixedOrientation != 0 && _frame.Finite.ShapeFrame.Radius.Sign > 0)
 139            {
 140                // A strictly curved contained section has one physical support;
 141                // off-peak rim rows would add artificial normal-impulse levers.
 12769142                int endpoint = _frame.Finite.Length == Fixed64.Zero ? 0
 12769143                    : _fixedOrientation * _frame.Normal.Y.Sign > 0 ? 1 : 0;
 12769144                var descriptor = new CapsulePlaneRayEvent(CapsulePlaneRayEventKind.Support, endpoint);
 12769145                Span<ulong> values = stackalloc ulong[SelectionWords];
 12769146                Span<int> signs = stackalloc int[CapsulePlaneRaySelection.SignCount];
 12769147                Span<sbyte> valueSigns = stackalloc sbyte[CapsulePlaneRaySelection.ValueSignCount];
 12769148                var support = new CapsulePlaneRaySelection(values, signs, valueSigns, _fieldWords, _rootWords, _valueWor
 12769149                bool found = CapsulePlaneRayEvents.Reconstruct(CapsulePlaneRayEventSource.Plane,
 12769150                    _frame, descriptor, _fixedOrientation, ref support);
 151                System.Diagnostics.Debug.Assert(found);
 12769152                AdmitPoint(CapsulePlaneRayEventSource.Plane, _frame, descriptor, _fixedOrientation, support);
 12769153                return;
 154            }
 402155            VisitSource(CapsulePlaneRayEventSource.Plane);
 13052156            for (int edge = first; edge < boundary.Length; edge += 2)
 157            {
 6124158                var segment = new FixedSegment(vertices[boundary[edge]], vertices[boundary[edge + 1]]);
 6124159                if (edge != first && !_frame.Finite.IntersectsSegment(segment)) continue;
 160                // A capsule intersects a straight canonical edge in one closed
 161                // interval; its admitted subedges therefore share one region.
 4552162                _sourceRegion = RegionCount == 1 ? 0 : MeshSurfaceBoundaryTopology.FindEdgeRegion(mesh,
 4552163                    mesh.GetManifoldSurfaceOwner(surfaceTriangle), boundary[edge], boundary[edge + 1],
 4552164                    connectivity, _frame.Finite);
 4552165                if (_sourceRegion < 0) continue;
 4552166                var source = new CapsulePlaneRayEventSource(segment);
 4552167                VisitSource(source);
 168            }
 402169        }
 170        finally
 171        {
 52684172            _gatherMesh = null; _gatherConnectivity = null; _containsSection = false; _usesConvexFan = false;
 13171173        }
 13171174    }
 175
 176    private void VisitSource(in CapsulePlaneRayEventSource source)
 177    {
 4954178        CapsulePlaneRayEvents.VisitEvents(source, _frame, _fixedOrientation == 0 ? 1 : _fixedOrientation, _visitor);
 5051179        if (_fixedOrientation == 0) CapsulePlaneRayEvents.VisitEvents(source, _frame, -1, _visitor);
 4954180    }
 181
 182    private int FindRegion(scoped in CapsulePlaneRaySelection point)
 183    {
 28436184        if (_containsSection) return 0;
 2274185        PhysicsMesh mesh = _gatherMesh!;
 2274186        MeshSurfaceConnectivity connectivity = _gatherConnectivity!;
 2274187        ReadOnlySpan<int> corners = _usesConvexFan
 2274188            ? mesh.GetConvexCoplanarPatchCornerVertexIndices(_gatherSurface) : ReadOnlySpan<int>.Empty;
 2274189        if (!corners.IsEmpty)
 190        {
 18191            ReadOnlySpan<Vector3d> vertices = mesh.GeometryVertices;
 100192            for (int corner = 1; corner < corners.Length - 1; corner++)
 34193                if (point.ContainsTrianglePoint(_frame, new FixedTriangle(vertices[corners[0]],
 36194                    vertices[corners[corner]], vertices[corners[corner + 1]]))) return 0;
 16195            return -1;
 196        }
 197        // Closed admitted intersections uniquely identify their connected region.
 56045198        foreach (int triangle in connectivity.TriangleIndices)
 199        {
 26021200            mesh.GetGeometryTriangleVertices(triangle, out Vector3d a, out Vector3d b, out Vector3d c);
 26021201            if (point.ContainsTrianglePoint(_frame, new FixedTriangle(a, b, c)))
 509202                return connectivity.GetRegionOrdinal(triangle);
 203        }
 1747204        return -1;
 205    }
 206
 207    private void AdmitPoint(in CapsulePlaneRayEventSource source, in CapsulePlaneRayFrame frame,
 208        CapsulePlaneRayEvent descriptor, int orientation, scoped in CapsulePlaneRaySelection candidate)
 209    {
 24988210        int region = source.IsSegment ? _sourceRegion : FindRegion(candidate);
 26751211        if (region < 0) return;
 23225212        int index = 2 * region + (orientation > 0 ? 0 : 1);
 23225213        var winner = BorrowWinner(index);
 46450214        winner.KeepEvaluated(candidate, frame); _winners[index] = winner.Metadata;
 215        // Opposite rays share the same exact base event. Retain both depth
 216        // winners, but materialize their common coverage point only once.
 258995217        foreach (Sample retained in _events.AsReadOnlySpan())
 106376218            if (retained.Region == region && retained.Source.IsSegment == source.IsSegment
 106376219                && retained.Source.A == source.A && retained.Source.B == source.B
 106583220                && retained.Event.Matches(descriptor)) return;
 23018221        bool represented = TryGetSamplingPoint(candidate, frame, out Vector3d p);
 222        // Admission makes q a convex combination of finite authored vertices.
 223        System.Diagnostics.Debug.Assert(represented);
 249502224        foreach (Sample retained in _events.AsReadOnlySpan())
 106611225            if (retained.Region == region && retained.Point == p && CompareToPoint(retained, candidate) == 0) return;
 19766226        _events.Add(new Sample(source, descriptor, region, p, RetainPoint(candidate)));
 19766227    }
 228
 229    private bool TryGetSamplingPoint(scoped in CapsulePlaneRaySelection selection, in CapsulePlaneRayFrame frame, out Ve
 23021230        frame.Finite.ShapeFrame.HasExactScale
 23021231            ? selection.TryGetPointInRigidFrame(frame, _meshOrigin, _meshRotation, _center, _rotation, out point)
 23021232            : selection.TryGetAuthoredPoint(frame, _meshOrigin, _meshRotation, _center, _rotation, out point);
 233
 234    private CapsulePlaneRaySelection BorrowWinner(int index)
 235    {
 94542236        var selection = new CapsulePlaneRaySelection(
 94542237            _values.AsSpan(index * SelectionWords, SelectionWords),
 94542238            _signs.AsSpan(index * CapsulePlaneRaySelection.SignCount, CapsulePlaneRaySelection.SignCount),
 94542239            _valueSigns.AsSpan(index * CapsulePlaneRaySelection.ValueSignCount, CapsulePlaneRaySelection.ValueSignCount)
 189084240        selection.Restore(_winners[index]); return selection;
 241    }
 242
 243    private void ReduceSamples(int region, WidePlaneMetrics metrics)
 244    {
 14346245        _pool.FastClear();
 14346246        var maximum = BorrowWinner(2 * region + (_orientations[region] > 0 ? 0 : 1));
 14346247        Sample seed = GetSeed(region, maximum);
 14346248        Vector3d p = seed.Point;
 14346249        _pool.Add(seed);
 119840250        foreach (Sample sample in _events.AsReadOnlySpan())
 251        {
 45574252            if (sample.Region != region || sample.Point == p && CompareToPoint(sample, maximum) == 0) continue;
 5420253            _pool.Add(sample);
 254        }
 14346255        int count = Math.Min(ContactManifold.MaxContactsPerGroup, _pool.Count);
 14346256        int offset = region * ContactManifold.MaxContactsPerGroup;
 14346257        _samples[offset] = seed;
 28692258        Span<int> chosen = stackalloc int[ContactManifold.MaxContactsPerGroup]; chosen[0] = 0;
 38078259        for (int slot = 1; slot < count; slot++)
 260        {
 4693261            int best = _frame.Finite.ShapeFrame.HasExactScale
 4693262                ? MeshPlaneSampleReduction.ChooseNext(_pool.AsReadOnlySpan(), chosen[..slot], _frame.Normal, _pointCompa
 4693263                : MeshPlaneSampleReduction.ChooseNext(_pool.AsReadOnlySpan(), chosen[..slot], metrics, _pointComparer);
 9386264            chosen[slot] = best; _samples[offset + slot] = _pool[best];
 265        }
 14346266        _counts[region] = count;
 14346267    }
 268
 269    private Sample GetSeed(int region, scoped in CapsulePlaneRaySelection maximum)
 270    {
 75077271        foreach (Sample sample in _events.AsReadOnlySpan())
 30364272            if (sample.Region == region && sample.Source.IsSegment == maximum.MaximumSource.IsSegment
 30364273                && sample.Source.A == maximum.MaximumSource.A && sample.Source.B == maximum.MaximumSource.B
 44707274                && sample.Event.Matches(maximum.MaximumEvent)) return sample;
 275        // Exact-point deduplication can retain an equivalent event descriptor.
 3276        bool represented = TryGetSamplingPoint(maximum, _frame, out Vector3d p);
 277        System.Diagnostics.Debug.Assert(represented);
 3278        return new Sample(maximum.MaximumSource, maximum.MaximumEvent, region, p, RetainPoint(maximum));
 279    }
 280
 281    private int RetainPoint(scoped in CapsulePlaneRaySelection point)
 282    {
 283        // Retain q once; exact coverage ties must not replay its event algebra.
 19769284        int index = _points.Count;
 19769285        int words = Math.Max(Math.Max(ContactQuadratic.ActiveWords(point.X), ContactQuadratic.ActiveWords(point.Y)),
 19769286            Math.Max(ContactQuadratic.ActiveWords(point.Z), ContactQuadratic.ActiveWords(point.Denominator)));
 19769287        int rootWords = WideArithmetic.GetActiveMagnitudeLength(point.Root);
 19769288        int needed = _pointWordCount + 8 * words + rootWords;
 20324289        if (_pointValues.Length < needed) Array.Resize(ref _pointValues, Math.Max(needed, 2 * _pointValues.Length));
 19769290        if (_pointSigns.Length < (index + 1) * FiniteSectionPoint.SignCount)
 291        {
 297292            Array.Resize(ref _pointSigns, Math.Max((index + 1) * FiniteSectionPoint.SignCount,
 297293                Math.Max(8 * FiniteSectionPoint.SignCount, 2 * _pointSigns.Length)));
 294        }
 39538295        _points.Add(new PointStorage(_pointWordCount, words, rootWords)); _pointWordCount = needed;
 19769296        var retained = BorrowPoint(index);
 39538297        point.X.CopyTo(retained.Coordinate(0)); point.Y.CopyTo(retained.Coordinate(1));
 39538298        point.Z.CopyTo(retained.Coordinate(2)); point.Denominator.CopyTo(retained.Denominator);
 19769299        point.Root[..rootWords].CopyTo(retained.Root);
 19769300        return index;
 301    }
 302
 303    private FiniteSectionPoint BorrowPoint(int index)
 304    {
 76039305        PointStorage storage = _points[index];
 76039306        return new(_pointValues.AsSpan(storage.Offset, 8 * storage.Words + storage.RootWords),
 76039307            _pointSigns.AsSpan(index * FiniteSectionPoint.SignCount, FiniteSectionPoint.SignCount),
 76039308            storage.Words, storage.RootWords);
 309    }
 310
 311    private readonly struct PointStorage
 312    {
 313        internal readonly int Offset, Words, RootWords;
 314        internal PointStorage(int offset, int words, int rootWords)
 143644315        { Offset = offset; Words = words; RootWords = rootWords; }
 316    }
 317
 318    private int CompareToPoint(Sample sample, scoped in CapsulePlaneRaySelection point)
 319    {
 17598320        var retained = BorrowPoint(sample.ExactPoint);
 17598321        return _frame.ComparePoints(retained.Coordinate(0), retained.Coordinate(1), retained.Coordinate(2),
 17598322            retained.Denominator, retained.Root, point.X, point.Y, point.Z, point.Denominator, point.Root);
 323    }
 324
 325    private int ComparePoints(Sample first, Sample second)
 326    {
 1960327        int order = first.Point.X.CompareTo(second.Point.X);
 2629328        if (order != 0) return order;
 1291329        var a = BorrowPoint(first.ExactPoint);
 1291330        var b = BorrowPoint(second.ExactPoint);
 1291331        return _frame.ComparePoints(a.Coordinate(0), a.Coordinate(1), a.Coordinate(2), a.Denominator, a.Root,
 1291332            b.Coordinate(0), b.Coordinate(1), b.Coordinate(2), b.Denominator, b.Root);
 333    }
 334
 19035335    internal Vector3d GetNormal(int region) => -_normal * GetOrientation(region);
 26516336    internal int GetOrientation(int region) => _orientations[ValidateRegion(region)];
 42126337    internal int GetSampleCount(int region) => _counts[ValidateRegion(region)];
 338
 339    internal bool TryGetSample(int region, int index, out FixedContactAnchors contact)
 340    {
 19041341        contact = default;
 19056342        if ((uint)region >= (uint)RegionCount || (uint)index >= (uint)_counts[region]) return false;
 19026343        Sample sample = _samples[region * ContactManifold.MaxContactsPerGroup + index];
 19026344        if (index == 0)
 345        {
 14348346            var maximum = BorrowWinner(2 * region + (_orientations[region] > 0 ? 0 : 1));
 14348347            return TryCreateContact(region, sample.Point, maximum, out contact);
 348        }
 4678349        Span<ulong> values = stackalloc ulong[SelectionWords];
 4678350        Span<int> signs = stackalloc int[CapsulePlaneRaySelection.SignCount];
 4678351        Span<sbyte> valueSigns = stackalloc sbyte[CapsulePlaneRaySelection.ValueSignCount];
 4678352        var selection = new CapsulePlaneRaySelection(values, signs, valueSigns, _fieldWords, _rootWords, _valueWords);
 4678353        bool found = CapsulePlaneRayEvents.Reconstruct(sample.Source, _frame, sample.Event, _orientations[region], ref s
 354        System.Diagnostics.Debug.Assert(found);
 4678355        return TryCreateContact(region, sample.Point, selection, out contact);
 356    }
 357
 358    private bool TryCreateContact(int region, Vector3d point, scoped CapsulePlaneRaySelection selection,
 359        out FixedContactAnchors contact)
 360    {
 19026361        bool represented = selection.TryGetExitAnchor(_frame, _orientations[region], _center, _rotation,
 19026362            out FixedPointAnchor exit, out Fixed64 depth, out bool clamped);
 363        // Admission bounds the radial exit and finite core separately; the
 364        // anchor remains valid even when its absolute world point cannot fit.
 365        System.Diagnostics.Debug.Assert(represented);
 19026366        contact = new FixedContactAnchors(new FixedPointAnchor(_meshOrigin, _meshRotation, point),
 19026367            exit, GetNormal(region), depth, clamped);
 19026368        return represented;
 369    }
 370
 371    private int ValidateRegion(int region)
 372    {
 68648373        if ((uint)region >= (uint)RegionCount) throw new ArgumentOutOfRangeException(nameof(region));
 68636374        return region;
 375    }
 376
 377    private readonly struct Sample : IPlaneContactSample
 378    {
 379        internal readonly CapsulePlaneRayEventSource Source;
 380        internal readonly CapsulePlaneRayEvent Event;
 381        internal readonly int Region;
 382        internal readonly int ExactPoint;
 383        public Vector3d Point { get; }
 384        internal Sample(CapsulePlaneRayEventSource source, CapsulePlaneRayEvent descriptor, int region, Vector3d point, 
 163476385        { Source = source; Event = descriptor; Region = region; Point = point; ExactPoint = exactPoint; }
 386    }
 387}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/CollisionHandling/Detection/3D/Mesh/FaceRegions/MeshCapsuleFaceRegions.Joined.cs

#LineLine coverage
 1//=======================================================================
 2// MeshCapsuleFaceRegions.Joined.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.Collections.Generic;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12using Gravitas.Colliders;
 13using SwiftCollections;
 14using SwiftCollections.Query;
 15using JoinedMember = Gravitas.CollisionHandling.Member<FixedMathSharp.Geometry.CapsulePlaneRayFrame>;
 16
 17namespace Gravitas.CollisionHandling;
 18
 19/// <content>Finite capsule sections across explicitly supplied static surface members.</content>
 20internal sealed partial class MeshCapsuleFaceRegions
 21{
 22    private JoinedState? _joined;
 23
 24    internal void ReleaseJoined()
 25    {
 100226        _joined = null;
 100227        RegionCount = 0;
 100228    }
 29
 30    /// <summary>Prepares unique committed surface owners from bounded input; membership/filter admission belongs to the
 31    internal void BuildJoined(ReadOnlySpan<(LSMeshCollider Collider, int Triangle)> surfaces,
 32        Vector3d center, FixedQuaternion rotation, Fixed64 coreLength, Fixed64 radius,
 33        ReadOnlySpan<PhysicsMesh> preparedMeshes = default,
 34        SwiftDictionary<(PhysicsMesh, int), MeshSurfaceBoundaryDomain>? prepared = null)
 35    {
 642536        JoinedState state = _joined ??= new JoinedState(this);
 642537        state.Prepare(surfaces, preparedMeshes, prepared);
 1285038        _center = center; _rotation = coreLength == Fixed64.Zero ? FixedQuaternion.Identity : rotation;
 642539        FixedBoundBox box = FixedBoundBox.FromCenteredCapsuleClippedToDomain(center, _rotation, Vector3d.Up, coreLength,
 642540        var bounds = new FixedBoundVolume(box.Min, box.Max);
 3875841        for (int index = 0; index < state.Inputs.Count; index++)
 42        {
 1295443            JoinedMember member = state.Members[index];
 1295444            PhysicsMesh mesh = member.Collider.Mesh;
 1295445            var finite = new CapsuleFiniteSectionFrame(mesh.GeometryFrame, center, _rotation, coreLength, radius);
 1295446            mesh.GetGeometryTriangleVertices(member.Triangle, out Vector3d a, out Vector3d b, out Vector3d c);
 1295447            member.Frame = new CapsulePlaneRayFrame(new FixedTriangle(a, b, c), mesh.GeometryFrame, finite);
 1295448            member.Admitted.FastClear();
 1295449            member.Collider.GetTrianglesInBounds(bounds, state.Candidates);
 8611850            foreach (int triangle in state.Candidates.AsReadOnlySpan())
 51            {
 3010552                if (mesh.GetManifoldSurfaceOwner(triangle) != member.Owner) continue;
 3004353                mesh.GetGeometryTriangleVertices(triangle, out a, out b, out c);
 3924454                if (CapsulePlaneRayEvents.IntersectsTriangle(finite, new FixedTriangle(a, b, c))) member.Admitted.Add(tr
 55            }
 1295456            member.Connectivity.BuildCapsule(mesh, member.Triangle, finite, member.Admitted.AsReadOnlySpan());
 1295457            state.AddRegions(index);
 58        }
 642559        bool wideBanks = false;
 3875860        foreach (JoinedMember member in state.Members.AsReadOnlySpan()[..state.Inputs.Count])
 61        {
 1295462            wideBanks |= member.Frame.UsesWideBanks;
 18599463            foreach (var span in member.Boundary.Spans) wideBanks |= span.Interval.HasWideBounds;
 64        }
 642565        if (wideBanks)
 14266            foreach (JoinedMember member in state.Members.AsReadOnlySpan()[..state.Inputs.Count])
 4867                member.Frame = member.Frame.WithWideParameters();
 642568        SelectBanks(state.Members[0].Frame);
 642569        JoinFiniteSpans(state);
 642570        state.CompleteRegions();
 1285071        RegionCount = state.Roots.Count; HasBoundaryIntersection = false;
 642572        Reserve(RegionCount);
 655473        if (state.BoundaryHits.Length < RegionCount) Array.Resize(ref state.BoundaryHits, RegionCount);
 655474        if (state.Trusted.Length < RegionCount) Array.Resize(ref state.Trusted, RegionCount);
 1285075        Array.Clear(state.BoundaryHits, 0, RegionCount); Array.Fill(state.Trusted, true, 0, RegionCount);
 3875876        foreach (JoinedMember member in state.Members.AsReadOnlySpan()[..state.Inputs.Count])
 77        {
 1295478            if (member.BoundaryTrusted) continue;
 14079            for (int local = 0; local < member.Connectivity.RegionCount; local++)
 2780                state.Trusted[state.RegionByRoot[state.Find(member.Offset + local)]] = false;
 81        }
 655482        if (state.Maximum.Length < 2 * RegionCount) Array.Resize(ref state.Maximum, 2 * RegionCount);
 655483        if (state.MaximumPoint.Length < 2 * RegionCount) Array.Resize(ref state.MaximumPoint, 2 * RegionCount);
 642584        Array.Clear(_winners, 0, 2 * RegionCount);
 2570085        _events.FastClear(); _points.FastClear(); _pointWordCount = 0; state.PointSources.FastClear();
 642586        if (!TryGatherContainedJoinedSupport(state))
 87        {
 88            // The intrinsic plane is shared by the whole joined component;
 89            // finite admission below still selects each actual supplying owner.
 95290            for (int region = 0; region < RegionCount; region++)
 91            {
 52092                state.CurrentRegion = region; state.CurrentMember = state.NodeMembers[state.Roots[region]];
 26093                _frame = state.Members[state.CurrentMember].Frame;
 26094                VisitJoinedSource(state, CapsulePlaneRayEventSource.Plane, default);
 95            }
 21696            state.CurrentRegion = -1;
 117697            for (int member = 0; member < state.Inputs.Count; member++)
 98            {
 37299                if (state.Members[member].Connectivity.RegionCount == 0) continue;
 341100                state.CurrentMember = member;
 682101                JoinedMember current = state.Members[member]; _frame = current.Frame;
 341102                ReadOnlySpan<BoundarySpan3D> spans = current.Boundary.Spans;
 3642103                for (int span = 0; span < spans.Length; span++)
 104                {
 1480105                    if (current.JoinedSpans[span] || !_frame.Finite.IntersectsSegment(new FixedSegment(spans[span].Start
 383106                    VisitJoinedSource(state, new CapsulePlaneRayEventSource(new FixedSegment(spans[span].Start, spans[sp
 107                }
 108            }
 109        }
 32257110        for (int region = 0; region < RegionCount; region++) ReduceJoinedSamples(state, region);
 6425111        state.Commit();
 6425112    }
 113
 114    internal CapsulePlaneRayFrame GetBoundaryFrame(LSMeshCollider collider, int triangle, out Vector3d normal)
 115    {
 1188116        if (_joined?.Active != true) { normal = _normal; return _frame; }
 66117        var frame = _joined.Members[_joined.MemberBySurface[(collider.Mesh, collider.Mesh.GetManifoldSurfaceOwner(triang
 66118        normal = frame.GetWorldNormal(collider.Mesh.Rotation);
 66119        return frame;
 120    }
 121
 122    internal int GetBoundaryOrientation(LSMeshCollider collider, int triangle, int localRegion)
 123    {
 15245124        if (_joined?.Active != true) return GetOrientation(localRegion);
 287125        JoinedState state = _joined;
 287126        JoinedMember member = state.Members[state.MemberBySurface[(collider.Mesh, collider.Mesh.GetManifoldSurfaceOwner(
 287127        int region = state.RegionByRoot[state.Find(member.Offset + localRegion)];
 287128        return WideDirection3d.Dot(member.Frame.Normal, GetJoinedRegionFrame(state, region).Normal).Sign * _orientations
 129    }
 130
 131    internal MeshSurfaceBoundaryDomain? GetJoinedBoundary(LSMeshCollider collider, int triangle) =>
 440132        _joined?.Active == true
 440133            ? _joined.Members[_joined.MemberBySurface[(collider.Mesh, collider.Mesh.GetManifoldSurfaceOwner(triangle))]]
 134
 135    internal bool IsJoinedSpan(LSMeshCollider collider, int triangle, int span) =>
 145136        _joined!.Members[_joined.MemberBySurface[(collider.Mesh, collider.Mesh.GetManifoldSurfaceOwner(triangle))]].Join
 137
 138    internal ReadOnlySpan<WideAxis3> GetJoinedEndpointFan(LSMeshCollider collider, int triangle, int span, bool upper, o
 139    {
 76140        return _joined!.GetEndpointFan(collider, triangle, span, upper, out suppress);
 141    }
 142
 143    internal bool AppendJoinedBoundaries(LSMeshCollider collider, Gravitas.Materials.PhysicsMaterial material,
 144        Vector3d center, FixedQuaternion rotation, Fixed64 coreLength, Fixed64 radius,
 145        MeshCapsuleSurfaceBoundary boundary, ContactManifold manifold)
 146    {
 13192147        bool overlaps = false;
 13192148        JoinedState state = _joined!;
 80182149        foreach (JoinedMember member in state.Members.AsReadOnlySpan()[..state.Inputs.Count])
 150        {
 26899151            if (member.Collider != collider || member.Connectivity.RegionCount == 0) continue;
 7883152            overlaps = true;
 7883153            if (HasBoundaryIntersection)
 66154                boundary.BuildSurfaceContacts(collider, material, center, rotation, coreLength, radius,
 66155                    member.Triangle, member.Connectivity, this, manifold);
 156        }
 13192157        return overlaps;
 158    }
 159
 160    private bool TryGatherContainedJoinedSupport(JoinedState state)
 161    {
 6509162        if (RegionCount != 1 || !state.Trusted[0]) return false;
 6341163        ref readonly CapsulePlaneRayFrame common = ref GetJoinedRegionFrame(state, 0);
 6341164        if (common.Finite.ShapeFrame.Radius.Sign <= 0 || common.Finite.Length != Fixed64.Zero
 6351165            && (!common.Normal.X.IsZero || !common.Normal.Z.IsZero)) return false;
 166        // Only the complete retained perimeter certifies containment. Testing
 167        // full original edges is conservative when a retained span is clipped.
 37952168        foreach (JoinedMember member in state.Members.AsReadOnlySpan()[..state.Inputs.Count])
 169        {
 12706170            if (member.Connectivity.RegionCount == 0) continue;
 7596171            ReadOnlySpan<BoundarySpan3D> spans = member.Boundary.Spans;
 77586172            for (int span = 0; span < spans.Length; span++)
 31319173                if (!member.JoinedSpans[span] && member.Frame.Finite.IntersectsSegment(new FixedSegment(spans[span].Star
 122174                    return false;
 175        }
 6209176        Span<ulong> values = stackalloc ulong[SelectionWords];
 6209177        Span<int> signs = stackalloc int[CapsulePlaneRaySelection.SignCount];
 6209178        Span<sbyte> valueSigns = stackalloc sbyte[CapsulePlaneRaySelection.ValueSignCount];
 18627179        state.CurrentRegion = 0; state.CurrentMember = state.NodeMembers[state.Roots[0]]; state.CurrentClip = default;
 6209180        _frame = state.Members[state.CurrentMember].Frame;
 37254181        for (int orientation = 1; orientation >= -1; orientation -= 2)
 182        {
 12418183            var support = new CapsulePlaneRaySelection(values, signs, valueSigns, _fieldWords, _rootWords, _valueWords);
 12418184            int endpoint = _frame.Finite.Length == Fixed64.Zero ? 0 : orientation * _frame.Normal.Y.Sign > 0 ? 1 : 0;
 12418185            var descriptor = new CapsulePlaneRayEvent(CapsulePlaneRayEventKind.Support, endpoint);
 12418186            bool found = CapsulePlaneRayEvents.Reconstruct(CapsulePlaneRayEventSource.Plane, _frame, descriptor, orienta
 187            System.Diagnostics.Debug.Assert(found);
 12418188            AdmitJoinedPoint(CapsulePlaneRayEventSource.Plane, _frame, descriptor, orientation, support);
 189        }
 6209190        return true;
 191    }
 192
 193    private void JoinFiniteSpans(JoinedState state)
 194    {
 38758195        for (int member = 0; member < state.Inputs.Count; member++)
 196        {
 12954197            JoinedMember source = state.Members[member];
 12954198            ReadOnlySpan<BoundarySpan3D> spans = source.Boundary.Spans;
 132632199            for (int span = 0; span < spans.Length; span++)
 200            {
 53362201                var edge = spans[span];
 53362202                if (edge.Kind != SpanKind.Joined) continue;
 18130203                if (!state.MemberBySurface.TryGetValue((state.Meshes[edge.OtherMember], edge.OtherSurface), out int othe
 12924204                JoinedMember target = state.Members[other];
 12924205                if (!edge.Interval.IsClipped && source.Connectivity.RegionCount == 1 && target.Connectivity.RegionCount 
 206                {
 207                    // A complete certified shared edge meets the convex capsule
 208                    // in one closed interval belonging to both unique regions.
 2503209                    if (source.Frame.Finite.IntersectsSegment(new FixedSegment(edge.Start, edge.End)))
 210                    {
 2501211                        state.Union(source.Offset, target.Offset);
 2501212                        source.JoinedSpans[span] = true;
 213                    }
 2501214                    continue;
 215                }
 31263216                state.CurrentMember = member; state.OtherMember = other; state.CurrentSpan = span;
 10421217                CapsulePlaneRayEvents.VisitEvents(new CapsulePlaneRayEventSource(new FixedSegment(edge.Start, edge.End))
 10421218                    source.Frame, 1, edge.Interval, state.JoinVisitor);
 219            }
 220        }
 6425221    }
 222
 223    private void JoinAtPoint(in CapsulePlaneRayEventSource source, in CapsulePlaneRayFrame frame,
 224        CapsulePlaneRayEvent descriptor, int orientation, scoped in CapsulePlaneRaySelection point)
 225    {
 582226        JoinedState state = _joined!;
 1164227        JoinedMember first = state.Members[state.CurrentMember], second = state.Members[state.OtherMember];
 2484228        foreach (int a in first.Connectivity.TriangleIndices)
 229        {
 660230            first.Collider.Mesh.GetGeometryTriangleVertices(a, out Vector3d aa, out Vector3d ab, out Vector3d ac);
 660231            if (!point.ContainsTrianglePoint(frame, new FixedTriangle(aa, ab, ac))) continue;
 2604232            foreach (int b in second.Connectivity.TriangleIndices)
 233            {
 715234                second.Collider.Mesh.GetGeometryTriangleVertices(b, out Vector3d ba, out Vector3d bb, out Vector3d bc);
 715235                if (!point.ContainsTrianglePoint(second.Frame, new FixedTriangle(ba, bb, bc), frame)) continue;
 605236                state.Union(first.Offset + first.Connectivity.GetRegionOrdinal(a),
 605237                    second.Offset + second.Connectivity.GetRegionOrdinal(b));
 605238                first.JoinedSpans[state.CurrentSpan] = true;
 239            }
 240        }
 582241    }
 242
 243    private void VisitJoinedSource(JoinedState state, in CapsulePlaneRayEventSource source, in RationalSegmentInterval c
 244    {
 643245        state.CurrentClip = clip;
 643246        CapsulePlaneRayEvents.VisitEvents(source, _frame, 1, clip, state.Visitor);
 643247        CapsulePlaneRayEvents.VisitEvents(source, _frame, -1, clip, state.Visitor);
 643248    }
 249
 250    private void AdmitJoinedPoint(in CapsulePlaneRayEventSource source, in CapsulePlaneRayFrame frame,
 251        CapsulePlaneRayEvent descriptor, int orientation, scoped in CapsulePlaneRaySelection candidate)
 252    {
 16976253        JoinedState state = _joined!;
 16976254        state.VisitedRegions.Clear();
 16976255        int first = state.CurrentRegion < 0 ? state.CurrentMember : 0;
 16976256        int end = state.CurrentRegion < 0 ? first + 1 : state.Inputs.Count;
 98608257        for (int memberIndex = first; memberIndex < end; memberIndex++)
 258        {
 32328259            JoinedMember member = state.Members[memberIndex];
 120456260            foreach (int triangle in member.Connectivity.TriangleIndices)
 261            {
 27900262                int region = state.RegionByRoot[state.Find(member.Offset + member.Connectivity.GetRegionOrdinal(triangle
 27900263                if (state.CurrentRegion >= 0 && region != state.CurrentRegion) continue;
 25450264                member.Collider.Mesh.GetGeometryTriangleVertices(triangle, out Vector3d a, out Vector3d b, out Vector3d 
 25450265                if (!candidate.ContainsTrianglePoint(member.Frame, new FixedTriangle(a, b, c), frame) || !state.VisitedR
 16142266                KeepJoinedPoint(state, memberIndex, region, source, frame, descriptor, orientation, candidate);
 267            }
 268        }
 16976269    }
 270
 271    private void KeepJoinedPoint(JoinedState state, int member, int region, in CapsulePlaneRayEventSource source,
 272        in CapsulePlaneRayFrame frame, CapsulePlaneRayEvent descriptor, int orientation, scoped in CapsulePlaneRaySelect
 273    {
 16142274        bool represented = candidate.TryGetPointInRigidFrame(frame, _center, _rotation, _center, _rotation, out Vector3d
 275        System.Diagnostics.Debug.Assert(represented);
 16142276        int point = RetainJoinedPoint(candidate, frame);
 16142277        var provenance = new JoinedWitness(member, state.CurrentMember, source, descriptor, state.CurrentClip);
 16142278        state.PointSources.Add(provenance);
 63033279        foreach (Sample old in _events.AsReadOnlySpan())
 280        {
 19707281            if (old.Region != region || old.Point != p
 19707282                || FiniteSectionPoint.CompareLexicographic(BorrowPoint(old.ExactPoint), BorrowPoint(point)) != 0) contin
 8665283            _pointWordCount = _points[point].Offset;
 25995284            _points.RemoveAt(point); state.PointSources.RemoveAt(point); point = old.ExactPoint;
 8665285            break;
 286        }
 16142287        bool retained = false;
 63033288        foreach (Sample old in _events.AsReadOnlySpan())
 37037289            if (old.Region == region && old.ExactPoint == point) { retained = true; break; }
 23619290        if (!retained) _events.Add(new Sample(source, descriptor, region, p, point));
 19846291        if (source.IsSegment) { HasBoundaryIntersection = true; state.BoundaryHits[region] = true; }
 16142292        ref readonly CapsulePlaneRayFrame common = ref GetJoinedRegionFrame(state, region);
 16142293        int aligned = WideDirection3d.Dot(frame.Normal, common.Normal).Sign * orientation;
 16142294        int slot = 2 * region + (aligned > 0 ? 0 : 1);
 16142295        var winner = BorrowWinner(slot);
 16142296        int comparison = !winner.HasValue ? 1 : candidate.CompareCoplanarDepth(winner, frame,
 16142297            state.Members[state.Maximum[slot].FrameMember].Frame);
 18604298        if (comparison < 0) return;
 13680299        if (comparison == 0)
 300        {
 610301            int order = FiniteSectionPoint.CompareLexicographic(BorrowPoint(point), BorrowPoint(state.MaximumPoint[slot]
 1112302            if (order > 0 || order == 0 && CompareJoinedWitness(state, provenance, state.Maximum[slot]) >= 0) return;
 303        }
 39534304        candidate.Values.CopyTo(winner.Values); candidate.Signs.CopyTo(winner.Signs); candidate.ValueSigns.CopyTo(winner
 26356305        winner.Restore(candidate.Metadata); _winners[slot] = winner.Metadata;
 26356306        state.Maximum[slot] = provenance; state.MaximumPoint[slot] = point;
 13178307    }
 308
 309    private static ref readonly CapsulePlaneRayFrame GetJoinedRegionFrame(JoinedState state, int region) =>
 43537310        ref state.Members[state.NodeMembers[state.Roots[region]]].Frame;
 311
 312    private int RetainJoinedPoint(scoped in CapsulePlaneRaySelection point, in CapsulePlaneRayFrame frame)
 313    {
 16142314        int words = Math.Max(Math.Max(ContactQuadratic.ActiveWords(point.X), ContactQuadratic.ActiveWords(point.Y)),
 16142315            Math.Max(ContactQuadratic.ActiveWords(point.Z), ContactQuadratic.ActiveWords(point.Denominator))) + 6;
 16142316        int rootWords = WideArithmetic.GetActiveMagnitudeLength(point.Root);
 32284317        int index = _points.Count, needed = _pointWordCount + 8 * words + rootWords;
 16558318        if (_pointValues.Length < needed) Array.Resize(ref _pointValues, Math.Max(needed, 2 * _pointValues.Length));
 16142319        if (_pointSigns.Length < (index + 1) * FiniteSectionPoint.SignCount)
 160320            Array.Resize(ref _pointSigns, Math.Max((index + 1) * FiniteSectionPoint.SignCount, Math.Max(64, 2 * _pointSi
 32284321        _points.Add(new PointStorage(_pointWordCount, words, rootWords)); _pointWordCount = needed;
 16142322        var retained = BorrowPoint(index);
 48426323        point.X.CopyTo(retained.Coordinate(0)); point.Y.CopyTo(retained.Coordinate(1)); point.Z.CopyTo(retained.Coordina
 16142324        Signed320 d = frame.Finite.ShapeFrame.CoordinateDenominator;
 16142325        ContactQuadratic.Scale(point.Denominator, Signed576.ExtendValue(WideArithmetic.AddSigned320(d, d)), retained.Den
 16142326        point.Root[..rootWords].CopyTo(retained.Root);
 16142327        return index;
 328    }
 329
 330    private static int CompareJoinedWitness(JoinedState state, JoinedWitness first, JoinedWitness second)
 331    {
 354332        int order = ((IPhysicsColliderRegistryItem)state.Members[first.Member].Collider).ReplayOrder
 354333            .CompareTo(((IPhysicsColliderRegistryItem)state.Members[second.Member].Collider).ReplayOrder);
 382334        if (order != 0) return order;
 326335        return state.Members[first.Member].Owner.CompareTo(state.Members[second.Member].Owner);
 336    }
 337
 338    private int CompareJoinedPoints(Sample first, Sample second)
 339    {
 699340        return FiniteSectionPoint.CompareLexicographic(BorrowPoint(first.ExactPoint), BorrowPoint(second.ExactPoint));
 341    }
 342
 343    private void ReduceJoinedSamples(JoinedState state, int region)
 344    {
 12938345        var positive = BorrowWinner(2 * region); var negative = BorrowWinner(2 * region + 1);
 6469346        var positiveFrame = state.Members[state.Maximum[2 * region].FrameMember].Frame;
 6469347        var negativeFrame = state.Members[state.Maximum[2 * region + 1].FrameMember].Frame;
 6469348        int orientation = positive.CompareCoplanarDepth(negative, positiveFrame, negativeFrame) <= 0 ? 1 : -1;
 6469349        _orientations[region] = orientation;
 12938350        int slot = 2 * region + (orientation > 0 ? 0 : 1), point = state.MaximumPoint[slot];
 6469351        _pool.FastClear();
 20427352        foreach (Sample sample in _events.AsReadOnlySpan())
 19917353            if (sample.Region == region && sample.ExactPoint == point) { _pool.Add(sample); break; }
 29150354        foreach (Sample sample in _events.AsReadOnlySpan())
 9114355            if (sample.Region == region && sample.ExactPoint != point) _pool.Add(sample);
 6469356        ref readonly CapsulePlaneRayFrame common = ref GetJoinedRegionFrame(state, region);
 6469357        WidePlaneMetrics metrics = common.Finite.ShapeFrame.HasExactScale ? default : new WidePlaneMetrics(new WideAxis3
 6469358            Signed320.NarrowValue(common.Normal.X), Signed320.NarrowValue(common.Normal.Y), Signed320.NarrowValue(common
 359
 360        // A nonempty connected section cannot leave an embedded filled union
 361        // without crossing its complete retained boundary. Only that global
 362        // certificate permits dropping off-peak samples for a strictly curved support.
 6469363        bool contained = state.Trusted[region] && !state.BoundaryHits[region];
 6469364        bool uniqueSupport = common.Finite.ShapeFrame.Radius.Sign > 0
 6469365            && (common.Finite.Length == Fixed64.Zero || common.Normal.X.IsZero && common.Normal.Z.IsZero);
 6469366        int count = contained && uniqueSupport ? 1 : Math.Min(ContactManifold.MaxContactsPerGroup, _pool.Count);
 12938367        Span<int> chosen = stackalloc int[ContactManifold.MaxContactsPerGroup]; chosen[0] = 0;
 27404368        for (int index = 0; index < count; index++)
 369        {
 7997370            if (index > 0) chosen[index] = common.Finite.ShapeFrame.HasExactScale
 764371                ? MeshPlaneSampleReduction.ChooseNext(_pool.AsReadOnlySpan(), chosen[..index], common.Normal, state.Poin
 764372                : MeshPlaneSampleReduction.ChooseNext(_pool.AsReadOnlySpan(), chosen[..index], metrics, state.PointCompa
 7233373            _samples[region * ContactManifold.MaxContactsPerGroup + index] = _pool[chosen[index]];
 374        }
 6469375        _counts[region] = count;
 6469376    }
 377
 378    internal bool TryGetJoinedSample(int region, int index, out FixedContactAnchors contact, out LSMeshCollider? supplie
 379    {
 28610380        contact = default; supplier = null;
 14312381        if (_joined == null || !_joined.Active || (uint)region >= (uint)RegionCount || (uint)index >= (uint)_counts[regi
 14298382        Sample sample = _samples[region * ContactManifold.MaxContactsPerGroup + index];
 14298383        int slot = 2 * region + (_orientations[region] > 0 ? 0 : 1);
 14298384        JoinedWitness witness = index == 0 ? _joined.Maximum[slot] : _joined.PointSources[sample.ExactPoint];
 28596385        JoinedMember member = _joined.Members[witness.Member]; supplier = member.Collider;
 14298386        JoinedMember producer = _joined.Members[witness.FrameMember];
 14298387        ref readonly CapsulePlaneRayFrame common = ref GetJoinedRegionFrame(_joined, region);
 14298388        int orientation = WideDirection3d.Dot(producer.Frame.Normal, common.Normal).Sign * _orientations[region];
 14298389        Span<ulong> values = stackalloc ulong[SelectionWords];
 14298390        Span<int> signs = stackalloc int[CapsulePlaneRaySelection.SignCount];
 14298391        Span<sbyte> valueSigns = stackalloc sbyte[CapsulePlaneRaySelection.ValueSignCount];
 14298392        var selection = index == 0 ? BorrowWinner(slot) : new CapsulePlaneRaySelection(values, signs, valueSigns, _field
 14298393        if (index != 0)
 394        {
 841395            bool found = CapsulePlaneRayEvents.Reconstruct(witness.Source, producer.Frame, witness.Event, orientation, w
 396            System.Diagnostics.Debug.Assert(found);
 397        }
 14298398        PhysicsMesh mesh = member.Collider.Mesh;
 14298399        bool represented = selection.TryGetPointInRigidFrame(producer.Frame, _center, _rotation, _center, _rotation, out
 14298400            & selection.TryGetExitAnchor(producer.Frame, orientation, _center, _rotation, out FixedPointAnchor exit, out
 14298401        contact = new FixedContactAnchors(new FixedPointAnchor(_center, _rotation, authored), exit,
 14298402            -producer.Frame.GetWorldNormal(producer.Collider.Mesh.Rotation) * orientation, depth, clamped);
 14298403        return represented;
 404    }
 405
 406    private readonly struct JoinedWitness
 407    {
 408        internal readonly int Member, FrameMember;
 409        internal readonly CapsulePlaneRayEventSource Source;
 410        internal readonly CapsulePlaneRayEvent Event;
 411        internal readonly RationalSegmentInterval Clip;
 412        internal JoinedWitness(int member, int frameMember, CapsulePlaneRayEventSource source, CapsulePlaneRayEvent desc
 413            RationalSegmentInterval clip)
 96852414        { Member = member; FrameMember = frameMember; Source = source; Event = descriptor; Clip = clip; }
 415    }
 416
 417    private sealed class JoinedState : MeshJoinedSurfaceRegions<CapsulePlaneRayFrame>
 418    {
 127419        internal readonly SwiftList<JoinedWitness> PointSources = new();
 127420        internal readonly SwiftHashSet<int> VisitedRegions = new();
 127421        internal JoinedWitness[] Maximum = Array.Empty<JoinedWitness>();
 127422        internal int[] MaximumPoint = Array.Empty<int>();
 254423        internal bool[] BoundaryHits = Array.Empty<bool>(), Trusted = Array.Empty<bool>();
 424        internal readonly IComparer<Sample> PointComparer;
 425        internal readonly CapsulePlaneRayEventVisitor Visitor, JoinVisitor;
 426        internal int CurrentMember, OtherMember, CurrentSpan, CurrentRegion;
 427        internal RationalSegmentInterval CurrentClip;
 127428        internal JoinedState(MeshCapsuleFaceRegions owner)
 429        {
 127430            PointComparer = Comparer<Sample>.Create(owner.CompareJoinedPoints);
 254431            Visitor = owner.AdmitJoinedPoint; JoinVisitor = owner.JoinAtPoint;
 127432        }
 433    }
 434}

Methods/Properties

.ctor()
get_SelectionWords()
SelectBanks(FixedMathSharp.Geometry.CapsulePlaneRayFrame&)
Build(Gravitas.Colliders.PhysicsMesh,System.Int32,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,Gravitas.CollisionHandling.MeshSurfaceConnectivity)
Build(Gravitas.Colliders.PhysicsMesh,System.Int32,FixedMathSharp.Geometry.CapsuleFiniteSectionFrame&,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,Gravitas.CollisionHandling.MeshSurfaceConnectivity)
Reserve(System.Int32)
Gather(Gravitas.Colliders.PhysicsMesh,System.Int32,Gravitas.CollisionHandling.MeshSurfaceConnectivity)
VisitSource(FixedMathSharp.Geometry.CapsulePlaneRayEventSource&)
FindRegion(FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
AdmitPoint(FixedMathSharp.Geometry.CapsulePlaneRayEventSource&,FixedMathSharp.Geometry.CapsulePlaneRayFrame&,FixedMathSharp.Geometry.CapsulePlaneRayEvent,System.Int32,FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
TryGetSamplingPoint(FixedMathSharp.Geometry.CapsulePlaneRaySelection&,FixedMathSharp.Geometry.CapsulePlaneRayFrame&,FixedMathSharp.Vector3d&)
BorrowWinner(System.Int32)
ReduceSamples(System.Int32,FixedMathSharp.Geometry.WidePlaneMetrics)
GetSeed(System.Int32,FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
RetainPoint(FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
BorrowPoint(System.Int32)
.ctor(System.Int32,System.Int32,System.Int32)
CompareToPoint(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/Sample,FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
ComparePoints(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/Sample,Gravitas.CollisionHandling.MeshCapsuleFaceRegions/Sample)
GetNormal(System.Int32)
GetOrientation(System.Int32)
GetSampleCount(System.Int32)
TryGetSample(System.Int32,System.Int32,FixedMathSharp.Geometry.FixedContactAnchors&)
TryCreateContact(System.Int32,FixedMathSharp.Vector3d,FixedMathSharp.Geometry.CapsulePlaneRaySelection,FixedMathSharp.Geometry.FixedContactAnchors&)
ValidateRegion(System.Int32)
.ctor(FixedMathSharp.Geometry.CapsulePlaneRayEventSource,FixedMathSharp.Geometry.CapsulePlaneRayEvent,System.Int32,FixedMathSharp.Vector3d,System.Int32)
ReleaseJoined()
BuildJoined(System.ReadOnlySpan`1<System.ValueTuple`2<Gravitas.Colliders.LSMeshCollider,System.Int32>>,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,System.ReadOnlySpan`1<Gravitas.Colliders.PhysicsMesh>,SwiftCollections.SwiftDictionary`2<System.ValueTuple`2<Gravitas.Colliders.PhysicsMesh,System.Int32>,Gravitas.CollisionHandling.MeshSurfaceBoundaryDomain>)
GetBoundaryFrame(Gravitas.Colliders.LSMeshCollider,System.Int32,FixedMathSharp.Vector3d&)
GetBoundaryOrientation(Gravitas.Colliders.LSMeshCollider,System.Int32,System.Int32)
GetJoinedBoundary(Gravitas.Colliders.LSMeshCollider,System.Int32)
IsJoinedSpan(Gravitas.Colliders.LSMeshCollider,System.Int32,System.Int32)
GetJoinedEndpointFan(Gravitas.Colliders.LSMeshCollider,System.Int32,System.Int32,System.Boolean,System.Boolean&)
AppendJoinedBoundaries(Gravitas.Colliders.LSMeshCollider,Gravitas.Materials.PhysicsMaterial,FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,Gravitas.CollisionHandling.MeshCapsuleSurfaceBoundary,Gravitas.CollisionHandling.ContactManifold)
TryGatherContainedJoinedSupport(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState)
JoinFiniteSpans(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState)
JoinAtPoint(FixedMathSharp.Geometry.CapsulePlaneRayEventSource&,FixedMathSharp.Geometry.CapsulePlaneRayFrame&,FixedMathSharp.Geometry.CapsulePlaneRayEvent,System.Int32,FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
VisitJoinedSource(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState,FixedMathSharp.Geometry.CapsulePlaneRayEventSource&,FixedMathSharp.Geometry.RationalSegmentInterval&)
AdmitJoinedPoint(FixedMathSharp.Geometry.CapsulePlaneRayEventSource&,FixedMathSharp.Geometry.CapsulePlaneRayFrame&,FixedMathSharp.Geometry.CapsulePlaneRayEvent,System.Int32,FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
KeepJoinedPoint(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState,System.Int32,System.Int32,FixedMathSharp.Geometry.CapsulePlaneRayEventSource&,FixedMathSharp.Geometry.CapsulePlaneRayFrame&,FixedMathSharp.Geometry.CapsulePlaneRayEvent,System.Int32,FixedMathSharp.Geometry.CapsulePlaneRaySelection&)
GetJoinedRegionFrame(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState,System.Int32)
RetainJoinedPoint(FixedMathSharp.Geometry.CapsulePlaneRaySelection&,FixedMathSharp.Geometry.CapsulePlaneRayFrame&)
CompareJoinedWitness(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState,Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedWitness,Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedWitness)
CompareJoinedPoints(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/Sample,Gravitas.CollisionHandling.MeshCapsuleFaceRegions/Sample)
ReduceJoinedSamples(Gravitas.CollisionHandling.MeshCapsuleFaceRegions/JoinedState,System.Int32)
TryGetJoinedSample(System.Int32,System.Int32,FixedMathSharp.Geometry.FixedContactAnchors&,Gravitas.Colliders.LSMeshCollider&)
.ctor(System.Int32,System.Int32,FixedMathSharp.Geometry.CapsulePlaneRayEventSource,FixedMathSharp.Geometry.CapsulePlaneRayEvent,FixedMathSharp.Geometry.RationalSegmentInterval)
.ctor(Gravitas.CollisionHandling.MeshCapsuleFaceRegions)