Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

35.1 KB
Raw Blame
using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;

namespace Aetheris.Kernel.Core.Brep.Tessellation;

internal static class TrimmedSurfaceTessellator
{
    private const double PointOnSegmentTolerance = 1e-9d;
    private const double SignedAreaTolerance = 1e-10d;
    private const int BoundaryRefinementDepth = 1;
    private const int MaxPointClassificationCacheEntries = 65_536;

    public static KernelResult<DisplayFaceMeshPatch> Tessellate(
        FaceId faceId,
        IReadOnlyList<IReadOnlyList<(double U, double V)>> uvLoops,
        Func<double, double, Point3D> evaluate,
        Func<double, double, Vector3D> evaluateNormal,
        DisplayTessellationOptions options,
        double uDomainStart,
        double uDomainEnd,
        double vDomainStart,
        double vDomainEnd,
        Func<string, string, KernelDiagnostic> createWarning,
        DisplayTessellationExecutionBudget? executionBudget = null,
        SurfaceGeometryKind? surfaceKind = null,
        int? explicitOuterLoopIndex = null,
        BSplineSurfaceWithKnots? splineSupport = null)
    {
        executionBudget?.ThrowIfExpired("TrimmedSurface.Start", faceId, surfaceKind);
        if (uvLoops.Count == 0)
        {
            return KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPatch(faceId));
        }

        var normalizedLoops = new List<List<(double U, double V)>>(uvLoops.Count);
        foreach (var loop in uvLoops)
        {
            var normalized = NormalizeLoop(loop);
            if (normalized.Count < 3)
            {
                return KernelResult<DisplayFaceMeshPatch>.Success(
                    CreateEmptyPatch(faceId),
                    [createWarning(
                        $"Face {faceId.Value} parametric trim loop evaluation produced fewer than three unique UV points; skipping face patch.",
                        "Viewer.Tessellation.TrimEvaluationFailed")]);
            }

            normalizedLoops.Add(normalized);
        }

        var outerLoopIndex = explicitOuterLoopIndex ?? SelectOuterLoop(normalizedLoops);
        var trimContext = TrimEvaluationContext.Create(normalizedLoops, outerLoopIndex);

        var (uStartRaw, uEndRaw, vStartRaw, vEndRaw) = trimContext.OuterLoop.Bounds;
        var uStart = System.Math.Max(uDomainStart, uStartRaw);
        var uEnd = System.Math.Min(uDomainEnd, uEndRaw);
        var vStart = System.Math.Max(vDomainStart, vStartRaw);
        var vEnd = System.Math.Min(vDomainEnd, vEndRaw);

        if ((uEnd - uStart) <= SignedAreaTolerance || (vEnd - vStart) <= SignedAreaTolerance)
        {
            return KernelResult<DisplayFaceMeshPatch>.Success(
                CreateEmptyPatch(faceId),
                [createWarning(
                    $"Face {faceId.Value} parametric trim evaluation derived a degenerate UV domain; skipping face patch.",
                    "Viewer.Tessellation.TrimEvaluationFailed")]);
        }

        var uSegments = ResolveSegmentCount(uEnd - uStart, options);
        var vSegments = ResolveSegmentCount(vEnd - vStart, options);

        // Prefer a boundary-conforming triangulation: the uniform-grid mask below leaves a staircase along every
        // trim curve and a gap of up to one cell between neighbouring faces. It stays as the fallback for loop sets
        // that are not a simple "outer minus holes" region (for example periodic wrap-around rings).
        // The conforming mesh refines by bisecting the longest edge in cell-normalized UV space. If the cells are
        // isotropic in UV although the surface only curves in one direction (a cone or cylinder), every needed split
        // across the curved direction also forces the same number of splits along the straight one. Size the cells
        // from the surface's actual turning in each direction instead.
        // Free-form B-splines use native knot spans below; sparse turning estimates are trusted only for analytic
        // surfaces, since a spline can complete several turns between the sampled iso-curves.
        var (curvedU, curvedV) = surfaceKind == SurfaceGeometryKind.BSplineSurfaceWithKnots
            ? (uSegments, vSegments)
            : EstimateCurvatureSegments(evaluate, evaluateNormal, uStart, uEnd, vStart, vEnd, options);
        var refineRectangle = false;
        if (splineSupport is { } spline)
        {
            // A free-form surface can turn several times between uniform samples. Native knot spans
            // bound the refinement cell size so midpoint tests do not alias a whole coil/profile period.
            var nativeU = KnotSegments(spline.KnotValuesU, uStart, uEnd);
            var nativeV = KnotSegments(spline.KnotValuesV, vStart, vEnd);
            refineRectangle = nativeU > uSegments || nativeV > vSegments;
            curvedU = System.Math.Max(curvedU, nativeU);
            curvedV = System.Math.Max(curvedV, nativeV);
        }
        // Sampled straight trim edges (cone generators, cylinder rulings) arrive as many UV-collinear points. They
        // add nothing but sliver triangles, so drop vertices that lie exactly on the segment between their neighbours.
        var cellUForSimplify = (uEnd - uStart) / curvedU;
        var cellVForSimplify = (vEnd - vStart) / curvedV;
        var simplifiedLoops = normalizedLoops
            .Select(loop => RemoveCollinearVertices(loop, cellUForSimplify, cellVForSimplify,
                splineSupport is null ? null : evaluate, options.ChordTolerance * 1e-3d))
            .ToList();
        // Keep adaptive work bounded by the existing display grid's maximum axis budget,
        // rather than truncating a long surface midway through it. This raises no sampling
        // density or tolerance: only failed chord/normal tests request a subdivision.
        var maximumTriangles = (int)System.Math.Clamp((long)options.MaximumSegments * options.MaximumSegments, 12_000, 65_536);
        if (refineRectangle && splineSupport is { } rectangleSupport && simplifiedLoops.Count == 1
            && IsDisplayRectangle(simplifiedLoops[0]))
        {
            var rectangle = SplineRectangleTessellator.Tessellate(faceId, rectangleSupport,
                uStart, uEnd, vStart, vEnd, evaluateNormal, options,
                () => executionBudget?.ThrowIfExpired("TrimmedSurface.SplineRectangle", faceId, surfaceKind),
                maximumTriangles, out var limited);
            if (rectangle is not null) return KernelResult<DisplayFaceMeshPatch>.Success(rectangle, limited ? [createWarning(
                $"Face {faceId.Value} knot-aligned display sampling reached its axis/triangle budget; retained rectangular patch covers the complete trim with limited fidelity.",
                "Viewer.Tessellation.RefinementIncomplete")] : []);
        }
        if (!refineRectangle && splineSupport is not null && simplifiedLoops.Count == 1
            && IsDisplayRectangle(simplifiedLoops[0]))
            simplifiedLoops[0] = [(uStart, vStart), (uEnd, vStart), (uEnd, vEnd), (uStart, vEnd)];
        (List<double> U, List<double> V)? localGrid = null;
        var gridIncomplete = false;
        if (refineRectangle && splineSupport is { } trimSupport)
            localGrid = SplineRectangleTessellator.PlanGrid(trimSupport, uStart, uEnd, vStart, vEnd,
                options, () => executionBudget?.ThrowIfExpired("TrimmedSurface.SplineGrid", faceId, surfaceKind),
                maximumTriangles / 2, out gridIncomplete);
        string? conformingFailure = null;
        var conformingPatch = BoundaryConformingTrimTessellator.TryTessellate(
            faceId,
            simplifiedLoops,
            outerLoopIndex,
            evaluate,
            evaluateNormal,
            (uEnd - uStart) / curvedU,
            (vEnd - vStart) / curvedV,
            options,
            () => executionBudget?.ThrowIfExpired("TrimmedSurface.Conforming", faceId, surfaceKind),
            out var refinementIncomplete,
            refineRectangles: refineRectangle,
            maximumTriangles: maximumTriangles,
            perceptualNormals: splineSupport is not null,
            grid: localGrid,
            reportFailure: reason => conformingFailure = reason);
        if (conformingPatch is not null)
        {
            var qualityWarnings = new List<KernelDiagnostic>();
            if (refinementIncomplete) qualityWarnings.Add(createWarning(
                    $"Face {faceId.Value} adaptive surface refinement reached its {maximumTriangles} live-triangle budget before satisfying display chord/normal criteria; retained mesh is incomplete in fidelity.",
                    "Viewer.Tessellation.RefinementIncomplete"));
            if (gridIncomplete) qualityWarnings.Add(createWarning(
                $"Face {faceId.Value} local knot-grid planning reached its axis/cell budget; the full trim remains covered with limited display chord/edge balance fidelity.",
                "Viewer.Tessellation.RefinementIncomplete"));
            return KernelResult<DisplayFaceMeshPatch>.Success(conformingPatch, qualityWarnings);
        }

        // A trim that is exactly the UV rectangle (a hole-wall strip between two section levels, say)
        // needs no trim fidelity from the grid: size it by the surface's turning, not by the chord
        // tolerance read as a parameter step, which made a straight ruling hundreds of cells long.
        if (splineSupport is null && simplifiedLoops.Count == 1 && IsDisplayRectangle(simplifiedLoops[0]))
        {
            // Only a straight direction is coarsened; the curved one keeps the samples its edges were cut with.
            if (curvedU <= 1) uSegments = 1;
            if (curvedV <= 1) vSegments = 1;
        }
        var positions = new List<Point3D>((uSegments + 1) * (vSegments + 1));
        var normals = new List<Vector3D>((uSegments + 1) * (vSegments + 1));
        var uvGrid = new List<(double U, double V)>((uSegments + 1) * (vSegments + 1));
        var indices = new List<int>(uSegments * vSegments * 6);

        for (var iv = 0; iv <= vSegments; iv++)
        {
            executionBudget?.ThrowIfExpired("TrimmedSurface.GridSampling", faceId, surfaceKind);
            var tv = (double)iv / vSegments;
            var v = vStart + ((vEnd - vStart) * tv);
            for (var iu = 0; iu <= uSegments; iu++)
            {
                var tu = (double)iu / uSegments;
                var u = uStart + ((uEnd - uStart) * tu);
                uvGrid.Add((u, v));
                positions.Add(evaluate(u, v));
                normals.Add(evaluateNormal(u, v));
            }
        }

        var rowWidth = uSegments + 1;
        for (var iv = 0; iv < vSegments; iv++)
        {
            executionBudget?.ThrowIfExpired("TrimmedSurface.TriangleClassification", faceId, surfaceKind);
            for (var iu = 0; iu < uSegments; iu++)
            {
                var i0 = (iv * rowWidth) + iu;
                var i1 = i0 + 1;
                var i2 = i0 + rowWidth;
                var i3 = i2 + 1;

                TryAppendTriangle(i0, i2, i1);
                TryAppendTriangle(i1, i2, i3);
            }
        }

        return KernelResult<DisplayFaceMeshPatch>.Success(new DisplayFaceMeshPatch(faceId, positions, normals, indices),
            indices.Count == 0 ? [createWarning(
                $"Face {faceId.Value} trim triangulation rejected the loop set and native-domain clipping retained zero triangles; outer loop has {normalizedLoops[outerLoopIndex].Count} samples, signed UV area={ComputeSignedArea(normalizedLoops[outerLoopIndex]):R}, U=[{uStart:R},{uEnd:R}], V=[{vStart:R},{vEnd:R}]. No substitute surface was added.",
                "Viewer.Tessellation.TrimEvaluationFailed")]
                // Existing periodic/non-simple charts deliberately use native-grid masking;
                // declining an outer-minus-holes strategy is normal dispatch there. Warn
                // when the new knot-local spline strategy itself had to be abandoned.
                : conformingFailure is null || localGrid is null ? [] : [createWarning(
                    $"Face {faceId.Value} boundary-conforming trim strategy failed: {conformingFailure} Retained conservative grid clipping has limited boundary fidelity; no fan or substitute support was added.",
                    "Viewer.Tessellation.RefinementIncomplete")]);

        int KnotSegments(IReadOnlyList<double> knots, double start, double end)
        {
            var minimum = end - start;
            for (var i = 1; i < knots.Count; i++)
            {
                var span = System.Math.Min(end, knots[i]) - System.Math.Max(start, knots[i - 1]);
                if (span > 0d) minimum = System.Math.Min(minimum, span);
            }

            return (int)double.Clamp(double.Ceiling((end - start) / minimum), 1, options.MaximumSegments);
        }

        bool IsDisplayRectangle(IReadOnlyList<(double U, double V)> loop)
        {
            var area = (uEnd - uStart) * (vEnd - vStart);
            if (area <= 0d || double.Abs(ComputeSignedArea(loop)) < area * .999d) return false;
            foreach (var p in loop)
            {
                var candidates = new[] { (U: uStart, p.V), (U: uEnd, p.V), (p.U, V: vStart), (p.U, V: vEnd) };
                var nearest = candidates.OrderBy(q => double.Abs(q.Item1 - p.U) / (uEnd - uStart)
                    + double.Abs(q.Item2 - p.V) / (vEnd - vStart)).First();
                if (double.Abs(nearest.Item1 - p.U) > (uEnd - uStart) * 1e-6d
                    || double.Abs(nearest.Item2 - p.V) > (vEnd - vStart) * 1e-6d
                    || (evaluate(p.U, p.V) - evaluate(nearest.Item1, nearest.Item2)).Length > options.ChordTolerance * .1d)
                    return false;
            }
            // Numerical pcurve noise is snapped only in this disposable display
            // rectangle; the engineering trim and native parameter map are retained.
            return true;
        }

        void TryAppendTriangle(int ia, int ib, int ic)
        {
            AppendTriangleWithBoundaryRefinement(ia, ib, ic, remainingDepth: BoundaryRefinementDepth);
        }

        void AppendTriangleWithBoundaryRefinement(int ia, int ib, int ic, int remainingDepth)
        {
            executionBudget?.ThrowIfExpired("TrimmedSurface.BoundaryRefinement", faceId, surfaceKind);
            var classification = ClassifyTriangle(uvGrid[ia], uvGrid[ib], uvGrid[ic], trimContext);
            switch (classification)
            {
                case TriangleTrimClassification.ConfidentlyInside:
                    indices.Add(ia);
                    indices.Add(ib);
                    indices.Add(ic);
                    return;
                case TriangleTrimClassification.ConfidentlyOutside:
                    return;
                default:
                    if (remainingDepth <= 0)
                    {
                        return;
                    }

                    var iab = AppendVertexAtUv(Interpolate(uvGrid[ia], uvGrid[ib]));
                    var ibc = AppendVertexAtUv(Interpolate(uvGrid[ib], uvGrid[ic]));
                    var ica = AppendVertexAtUv(Interpolate(uvGrid[ic], uvGrid[ia]));

                    AppendTriangleWithBoundaryRefinement(ia, iab, ica, remainingDepth - 1);
                    AppendTriangleWithBoundaryRefinement(iab, ib, ibc, remainingDepth - 1);
                    AppendTriangleWithBoundaryRefinement(ica, ibc, ic, remainingDepth - 1);
                    AppendTriangleWithBoundaryRefinement(iab, ibc, ica, remainingDepth - 1);
                    return;
            }
        }

        int AppendVertexAtUv((double U, double V) uv)
        {
            var index = uvGrid.Count;
            uvGrid.Add(uv);
            positions.Add(evaluate(uv.U, uv.V));
            normals.Add(evaluateNormal(uv.U, uv.V));
            return index;
        }
    }

    private static TriangleTrimClassification ClassifyTriangle(
        (double U, double V) a,
        (double U, double V) b,
        (double U, double V) c,
        TrimEvaluationContext trimContext)
    {
        var samples = new[]
        {
            a,
            b,
            c,
            Interpolate(a, b),
            Interpolate(b, c),
            Interpolate(c, a),
            ((a.U + b.U + c.U) / 3d, (a.V + b.V + c.V) / 3d),
        };

        var insideCount = 0;
        foreach (var sample in samples)
        {
            if (trimContext.IsInsideTrimRegion(sample))
            {
                insideCount++;
            }
        }

        if (insideCount == samples.Length)
        {
            return TriangleTrimClassification.ConfidentlyInside;
        }

        if (insideCount == 0)
        {
            return TriangleTrimClassification.ConfidentlyOutside;
        }

        return TriangleTrimClassification.BoundaryStraddling;
    }

    private static int SelectOuterLoop(IReadOnlyList<IReadOnlyList<(double U, double V)>> loops)
    {
        var bestIndex = 0;
        var bestArea = double.NegativeInfinity;
        for (var i = 0; i < loops.Count; i++)
        {
            var area = System.Math.Abs(ComputeSignedArea(loops[i]));
            if (area > bestArea + SignedAreaTolerance
                || (System.Math.Abs(area - bestArea) <= SignedAreaTolerance && i < bestIndex))
            {
                bestArea = area;
                bestIndex = i;
            }
        }

        return bestIndex;
    }

    private static (double UMin, double UMax, double VMin, double VMax) ComputeBounds(IReadOnlyList<(double U, double V)> loop)
        => (
            loop.Min(point => point.U),
            loop.Max(point => point.U),
            loop.Min(point => point.V),
            loop.Max(point => point.V));

    internal static TrimEvaluationMetrics EvaluatePointContainmentMetricsForTest(
        IReadOnlyList<IReadOnlyList<(double U, double V)>> normalizedLoops,
        int outerLoopIndex,
        IReadOnlyList<(double U, double V)> points)
    {
        var metrics = new TrimEvaluationMetrics();
        var context = TrimEvaluationContext.Create(normalizedLoops, outerLoopIndex, metrics);
        foreach (var point in points)
        {
            context.IsInsideTrimRegion(point);
        }

        return metrics;
    }

    private static List<(double U, double V)> NormalizeLoop(IReadOnlyList<(double U, double V)> loop)
    {
        var normalized = new List<(double U, double V)>(loop.Count);
        foreach (var point in loop)
        {
            if (normalized.Count == 0 || !AlmostEqual(normalized[^1], point))
            {
                normalized.Add(point);
            }
        }

        if (normalized.Count > 1 && AlmostEqual(normalized[0], normalized[^1]))
        {
            normalized.RemoveAt(normalized.Count - 1);
        }

        return normalized;
    }

    /// <summary>
    /// Estimates how many segments each parameter direction needs to satisfy the angular and chord tolerances, from
    /// the normal turning along a few sampled iso-curves. A direction with no curvature needs a single segment.
    /// </summary>
    private static (int USegments, int VSegments) EstimateCurvatureSegments(
        Func<double, double, Point3D> evaluate,
        Func<double, double, Vector3D> evaluateNormal,
        double uStart,
        double uEnd,
        double vStart,
        double vEnd,
        DisplayTessellationOptions options)
    {
        const int samples = 16;
        const int rows = 5;

        int Estimate(bool alongU)
        {
            var bestSegments = 1;
            for (var row = 0; row < rows; row++)
            {
                var fixedT = (row + 0.5d) / rows;
                var turning = 0d;
                var length = 0d;
                Point3D? previousPoint = null;
                Vector3D? previousNormal = null;
                for (var i = 0; i <= samples; i++)
                {
                    var t = (double)i / samples;
                    var u = alongU ? uStart + ((uEnd - uStart) * t) : uStart + ((uEnd - uStart) * fixedT);
                    var v = alongU ? vStart + ((vEnd - vStart) * fixedT) : vStart + ((vEnd - vStart) * t);
                    var point = evaluate(u, v);
                    var normal = evaluateNormal(u, v);
                    if (previousPoint is { } p)
                    {
                        length += (point - p).Length;
                    }

                    if (previousNormal is { } n && n.Length > 1e-12d && normal.Length > 1e-12d)
                    {
                        turning += double.Acos(double.Clamp(n.Dot(normal) / (n.Length * normal.Length), -1d, 1d));
                    }

                    previousPoint = point;
                    previousNormal = normal;
                }

                if (turning <= 1e-6d)
                {
                    continue;
                }

                var byAngle = (int)double.Ceiling(turning / options.AngularToleranceRadians);
                var radius = length / turning;
                var ratio = double.Clamp(1d - (options.ChordTolerance / System.Math.Max(radius, 1e-9d)), -1d, 1d);
                var halfStep = double.Acos(ratio);
                var byChord = halfStep > 0d ? (int)double.Ceiling(turning / (2d * halfStep)) : 1;
                bestSegments = System.Math.Max(bestSegments, System.Math.Max(byAngle, byChord));
            }

            // Sampling can miss localized curvature; keep a small floor so bumpy patches still get a usable seed grid.
            return System.Math.Clamp(bestSegments, 1, options.MaximumSegments);
        }

        return (Estimate(alongU: true), Estimate(alongU: false));
    }

    private static List<(double U, double V)> RemoveCollinearVertices(List<(double U, double V)> loop, double cellU, double cellV,
        Func<double, double, Point3D>? evaluate = null, double physicalTolerance = 0d)
    {
        if (loop.Count <= 3 || !(cellU > 0d) || !(cellV > 0d))
        {
            return loop;
        }

        var kept = new List<(double U, double V)>(loop);
        var changed = true;
        while (changed && kept.Count > 3)
        {
            changed = false;
            for (var i = 0; i < kept.Count && kept.Count > 3; i++)
            {
                var previous = kept[(i + kept.Count - 1) % kept.Count];
                var current = kept[i];
                var next = kept[(i + 1) % kept.Count];

                // Work in cell units so anisotropic (radians x millimetres) parameter spaces compare fairly.
                var ax = (next.U - previous.U) / cellU;
                var ay = (next.V - previous.V) / cellV;
                var bx = (current.U - previous.U) / cellU;
                var by = (current.V - previous.V) / cellV;
                var chordLengthSquared = (ax * ax) + (ay * ay);
                if (chordLengthSquared <= 1e-24d)
                {
                    continue;
                }

                var along = ((ax * bx) + (ay * by)) / chordLengthSquared;
                var deviation = double.Abs((ax * by) - (ay * bx)) / double.Sqrt(chordLengthSquared);
                var collinear = deviation <= 1e-7d;
                // Numerical inversion leaves tiny UV noise on exact spline iso-curves. Avoid sliver seeds
                // only when the projected segment also agrees in 3D to one thousandth of the display budget.
                if (!collinear && evaluate is not null && deviation <= 1e-5d)
                    collinear = (evaluate(current.U, current.V) - evaluate(
                        previous.U + along * (next.U - previous.U), previous.V + along * (next.V - previous.V))).Length <= physicalTolerance;
                if (along > 0d && along < 1d && collinear)
                {
                    kept.RemoveAt(i);
                    i--;
                    changed = true;
                }
            }
        }

        return kept;
    }

    private static int ResolveSegmentCount(double span, DisplayTessellationOptions options)
    {
        var ratio = span / System.Math.Max(1e-6d, options.ChordTolerance);
        var segmentCount = (int)double.Ceiling(ratio);
        segmentCount = System.Math.Max(options.MinimumSegments, segmentCount);
        return System.Math.Clamp(segmentCount, options.MinimumSegments, options.MaximumSegments);
    }

    private static bool ContainsPoint(IReadOnlyList<(double U, double V)> polygon, (double U, double V) point)
    {
        var inside = false;
        for (var i = 0; i < polygon.Count; i++)
        {
            var a = polygon[i];
            var b = polygon[(i + 1) % polygon.Count];

            if (IsPointOnSegment(point, a, b))
            {
                return true;
            }

            var crosses = ((a.V > point.V) != (b.V > point.V))
                && (point.U < (((b.U - a.U) * (point.V - a.V)) / (b.V - a.V)) + a.U);
            if (crosses)
            {
                inside = !inside;
            }
        }

        return inside;
    }

    /// <summary>Test hook: the indexed containment answer and the reference loop's, for one point.</summary>
    internal static (bool Indexed, bool Reference) ContainsPointBothWays(IReadOnlyList<(double U, double V)> polygon, (double U, double V) point)
        => (PolygonIndex.Create(polygon) is { } index ? index.Contains(point) : ContainsPoint(polygon, point), ContainsPoint(polygon, point));

    private static bool IsPointOnSegment((double U, double V) point, (double U, double V) a, (double U, double V) b)
    {
        var cross = ((point.U - a.U) * (b.V - a.V)) - ((point.V - a.V) * (b.U - a.U));
        if (System.Math.Abs(cross) > PointOnSegmentTolerance)
        {
            return false;
        }

        var dot = ((point.U - a.U) * (b.U - a.U)) + ((point.V - a.V) * (b.V - a.V));
        if (dot < -PointOnSegmentTolerance)
        {
            return false;
        }

        var lengthSquared = ((b.U - a.U) * (b.U - a.U)) + ((b.V - a.V) * (b.V - a.V));
        return dot <= lengthSquared + PointOnSegmentTolerance;
    }

    private static double ComputeSignedArea(IReadOnlyList<(double U, double V)> polygon)
    {
        var area = 0d;
        for (var i = 0; i < polygon.Count; i++)
        {
            var current = polygon[i];
            var next = polygon[(i + 1) % polygon.Count];
            area += (current.U * next.V) - (next.U * current.V);
        }

        return area * 0.5d;
    }

    private static bool AlmostEqual((double U, double V) left, (double U, double V) right)
        => System.Math.Abs(left.U - right.U) <= PointOnSegmentTolerance
            && System.Math.Abs(left.V - right.V) <= PointOnSegmentTolerance;

    private static (double U, double V) Interpolate((double U, double V) left, (double U, double V) right)
        => ((left.U + right.U) * 0.5d, (left.V + right.V) * 0.5d);

    private static DisplayFaceMeshPatch CreateEmptyPatch(FaceId faceId)
        => new(faceId, Array.Empty<Point3D>(), Array.Empty<Vector3D>(), Array.Empty<int>());

    internal sealed class TrimEvaluationMetrics
    {
        public int FullContainsPointEvaluations { get; private set; }

        public int CacheHits { get; private set; }

        internal void IncrementContainsPointEvaluations() => FullContainsPointEvaluations++;

        internal void IncrementCacheHits() => CacheHits++;
    }

    private sealed class TrimEvaluationContext
    {
        private readonly Dictionary<UvPointCacheKey, bool> pointInsideCache = new();
        private readonly TrimEvaluationMetrics? metrics;

        private TrimEvaluationContext(TrimLoopData outerLoop, IReadOnlyList<TrimLoopData> innerLoops, TrimEvaluationMetrics? metrics)
        {
            OuterLoop = outerLoop;
            InnerLoops = innerLoops;
            this.metrics = metrics;
        }

        public TrimLoopData OuterLoop { get; }

        public IReadOnlyList<TrimLoopData> InnerLoops { get; }

        public static TrimEvaluationContext Create(
            IReadOnlyList<IReadOnlyList<(double U, double V)>> loops,
            int outerLoopIndex,
            TrimEvaluationMetrics? metrics = null)
        {
            var loopData = new List<TrimLoopData>(loops.Count);
            for (var i = 0; i < loops.Count; i++)
            {
                var polygon = loops[i];
                var bounds = ComputeBounds(polygon);
                loopData.Add(new TrimLoopData(i == outerLoopIndex, polygon, bounds, PolygonIndex.Create(polygon)));
            }

            var outer = loopData[outerLoopIndex];
            var inner = loopData.Where(static loop => !loop.IsOuterLoop).ToArray();
            return new TrimEvaluationContext(outer, inner, metrics);
        }

        public bool IsInsideTrimRegion((double U, double V) point)
        {
            var key = new UvPointCacheKey(point.U, point.V);
            if (pointInsideCache.TryGetValue(key, out var isInsideCached))
            {
                metrics?.IncrementCacheHits();
                return isInsideCached;
            }

            var isInside = IsInsideTrimRegionUncached(point);
            if (pointInsideCache.Count < MaxPointClassificationCacheEntries)
            {
                pointInsideCache.Add(key, isInside);
            }

            return isInside;
        }

        private bool IsInsideTrimRegionUncached((double U, double V) point)
        {
            if (!ContainsPoint(OuterLoop, point, metrics))
            {
                return false;
            }

            foreach (var hole in InnerLoops)
            {
                if (ContainsPoint(hole, point, metrics))
                {
                    return false;
                }
            }

            return true;
        }
    }

    private readonly record struct TrimLoopData(
        bool IsOuterLoop,
        IReadOnlyList<(double U, double V)> Polygon,
        (double UMin, double UMax, double VMin, double VMax) Bounds,
        PolygonIndex? Index = null);

    /// <summary>
    /// BUILD-PERF-M4: answers <see cref="ContainsPoint(IReadOnlyList{ValueTuple{double, double}}, ValueTuple{double, double})"/>
    /// exactly, visiting only the segments that can matter for a point. A segment can flip the
    /// crossing parity only if the point's V lies in its V range, and can report the point "on
    /// segment" only if the point lies within tol/length of it (|cross| = distance·length ≤ tol); every
    /// other segment contributes nothing. Segments are bucketed by their V range widened by that
    /// margin (×4, plus an absolute epsilon, for rounding), and a candidate is tested with the
    /// original expressions, so the answer is identical. A zero-length segment makes every point
    /// "on segment" in the original loop; such polygons, and polygons with non-finite coordinates,
    /// answer the way the loop would without an index.
    /// </summary>
    private sealed class PolygonIndex
    {
        private readonly IReadOnlyList<(double U, double V)> polygon;
        private readonly int[][] buckets;
        private readonly double origin;
        private readonly double width;
        private readonly bool everyPointOnSegment;

        private PolygonIndex(IReadOnlyList<(double U, double V)> polygon, int[][] buckets, double origin, double width, bool everyPointOnSegment)
        {
            this.polygon = polygon;
            this.buckets = buckets;
            this.origin = origin;
            this.width = width;
            this.everyPointOnSegment = everyPointOnSegment;
        }

        public static PolygonIndex? Create(IReadOnlyList<(double U, double V)> polygon)
        {
            var count = polygon.Count;
            if (count < 32) return null;
            var low = new double[count]; var high = new double[count];
            var everyPointOnSegment = false;
            for (var i = 0; i < count; i++)
            {
                var a = polygon[i]; var b = polygon[(i + 1) % count];
                if (!double.IsFinite(a.U) || !double.IsFinite(a.V)) return null;
                var du = b.U - a.U; var dv = b.V - a.V;
                if (du == 0d && dv == 0d) everyPointOnSegment = true;
                var length = double.Sqrt((du * du) + (dv * dv));
                var margin = 4d * PointOnSegmentTolerance / double.Max(length, 1e-300) + 1e-12 * (1d + double.Abs(a.V) + double.Abs(b.V));
                if (!double.IsFinite(margin)) margin = double.MaxValue;
                low[i] = double.Min(a.V, b.V) - margin;
                high[i] = double.Max(a.V, b.V) + margin;
            }
            var origin = low.Min(); var top = high.Max();
            if (!double.IsFinite(origin) || !double.IsFinite(top) || top <= origin) return null;
            var bucketCount = System.Math.Max(1, count / 4);
            var width = (top - origin) / bucketCount;
            if (!(width > 0d)) return null;
            var lists = new List<int>[bucketCount];
            for (var b = 0; b < bucketCount; b++) lists[b] = [];
            for (var i = 0; i < count; i++)
                for (var b = BucketOf(low[i], origin, width, bucketCount); b <= BucketOf(high[i], origin, width, bucketCount); b++) lists[b].Add(i);
            return new(polygon, lists.Select(list => list.ToArray()).ToArray(), origin, width, everyPointOnSegment);
        }

        // Monotone in v (IEEE subtraction and division by a positive constant are), so a value inside
        // a segment's range always falls in a bucket between its range's end buckets.
        private static int BucketOf(double v, double origin, double width, int bucketCount) =>
            (int)System.Math.Clamp(double.Floor((v - origin) / width), 0d, bucketCount - 1d);

        private int Bucket(double v) => BucketOf(v, origin, width, buckets.Length);

        public bool Contains((double U, double V) point)
        {
            if (everyPointOnSegment || !double.IsFinite(point.U) || !double.IsFinite(point.V)) return ContainsPoint(polygon, point);
            var candidates = buckets[Bucket(point.V)];
            var inside = false;
            foreach (var i in candidates)
            {
                var a = polygon[i];
                var b = polygon[(i + 1) % polygon.Count];
                if (IsPointOnSegment(point, a, b)) return true;
                var crosses = ((a.V > point.V) != (b.V > point.V))
                    && (point.U < (((b.U - a.U) * (point.V - a.V)) / (b.V - a.V)) + a.U);
                if (crosses) inside = !inside;
            }
            return inside;
        }
    }

    private readonly record struct UvPointCacheKey(ulong UBits, ulong VBits)
    {
        public UvPointCacheKey(double u, double v)
            : this(BitConverter.DoubleToUInt64Bits(u), BitConverter.DoubleToUInt64Bits(v))
        {
        }
    }

    private static bool ContainsPoint(
        TrimLoopData loop,
        (double U, double V) point,
        TrimEvaluationMetrics? metrics)
    {
        if (!IsWithinBounds(loop.Bounds, point))
        {
            return false;
        }

        metrics?.IncrementContainsPointEvaluations();
        return loop.Index is { } index ? index.Contains(point) : ContainsPoint(loop.Polygon, point);
    }

    private static bool IsWithinBounds((double UMin, double UMax, double VMin, double VMax) bounds, (double U, double V) point)
        => point.U >= (bounds.UMin - PointOnSegmentTolerance)
            && point.U <= (bounds.UMax + PointOnSegmentTolerance)
            && point.V >= (bounds.VMin - PointOnSegmentTolerance)
            && point.V <= (bounds.VMax + PointOnSegmentTolerance);

    private enum TriangleTrimClassification
    {
        ConfidentlyOutside = 0,
        BoundaryStraddling = 1,
        ConfidentlyInside = 2,
    }
}