Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add orthographic map probe to analyze CLI
Yuechen Libcdec2e3eb9c
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.csindex 5a26586c..f4b20b61 100644--- a/Aetheris.CLI.Tests/CliBaselineTests.cs+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs@@ -150,6 +150,85 @@ public sealed class CliBaselineTestsAssert.True(vertex.GetProperty("incidentEdgeIds").GetArrayLength() >= 1);}+ [Fact]+ public void Analyze_Map_BoxTop_Respects_Grid_And_Reports_DepthThickness()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateBox(10d, 6d, 4d).Value, "cli-map-box-top");+ using var doc = RunAnalyzeMap(stepPath, "--top", 6, 8);+ var root = doc.RootElement;++ var metadata = root.GetProperty("metadata");+ Assert.Equal("Top", metadata.GetProperty("view").GetString());+ Assert.Equal(6, metadata.GetProperty("rows").GetInt32());+ Assert.Equal(8, metadata.GetProperty("cols").GetInt32());+ Assert.Equal("-Z", metadata.GetProperty("rayDirectionAxis").GetString());++ var summary = root.GetProperty("summary");+ Assert.Equal(48, summary.GetProperty("totalSamples").GetInt32());+ Assert.Equal(48, summary.GetProperty("hitSamples").GetInt32());+ Assert.Equal(0d, summary.GetProperty("entryDepthMin").GetDouble(), 8);+ Assert.Equal(0d, summary.GetProperty("entryDepthMax").GetDouble(), 8);+ Assert.Equal(4d, summary.GetProperty("thicknessMin").GetDouble(), 8);+ Assert.Equal(4d, summary.GetProperty("thicknessMax").GetDouble(), 8);++ var grid = root.GetProperty("grid");+ Assert.Equal(6, grid.GetArrayLength());+ Assert.Equal(8, grid[0].GetArrayLength());+ var sample = grid[0][0];+ Assert.True(sample.GetProperty("hit").GetBoolean());+ Assert.Equal(4d, sample.GetProperty("thickness").GetDouble(), 8);+ }++ [Fact]+ public void Analyze_Map_SphereTop_Reveals_Thickness_Variation_And_Empty_Samples()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateSphere(3d).Value, "cli-map-sphere-top");+ using var doc = RunAnalyzeMap(stepPath, "--top", 11, 11);+ var summary = doc.RootElement.GetProperty("summary");++ Assert.True(summary.GetProperty("hitSamples").GetInt32() > 0);+ Assert.True(summary.GetProperty("emptySamples").GetInt32() > 0);+ Assert.True(summary.GetProperty("thicknessMax").GetDouble() > summary.GetProperty("thicknessMin").GetDouble());+ }++ [Fact]+ public void Analyze_Map_BoxRight_Reports_Coherent_Face_Ids_And_Surface_Types()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateBox(10d, 6d, 4d).Value, "cli-map-box-right");+ using var doc = RunAnalyzeMap(stepPath, "--right", 5, 7);+ var summary = doc.RootElement.GetProperty("summary");+ Assert.Equal(1, summary.GetProperty("visibleFaceIds").GetArrayLength());+ Assert.Equal(1, summary.GetProperty("visibleSurfaceTypes").GetArrayLength());+ Assert.Equal("Plane", summary.GetProperty("visibleSurfaceTypes")[0].GetString());+ foreach (var row in doc.RootElement.GetProperty("grid").EnumerateArray())+ {+ foreach (var sample in row.EnumerateArray())+ {+ Assert.True(sample.GetProperty("hit").GetBoolean());+ Assert.True(sample.GetProperty("entryFaceId").GetInt32() > 0);+ Assert.Equal("Plane", sample.GetProperty("entrySurfaceType").GetString());+ }+ }+ }++ [Fact]+ public void Analyze_Map_Cli_Contract_Returns_Expected_Json_Shape()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateBox(8d, 8d, 2d).Value, "cli-map-contract");+ using var doc = RunAnalyzeMap(stepPath, "--front", 4, 5);+ var root = doc.RootElement;++ Assert.True(root.TryGetProperty("metadata", out _));+ Assert.True(root.TryGetProperty("summary", out _));+ Assert.True(root.TryGetProperty("grid", out var grid));+ Assert.True(root.TryGetProperty("notes", out _));+ Assert.Equal(4, grid.GetArrayLength());+ Assert.Equal(5, grid[0].GetArrayLength());+ Assert.True(grid[0][0].TryGetProperty("entryDepth", out _));+ Assert.True(grid[0][0].TryGetProperty("entryFaceId", out _));+ Assert.True(grid[0][0].TryGetProperty("entrySurfaceType", out _));+ }+[Fact]public void Analyze_Command_Provides_Cylinder_Sphere_And_Torus_Anchors_With_Sphere_Axis_Omitted(){@@ -482,6 +561,19 @@ public sealed class CliBaselineTestsreturn doc.RootElement.GetProperty("edge").Clone();}+ private static JsonDocument RunAnalyzeMap(string stepPath, string viewFlag, int rows, int cols)+ {+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(+ ["analyze", "map", stepPath, viewFlag, "--rows", rows.ToString(), "--cols", cols.ToString(), "--json"],+ stdout,+ stderr);+ Assert.Equal(0, exitCode);+ Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());+ return JsonDocument.Parse(stdout.ToString());+ }+private static string ExportPrimitiveToTempStep(BrepBody body, string stem){var export = Step242Exporter.ExportBody(body);diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 8599a3f2..5e0d2d40 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -1,4 +1,5 @@using System.Text.Json;+using System.Text.Json.Serialization;using Aetheris.Kernel.Firmament;namespace Aetheris.CLI;@@ -11,6 +12,11 @@ public static class CliRunnerPropertyNamingPolicy = JsonNamingPolicy.CamelCase};+ static CliRunner()+ {+ JsonOptions.Converters.Add(new JsonStringEnumConverter());+ }+public static int Run(string[] args, TextWriter stdout, TextWriter stderr){if (args.Length == 0)@@ -108,9 +114,15 @@ public static class CliRunnerif (args.Length == 0){stderr.WriteLine("Usage: aetheris analyze <file.step> [--face <id>] [--edge <id>] [--vertex <id>] [--json]");+ stderr.WriteLine(" or: aetheris analyze map <file.step> (--top|--bottom|--front|--back|--left|--right) --rows <N> --cols <N> --json");return 1;}+ if (string.Equals(args[0], "map", StringComparison.Ordinal))+ {+ return RunAnalyzeMap(args.Skip(1).ToArray(), stdout, stderr);+ }+var stepPath = args[0];int? faceId = null;int? edgeId = null;@@ -180,6 +192,116 @@ public static class CliRunnerreturn 0;}+ private static int RunAnalyzeMap(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0)+ {+ stderr.WriteLine("Usage: aetheris analyze map <file.step> (--top|--bottom|--front|--back|--left|--right) --rows <N> --cols <N> --json");+ return 1;+ }++ var stepPath = args[0];+ OrthographicView? view = null;+ var viewOptionCount = 0;+ int? rows = null;+ int? cols = null;+ var json = false;++ for (var i = 1; i < args.Length; i++)+ {+ switch (args[i])+ {+ case "--top":+ view = OrthographicView.Top;+ viewOptionCount++;+ break;+ case "--bottom":+ view = OrthographicView.Bottom;+ viewOptionCount++;+ break;+ case "--front":+ view = OrthographicView.Front;+ viewOptionCount++;+ break;+ case "--back":+ view = OrthographicView.Back;+ viewOptionCount++;+ break;+ case "--left":+ view = OrthographicView.Left;+ viewOptionCount++;+ break;+ case "--right":+ view = OrthographicView.Right;+ viewOptionCount++;+ break;+ case "--rows" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedRows):+ rows = parsedRows;+ break;+ case "--cols" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedCols):+ cols = parsedCols;+ break;+ case "--json":+ json = true;+ break;+ default:+ stderr.WriteLine($"Unknown analyze map option '{args[i]}'.");+ return 1;+ }+ }++ if (!view.HasValue || viewOptionCount != 1)+ {+ stderr.WriteLine("Analyze map requires exactly one orthographic view option (--top|--bottom|--front|--back|--left|--right).");+ return 1;+ }++ if (!rows.HasValue || !cols.HasValue)+ {+ stderr.WriteLine("Analyze map requires both --rows <N> and --cols <N>.");+ return 1;+ }++ if (rows <= 0 || cols <= 0)+ {+ stderr.WriteLine("Analyze map requires positive --rows and --cols values.");+ return 1;+ }++ OrthographicMapResult map;+ try+ {+ map = StepAnalyzer.AnalyzeMap(stepPath, view.Value, rows.Value, cols.Value);+ }+ 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)+ {+ stderr.WriteLine("Analyze map currently requires --json output.");+ return 1;+ }++ stdout.WriteLine(JsonSerializer.Serialize(map, JsonOptions));+ return 0;+ }+private static void WriteSummaryText(AnalyzeResult analysis, TextWriter stdout){var summary = analysis.Summary;diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.csindex 8a2160a1..3b61446d 100644--- a/Aetheris.CLI/StepAnalysisModels.cs+++ b/Aetheris.CLI/StepAnalysisModels.cs@@ -66,3 +66,54 @@ public sealed record AnalyzeResult(EdgeDetail? Edge,VertexDetail? Vertex,IReadOnlyList<string> Notes);++public enum OrthographicView+{+ Top,+ Bottom,+ Front,+ Back,+ Left,+ Right+}++public sealed record OrthographicMapMetadata(+ string SourcePath,+ BoundingBox3D BoundingBox,+ OrthographicView View,+ int Rows,+ int Cols,+ string PlaneAxisU,+ string PlaneAxisV,+ string RayDirectionAxis,+ string DepthReference);++public sealed record OrthographicMapSummary(+ int TotalSamples,+ int HitSamples,+ int EmptySamples,+ double? EntryDepthMin,+ double? EntryDepthMax,+ double? ThicknessMin,+ double? ThicknessMax,+ IReadOnlyList<int> VisibleFaceIds,+ IReadOnlyList<string> VisibleSurfaceTypes);++public sealed record OrthographicSample(+ bool Hit,+ double PlaneU,+ double PlaneV,+ double? EntryDepth,+ double? ExitDepth,+ double? Thickness,+ int? EntryFaceId,+ string? EntrySurfaceType,+ Point3D? EntryPoint,+ Vector3D? EntryNormal,+ Point3D? ExitPoint);++public sealed record OrthographicMapResult(+ OrthographicMapMetadata Metadata,+ OrthographicMapSummary Summary,+ IReadOnlyList<IReadOnlyList<OrthographicSample>> Grid,+ IReadOnlyList<string> Notes);diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex 6fa31789..1513a119 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -1,6 +1,8 @@using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Queries;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Numerics;using Aetheris.Kernel.Core.Step242;using Aetheris.Kernel.Core.Topology;@@ -32,6 +34,133 @@ public static class StepAnalyzerreturn new AnalyzeResult(stepPath, summary, face, edge, vertex, notes);}+ public static OrthographicMapResult AnalyzeMap(string stepPath, OrthographicView view, int rows, int cols)+ {+ var fullPath = Path.GetFullPath(stepPath);+ var import = Step242Importer.ImportBody(File.ReadAllText(fullPath));+ if (!import.IsSuccess)+ {+ throw new InvalidOperationException(string.Join(Environment.NewLine, import.Diagnostics.Select(d => d.Message)));+ }++ return AnalyzeImportedBodyMap(import.Value, fullPath, view, rows, cols);+ }++ public static OrthographicMapResult AnalyzeImportedBodyMap(BrepBody body, string stepPath, OrthographicView view, int rows, int cols)+ {+ if (rows <= 0 || cols <= 0)+ {+ throw new InvalidOperationException("Map rows and cols must be positive integers.");+ }++ var notes = new List<string>();+ var bbox = TryComputeBodyBoundingBox(body) ?? throw new InvalidOperationException("Map probe requires body vertex coordinates to compute a bounding box.");+ var frame = ResolveProjectionFrame(view, bbox);+ var epsilon = Math.Max(ToleranceContext.Default.Linear * 64d, 1e-5d);+ var faceSurfaceKinds = BuildFaceSurfaceKinds(body);++ var grid = new List<IReadOnlyList<OrthographicSample>>(rows);+ var hitSamples = 0;+ var entryDepths = new List<double>();+ var thicknesses = new List<double>();+ var visibleFaceIds = new HashSet<int>();+ var visibleSurfaceTypes = new HashSet<string>(StringComparer.Ordinal);++ for (var rowIndex = 0; rowIndex < rows; rowIndex++)+ {+ var row = new List<OrthographicSample>(cols);+ var planeV = frame.MinV + ((rowIndex + 0.5d) / rows * frame.RangeV);++ for (var colIndex = 0; colIndex < cols; colIndex++)+ {+ var planeU = frame.MinU + ((colIndex + 0.5d) / cols * frame.RangeU);+ var planePoint = frame.PlaneOrigin + (frame.UAxis * planeU) + (frame.VAxis * planeV);+ var rayOrigin = planePoint - (frame.RayDirection * epsilon);+ var ray = new Ray3D(rayOrigin, Direction3D.Create(frame.RayDirection));+ var cast = BrepSpatialQueries.Raycast(body, ray, RayQueryOptions.Default with { IncludeBackfaces = true });+ if (!cast.IsSuccess)+ {+ var first = cast.Diagnostics.FirstOrDefault();+ var message = first?.Message ?? "unknown raycast error";+ throw new InvalidOperationException($"Orthographic map v1 currently supports bodies accepted by BrepSpatialQueries.Raycast ({message}).");+ }++ var forwardHits = cast.Value+ .Where(hit => hit.T >= 0d)+ .OrderBy(hit => hit.T)+ .ToArray();++ if (forwardHits.Length == 0)+ {+ row.Add(new OrthographicSample(false, planeU, planeV, null, null, null, null, null, null, null, null));+ continue;+ }++ var entry = forwardHits[0];+ var exit = forwardHits[^1];+ var entryDepth = Math.Max(0d, entry.T - epsilon);+ var exitDepth = Math.Max(entryDepth, exit.T - epsilon);+ var thickness = exitDepth - entryDepth;+ var faceId = entry.FaceId?.Value;+ var surfaceType = faceId.HasValue && faceSurfaceKinds.TryGetValue(faceId.Value, out var kind) ? kind : null;++ hitSamples++;+ entryDepths.Add(entryDepth);+ thicknesses.Add(thickness);+ if (faceId.HasValue)+ {+ visibleFaceIds.Add(faceId.Value);+ }++ if (surfaceType is not null)+ {+ visibleSurfaceTypes.Add(surfaceType);+ }++ row.Add(new OrthographicSample(+ true,+ planeU,+ planeV,+ entryDepth,+ exitDepth,+ thickness,+ faceId,+ surfaceType,+ entry.Point,+ entry.Normal?.ToVector(),+ exit.Point));+ }++ grid.Add(row);+ }++ var summary = new OrthographicMapSummary(+ rows * cols,+ hitSamples,+ rows * cols - hitSamples,+ entryDepths.Count == 0 ? null : entryDepths.Min(),+ entryDepths.Count == 0 ? null : entryDepths.Max(),+ thicknesses.Count == 0 ? null : thicknesses.Min(),+ thicknesses.Count == 0 ? null : thicknesses.Max(),+ visibleFaceIds.OrderBy(v => v).ToArray(),+ visibleSurfaceTypes.OrderBy(v => v, StringComparer.Ordinal).ToArray());++ var metadata = new OrthographicMapMetadata(+ stepPath,+ bbox,+ view,+ rows,+ cols,+ frame.PlaneAxisU,+ frame.PlaneAxisV,+ frame.RayDirectionAxis,+ frame.DepthReference);++ notes.Add("Depth values are measured from the selected view's projection plane on the near bounding-box side, increasing along ray direction.");++ return new OrthographicMapResult(metadata, summary, grid, notes);+ }+private static AnalyzeSummary BuildSummary(BrepBody body, ICollection<string> notes){var topology = body.Topology;@@ -295,7 +424,33 @@ public static class StepAnalyzer.Select(p => p!.Value).ToArray();- return points.Length == 0 ? null : ComputeBoundingBox(points);+ if (points.Length > 0)+ {+ return ComputeBoundingBox(points);+ }++ var sphereBounds = new List<BoundingBox3D>();+ foreach (var face in body.Topology.Faces)+ {+ if (!body.TryGetFaceSurface(face.Id, out var surface)+ || surface?.Sphere is not { } sphere)+ {+ continue;+ }++ sphereBounds.Add(new BoundingBox3D(+ new Point3D(sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius),+ new Point3D(sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius)));+ }++ if (sphereBounds.Count == 0)+ {+ return null;+ }++ return new BoundingBox3D(+ new Point3D(sphereBounds.Min(b => b.Min.X), sphereBounds.Min(b => b.Min.Y), sphereBounds.Min(b => b.Min.Z)),+ new Point3D(sphereBounds.Max(b => b.Max.X), sphereBounds.Max(b => b.Max.Y), sphereBounds.Max(b => b.Max.Z)));}private static BoundingBox3D ComputeBoundingBox(IReadOnlyList<Point3D> points)@@ -371,4 +526,124 @@ public static class StepAnalyzerreturn edgeCounts;}++ private static Dictionary<int, string> BuildFaceSurfaceKinds(BrepBody body)+ {+ var result = new Dictionary<int, string>();+ foreach (var face in body.Topology.Faces)+ {+ if (!body.TryGetFaceSurface(face.Id, out var surface) || surface is null)+ {+ continue;+ }++ result[face.Id.Value] = surface.Kind.ToString();+ }++ return result;+ }++ private static ProjectionFrame ResolveProjectionFrame(OrthographicView view, BoundingBox3D bbox)+ {+ return view switch+ {+ OrthographicView.Top => new ProjectionFrame(+ new Point3D(0d, 0d, bbox.Max.Z),+ new Vector3D(1d, 0d, 0d),+ new Vector3D(0d, 1d, 0d),+ new Vector3D(0d, 0d, -1d),+ bbox.Min.X,+ bbox.Max.X,+ bbox.Min.Y,+ bbox.Max.Y,+ "X",+ "Y",+ "-Z",+ $"z={bbox.Max.Z:G17}"),+ OrthographicView.Bottom => new ProjectionFrame(+ new Point3D(0d, 0d, bbox.Min.Z),+ new Vector3D(1d, 0d, 0d),+ new Vector3D(0d, 1d, 0d),+ new Vector3D(0d, 0d, 1d),+ bbox.Min.X,+ bbox.Max.X,+ bbox.Min.Y,+ bbox.Max.Y,+ "X",+ "Y",+ "+Z",+ $"z={bbox.Min.Z:G17}"),+ OrthographicView.Front => new ProjectionFrame(+ new Point3D(0d, bbox.Max.Y, 0d),+ new Vector3D(1d, 0d, 0d),+ new Vector3D(0d, 0d, 1d),+ new Vector3D(0d, -1d, 0d),+ bbox.Min.X,+ bbox.Max.X,+ bbox.Min.Z,+ bbox.Max.Z,+ "X",+ "Z",+ "-Y",+ $"y={bbox.Max.Y:G17}"),+ OrthographicView.Back => new ProjectionFrame(+ new Point3D(0d, bbox.Min.Y, 0d),+ new Vector3D(1d, 0d, 0d),+ new Vector3D(0d, 0d, 1d),+ new Vector3D(0d, 1d, 0d),+ bbox.Min.X,+ bbox.Max.X,+ bbox.Min.Z,+ bbox.Max.Z,+ "X",+ "Z",+ "+Y",+ $"y={bbox.Min.Y:G17}"),+ OrthographicView.Left => new ProjectionFrame(+ new Point3D(bbox.Min.X, 0d, 0d),+ new Vector3D(0d, 1d, 0d),+ new Vector3D(0d, 0d, 1d),+ new Vector3D(1d, 0d, 0d),+ bbox.Min.Y,+ bbox.Max.Y,+ bbox.Min.Z,+ bbox.Max.Z,+ "Y",+ "Z",+ "+X",+ $"x={bbox.Min.X:G17}"),+ OrthographicView.Right => new ProjectionFrame(+ new Point3D(bbox.Max.X, 0d, 0d),+ new Vector3D(0d, 1d, 0d),+ new Vector3D(0d, 0d, 1d),+ new Vector3D(-1d, 0d, 0d),+ bbox.Min.Y,+ bbox.Max.Y,+ bbox.Min.Z,+ bbox.Max.Z,+ "Y",+ "Z",+ "-X",+ $"x={bbox.Max.X:G17}"),+ _ => throw new InvalidOperationException($"Unsupported view '{view}'.")+ };+ }++ private readonly record struct ProjectionFrame(+ Point3D PlaneOrigin,+ Vector3D UAxis,+ Vector3D VAxis,+ Vector3D RayDirection,+ double MinU,+ double MaxU,+ double MinV,+ double MaxV,+ string PlaneAxisU,+ string PlaneAxisV,+ string RayDirectionAxis,+ string DepthReference)+ {+ public double RangeU => MaxU - MinU;+ public double RangeV => MaxV - MinV;+ }}