Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add bounded B-spline face trim-mask extraction for scaffold lane
Yuechen Li802ae6ca71b5
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayPreparationFallbackBuilderTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayPreparationFallbackBuilderTests.csindex 56648b24..7c5e77f0 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayPreparationFallbackBuilderTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayPreparationFallbackBuilderTests.cs@@ -1,6 +1,5 @@using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Tessellation;-using Aetheris.Kernel.Core.Step242;namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;@@ -9,7 +8,7 @@ public sealed class DisplayPreparationFallbackBuilderTests[Fact]public void Build_SingleFaceBsplineBody_UsesAcceptedScaffoldPatch(){- var body = ImportRepresentativeBsplineBody();+ var body = UvTrimMaskExtractorTests.ImportSingleLoopBsplineBody();var result = DisplayPreparationFallbackBuilder.Build(body);@@ -22,7 +21,7 @@ public sealed class DisplayPreparationFallbackBuilderTests[Fact]public void Build_StrictScaffoldThreshold_RejectedAndFallsBackToTessellator(){- var body = ImportRepresentativeBsplineBody();+ var body = UvTrimMaskExtractorTests.ImportSingleLoopBsplineBody();var result = DisplayPreparationFallbackBuilder.Build(body,@@ -54,10 +53,31 @@ public sealed class DisplayPreparationFallbackBuilderTests});}+ [Fact]+ public void Build_UnsupportedTrimExtraction_FallsBackDeterministically()+ {+ var body = UvTrimMaskExtractorTests.CreateBodyWithMissingVertexPoint(UvTrimMaskExtractorTests.ImportSingleLoopBsplineBody());++ var first = DisplayPreparationFallbackBuilder.Build(body);+ var second = DisplayPreparationFallbackBuilder.Build(body);++ Assert.True(first.IsSuccess);+ Assert.True(second.IsSuccess);++ var firstPatch = Assert.Single(first.Value.FacePatches);+ var secondPatch = Assert.Single(second.Value.FacePatches);++ Assert.Equal(DisplayFaceMeshSource.Tessellator, firstPatch.Source);+ Assert.Equal("TrimMaskExtraction:MissingVertexPoint", firstPatch.ScaffoldRejectionReason);+ Assert.Equal(firstPatch.Source, secondPatch.Source);+ Assert.Equal(firstPatch.ScaffoldRejectionReason, secondPatch.ScaffoldRejectionReason);+ Assert.Equal(CreateSignature(first.Value), CreateSignature(second.Value));+ }+[Fact]public void Build_AcceptedScaffoldCase_IsDeterministic(){- var body = ImportRepresentativeBsplineBody();+ var body = UvTrimMaskExtractorTests.ImportSingleLoopBsplineBody();var first = DisplayPreparationFallbackBuilder.Build(body);var second = DisplayPreparationFallbackBuilder.Build(body);@@ -72,12 +92,4 @@ public sealed class DisplayPreparationFallbackBuilderTests"|",result.FacePatches.Select(patch =>$"{patch.FaceId.Value}:{patch.Source}:{patch.ScaffoldRejectionReason}:{patch.Positions.Count}:{patch.TriangleIndices.Count}:{string.Join(',', patch.TriangleIndices.Take(24))}"));-- private static BrepBody ImportRepresentativeBsplineBody()- {- const string text = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=MANIFOLD_SOLID_BREP('s',#2);\n#2=CLOSED_SHELL($,(#3));\n#3=ADVANCED_FACE((#4),#5,.T.);\n#4=FACE_OUTER_BOUND($,#6,.T.);\n#5=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,((#100,#101,#102,#103),(#104,#105,#106,#107),(#108,#109,#110,#111),(#112,#113,#114,#115)),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n#6=EDGE_LOOP($,(#10,#11,#12,#13));\n#10=ORIENTED_EDGE($,$,$,#20,.T.);\n#11=ORIENTED_EDGE($,$,$,#21,.T.);\n#12=ORIENTED_EDGE($,$,$,#22,.T.);\n#13=ORIENTED_EDGE($,$,$,#23,.T.);\n#20=EDGE_CURVE($,#30,#31,#40,.T.);\n#21=EDGE_CURVE($,#31,#32,#41,.T.);\n#22=EDGE_CURVE($,#32,#33,#42,.T.);\n#23=EDGE_CURVE($,#33,#30,#43,.T.);\n#30=VERTEX_POINT($,#50);\n#31=VERTEX_POINT($,#51);\n#32=VERTEX_POINT($,#52);\n#33=VERTEX_POINT($,#53);\n#40=LINE($,#50,#80);\n#41=LINE($,#51,#81);\n#42=LINE($,#52,#82);\n#43=LINE($,#53,#83);\n#50=CARTESIAN_POINT($,(0,0,0));\n#51=CARTESIAN_POINT($,(1,0,0));\n#52=CARTESIAN_POINT($,(1,1,0));\n#53=CARTESIAN_POINT($,(0,1,0));\n#80=VECTOR($,#84,1.0);\n#81=VECTOR($,#85,1.0);\n#82=VECTOR($,#86,1.0);\n#83=VECTOR($,#87,1.0);\n#84=DIRECTION($,(1,0,0));\n#85=DIRECTION($,(0,1,0));\n#86=DIRECTION($,(-1,0,0));\n#87=DIRECTION($,(0,-1,0));\n#100=CARTESIAN_POINT($,(0,0,0));\n#101=CARTESIAN_POINT($,(0,0.33,0));\n#102=CARTESIAN_POINT($,(0,0.66,0));\n#103=CARTESIAN_POINT($,(0,1,0));\n#104=CARTESIAN_POINT($,(0.33,0,0));\n#105=CARTESIAN_POINT($,(0.33,0.33,0));\n#106=CARTESIAN_POINT($,(0.33,0.66,0));\n#107=CARTESIAN_POINT($,(0.33,1,0));\n#108=CARTESIAN_POINT($,(0.66,0,0));\n#109=CARTESIAN_POINT($,(0.66,0.33,0));\n#110=CARTESIAN_POINT($,(0.66,0.66,0));\n#111=CARTESIAN_POINT($,(0.66,1,0));\n#112=CARTESIAN_POINT($,(1,0,0));\n#113=CARTESIAN_POINT($,(1,0.33,0));\n#114=CARTESIAN_POINT($,(1,0.66,0));\n#115=CARTESIAN_POINT($,(1,1,0));\nENDSEC;\nEND-ISO-10303-21;";- var import = Step242Importer.ImportBody(text);- Assert.True(import.IsSuccess);- return import.Value;- }}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/UvTrimMaskExtractorTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/UvTrimMaskExtractorTests.csnew file mode 100644index 00000000..c2bce5a2--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/UvTrimMaskExtractorTests.cs@@ -0,0 +1,153 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;++public sealed class UvTrimMaskExtractorTests+{+ [Fact]+ public void TryExtract_RealBsplineFace_BuildsDeterministicTrimMaskAndSupportsScaffold()+ {+ var body = ImportSingleLoopBsplineBody();+ var face = Assert.Single(body.Topology.Faces);+ Assert.True(body.TryGetFaceSurfaceGeometry(face.Id, out var surface));+ var bspline = surface?.BSplineSurfaceWithKnots;+ Assert.NotNull(bspline);++ var extractor = new UvTrimMaskExtractor();+ var first = extractor.TryExtract(body, face.Id, bspline!);+ var second = extractor.TryExtract(body, face.Id, bspline!);++ Assert.True(first.IsSuccess);+ Assert.True(second.IsSuccess);+ Assert.NotNull(first.TrimMask);+ Assert.NotNull(second.TrimMask);+ Assert.Equal(first.TrimMask!.OuterLoop, second.TrimMask!.OuterLoop);++ var fallback = DisplayPreparationFallbackBuilder.Build(body);+ Assert.True(fallback.IsSuccess);+ var existingPatch = Assert.Single(fallback.Value.FacePatches);++ var builder = new BsplineUvGridScaffoldBuilder();+ var scaffold = builder.Build(+ bspline!,+ new BsplineUvGridScaffoldBuildRequest(+ USegments: 12,+ VSegments: 12,+ TrimMask: first.TrimMask,+ ReferencePositions: existingPatch.Positions,+ ReferenceTriangleCount: existingPatch.TriangleIndices.Count / 3,+ Acceptance: BsplineUvGridScaffoldAcceptanceThresholds.ConservativeDefaults));++ Assert.Equal(BsplineUvGridScaffoldAcceptance.Accepted, scaffold.Acceptance);+ Assert.Equal(BsplineUvGridScaffoldRejectionReason.None, scaffold.RejectionReason);+ }++ [Fact]+ public void TryExtract_BsplineFaceWithUnsupportedTrimEdge_IsExplicitlyUnsupported()+ {+ var body = CreateBodyWithUnsupportedTrimEdge(ImportSingleLoopBsplineBody());+ var face = Assert.Single(body.Topology.Faces);+ Assert.True(body.TryGetFaceSurfaceGeometry(face.Id, out var surface));+ var bspline = surface?.BSplineSurfaceWithKnots;+ Assert.NotNull(bspline);++ var extractor = new UvTrimMaskExtractor();+ var result = extractor.TryExtract(body, face.Id, bspline!);++ Assert.False(result.IsSuccess);+ Assert.Equal(UvTrimMaskExtractionFailureReason.UnsupportedEdgeGeometry, result.FailureReason);+ Assert.Null(result.TrimMask);+ }++ internal static BrepBody ImportSingleLoopBsplineBody()+ {+ const string text = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=MANIFOLD_SOLID_BREP('s',#2);\n#2=CLOSED_SHELL($,(#3));\n#3=ADVANCED_FACE((#4),#5,.T.);\n#4=FACE_OUTER_BOUND($,#6,.T.);\n#5=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,((#100,#101,#102,#103),(#104,#105,#106,#107),(#108,#109,#110,#111),(#112,#113,#114,#115)),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n#6=EDGE_LOOP($,(#10,#11,#12,#13));\n#10=ORIENTED_EDGE($,$,$,#20,.T.);\n#11=ORIENTED_EDGE($,$,$,#21,.T.);\n#12=ORIENTED_EDGE($,$,$,#22,.T.);\n#13=ORIENTED_EDGE($,$,$,#23,.T.);\n#20=EDGE_CURVE($,#30,#31,#40,.T.);\n#21=EDGE_CURVE($,#31,#32,#41,.T.);\n#22=EDGE_CURVE($,#32,#33,#42,.T.);\n#23=EDGE_CURVE($,#33,#30,#43,.T.);\n#30=VERTEX_POINT($,#50);\n#31=VERTEX_POINT($,#51);\n#32=VERTEX_POINT($,#52);\n#33=VERTEX_POINT($,#53);\n#40=LINE($,#50,#80);\n#41=LINE($,#51,#81);\n#42=LINE($,#52,#82);\n#43=LINE($,#53,#83);\n#50=CARTESIAN_POINT($,(0,0,0));\n#51=CARTESIAN_POINT($,(1,0,0));\n#52=CARTESIAN_POINT($,(1,1,0));\n#53=CARTESIAN_POINT($,(0,1,0));\n#80=VECTOR($,#84,1.0);\n#81=VECTOR($,#85,1.0);\n#82=VECTOR($,#86,1.0);\n#83=VECTOR($,#87,1.0);\n#84=DIRECTION($,(1,0,0));\n#85=DIRECTION($,(0,1,0));\n#86=DIRECTION($,(-1,0,0));\n#87=DIRECTION($,(0,-1,0));\n#100=CARTESIAN_POINT($,(0,0,0));\n#101=CARTESIAN_POINT($,(0,0.33,0));\n#102=CARTESIAN_POINT($,(0,0.66,0));\n#103=CARTESIAN_POINT($,(0,1,0));\n#104=CARTESIAN_POINT($,(0.33,0,0));\n#105=CARTESIAN_POINT($,(0.33,0.33,0));\n#106=CARTESIAN_POINT($,(0.33,0.66,0));\n#107=CARTESIAN_POINT($,(0.33,1,0));\n#108=CARTESIAN_POINT($,(0.66,0,0));\n#109=CARTESIAN_POINT($,(0.66,0.33,0));\n#110=CARTESIAN_POINT($,(0.66,0.66,0));\n#111=CARTESIAN_POINT($,(0.66,1,0));\n#112=CARTESIAN_POINT($,(1,0,0));\n#113=CARTESIAN_POINT($,(1,0.33,0));\n#114=CARTESIAN_POINT($,(1,0.66,0));\n#115=CARTESIAN_POINT($,(1,1,0));\nENDSEC;\nEND-ISO-10303-21;";+ var import = Step242Importer.ImportBody(text);+ Assert.True(import.IsSuccess);+ return import.Value;+ }++ internal static BrepBody CreateBodyWithMissingVertexPoint(BrepBody source)+ {+ var geometry = new BrepGeometryStore();+ foreach (var (id, curve) in source.Geometry.Curves)+ {+ geometry.AddCurve(id, curve);+ }++ foreach (var (id, surface) in source.Geometry.Surfaces)+ {+ geometry.AddSurface(id, surface);+ }++ var bindings = new BrepBindingModel();+ foreach (var edgeBinding in source.Bindings.EdgeBindings)+ {+ bindings.AddEdgeBinding(edgeBinding);+ }++ foreach (var faceBinding in source.Bindings.FaceBindings)+ {+ bindings.AddFaceBinding(faceBinding);+ }++ var removedVertexId = source.Topology.Vertices.OrderBy(vertex => vertex.Id.Value).First().Id;+ var vertexPoints = source.Topology.Vertices+ .Where(vertex => vertex.Id != removedVertexId && source.TryGetVertexPoint(vertex.Id, out _))+ .ToDictionary(vertex => vertex.Id, vertex =>+ {+ source.TryGetVertexPoint(vertex.Id, out var point);+ return point;+ });++ return new BrepBody(source.Topology, geometry, bindings, vertexPoints, source.SafeBooleanComposition, source.ShellRepresentation);+ }++ internal static BrepBody CreateBodyWithUnsupportedTrimEdge(BrepBody source)+ {+ var geometry = new BrepGeometryStore();+ foreach (var (id, curve) in source.Geometry.Curves)+ {+ geometry.AddCurve(id, curve);+ }++ foreach (var (id, surface) in source.Geometry.Surfaces)+ {+ geometry.AddSurface(id, surface);+ }++ var bindings = new BrepBindingModel();+ var firstEdgeId = source.Topology.Edges.OrderBy(edge => edge.Id.Value).First().Id;+ foreach (var edgeBinding in source.Bindings.EdgeBindings)+ {+ if (edgeBinding.EdgeId == firstEdgeId)+ {+ bindings.AddEdgeBinding(edgeBinding with { CurveGeometryId = new CurveGeometryId(999_001) });+ }+ else+ {+ bindings.AddEdgeBinding(edgeBinding);+ }+ }++ foreach (var faceBinding in source.Bindings.FaceBindings)+ {+ bindings.AddFaceBinding(faceBinding);+ }++ geometry.AddCurve(new CurveGeometryId(999_001), CurveGeometry.FromUnsupported("unsupported-trim-edge"));++ var vertexPoints = source.Topology.Vertices+ .Where(vertex => source.TryGetVertexPoint(vertex.Id, out _))+ .ToDictionary(vertex => vertex.Id, vertex =>+ {+ source.TryGetVertexPoint(vertex.Id, out var point);+ return point;+ });++ return new BrepBody(source.Topology, geometry, bindings, vertexPoints, source.SafeBooleanComposition, source.ShellRepresentation);+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.csindex 551b1436..a17a8202 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs@@ -26,6 +26,7 @@ public static class DisplayPreparationFallbackBuildervar effectiveScaffoldOptions = scaffoldOptions ?? DisplayPreparationBsplineScaffoldOptions.ConservativeDefaults;var fallbackByFace = tessellation.Value.FacePatches.ToDictionary(patch => patch.FaceId);var scaffoldBuilder = new BsplineUvGridScaffoldBuilder();+ var trimMaskExtractor = new UvTrimMaskExtractor();foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value)){@@ -44,10 +45,21 @@ public static class DisplayPreparationFallbackBuildercontinue;}+ var trimMaskResult = trimMaskExtractor.TryExtract(body, face.Id, bspline);+ if (!trimMaskResult.IsSuccess || trimMaskResult.TrimMask is null)+ {+ fallbackByFace[face.Id] = existingPatch with+ {+ Source = DisplayFaceMeshSource.Tessellator,+ ScaffoldRejectionReason = $"TrimMaskExtraction:{trimMaskResult.FailureReason}",+ };+ continue;+ }+var request = new BsplineUvGridScaffoldBuildRequest(effectiveScaffoldOptions.USegments,effectiveScaffoldOptions.VSegments,- TrimMask: null,+ TrimMask: trimMaskResult.TrimMask,ReferencePositions: existingPatch.Positions,ReferenceTriangleCount: existingPatch.TriangleIndices.Count / 3,Acceptance: effectiveScaffoldOptions.Acceptance);@@ -90,7 +102,7 @@ public static class DisplayPreparationFallbackBuilder}var loopIds = body.GetLoopIds(faceId);- return loopIds.Count == 1;+ return loopIds.Count >= 1 && loopIds.Count <= 2;}private static IReadOnlyList<Vector3D> ComputeVertexNormals(IReadOnlyList<Point3D> positions, IReadOnlyList<int> triangleIndices)diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/UvTrimMaskExtractor.cs b/Aetheris.Kernel.Core/Brep/Tessellation/UvTrimMaskExtractor.csnew file mode 100644index 00000000..41106cf3--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Tessellation/UvTrimMaskExtractor.cs@@ -0,0 +1,232 @@+using Aetheris.Kernel.Core.Brep;+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 sealed class UvTrimMaskExtractor+{+ internal UvTrimMaskExtractionResult TryExtract(BrepBody body, FaceId faceId, BSplineSurfaceWithKnots surface)+ {+ var loopIds = body.GetLoopIds(faceId).OrderBy(id => id.Value).ToArray();+ if (loopIds.Length != 1)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.UnsupportedLoopTopology);+ }++ var loopVertices = new List<(LoopId LoopId, IReadOnlyList<UvPoint> Vertices)>(loopIds.Length);+ foreach (var loopId in loopIds)+ {+ var loop = body.Topology.GetLoop(loopId);+ if (loop.CoedgeIds.Count < 3)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.InsufficientLoopVertices);+ }++ var uvLoop = new List<UvPoint>(loop.CoedgeIds.Count);+ foreach (var coedgeId in loop.CoedgeIds)+ {+ var coedge = body.Topology.GetCoedge(coedgeId);+ if (!body.Topology.TryGetEdge(coedge.EdgeId, out var edge) || edge is null)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.MissingTopology);+ }++ if (!body.TryGetEdgeCurveGeometry(coedge.EdgeId, out var curve) || curve is null)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.MissingEdgeGeometry);+ }++ if (curve.Kind != CurveGeometryKind.Line3)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.UnsupportedEdgeGeometry);+ }++ var vertexId = coedge.IsReversed ? edge.EndVertexId : edge.StartVertexId;+ if (!body.TryGetVertexPoint(vertexId, out var point))+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.MissingVertexPoint);+ }++ var uv = TryProjectPointToBSplineUv(surface, point);+ if (!uv.HasValue)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.UvProjectionFailed);+ }++ AppendUniqueUvPoint(uvLoop, new UvPoint(uv.Value.U, uv.Value.V));+ }++ if (uvLoop.Count > 1 && UvPointsAlmostEqual(uvLoop[0], uvLoop[^1]))+ {+ uvLoop.RemoveAt(uvLoop.Count - 1);+ }++ if (uvLoop.Count < 3)+ {+ return UvTrimMaskExtractionResult.Unsupported(UvTrimMaskExtractionFailureReason.InsufficientLoopVertices);+ }++ loopVertices.Add((loopId, uvLoop));+ }++ var orderedByArea = loopVertices+ .OrderByDescending(entry => double.Abs(ComputeSignedArea(entry.Vertices)))+ .ThenBy(entry => entry.LoopId.Value)+ .ToArray();+ var outerLoop = orderedByArea[0].Vertices;+ var innerLoops = orderedByArea.Skip(1).Select(loop => loop.Vertices).ToArray();++ return UvTrimMaskExtractionResult.Success(new UvTrimMask(outerLoop, innerLoops));+ }++ private static void AppendUniqueUvPoint(List<UvPoint> points, UvPoint point)+ {+ if (points.Count == 0 || !UvPointsAlmostEqual(points[^1], point))+ {+ points.Add(point);+ }+ }++ private static bool UvPointsAlmostEqual(UvPoint left, UvPoint right)+ => double.Abs(left.U - right.U) <= 1e-9d+ && double.Abs(left.V - right.V) <= 1e-9d;++ private static double ComputeSignedArea(IReadOnlyList<UvPoint> loop)+ {+ var area = 0d;+ for (var i = 0; i < loop.Count; i++)+ {+ var current = loop[i];+ var next = loop[(i + 1) % loop.Count];+ area += (current.U * next.V) - (next.U * current.V);+ }++ return area * 0.5d;+ }++ private static (double U, double V)? TryProjectPointToBSplineUv(BSplineSurfaceWithKnots surface, Point3D point)+ {+ var uStart = surface.DomainStartU;+ var uEnd = surface.DomainEndU;+ var vStart = surface.DomainStartV;+ var vEnd = surface.DomainEndV;++ const int coarseSegments = 10;+ var bestU = uStart;+ var bestV = vStart;+ var bestDistanceSquared = double.PositiveInfinity;++ for (var iu = 0; iu <= coarseSegments; iu++)+ {+ var tu = (double)iu / coarseSegments;+ var u = uStart + ((uEnd - uStart) * tu);+ for (var iv = 0; iv <= coarseSegments; iv++)+ {+ var tv = (double)iv / coarseSegments;+ var v = vStart + ((vEnd - vStart) * tv);+ var sample = surface.Evaluate(u, v);+ var delta = sample - point;+ var distanceSquared = delta.Dot(delta);+ if (distanceSquared < bestDistanceSquared)+ {+ bestDistanceSquared = distanceSquared;+ bestU = u;+ bestV = v;+ }+ }+ }++ var uStep = (uEnd - uStart) / coarseSegments;+ var vStep = (vEnd - vStart) / coarseSegments;++ for (var iteration = 0; iteration < 6; iteration++)+ {+ var nextUStep = uStep * 0.5d;+ var nextVStep = vStep * 0.5d;+ var localBestU = bestU;+ var localBestV = bestV;+ var localBestDistance = bestDistanceSquared;++ for (var du = -1; du <= 1; du++)+ {+ var u = System.Math.Clamp(bestU + (du * uStep), uStart, uEnd);+ for (var dv = -1; dv <= 1; dv++)+ {+ var v = System.Math.Clamp(bestV + (dv * vStep), vStart, vEnd);+ var sample = surface.Evaluate(u, v);+ var delta = sample - point;+ var distanceSquared = delta.Dot(delta);+ if (distanceSquared < localBestDistance)+ {+ localBestDistance = distanceSquared;+ localBestU = u;+ localBestV = v;+ }+ }+ }++ bestU = localBestU;+ bestV = localBestV;+ bestDistanceSquared = localBestDistance;+ uStep = nextUStep;+ vStep = nextVStep;+ }++ var bestSample = surface.Evaluate(bestU, bestV);+ var residual = bestSample - point;+ var residualDistance = System.Math.Sqrt(residual.Dot(residual));+ var tolerance = ComputeBSplineProjectionTolerance(surface);+ if (residualDistance > tolerance)+ {+ return null;+ }++ return (bestU, bestV);+ }++ private static double ComputeBSplineProjectionTolerance(BSplineSurfaceWithKnots surface)+ {+ var points = surface.ControlPoints.SelectMany(row => row).ToArray();+ if (points.Length == 0)+ {+ return 1e-4d;+ }++ var minX = points.Min(point => point.X);+ var minY = points.Min(point => point.Y);+ var minZ = points.Min(point => point.Z);+ var maxX = points.Max(point => point.X);+ var maxY = points.Max(point => point.Y);+ var maxZ = points.Max(point => point.Z);+ var diagonal = new Vector3D(maxX - minX, maxY - minY, maxZ - minZ).Length;+ return System.Math.Max(1e-5d, diagonal * 1e-4d);+ }+}++internal enum UvTrimMaskExtractionFailureReason+{+ None = 0,+ UnsupportedLoopTopology,+ UnsupportedEdgeGeometry,+ MissingEdgeGeometry,+ MissingVertexPoint,+ MissingTopology,+ UvProjectionFailed,+ InsufficientLoopVertices,+}++internal sealed record UvTrimMaskExtractionResult(+ bool IsSuccess,+ UvTrimMask? TrimMask,+ UvTrimMaskExtractionFailureReason FailureReason)+{+ internal static UvTrimMaskExtractionResult Success(UvTrimMask trimMask)+ => new(true, trimMask, UvTrimMaskExtractionFailureReason.None);++ internal static UvTrimMaskExtractionResult Unsupported(UvTrimMaskExtractionFailureReason reason)+ => new(false, null, reason);+}