Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Stabilize STEP242 vertex resolution and validate with .NET tests

Yuechen Li939b1d7c334b
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterSolidWorksValidityTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterSolidWorksValidityTests.cs
new file mode 100644
index 00000000..98ed3315
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterSolidWorksValidityTests.cs
@@ -0,0 +1,205 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242ExporterSolidWorksValidityTests
+{
+ private const double Tolerance = 1e-6;
+
+ [Fact]
+ public void ExportBody_Box_ProducesLineEdgeCurvesWithEndpointsOnLineAndCoherentVertexReuse()
+ {
+ var box = BrepPrimitives.CreateBox(4d, 6d, 8d);
+ Assert.True(box.IsSuccess);
+
+ var step = Step242Exporter.ExportBody(box.Value);
+ Assert.True(step.IsSuccess);
+
+ var graph = Parse(step.Value);
+
+ foreach (var edge in graph.EdgeCurves)
+ {
+ if (!graph.Lines.TryGetValue(edge.CurveId, out var line))
+ {
+ continue;
+ }
+
+ var startPoint = graph.ResolveVertex(edge.StartVertexId);
+ var endPoint = graph.ResolveVertex(edge.EndVertexId);
+
+ Assert.True(IsPointOnLine(startPoint, line.Origin, line.Direction, Tolerance),
+ $"EDGE_CURVE #{edge.EdgeCurveId} start vertex is off line #{edge.CurveId}.");
+ Assert.True(IsPointOnLine(endPoint, line.Origin, line.Direction, Tolerance),
+ $"EDGE_CURVE #{edge.EdgeCurveId} end vertex is off line #{edge.CurveId}.");
+ }
+
+ var uniqueVertices = DeduplicatePoints(graph.VertexToPoint.Values.Select(id => graph.Points[id]).ToArray(), Tolerance);
+ Assert.Equal(8, uniqueVertices.Count);
+
+ var uniqueEdges = new HashSet<(int A, int B)>();
+ foreach (var edge in graph.EdgeCurves)
+ {
+ var a = edge.StartVertexId;
+ var b = edge.EndVertexId;
+ uniqueEdges.Add(a <= b ? (a, b) : (b, a));
+ }
+
+ Assert.Equal(12, uniqueEdges.Count);
+ }
+
+ private static bool IsPointOnLine((double X, double Y, double Z) p, (double X, double Y, double Z) origin, (double X, double Y, double Z) direction, double tolerance)
+ {
+ var vx = p.X - origin.X;
+ var vy = p.Y - origin.Y;
+ var vz = p.Z - origin.Z;
+
+ var t = (vx * direction.X) + (vy * direction.Y) + (vz * direction.Z);
+ var projected = (
+ origin.X + (direction.X * t),
+ origin.Y + (direction.Y * t),
+ origin.Z + (direction.Z * t));
+
+ var dx = p.X - projected.Item1;
+ var dy = p.Y - projected.Item2;
+ var dz = p.Z - projected.Item3;
+ var distance = double.Sqrt((dx * dx) + (dy * dy) + (dz * dz));
+ return distance <= tolerance;
+ }
+
+ private static List<(double X, double Y, double Z)> DeduplicatePoints((double X, double Y, double Z)[] points, double tolerance)
+ {
+ var unique = new List<(double X, double Y, double Z)>();
+ var toleranceSq = tolerance * tolerance;
+ foreach (var point in points)
+ {
+ var exists = unique.Any(existing =>
+ {
+ var dx = existing.X - point.X;
+ var dy = existing.Y - point.Y;
+ var dz = existing.Z - point.Z;
+ return ((dx * dx) + (dy * dy) + (dz * dz)) <= toleranceSq;
+ });
+
+ if (!exists)
+ {
+ unique.Add(point);
+ }
+ }
+
+ return unique;
+ }
+
+ private static ParsedGraph Parse(string stepText)
+ {
+ var rhsById = new Dictionary<int, string>();
+ foreach (var rawLine in stepText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ if (!rawLine.StartsWith("#", StringComparison.Ordinal))
+ {
+ continue;
+ }
+
+ var equalsIndex = rawLine.IndexOf('=');
+ if (equalsIndex <= 1)
+ {
+ continue;
+ }
+
+ var id = int.Parse(rawLine.AsSpan(1, equalsIndex - 1), CultureInfo.InvariantCulture);
+ rhsById[id] = rawLine[(equalsIndex + 1)..];
+ }
+
+ var points = new Dictionary<int, (double X, double Y, double Z)>();
+ var vertexToPoint = new Dictionary<int, int>();
+ var directions = new Dictionary<int, (double X, double Y, double Z)>();
+ var vectors = new Dictionary<int, int>();
+ var lines = new Dictionary<int, ParsedLine>();
+ var edgeCurves = new List<ParsedEdgeCurve>();
+
+ foreach (var (id, rhs) in rhsById)
+ {
+ if (rhs.StartsWith("CARTESIAN_POINT", StringComparison.Ordinal))
+ {
+ points[id] = ReadTriplet(rhs);
+ }
+ else if (rhs.StartsWith("VERTEX_POINT", StringComparison.Ordinal))
+ {
+ vertexToPoint[id] = ReadReference(rhs, 1);
+ }
+ else if (rhs.StartsWith("DIRECTION", StringComparison.Ordinal))
+ {
+ directions[id] = ReadTriplet(rhs);
+ }
+ else if (rhs.StartsWith("VECTOR", StringComparison.Ordinal))
+ {
+ vectors[id] = ReadReference(rhs, 1);
+ }
+ else if (rhs.StartsWith("LINE", StringComparison.Ordinal))
+ {
+ lines[id] = new ParsedLine(points[ReadReference(rhs, 1)], directions[vectors[ReadReference(rhs, 2)]]);
+ }
+ else if (rhs.StartsWith("EDGE_CURVE", StringComparison.Ordinal))
+ {
+ edgeCurves.Add(new ParsedEdgeCurve(id, ReadReference(rhs, 1), ReadReference(rhs, 2), ReadReference(rhs, 3)));
+ }
+ }
+
+ return new ParsedGraph(points, vertexToPoint, lines, edgeCurves);
+ }
+
+ private static int ReadReference(string rhs, int occurrence)
+ {
+ var index = -1;
+ for (var i = 0; i < occurrence; i++)
+ {
+ index = rhs.IndexOf('#', index + 1);
+ if (index < 0)
+ {
+ throw new InvalidOperationException($"Missing reference #{occurrence} in {rhs}");
+ }
+ }
+
+ var end = index + 1;
+ while (end < rhs.Length && char.IsDigit(rhs[end]))
+ {
+ end++;
+ }
+
+ return int.Parse(rhs.AsSpan(index + 1, end - index - 1), CultureInfo.InvariantCulture);
+ }
+
+ private static (double X, double Y, double Z) ReadTriplet(string rhs)
+ {
+ var start = rhs.IndexOf("((", StringComparison.Ordinal);
+ if (start >= 0)
+ {
+ start += 2;
+ }
+ else
+ {
+ start = rhs.LastIndexOf('(') + 1;
+ }
+
+ var end = rhs.IndexOf(')', start);
+ var parts = rhs[start..end].Split(',', StringSplitOptions.TrimEntries);
+ return (
+ double.Parse(parts[0], CultureInfo.InvariantCulture),
+ double.Parse(parts[1], CultureInfo.InvariantCulture),
+ double.Parse(parts[2], CultureInfo.InvariantCulture));
+ }
+
+ private sealed record ParsedGraph(
+ IReadOnlyDictionary<int, (double X, double Y, double Z)> Points,
+ IReadOnlyDictionary<int, int> VertexToPoint,
+ IReadOnlyDictionary<int, ParsedLine> Lines,
+ IReadOnlyList<ParsedEdgeCurve> EdgeCurves)
+ {
+ public (double X, double Y, double Z) ResolveVertex(int vertexPointId) => Points[VertexToPoint[vertexPointId]];
+ }
+
+ private sealed record ParsedLine((double X, double Y, double Z) Origin, (double X, double Y, double Z) Direction);
+
+ private sealed record ParsedEdgeCurve(int EdgeCurveId, int StartVertexId, int EndVertexId, int CurveId);
+}
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
index 3ed30068..23417806 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
@@ -189,11 +189,10 @@ public sealed class Step242ExporterTests
var dx = point.X - projectedX;
var dy = point.Y - projectedY;
var dz = point.Z - projectedZ;
- var distanceToLine = Math.Sqrt((dx * dx) + (dy * dy) + (dz * dz));
+ var distanceToLine = double.Sqrt((dx * dx) + (dy * dy) + (dz * dz));
- var inRange = t >= -tolerance && t <= length + tolerance;
var onLine = distanceToLine <= tolerance;
- return (onLine && inRange, t, distanceToLine);
+ return (onLine, t, distanceToLine);
}
private static int ReadReference(string rhs, int occurrence)
@@ -219,9 +218,18 @@ public sealed class Step242ExporterTests
private static (double X, double Y, double Z) ReadTriplet(string rhs)
{
- var start = rhs.LastIndexOf('(');
- var end = rhs.LastIndexOf(')');
- var parts = rhs[(start + 1)..end].Split(',', StringSplitOptions.TrimEntries);
+ var start = rhs.IndexOf("((", StringComparison.Ordinal);
+ if (start >= 0)
+ {
+ start += 2;
+ }
+ else
+ {
+ start = rhs.LastIndexOf('(') + 1;
+ }
+
+ var end = rhs.IndexOf(')', start);
+ var parts = rhs[start..end].Split(',', StringSplitOptions.TrimEntries);
return (
double.Parse(parts[0], CultureInfo.InvariantCulture),
double.Parse(parts[1], CultureInfo.InvariantCulture),
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index ed545ef2..f39ffbaf 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -33,6 +33,7 @@ public static class Step242Exporter
var vertexPointIds = new Dictionary<VertexId, string>();
var cartesianPointIds = new Dictionary<VertexId, string>();
+ var vertexPoints = new Dictionary<VertexId, Point3D>();
var edgeCurveIds = new Dictionary<EdgeId, string>();
var orientedEdgeIds = new Dictionary<CoedgeId, string>();
@@ -74,7 +75,7 @@ public static class Step242Exporter
if (!edgeCurveIds.TryGetValue(coedge.EdgeId, out var edgeCurveId))
{
- var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, cartesianPointIds, vertexPointIds, lineIds);
+ var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, vertexPoints, cartesianPointIds, vertexPointIds, lineIds);
if (!edgeResult.IsSuccess)
{
return KernelResult<string>.Failure(edgeResult.Diagnostics);
@@ -145,6 +146,7 @@ public static class Step242Exporter
TopologyModel model,
Step242TextWriter writer,
EdgeId edgeId,
+ IDictionary<VertexId, Point3D> vertexPoints,
IDictionary<VertexId, string> cartesianPointIds,
IDictionary<VertexId, string> vertexPointIds,
IDictionary<EdgeId, string> lineIds)
@@ -171,17 +173,44 @@ public static class Step242Exporter
return Failure("Line edge must provide trim interval for vertex mapping.", $"Edge:{edgeId.Value}");
}
- var line = curve.Line3.Value;
- var startPoint = line.Evaluate(edgeBinding.TrimInterval.Value.Start);
- var endPoint = line.Evaluate(edgeBinding.TrimInterval.Value.End);
+ var startPointResult = ResolveVertexPoint(body, model, edge.StartVertexId, vertexPoints);
+ if (!startPointResult.IsSuccess)
+ {
+ return KernelResult<string>.Failure(startPointResult.Diagnostics);
+ }
- var startVertexId = EnsureVertex(writer, edge.StartVertexId, startPoint, cartesianPointIds, vertexPointIds);
- var endVertexId = EnsureVertex(writer, edge.EndVertexId, endPoint, cartesianPointIds, vertexPointIds);
+ var endPointResult = ResolveVertexPoint(body, model, edge.EndVertexId, vertexPoints);
+ if (!endPointResult.IsSuccess)
+ {
+ return KernelResult<string>.Failure(endPointResult.Diagnostics);
+ }
+
+ var startPoint = startPointResult.Value;
+ var endPoint = endPointResult.Value;
+
+ var startVertexId = EnsureVertex(writer, edge.StartVertexId, startPoint, vertexPoints, cartesianPointIds, vertexPointIds);
+ var endVertexId = EnsureVertex(writer, edge.EndVertexId, endPoint, vertexPoints, cartesianPointIds, vertexPointIds);
if (!lineIds.TryGetValue(edgeId, out var lineId))
{
- var originId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(line.Origin));
- var direction = line.Direction.ToVector();
+ var edgeVector = endPoint - startPoint;
+ if (edgeVector.LengthSquared <= 1e-24d || !edgeVector.TryNormalize(out var endpointDirection))
+ {
+ return Failure("Edge endpoints resolve to a degenerate line direction.", $"Edge:{edgeId.Value}");
+ }
+
+ var direction = endpointDirection;
+ var curveDirection = curve.Line3.Value.Direction.ToVector();
+ if (curveDirection.TryNormalize(out var normalizedCurveDirection))
+ {
+ var alignment = double.Abs(normalizedCurveDirection.Dot(endpointDirection));
+ if (alignment >= 0.999999999999d)
+ {
+ direction = normalizedCurveDirection;
+ }
+ }
+
+ var originId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(startPoint));
var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(direction.X), Step242TextWriter.Number(direction.Y), Step242TextWriter.Number(direction.Z)));
var vectorId = writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(1d));
lineId = writer.AddEntity("LINE", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(vectorId));
@@ -196,9 +225,26 @@ public static class Step242Exporter
Step242TextWriter writer,
VertexId vertexId,
Point3D point,
+ IDictionary<VertexId, Point3D> vertexPoints,
IDictionary<VertexId, string> cartesianPointIds,
IDictionary<VertexId, string> vertexPointIds)
{
+ const double tolerance = 1e-9;
+ if (vertexPoints.TryGetValue(vertexId, out var existingPoint))
+ {
+ var delta = existingPoint - point;
+ if (delta.LengthSquared > tolerance * tolerance)
+ {
+#if DEBUG
+ throw new InvalidOperationException($"Vertex {vertexId.Value} point inconsistency detected during STEP export.");
+#endif
+ }
+ }
+ else
+ {
+ vertexPoints[vertexId] = point;
+ }
+
if (!cartesianPointIds.TryGetValue(vertexId, out var pointId))
{
pointId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(point));
@@ -214,6 +260,147 @@ public static class Step242Exporter
return vertexPointId;
}
+ private static KernelResult<Point3D> ResolveVertexPoint(
+ BrepBody body,
+ TopologyModel model,
+ VertexId vertexId,
+ IDictionary<VertexId, Point3D> vertexPoints)
+ {
+ if (vertexPoints.TryGetValue(vertexId, out var resolved))
+ {
+ return KernelResult<Point3D>.Success(resolved);
+ }
+
+ var fromPlanes = ResolveVertexFromIncidentPlanes(body, model, vertexId);
+ if (fromPlanes.IsSuccess)
+ {
+ vertexPoints[vertexId] = fromPlanes.Value;
+ return fromPlanes;
+ }
+
+ foreach (var edge in model.Edges.OrderBy(e => e.Id.Value))
+ {
+ var useStart = false;
+ if (edge.StartVertexId == vertexId)
+ {
+ useStart = true;
+ }
+ else if (edge.EndVertexId != vertexId)
+ {
+ continue;
+ }
+
+ var pointResult = EvaluateEdgeEndpoint(body, edge.Id, useStart);
+ if (!pointResult.IsSuccess)
+ {
+ continue;
+ }
+
+ vertexPoints[vertexId] = pointResult.Value;
+ return KernelResult<Point3D>.Success(pointResult.Value);
+ }
+
+ return FailurePoint($"Vertex {vertexId.Value} cannot be resolved to a geometric point for STEP export.", $"Vertex:{vertexId.Value}");
+ }
+
+ private static KernelResult<Point3D> ResolveVertexFromIncidentPlanes(BrepBody body, TopologyModel model, VertexId vertexId)
+ {
+ var planes = new List<PlaneSurface>();
+ foreach (var face in model.Faces.OrderBy(f => f.Id.Value))
+ {
+ var touchesVertex = false;
+ foreach (var loopId in face.LoopIds)
+ {
+ var loop = model.GetLoop(loopId);
+ foreach (var coedgeId in loop.CoedgeIds)
+ {
+ var coedge = model.GetCoedge(coedgeId);
+ var edge = model.GetEdge(coedge.EdgeId);
+ if (edge.StartVertexId == vertexId || edge.EndVertexId == vertexId)
+ {
+ touchesVertex = true;
+ break;
+ }
+ }
+
+ if (touchesVertex)
+ {
+ break;
+ }
+ }
+
+ if (!touchesVertex || !body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding))
+ {
+ continue;
+ }
+
+ if (!body.Geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface?.Plane is null)
+ {
+ continue;
+ }
+
+ planes.Add(surface.Plane.Value);
+ }
+
+ for (var i = 0; i < planes.Count; i++)
+ {
+ for (var j = i + 1; j < planes.Count; j++)
+ {
+ for (var k = j + 1; k < planes.Count; k++)
+ {
+ if (TryIntersectPlanes(planes[i], planes[j], planes[k], out var intersection))
+ {
+ return KernelResult<Point3D>.Success(intersection);
+ }
+ }
+ }
+ }
+
+ return FailurePoint($"Vertex {vertexId.Value} cannot be resolved from incident face planes.", $"Vertex:{vertexId.Value}");
+ }
+
+ private static bool TryIntersectPlanes(PlaneSurface a, PlaneSurface b, PlaneSurface c, out Point3D point)
+ {
+ var n1 = a.Normal.ToVector();
+ var n2 = b.Normal.ToVector();
+ var n3 = c.Normal.ToVector();
+ var denominator = n1.Dot(n2.Cross(n3));
+ if (double.Abs(denominator) <= 1e-12d)
+ {
+ point = Point3D.Origin;
+ return false;
+ }
+
+ var d1 = n1.Dot(new Vector3D(a.Origin.X, a.Origin.Y, a.Origin.Z));
+ var d2 = n2.Dot(new Vector3D(b.Origin.X, b.Origin.Y, b.Origin.Z));
+ var d3 = n3.Dot(new Vector3D(c.Origin.X, c.Origin.Y, c.Origin.Z));
+
+ var numerator = (n2.Cross(n3) * d1) + (n3.Cross(n1) * d2) + (n1.Cross(n2) * d3);
+ point = new Point3D(numerator.X / denominator, numerator.Y / denominator, numerator.Z / denominator);
+ return double.IsFinite(point.X) && double.IsFinite(point.Y) && double.IsFinite(point.Z);
+ }
+
+ private static KernelResult<Point3D> EvaluateEdgeEndpoint(BrepBody body, EdgeId edgeId, bool useStart)
+ {
+ if (!body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding))
+ {
+ return FailurePoint("Edge is missing curve binding.", $"Edge:{edgeId.Value}");
+ }
+
+ if (edgeBinding.TrimInterval is null)
+ {
+ return FailurePoint("Line edge must provide trim interval for vertex mapping.", $"Edge:{edgeId.Value}");
+ }
+
+ if (!body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null || curve.Kind != CurveGeometryKind.Line3 || curve.Line3 is null)
+ {
+ return FailurePoint("Line edge geometry was not found.", $"Curve:{edgeBinding.CurveGeometryId.Value}");
+ }
+
+ var parameter = useStart ? edgeBinding.TrimInterval.Value.Start : edgeBinding.TrimInterval.Value.End;
+ return KernelResult<Point3D>.Success(curve.Line3.Value.Evaluate(parameter));
+ }
+
private static string PointList(Point3D point) => Step242TextWriter.List(
Step242TextWriter.Number(point.X),
Step242TextWriter.Number(point.Y),
@@ -227,4 +414,13 @@ public static class Step242Exporter
message,
source)
]);
+
+ private static KernelResult<Point3D> FailurePoint(string message, string source) =>
+ KernelResult<Point3D>.Failure([
+ new KernelDiagnostic(
+ KernelDiagnosticCode.NotImplemented,
+ KernelDiagnosticSeverity.Error,
+ message,
+ source)
+ ]);
}
diff --git a/docs/support-matrix-step242-v0.md b/docs/support-matrix-step242-v0.md
index c586a69b..06ba04e1 100644
--- a/docs/support-matrix-step242-v0.md
+++ b/docs/support-matrix-step242-v0.md
@@ -7,6 +7,7 @@ Aetheris STEP242 v0 is intentionally narrow and deterministic.
- Single solid only: exactly one `MANIFOLD_SOLID_BREP` root is required.
- Backend-authoritative flow: import -> render -> canonical export (+ SHA256).
- Deterministic diagnostics: stable `(code, source, messagePrefix)` for expected fail cases.
+- Exporter line-edge consistency: for exported `EDGE_CURVE` instances backed by `LINE`, both referenced vertex points are guaranteed to lie on the exported line geometry within export tolerance.
- STEP Part 21 complex entity-instance assignments are accepted for parser/decoder context use (for example `#5=(GEOMETRIC_REPRESENTATION_CONTEXT(...)...REPRESENTATION_CONTEXT(...));`).
- STEP Part 21 typed parameter values are supported in value position with deterministic normalization (`IDENT(...)` parsed as uppercase identifier + argument list), including common nested wrappers such as `LENGTH_MEASURE(...)` and `LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(...),#...)`.