Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Refactor CIR rematerialization into replay-guided strategy registry

Yuechen Li463da50a2429
diff --git a/Aetheris.Kernel.Firmament.Tests/CirBrepMaterializerTests.cs b/Aetheris.Kernel.Firmament.Tests/CirBrepMaterializerTests.cs
index cc751ac5..703185e2 100644
--- a/Aetheris.Kernel.Firmament.Tests/CirBrepMaterializerTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/CirBrepMaterializerTests.cs
@@ -8,102 +8,98 @@ namespace Aetheris.Kernel.Firmament.Tests;
public sealed class CirBrepMaterializerTests
{
[Fact]
- public void CirMaterializer_BoxMinusCylinder_Succeeds()
+ public void MaterializerRegistry_Selects_BoxMinusCylinder()
{
var root = new CirSubtractNode(
new CirTransformNode(new CirBoxNode(20, 20, 10), Transform3D.CreateTranslation(new Vector3D(0, 0, 5))),
new CirTransformNode(new CirCylinderNode(3, 20), Transform3D.CreateTranslation(new Vector3D(0, 0, 5))));
+ var replay = BuildReplay("cylinder");
- var result = CirBrepMaterializer.TryMaterialize(root);
+ var result = CirBrepMaterializer.TryMaterialize(new CirBrepMaterializer.CirBrepMaterializerContext(root, replay));
Assert.True(result.IsSuccess);
- Assert.NotNull(result.Body);
+ Assert.Equal("subtract_box_cylinder", result.SelectedStrategy);
Assert.Equal(CirBrepMaterializer.BoxMinusCylinderPattern, result.PatternName);
}
-
[Fact]
- public void CirMaterializer_BoxMinusBox_Succeeds()
+ public void MaterializerRegistry_Selects_BoxMinusBox()
{
var root = new CirSubtractNode(
new CirTransformNode(new CirBoxNode(20, 20, 10), Transform3D.CreateTranslation(new Vector3D(0, 0, 5))),
new CirTransformNode(new CirBoxNode(6, 20, 10), Transform3D.CreateTranslation(new Vector3D(7, 0, 5))));
- var result = CirBrepMaterializer.TryMaterialize(root);
+ var result = CirBrepMaterializer.TryMaterialize(new CirBrepMaterializer.CirBrepMaterializerContext(root, BuildReplay("box")));
Assert.True(result.IsSuccess);
- Assert.NotNull(result.Body);
+ Assert.Equal("subtract_box_box", result.SelectedStrategy);
Assert.Equal(CirBrepMaterializer.BoxMinusBoxPattern, result.PatternName);
- Assert.Null(result.UnsupportedReason);
- Assert.Empty(result.Diagnostics);
}
[Fact]
- public void CirMaterializer_UnsupportedPattern_FailsClearly()
+ public void MaterializerRegistry_RejectionDiagnostics_ListRejectedStrategies()
+ {
+ var result = CirBrepMaterializer.TryMaterialize(new CirBrepMaterializer.CirBrepMaterializerContext(new CirUnionNode(new CirBoxNode(1, 1, 1), new CirBoxNode(1, 1, 1)), null));
+
+ Assert.False(result.IsSuccess);
+ Assert.Equal("no-strategy-matched", result.UnsupportedReason);
+ Assert.Contains(result.StrategyRejections, r => r.CandidateName == "subtract_box_cylinder");
+ Assert.Contains(result.StrategyRejections, r => r.CandidateName == "subtract_box_box");
+ }
+
+ [Fact]
+ public void ReplayGuided_Mismatch_IsDiagnosed()
{
- var root = new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(3));
- var result = CirBrepMaterializer.TryMaterialize(root);
+ var root = new CirSubtractNode(new CirBoxNode(20, 20, 10), new CirBoxNode(6, 20, 10));
+ var mismatchReplay = BuildReplay("cylinder");
+
+ var result = CirBrepMaterializer.TryMaterialize(new CirBrepMaterializer.CirBrepMaterializerContext(root, mismatchReplay));
Assert.False(result.IsSuccess);
- Assert.Null(result.Body);
- Assert.Equal("rhs-unsupported", result.UnsupportedReason);
+ Assert.Contains("Replay/CIR mismatch", result.Message, StringComparison.Ordinal);
}
[Fact]
public void CirOnly_BoxMinusCylinder_RematerializesToBRepActive()
{
var plan = BuildBoxMinusCylinderPlan();
- var state = new NativeGeometryState(NativeGeometryExecutionMode.CirOnly, NativeGeometryMaterializationAuthority.PendingRematerialization, null, "hole", new NativeGeometryReplayLog([]), [], new NativeGeometryCirMirrorState(CirMirrorStatus.NotAttempted, null, []));
+ var state = new NativeGeometryState(NativeGeometryExecutionMode.CirOnly, NativeGeometryMaterializationAuthority.PendingRematerialization, null, "hole", BuildReplay("cylinder"), [], new NativeGeometryCirMirrorState(CirMirrorStatus.NotAttempted, null, []));
var remat = NativeGeometryRematerializer.TryRematerialize(plan, state);
Assert.True(remat.IsSuccess, string.Join(" | ", remat.Diagnostics.Select(d => d.Message)));
Assert.Equal(NativeGeometryExecutionMode.BRepActive, remat.Value.ExecutionMode);
- Assert.NotNull(remat.Value.MaterializedBody);
- Assert.Contains(remat.Value.TransitionEvents, e => e.FromMode == NativeGeometryExecutionMode.CirOnly && e.ToMode == NativeGeometryExecutionMode.BRepActive);
}
-
[Fact]
public void CirOnly_BoxMinusBox_RematerializesToBRepActive()
{
var plan = BuildBoxMinusBoxPlan();
- var state = new NativeGeometryState(NativeGeometryExecutionMode.CirOnly, NativeGeometryMaterializationAuthority.PendingRematerialization, null, "notch", new NativeGeometryReplayLog([]), [], new NativeGeometryCirMirrorState(CirMirrorStatus.NotAttempted, null, []));
+ var state = new NativeGeometryState(NativeGeometryExecutionMode.CirOnly, NativeGeometryMaterializationAuthority.PendingRematerialization, null, "notch", BuildReplay("box"), [], new NativeGeometryCirMirrorState(CirMirrorStatus.NotAttempted, null, []));
var remat = NativeGeometryRematerializer.TryRematerialize(plan, state);
Assert.True(remat.IsSuccess, string.Join(" | ", remat.Diagnostics.Select(d => d.Message)));
Assert.Equal(NativeGeometryExecutionMode.BRepActive, remat.Value.ExecutionMode);
- Assert.Equal(NativeGeometryMaterializationAuthority.BRepAuthoritative, remat.Value.MaterializationAuthority);
- Assert.NotNull(remat.Value.MaterializedBody);
- Assert.Contains(remat.Value.TransitionEvents, e => e.FromMode == NativeGeometryExecutionMode.CirOnly && e.ToMode == NativeGeometryExecutionMode.BRepActive);
}
+ private static NativeGeometryReplayLog BuildReplay(string toolKind)
+ => new([
+ new NativeGeometryReplayOperation(0, "base", "primitive:box", null, null, null, null, new NativeGeometryResolvedPlacement(NativeGeometryPlacementKind.None, null, null, Vector3D.Zero, Vector3D.Zero, true, null), null),
+ new NativeGeometryReplayOperation(1, "cut", "boolean:subtract", "base", toolKind, "tool", null, new NativeGeometryResolvedPlacement(NativeGeometryPlacementKind.None, null, null, Vector3D.Zero, Vector3D.Zero, true, null), null)
+ ]);
+
private static FirmamentPrimitiveLoweringPlan BuildBoxMinusCylinderPlan()
{
- var primitives = new[]
- {
- new FirmamentLoweredPrimitive(0, "base", FirmamentLoweredPrimitiveKind.Box, new FirmamentLoweredBoxParameters(20,20,10), null)
- };
- var booleans = new[]
- {
- new FirmamentLoweredBoolean(1, "hole", FirmamentLoweredBooleanKind.Subtract, "from", "base", new FirmamentLoweredToolOp("cylinder", new Dictionary<string,string>{{"op","cylinder"},{"radius","3"},{"height","20"}}, "op cylinder radius=3 height=20"), null)
- };
+ var primitives = new[] { new FirmamentLoweredPrimitive(0, "base", FirmamentLoweredPrimitiveKind.Box, new FirmamentLoweredBoxParameters(20,20,10), null) };
+ var booleans = new[] { new FirmamentLoweredBoolean(1, "hole", FirmamentLoweredBooleanKind.Subtract, "from", "base", new FirmamentLoweredToolOp("cylinder", new Dictionary<string,string>{{"op","cylinder"},{"radius","3"},{"height","20"}}, "op cylinder radius=3 height=20"), null) };
return new FirmamentPrimitiveLoweringPlan(primitives, booleans, []);
}
-
private static FirmamentPrimitiveLoweringPlan BuildBoxMinusBoxPlan()
{
- var primitives = new[]
- {
- new FirmamentLoweredPrimitive(0, "base", FirmamentLoweredPrimitiveKind.Box, new FirmamentLoweredBoxParameters(20,20,10), null)
- };
- var booleans = new[]
- {
- new FirmamentLoweredBoolean(1, "notch", FirmamentLoweredBooleanKind.Subtract, "from", "base", new FirmamentLoweredToolOp("box", new Dictionary<string,string>{{"op","box"},{"size","[6,20,10]"}}, "op box size=[6,20,10]"), new FirmamentLoweredPlacement(new FirmamentLoweredPlacementOriginAnchor(), true, new double[] { 7, 0, 0 }, null, null, null, []))
- };
+ var primitives = new[] { new FirmamentLoweredPrimitive(0, "base", FirmamentLoweredPrimitiveKind.Box, new FirmamentLoweredBoxParameters(20,20,10), null) };
+ var booleans = new[] { new FirmamentLoweredBoolean(1, "notch", FirmamentLoweredBooleanKind.Subtract, "from", "base", new FirmamentLoweredToolOp("box", new Dictionary<string,string>{{"op","box"},{"size","[6,20,10]"}}, "op box size=[6,20,10]"), new FirmamentLoweredPlacement(new FirmamentLoweredPlacementOriginAnchor(), true, new double[] { 7, 0, 0 }, null, null, null, [])) };
return new FirmamentPrimitiveLoweringPlan(primitives, booleans, []);
}
-
}
diff --git a/Aetheris.Kernel.Firmament/Execution/CirBrepMaterializer.cs b/Aetheris.Kernel.Firmament/Execution/CirBrepMaterializer.cs
index 0f110051..3e4b0c88 100644
--- a/Aetheris.Kernel.Firmament/Execution/CirBrepMaterializer.cs
+++ b/Aetheris.Kernel.Firmament/Execution/CirBrepMaterializer.cs
@@ -1,8 +1,9 @@
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Boolean;
using Aetheris.Kernel.Core.Cir;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Judgment;
using Aetheris.Kernel.Core.Math;
-using Aetheris.Kernel.Core.Results;
namespace Aetheris.Kernel.Firmament.Execution;
@@ -10,157 +11,106 @@ internal static class CirBrepMaterializer
{
internal const string BoxMinusCylinderPattern = "subtract(box,cylinder)";
internal const string BoxMinusBoxPattern = "subtract(box,box)";
+ private static readonly JudgmentEngine<CirBrepMaterializerContext> Engine = new();
+ private static readonly ICirBrepMaterializerStrategy[] Registry = [new SubtractBoxCylinderStrategy(), new SubtractBoxBoxStrategy()];
- internal static CirBrepMaterializationResult TryMaterialize(CirNode root)
- {
- ArgumentNullException.ThrowIfNull(root);
+ internal static CirBrepMaterializationResult TryMaterialize(CirNode root) => TryMaterialize(new CirBrepMaterializerContext(root, null));
- if (root is not CirSubtractNode subtract)
- {
- return Unsupported(BoxMinusCylinderPattern, "Root CIR node must be subtract.", "root-not-subtract");
- }
-
- if (!TryUnwrapTranslation(subtract.Left, out var leftNode, out var leftTranslation) || leftNode is not CirBoxNode leftBox)
+ internal static CirBrepMaterializationResult TryMaterialize(CirBrepMaterializerContext context)
+ {
+ var candidates = Registry.Select((s, i) => new JudgmentCandidate<CirBrepMaterializerContext>(s.Name, s.IsAdmissible, s.Score, s.RejectionReason, i)).ToArray();
+ var judgment = Engine.Evaluate(context, candidates);
+ if (!judgment.IsSuccess)
{
- return Unsupported(BoxMinusCylinderPattern, "Subtract lhs must be a translated/untranslated box node.", "lhs-not-box");
+ var message = "No CIR→BRep materializer strategy matched. " + string.Join("; ", judgment.Rejections.Select(r => $"{r.CandidateName}: {r.Reason}"));
+ return new(false, null, "unsupported", "no-strategy-matched", [], message, null, judgment.Rejections);
}
- return subtract.Right switch
- {
- CirCylinderNode cylinder => TryMaterializeBoxMinusCylinder(leftBox, leftTranslation, cylinder, Vector3D.Zero),
- CirTransformNode transformedCylinder when TryUnwrapTranslation(transformedCylinder, out var cylinderNode, out var cylinderTranslation) && cylinderNode is CirCylinderNode cylinder
- => TryMaterializeBoxMinusCylinder(leftBox, leftTranslation, cylinder, cylinderTranslation),
- CirBoxNode rightBox => TryMaterializeBoxMinusBox(leftBox, leftTranslation, rightBox, Vector3D.Zero),
- CirTransformNode transformedBox when TryUnwrapTranslation(transformedBox, out var rightNode, out var rightTranslation) && rightNode is CirBoxNode rightBox
- => TryMaterializeBoxMinusBox(leftBox, leftTranslation, rightBox, rightTranslation),
- _ => Unsupported(BoxMinusCylinderPattern, "Subtract rhs must be a translated/untranslated cylinder or box node.", "rhs-unsupported")
- };
+ var selected = judgment.Selection!.Value.Candidate.Name;
+ var result = Registry.Single(s => s.Name == selected).Materialize(context);
+ return result with { SelectedStrategy = selected, StrategyRejections = judgment.Rejections };
}
- private static CirBrepMaterializationResult TryMaterializeBoxMinusCylinder(CirBoxNode box, Vector3D boxTranslation, CirCylinderNode cylinder, Vector3D cylinderTranslation)
+ internal sealed record CirBrepMaterializerContext(CirNode Root, NativeGeometryReplayLog? ReplayLog)
{
- var boxResult = BrepPrimitives.CreateBox(box.Width, box.Height, box.Depth);
- if (!boxResult.IsSuccess)
- {
- return Failed(BoxMinusCylinderPattern, "Failed to create BRep box primitive.", boxResult.Diagnostics);
- }
-
- var cylinderResult = BrepPrimitives.CreateCylinder(cylinder.Radius, cylinder.Height);
- if (!cylinderResult.IsSuccess)
- {
- return Failed(BoxMinusCylinderPattern, "Failed to create BRep cylinder primitive.", cylinderResult.Diagnostics);
- }
-
- var placedBox = TranslateBody(boxResult.Value, boxTranslation);
- var placedCylinder = TranslateBody(cylinderResult.Value, cylinderTranslation);
- var subtractResult = BrepBoolean.Subtract(placedBox, placedCylinder);
- if (!subtractResult.IsSuccess)
- {
- return Failed(BoxMinusCylinderPattern, "Failed to boolean subtract box/cylinder during CIR rematerialization.", subtractResult.Diagnostics);
- }
-
- return new CirBrepMaterializationResult(true, subtractResult.Value, BoxMinusCylinderPattern, null, [], "matched-box-minus-cylinder");
+ internal NativeGeometryReplayOperation? LatestOperation => ReplayLog?.Operations.LastOrDefault(op => op.OperationKind.StartsWith("boolean:subtract", StringComparison.OrdinalIgnoreCase)) ?? ReplayLog?.Operations.LastOrDefault();
}
- private static CirBrepMaterializationResult TryMaterializeBoxMinusBox(CirBoxNode leftBox, Vector3D leftTranslation, CirBoxNode rightBox, Vector3D rightTranslation)
+ private interface ICirBrepMaterializerStrategy
{
- var leftBoxResult = BrepPrimitives.CreateBox(leftBox.Width, leftBox.Height, leftBox.Depth);
- if (!leftBoxResult.IsSuccess)
- {
- return Failed(BoxMinusBoxPattern, "Failed to create lhs BRep box primitive.", leftBoxResult.Diagnostics);
- }
-
- var rightBoxResult = BrepPrimitives.CreateBox(rightBox.Width, rightBox.Height, rightBox.Depth);
- if (!rightBoxResult.IsSuccess)
- {
- return Failed(BoxMinusBoxPattern, "Failed to create rhs BRep box primitive.", rightBoxResult.Diagnostics);
- }
-
- var placedLeft = TranslateBody(leftBoxResult.Value, leftTranslation);
- var placedRight = TranslateBody(rightBoxResult.Value, rightTranslation);
- var subtractResult = BrepBoolean.Subtract(placedLeft, placedRight);
- if (!subtractResult.IsSuccess)
- {
- return Failed(BoxMinusBoxPattern, "Failed to boolean subtract box/box during CIR rematerialization.", subtractResult.Diagnostics);
- }
-
- return new CirBrepMaterializationResult(true, subtractResult.Value, BoxMinusBoxPattern, null, [], "matched-box-minus-box");
+ string Name { get; }
+ bool IsAdmissible(CirBrepMaterializerContext context);
+ string RejectionReason(CirBrepMaterializerContext context);
+ double Score(CirBrepMaterializerContext context);
+ CirBrepMaterializationResult Materialize(CirBrepMaterializerContext context);
}
- private static bool TryUnwrapTranslation(CirNode node, out CirNode unwrapped, out Vector3D translation)
+ private sealed class SubtractBoxCylinderStrategy : ICirBrepMaterializerStrategy
{
- var total = Vector3D.Zero;
- var current = node;
+ public string Name => "subtract_box_cylinder";
+ public bool IsAdmissible(CirBrepMaterializerContext context) => TryMatch(context, true, out _, out _);
+ public string RejectionReason(CirBrepMaterializerContext context) => TryMatch(context, true, out _, out var reason) ? "admissible" : reason;
+ public double Score(CirBrepMaterializerContext context) => context.ReplayLog is null ? 1d : 2d;
- while (current is CirTransformNode transformNode)
+ public CirBrepMaterializationResult Materialize(CirBrepMaterializerContext context)
{
- if (!TryExtractPureTranslation(transformNode.Transform, out var localTranslation))
- {
- unwrapped = node;
- translation = Vector3D.Zero;
- return false;
- }
-
- total += localTranslation;
- current = transformNode.Child;
+ if (!TryMatch(context, true, out var m, out var reason)) return new(false, null, BoxMinusCylinderPattern, "strategy-no-longer-admissible", [], reason, Name, []);
+ var b = BrepPrimitives.CreateBox(m!.LeftBox.Width, m.LeftBox.Height, m.LeftBox.Depth);
+ var c = BrepPrimitives.CreateCylinder(m.Cylinder!.Radius, m.Cylinder.Height);
+ if (!b.IsSuccess) return Failed(BoxMinusCylinderPattern, "Failed to create BRep box primitive.", b.Diagnostics);
+ if (!c.IsSuccess) return Failed(BoxMinusCylinderPattern, "Failed to create BRep cylinder primitive.", c.Diagnostics);
+ var s = BrepBoolean.Subtract(TranslateBody(b.Value, m.LeftTranslation), TranslateBody(c.Value, m.RightTranslation));
+ return s.IsSuccess ? new(true, s.Value, BoxMinusCylinderPattern, null, [], "matched-box-minus-cylinder", Name, []) : Failed(BoxMinusCylinderPattern, "Failed to boolean subtract box/cylinder during CIR rematerialization.", s.Diagnostics);
}
-
- translation = total;
- unwrapped = current;
- return true;
}
- private static bool TryExtractPureTranslation(Transform3D transform, out Vector3D translation)
+ private sealed class SubtractBoxBoxStrategy : ICirBrepMaterializerStrategy
{
- var origin = transform.Apply(Point3D.Origin);
- var x = transform.Apply(new Point3D(1d, 0d, 0d));
- var y = transform.Apply(new Point3D(0d, 1d, 0d));
- var z = transform.Apply(new Point3D(0d, 0d, 1d));
-
- var eps = 1e-9d;
- var xDelta = x - origin;
- var yDelta = y - origin;
- var zDelta = z - origin;
- var isIdentityBasis = NearlyEqual(xDelta, new Vector3D(1d, 0d, 0d), eps)
- && NearlyEqual(yDelta, new Vector3D(0d, 1d, 0d), eps)
- && NearlyEqual(zDelta, new Vector3D(0d, 0d, 1d), eps);
-
- if (!isIdentityBasis)
+ public string Name => "subtract_box_box";
+ public bool IsAdmissible(CirBrepMaterializerContext context) => TryMatch(context, false, out _, out _);
+ public string RejectionReason(CirBrepMaterializerContext context) => TryMatch(context, false, out _, out var reason) ? "admissible" : reason;
+ public double Score(CirBrepMaterializerContext context) => context.ReplayLog is null ? 1d : 2d;
+ public CirBrepMaterializationResult Materialize(CirBrepMaterializerContext context)
{
- translation = Vector3D.Zero;
- return false;
+ if (!TryMatch(context, false, out var m, out var reason)) return new(false, null, BoxMinusBoxPattern, "strategy-no-longer-admissible", [], reason, Name, []);
+ var l = BrepPrimitives.CreateBox(m!.LeftBox.Width, m.LeftBox.Height, m.LeftBox.Depth);
+ var r = BrepPrimitives.CreateBox(m.RightBox!.Width, m.RightBox.Height, m.RightBox.Depth);
+ if (!l.IsSuccess) return Failed(BoxMinusBoxPattern, "Failed to create lhs BRep box primitive.", l.Diagnostics);
+ if (!r.IsSuccess) return Failed(BoxMinusBoxPattern, "Failed to create rhs BRep box primitive.", r.Diagnostics);
+ var s = BrepBoolean.Subtract(TranslateBody(l.Value, m.LeftTranslation), TranslateBody(r.Value, m.RightTranslation));
+ return s.IsSuccess ? new(true, s.Value, BoxMinusBoxPattern, null, [], "matched-box-minus-box", Name, []) : Failed(BoxMinusBoxPattern, "Failed to boolean subtract box/box during CIR rematerialization.", s.Diagnostics);
}
-
- translation = origin - Point3D.Origin;
- return true;
}
- private static bool NearlyEqual(Vector3D left, Vector3D right, double eps)
- => double.Abs(left.X - right.X) <= eps
- && double.Abs(left.Y - right.Y) <= eps
- && double.Abs(left.Z - right.Z) <= eps;
-
- private static BrepBody TranslateBody(BrepBody body, Vector3D translation)
+ private sealed record Match(CirBoxNode LeftBox, Vector3D LeftTranslation, Vector3D RightTranslation, CirCylinderNode? Cylinder, CirBoxNode? RightBox);
+ private static bool TryMatch(CirBrepMaterializerContext context, bool cylinder, out Match? match, out string reason)
{
- if (translation == Vector3D.Zero)
- {
- return body;
- }
-
- return FirmamentPrimitiveExecutionTranslation.TranslateBody(body, translation);
+ match = null;
+ if (context.Root is not CirSubtractNode s) { reason = "CIR root is not subtract."; return false; }
+ if (!TryUnwrapTranslation(s.Left, out var lnode, out var lt) || lnode is not CirBoxNode lb) { reason = "Subtract lhs must be translated/untranslated box with translation-only transforms."; return false; }
+ if (!TryUnwrapTranslation(s.Right, out var rnode, out var rt)) { reason = "Subtract rhs contains unsupported non-translation transform."; return false; }
+ if (!ReplayMatches(context, cylinder ? "cylinder" : "box", out reason)) return false;
+ if (cylinder && rnode is CirCylinderNode rc) { match = new(lb, lt, rt, rc, null); reason = "matched"; return true; }
+ if (!cylinder && rnode is CirBoxNode rb) { match = new(lb, lt, rt, null, rb); reason = "matched"; return true; }
+ reason = cylinder ? "Subtract rhs must be translated/untranslated cylinder." : "Subtract rhs must be translated/untranslated box.";
+ return false;
}
- private static CirBrepMaterializationResult Unsupported(string pattern, string diagnostic, string reason)
- => new(false, null, pattern, reason, [], diagnostic);
+ private static bool ReplayMatches(CirBrepMaterializerContext context, string expectedToolKind, out string reason)
+ {
+ if (context.ReplayLog is null) { reason = "Replay log missing; using CIR tree-only fallback."; return true; }
+ var op = context.LatestOperation;
+ if (op is null) { reason = "Replay log present but contains no operations."; return false; }
+ if (!op.OperationKind.StartsWith("boolean:subtract", StringComparison.OrdinalIgnoreCase)) { reason = $"Replay/CIR mismatch: expected latest replay operation boolean:subtract, got '{op.OperationKind}'."; return false; }
+ if (!string.IsNullOrWhiteSpace(op.ToolKind) && !string.Equals(op.ToolKind, expectedToolKind, StringComparison.OrdinalIgnoreCase)) { reason = $"Replay/CIR mismatch: expected replay tool kind '{expectedToolKind}', got '{op.ToolKind}'."; return false; }
+ reason = "matched"; return true;
+ }
- private static CirBrepMaterializationResult Failed(string pattern, string diagnostic, IReadOnlyList<Core.Diagnostics.KernelDiagnostic> diagnostics)
- => new(false, null, pattern, "materialize-failed", diagnostics, diagnostic);
+ private static CirBrepMaterializationResult Failed(string pattern, string message, IReadOnlyList<KernelDiagnostic> d) => new(false, null, pattern, "materialize-failed", d, message, null, []);
+ private static BrepBody TranslateBody(BrepBody body, Vector3D t) => t == Vector3D.Zero ? body : FirmamentPrimitiveExecutionTranslation.TranslateBody(body, t);
+ private static bool TryUnwrapTranslation(CirNode node, out CirNode unwrapped, out Vector3D translation) { var total = Vector3D.Zero; var cur = node; while (cur is CirTransformNode tr) { if (!TryExtractPureTranslation(tr.Transform, out var local)) { unwrapped = node; translation = Vector3D.Zero; return false; } total += local; cur = tr.Child; } unwrapped = cur; translation = total; return true; }
+ private static bool TryExtractPureTranslation(Transform3D transform, out Vector3D translation) { var o = transform.Apply(Point3D.Origin); var x = transform.Apply(new Point3D(1,0,0)); var y = transform.Apply(new Point3D(0,1,0)); var z = transform.Apply(new Point3D(0,0,1)); var eps=1e-9d; if(!NearlyEqual(x-o,new Vector3D(1,0,0),eps)||!NearlyEqual(y-o,new Vector3D(0,1,0),eps)||!NearlyEqual(z-o,new Vector3D(0,0,1),eps)){ translation=Vector3D.Zero; return false;} translation=o-Point3D.Origin; return true; }
+ private static bool NearlyEqual(Vector3D l, Vector3D r, double eps) => double.Abs(l.X-r.X)<=eps && double.Abs(l.Y-r.Y)<=eps && double.Abs(l.Z-r.Z)<=eps;
}
-internal sealed record CirBrepMaterializationResult(
- bool IsSuccess,
- BrepBody? Body,
- string PatternName,
- string? UnsupportedReason,
- IReadOnlyList<Core.Diagnostics.KernelDiagnostic> Diagnostics,
- string Message);
+internal sealed record CirBrepMaterializationResult(bool IsSuccess, BrepBody? Body, string PatternName, string? UnsupportedReason, IReadOnlyList<KernelDiagnostic> Diagnostics, string Message, string? SelectedStrategy, IReadOnlyList<JudgmentRejection> StrategyRejections);
diff --git a/Aetheris.Kernel.Firmament/Execution/NativeGeometryRematerializer.cs b/Aetheris.Kernel.Firmament/Execution/NativeGeometryRematerializer.cs
index 214c5d19..d1aa34e4 100644
--- a/Aetheris.Kernel.Firmament/Execution/NativeGeometryRematerializer.cs
+++ b/Aetheris.Kernel.Firmament/Execution/NativeGeometryRematerializer.cs
@@ -23,7 +23,7 @@ internal static class NativeGeometryRematerializer
return KernelResult<NativeGeometryState>.Failure(lowered.Diagnostics);
}
- var materialized = CirBrepMaterializer.TryMaterialize(lowered.Value.Root);
+ var materialized = CirBrepMaterializer.TryMaterialize(new CirBrepMaterializer.CirBrepMaterializerContext(lowered.Value.Root, state.ReplayLog));
if (!materialized.IsSuccess || materialized.Body is null)
{
var diagnostics = materialized.Diagnostics.Count > 0
diff --git a/docs/cir-f6-replay-guided-materializer-registry.md b/docs/cir-f6-replay-guided-materializer-registry.md
new file mode 100644
index 00000000..1f36d12c
--- /dev/null
+++ b/docs/cir-f6-replay-guided-materializer-registry.md
@@ -0,0 +1,64 @@
+# CIR-F6: replay-guided materializer strategy registry
+
+CIR-F6 refactors bounded CIR→BRep rematerialization from a hard-coded switch into a strategy registry.
+
+## Why this is not arbitrary F-Rep→BRep recovery
+
+Aetheris is not trying to infer BRep from opaque sampled fields. Instead it uses:
+
+- typed CIR node kinds,
+- Firmament replay operations,
+- provenance/tool kinds,
+- resolved placement facts.
+
+That enables bounded exact strategy selection (`replay + CIR subtree -> exact builder`).
+
+## Registry shape
+
+`CirBrepMaterializer` now evaluates a set of named strategies via `JudgmentEngine`.
+
+Each strategy provides:
+
+- stable strategy name,
+- admissibility check,
+- rejection reason,
+- deterministic score,
+- materialization execution.
+
+A shared `CirBrepMaterializerContext` carries:
+
+- CIR root,
+- optional replay log,
+- latest replay operation (derived helper).
+
+## Current strategies
+
+- `subtract_box_cylinder` -> `subtract(box,cylinder)`
+- `subtract_box_box` -> `subtract(box,box)`
+
+Both preserve existing bounded behavior (translation-only transforms, simple subtract trees).
+
+## Replay/CIR verification model
+
+When replay is available, strategies require latest replay op to match:
+
+- operation kind `boolean:subtract`,
+- expected tool kind (`cylinder` or `box`).
+
+CIR subtree checks remain required and authoritative for shape form.
+
+When replay is absent, tree-only fallback is still allowed, but reflected in strategy rejection diagnostics.
+
+## Diagnostics
+
+Failure now reports:
+
+- no strategy matched,
+- per-strategy rejection reasons,
+- replay/CIR mismatch reasons,
+- transform/subtree mismatch details,
+- builder execution failures when applicable.
+
+## Recommended CIR-F7 next step
+
+Add the next bounded subtract family as another strategy (no registry redesign), and extend replay-guided checks to include resolved placement compatibility preconditions before execution.