Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Recover rational STEP B-spline circles

Yuechen Li4309082b1984
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs
new file mode 100644
index 00000000..175919d5
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs
@@ -0,0 +1,126 @@
+using Aetheris.Kernel.Core.Geometry;
+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 Step242RationalBSplineCurveRecoveryTests
+{
+ [Fact]
+ public void RecoversRationalQuadraticCircleAsCircle3()
+ {
+ var curve = CreateQuarterCircleSpline(System.Math.Sqrt(0.5d));
+ var decision = Step242BsplineCurveRecoveryLane.Decide(CreateRationalCurveEntity(), curve, [1d, System.Math.Sqrt(0.5d), 1d]);
+
+ Assert.Equal(Step242BsplineCurveRecoveryLane.AnalyticCircleCandidate, decision.CandidateName);
+ Assert.NotNull(decision.RecoveredCurve);
+ Assert.Equal(CurveGeometryKind.Circle3, decision.RecoveredCurve!.Kind);
+ Assert.Equal(1d, decision.RecoveredCurve.Circle3!.Value.Radius, 6);
+ AssertNear(Point3D.Origin, decision.RecoveredCurve.Circle3.Value.Center, 1e-6d);
+ }
+
+ [Fact]
+ public void DoesNotIgnoreRationalWeights()
+ {
+ const double weight = 0.939858145324778d;
+ var angle = 2d * System.Math.Acos(weight);
+ var curve = new BSpline3Curve(
+ 2,
+ [new Point3D(1d, 0d, 0d), new Point3D(1d, System.Math.Tan(angle / 2d), 0d), new Point3D(System.Math.Cos(angle), System.Math.Sin(angle), 0d)],
+ [3, 3],
+ [0d, 1d],
+ "CIRCULAR_ARC",
+ false,
+ false,
+ "UNSPECIFIED");
+
+ var rationalMid = Step242BsplineCurveRecoveryLane.EvaluateRational(curve, [1d, weight, 1d], 0.5d);
+ var unweightedMid = curve.Evaluate(0.5d);
+ Assert.NotNull(rationalMid);
+ Assert.InRange(System.Math.Abs((rationalMid.Value - Point3D.Origin).Length - 1d), 0d, 1e-12d);
+ Assert.True(System.Math.Abs((unweightedMid - Point3D.Origin).Length - 1d) > 1e-3d);
+
+ var decision = Step242BsplineCurveRecoveryLane.Decide(CreateRationalCurveEntity(), curve, [1d, weight, 1d]);
+ Assert.Equal(CurveGeometryKind.Circle3, decision.RecoveredCurve!.Kind);
+ }
+
+ [Fact]
+ public void RejectsRationalNonCircle()
+ {
+ var curve = new BSpline3Curve(
+ 2,
+ [new Point3D(0d, 0d, 0d), new Point3D(0.3d, 0.9d, 0.2d), new Point3D(1d, 0d, 0d), new Point3D(1.5d, 0.4d, 0.6d)],
+ [3, 1, 3],
+ [0d, 0.5d, 1d],
+ "UNSPECIFIED",
+ false,
+ false,
+ "UNSPECIFIED");
+
+ var decision = Step242BsplineCurveRecoveryLane.Decide(CreateRationalCurveEntity(), curve, [1d, 0.8d, 1.2d, 1d]);
+
+ Assert.Equal(Step242BsplineCurveRecoveryLane.RejectCandidate, decision.CandidateName);
+ Assert.Null(decision.RecoveredCurve);
+ Assert.Contains("step242-rational-bspline-circle", decision.Reason, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void LeavesNonRationalBSplineUnchanged()
+ {
+ var curve = CreateQuarterCircleSpline(System.Math.Sqrt(0.5d));
+ var decision = Step242BsplineCurveRecoveryLane.Decide(CreateNonRationalCurveEntity(), curve, [1d, System.Math.Sqrt(0.5d), 1d]);
+
+ Assert.Equal(Step242BsplineCurveRecoveryLane.RejectCandidate, decision.CandidateName);
+ Assert.Null(decision.RecoveredCurve);
+ Assert.Contains("not a rational", decision.Reason, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void PlainCircleImportStillWorks()
+ {
+ var text = """
+ISO-10303-21;
+HEADER;
+ENDSEC;
+DATA;
+#1=CARTESIAN_POINT('',(0.,0.,0.));
+#2=DIRECTION('',(0.,0.,1.));
+#3=DIRECTION('',(1.,0.,0.));
+#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);
+#5=CIRCLE('',#4,2.5);
+ENDSEC;
+END-ISO-10303-21;
+""";
+ var parse = Step242SubsetParser.Parse(text);
+ Assert.True(parse.IsSuccess);
+ var circle = Step242SubsetDecoder.ReadCircleCurve(parse.Value, parse.Value.TryGetEntity(5).Value);
+ Assert.True(circle.IsSuccess);
+ Assert.Equal(2.5d, circle.Value.Radius, 6);
+ }
+
+ private static BSpline3Curve CreateQuarterCircleSpline(double middleWeight) => new(
+ 2,
+ [new Point3D(1d, 0d, 0d), new Point3D(1d, 1d, 0d), new Point3D(0d, 1d, 0d)],
+ [3, 3],
+ [0d, 1d],
+ "CIRCULAR_ARC",
+ false,
+ false,
+ "UNSPECIFIED");
+
+ private static Step242ParsedEntity CreateRationalCurveEntity() => new(
+ 1,
+ new Step242ComplexEntityInstance([
+ new Step242EntityConstructor("B_SPLINE_CURVE_WITH_KNOTS", []),
+ new Step242EntityConstructor("RATIONAL_B_SPLINE_CURVE", [new Step242ListValue([])])]));
+
+ private static Step242ParsedEntity CreateNonRationalCurveEntity() => new(
+ 1,
+ new Step242SimpleEntityInstance(new Step242EntityConstructor("B_SPLINE_CURVE_WITH_KNOTS", [])));
+
+ private static void AssertNear(Point3D expected, Point3D actual, double tolerance)
+ {
+ Assert.InRange((actual - expected).Length, 0d, tolerance);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs b/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs
new file mode 100644
index 00000000..f71b2246
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs
@@ -0,0 +1,195 @@
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Judgment;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Kernel.Core.Step242;
+
+internal static class Step242BsplineCurveRecoveryLane
+{
+ internal const string AnalyticCircleCandidate = "analytic_circle";
+ internal const string RejectCandidate = "reject";
+ private const double FitTolerance = 1e-6d;
+ private const double DegenerateTolerance = 1e-10d;
+
+ internal readonly record struct RecoveryDecision(string CandidateName, CurveGeometry? RecoveredCurve, string Reason);
+
+ public static RecoveryDecision Decide(Step242ParsedEntity sourceEntity, BSpline3Curve curve, IReadOnlyList<double> weights)
+ {
+ var probe = ProbeCircleRecovery(curve, weights);
+ var context = new RecoveryContext(
+ IsRationalLike: Step242SubsetDecoder.TryGetConstructor(sourceEntity.Instance, "RATIONAL_B_SPLINE_CURVE") is not null,
+ CircleProbe: probe);
+
+ var engine = new JudgmentEngine<RecoveryContext>();
+ var judgment = engine.Evaluate(context, BuildCandidates());
+ if (!judgment.IsSuccess || !judgment.Selection.HasValue)
+ {
+ var reason = judgment.Rejections.Count == 0
+ ? "step242-rational-bspline-circle-rejected: no bounded analytic recovery candidate was admissible."
+ : string.Join(" ", judgment.Rejections.Select(r => $"{r.CandidateName}: {r.Reason}."));
+ return new RecoveryDecision(RejectCandidate, null, reason);
+ }
+
+ if (string.Equals(judgment.Selection.Value.Candidate.Name, AnalyticCircleCandidate, StringComparison.Ordinal)
+ && context.CircleProbe.Circle.HasValue)
+ {
+ return new RecoveryDecision(
+ AnalyticCircleCandidate,
+ CurveGeometry.FromCircle(context.CircleProbe.Circle.Value),
+ "step242-rational-bspline-circle-recovered: recovered analytic circle from rational B-spline curve.");
+ }
+
+ var rejectReason = context.IsRationalLike
+ ? context.CircleProbe.Reason
+ : "step242-rational-bspline-circle-rejected: curve is not a rational B-spline representation.";
+ return new RecoveryDecision(RejectCandidate, null, rejectReason);
+ }
+
+ private static IReadOnlyList<JudgmentCandidate<RecoveryContext>> BuildCandidates() =>
+ [
+ new JudgmentCandidate<RecoveryContext>(
+ Name: AnalyticCircleCandidate,
+ IsAdmissible: When.All<RecoveryContext>(
+ context => context.IsRationalLike,
+ context => context.CircleProbe.Circle.HasValue),
+ Score: _ => 100d,
+ RejectionReason: context => context.IsRationalLike
+ ? context.CircleProbe.Reason
+ : "step242-rational-bspline-circle-rejected: curve is not a rational B-spline representation.",
+ TieBreakerPriority: 0),
+ new JudgmentCandidate<RecoveryContext>(
+ Name: RejectCandidate,
+ IsAdmissible: _ => true,
+ Score: _ => -1d,
+ RejectionReason: context => context.CircleProbe.Reason,
+ TieBreakerPriority: 1)
+ ];
+
+ private static CircleProbe ProbeCircleRecovery(BSpline3Curve curve, IReadOnlyList<double> weights)
+ {
+ if (weights.Count == 0) return new CircleProbe(null, "step242-rational-bspline-weights-missing: rational curve has no weights.");
+ if (weights.Count != curve.ControlPoints.Count) return new CircleProbe(null, "step242-rational-bspline-circle-rejected: weight count does not match control point count.");
+ if (curve.Degree != 2) return new CircleProbe(null, "step242-rational-bspline-unsupported-degree: only rational quadratic circle recovery is bounded.");
+ if (weights.Any(w => !double.IsFinite(w) || w <= DegenerateTolerance)) return new CircleProbe(null, "step242-rational-bspline-circle-rejected: rational weights must be positive finite values.");
+
+ var samples = new List<Point3D>();
+ const int sampleCount = 9;
+ for (var i = 0; i < sampleCount; i++)
+ {
+ var t = i / (double)(sampleCount - 1);
+ var u = curve.DomainStart + ((curve.DomainEnd - curve.DomainStart) * t);
+ var sample = EvaluateRational(curve, weights, u);
+ if (!sample.HasValue) return new CircleProbe(null, "step242-rational-bspline-circle-rejected: rational evaluation produced a degenerate denominator.");
+ samples.Add(sample.Value);
+ }
+
+ if (!TryFitCircle(samples, out var circle, out var reason)) return new CircleProbe(null, reason);
+
+ foreach (var sample in samples)
+ {
+ var planeResidual = double.Abs((sample - circle.Center).Dot(circle.Normal.ToVector()));
+ var radiusResidual = double.Abs((sample - circle.Center).Length - circle.Radius);
+ if (planeResidual > FitTolerance || radiusResidual > FitTolerance)
+ {
+ return new CircleProbe(null, "step242-rational-bspline-circle-fit-residual-exceeded: sampled rational curve does not remain on the recovered circle.");
+ }
+ }
+
+ return new CircleProbe(circle, "step242-rational-bspline-circle-recovered: bounded rational quadratic samples fit a circle.");
+ }
+
+ internal static Point3D? EvaluateRational(BSpline3Curve curve, IReadOnlyList<double> weights, double parameter)
+ {
+ var p = curve.Degree;
+ var u = double.Min(double.Max(parameter, curve.DomainStart), curve.DomainEnd);
+ if (double.Abs(u - curve.DomainEnd) <= 1e-12d) return curve.ControlPoints[^1];
+ var span = FindSpan(curve, u);
+ var points = new (double X, double Y, double Z, double W)[p + 1];
+ for (var j = 0; j <= p; j++)
+ {
+ var index = span - p + j;
+ var w = weights[index];
+ var cp = curve.ControlPoints[index];
+ points[j] = (cp.X * w, cp.Y * w, cp.Z * w, w);
+ }
+
+ for (var r = 1; r <= p; r++)
+ {
+ for (var j = p; j >= r; j--)
+ {
+ var leftKnot = curve.FullKnots[span - p + j];
+ var rightKnot = curve.FullKnots[span + 1 + j - r];
+ var denominator = rightKnot - leftKnot;
+ var alpha = double.Abs(denominator) <= 1e-15d ? 0d : (u - leftKnot) / denominator;
+ points[j] = Lerp(points[j - 1], points[j], alpha);
+ }
+ }
+
+ if (double.Abs(points[p].W) <= DegenerateTolerance) return null;
+ return new Point3D(points[p].X / points[p].W, points[p].Y / points[p].W, points[p].Z / points[p].W);
+ }
+
+ private static bool TryFitCircle(IReadOnlyList<Point3D> samples, out Circle3Curve circle, out string reason)
+ {
+ circle = default;
+ var p0 = samples[0];
+ var p1 = samples[samples.Count / 2];
+ var p2 = samples[^1];
+ var a = p1 - p0;
+ var b = p2 - p0;
+ var normalVector = a.Cross(b);
+ if (!Direction3D.TryCreate(normalVector, out var normal))
+ {
+ reason = "step242-rational-bspline-circle-rejected: sampled rational curve is collinear or degenerate.";
+ return false;
+ }
+
+ var aa = a.Dot(a);
+ var ab = a.Dot(b);
+ var bb = b.Dot(b);
+ var determinant = (aa * bb) - (ab * ab);
+ if (determinant <= DegenerateTolerance)
+ {
+ reason = "step242-rational-bspline-circle-rejected: sampled rational curve cannot define a stable circle.";
+ return false;
+ }
+
+ var rhsA = aa * 0.5d;
+ var rhsB = bb * 0.5d;
+ var x = ((rhsA * bb) - (rhsB * ab)) / determinant;
+ var y = ((aa * rhsB) - (ab * rhsA)) / determinant;
+ var center = p0 + (a * x) + (b * y);
+ var radius = (p0 - center).Length;
+ if (!double.IsFinite(radius) || radius <= DegenerateTolerance || !Direction3D.TryCreate(p0 - center, out var xAxis))
+ {
+ reason = "step242-rational-bspline-circle-rejected: recovered circle radius/reference axis is degenerate.";
+ return false;
+ }
+
+ circle = new Circle3Curve(center, normal, radius, xAxis);
+ reason = string.Empty;
+ return true;
+ }
+
+ private static int FindSpan(BSpline3Curve curve, double u)
+ {
+ var n = curve.ControlPoints.Count - 1;
+ if (u >= curve.FullKnots[n + 1]) return n;
+ var low = curve.Degree;
+ var high = n + 1;
+ var mid = (low + high) / 2;
+ while (u < curve.FullKnots[mid] || u >= curve.FullKnots[mid + 1])
+ {
+ if (u < curve.FullKnots[mid]) high = mid; else low = mid;
+ mid = (low + high) / 2;
+ }
+ return mid;
+ }
+
+ private static (double X, double Y, double Z, double W) Lerp((double X, double Y, double Z, double W) a, (double X, double Y, double Z, double W) b, double t) =>
+ (a.X + ((b.X - a.X) * t), a.Y + ((b.Y - a.Y) * t), a.Z + ((b.Z - a.Z) * t), a.W + ((b.W - a.W) * t));
+
+ private readonly record struct RecoveryContext(bool IsRationalLike, CircleProbe CircleProbe);
+ private readonly record struct CircleProbe(Circle3Curve? Circle, string Reason);
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index ec9b1c30..c3c4fb9e 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -828,6 +828,43 @@ public static class Step242Importer
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(splineResult.Diagnostics);
}
+ var rationalConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "RATIONAL_B_SPLINE_CURVE");
+ if (rationalConstructor is not null)
+ {
+ var rationalEntity = WithConstructor(curveEntity, rationalConstructor);
+ var weightsResult = Step242SubsetDecoder.ReadRationalBSplineCurveWeights(rationalEntity);
+ if (!weightsResult.IsSuccess)
+ {
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(weightsResult.Diagnostics);
+ }
+
+ var hasMaterialRationalWeights = weightsResult.Value.Any(w => double.IsFinite(w) && double.Abs(w - 1d) > 1e-12d);
+ if (splineResult.Value.Degree != 2 || !hasMaterialRationalWeights)
+ {
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
+ CurveGeometry.FromBSpline(splineResult.Value),
+ new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd)));
+ }
+
+ var recoveryDecision = Step242BsplineCurveRecoveryLane.Decide(curveEntity, splineResult.Value, weightsResult.Value);
+ if (recoveryDecision.RecoveredCurve is CurveGeometry recoveredCurve)
+ {
+ var trimResult = recoveredCurve.Kind == CurveGeometryKind.Circle3 && recoveredCurve.Circle3 is Circle3Curve recoveredCircle
+ ? ComputeCircleTrim(recoveredCircle, startPoint, endPoint, edgeSameSense)
+ : KernelResult<ParameterInterval>.Success(new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd));
+ if (!trimResult.IsSuccess)
+ {
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
+ }
+
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((recoveredCurve, trimResult.Value));
+ }
+
+ return FailureCurveBinding(
+ $"RATIONAL_B_SPLINE_CURVE is unsupported unless it recovers as an analytic circle. {recoveryDecision.Reason}",
+ SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineCurve"));
+ }
+
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromBSpline(splineResult.Value),
new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd)));
diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs
index 130f22d9..10137c84 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs
@@ -1018,6 +1018,9 @@ internal static class Step242SubsetDecoder
return KernelResult<IReadOnlyList<int>>.Success(ints);
}
+ internal static KernelResult<IReadOnlyList<double>> ReadRationalBSplineCurveWeights(Step242ParsedEntity rationalCurveEntity) =>
+ ReadNumberListArgument(rationalCurveEntity, 0, "RATIONAL_B_SPLINE_CURVE weights_data", "Importer.Geometry.RationalBSplineCurve");
+
private static KernelResult<IReadOnlyList<double>> ReadNumberListArgument(
Step242ParsedEntity entity,
int argumentIndex,
diff --git a/docs/step242-rational-bspline-circle-recovery.md b/docs/step242-rational-bspline-circle-recovery.md
new file mode 100644
index 00000000..f539c766
--- /dev/null
+++ b/docs/step242-rational-bspline-circle-recovery.md
@@ -0,0 +1,33 @@
+# STEP AP242 rational B-spline circle recovery
+
+## Bug summary
+
+Some STEP producers encode exact circular trim curves as complex B-spline entities that combine `B_SPLINE_CURVE_WITH_KNOTS` with a sibling `RATIONAL_B_SPLINE_CURVE`. The previous curve import path only decoded the non-rational B-spline constructor, so the rational weights were ignored and exact circular arcs could display as visibly bulged or faceted spline trims on toroidal/fillet-like geometry.
+
+## Why weights matter
+
+A rational quadratic B-spline represents a circular arc by weighting its middle control point. Treating the same poles as an ordinary unweighted quadratic changes the evaluated curve and moves sampled points off the intended circle. The STEP importer now reads the sibling `RATIONAL_B_SPLINE_CURVE` weights before allowing the bounded rational quadratic recovery path to decide whether the curve is an analytic circle.
+
+## Recovery policy
+
+Aetheris still does not expose a general `RationalBSpline3`/NURBS curve primitive. The importer instead follows the existing analytic-recovery precedent from `Step242BsplineSurfaceRecoveryLane`: detect the rational STEP encoding, evaluate the rational curve in the recovery lane, fit and verify an analytic primitive, and recover only when the bounded analytic interpretation is admissible.
+
+`Step242BsplineCurveRecoveryLane` currently supports rational quadratic circle/arc recovery. It samples the rational curve over the knot domain, fits a common plane and circle through representative samples, and verifies sampled plane/radius residuals against tolerance before returning `Circle3Curve`.
+
+## Diagnostics and limits
+
+Stable reason strings include:
+
+- `step242-rational-bspline-circle-recovered`
+- `step242-rational-bspline-circle-rejected`
+- `step242-rational-bspline-weights-missing`
+- `step242-rational-bspline-unsupported-degree`
+- `step242-rational-bspline-circle-fit-residual-exceeded`
+
+Known limits:
+
+- No public/kernel rational NURBS curve representation is added.
+- Non-rational B-spline import remains on the existing `BSpline3Curve` path.
+- Plain STEP `CIRCLE` import remains unchanged.
+- STEP export behavior is unchanged.
+- Firmament V2, AIR Region behavior, and broad BRep topology behavior are not changed.
diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.json
index 5b00ded7..d91fdeef 100644
--- a/testdata/step242/manifests/nist.v0.report.json
+++ b/testdata/step242/manifests/nist.v0.report.json
@@ -117,7 +117,7 @@
"edges": 476,
"faces": 187
},
- "canonicalSha256": "4c9eee2cc02bff8f4a0eb27f69651214a773d03acab2ed5322cc396ada0592ae"
+ "canonicalSha256": "3968552736ab6306796684e11d43bcca64d596b5ccee24d507d00556210d2ddf"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_07_asme1_ap242-e2",