Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Implement bounded M4 draft operation for box-like roots
Yuechen Lid0f2692a7870
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Features/BrepBoundedDraftTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Features/BrepBoundedDraftTests.csnew file mode 100644index 00000000..9d91a623--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Features/BrepBoundedDraftTests.cs@@ -0,0 +1,46 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Boolean;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Numerics;++namespace Aetheris.Kernel.Core.Tests.Brep.Features;++public sealed class BrepBoundedDraftTests+{+ [Fact]+ public void DraftAxisAlignedBoxSideFaces_Succeeds_ForBoundedFaces()+ {+ var box = new AxisAlignedBoxExtents(-20d, 20d, -10d, 10d, 0d, 20d);++ var result = BrepBoundedDraft.DraftAxisAlignedBoxSideFaces(+ box,+ draftAngleDegrees: 2d,+ faces: BrepBoundedDraftFaces.XMin | BrepBoundedDraftFaces.XMax);++ Assert.True(result.IsSuccess);+ Assert.Equal(6, result.Value.Topology.Faces.Count());++ var topFace = result.Value.Topology.Faces+ .Select(face => (face, surface: result.Value.Geometry.GetSurface(result.Value.Bindings.FaceBindings.Single(binding => binding.FaceId == face.Id).SurfaceGeometryId)))+ .Single(pair => pair.surface.Kind == SurfaceGeometryKind.Plane+ && ToleranceMath.AlmostEqual(pair.surface.Plane!.Value.Normal.Z, 1d, ToleranceContext.Default));++ Assert.NotNull(topFace.face);+ }++ [Fact]+ public void DraftAxisAlignedBoxSideFaces_Rejects_TooLargeAngle()+ {+ var box = new AxisAlignedBoxExtents(-5d, 5d, -5d, 5d, 0d, 50d);++ var result = BrepBoundedDraft.DraftAxisAlignedBoxSideFaces(+ box,+ draftAngleDegrees: 20d,+ faces: BrepBoundedDraftFaces.XMin | BrepBoundedDraftFaces.XMax | BrepBoundedDraftFaces.YMin | BrepBoundedDraftFaces.YMax);++ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.Contains("collapses top profile", StringComparison.Ordinal));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepBoundedDraft.cs b/Aetheris.Kernel.Core/Brep/Features/BrepBoundedDraft.csnew file mode 100644index 00000000..9a6dbf83--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepBoundedDraft.cs@@ -0,0 +1,231 @@+using Aetheris.Kernel.Core.Brep.Boolean;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++[Flags]+public enum BrepBoundedDraftFaces+{+ None = 0,+ XMin = 1,+ XMax = 2,+ YMin = 4,+ YMax = 8+}++/// <summary>+/// M4 bounded manufacturing draft for axis-aligned box roots only.+/// Supports planar side-face draft against world +Z pull with a uniform inward angle.+/// </summary>+public static class BrepBoundedDraft+{+ public static KernelResult<BrepBody> DraftAxisAlignedBoxSideFaces(+ AxisAlignedBoxExtents box,+ double draftAngleDegrees,+ BrepBoundedDraftFaces faces)+ {+ var diagnostics = new List<KernelDiagnostic>();++ if (faces == BrepBoundedDraftFaces.None)+ {+ diagnostics.Add(Failure("Bounded draft requires at least one explicit side face in {x_min,x_max,y_min,y_max}.", "firmament.draft-bounded"));+ return KernelResult<BrepBody>.Failure(diagnostics);+ }++ if (!double.IsFinite(draftAngleDegrees) || draftAngleDegrees <= 0d)+ {+ diagnostics.Add(Failure("Bounded draft angle must be a finite value greater than 0 degrees.", "firmament.draft-bounded"));+ return KernelResult<BrepBody>.Failure(diagnostics);+ }++ var height = box.MaxZ - box.MinZ;+ if (!double.IsFinite(height) || height <= 0d)+ {+ diagnostics.Add(Failure("Bounded draft source box must have positive height.", "firmament.draft-bounded"));+ return KernelResult<BrepBody>.Failure(diagnostics);+ }++ var radians = draftAngleDegrees * (System.Math.PI / 180d);+ var inset = System.Math.Tan(radians) * height;++ var topMinX = box.MinX + (faces.HasFlag(BrepBoundedDraftFaces.XMin) ? inset : 0d);+ var topMaxX = box.MaxX - (faces.HasFlag(BrepBoundedDraftFaces.XMax) ? inset : 0d);+ var topMinY = box.MinY + (faces.HasFlag(BrepBoundedDraftFaces.YMin) ? inset : 0d);+ var topMaxY = box.MaxY - (faces.HasFlag(BrepBoundedDraftFaces.YMax) ? inset : 0d);++ if (topMaxX <= topMinX || topMaxY <= topMinY)+ {+ diagnostics.Add(Failure("Bounded draft collapses top profile (angle too large for selected faces and box height).", "firmament.draft-bounded"));+ return KernelResult<BrepBody>.Failure(diagnostics);+ }++ return CreateLoftedRectangularPrism(+ box.MinX,+ box.MaxX,+ box.MinY,+ box.MaxY,+ box.MinZ,+ topMinX,+ topMaxX,+ topMinY,+ topMaxY,+ box.MaxZ);+ }++ private static KernelResult<BrepBody> CreateLoftedRectangularPrism(+ double bottomMinX,+ double bottomMaxX,+ double bottomMinY,+ double bottomMaxY,+ double bottomZ,+ double topMinX,+ double topMaxX,+ double topMinY,+ double topMaxY,+ double topZ)+ {+ var builder = new TopologyBuilder();++ var bottomVertices = new VertexId[4];+ var topVertices = new VertexId[4];+ for (var i = 0; i < 4; i++)+ {+ bottomVertices[i] = builder.AddVertex();+ topVertices[i] = builder.AddVertex();+ }++ var bottomEdges = new EdgeId[4];+ var topEdges = new EdgeId[4];+ var sideEdges = new EdgeId[4];+ for (var i = 0; i < 4; i++)+ {+ var next = (i + 1) % 4;+ bottomEdges[i] = builder.AddEdge(bottomVertices[i], bottomVertices[next]);+ topEdges[i] = builder.AddEdge(topVertices[i], topVertices[next]);+ sideEdges[i] = builder.AddEdge(bottomVertices[i], topVertices[i]);+ }++ var faces = new List<FaceId>(6)+ {+ AddFaceWithLoop(builder, bottomEdges.Select(EdgeUse.Forward).ToArray()),+ AddFaceWithLoop(builder, topEdges.Select(EdgeUse.Reversed).ToArray())+ };++ for (var i = 0; i < 4; i++)+ {+ var next = (i + 1) % 4;+ faces.Add(AddFaceWithLoop(+ builder,+ [+ EdgeUse.Forward(bottomEdges[i]),+ EdgeUse.Forward(sideEdges[next]),+ EdgeUse.Reversed(topEdges[i]),+ EdgeUse.Reversed(sideEdges[i])+ ]));+ }++ var shell = builder.AddShell(faces);+ builder.AddBody([shell]);++ var b = new[]+ {+ new Point3D(bottomMinX, bottomMinY, bottomZ),+ new Point3D(bottomMaxX, bottomMinY, bottomZ),+ new Point3D(bottomMaxX, bottomMaxY, bottomZ),+ new Point3D(bottomMinX, bottomMaxY, bottomZ)+ };++ var t = new[]+ {+ new Point3D(topMinX, topMinY, topZ),+ new Point3D(topMaxX, topMinY, topZ),+ new Point3D(topMaxX, topMaxY, topZ),+ new Point3D(topMinX, topMaxY, topZ)+ };++ var geometry = new BrepGeometryStore();+ var curveId = 1;+ for (var i = 0; i < 4; i++)+ {+ var next = (i + 1) % 4;+ geometry.AddCurve(new CurveGeometryId(curveId++), CurveGeometry.FromLine(new Line3Curve(b[i], Direction3D.Create(b[next] - b[i]))));+ }++ for (var i = 0; i < 4; i++)+ {+ var next = (i + 1) % 4;+ geometry.AddCurve(new CurveGeometryId(curveId++), CurveGeometry.FromLine(new Line3Curve(t[i], Direction3D.Create(t[next] - t[i]))));+ }++ for (var i = 0; i < 4; i++)+ {+ geometry.AddCurve(new CurveGeometryId(curveId++), CurveGeometry.FromLine(new Line3Curve(b[i], Direction3D.Create(t[i] - b[i]))));+ }++ geometry.AddSurface(new SurfaceGeometryId(1), SurfaceGeometry.FromPlane(new PlaneSurface(b[0], Direction3D.Create(new Vector3D(0d, 0d, -1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d)))));+ geometry.AddSurface(new SurfaceGeometryId(2), SurfaceGeometry.FromPlane(new PlaneSurface(t[0], Direction3D.Create(new Vector3D(0d, 0d, 1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d)))));++ for (var i = 0; i < 4; i++)+ {+ var next = (i + 1) % 4;+ var edgeDir = t[next] - t[i];+ var sideDir = t[i] - b[i];+ var normal = Direction3D.Create(edgeDir.Cross(sideDir));+ geometry.AddSurface(new SurfaceGeometryId(3 + i), SurfaceGeometry.FromPlane(new PlaneSurface(b[i], normal, Direction3D.Create(edgeDir))));+ }++ var bindings = new BrepBindingModel();+ for (var i = 0; i < 4; i++)+ {+ bindings.AddEdgeBinding(new EdgeGeometryBinding(bottomEdges[i], new CurveGeometryId(i + 1), new ParameterInterval(0d, (b[(i + 1) % 4] - b[i]).Length)));+ bindings.AddEdgeBinding(new EdgeGeometryBinding(topEdges[i], new CurveGeometryId(5 + i), new ParameterInterval(0d, (t[(i + 1) % 4] - t[i]).Length)));+ bindings.AddEdgeBinding(new EdgeGeometryBinding(sideEdges[i], new CurveGeometryId(9 + i), new ParameterInterval(0d, (t[i] - b[i]).Length)));+ }++ for (var i = 0; i < faces.Count; i++)+ {+ bindings.AddFaceBinding(new FaceGeometryBinding(faces[i], new SurfaceGeometryId(i + 1)));+ }++ var body = new BrepBody(builder.Model, geometry, bindings);+ var validation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);+ return validation.IsSuccess+ ? KernelResult<BrepBody>.Success(body, validation.Diagnostics)+ : KernelResult<BrepBody>.Failure(validation.Diagnostics);+ }++ private static FaceId AddFaceWithLoop(TopologyBuilder builder, IReadOnlyList<EdgeUse> edgeUses)+ {+ var loopId = builder.AllocateLoopId();+ var coedgeIds = new CoedgeId[edgeUses.Count];+ for (var i = 0; i < edgeUses.Count; i++)+ {+ coedgeIds[i] = builder.AllocateCoedgeId();+ }++ for (var i = 0; i < edgeUses.Count; i++)+ {+ var next = coedgeIds[(i + 1) % edgeUses.Count];+ var prev = coedgeIds[(i + edgeUses.Count - 1) % edgeUses.Count];+ builder.AddCoedge(new Coedge(coedgeIds[i], edgeUses[i].EdgeId, loopId, next, prev, edgeUses[i].IsReversed));+ }++ builder.AddLoop(new Loop(loopId, coedgeIds));+ return builder.AddFace([loopId]);+ }++ private static KernelDiagnostic Failure(string message, string source)+ => new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, Source: source);++ private readonly record struct EdgeUse(EdgeId EdgeId, bool IsReversed)+ {+ public static EdgeUse Forward(EdgeId edgeId) => new(edgeId, false);+ public static EdgeUse Reversed(EdgeId edgeId) => new(edgeId, true);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanRequiredFieldValidationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanRequiredFieldValidationTests.csindex 17c6b92d..fc52a38d 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanRequiredFieldValidationTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanRequiredFieldValidationTests.cs@@ -110,6 +110,66 @@ public sealed class FirmamentBooleanRequiredFieldValidationTests1""");+ [Fact]+ public void Compiler_Accepts_ValidBoundedDraftShape() =>+ AssertValidBooleanOp("""+ firmament:+ version: 1++ model:+ name: demo+ units: mm++ ops[2]:+ -+ op: box+ id: base+ size[3]:+ 40+ 20+ 10+ -+ op: draft+ id: drafted+ from: base+ pull: +z+ angle: 2+ faces[2]:+ x_min+ x_max+ """);++ [Fact]+ public void Compiler_Rejects_Draft_UnsupportedPullDirection() =>+ AssertBooleanFailure(+ """+ firmament:+ version: 1++ model:+ name: demo+ units: mm++ ops[2]:+ -+ op: box+ id: base+ size[3]:+ 20+ 20+ 20+ -+ op: draft+ id: drafted+ from: base+ pull: +x+ angle: 2+ faces[1]:+ x_min+ """,+ FirmamentDiagnosticCodes.BooleanInvalidFieldValue,+ "Boolean op 'draft' at index 1 has invalid field 'pull'; expected '+z' for bounded M4 draft pull direction.");+[Fact]public void Compiler_Allows_ValidTorusBooleanToolShape_Past_FieldValidation(){diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.csindex 3ff7fd5d..81a2375d 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs@@ -162,6 +162,18 @@ public sealed class FirmamentBuildAndExportTests"intersect");}+ [Fact]+ public void Run_M4DraftBoxBasicExample_Writes_Default_Export_Artifact()+ {+ AssertExampleBuildAndExport(+ "testdata/firmament/examples/m4_draft_box_basic.firmament",+ "m4_draft_box_basic.step",+ "drafted",+ 1,+ "boolean",+ "draft");+ }+[Fact]public void Run_BooleanBoxCylinderHoleExample_Writes_Default_Export_Artifact(){diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.csindex 76d5fc01..ba227e32 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentPrimitiveExecutionTests.cs@@ -256,6 +256,29 @@ public sealed class FirmamentPrimitiveExecutionTestsAssert.NotEmpty(executedBoolean.Body.Topology.Faces);}+ [Fact]+ public void Compile_Executes_BoundedDraft_On_BoxRoot_Into_Real_Body()+ {+ var result = CompileFixture("testdata/firmament/fixtures/m4-valid-draft-box-exec.firmament");++ Assert.True(result.Compilation.IsSuccess);+ var executedBoolean = Assert.Single(result.Compilation.Value.PrimitiveExecutionResult!.ExecutedBooleans);+ Assert.Equal("drafted", executedBoolean.FeatureId);+ Assert.Equal(FirmamentLoweredBooleanKind.Draft, executedBoolean.Kind);+ Assert.Equal(6, executedBoolean.Body.Topology.Faces.Count());+ Assert.NotEmpty(executedBoolean.Body.Topology.Bodies);+ }++ [Fact]+ public void Compile_Rejects_BoundedDraft_On_UnsupportedRoot()+ {+ var result = CompileFixture("testdata/firmament/fixtures/m4-invalid-draft-cylinder-root.firmament");++ Assert.False(result.Compilation.IsSuccess);+ Assert.Contains(result.Compilation.Diagnostics, diagnostic =>+ diagnostic.Message.Contains("Bounded draft requires a box-root or recognized orthogonal additive root input", StringComparison.Ordinal));+ }+[Fact]public void Compile_Mixed_Document_With_Unsupported_Boolean_Fails_Before_Publishing_Success_Artifact(){diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.csindex 3bdf4d8f..d86c9d25 100644--- a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs@@ -54,6 +54,26 @@ internal static class FirmamentPrimitiveExecutorcontinue;}+ if (boolean.Kind == FirmamentLoweredBooleanKind.Draft)+ {+ var draftResult = ExecuteBoundedDraftOnRecognizedOrthogonalRoot(boolean, baseBody, featureGraphStates);+ if (!draftResult.IsSuccess)+ {+ return KernelResult<FirmamentPrimitiveExecutionResult>.Failure(+ [+ CreateBooleanExecutionFailureDiagnostic(boolean),+ .. WithBooleanContext(boolean, draftResult.Diagnostics)+ ]);+ }++ var draftedBody = draftResult.Value;+ executedBooleans.Add(new FirmamentExecutedBoolean(boolean.OpIndex, boolean.FeatureId, boolean.Kind, draftedBody));+ publishedBodiesByFeatureId[boolean.FeatureId] = draftedBody;+ booleanExecutionBodiesByFeatureId[boolean.FeatureId] = draftedBody;+ featureGraphStates[boolean.FeatureId] = FirmamentSafeSubtractFeatureGraphState.Other;+ continue;+ }+if (IsPatternGeneratedFeature(boolean.FeatureId)){var patternToolResult = FirmamentBooleanToolBodyFactory.CreateBody(boolean.Tool);@@ -550,6 +570,156 @@ internal static class FirmamentPrimitiveExecutor]);}+ private static KernelResult<BrepBody> ExecuteBoundedDraftOnRecognizedOrthogonalRoot(+ FirmamentLoweredBoolean boolean,+ BrepBody baseBody,+ IReadOnlyDictionary<string, FirmamentSafeSubtractFeatureGraphState> featureGraphStates)+ {+ if (!featureGraphStates.TryGetValue(boolean.PrimaryReferenceFeatureId, out var sourceState)+ || sourceState is not (FirmamentSafeSubtractFeatureGraphState.BoxRoot+ or FirmamentSafeSubtractFeatureGraphState.BoundedOrthogonalAdditiveSafeRoot+ or FirmamentSafeSubtractFeatureGraphState.BoundedOrthogonalAdditiveOutsideSafeRoot))+ {+ return KernelResult<BrepBody>.Failure([+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"Bounded draft requires a box-root or recognized orthogonal additive root input; '{boolean.PrimaryReferenceFeatureId}' is not eligible.",+ Source: "firmament.draft-bounded")+ ]);+ }++ if (!BrepBooleanBoxRecognition.TryRecognizeAxisAlignedBox(baseBody, ToleranceContext.Default, out var box, out var reason))+ {+ return KernelResult<BrepBody>.Failure([+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"Bounded draft requires an axis-aligned box-like source body; failed to recognize source body ({reason}).",+ Source: "firmament.draft-bounded")+ ]);+ }++ if (!boolean.Tool.RawFields.TryGetValue("pull", out var pullRaw)+ || !string.Equals(UnquoteScalar(pullRaw), "+z", StringComparison.Ordinal))+ {+ return KernelResult<BrepBody>.Failure([+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ "Bounded draft supports principal pull direction '+z' only.",+ Source: "firmament.draft-bounded")+ ]);+ }++ if (!boolean.Tool.RawFields.TryGetValue("angle", out var angleRaw)+ || !FirmamentPrimitiveToolParsing.TryParseScalar(angleRaw, out var angleDegrees))+ {+ return KernelResult<BrepBody>.Failure([+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ "Bounded draft execution expected validated 'angle' scalar.",+ Source: "firmament.draft-bounded")+ ]);+ }++ if (!TryParseDraftFaces(boolean.Tool.RawFields, out var faces, out var faceError))+ {+ return KernelResult<BrepBody>.Failure([+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"Bounded draft faces are invalid: {faceError}.",+ Source: "firmament.draft-bounded")+ ]);+ }++ return BrepBoundedDraft.DraftAxisAlignedBoxSideFaces(box, angleDegrees, faces);+ }++ private static bool TryParseDraftFaces(+ IReadOnlyDictionary<string, string> fields,+ out BrepBoundedDraftFaces faces,+ out string error)+ {+ faces = BrepBoundedDraftFaces.None;+ error = string.Empty;++ if (!fields.TryGetValue("faces", out var facesRaw))+ {+ error = "missing 'faces' field";+ return false;+ }++ try+ {+ using var doc = System.Text.Json.JsonDocument.Parse(facesRaw);+ if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Array)+ {+ error = "expected array";+ return false;+ }++ foreach (var element in doc.RootElement.EnumerateArray())+ {+ if (element.ValueKind != System.Text.Json.JsonValueKind.String)+ {+ error = "all face entries must be strings";+ return false;+ }++ var token = element.GetString();+ faces |= token switch+ {+ "x_min" => BrepBoundedDraftFaces.XMin,+ "x_max" => BrepBoundedDraftFaces.XMax,+ "y_min" => BrepBoundedDraftFaces.YMin,+ "y_max" => BrepBoundedDraftFaces.YMax,+ _ => BrepBoundedDraftFaces.None+ };+ }+ }+ catch (System.Text.Json.JsonException)+ {+ var trimmed = facesRaw.Trim();+ if (!trimmed.StartsWith("[", StringComparison.Ordinal) || !trimmed.EndsWith("]", StringComparison.Ordinal))+ {+ error = "faces must be valid array syntax";+ return false;+ }++ foreach (var token in trimmed[1..^1].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))+ {+ var parsedToken = token.Trim().Trim('"');+ faces |= parsedToken switch+ {+ "x_min" => BrepBoundedDraftFaces.XMin,+ "x_max" => BrepBoundedDraftFaces.XMax,+ "y_min" => BrepBoundedDraftFaces.YMin,+ "y_max" => BrepBoundedDraftFaces.YMax,+ _ => BrepBoundedDraftFaces.None+ };+ }+ }++ if (faces == BrepBoundedDraftFaces.None)+ {+ error = "no supported side faces were selected";+ return false;+ }++ return true;+ }++ private static string UnquoteScalar(string raw)+ {+ var trimmed = raw.Trim();+ return trimmed.Length >= 2 && trimmed.StartsWith('"') && trimmed.EndsWith('"')+ ? trimmed[1..^1]+ : trimmed;+ }+private static BrepBody TranslateBody(BrepBody body, Vector3D translation){if (translation == Vector3D.Zero) return body;@@ -612,4 +782,15 @@ internal static class FirmamentPrimitiveToolParsingreturn double.Parse(trimmed, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);}++ public static bool TryParseScalar(string raw, out double value)+ {+ var trimmed = raw.Trim();+ if (trimmed.StartsWith("\"", StringComparison.Ordinal) && trimmed.EndsWith("\"", StringComparison.Ordinal) && trimmed.Length >= 2)+ {+ trimmed = trimmed[1..^1];+ }++ return double.TryParse(trimmed, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out value);+ }}diff --git a/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.cs b/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.csindex 2f0f8f2a..878351bf 100644--- a/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.cs+++ b/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.cs@@ -157,6 +157,13 @@ internal static class FirmamentCanonicalFormatterEmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "left");EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "with");break;+ case FirmamentKnownOpKind.Draft:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "from");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "pull");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "angle");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "faces");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "direction");+ break;case FirmamentKnownOpKind.ExpectExists:EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "target");break;diff --git a/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLowerer.cs b/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLowerer.csindex 50674bd4..ef546dcb 100644--- a/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLowerer.cs+++ b/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLowerer.cs@@ -120,6 +120,10 @@ internal static class FirmamentPrimitiveLowererloweredBooleans.Add(LowerBoolean(index, entry, FirmamentLoweredBooleanKind.Intersect, "left"));break;+ case FirmamentKnownOpKind.Draft:+ loweredBooleans.Add(LowerDraft(index, entry));+ break;+default:skippedOps.Add(new FirmamentLoweringSkippedOp(OpIndex: index,@@ -177,6 +181,18 @@ internal static class FirmamentPrimitiveLowererPlacement: LowerPlacement(entry.Placement));}+ private static FirmamentLoweredBoolean LowerDraft(int opIndex, FirmamentParsedOpEntry entry)+ {+ return new FirmamentLoweredBoolean(+ OpIndex: opIndex,+ FeatureId: entry.RawFields["id"],+ Kind: FirmamentLoweredBooleanKind.Draft,+ PrimaryReferenceField: "from",+ PrimaryReferenceFeatureId: entry.RawFields["from"],+ Tool: new FirmamentLoweredToolOp("draft", entry.RawFields, string.Empty),+ Placement: null);+ }+private static FirmamentLoweredToolOp ParseTool(string rawWith){var trimmed = rawWith.Trim();diff --git a/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLoweringPlan.cs b/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLoweringPlan.csindex 92747509..3cb267d9 100644--- a/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLoweringPlan.cs+++ b/Aetheris.Kernel.Firmament/Lowering/FirmamentPrimitiveLoweringPlan.cs@@ -43,7 +43,8 @@ public enum FirmamentLoweredBooleanKind{Add,Subtract,- Intersect+ Intersect,+ Draft}public enum FirmamentLoweredPrimitiveKinddiff --git a/Aetheris.Kernel.Firmament/ParsedModel/FirmamentKnownOpKind.cs b/Aetheris.Kernel.Firmament/ParsedModel/FirmamentKnownOpKind.csindex 853d1794..618cd666 100644--- a/Aetheris.Kernel.Firmament/ParsedModel/FirmamentKnownOpKind.cs+++ b/Aetheris.Kernel.Firmament/ParsedModel/FirmamentKnownOpKind.cs@@ -13,6 +13,7 @@ public enum FirmamentKnownOpKindAdd,Subtract,Intersect,+ Draft,ExpectExists,ExpectSelectable,ExpectManifold,@@ -37,6 +38,7 @@ internal static class FirmamentKnownOpKinds["add"] = FirmamentKnownOpKind.Add,["subtract"] = FirmamentKnownOpKind.Subtract,["intersect"] = FirmamentKnownOpKind.Intersect,+ ["draft"] = FirmamentKnownOpKind.Draft,["expect_exists"] = FirmamentKnownOpKind.ExpectExists,["expect_selectable"] = FirmamentKnownOpKind.ExpectSelectable,["expect_manifold"] = FirmamentKnownOpKind.ExpectManifold,@@ -62,6 +64,7 @@ internal static class FirmamentKnownOpKindsFirmamentKnownOpKind.Add => FirmamentOpFamily.Boolean,FirmamentKnownOpKind.Subtract => FirmamentOpFamily.Boolean,FirmamentKnownOpKind.Intersect => FirmamentOpFamily.Boolean,+ FirmamentKnownOpKind.Draft => FirmamentOpFamily.Boolean,FirmamentKnownOpKind.ExpectExists => FirmamentOpFamily.Validation,FirmamentKnownOpKind.ExpectSelectable => FirmamentOpFamily.Validation,FirmamentKnownOpKind.ExpectManifold => FirmamentOpFamily.Validation,diff --git a/Aetheris.Kernel.Firmament/Validation/FirmamentBooleanRequiredFieldValidator.cs b/Aetheris.Kernel.Firmament/Validation/FirmamentBooleanRequiredFieldValidator.csindex 23e046d0..8dee0765 100644--- a/Aetheris.Kernel.Firmament/Validation/FirmamentBooleanRequiredFieldValidator.cs+++ b/Aetheris.Kernel.Firmament/Validation/FirmamentBooleanRequiredFieldValidator.cs@@ -28,6 +28,7 @@ internal static class FirmamentBooleanRequiredFieldValidatorFirmamentKnownOpKind.Add => ValidateBooleanEntry(entry, index, targetFieldName: "to"),FirmamentKnownOpKind.Subtract => ValidateBooleanEntry(entry, index, targetFieldName: "from"),FirmamentKnownOpKind.Intersect => ValidateBooleanEntry(entry, index, targetFieldName: "left"),+ FirmamentKnownOpKind.Draft => ValidateDraftEntry(entry, index),_ => KernelResult<bool>.Success(true)};@@ -76,6 +77,66 @@ internal static class FirmamentBooleanRequiredFieldValidatorreturn ValidatePlacement(entry, opIndex);}+ private static KernelResult<bool> ValidateDraftEntry(FirmamentParsedOpEntry entry, int opIndex)+ {+ if (!TryGetRequiredNonEmptyScalar(entry, "id", opIndex, out var missingOrTypeDiagnostic))+ {+ return KernelResult<bool>.Failure([missingOrTypeDiagnostic!]);+ }++ if (!TryGetRequiredNonEmptyScalar(entry, "from", opIndex, out missingOrTypeDiagnostic))+ {+ return KernelResult<bool>.Failure([missingOrTypeDiagnostic!]);+ }++ if (!entry.RawFields.TryGetValue("pull", out var pullRaw) || string.IsNullOrWhiteSpace(pullRaw))+ {+ return MissingField("pull", opIndex, entry.OpName);+ }++ if (!string.Equals(Unquote(pullRaw), "+z", StringComparison.Ordinal))+ {+ return InvalidFieldValue("pull", opIndex, entry.OpName, "expected '+z' for bounded M4 draft pull direction");+ }++ if (!entry.RawFields.TryGetValue("angle", out var angleRaw) || string.IsNullOrWhiteSpace(angleRaw))+ {+ return MissingField("angle", opIndex, entry.OpName);+ }++ if (!TryParseNumeric(angleRaw, out var angle) || angle <= 0d || angle >= 10d)+ {+ return InvalidFieldValue("angle", opIndex, entry.OpName, "expected a numeric value in (0, 10) degrees for bounded M4 draft");+ }++ if (!entry.RawFields.TryGetValue("faces", out var facesRaw) || string.IsNullOrWhiteSpace(facesRaw))+ {+ return MissingField("faces", opIndex, entry.OpName);+ }++ if (!TryParseFaceTokens(facesRaw, out var tokens) || tokens.Count == 0)+ {+ return InvalidFieldTypeOrShape("faces", opIndex, entry.OpName, "expected a non-empty string array of side face tokens");+ }++ foreach (var token in tokens)+ {+ if (token is not ("x_min" or "x_max" or "y_min" or "y_max"))+ {+ return InvalidFieldValue("faces", opIndex, entry.OpName, "supported tokens are x_min, x_max, y_min, y_max only");+ }+ }++ if (entry.RawFields.TryGetValue("direction", out var directionRaw)+ && !string.IsNullOrWhiteSpace(directionRaw)+ && !string.Equals(Unquote(directionRaw), "inward", StringComparison.Ordinal))+ {+ return InvalidFieldValue("direction", opIndex, entry.OpName, "expected 'inward' for bounded M4 draft");+ }++ return KernelResult<bool>.Success(true);+ }+private static KernelResult<bool> ValidateNestedPrimitiveToolFields(FirmamentParsedOpEntry entry, int opIndex, string withOpRaw, IReadOnlyDictionary<string, string> withFields){if (string.Equals(withOpRaw, "box", StringComparison.Ordinal))@@ -694,6 +755,68 @@ internal static class FirmamentBooleanRequiredFieldValidator}}+ private static bool TryParseFaceTokens(string raw, out IReadOnlyList<string> tokens)+ {+ tokens = Array.Empty<string>();+ var trimmed = raw.Trim();+ if (!trimmed.StartsWith("[", StringComparison.Ordinal) || !trimmed.EndsWith("]", StringComparison.Ordinal))+ {+ return false;+ }++ try+ {+ using var doc = JsonDocument.Parse(trimmed);+ if (doc.RootElement.ValueKind != JsonValueKind.Array)+ {+ return false;+ }++ var parsed = new List<string>();+ foreach (var element in doc.RootElement.EnumerateArray())+ {+ if (element.ValueKind != JsonValueKind.String)+ {+ return false;+ }++ var token = element.GetString();+ if (string.IsNullOrWhiteSpace(token))+ {+ return false;+ }++ parsed.Add(token);+ }++ tokens = parsed;+ return true;+ }+ catch (JsonException)+ {+ var content = trimmed[1..^1];+ var split = content.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)+ .Select(token => token.Trim().Trim('"'))+ .Where(token => !string.IsNullOrWhiteSpace(token))+ .ToArray();+ if (split.Length == 0)+ {+ return false;+ }++ tokens = split;+ return true;+ }+ }++ private static string Unquote(string raw)+ {+ var trimmed = raw.Trim();+ return trimmed.Length >= 2 && trimmed.StartsWith('"') && trimmed.EndsWith('"')+ ? trimmed[1..^1]+ : trimmed;+ }+private static KernelResult<bool> MissingField(string fieldName, int opIndex, string opName) =>KernelResult<bool>.Failure([MissingFieldDiagnostic(fieldName, opIndex, opName)]);diff --git a/Aetheris.Kernel.Firmament/Validation/FirmamentDocumentCoherenceValidator.cs b/Aetheris.Kernel.Firmament/Validation/FirmamentDocumentCoherenceValidator.csindex b5ff0486..2f505857 100644--- a/Aetheris.Kernel.Firmament/Validation/FirmamentDocumentCoherenceValidator.cs+++ b/Aetheris.Kernel.Firmament/Validation/FirmamentDocumentCoherenceValidator.cs@@ -685,6 +685,7 @@ internal static class FirmamentDocumentCoherenceValidatorFirmamentKnownOpKind.Add => "to",FirmamentKnownOpKind.Subtract => "from",FirmamentKnownOpKind.Intersect => "left",+ FirmamentKnownOpKind.Draft => "from",_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Boolean op kind must map to a feature reference field.")};diff --git a/Aetheris.Kernel.Firmament/Validation/FirmamentSelectorContracts.cs b/Aetheris.Kernel.Firmament/Validation/FirmamentSelectorContracts.csindex aec8db43..b5fec60f 100644--- a/Aetheris.Kernel.Firmament/Validation/FirmamentSelectorContracts.cs+++ b/Aetheris.Kernel.Firmament/Validation/FirmamentSelectorContracts.cs@@ -87,6 +87,7 @@ internal static class FirmamentSelectorContractscase FirmamentKnownOpKind.Add:case FirmamentKnownOpKind.Subtract:case FirmamentKnownOpKind.Intersect:+ case FirmamentKnownOpKind.Draft:allowedPorts = BooleanAllowedPorts;return true;default:@@ -134,6 +135,7 @@ internal static class FirmamentSelectorContractscase FirmamentKnownOpKind.Add:case FirmamentKnownOpKind.Subtract:case FirmamentKnownOpKind.Intersect:+ case FirmamentKnownOpKind.Draft:contracts = BooleanPorts;return true;default:diff --git a/testdata/firmament/examples/m4_draft_box_basic.firmament b/testdata/firmament/examples/m4_draft_box_basic.firmamentnew file mode 100644index 00000000..3da776cf--- /dev/null+++ b/testdata/firmament/examples/m4_draft_box_basic.firmament@@ -0,0 +1,26 @@+firmament:+ version: 1++model:+ name: m4-draft-box-basic+ units: mm++ops[2]:+ -+ op: box+ id: base+ size[3]:+ 40+ 30+ 20+ -+ op: draft+ id: drafted+ from: base+ pull: +z+ angle: 2+ faces[4]:+ x_min+ x_max+ y_min+ y_maxdiff --git a/testdata/firmament/fixtures/m4-invalid-draft-cylinder-root.firmament b/testdata/firmament/fixtures/m4-invalid-draft-cylinder-root.firmamentnew file mode 100644index 00000000..1b25c67f--- /dev/null+++ b/testdata/firmament/fixtures/m4-invalid-draft-cylinder-root.firmament@@ -0,0 +1,21 @@+firmament:+ version: 1++model:+ name: m4-draft-bad-root+ units: mm++ops[2]:+ -+ op: cylinder+ id: base+ radius: 10+ height: 30+ -+ op: draft+ id: drafted+ from: base+ pull: +z+ angle: 2+ faces[1]:+ x_mindiff --git a/testdata/firmament/fixtures/m4-valid-draft-box-exec.firmament b/testdata/firmament/fixtures/m4-valid-draft-box-exec.firmamentnew file mode 100644index 00000000..20d6f72f--- /dev/null+++ b/testdata/firmament/fixtures/m4-valid-draft-box-exec.firmament@@ -0,0 +1,26 @@+firmament:+ version: 1++model:+ name: m4-draft-box+ units: mm++ops[2]:+ -+ op: box+ id: base+ size[3]:+ 40+ 30+ 20+ -+ op: draft+ id: drafted+ from: base+ pull: +z+ angle: 2+ faces[4]:+ x_min+ x_max+ y_min+ y_max