Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add AP242 subset importer for M22 round-trip

Yuechen Li761e757ed47b
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs
new file mode 100644
index 00000000..b91bdd24
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs
@@ -0,0 +1,84 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242ImporterTests
+{
+ [Fact]
+ public void ImportBody_KnownGoodM22SubsetText_ReturnsValidatedBody()
+ {
+ var fixtureText = CreateM22BoxFixtureText();
+
+ var import = Step242Importer.ImportBody(fixtureText);
+
+ Assert.True(import.IsSuccess);
+ var validation = BrepBindingValidator.Validate(import.Value, requireAllEdgeAndFaceBindings: true);
+ Assert.True(validation.IsSuccess);
+
+ var tessellation = BrepDisplayTessellator.Tessellate(import.Value);
+ Assert.True(tessellation.IsSuccess);
+ Assert.NotEmpty(tessellation.Value.FacePatches);
+ }
+
+ [Fact]
+ public void ExportImportRoundTrip_BoxSubset_PreservesBasicTopologyInvariants()
+ {
+ var boxResult = BrepPrimitives.CreateBox(4d, 6d, 8d);
+ Assert.True(boxResult.IsSuccess);
+
+ var export = Step242Exporter.ExportBody(boxResult.Value);
+ Assert.True(export.IsSuccess);
+
+ var import = Step242Importer.ImportBody(export.Value);
+
+ Assert.True(import.IsSuccess);
+ Assert.Equal(boxResult.Value.Topology.Vertices.Count(), import.Value.Topology.Vertices.Count());
+ Assert.Equal(boxResult.Value.Topology.Edges.Count(), import.Value.Topology.Edges.Count());
+ Assert.Equal(boxResult.Value.Topology.Faces.Count(), import.Value.Topology.Faces.Count());
+
+ var tessellation = BrepDisplayTessellator.Tessellate(import.Value);
+ Assert.True(tessellation.IsSuccess);
+ }
+
+ [Fact]
+ public void ImportBody_MalformedStep_ReturnsDiagnosticWithoutThrowing()
+ {
+ var malformed = "ISO-10303-21; DATA; #1=MANIFOLD_SOLID_BREP('bad',#2) ENDSEC; END-ISO-10303-21;";
+
+ var import = Step242Importer.ImportBody(malformed);
+
+ Assert.False(import.IsSuccess);
+ var diagnostic = Assert.Single(import.Diagnostics);
+ Assert.Equal(KernelDiagnosticCode.InvalidArgument, diagnostic.Code);
+ Assert.Equal(KernelDiagnosticSeverity.Error, diagnostic.Severity);
+ Assert.Equal("Parser", diagnostic.Source);
+ }
+
+ [Fact]
+ public void ImportBody_UnsupportedEntityInParseableText_ReturnsNotImplementedDiagnostic()
+ {
+ var unsupported = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=SPHERICAL_SURFACE($,#2,1.0);\n#2=AXIS2_PLACEMENT_3D($,#3,#4,#5);\n#3=CARTESIAN_POINT($,(0,0,0));\n#4=DIRECTION($,(0,0,1));\n#5=DIRECTION($,(1,0,0));\nENDSEC;\nEND-ISO-10303-21;";
+
+ var import = Step242Importer.ImportBody(unsupported);
+
+ Assert.False(import.IsSuccess);
+ var diagnostic = Assert.Single(import.Diagnostics);
+ Assert.Equal(KernelDiagnosticCode.NotImplemented, diagnostic.Code);
+ Assert.Equal(KernelDiagnosticSeverity.Error, diagnostic.Severity);
+ Assert.Equal("Entity:1", diagnostic.Source);
+ Assert.Contains("unsupported", diagnostic.Message, StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static string CreateM22BoxFixtureText()
+ {
+ var boxResult = BrepPrimitives.CreateBox(2d, 2d, 2d);
+ Assert.True(boxResult.IsSuccess);
+
+ var export = Step242Exporter.ExportBody(boxResult.Value);
+ Assert.True(export.IsSuccess);
+ return export.Value;
+ }
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
new file mode 100644
index 00000000..e14f412b
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -0,0 +1,356 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+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.Step242;
+
+public static class Step242Importer
+{
+ public static KernelResult<BrepBody> ImportBody(string stepText)
+ {
+ var parseResult = Step242SubsetParser.Parse(stepText);
+ if (!parseResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(parseResult.Diagnostics);
+ }
+
+ return MapSubset(parseResult.Value);
+ }
+
+ private static KernelResult<BrepBody> MapSubset(Step242ParsedDocument document)
+ {
+ var unsupportedEntity = document.Entities.FirstOrDefault(IsClearlyUnsupportedEntity);
+ if (unsupportedEntity is not null)
+ {
+ return Failure($"Entity '{unsupportedEntity.Name}' is unsupported in M23 import subset.", $"Entity:{unsupportedEntity.Id}");
+ }
+
+ var brepEntity = document.Entities.FirstOrDefault(e => string.Equals(e.Name, "MANIFOLD_SOLID_BREP", StringComparison.OrdinalIgnoreCase));
+ if (brepEntity is null)
+ {
+ return Failure("Missing MANIFOLD_SOLID_BREP root entity.", "Importer");
+ }
+
+ var shellRefResult = Step242SubsetDecoder.ReadReference(brepEntity, 1, "MANIFOLD_SOLID_BREP shell");
+ if (!shellRefResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(shellRefResult.Diagnostics);
+ }
+
+ var shellEntityResult = document.TryGetEntity(shellRefResult.Value.TargetId, "CLOSED_SHELL");
+ if (!shellEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(shellEntityResult.Diagnostics);
+ }
+
+ var faceRefsResult = Step242SubsetDecoder.ReadReferenceList(shellEntityResult.Value, 1, "CLOSED_SHELL faces");
+ if (!faceRefsResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(faceRefsResult.Diagnostics);
+ }
+
+ var builder = new TopologyBuilder();
+ var geometry = new BrepGeometryStore();
+ var bindings = new BrepBindingModel();
+
+ var vertexMap = new Dictionary<int, (VertexId VertexId, Point3D Point)>();
+ var edgeMap = new Dictionary<int, EdgeId>();
+ var coedges = new List<Coedge>();
+
+ var nextCurveGeometryId = 1;
+ var nextSurfaceGeometryId = 1;
+ var faceIds = new List<FaceId>();
+
+ foreach (var faceRef in faceRefsResult.Value)
+ {
+ var faceEntityResult = document.TryGetEntity(faceRef.TargetId, "ADVANCED_FACE");
+ if (!faceEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(faceEntityResult.Diagnostics);
+ }
+
+ var faceEntity = faceEntityResult.Value;
+ var boundRefsResult = Step242SubsetDecoder.ReadReferenceList(faceEntity, 0, "ADVANCED_FACE bounds");
+ if (!boundRefsResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(boundRefsResult.Diagnostics);
+ }
+
+ if (boundRefsResult.Value.Count == 0)
+ {
+ return Failure("ADVANCED_FACE without bounds is unsupported in M23 subset.", $"Entity:{faceEntity.Id}");
+ }
+
+ var loopIds = new List<LoopId>(boundRefsResult.Value.Count);
+ foreach (var boundRef in boundRefsResult.Value)
+ {
+ var boundEntityResult = document.TryGetEntity(boundRef.TargetId);
+ if (!boundEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(boundEntityResult.Diagnostics);
+ }
+
+ var boundEntity = boundEntityResult.Value;
+ var isFaceBound = string.Equals(boundEntity.Name, "FACE_BOUND", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(boundEntity.Name, "FACE_OUTER_BOUND", StringComparison.OrdinalIgnoreCase);
+ if (!isFaceBound)
+ {
+ return Failure($"Entity '{boundEntity.Name}' is unsupported in M23 import subset.", $"Entity:{boundEntity.Id}");
+ }
+
+ var loopRefResult = Step242SubsetDecoder.ReadReference(boundEntity, 1, "FACE_BOUND loop");
+ if (!loopRefResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(loopRefResult.Diagnostics);
+ }
+
+ var loopEntityResult = document.TryGetEntity(loopRefResult.Value.TargetId, "EDGE_LOOP");
+ if (!loopEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(loopEntityResult.Diagnostics);
+ }
+
+ var orientedEdgeRefsResult = Step242SubsetDecoder.ReadReferenceList(loopEntityResult.Value, 1, "EDGE_LOOP coedges");
+ if (!orientedEdgeRefsResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(orientedEdgeRefsResult.Diagnostics);
+ }
+
+ if (orientedEdgeRefsResult.Value.Count == 0)
+ {
+ return Failure("EDGE_LOOP must contain at least one ORIENTED_EDGE.", $"Entity:{loopEntityResult.Value.Id}");
+ }
+
+ var loopId = builder.AllocateLoopId();
+ var coedgeIds = new List<CoedgeId>(orientedEdgeRefsResult.Value.Count);
+ for (var i = 0; i < orientedEdgeRefsResult.Value.Count; i++)
+ {
+ coedgeIds.Add(builder.AllocateCoedgeId());
+ }
+
+ for (var i = 0; i < orientedEdgeRefsResult.Value.Count; i++)
+ {
+ var orientedEdgeEntityResult = document.TryGetEntity(orientedEdgeRefsResult.Value[i].TargetId, "ORIENTED_EDGE");
+ if (!orientedEdgeEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(orientedEdgeEntityResult.Diagnostics);
+ }
+
+ var orientedEdgeEntity = orientedEdgeEntityResult.Value;
+ var edgeCurveRefResult = Step242SubsetDecoder.ReadReference(orientedEdgeEntity, 3, "ORIENTED_EDGE edge element");
+ if (!edgeCurveRefResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(edgeCurveRefResult.Diagnostics);
+ }
+
+ var edgeCurveEntityResult = document.TryGetEntity(edgeCurveRefResult.Value.TargetId, "EDGE_CURVE");
+ if (!edgeCurveEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(edgeCurveEntityResult.Diagnostics);
+ }
+
+ var edgeIdResult = EnsureEdge(
+ document,
+ edgeCurveEntityResult.Value,
+ builder,
+ geometry,
+ bindings,
+ vertexMap,
+ edgeMap,
+ ref nextCurveGeometryId);
+
+ if (!edgeIdResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(edgeIdResult.Diagnostics);
+ }
+
+ var orientedSenseResult = Step242SubsetDecoder.ReadBoolean(orientedEdgeEntity, 4, "ORIENTED_EDGE orientation");
+ if (!orientedSenseResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(orientedSenseResult.Diagnostics);
+ }
+
+ coedges.Add(new Coedge(
+ coedgeIds[i],
+ edgeIdResult.Value,
+ loopId,
+ coedgeIds[(i + 1) % coedgeIds.Count],
+ coedgeIds[(i + coedgeIds.Count - 1) % coedgeIds.Count],
+ isReversed: !orientedSenseResult.Value));
+ }
+
+ builder.AddLoop(new Loop(loopId, coedgeIds));
+ loopIds.Add(loopId);
+ }
+
+ var faceId = builder.AddFace(loopIds);
+ faceIds.Add(faceId);
+
+ var planeRefResult = Step242SubsetDecoder.ReadReference(faceEntity, 1, "ADVANCED_FACE surface");
+ if (!planeRefResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(planeRefResult.Diagnostics);
+ }
+
+ var planeEntityResult = document.TryGetEntity(planeRefResult.Value.TargetId, "PLANE");
+ if (!planeEntityResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(planeEntityResult.Diagnostics);
+ }
+
+ var planeResult = Step242SubsetDecoder.ReadPlaneSurface(document, planeEntityResult.Value);
+ if (!planeResult.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(planeResult.Diagnostics);
+ }
+
+ var surfaceGeometryId = new SurfaceGeometryId(nextSurfaceGeometryId++);
+ geometry.AddSurface(surfaceGeometryId, SurfaceGeometry.FromPlane(planeResult.Value));
+ bindings.AddFaceBinding(new FaceGeometryBinding(faceId, surfaceGeometryId));
+ }
+
+ foreach (var coedge in coedges)
+ {
+ builder.AddCoedge(coedge);
+ }
+
+ var shellId = builder.AddShell(faceIds);
+ builder.AddBody([shellId]);
+
+ var body = new BrepBody(builder.Model, geometry, bindings);
+ var validation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);
+ if (!validation.IsSuccess)
+ {
+ return KernelResult<BrepBody>.Failure(validation.Diagnostics);
+ }
+
+ return KernelResult<BrepBody>.Success(body, validation.Diagnostics);
+ }
+
+ private static KernelResult<EdgeId> EnsureEdge(
+ Step242ParsedDocument document,
+ Step242ParsedEntity edgeCurveEntity,
+ TopologyBuilder builder,
+ BrepGeometryStore geometry,
+ BrepBindingModel bindings,
+ IDictionary<int, (VertexId VertexId, Point3D Point)> vertexMap,
+ IDictionary<int, EdgeId> edgeMap,
+ ref int nextCurveGeometryId)
+ {
+ if (edgeMap.TryGetValue(edgeCurveEntity.Id, out var existingEdgeId))
+ {
+ return KernelResult<EdgeId>.Success(existingEdgeId);
+ }
+
+ var startRefResult = Step242SubsetDecoder.ReadReference(edgeCurveEntity, 1, "EDGE_CURVE start");
+ if (!startRefResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(startRefResult.Diagnostics);
+ }
+
+ var endRefResult = Step242SubsetDecoder.ReadReference(edgeCurveEntity, 2, "EDGE_CURVE end");
+ if (!endRefResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(endRefResult.Diagnostics);
+ }
+
+ var lineRefResult = Step242SubsetDecoder.ReadReference(edgeCurveEntity, 3, "EDGE_CURVE geometry");
+ if (!lineRefResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(lineRefResult.Diagnostics);
+ }
+
+ var sameSenseResult = Step242SubsetDecoder.ReadBoolean(edgeCurveEntity, 4, "EDGE_CURVE same_sense");
+ if (!sameSenseResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(sameSenseResult.Diagnostics);
+ }
+
+ if (!sameSenseResult.Value)
+ {
+ return KernelResult<EdgeId>.Failure([
+ new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, "EDGE_CURVE with same_sense=.F. is unsupported in M23 subset.", $"Entity:{edgeCurveEntity.Id}")
+ ]);
+ }
+
+ var startVertexResult = EnsureVertex(document, startRefResult.Value.TargetId, builder, vertexMap);
+ if (!startVertexResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(startVertexResult.Diagnostics);
+ }
+
+ var endVertexResult = EnsureVertex(document, endRefResult.Value.TargetId, builder, vertexMap);
+ if (!endVertexResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(endVertexResult.Diagnostics);
+ }
+
+ var lineEntityResult = document.TryGetEntity(lineRefResult.Value.TargetId, "LINE");
+ if (!lineEntityResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(lineEntityResult.Diagnostics);
+ }
+
+ var lineResult = Step242SubsetDecoder.ReadLineCurve(document, lineEntityResult.Value);
+ if (!lineResult.IsSuccess)
+ {
+ return KernelResult<EdgeId>.Failure(lineResult.Diagnostics);
+ }
+
+ var edgeId = builder.AddEdge(startVertexResult.Value.VertexId, endVertexResult.Value.VertexId);
+ edgeMap.Add(edgeCurveEntity.Id, edgeId);
+
+ var startParameter = ComputeLineParameter(lineResult.Value, startVertexResult.Value.Point);
+ var endParameter = ComputeLineParameter(lineResult.Value, endVertexResult.Value.Point);
+ var curveGeometryId = new CurveGeometryId(nextCurveGeometryId++);
+
+ geometry.AddCurve(curveGeometryId, CurveGeometry.FromLine(lineResult.Value));
+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edgeId, curveGeometryId, new ParameterInterval(startParameter, endParameter)));
+
+ return KernelResult<EdgeId>.Success(edgeId);
+ }
+
+ private static KernelResult<(VertexId VertexId, Point3D Point)> EnsureVertex(
+ Step242ParsedDocument document,
+ int vertexPointEntityId,
+ TopologyBuilder builder,
+ IDictionary<int, (VertexId VertexId, Point3D Point)> vertexMap)
+ {
+ if (vertexMap.TryGetValue(vertexPointEntityId, out var existingVertex))
+ {
+ return KernelResult<(VertexId VertexId, Point3D Point)>.Success(existingVertex);
+ }
+
+ var pointResult = Step242SubsetDecoder.ReadVertexPoint(document, vertexPointEntityId);
+ if (!pointResult.IsSuccess)
+ {
+ return KernelResult<(VertexId VertexId, Point3D Point)>.Failure(pointResult.Diagnostics);
+ }
+
+ var vertex = (builder.AddVertex(), pointResult.Value);
+ vertexMap.Add(vertexPointEntityId, vertex);
+ return KernelResult<(VertexId VertexId, Point3D Point)>.Success(vertex);
+ }
+
+ private static bool IsClearlyUnsupportedEntity(Step242ParsedEntity entity)
+ {
+ return string.Equals(entity.Name, "SPHERICAL_SURFACE", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(entity.Name, "CIRCLE", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(entity.Name, "CYLINDRICAL_SURFACE", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(entity.Name, "CONICAL_SURFACE", StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static double ComputeLineParameter(Line3Curve line, Point3D point)
+ {
+ var offset = point - line.Origin;
+ return offset.Dot(line.Direction.ToVector());
+ }
+
+ private static KernelResult<BrepBody> Failure(string message, string source) =>
+ KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs
new file mode 100644
index 00000000..8bc90114
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs
@@ -0,0 +1,285 @@
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Results;
+
+namespace Aetheris.Kernel.Core.Step242;
+
+internal static class Step242SubsetDecoder
+{
+ public static KernelResult<Step242EntityReference> ReadReference(Step242ParsedEntity entity, int argumentIndex, string context)
+ {
+ if (argumentIndex < 0 || argumentIndex >= entity.Arguments.Count)
+ {
+ return FailureRef($"{context}: missing argument at index {argumentIndex}.", $"Entity:{entity.Id}");
+ }
+
+ if (entity.Arguments[argumentIndex] is not Step242EntityReference reference)
+ {
+ return FailureRef($"{context}: expected entity reference argument.", $"Entity:{entity.Id}");
+ }
+
+ return KernelResult<Step242EntityReference>.Success(reference);
+ }
+
+ public static KernelResult<IReadOnlyList<Step242EntityReference>> ReadReferenceList(Step242ParsedEntity entity, int argumentIndex, string context)
+ {
+ if (argumentIndex < 0 || argumentIndex >= entity.Arguments.Count)
+ {
+ return FailureList($"{context}: missing argument at index {argumentIndex}.", $"Entity:{entity.Id}");
+ }
+
+ if (entity.Arguments[argumentIndex] is not Step242ListValue list)
+ {
+ return FailureList($"{context}: expected list argument.", $"Entity:{entity.Id}");
+ }
+
+ var refs = new List<Step242EntityReference>(list.Items.Count);
+ for (var i = 0; i < list.Items.Count; i++)
+ {
+ if (list.Items[i] is not Step242EntityReference reference)
+ {
+ return FailureList($"{context}: list item {i} must be an entity reference.", $"Entity:{entity.Id}");
+ }
+
+ refs.Add(reference);
+ }
+
+ return KernelResult<IReadOnlyList<Step242EntityReference>>.Success(refs);
+ }
+
+ public static KernelResult<bool> ReadBoolean(Step242ParsedEntity entity, int argumentIndex, string context)
+ {
+ if (argumentIndex < 0 || argumentIndex >= entity.Arguments.Count)
+ {
+ return FailureBool($"{context}: missing argument at index {argumentIndex}.", $"Entity:{entity.Id}");
+ }
+
+ if (entity.Arguments[argumentIndex] is not Step242BooleanValue value)
+ {
+ return FailureBool($"{context}: expected boolean logical (.T. / .F.).", $"Entity:{entity.Id}");
+ }
+
+ return KernelResult<bool>.Success(value.Value);
+ }
+
+ public static KernelResult<Point3D> ReadVertexPoint(Step242ParsedDocument document, int vertexPointEntityId)
+ {
+ var vertexPointEntityResult = document.TryGetEntity(vertexPointEntityId, "VERTEX_POINT");
+ if (!vertexPointEntityResult.IsSuccess)
+ {
+ return KernelResult<Point3D>.Failure(vertexPointEntityResult.Diagnostics);
+ }
+
+ var pointRefResult = ReadReference(vertexPointEntityResult.Value, 1, "VERTEX_POINT point");
+ if (!pointRefResult.IsSuccess)
+ {
+ return KernelResult<Point3D>.Failure(pointRefResult.Diagnostics);
+ }
+
+ var pointEntityResult = document.TryGetEntity(pointRefResult.Value.TargetId, "CARTESIAN_POINT");
+ if (!pointEntityResult.IsSuccess)
+ {
+ return KernelResult<Point3D>.Failure(pointEntityResult.Diagnostics);
+ }
+
+ return ReadCartesianPoint(pointEntityResult.Value, "VERTEX_POINT point");
+ }
+
+ public static KernelResult<Line3Curve> ReadLineCurve(Step242ParsedDocument document, Step242ParsedEntity lineEntity)
+ {
+ var originRefResult = ReadReference(lineEntity, 1, "LINE origin");
+ if (!originRefResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(originRefResult.Diagnostics);
+ }
+
+ var originEntityResult = document.TryGetEntity(originRefResult.Value.TargetId, "CARTESIAN_POINT");
+ if (!originEntityResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(originEntityResult.Diagnostics);
+ }
+
+ var originResult = ReadCartesianPoint(originEntityResult.Value, "LINE origin point");
+ if (!originResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(originResult.Diagnostics);
+ }
+
+ var vectorRefResult = ReadReference(lineEntity, 2, "LINE vector");
+ if (!vectorRefResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(vectorRefResult.Diagnostics);
+ }
+
+ var vectorEntityResult = document.TryGetEntity(vectorRefResult.Value.TargetId, "VECTOR");
+ if (!vectorEntityResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(vectorEntityResult.Diagnostics);
+ }
+
+ var directionRefResult = ReadReference(vectorEntityResult.Value, 1, "VECTOR direction");
+ if (!directionRefResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(directionRefResult.Diagnostics);
+ }
+
+ var directionEntityResult = document.TryGetEntity(directionRefResult.Value.TargetId, "DIRECTION");
+ if (!directionEntityResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(directionEntityResult.Diagnostics);
+ }
+
+ var directionResult = ReadDirection(directionEntityResult.Value, "VECTOR direction");
+ if (!directionResult.IsSuccess)
+ {
+ return KernelResult<Line3Curve>.Failure(directionResult.Diagnostics);
+ }
+
+ return KernelResult<Line3Curve>.Success(new Line3Curve(originResult.Value, directionResult.Value));
+ }
+
+ public static KernelResult<PlaneSurface> ReadPlaneSurface(Step242ParsedDocument document, Step242ParsedEntity planeEntity)
+ {
+ var placementRefResult = ReadReference(planeEntity, 1, "PLANE position");
+ if (!placementRefResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(placementRefResult.Diagnostics);
+ }
+
+ var placementEntityResult = document.TryGetEntity(placementRefResult.Value.TargetId, "AXIS2_PLACEMENT_3D");
+ if (!placementEntityResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(placementEntityResult.Diagnostics);
+ }
+
+ var originRefResult = ReadReference(placementEntityResult.Value, 1, "AXIS2_PLACEMENT_3D origin");
+ if (!originRefResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(originRefResult.Diagnostics);
+ }
+
+ var originEntityResult = document.TryGetEntity(originRefResult.Value.TargetId, "CARTESIAN_POINT");
+ if (!originEntityResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(originEntityResult.Diagnostics);
+ }
+
+ var originResult = ReadCartesianPoint(originEntityResult.Value, "AXIS2_PLACEMENT_3D origin");
+ if (!originResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(originResult.Diagnostics);
+ }
+
+ var normalRefResult = ReadReference(placementEntityResult.Value, 2, "AXIS2_PLACEMENT_3D axis");
+ if (!normalRefResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(normalRefResult.Diagnostics);
+ }
+
+ var normalEntityResult = document.TryGetEntity(normalRefResult.Value.TargetId, "DIRECTION");
+ if (!normalEntityResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(normalEntityResult.Diagnostics);
+ }
+
+ var normalResult = ReadDirection(normalEntityResult.Value, "AXIS2_PLACEMENT_3D axis");
+ if (!normalResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(normalResult.Diagnostics);
+ }
+
+ var refDirRefResult = ReadReference(placementEntityResult.Value, 3, "AXIS2_PLACEMENT_3D ref direction");
+ if (!refDirRefResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(refDirRefResult.Diagnostics);
+ }
+
+ var refDirEntityResult = document.TryGetEntity(refDirRefResult.Value.TargetId, "DIRECTION");
+ if (!refDirEntityResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(refDirEntityResult.Diagnostics);
+ }
+
+ var refDirResult = ReadDirection(refDirEntityResult.Value, "AXIS2_PLACEMENT_3D ref direction");
+ if (!refDirResult.IsSuccess)
+ {
+ return KernelResult<PlaneSurface>.Failure(refDirResult.Diagnostics);
+ }
+
+ return KernelResult<PlaneSurface>.Success(new PlaneSurface(originResult.Value, normalResult.Value, refDirResult.Value));
+ }
+
+ private static KernelResult<Point3D> ReadCartesianPoint(Step242ParsedEntity pointEntity, string context)
+ {
+ if (pointEntity.Arguments.Count < 2)
+ {
+ return FailurePoint($"{context}: CARTESIAN_POINT requires coordinate list argument.", $"Entity:{pointEntity.Id}");
+ }
+
+ if (pointEntity.Arguments[1] is not Step242ListValue coordinates || coordinates.Items.Count != 3)
+ {
+ return FailurePoint($"{context}: CARTESIAN_POINT coordinates must be a 3-item list.", $"Entity:{pointEntity.Id}");
+ }
+
+ var xResult = ReadNumber(coordinates.Items[0], context, pointEntity.Id);
+ if (!xResult.IsSuccess)
+ {
+ return KernelResult<Point3D>.Failure(xResult.Diagnostics);
+ }
+
+ var yResult = ReadNumber(coordinates.Items[1], context, pointEntity.Id);
+ if (!yResult.IsSuccess)
+ {
+ return KernelResult<Point3D>.Failure(yResult.Diagnostics);
+ }
+
+ var zResult = ReadNumber(coordinates.Items[2], context, pointEntity.Id);
+ if (!zResult.IsSuccess)
+ {
+ return KernelResult<Point3D>.Failure(zResult.Diagnostics);
+ }
+
+ return KernelResult<Point3D>.Success(new Point3D(xResult.Value, yResult.Value, zResult.Value));
+ }
+
+ private static KernelResult<Direction3D> ReadDirection(Step242ParsedEntity directionEntity, string context)
+ {
+ var pointResult = ReadCartesianPoint(directionEntity, context);
+ if (!pointResult.IsSuccess)
+ {
+ return KernelResult<Direction3D>.Failure(pointResult.Diagnostics);
+ }
+
+ return KernelResult<Direction3D>.Success(Direction3D.Create(pointResult.Value - Point3D.Origin));
+ }
+
+ private static KernelResult<double> ReadNumber(Step242Value value, string context, int entityId)
+ {
+ if (value is not Step242NumberValue number)
+ {
+ return FailureNumber($"{context}: expected numeric value.", $"Entity:{entityId}");
+ }
+
+ if (!double.IsFinite(number.Value))
+ {
+ return FailureNumber($"{context}: numeric value must be finite.", $"Entity:{entityId}");
+ }
+
+ return KernelResult<double>.Success(number.Value);
+ }
+
+ private static KernelResult<Step242EntityReference> FailureRef(string message, string source) => Failure<Step242EntityReference>(message, source);
+
+ private static KernelResult<IReadOnlyList<Step242EntityReference>> FailureList(string message, string source) => Failure<IReadOnlyList<Step242EntityReference>>(message, source);
+
+ private static KernelResult<bool> FailureBool(string message, string source) => Failure<bool>(message, source);
+
+ private static KernelResult<Point3D> FailurePoint(string message, string source) => Failure<Point3D>(message, source);
+
+ private static KernelResult<double> FailureNumber(string message, string source) => Failure<double>(message, source);
+
+ private static KernelResult<T> Failure<T>(string message, string source) =>
+ KernelResult<T>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
new file mode 100644
index 00000000..bd54f79f
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
@@ -0,0 +1,405 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Results;
+
+namespace Aetheris.Kernel.Core.Step242;
+
+internal static class Step242SubsetParser
+{
+ public static KernelResult<Step242ParsedDocument> Parse(string stepText)
+ {
+ if (string.IsNullOrWhiteSpace(stepText))
+ {
+ return Failure("STEP text must be non-empty.", "Parser");
+ }
+
+ var parser = new Reader(stepText);
+ var entities = new List<Step242ParsedEntity>();
+
+ try
+ {
+ while (!parser.End)
+ {
+ parser.SkipWhitespace();
+ if (parser.End)
+ {
+ break;
+ }
+
+ if (parser.Peek() == '#')
+ {
+ var entity = parser.ReadEntity();
+ entities.Add(entity);
+ }
+ else
+ {
+ parser.ReadToStatementTerminator();
+ }
+ }
+ }
+ catch (Step242ParseException ex)
+ {
+ return Failure(ex.Message, ex.SourceTag);
+ }
+
+ var duplicateId = entities
+ .GroupBy(e => e.Id)
+ .FirstOrDefault(g => g.Count() > 1);
+
+ if (duplicateId is not null)
+ {
+ return Failure($"Duplicate entity id #{duplicateId.Key} detected.", "Parser");
+ }
+
+ return KernelResult<Step242ParsedDocument>.Success(new Step242ParsedDocument(entities));
+ }
+
+ private static KernelResult<Step242ParsedDocument> Failure(string message, string source) =>
+ KernelResult<Step242ParsedDocument>.Failure([
+ new KernelDiagnostic(KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, message, source)
+ ]);
+
+ private sealed class Reader(string text)
+ {
+ private int _index;
+
+ public bool End => _index >= text.Length;
+
+ public char Peek() => text[_index];
+
+ public void SkipWhitespace()
+ {
+ while (!End && char.IsWhiteSpace(text[_index]))
+ {
+ _index++;
+ }
+ }
+
+ public Step242ParsedEntity ReadEntity()
+ {
+ Expect('#');
+ var id = ReadInteger();
+ SkipWhitespace();
+ Expect('=');
+ SkipWhitespace();
+ var name = ReadIdentifier();
+ SkipWhitespace();
+ Expect('(');
+ var args = ReadArgumentList();
+ SkipWhitespace();
+ Expect(';');
+ return new Step242ParsedEntity(id, name, args);
+ }
+
+ public void ReadToStatementTerminator()
+ {
+ while (!End)
+ {
+ var c = text[_index++];
+ if (c == ';')
+ {
+ return;
+ }
+ }
+ }
+
+ private List<Step242Value> ReadArgumentList()
+ {
+ var values = new List<Step242Value>();
+ SkipWhitespace();
+ if (!End && Peek() == ')')
+ {
+ _index++;
+ return values;
+ }
+
+ while (true)
+ {
+ values.Add(ReadValue());
+ SkipWhitespace();
+
+ if (End)
+ {
+ throw Error("Unexpected end of text in argument list.");
+ }
+
+ var next = text[_index++];
+ if (next == ')')
+ {
+ break;
+ }
+
+ if (next != ',')
+ {
+ throw Error($"Expected ',' or ')' in argument list, found '{next}'.");
+ }
+
+ SkipWhitespace();
+ }
+
+ return values;
+ }
+
+ private Step242Value ReadValue()
+ {
+ SkipWhitespace();
+ if (End)
+ {
+ throw Error("Unexpected end of text while reading value.");
+ }
+
+ var c = Peek();
+ return c switch
+ {
+ '#' => ReadReference(),
+ '\'' => ReadString(),
+ '$' => ReadOmitted(),
+ '(' => ReadList(),
+ '.' => ReadEnumOrLogical(),
+ '+' or '-' or >= '0' and <= '9' => ReadNumber(),
+ _ => throw Error($"Unsupported value token '{c}'.")
+ };
+ }
+
+ private Step242Value ReadReference()
+ {
+ Expect('#');
+ return new Step242EntityReference(ReadInteger());
+ }
+
+ private Step242Value ReadString()
+ {
+ Expect('\'');
+ var chars = new List<char>();
+ while (!End)
+ {
+ var c = text[_index++];
+ if (c == '\'')
+ {
+ if (!End && Peek() == '\'')
+ {
+ _index++;
+ chars.Add('\'');
+ continue;
+ }
+
+ return new Step242StringValue(new string(chars.ToArray()));
+ }
+
+ chars.Add(c);
+ }
+
+ throw Error("Unterminated string literal.");
+ }
+
+ private Step242Value ReadOmitted()
+ {
+ Expect('$');
+ return Step242OmittedValue.Instance;
+ }
+
+ private Step242Value ReadList()
+ {
+ Expect('(');
+ var items = new List<Step242Value>();
+ SkipWhitespace();
+ if (!End && Peek() == ')')
+ {
+ _index++;
+ return new Step242ListValue(items);
+ }
+
+ while (true)
+ {
+ items.Add(ReadValue());
+ SkipWhitespace();
+ if (End)
+ {
+ throw Error("Unexpected end of text in list literal.");
+ }
+
+ var next = text[_index++];
+ if (next == ')')
+ {
+ break;
+ }
+
+ if (next != ',')
+ {
+ throw Error($"Expected ',' or ')' in list literal, found '{next}'.");
+ }
+
+ SkipWhitespace();
+ }
+
+ return new Step242ListValue(items);
+ }
+
+ private Step242Value ReadEnumOrLogical()
+ {
+ Expect('.');
+ var token = ReadIdentifier();
+ Expect('.');
+
+ if (string.Equals(token, "T", StringComparison.OrdinalIgnoreCase))
+ {
+ return new Step242BooleanValue(true);
+ }
+
+ if (string.Equals(token, "F", StringComparison.OrdinalIgnoreCase))
+ {
+ return new Step242BooleanValue(false);
+ }
+
+ return new Step242EnumValue(token);
+ }
+
+ private Step242Value ReadNumber()
+ {
+ var start = _index;
+ if (!End && (Peek() == '+' || Peek() == '-'))
+ {
+ _index++;
+ }
+
+ while (!End && char.IsDigit(Peek()))
+ {
+ _index++;
+ }
+
+ if (!End && Peek() == '.')
+ {
+ _index++;
+ while (!End && char.IsDigit(Peek()))
+ {
+ _index++;
+ }
+ }
+
+ if (!End && (Peek() == 'E' || Peek() == 'e'))
+ {
+ _index++;
+ if (!End && (Peek() == '+' || Peek() == '-'))
+ {
+ _index++;
+ }
+
+ while (!End && char.IsDigit(Peek()))
+ {
+ _index++;
+ }
+ }
+
+ var token = text[start.._index];
+ if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
+ {
+ throw Error($"Invalid numeric literal '{token}'.");
+ }
+
+ return new Step242NumberValue(value);
+ }
+
+ private string ReadIdentifier()
+ {
+ var start = _index;
+ while (!End && (char.IsLetterOrDigit(Peek()) || Peek() == '_'))
+ {
+ _index++;
+ }
+
+ if (start == _index)
+ {
+ throw Error("Expected identifier.");
+ }
+
+ return text[start.._index];
+ }
+
+ private int ReadInteger()
+ {
+ var start = _index;
+ while (!End && char.IsDigit(Peek()))
+ {
+ _index++;
+ }
+
+ if (start == _index || !int.TryParse(text[start.._index], NumberStyles.None, CultureInfo.InvariantCulture, out var value))
+ {
+ throw Error("Expected integer id.");
+ }
+
+ return value;
+ }
+
+ private void Expect(char expected)
+ {
+ if (End || text[_index] != expected)
+ {
+ throw Error($"Expected '{expected}'.");
+ }
+
+ _index++;
+ }
+
+ private Step242ParseException Error(string message) => new($"{message} (position {_index}).", "Parser");
+ }
+}
+
+internal sealed class Step242ParseException(string message, string sourceTag) : Exception(message)
+{
+ public string SourceTag { get; } = sourceTag;
+}
+
+internal sealed record Step242ParsedEntity(int Id, string Name, IReadOnlyList<Step242Value> Arguments);
+
+internal sealed class Step242ParsedDocument
+{
+ private readonly Dictionary<int, Step242ParsedEntity> _entitiesById;
+
+ public Step242ParsedDocument(IReadOnlyList<Step242ParsedEntity> entities)
+ {
+ Entities = entities;
+ _entitiesById = entities.ToDictionary(e => e.Id);
+ }
+
+ public IReadOnlyList<Step242ParsedEntity> Entities { get; }
+
+ public KernelResult<Step242ParsedEntity> TryGetEntity(int id, string? expectedName = null)
+ {
+ if (!_entitiesById.TryGetValue(id, out var entity))
+ {
+ return Failure($"Missing referenced entity #{id}.", $"Entity:{id}");
+ }
+
+ if (expectedName is not null && !string.Equals(entity.Name, expectedName, StringComparison.OrdinalIgnoreCase))
+ {
+ return Failure($"Entity #{id} expected '{expectedName}' but found '{entity.Name}'.", $"Entity:{id}");
+ }
+
+ return KernelResult<Step242ParsedEntity>.Success(entity);
+ }
+
+ private static KernelResult<Step242ParsedEntity> Failure(string message, string source) =>
+ KernelResult<Step242ParsedEntity>.Failure([
+ new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)
+ ]);
+}
+
+internal abstract record Step242Value;
+
+internal sealed record Step242EntityReference(int TargetId) : Step242Value;
+
+internal sealed record Step242StringValue(string Value) : Step242Value;
+
+internal sealed record Step242NumberValue(double Value) : Step242Value;
+
+internal sealed record Step242BooleanValue(bool Value) : Step242Value;
+
+internal sealed record Step242EnumValue(string Value) : Step242Value;
+
+internal sealed record Step242ListValue(IReadOnlyList<Step242Value> Items) : Step242Value;
+
+internal sealed record Step242OmittedValue : Step242Value
+{
+ public static Step242OmittedValue Instance { get; } = new();
+}
diff --git a/docs/milestones.md b/docs/milestones.md
index e13aba46..d3c39592 100644
--- a/docs/milestones.md
+++ b/docs/milestones.md
@@ -207,3 +207,13 @@
- [x] Return structured `NotImplemented` diagnostics for unsupported export cases (for example: periodic/loopless sphere face, non-planar surfaces, non-line edge curves, multi-body layouts).
- [x] Add regression tests for successful box export structure, deterministic output stability, and unsupported-case no-throw diagnostics.
- [x] Defer AP242 import work to M23 and broader schema/entity coverage to later milestones.
+
+## M23 — AP242 Import v1 (Subset Only, Export-Roundtrip-Oriented)
+
+- [x] Add a subset-only AP242 import entry point (`Step242Importer.ImportBody(string)`) that returns `KernelResult<BrepBody>` and operates on STEP text (no file I/O).
+- [x] Add a minimal STEP text parser/AST for M22-compatible entity assignment syntax (`#n=ENTITY(...);`), references, strings, numbers, logicals, and lists.
+- [x] Decode and map the M22 export subset (line edges + planar faces with loop/shell topology) into kernel topology, geometry, and bindings.
+- [x] Run `BrepBindingValidator` as the final import acceptance gate; return structured diagnostics on parse/import/validation failures.
+- [x] Add importer-focused tests for success, M22 export→import round-trip (box subset), and malformed/unsupported no-throw behavior.
+- [x] Explicitly keep support narrow: arbitrary third-party STEP/AP242 files are expected to fail with diagnostics; broader schema/entity coverage is deferred.
+- [x] Defer import scope expansion and broader round-trip reliability hardening to M24.