Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add experimental Firmament-to-CIR lowerer and analyzer API
Yuechen Li5274e4928e65
diff --git a/Aetheris.Kernel.Core/Cir/CirAnalysis.cs b/Aetheris.Kernel.Core/Cir/CirAnalysis.csnew file mode 100644index 00000000..7fb0fdcf--- /dev/null+++ b/Aetheris.Kernel.Core/Cir/CirAnalysis.cs@@ -0,0 +1,29 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Core.Cir;++public enum CirPointClassification+{+ Inside,+ Outside,+ Boundary+}++public sealed record CirAnalyzerResult(CirPointClassification Classification, double SignedDistance);++public static class CirAnalyzer+{+ public static CirAnalyzerResult ClassifyPoint(CirNode node, Point3D point, double boundaryTolerance = 1e-6)+ {+ ArgumentNullException.ThrowIfNull(node);+ var value = node.Evaluate(point);+ var classification = double.Abs(value) <= boundaryTolerance+ ? CirPointClassification.Boundary+ : value < 0d+ ? CirPointClassification.Inside+ : CirPointClassification.Outside;+ return new CirAnalyzerResult(classification, value);+ }++ public static double EstimateVolume(CirNode node, int resolution) => CirVolumeEstimator.EstimateVolume(node, resolution);+}diff --git a/Aetheris.Kernel.Core/Cir/CirNode.cs b/Aetheris.Kernel.Core/Cir/CirNode.csindex 3e75afdf..4d384aee 100644--- a/Aetheris.Kernel.Core/Cir/CirNode.cs+++ b/Aetheris.Kernel.Core/Cir/CirNode.cs@@ -2,7 +2,7 @@ using Aetheris.Kernel.Core.Math;namespace Aetheris.Kernel.Core.Cir;-internal enum CirNodeKind+public enum CirNodeKind{Box,Cylinder,@@ -13,7 +13,7 @@ internal enum CirNodeKindTransform,}-internal readonly record struct CirBounds(Point3D Min, Point3D Max)+public readonly record struct CirBounds(Point3D Min, Point3D Max){public double SizeX => Max.X - Min.X;public double SizeY => Max.Y - Min.Y;@@ -25,7 +25,7 @@ internal readonly record struct CirBounds(Point3D Min, Point3D Max)new Point3D(double.Max(left.Max.X, right.Max.X), double.Max(left.Max.Y, right.Max.Y), double.Max(left.Max.Z, right.Max.Z)));}-internal abstract record CirNode(CirNodeKind Kind)+public abstract record CirNode(CirNodeKind Kind){public abstract CirBounds Bounds { get; }diff --git a/Aetheris.Kernel.Core/Cir/CirNodes.cs b/Aetheris.Kernel.Core/Cir/CirNodes.csindex 3da68cc5..878dfc6c 100644--- a/Aetheris.Kernel.Core/Cir/CirNodes.cs+++ b/Aetheris.Kernel.Core/Cir/CirNodes.cs@@ -3,7 +3,7 @@ using Aetheris.Kernel.Core.Math;namespace Aetheris.Kernel.Core.Cir;-internal sealed record CirBoxNode(double Width, double Height, double Depth) : CirNode(CirNodeKind.Box)+public sealed record CirBoxNode(double Width, double Height, double Depth) : CirNode(CirNodeKind.Box){public override CirBounds Bounds => new(new Point3D(-Width * 0.5d, -Height * 0.5d, -Depth * 0.5d), new Point3D(Width * 0.5d, Height * 0.5d, Depth * 0.5d));@@ -24,7 +24,7 @@ internal sealed record CirBoxNode(double Width, double Height, double Depth) : C}}-internal sealed record CirCylinderNode(double Radius, double Height) : CirNode(CirNodeKind.Cylinder)+public sealed record CirCylinderNode(double Radius, double Height) : CirNode(CirNodeKind.Cylinder){public override CirBounds Bounds => new(new Point3D(-Radius, -Radius, -Height * 0.5d), new Point3D(Radius, Radius, Height * 0.5d));@@ -41,32 +41,32 @@ internal sealed record CirCylinderNode(double Radius, double Height) : CirNode(C}}-internal sealed record CirSphereNode(double Radius) : CirNode(CirNodeKind.Sphere)+public sealed record CirSphereNode(double Radius) : CirNode(CirNodeKind.Sphere){public override CirBounds Bounds => new(new Point3D(-Radius, -Radius, -Radius), new Point3D(Radius, Radius, Radius));public override double Evaluate(Point3D point) => double.Sqrt((point.X * point.X) + (point.Y * point.Y) + (point.Z * point.Z)) - Radius;}-internal sealed record CirUnionNode(CirNode Left, CirNode Right) : CirNode(CirNodeKind.Union)+public sealed record CirUnionNode(CirNode Left, CirNode Right) : CirNode(CirNodeKind.Union){public override CirBounds Bounds => CirBounds.Union(Left.Bounds, Right.Bounds);public override double Evaluate(Point3D point) => double.Min(Left.Evaluate(point), Right.Evaluate(point));}-internal sealed record CirSubtractNode(CirNode Left, CirNode Right) : CirNode(CirNodeKind.Subtract)+public sealed record CirSubtractNode(CirNode Left, CirNode Right) : CirNode(CirNodeKind.Subtract){public override CirBounds Bounds => Left.Bounds;public override double Evaluate(Point3D point) => double.Max(Left.Evaluate(point), -Right.Evaluate(point));}-internal sealed record CirIntersectNode(CirNode Left, CirNode Right) : CirNode(CirNodeKind.Intersect)+public sealed record CirIntersectNode(CirNode Left, CirNode Right) : CirNode(CirNodeKind.Intersect){public override CirBounds Bounds => CirBounds.Union(Left.Bounds, Right.Bounds);public override double Evaluate(Point3D point) => double.Max(Left.Evaluate(point), Right.Evaluate(point));}-internal sealed record CirTransformNode(CirNode Child, Transform3D Transform) : CirNode(CirNodeKind.Transform)+public sealed record CirTransformNode(CirNode Child, Transform3D Transform) : CirNode(CirNodeKind.Transform){public override CirBounds Bounds{@@ -101,7 +101,7 @@ internal sealed record CirTransformNode(CirNode Child, Transform3D Transform) :private Point3D TransformPoint(Point3D p) => Transform.Apply(p);}-internal static class CirVolumeEstimator+public static class CirVolumeEstimator{public static double EstimateVolume(CirNode node, int resolution){diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.csnew file mode 100644index 00000000..7d867c0f--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCirLoweringTests.cs@@ -0,0 +1,50 @@+using Aetheris.Kernel.Core.Cir;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Lowering;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentCirLoweringTests+{+ [Fact]+ public void FirmamentCirLowerer_BoxBasic_Succeeds()+ {+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/box_basic.firmament"));+ var lower = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.True(lower.IsSuccess);++ var estimate = CirAnalyzer.EstimateVolume(lower.Value.Root, 40);+ Assert.InRange(estimate, 13950d, 14850d);+ }++ [Fact]+ public void FirmamentCirLowerer_CylinderBasic_Succeeds()+ {+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/cylinder_basic.firmament"));+ var lower = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.True(lower.IsSuccess);++ Assert.Equal(CirPointClassification.Inside, CirAnalyzer.ClassifyPoint(lower.Value.Root, new Point3D(0d, 0d, 0d)).Classification);+ Assert.Equal(CirPointClassification.Outside, CirAnalyzer.ClassifyPoint(lower.Value.Root, new Point3D(100d, 0d, 0d)).Classification);+ }++ [Fact]+ public void FirmamentCirLowerer_BoxMinusCylinder_Succeeds()+ {+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/boolean_box_cylinder_hole.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);+ }++ [Fact]+ public void FirmamentCirLowerer_UnsupportedOp_FailsClearly()+ {+ var compile = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/rounded_corner_box_basic.firmament"));+ var lower = FirmamentCirLowerer.Lower(compile.Compilation.Value.PrimitiveLoweringPlan!);+ Assert.False(lower.IsSuccess);+ Assert.Contains(lower.Diagnostics, d => d.Message.Contains("Unsupported primitive", StringComparison.Ordinal));+ }+}diff --git a/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.cs b/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.csnew file mode 100644index 00000000..b4cb7152--- /dev/null+++ b/Aetheris.Kernel.Firmament/Lowering/FirmamentCirLowerer.cs@@ -0,0 +1,153 @@+using Aetheris.Kernel.Core.Cir;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Firmament.ParsedModel;++namespace Aetheris.Kernel.Firmament.Lowering;++public sealed record CirLoweringDiagnostic(int OpIndex, string FeatureId, string Message);+public sealed record CirLoweringResult(CirNode Root, IReadOnlyList<CirLoweringDiagnostic> Diagnostics);++internal static class FirmamentCirLowerer+{+ public static KernelResult<CirLoweringResult> Lower(FirmamentPrimitiveLoweringPlan plan)+ {+ ArgumentNullException.ThrowIfNull(plan);+ var nodesByFeature = new Dictionary<string, CirNode>(StringComparer.Ordinal);+ var diagnostics = new List<CirLoweringDiagnostic>();++ foreach (var primitive in plan.Primitives.OrderBy(p => p.OpIndex))+ {+ var node = LowerPrimitive(primitive, diagnostics);+ if (node is null)+ {+ continue;+ }++ nodesByFeature[primitive.FeatureId] = ApplyPlacement(node, primitive.Placement, primitive.OpIndex, primitive.FeatureId, diagnostics);+ }++ foreach (var boolean in plan.Booleans.OrderBy(b => b.OpIndex))+ {+ if (boolean.Kind is not (FirmamentLoweredBooleanKind.Add or FirmamentLoweredBooleanKind.Subtract or FirmamentLoweredBooleanKind.Intersect))+ {+ diagnostics.Add(new(boolean.OpIndex, boolean.FeatureId, $"Unsupported boolean op for CIR-M1: {boolean.Kind}."));+ continue;+ }++ if (!nodesByFeature.TryGetValue(boolean.PrimaryReferenceFeatureId, out var lhs))+ {+ diagnostics.Add(new(boolean.OpIndex, boolean.FeatureId, $"Missing primary reference '{boolean.PrimaryReferenceFeatureId}'."));+ continue;+ }++ var rhs = LowerTool(boolean, diagnostics);+ if (rhs is null)+ {+ continue;+ }++ rhs = ApplyPlacement(rhs, boolean.Placement, boolean.OpIndex, boolean.FeatureId, diagnostics);+ var composed = boolean.Kind switch+ {+ FirmamentLoweredBooleanKind.Add => new CirUnionNode(lhs, rhs),+ FirmamentLoweredBooleanKind.Subtract => new CirSubtractNode(lhs, rhs),+ FirmamentLoweredBooleanKind.Intersect => new CirIntersectNode(lhs, rhs),+ _ => lhs+ };++ nodesByFeature[boolean.FeatureId] = composed;+ }++ if (diagnostics.Count > 0)+ {+ return KernelResult<CirLoweringResult>.Failure(diagnostics.Select(d => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Message, d.FeatureId)).ToList());+ }++ if (plan.Booleans.Count > 0)+ {+ var lastBoolean = plan.Booleans.OrderBy(b => b.OpIndex).Last();+ if (!nodesByFeature.TryGetValue(lastBoolean.FeatureId, out var rootFromBoolean))+ {+ return KernelResult<CirLoweringResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Unable to resolve final boolean root.", "Firmament.CirLowering")]);+ }++ return KernelResult<CirLoweringResult>.Success(new CirLoweringResult(rootFromBoolean, diagnostics));+ }++ var finalPrimitive = plan.Primitives.OrderBy(p => p.OpIndex).LastOrDefault();+ if (finalPrimitive is null || !nodesByFeature.TryGetValue(finalPrimitive.FeatureId, out var root))+ {+ return KernelResult<CirLoweringResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "No CIR-lowerable root found.", "Firmament.CirLowering")]);+ }++ return KernelResult<CirLoweringResult>.Success(new CirLoweringResult(root, diagnostics));+ }++ private static CirNode? LowerTool(FirmamentLoweredBoolean boolean, List<CirLoweringDiagnostic> diagnostics)+ {+ if (!boolean.Tool.RawFields.TryGetValue("op", out var op))+ {+ diagnostics.Add(new(boolean.OpIndex, boolean.FeatureId, "Boolean tool missing op."));+ return null;+ }++ return op switch+ {+ "box" when boolean.Tool.RawFields.TryGetValue("size", out var size) => BuildBox(size),+ "cylinder" when boolean.Tool.RawFields.TryGetValue("radius", out var radius) && boolean.Tool.RawFields.TryGetValue("height", out var height)+ => new CirCylinderNode(double.Parse(radius), double.Parse(height)),+ "sphere" when boolean.Tool.RawFields.TryGetValue("radius", out var sr) => new CirSphereNode(double.Parse(sr)),+ _ => UnsupportedTool(boolean, diagnostics)+ };+ }++ private static CirNode? UnsupportedTool(FirmamentLoweredBoolean boolean, List<CirLoweringDiagnostic> diagnostics)+ {+ diagnostics.Add(new(boolean.OpIndex, boolean.FeatureId, $"Unsupported boolean tool op for CIR-M1: {boolean.Tool.OpName}."));+ return null;+ }++ private static CirNode? LowerPrimitive(FirmamentLoweredPrimitive primitive, List<CirLoweringDiagnostic> diagnostics) => primitive switch+ {+ { Kind: FirmamentLoweredPrimitiveKind.Box, Parameters: FirmamentLoweredBoxParameters box } => new CirBoxNode(box.SizeX, box.SizeY, box.SizeZ),+ { Kind: FirmamentLoweredPrimitiveKind.Cylinder, Parameters: FirmamentLoweredCylinderParameters cylinder } => new CirCylinderNode(cylinder.Radius, cylinder.Height),+ { Kind: FirmamentLoweredPrimitiveKind.Sphere, Parameters: FirmamentLoweredSphereParameters sphere } => new CirSphereNode(sphere.Radius),+ _ => UnsupportedPrimitive(primitive, diagnostics)+ };++ private static CirNode? UnsupportedPrimitive(FirmamentLoweredPrimitive primitive, List<CirLoweringDiagnostic> diagnostics)+ {+ diagnostics.Add(new(primitive.OpIndex, primitive.FeatureId, $"Unsupported primitive for CIR-M1: {primitive.Kind}."));+ return null;+ }++ private static CirNode BuildBox(string sizeRaw)+ {+ var parts = sizeRaw.Trim('[', ']').Split(',').Select(p => double.Parse(p.Trim())).ToArray();+ return new CirBoxNode(parts[0], parts[1], parts[2]);+ }++ private static CirNode ApplyPlacement(CirNode node, FirmamentLoweredPlacement? placement, int opIndex, string featureId, List<CirLoweringDiagnostic> diagnostics)+ {+ if (placement is null || placement.Offset.Count == 0)+ {+ return node;+ }++ if (placement.On is not null and not FirmamentLoweredPlacementOriginAnchor)+ {+ diagnostics.Add(new(opIndex, featureId, "Only origin placement anchor is supported in CIR-M1."));+ return node;+ }++ if (placement.Offset.Count != 3)+ {+ 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])));+ }+}diff --git a/docs/cir-m1-lowering.md b/docs/cir-m1-lowering.mdnew file mode 100644index 00000000..ea7dbaad--- /dev/null+++ b/docs/cir-m1-lowering.md@@ -0,0 +1,32 @@+# CIR-M1: Experimental Firmament-to-CIR Lowering++CIR-M1 adds an **experimental** side-by-side lowerer from existing Firmament primitive-lowering plans into CIR trees.++## Supported subset (M1)++- Primitives: `box`, `cylinder`, `sphere`+- Booleans: `add`, `subtract`, `intersect`+- Placement: `place.on: origin` with simple `place.offset[3]` translation++## Unsupported in M1++Anything outside the subset above is rejected with explicit CIR-lowering diagnostics, including:++- `cone`, `torus`, prism/slot families+- `draft`, `chamfer`, `fillet`+- `library_part`, rounded-corner-box+- selector-based semantic placement anchors++## Important boundary++This does **not** replace production Firmament execution.++- Production path remains: Firmament -> primitive lowering -> BRep execution -> STEP export.+- CIR path is internal/test-facing for point classification and approximate volume only.+- No CIR->BRep materialization is added in M1.++## Recommended M2++- Expand placement lowering to a bounded selector subset with explicit reference-frame tests.+- Add differential tests comparing CIR-vs-BRep containment/approx volume on shared fixtures.+- Keep unsupported diagnostics first-class while growing subset coverage incrementally.