Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add narrow TESSELLATED_SOLID tg import lane for FTC08
Yuechen Li77b6aaa04fe3
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.csindex 052ebc11..aa633025 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs@@ -104,6 +104,38 @@ public sealed class Step242ImporterTestsAssert.StartsWith("Multiple MANIFOLD_SOLID_BREP", diagnostic.Message, StringComparison.Ordinal);}+ [Fact]+ public void ImportBody_TessellatedSolidWithComplexTriangulatedFace_ImportsWithoutManifoldSolidBrep()+ {+ const string tessellated = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=TESSELLATED_SOLID('part',(#2));\n#2=TESSELLATED_SHELL('shell',(#3));\n#3=COMPLEX_TRIANGULATED_FACE('',#10,3,((0,0,1)),#20,(1,2,3),((1,2,3)),());\n#10=COORDINATES_LIST('',3,((0,0,0),(1,0,0),(0,1,0)));\n#20=PLANE('',#30);\n#30=AXIS2_PLACEMENT_3D('',#31,#32,#33);\n#31=CARTESIAN_POINT('',(0,0,0));\n#32=DIRECTION('',(0,0,1));\n#33=DIRECTION('',(1,0,0));\nENDSEC;\nEND-ISO-10303-21;";++ var import = Step242Importer.ImportBody(tessellated);++ Assert.True(import.IsSuccess);+ Assert.Single(import.Value.Topology.Faces);+ Assert.DoesNotContain(import.Diagnostics, d => string.Equals(d.Source, "Importer.TopologyRoot", StringComparison.Ordinal));+ }++ [Fact]+ public void NistFtc08Tg_TessellatedVariant_ImportsDeterministically()+ {+ var text = LoadFixture("testdata/step242/nist/FTC/nist_ftc_08_asme1_ap242-e1-tg.stp");++ var first = Step242Importer.ImportBody(text);+ var second = Step242Importer.ImportBody(text);++ Assert.True(first.IsSuccess, string.Join(" | ", first.Diagnostics.Select(d => $"{d.Source}: {d.Message}")));+ Assert.True(second.IsSuccess, string.Join(" | ", second.Diagnostics.Select(d => $"{d.Source}: {d.Message}")));++ Assert.Equal(first.Value.Topology.Vertices.Count(), second.Value.Topology.Vertices.Count());+ Assert.Equal(first.Value.Topology.Edges.Count(), second.Value.Topology.Edges.Count());+ Assert.Equal(first.Value.Topology.Faces.Count(), second.Value.Topology.Faces.Count());++ var tessellation = BrepDisplayTessellator.Tessellate(first.Value);+ Assert.True(tessellation.IsSuccess);+ Assert.NotEmpty(tessellation.Value.FacePatches);+ }+[Fact]public void ImportBody_DegenerateDirection_ReturnsDiagnosticWithoutThrowing(){diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 26e7a762..53c176e8 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -76,6 +76,12 @@ public static class Step242Importerprivate static KernelResult<BrepBody> MapSubset(Step242ParsedDocument document){+ var tessellatedSolidResult = TryImportTessellatedSolid(document);+ if (tessellatedSolidResult is not null)+ {+ return tessellatedSolidResult;+ }+var manifoldSolidBreps = document.Entities.Where(e => string.Equals(e.Name, "MANIFOLD_SOLID_BREP", StringComparison.OrdinalIgnoreCase)).ToList();@@ -443,6 +449,342 @@ public static class Step242Importerreturn KernelResult<BrepBody>.Success(body, validation.Diagnostics);}+ private static KernelResult<BrepBody>? TryImportTessellatedSolid(Step242ParsedDocument document)+ {+ var tessellatedSolids = document.Entities+ .Where(e => string.Equals(e.Name, "TESSELLATED_SOLID", StringComparison.OrdinalIgnoreCase))+ .ToList();+ if (tessellatedSolids.Count == 0)+ {+ return null;+ }++ if (tessellatedSolids.Count > 1)+ {+ return Failure("Multiple TESSELLATED_SOLID roots are unsupported in M118 tessellated import subset.", "Importer.TessellatedSolid.SingleRoot");+ }++ var shellRefsResult = Step242SubsetDecoder.ReadReferenceList(tessellatedSolids[0], 1, "TESSELLATED_SOLID shells");+ if (!shellRefsResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(shellRefsResult.Diagnostics);+ }++ var faceEntityIds = new List<int>();+ foreach (var shellRef in shellRefsResult.Value)+ {+ var shellResult = document.TryGetEntity(shellRef.TargetId);+ if (!shellResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(shellResult.Diagnostics);+ }++ if (string.Equals(shellResult.Value.Name, "COMPLEX_TRIANGULATED_FACE", StringComparison.OrdinalIgnoreCase))+ {+ faceEntityIds.Add(shellResult.Value.Id);+ continue;+ }++ if (!string.Equals(shellResult.Value.Name, "TESSELLATED_SHELL", StringComparison.OrdinalIgnoreCase))+ {+ return Failure($"TESSELLATED_SOLID supports TESSELLATED_SHELL or direct COMPLEX_TRIANGULATED_FACE items in M118 subset; got '{shellResult.Value.Name}'.", "Importer.TessellatedSolid.ShellType");+ }++ var shellFaceRefsResult = Step242SubsetDecoder.ReadReferenceList(shellResult.Value, 1, "TESSELLATED_SHELL faces");+ if (!shellFaceRefsResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(shellFaceRefsResult.Diagnostics);+ }++ faceEntityIds.AddRange(shellFaceRefsResult.Value.Select(r => r.TargetId));+ }++ var builder = new TopologyBuilder();+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var allFaceIds = new List<FaceId>();+ var coedges = new List<Coedge>();+ var nextCurveGeometryId = 1;+ var nextSurfaceGeometryId = 1;++ for (var faceIndex = 0; faceIndex < faceEntityIds.Count; faceIndex++)+ {+ var faceEntityResult = document.TryGetEntity(faceEntityIds[faceIndex]);+ if (!faceEntityResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(faceEntityResult.Diagnostics);+ }++ if (!string.Equals(faceEntityResult.Value.Name, "COMPLEX_TRIANGULATED_FACE", StringComparison.OrdinalIgnoreCase))+ {+ return Failure(+ $"TESSELLATED_SOLID supports only COMPLEX_TRIANGULATED_FACE in M118 subset; got '{faceEntityResult.Value.Name}'.",+ "Importer.TessellatedSolid.FaceFamily");+ }++ var trianglesResult = DecodeComplexTriangulatedFaceTriangles(document, faceEntityResult.Value);+ if (!trianglesResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(trianglesResult.Diagnostics);+ }++ foreach (var triangle in trianglesResult.Value)+ {+ var buildResult = AppendTriangleFace(builder, geometry, bindings, coedges, triangle, ref nextCurveGeometryId, ref nextSurfaceGeometryId);+ if (!buildResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(buildResult.Diagnostics);+ }++ if (buildResult.Value is FaceId faceId)+ {+ allFaceIds.Add(faceId);+ }+ }+ }++ foreach (var coedge in coedges)+ {+ builder.AddCoedge(coedge);+ }++ if (allFaceIds.Count == 0)+ {+ return Failure("TESSELLATED_SOLID contains no triangulated polygons to import in M118 subset.", "Importer.TessellatedSolid.Empty");+ }++ var shellId = builder.AddShell(allFaceIds);+ 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<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>> DecodeComplexTriangulatedFaceTriangles(+ Step242ParsedDocument document,+ Step242ParsedEntity faceEntity)+ {+ if (faceEntity.Arguments.Count < 7)+ {+ return FailureTessellatedFaceTriangles("COMPLEX_TRIANGULATED_FACE requires at least 7 arguments.", "Importer.TessellatedSolid.ComplexTriangulatedFace");+ }++ var coordinatesRefResult = Step242SubsetDecoder.ReadReference(faceEntity, 1, "COMPLEX_TRIANGULATED_FACE coordinates");+ if (!coordinatesRefResult.IsSuccess)+ {+ return KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Failure(coordinatesRefResult.Diagnostics);+ }++ var coordinatesEntityResult = document.TryGetEntity(coordinatesRefResult.Value.TargetId, "COORDINATES_LIST");+ if (!coordinatesEntityResult.IsSuccess)+ {+ return KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Failure(coordinatesEntityResult.Diagnostics);+ }++ var coordinatesResult = ReadCoordinatesListPoints(coordinatesEntityResult.Value);+ if (!coordinatesResult.IsSuccess)+ {+ return KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Failure(coordinatesResult.Diagnostics);+ }++ var pointNodeIndicesResult = ReadOneBasedIntegerList(faceEntity, 5, "COMPLEX_TRIANGULATED_FACE pnindex", "Importer.TessellatedSolid.ComplexTriangulatedFace");+ if (!pointNodeIndicesResult.IsSuccess)+ {+ return KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Failure(pointNodeIndicesResult.Diagnostics);+ }++ var polygonsResult = ReadOneBasedIntegerListList(faceEntity, 6, "COMPLEX_TRIANGULATED_FACE polygon loops", "Importer.TessellatedSolid.ComplexTriangulatedFace");+ if (!polygonsResult.IsSuccess)+ {+ return KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Failure(polygonsResult.Diagnostics);+ }++ var triangles = new List<(Point3D A, Point3D B, Point3D C)>();+ var pnindex = pointNodeIndicesResult.Value;+ var coordinates = coordinatesResult.Value;++ foreach (var polygon in polygonsResult.Value)+ {+ if (polygon.Count < 3)+ {+ continue;+ }++ var polygonCoordinates = new List<Point3D>(polygon.Count);+ for (var i = 0; i < polygon.Count; i++)+ {+ var polygonNodeIndex = polygon[i] - 1;+ if (polygonNodeIndex < 0 || polygonNodeIndex >= pnindex.Count)+ {+ return FailureTessellatedFaceTriangles("COMPLEX_TRIANGULATED_FACE polygon index is outside pnindex range.", "Importer.TessellatedSolid.ComplexTriangulatedFace");+ }++ var coordinateIndex = pnindex[polygonNodeIndex] - 1;+ if (coordinateIndex < 0 || coordinateIndex >= coordinates.Count)+ {+ return FailureTessellatedFaceTriangles("COMPLEX_TRIANGULATED_FACE pnindex value is outside COORDINATES_LIST range.", "Importer.TessellatedSolid.ComplexTriangulatedFace");+ }++ polygonCoordinates.Add(coordinates[coordinateIndex]);+ }++ for (var i = 1; i < polygonCoordinates.Count - 1; i++)+ {+ triangles.Add((polygonCoordinates[0], polygonCoordinates[i], polygonCoordinates[i + 1]));+ }+ }++ return KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Success(triangles);+ }++ private static KernelResult<FaceId?> AppendTriangleFace(+ TopologyBuilder builder,+ BrepGeometryStore geometry,+ BrepBindingModel bindings,+ ICollection<Coedge> coedges,+ (Point3D A, Point3D B, Point3D C) triangle,+ ref int nextCurveGeometryId,+ ref int nextSurfaceGeometryId)+ {+ var ab = triangle.B - triangle.A;+ var ac = triangle.C - triangle.A;+ var normal = ab.Cross(ac);+ if (!Direction3D.TryCreate(normal, out var normalDirection))+ {+ return KernelResult<FaceId?>.Success(null);+ }++ var uAxis = Direction3D.Create(ab);+ var surfaceGeometryId = new SurfaceGeometryId(nextSurfaceGeometryId++);+ geometry.AddSurface(surfaceGeometryId, SurfaceGeometry.FromPlane(new PlaneSurface(triangle.A, normalDirection, uAxis)));++ var va = builder.AddVertex();+ var vb = builder.AddVertex();+ var vc = builder.AddVertex();++ var eab = builder.AddEdge(va, vb);+ var ebc = builder.AddEdge(vb, vc);+ var eca = builder.AddEdge(vc, va);++ var edges = new[]+ {+ (Edge: eab, Start: triangle.A, End: triangle.B),+ (Edge: ebc, Start: triangle.B, End: triangle.C),+ (Edge: eca, Start: triangle.C, End: triangle.A)+ };++ foreach (var edge in edges)+ {+ var edgeVector = edge.End - edge.Start;+ if (!Direction3D.TryCreate(edgeVector, out var edgeDirection))+ {+ return KernelResult<FaceId?>.Success(null);+ }++ var length = edgeVector.Length;+ var curveGeometryId = new CurveGeometryId(nextCurveGeometryId++);+ geometry.AddCurve(curveGeometryId, CurveGeometry.FromLine(new Line3Curve(edge.Start, edgeDirection)));+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edge.Edge, curveGeometryId, new ParameterInterval(0d, length), OrientedEdgeSense: true));+ }++ var loopId = builder.AllocateLoopId();+ var c1 = builder.AllocateCoedgeId();+ var c2 = builder.AllocateCoedgeId();+ var c3 = builder.AllocateCoedgeId();++ coedges.Add(new Coedge(c1, eab, loopId, c2, c3, IsReversed: false));+ coedges.Add(new Coedge(c2, ebc, loopId, c3, c1, IsReversed: false));+ coedges.Add(new Coedge(c3, eca, loopId, c1, c2, IsReversed: false));++ builder.AddLoop(new Loop(loopId, [c1, c2, c3]));+ var faceId = builder.AddFace([loopId]);+ bindings.AddFaceBinding(new FaceGeometryBinding(faceId, surfaceGeometryId));+ return KernelResult<FaceId?>.Success(faceId);+ }++ private static KernelResult<IReadOnlyList<Point3D>> ReadCoordinatesListPoints(Step242ParsedEntity coordinatesEntity)+ {+ if (coordinatesEntity.Arguments.Count < 3 || coordinatesEntity.Arguments[2] is not Step242ListValue points)+ {+ return FailureTessellatedFacePoints("COORDINATES_LIST points argument is missing or malformed.", "Importer.TessellatedSolid.CoordinatesList");+ }++ var result = new List<Point3D>(points.Items.Count);+ for (var i = 0; i < points.Items.Count; i++)+ {+ if (points.Items[i] is not Step242ListValue tuple || tuple.Items.Count != 3+ || tuple.Items[0] is not Step242NumberValue x+ || tuple.Items[1] is not Step242NumberValue y+ || tuple.Items[2] is not Step242NumberValue z)+ {+ return FailureTessellatedFacePoints("COORDINATES_LIST contains a non-XYZ tuple.", "Importer.TessellatedSolid.CoordinatesList");+ }++ result.Add(new Point3D(x.Value, y.Value, z.Value));+ }++ return KernelResult<IReadOnlyList<Point3D>>.Success(result);+ }++ private static KernelResult<IReadOnlyList<int>> ReadOneBasedIntegerList(Step242ParsedEntity entity, int argumentIndex, string context, string source)+ {+ if (argumentIndex < 0 || argumentIndex >= entity.Arguments.Count || entity.Arguments[argumentIndex] is not Step242ListValue list)+ {+ return FailureIntegerList($"{context}: expected integer list argument.", source);+ }++ var values = new List<int>(list.Items.Count);+ for (var i = 0; i < list.Items.Count; i++)+ {+ if (list.Items[i] is not Step242NumberValue number || number.Value <= 0 || number.Value != System.Math.Floor(number.Value))+ {+ return FailureIntegerList($"{context}: list item {i} must be a positive integer.", source);+ }++ values.Add((int)number.Value);+ }++ return KernelResult<IReadOnlyList<int>>.Success(values);+ }++ private static KernelResult<IReadOnlyList<IReadOnlyList<int>>> ReadOneBasedIntegerListList(Step242ParsedEntity entity, int argumentIndex, string context, string source)+ {+ if (argumentIndex < 0 || argumentIndex >= entity.Arguments.Count || entity.Arguments[argumentIndex] is not Step242ListValue outer)+ {+ return FailureIntegerListList($"{context}: expected list-of-list integer argument.", source);+ }++ var lists = new List<IReadOnlyList<int>>(outer.Items.Count);+ for (var i = 0; i < outer.Items.Count; i++)+ {+ if (outer.Items[i] is not Step242ListValue inner)+ {+ return FailureIntegerListList($"{context}: item {i} must be an integer list.", source);+ }++ var values = new List<int>(inner.Items.Count);+ for (var j = 0; j < inner.Items.Count; j++)+ {+ if (inner.Items[j] is not Step242NumberValue number || number.Value <= 0 || number.Value != System.Math.Floor(number.Value))+ {+ return FailureIntegerListList($"{context}: item {i} value {j} must be a positive integer.", source);+ }++ values.Add((int)number.Value);+ }++ lists.Add(values);+ }++ return KernelResult<IReadOnlyList<IReadOnlyList<int>>>.Success(lists);+ }+private static void AppendSupportedOrphanPlanarFaces(Step242ParsedDocument document, IList<int> faceEntityIds){var known = new HashSet<int>(faceEntityIds);@@ -2892,6 +3234,19 @@ public static class Step242Importerprivate static KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)> FailureSurfaceBinding(string message, string source) =>KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);+ private static KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>> FailureTessellatedFaceTriangles(string message, string source) =>+ KernelResult<IReadOnlyList<(Point3D A, Point3D B, Point3D C)>>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);+++ private static KernelResult<IReadOnlyList<Point3D>> FailureTessellatedFacePoints(string message, string source) =>+ KernelResult<IReadOnlyList<Point3D>>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);++ private static KernelResult<IReadOnlyList<int>> FailureIntegerList(string message, string source) =>+ KernelResult<IReadOnlyList<int>>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);++ private static KernelResult<IReadOnlyList<IReadOnlyList<int>>> FailureIntegerListList(string message, string source) =>+ KernelResult<IReadOnlyList<IReadOnlyList<int>>>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);+private static KernelResult<ParameterInterval> FailureCircleTrim(string message, string source) =>KernelResult<ParameterInterval>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source)]);diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.jsonindex 33aa343a..124aa162 100644--- a/testdata/step242/manifests/nist.v0.report.json+++ b/testdata/step242/manifests/nist.v0.report.json@@ -171,25 +171,25 @@"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e1-tg","path": "testdata/step242/nist/FTC/nist_ftc_08_asme1_ap242-e1-tg.stp","sizeBytes": 2120356,- "status": "importFail",- "firstFailureLayer": "importer-topology",+ "status": "success",+ "firstFailureLayer": "","firstDiagnostic": {- "code": "NotImplemented",- "source": "Importer.TopologyRoot",- "messagePrefix": "Missing MANIFOLD_SOLID_BREP root entity."+ "code": "Unknown",+ "source": "Audit.None",+ "messagePrefix": "No diagnostics."},- "diagnosticCount": 1,+ "diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 0,- "edges": 0,- "faces": 0+ "vertices": 10083,+ "edges": 10083,+ "faces": 3361},"tessellationCounts": {- "facePatches": 0,- "edgePolylines": 0+ "facePatches": 3361,+ "edgePolylines": 10083},- "canonicalSha256": null+ "canonicalSha256": "02272208c101eede63651658006f4b483dbabe4d7148654a12dc9e01f8509b19"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e2",