Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add compound and arbitrary section STEP analysis
Yuechen Lia2f2bfabf881
diff --git a/.wrangler/cache/wrangler-account.json b/.wrangler/cache/wrangler-account.jsonnew file mode 100644index 00000000..9940b80d--- /dev/null+++ b/.wrangler/cache/wrangler-account.json@@ -0,0 +1,6 @@+{+ "account": {+ "id": "b16e20858013418767fbb55680713b33",+ "name": "[email protected]'s Account"+ }+}\ No newline at end of filediff --git a/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js b/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.jsnew file mode 100644index 00000000..d762e8c0--- /dev/null+++ b/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js@@ -0,0 +1,15 @@+// ../../../AppData/Local/npm-cache/_npx/32026684e21afda6/node_modules/wrangler/templates/no-op-worker.js+var no_op_worker_default = {+ fetch() {+ return new Response("Not found", {+ status: 404,+ headers: {+ "Content-Type": "text/html"+ }+ });+ }+};+export {+ no_op_worker_default as default+};+//# sourceMappingURL=no-op-worker.js.mapdiff --git a/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js.map b/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js.mapnew file mode 100644index 00000000..737ba7d4--- /dev/null+++ b/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js.map@@ -0,0 +1,8 @@+{+ "version": 3,+ "sources": ["../../../../../../AppData/Local/npm-cache/_npx/32026684e21afda6/node_modules/wrangler/templates/no-op-worker.js"],+ "sourceRoot": "C:\\Users\\yuech\\source\\repos\\Aetheris\\.wrangler\\tmp\\deploy-g2Y6fL",+ "sourcesContent": ["export default {\n\tfetch() {\n\t\treturn new Response(\"Not found\", {\n\t\t\tstatus: 404,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t},\n\t\t});\n\t},\n};\n"],+ "mappings": ";AAAA,IAAO,uBAAQ;AAAA,EACd,QAAQ;AACP,WAAO,IAAI,SAAS,aAAa;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS;AAAA,QACR,gBAAgB;AAAA,MACjB;AAAA,IACD,CAAC;AAAA,EACF;AACD;",+ "names": []+}diff --git a/Aetheris.CLI.Tests/ReconstructionPrimitiveClosureTests.cs b/Aetheris.CLI.Tests/ReconstructionPrimitiveClosureTests.csnew file mode 100644index 00000000..197045ec--- /dev/null+++ b/Aetheris.CLI.Tests/ReconstructionPrimitiveClosureTests.cs@@ -0,0 +1,97 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.CLI.Tests;++public sealed class ReconstructionPrimitiveClosureTests+{+ [Fact]+ public void MajorArc_BoundsAndSectionRetainTrimmedAnalyticExtrema()+ {+ var loop = new LineArcProfileLoop2D([+ new LineArcCircularArc2D((0, 0), 5, 0, 3d * Math.PI / 2d),+ new LineArcLineSegment2D((0, -5), (0, 0)),+ new LineArcLineSegment2D((0, 0), (5, 0))], false);+ var emitted = LineArcProfileExtrudeEmitter.TryEmit(new LineArcProfileExtrudeRequest([loop], 2));+ var body = Assert.IsType<BrepBody>(emitted.Body);+ var path = WriteStep(body, "major-arc");+ try+ {+ var analysis = StepAnalyzer.Analyze(path);+ Assert.Equal(-5d, analysis.Summary.BoundingBox!.Value.Min.X, 8);+ Assert.Equal(5d, analysis.Summary.BoundingBox.Value.Max.Y, 8);+ var cylindricalFace = body.Topology.Faces.Single(face =>+ body.TryGetFaceSurface(face.Id, out var surface) && surface?.Cylinder is not null);+ var faceAnalysis = StepAnalyzer.Analyze(path, faceId: cylindricalFace.Id.Value);+ Assert.Equal(2d, faceAnalysis.Face!.AxialExtent!.Value, 8);+ Assert.Equal(3d * Math.PI / 2d, faceAnalysis.Face.BoundaryAngularExtentRadians!.Value, 8);+ Assert.Equal(-5d, faceAnalysis.Face.BoundingBox!.Value.Min.X, 8);+ Assert.Equal(5d, faceAnalysis.Face.BoundingBox.Value.Max.Y, 8);+ var section = StepAnalyzer.AnalyzeSection(path, SectionPlaneFamily.XY, 0d);+ var arc = Assert.Single(section.Loops.SelectMany(loopResult => loopResult.Segments), segment => segment.Kind == "arc");+ Assert.Equal(3d * Math.PI / 2d, Math.Abs(arc.SweepRadians!.Value), 8);+ Assert.Equal(-5d, section.Summary.SectionBoundingBox2D!.Min.U, 8);+ }+ finally { File.Delete(path); }+ }++ [Fact]+ public void ArbitraryPlaneSection_WritesDeterministicSvg()+ {+ var path = WriteStep(BrepPrimitives.CreateBox(10, 8, 6).Value, "arbitrary-section");+ var svg = Path.Combine(Path.GetTempPath(), "aetheris-arbitrary-section.svg");+ try+ {+ string Run()+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var code = CliRunner.Run(["analyze", "section", path, "--origin", "0,0,0", "--normal", "1,1,0", "--out", svg, "--json"], stdout, stderr);+ Assert.Equal(0, code); Assert.True(File.Exists(svg), stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("Custom", json.RootElement.GetProperty("metadata").GetProperty("planeFamily").GetString());+ return File.ReadAllText(svg);+ }+ var first = Run(); var second = Run();+ Assert.Equal(first, second);+ Assert.Contains("<path data-loop=", first, StringComparison.Ordinal);+ }+ finally { File.Delete(path); if (File.Exists(svg)) File.Delete(svg); }+ }++ [Fact]+ public void CompoundAnalysis_ReportsEverySolidAndAggregatePlacement()+ {+ var exported = Step242AssemblyExporter.Export(new Step242AssemblyExportModel("Pair", "root", [+ new("box-def", "Box", BrepPrimitives.CreateBox(2, 4, 6).Value),+ new("sphere-def", "Sphere", BrepPrimitives.CreateSphere(3).Value)], [+ new("root", "Pair", null, null, Identity()),+ new("box-occ", "Box", "root", "box-def", Identity()),+ new("sphere-occ", "Sphere", "root", "sphere-def", Translated(0, 0, 10))]));+ Assert.True(exported.IsSuccess);+ var path = Path.Combine(Path.GetTempPath(), $"aetheris-compound-{Guid.NewGuid():N}.step");+ File.WriteAllText(path, exported.Value);+ try+ {+ var result = StepAnalyzer.AnalyzeCompound(path);+ Assert.Equal(2, result.RootCount);+ Assert.Equal(2, result.SolidCount);+ Assert.NotNull(result.AggregateVolume);+ Assert.Equal(0d, result.Solids[1].OffsetFromFirst.Z, 8);+ Assert.Equal(3d, result.AggregateBoundingBox!.Value.Max.Z, 8);+ }+ finally { File.Delete(path); }+ }++ private static string WriteStep(BrepBody body, string name)+ {+ var exported = Step242Exporter.ExportBody(body); Assert.True(exported.IsSuccess);+ var path = Path.Combine(Path.GetTempPath(), $"aetheris-{name}-{Guid.NewGuid():N}.step");+ File.WriteAllText(path, exported.Value); return path;+ }++ private static double[] Identity() => Translated(0, 0, 0);+ private static double[] Translated(double x, double y, double z) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 02f81680..050b455a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -142,9 +142,10 @@ public static class CliRunnerprivate const string InspectSelectionsUsage = "Usage: aetheris inspect-selections <file.firmament> --json";private 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> (--plane <xy|xz|yz> --direction <+x|-x|+y|-y|+z|-z> | --views six --llm) --resolution <NxM> [--point <u,v>] [--rank-probes|--evidence-bundle] --json";- private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> (--xy|--xz|--yz) --offset <value> --json";+ private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> ((--xy|--xz|--yz) --offset <value>|--origin <x,y,z> --normal <x,y,z>) [--out <section.svg>] [--json]";private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--approximate --resolution <N>] [--json]";private const string AnalyzeCompareUsage = "Usage: aetheris analyze compare <reference.step> <candidate.step> [--approximate-volume --resolution <N>] [--json]";+ private const string AnalyzeCompoundUsage = "Usage: aetheris analyze compound <file.step> [--json]";private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";private const string VerifyUsage = "Usage: aetheris verify <file.firmament|file.step> [--expected-volume <value>] [--cad-assistant] [--cad-assistant-path <path>] [--timeout <seconds>] [--evidence-dir <path>] [--require-external] [--json]";private const string InspectUsage = "Usage: aetheris inspect <file.firmament|file.step> [--json]";@@ -2739,6 +2740,7 @@ Model CanonicalPanel {stderr.WriteLine($" or: {AnalyzeSectionUsage[7..]}");stderr.WriteLine($" or: {AnalyzeVolumeUsage[7..]}");stderr.WriteLine($" or: {AnalyzeCompareUsage[7..]}");+ stderr.WriteLine($" or: {AnalyzeCompoundUsage[7..]}");stderr.WriteLine("Run 'aetheris analyze --help' for examples.");return 1;}@@ -2763,6 +2765,10 @@ Model CanonicalPanel {{return RunAnalyzeVolume(args.Skip(1).ToArray(), stdout, stderr);}+ if (string.Equals(args[0], "compound", StringComparison.Ordinal))+ {+ return RunAnalyzeCompound(args.Skip(1).ToArray(), stdout, stderr);+ }if (string.Equals(args[0], "compare", StringComparison.Ordinal)){return RunAnalyzeCompare(args.Skip(1).ToArray(), stdout, stderr);@@ -2770,7 +2776,7 @@ Model CanonicalPanel {if (args[0].StartsWith("-", StringComparison.Ordinal)){- stderr.WriteLine("Analyze requires <file.step> as the first argument, or a subcommand ('map', 'section', 'volume', or 'compare').");+ stderr.WriteLine("Analyze requires <file.step> as the first argument, or a subcommand ('map', 'section', 'volume', 'compound', or 'compare').");stderr.WriteLine(AnalyzeUsage);return 1;}@@ -4268,6 +4274,39 @@ Model CanonicalPanel {return 0;}+ private static int RunAnalyzeCompound(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || IsHelpFlag(args[0]))+ {+ stdout.WriteLine("Inspect every exact rigid root in a STEP serialization without assigning Part or Assembly semantics.");+ stdout.WriteLine(AnalyzeCompoundUsage);+ return args.Length == 0 ? 1 : 0;+ }+ var json = args.Skip(1).Any(arg => arg == "--json");+ if (args.Skip(1).Any(arg => arg != "--json"))+ {+ stderr.WriteLine(AnalyzeCompoundUsage);+ return 1;+ }+ try+ {+ var result = StepAnalyzer.AnalyzeCompound(args[0]);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions));+ else+ {+ stdout.WriteLine($"Roots: {result.RootCount}; solids: {result.SolidCount}; aggregate volume: {result.AggregateVolume?.ToString("G12", System.Globalization.CultureInfo.InvariantCulture) ?? "unavailable"}");+ foreach (var solid in result.Solids)+ stdout.WriteLine($" #{solid.RootEntityId}: solids={solid.SolidCount}, volume={solid.Volume?.ToString("G12", System.Globalization.CultureInfo.InvariantCulture) ?? "unavailable"}, center=({solid.PlacementCenter.X:G6},{solid.PlacementCenter.Y:G6},{solid.PlacementCenter.Z:G6})");+ }+ return 0;+ }+ catch (Exception ex)+ {+ WriteAnalyzeFailureJson(stdout, args[0], ex);+ return 1;+ }+ }+private static int RunAnalyzeSection(string[] args, TextWriter stdout, TextWriter stderr){if (args.Length == 0)@@ -4294,6 +4333,9 @@ Model CanonicalPanel {SectionPlaneFamily? plane = null;var planeOptionCount = 0;double? offset = null;+ Point3D? customOrigin = null;+ Vector3D? customNormal = null;+ string? outputSvg = null;var json = false;for (var i = 1; i < args.Length; i++)@@ -4319,6 +4361,22 @@ Model CanonicalPanel {stderr.WriteLine("Analyze section option --offset requires a numeric value.");stderr.WriteLine(AnalyzeSectionUsage);return 1;+ case "--origin" when i + 1 < args.Length && TryParseTriple(args[++i], out var parsedOrigin):+ customOrigin = new Point3D(parsedOrigin.X, parsedOrigin.Y, parsedOrigin.Z);+ break;+ case "--normal" when i + 1 < args.Length && TryParseTriple(args[++i], out var parsedNormal):+ customNormal = new Vector3D(parsedNormal.X, parsedNormal.Y, parsedNormal.Z);+ break;+ case "--origin":+ case "--normal":+ stderr.WriteLine($"Analyze section option {args[i]} requires x,y,z numeric values.");+ return 1;+ case "--out" when i + 1 < args.Length:+ outputSvg = Path.GetFullPath(args[++i]);+ break;+ case "--out":+ stderr.WriteLine("Analyze section option --out requires an SVG path.");+ return 1;case "--json":json = true;break;@@ -4333,28 +4391,31 @@ Model CanonicalPanel {}}- if (!plane.HasValue || planeOptionCount != 1)+ var custom = customOrigin.HasValue || customNormal.HasValue;+ if (custom && (!customOrigin.HasValue || !customNormal.HasValue || planeOptionCount != 0 || offset.HasValue)){- stderr.WriteLine("Analyze section requires exactly one plane selector (--xy|--xz|--yz).");+ stderr.WriteLine("Custom section requires both --origin and --normal, without a principal plane or --offset.");return 1;}-- if (!offset.HasValue)+ if (!custom && (!plane.HasValue || planeOptionCount != 1 || !offset.HasValue)){- stderr.WriteLine("Analyze section requires --offset <value>.");+ stderr.WriteLine(planeOptionCount == 1 && !offset.HasValue+ ? "Analyze section requires --offset <value>."+ : "Principal section requires exactly one of --xy|--xz|--yz and --offset <value>.");return 1;}-- if (!json)+ if (!json && outputSvg is null){- stderr.WriteLine("Analyze section currently requires --json output. Re-run with --json.");+ stderr.WriteLine("Analyze section requires --json, --out <section.svg>, or both.");return 1;}SectionAnalysisResult section;try{- section = StepAnalyzer.AnalyzeSection(stepPath, plane.Value, offset.Value);+ section = custom+ ? StepAnalyzer.AnalyzeSection(stepPath, customOrigin!.Value, customNormal!.Value)+ : StepAnalyzer.AnalyzeSection(stepPath, plane!.Value, offset!.Value);}catch (Exception ex){@@ -4362,7 +4423,13 @@ Model CanonicalPanel {return 1;}- stdout.WriteLine(JsonSerializer.Serialize(section, JsonOptions));+ if (outputSvg is not null)+ {+ Directory.CreateDirectory(Path.GetDirectoryName(outputSvg)!);+ File.WriteAllText(outputSvg, StepSectionSvgRenderer.Render(section));+ }+ if (json) stdout.WriteLine(JsonSerializer.Serialize(section, JsonOptions));+ else stdout.WriteLine($"Section SVG: {outputSvg}");return 0;}@@ -4548,6 +4615,17 @@ Model CanonicalPanel {return true;}+ private static bool TryParseTriple(string value, out (double X, double Y, double Z) triple)+ {+ triple = default;+ var parts = value.Split(',');+ return parts.Length == 3+ && double.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out triple.X)+ && double.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out triple.Y)+ && double.TryParse(parts[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out triple.Z)+ && double.IsFinite(triple.X) && double.IsFinite(triple.Y) && double.IsFinite(triple.Z);+ }+private static bool IsVersionFlag(string value) =>string.Equals(value, "--version", StringComparison.Ordinal)|| string.Equals(value, "-v", StringComparison.Ordinal);@@ -4746,6 +4824,7 @@ Model CanonicalPanel {stdout.WriteLine(AnalyzeUsage);stdout.WriteLine($" or: {AnalyzeMapUsage[7..]}");stdout.WriteLine($" or: {AnalyzeSectionUsage[7..]}");+ stdout.WriteLine($" or: {AnalyzeCompoundUsage[7..]}");stdout.WriteLine();stdout.WriteLine("Options (summary mode):");stdout.WriteLine(" --face <id> Inspect one face.");@@ -4759,7 +4838,7 @@ Model CanonicalPanel {stdout.WriteLine(" - Use 'aetheris analyze map --help' for orthographic map options.");stdout.WriteLine(" - Use 'aetheris analyze section --help' for section options.");stdout.WriteLine(" - Use 'aetheris analyze volume --help' for volume options.");- stdout.WriteLine(" - Assembly-like multi-root STEP is rejected here with a route hint to assembly extraction/import.");+ stdout.WriteLine(" - Summary mode remains single-part; use 'analyze compound' to inspect every multi-root solid without assigning product semantics.");stdout.WriteLine();stdout.WriteLine("Examples:");stdout.WriteLine(" aetheris analyze part.step");@@ -4768,6 +4847,7 @@ Model CanonicalPanel {stdout.WriteLine(" aetheris analyze part.step --face 12 --json");stdout.WriteLine(" aetheris analyze map part.step --right --rows 20 --cols 30 --json");stdout.WriteLine(" aetheris analyze section part.step --yz --offset 1.25 --json");+ stdout.WriteLine(" aetheris analyze compound multi-solid.step --json");}private static void WriteAnalyzeMapHelp(TextWriter stdout)@@ -4794,17 +4874,19 @@ Model CanonicalPanel {private static void WriteAnalyzeSectionHelp(TextWriter stdout){- stdout.WriteLine("Analyze STEP body by intersecting a principal section plane.");+ stdout.WriteLine("Analyze STEP body by intersecting a principal or arbitrary section plane.");stdout.WriteLine();stdout.WriteLine(AnalyzeSectionUsage);stdout.WriteLine();stdout.WriteLine("Required:");- stdout.WriteLine(" exactly one plane: --xy | --xz | --yz");- stdout.WriteLine(" --offset <value> Plane offset along the orthogonal axis.");- stdout.WriteLine(" --json Required output mode.");+ stdout.WriteLine(" principal: exactly one of --xy | --xz | --yz plus --offset <value>");+ stdout.WriteLine(" arbitrary: --origin <x,y,z> plus --normal <x,y,z>");+ stdout.WriteLine(" --out <path> Write deterministic 2D SVG evidence.");+ stdout.WriteLine(" --json Emit ordered analytic loops and provenance.");stdout.WriteLine();stdout.WriteLine("Example:");stdout.WriteLine(" aetheris analyze section part.step --xz --offset 5.0 --json");+ stdout.WriteLine(" aetheris analyze section part.step --origin 1,2,3 --normal 1,1,0 --out section.svg --json");}private static void WriteAnalyzeVolumeHelp(TextWriter stdout)diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.csindex 11966337..c8983175 100644--- a/Aetheris.CLI/StepAnalysisModels.cs+++ b/Aetheris.CLI/StepAnalysisModels.cs@@ -43,7 +43,9 @@ public sealed record FaceDetail(double? MinorRadius,double? SemiAngleRadians,IReadOnlyList<int> AdjacentEdgeIds,- [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? StepEntity = null);+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? StepEntity = null,+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] double? AxialExtent = null,+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] double? BoundaryAngularExtentRadians = null);public sealed record EdgeDetail(int EdgeId,@@ -55,7 +57,13 @@ public sealed record EdgeDetail(IReadOnlyList<int> AdjacentFaceIds,double? ParameterRange,double? ArcLength,- string ArcLengthStatus);+ string ArcLengthStatus,+ Point3D? Center = null,+ Vector3D? Direction = null,+ Vector3D? PlaneNormal = null,+ double? Radius = null,+ double? SweepRadians = null,+ string? Orientation = null);public sealed record VertexDetail(int VertexId,@@ -71,6 +79,28 @@ public sealed record AnalyzeResult(IReadOnlyList<string> Notes,Step242SemanticPmiInspectionResult? SemanticPmi = null);+public sealed record CompoundSolidInspection(+ int Ordinal,+ int RootEntityId,+ string RootEntityKind,+ int SolidCount,+ BoundingBox3D? BoundingBox,+ double? Volume,+ bool VolumeExact,+ IReadOnlyDictionary<string, int> SurfaceFamilies,+ Point3D PlacementCenter,+ Vector3D OffsetFromFirst);++public sealed record CompoundAnalysisResult(+ string StepPath,+ int RootCount,+ int SolidCount,+ IReadOnlyList<CompoundSolidInspection> Solids,+ BoundingBox3D? AggregateBoundingBox,+ double? AggregateVolume,+ IReadOnlyDictionary<string, int> AggregateSurfaceFamilies,+ IReadOnlyList<string> Notes);+public enum OrthographicView{Top,@@ -156,7 +186,8 @@ public enum SectionPlaneFamily{XY,XZ,- YZ+ YZ,+ Custom}public sealed record SectionAnalysisMetadata(@@ -168,7 +199,9 @@ public sealed record SectionAnalysisMetadata(string OffsetEquation,string SectionAxisU,string SectionAxisV,- string WorldToSectionMapping);+ string WorldToSectionMapping,+ Point3D? PlaneOrigin = null,+ Vector3D? PlaneNormal = null);public sealed record SectionAnalysisSummary(int LoopCount,diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex 968eb4b8..8753bc8e 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -55,6 +55,39 @@ public sealed record VolumeAnalysisResult(return analysis with { Face = analysis.Face with { StepEntity = entity } };}+ public static CompoundAnalysisResult AnalyzeCompound(string stepPath)+ {+ var fullPath = Path.GetFullPath(stepPath);+ if (!File.Exists(fullPath)) throw new FileNotFoundException("STEP file was not found.", fullPath);+ var imported = Step242Importer.ImportRigidRoots(File.ReadAllText(fullPath));+ if (!imported.IsSuccess || imported.Value is null) throw new StepAnalysisImportException(fullPath, imported.Diagnostics);+ var notes = imported.Diagnostics.Select(diagnostic => diagnostic.Message).ToList();+ var entries = new List<CompoundSolidInspection>();+ Point3D? firstCenter = null;+ foreach (var (root, index) in imported.Value.Select((root, index) => (root, index)))+ {+ var summary = AnalyzeImportedBody(root.Body, fullPath).Summary;+ var mass = Aetheris.Kernel.Core.Brep.Verification.BrepMassProperties.Evaluate(root.Body);+ var center = mass.Centroid ?? (summary.BoundingBox is { } bounds+ ? new Point3D((bounds.Min.X + bounds.Max.X) / 2d, (bounds.Min.Y + bounds.Max.Y) / 2d, (bounds.Min.Z + bounds.Max.Z) / 2d)+ : Point3D.Origin);+ firstCenter ??= center;+ var exact = mass.Status != Aetheris.Kernel.Core.Brep.Verification.BrepMassPropertiesStatus.Unavailable+ && mass.IsEnclosed && mass.IsOrientationConsistent;+ entries.Add(new(index + 1, root.StepEntityId, root.StepEntityKind, root.Body.Topology.Bodies.Count(), summary.BoundingBox,+ exact ? mass.AbsoluteVolume : null, exact, summary.SurfaceFamilies, center, center - firstCenter.Value));+ if (!exact) notes.Add($"Root #{root.StepEntityId} exact volume unavailable: {mass.Status}.");+ }+ var boxes = entries.Where(entry => entry.BoundingBox is not null).Select(entry => entry.BoundingBox!.Value).ToArray();+ var aggregateBounds = boxes.Length == 0 ? (BoundingBox3D?)null : new BoundingBox3D(+ new Point3D(boxes.Min(b => b.Min.X), boxes.Min(b => b.Min.Y), boxes.Min(b => b.Min.Z)),+ new Point3D(boxes.Max(b => b.Max.X), boxes.Max(b => b.Max.Y), boxes.Max(b => b.Max.Z)));+ var surfaces = entries.SelectMany(entry => entry.SurfaceFamilies).GroupBy(pair => pair.Key, StringComparer.Ordinal)+ .ToDictionary(group => group.Key, group => group.Sum(pair => pair.Value), StringComparer.Ordinal);+ var aggregateVolume = entries.All(entry => entry.VolumeExact) ? entries.Sum(entry => entry.Volume!.Value) : (double?)null;+ return new(fullPath, entries.Count, entries.Sum(entry => entry.SolidCount), entries, aggregateBounds, aggregateVolume, surfaces, notes);+ }+public static AnalyzeResult AnalyzeImportedBody(BrepBody body, string stepPath, int? faceId = null, int? edgeId = null, int? vertexId = null){var notes = new List<string>();@@ -76,7 +109,13 @@ public sealed record VolumeAnalysisResult(public static SectionAnalysisResult AnalyzeSection(string stepPath, SectionPlaneFamily planeFamily, double offset){var (fullPath, body) = ImportStepBody(stepPath);- return AnalyzeImportedBodySection(body, fullPath, planeFamily, offset);+ return AnalyzeImportedBodySection(body, fullPath, ResolveSectionFrame(planeFamily, offset));+ }++ public static SectionAnalysisResult AnalyzeSection(string stepPath, Point3D origin, Vector3D normal)+ {+ var (fullPath, body) = ImportStepBody(stepPath);+ return AnalyzeImportedBodySection(body, fullPath, ResolveSectionFrame(origin, normal));}public static VolumeAnalysisResult AnalyzeVolume(string stepPath, bool approximate = false, int? resolution = null)@@ -828,10 +867,13 @@ public sealed record VolumeAnalysisResult(}public static SectionAnalysisResult AnalyzeImportedBodySection(BrepBody body, string stepPath, SectionPlaneFamily planeFamily, double offset)+ => AnalyzeImportedBodySection(body, stepPath, ResolveSectionFrame(planeFamily, offset));++ private static SectionAnalysisResult AnalyzeImportedBodySection(BrepBody body, string stepPath, SectionFrame frame){var notes = new List<string>();var bbox = TryComputeBodyBoundingBox(body) ?? throw new InvalidOperationException("Section analyzer requires body vertex coordinates to compute bounding box.");- var frame = ResolveSectionFrame(planeFamily, offset);+ var offset = frame.Offset;var epsilon = Math.Max(ToleranceContext.Default.Linear * 64d, 1e-6d);var rawSegments = new List<RawSectionSegment>();@@ -865,13 +907,10 @@ public sealed record VolumeAnalysisResult(// Importer fragments are normalized by the shared analytic arrangement; do// not reintroduce the former first-neighbour greedy chain walker here.+ rawSegments = OrientClosedSectionFragments(rawSegments, epsilon, notes).ToList();var arrangement = NormalizeSectionFragments(rawSegments, frame, offset, notes);var loops = arrangement.Diagnostics.Count == 0- ? arrangement.ResultLoops.Select((loop, index) => new SectionLoop(index + 1, true, loop.SignedArea > 0d ? "ccw" : "cw", ComputeBoundingBox2D(loop.Fragments.SelectMany(x => x.Geometry switch- {- LineArcLineSegment2D l => new[] { new Point2D(l.Start.X, l.Start.Y), new Point2D(l.End.X, l.End.Y) },- LineArcCircularArc2D a => new[] { new Point2D(a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians)), new Point2D(a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians + a.SweepAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians + a.SweepAngleRadians)) },- _ => [] }).ToArray()), loop.Fragments.Select(ToSectionSegment).ToArray(), loop.IsOuter ? "Outer" : "Inner"))+ ? arrangement.ResultLoops.Select((loop, index) => new SectionLoop(index + 1, true, loop.SignedArea > 0d ? "ccw" : "cw", ComputeBoundingBox2D(loop.Fragments.SelectMany(x => SectionGeometryExtrema(x.Geometry)).ToArray()), loop.Fragments.Select(ToSectionSegment).ToArray(), loop.IsOuter ? "Outer" : "Inner")).Concat(rawSegments.Where(x => x.IsClosed).GroupBy(x => $"{x.Center!.U:R}:{x.Center.V:R}:{x.Radius:R}", StringComparer.Ordinal).Select((g, index) => FullCircleLoop(arrangement.ResultLoops.Count + index + 1, g.First()))).ToArray(): Array.Empty<SectionLoop>();notes.AddRange(arrangement.Diagnostics);@@ -879,13 +918,15 @@ public sealed record VolumeAnalysisResult(var metadata = new SectionAnalysisMetadata(stepPath,bbox,- planeFamily,+ frame.Family,offset,frame.FixedAxis,frame.OffsetEquation,frame.AxisU,frame.AxisV,- frame.MappingDescription);+ frame.MappingDescription,+ frame.Origin,+ frame.Normal);var summary = BuildSectionSummary(loops);var unaccounted = arrangement.Diagnostics.Where(x => x.StartsWith("OpenSection:unaccounted-atomic-fragments:", StringComparison.Ordinal)).Select(x => x.Split(':')).Select(x => x.Length > 2 && int.TryParse(x[2], out var n) ? n : 0).Sum();var normalization = new SectionNormalizationDiagnostics(rawSegments.Count, arrangement.IntersectionVertices.Count, arrangement.AtomicFragments.Count,@@ -895,12 +936,72 @@ public sealed record VolumeAnalysisResult(return new SectionAnalysisResult(metadata, summary, loops, notes, normalization);}+ private static IReadOnlyList<RawSectionSegment> OrientClosedSectionFragments(IReadOnlyList<RawSectionSegment> source, double epsilon, ICollection<string> notes)+ {+ var closed = source.Where(segment => segment.IsClosed).ToList();+ var remaining = source.Where(segment => !segment.IsClosed).ToList();+ if (remaining.Any(segment => segment.Kind == RawSectionSegmentKind.Unsupported)) return source;+ string Key(Point2D point) => $"{Math.Round(point.U / epsilon):F0}:{Math.Round(point.V / epsilon):F0}";+ var degrees = remaining.SelectMany(segment => new[] { Key(segment.Start), Key(segment.End) })+ .GroupBy(key => key, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal);+ if (degrees.Values.Any(degree => degree != 2)) return source;++ var oriented = new List<RawSectionSegment>(source.Count);+ while (remaining.Count > 0)+ {+ var cycle = new List<RawSectionSegment>();+ var first = remaining[0];+ remaining.RemoveAt(0);+ cycle.Add(first);+ var current = first.End;+ while (Key(current) != Key(first.Start))+ {+ var index = remaining.FindIndex(segment => Key(segment.Start) == Key(current) || Key(segment.End) == Key(current));+ if (index < 0) return source;+ var next = remaining[index];+ remaining.RemoveAt(index);+ if (Key(next.End) == Key(current)) next = next.Reversed();+ cycle.Add(next);+ current = next.End;+ }+ if (SectionSignedArea(cycle) < 0d)+ cycle = cycle.AsEnumerable().Reverse().Select(segment => segment.Reversed()).ToList();+ oriented.AddRange(cycle);+ }+ oriented.AddRange(closed);+ notes.Add("section-orientation:closed degree-two fragment graph normalized before analytic arrangement");+ return oriented;+ }++ private static double SectionSignedArea(IReadOnlyList<RawSectionSegment> cycle)+ {+ var twiceArea = 0d;+ foreach (var segment in cycle)+ {+ if (segment.Kind == RawSectionSegmentKind.Line)+ {+ twiceArea += segment.Start.U * segment.End.V - segment.End.U * segment.Start.V;+ continue;+ }+ if (segment.Kind != RawSectionSegmentKind.Arc || segment.Center is null || segment.Radius is null || segment.SweepRadians is null) continue;+ var center = segment.Center;+ var radius = segment.Radius.Value;+ var start = Math.Atan2(segment.Start.V - center.V, segment.Start.U - center.U);+ var sweep = (segment.Direction == "cw" ? -1d : 1d) * Math.Abs(segment.SweepRadians.Value);+ var end = start + sweep;+ twiceArea += radius * center.U * (Math.Sin(end) - Math.Sin(start))+ + radius * center.V * (Math.Cos(start) - Math.Cos(end))+ + radius * radius * sweep;+ }+ return twiceArea / 2d;+ }+private static ProfileArrangement2D NormalizeSectionFragments(IReadOnlyList<RawSectionSegment> raw, SectionFrame frame, double offset, ICollection<string> notes){var sources = new List<ArrangementSourceCurve2D>();foreach (var (segment, index) in raw.Select((x, i) => (x, i))){- var provenance = new ProfileSegmentProvenance($"step-section:{frame.FixedAxis}:{offset:R}:{index}", segment.SourceEntity ?? $"face:{segment.SourceFace}", $"face:{segment.SourceFace}", $"STEP plane/surface intersection; {segment.MaterialSideEvidence ?? "material-side-unresolved"}", "XY");+ var provenance = new ProfileSegmentProvenance($"step-section:{frame.FixedAxis}:{offset:R}:{index}", segment.SourceEntity ?? $"face:{segment.SourceFace}", $"face:{segment.SourceFace}", $"STEP plane/surface intersection; surface={segment.SurfaceFamily ?? "Unknown"}; {segment.MaterialSideEvidence ?? "material-side-unresolved"}", "XY");var common = (StableId: $"step:{segment.SourceFace}:{index}", Provenance: provenance);switch (segment.Kind){@@ -1674,11 +1775,22 @@ public sealed record VolumeAnalysisResult(.Select(v => body.TryGetVertexPoint(v, out var p) ? (Point3D?)p : null).Where(p => p.HasValue).Select(p => p!.Value)- .ToArray();+ .ToList();++ foreach (var edgeId in body.GetEdges(faceId))+ {+ if (body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding)+ && edgeBinding.TrimInterval is { } edgeTrim+ && body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var edgeGeometry)+ && edgeGeometry?.Circle3 is { } edgeCircle)+ {+ AddTrimmedCircleExtrema(faceVertices, edgeCircle, edgeTrim);+ }+ }BoundingBox3D? bbox = null;Point3D? rep = null;- if (faceVertices.Length > 0)+ if (faceVertices.Count > 0){bbox = ComputeBoundingBox(faceVertices);rep = new Point3D(faceVertices.Average(v => v.X), faceVertices.Average(v => v.Y), faceVertices.Average(v => v.Z));@@ -1702,6 +1814,19 @@ public sealed record VolumeAnalysisResult(double? majorRadius = null;double? minorRadius = null;double? semiAngle = null;+ double? axialExtent = null;+ double? boundaryAngularExtent = body.GetEdges(faceId)+ .Select(edgeId => body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding)+ && edgeBinding.TrimInterval is { } edgeTrim+ && body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var edgeGeometry)+ && edgeGeometry?.Circle3 is not null+ ? Math.Abs(edgeTrim.End - edgeTrim.Start)+ : (double?)null)+ .Where(value => value.HasValue)+ .Select(value => value!.Value)+ .DefaultIfEmpty()+ .Max();+ if (boundaryAngularExtent == 0d) boundaryAngularExtent = null;if (surface.Plane is { } plane){@@ -1714,6 +1839,7 @@ public sealed record VolumeAnalysisResult(anchor = cylinder.Origin;axis = cylinder.Axis.ToVector();radius = cylinder.Radius;+ axialExtent = ProjectedExtent(faceVertices, cylinder.Origin, axis.Value);}if (surface.Cone is { } cone)@@ -1723,6 +1849,7 @@ public sealed record VolumeAnalysisResult(axis = cone.Axis.ToVector();semiAngle = cone.SemiAngleRadians;placementRadius = cone.PlacementRadius;+ axialExtent = ProjectedExtent(faceVertices, cone.PlacementOrigin, axis.Value);}if (surface.Sphere is { } sphere)@@ -1740,7 +1867,14 @@ public sealed record VolumeAnalysisResult(minorRadius = torus.MinorRadius;}- return new FaceDetail(faceId.Value, surface.Kind.ToString(), "bound", bbox, rep, anchor, apex, normal, axis, radius, placementRadius, majorRadius, minorRadius, semiAngle, edgeIds);+ return new FaceDetail(faceId.Value, surface.Kind.ToString(), "bound", bbox, rep, anchor, apex, normal, axis, radius, placementRadius, majorRadius, minorRadius, semiAngle, edgeIds, AxialExtent: axialExtent, BoundaryAngularExtentRadians: boundaryAngularExtent);+ }++ private static double? ProjectedExtent(IReadOnlyCollection<Point3D> points, Point3D origin, Vector3D axis)+ {+ if (points.Count == 0) return null;+ var parameters = points.Select(point => (point - origin).Dot(axis)).ToArray();+ return parameters.Max() - parameters.Min();}private static EdgeDetail BuildEdgeDetail(BrepBody body, EdgeId edgeId, ICollection<string> notes)@@ -1754,6 +1888,12 @@ public sealed record VolumeAnalysisResult(double? parameterRange = null;double? arcLength = null;var arcLengthStatus = "unavailable";+ Point3D? center = null;+ Vector3D? direction = null;+ Vector3D? planeNormal = null;+ double? radius = null;+ double? sweepRadians = null;+ string? orientation = null;if (body.Bindings.TryGetEdgeBinding(edgeId, out var binding)){@@ -1773,10 +1913,16 @@ public sealed record VolumeAnalysisResult(case CurveGeometryKind.Line3:arcLength = double.Abs(trim.End - trim.Start);arcLengthStatus = "computed";+ direction = curve.Line3!.Value.Direction.ToVector() * (binding.OrientedEdgeSense ? 1d : -1d);break;case CurveGeometryKind.Circle3 when curve.Circle3 is { } circle:arcLength = circle.Radius * double.Abs(trim.End - trim.Start);arcLengthStatus = "computed";+ center = circle.Center;+ planeNormal = circle.Normal.ToVector();+ radius = circle.Radius;+ sweepRadians = double.Abs(trim.End - trim.Start);+ orientation = binding.OrientedEdgeSense ? "counterclockwise" : "clockwise";break;default:arcLengthStatus = "unsupported-for-curve-kind";@@ -1806,7 +1952,7 @@ public sealed record VolumeAnalysisResult(? faces.Select(id => id.Value).OrderBy(v => v).ToArray(): [];- return new EdgeDetail(edgeId.Value, curveType, edge.StartVertexId.Value, startPoint, edge.EndVertexId.Value, endPoint, adjacentFaces, parameterRange, arcLength, arcLengthStatus);+ return new EdgeDetail(edgeId.Value, curveType, edge.StartVertexId.Value, startPoint, edge.EndVertexId.Value, endPoint, adjacentFaces, parameterRange, arcLength, arcLengthStatus, center, direction, planeNormal, radius, sweepRadians, orientation);}private static VertexDetail BuildVertexDetail(BrepBody body, VertexId vertexId, ICollection<string> notes)@@ -1860,22 +2006,16 @@ public sealed record VolumeAnalysisResult(.Select(p => p!.Value).ToList();- // Periodic circle edges commonly use one seam vertex, so vertex-only bounds collapse- // their radial extent. Include exact axis-aligned extrema for full-circle bindings.- var hasAxialCircularSurface = body.Geometry.Surfaces.Any(s => s.Value.Kind is SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone);- foreach (var binding in hasAxialCircularSurface ? body.Bindings.EdgeBindings : [])+ // Analytic circular edges can reach extrema away from their vertices. Evaluate+ // endpoints plus world-axis stationary parameters inside the actual trim domain;+ // this covers minor, major, wrapped (canonically unwrapped), and full circles.+ foreach (var binding in body.Bindings.EdgeBindings){- if (binding.TrimInterval is not { } interval || interval.End - interval.Start < 2d * Math.PI - 1e-9+ if (binding.TrimInterval is not { } interval|| !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var geometry)|| geometry?.Circle3 is not { } circle)continue;- var x = circle.XAxis.ToVector();- var y = circle.YAxis.ToVector();- var dx = circle.Radius * Math.Sqrt(x.X * x.X + y.X * y.X);- var dy = circle.Radius * Math.Sqrt(x.Y * x.Y + y.Y * y.Y);- var dz = circle.Radius * Math.Sqrt(x.Z * x.Z + y.Z * y.Z);- points.Add(new Point3D(circle.Center.X - dx, circle.Center.Y - dy, circle.Center.Z - dz));- points.Add(new Point3D(circle.Center.X + dx, circle.Center.Y + dy, circle.Center.Z + dz));+ AddTrimmedCircleExtrema(points, circle, interval);}// A full torus is periodic in both parameters. Its seam vertices (and even its@@ -1914,12 +2054,7 @@ public sealed record VolumeAnalysisResult(}}- if (points.Count > 0)- {- return ComputeBoundingBox(points);- }-- var sphereBounds = new List<BoundingBox3D>();+ // A sphere is also periodic and normally exposes only seam/pole vertices.foreach (var face in body.Topology.Faces){if (!body.TryGetFaceSurface(face.Id, out var surface)@@ -1928,19 +2063,36 @@ public sealed record VolumeAnalysisResult(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)));+ points.Add(new Point3D(sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius));+ points.Add(new Point3D(sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius));}- if (sphereBounds.Count == 0)+ return points.Count == 0 ? null : ComputeBoundingBox(points);+ }++ private static void AddTrimmedCircleExtrema(ICollection<Point3D> points, Circle3Curve circle, ParameterInterval trim)+ {+ points.Add(circle.Evaluate(trim.Start));+ points.Add(circle.Evaluate(trim.End));+ var x = circle.XAxis.ToVector();+ var y = circle.YAxis.ToVector();+ foreach (var angle in new[]{- return null;+ Math.Atan2(y.X, x.X), Math.Atan2(y.X, x.X) + Math.PI,+ Math.Atan2(y.Y, x.Y), Math.Atan2(y.Y, x.Y) + Math.PI,+ Math.Atan2(y.Z, x.Z), Math.Atan2(y.Z, x.Z) + Math.PI+ })+ {+ if (TryEquivalentAngleInInterval(angle, trim, out var included))+ points.Add(circle.Evaluate(included));}+ }- 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 bool TryEquivalentAngleInInterval(double angle, ParameterInterval interval, out double included)+ {+ var turns = Math.Ceiling((interval.Start - angle) / (2d * Math.PI));+ included = angle + turns * 2d * Math.PI;+ return included <= interval.End + 1e-10d;}private static bool IsFullPeriodicTorusFace(BrepBody body, FaceId faceId)@@ -2187,13 +2339,26 @@ public sealed record VolumeAnalysisResult(var angles = body.GetEdges(face.Id).SelectMany(edge => IntersectEdgeWithSectionPlane(body, edge, frame, epsilon)).Select(p => ProjectPoint(frame, p)).Where(p => Math.Abs(Math.Sqrt((p.U-center.U)*(p.U-center.U)+(p.V-center.V)*(p.V-center.V))-cylinder.Radius) <= epsilon * 32d).Select(p => Math.Atan2(p.V-center.V,p.U-center.U)).Order().Aggregate(new List<double>(), (a,x) => { if(a.Count==0 || Math.Abs(a[^1]-x)>1e-7d) a.Add(x); return a; });if (angles.Count == 2){- var sweep = angles[1] - angles[0];- if (sweep > Math.PI) { (angles[0], angles[1]) = (angles[1], angles[0]); sweep = 2d * Math.PI - sweep; }- var start = new Point2D(center.U + cylinder.Radius * Math.Cos(angles[0]), center.V + cylinder.Radius * Math.Sin(angles[0]));- var end = new Point2D(center.U + cylinder.Radius * Math.Cos(angles[0] + sweep), center.V + cylinder.Radius * Math.Sin(angles[0] + sweep));+ var circularBoundarySweeps = new List<double>();+ foreach (var edgeId in body.GetEdges(face.Id))+ {+ if (!body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding)+ || edgeBinding.TrimInterval is not { } edgeTrim+ || !body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var edgeCurve)+ || edgeCurve?.Circle3 is null)+ continue;+ var candidate = edgeTrim.End - edgeTrim.Start;+ if (candidate < 2d * Math.PI - 1e-9d) circularBoundarySweeps.Add(candidate);+ }+ var boundedSweep = circularBoundarySweeps.DefaultIfEmpty(angles[1] - angles[0]).Max();+ var minorSweep = angles[1] - angles[0];+ var startAngle = boundedSweep > Math.PI + 1e-9d ? angles[1] : angles[0];+ var sweep = boundedSweep > Math.PI + 1e-9d ? 2d * Math.PI - minorSweep : minorSweep;+ var start = new Point2D(center.U + cylinder.Radius * Math.Cos(startAngle), center.V + cylinder.Radius * Math.Sin(startAngle));+ var end = new Point2D(center.U + cylinder.Radius * Math.Cos(startAngle + sweep), center.V + cylinder.Radius * Math.Sin(startAngle + sweep));var sameSense = body.Bindings.TryGetFaceBinding(face.Id, out var binding) && binding.SameSense;notes.Add($"section-fragment:cylinder:face={face.Id.Value}:sameSense={sameSense}:center=({center.U:R},{center.V:R}):radius={cylinder.Radius:R}:angles=({angles[0]:R},{angles[1]:R}):sweep={sweep:R}:start=({start.U:R},{start.V:R}):end=({end.U:R},{end.V:R})");- var midAngle = angles[0] + sweep * .5d;+ var midAngle = startAngle + sweep * .5d;var radial = (center3D - cylinder.Origin) + (frame.UAxis * (cylinder.Radius * Math.Cos(midAngle))) + (frame.VAxis * (cylinder.Radius * Math.Sin(midAngle)));var hasCylinderBinding = body.Bindings.TryGetFaceBinding(face.Id, out var cylinderBinding);if (hasCylinderBinding && !cylinderBinding.SameSense) radial = -radial;@@ -2299,16 +2464,8 @@ public sealed record VolumeAnalysisResult(private static SectionAnalysisSummary BuildSectionSummary(IReadOnlyList<SectionLoop> loops){var segments = loops.SelectMany(loop => loop.Segments).ToArray();- var points = segments.SelectMany(segment =>- {- var result = new List<Point2D> { segment.Start, segment.End };- if (segment.Center is not null)- {- result.Add(segment.Center);- }-- return result;- }).ToArray();+ var points = loops.Where(loop => loop.BoundingBox2D is not null)+ .SelectMany(loop => new[] { loop.BoundingBox2D!.Min, loop.BoundingBox2D.Max }).ToArray();return new SectionAnalysisSummary(loops.Count,@@ -2327,12 +2484,20 @@ public sealed record VolumeAnalysisResult(_ => new SectionSegment("unsupported", raw.Start, raw.End, null, null, null, null, raw.UnsupportedReason ?? "unsupported", raw.SourceFace, raw.SourceEntity, raw.SurfaceFamily, null, null, null, raw.MaterialSideEvidence)};- private static SectionSegment ToSectionSegment(ArrangementFragment2D fragment) => fragment.Geometry switch+ private static SectionSegment ToSectionSegment(ArrangementFragment2D fragment){- LineArcLineSegment2D line => new("line", new(line.Start.X, line.Start.Y), new(line.End.X, line.End.Y), null, null, null, null, null),- LineArcCircularArc2D arc => new("arc", new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)), new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians)), new(arc.Center.X, arc.Center.Y), arc.Radius, arc.SweepAngleRadians >= 0d ? "ccw" : "cw", arc.SweepAngleRadians, null),- _ => new("unsupported", new(0, 0), new(0, 0), null, null, null, null, "UnsupportedSectionCurve")- };+ var face = fragment.Source.Operation.StartsWith("face:", StringComparison.Ordinal)+ && int.TryParse(fragment.Source.Operation[5..], out var faceId) ? faceId : (int?)null;+ var entity = fragment.Source.Provenance.ConceptStableId;+ var family = Regex.Match(fragment.Source.Provenance.Derivation, @"surface=(?<family>[^;]+)").Groups["family"].Value;+ if (string.IsNullOrWhiteSpace(family)) family = "Unknown";+ return fragment.Geometry switch+ {+ LineArcLineSegment2D line => new("line", new(line.Start.X, line.Start.Y), new(line.End.X, line.End.Y), null, null, null, null, null, face, entity, family, "NormalizedLinear", fragment.FromParameter, fragment.ToParameter, fragment.Source.Provenance.Derivation),+ LineArcCircularArc2D arc => new("arc", new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)), new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians)), new(arc.Center.X, arc.Center.Y), arc.Radius, arc.SweepAngleRadians >= 0d ? "ccw" : "cw", arc.SweepAngleRadians, null, face, entity, family, "AngularRadians", fragment.FromParameter, fragment.ToParameter, fragment.Source.Provenance.Derivation),+ _ => new("unsupported", new(0, 0), new(0, 0), null, null, null, null, "UnsupportedSectionCurve", face, entity, family)+ };+ }private static SectionLoop FullCircleLoop(int id, RawSectionSegment segment){@@ -2354,8 +2519,35 @@ public sealed record VolumeAnalysisResult(new Point2D(points.Max(point => point.U), points.Max(point => point.V)));}+ private static IEnumerable<Point2D> SectionGeometryExtrema(LineArcProfileCurve2D geometry)+ {+ switch (geometry)+ {+ case LineArcLineSegment2D line:+ yield return new(line.Start.X, line.Start.Y);+ yield return new(line.End.X, line.End.Y);+ break;+ case LineArcCircularArc2D arc:+ {+ var end = arc.StartAngleRadians + arc.SweepAngleRadians;+ var low = Math.Min(arc.StartAngleRadians, end);+ var high = Math.Max(arc.StartAngleRadians, end);+ yield return new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians));+ yield return new(arc.Center.X + arc.Radius * Math.Cos(end), arc.Center.Y + arc.Radius * Math.Sin(end));+ foreach (var cardinal in new[] { 0d, Math.PI / 2d, Math.PI, 3d * Math.PI / 2d })+ {+ var turns = Math.Ceiling((low - cardinal) / (2d * Math.PI));+ var candidate = cardinal + turns * 2d * Math.PI;+ if (candidate <= high + 1e-10d)+ yield return new(arc.Center.X + arc.Radius * Math.Cos(candidate), arc.Center.Y + arc.Radius * Math.Sin(candidate));+ }+ break;+ }+ }+ }+private static double SignedSectionDistance(Point3D point, SectionFrame frame) =>- (point - Point3D.Origin).Dot(frame.Normal) - frame.Offset;+ (point - frame.Origin).Dot(frame.Normal);private static string QuantizedPointKey(Point3D point, double epsilon){@@ -2364,14 +2556,14 @@ public sealed record VolumeAnalysisResult(}private static Point2D ProjectPoint(SectionFrame frame, Point3D point) =>- new((point - Point3D.Origin).Dot(frame.UAxis), (point - Point3D.Origin).Dot(frame.VAxis));+ new((point - frame.Origin).Dot(frame.UAxis), (point - frame.Origin).Dot(frame.VAxis));private static bool TrySolvePlaneIntersectionPoint(PlaneSurface a, SectionFrame b, out Point3D point){var n1 = a.Normal.ToVector();var n2 = b.Normal;var d1 = n1.Dot(a.Origin - Point3D.Origin);- var d2 = b.Offset;+ var d2 = b.Normal.Dot(b.Origin - Point3D.Origin);var cross = n1.Cross(n2);var denom = cross.Dot(cross);if (denom <= 1e-20d)@@ -2387,13 +2579,13 @@ public sealed record VolumeAnalysisResult(private static bool TryNormalize(Vector3D vector, out Vector3D normalized){- if (vector.Length <= 1e-20d)+ if (vector.Length <= 1e-12d){normalized = default;return false;}- normalized = vector / vector.Length;+ normalized = vector * (1d / vector.Length);return true;}@@ -2402,12 +2594,23 @@ public sealed record VolumeAnalysisResult(private static SectionFrame ResolveSectionFrame(SectionPlaneFamily family, double offset) =>family switch{- SectionPlaneFamily.XY => new SectionFrame(new Vector3D(0d, 0d, 1d), new Vector3D(1d, 0d, 0d), new Vector3D(0d, 1d, 0d), offset, "Z", "z = offset", "X", "Y", "(u,v) -> (x,y)"),- SectionPlaneFamily.XZ => new SectionFrame(new Vector3D(0d, 1d, 0d), new Vector3D(1d, 0d, 0d), new Vector3D(0d, 0d, 1d), offset, "Y", "y = offset", "X", "Z", "(u,v) -> (x,z)"),- SectionPlaneFamily.YZ => new SectionFrame(new Vector3D(1d, 0d, 0d), new Vector3D(0d, 1d, 0d), new Vector3D(0d, 0d, 1d), offset, "X", "x = offset", "Y", "Z", "(u,v) -> (y,z)"),+ SectionPlaneFamily.XY => new SectionFrame(family, new Point3D(0d, 0d, offset), new Vector3D(0d, 0d, 1d), new Vector3D(1d, 0d, 0d), new Vector3D(0d, 1d, 0d), offset, "Z", "z = offset", "X", "Y", "(u,v) -> (x,y)"),+ SectionPlaneFamily.XZ => new SectionFrame(family, new Point3D(0d, offset, 0d), new Vector3D(0d, 1d, 0d), new Vector3D(1d, 0d, 0d), new Vector3D(0d, 0d, 1d), offset, "Y", "y = offset", "X", "Z", "(u,v) -> (x,z)"),+ SectionPlaneFamily.YZ => new SectionFrame(family, new Point3D(offset, 0d, 0d), new Vector3D(1d, 0d, 0d), new Vector3D(0d, 1d, 0d), new Vector3D(0d, 0d, 1d), offset, "X", "x = offset", "Y", "Z", "(u,v) -> (y,z)"),_ => throw new InvalidOperationException($"Unsupported section plane family '{family}'.")};+ private static SectionFrame ResolveSectionFrame(Point3D origin, Vector3D normal)+ {+ if (!TryNormalize(normal, out var n)) throw new ArgumentException("Section normal must be finite and nonzero.", nameof(normal));+ var hints = new[] { new Vector3D(0d, 0d, 1d), new Vector3D(0d, 1d, 0d), new Vector3D(1d, 0d, 0d) };+ var hint = hints.OrderBy(axis => Math.Abs(axis.Dot(n))).First();+ var u = hint.Cross(n);+ if (!TryNormalize(u, out u)) throw new InvalidOperationException("Unable to derive deterministic section U axis.");+ var v = n.Cross(u);+ return new(SectionPlaneFamily.Custom, origin, n, u, v, n.Dot(origin - Point3D.Origin), "custom", "dot(point-origin,normal) = 0", "U", "V", "origin + u*U + v*V");+ }+private static ProjectionFrame ResolveProjectionFrame(OrthographicView view, BoundingBox3D bbox){return view switch@@ -2978,6 +3181,8 @@ public sealed record VolumeAnalysisResult(}private readonly record struct SectionFrame(+ SectionPlaneFamily Family,+ Point3D Origin,Vector3D Normal,Vector3D UAxis,Vector3D VAxis,diff --git a/Aetheris.CLI/StepSectionSvgRenderer.cs b/Aetheris.CLI/StepSectionSvgRenderer.csnew file mode 100644index 00000000..db031168--- /dev/null+++ b/Aetheris.CLI/StepSectionSvgRenderer.cs@@ -0,0 +1,53 @@+using System.Globalization;+using System.Text;++namespace Aetheris.CLI;++internal static class StepSectionSvgRenderer+{+ public static string Render(SectionAnalysisResult section)+ {+ var bounds = section.Summary.SectionBoundingBox2D ?? throw new InvalidOperationException("Section has no bounded geometry to render.");+ var width = Math.Max(bounds.Max.U - bounds.Min.U, 1e-6d);+ var height = Math.Max(bounds.Max.V - bounds.Min.V, 1e-6d);+ var margin = Math.Max(width, height) * .05d;+ var minU = bounds.Min.U - margin;+ var minV = bounds.Min.V - margin;+ var viewWidth = width + 2d * margin;+ var viewHeight = height + 2d * margin;+ var sb = new StringBuilder();+ sb.Append("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"").Append(F(minU)).Append(' ').Append(F(-minV-viewHeight)).Append(' ').Append(F(viewWidth)).Append(' ').Append(F(viewHeight)).Append("\">\n");+ sb.Append(" <rect x=\"").Append(F(minU)).Append("\" y=\"").Append(F(-minV-viewHeight)).Append("\" width=\"").Append(F(viewWidth)).Append("\" height=\"").Append(F(viewHeight)).Append("\" fill=\"#f4f7fa\"/>\n");+ sb.Append(" <g transform=\"scale(1,-1)\" fill=\"none\" stroke=\"#17212b\" stroke-width=\"").Append(F(Math.Max(width, height) / 500d)).Append("\">\n");+ foreach (var loop in section.Loops.OrderBy(loop => loop.LoopId))+ {+ sb.Append(" <path data-loop=\"").Append(loop.LoopId).Append("\" data-role=\"").Append(loop.Role ?? "Unknown").Append("\" d=\"");+ if (loop.Segments.Count > 0)+ {+ var first = loop.Segments[0];+ sb.Append('M').Append(F(first.Start.U)).Append(' ').Append(F(first.Start.V));+ foreach (var segment in loop.Segments)+ {+ if (segment.Kind == "line") sb.Append(" L").Append(F(segment.End.U)).Append(' ').Append(F(segment.End.V));+ else if (segment.Kind == "arc" && segment.Radius is { } radius && segment.SweepRadians is { } sweep)+ {+ if (Math.Abs(sweep) >= 2d * Math.PI - 1e-9d)+ {+ var center = segment.Center!;+ sb.Append(" M").Append(F(center.U + radius)).Append(' ').Append(F(center.V));+ sb.Append(" A").Append(F(radius)).Append(' ').Append(F(radius)).Append(" 0 1 1 ").Append(F(center.U - radius)).Append(' ').Append(F(center.V));+ sb.Append(" A").Append(F(radius)).Append(' ').Append(F(radius)).Append(" 0 1 1 ").Append(F(center.U + radius)).Append(' ').Append(F(center.V));+ }+ else sb.Append(" A").Append(F(radius)).Append(' ').Append(F(radius)).Append(" 0 ").Append(Math.Abs(sweep) > Math.PI ? '1' : '0').Append(' ').Append(sweep >= 0d ? '1' : '0').Append(' ').Append(F(segment.End.U)).Append(' ').Append(F(segment.End.V));+ }+ }+ if (loop.IsClosed) sb.Append(" Z");+ }+ sb.Append("\"/>\n");+ }+ sb.Append(" </g>\n</svg>\n");+ return sb.ToString();+ }++ private static string F(double value) => value.ToString("0.###############", CultureInfo.InvariantCulture);+}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.csindex dca1c136..d52d71ee 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs@@ -105,6 +105,28 @@ public sealed class Step242ImporterTestsAssert.Contains("detected 2 exact BRep rigid roots", diagnostic.Message, StringComparison.Ordinal);}+ [Fact]+ public void ImportRigidRoots_MultipleSolidRoots_ImportsEveryRootWithoutWeakeningPartContract()+ {+ var box = BrepPrimitives.CreateBox(2, 4, 6).Value;+ var sphere = BrepPrimitives.CreateSphere(3).Value;+ var exported = Step242AssemblyExporter.Export(new Step242AssemblyExportModel("Pair", "root", [+ new("box-def", "Box", box), new("sphere-def", "Sphere", sphere)], [+ new("root", "Pair", null, null, Identity()),+ new("box-occ", "Box", "root", "box-def", Identity()),+ new("sphere-occ", "Sphere", "root", "sphere-def", Identity())]));+ Assert.True(exported.IsSuccess);++ var strictPart = Step242Importer.ImportBody(exported.Value);+ Assert.False(strictPart.IsSuccess);+ var roots = Step242Importer.ImportRigidRoots(exported.Value);+ Assert.True(roots.IsSuccess, string.Join("; ", roots.Diagnostics.Select(d => d.Message)));+ Assert.Equal(2, roots.Value.Count);+ Assert.Equal([6, 1], roots.Value.Select(root => root.Body.Topology.Faces.Count()).OrderDescending().ToArray());+ }++ private static double[] Identity() => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+[Fact]public void ImportBody_TessellatedSolidWithComplexTriangulatedFace_ImportsWithoutManifoldSolidBrep(){diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242SeamCurveTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242SeamCurveTests.csnew file mode 100644index 00000000..0aaa89cf--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242SeamCurveTests.cs@@ -0,0 +1,57 @@+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Geometry;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242SeamCurveTests+{+ [Fact]+ public void ImportBody_SeamCurve_UsesAuthoritativeThreeDimensionalCurve()+ {+ const string cylinderFace = @"ISO-10303-21;+HEADER;+ENDSEC;+DATA;+#1=MANIFOLD_SOLID_BREP('solid',#2);+#2=CLOSED_SHELL($,(#3));+#3=ADVANCED_FACE((#4),#5,.T.);+#4=FACE_OUTER_BOUND($,#6,.T.);+#5=CYLINDRICAL_SURFACE($,#30,1.0);+#6=EDGE_LOOP($,(#7,#8,#9,#10));+#7=ORIENTED_EDGE($,$,$,#11,.T.);+#8=ORIENTED_EDGE($,$,$,#12,.T.);+#9=ORIENTED_EDGE($,$,$,#13,.T.);+#10=ORIENTED_EDGE($,$,$,#14,.T.);+#11=EDGE_CURVE($,#15,#16,#17,.T.);+#12=EDGE_CURVE($,#16,#16,#40,.T.);+#13=EDGE_CURVE($,#16,#15,#19,.T.);+#14=EDGE_CURVE($,#15,#15,#20,.T.);+#15=VERTEX_POINT($,#21);+#16=VERTEX_POINT($,#22);+#17=LINE($,#21,#23);+#18=CIRCLE($,#31,1.0);+#19=LINE($,#22,#24);+#20=CIRCLE($,#30,1.0);+#21=CARTESIAN_POINT($,(1,0,0));+#22=CARTESIAN_POINT($,(1,0,1));+#23=VECTOR($,#25,1.0);+#24=VECTOR($,#26,1.0);+#25=DIRECTION($,(0,0,1));+#26=DIRECTION($,(0,0,-1));+#30=AXIS2_PLACEMENT_3D($,#27,#28,#29);+#31=AXIS2_PLACEMENT_3D($,#32,#28,#29);+#32=CARTESIAN_POINT($,(0,0,1));+#27=CARTESIAN_POINT($,(0,0,0));+#28=DIRECTION($,(0,0,1));+#29=DIRECTION($,(1,0,0));+#40=SEAM_CURVE('',#18,(),.PCURVE_S1.);+ENDSEC;+END-ISO-10303-21;";++ var import = Step242Importer.ImportBody(cylinderFace);++ Assert.True(import.IsSuccess);+ Assert.Equal(4, import.Value.Topology.Edges.Count());+ Assert.Contains(import.Value.Geometry.Curves.Select(binding => binding.Value), curve => curve.Kind == CurveGeometryKind.Circle3);+ }+}diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex baceb477..da297e85 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -14,6 +14,38 @@ namespace Aetheris.Kernel.Core.Step242;public static class Step242Importer{+ /// <summary>+ /// Imports every exact rigid B-rep root without assigning part or assembly semantics.+ /// This is the inspection boundary for compound serialization; <see cref="ImportBody(string)"/>+ /// deliberately remains strict about its single-part contract.+ /// </summary>+ public static KernelResult<IReadOnlyList<Step242RigidRootBody>> ImportRigidRoots(string stepText)+ {+ ArgumentNullException.ThrowIfNull(stepText);+ var parsed = Step242SubsetParser.Parse(stepText);+ if (!parsed.IsSuccess || parsed.Value is null)+ return KernelResult<IReadOnlyList<Step242RigidRootBody>>.Failure(parsed.Diagnostics);++ var classification = Step242RigidRootClassifier.Classify(parsed.Value);+ if (classification.Kind == Step242RigidRootClassificationKind.MissingRigidRoot)+ return Step242ImportSharedUtilities.NotImplementedFailure<IReadOnlyList<Step242RigidRootBody>>(+ "Missing MANIFOLD_SOLID_BREP or BREP_WITH_VOIDS root entity.",+ "Importer.TopologyRoot");++ var roots = new List<Step242RigidRootBody>(classification.RigidRoots.Count);+ var diagnostics = new List<KernelDiagnostic>();+ foreach (var root in classification.RigidRoots.OrderBy(entity => entity.Id))+ {+ var imported = ImportExactBrepCore(parsed.Value, root.Id, includeOrphanPlanarFaces: classification.RigidRoots.Count == 1);+ diagnostics.AddRange(imported.Diagnostics);+ if (!imported.IsSuccess || imported.Value is null)+ return KernelResult<IReadOnlyList<Step242RigidRootBody>>.Failure(diagnostics);+ roots.Add(new Step242RigidRootBody(root.Id, root.Name, imported.Value));+ }++ return KernelResult<IReadOnlyList<Step242RigidRootBody>>.Success(roots, diagnostics);+ }+private const double AreaEps = 1e-8d;private const double PointOnSurfaceEps = 1e-5d;private const double TinyCoedgeGapSnapEps = 2.5e-5d;@@ -778,11 +810,12 @@ public static class Step242Importerint edgeCurveEntityId){ParameterInterval? explicitTrim = null;- var surfaceCurveConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "SURFACE_CURVE");+ var surfaceCurveConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "SURFACE_CURVE")+ ?? Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "SEAM_CURVE");if (surfaceCurveConstructor is not null){if (surfaceCurveConstructor.Arguments.ElementAtOrDefault(1) is not Step242EntityReference curve3dReference)- return FailureCurveBinding("SURFACE_CURVE must reference its authoritative 3D curve.", SourceFor(edgeCurveEntityId, "Importer.Geometry.SurfaceCurve"));+ return FailureCurveBinding("SURFACE_CURVE/SEAM_CURVE must reference its authoritative 3D curve.", SourceFor(edgeCurveEntityId, "Importer.Geometry.SurfaceCurve"));var curve3dResult = document.TryGetEntity(curve3dReference.TargetId);if (!curve3dResult.IsSuccess)return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(curve3dResult.Diagnostics);diff --git a/Aetheris.Kernel.Core/Step242/Step242RigidRootBody.cs b/Aetheris.Kernel.Core/Step242/Step242RigidRootBody.csnew file mode 100644index 00000000..ff731a8c--- /dev/null+++ b/Aetheris.Kernel.Core/Step242/Step242RigidRootBody.cs@@ -0,0 +1,6 @@+using Aetheris.Kernel.Core.Brep;++namespace Aetheris.Kernel.Core.Step242;++/// <summary>An exact rigid B-rep root recovered from a STEP serialization compound.</summary>+public sealed record Step242RigidRootBody(int StepEntityId, string StepEntityKind, BrepBody Body);diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM1Tests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM1Tests.csindex 73ef264c..1f7ccb2d 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM1Tests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM1Tests.cs@@ -1,10 +1,48 @@using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;using Aetheris.Semantics;namespace Aetheris.Kernel.Firmament.Tests.Assembly;public sealed class AssemblyM1Tests{+ [Fact]+ public void ModelTargetTemplates_MaterializeAnalyticPrimitiveDefinitionsAndExportProductOccurrences()+ {+ const string source = """+ Template < R: Length > Model Ball { Units: mm Sphere Body { Radius: R } }+ Template < R: Length > Model Stem { Units: mm Cylinder Body { Radius: R; Height: 20mm } }+ Assembly Pair {+ <Assembly Pair>+ <Part Knob = Ball<R: 5mm>> Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; </Part>+ <Part Shaft = Stem<R: 2mm>> Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,-25,1]; </Part>+ </Assembly>+ Anchor: Pair;+ }+ """;+ var path = Path.Combine(Path.GetTempPath(), "aetheris-model-template-assembly-" + Guid.NewGuid().ToString("N") + ".firmament");+ try+ {+ File.WriteAllText(path, source);+ var compilation = new AssemblyM1Pipeline().CompileFile(path);+ Assert.True(compilation.IsSuccess, string.Join(Environment.NewLine, compilation.Diagnostics.Select(item => $"{item.Code}: {item.Message}")));+ Assert.Equal(2, compilation.Geometry!.DefinitionBodies.Count);+ Assert.Contains(compilation.Geometry.DefinitionBodies.Values, body => body.Geometry.Surfaces.Any(surface => surface.Value.Kind == SurfaceGeometryKind.Sphere));+ Assert.Contains(compilation.Geometry.DefinitionBodies.Values, body => body.Geometry.Surfaces.Any(surface => surface.Value.Kind == SurfaceGeometryKind.Cylinder));++ var exported = AssemblyIrAp242Exporter.Export(compilation);+ Assert.True(exported.IsSuccess, string.Join(Environment.NewLine, exported.Diagnostics.Select(item => item.Message)));+ var product = Step242AssemblyImporter.Import(exported.Value);+ Assert.True(product.IsSuccess, string.Join(Environment.NewLine, product.Diagnostics.Select(item => item.Message)));+ Assert.Equal(2, product.Value.Occurrences.Count);+ }+ finally+ {+ if (File.Exists(path)) File.Delete(path);+ }+ }+[Fact]public void TemplateRecordParts_ExecuteAsReusedExactWorldGeometryWithResidualValidation(){diff --git a/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs b/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.csindex 88637c20..87ab15b9 100644--- a/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs@@ -155,9 +155,9 @@ public sealed class PrismaticProfileCompositionRoundTripTests}[Theory]- [InlineData("Anchor: [0mm, 0mm, 0mm]", "Anchor: [1mm, 0mm, 0mm]", "compose-placement-unsupported-nonzero-anchor")]- [InlineData("Axis: +Z", "Axis: -Z", "compose-placement-unsupported-orientation")]- public void ExplicitComposePlacement_RejectsUnsupportedTransformInsteadOfIgnoringIt(string before, string after, string expected)+ [InlineData("ProfilePlane: XY", "ProfilePlane: YZ", "compose-placement-plane-axis-mismatch")]+ [InlineData("ReferenceDirection: +X", "ReferenceDirection: +Z", "compose-placement-reference-parallel-to-axis")]+ public void ExplicitComposePlacement_RejectsInvalidFrameInsteadOfIgnoringIt(string before, string after, string expected){var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "fixtures", "Compatibility", "LegacyV1", "Reconstruction", "nist_ctc_01", "ctc01_prismatic_blockout_x2.firmament")));var parsed = PrismaticProfileCompositionParser.Parse(source.Replace(before, after, StringComparison.Ordinal));@@ -165,6 +165,61 @@ public sealed class PrismaticProfileCompositionRoundTripTestsAssert.Contains(parsed.Diagnostics, diagnostic => diagnostic.Contains(expected, StringComparison.Ordinal));}+ [Theory]+ [InlineData("XY", "+Z", "+X", 9d, 18d, 30d, 11d, 22d, 36d)]+ [InlineData("XY", "-Z", "+X", 9d, 18d, 24d, 11d, 22d, 30d)]+ [InlineData("YZ", "+X", "+Y", 10d, 19d, 28d, 16d, 21d, 32d)]+ [InlineData("YZ", "-X", "+Y", 4d, 19d, 28d, 10d, 21d, 32d)]+ [InlineData("XZ", "+Y", "+X", 9d, 20d, 28d, 11d, 26d, 32d)]+ [InlineData("XZ", "-Y", "+X", 9d, 14d, 28d, 11d, 20d, 32d)]+ public void ExplicitComposePlacement_EmbedsOneLocalSectionStackAlongEverySignedPrincipalAxis(+ string plane, string axis, string reference,+ double minX, double minY, double minZ, double maxX, double maxY, double maxZ)+ {+ var source = $$"""+ Model OrientedCompose {+ Units: mm+ Concept Struct Layout On XY { Rect2 Stock { Center: [0mm, 0mm]; Size: [2mm, 4mm] } }+ Profile StockProfile Using Layout { Loop Outer {+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }+ } }+ Struct Body { Compose Body {+ Placement Frame { Anchor: [10mm, 20mm, 30mm]; ProfilePlane: {{plane}}; Axis: {{axis}}; ReferenceDirection: {{reference}} }+ Base Stock { Profile: StockProfile; From: 0mm; To: 6mm; Role: Stock }+ } }+ }+ """;+ var parsed = PrismaticProfileCompositionParser.Parse(source);+ Assert.Empty(parsed.Diagnostics);+ var stack = Assert.IsType<PrismaticSectionStackConstruction>(PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics));+ Assert.Empty(diagnostics);+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(PrismaticSectionStackEmitter.Emit(stack).Body);+ var bounds = VertexBounds(body);+ Assert.Equal(new Aetheris.Kernel.Core.Math.Point3D(minX, minY, minZ), bounds.Min);+ Assert.Equal(new Aetheris.Kernel.Core.Math.Point3D(maxX, maxY, maxZ), bounds.Max);++ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(step.IsSuccess, string.Join(" | ", step.Diagnostics.Select(item => item.Message)));+ var imported = Step242Importer.ImportBody(step.Value);+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(item => item.Message)));+ Assert.Equal(bounds, VertexBounds(imported.Value));+ }++ private static Aetheris.Kernel.Core.Math.BoundingBox3D VertexBounds(Aetheris.Kernel.Core.Brep.BrepBody body)+ {+ var points = body.Topology.Vertices.Select(vertex =>+ {+ Assert.True(body.TryGetVertexPoint(vertex.Id, out var point));+ return point;+ }).ToArray();+ return new(+ new(points.Min(point => point.X), points.Min(point => point.Y), points.Min(point => point.Z)),+ new(points.Max(point => point.X), points.Max(point => point.Y), points.Max(point => point.Z)));+ }+[Theory][InlineData("point-only-tangent-connection.firmament", "point-only-tangent-or-zero-width-ligament")][InlineData("zero-width-ligament.firmament", "point-only-tangent-or-zero-width-ligament")]diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex 6831bf75..9551aadd 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -87,11 +87,19 @@ internal static class AssemblyDefinitionMaterializer// Assembly files keep reusable declarations beside relational assembly syntax.// Wrap that declaration catalog in the ordinary V2 Model root for the exact// same compiler/build path used by standalone Firmament parts.- var module = "Model __AssemblyDefinition {" + Environment.NewLine- + "Units: mm" + Environment.NewLine- + definitionSource + Environment.NewLine- + $"Struct __AssemblyPart = {definitionIdentity}" + Environment.NewLine- + "}" + Environment.NewLine;+ var templateName = definitionIdentity[..definitionIdentity.IndexOf('<')];+ var inspectionDiagnostics = new List<string>();+ var targetKind = FirmamentV2TemplateExpansion.Inspect(definitionSource, inspectionDiagnostics)+ .SingleOrDefault(template => string.Equals(template.Name, templateName, StringComparison.Ordinal))?.TargetKind+ ?? "Struct";+ var application = $"{targetKind} __AssemblyPart = {definitionIdentity}" + Environment.NewLine;+ var module = targetKind == "Model"+ ? definitionSource + Environment.NewLine + application+ : "Model __AssemblyDefinition {" + Environment.NewLine+ + "Units: mm" + Environment.NewLine+ + definitionSource + Environment.NewLine+ + application+ + "}" + Environment.NewLine;var build = FirmamentBuildAndExport.CompileSource(module, Path.GetDirectoryName(Path.GetFullPath(sourceIdentity)));if (!build.IsSuccess || build.Value is null){diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 29f9ced6..b2bc4f66 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -62,7 +62,61 @@ public sealed record PrismaticRoundedRectangleSlotFeature(string Extent, string SemanticRole, string SourceSpan);public sealed record PrismaticProfilePlacement(string Name, double AnchorX, double AnchorY, double AnchorZ,- string ProfilePlane, string Axis, string ReferenceDirection, bool IsExplicit);+ string ProfilePlane, string Axis, string ReferenceDirection, bool IsExplicit)+{+ /// <summary>+ /// Resolves the legacy textual placement through the shared construction-plane+ /// authority. ReferenceDirection is the local profile X axis; local Y is derived+ /// by the right-handed frame law rather than by world-plane special cases.+ /// </summary>+ public bool TryResolveConstructionPlane(out ConstructionPlane? frame, out string? diagnostic)+ {+ frame = null;+ diagnostic = null;+ if (!TryAxis(Axis, out var normal) || !TryAxis(ReferenceDirection, out var reference))+ {+ diagnostic = $"compose-placement-invalid-axis:{Name}:axis={Axis}:reference={ReferenceDirection}";+ return false;+ }+ if (Math.Abs(normal.Dot(reference)) > 1e-12d)+ {+ diagnostic = $"compose-placement-reference-parallel-to-axis:{Name}:axis={Axis}:reference={ReferenceDirection}";+ return false;+ }+ var expectedNormal = ProfilePlane switch+ {+ "XY" => new Vector3D(0d, 0d, 1d),+ "XZ" => new Vector3D(0d, 1d, 0d),+ "YZ" => new Vector3D(1d, 0d, 0d),+ _ => default+ };+ if (expectedNormal.LengthSquared == 0d || Math.Abs(Math.Abs(normal.Dot(expectedNormal)) - 1d) > 1e-12d)+ {+ diagnostic = $"compose-placement-plane-axis-mismatch:{Name}:plane={ProfilePlane}:axis={Axis}";+ return false;+ }+ var axisZ = Direction3D.Create(normal);+ var axisX = Direction3D.Create(reference);+ var axisY = Direction3D.Create(normal.Cross(reference));+ frame = new ConstructionPlane(+ $"construction:compose:{Name}", $"placement:{Name}",+ new Point3D(AnchorX, AnchorY, AnchorZ), axisX, axisY, axisZ,+ "PrismaticProfilePlacement", "ComposePlacementToConstructionPlane");+ return true;+ }++ private static bool TryAxis(string value, out Vector3D axis)+ {+ axis = value switch+ {+ "+X" => new Vector3D(1d, 0d, 0d), "-X" => new Vector3D(-1d, 0d, 0d),+ "+Y" => new Vector3D(0d, 1d, 0d), "-Y" => new Vector3D(0d, -1d, 0d),+ "+Z" => new Vector3D(0d, 0d, 1d), "-Z" => new Vector3D(0d, 0d, -1d),+ _ => default+ };+ return axis.LengthSquared > 0d;+ }+}public sealed record PrismaticProfileCompositionFeature(string Name, string Frame, string Axis, PrismaticProfilePlacement Placement, IReadOnlyList<PrismaticProfileOperation> Operations,IReadOnlyList<double> CriticalLevels, string Provenance, IReadOnlyList<PrismaticShaftHoleFeature>? ShaftHoles = null,@@ -233,10 +287,8 @@ public static class PrismaticProfileCompositionParserif (placementMatch.Success){placement = new(placementMatch.Groups["n"].Value, N(placementMatch, "x"), N(placementMatch, "y"), N(placementMatch, "z"), placementMatch.Groups["plane"].Value, placementMatch.Groups["axis"].Value, placementMatch.Groups["reference"].Value, true);- if (placement.ProfilePlane != "XY" || placement.Axis != "+Z" || placement.ReferenceDirection != "+X")- diagnostics.Add($"compose-placement-unsupported-orientation:{placement.Name}:plane={placement.ProfilePlane}:axis={placement.Axis}:reference={placement.ReferenceDirection}");- if (Math.Abs(placement.AnchorX) > 1e-12d || Math.Abs(placement.AnchorY) > 1e-12d || Math.Abs(placement.AnchorZ) > 1e-12d)- diagnostics.Add($"compose-placement-unsupported-nonzero-anchor:{placement.Name}:[{placement.AnchorX:R},{placement.AnchorY:R},{placement.AnchorZ:R}]");+ if (!placement.TryResolveConstructionPlane(out _, out var placementDiagnostic))+ diagnostics.Add(placementDiagnostic!);}var operations = new List<PrismaticProfileOperation>();var names = new HashSet<string>(StringComparer.Ordinal);@@ -489,7 +541,7 @@ public static class PrismaticProfileCompositionParser}}var levels = operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();- var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Groups["n"].Value, "XY", "+Z", placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets) : null;+ var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Groups["n"].Value, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets) : null;return new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);}diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.csindex 7896976b..a1341470 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs@@ -160,6 +160,9 @@ public static class PrismaticSectionStackEmitterpublic static PrismaticSectionStackPlanResult TryPlan(PrismaticSectionStackConstruction stack){var d = stack.Diagnostics.ToList();+ if (!stack.Feature.Placement.TryResolveConstructionPlane(out var resolvedFrame, out var frameDiagnostic))+ return new(null, d.Append(frameDiagnostic!).Distinct().ToArray());+ var frame = resolvedFrame!;var builder = new TopologyBuilder(); var points = new Dictionary<VertexId, Point3D>(); var curves = new Dictionary<EdgeId, CurveGeometry>(); var profileCurves = new Dictionary<EdgeId, LineArcProfileCurve2D>();var vertices = new Dictionary<(long X, long Y, long Z), VertexId>(); var edges = new Dictionary<string, EdgeId>();var sideFaces = new List<(LoopId Loop, SurfaceGeometry Surface, bool SameSense, string Source, string Construction, double From, double To)>(); var capFaces = new List<(FaceId Face, double Z, bool Up)>();@@ -237,14 +240,14 @@ public static class PrismaticSectionStackEmitterforeach (var edge in builder.Model.Edges.OrderBy(e => e.Id.Value)){var curve = curves[edge.Id];- geometry.AddCurve(new CurveGeometryId(curveId), curve);+ geometry.AddCurve(new CurveGeometryId(curveId), Transform(curve, frame));var (trim, oriented) = profileCurves.TryGetValue(edge.Id, out var sourceCurve) ? CurveTrim(sourceCurve) : (new ParameterInterval(0d, (points[edge.EndVertexId] - points[edge.StartVertexId]).Length), true);bindings.AddEdgeBinding(new EdgeGeometryBinding(edge.Id, new CurveGeometryId(curveId), trim, OrientedEdgeSense: oriented));curveId++;}var surfaceId = 1;- foreach (var cap in capFaces) { geometry.AddSurface(new SurfaceGeometryId(surfaceId), SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(0, 0, cap.Z), Direction3D.Create(new Vector3D(0, 0, cap.Up ? 1 : -1)), Direction3D.Create(new Vector3D(1, 0, 0))))); bindings.AddFaceBinding(new FaceGeometryBinding(cap.Face, new SurfaceGeometryId(surfaceId++))); }- foreach (var side in sideFaces) { var face = faces[capFaces.Count + sideFaces.IndexOf(side)]; geometry.AddSurface(new SurfaceGeometryId(surfaceId), side.Surface); bindings.AddFaceBinding(new FaceGeometryBinding(face, new SurfaceGeometryId(surfaceId++), side.SameSense)); }+ foreach (var cap in capFaces) { geometry.AddSurface(new SurfaceGeometryId(surfaceId), SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), cap.Z), cap.Up ? frame.AxisZ : Direction3D.Create(-frame.AxisZ.ToVector()), frame.AxisX))); bindings.AddFaceBinding(new FaceGeometryBinding(cap.Face, new SurfaceGeometryId(surfaceId++))); }+ foreach (var side in sideFaces) { var face = faces[capFaces.Count + sideFaces.IndexOf(side)]; geometry.AddSurface(new SurfaceGeometryId(surfaceId), Transform(side.Surface, frame)); bindings.AddFaceBinding(new FaceGeometryBinding(face, new SurfaceGeometryId(surfaceId++), side.SameSense)); }foreach (var incidence in builder.Model.Coedges.GroupBy(x => x.EdgeId).Where(x => x.Count() != 2)){var edge = builder.Model.Edges.Single(x => x.Id == incidence.Key);@@ -388,7 +391,7 @@ public static class PrismaticSectionStackEmitter["PrismaticSectionStackConstruction", "ProfileArrangement2D", side.Source, side.Construction]));}var topologyPlan = new PrismaticSectionStackTopologyPlan($"compose-plan:{stack.Feature.Name}", builder.Model, geometry, bindings,- points.ToDictionary(x => x.Key, x => x.Value), faceMappings, correspondence, provenance);+ points.ToDictionary(x => x.Key, x => frame.ToWorld((x.Value.X, x.Value.Y), x.Value.Z)), faceMappings, correspondence, provenance);var plan = new PrismaticSectionStackBrepPlan($"compose:{stack.Feature.Name}:slabs={stack.Slabs.Count}:transitions={stack.Transitions.Count}", points.Count, builder.Model.Edges.Count(), faces.Count, "deterministic-slab-partitions", true, correspondence, topologyPlan);d.Add("compose-authoritative-section-stack-brep-plan"); d.Add("compose-no-3d-boolean-used");d.Add("compose-plan-first-materialization-boundary");@@ -446,6 +449,18 @@ public static class PrismaticSectionStackEmitter};private static CurveGeometry Curve(LineArcProfileCurve2D curve, double z) => curve switch { LineArcLineSegment2D l => CurveGeometry.FromLine(new Line3Curve(new Point3D(l.Start.X, l.Start.Y, z), Direction3D.Create(new Vector3D(l.End.X - l.Start.X, l.End.Y - l.Start.Y, 0)))), LineArcCircularArc2D a => CurveGeometry.FromCircle(new Circle3Curve(new Point3D(a.Center.X, a.Center.Y, z), Direction3D.Create(new Vector3D(0, 0, 1)), a.Radius, Direction3D.Create(new Vector3D(1, 0, 0)))), _ => throw new NotSupportedException() };private static SurfaceGeometry SideSurface(LineArcProfileCurve2D curve, double z, bool hole) => curve switch { LineArcLineSegment2D l => SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(l.Start.X, l.Start.Y, z), Direction3D.Create(new Vector3D(hole ? l.Start.Y - l.End.Y : l.End.Y - l.Start.Y, hole ? l.End.X - l.Start.X : l.Start.X - l.End.X, 0)), Direction3D.Create(new Vector3D(0, 0, 1)))), LineArcCircularArc2D a => SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(a.Center.X, a.Center.Y, z), Direction3D.Create(new Vector3D(0, 0, 1)), a.Radius, Direction3D.Create(new Vector3D(1, 0, 0)))), _ => throw new NotSupportedException() };+ private static CurveGeometry Transform(CurveGeometry curve, ConstructionPlane frame) => curve.Kind switch+ {+ CurveGeometryKind.Line3 => CurveGeometry.FromLine(new Line3Curve(frame.ToWorld((curve.Line3!.Value.Origin.X, curve.Line3.Value.Origin.Y), curve.Line3.Value.Origin.Z), Direction3D.Create(frame.ToWorldDirection(curve.Line3.Value.Direction.ToVector())))),+ CurveGeometryKind.Circle3 => CurveGeometry.FromCircle(new Circle3Curve(frame.ToWorld((curve.Circle3!.Value.Center.X, curve.Circle3.Value.Center.Y), curve.Circle3.Value.Center.Z), Direction3D.Create(frame.ToWorldDirection(curve.Circle3.Value.Normal.ToVector())), curve.Circle3.Value.Radius, Direction3D.Create(frame.ToWorldDirection(curve.Circle3.Value.XAxis.ToVector())))),+ _ => throw new NotSupportedException($"Section-stack frame transform does not support curve {curve.Kind}.")+ };+ private static SurfaceGeometry Transform(SurfaceGeometry surface, ConstructionPlane frame) => surface.Kind switch+ {+ SurfaceGeometryKind.Plane => SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((surface.Plane!.Value.Origin.X, surface.Plane.Value.Origin.Y), surface.Plane.Value.Origin.Z), Direction3D.Create(frame.ToWorldDirection(surface.Plane.Value.Normal.ToVector())), Direction3D.Create(frame.ToWorldDirection(surface.Plane.Value.UAxis.ToVector())))),+ SurfaceGeometryKind.Cylinder => SurfaceGeometry.FromCylinder(new CylinderSurface(frame.ToWorld((surface.Cylinder!.Value.Origin.X, surface.Cylinder.Value.Origin.Y), surface.Cylinder.Value.Origin.Z), Direction3D.Create(frame.ToWorldDirection(surface.Cylinder.Value.Axis.ToVector())), surface.Cylinder.Value.Radius, Direction3D.Create(frame.ToWorldDirection(surface.Cylinder.Value.XAxis.ToVector())))),+ _ => throw new NotSupportedException($"Section-stack frame transform does not support surface {surface.Kind}.")+ };private static LoopId AddLoop(TopologyBuilder builder, IReadOnlyList<Use> uses) { var id = builder.AllocateLoopId(); var coedges = uses.Select(_ => builder.AllocateCoedgeId()).ToArray(); for (var i = 0; i < uses.Count; i++) builder.AddCoedge(new Coedge(coedges[i], uses[i].Edge, id, coedges[(i + 1) % coedges.Length], coedges[(i + coedges.Length - 1) % coedges.Length], uses[i].Reverse)); builder.AddLoop(new Loop(id, coedges)); return id; }private readonly record struct Use(EdgeId Edge, bool Reverse);}diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.mdindex 0d9f3639..20b7d02a 100644--- a/docs/public/firmament/step-import.md+++ b/docs/public/firmament/step-import.md@@ -1,7 +1,7 @@# STEP import and inlineSTEP-Use `aetheris analyze part.step --json` to inspect STEP topology, analytic surface families, bounds, manifold assessment, and semantic PMI. Use `aetheris sheetmetal recognize` for bounded Sheet Metal recognition rather than treating generic topology analysis as manufacturing intent.+Use `aetheris analyze part.step --json` to inspect STEP topology, analytic surface families, bounds, manifold assessment, and semantic PMI. When a part is easiest to understand by its manufacturing section, inspect it first with `aetheris analyze section part.step --xy|--xz|--yz --offset value --json`; use `--origin x,y,z --normal x,y,z` for an arbitrary construction plane and `--out section.svg` for deterministic visual evidence. This section-first path preserves analytic line/arc trims and reports closed-loop nesting instead of asking a tessellated view to carry design intent. Use `aetheris sheetmetal recognize` for bounded Sheet Metal recognition rather than treating generic topology analysis as manufacturing intent.Firmament `inlineSTEP` consumes Aetheris-canonical AP242 on the bounded production path. Imported faces are selected by source entity identity, for example `body.face(#170)`, and recognized regions may supply stable semantic aliases. [`inline-step-cantilever.firmament`](../../../fixtures/Canonical/FEA/inline-step-cantilever.firmament) demonstrates FEA on a checked-in canonical STEP resource.-The importer does not promise arbitrary containment, multi-root assemblies, or every AP242 surface family as a single native body. Multi-root assembly-like STEP belongs to assembly import. Unsupported containment in FEA reports `firmament-analysis-inline-step-containment-unsupported`; missing files and unresolved face identities are fatal diagnostics.+The single-body importer does not promise arbitrary containment, multi-root assemblies, or every AP242 surface family as one native body. `aetheris analyze compound part.step --json` is the exact inspection path for disconnected rigid roots: it reports each root independently and never silently selects or merges one. Multiple geometric roots alone do **not** establish product structure, occurrence transforms, mates, or interfaces. Use assembly import when the STEP product graph carries that semantics, and use Firmament assembly authoring when the intended component relationships must be stated explicitly. Unsupported containment in FEA reports `firmament-analysis-inline-step-containment-unsupported`; missing files and unresolved face identities are fatal diagnostics.diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex 5b4e91a4..f0f2a317 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -8,6 +8,8 @@ Primary public commands:| `build <file> [--output path] [--json]` | Materialize and export exact STEP AP242 || `inspect <firmament-or-step> [--json]` | Inspect source semantics or route STEP to analysis || `analyze <step> [--json]` | Reinspect topology, surfaces, bounds, manifold state, and PMI |+| `analyze section <step> ((--xy\|--xz\|--yz) --offset value\|--origin x,y,z --normal x,y,z) [--out section.svg] [--json]` | Extract trim-aware analytic section loops in a principal or arbitrary plane and optionally render deterministic SVG evidence |+| `analyze compound <step> [--json]` | Inspect every disconnected rigid root without silently selecting or merging one || `view <file>` | Open in bundled Cadmata || `fea <file> --out-dir dir [--json]` | Compile and solve the bounded linear-elastic analysis || `sheetmetal ...` | Inspect, recognize, recover, compare, or flatten Sheet Metal |@@ -18,6 +20,8 @@ Primary public commands:Run `aetheris <command> --help` for exact options. JSON is a public automation surface, but its root is command-specific: process exit status is authoritative, `validate` reports `firmamentV2Validation.status`, and materializing/analysis commands report `success` where documented. Diagnostics are structured; artifact paths are explicit; wireframe reports trim/pcurve coverage and a deterministic SVG hash; Sheet Metal reports regions, bends, and lowered features separately; FEA reports requested/result artifacts; sculpting builds report every `BodyState`, `GeometricDelta`, validation evidence, surface-family inventory, and the sibling `.delta.json` path; other builds report emitted features and PMI export evidence. Counts describe semantic items at the stated layer, not arbitrary STEP entity counts.+Generic STEP analysis reports analytic placement and size information where it is present: planes include origin and normal; bounded cylinders and cones include axis, axial extent, and circular-boundary angular extent; spheres include center and radius; and circles include center, axis, radius, sweep, orientation, and their actual trimmed endpoints. Circular-edge bounds and section output are computed from those trims rather than from the supporting full circle. `analyze section` returns normalized closed loops with deterministic orientation and nesting metadata; `--out` is intended as compact geometry evidence, not a substitute for the JSON record.+## Assembly display meshes`aetheris mesh <assembly.firmament|assembly.firmasm> --format assembly-json --output <file.mesh.json> --json` exports shared local definition meshes and stable world-space occurrences. Failed geometry is not omitted. The default destination is `artifacts/local/mesh/<name>.mesh.json`. See [editable mechanisms](../firmament/editable-mechanisms.md) for the schema and a working consumer.diff --git a/docs/release/BENCHCAD-AETHERIS-X0.md b/docs/release/BENCHCAD-AETHERIS-X0.mdnew file mode 100644index 00000000..1db75b56--- /dev/null+++ b/docs/release/BENCHCAD-AETHERIS-X0.md@@ -0,0 +1,182 @@+# BENCHCAD-AETHERIS-X0 — open-book reconstruction smoke qualification++## Status and executive answer++This document reports an **open-book BenchCAD reconstruction score**. It is not an official BenchCAD Vision2Code score, an official CodeEdit score, a blind result, or a leaderboard-comparable result.++The full requested experiment covers 18,648 records. This X0 run has completed the repository/scorer audit and a source-assisted, eight-record smoke qualification over the STEP targets committed in BenchCAD's `test_data/`. It is therefore a meaningful progression checkpoint, not the full experiment result.++On the four committed Vision2Code targets, GPT-5.6 Sol Codex plus Aetheris produced three exact voxel matches after bounded refinement. Mean IoU rose from 0.7479 to 0.7581; the remaining axis-rotated washer scored 0.0325 because public Firmament profile extrusion is fixed to XY/+Z. On the four committed CodeEdit targets, raw target IoU averaged 0.2180 and normalized IoU averaged 0.0102. The dominant failures require semantic geometry Aetheris does not yet admit: connected sphere/shaft or revolved-profile construction and bounded blind side-cylinder removal.++The run also found and fixed a general inspection blocker: Aetheris now unwraps STEP `SEAM_CURVE` exactly like its `SURFACE_CURVE` sibling and follows the authoritative 3D curve. That change made ordinary CadQuery STEP topology inspectable and has a focused regression test.++## Reproducibility++| Item | Value |+| --- | --- |+| BenchCAD repository | `https://github.com/BenchCAD/BenchCAD-main.git` |+| BenchCAD commit | `52087ef4b08811c21c09b8b16d0ae36c70844865` |+| Aetheris commit at start | `4605ac2355b5ff5aeca334225eb18c3df8e3d19b` plus this report's working-tree changes |+| Model | GPT-5.6 Sol Codex |+| Mode | Open book; STEP inspected first, public GT CadQuery subsequently used; final authority remains independent Firmament |+| Scorer | `benchcad_core/scoring/iou.py::iou_step_vs_step`, normalized 64-cube voxel IoU |+| Local artifacts | `artifacts/local/benchcad-aetheris/` |+| Harness | `scripts/benchcad-aetheris-x0.py` |++Reproduce the qualified smoke run from the Aetheris root with an adjacent BenchCAD checkout:++```powershell+$aetherisRoot = (Get-Location).Path+$benchCadRoot = (Resolve-Path ..\BenchCAD-main).Path+uv run --project $benchCadRoot python scripts\benchcad-aetheris-x0.py `+ --aetheris-root $aetherisRoot `+ --benchcad-root $benchCadRoot+```++Each record directory contains `target-summary.json`, `reconstruction.firmament`, `reconstructed.step`, `inspect-target.json`, `inspect-reconstructed.json`, `score.json`, `notes.md`, and GT/reconstruction preview PNGs. The harness rebuilds every Firmament source before scoring. None contains `inlineSTEP`, an imported target path, target vertices, or hand-authored STEP entities.++## Upstream repository and scoring audit++Vision2Code target records are sourced by `Vision2Code/tools/download_codegen_bench.py` from Hugging Face config path `code_gen/data/*.parquet`. The current schema supplies `stem`, `family`, CadQuery `code`, and render images, but no shipped GT STEP. The downloader executes each GT CadQuery program through `benchcad_core/scoring/exec_cq.py::execute_cq_to_step` and writes `Vision2Code/data/steps/<record>.step`. The committed four-record qualification corpus is under `Vision2Code/test_data/`.++CodeEdit target records are sourced by `CodeEdit/tools/download_edit_bench.py` from `edit-bench/*`. Each row supplies original and target CadQuery plus `orig_step` and `gt_step` bytes. The downloader writes `CodeEdit/data/steps/<record>_{orig,gt}.step`; the committed four-record corpus is under `CodeEdit/test_data/`.++Both tasks call `benchcad_core/scoring/iou.py::iou_step_vs_step`. Each STEP is tessellated independently, translated so its bounding-box center is `(0.5, 0.5, 0.5)`, uniformly scaled so its longest bounding-box side is 1, voxelized at pitch 1/64, filled, centered in a padded 68-cube grid, and compared without rotational search or post-score alignment. Orientation therefore remains significant.++CodeEdit additionally computes:++```text+normalized IoU = clip((model IoU - baseline IoU) / (1 - baseline IoU), 0, 1)+```++The current BenchCAD errata documents 26 historical Vision2Code GT timeouts. It explicitly classifies them as valid programs, not broken targets: all 185 members of the slow `double_simplex_sprocket` family were rebuilt successfully in the pinned environment, and the default timeout was raised from 90 to 300 seconds. There are no current per-record invalid-target entries. Until the full GT materialization is executed on this machine, the auditable expected inventory is 17,900 eligible Vision2Code records and 748 eligible CodeEdit records; this report does not pretend they were locally reconstructed.++## Qualified target inventory++Exact bounds, volumes, body counts, and topology below come from CadQuery/OCP over the authoritative STEP. Aetheris inspection is retained separately so importer failures are not hidden.++| Record | Task | Bounds size (mm) | Volume (mm³) | Bodies | Surface families | Faces | Edges | Status |+| --- | --- | ---: | ---: | ---: | --- | ---: | ---: | --- |+| `bolt_000008_s20260505` | Vision2Code | 27.71 × 24 × 120 | 27014.4819 | 1 | plane 15, cylinder 1 | 16 | 33 | Eligible |+| `hex_nut_000006_s20260505` | Vision2Code | 6.35 × 5.499 × 2.4 | 45.8920 | 1 | plane 8, cylinder 1 | 9 | 21 | Eligible |+| `spacer_ring_000007_s20260505` | Vision2Code | 23.95 × 24 × 0.8 | 212.4207 | 1 | plane 4, cylinder 2 | 6 | 12 | Eligible |+| `washer_000001_s20260505` | Vision2Code | 64.8 × 5 × 64.8 | 11087.9560 | 1 | plane 2, cylinder 2, cone 2 | 6 | 10 | Eligible |+| `ball_knob_cylinder_radius_f130` | CodeEdit | 25 × 25 × 75 | 13556.8886 | 2 | plane 2, cylinder 1, sphere 1 | 4 | 4 | Eligible |+| `battery_holder_box_y_f130` | CodeEdit | 48.5 × 39 × 8.8 | 9817.6798 | 1 | plane 10, cylinder 2 | 12 | 24 | Eligible |+| `topup_ball_knob_axial_hole` | CodeEdit | 25 × 25 × 74.63 | 9251.7970 | 2 | plane 2, cylinder 3, sphere 1 | 6 | 10 | Eligible |+| `topup_ball_knob_axial_hole_rev` | CodeEdit | 25 × 25 × 75 | 11362.0934 | 2 | plane 2, cylinder 1, sphere 1 | 4 | 4 | Eligible |++The smoke corpus spans six part families. Its target topology contains 11 solids, 63 faces, and analytic plane/cylinder/cone/sphere surfaces; it contains no thread target. Thread was therefore not pre-implemented.++## First pass++Every qualified record received a buildable current-capability attempt before benchmark-driven geometry changes. The first-pass failure cause was recorded before refinement.++| Task | Records | Mean raw IoU | Median raw IoU | IoU ≥ 0.99 | Build success | Mean normalized IoU |+| --- | ---: | ---: | ---: | ---: | ---: | ---: |+| Vision2Code | 4 | 0.7479 | 0.9795 | 2 | 4/4 | n/a |+| CodeEdit | 4 | 0.2180 | 0.0668 | 0 | 4/4 | 0.0102 |++## Capability and refinement pass++One reusable Aetheris capability was added: `Step242Importer.DecodeCurveGeometry` now accepts `SEAM_CURVE` and follows its authoritative 3D curve. The focused regression constructs a cylindrical STEP face whose circular edge is carried by `SEAM_CURVE`. This removes `Importer.EntityFamily: EDGE_CURVE geometry 'SEAM_CURVE' is unsupported` for CadQuery STEP and is not record-ID-specific. Its direct score impact is zero; its experiment impact is that the required topology inventory can proceed through Aetheris for single-root targets.++Two record reconstructions were refined using already-general Firmament constructs:++- The spacer ring became one exact line/arc C-profile rather than a full annulus, improving IoU by 0.0394.+- The bolt's explicit six-line head profile admitted a semantic `EdgeFinish` chamfer, improving IoU by 0.0016.++No new semantic primitive was added merely to rescue one sample. In particular, this smoke corpus did not justify a Thread implementation.++## Second pass++| Task | First-pass mean IoU | Second-pass mean IoU | Delta | Second-pass normalized IoU |+| --- | ---: | ---: | ---: | ---: |+| Vision2Code | 0.7479 | 0.7581 | +0.0102 | n/a |+| CodeEdit | 0.2180 | 0.2180 | 0.0000 | 0.0102 |++| Record | First IoU | Second IoU | Delta | CodeEdit normalized IoU |+| --- | ---: | ---: | ---: | ---: |+| `bolt_000008_s20260505` | 0.9984 | 1.0000 | +0.0016 | n/a |+| `hex_nut_000006_s20260505` | 1.0000 | 1.0000 | 0.0000 | n/a |+| `spacer_ring_000007_s20260505` | 0.9606 | 1.0000 | +0.0394 | n/a |+| `washer_000001_s20260505` | 0.0325 | 0.0325 | 0.0000 | n/a |+| `ball_knob_cylinder_radius_f130` | 0.0716 | 0.0716 | 0.0000 | 0.0000 |+| `battery_holder_box_y_f130` | 0.6813 | 0.6813 | 0.0000 | 0.0410 |+| `topup_ball_knob_axial_hole` | 0.0570 | 0.0570 | 0.0000 | 0.0000 |+| `topup_ball_knob_axial_hole_rev` | 0.0620 | 0.0620 | 0.0000 | 0.0000 |++## Score distribution++| Task/pass | p10 | p25 | Median | p75 | p90 | ≥0.90 | ≥0.95 | ≥0.99 |+| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |+| Vision2Code first | 0.3109 | 0.7286 | 0.9795 | 0.9988 | 0.9995 | 3 | 3 | 2 |+| Vision2Code second | 0.3227 | 0.7581 | 1.0000 | 1.0000 | 1.0000 | 3 | 3 | 3 |+| CodeEdit first | 0.0585 | 0.0607 | 0.0668 | 0.2240 | 0.4984 | 0 | 0 | 0 |+| CodeEdit second | 0.0585 | 0.0607 | 0.0668 | 0.2240 | 0.4984 | 0 | 0 | 0 |++These percentiles describe four records per task and must not be generalized to the full dataset.++## Failure taxonomy++| Primary cause | Count | Mean lost raw IoU | General fix? |+| --- | ---: | ---: | --- |+| MissingSemanticPrimitive | 5 | 0.8190 | Yes: axis-aware profile placement; bounded revolved profiles or connected ball-end shafts; bounded blind side-cylinder removal |++There were no build failures, scorer failures, invalid targets, kernel failures, or STEP-export failures in the eight final attempts. The five non-near-perfect reconstructions all built successfully but could not express the target construction through currently admitted public semantics.++## Representative parts++### Easy: hex nut++The STEP showed one regular hexagonal prism and one axial cylindrical bore. A `RegularPolygon2<6>` plus `Circle2` inner loop extruded to the measured thickness scored 1.0000 on both passes.++### Medium: spacer ring++The initial annulus captured most material and scored 0.9606. STEP/source inspection showed that a rectangular radial cut joins the bore to the exterior. Re-authoring the part as one closed boundary containing major outer and inner arcs plus two cut lines scored 1.0000 without adding a primitive.++### High score: bolt++An axial circular Base plus a six-line semantic Boss recovered the shaft and head. Adding the supported top-boundary chamfer raised 0.9984 to 1.0000. Bounds and volume match to reported precision. The Aetheris result has 19 faces/42 edges versus the GT's 16/33 because its chamfer route partitions three cylindrical support faces; this is an accepted topological partition difference, not hidden geometric drift.++### Hard/failure: ball-knob edits++The targets are two-solid STEP compounds containing a spherical knob and cylindrical stem; one variant also carries an axial bore. Public Firmament can emit the sphere or cylinder independently but deliberately has no arbitrary Union. The bounded sphere witness therefore scores only 0.0570–0.0716. A general revolved-profile or ball-end-shaft semantic contract is the appropriate next design question; importing or embedding the GT compound is not.++Local GT and Aetheris preview pairs are stored as `target-preview.png` and `reconstructed-preview.png` in each record artifact directory.++## Tooling friction and next isolated blockers++1. CadQuery writes `SEAM_CURVE`; Aetheris previously rejected it. This run fixed and tested that general importer gap.+2. The three ball-knob targets are multi-root compounds representing one benchmark part. `aetheris analyze` classifies them as assembly-like and refuses single-part analysis. The artifact retains this failure while CadQuery/OCP supplies exact aggregate inventory. A part-compound inspection route is needed; silently choosing one root would be wrong.+3. Aetheris reports incomplete bounds for the spacer ring because extrema of a major trimmed circular arc are lost. CadQuery/OCP reports the authoritative full bounds. Trim-aware analytic bounds are the next concrete inspection-correctness blocker.+4. Exact `aetheris analyze volume` is intentionally narrow. The harness uses the same pinned OCP geometry behind BenchCAD for exact inventory volume and retains Aetheris inspection separately.+5. Firmament has no public axis placement for ordinary Profile extrusion, so the washer cannot preserve the target's Y-axis orientation even though its 2D annular section is trivial.+6. The battery-holder target requires two half-depth +X cylindrical channels open through the top. The current construction-plane hole is through-all only.++## Capability amortization++Within this small corpus, solving early records did make later work easier: the SEAM_CURVE fix removed a repeated CadQuery inspection failure, and the explicit bounded line/arc profile technique used for the bolt and ring produced two exact matches without kernel special cases. The evidence is not yet sufficient to claim reduced iterations or higher first-attempt scores across the 18,648-record full split.++## Validation ledger++Completed for this checkpoint:++- BenchCAD environment synchronized with the upstream lock; all eight GT-vs-GT scorer sanity checks returned IoU 1.0.+- All eight committed Firmament reconstructions build through the real Aetheris CLI.+- All eight reconstructed STEP files score through BenchCAD's scorer.+- Second-pass score files and aggregate result JSON regenerated deterministically.+- SEAM_CURVE focused importer test passed as part of the full suite.+- All eight final STEP files reimport through the locally published Aetheris CLI.+- Representative bolt and hex-nut packaged-CLI rebuilds are byte-identical to the scored STEP files.+- `dotnet build Aetheris.slnx -c Release -m:1` passed with zero warnings and zero errors.+- `dotnet test Aetheris.slnx -c Release --no-build -m:1` passed all 3,405 discovered tests; the intentionally empty FrictionLab assembly reported no tests.+- Python harness lint and the repository information-architecture guard passed.+- BenchCAD's focused Vision2Code/CodeEdit scorer suites passed 13 tests (upstream dependency deprecation warnings only).++Not completed, and therefore not claimed:++- materialization/inventory/reconstruction of all 17,900 Vision2Code and 748 CodeEdit records;+- a dataset-wide first or second pass;+- Thread tests, because no thread occurs in the qualified corpus;+- a public full-dataset score.diff --git a/docs/release/BENCHCAD-PREP-X1.md b/docs/release/BENCHCAD-PREP-X1.mdnew file mode 100644index 00000000..478f0d95--- /dev/null+++ b/docs/release/BENCHCAD-PREP-X1.md@@ -0,0 +1,156 @@+# BENCHCAD-PREP-X1 — reconstruction primitive closure++## Status and executive answer++This milestone reaches **meaningful progression**. Seven of the same eight X0 smoke records now score exactly `1.0000`; the eighth rises from `0.0570` to `0.9409`. The remaining error is isolated: the axial bore crosses both the stem and sphere, while public Firmament can express the annular stem but does not apply `Hole` to a `Sphere`. Adding a record-specific Boolean, `BallKnob`, or premature `Revolve` would violate this milestone's scope.++The X0 failures primarily reflected missing basic orientation, inspection, and semantic-decomposition tools—not missing complex geometry. The rotated washer is an annular profile on a Y-normal construction plane. In fact, the audit found that ordinary `Profile Using <Construction Plane>` extrusion already had arbitrary-frame authority; X0 had failed to discover and use it. X1 reuses that path and makes Compose's explicit placement honor its declared signed frame instead of rejecting it. The battery holder is rectangular stock modified by two repeated major-arc profile deltas and extruded along X. The ball knob is a two-component sphere-and-cylinder assembly with an explicit interface. Once those facts were visible and authorable, three formerly difficult records became exact.++This remains an open-book, human-assisted smoke qualification. It is not blind, is not an official BenchCAD score, and is not leaderboard-comparable.++## Reproducibility++| Item | Value |+| --- | --- |+| BenchCAD commit | `52087ef4b08811c21c09b8b16d0ae36c70844865` |+| Aetheris base commit | `4605ac2355b5ff5aeca334225eb18c3df8e3d19b` plus this milestone's working-tree changes |+| Corpus | The exact eight committed X0 smoke records |+| Scorer | BenchCAD `iou_step_vs_step`, normalized 64-cube voxel IoU |+| Harness | `scripts/benchcad-aetheris-x1.py`, reusing `scripts/benchcad-aetheris-x0.py` |+| Generated evidence | `artifacts/local/benchcad-aetheris-x1/` (ignored) |++The X0 baseline is supplied explicitly rather than inferred from an intermediate run:++```powershell+python scripts/benchcad-aetheris-x1.py `+ --aetheris-root (Get-Location).Path `+ --benchcad-root (Resolve-Path ..\BenchCAD-main).Path `+ --aetheris-cli artifacts/local/benchcad-aetheris-x1/publish/aetheris.exe `+ --baseline-summary artifacts/local/benchcad-aetheris/results-summary.json+```++## X0 to X1 scores++| Record | X0 raw IoU | X1 raw IoU | Delta | X1 normalized IoU | Primary reason |+| --- | ---: | ---: | ---: | ---: | --- |+| `bolt_000008_s20260505` | 1.0000 | 1.0000 | 0.0000 | n/a | Baseline preserved |+| `hex_nut_000006_s20260505` | 1.0000 | 1.0000 | 0.0000 | n/a | Baseline preserved |+| `spacer_ring_000007_s20260505` | 1.0000 | 1.0000 | 0.0000 | n/a | Geometry preserved; trimmed-major-arc bounds fixed |+| `washer_000001_s20260505` | 0.0325 | 1.0000 | +0.9675 | n/a | Construction-plane profile and Y-axis extrusion |+| `ball_knob_cylinder_radius_f130` | 0.0716 | 1.0000 | +0.9284 | 1.0000 | Sphere + cylinder assembly, not a unioned feature |+| `battery_holder_box_y_f130` | 0.6813 | 1.0000 | +0.3187 | 1.0000 | Rectangle plus two major-arc deltas, extruded along X |+| `topup_ball_knob_axial_hole` | 0.0570 | 0.9409 | +0.8839 | 0.4911 | Exact annular stem; sphere-side continuation remains unsupported |+| `topup_ball_knob_axial_hole_rev` | 0.0620 | 1.0000 | +0.9380 | 1.0000 | Sphere + narrower cylinder assembly |++Vision2Code mean raw IoU rises from `0.7581` to `1.0000`. CodeEdit mean raw IoU rises from `0.2180` to `0.9852`, and its mean normalized IoU is `0.8728`. All eight sources build; seven are exact.++## Corrected geometry interpretation++Human visual review corrected three X0 hypotheses:++- **Washer:** the geometry was already trivial; only the coordinate frame was wrong. The X1 source uses an ordinary annular `Profile Using WasherFrame` whose plane normal is world `-Y`.+- **Ball knob:** the STEP contains two disconnected simple solids. Compound inspection reports one cylindrical solid and one spherical solid, so the reconstruction uses definitions, occurrences, an `Interface`, and a `FrameCoincident` mate.+- **Battery holder:** it is not a blind-cylinder feature. Its constant YZ section is a rectangle whose top carrier is replaced by two inward major circular arcs. Following the supplied red/green sketch, X1 starts with the red rectangular loop and applies two green arc deltas; thin full-stock end slices preserve the end walls.++This human intervention is part of the experiment and is why the result must not be described as blind.++## Inspection evidence++The new section command makes the battery-holder construction explicit:++```text+plane: YZ at x=0+closed loops: 1+segments: 6 lines + 2 arcs+each arc: radius 5.25 mm, sweep 4.381389 rad (251.04 degrees)+section bounds: [-19.5,-4.4] to [19.5,4.4] mm+```++The deterministic SVG is generated at `artifacts/local/benchcad-aetheris-x1/battery-holder-target-section.svg`. Both sweeps exceed 180 degrees; their cardinal extrema are included only when they lie in the periodic trim interval.++Compound inspection of `ball_knob_cylinder_radius_f130` reports `RootCount=2`, `SolidCount=2`, aggregate bounds `[-12.5,-12.5,-62.5]` to `[12.5,12.5,12.5]`, and separate inventories of one cylinder plus two planes and one sphere. It neither rejects the file nor silently selects a root. The assembly remains inspectable as `Knob`, `Stem`, `KnobStemInterface`, and `TangentAttachment`.++The washer source inspection identifies a construction plane with origin `[0,0,0]`, normal `[0,-1,0]`, local up `[0,0,1]`, and extrusion span 0–5 mm. STEP export and reimport preserve those world-space bounds.++The spacer-ring major-arc regression now reports the authoritative full bounds rather than endpoint-only bounds. Periodic cardinal candidates at 0, 90, 180, and 270 degrees are admitted only when contained by the actual wrapped sweep.++## Before and after authoring++The washer changed from an implicitly XY/+Z profile to the same profile on shared plane authority:++```firmament+Concept Struct WasherDatum {+ Plane: Plane { Origin: [0mm,0mm,0mm]; Normal: [0,-1,0]; Up: [0,0,1] }+}+Construction Plane WasherFrame { Trace: WasherDatum.Plane }+Profile WasherProfile Using WasherFrame { ... }+Struct Washer { Extrude Body { Profile: WasherProfile; From: 0mm; To: 5mm } }+```++The ball witness changed from a lone `Sphere` to ordinary assembly semantics:++```firmament+Assembly BallKnob {+ <Assembly BallKnob>+ <Part Knob = KnobSphere<R: 12.5mm>> ... </Part>+ <Part Stem = KnobStem<R: 5.85mm>> ... </Part>+ </Assembly>+ Mate TangentAttachment: KnobStemInterface { ... }+}+```++The battery holder now directly encodes the reviewed cross-section:++```firmament+Rect2 Stock { Center: [0mm,0mm]; Size: [8.8mm,39mm] }+ProfileDelta RightPocket { On: Stock.Right ... Transition ArcA { Kind: Round; Radius: 5.25mm; ... } ... }+ProfileDelta LeftPocket { On: Stock.Right ... Transition ArcA { Kind: Round; Radius: 5.25mm; ... } ... }+Profile GroovedProfile From Stock+Compose Body {+ Placement HolderPlacement { ProfilePlane: YZ; Axis: +X; ReferenceDirection: +Z }+ Base GroovedStock { Profile: GroovedProfile; From: -24.25mm; To: 24.25mm; Role: Stock }+}+```++This uses the existing `ProfileDelta` and Compose lowering authority; there is no benchmark-specific pocket type or second extrusion backend.++## Architectural value++| Capability | Motivating record | General CAD value | Public? |+| --- | --- | --- | --- |+| Existing construction-plane Profile extrusion, plus signed Compose placement closure | Washer | Arbitrarily oriented prismatic construction and signed principal Compose placement through shared frame math | Yes |+| Principal/arbitrary-plane analytic section plus SVG | Battery holder | Reveals constant-section construction before feature invention | Yes, CLI |+| Trim-correct periodic arc bounds and sweep | Spacer ring, battery holder | Correct major/minor arc geometry, bounds, and machine-readable provenance | Yes, CLI analysis |+| Exact compound-root inspection | Ball knobs | Inventories disconnected solids without inventing product semantics | Yes, CLI |+| Model-target assembly definitions | Ball knobs | Reuses analytic model definitions as typed assembly components | Yes |+| Explicit sphere/cylinder interface reconstruction | Ball knobs | Preserves engineering identity and attachment semantics while exporting occupied STEP geometry | Yes |++## Compatibility and scope++Profiles without an explicit plane retain canonical XY/+Z behavior. Existing arbitrary construction-plane Profile extrusion remains authoritative. Compose placements now resolve all signed principal axes `+X/-X/+Y/-Y/+Z/-Z` through the same `ConstructionPlane` math and apply the world transform once at lowering. No `ExtrusionPlane`, axis-specific profile type, multibody Part, automatic feature recognizer, arbitrary Boolean union, `BallKnob`, `BatteryHolderPocket`, or benchmark scoring change was introduced.++Multiple STEP roots remain serialization facts, not automatic Firmament product semantics. `analyze compound` reports them exactly; assembly import/authoring owns product structure and relationships.++## Validation ledger++The release validation for this milestone completed as follows:++- `dotnet build Aetheris.slnx -c Release -m:1 --no-restore`: passed with zero warnings and zero errors;+- `dotnet test Aetheris.slnx -c Release --no-build -m:1`: 3,416 tests passed; the intentionally empty FrictionLab assembly reported no tests;+- default and arbitrary construction-plane Profile binding/materialization, including a non-principal normal;+- all six signed principal Compose extrusion axes and a nonzero placement anchor;+- STEP export/reimport orientation;+- principal and arbitrary section extraction, deterministic SVG, >180-degree arc sweep, wrapped periodic trims, and spacer-ring bounds;+- two-root compound inventory without first-root selection;+- sphere/cylinder assembly materialization, interface inspection, AP242 export, and reimport;+- a freshly published CLI rebuilding/scoring the washer, battery holder, ball-knob family, and the same eight X0 records;+- deterministic repeated packaged-CLI output: 26 reconstructed STEP, inspection JSON, and SVG files checked, zero SHA-256 mismatches;+- modified-document relative-link check: three files checked, zero broken links;+- repository information-architecture guard: 4,069 tracked files inspected, passed;+- Python harness compilation and `git diff --check`: passed (line-ending notices only).++The detailed generated JSON, STEP, SVG, scoring, and preview evidence remains under ignored `artifacts/local/benchcad-aetheris-x1/` in accordance with the generated-artifact policy.++## Honest residual++Inspection of the axial-hole target shows cylindrical bore surfaces in both disconnected solids. The assembly reconstruction therefore must not pretend the hole belongs only to the stem. X1 expresses the stem exactly as an annular extrusion, but the public `Hole` host set does not include `Sphere`; this leaves raw IoU `0.9409`. Closing that gap responsibly requires a separately justified sphere-cylinder subtraction or a general revolved-section capability. This milestone stops at that precise boundary instead of adding brittle record-specific geometry.diff --git a/scripts/benchcad-aetheris-x0.py b/scripts/benchcad-aetheris-x0.pynew file mode 100644index 00000000..84720fbf--- /dev/null+++ b/scripts/benchcad-aetheris-x0.py@@ -0,0 +1,201 @@+"""Build, inspect, and score local BenchCAD-to-Firmament reconstructions.++This is an experiment harness, not a BenchCAD submission runner. It consumes+independently authored Firmament under artifacts/local/benchcad-aetheris and+uses BenchCAD's own voxel scorer from an explicitly supplied checkout.+"""++from __future__ import annotations++import argparse+import json+import subprocess+import sys+from collections import Counter+from pathlib import Path+++def run(command: list[str], cwd: Path) -> tuple[int, str, str]:+ completed = subprocess.run(command, cwd=cwd, text=True, capture_output=True, check=False)+ return completed.returncode, completed.stdout, completed.stderr+++def write_json(path: Path, value: object) -> None:+ path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")+++def parse_json_output(code: int, stdout: str, stderr: str) -> object:+ try:+ return json.loads(stdout)+ except json.JSONDecodeError:+ return {"success": code == 0, "stdout": stdout.strip(), "stderr": stderr.strip()}+++def cad_summary(step: Path, cq) -> dict[str, object]:+ imported = cq.importers.importStep(str(step))+ solids = imported.solids().vals()+ faces = imported.faces().vals()+ edges = imported.edges().vals()+ vertices = imported.vertices().vals()+ box = imported.val().BoundingBox()+ surfaces = Counter(face.geomType().lower().replace("_", "-") for face in faces)+ return {+ "bounds": {+ "min": [box.xmin, box.ymin, box.zmin],+ "max": [box.xmax, box.ymax, box.zmax],+ "size": [box.xlen, box.ylen, box.zlen],+ },+ "volume": sum(solid.Volume() for solid in solids),+ "bodyCount": len(solids),+ "faceCount": len(faces),+ "edgeCount": len(edges),+ "vertexCount": len(vertices),+ "surfaceFamilies": dict(sorted(surfaces.items())),+ }+++def load_records(path: Path) -> dict[str, dict[str, object]]:+ return {+ row["record_id"]: row+ for line in path.read_text(encoding="utf-8").splitlines()+ if line.strip()+ for row in [json.loads(line)]+ }+++def classification(task: str, record_id: str, second_iou: float) -> tuple[str | None, str]:+ if second_iou >= 0.99:+ return None, "Success"+ if task == "Vision2Code" and record_id.startswith("washer_"):+ return "Reasoning", "Use the existing construction-plane Profile extrusion rather than a world-XY profile."+ if task == "CodeEdit" and record_id.startswith("battery_holder_"):+ return "Reasoning", "Inspect the constant major-arc section and preserve the finite end walls with a section stack."+ if task == "CodeEdit" and record_id == "topup_ball_knob_axial_hole":+ return "MissingSemanticPrimitive", "The stem uses an annular Profile; the remaining delta is the same axial Hole on the Sphere component."+ if task == "CodeEdit" and "ball_knob" in record_id:+ return "Reasoning", "Use two analytic component definitions, a DatumFrame Interface, and Assembly AP242 export."+ return "Reasoning", "The bounded reconstruction did not reach near-parity."+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--aetheris-root", type=Path, required=True)+ parser.add_argument("--benchcad-root", type=Path, required=True)+ parser.add_argument("--artifact-root", type=Path)+ parser.add_argument("--aetheris-cli", type=Path, help="Freshly published aetheris executable; defaults to dotnet run.")+ parser.add_argument("--baseline-summary", type=Path, help="Prior milestone results-summary.json; compares against its second pass.")+ parser.add_argument("--corpus", default="test_data", choices=["test_data", "data"])+ args = parser.parse_args()++ aetheris = args.aetheris_root.resolve()+ benchcad = args.benchcad_root.resolve()+ artifacts = (args.artifact_root or aetheris / "artifacts/local/benchcad-aetheris").resolve()+ first_pass = json.loads((artifacts / "first-pass-results.json").read_text(encoding="utf-8"))+ prior = {}+ if args.baseline_summary:+ prior = {(row["task"], row["recordId"]): float(row["secondPassIou"])+ for row in json.loads(args.baseline_summary.read_text(encoding="utf-8"))["records"]}++ sys.path.insert(0, str(benchcad))+ from benchcad_core.scoring.iou import _ocp_hashcode_fix, iou_step_vs_step, norm_iou+ from benchcad_core.scoring.views import composite_for_step++ _ocp_hashcode_fix()+ import cadquery as cq++ records_by_task = {+ "Vision2Code": load_records(benchcad / "Vision2Code" / args.corpus / "records.jsonl"),+ "CodeEdit": load_records(benchcad / "CodeEdit" / args.corpus / "records.jsonl"),+ }+ result_rows: list[dict[str, object]] = []++ for task, records in records_by_task.items():+ task_dir = artifacts / task+ if not task_dir.exists():+ continue+ for record_dir in sorted(path for path in task_dir.iterdir() if path.is_dir()):+ record_id = record_dir.name+ record = records.get(record_id)+ if record is None:+ raise SystemExit(f"No {task} {args.corpus} record named {record_id}")+ target_rel = record["step_path"] if task == "Vision2Code" else record["gt_step_path"]+ target = (benchcad / task / args.corpus / str(target_rel)).resolve()+ assembly_source = record_dir / "reconstruction.assembly.firmament"+ source = assembly_source if assembly_source.exists() else record_dir / "reconstruction.firmament"+ candidate = record_dir / "reconstructed.step"++ cli = [str(args.aetheris_cli.resolve())] if args.aetheris_cli else ["dotnet", "run", "--project", "Aetheris.CLI", "-c", "Release", "--no-build", "--"]+ build_args = (["asm", "export-ap242", str(source), "--out", str(candidate), "--json"]+ if source == assembly_source else ["build", str(source), "--output", str(candidate), "--json"])+ build_code, build_out, build_err = run(cli + build_args, aetheris)+ write_json(record_dir / "build.json", parse_json_output(build_code, build_out, build_err))++ for name, step in (("target", target), ("reconstructed", candidate)):+ inspect_args = ["analyze", "compound", str(step), "--json"] if source == assembly_source else ["analyze", str(step), "--json"]+ code, stdout, stderr = run(cli + inspect_args, aetheris)+ write_json(record_dir / f"inspect-{name}.json", parse_json_output(code, stdout, stderr))++ target_summary = {+ "recordId": record_id,+ "task": task,+ "targetStepPath": str(target),+ "metadata": record,+ "classification": "Eligible",+ "scorerAvailability": "BenchCAD voxel IoU available",+ **cad_summary(target, cq),+ }+ write_json(record_dir / "target-summary.json", target_summary)+ composite_for_step(target, record_dir / "target-preview.png")+ if build_code == 0:+ composite_for_step(candidate, record_dir / "reconstructed-preview.png")++ model_iou = iou_step_vs_step(candidate, target) if build_code == 0 else 0.0+ first = prior.get((task, record_id), float(first_pass[task][record_id]["iou"]))+ baseline = float(record.get("iou", 0.0)) if task == "CodeEdit" else None+ score = {+ "recordId": record_id,+ "task": task,+ "metric": "voxel_iou_64_normalized",+ "firstPass": {"rawTargetIou": first},+ "secondPass": {"rawTargetIou": model_iou},+ "delta": model_iou - first,+ }+ if baseline is not None:+ score["baselineIou"] = baseline+ score["firstPass"]["normalizedIou"] = norm_iou(first, baseline)+ score["secondPass"]["normalizedIou"] = norm_iou(model_iou, baseline)+ write_json(record_dir / "score.json", score)++ cause, status = classification(task, record_id, model_iou)+ note = classification(task, record_id, model_iou)[1]+ notes = (+ f"# {record_id}\n\n"+ f"- Mode: source-assisted open-book reconstruction after STEP inspection.\n"+ f"- First-pass status: {'Success' if first >= 0.99 else 'BoundedAttempt'}.\n"+ f"- Second-pass status: {status}.\n"+ f"- Primary failure cause: {cause or 'None'}.\n"+ f"- Observation: {note}\n"+ f"- Independence: the Firmament source contains no STEP import or target path.\n"+ )+ (record_dir / "notes.md").write_text(notes, encoding="utf-8")++ result_rows.append({+ "task": task,+ "recordId": record_id,+ "firstPassIou": first,+ "secondPassIou": model_iou,+ "delta": model_iou - first,+ "baselineIou": baseline,+ "firstPassNormalizedIou": norm_iou(first, baseline) if baseline is not None else None,+ "secondPassNormalizedIou": norm_iou(model_iou, baseline) if baseline is not None else None,+ "buildSuccess": build_code == 0,+ "failureCause": cause,+ })++ write_json(artifacts / "results-summary.json", {"records": result_rows})+ print(json.dumps({"artifactRoot": str(artifacts), "recordCount": len(result_rows)}, indent=2))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/benchcad-aetheris-x1.py b/scripts/benchcad-aetheris-x1.pynew file mode 100644index 00000000..e8ccfe0e--- /dev/null+++ b/scripts/benchcad-aetheris-x1.py@@ -0,0 +1,6 @@+"""X1 entry point; reuses the X0 scorer integration with X1 assembly support."""++from pathlib import Path+import runpy++runpy.run_path(str(Path(__file__).with_name("benchcad-aetheris-x0.py")), run_name="__main__")