Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Build holes that break out through a plate edge; explain tangency
Yuechen Li891c24dd59e2
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanTests.csindex 3c790747..489180d4 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanTests.cs@@ -826,7 +826,7 @@ public sealed class BrepBooleanTestsvar diagnostic = Assert.Single(result.Diagnostics);Assert.Equal(KernelDiagnosticCode.NotImplemented, diagnostic.Code);Assert.Equal("BrepBoolean.AnalyticHole.TangentContact", diagnostic.Source);- Assert.Contains("tangent to a box side wall", diagnostic.Message, StringComparison.Ordinal);+ Assert.Contains("side wall, which would leave a wall of zero thickness", diagnostic.Message, StringComparison.Ordinal);}[Fact]@@ -1040,7 +1040,7 @@ public sealed class BrepBooleanTestsvar diagnostic = Assert.Single(result.Diagnostics);Assert.Equal(KernelDiagnosticCode.NotImplemented, diagnostic.Code);Assert.Equal("BrepBoolean.AnalyticHole.RadiusExceedsBoundary", diagnostic.Source);- Assert.Equal("Boolean Subtract has top boundary circle extending outside the box side-wall footprint. Reduce the boundary radius or move the cone center farther inside the box XY boundary.", diagnostic.Message);+ Assert.Equal("Boolean Subtract has top boundary circle (centre (13.7, 0), radius 6.4) extending outside the box side-wall footprint. This analytic-hole route builds only holes that stay inside the box; reduce the radius or move the centre inward.", diagnostic.Message);}[Fact]@@ -1055,7 +1055,7 @@ public sealed class BrepBooleanTestsvar diagnostic = Assert.Single(result.Diagnostics);Assert.Equal(KernelDiagnosticCode.NotImplemented, diagnostic.Code);Assert.Equal("BrepBoolean.AnalyticHole.TangentContact", diagnostic.Source);- Assert.Equal("Boolean Subtract has top boundary circle tangent to a box side wall; tangent analytic-hole cases are rejected to avoid zero-thickness geometry. Move the cone inward or reduce the boundary radius at that plane.", diagnostic.Message);+ Assert.Equal("Boolean Subtract has top boundary circle (centre (13.6, 0), radius 6.4) exactly tangent to the box's +X side wall, which would leave a wall of zero thickness along a line - neither machinable nor a manifold solid. Move the hole so it either leaves a wall of positive thickness or clearly cuts through the +X wall.", diagnostic.Message);}[Fact]diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanCylinderRecognition.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanCylinderRecognition.csindex e02ff172..b04cce4d 100644--- a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanCylinderRecognition.cs+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanCylinderRecognition.cs@@ -445,7 +445,13 @@ public static class BrepBooleanCylinderRecognition|| ToleranceMath.AlmostEqual(maxFootprintY, box.MaxY, tolerance);if (tangentContact){- diagnostic = CreateTangentContactDiagnostic(diagnosticContext, $"has {circleLabel} tangent to a box side wall; tangent analytic-hole cases are rejected to avoid zero-thickness geometry. Move the cone inward or reduce the boundary radius at that plane.");+ var wall = ToleranceMath.AlmostEqual(maxFootprintX, box.MaxX, tolerance) ? "+X"+ : ToleranceMath.AlmostEqual(minFootprintX, box.MinX, tolerance) ? "-X"+ : ToleranceMath.AlmostEqual(maxFootprintY, box.MaxY, tolerance) ? "+Y" : "-Y";+ diagnostic = CreateTangentContactDiagnostic(diagnosticContext,+ $"has {circleLabel} (centre ({centerX:0.######}, {centerY:0.######}), radius {radius:0.######}) exactly tangent to the box's {wall} side wall, "+ + "which would leave a wall of zero thickness along a line - neither machinable nor a manifold solid. "+ + $"Move the hole so it either leaves a wall of positive thickness or clearly cuts through the {wall} wall.");return false;}@@ -454,7 +460,9 @@ public static class BrepBooleanCylinderRecognition|| minFootprintY < (box.MinY - tolerance.Linear)|| maxFootprintY > (box.MaxY + tolerance.Linear)){- diagnostic = CreateRadiusExceedsBoundaryDiagnostic(diagnosticContext, $"has {circleLabel} extending outside the box side-wall footprint. Reduce the boundary radius or move the cone center farther inside the box XY boundary.");+ diagnostic = CreateRadiusExceedsBoundaryDiagnostic(diagnosticContext,+ $"has {circleLabel} (centre ({centerX:0.######}, {centerY:0.######}), radius {radius:0.######}) extending outside the box side-wall footprint. "+ + "This analytic-hole route builds only holes that stay inside the box; reduce the radius or move the centre inward.");return false;}diff --git a/Aetheris.Kernel.Firmament.Tests/EdgeHoleBreakoutTests.cs b/Aetheris.Kernel.Firmament.Tests/EdgeHoleBreakoutTests.csnew file mode 100644index 00000000..94c8fc91--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/EdgeHoleBreakoutTests.cs@@ -0,0 +1,159 @@+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++/// <summary>+/// A 50 x 30 x 12 plate with a 12 mm through hole slid toward the +X edge. The sweep walks through every state a boolean+/// kernel finds hard - a thin wall, a 0.1 mm sliver, exact tangency, a hairline breakout and a clean notch - using the+/// most ordinary edit in mechanical design. Both authoring routes must agree, and must agree with the analytic volume.+/// </summary>+public sealed class EdgeHoleBreakoutTests+{+ private const double HoleRadius = 6d;+ private const double HalfLength = 25d;++ public static TheoryData<double> NonDegenerateOffsets => new() { 0d, 12d, 18d, 18.9d, 19.1d, 22d };++ [Theory]+ [MemberData(nameof(NonDegenerateOffsets))]+ public void SemanticHole_BuildsAtEveryNonDegenerateOffset_AndMatchesTheAnalyticVolume(double x)+ => AssertBuildsWithAnalyticVolume(SemanticHoleSource(x), x, relativeTolerance: 2e-3);++ [Theory]+ [MemberData(nameof(NonDegenerateOffsets))]+ public void ComposeRemove_BuildsAtEveryNonDegenerateOffset_AndMatchesTheAnalyticVolume(double x)+ => AssertBuildsWithAnalyticVolume(ComposeSource(x), x, relativeTolerance: 1e-4);++ /// <summary>+ /// Tangency is rejected on purpose: the wall there has zero thickness along a line, which is neither machinable nor a+ /// manifold solid. What is tested is that the rejection says so in the author's terms and gives the threshold.+ /// </summary>+ [Fact]+ public void SemanticHole_ExactTangency_IsRejectedWithTheThresholdInTheAuthorsTerms()+ {+ var build = FirmamentBuildAndExport.CompileSource(SemanticHoleSource(19d));++ Assert.False(build.IsSuccess);+ var error = Assert.Single(build.Diagnostics, d => d.Severity == KernelDiagnosticSeverity.Error);+ Assert.Contains("exactly tangent to the +X face", error.Message, StringComparison.Ordinal);+ Assert.Contains("Put Center X below 19mm to keep a wall on that side, or above it to cut through the +X face.", error.Message, StringComparison.Ordinal);+ }++ [Fact]+ public void ComposeRemove_ExactTangency_NamesTheZeroWidthPointInsteadOfAnEmptyStack()+ {+ var build = FirmamentBuildAndExport.CompileSource(ComposeSource(19d));++ Assert.False(build.IsSuccess);+ Assert.Contains(build.Diagnostics, d => d.Message.Contains("two boundaries touch only at the point (25, 0)", StringComparison.Ordinal));+ Assert.DoesNotContain(build.Diagnostics, d => d.Message.Contains("compose-no-material-slabs", StringComparison.Ordinal));+ }++ /// <summary>+ /// The planners narrate their route before stating why they stopped. Only the cause is an error; the narration used+ /// to be reported as errors too, which put "planner started" above the reason. A countersunk hole breaking out is a+ /// deterministic narrate-then-fail case: the breakout route announces itself, then rejects the conical entry.+ /// </summary>+ [Fact]+ public void SemanticHoleFailure_ReportsOnlyTheCauseAsAnError()+ {+ var source = SemanticHoleSource(22d)+ .Replace("Hole<Shaft>", "Hole<Countersink>", StringComparison.Ordinal)+ .Replace("Diameter: 12mm", "Diameter: 12mm\n CountersinkDiameter: 16mm\n CountersinkAngle: 90deg", StringComparison.Ordinal);++ var build = FirmamentBuildAndExport.CompileSource(source);++ Assert.False(build.IsSuccess);+ var error = Assert.Single(build.Diagnostics, d => d.Severity == KernelDiagnosticSeverity.Error);+ Assert.Contains("countersink is conical", error.Message, StringComparison.Ordinal);+ Assert.Contains(build.Diagnostics, d => d.Severity == KernelDiagnosticSeverity.Info && d.Message.StartsWith("hole-breakout:", StringComparison.Ordinal));+ }++ /// <summary>+ /// The arrangement bug behind the breakout failure: a clockwise arc starting at or beyond pi reported points on its+ /// own lower half as off the arc, because the angle was wrapped in only one direction.+ /// </summary>+ [Fact]+ public void ClockwiseArcStartingPastPi_StillReportsItsOwnPoints()+ {+ // Lower-left quarter of a unit circle, traversed clockwise from 3pi/2 to pi.+ var arc = new LineArcCircularArc2D((0d, 0d), 1d, 3d * Math.PI / 2d, -Math.PI / 2d);+ var chord = new LineArcLineSegment2D((-2d, -Math.Sqrt(0.5d)), (0d, -Math.Sqrt(0.5d)));++ var hit = Assert.Single(ProfileArrangementBuilder.IntersectBounded(chord, arc).Intersections);++ Assert.Equal(-Math.Sqrt(0.5d), hit.Point.X, 12);+ Assert.Equal(0.5d, hit.SecondParameter, 12);+ }++ private static void AssertBuildsWithAnalyticVolume(string source, double x, double relativeTolerance)+ {+ var build = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(build.IsSuccess, string.Join(" | ", build.Diagnostics.Select(d => d.Message)));++ // Measure the exported STEP, not the in-process body: the claim is about what leaves the kernel.+ var reimport = Step242Importer.ImportBody(build.Value.StepText);+ Assert.True(reimport.IsSuccess, string.Join(" | ", reimport.Diagnostics.Select(d => d.Message)));+ var mass = BrepMassProperties.Evaluate(reimport.Value);+ Assert.True(mass.IsEnclosed, string.Join("; ", mass.Diagnostics));+ Assert.True(mass.IsOrientationConsistent, string.Join("; ", mass.Diagnostics));++ var expected = AnalyticVolume(x);+ Assert.InRange(Math.Abs(mass.AbsoluteVolume - expected) / expected, 0d, relativeTolerance);+ }++ private static double AnalyticVolume(double x)+ {+ var wall = HalfLength - x;+ var area = Math.PI * HoleRadius * HoleRadius;+ if (wall < HoleRadius)+ area -= HoleRadius * HoleRadius * Math.Acos(wall / HoleRadius) - wall * Math.Sqrt(HoleRadius * HoleRadius - wall * wall);+ return 50d * 30d * 12d - area * 12d;+ }++ private static string Mm(double value) => value.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture) + "mm";++ private static string SemanticHoleSource(double x) => $$"""+ Model EdgeClearancePlate {+ Units: mm++ Box Plate { Size: [50mm, 30mm, 12mm] }+ Modify Plate {+ Hole<Shaft> Bolt {+ On: +Z+ Center: Point2({{Mm(x)}}, 0mm)+ Diameter: 12mm+ End: ThroughAll+ }+ }+ }+ """;++ private static string ComposeSource(double x) => $$"""+ Model EdgeClearancePlate {+ Units: mm+ Concept Struct Layout On XY {+ Rect2 Stock { Center: [0mm, 0mm]; Size: [50mm, 30mm] }+ Point2 C { Position: [{{Mm(x)}}, 0mm] }+ Circle2 Bore { Center: C; Radius: 6mm }+ }+ Profile PlateProfile Using Layout { Loop Outer {+ Stock.Bottom+ |> Stock.Right+ |> Stock.Top+ |> Stock.Left+ |> Close+ } }+ Profile BoltProfile Using Layout { Loop Outer {+ Bore |> TraceLoop+ } }+ Struct Plate { Compose Body {+ Base Stock { Profile: PlateProfile; From: 0mm; To: 12mm; Role: Stock }+ Remove Bolt { Profile: BoltProfile; From: 0mm; To: 12mm; Role: Relief }+ } }+ }+ """;+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex cf918b24..a6f634ac 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -2445,12 +2445,28 @@ public static class FirmamentBuildAndExport.OrderBy(item => item.FeatureId, StringComparer.Ordinal).ToArray();- private static KernelResult<FirmamentStepExportResult> SemanticHoleFailure(IEnumerable<string> diagnostics) =>- KernelResult<FirmamentStepExportResult>.Failure(diagnostics.Select(d => new Kernel.Core.Diagnostics.KernelDiagnostic(+ /// <summary>+ /// The hole planners narrate their route as they go ("planner started", "plan created", "execution route: ...")+ /// and then state the one thing that stopped them. Reporting every line as an error buried that cause under the+ /// narration, so only lines that state a cause are errors; the narration is kept, as information, for provenance.+ /// </summary>+ private static KernelResult<FirmamentStepExportResult> SemanticHoleFailure(IEnumerable<string> diagnostics)+ {+ var lines = diagnostics.ToArray();+ var anyCause = lines.Any(IsSemanticHoleFailureCause);+ return KernelResult<FirmamentStepExportResult>.Failure(lines.Select(d => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,- Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,+ !anyCause || IsSemanticHoleFailureCause(d) ? Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error : Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Info,d,"FirmamentV2.SemanticHoleBuild")).ToArray());+ }++ private static bool IsSemanticHoleFailureCause(string line) =>+ line.Contains("rejected", StringComparison.Ordinal)+ || line.Contains("failed", StringComparison.Ordinal)+ || line.Contains("Unsupported", StringComparison.Ordinal)+ || line.StartsWith("semantic diagnostic", StringComparison.Ordinal)+ || line.StartsWith("firmament-", StringComparison.Ordinal);private static string ResolveDefaultOutputPath(string fullSourcePath){diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleBreakoutMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleBreakoutMaterializer.csnew file mode 100644index 00000000..d612b34c--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleBreakoutMaterializer.cs@@ -0,0 +1,107 @@+using Aetheris.Kernel.Core.Air;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>+/// Materializes Box holes whose mouth crosses the edge of the entry face.+/// <para>+/// The interior-hole routes build a box with circular inner loops, so they cannot express a hole that opens through a+/// side face. That is still an ordinary hole - a through hole drilled near an edge leaves a notch - and the author wrote+/// exactly what they meant, so no new syntax is involved. The Box is lowered as a prismatic section stack instead: one+/// Base rectangle over the stock thickness and one Remove disc per hole layer, resolved by the same planar arrangement+/// that already handles Compose/Remove. Shaft and counterbore stacks are prismatic and are supported; a countersink or+/// drill-point tip is conical, which a section stack cannot represent, so those are rejected with that reason.+/// </para>+/// </summary>+internal static class AirHoleBreakoutMaterializer+{+ public static AirHoleSimpleShaftMaterializationResult Execute(IReadOnlyList<AirHoleFeature> features, AirHoleSimpleShaftHost host)+ {+ var diagnostics = new List<string> { "hole-breakout: a hole crosses the edge of its entry face; lowering the Box and its holes as a prismatic section stack." };+ var halfW = host.Width / 2d; var halfD = host.Depth / 2d;+ var profiles = new Dictionary<string, ResolvedProfile2D>(StringComparer.Ordinal)+ {+ ["stock"] = Profile("stock", "Stock", Rectangle(halfW, halfD))+ };+ var operations = new List<PrismaticProfileOperation>+ {+ new("Stock", PrismaticProfileIntent.Base, "stock", host.ZMin, host.ZMax, "Stock", "hole-breakout:stock")+ };++ foreach (var feature in features)+ {+ if (feature.Placement is not AirFaceLocalHolePlacement placement)+ return Fail(diagnostics, $"Hole '{feature.FeatureId}' cuts through a side face, which is supported only for face-local placements on +Z or -Z.");+ if (feature.Stack.Kind == AirHoleStackKind.Countersink)+ return Fail(diagnostics, $"Hole '{feature.FeatureId}' cuts through a side face, but its countersink is conical and a conical hole breaking out through a side face is not supported yet. Move it inward to keep a wall, or use a counterbore.");+ if (feature.Termination is AirHoleTermination.DrillPoint)+ return Fail(diagnostics, $"Hole '{feature.FeatureId}' cuts through a side face, but its drill-point tip is conical and is not supported when the hole breaks out yet. Use a flat-bottomed or through hole there.");++ var top = feature.Axis.Direction.Z > 0d;+ var (cutMin, cutMax) = feature.EndCondition switch+ {+ AirHoleEndCondition.ThroughAll => (host.ZMin, host.ZMax),+ AirHoleEndCondition.Depth depth => top ? (Math.Max(host.ZMin, host.ZMax - depth.Value), host.ZMax) : (host.ZMin, Math.Min(host.ZMax, host.ZMin + depth.Value)),+ _ => (double.NaN, double.NaN)+ };+ if (double.IsNaN(cutMin))+ return Fail(diagnostics, $"Hole '{feature.FeatureId}' cuts through a side face with end condition {feature.EndCondition.Kind}, which this route does not support yet.");++ var shaftKey = $"{feature.FeatureId}.shaft";+ profiles[shaftKey] = Profile(shaftKey, "Bore", new LineArcFullCircle2D((placement.U, placement.V), feature.Shaft.Radius));+ operations.Add(new(feature.FeatureId, PrismaticProfileIntent.Remove, shaftKey, cutMin, cutMax, "Hole", feature.FeatureId, feature.FeatureId, "Hole", feature.Shaft.Diameter));++ if (feature.Stack.Components.OfType<AirHoleCounterboreComponent>().SingleOrDefault() is { } counterbore)+ {+ var (boreMin, boreMax) = top ? (Math.Max(cutMin, cutMax - counterbore.Depth), cutMax) : (cutMin, Math.Min(cutMax, cutMin + counterbore.Depth));+ var counterboreKey = $"{feature.FeatureId}.counterbore";+ profiles[counterboreKey] = Profile(counterboreKey, "Counterbore", new LineArcFullCircle2D((placement.U, placement.V), counterbore.Radius));+ operations.Add(new($"{feature.FeatureId}.Counterbore", PrismaticProfileIntent.Remove, counterboreKey, boreMin, boreMax, "Hole", feature.FeatureId, feature.FeatureId, "Hole", counterbore.Radius * 2d));+ }+ }++ var levels = operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();+ var composition = new PrismaticProfileCompositionFeature(+ features[0].TargetBodyId ?? "semantic-hole-host", "XY", "+Z",+ new PrismaticProfilePlacement("LegacyImplicitWorldXY", 0d, 0d, 0d, "XY", "+Z", "+X", false),+ operations, levels, "hole-breakout");+ var stack = PrismaticSectionStackCompiler.Normalize(new PrismaticProfileCompositionParseResult(composition, profiles, []), out var stackDiagnostics);+ diagnostics.AddRange(stackDiagnostics);+ if (stack is null) return Fail(diagnostics, "The section stack for the broken-out hole could not be resolved; see the arrangement diagnostics above.");++ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ diagnostics.AddRange(emitted.Diagnostics);+ if (emitted.Body is null) return Fail(diagnostics, "The section stack for the broken-out hole resolved but did not materialize a body.");++ diagnostics.Add("hole-breakout: materialized through the prismatic section stack.");+ return new(AirHoleSimpleShaftMaterializationStatus.Succeeded, null, emitted.Body, diagnostics, emitted.Correspondence);+ }++ private static AirHoleSimpleShaftMaterializationResult Fail(List<string> diagnostics, string reason)+ {+ diagnostics.Add("rejected: " + reason);+ return new(AirHoleSimpleShaftMaterializationStatus.UnsupportedPlacement, null, null, diagnostics);+ }++ private static IReadOnlyList<LineArcProfileCurve2D> Rectangle(double halfW, double halfD) =>+ [+ new LineArcLineSegment2D((-halfW, -halfD), (halfW, -halfD)),+ new LineArcLineSegment2D((halfW, -halfD), (halfW, halfD)),+ new LineArcLineSegment2D((halfW, halfD), (-halfW, halfD)),+ new LineArcLineSegment2D((-halfW, halfD), (-halfW, -halfD)),+ ];++ private static ResolvedProfile2D Profile(string name, string segmentPrefix, params LineArcProfileCurve2D[] curves) => Profile(name, segmentPrefix, (IReadOnlyList<LineArcProfileCurve2D>)curves);++ private static ResolvedProfile2D Profile(string name, string segmentPrefix, IReadOnlyList<LineArcProfileCurve2D> curves)+ {+ string[] sides = ["Bottom", "Right", "Top", "Left"];+ var segments = curves.Select((curve, index) =>+ {+ var segmentName = curves.Count == 4 ? sides[index] : segmentPrefix;+ return new ResolvedProfileSegment2D(segmentName, curve,+ new ProfileSegmentProvenance($"profile:{name}.Outer.{segmentName}", $"hole-breakout:{name}", "hole-breakout", "HoleBreakout", "XY"));+ }).ToArray();+ return new ResolvedProfile2D(name, "XY", [new ResolvedProfileLoop2D("Outer", true, segments)]);+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.csindex f8576676..76751e5b 100644--- a/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.cs@@ -28,6 +28,21 @@ internal static class AirHoleCompositeMaterializerreturn new(false, null, [], diagnostics);}+ // Classify every hole before planning any: one tangent hole rejects the set with its own reason, and one hole+ // that breaks out moves the whole set onto the section-stack route, which resolves all of them together.+ var footprints = features.Select(f => (Feature: f, Footprint: AirHoleFootprint.Classify(f, host, AirHoleSimpleShaftMaterializer.FootprintTolerance))).ToArray();+ if (footprints.FirstOrDefault(x => x.Footprint.Contact is AirHoleFootprintContact.Tangent or AirHoleFootprintContact.Misses) is { Feature: not null } blocked)+ {+ diagnostics.Add("rejected: " + blocked.Footprint.Explain(blocked.Feature));+ return new(false, null, [], diagnostics);+ }+ if (footprints.Any(x => x.Footprint.Contact == AirHoleFootprintContact.Breakout))+ {+ var breakout = AirHoleBreakoutMaterializer.Execute(features, host);+ diagnostics.AddRange(breakout.Diagnostics);+ return new(breakout.Succeeded, breakout.Body, [], diagnostics, breakout.Correspondence);+ }+var plans = new List<AirHoleSimpleShaftMaterializationPlan>(features.Count);foreach (var feature in features){diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleFootprint.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleFootprint.csnew file mode 100644index 00000000..37497a31--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleFootprint.cs@@ -0,0 +1,64 @@+using Aetheris.Kernel.Core.Air;++namespace Aetheris.Kernel.Firmament.Materializer;++internal enum AirHoleFootprintContact+{+ /// <summary>The hole mouth lies wholly inside the entry face, leaving a wall of positive thickness on every side.</summary>+ Inside,+ /// <summary>The hole wall touches a side face along a line: the wall there would have zero thickness.</summary>+ Tangent,+ /// <summary>The hole cuts through at least one side face. A through hole at an edge is a notch, not an error.</summary>+ Breakout,+ /// <summary>The hole mouth does not overlap the entry face at all, so it would remove nothing.</summary>+ Misses+}++internal sealed record AirHoleFootprint(AirHoleFootprintContact Contact, string? Face, double? Threshold, string Axis)+{+ /// <summary>+ /// Classifies a face-local hole mouth against the rectangular entry face of a Box host. This is the only place the+ /// question "does this hole break out?" is answered, so every hole route gives the same answer to it.+ /// </summary>+ public static AirHoleFootprint Classify(AirHoleFeature feature, AirHoleSimpleShaftHost host, double tolerance)+ {+ if (feature.Placement is not AirFaceLocalHolePlacement placement) return new(AirHoleFootprintContact.Inside, null, null, "");+ var u = placement.U; var v = placement.V; var r = feature.Shaft.Radius;+ var halfW = host.Width / 2d; var halfD = host.Depth / 2d;++ // Nearest distance from the mouth centre to the face rectangle. A mouth that at most grazes the rectangle removes+ // no material from the face, which is never what an author means by a hole.+ var outsideX = Math.Max(Math.Abs(u) - halfW, 0d);+ var outsideY = Math.Max(Math.Abs(v) - halfD, 0d);+ if (Math.Sqrt(outsideX * outsideX + outsideY * outsideY) >= r - tolerance) return new(AirHoleFootprintContact.Misses, null, null, "");++ // Signed wall thickness left on each side: positive leaves material, zero is tangency, negative cuts through.+ var walls = new (string Face, double Gap, double Threshold, string Axis)[]+ {+ ("+X", halfW - (u + r), halfW - r, "X"),+ ("-X", halfW - (r - u), r - halfW, "X"),+ ("+Y", halfD - (v + r), halfD - r, "Y"),+ ("-Y", halfD - (r - v), r - halfD, "Y"),+ };+ var tangent = walls.FirstOrDefault(w => Math.Abs(w.Gap) <= tolerance);+ if (tangent.Face is not null) return new(AirHoleFootprintContact.Tangent, tangent.Face, tangent.Threshold, tangent.Axis);+ var breakout = walls.FirstOrDefault(w => w.Gap < -tolerance);+ return breakout.Face is not null+ ? new(AirHoleFootprintContact.Breakout, breakout.Face, breakout.Threshold, breakout.Axis)+ : new(AirHoleFootprintContact.Inside, null, null, "");+ }++ /// <summary>The author-facing rejection for a tangent or missing hole, in the author's own terms and units.</summary>+ public string Explain(AirHoleFeature feature) => Contact switch+ {+ AirHoleFootprintContact.Tangent =>+ $"Hole '{feature.FeatureId}' (diameter {Format(feature.Shaft.Diameter)}) is exactly tangent to the {Face} face: its wall would be zero thickness along a line, "+ + $"which is neither machinable nor a valid solid. Put Center {Axis} {(Face!.StartsWith('+') ? "below" : "above")} {Format(Threshold!.Value)} to keep a wall on that side, "+ + $"or {(Face!.StartsWith('+') ? "above" : "below")} it to cut through the {Face} face.",+ AirHoleFootprintContact.Misses =>+ $"Hole '{feature.FeatureId}' does not overlap its entry face, so it would remove no material. Move its Center onto the face.",+ _ => ""+ };++ private static string Format(double millimetres) => $"{millimetres:0.######}mm";+}diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.csindex 937a6098..8054b259 100644--- a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs@@ -99,11 +99,23 @@ internal static class AirHoleSimpleShaftMaterializer{private const double Tolerance = 1e-9;+ /// <summary>+ /// Wall thickness below which a hole is treated as tangent to a side face rather than as leaving a wall or cutting+ /// through it. It matches the kernel's linear tolerance so every route agrees on where tangency is.+ /// </summary>+ internal const double FootprintTolerance = 1e-6;+public static AirHoleSimpleShaftMaterializationResult Execute(AirHoleFeature feature, AirHoleSimpleShaftHost host){if (feature.ConstructionPlanePlacement is { } constructionPlacement)return ExecuteConstructionPlaneThroughAll(feature, host, constructionPlacement);+ var footprint = AirHoleFootprint.Classify(feature, host, FootprintTolerance);+ if (footprint.Contact is AirHoleFootprintContact.Tangent or AirHoleFootprintContact.Misses)+ return new(AirHoleSimpleShaftMaterializationStatus.UnsupportedPlacement, null, null, ["rejected: " + footprint.Explain(feature)]);+ if (footprint.Contact == AirHoleFootprintContact.Breakout)+ return AirHoleBreakoutMaterializer.Execute([feature], host);+var planResult = TryCreatePlan(feature, host);if (planResult.Status != AirHoleSimpleShaftMaterializationStatus.Succeeded || planResult.Plan is null){@@ -186,7 +198,9 @@ internal static class AirHoleSimpleShaftMaterializerif (Math.Abs(placement.U) + feature.Shaft.Radius > host.Width / 2d + Tolerance ||Math.Abs(placement.V) + feature.Shaft.Radius > host.Depth / 2d + Tolerance){- diagnostics.Add("air-hole-x2 rejected: face-local center/radius does not fit within the supported rectangular entry face.");+ // Execute classifies the footprint before planning and routes tangent and broken-out holes elsewhere, so+ // only callers that plan directly - the combined EdgeFinish route - can still reach this.+ diagnostics.Add($"air-hole-x2 rejected: hole '{feature.FeatureId}' crosses the edge of its entry face, and this route (a hole combined with an EdgeFinish) only builds holes that stay inside the face.");return new(AirHoleSimpleShaftMaterializationStatus.UnsupportedPlacement, null, null, diagnostics);}diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.csindex b5f07114..14468cb6 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs@@ -96,7 +96,9 @@ public static class PrismaticSectionStackCompilerd.AddRange(arrangement.Arrangement.Diagnostics);if (arrangement.Region is not null) slabs.Add(new(pair.First, pair.Second, arrangement.Region, active.Select(x => x.Name).Order().ToArray(), arrangement.Arrangement));}- if (slabs.Count == 0) d.Add("compose-no-material-slabs");+ // An empty stack is usually the consequence of a rejected arrangement, which has already said why; reporting+ // the consequence as well used to make it the last and most visible line.+ if (slabs.Count == 0 && !d.Any(x => x.StartsWith("arrangement-rejected", StringComparison.Ordinal))) d.Add("compose-no-material-slabs");var transitions = new List<PrismaticSectionTransition>();foreach (var level in parsed.Feature.CriticalLevels){diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.csindex e3dabbd4..d92900ac 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs@@ -327,10 +327,12 @@ public static class ProfileArrangementBuildervar outCount = outgoing.GetValueOrDefault(vertex);if (inCount == 1 && outCount == 1) continue;if (inCount == 0 || outCount == 0)- diagnostics.Add($"arrangement-rejected:dangling-arrangement-fragment:vertex={vertex}:incoming={inCount}:outgoing={outCount}:context={context}");+ diagnostics.Add($"arrangement-rejected:dangling-arrangement-fragment:vertex={vertex}:incoming={inCount}:outgoing={outCount}:context={context}: "+ + $"a boundary ends at {VertexMillimetres(vertex)} without continuing. This is an internal arrangement failure rather than a modelling error; please report it with the source.");else{- diagnostics.Add($"arrangement-rejected:point-only-tangent-or-zero-width-ligament:vertex={vertex}:incoming={inCount}:outgoing={outCount}:context={context}");+ diagnostics.Add($"arrangement-rejected:point-only-tangent-or-zero-width-ligament:vertex={vertex}:incoming={inCount}:outgoing={outCount}:context={context}: "+ + $"two boundaries touch only at the point {VertexMillimetres(vertex)}, which would leave a wall of zero width there. Move one so they either stay apart or overlap by a real width.");diagnostics.Add($"arrangement-rejected:unresolved-angular-order:vertex={vertex}:incoming={inCount}:outgoing={outCount}:context={context}");}}@@ -517,12 +519,35 @@ public static class ProfileArrangementBuilder}}+ /// <summary>+ /// Normalized position of <paramref name="angle"/> along the arc: 0 at its start, 1 at its end, outside [0,1]+ /// when the angle is not on the swept interval.+ /// <para>+ /// The angle comes from <c>atan2</c>, in (-pi, pi], while arc start angles are unbounded because trimming+ /// accumulates them. The difference therefore has to be wrapped in <em>both</em> directions. This used to wrap+ /// only one way per sweep sign - positive deltas were never reduced for a clockwise arc - so a clockwise arc+ /// starting at or beyond pi reported points on its own lower half as t = 4.5 and the like. Region classification+ /// then saw both sides of those fragments as the same material and dropped them, which is how a circular hole+ /// breaking out through a straight boundary produced dangling-fragment rejections. A hole wholly inside the+ /// boundary never tripped it because its circle stays a separate, counter-clockwise loop.+ /// </para>+ /// </summary>private static double ArcParameter(LineArcCircularArc2D arc, double angle){- var delta = angle - arc.StartAngleRadians;- if (arc.SweepAngleRadians >= 0d) while (delta < 0d) delta += 2d * Math.PI;- else while (delta > 0d) delta -= 2d * Math.PI;- return delta / arc.SweepAngleRadians;+ const double turn = 2d * Math.PI;+ var sweep = arc.SweepAngleRadians;+ var delta = Math.IEEERemainder(angle - arc.StartAngleRadians, turn);+ // Pick the 2pi-representative nearest the swept interval: on-arc points land in [0, 1] whichever way the arc+ // runs, and off-arc points stay outside it, so callers' [0, 1] range tests keep their meaning.+ var best = delta / sweep;+ var bestDistance = double.PositiveInfinity;+ for (var k = -2; k <= 2; k++)+ {+ var candidate = (delta + k * turn) / sweep;+ var distance = candidate < 0d ? -candidate : candidate > 1d ? candidate - 1d : 0d;+ if (distance < bestDistance) { bestDistance = distance; best = candidate; }+ }+ return best;}private static LineArcProfileCurve2D Trim(LineArcProfileCurve2D curve, double from, double to) => curve switch{@@ -614,6 +639,15 @@ public static class ProfileArrangementBuilder_ => false};}+ /// <summary>Renders a <see cref="VertexKey"/> back into model coordinates for people reading a diagnostic.</summary>+ private static string VertexMillimetres(string key)+ {+ var parts = key.Split(',');+ return parts.Length == 2 && double.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var x)+ && double.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var y)+ ? $"({x * VertexTol:0.#####}, {y * VertexTol:0.#####})" : key;+ }+private static string VertexKey((double X, double Y) p){// IEEE-754 preserves the sign of zero and the fixed-point formatter rendersdiff --git a/docs/public/firmament/geometry.md b/docs/public/firmament/geometry.mdindex 51a062fe..192054d8 100644--- a/docs/public/firmament/geometry.md+++ b/docs/public/firmament/geometry.md@@ -6,6 +6,8 @@ Analytic single solids use the same direct named declaration family: `Sphere BodUse named features and selectors, never raw internal B-rep IDs in native authoring. [`multiple-hole-dimensions-with-chamfer.firmament`](../../../fixtures/Canonical/PMI/multiple-hole-dimensions-with-chamfer.firmament) demonstrates two holes, an outer-boundary chamfer, and PMI surviving the same AP242 build. [`counterbore-shaft-diameter.firmament`](../../../fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament) demonstrates a profile-composed part, pattern holes, a counterbore, a chamfer, and shaft-diameter PMI.+A face-local `Hole<Shaft>` or `Hole<Counterbore>` on a `Box` may cross the edge of its entry face: a through hole drilled near an edge leaves a notch, and it builds as one. Only exact tangency is rejected, because the wall there would have zero thickness along a line; the diagnostic gives the threshold in your own terms (for example, "Put Center X below 19mm to keep a wall on that side, or above it to cut through the +X face"). Countersunk and drill-point holes, whose entries are conical, are not yet supported when they break out, and say so.+`HoleDiameter` on a `Hole<Counterbore>` targets the shaft `Diameter`; `CounterboreDiameter` remains a distinct feature field and has no separate public PMI record kind in Preview 3. Pattern generation supports geometry as a semantic whole; authored names for generated instances are not a stable public instance-selector family in Preview 3.## Boss