Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add explicit voxel-approximate analyze volume mode
Yuechen Li3a034fbf2092
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.csindex ab3848cb..589d3219 100644--- a/Aetheris.CLI.Tests/CliBaselineTests.cs+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs@@ -709,6 +709,74 @@ public sealed class CliBaselineTestsAssert.Contains("unsupported non-planar face", doc.RootElement.GetProperty("error").GetString(), StringComparison.OrdinalIgnoreCase);}+ [Fact]+ public void AnalyzeVolume_ApproximateModeRequiresResolution()+ {+ var stepPath = Path.Combine(RepoRoot, "testdata/firmament/exports/box_basic.step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", "volume", stepPath, "--approximate"], stdout, stderr);+ Assert.Equal(1, exitCode);+ Assert.Contains("--resolution", stderr.ToString(), StringComparison.OrdinalIgnoreCase);+ }++ [Theory]+ [InlineData("0")]+ [InlineData("700")]+ [InlineData("-2")]+ public void AnalyzeVolume_Approximate_ResolutionValidation(string resolution)+ {+ var stepPath = Path.Combine(RepoRoot, "testdata/firmament/exports/box_basic.step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", "volume", stepPath, "--approximate", "--resolution", resolution, "--json"], stdout, stderr);+ Assert.Equal(1, exitCode);+ using var doc = JsonDocument.Parse(stdout.ToString());+ Assert.Contains("between 8 and 512", doc.RootElement.GetProperty("error").GetString(), StringComparison.OrdinalIgnoreCase);+ }++ [Fact]+ public void AnalyzeVolume_ApproximateBoxVolume_IsClose()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateBox(10d, 6d, 4d).Value, "cli-volume-approx-box");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", "volume", stepPath, "--approximate", "--resolution", "32", "--json"], stdout, stderr);+ Assert.Equal(0, exitCode);+ using var doc = JsonDocument.Parse(stdout.ToString());+ var root = doc.RootElement;+ Assert.True(root.GetProperty("approximate").GetBoolean());+ Assert.False(root.GetProperty("exact").GetBoolean());+ Assert.Equal("voxel-approximation", root.GetProperty("method").GetString());+ Assert.InRange(root.GetProperty("volume").GetDouble(), 239d, 241d);+ }++ [Fact]+ public void AnalyzeVolume_ApproximateCurvedMixedVolume_FailsClearlyWhenContainmentUnsupported()+ {+ var stepPath = Path.Combine(RepoRoot, "testdata/firmament/exports/boolean_box_cylinder_hole.step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", "volume", stepPath, "--approximate", "--resolution", "48", "--json"], stdout, stderr);+ Assert.Equal(1, exitCode);+ using var doc = JsonDocument.Parse(stdout.ToString());+ Assert.Contains("unsupported", doc.RootElement.GetProperty("error").GetString(), StringComparison.OrdinalIgnoreCase);+ }++ [Fact]+ public void AnalyzeVolume_JsonContractIncludesApproximationMetadata()+ {+ var stepPath = Path.Combine(RepoRoot, "testdata/firmament/exports/boolean_box_cylinder_hole.step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exitCode = Aetheris.CLI.CliRunner.Run(["analyze", "volume", stepPath, "--approximate", "--resolution", "64", "--json"], stdout, stderr);+ Assert.Equal(0, exitCode);+ using var doc = JsonDocument.Parse(stdout.ToString());+ var root = doc.RootElement;+ Assert.True(root.GetProperty("success").GetBoolean());+ Assert.True(root.GetProperty("approximate").GetBoolean());+ Assert.False(root.GetProperty("exact").GetBoolean());+ Assert.Equal(64, root.GetProperty("resolution").GetInt32());+ Assert.True(root.TryGetProperty("voxelSize", out _));+ Assert.True(root.TryGetProperty("occupiedCount", out _));+ Assert.True(root.TryGetProperty("totalCount", out _));+ }+[Fact]public void Analyze_Command_Returns_Structured_Json_Failure(){diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 6a882f1a..fdbbe766 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -12,7 +12,7 @@ public static class CliRunnerprivate const string AnalyzeUsage = "Usage: aetheris analyze <file.step> [--face <id>] [--edge <id>] [--vertex <id>] [--json]";private const string AnalyzeMapUsage = "Usage: aetheris analyze map <file.step> (--top|--bottom|--front|--back|--left|--right) --rows <N> --cols <N> --json";private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> (--xy|--xz|--yz) --offset <value> --json";- private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--json]";+ private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--approximate --resolution <N>] [--json]";private const string CanonUsage = "Usage: aetheris canon <file.step> --out <canonical.step> [--json]";private const string AsmExecUsage = "Usage: aetheris asm exec <file.firmasm> [--json]";private const string AsmExportUsage = "Usage: aetheris asm export <file.firmasm> --out <directory> [--json]";@@ -534,8 +534,10 @@ public static class CliRunnerreturn 0;}- var json = args.Contains("--json", StringComparer.Ordinal);var stepPath = args[0];+ var json = false;+ var approximate = false;+ int? resolution = null;if (stepPath.StartsWith("-", StringComparison.Ordinal)){stderr.WriteLine("Analyze volume requires <file.step> as the first argument.");@@ -543,15 +545,41 @@ public static class CliRunnerreturn 1;}- if (args.Any(a => a.StartsWith("--box", StringComparison.Ordinal)))+ for (var i = 1; i < args.Length; i++){- stderr.WriteLine("Analyze volume sub-box probing is deferred: exact bounded clipping against an axis-aligned sub-box is not available yet.");+ switch (args[i])+ {+ case "--json":+ json = true;+ break;+ case "--approximate":+ approximate = true;+ break;+ case "--resolution" when i + 1 < args.Length && int.TryParse(args[++i], out var parsed):+ resolution = parsed;+ break;+ case "--resolution":+ stderr.WriteLine("Analyze volume option --resolution requires an integer value.");+ return 1;+ case var _ when args[i].StartsWith("--box", StringComparison.Ordinal):+ stderr.WriteLine("Analyze volume sub-box probing is deferred: exact bounded clipping against an axis-aligned sub-box is not available yet.");+ return 1;+ default:+ stderr.WriteLine($"Unknown analyze volume option '{args[i]}'.");+ stderr.WriteLine(AnalyzeVolumeUsage);+ return 1;+ }+ }++ if (approximate && !resolution.HasValue)+ {+ stderr.WriteLine("Analyze volume approximate mode requires --resolution <N>.");return 1;}try{- var result = StepAnalyzer.AnalyzeVolume(stepPath);+ var result = StepAnalyzer.AnalyzeVolume(stepPath, approximate, resolution);if (json){stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions));@@ -565,6 +593,20 @@ public static class CliRunnerstdout.WriteLine($"Volume unit: {result.VolumeUnit}");stdout.WriteLine($"Bounding box: min=({result.BoundingBox.Min.X:G17},{result.BoundingBox.Min.Y:G17},{result.BoundingBox.Min.Z:G17}), max=({result.BoundingBox.Max.X:G17},{result.BoundingBox.Max.Y:G17},{result.BoundingBox.Max.Z:G17})");stdout.WriteLine($"Method: {result.Method}");+ stdout.WriteLine($"Exact: {result.Exact}");+ stdout.WriteLine($"Approximate: {result.Approximate}");+ if (result.Resolution.HasValue)+ {+ stdout.WriteLine($"Resolution: {result.Resolution.Value}");+ }+ if (result.VoxelSize is { } voxelSize)+ {+ stdout.WriteLine($"Voxel size: ({voxelSize.X:G17},{voxelSize.Y:G17},{voxelSize.Z:G17})");+ }+ if (result.OccupiedCount.HasValue && result.TotalCount.HasValue)+ {+ stdout.WriteLine($"Occupied voxels: {result.OccupiedCount.Value}/{result.TotalCount.Value}");+ }foreach (var n in result.Notes) stdout.WriteLine($"Note: {n}");}return 0;@@ -1246,14 +1288,18 @@ public static class CliRunnerstdout.WriteLine();stdout.WriteLine("Options:");stdout.WriteLine(" --json Emit machine-readable JSON output.");+ stdout.WriteLine(" --approximate Compute explicit voxel-based approximate volume.");+ stdout.WriteLine(" --resolution Required with --approximate. Integer samples along longest bbox axis.");stdout.WriteLine();stdout.WriteLine("Notes:");stdout.WriteLine(" - Exact whole-body volume currently supports canonical spheres and single-lateral-face cylinders.");+ stdout.WriteLine(" - Approximate mode is opt-in and deterministic (center-point voxel occupancy sampling).");stdout.WriteLine(" - Exact sub-box volume clipping (--box ...) is deferred in ANALYZE-P1.");stdout.WriteLine();stdout.WriteLine("Examples:");stdout.WriteLine(" aetheris analyze volume part.step");stdout.WriteLine(" aetheris analyze volume part.step --json");+ stdout.WriteLine(" aetheris analyze volume part.step --approximate --resolution 64 --json");}private static void WriteCanonHelp(TextWriter stdout)diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex c97e1cf6..a23d629e 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -14,7 +14,21 @@ public static class StepAnalyzer{public sealed record VolumeBoundingBox(Point3D Min, Point3D Max);-public sealed record VolumeAnalysisResult(string InputPath, bool Success, double Volume, string LengthUnit, string VolumeUnit, VolumeBoundingBox BoundingBox, string Method, IReadOnlyList<string> Notes);+public sealed record VolumeAnalysisResult(+ string InputPath,+ bool Success,+ double Volume,+ string LengthUnit,+ string VolumeUnit,+ VolumeBoundingBox BoundingBox,+ string Method,+ bool Exact,+ bool Approximate,+ int? Resolution,+ Point3D? VoxelSize,+ int? OccupiedCount,+ int? TotalCount,+ IReadOnlyList<string> Notes);public static AnalyzeResult Analyze(string stepPath, int? faceId = null, int? edgeId = null, int? vertexId = null){@@ -46,7 +60,7 @@ public sealed record VolumeAnalysisResult(string InputPath, bool Success, doublereturn AnalyzeImportedBodySection(body, fullPath, planeFamily, offset);}- public static VolumeAnalysisResult AnalyzeVolume(string stepPath)+ public static VolumeAnalysisResult AnalyzeVolume(string stepPath, bool approximate = false, int? resolution = null){var (fullPath, body) = ImportStepBody(stepPath);var notes = new List<string>();@@ -57,6 +71,16 @@ public sealed record VolumeAnalysisResult(string InputPath, bool Success, doublethrow new InvalidOperationException("Volume analysis requires explicit shell-role representation.");}+ if (approximate)+ {+ if (!resolution.HasValue)+ {+ throw new InvalidOperationException("Approximate volume mode requires explicit --resolution <N>.");+ }++ return ComputeApproximateVoxelVolume(stepPath, body, bbox, resolution.Value);+ }+var sphereFaces = body.Topology.Faces.Where(f => body.TryGetFaceSurface(f.Id, out var sf) && sf?.Sphere is not null).ToArray();if (body.Topology.Faces.Count() == 1 && sphereFaces.Length == 1){@@ -65,7 +89,7 @@ public sealed record VolumeAnalysisResult(string InputPath, bool Success, doublevar radius = sph!.Sphere!.Value.Radius;var vol = 4d/3d*double.Pi*radius*radius*radius;notes.Add("Exact analytic sphere volume from spherical face radius.");- return new VolumeAnalysisResult(stepPath, true, vol, "model-unit", "model-unit^3", new VolumeBoundingBox(bbox.Min, bbox.Max), "analytic-sphere", notes);+ return new VolumeAnalysisResult(stepPath, true, vol, "model-unit", "model-unit^3", new VolumeBoundingBox(bbox.Min, bbox.Max), "analytic-sphere", true, false, null, null, null, null, notes);}var cylFaces = body.Topology.Faces.Where(f => body.TryGetFaceSurface(f.Id, out var sf) && sf?.Cylinder is not null).ToArray();@@ -85,19 +109,91 @@ public sealed record VolumeAnalysisResult(string InputPath, bool Success, doublethrow new InvalidOperationException("Cylinder volume analysis could not resolve finite axial span from vertices.");var h=max-min; var vol=double.Pi*cyl.Radius*cyl.Radius*h;notes.Add("Exact analytic cylinder volume from cylinder radius and cap-span derived from bound vertices.");- return new VolumeAnalysisResult(stepPath, true, vol, "model-unit", "model-unit^3", new VolumeBoundingBox(bbox.Min, bbox.Max), "analytic-cylinder", notes);+ return new VolumeAnalysisResult(stepPath, true, vol, "model-unit", "model-unit^3", new VolumeBoundingBox(bbox.Min, bbox.Max), "analytic-cylinder", true, false, null, null, null, null, notes);}var shellVolume = TryComputePlanarClosedShellVolume(body, shells, out var planarVolume, out var planarFailureReason);if (shellVolume){notes.Add("Exact closed-shell volume from oriented planar-face triangulation and signed tetrahedral accumulation.");- return new VolumeAnalysisResult(stepPath, true, planarVolume, "model-unit", "model-unit^3", new VolumeBoundingBox(bbox.Min, bbox.Max), "planar-closed-shell", notes);+ return new VolumeAnalysisResult(stepPath, true, planarVolume, "model-unit", "model-unit^3", new VolumeBoundingBox(bbox.Min, bbox.Max), "planar-closed-shell", true, false, null, null, null, null, notes);}throw new InvalidOperationException(planarFailureReason ?? "Volume analysis currently supports canonical sphere, single-lateral-face cylinder, and enclosed planar closed-shell bodies only.");}+ private static VolumeAnalysisResult ComputeApproximateVoxelVolume(string stepPath, BrepBody body, BoundingBox3D bbox, int resolution)+ {+ if (resolution is < 8 or > 512)+ {+ throw new InvalidOperationException("Approximate volume resolution must be an integer between 8 and 512.");+ }++ var dx = bbox.Max.X - bbox.Min.X;+ var dy = bbox.Max.Y - bbox.Min.Y;+ var dz = bbox.Max.Z - bbox.Min.Z;+ if (dx <= 0d || dy <= 0d || dz <= 0d)+ {+ throw new InvalidOperationException("Approximate volume requires a non-degenerate body bounding box.");+ }++ var longest = double.Max(dx, double.Max(dy, dz));+ var nx = int.Max(1, (int)double.Round(resolution * (dx / longest), MidpointRounding.AwayFromZero));+ var ny = int.Max(1, (int)double.Round(resolution * (dy / longest), MidpointRounding.AwayFromZero));+ var nz = int.Max(1, (int)double.Round(resolution * (dz / longest), MidpointRounding.AwayFromZero));+ var cell = new Point3D(dx / nx, dy / ny, dz / nz);+ var cellVolume = cell.X * cell.Y * cell.Z;+ var total = nx * ny * nz;+ var occupied = 0;++ for (var ix = 0; ix < nx; ix++)+ for (var iy = 0; iy < ny; iy++)+ for (var iz = 0; iz < nz; iz++)+ {+ var sample = new Point3D(+ bbox.Min.X + (ix + 0.5d) * cell.X,+ bbox.Min.Y + (iy + 0.5d) * cell.Y,+ bbox.Min.Z + (iz + 0.5d) * cell.Z);+ var containment = BrepSpatialQueries.ClassifyPoint(body, sample);+ if (!containment.IsSuccess)+ {+ throw new InvalidOperationException($"Approximate volume classification is unsupported for this body ({containment.Diagnostics.FirstOrDefault().Message}).");+ }++ if (containment.Value == PointContainment.Unknown)+ {+ throw new InvalidOperationException("Approximate volume classification is unsupported for this body (point containment returned unknown).");+ }++ if (containment.Value is PointContainment.Inside or PointContainment.Boundary)+ {+ occupied++;+ }+ }++ var volume = occupied * cellVolume;+ return new VolumeAnalysisResult(+ stepPath,+ true,+ volume,+ "model-unit",+ "model-unit^3",+ new VolumeBoundingBox(bbox.Min, bbox.Max),+ "voxel-approximation",+ false,+ true,+ resolution,+ cell,+ occupied,+ total,+ new[]+ {+ "Approximate volume mode: deterministic center-point voxel sampling over the body axis-aligned bounding box.",+ "Resolution means samples along the longest bounding-box axis; other axis counts are derived proportionally.",+ "Estimated result is not exact and should be used for comparison/localization only."+ });+ }+private static bool TryComputePlanarClosedShellVolume(BrepBody body, BrepBodyShellRepresentation shells, out double volume, out string? failureReason){volume = 0d;