Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add bounded CIR-M2 placement lowering and CIR-vs-BRep differential tests
Yuechen Li3af5c8cca9bf
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCirDifferentialAnalysisTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCirDifferentialAnalysisTests.csnew file mode 100644index 00000000..420a1bb1--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCirDifferentialAnalysisTests.cs@@ -0,0 +1,86 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Cir;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Lowering;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentCirDifferentialAnalysisTests+{+ [Fact]+ public void CIRvsBRep_BoxMinusCylinder_VolumeComparison()+ {+ var fixture = "testdata/firmament/examples/boolean_box_cylinder_hole.firmament";+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText(fixture));+ var cir = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.True(cir.IsSuccess);++ var brep = compile.Compilation.Value.PrimitiveExecutionResult!.ExecutedBooleans.Single(b => b.FeatureId == "hole").Body;+ var cirVolume = CirAnalyzer.EstimateVolume(cir.Value.Root, 72);+ var brepVolume = EstimateBrepVolume(brep, 72);+ Assert.InRange(Math.Abs(cirVolume - brepVolume) / brepVolume, 0d, 0.08d);+ }++ [Fact]+ public void CIRvsBRep_SemanticPlacementFixture_Comparison()+ {+ var fixture = "testdata/firmament/examples/w2_cylinder_root_blind_bore_semantic.firmament";+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText(fixture));+ var cir = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.True(cir.IsSuccess);++ var brep = compile.Compilation.Value.PrimitiveExecutionResult!.ExecutedBooleans.Single(b => b.FeatureId == "blind_bore").Body;+ var cirBounds = cir.Value.Root.Bounds;+ var probes = new[] { new Point3D(0d, 0d, 5d), new Point3D(30d, 0d, 0d), new Point3D(0d, 0d, -20d) };+ foreach (var probe in probes)+ {+ var cirClass = CirAnalyzer.ClassifyPoint(cir.Value.Root, probe).Classification;+ var brepResult = BrepSpatialQueries.ClassifyPoint(brep, probe);+ if (brepResult.IsSuccess && brepResult.Value != PointContainment.Unknown)+ {+ Assert.Equal(cirClass == CirPointClassification.Inside, brepResult.Value == PointContainment.Inside);+ }+ }+ }++ private static double EstimateBrepVolume(BrepBody body, int resolution)+ {+ var bounds = ComputeBoundsFromVertices(body)!.Value;+ var dx = (bounds.Max.X - bounds.Min.X) / resolution;+ var dy = (bounds.Max.Y - bounds.Min.Y) / resolution;+ var dz = (bounds.Max.Z - bounds.Min.Z) / resolution;+ var cell = dx * dy * dz;+ var inside = 0;+ for (var ix = 0; ix < resolution; ix++)+ for (var iy = 0; iy < resolution; iy++)+ for (var iz = 0; iz < resolution; iz++)+ {+ var p = new Point3D(bounds.Min.X + (ix + 0.5d) * dx, bounds.Min.Y + (iy + 0.5d) * dy, bounds.Min.Z + (iz + 0.5d) * dz);+ var result = BrepSpatialQueries.ClassifyPoint(body, p);+ if (result.IsSuccess && result.Value == PointContainment.Inside)+ {+ inside++;+ }+ }++ return inside * cell;+ }++ private static BoundingBox3D? ComputeBoundsFromVertices(BrepBody body)+ {+ var points = body.Topology.Vertices+ .Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : (Point3D?)null)+ .Where(p => p.HasValue)+ .Select(p => p!.Value)+ .ToArray();+ if (points.Length == 0)+ {+ return null;+ }++ return new BoundingBox3D(+ new Point3D(points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z)),+ new Point3D(points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z)));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.csindex 7d867c0f..50ade894 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.cs@@ -29,14 +29,32 @@ public sealed class FirmamentCirLoweringTests}[Fact]- public void FirmamentCirLowerer_BoxMinusCylinder_Succeeds()+ public void FirmamentCirLowerer_OffsetPlacement_StillWorks(){- var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/boolean_box_cylinder_hole.firmament"));+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/placed_primitive.firmament"));var lower = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);Assert.True(lower.IsSuccess);var estimate = CirAnalyzer.EstimateVolume(lower.Value.Root, 48);- Assert.InRange(estimate, 13350d, 14250d);+ Assert.InRange(estimate, 200d, 400d);+ }++ [Fact]+ public void FirmamentCirLowerer_OnFacePlacement_Succeeds_ForBoundedCase()+ {+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/w2_cylinder_root_blind_bore_semantic.firmament"));+ var lower = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.True(lower.IsSuccess);+ Assert.True(lower.Value.Root.Bounds.Max.Z > 5d);+ }++ [Fact]+ public void FirmamentCirLowerer_UnsupportedPlacement_FailsClearly()+ {+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/p1_flange_radial_hole_semantic.firmament"));+ var lower = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.False(lower.IsSuccess);+ Assert.Contains(lower.Diagnostics, d => d.Message.Contains("around-axis", StringComparison.OrdinalIgnoreCase));}[Fact]diff --git a/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.cs b/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.csindex b4cb7152..b854f4a2 100644--- a/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.cs+++ b/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.cs@@ -25,7 +25,7 @@ internal static class FirmamentCirLowerercontinue;}- nodesByFeature[primitive.FeatureId] = ApplyPlacement(node, primitive.Placement, primitive.OpIndex, primitive.FeatureId, diagnostics);+ nodesByFeature[primitive.FeatureId] = ApplyPlacement(node, primitive.Placement, primitive.OpIndex, primitive.FeatureId, nodesByFeature, diagnostics);}foreach (var boolean in plan.Booleans.OrderBy(b => b.OpIndex))@@ -48,7 +48,7 @@ internal static class FirmamentCirLowerercontinue;}- rhs = ApplyPlacement(rhs, boolean.Placement, boolean.OpIndex, boolean.FeatureId, diagnostics);+ rhs = ApplyPlacement(rhs, boolean.Placement, boolean.OpIndex, boolean.FeatureId, nodesByFeature, diagnostics);var composed = boolean.Kind switch{FirmamentLoweredBooleanKind.Add => new CirUnionNode(lhs, rhs),@@ -129,25 +129,79 @@ internal static class FirmamentCirLowererreturn new CirBoxNode(parts[0], parts[1], parts[2]);}- private static CirNode ApplyPlacement(CirNode node, FirmamentLoweredPlacement? placement, int opIndex, string featureId, List<CirLoweringDiagnostic> diagnostics)+ private static CirNode ApplyPlacement(CirNode node, FirmamentLoweredPlacement? placement, int opIndex, string featureId, IReadOnlyDictionary<string, CirNode> loweredFeatures, List<CirLoweringDiagnostic> diagnostics){- if (placement is null || placement.Offset.Count == 0)+ if (placement is null){return node;}- if (placement.On is not null and not FirmamentLoweredPlacementOriginAnchor)+ if (placement.Offset.Count != 0 && placement.Offset.Count != 3){- diagnostics.Add(new(opIndex, featureId, "Only origin placement anchor is supported in CIR-M1."));+ diagnostics.Add(new(opIndex, featureId, "Placement offset must have exactly 3 components."));return node;}- if (placement.Offset.Count != 3)+ var anchor = ResolvePlacementAnchor(placement, loweredFeatures, opIndex, featureId, diagnostics);+ if (anchor is null){- diagnostics.Add(new(opIndex, featureId, "Placement offset must have exactly 3 components."));return node;}- return new CirTransformNode(node, Transform3D.CreateTranslation(new Vector3D(placement.Offset[0], placement.Offset[1], placement.Offset[2])));+ var offset = placement.Offset.Count == 3 ? new Vector3D(placement.Offset[0], placement.Offset[1], placement.Offset[2]) : Vector3D.Zero;+ var translation = (anchor.Value - Point3D.Origin) + offset;+ if (translation.LengthSquared <= 1e-24d)+ {+ return node;+ }++ return new CirTransformNode(node, Transform3D.CreateTranslation(translation));+ }+++ private static Point3D? ResolvePlacementAnchor(FirmamentLoweredPlacement placement, IReadOnlyDictionary<string, CirNode> loweredFeatures, int opIndex, string featureId, List<CirLoweringDiagnostic> diagnostics)+ {+ if (placement.On is null || placement.On is FirmamentLoweredPlacementOriginAnchor)+ {+ return Point3D.Origin;+ }++ if (placement.AroundAxis is not null || placement.RadialOffset is not null || placement.AngleDegrees is not null)+ {+ diagnostics.Add(new(opIndex, featureId, "CIR-M2 does not support around-axis placement semantics."));+ return null;+ }++ if (placement.On is not FirmamentLoweredPlacementSelectorAnchor selectorAnchor)+ {+ diagnostics.Add(new(opIndex, featureId, "Unsupported placement anchor shape for CIR-M2."));+ return null;+ }++ var selector = selectorAnchor.Selector;+ var split = selector.IndexOf('.', StringComparison.Ordinal);+ if (split <= 0 || split >= selector.Length - 1)+ {+ diagnostics.Add(new(opIndex, featureId, $"Placement selector '{selector}' is not selector-shaped."));+ return null;+ }++ var referencedFeature = selector[..split];+ var port = selector[(split + 1)..];+ if (!loweredFeatures.TryGetValue(referencedFeature, out var referencedNode))+ {+ diagnostics.Add(new(opIndex, featureId, $"Placement selector '{selector}' references unknown feature '{referencedFeature}' for CIR lowering."));+ return null;+ }++ if (!string.Equals(port, "top_face", StringComparison.Ordinal))+ {+ diagnostics.Add(new(opIndex, featureId, $"CIR-M2 placement supports only '.top_face' selectors; got '{selector}'."));+ return null;+ }++ var bounds = referencedNode.Bounds;+ return new Point3D((bounds.Min.X + bounds.Max.X) * 0.5d, (bounds.Min.Y + bounds.Max.Y) * 0.5d, bounds.Max.Z);}+}diff --git a/docs/cir-m2-differential-analysis.md b/docs/cir-m2-differential-analysis.mdnew file mode 100644index 00000000..81d528d1--- /dev/null+++ b/docs/cir-m2-differential-analysis.md@@ -0,0 +1,57 @@+# CIR-M2 differential CIR-vs-BRep analysis++CIR-M2 extends the experimental Firmament-to-CIR lowerer with a bounded selector-aware placement subset and adds differential checks against the production BRep execution/analyzer path.++## Supported placement subset (CIR-M2)++- `place.offset[3]` (existing CIR-M1 behavior, preserved).+- `place.on_face` lowered when canonicalized to a selector anchor with `.top_face` port.+- Supported selector lowering shape: `<featureId>.top_face`, where `<featureId>` is already lowered in-sequence.+- Anchor lowering: top-face anchor maps to `(centerX, centerY, maxZ)` from the referenced feature's CIR bounds, then optional `offset[3]` is added and emitted as a CIR `Transform` translation.++This is intentionally bounded to avoid semantic drift.++## Explicitly unsupported/deferred in CIR-M2++- `around_axis`, `radial_offset`, `angle_degrees` placement semantics.+- non-`.top_face` selector ports (edge/vertex/side faces/etc.).+- assembly placement, library-part placement semantics, custom op placement forms.+- generalized selector evaluation and runtime topology-dependent selector semantics.++Unsupported forms fail with explicit lowering diagnostics.++## Differential checks (CIR vs BRep)++For shared Firmament fixtures, tests compare:++1. Approximate volume+ - CIR: `CirAnalyzer.EstimateVolume`.+ - BRep: voxelized `BrepSpatialQueries.ClassifyPoint` over body vertex bounds.+2. Point classification+ - CIR: `CirAnalyzer.ClassifyPoint`.+ - BRep: `BrepSpatialQueries.ClassifyPoint` for selected probe points.+3. Bounds+ - CIR: `CirNode.Bounds`.+ - BRep: bounds reconstructed from body vertices.++## What mismatches mean++A mismatch indicates either:++- placement anchor mismatch (feature anchor point or offset semantics differ),+- primitive local-frame convention mismatch,+- estimator-resolution sensitivity.++Given CIR-M2 scope, failures should be interpreted as semantic drift signals, not proof that one kernel is globally incorrect.++## Dual-kernel drift risks++- CIR currently approximates selector-anchor semantics via CIR bounds for a narrow anchor class.+- Production placement resolves anchors from runtime BRep topology/surfaces.+- Any expansion beyond bounded `.top_face` should either share resolver math/helpers or explicitly document divergence risk.++## Recommended CIR-M3++- Introduce a small shared placement-anchor semantic helper usable by both production execution and CIR lowering for face-anchor classes.+- Add bounded support for one additional deterministic face anchor class (`bottom_face`) with parity tests.+- Expand differential fixtures to include sphere-on-box semantic placement and explicit unknown-classification handling policy.