Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Remove planar multi-loop fallback fill
Yuechen Licf861c7a5d69
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarPolygonTriangulatorTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarPolygonTriangulatorTests.csnew file mode 100644index 00000000..dea717ee--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarPolygonTriangulatorTests.cs@@ -0,0 +1,162 @@+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;++public sealed class PlanarPolygonTriangulatorTests+{+ [Fact]+ public void TryTriangulateWithHoles_RectangleWithRectangularHole_PreservesHoleDeterministically()+ {+ var outer = Rectangle(0d, 0d, 10d, 10d);+ var hole = Rectangle(3d, 3d, 7d, 7d);++ var first = TryTriangulateWithHoles(outer, [hole]);+ var second = TryTriangulateWithHoles(outer, [hole]);++ Assert.Equal(first.Points, second.Points);+ Assert.Equal(first.Indices, second.Indices);+ Assert.Equal(24, first.Indices.Count);+ Assert.All(GetTriangleCentroids(first.Points, first.Indices), centroid =>+ Assert.False(PointInPolygon2D(centroid, hole), $"triangle centroid {centroid} fell inside the rectangular hole"));+ }++ [Fact]+ public void TryTriangulateWithHoles_RectangleWithCircularHole_PreservesHole()+ {+ var outer = Rectangle(0d, 0d, 20d, 20d);+ var hole = ApproximateCircle(new Point3D(10d, 10d, 0d), radius: 3d, segmentCount: 16);++ var result = TryTriangulateWithHoles(outer, [hole]);++ Assert.NotEmpty(result.Indices);+ Assert.All(GetTriangleCentroids(result.Points, result.Indices), centroid =>+ Assert.False(PointInPolygon2D(centroid, hole), $"triangle centroid {centroid} fell inside the circular hole"));+ }++ [Fact]+ public void TryTriangulateWithHoles_RectangleWithMultipleHoles_PreservesAllHolesDeterministically()+ {+ var outer = Rectangle(0d, 0d, 20d, 12d);+ var holes = new[]+ {+ Rectangle(2d, 2d, 5d, 5d),+ Rectangle(8d, 3d, 11d, 6d),+ Rectangle(14d, 2d, 18d, 8d),+ };++ var first = TryTriangulateWithHoles(outer, holes);+ var second = TryTriangulateWithHoles(outer, holes);++ Assert.Equal(first.Points, second.Points);+ Assert.Equal(first.Indices, second.Indices);+ Assert.All(GetTriangleCentroids(first.Points, first.Indices), centroid =>+ {+ Assert.DoesNotContain(holes, hole => PointInPolygon2D(centroid, hole));+ });+ }++ [Fact]+ public void TryTriangulate_SimpleSingleLoop_RegressionPathRemainsValid()+ {+ var polygon = new[]+ {+ new Point3D(0d, 0d, 0d),+ new Point3D(5d, 0d, 0d),+ new Point3D(5d, 2d, 0d),+ new Point3D(3d, 2d, 0d),+ new Point3D(3d, 5d, 0d),+ new Point3D(0d, 5d, 0d),+ };++ var firstSuccess = PlanarPolygonTriangulator.TryTriangulate(+ polygon,+ new Vector3D(0d, 0d, 1d),+ out var firstIndices,+ out var firstFailure);+ var secondSuccess = PlanarPolygonTriangulator.TryTriangulate(+ polygon,+ new Vector3D(0d, 0d, 1d),+ out var secondIndices,+ out var secondFailure);++ Assert.True(firstSuccess);+ Assert.True(secondSuccess);+ Assert.Null(firstFailure);+ Assert.Null(secondFailure);+ Assert.Equal(firstIndices, secondIndices);+ Assert.Equal((polygon.Length - 2) * 3, firstIndices.Count);+ }++ private static (IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices) TryTriangulateWithHoles(+ IReadOnlyList<Point3D> outer,+ IReadOnlyList<IReadOnlyList<Point3D>> holes)+ {+ var success = PlanarPolygonTriangulator.TryTriangulateWithHoles(+ outer,+ holes,+ new Vector3D(0d, 0d, 1d),+ out var points,+ out var indices,+ out var failure);++ Assert.True(success, failure?.ToString());+ Assert.Null(failure);+ return (points, indices);+ }++ private static Point3D[] Rectangle(double minX, double minY, double maxX, double maxY)+ =>+ [+ new Point3D(minX, minY, 0d),+ new Point3D(maxX, minY, 0d),+ new Point3D(maxX, maxY, 0d),+ new Point3D(minX, maxY, 0d),+ ];++ private static Point3D[] ApproximateCircle(Point3D center, double radius, int segmentCount)+ {+ var points = new Point3D[segmentCount];+ for (var i = 0; i < segmentCount; i++)+ {+ var angle = (2d * double.Pi * i) / segmentCount;+ points[i] = new Point3D(+ center.X + (radius * double.Cos(angle)),+ center.Y + (radius * double.Sin(angle)),+ center.Z);+ }++ return points;+ }++ private static IEnumerable<Point3D> GetTriangleCentroids(IReadOnlyList<Point3D> points, IReadOnlyList<int> indices)+ {+ for (var i = 0; i < indices.Count; i += 3)+ {+ var p0 = points[indices[i]];+ var p1 = points[indices[i + 1]];+ var p2 = points[indices[i + 2]];+ yield return new Point3D(+ (p0.X + p1.X + p2.X) / 3d,+ (p0.Y + p1.Y + p2.Y) / 3d,+ (p0.Z + p1.Z + p2.Z) / 3d);+ }+ }++ private static bool PointInPolygon2D(Point3D point, IReadOnlyList<Point3D> polygon)+ {+ var inside = false;+ for (var i = 0; i < polygon.Count; i++)+ {+ var current = polygon[i];+ var next = polygon[(i + 1) % polygon.Count];+ if (((current.Y > point.Y) != (next.Y > point.Y))+ && point.X < (((next.X - current.X) * (point.Y - current.Y)) / (next.Y - current.Y + double.Epsilon)) + current.X)+ {+ inside = !inside;+ }+ }++ return inside;+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.csindex ac38efdb..8296f41f 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs@@ -10,10 +10,65 @@ namespace Aetheris.Kernel.Core.Tests.Step242;public sealed class Step242TessellationRobustnessTests{[Fact]- public void Step242_Tessellate_PlanarFace_AllowsMultipleLoops_UsesOuterOnly()+ public void Step242_Tessellate_PlanarFace_WithHole_PreservesHoleDeterministically(){var text = LoadFixture("testdata/step242/tessellation-robustness/planar-face-with-hole-outer-and-inner.step");+ var firstImport = Step242Importer.ImportBody(text);+ var secondImport = Step242Importer.ImportBody(text);++ Assert.True(firstImport.IsSuccess);+ Assert.True(secondImport.IsSuccess);++ var first = BrepDisplayTessellator.Tessellate(firstImport.Value);+ var second = BrepDisplayTessellator.Tessellate(secondImport.Value);++ Assert.True(first.IsSuccess);+ Assert.True(second.IsSuccess);+ Assert.DoesNotContain(first.Diagnostics, d => d.Message.Contains("requires exactly one loop", StringComparison.Ordinal));+ Assert.DoesNotContain(first.Diagnostics, d => string.Equals(d.Source, "Viewer.Tessellation.PlanarHolesIgnored", StringComparison.Ordinal));++ var firstPatch = Assert.Single(first.Value.FacePatches);+ var secondPatch = Assert.Single(second.Value.FacePatches);++ Assert.NotEmpty(firstPatch.TriangleIndices);+ Assert.Equal(firstPatch.Positions, secondPatch.Positions);+ Assert.Equal(firstPatch.TriangleIndices, secondPatch.TriangleIndices);+ Assert.All(GetTriangleCentroids(firstPatch), centroid =>+ Assert.False(IsInsideAxisAlignedRectangle(centroid, minX: 3d, minY: 3d, maxX: 7d, maxY: 7d)));+ }++ [Fact]+ public void Step242_Tessellate_BoxTopCapWithCircularHole_PreservesHoleDeterministically()+ {+ var text = LoadFixture("testdata/firmament/exports/boolean_box_cylinder_hole.step");++ var firstImport = Step242Importer.ImportBody(text);+ var secondImport = Step242Importer.ImportBody(text);++ Assert.True(firstImport.IsSuccess);+ Assert.True(secondImport.IsSuccess);++ var first = BrepDisplayTessellator.Tessellate(firstImport.Value);+ var second = BrepDisplayTessellator.Tessellate(secondImport.Value);++ Assert.True(first.IsSuccess);+ Assert.True(second.IsSuccess);++ var firstPatch = GetPlanarCapPatch(first.Value, zValue: 6d);+ var secondPatch = GetPlanarCapPatch(second.Value, zValue: 6d);++ Assert.Equal(firstPatch.Positions, secondPatch.Positions);+ Assert.Equal(firstPatch.TriangleIndices, secondPatch.TriangleIndices);+ Assert.All(GetTriangleCentroids(firstPatch), centroid =>+ Assert.True(((centroid.X * centroid.X) + (centroid.Y * centroid.Y)) >= (4d * 4d) - 1e-6d));+ }++ [Fact]+ public void Step242_Tessellate_BoxPlanarFaceWithoutHole_RemainsValid()+ {+ var text = LoadFixture("testdata/firmament/exports/box_basic.step");+var import = Step242Importer.ImportBody(text);Assert.True(import.IsSuccess);@@ -21,16 +76,34 @@ public sealed class Step242TessellationRobustnessTestsvar tessellation = BrepDisplayTessellator.Tessellate(import.Value);Assert.True(tessellation.IsSuccess);- Assert.DoesNotContain(tessellation.Diagnostics, d => d.Message.Contains("requires exactly one loop", StringComparison.Ordinal));+ Assert.Equal(6, tessellation.Value.FacePatches.Count);+ Assert.All(tessellation.Value.FacePatches, patch => Assert.NotEmpty(patch.TriangleIndices));+ }- var facePatch = Assert.Single(tessellation.Value.FacePatches);- Assert.NotEmpty(facePatch.TriangleIndices);+ [Fact]+ public void Step242_Tessellate_UnsupportedComplexPlanarMultiLoop_DoesNotFallbackToOuterLoopFill()+ {+ var text = LoadFixture("testdata/step242/nist/CTC/nist_ctc_02_asme1_ap242-e2.stp");- var warning = tessellation.Diagnostics.SingleOrDefault(d => string.Equals(d.Source, "Viewer.Tessellation.PlanarHolesIgnored", StringComparison.Ordinal));- if (warning is not null)- {- Assert.Contains("ignored", warning.Message, StringComparison.Ordinal);- }+ var import = Step242Importer.ImportBody(text);++ Assert.True(import.IsSuccess);++ var tessellation = BrepDisplayTessellator.Tessellate(import.Value);++ Assert.True(tessellation.IsSuccess);++ var diagnostics = tessellation.Diagnostics+ .Where(d => string.Equals(d.Source, "Viewer.Tessellation.PlanarMultiLoopTriangulationSkipped", StringComparison.Ordinal))+ .ToArray();+ Assert.NotEmpty(diagnostics);+ var diagnostic = Assert.Single(diagnostics, d => d.Message.Contains("Face 2 ", StringComparison.Ordinal));+ Assert.Equal(KernelDiagnosticCode.ValidationFailed, diagnostic.Code);+ Assert.Contains("skipping face patch", diagnostic.Message, StringComparison.Ordinal);++ var skippedPatch = Assert.Single(tessellation.Value.FacePatches, patch => patch.FaceId.Value == 2);+ Assert.Empty(skippedPatch.Positions);+ Assert.Empty(skippedPatch.TriangleIndices);}[Fact]@@ -242,6 +315,30 @@ public sealed class Step242TessellationRobustnessTestsreturn patches;}+ private static DisplayFaceMeshPatch GetPlanarCapPatch(DisplayTessellationResult tessellation, double zValue)+ {+ return Assert.Single(tessellation.FacePatches, patch =>+ patch.Positions.Count > 0+ && patch.Positions.All(point => double.Abs(point.Z - zValue) <= 1e-6d));+ }++ private static IEnumerable<Point3D> GetTriangleCentroids(DisplayFaceMeshPatch patch)+ {+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)+ {+ var p0 = patch.Positions[patch.TriangleIndices[i]];+ var p1 = patch.Positions[patch.TriangleIndices[i + 1]];+ var p2 = patch.Positions[patch.TriangleIndices[i + 2]];+ yield return new Point3D(+ (p0.X + p1.X + p2.X) / 3d,+ (p0.Y + p1.Y + p2.Y) / 3d,+ (p0.Z + p1.Z + p2.Z) / 3d);+ }+ }++ private static bool IsInsideAxisAlignedRectangle(Point3D point, double minX, double minY, double maxX, double maxY)+ => point.X > minX && point.X < maxX && point.Y > minY && point.Y < maxY;+private static double ComputeAngularSpan(CylinderSurface cylinder, IReadOnlyList<Point3D> positions){var axis = cylinder.Axis.ToVector();diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.csindex 30e14aae..f142ab86 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs@@ -31,6 +31,7 @@ public static class BrepDisplayTessellatorprivate const string SphereTrimTwoCoedgeBiArcLuneSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeBiArcLune";private const string SphereTrimTwoCoedgeBsplineBiArcSurrogateSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeBsplineBiArcSurrogate";private const string SphereTrimTwoCoedgeUnsupportedSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeUnsupported";+ private const string PlanarMultiLoopTriangulationSkippedSource = "Viewer.Tessellation.PlanarMultiLoopTriangulationSkipped";public static KernelResult<DisplayTessellationResult> Tessellate(BrepBody body, DisplayTessellationOptions? options = null){@@ -104,29 +105,57 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} planar tessellation requires at least one loop.")]);}- var selectedLoopId = SelectPlanarPrimaryLoop(body, faceId, plane, loopIds);- var ignoredLoopCount = System.Math.Max(0, loopIds.Count - 1);- var successDiagnostics = ignoredLoopCount > 0- ? new[] { CreateValidationWarning($"Face {faceId.Value} planar tessellation ignored {ignoredLoopCount} inner loop(s).", "Viewer.Tessellation.PlanarHolesIgnored") }- : Array.Empty<KernelDiagnostic>();+ if (loopIds.Count == 1)+ {+ var simpleLoopPoints = FlattenPlanarLoop(body, faceId, plane, options, loopIds[0]);+ if (!simpleLoopPoints.IsSuccess)+ {+ return KernelResult<DisplayFaceMeshPatch>.Failure(simpleLoopPoints.Diagnostics);+ }- var coedges = body.GetCoedgeIds(selectedLoopId)- .Select(id => body.Topology.GetCoedge(id))- .ToArray();+ return TriangulatePlanarPatch(faceId, plane, simpleLoopPoints.Value);+ }- var polygonPointsResult = BuildFlattenedPlanarLoopPoints(body, coedges, faceId, plane, options);- if (!polygonPointsResult.IsSuccess)+ var flattenedLoops = new Dictionary<LoopId, IReadOnlyList<Point3D>>();+ foreach (var loopId in loopIds.OrderBy(id => id.Value)){- return KernelResult<DisplayFaceMeshPatch>.Failure(polygonPointsResult.Diagnostics);+ var flattenedLoop = FlattenPlanarLoop(body, faceId, plane, options, loopId);+ if (!flattenedLoop.IsSuccess)+ {+ return KernelResult<DisplayFaceMeshPatch>.Failure(flattenedLoop.Diagnostics);+ }++ flattenedLoops[loopId] = flattenedLoop.Value;}- var polygonPoints = polygonPointsResult.Value;+ var outerLoopId = SelectPlanarPrimaryLoop(body, faceId, plane, loopIds);+ var outerLoop = flattenedLoops[outerLoopId];+ var holes = loopIds+ .Where(loopId => loopId != outerLoopId)+ .OrderBy(loopId => loopId.Value)+ .Select(loopId => flattenedLoops[loopId])+ .ToArray();- if (polygonPoints.Count < 3)+ if (!PlanarPolygonTriangulator.TryTriangulateWithHoles(+ outerLoop,+ holes,+ plane.Normal.ToVector(),+ out var triangulationPoints,+ out var indices,+ out var failure)){- return KernelResult<DisplayFaceMeshPatch>.Failure([CreateInvalidArgument($"Face {faceId.Value} planar loop flattening produced fewer than three unique points.", PlanarCurveFlatteningFailedSource)]);+ return KernelResult<DisplayFaceMeshPatch>.Success(+ CreateEmptyPlanarPatch(faceId),+ [CreateValidationWarning(+ $"Face {faceId.Value} planar multi-loop tessellation could not be resolved ({failure?.ToString() ?? "Unknown"}); skipping face patch to avoid misleading filled geometry.",+ PlanarMultiLoopTriangulationSkippedSource)]);}+ return KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, triangulationPoints, plane.Normal.ToVector(), indices));+ }++ private static KernelResult<DisplayFaceMeshPatch> TriangulatePlanarPatch(FaceId faceId, PlaneSurface plane, IReadOnlyList<Point3D> polygonPoints)+ {if (!PlanarPolygonTriangulator.TryTriangulate(polygonPoints, plane.Normal.ToVector(), out var indices, out var failure)){return failure switch@@ -140,7 +169,34 @@ public static class BrepDisplayTessellator};}- return KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, polygonPoints, plane.Normal.ToVector(), indices), successDiagnostics);+ return KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, polygonPoints, plane.Normal.ToVector(), indices));+ }++ private static KernelResult<IReadOnlyList<Point3D>> FlattenPlanarLoop(+ BrepBody body,+ FaceId faceId,+ PlaneSurface plane,+ DisplayTessellationOptions options,+ LoopId loopId)+ {+ var coedges = body.GetCoedgeIds(loopId)+ .Select(id => body.Topology.GetCoedge(id))+ .ToArray();++ var polygonPointsResult = BuildFlattenedPlanarLoopPoints(body, coedges, faceId, plane, options);+ if (!polygonPointsResult.IsSuccess)+ {+ return KernelResult<IReadOnlyList<Point3D>>.Failure(polygonPointsResult.Diagnostics);+ }++ var polygonPoints = polygonPointsResult.Value;+ if (polygonPoints.Count < 3)+ {+ return KernelResult<IReadOnlyList<Point3D>>.Failure([+ CreateInvalidArgument($"Face {faceId.Value} planar loop flattening produced fewer than three unique points.", PlanarCurveFlatteningFailedSource)]);+ }++ return KernelResult<IReadOnlyList<Point3D>>.Success(polygonPoints);}private static LoopId SelectPlanarPrimaryLoop(BrepBody body, FaceId faceId, PlaneSurface plane, IReadOnlyList<LoopId> loopIds)@@ -2454,6 +2510,9 @@ public static class BrepDisplayTessellatorreturn new DisplayFaceMeshPatch(faceId, polygonPoints.ToArray(), normals, triangleIndices.ToArray());}+ private static DisplayFaceMeshPatch CreateEmptyPlanarPatch(FaceId faceId)+ => new(faceId, Array.Empty<Point3D>(), Array.Empty<Vector3D>(), Array.Empty<int>());+private static KernelResult<IReadOnlyList<Point3D>> BuildFlattenedPlanarLoopPoints(BrepBody body,IReadOnlyList<Coedge> coedges,diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.csindex 0120634f..ca1bcde6 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.cs@@ -28,13 +28,12 @@ internal static class PlanarPolygonTriangulatorreturn false;}- if (!planeNormal.TryNormalize(out var normal))+ if (!TryCreateProjection(polygonPoints, planeNormal, out var projection, out failure)){- failure = PlanarPolygonTriangulationFailure.Degenerate;return false;}- var projected = ProjectToStablePlane(polygonPoints, normal);+ var projected = ProjectPoints(polygonPoints, projection);if (!ValidatePolygon(projected)){failure = PlanarPolygonTriangulationFailure.Degenerate;@@ -54,10 +53,510 @@ internal static class PlanarPolygonTriangulatorreturn false;}- var working = Enumerable.Range(0, polygonPoints.Count).ToList();- var result = new List<int>((polygonPoints.Count - 2) * 3);- var isCounterClockwise = winding > 0d;+ if (!TryEarClipSimplePolygon(projected, Enumerable.Range(0, polygonPoints.Count).ToList(), out var result))+ {+ failure = PlanarPolygonTriangulationFailure.TriangulationFailed;+ return false;+ }++ OrientTrianglesToExpectedNormal(polygonPoints, projection.Normal, result);++ indices = result;+ return true;+ }++ public static bool TryTriangulateWithHoles(+ IReadOnlyList<Point3D> outerPolygonPoints,+ IReadOnlyList<IReadOnlyList<Point3D>> holePolygonPoints,+ Vector3D planeNormal,+ out IReadOnlyList<Point3D> triangulationPoints,+ out IReadOnlyList<int> indices,+ out PlanarPolygonTriangulationFailure? failure)+ {+ triangulationPoints = Array.Empty<Point3D>();+ indices = Array.Empty<int>();+ failure = null;++ if (holePolygonPoints.Count == 0)+ {+ if (!TryTriangulate(outerPolygonPoints, planeNormal, out indices, out failure))+ {+ return false;+ }++ triangulationPoints = outerPolygonPoints.ToArray();+ return true;+ }++ if (outerPolygonPoints.Count < 3 || holePolygonPoints.Any(hole => hole.Count < 3))+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ if (!TryCreateProjection(outerPolygonPoints, planeNormal, out var projection, out failure))+ {+ return false;+ }++ var outerProjected = ProjectPoints(outerPolygonPoints, projection);+ if (!ValidatePolygon(outerProjected))+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ if (HasSelfIntersection(outerProjected))+ {+ failure = PlanarPolygonTriangulationFailure.NonSimple;+ return false;+ }++ var outerArea = SignedArea(outerProjected);+ if (double.Abs(outerArea) <= Epsilon)+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ var allPoints = new List<Point3D>();+ var allProjected = new List<Point2>();+ var outerNode = CreateLinkedRing(outerPolygonPoints, outerProjected, clockwise: false, allPoints, allProjected);+ if (outerNode is null)+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ var holeEntries = new List<HoleEntry>(holePolygonPoints.Count);+ for (var holeIndex = 0; holeIndex < holePolygonPoints.Count; holeIndex++)+ {+ var hole = holePolygonPoints[holeIndex];+ var holeProjected = ProjectPoints(hole, projection);+ if (!ValidatePolygon(holeProjected))+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ if (HasSelfIntersection(holeProjected))+ {+ failure = PlanarPolygonTriangulationFailure.NonSimple;+ return false;+ }++ var holeArea = SignedArea(holeProjected);+ if (double.Abs(holeArea) <= Epsilon)+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ var holeNode = CreateLinkedRing(hole, holeProjected, clockwise: true, allPoints, allProjected);+ if (holeNode is null)+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ holeEntries.Add(new HoleEntry(holeIndex, holeNode, SelectBridgeHoleVertex(holeNode)));+ }++ if (HoleIntersectsBoundary(outerNode, holeEntries.Select(entry => entry.RingStart).ToArray()))+ {+ failure = PlanarPolygonTriangulationFailure.NonSimple;+ return false;+ }++ foreach (var holeEntry in holeEntries+ .OrderByDescending(entry => entry.Anchor.Point.X)+ .ThenBy(entry => entry.Anchor.Point.Y)+ .ThenBy(entry => entry.Anchor.Index))+ {+ var candidate = FindDeterministicBridgeVertex(outerNode, holeEntry.Anchor, holeEntries);+ if (candidate is null)+ {+ failure = PlanarPolygonTriangulationFailure.TriangulationFailed;+ return false;+ }++ outerNode = SplitPolygon(candidate, holeEntry.Anchor, allPoints, allProjected);+ outerNode = FilterPoints(outerNode);+ if (outerNode is null)+ {+ failure = PlanarPolygonTriangulationFailure.TriangulationFailed;+ return false;+ }+ }++ outerNode = FilterPoints(outerNode);+ if (outerNode is null)+ {+ failure = PlanarPolygonTriangulationFailure.TriangulationFailed;+ return false;+ }++ if (!TryEarClipLinkedPolygon(outerNode, allProjected, out var result))+ {+ failure = PlanarPolygonTriangulationFailure.TriangulationFailed;+ return false;+ }++ OrientTrianglesToExpectedNormal(allPoints, projection.Normal, result);++ triangulationPoints = allPoints;+ indices = result;+ return true;+ }++ private static bool TryCreateProjection(+ IReadOnlyList<Point3D> polygonPoints,+ Vector3D planeNormal,+ out PlaneProjection projection,+ out PlanarPolygonTriangulationFailure? failure)+ {+ projection = default;+ failure = null;++ if (!planeNormal.TryNormalize(out var normal))+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ var referenceAxis = double.Abs(normal.Z) < 0.9d+ ? new Vector3D(0d, 0d, 1d)+ : new Vector3D(1d, 0d, 0d);++ var uAxis = referenceAxis.Cross(normal);+ if (!uAxis.TryNormalize(out uAxis))+ {+ referenceAxis = new Vector3D(0d, 1d, 0d);+ uAxis = referenceAxis.Cross(normal);+ if (!uAxis.TryNormalize(out uAxis))+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }+ }++ var vAxis = normal.Cross(uAxis);+ if (!vAxis.TryNormalize(out vAxis))+ {+ failure = PlanarPolygonTriangulationFailure.Degenerate;+ return false;+ }++ projection = new PlaneProjection(polygonPoints[0], normal, uAxis, vAxis);+ return true;+ }++ private static List<Point2> ProjectPoints(IReadOnlyList<Point3D> polygonPoints, PlaneProjection projection)+ {+ return polygonPoints+ .Select(point =>+ {+ var offset = point - projection.Origin;+ return new Point2(offset.Dot(projection.UAxis), offset.Dot(projection.VAxis));+ })+ .ToList();+ }++ private static Node? CreateLinkedRing(+ IReadOnlyList<Point3D> points3D,+ IReadOnlyList<Point2> points2D,+ bool clockwise,+ List<Point3D> allPoints,+ List<Point2> allProjected)+ {+ var signedArea = SignedArea(points2D);+ if (double.Abs(signedArea) <= Epsilon)+ {+ return null;+ }++ var shouldReverse = clockwise ? signedArea > 0d : signedArea < 0d;+ Node? last = null;++ if (shouldReverse)+ {+ for (var i = points3D.Count - 1; i >= 0; i--)+ {+ last = InsertNode(allPoints.Count, points3D[i], points2D[i], ref last, allPoints, allProjected);+ }+ }+ else+ {+ for (var i = 0; i < points3D.Count; i++)+ {+ last = InsertNode(allPoints.Count, points3D[i], points2D[i], ref last, allPoints, allProjected);+ }+ }++ return FilterPoints(last?.Next);+ }++ private static Node InsertNode(+ int index,+ Point3D point3D,+ Point2 point2D,+ ref Node? last,+ List<Point3D> allPoints,+ List<Point2> allProjected)+ {+ allPoints.Add(point3D);+ allProjected.Add(point2D);++ var node = new Node(index, point2D);+ if (last is null)+ {+ node.Prev = node;+ node.Next = node;+ }+ else+ {+ node.Next = last.Next!;+ node.Prev = last;+ last.Next!.Prev = node;+ last.Next = node;+ }++ last = node;+ return node;+ }++ private static Node SelectBridgeHoleVertex(Node start)+ {+ var best = start;+ var node = start.Next!;+ while (node != start)+ {+ if (node.Point.X > best.Point.X + Epsilon+ || (double.Abs(node.Point.X - best.Point.X) <= Epsilon && node.Point.Y < best.Point.Y - Epsilon)+ || (double.Abs(node.Point.X - best.Point.X) <= Epsilon && double.Abs(node.Point.Y - best.Point.Y) <= Epsilon && node.Index < best.Index))+ {+ best = node;+ }++ node = node.Next!;+ }+ return best;+ }++ private static bool HoleIntersectsBoundary(Node outerRing, IReadOnlyList<Node> holeStarts)+ {+ for (var i = 0; i < holeStarts.Count; i++)+ {+ if (RingIntersectsRing(outerRing, holeStarts[i]))+ {+ return true;+ }++ for (var j = i + 1; j < holeStarts.Count; j++)+ {+ if (RingIntersectsRing(holeStarts[i], holeStarts[j]))+ {+ return true;+ }+ }+ }++ return false;+ }++ private static bool RingIntersectsRing(Node first, Node second)+ {+ var a = first;+ do+ {+ var b = second;+ do+ {+ if (SegmentsIntersect(a.Point, a.Next!.Point, b.Point, b.Next!.Point)+ && !SegmentsShareEndpoint(a.Point, a.Next.Point, b.Point, b.Next.Point))+ {+ return true;+ }++ b = b.Next!;+ } while (b != second);++ a = a.Next!;+ } while (a != first);++ return false;+ }++ private static Node? FindDeterministicBridgeVertex(+ Node outerRing,+ Node holeAnchor,+ IReadOnlyList<HoleEntry> holes)+ {+ var bridgeMidpointHoles = holes+ .Where(entry => entry.Anchor != holeAnchor)+ .Select(entry => entry.RingStart)+ .ToArray();++ Node? best = null;+ var bestScore = (DistanceSquared: double.PositiveInfinity, X: double.PositiveInfinity, Y: double.PositiveInfinity, Index: int.MaxValue);++ var candidate = outerRing;+ do+ {+ if (IsBridgeVisible(candidate, holeAnchor, outerRing, holeAnchor, bridgeMidpointHoles))+ {+ var score = (+ DistanceSquared(holeAnchor.Point, candidate.Point),+ candidate.Point.X,+ candidate.Point.Y,+ candidate.Index);++ if (score.CompareTo(bestScore) < 0)+ {+ best = candidate;+ bestScore = score;+ }+ }++ candidate = candidate.Next!;+ } while (candidate != outerRing);++ return best;+ }++ private static bool IsBridgeVisible(+ Node outerCandidate,+ Node holeAnchor,+ Node outerRing,+ Node currentHoleRing,+ IReadOnlyList<Node> otherHoleRings)+ {+ if (PointsAlmostEqual(outerCandidate.Point, holeAnchor.Point))+ {+ return false;+ }++ if (!BridgeClearsRing(outerCandidate, holeAnchor, outerRing))+ {+ return false;+ }++ if (!BridgeClearsRing(outerCandidate, holeAnchor, currentHoleRing))+ {+ return false;+ }++ for (var i = 0; i < otherHoleRings.Count; i++)+ {+ if (!BridgeClearsRing(outerCandidate, holeAnchor, otherHoleRings[i]))+ {+ return false;+ }+ }++ return true;+ }++ private static bool BridgeClearsRing(Node outerCandidate, Node holeAnchor, Node ringStart)+ {+ var edge = ringStart;+ do+ {+ var edgeStart = edge.Point;+ var edgeEnd = edge.Next!.Point;+ if (SegmentsIntersect(outerCandidate.Point, holeAnchor.Point, edgeStart, edgeEnd)+ && !SegmentsShareEndpoint(outerCandidate.Point, holeAnchor.Point, edgeStart, edgeEnd))+ {+ return false;+ }++ edge = edge.Next!;+ } while (edge != ringStart);++ return true;+ }++ private static Node SplitPolygon(Node outerCandidate, Node holeAnchor, List<Point3D> allPoints, List<Point2> allProjected)+ {+ var outerCandidateCopy = CreateDuplicateNode(outerCandidate, allPoints, allProjected);+ var holeAnchorCopy = CreateDuplicateNode(holeAnchor, allPoints, allProjected);+ var outerNext = outerCandidate.Next!;+ var holePrev = holeAnchor.Prev!;++ outerCandidate.Next = holeAnchor;+ holeAnchor.Prev = outerCandidate;++ outerCandidateCopy.Next = outerNext;+ outerNext.Prev = outerCandidateCopy;++ holeAnchorCopy.Next = outerCandidateCopy;+ outerCandidateCopy.Prev = holeAnchorCopy;++ holePrev.Next = holeAnchorCopy;+ holeAnchorCopy.Prev = holePrev;++ return outerCandidateCopy;+ }++ private static Node CreateDuplicateNode(Node source, List<Point3D> allPoints, List<Point2> allProjected)+ {+ var index = allPoints.Count;+ allPoints.Add(allPoints[source.Index]);+ allProjected.Add(allProjected[source.Index]);+ return new Node(index, source.Point);+ }++ private static Node? FilterPoints(Node? start)+ {+ if (start is null)+ {+ return null;+ }++ var node = start;+ var changed = false;+ do+ {+ changed = false;++ if (PointsAlmostEqual(node.Point, node.Next!.Point))+ {+ RemoveNode(node);+ node = node.Prev!;+ changed = true;+ }+ else if (double.Abs(Orientation(node.Prev!.Point, node.Point, node.Next.Point)) <= Epsilon)+ {+ RemoveNode(node);+ node = node.Prev!;+ changed = true;+ }+ else+ {+ node = node.Next!;+ }+ } while (changed || node != start);++ return node;+ }++ private static void RemoveNode(Node node)+ {+ node.Next!.Prev = node.Prev;+ node.Prev!.Next = node.Next;+ }++ private static bool TryEarClipSimplePolygon(IReadOnlyList<Point2> projected, List<int> working, out List<int> result)+ {+ result = new List<int>((working.Count - 2) * 3);+ var winding = SignedArea(working.Select(index => projected[index]).ToArray());+ if (double.Abs(winding) <= Epsilon)+ {+ return false;+ }++ var isCounterClockwise = winding > 0d;while (working.Count > 3){var earFound = false;@@ -103,7 +602,6 @@ internal static class PlanarPolygonTriangulatorif (!earFound){- failure = PlanarPolygonTriangulationFailure.TriangulationFailed;return false;}}@@ -111,50 +609,112 @@ internal static class PlanarPolygonTriangulatorresult.Add(working[0]);result.Add(working[1]);result.Add(working[2]);+ return true;+ }- var expectedNormal = normal;- if (result.Count >= 3)+ private static bool TryEarClipLinkedPolygon(Node start, IReadOnlyList<Point2> allProjected, out List<int> result)+ {+ result = new List<int>();+ var vertexCount = CountNodes(start);+ if (vertexCount < 3){- var firstNormal = (polygonPoints[result[1]] - polygonPoints[result[0]])- .Cross(polygonPoints[result[2]] - polygonPoints[result[0]]);- if (firstNormal.Dot(expectedNormal) < 0d)+ return false;+ }++ result.Capacity = (vertexCount - 2) * 3;+ var current = start;+ var remaining = vertexCount;+ var iterationsWithoutEar = 0;++ while (remaining > 3)+ {+ if (IsEar(current, start, allProjected)){- for (var i = 0; i < result.Count; i += 3)- {- (result[i + 1], result[i + 2]) = (result[i + 2], result[i + 1]);- }+ result.Add(current.Prev!.Index);+ result.Add(current.Index);+ result.Add(current.Next!.Index);++ RemoveNode(current);+ current = current.Next!;+ start = current;+ remaining--;+ iterationsWithoutEar = 0;+ continue;+ }++ current = current.Next!;+ iterationsWithoutEar++;+ if (iterationsWithoutEar > remaining)+ {+ return false;}}- indices = result;+ result.Add(current.Prev!.Index);+ result.Add(current.Index);+ result.Add(current.Next!.Index);return true;}- private static List<Point2> ProjectToStablePlane(IReadOnlyList<Point3D> polygonPoints, Vector3D normal)+ private static int CountNodes(Node start){- var referenceAxis = double.Abs(normal.Z) < 0.9d- ? new Vector3D(0d, 0d, 1d)- : new Vector3D(1d, 0d, 0d);+ var count = 0;+ var node = start;+ do+ {+ count++;+ node = node.Next!;+ } while (node != start);- var uAxis = referenceAxis.Cross(normal);- if (!uAxis.TryNormalize(out uAxis))+ return count;+ }++ private static bool IsEar(Node node, Node polygonStart, IReadOnlyList<Point2> allProjected)+ {+ var a = node.Prev!;+ var b = node;+ var c = node.Next!;+ if (Orientation(a.Point, b.Point, c.Point) <= Epsilon){- referenceAxis = new Vector3D(0d, 1d, 0d);- uAxis = referenceAxis.Cross(normal);- uAxis.TryNormalize(out uAxis);+ return false;}- var vAxis = normal.Cross(uAxis);- vAxis.TryNormalize(out vAxis);- var origin = polygonPoints[0];+ var candidate = c.Next!;+ while (candidate != a)+ {+ if (candidate != b+ && candidate != node.Prev+ && candidate != node.Next+ && PointInTriangleStrict(candidate.Point, a.Point, b.Point, c.Point))+ {+ return false;+ }- return polygonPoints- .Select(point =>+ candidate = candidate.Next!;+ }++ return true;+ }++ private static void OrientTrianglesToExpectedNormal(+ IReadOnlyList<Point3D> polygonPoints,+ Vector3D expectedNormal,+ List<int> result)+ {+ if (result.Count < 3)+ {+ return;+ }++ var firstNormal = (polygonPoints[result[1]] - polygonPoints[result[0]])+ .Cross(polygonPoints[result[2]] - polygonPoints[result[0]]);+ if (firstNormal.Dot(expectedNormal) < 0d)+ {+ for (var i = 0; i < result.Count; i += 3){- var offset = point - origin;- return new Point2(offset.Dot(uAxis), offset.Dot(vAxis));- })- .ToList();+ (result[i + 1], result[i + 2]) = (result[i + 2], result[i + 1]);+ }+ }}private static bool ValidatePolygon(IReadOnlyList<Point2> points)@@ -197,6 +757,7 @@ internal static class PlanarPolygonTriangulatorreturn false;}+private static bool SegmentsIntersect(Point2 a0, Point2 a1, Point2 b0, Point2 b1){var o1 = Orientation(a0, a1, b0);@@ -216,6 +777,12 @@ internal static class PlanarPolygonTriangulatorreturn false;}+ private static bool SegmentsShareEndpoint(Point2 a0, Point2 a1, Point2 b0, Point2 b1)+ => PointsAlmostEqual(a0, b0)+ || PointsAlmostEqual(a0, b1)+ || PointsAlmostEqual(a1, b0)+ || PointsAlmostEqual(a1, b1);+private static bool IsConvex(Point2 a, Point2 b, Point2 c, bool isCounterClockwise){var cross = Orientation(a, b, c);@@ -233,6 +800,17 @@ internal static class PlanarPolygonTriangulatorreturn !(hasNeg && hasPos);}+ private static bool PointInTriangleStrict(Point2 p, Point2 a, Point2 b, Point2 c)+ {+ var o1 = Orientation(a, b, p);+ var o2 = Orientation(b, c, p);+ var o3 = Orientation(c, a, p);++ var allPositive = o1 > Epsilon && o2 > Epsilon && o3 > Epsilon;+ var allNegative = o1 < -Epsilon && o2 < -Epsilon && o3 < -Epsilon;+ return allPositive || allNegative;+ }+private static double SignedArea(IReadOnlyList<Point2> points){var area = 0d;@@ -255,6 +833,9 @@ internal static class PlanarPolygonTriangulator&& p.Y >= double.Min(a.Y, b.Y) - Epsilon&& p.Y <= double.Max(a.Y, b.Y) + Epsilon;+ private static bool PointsAlmostEqual(Point2 a, Point2 b)+ => DistanceSquared(a, b) <= Epsilon * Epsilon;+private static double DistanceSquared(Point2 a, Point2 b){var dx = a.X - b.X;@@ -262,5 +843,20 @@ internal static class PlanarPolygonTriangulatorreturn (dx * dx) + (dy * dy);}+ private readonly record struct PlaneProjection(Point3D Origin, Vector3D Normal, Vector3D UAxis, Vector3D VAxis);++ private sealed class Node(int index, Point2 point)+ {+ public int Index { get; } = index;++ public Point2 Point { get; } = point;++ public Node? Prev { get; set; }++ public Node? Next { get; set; }+ }++ private readonly record struct HoleEntry(int Order, Node RingStart, Node Anchor);+private readonly record struct Point2(double X, double Y);}