Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
E3: route non-orth corner chamfer policy through judgment reject path
Yuechen Li5304804d8ba3
diff --git a/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerJudgmentTests.cs b/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerJudgmentTests.csindex 66536e83..57bc6a83 100644--- a/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerJudgmentTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerJudgmentTests.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Brep.Boolean;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.EdgeFinishing;namespace Aetheris.Kernel.Core.Tests.Brep.EdgeFinishing;@@ -17,4 +18,19 @@ public sealed class BrepBoundedChamferCornerJudgmentTestsAssert.False(result.IsSuccess);Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.Contains("No bounded corner-resolution candidate was admissible", StringComparison.Ordinal));}++ [Fact]+ public void ChamferTrustedPolyhedralSingleCorner_Rejects_NonOrthogonalTriangularPrismCorner_WithExplicitPolicyReason()+ {+ var prism = BrepPrimitives.CreateTriangularPrism(baseWidth: 8d, baseDepth: 6d, height: 10d);+ Assert.True(prism.IsSuccess);++ var result = BrepBoundedChamfer.ChamferTrustedPolyhedralSingleCorner(+ prism.Value,+ BrepBoundedChamferCorner.XMaxYMaxZMax,+ distance: 1d);++ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.Contains("corner resolution rejected", StringComparison.Ordinal));+ }}diff --git a/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs b/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.csindex bb26b497..219b0744 100644--- a/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs+++ b/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs@@ -16,6 +16,9 @@ namespace Aetheris.Kernel.Core.Brep.EdgeFinishing;/// </summary>public static class BrepBoundedChamfer{+ private const string PlanarCornerCutCandidate = "planar_corner_cut";+ private const string RejectCandidate = "reject";+public static KernelResult<BrepBody> ChamferAxisAlignedBoxSingleCorner(AxisAlignedBoxExtents box,BrepBoundedChamferCorner corner,@@ -40,7 +43,7 @@ public static class BrepBoundedChamfer}var selected = judgment.Selection.Value.Candidate.Name;- if (selected == "reject")+ if (selected == RejectCandidate){var reason = judgment.Rejections.Count == 0? "No bounded corner-resolution candidate was admissible."@@ -50,11 +53,44 @@ public static class BrepBoundedChamferreturn selected switch{- "planar-tri-corner-cut" => CreateSingleCornerPlanarChamferBody(context),+ PlanarCornerCutCandidate => CreateSingleCornerPlanarChamferBody(context),_ => KernelResult<BrepBody>.Failure([Failure($"Bounded chamfer corner resolution selected unsupported candidate '{selected}'.", "firmament.chamfer-bounded")])};}+ public static KernelResult<BrepBody> ChamferTrustedPolyhedralSingleCorner(+ BrepBody sourceBody,+ BrepBoundedChamferCorner corner,+ double distance)+ {+ var contextResult = BrepBoundedChamferCornerContext.TryCreateFromTrustedBody(sourceBody, corner, distance);+ if (!contextResult.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(contextResult.Diagnostics);+ }++ var context = contextResult.Value;+ var engine = new JudgmentEngine<BrepBoundedChamferCornerContext>();+ var candidates = BuildCornerCandidates();+ var judgment = engine.Evaluate(context, candidates);+ if (!judgment.IsSuccess || !judgment.Selection.HasValue || judgment.Selection.Value.Candidate.Name == RejectCandidate)+ {+ var reason = judgment.Rejections.Count == 0+ ? "No bounded corner-resolution candidate was admissible."+ : string.Join(" ", judgment.Rejections.Select(rejection => $"{rejection.CandidateName}: {rejection.Reason}."));+ return KernelResult<BrepBody>.Failure([Failure($"Bounded chamfer corner resolution rejected: {reason}", "firmament.chamfer-bounded")]);+ }++ if (!context.IsTrustedOrthogonalBody || !context.HasOrthogonalGeometryConstructor)+ {+ return KernelResult<BrepBody>.Failure([Failure(+ "Bounded chamfer corner resolution reached non-orthogonal tri-planar corner policy, but geometry construction is currently bounded to orthogonal box-like corners only.",+ "firmament.chamfer-bounded")]);+ }++ return CreateSingleCornerPlanarChamferBody(context);+ }+public static KernelResult<BrepBody> ChamferAxisAlignedBoxVerticalEdge(AxisAlignedBoxExtents box,BrepBoundedChamferEdge edge,@@ -146,25 +182,25 @@ public static class BrepBoundedChamferprivate static IReadOnlyList<JudgmentCandidate<BrepBoundedChamferCornerContext>> BuildCornerCandidates(){- var canonicalCornerGuard = When.All<BrepBoundedChamferCornerContext>(- context => context.IsTrustedOrthogonalBody,+ var planarCornerGuard = When.All<BrepBoundedChamferCornerContext>(context => context.ParticipatingEdgeCount == 3,context => context.IsConvexCorner,context => context.AllFacesPlanar,- context => context.AllAdjacentFacesOrthogonal,context => context.AreChamferDistancesEqual,context => context.IsDistanceWithinLocalBounds,+ context => context.HasCoherentBoundedPlanarCut,+ context => context.PreservesManifoldTopology,context => context.Corner == BrepBoundedChamferCorner.XMaxYMaxZMax);return[new JudgmentCandidate<BrepBoundedChamferCornerContext>(- Name: "planar-tri-corner-cut",- IsAdmissible: canonicalCornerGuard,- Score: _ => 100d,- RejectionReason: _ => "requires a trusted orthogonal 3-edge convex planar 90-degree corner with equal bounded distance at x_max_y_max_z_max",+ Name: PlanarCornerCutCandidate,+ IsAdmissible: planarCornerGuard,+ Score: context => context.AllAdjacentFacesOrthogonal ? 200d : 150d,+ RejectionReason: context => $"requires a convex planar tri-corner with coherent bounded planar cut and manifold safety (orthogonal={context.AllAdjacentFacesOrthogonal}, acuteAngles={context.AcuteFaceAngleCount}, obtuseAngles={context.ObtuseFaceAngleCount})",TieBreakerPriority: 0),new JudgmentCandidate<BrepBoundedChamferCornerContext>(- Name: "reject",+ Name: RejectCandidate,IsAdmissible: _ => true,Score: _ => 0d,RejectionReason: _ => "fallback reject candidate",@@ -329,9 +365,14 @@ public readonly record struct BrepBoundedChamferCornerContext(bool IsConvexCorner,bool AllFacesPlanar,bool AllAdjacentFacesOrthogonal,+ int AcuteFaceAngleCount,+ int ObtuseFaceAngleCount,bool AreChamferDistancesEqual,bool IsDistanceWithinLocalBounds,- bool IsTrustedOrthogonalBody)+ bool HasCoherentBoundedPlanarCut,+ bool PreservesManifoldTopology,+ bool IsTrustedOrthogonalBody,+ bool HasOrthogonalGeometryConstructor){public static KernelResult<BrepBoundedChamferCornerContext> TryCreate(AxisAlignedBoxExtents box,@@ -360,9 +401,246 @@ public readonly record struct BrepBoundedChamferCornerContext(IsConvexCorner: true,AllFacesPlanar: true,AllAdjacentFacesOrthogonal: true,+ AcuteFaceAngleCount: 0,+ ObtuseFaceAngleCount: 0,AreChamferDistancesEqual: true,IsDistanceWithinLocalBounds: withinBounds,- IsTrustedOrthogonalBody: true));+ HasCoherentBoundedPlanarCut: true,+ PreservesManifoldTopology: true,+ IsTrustedOrthogonalBody: true,+ HasOrthogonalGeometryConstructor: true));+ }++ public static KernelResult<BrepBoundedChamferCornerContext> TryCreateFromTrustedBody(+ BrepBody sourceBody,+ BrepBoundedChamferCorner corner,+ double distance)+ {+ if (!double.IsFinite(distance) || distance <= 0d)+ {+ return KernelResult<BrepBoundedChamferCornerContext>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Bounded chamfer corner distance must be finite and greater than 0.", Source: "firmament.chamfer-bounded")]);+ }++ if (!TryResolveMaxCornerVertex(sourceBody, out var cornerVertex, out var cornerPoint, out var resolveReason))+ {+ return KernelResult<BrepBoundedChamferCornerContext>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, $"Bounded chamfer corner resolution rejected: {resolveReason}", Source: "firmament.chamfer-bounded")]);+ }++ var incidentEdges = sourceBody.Topology.Edges+ .Where(edge => edge.StartVertexId == cornerVertex || edge.EndVertexId == cornerVertex)+ .ToArray();+ var participatingEdgeCount = incidentEdges.Length;+ var edgeVectors = new List<Vector3D>(participatingEdgeCount);+ var localMinEdgeLength = double.PositiveInfinity;+ foreach (var edge in incidentEdges)+ {+ var other = edge.StartVertexId == cornerVertex ? edge.EndVertexId : edge.StartVertexId;+ if (!TryResolveVertexPoint(sourceBody, other, out var otherPoint))+ {+ continue;+ }++ var vector = otherPoint - cornerPoint;+ edgeVectors.Add(vector);+ localMinEdgeLength = double.Min(localMinEdgeLength, vector.Length);+ }++ var incidentFaceNormals = new List<Vector3D>();+ foreach (var face in sourceBody.Topology.Faces)+ {+ if (!FaceContainsVertex(sourceBody, face, cornerVertex))+ {+ continue;+ }++ if (sourceBody.TryGetFaceSurfaceGeometry(face.Id, out var surface)+ && surface?.Kind == SurfaceGeometryKind.Plane+ && surface.Plane.HasValue)+ {+ incidentFaceNormals.Add(surface.Plane.Value.Normal.ToVector());+ }+ }++ var allPlanar = incidentFaceNormals.Count >= 3;+ var angleFacts = AnalyzeAngles(incidentFaceNormals);+ var withinBounds = double.IsFinite(localMinEdgeLength) && distance < localMinEdgeLength;+ var isConvex = edgeVectors.Count == 3 && TryIsConvexTrihedral(edgeVectors, incidentFaceNormals);+ var allOrthogonal = angleFacts.nonOrthogonalCount == 0;+ var coherentCut = participatingEdgeCount == 3 && withinBounds && allPlanar && isConvex;++ return KernelResult<BrepBoundedChamferCornerContext>.Success(new BrepBoundedChamferCornerContext(+ Box: default,+ Corner: corner,+ Distance: distance,+ ParticipatingEdgeCount: participatingEdgeCount,+ IsConvexCorner: isConvex,+ AllFacesPlanar: allPlanar,+ AllAdjacentFacesOrthogonal: allOrthogonal,+ AcuteFaceAngleCount: angleFacts.acuteCount,+ ObtuseFaceAngleCount: angleFacts.obtuseCount,+ AreChamferDistancesEqual: true,+ IsDistanceWithinLocalBounds: withinBounds,+ HasCoherentBoundedPlanarCut: coherentCut,+ PreservesManifoldTopology: coherentCut,+ IsTrustedOrthogonalBody: allOrthogonal,+ HasOrthogonalGeometryConstructor: allOrthogonal));+ }++ private static bool TryResolveMaxCornerVertex(BrepBody body, out VertexId vertexId, out Point3D point, out string reason)+ {+ vertexId = default;+ point = default;+ reason = "could not resolve x_max_y_max_z_max corner from source body vertex points";++ var allPoints = body.Topology.Vertices+ .Where(vertex => TryResolveVertexPoint(body, vertex.Id, out _))+ .Select(vertex =>+ {+ TryResolveVertexPoint(body, vertex.Id, out var p);+ return (vertex.Id, Point: p);+ })+ .ToArray();+ if (allPoints.Length == 0)+ {+ reason = "source body is missing explicit vertex points for corner-token resolution";+ return false;+ }++ var maxScore = allPoints.Max(item => item.Point.X + item.Point.Y + item.Point.Z);+ var tolerance = 1e-9d;+ var candidates = allPoints+ .Where(item => double.Abs((item.Point.X + item.Point.Y + item.Point.Z) - maxScore) <= tolerance)+ .OrderByDescending(item => item.Point.Z)+ .ThenByDescending(item => item.Point.Y)+ .ThenByDescending(item => item.Point.X)+ .ToArray();+ if (candidates.Length == 0)+ {+ reason = "corner token x_max_y_max_z_max could not resolve a dominant positive-octant corner vertex on source body";+ return false;+ }++ vertexId = candidates[0].Id;+ point = candidates[0].Point;+ return true;+ }++ private static bool FaceContainsVertex(BrepBody body, Face face, VertexId vertexId)+ {+ foreach (var loopId in face.LoopIds)+ {+ if (!body.Topology.TryGetLoop(loopId, out var loop) || loop is null)+ {+ continue;+ }++ foreach (var coedgeId in loop.CoedgeIds)+ {+ if (!body.Topology.TryGetCoedge(coedgeId, out var coedge) || coedge is null+ || !body.Topology.TryGetEdge(coedge.EdgeId, out var edge) || edge is null)+ {+ continue;+ }++ if (edge.StartVertexId == vertexId || edge.EndVertexId == vertexId)+ {+ return true;+ }+ }+ }++ return false;+ }++ private static bool TryResolveVertexPoint(BrepBody body, VertexId vertexId, out Point3D point)+ {+ if (body.TryGetVertexPoint(vertexId, out point))+ {+ return true;+ }++ foreach (var edge in body.Topology.Edges)+ {+ var isStart = edge.StartVertexId == vertexId;+ var isEnd = edge.EndVertexId == vertexId;+ if (!isStart && !isEnd)+ {+ continue;+ }++ if (!body.Bindings.TryGetEdgeBinding(edge.Id, out var binding)+ || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve)+ || curve?.Kind != CurveGeometryKind.Line3+ || curve.Line3 is null)+ {+ continue;+ }++ var interval = binding.TrimInterval ?? new ParameterInterval(0d, 1d);+ point = curve.Line3.Value.Evaluate(isStart ? interval.Start : interval.End);+ return true;+ }++ point = default;+ return false;+ }++ private static (int acuteCount, int obtuseCount, int nonOrthogonalCount) AnalyzeAngles(IReadOnlyList<Vector3D> normals)+ {+ var acute = 0;+ var obtuse = 0;+ var nonOrth = 0;+ const double orthTolerance = 1e-6d;+ for (var i = 0; i < normals.Count; i++)+ {+ if (!normals[i].TryNormalize(out var ni))+ {+ continue;+ }++ for (var j = i + 1; j < normals.Count; j++)+ {+ if (!normals[j].TryNormalize(out var nj))+ {+ continue;+ }++ var dot = double.Clamp(ni.Dot(nj), -1d, 1d);+ if (double.Abs(dot) > orthTolerance)+ {+ nonOrth++;+ }++ if (dot > orthTolerance)+ {+ obtuse++;+ }+ else if (dot < -orthTolerance)+ {+ acute++;+ }+ }+ }++ return (acute, obtuse, nonOrth);+ }++ private static bool TryIsConvexTrihedral(IReadOnlyList<Vector3D> edgeVectors, IReadOnlyList<Vector3D> faceNormals)+ {+ if (edgeVectors.Count != 3 || faceNormals.Count < 3)+ {+ return false;+ }++ var cross = edgeVectors[0].Cross(edgeVectors[1]);+ if (!cross.TryNormalize(out var triNormal))+ {+ return false;+ }++ return faceNormals.Any(normal =>+ normal.TryNormalize(out var n)+ && n.Dot(triNormal) > 1e-6d);}}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.csindex c1c05655..87d8da69 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.cs@@ -325,6 +325,16 @@ public sealed class FirmamentPrimitiveExecutionTestsdiagnostic.Message.Contains("supported bounded E2 corner tokens", StringComparison.Ordinal));}+ [Fact]+ public void Compile_Rejects_BoundedChamfer_SingleCorner_For_NonOrthogonalTriangularPrism()+ {+ var result = CompileFixture("testdata/firmament/fixtures/m5a-invalid-chamfer-triangular-prism-nonorth-corner.firmament");++ Assert.False(result.Compilation.IsSuccess);+ Assert.Contains(result.Compilation.Diagnostics, diagnostic =>+ diagnostic.Message.Contains("corner resolution rejected", StringComparison.Ordinal));+ }+[Fact]public void Compile_BoundedFilletCanonicalInternalCase_Reaches_Narrow_TruthfulRebuildBlocker(){diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.csindex 0b374302..594c2921 100644--- a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs@@ -712,27 +712,14 @@ internal static class FirmamentPrimitiveExecutorBrepBody baseBody,IReadOnlyDictionary<string, FirmamentSafeSubtractFeatureGraphState> featureGraphStates){- if (!featureGraphStates.TryGetValue(boolean.PrimaryReferenceFeatureId, out var sourceState)- || sourceState is not (FirmamentSafeSubtractFeatureGraphState.BoxRoot or FirmamentSafeSubtractFeatureGraphState.BoundedOrthogonalAdditiveSafeRoot))- {- return KernelResult<BrepBody>.Failure(- [- new KernelDiagnostic(- KernelDiagnosticCode.ValidationFailed,- KernelDiagnosticSeverity.Error,- $"Bounded chamfer requires a box-root or recognized orthogonal additive root input; '{boolean.PrimaryReferenceFeatureId}' is not eligible.",- Source: "firmament.chamfer-bounded")- ]);- }-- if (!BrepBooleanBoxRecognition.TryRecognizeAxisAlignedBox(baseBody, ToleranceContext.Default, out var box, out var reason))+ if (!featureGraphStates.TryGetValue(boolean.PrimaryReferenceFeatureId, out var sourceState)){return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,- $"Bounded chamfer requires an axis-aligned box-like source body; failed to recognize source body ({reason}).",+ $"Bounded chamfer requires a resolvable source body state; '{boolean.PrimaryReferenceFeatureId}' is not eligible.",Source: "firmament.chamfer-bounded")]);}@@ -765,12 +752,41 @@ internal static class FirmamentPrimitiveExecutorif (edge.HasValue){+ if (sourceState is not (FirmamentSafeSubtractFeatureGraphState.BoxRoot or FirmamentSafeSubtractFeatureGraphState.BoundedOrthogonalAdditiveSafeRoot))+ {+ return KernelResult<BrepBody>.Failure(+ [+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"Bounded chamfer edge mode requires a box-root or recognized orthogonal additive root input; '{boolean.PrimaryReferenceFeatureId}' is not eligible.",+ Source: "firmament.chamfer-bounded")+ ]);+ }++ if (!BrepBooleanBoxRecognition.TryRecognizeAxisAlignedBox(baseBody, ToleranceContext.Default, out var box, out var reason))+ {+ return KernelResult<BrepBody>.Failure(+ [+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"Bounded chamfer edge mode requires an axis-aligned box-like source body; failed to recognize source body ({reason}).",+ Source: "firmament.chamfer-bounded")+ ]);+ }+return BrepBoundedChamfer.ChamferAxisAlignedBoxVerticalEdge(box, edge.Value, distance);}if (corner.HasValue){- return BrepBoundedChamfer.ChamferAxisAlignedBoxSingleCorner(box, corner.Value, distance);+ if (BrepBooleanBoxRecognition.TryRecognizeAxisAlignedBox(baseBody, ToleranceContext.Default, out var box, out _))+ {+ return BrepBoundedChamfer.ChamferAxisAlignedBoxSingleCorner(box, corner.Value, distance);+ }++ return BrepBoundedChamfer.ChamferTrustedPolyhedralSingleCorner(baseBody, corner.Value, distance);}return KernelResult<BrepBody>.Failure(diff --git a/testdata/firmament/fixtures/m5a-invalid-chamfer-triangular-prism-nonorth-corner.firmament b/testdata/firmament/fixtures/m5a-invalid-chamfer-triangular-prism-nonorth-corner.firmamentnew file mode 100644index 00000000..8e239a25--- /dev/null+++ b/testdata/firmament/fixtures/m5a-invalid-chamfer-triangular-prism-nonorth-corner.firmament@@ -0,0 +1,21 @@+firmament:+ version: 1++model:+ name: m5a_invalid_chamfer_triangular_prism_nonorth_corner+ units: mm++ops[2]:+ -+ op: triangular_prism+ id: base+ base_width: 10+ base_depth: 6+ height: 8+ -+ op: chamfer+ id: corner_break+ from: base+ corners[1]:+ x_max_y_max_z_max+ distance: 1