Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Harden analyze truthfulness output and probes
Yuechen Lie2c5450edbcf
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.csindex c2d2cfbb..5fdd816f 100644--- a/Aetheris.CLI.Tests/CliBaselineTests.cs+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs@@ -1,4 +1,6 @@using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;namespace Aetheris.CLI.Tests;@@ -50,35 +52,40 @@ public sealed class CliBaselineTestsAssert.Equal(12, summary.GetProperty("edgeCount").GetInt32());Assert.Equal(8, summary.GetProperty("vertexCount").GetInt32());Assert.Equal("enclosed-manifold", summary.GetProperty("structuralAssessment").GetString());+ Assert.Equal(0, summary.GetProperty("surfaceFamilies").GetProperty("bspline").GetInt32());}[Fact]- public void Analyze_Command_Supports_Face_Detail()+ public void Analyze_Command_Provides_Numeric_Face_Detail_Anchors(){+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateCylinder(5d, 12d).Value, "cli-cylinder-face-truth");var stdout = new StringWriter();var stderr = new StringWriter();var exitCode = Aetheris.CLI.CliRunner.Run(- ["analyze", Path.Combine(RepoRoot, "testdata/firmament/exports/box_basic.step"), "--face", "1", "--json"],+ ["analyze", stepPath, "--face", "2", "--json"],stdout,stderr);Assert.Equal(0, exitCode);using var doc = JsonDocument.Parse(stdout.ToString());var face = doc.RootElement.GetProperty("face");- Assert.Equal(1, face.GetProperty("faceId").GetInt32());+ Assert.Equal(2, face.GetProperty("faceId").GetInt32());Assert.Equal("Plane", face.GetProperty("surfaceType").GetString());- Assert.True(face.GetProperty("adjacentEdgeIds").GetArrayLength() >= 4);+ AssertPoint(face.GetProperty("anchorPoint"), 0d, 0d, 6d);+ AssertVector(face.GetProperty("planarNormal"), 0d, 0d, 1d);+ Assert.Single(face.GetProperty("adjacentEdgeIds").EnumerateArray());}[Fact]- public void Analyze_Command_Supports_Edge_Detail()+ public void Analyze_Command_Reports_Truthful_Edge_Length_Fields(){+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateCylinder(5d, 8d).Value, "cli-cylinder-edge-truth");var stdout = new StringWriter();var stderr = new StringWriter();var exitCode = Aetheris.CLI.CliRunner.Run(- ["analyze", Path.Combine(RepoRoot, "testdata/firmament/exports/box_basic.step"), "--edge", "1", "--json"],+ ["analyze", stepPath, "--edge", "1", "--json"],stdout,stderr);@@ -87,7 +94,21 @@ public sealed class CliBaselineTestsvar edge = doc.RootElement.GetProperty("edge");Assert.Equal(1, edge.GetProperty("edgeId").GetInt32());Assert.Equal("Line3", edge.GetProperty("curveType").GetString());- Assert.True(edge.GetProperty("adjacentFaceIds").GetArrayLength() >= 1);+ Assert.Equal(8d, edge.GetProperty("arcLength").GetDouble(), 8);+ Assert.Equal(8d, edge.GetProperty("parameterRange").GetDouble(), 8);++ stdout.GetStringBuilder().Clear();+ stderr.GetStringBuilder().Clear();+ exitCode = Aetheris.CLI.CliRunner.Run(+ ["analyze", stepPath, "--edge", "2", "--json"],+ stdout,+ stderr);+ Assert.Equal(0, exitCode);+ using var circleDoc = JsonDocument.Parse(stdout.ToString());+ var circleEdge = circleDoc.RootElement.GetProperty("edge");+ Assert.Equal("Circle3", circleEdge.GetProperty("curveType").GetString());+ Assert.Equal(2d * double.Pi, circleEdge.GetProperty("parameterRange").GetDouble(), 8);+ Assert.Equal(10d * double.Pi, circleEdge.GetProperty("arcLength").GetDouble(), 8);}[Fact]@@ -109,6 +130,99 @@ public sealed class CliBaselineTestsAssert.True(vertex.GetProperty("incidentEdgeIds").GetArrayLength() >= 1);}+ [Fact]+ public void Analyze_Command_Provides_Cylinder_Sphere_And_Torus_Anchors()+ {+ var cylinderStepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateCylinder(4d, 12d).Value, "cli-cylinder-face-anchor");+ var sphereStepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateSphere(3d).Value, "cli-sphere-face-anchor");+ var torusStepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateTorus(7d, 2d).Value, "cli-torus-face-anchor");++ var cylinderFace = AnalyzeFace(cylinderStepPath, 1);+ Assert.Equal("Cylinder", cylinderFace.GetProperty("surfaceType").GetString());+ AssertPoint(cylinderFace.GetProperty("anchorPoint"), 0d, 0d, -6d);+ AssertVector(cylinderFace.GetProperty("axis"), 0d, 0d, 1d);+ Assert.Equal(4d, cylinderFace.GetProperty("radius").GetDouble(), 8);++ var sphereFace = AnalyzeFace(sphereStepPath, 1);+ Assert.Equal("Sphere", sphereFace.GetProperty("surfaceType").GetString());+ AssertPoint(sphereFace.GetProperty("anchorPoint"), 0d, 0d, 0d);+ AssertVector(sphereFace.GetProperty("axis"), 0d, 0d, 1d);+ Assert.Equal(3d, sphereFace.GetProperty("radius").GetDouble(), 8);++ var torusFace = AnalyzeFace(torusStepPath, 1);+ Assert.Equal("Torus", torusFace.GetProperty("surfaceType").GetString());+ AssertPoint(torusFace.GetProperty("anchorPoint"), 0d, 0d, 0d);+ AssertVector(torusFace.GetProperty("axis"), 0d, 1d, 0d);+ Assert.Equal(7d, torusFace.GetProperty("majorRadius").GetDouble(), 8);+ Assert.Equal(2d, torusFace.GetProperty("minorRadius").GetDouble(), 8);+ }++ [Fact]+ public void Analyze_Command_Returns_Structured_Json_Failure()+ {+ var stdout = new StringWriter();+ var stderr = new StringWriter();++ var missingPath = Path.Combine(RepoRoot, "testdata/firmament/exports/does-not-exist.step");+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", missingPath, "--json"], stdout, stderr);+ Assert.Equal(1, exitCode);+ Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()));++ using var doc = JsonDocument.Parse(stdout.ToString());+ var root = doc.RootElement;+ Assert.False(root.GetProperty("success").GetBoolean());+ Assert.Equal(Path.GetFullPath(missingPath), root.GetProperty("stepPath").GetString());+ Assert.True(root.GetProperty("error").GetString()?.Length > 0);+ }++ [Fact]+ public void Analyze_Command_Treats_Periodic_Seam_Coedge_Incidence_As_Enclosed()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateTorus(6d, 1d).Value, "cli-torus-structure");+ var stdout = new StringWriter();+ var stderr = new StringWriter();++ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", stepPath, "--json"], stdout, stderr);+ Assert.Equal(0, exitCode);+ using var doc = JsonDocument.Parse(stdout.ToString());+ var summary = doc.RootElement.GetProperty("summary");+ Assert.Equal("enclosed-manifold", summary.GetProperty("structuralAssessment").GetString());+ Assert.Contains("coedge incidence", summary.GetProperty("structuralAssessmentBasis").GetString(), StringComparison.OrdinalIgnoreCase);+ }++ private static JsonElement AnalyzeFace(string stepPath, int faceId)+ {+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", stepPath, "--face", faceId.ToString(), "--json"], stdout, stderr);+ Assert.Equal(0, exitCode);+ using var doc = JsonDocument.Parse(stdout.ToString());+ return doc.RootElement.GetProperty("face").Clone();+ }++ private static string ExportPrimitiveToTempStep(BrepBody body, string stem)+ {+ var export = Step242Exporter.ExportBody(body);+ Assert.True(export.IsSuccess, string.Join(Environment.NewLine, export.Diagnostics.Select(d => d.Message)));+ var outputPath = Path.Combine(Path.GetTempPath(), $"{stem}-{Guid.NewGuid():N}.step");+ File.WriteAllText(outputPath, export.Value);+ return outputPath;+ }++ private static void AssertPoint(JsonElement point, double x, double y, double z)+ {+ Assert.Equal(x, point.GetProperty("x").GetDouble(), 8);+ Assert.Equal(y, point.GetProperty("y").GetDouble(), 8);+ Assert.Equal(z, point.GetProperty("z").GetDouble(), 8);+ }++ private static void AssertVector(JsonElement vector, double x, double y, double z)+ {+ Assert.Equal(x, vector.GetProperty("x").GetDouble(), 8);+ Assert.Equal(y, vector.GetProperty("y").GetDouble(), 8);+ Assert.Equal(z, vector.GetProperty("z").GetDouble(), 8);+ }+private static string FindRepoRoot(){var directory = new DirectoryInfo(AppContext.BaseDirectory);diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 1a732693..b2b56bbb 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -146,7 +146,30 @@ public static class CliRunnerreturn 1;}- var analysis = StepAnalyzer.Analyze(stepPath, faceId, edgeId, vertexId);+ AnalyzeResult analysis;+ try+ {+ analysis = StepAnalyzer.Analyze(stepPath, faceId, edgeId, vertexId);+ }+ catch (Exception ex)+ {+ if (json)+ {+ stdout.WriteLine(JsonSerializer.Serialize(new+ {+ success = false,+ stepPath = Path.GetFullPath(stepPath),+ error = ex.Message+ }, JsonOptions));+ }+ else+ {+ stderr.WriteLine(ex.Message);+ }++ return 1;+ }+if (json){stdout.WriteLine(JsonSerializer.Serialize(analysis, JsonOptions));@@ -176,12 +199,12 @@ public static class CliRunnerif (analysis.Face is not null){- stdout.WriteLine($"Face {analysis.Face.FaceId}: type={analysis.Face.SurfaceType}, bbox={FormatBox(analysis.Face.BoundingBox)}, point={FormatPoint(analysis.Face.RepresentativePoint)}, normal={FormatVector(analysis.Face.PlanarNormal)}, axis={FormatVector(analysis.Face.Axis)}, radius={FormatDouble(analysis.Face.Radius)}, semiAngleRadians={FormatDouble(analysis.Face.SemiAngleRadians)}, edges=[{string.Join(",", analysis.Face.AdjacentEdgeIds)}]");+ stdout.WriteLine($"Face {analysis.Face.FaceId}: type={analysis.Face.SurfaceType}, bbox={FormatBox(analysis.Face.BoundingBox)}, point={FormatPoint(analysis.Face.RepresentativePoint)}, anchor={FormatPoint(analysis.Face.AnchorPoint)}, apex={FormatPoint(analysis.Face.Apex)}, normal={FormatVector(analysis.Face.PlanarNormal)}, axis={FormatVector(analysis.Face.Axis)}, radius={FormatDouble(analysis.Face.Radius)}, placementRadius={FormatDouble(analysis.Face.PlacementRadius)}, majorRadius={FormatDouble(analysis.Face.MajorRadius)}, minorRadius={FormatDouble(analysis.Face.MinorRadius)}, semiAngleRadians={FormatDouble(analysis.Face.SemiAngleRadians)}, edges=[{string.Join(",", analysis.Face.AdjacentEdgeIds)}]");}if (analysis.Edge is not null){- stdout.WriteLine($"Edge {analysis.Edge.EdgeId}: curve={analysis.Edge.CurveType}, start={analysis.Edge.StartVertexId}:{FormatPoint(analysis.Edge.StartVertex)}, end={analysis.Edge.EndVertexId}:{FormatPoint(analysis.Edge.EndVertex)}, faces=[{string.Join(",", analysis.Edge.AdjacentFaceIds)}], length={FormatDouble(analysis.Edge.Length)}");+ stdout.WriteLine($"Edge {analysis.Edge.EdgeId}: curve={analysis.Edge.CurveType}, start={analysis.Edge.StartVertexId}:{FormatPoint(analysis.Edge.StartVertex)}, end={analysis.Edge.EndVertexId}:{FormatPoint(analysis.Edge.EndVertex)}, faces=[{string.Join(",", analysis.Edge.AdjacentFaceIds)}], parameterRange={FormatDouble(analysis.Edge.ParameterRange)}, arcLength={FormatDouble(analysis.Edge.ArcLength)}");}if (analysis.Vertex is not null)diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.csindex ef3b42fb..947011ab 100644--- a/Aetheris.CLI/StepAnalysisModels.cs+++ b/Aetheris.CLI/StepAnalysisModels.cs@@ -18,9 +18,14 @@ public sealed record FaceDetail(string SurfaceType,BoundingBox3D? BoundingBox,Point3D? RepresentativePoint,+ Point3D? AnchorPoint,+ Point3D? Apex,Vector3D? PlanarNormal,Vector3D? Axis,double? Radius,+ double? PlacementRadius,+ double? MajorRadius,+ double? MinorRadius,double? SemiAngleRadians,IReadOnlyList<int> AdjacentEdgeIds);@@ -32,7 +37,8 @@ public sealed record EdgeDetail(int EndVertexId,Point3D? EndVertex,IReadOnlyList<int> AdjacentFaceIds,- double? Length);+ double? ParameterRange,+ double? ArcLength);public sealed record VertexDetail(int VertexId,diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex e67f1493..7d12be9b 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -38,6 +38,7 @@ public static class StepAnalyzer["cone"] = 0,["sphere"] = 0,["torus"] = 0,+ ["bspline"] = 0,["other"] = 0};@@ -56,6 +57,7 @@ public static class StepAnalyzercase SurfaceGeometryKind.Cone: surfaceFamilies["cone"]++; break;case SurfaceGeometryKind.Sphere: surfaceFamilies["sphere"]++; break;case SurfaceGeometryKind.Torus: surfaceFamilies["torus"]++; break;+ case SurfaceGeometryKind.BSplineSurfaceWithKnots: surfaceFamilies["bspline"]++; break;default: surfaceFamilies["other"]++; break;}}@@ -66,11 +68,11 @@ public static class StepAnalyzernotes.Add("Bounding box unavailable because one or more vertices did not expose XYZ coordinates.");}- var edgeFaces = BuildEdgeFaceAdjacency(body);- var leakyEdges = edgeFaces.Count(kvp => kvp.Value.Count == 1);- var nonManifoldEdges = edgeFaces.Count(kvp => kvp.Value.Count != 2);+ var edgeUseCounts = BuildEdgeFaceIncidenceCounts(body);+ var leakyEdges = edgeUseCounts.Count(kvp => kvp.Value == 1);+ var nonManifoldEdges = edgeUseCounts.Count(kvp => kvp.Value != 2);var structural = nonManifoldEdges == 0 ? "enclosed-manifold" : (leakyEdges > 0 ? "leaky-or-open" : "non-manifold");- var basis = "derived from imported topology edge-to-face adjacency counts";+ var basis = "derived from imported topology edge-to-face coedge incidence counts";return new AnalyzeSummary(topology.Bodies.Count(),@@ -114,33 +116,57 @@ public static class StepAnalyzerif (!body.TryGetFaceSurface(faceId, out var surface) || surface is null){- return new FaceDetail(faceId.Value, "unknown", bbox, rep, null, null, null, null, edgeIds);+ return new FaceDetail(faceId.Value, "unknown", bbox, rep, null, null, null, null, null, null, null, null, null, edgeIds);}+ Point3D? anchor = null;+ Point3D? apex = null;Vector3D? normal = null;Vector3D? axis = null;double? radius = null;+ double? placementRadius = null;+ double? majorRadius = null;+ double? minorRadius = null;double? semiAngle = null;if (surface.Plane is { } plane){+ anchor = plane.Origin;normal = plane.Normal.ToVector();}if (surface.Cylinder is { } cylinder){+ anchor = cylinder.Origin;axis = cylinder.Axis.ToVector();radius = cylinder.Radius;}if (surface.Cone is { } cone){+ anchor = cone.PlacementOrigin;+ apex = cone.Apex;axis = cone.Axis.ToVector();semiAngle = cone.SemiAngleRadians;- radius = cone.PlacementRadius;+ placementRadius = cone.PlacementRadius;}- return new FaceDetail(faceId.Value, surface.Kind.ToString(), bbox, rep, normal, axis, radius, semiAngle, edgeIds);+ if (surface.Sphere is { } sphere)+ {+ anchor = sphere.Center;+ axis = sphere.Axis.ToVector();+ radius = sphere.Radius;+ }++ if (surface.Torus is { } torus)+ {+ anchor = torus.Center;+ axis = torus.Axis.ToVector();+ majorRadius = torus.MajorRadius;+ minorRadius = torus.MinorRadius;+ }++ return new FaceDetail(faceId.Value, surface.Kind.ToString(), bbox, rep, anchor, apex, normal, axis, radius, placementRadius, majorRadius, minorRadius, semiAngle, edgeIds);}private static EdgeDetail BuildEdgeDetail(BrepBody body, EdgeId edgeId, ICollection<string> notes)@@ -151,17 +177,31 @@ public static class StepAnalyzer}var curveType = "unknown";- double? length = null;+ double? parameterRange = null;+ double? arcLength = null;if (body.Bindings.TryGetEdgeBinding(edgeId, out var binding)){curveType = binding.TrimInterval is null ? "untrimmed" : "trimmed";- length = binding.TrimInterval is { } interval ? interval.End - interval.Start : null;+ parameterRange = binding.TrimInterval is { } interval ? interval.End - interval.Start : null;if (body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) && curve is not null){curveType = curve.Kind == CurveGeometryKind.Unsupported? $"Unsupported({curve.UnsupportedKind ?? "unknown"})": curve.Kind.ToString();++ if (binding.TrimInterval is { } trim)+ {+ switch (curve.Kind)+ {+ case CurveGeometryKind.Line3:+ arcLength = double.Abs(trim.End - trim.Start);+ break;+ case CurveGeometryKind.Circle3 when curve.Circle3 is { } circle:+ arcLength = circle.Radius * double.Abs(trim.End - trim.Start);+ break;+ }+ }}}else@@ -176,7 +216,7 @@ public static class StepAnalyzer? faces.Select(id => id.Value).OrderBy(v => v).ToArray(): [];- return new EdgeDetail(edgeId.Value, curveType, edge.StartVertexId.Value, startPoint, edge.EndVertexId.Value, endPoint, adjacentFaces, length);+ return new EdgeDetail(edgeId.Value, curveType, edge.StartVertexId.Value, startPoint, edge.EndVertexId.Value, endPoint, adjacentFaces, parameterRange, arcLength);}private static VertexDetail BuildVertexDetail(BrepBody body, VertexId vertexId, ICollection<string> notes)@@ -256,4 +296,33 @@ public static class StepAnalyzerreturn edgeFaces;}++ private static Dictionary<EdgeId, int> BuildEdgeFaceIncidenceCounts(BrepBody body)+ {+ var edgeCounts = new Dictionary<EdgeId, int>();++ foreach (var face in body.Topology.Faces)+ {+ foreach (var loopId in face.LoopIds)+ {+ if (!body.Topology.TryGetLoop(loopId, out var loop) || loop is null)+ {+ continue;+ }++ foreach (var coedgeId in loop.CoedgeIds)+ {+ if (!body.Topology.TryGetCoedge(coedgeId, out var coedge) || coedge is null)+ {+ continue;+ }++ edgeCounts.TryGetValue(coedge.EdgeId, out var count);+ edgeCounts[coedge.EdgeId] = count + 1;+ }+ }+ }++ return edgeCounts;+ }}