Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Reconstruct CTC-01 in Firmament; add shape comparison oracle

Claude8c610ee0a23c
diff --git a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs
index 5a4e90df..de015107 100644
--- a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs
+++ b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs
@@ -126,7 +126,6 @@ public sealed class FirmamentFixtureCorpusTests
Assert.Contains(fixtures, p => p.EndsWith("Speculative/PMI/future/pmi-datum-flatness-position-v2.valid.firmfixture", StringComparison.Ordinal));
Assert.Contains(fixtures, p => p.EndsWith("Speculative/PMI/future/pmi-material-surface-finish-v2.valid.firmfixture", StringComparison.Ordinal));
Assert.Contains(fixtures, p => p.EndsWith("Invalid/PMI/pmi-raw-brep-id-target-v2.invalid.firmfixture", StringComparison.Ordinal));
- Assert.Contains(fixtures, p => p.EndsWith("Regression/Decompile/ctc-01-candidate-v2.firmfixture", StringComparison.Ordinal));
foreach (var path in fixtures)
{
diff --git a/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs b/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs
new file mode 100644
index 00000000..d3606082
--- /dev/null
+++ b/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs
@@ -0,0 +1,127 @@
+using System.Text.Json;
+using Aetheris.CLI;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class ShapeComparisonCliTests
+{
+ private static readonly string RepoRoot = FindRepoRoot();
+ private static readonly Lazy<string> PlateBossHole = new(() => Build("fixtures/Regression/ShapeCompare/plate-boss-hole.firmament"));
+ private static readonly Lazy<string> PlateBoss = new(() => Build("fixtures/Regression/ShapeCompare/plate-boss.firmament"));
+ private static readonly Lazy<string> Ctc01 = new(() => Build("fixtures/Regression/Decompile/ctc-01.firmament"));
+ private static string Ctc01Original => Path.Combine(RepoRoot, "testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp");
+
+ [Fact]
+ public void MissingHoleIsNamedLocatedAndMeasured()
+ {
+ var result = StepShapeComparison.Compare(PlateBossHole.Value, PlateBoss.Value, resolution: 300);
+
+ var missing = Assert.Single(result.Carriers.MissingFromCandidate);
+ Assert.Equal("Cylinder", missing.Kind);
+ Assert.Contains("r=4", missing.Description, StringComparison.Ordinal);
+ Assert.Contains("(15, 5, 0)", missing.Description, StringComparison.Ordinal);
+ Assert.Empty(result.Carriers.ExtraInCandidate);
+
+ var hole = Math.PI * 4 * 4 * 6;
+ Assert.InRange(result.Overlap.CandidateOnlyVolume, hole * 0.97, hole * 1.03);
+ Assert.Equal(0d, result.Overlap.ReferenceOnlyVolume, 3);
+ var region = Assert.Single(result.Overlap.Regions);
+ Assert.Equal("candidate-only", region.Side);
+ Assert.InRange(region.BoundsMin[0], 10.5, 11.5);
+ Assert.InRange(region.BoundsMax[1], 8.5, 9.5);
+ Assert.Equal(0d, region.BoundsMin[2], 6);
+ Assert.Equal(6d, region.BoundsMax[2], 6);
+ }
+
+ [Fact]
+ public void SelfComparisonMatchesEveryCarrierAndAllMaterial()
+ {
+ var result = StepShapeComparison.Compare(Ctc01Original, Ctc01Original, resolution: 200);
+
+ Assert.Empty(result.Carriers.MissingFromCandidate);
+ Assert.Empty(result.Carriers.ExtraInCandidate);
+ Assert.Equal(result.Carriers.ReferenceCarrierCount, result.Carriers.MatchedCarrierCount);
+ Assert.Equal(1d, result.Overlap.IntersectionOverUnion, 9);
+ Assert.Empty(result.Overlap.Regions);
+ }
+
+ [Fact]
+ public void Ctc01ReconstructionMatchesTheOriginalExceptForKnownLanguageGaps()
+ {
+ var result = StepShapeComparison.Compare(Ctc01Original, Ctc01.Value);
+
+ // Everything the reconstruction builds is on the original's surfaces.
+ Assert.Empty(result.Carriers.ExtraInCandidate);
+ Assert.True(result.Overlap.IntersectionOverUnion >= 0.996, $"IoU {result.Overlap.IntersectionOverUnion}");
+
+ // What is missing is exactly the features Firmament cannot yet express (see the fixture's header).
+ // Closing one of these gaps shrinks this list; a new kind of discrepancy fails here.
+ foreach (var carrier in result.Carriers.MissingFromCandidate)
+ {
+ Assert.True(
+ IsSideDrill(carrier) || IsHexFootFillet(carrier) || IsLugUndersideFillet(carrier),
+ $"Unexpected missing carrier: {carrier.Description}");
+ }
+ }
+
+ [Fact]
+ public void BoxMinusHoleVolumeIsNotClaimedForStockThatIsNotTheBoundingBox()
+ {
+ foreach (var step in new[] { PlateBossHole.Value, Ctc01.Value })
+ {
+ try
+ {
+ var volume = StepAnalyzer.AnalyzeVolume(step);
+ Assert.NotEqual("analytic-box-minus-z-hole", volume.Method);
+ }
+ catch (InvalidOperationException)
+ {
+ // No exact route for this body is an honest answer; a box formula on a non-box is not.
+ }
+ }
+ }
+
+ [Fact]
+ public void CompareShapeOptionReportsCarriersAndOverlapInJson()
+ {
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+ var exit = CliRunner.Run(["analyze", "compare", PlateBossHole.Value, PlateBoss.Value, "--shape", "--shape-resolution", "150", "--json"], stdout, stderr);
+
+ Assert.True(exit == 0, stderr.ToString());
+ using var document = JsonDocument.Parse(stdout.ToString());
+ var shape = document.RootElement.GetProperty("shapeComparison");
+ Assert.Equal(1, shape.GetProperty("carriers").GetProperty("missingFromCandidate").GetArrayLength());
+ Assert.True(shape.GetProperty("overlap").GetProperty("candidateOnlyVolume").GetDouble() > 0);
+ }
+
+ private static bool IsSideDrill(StepShapeComparison.CarrierGroup c)
+ => c.BoundsMin is { } lo && c.BoundsMax is { } hi && lo[1] >= -125.01 && hi[1] <= -73.9 && lo[2] >= -35.01 && hi[2] <= -14.99
+ && (c.Kind == "Cone" || (c.Kind == "Cylinder" && c.Description.Contains("r=10 ", StringComparison.Ordinal)));
+
+ private static bool IsHexFootFillet(StepShapeComparison.CarrierGroup c)
+ => c.Kind == "Cylinder" && c.Description.Contains("r=5 ", StringComparison.Ordinal) && c.BoundsMax is { } hi && hi[2] <= 5.01;
+
+ private static bool IsLugUndersideFillet(StepShapeComparison.CarrierGroup c)
+ => c.Kind == "Cylinder" && c.Description.Contains("r=10 ", StringComparison.Ordinal)
+ && c.BoundsMin is { } lo && c.BoundsMax is { } hi && lo[2] >= -60.01 && hi[2] <= -49.99;
+
+ private static string Build(string fixture)
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-shape-compare", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ var step = Path.Combine(directory, Path.GetFileNameWithoutExtension(fixture) + ".step");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+ var exit = CliRunner.Run(["build", Path.Combine(RepoRoot, fixture), "--out", step], stdout, stderr);
+ Assert.True(exit == 0, $"{fixture}: {stderr}");
+ return step;
+ }
+
+ private static string FindRepoRoot()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index e022e288..dea4825c 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -145,7 +145,7 @@ public static class CliRunner
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>|--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 AnalyzeCompareUsage = "Usage: aetheris analyze compare <reference.step> <candidate.step> [--approximate-volume --resolution <N>] [--shape [--shape-resolution <N>]] [--json]";
private const string AnalyzeCompoundUsage = "Usage: aetheris analyze compound <file.step> [--json]";
private const string AnalyzeAssemblyUsage = "Usage: aetheris analyze assembly <file.step> [--json]";
private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";
@@ -3426,6 +3426,8 @@ Model CanonicalPanel {
var json = false;
var approximateVolume = false;
int? resolution = null;
+ var shape = false;
+ var shapeResolution = 400;
for (var i = 2; i < args.Length; i++)
{
switch (args[i])
@@ -3433,6 +3435,16 @@ Model CanonicalPanel {
case "--json":
json = true;
break;
+ case "--shape":
+ shape = true;
+ break;
+ case "--shape-resolution" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedShape) && parsedShape > 0:
+ shape = true;
+ shapeResolution = parsedShape;
+ break;
+ case "--shape-resolution":
+ stderr.WriteLine("Analyze compare option --shape-resolution requires a positive integer value.");
+ return 1;
case "--approximate-volume":
approximateVolume = true;
break;
@@ -3463,6 +3475,20 @@ Model CanonicalPanel {
var surfaceComparison = CompareSurfaceFamilies(reference.Analysis?.Summary.SurfaceFamilies, candidate.Analysis?.Summary.SurfaceFamilies);
var volumeComparison = CompareVolumes(reference.Volume, candidate.Volume, approximateVolume, resolution);
var success = reference.Success && candidate.Success;
+ StepShapeComparison.ShapeComparisonResult? shapeComparison = null;
+ string? shapeError = null;
+ if (shape && success)
+ {
+ try
+ {
+ shapeComparison = StepShapeComparison.Compare(referencePath, candidatePath, shapeResolution);
+ }
+ catch (Exception ex) when (ex is StepAnalysisImportException or InvalidOperationException)
+ {
+ shapeError = ex.Message;
+ success = false;
+ }
+ }
if (json)
{
@@ -3475,6 +3501,8 @@ Model CanonicalPanel {
topologyComparison,
surfaceFamilyComparison = surfaceComparison,
volumeComparison,
+ shapeComparison,
+ shapeError,
notes = new[] { approximateVolume ? "Volume comparison uses explicit voxel approximation when exact fails per-side." : "Volume comparison uses exact path only." }
}, JsonOptions));
return success ? 0 : 1;
@@ -3496,6 +3524,32 @@ Model CanonicalPanel {
stdout.WriteLine($" Comparison: {JsonSerializer.Serialize(surfaceComparison, JsonOptions)}");
stdout.WriteLine("Volume:");
stdout.WriteLine($" Comparison: {JsonSerializer.Serialize(volumeComparison, JsonOptions)}");
+ if (shapeError is not null) stdout.WriteLine($"Shape comparison failed: {shapeError}");
+ if (shapeComparison is { } sc)
+ {
+ var o = sc.Overlap;
+ stdout.WriteLine("Shape overlap (approximate, tessellated rays):");
+ stdout.WriteLine(FormattableString.Invariant($" Reference {o.ReferenceVolume:0.###} Candidate {o.CandidateVolume:0.###} IoU {o.IntersectionOverUnion:0.######}"));
+ stdout.WriteLine(FormattableString.Invariant($" Reference only {o.ReferenceOnlyVolume:0.###} Candidate only {o.CandidateOnlyVolume:0.###} (grid {o.ColumnsX}x{o.ColumnsY}, cell {o.CellSize:0.####})"));
+ foreach (var r in o.Regions)
+ {
+ stdout.WriteLine(FormattableString.Invariant($" {r.Side,-15} {r.Volume,12:0.###} x {r.BoundsMin[0]:0.##}..{r.BoundsMax[0]:0.##} y {r.BoundsMin[1]:0.##}..{r.BoundsMax[1]:0.##} z {r.BoundsMin[2]:0.##}..{r.BoundsMax[2]:0.##}"));
+ }
+
+ var c = sc.Carriers;
+ stdout.WriteLine($"Carriers: reference {c.ReferenceCarrierCount}, candidate {c.CandidateCarrierCount}, matched {c.MatchedCarrierCount}");
+ foreach (var (label, groups) in new[] { ("missing", c.MissingFromCandidate), ("extra", c.ExtraInCandidate) })
+ {
+ foreach (var g in groups)
+ {
+ var where = g.BoundsMin is { } lo && g.BoundsMax is { } hi
+ ? FormattableString.Invariant($" [{lo[0]:0.##},{lo[1]:0.##},{lo[2]:0.##}]..[{hi[0]:0.##},{hi[1]:0.##},{hi[2]:0.##}]")
+ : string.Empty;
+ stdout.WriteLine($" {label,-7} {g.Description} faces {string.Join(',', g.FaceIds)}{where}");
+ }
+ }
+ }
+
return success ? 0 : 1;
}
diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.cs
index 5232d1b0..ec69eeaa 100644
--- a/Aetheris.CLI/StepAnalyzer.cs
+++ b/Aetheris.CLI/StepAnalyzer.cs
@@ -301,6 +301,11 @@ public sealed record VolumeAnalysisResult(
return false;
}
+ if (!PlanarFacesBoundTheBox(body, bbox, holeAxis: 0))
+ {
+ return false;
+ }
+
var baseVolume = (bbox.Max.X - bbox.Min.X) * (bbox.Max.Y - bbox.Min.Y) * (bbox.Max.Z - bbox.Min.Z);
// One analytic cylinder may be represented by multiple trimmed faces
// (the local-frame hole planner deliberately uses two arcs to avoid a
@@ -356,6 +361,11 @@ public sealed record VolumeAnalysisResult(
return false;
}
+ if (!PlanarFacesBoundTheBox(body, bbox, holeAxis: 2))
+ {
+ return false;
+ }
+
var baseVolume = (bbox.Max.X - bbox.Min.X) * (bbox.Max.Y - bbox.Min.Y) * (bbox.Max.Z - bbox.Min.Z);
var breakpoints = cylinders.SelectMany(c => new[] { c.ZMin, c.ZMax }).Distinct().OrderBy(z => z).ToArray();
var removed = 0d;
@@ -389,6 +399,32 @@ public sealed record VolumeAnalysisResult(
return double.IsFinite(volume) && volume > 0d;
}
+ /// <summary>
+ /// The box-minus-hole formulas take the bounding box as the stock, so they only hold when every planar face is
+ /// axis-aligned and lies on a bounding-box side. Planes normal to the hole axis may also sit inside the box
+ /// (counterbore shoulders and blind-hole floors); any other plane means the stock is not the box.
+ /// </summary>
+ private static bool PlanarFacesBoundTheBox(BrepBody body, BoundingBox3D bbox, int holeAxis)
+ {
+ var tolerance = double.Max(1e-7, (bbox.Max - bbox.Min).Length * 1e-9);
+ foreach (var face in body.Topology.Faces)
+ {
+ if (!body.TryGetFaceSurface(face.Id, out var surface) || surface?.Plane is not { } plane) continue;
+ var n = plane.Normal.ToVector();
+ var o = plane.Origin;
+ double[] normal = [n.X, n.Y, n.Z];
+ double[] origin = [o.X, o.Y, o.Z];
+ double[] lo = [bbox.Min.X, bbox.Min.Y, bbox.Min.Z];
+ double[] hi = [bbox.Max.X, bbox.Max.Y, bbox.Max.Z];
+ var axis = Array.FindIndex(normal, c => double.Abs(double.Abs(c) - 1d) <= 1e-9);
+ if (axis < 0) return false;
+ if (axis == holeAxis) continue;
+ if (double.Abs(origin[axis] - lo[axis]) > tolerance && double.Abs(origin[axis] - hi[axis]) > tolerance) return false;
+ }
+
+ return true;
+ }
+
private static bool TryResolveFaceZSpan(BrepBody body, FaceId faceId, out double zMin, out double zMax)
{
zMin = double.PositiveInfinity;
@@ -855,7 +891,7 @@ public sealed record VolumeAnalysisResult(
return av.Dot(bv.Cross(cv)) / 6d;
}
- private static (string FullPath, BrepBody Body) ImportStepBody(string stepPath)
+ internal static (string FullPath, BrepBody Body) ImportStepBody(string stepPath)
{
var fullPath = Path.GetFullPath(stepPath);
var import = Step242Importer.ImportBody(File.ReadAllText(fullPath));
diff --git a/Aetheris.CLI/StepShapeComparison.cs b/Aetheris.CLI/StepShapeComparison.cs
new file mode 100644
index 00000000..7eba1fb0
--- /dev/null
+++ b/Aetheris.CLI/StepShapeComparison.cs
@@ -0,0 +1,393 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using System.Globalization;
+
+namespace Aetheris.CLI;
+
+/// <summary>
+/// Geometric comparison of a candidate body against a reference body, for reconstruction work: which analytic
+/// carriers (planes, cylinders, cones, spheres, tori) each side has that the other lacks, and where material
+/// differs. Carriers are compared by canonical parameters, not face ids, so a reconstruction that splits or
+/// merges faces differently still matches; material is compared along parallel Z rays through both
+/// tessellations, so the overlap figures are approximate to the display chord tolerance.
+/// </summary>
+public static class StepShapeComparison
+{
+ public sealed record CarrierGroup(string Kind, string Description, IReadOnlyList<int> FaceIds, double[]? BoundsMin, double[]? BoundsMax);
+
+ public sealed record CarrierComparison(
+ int ReferenceCarrierCount,
+ int CandidateCarrierCount,
+ int MatchedCarrierCount,
+ IReadOnlyList<CarrierGroup> MissingFromCandidate,
+ IReadOnlyList<CarrierGroup> ExtraInCandidate);
+
+ public sealed record DiscrepancyRegion(string Side, double Volume, int ColumnCount, double[] BoundsMin, double[] BoundsMax);
+
+ public sealed record OverlapComparison(
+ int ColumnsX,
+ int ColumnsY,
+ double CellSize,
+ double ReferenceVolume,
+ double CandidateVolume,
+ double ReferenceOnlyVolume,
+ double CandidateOnlyVolume,
+ double IntersectionOverUnion,
+ int UnpairedReferenceColumns,
+ int UnpairedCandidateColumns,
+ IReadOnlyList<DiscrepancyRegion> Regions,
+ int SuppressedSingleColumnRegions,
+ string Basis);
+
+ public sealed record ShapeComparisonResult(CarrierComparison Carriers, OverlapComparison Overlap);
+
+ public static ShapeComparisonResult Compare(string referencePath, string candidatePath, int resolution = 400)
+ {
+ var (_, reference) = StepAnalyzer.ImportStepBody(referencePath);
+ var (_, candidate) = StepAnalyzer.ImportStepBody(candidatePath);
+ return Compare(reference, candidate, resolution);
+ }
+
+ public static ShapeComparisonResult Compare(BrepBody reference, BrepBody candidate, int resolution = 400)
+ {
+ var referenceMesh = Tessellate(reference);
+ var candidateMesh = Tessellate(candidate);
+ var (min, max) = UnionBounds(referenceMesh, candidateMesh);
+ var diagonal = (max - min).Length;
+ var linear = double.Max(1e-4, diagonal * 1e-6);
+ var carriers = CompareCarriers(reference, referenceMesh, candidate, candidateMesh, linear);
+ var overlap = CompareOverlap(referenceMesh, candidateMesh, min, max, resolution);
+ return new ShapeComparisonResult(carriers, overlap);
+ }
+
+ private static DisplayTessellationResult Tessellate(BrepBody body)
+ => BrepDisplayTessellator.TessellateBoundedPartial(body, DisplayTessellationOptions.Default with { ChordTolerance = 0.02d }, TimeSpan.FromSeconds(30));
+
+ private static (Point3D Min, Point3D Max) UnionBounds(params DisplayTessellationResult[] meshes)
+ {
+ double x0 = double.PositiveInfinity, y0 = x0, z0 = x0, x1 = double.NegativeInfinity, y1 = x1, z1 = x1;
+ foreach (var p in meshes.SelectMany(m => m.FacePatches).SelectMany(p => p.Positions))
+ {
+ x0 = double.Min(x0, p.X); y0 = double.Min(y0, p.Y); z0 = double.Min(z0, p.Z);
+ x1 = double.Max(x1, p.X); y1 = double.Max(y1, p.Y); z1 = double.Max(z1, p.Z);
+ }
+
+ if (!double.IsFinite(x0)) throw new InvalidOperationException("Shape comparison requires tessellated faces on both sides.");
+ return (new Point3D(x0, y0, z0), new Point3D(x1, y1, z1));
+ }
+
+ // ---- Carriers ---------------------------------------------------------------------------------------------
+
+ private sealed record Carrier(string Kind, double[] Key, bool[] Angular, string Description);
+
+ private static CarrierComparison CompareCarriers(BrepBody reference, DisplayTessellationResult referenceMesh, BrepBody candidate, DisplayTessellationResult candidateMesh, double linear)
+ {
+ var referenceGroups = GroupCarriers(reference, referenceMesh, linear);
+ var candidateGroups = GroupCarriers(candidate, candidateMesh, linear);
+ var matchedReference = new bool[referenceGroups.Count];
+ var matchedCandidate = new bool[candidateGroups.Count];
+ for (var i = 0; i < referenceGroups.Count; i++)
+ {
+ for (var j = 0; j < candidateGroups.Count; j++)
+ {
+ if (!Same(referenceGroups[i].Carrier, candidateGroups[j].Carrier, linear)) continue;
+ matchedReference[i] = true;
+ matchedCandidate[j] = true;
+ }
+ }
+
+ return new CarrierComparison(
+ referenceGroups.Count,
+ candidateGroups.Count,
+ matchedReference.Count(m => m),
+ referenceGroups.Where((_, i) => !matchedReference[i]).Select(g => g.Group).ToArray(),
+ candidateGroups.Where((_, j) => !matchedCandidate[j]).Select(g => g.Group).ToArray());
+ }
+
+ private static List<(Carrier Carrier, CarrierGroup Group)> GroupCarriers(BrepBody body, DisplayTessellationResult mesh, double linear)
+ {
+ var patches = mesh.FacePatches.GroupBy(p => p.FaceId.Value).ToDictionary(g => g.Key, g => g.SelectMany(p => p.Positions).ToArray());
+ var groups = new List<(Carrier Carrier, List<int> Faces)>();
+ foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value))
+ {
+ var carrier = body.TryGetFaceSurface(face.Id, out var surface) && surface is not null
+ ? Canonical(surface)
+ : new Carrier("Unknown", [], [], "unresolved surface");
+ var existing = groups.FindIndex(g => Same(g.Carrier, carrier, linear));
+ if (existing >= 0) groups[existing].Faces.Add(face.Id.Value);
+ else groups.Add((carrier, [face.Id.Value]));
+ }
+
+ return groups.Select(g =>
+ {
+ var points = g.Faces.Where(patches.ContainsKey).SelectMany(f => patches[f]).ToArray();
+ double[]? lo = points.Length == 0 ? null : [Round(points.Min(p => p.X)), Round(points.Min(p => p.Y)), Round(points.Min(p => p.Z))];
+ double[]? hi = points.Length == 0 ? null : [Round(points.Max(p => p.X)), Round(points.Max(p => p.Y)), Round(points.Max(p => p.Z))];
+ return (g.Carrier, new CarrierGroup(g.Carrier.Kind, g.Carrier.Description, g.Faces, lo, hi));
+ }).ToList();
+ }
+
+ private static bool Same(Carrier a, Carrier b, double linear)
+ {
+ if (a.Kind != b.Kind || a.Key.Length != b.Key.Length) return false;
+ if (a.Key.Length == 0) return false; // unknown/freeform carriers never match by parameters
+ for (var i = 0; i < a.Key.Length; i++)
+ {
+ var tolerance = a.Angular[i] ? 1e-6d : linear;
+ if (double.Abs(a.Key[i] - b.Key[i]) > tolerance) return false;
+ }
+
+ return true;
+ }
+
+ private static Carrier Canonical(SurfaceGeometry surface)
+ {
+ switch (surface.Kind)
+ {
+ case SurfaceGeometryKind.Plane when surface.Plane is { } plane:
+ {
+ var n = CanonicalDirection(plane.Normal.ToVector());
+ var d = n.Dot(plane.Origin - Point3D.Origin);
+ return new Carrier("Plane", [n.X, n.Y, n.Z, d], [true, true, true, false],
+ $"plane n=({F(n.X)}, {F(n.Y)}, {F(n.Z)}) d={F(d)}");
+ }
+ case SurfaceGeometryKind.Cylinder when surface.Cylinder is { } cylinder:
+ {
+ var a = CanonicalDirection(cylinder.Axis.ToVector());
+ var p = AxisFoot(cylinder.Origin, a);
+ return new Carrier("Cylinder", [a.X, a.Y, a.Z, p.X, p.Y, p.Z, cylinder.Radius], [true, true, true, false, false, false, false],
+ $"cylinder r={F(cylinder.Radius)} axis=({F(a.X)}, {F(a.Y)}, {F(a.Z)}) through ({F(p.X)}, {F(p.Y)}, {F(p.Z)})");
+ }
+ case SurfaceGeometryKind.Cone when surface.Cone is { } cone:
+ {
+ var a = CanonicalDirection(cone.Axis.ToVector());
+ var half = double.Abs(cone.SemiAngleRadians);
+ return new Carrier("Cone", [a.X, a.Y, a.Z, cone.Apex.X, cone.Apex.Y, cone.Apex.Z, half], [true, true, true, false, false, false, true],
+ $"cone half-angle={F(half * 180d / double.Pi)}deg apex=({F(cone.Apex.X)}, {F(cone.Apex.Y)}, {F(cone.Apex.Z)}) axis=({F(a.X)}, {F(a.Y)}, {F(a.Z)})");
+ }
+ case SurfaceGeometryKind.Sphere when surface.Sphere is { } sphere:
+ return new Carrier("Sphere", [sphere.Center.X, sphere.Center.Y, sphere.Center.Z, sphere.Radius], [false, false, false, false],
+ $"sphere r={F(sphere.Radius)} center=({F(sphere.Center.X)}, {F(sphere.Center.Y)}, {F(sphere.Center.Z)})");
+ case SurfaceGeometryKind.Torus when surface.Torus is { } torus:
+ {
+ var a = CanonicalDirection(torus.Axis.ToVector());
+ return new Carrier("Torus", [a.X, a.Y, a.Z, torus.Center.X, torus.Center.Y, torus.Center.Z, torus.MajorRadius, torus.MinorRadius],
+ [true, true, true, false, false, false, false, false],
+ $"torus R={F(torus.MajorRadius)} r={F(torus.MinorRadius)} center=({F(torus.Center.X)}, {F(torus.Center.Y)}, {F(torus.Center.Z)}) axis=({F(a.X)}, {F(a.Y)}, {F(a.Z)})");
+ }
+ default:
+ return new Carrier(surface.Kind.ToString(), [], [], $"{surface.Kind} (compared by count only)");
+ }
+ }
+
+ private static Vector3D CanonicalDirection(Vector3D v)
+ {
+ var u = v / v.Length;
+ var flip = double.Abs(u.X) > 1e-9 ? u.X < 0 : double.Abs(u.Y) > 1e-9 ? u.Y < 0 : u.Z < 0;
+ return flip ? -u : u;
+ }
+
+ private static Point3D AxisFoot(Point3D origin, Vector3D axis)
+ {
+ var o = origin - Point3D.Origin;
+ var foot = o - axis * o.Dot(axis);
+ return Point3D.Origin + foot;
+ }
+
+ // ---- Overlap ----------------------------------------------------------------------------------------------
+
+ private readonly record struct Triangle(double Ax, double Ay, double Az, double Bx, double By, double Bz, double Cx, double Cy, double Cz);
+
+ private static OverlapComparison CompareOverlap(DisplayTessellationResult referenceMesh, DisplayTessellationResult candidateMesh, Point3D min, Point3D max, int resolution)
+ {
+ resolution = int.Clamp(resolution, 16, 4096);
+ var spanX = max.X - min.X;
+ var spanY = max.Y - min.Y;
+ var cell = double.Max(spanX, spanY) / resolution;
+ var nx = int.Max(1, (int)double.Ceiling(spanX / cell));
+ var ny = int.Max(1, (int)double.Ceiling(spanY / cell));
+ var referenceColumns = CastColumns(referenceMesh, min, cell, nx, ny, out var unpairedReference);
+ var candidateColumns = CastColumns(candidateMesh, min, cell, nx, ny, out var unpairedCandidate);
+ var area = cell * cell;
+
+ double referenceVolume = 0, candidateVolume = 0, referenceOnly = 0, candidateOnly = 0, union = 0;
+ var referenceOnlyColumns = new (double Length, double ZMin, double ZMax)[nx * ny];
+ var candidateOnlyColumns = new (double Length, double ZMin, double ZMax)[nx * ny];
+ for (var k = 0; k < nx * ny; k++)
+ {
+ var r = referenceColumns[k];
+ var c = candidateColumns[k];
+ referenceVolume += Length(r) * area;
+ candidateVolume += Length(c) * area;
+ union += Length(Combine(r, c, (a, b) => a || b)) * area;
+ var rOnly = Combine(r, c, (a, b) => a && !b);
+ var cOnly = Combine(r, c, (a, b) => b && !a);
+ referenceOnly += Length(rOnly) * area;
+ candidateOnly += Length(cOnly) * area;
+ referenceOnlyColumns[k] = Summarize(rOnly);
+ candidateOnlyColumns[k] = Summarize(cOnly);
+ }
+
+ // Thin slivers along curved walls come from the two tessellations' chords disagreeing, not from the shapes.
+ var noise = 4d * 0.02d;
+ var regions = new List<DiscrepancyRegion>();
+ var suppressed = 0;
+ foreach (var (side, columns) in new[] { ("reference-only", referenceOnlyColumns), ("candidate-only", candidateOnlyColumns) })
+ {
+ foreach (var region in Cluster(columns, nx, ny, noise))
+ {
+ if (region.Count <= 1) { suppressed++; continue; }
+ var volume = region.Sum(k => columns[k].Length) * area;
+ var xs = region.Select(k => min.X + (k % nx) * cell).ToArray();
+ var ys = region.Select(k => min.Y + (k / nx) * cell).ToArray();
+ regions.Add(new DiscrepancyRegion(side, Round(volume), region.Count,
+ [Round(xs.Min()), Round(ys.Min()), Round(region.Min(k => columns[k].ZMin))],
+ [Round(xs.Max() + cell), Round(ys.Max() + cell), Round(region.Max(k => columns[k].ZMax))]));
+ }
+ }
+
+ return new OverlapComparison(nx, ny, Round(cell), Round(referenceVolume), Round(candidateVolume), Round(referenceOnly), Round(candidateOnly),
+ union > 0 ? double.Round((union - referenceOnly - candidateOnly) / union, 6) : 1d,
+ unpairedReference, unpairedCandidate,
+ regions.OrderByDescending(r => r.Volume).Take(40).ToArray(), suppressed,
+ "Parallel +Z rays at cell centres through each side's display tessellation (chord 0.02); inside intervals by crossing parity.");
+ }
+
+ private static List<double>[] CastColumns(DisplayTessellationResult mesh, Point3D min, double cell, int nx, int ny, out int unpaired)
+ {
+ var bins = new List<Triangle>[nx * ny];
+ foreach (var patch in mesh.FacePatches)
+ {
+ for (var i = 0; i + 2 < patch.TriangleIndices.Count; i += 3)
+ {
+ var a = patch.Positions[patch.TriangleIndices[i]];
+ var b = patch.Positions[patch.TriangleIndices[i + 1]];
+ var c = patch.Positions[patch.TriangleIndices[i + 2]];
+ var t = new Triangle(a.X, a.Y, a.Z, b.X, b.Y, b.Z, c.X, c.Y, c.Z);
+ var i0 = int.Clamp((int)double.Floor((double.Min(a.X, double.Min(b.X, c.X)) - min.X) / cell), 0, nx - 1);
+ var i1 = int.Clamp((int)double.Floor((double.Max(a.X, double.Max(b.X, c.X)) - min.X) / cell), 0, nx - 1);
+ var j0 = int.Clamp((int)double.Floor((double.Min(a.Y, double.Min(b.Y, c.Y)) - min.Y) / cell), 0, ny - 1);
+ var j1 = int.Clamp((int)double.Floor((double.Max(a.Y, double.Max(b.Y, c.Y)) - min.Y) / cell), 0, ny - 1);
+ for (var j = j0; j <= j1; j++)
+ for (var k = i0; k <= i1; k++)
+ (bins[j * nx + k] ??= []).Add(t);
+ }
+ }
+
+ // An irrational offset keeps ray centres off mesh vertices and edges, which sit on round numbers.
+ const double jitterX = 0.5d + 0.0012345678d;
+ const double jitterY = 0.5d - 0.0008765432d;
+ var columns = new List<double>[nx * ny];
+ var odd = 0;
+ Parallel.For(0, nx * ny, k =>
+ {
+ var x = min.X + ((k % nx) + jitterX) * cell;
+ var y = min.Y + ((k / nx) + jitterY) * cell;
+ var hits = new List<double>();
+ foreach (var t in bins[k] ?? [])
+ {
+ if (TryHitZ(t, x, y, out var z)) hits.Add(z);
+ }
+
+ hits.Sort();
+ if (hits.Count % 2 != 0)
+ {
+ Interlocked.Increment(ref odd);
+ hits.Clear();
+ }
+
+ columns[k] = hits;
+ });
+ unpaired = odd;
+ return columns;
+ }
+
+ private static bool TryHitZ(Triangle t, double x, double y, out double z)
+ {
+ z = 0;
+ var d = (t.By - t.Cy) * (t.Ax - t.Cx) + (t.Cx - t.Bx) * (t.Ay - t.Cy);
+ if (double.Abs(d) < 1e-14) return false;
+ var l1 = ((t.By - t.Cy) * (x - t.Cx) + (t.Cx - t.Bx) * (y - t.Cy)) / d;
+ var l2 = ((t.Cy - t.Ay) * (x - t.Cx) + (t.Ax - t.Cx) * (y - t.Cy)) / d;
+ var l3 = 1 - l1 - l2;
+ if (l1 < 0 || l2 < 0 || l3 < 0) return false;
+ z = l1 * t.Az + l2 * t.Bz + l3 * t.Cz;
+ return true;
+ }
+
+ private static double Length(List<double> intervals)
+ {
+ var sum = 0d;
+ for (var i = 0; i + 1 < intervals.Count; i += 2) sum += intervals[i + 1] - intervals[i];
+ return sum;
+ }
+
+ private static List<double> Combine(List<double> a, List<double> b, Func<bool, bool, bool> op)
+ {
+ var events = a.Select(z => (z, 0)).Concat(b.Select(z => (z, 1))).OrderBy(e => e.z).ToArray();
+ var inside = new bool[2];
+ var result = new List<double>();
+ var was = false;
+ foreach (var (z, side) in events)
+ {
+ inside[side] = !inside[side];
+ var now = op(inside[0], inside[1]);
+ if (now != was) result.Add(z);
+ was = now;
+ }
+
+ if (result.Count % 2 != 0) result.RemoveAt(result.Count - 1);
+ // Coincident faces on both sides (a shared bottom plane) leave zero-length slivers; they are not material.
+ var kept = new List<double>(result.Count);
+ for (var i = 0; i + 1 < result.Count; i += 2)
+ {
+ if (result[i + 1] - result[i] <= 1e-6) continue;
+ kept.Add(result[i]);
+ kept.Add(result[i + 1]);
+ }
+
+ return kept;
+ }
+
+ private static (double Length, double ZMin, double ZMax) Summarize(List<double> intervals)
+ => intervals.Count == 0 ? (0, 0, 0) : (Length(intervals), intervals[0], intervals[^1]);
+
+ private static List<List<int>> Cluster((double Length, double ZMin, double ZMax)[] columns, int nx, int ny, double noise)
+ {
+ var seen = new bool[columns.Length];
+ var regions = new List<List<int>>();
+ for (var start = 0; start < columns.Length; start++)
+ {
+ if (seen[start] || columns[start].Length <= noise) continue;
+ var region = new List<int>();
+ var stack = new Stack<int>();
+ stack.Push(start);
+ seen[start] = true;
+ while (stack.Count > 0)
+ {
+ var k = stack.Pop();
+ region.Add(k);
+ var (i, j) = (k % nx, k / nx);
+ foreach (var (di, dj) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) })
+ {
+ var (ii, jj) = (i + di, j + dj);
+ if (ii < 0 || jj < 0 || ii >= nx || jj >= ny) continue;
+ var n = jj * nx + ii;
+ if (seen[n] || columns[n].Length <= noise) continue;
+ seen[n] = true;
+ stack.Push(n);
+ }
+ }
+
+ regions.Add(region);
+ }
+
+ return regions;
+ }
+
+ private static double Round(double value) => double.Round(value, 4);
+
+ private static string F(double value) => double.Round(value, 4).ToString("0.####", CultureInfo.InvariantCulture);
+}
diff --git a/docs/development/reports/2026-11/CTC-01-DECOMPILE.md b/docs/development/reports/2026-11/CTC-01-DECOMPILE.md
new file mode 100644
index 00000000..493ff0d9
--- /dev/null
+++ b/docs/development/reports/2026-11/CTC-01-DECOMPILE.md
@@ -0,0 +1,85 @@
+# CTC-01 decompile
+
+## What changed
+
+- `fixtures/Regression/Decompile/ctc-01.firmament`: NIST CTC-01 reconstructed as design intent in
+ current Firmament (about 130 lines). It replaces the design-only `ctc-01-candidate-v2.firmfixture`,
+ which did not parse, and its `missing-capabilities.json`. Everything on that list (line/arc profiles,
+ slots, mirror, construction geometry) now exists.
+- `aetheris analyze compare --shape` (`Aetheris.CLI/StepShapeComparison.cs`) is the fidelity oracle.
+ - Carrier matching: faces are grouped by canonical analytic surface, so the comparison does not
+ depend on face ids. The report lists missing and extra carriers, with face ids and bounds.
+ - Material overlap: Z-ray column intervals through both tessellations give reference-only and
+ candidate-only volume, IoU, and the connected regions of difference.
+ - CTC-01 compares in about 6 s.
+- `analyze volume` bug: the "box minus Z/X holes" exact formulas accepted any all-plane body with
+ axis-parallel cylinders. They took the bounding box as stock and returned confident wrong numbers:
+ 47.3M mm³ for CTC-01, and 28498 for a 15634 plate with a boss. Planes must now lie on the bounding
+ box. Planes normal to the hole axis are also allowed, for shoulders and floors.
+- `ShapeComparisonCliTests` cover: a missing hole is named, located and measured; self-comparison is
+ exact; CTC-01 holds IoU ≥ 0.996 with no extra carriers and only known-gap missing carriers; the
+ volume guard; the CLI JSON.
+
+## Evidence
+
+| | Original | Reconstruction |
+| --- | --- | --- |
+| Bounds | ±400, ±225, −100..50 | identical |
+| Volume (ray columns, 2 mm) | 14 655 778 | 14 672 268 |
+| IoU | | 0.9967 |
+| Analytic carriers | 85 | 71, all on the original's surfaces (0 extra) |
+
+The 14 missing carriers are exactly three features, all inexpressible today:
+
+| Missing | Volume | Why |
+| --- | --- | --- |
+| 2 × Ø20 blind drilled holes with 118° points, from the −Y face | 2 × 16 039 | Compose holes are `+Z` `ThroughAll` only; no subtract |
+| R10 fillets where the lugs' inner walls meet the plate underside (mitred) | 4 × ~3 515 | No selection of individual concave edges |
+| R5 fillet at the hex boss's foot | ~1 840 | One finish per body (the boss top chamfer uses it); concave boss foot refused |
+
+The first comparison found one real modelling error, which carrier matching made obvious: the hexagon
+was rotated 30° (flats on ±y instead of ±x). It showed as six extra and six missing planes at the boss.
+The hex top chamfer, added with `EdgeFinish<Chamfer> { on: Top; target: HexBoss.Outer }`, then matched
+all twelve chamfer and flat planes.
+
+## Language friction, ranked by value
+
+1. **Holes on any planar face, with a drill point.** For example
+ `Hole<Shaft> { on: PlateStock.Front; center: …; end: Blind 45mm; tip: Drill 118deg }`. This is the
+ only CTC-01 gap that loses volume rather than a blend, and side or angled holes are routine on
+ machined parts. There is no workaround, because public Boolean subtraction is deliberately absent.
+2. **Junction fillets by feature relationship.** For example
+ `EdgeFinish<Fillet> { where: BackLeftLug meets PlateStock; radius: 10mm }` or `at: Hex.Foot`. This
+ would also mean allowing more than one finish per body when their edge sets are disjoint. Both fillet
+ gaps are "round the edges where feature A meets feature B", which is how designers say it. The
+ current selectors only name a profile rim on Top or Bottom.
+3. **Path vertex rounding and coordinate-terminated lines.** For example `round: 10mm` on a step, and
+ `Line { until: y = -95mm }`.
+ - Every arc in the CTC-01 outline is a fillet of a sharp polygon corner. Each V-notch needed three
+ √3-derived Statics, and each rectangular notch takes five steps.
+ - Rounding hand-derived lengths to three decimals left 2 µm gaps. These surfaced as arrangement
+ "dangling edge" rejections at an unrelated vertex, a trap with no pointer to its cause.
+4. **Trig and `Sqrt` in Static arithmetic.** `Tan(60deg)` is rejected, so `Pow(3, 0.5)` stands in.
+ The diagnostic talks about `tol` placement, which is unrelated.
+5. **`Close` on an already-closed path** fails with `concept-path-zero-length`. It should accept
+ closure within tolerance. The workaround was to restart the path mid-edge.
+6. **`Profile X = RegularPolygon2<N> { … }`** is rejected (`firmament-boundary2-profile-value-unsupported`),
+ although `profiles.md` lists it beside `Rect2` and `Slot2`. It works through a Concept Struct and
+ `TraceLoop`.
+
+Diagnostic quality: the items 5 and 6 diagnostics repeat their code as the message. The boss-foot fillet
+refusal speaks in planner terms ("single-stock prism rebuild", "section-stack planner") instead of
+naming the unsupported geometry.
+
+What worked well: Turtle Paths with named steps, `Mirrored Profile` and `Mirrored Feature` across
+traced construction planes, `Slot2` and `RoundedRect2` one-liners, `Boss on: Top`, pockets through
+`ThroughAll`, and holes through bosses and lugs. No construct had to be faked. The model reads as the
+drawing would: plate, lugs, boss, cuts, holes, chamfer.
+
+Not investigated: `analyze section` reports "no bounded geometry" on CTC-01 at z = −75, −55 and −25.
+
+## Verdict
+
+Meaningful progression. CTC-01 builds with every feature Firmament can express, and the comparison
+proves the rest are exactly three language gaps. Items 1 and 2 are the features worth designing. Items
+3–6 are small and independent.
diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.md
index e4d41937..63790a00 100644
--- a/docs/public/reference/cli.md
+++ b/docs/public/reference/cli.md
@@ -15,6 +15,7 @@ Commands use `aetheris` unless a separate executable is shown. The optional `aet
| `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 |
+| `analyze compare <reference.step> <candidate.step> [--shape [--shape-resolution N]] [--json]` | Compare two parts: bounds, counts and surface families; with `--shape`, also which analytic surfaces each side lacks and where material differs |
| `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 |
@@ -48,6 +49,8 @@ Run `aetheris <command> --help` for exact options. JSON is a public automation s
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.
+`analyze compare --shape` is for checking a reconstruction against an original. Faces are grouped by their analytic surface (plane normal and offset, cylinder axis and radius, cone apex and half-angle, sphere, torus), so a candidate that splits or merges faces differently still matches. The report lists each surface the candidate is missing and each one it adds, with the original's face ids and bounds. For example, a missing `cylinder r=10 axis=(0, 1, 0) through (30, 0, -25)` is a horizontal hole the candidate does not have. Material is compared by casting parallel Z rays through both tessellations on a grid (`--shape-resolution` cells along the longer side, default 400). The report gives each side's volume, the volume only the reference has and the volume only the candidate has, intersection over union, and the connected regions of difference with their bounds. These volumes are approximate to the display tessellation. Single-cell slivers along curved walls, where the two tessellations' chords disagree, are counted but not listed. Spline surfaces are compared by count only.
+
## Part mesh exports
```sh
diff --git a/docs/public/skills/firmament-modeling-strategy/SKILL.md b/docs/public/skills/firmament-modeling-strategy/SKILL.md
index 7b7d5c82..8d3d1b0b 100644
--- a/docs/public/skills/firmament-modeling-strategy/SKILL.md
+++ b/docs/public/skills/firmament-modeling-strategy/SKILL.md
@@ -234,6 +234,11 @@ Scale verification to the claim:
interfaces, and resolved placements.
- Geometry: build the actual BRep, inspect topology and contact, and verify
the relevant STEP export/reimport path.
+- Reconstruction of an existing STEP part: build, then run
+ `aetheris analyze compare <original> <built> --shape`. Extra surfaces mean
+ something is placed or sized wrong; missing surfaces name the features still
+ to model. Iterate until every remaining missing surface is a feature the
+ language cannot express, and report those.
- Presentation: inspect the actual exported scene and multiple views. Keep
rendering edits separate from product geometry.
- Performance, when requested: state cold/warm/cache conditions; separate
diff --git a/fixtures/Regression/Decompile/ctc-01-candidate-v2.firmfixture b/fixtures/Regression/Decompile/ctc-01-candidate-v2.firmfixture
deleted file mode 100644
index e1cc7429..00000000
--- a/fixtures/Regression/Decompile/ctc-01-candidate-v2.firmfixture
+++ /dev/null
@@ -1,165 +0,0 @@
-// fixture-id: ctc-01-candidate-v2
-// case: air-firmament-decompile-x1-ctc01-semantic-candidate
-// category: Decompile
-// syntax-version: FirmamentV2
-// validity: semantic-candidate
-// implementation: design-only-not-implemented
-// expected: not-implemented
-// expected-stage: semantic-candidate
-// parser-backed: false
-// source-model: CTC-01
-// source-step: testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp
-// source-topology: bodies=1 shells=1 faces=117 edges=318 vertices=206
-// source-surfaces: plane=56 cylinder=57 cone=4 sphere=0 torus=0 bspline=0 other=0
-// source-bounds-mm: min=[-400,-225,-100] max=[400,225,50]
-// decompile-confidence: main-web=medium, end-tabs=medium, through-holes=medium, slots=medium, center-boss=low, rounds=medium
-// unsupported-features: profile-sketch, profile-extrude, arbitrary-prismatic-add, arbitrary-through-cut, slot-cut, fillet-round, mirror-pattern, feature-references, construction-geometry
-// notes: Experimental semantic decompilation candidate only. This file is intentionally outside parser-backed valid/invalid corpus folders.
-
-model CTC01SemanticCandidate {
- units mm
-
- // FIRMAMENT-V2-MISSING: profile sketch with named construction geometry, dimensions,
- // line/arc outline elements, and constraints. Coordinates are approximate semantic
- // anchors from analyze bounds and visual evidence, not recovered PMI dimensions.
- profile mainWebOutline on XY {
- // Overall imported bounds: X -400..400, Y -225..225, Z -100..50.
- // Likely design plane is XY; thickness/height is along Z.
- // Semantic outline: long central web connecting four rounded/lobed corner/end
- // regions, with side steps and notches near the inner tab roots.
- construction symmetryX: axis X at y: 0
- construction symmetryY: axis Y at x: 0
-
- region leftUpperRoundedTab at [-320, 150]
- region leftLowerRoundedEnd at [-320, -150]
- region rightUpperRoundedTab at [320, 150]
- region rightLowerRoundedEnd at [320, -150]
- region centralBridge from [-170, -70] to [170, 70]
-
- // FIRMAMENT-V2-MISSING: closed polyline/arc profile syntax.
- // outline closed {
- // line/arc chain through the lobed outer perimeter, neck-down steps,
- // concave reliefs, and central bridge shoulders.
- // }
- }
-
- // FIRMAMENT-V2-MISSING: ProfileExtrude from line/arc profile to a bounded solid.
- solid basePlate: ProfileExtrude {
- profile: mainWebOutline
- depth: 150
- direction: +Z
- originZ: -100
- expose {
- face(+Z) => top
- face(-Z) => bottom
- sideLoop(mainWebOutline) => perimeter
- }
- }
-
- modify basePlate {
- // FIRMAMENT-V2-MISSING: semantic slot primitive and slot-through cut lowering.
- cut ThroughSlot {
- name: leftWebSlot
- on: top
- center: [-285, 0]
- length: 120
- radius: 25
- axis: X
- through: bottom
- confidence: medium
- }
-
- cut ThroughSlot {
- name: rightWebSlot
- on: top
- center: [285, 0]
- length: 120
- radius: 25
- axis: X
- through: bottom
- confidence: medium
- }
-
- // FIRMAMENT-V2-MISSING: arbitrary face-normal through-cuts and feature arrays.
- pattern Mirror about symmetryY {
- seed upperTabHoleLeft
- produces: [upperTabHoleRight]
- }
-
- cut PrismaticThroughCut {
- name: upperTabHoleLeft
- on: leftSideTabOuterFace
- tool: Cylinder { radius: 30 }
- axis: X
- center: [-320, 150, -25]
- through: rightSideOfLeftTab
- confidence: medium
- }
-
- cut PrismaticThroughCut {
- name: lowerEndHoleLeft
- on: leftSideLowerOuterFace
- tool: Cylinder { radius: 30 }
- axis: X
- center: [-320, -150, -25]
- through: rightSideOfLeftLowerEnd
- confidence: medium
- }
-
- pattern Mirror about symmetryY {
- seed lowerEndHoleLeft
- produces: [lowerEndHoleRight]
- }
-
- // FIRMAMENT-V2-MISSING: small repeated through-hole family with named centers.
- cut HolePattern {
- name: centralSmallThroughHoles
- tool: Cylinder { radius: 18 }
- axis: Z
- through: bottom
- centers: [[-85, -75], [-25, -55], [25, -55], [85, -75], [-110, 35], [110, 35]]
- confidence: low
- }
-
- // FIRMAMENT-V2-MISSING: additive boss/block with chamfered/rounded top contour.
- add ProfileExtrude {
- name: centralRaisedBoss
- profile: centralBossHexProfile
- on: top
- height: 95
- confidence: low
- }
-
- // FIRMAMENT-V2-MISSING: rectangular pocket/notch through-cuts from top/side faces.
- cut PrismaticThroughCut {
- name: rightRectangularPocket
- tool: RoundedRectangle { size: [95, 55] radius: 12 }
- on: top
- through: bottom
- center: [235, 30]
- confidence: medium
- }
-
- cut PrismaticThroughCut {
- name: leftUpperStepRelief
- tool: Box { size: [70, 55, 70] }
- on: perimeter
- confidence: low
- }
-
- // FIRMAMENT-V2-MISSING: edge-set selection, constant-radius round/fillet lowering,
- // conical/chamfer-like transition handling, and stable face naming across features.
- round Edges {
- name: perimeterAndSlotRounds
- radius: inferred-from-cylindrical-faces
- targets: [outerLobes, slotEnds, pocketCorners, tabTopEdges]
- confidence: medium
- }
- }
-
- profile centralBossHexProfile on XY {
- // FIRMAMENT-V2-MISSING: explicit polygon/profile syntax.
- // A raised central boss is visible, but STEP BRep alone does not prove whether it
- // was authored as a hex/house-shaped boss, drafted boss, or later-trimmed block.
- }
-}
diff --git a/fixtures/Regression/Decompile/ctc-01-missing-capabilities.json b/fixtures/Regression/Decompile/ctc-01-missing-capabilities.json
deleted file mode 100644
index 6417ed2d..00000000
--- a/fixtures/Regression/Decompile/ctc-01-missing-capabilities.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "fixtureId": "ctc-01-candidate-v2",
- "sourceStep": "testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp",
- "expectedStage": "semantic-candidate",
- "parserBacked": false,
- "missingCapabilities": {
- "language": [
- "profile/sketch syntax with line and arc chains",
- "dimensioned construction geometry and constraints",
- "profile/feature references with stable named face and loop aliases",
- "slot and rounded-rectangle feature syntax",
- "mirror and pattern source semantics",
- "compound feature groups and confidence metadata"
- ],
- "airLowering": [
- "profile extrude from line/arc sketch",
- "arbitrary prismatic add/extrude",
- "arbitrary through-cut beyond controlled box side-hole route",
- "slot cut lowering",
- "multi-feature boolean sequencing and region integration",
- "fillet/round selection and ordering policy"
- ],
- "brepKernel": [
- "robust profile extrusion with arc boundaries",
- "slot cut topology generation",
- "constant-radius fillet/round topology for imported-style edge sets",
- "feature adjacency and merge policy",
- "stable face naming across additive and subtractive operations"
- ],
- "display": [
- "no display blocker identified for this milestone; display issues are non-goals"
- ]
- }
-}
diff --git a/fixtures/Regression/Decompile/ctc-01.firmament b/fixtures/Regression/Decompile/ctc-01.firmament
new file mode 100644
index 00000000..5dda8d28
--- /dev/null
+++ b/fixtures/Regression/Decompile/ctc-01.firmament
@@ -0,0 +1,142 @@
+// NIST CTC-01 (testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp) reconstructed as design intent:
+// a dog-bone plate with four corner lugs underneath, a hexagonal boss on top, through holes and slots, and
+// notches in the long edges. Compare against the original with
+// aetheris analyze compare <original.stp> <this.step> --shape
+// Not expressible yet, and therefore absent here:
+// - two horizontal Ø20 blind drilled holes with 118° points entering the -Y face at x = ±30, z = -25
+// (Compose holes are +Z through holes only);
+// - the R5 fillet at the hex boss's foot (a second finish on the body, and a concave boss foot);
+// - R10 fillets where the lugs' inner walls meet the plate underside (no selection of individual
+// concave edges).
+Model Ctc01 {
+ units: mm
+
+ Concept Struct Datums {
+ Center: Plane { origin: [0mm, 0mm, 0mm]; normal: [1, 0, 0]; up: [0, 0, 1] }
+ Midline: Plane { origin: [0mm, 0mm, 0mm]; normal: [0, 1, 0]; up: [0, 0, 1] }
+ }
+ Construction Plane CenterPlane { Trace: Datums.Center }
+ Construction Plane MidPlane { Trace: Datums.Midline }
+
+ // V-notch: 60° included angle, R10 tip whose centre is 30 mm in from the edge. Lengths follow from the
+ // angle (no trig in Static arithmetic, so tan 60° is written as Pow(3, 0.5)).
+ Static root3: Float = Pow(3, 0.5)
+ Static vTip: Length = 10mm
+ Static vTipCentre: Length = 30mm
+ Static vHalfMouth: Length = (vTipCentre + 2 * vTip) / root3
+ Static vFlank: Length = (vTipCentre + vTip / 2) * 2 / root3
+ Static vX: Length = 110mm
+ Static chamfer: Length = 50mm * Pow(2, 0.5)
+
+ // Plate silhouette, counterclockwise from the bottom-left lug. The long edges carry two 60° V-notches
+ // (y = -125, R10 tips at x = ±110) and two rectangular notches (y = +125, 85 wide, 25 deep, R10 corners).
+ Path Outline {
+ start: Point2(-400mm, 0mm)
+ heading: -90deg
+ Line EndLeftLower { length: 175mm }
+ Arc LugOuterFrontLeft { radius: 50mm; turn: 90deg }
+ Line LugFootLeft { length: 50mm }
+ Arc LugCornerLeft { radius: 50mm; turn: 90deg }
+ Line LugInnerLeft { length: 25mm }
+ Arc WaistLeft { radius: 25mm; turn: -90deg }
+ Line FrontLeft { length: 115mm - vHalfMouth }
+ Line VLeftIn { turn: 60deg; length: vFlank }
+ Arc VLeftTip { radius: 10mm; turn: -120deg }
+ Line VLeftOut { length: vFlank }
+ Line FrontMiddle { turn: 60deg; length: 2 * (vX - vHalfMouth) }
+ Line VRightIn { turn: 60deg; length: vFlank }
+ Arc VRightTip { radius: 10mm; turn: -120deg }
+ Line VRightOut { length: vFlank }
+ Line FrontRight { turn: 60deg; length: 115mm - vHalfMouth }
+ Arc WaistFrontRight { radius: 25mm; turn: -90deg }
+ Line LugInnerFrontRight { length: 25mm }
+ Arc LugCornerFrontRight { radius: 50mm; turn: 90deg }
+ Line LugFootFrontRight { length: 50mm }
+ Arc LugOuterFrontRight { radius: 50mm; turn: 90deg }
+ Line EndRight { length: 350mm }
+ Line Chamfer { turn: 45deg; length: chamfer }
+ Line LugFootBackRight { turn: 45deg; length: 50mm }
+ Arc LugCornerBackRight { radius: 50mm; turn: 90deg }
+ Line LugInnerBackRight { length: 25mm }
+ Arc WaistBackRight { radius: 25mm; turn: -90deg }
+ Line BackRight { length: 32.5mm }
+ Line NotchRightIn { turn: 90deg; length: 15mm }
+ Arc NotchRightCornerA { radius: 10mm; turn: -90deg }
+ Line NotchRightFloor { length: 65mm }
+ Arc NotchRightCornerB { radius: 10mm; turn: -90deg }
+ Line NotchRightOut { length: 15mm }
+ Line BackMiddle { turn: 90deg; length: 215mm }
+ Line NotchLeftIn { turn: 90deg; length: 15mm }
+ Arc NotchLeftCornerA { radius: 10mm; turn: -90deg }
+ Line NotchLeftFloor { length: 65mm }
+ Arc NotchLeftCornerB { radius: 10mm; turn: -90deg }
+ Line NotchLeftOut { length: 15mm }
+ Line BackLeft { turn: 90deg; length: 32.5mm }
+ Arc WaistBackLeft { radius: 25mm; turn: -90deg }
+ Line LugInnerBackLeft { length: 25mm }
+ Arc LugCornerBackLeft { radius: 50mm; turn: 90deg }
+ Line LugFootBackLeft { length: 50mm }
+ Arc LugOuterBackLeft { radius: 50mm; turn: 90deg }
+ Close EndLeftUpper
+ }
+ Profile Plate from Outline
+
+ // A lug below the plate: the end's footprint beyond the waist, rounded on its outer edge.
+ Path LugPath {
+ start: Point2(-400mm, 125mm)
+ heading: 0deg
+ Line Inner { length: 150mm }
+ Line Side { turn: 90deg; length: 50mm }
+ Arc InnerCorner { radius: 50mm; turn: 90deg }
+ Line Foot { length: 50mm }
+ Arc OuterCorner { radius: 50mm; turn: 90deg }
+ Close Outer
+ }
+ Profile LugBackLeft from LugPath
+ Mirrored Profile LugFrontLeft from LugBackLeft { across: MidPlane }
+ Mirrored Profile LugFrontRight from LugFrontLeft { across: CenterPlane }
+ // The back-right lug's outer corner is a 50 mm chamfer, not a radius.
+ Path LugChamferedPath {
+ start: Point2(250mm, 125mm)
+ heading: 0deg
+ Line Inner { length: 150mm }
+ Line Side { turn: 90deg; length: 50mm }
+ Line Chamfer { turn: 45deg; length: chamfer }
+ Line Foot { turn: 45deg; length: 50mm }
+ Arc InnerCorner { radius: 50mm; turn: 90deg }
+ Close Outer
+ }
+ Profile LugBackRight from LugChamferedPath
+
+ Concept Struct BossLayout on XY {
+ RegularPolygon2<6> Hexagon { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ }
+ Profile HexBoss using BossLayout { Loop Outer { Hexagon |> TraceLoop } }
+ Profile Obround = Slot2 { center: [-285mm, 0mm]; length: 120mm; width: 40mm }
+ Profile Window = RoundedRect2 { center: [285mm, 0mm]; size: [100mm, 50mm]; radius: 10mm }
+
+ Struct Part {
+ Compose Body {
+ Base PlateStock { profile: Plate; from: -50mm; to: 0mm; role: Stock }
+ Add BackLeftLug { profile: LugBackLeft; from: -100mm; to: -50mm; role: Pad }
+ Add FrontLeftLug { profile: LugFrontLeft; from: -100mm; to: -50mm; role: Pad }
+ Add FrontRightLug { profile: LugFrontRight; from: -100mm; to: -50mm; role: Pad }
+ Add BackRightLug { profile: LugBackRight; from: -100mm; to: -50mm; role: Pad }
+ Boss Hex { on: Top; profile: HexBoss; height: 50mm }
+ Pocket ObroundSlot { on: Top; profile: Obround; end: ThroughAll }
+ Pocket RectWindow { on: Top; profile: Window; end: ThroughAll }
+ }
+ }
+
+ Modify Body {
+ Hole<Shaft> BoltBackLeft { on: +Z; center: Point2(-160mm, 45mm); diameter: 25mm; end: ThroughAll }
+ Mirrored Feature BoltBackRight from BoltBackLeft { across: CenterPlane }
+ Mirrored Feature BoltFrontLeft from BoltBackLeft { across: MidPlane }
+ Mirrored Feature BoltFrontRight from BoltBackRight { across: MidPlane }
+ Hole<Shaft> LugHoleBackLeft { on: +Z; center: Point2(-325mm, 175mm); diameter: 35mm; end: ThroughAll }
+ Mirrored Feature LugHoleBackRight from LugHoleBackLeft { across: CenterPlane }
+ Mirrored Feature LugHoleFrontLeft from LugHoleBackLeft { across: MidPlane }
+ Mirrored Feature LugHoleFrontRight from LugHoleBackRight { across: MidPlane }
+ EdgeFinish<Chamfer> HexTop { on: Top; target: HexBoss.Outer; distance: 5mm }
+ }
+}
diff --git a/fixtures/Regression/ShapeCompare/plate-boss-hole.firmament b/fixtures/Regression/ShapeCompare/plate-boss-hole.firmament
new file mode 100644
index 00000000..22e168f5
--- /dev/null
+++ b/fixtures/Regression/ShapeCompare/plate-boss-hole.firmament
@@ -0,0 +1,13 @@
+// A plate with a square boss and one Ø8 through hole: the reference for shape-comparison tests.
+Model PlateBossHole {
+ units: mm
+ Profile Stock = Rect2 { center: [0mm, 0mm]; size: [60mm, 40mm] }
+ Profile Pad = Rect2 { center: [-15mm, 0mm]; size: [16mm, 16mm] }
+ Compose Body {
+ Base Plate { profile: Stock; from: 0mm; to: 6mm; role: Stock }
+ Boss Block { on: Top; profile: Pad; height: 6mm }
+ }
+ Modify Body {
+ Hole<Shaft> Bore { on: +Z; center: Point2(15mm, 5mm); diameter: 8mm; end: ThroughAll }
+ }
+}
diff --git a/fixtures/Regression/ShapeCompare/plate-boss.firmament b/fixtures/Regression/ShapeCompare/plate-boss.firmament
new file mode 100644
index 00000000..dcd969cc
--- /dev/null
+++ b/fixtures/Regression/ShapeCompare/plate-boss.firmament
@@ -0,0 +1,10 @@
+// The same plate and boss as plate-boss-hole.firmament, without the hole.
+Model PlateBoss {
+ units: mm
+ Profile Stock = Rect2 { center: [0mm, 0mm]; size: [60mm, 40mm] }
+ Profile Pad = Rect2 { center: [-15mm, 0mm]; size: [16mm, 16mm] }
+ Compose Body {
+ Base Plate { profile: Stock; from: 0mm; to: 6mm; role: Stock }
+ Boss Block { on: Top; profile: Pad; height: 6mm }
+ }
+}