Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
fixed internal gear
Yuechen Li0cfd551f47ed
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242CircleTrimTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242CircleTrimTests.csnew file mode 100644index 00000000..ea1a1eba--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242CircleTrimTests.cs@@ -0,0 +1,50 @@+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242CircleTrimTests+{+ private static Circle3Curve CircleAt(double radius)+ => new(Point3D.Origin, Direction3D.Create(new Vector3D(0d, 0d, 1d)), radius, Direction3D.Create(new Vector3D(1d, 0d, 0d)));++ private static Point3D OnCircle(double radius, double angle)+ => new(radius * double.Cos(angle), radius * double.Sin(angle), 0d);++ [Theory]+ [InlineData(25d, 0.011d)]+ [InlineData(25d, 0.002d)]+ [InlineData(100d, 0.004d)]+ public void ShortArcOnLargeCircle_IsNotTreatedAsFullCircle(double radius, double arcAngle)+ {+ // Gear-tooth sub-arcs: the chord (~0.27 mm) is well above the linear trim tolerance, but the arc angle is+ // smaller than that tolerance expressed as a raw number. It must not collapse into a 0..2pi trim.+ var trim = Step242Importer.ComputeCircleTrim(CircleAt(radius), OnCircle(radius, 0d), OnCircle(radius, arcAngle), edgeSameSense: true);++ Assert.True(trim.IsSuccess);+ Assert.Equal(arcAngle, trim.Value.End - trim.Value.Start, 6);+ }++ [Fact]+ public void ClosedCircle_StartsAtItsSeamVertex()+ {+ var seam = OnCircle(35d, double.Pi);++ var trim = Step242Importer.ComputeCircleTrim(CircleAt(35d), seam, seam, edgeSameSense: true);++ Assert.True(trim.IsSuccess);+ Assert.Equal(2d * double.Pi, trim.Value.End - trim.Value.Start, 9);+ Assert.Equal(double.Pi, trim.Value.Start, 9);+ }++ [Fact]+ public void ClosedCircle_WithSeamAtParameterOrigin_KeepsCanonicalTrim()+ {+ var trim = Step242Importer.ComputeCircleTrim(CircleAt(35d), OnCircle(35d, 0d), OnCircle(35d, 0d), edgeSameSense: true);++ Assert.True(trim.IsSuccess);+ Assert.Equal(0d, trim.Value.Start, 9);+ Assert.Equal(2d * double.Pi, trim.Value.End, 9);+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.csindex 57e54e58..10554ae3 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs@@ -928,7 +928,7 @@ public static class BrepDisplayTessellatorbody,faceId,loopIds,- point => TryProjectPointToBSplineUv(surface, point),+ new BSplineUvProjector(surface).Project,options,executionBudget,SurfaceGeometryKind.BSplineSurfaceWithKnots);@@ -956,114 +956,175 @@ public static class BrepDisplayTessellatorSurfaceGeometryKind.BSplineSurfaceWithKnots);}- private static (double U, double V)? TryProjectPointToBSplineUv(BSplineSurfaceWithKnots surface, Point3D point)+ /// <summary>+ /// Projects 3D loop samples onto a B-spline surface. One instance serves all samples of a face: the coarse seed+ /// grid is evaluated once, and consecutive samples along a trim loop are near each other, so each projection first+ /// refines from the previous result and only falls back to the grid search when that fails.+ /// </summary>+ private sealed class BSplineUvProjector{- var uStart = surface.DomainStartU;- var uEnd = surface.DomainEndU;- var vStart = surface.DomainStartV;- var vEnd = surface.DomainEndV;-- // Coarse grid seed. Scale with the control net so long, thin or heavily curved patches- // (e.g. gear tooth flanks) still seed inside the correct basin.- var controlRows = surface.ControlPoints.Count;- var controlColumns = controlRows > 0 ? surface.ControlPoints[0].Count : 0;- var coarseSegments = System.Math.Clamp(System.Math.Max(controlRows, controlColumns) * 4, 16, 32);- var bestU = uStart;- var bestV = vStart;- var bestDistanceSquared = double.PositiveInfinity;-- for (var iu = 0; iu <= coarseSegments; iu++)- {- var u = uStart + ((uEnd - uStart) * iu / coarseSegments);- for (var iv = 0; iv <= coarseSegments; iv++)+ private readonly BSplineSurfaceWithKnots _surface;+ private readonly int _coarseSegments;+ private readonly double _tolerance;+ private Point3D[]? _grid;+ private (double U, double V)? _last;++ public BSplineUvProjector(BSplineSurfaceWithKnots surface)+ {+ _surface = surface;+ // Coarse grid seed. Scale with the control net so long, thin or heavily curved patches+ // (e.g. gear tooth flanks) still seed inside the correct basin.+ var controlRows = surface.ControlPoints.Count;+ var controlColumns = controlRows > 0 ? surface.ControlPoints[0].Count : 0;+ _coarseSegments = System.Math.Clamp(System.Math.Max(controlRows, controlColumns) * 4, 16, 32);+ _tolerance = ComputeBSplineProjectionTolerance(surface);+ }++ public (double U, double V)? Project(Point3D point)+ {+ if (_last is { } seed){- var v = vStart + ((vEnd - vStart) * iv / coarseSegments);- var delta = surface.Evaluate(u, v) - point;- var distanceSquared = delta.Dot(delta);- if (distanceSquared < bestDistanceSquared)+ var warm = Refine(seed.U, seed.V, point);+ if (warm.HasValue){- bestDistanceSquared = distanceSquared;- bestU = u;- bestV = v;+ _last = warm;+ return warm;}}++ var cold = SeedFromGrid(point);+ var result = Refine(cold.U, cold.V, point);+ if (result.HasValue)+ {+ _last = result;+ }++ return result;}- // Levenberg-Marquardt refinement of |S(u,v) - P|^2, clamped to the surface domain. The previous- // fixed 6-step pattern search only resolved ~1/640 of the domain, which left residuals above the- // acceptance tolerance for perfectly valid boundary samples and dropped whole faces.- var uSpan = uEnd - uStart;- var vSpan = vEnd - vStart;- var lambda = 1e-3d;- var done = false;- for (var iteration = 0; iteration < 60 && !done; iteration++)- {- var uPlus = System.Math.Min(bestU + (uSpan * 1e-6d), uEnd);- var uMinus = System.Math.Max(bestU - (uSpan * 1e-6d), uStart);- var vPlus = System.Math.Min(bestV + (vSpan * 1e-6d), vEnd);- var vMinus = System.Math.Max(bestV - (vSpan * 1e-6d), vStart);- if (uPlus - uMinus <= 0d || vPlus - vMinus <= 0d)+ private (double U, double V) SeedFromGrid(Point3D point)+ {+ var surface = _surface;+ var n = _coarseSegments;+ var uStart = surface.DomainStartU;+ var vStart = surface.DomainStartV;+ var uStep = (surface.DomainEndU - uStart) / n;+ var vStep = (surface.DomainEndV - vStart) / n;+ if (_grid is null){- break;+ var grid = new Point3D[(n + 1) * (n + 1)];+ for (var iu = 0; iu <= n; iu++)+ {+ for (var iv = 0; iv <= n; iv++)+ {+ grid[(iu * (n + 1)) + iv] = surface.Evaluate(uStart + (uStep * iu), vStart + (vStep * iv));+ }+ }++ _grid = grid;}- var tangentU = (surface.Evaluate(uPlus, bestV) - surface.Evaluate(uMinus, bestV)) * (1d / (uPlus - uMinus));- var tangentV = (surface.Evaluate(bestU, vPlus) - surface.Evaluate(bestU, vMinus)) * (1d / (vPlus - vMinus));- var residualVector = surface.Evaluate(bestU, bestV) - point;- var a11 = tangentU.Dot(tangentU);- var a12 = tangentU.Dot(tangentV);- var a22 = tangentV.Dot(tangentV);- var b1 = -tangentU.Dot(residualVector);- var b2 = -tangentV.Dot(residualVector);-- var accepted = false;- for (var attempt = 0; attempt < 10 && !accepted; attempt++)+ var bestU = uStart;+ var bestV = vStart;+ var bestDistanceSquared = double.PositiveInfinity;+ for (var iu = 0; iu <= n; iu++){- var m11 = (a11 * (1d + lambda)) + 1e-30d;- var m22 = (a22 * (1d + lambda)) + 1e-30d;- var determinant = (m11 * m22) - (a12 * a12);- if (!(System.Math.Abs(determinant) > 1e-300d))+ for (var iv = 0; iv <= n; iv++){- lambda *= 10d;- continue;+ var delta = _grid[(iu * (n + 1)) + iv] - point;+ var distanceSquared = delta.Dot(delta);+ if (distanceSquared < bestDistanceSquared)+ {+ bestDistanceSquared = distanceSquared;+ bestU = uStart + (uStep * iu);+ bestV = vStart + (vStep * iv);+ }}+ }- var stepU = ((b1 * m22) - (a12 * b2)) / determinant;- var stepV = ((m11 * b2) - (a12 * b1)) / determinant;- var candidateU = System.Math.Clamp(bestU + stepU, uStart, uEnd);- var candidateV = System.Math.Clamp(bestV + stepV, vStart, vEnd);- var candidateDelta = surface.Evaluate(candidateU, candidateV) - point;- var candidateDistanceSquared = candidateDelta.Dot(candidateDelta);- if (candidateDistanceSquared < bestDistanceSquared)+ return (bestU, bestV);+ }++ // Levenberg-Marquardt refinement of |S(u,v) - P|^2, clamped to the surface domain. The previous+ // fixed 6-step pattern search only resolved ~1/640 of the domain, which left residuals above the+ // acceptance tolerance for perfectly valid boundary samples and dropped whole faces.+ private (double U, double V)? Refine(double startU, double startV, Point3D point)+ {+ var surface = _surface;+ var uStart = surface.DomainStartU;+ var uEnd = surface.DomainEndU;+ var vStart = surface.DomainStartV;+ var vEnd = surface.DomainEndV;+ var uSpan = uEnd - uStart;+ var vSpan = vEnd - vStart;+ var bestU = startU;+ var bestV = startV;+ var startDelta = surface.Evaluate(bestU, bestV) - point;+ var bestDistanceSquared = startDelta.Dot(startDelta);+ var lambda = 1e-3d;+ var done = false;+ for (var iteration = 0; iteration < 60 && !done; iteration++)+ {+ var uPlus = System.Math.Min(bestU + (uSpan * 1e-6d), uEnd);+ var uMinus = System.Math.Max(bestU - (uSpan * 1e-6d), uStart);+ var vPlus = System.Math.Min(bestV + (vSpan * 1e-6d), vEnd);+ var vMinus = System.Math.Max(bestV - (vSpan * 1e-6d), vStart);+ if (uPlus - uMinus <= 0d || vPlus - vMinus <= 0d){- done = System.Math.Abs(candidateU - bestU) <= uSpan * 1e-13d- && System.Math.Abs(candidateV - bestV) <= vSpan * 1e-13d;- bestU = candidateU;- bestV = candidateV;- bestDistanceSquared = candidateDistanceSquared;- lambda = System.Math.Max(lambda * 0.3d, 1e-12d);- accepted = true;+ break;}- else++ var tangentU = (surface.Evaluate(uPlus, bestV) - surface.Evaluate(uMinus, bestV)) * (1d / (uPlus - uMinus));+ var tangentV = (surface.Evaluate(bestU, vPlus) - surface.Evaluate(bestU, vMinus)) * (1d / (vPlus - vMinus));+ var residualVector = surface.Evaluate(bestU, bestV) - point;+ var a11 = tangentU.Dot(tangentU);+ var a12 = tangentU.Dot(tangentV);+ var a22 = tangentV.Dot(tangentV);+ var b1 = -tangentU.Dot(residualVector);+ var b2 = -tangentV.Dot(residualVector);++ var accepted = false;+ for (var attempt = 0; attempt < 10 && !accepted; attempt++){- lambda *= 10d;+ var m11 = (a11 * (1d + lambda)) + 1e-30d;+ var m22 = (a22 * (1d + lambda)) + 1e-30d;+ var determinant = (m11 * m22) - (a12 * a12);+ if (!(System.Math.Abs(determinant) > 1e-300d))+ {+ lambda *= 10d;+ continue;+ }++ var stepU = ((b1 * m22) - (a12 * b2)) / determinant;+ var stepV = ((m11 * b2) - (a12 * b1)) / determinant;+ var candidateU = System.Math.Clamp(bestU + stepU, uStart, uEnd);+ var candidateV = System.Math.Clamp(bestV + stepV, vStart, vEnd);+ var candidateDelta = surface.Evaluate(candidateU, candidateV) - point;+ var candidateDistanceSquared = candidateDelta.Dot(candidateDelta);+ if (candidateDistanceSquared < bestDistanceSquared)+ {+ done = System.Math.Abs(candidateU - bestU) <= uSpan * 1e-13d+ && System.Math.Abs(candidateV - bestV) <= vSpan * 1e-13d;+ bestU = candidateU;+ bestV = candidateV;+ bestDistanceSquared = candidateDistanceSquared;+ lambda = System.Math.Max(lambda * 0.3d, 1e-12d);+ accepted = true;+ }+ else+ {+ lambda *= 10d;+ }}- }- if (!accepted)- {- break;+ if (!accepted)+ {+ break;+ }}- }- var residualDistance = System.Math.Sqrt(bestDistanceSquared);- var tolerance = ComputeBSplineProjectionTolerance(surface);- if (residualDistance > tolerance)- {- return null;+ return System.Math.Sqrt(bestDistanceSquared) > _tolerance ? null : (bestU, bestV);}-- return (bestU, bestV);}private static KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>> TryBuildDoublyPeriodicTrimmedSurfaceUvLoops(diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 41500389..e99c5f3b 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -1572,11 +1572,20 @@ public static class Step242Importerreturn System.Math.Max(1e-6d, scale * 1e-8d);}- private static KernelResult<ParameterInterval> ComputeCircleTrim(Circle3Curve circle, Point3D startPoint, Point3D endPoint, bool edgeSameSense)+ internal static KernelResult<ParameterInterval> ComputeCircleTrim(Circle3Curve circle, Point3D startPoint, Point3D endPoint, bool edgeSameSense){var tolerance = ComputeCircleTrimTolerance(circle, startPoint, endPoint);if ((startPoint - endPoint).Length <= tolerance){+ // A closed circular edge starts wherever its vertex sits (CAD exporters frequently put the seam+ // vertex away from the circle's parameter origin), so the full-circle trim must begin at that angle or+ // the curve's trim endpoints no longer coincide with the edge's vertices.+ var seamAngle = ProjectPointToCircleAngle(circle, startPoint, tolerance);+ if (seamAngle.IsSuccess && seamAngle.Value > 1e-9d && seamAngle.Value < (2d * double.Pi) - 1e-9d)+ {+ return KernelResult<ParameterInterval>.Success(new ParameterInterval(seamAngle.Value, seamAngle.Value + (2d * double.Pi)));+ }+return KernelResult<ParameterInterval>.Success(new ParameterInterval(0d, 2d * double.Pi));}@@ -1592,7 +1601,10 @@ public static class Step242Importerreturn KernelResult<ParameterInterval>.Failure(endAngleResult.Diagnostics);}- var intervalResult = CanonicalizeCircleTrimInterval(startAngleResult.Value, endAngleResult.Value, tolerance, edgeSameSense);+ // The tolerance is a linear distance. Coincident endpoints were already treated as a full circle above, so the+ // angular threshold for "empty" or "full" spans must be that distance divided by the radius; using the raw+ // linear value made every arc shorter than ~0.0123 rad on a 25 mm circle (gear-tooth sub-arcs) look like a full circle.+ var intervalResult = CanonicalizeCircleTrimInterval(startAngleResult.Value, endAngleResult.Value, tolerance / double.Max(circle.Radius, tolerance), edgeSameSense);if (!intervalResult.IsSuccess){return KernelResult<ParameterInterval>.Failure(intervalResult.Diagnostics);