Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Drilled holes: drill-point default, Path-step planes, multiple side drills
Claude86ed9f01acdc
diff --git a/Aetheris.CLI.Tests/DrilledHoleCliTests.cs b/Aetheris.CLI.Tests/DrilledHoleCliTests.csnew file mode 100644index 00000000..2d6e5a26--- /dev/null+++ b/Aetheris.CLI.Tests/DrilledHoleCliTests.cs@@ -0,0 +1,92 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.CLI.Tests;++/// <summary>Blind holes are drilled holes: a 118° point unless stated otherwise, the depth measured to full diameter,+/// and side holes drilled from planes derived from source (Construction Planes or Path steps), never face references.</summary>+public sealed class DrilledHoleCliTests+{+ private static readonly string RepoRoot = FindRepoRoot();+ private static double Tip(double radius, double angle) => radius / Math.Tan(angle * Math.PI / 360d);++ [Theory]+ [InlineData("blind-drillpoint-default.firmament", 118d)]+ [InlineData("blind-drillpoint-angle.firmament", 135d)]+ public void TopFaceBlindHoleEndsInADrillPointBelowTheFullDiameterDepth(string fixture, double angle)+ {+ var body = BuildAndImport("fixtures/Regression/Hole/valid/" + fixture);+ var cone = Assert.Single(Cones(body));+ // Box z 0..20, 10 mm full-diameter depth, Ø8: the apex sits one tip length below z = 10 on the hole axis.+ Assert.Equal(-15d, cone.Apex.X, 9);+ Assert.Equal(5d, cone.Apex.Y, 9);+ Assert.Equal(10d - Tip(4d, angle), cone.Apex.Z, 9);+ Assert.Equal(angle / 2d, cone.SemiAngleRadians * 180d / Math.PI, 9);+ }++ [Fact]+ public void FlatTerminationKeepsAFlatFloor()+ {+ var body = BuildAndImport("fixtures/Regression/Hole/valid/blind-flat-floor.firmament");+ Assert.Empty(Cones(body));+ Assert.Contains(body.Topology.Faces, f => body.TryGetFaceSurface(f.Id, out var s) && s?.Plane is { } p+ && Math.Abs(Math.Abs(p.Normal.Z) - 1d) < 1e-12 && Math.Abs(p.Origin.Z - 10d) < 1e-9);+ }++ [Fact]+ public void PathStepPlanesDrillIntoTheirOwnCoplanarFaces()+ {+ var body = BuildAndImport("fixtures/Regression/Hole/valid/path-step-plane-drills.firmament");+ var tip = Tip(2d, 118d);+ var apexes = Cones(body).Select(c => (Math.Round(c.Apex.X, 9), Math.Round(c.Apex.Y, 9), Math.Round(c.Apex.Z, 9))).OrderBy(a => a).ToArray();+ (double, double, double)[] expected =+ [+ (-20d, Math.Round(-15d + 8d + tip, 9), -5d),+ (0d, Math.Round(15d - 8d - tip, 9), -5d),+ (20d, Math.Round(-15d + 8d + tip, 9), -5d),+ ];+ Assert.Equal(expected.OrderBy(a => a).ToArray(), apexes);+ }++ [Theory]+ [InlineData("drill-envelopes-touch.firmament", "SectionStackBlindDrillToolEnvelopesIntersect")]+ [InlineData("plane-drill-flat.firmament", "a flat floor from a plane is not supported")]+ public void UnsupportedDrillsAreRefused(string fixture, string expected)+ {+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ var exit = CliRunner.Run(["validate", Path.Combine(RepoRoot, "fixtures/Invalid/Hole", fixture), "--json"], stdout, stderr);+ Assert.NotEqual(0, exit);+ using var document = JsonDocument.Parse(stdout.ToString());+ var report = document.RootElement.TryGetProperty("firmamentV2Validation", out var nested) ? nested : document.RootElement;+ var diagnostics = report.GetProperty("diagnostics").EnumerateArray()+ .Select(d => d.GetProperty("code").GetString() + " " + d.GetProperty("message").GetString()).ToArray();+ Assert.Contains(diagnostics, d => d.Contains(expected, StringComparison.Ordinal));+ Assert.DoesNotContain(diagnostics, d => d.Contains("CavityPlanCreated", StringComparison.Ordinal));+ }++ private static IEnumerable<Aetheris.Kernel.Core.Geometry.Surfaces.ConeSurface> Cones(BrepBody body)+ => body.Topology.Faces.Select(f => body.TryGetFaceSurface(f.Id, out var s) ? s?.Cone : null).OfType<Aetheris.Kernel.Core.Geometry.Surfaces.ConeSurface>();++ private static BrepBody BuildAndImport(string fixture)+ {+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-drilled-holes", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ var step = Path.Combine(directory, Path.GetFileNameWithoutExtension(fixture) + ".step");+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ Assert.True(CliRunner.Run(["build", Path.Combine(RepoRoot, fixture), "--out", step], stdout, stderr) == 0, $"{fixture}: {stderr}{stdout}");+ var import = Step242Importer.ImportBody(File.ReadAllText(step));+ Assert.True(import.IsSuccess, string.Join("; ", import.Diagnostics.Select(d => d.Message)));+ return import.Value;+ }++ private static string FindRepoRoot()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");+ }+}diff --git a/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs b/Aetheris.CLI.Tests/ShapeComparisonCliTests.csindex d3606082..7d2468f8 100644--- a/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs+++ b/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs@@ -52,14 +52,15 @@ public sealed class ShapeComparisonCliTests// Everything the reconstruction builds is on the original's surfaces.Assert.Empty(result.Carriers.ExtraInCandidate);- Assert.True(result.Overlap.IntersectionOverUnion >= 0.996, $"IoU {result.Overlap.IntersectionOverUnion}");+ Assert.True(result.Overlap.IntersectionOverUnion >= 0.9985, $"IoU {result.Overlap.IntersectionOverUnion}");+ Assert.True(result.Carriers.MatchedCarrierCount >= 75, $"matched {result.Carriers.MatchedCarrierCount}");// What is missing is exactly the features Firmament cannot yet express (see the fixture's header).// Closing one of these gaps shrinks this list; a new kind of discrepancy fails here.foreach (var carrier in result.Carriers.MissingFromCandidate){Assert.True(- IsSideDrill(carrier) || IsHexFootFillet(carrier) || IsLugUndersideFillet(carrier),+ IsHexFootFillet(carrier) || IsLugUndersideFillet(carrier),$"Unexpected missing carrier: {carrier.Description}");}}@@ -95,10 +96,6 @@ public sealed class ShapeComparisonCliTestsAssert.True(shape.GetProperty("overlap").GetProperty("candidateOnlyVolume").GetDouble() > 0);}- private static bool IsSideDrill(StepShapeComparison.CarrierGroup c)- => c.BoundsMin is { } lo && c.BoundsMax is { } hi && lo[1] >= -125.01 && hi[1] <= -73.9 && lo[2] >= -35.01 && hi[2] <= -14.99- && (c.Kind == "Cone" || (c.Kind == "Cylinder" && c.Description.Contains("r=10 ", StringComparison.Ordinal)));-private static bool IsHexFootFillet(StepShapeComparison.CarrierGroup c)=> c.Kind == "Cylinder" && c.Description.Contains("r=5 ", StringComparison.Ordinal) && c.BoundsMax is { } hi && hi[2] <= 5.01;diff --git a/Aetheris.CLI/StepShapeComparison.cs b/Aetheris.CLI/StepShapeComparison.csindex 7eba1fb0..f3e8201b 100644--- a/Aetheris.CLI/StepShapeComparison.cs+++ b/Aetheris.CLI/StepShapeComparison.cs@@ -217,8 +217,7 @@ public static class StepShapeComparisonvar candidateOnlyColumns = new (double Length, double ZMin, double ZMax)[nx * ny];for (var k = 0; k < nx * ny; k++){- var r = referenceColumns[k];- var c = candidateColumns[k];+ if (referenceColumns[k] is not { } r || candidateColumns[k] is not { } c) continue;referenceVolume += Length(r) * area;candidateVolume += Length(c) * area;union += Length(Combine(r, c, (a, b) => a || b)) * area;@@ -255,7 +254,7 @@ public static class StepShapeComparison"Parallel +Z rays at cell centres through each side's display tessellation (chord 0.02); inside intervals by crossing parity.");}- private static List<double>[] CastColumns(DisplayTessellationResult mesh, Point3D min, double cell, int nx, int ny, out int unpaired)+ private static List<double>?[] CastColumns(DisplayTessellationResult mesh, Point3D min, double cell, int nx, int ny, out int unpaired){var bins = new List<Triangle>[nx * ny];foreach (var patch in mesh.FacePatches)@@ -279,7 +278,7 @@ public static class StepShapeComparison// An irrational offset keeps ray centres off mesh vertices and edges, which sit on round numbers.const double jitterX = 0.5d + 0.0012345678d;const double jitterY = 0.5d - 0.0008765432d;- var columns = new List<double>[nx * ny];+ var columns = new List<double>?[nx * ny];var odd = 0;Parallel.For(0, nx * ny, k =>{@@ -292,10 +291,13 @@ public static class StepShapeComparison}hits.Sort();+ // An odd crossing count (a ray grazing a seam or apex) cannot be classified; it is skipped on+ // both sides rather than read as empty, which would show as a false difference.if (hits.Count % 2 != 0){Interlocked.Increment(ref odd);- hits.Clear();+ columns[k] = null;+ return;}columns[k] = hits;diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 56b297de..916afa77 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -525,16 +525,8 @@ public static partial class FirmamentBuildAndExportvar emitted = PrismaticSectionStackEmitter.Emit(stack);if (emitted.Body is null)return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());- if ((stack.Feature.ConstructionPlaneBlindDrills?.Count ?? 0) > 0)- {- var finalPlan = SectionStackBlindDrillComposeBridge.TryApply(stack, emitted.Plan!, out var bridgeDiagnostics, out _);- if (finalPlan?.TopologyPlan is null)- return KernelResult<FirmamentStepExportResult>.Failure(bridgeDiagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition.BlindDrill")).ToArray());- var materialized = PrismaticSectionStackBrepMaterializer.TryMaterialize(finalPlan.TopologyPlan);- if (materialized.Body is null)- return KernelResult<FirmamentStepExportResult>.Failure(materialized.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition.BlindDrill")).ToArray());- emitted = new PrismaticSectionStackEmissionResult(materialized.Body, finalPlan, emitted.Diagnostics.Concat(bridgeDiagnostics).ToArray(), finalPlan.Correspondence);- }+ if (ApplyConstructionPlaneBlindDrills(stack, emitted, out var drilled) is { } drillFailure) return drillFailure;+ emitted = drilled;if (materializerSource.Contains("EdgeFinish", StringComparison.Ordinal))return ExportComposedSemanticTopBoundaryChamfer(materializerSource, parsed, stack, emitted, v2Parse.Document);// The composition route either retained the checked body above or@@ -1168,6 +1160,23 @@ public static partial class FirmamentBuildAndExport"template-exact-construction", "ExactCoaxialPart", ConceptIr: document.ConceptIr, StandardPart: report));}+ /// <summary>Applies a section stack's construction-plane blind drills to an emitted plan and materializes the+ /// result; returns a failure, or null with the drilled emission (unchanged when there are no drills).</summary>+ private static KernelResult<FirmamentStepExportResult>? ApplyConstructionPlaneBlindDrills(+ PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted, out PrismaticSectionStackEmissionResult result)+ {+ result = emitted;+ if ((stack.Feature.ConstructionPlaneBlindDrills?.Count ?? 0) == 0) return null;+ static KernelResult<FirmamentStepExportResult> Failure(IEnumerable<string> codes) => KernelResult<FirmamentStepExportResult>.Failure(codes.Select(x =>+ new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition.BlindDrill")).ToArray());+ var finalPlan = SectionStackBlindDrillComposeBridge.TryApply(stack, emitted.Plan!, out var bridgeDiagnostics, out _);+ if (finalPlan?.TopologyPlan is null) return Failure(bridgeDiagnostics);+ var materialized = PrismaticSectionStackBrepMaterializer.TryMaterialize(finalPlan.TopologyPlan);+ if (materialized.Body is null) return Failure(materialized.Diagnostics);+ result = new PrismaticSectionStackEmissionResult(materialized.Body, finalPlan, emitted.Diagnostics.Concat(bridgeDiagnostics).ToArray(), finalPlan.Correspondence);+ return null;+ }+private static KernelResult<FirmamentStepExportResult> ExportComposedSemanticTopBoundaryChamfer(string source, PrismaticProfileCompositionParseResult parsed, PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted,FirmamentV2Document? canonicalDocument)@@ -1211,6 +1220,9 @@ public static partial class FirmamentBuildAndExportif (adjusted is null) return Fail(planDiagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferComposeTopologyPlanNotMaterialized");var plannedEmission = PrismaticSectionStackEmitter.Emit(adjusted);if (plannedEmission.Body is null) return Fail(plannedEmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferComposeMaterializationFailed");+ // The chamfer re-emits the adjusted stack, so construction-plane drills apply again to that plan.+ if (ApplyConstructionPlaneBlindDrills(adjusted, plannedEmission, out var drilledEmission) is { } chamferDrillFailure) return chamferDrillFailure;+ plannedEmission = drilledEmission;if (!FirmamentManifoldChecker.IsManifold(plannedEmission.Body)) return Fail("ProfileBoundaryChamferNonManifold");var semanticPmi = Array.Empty<Step242SemanticPmi>();if (canonicalDocument is not null)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 7f48e0ba..673500ad 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -489,6 +489,11 @@ internal static class ConceptIrResolvervar localEnd = ParseConstructionPlaneHoleEnd(localEndText);if (localEnd is null) { diagnostics.Add(string.Equals(localEndText, "Blind", StringComparison.OrdinalIgnoreCase) ? FirmamentV2Parser.HoleConstructionPlaneExtentUnsupported : FirmamentV2Parser.HoleBlindDepthInvalid); continue; }var termination = ParseConstructionPlaneHoleTermination(holeBody, diagnostics);+ if (Regex.IsMatch(holeBody, @"\btermination\s*:\s*Flat", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))+ { diagnostics.Add($"{FirmamentV2Parser.HoleConstructionPlaneExtentUnsupported}: A hole drilled from a Construction Plane ends in a drill point; a flat floor from a plane is not supported."); continue; }+ // A blind drilled hole has a 118° point unless Termination says otherwise.+ if (termination is null && localEnd.Kind != FirmamentV2SemanticHoleEndKind.ThroughAll && !Regex.IsMatch(holeBody, @"\btermination\s*:", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))+ termination = new(FirmamentV2SemanticHoleTerminationKind.DrillPoint, AirHoleTermination.DrillPoint.DefaultPointAngleDegrees);if (localEnd.Kind == FirmamentV2SemanticHoleEndKind.ThroughAll){if (termination is not null) { diagnostics.Add(FirmamentV2Parser.HoleTerminationConflictsWithExtent); continue; }@@ -1034,11 +1039,12 @@ internal static class ConceptIrResolverprivate static FirmamentV2SemanticHoleEnd? ParseConstructionPlaneHoleEnd(string value){if (string.Equals(value, "ThroughAll", StringComparison.OrdinalIgnoreCase) || string.Equals(value, "Through", StringComparison.OrdinalIgnoreCase)) return new(FirmamentV2SemanticHoleEndKind.ThroughAll);- var match = Regex.Match(value, @"^(?<kind>ShaftDepth|TotalDepth)\s*\(\s*(?<value>[^)]+)\s*\)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);+ // "Blind 45mm" is the shaft depth: the full-diameter depth, excluding the point.+ var match = Regex.Match(value, @"^(?:(?<kind>ShaftDepth|TotalDepth)\s*\(\s*(?<value>[^)]+)\s*\)|(?<kind>Blind)\s+(?<value>\S+))$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);if (!match.Success) return null;var depth = ParseLengthOrUnitless(match.Groups["value"].Value);- if (!double.IsFinite(depth) || (string.Equals(match.Groups["kind"].Value, "ShaftDepth", StringComparison.OrdinalIgnoreCase) ? depth < 0d : depth <= 0d)) return null;- return new(string.Equals(match.Groups["kind"].Value, "ShaftDepth", StringComparison.OrdinalIgnoreCase) ? FirmamentV2SemanticHoleEndKind.ShaftDepth : FirmamentV2SemanticHoleEndKind.TotalDepth, depth);+ if (!double.IsFinite(depth) || (string.Equals(match.Groups["kind"].Value, "TotalDepth", StringComparison.OrdinalIgnoreCase) ? depth <= 0d : depth < 0d)) return null;+ return new(string.Equals(match.Groups["kind"].Value, "TotalDepth", StringComparison.OrdinalIgnoreCase) ? FirmamentV2SemanticHoleEndKind.TotalDepth : FirmamentV2SemanticHoleEndKind.ShaftDepth, depth);}private static FirmamentV2SemanticHoleTermination? ParseConstructionPlaneHoleTermination(string body, List<string> diagnostics){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex 03fb5ad2..367dece4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -439,6 +439,21 @@ public static partial class FirmamentV2Parser&& FirmamentSyntaxValues.TryMeasure(blind.Arguments[0].Value, "mm", out var depth, compatibilityStock is null ? null : "mm") && depth > 0) termination = new(FirmamentV2SemanticHoleEndKind.Depth, depth);if (compatibilityStock is not null && termination is null)diagnostics.Add(endExpression is CallSyntax { Target: ReferenceSyntax { Name.Text: "depth" } } ? HoleDepthInvalid : HoleEndMissing);+ // A blind drilled hole has a drill point unless the author says otherwise; a flat floor is a deliberate+ // choice (flat-bottom drill or end mill), written Termination: Flat.+ FirmamentV2SemanticHoleTermination? tip = null;+ var tipExpression = compatibilityStock is null ? f.Take("Termination") : null;+ if (tipExpression is not null)+ {+ tip = BindHoleTermination(tipExpression, diagnostics);+ if (tip is null) return null;+ if (termination?.Kind != FirmamentV2SemanticHoleEndKind.Depth)+ { diagnostics.Add($"{HoleTerminationConflictsWithExtent}: Termination applies to a Blind hole; a ThroughAll hole has no floor."); return null; }+ if (variant != FirmamentV2SemanticHoleVariant.Shaft && tip.Kind == FirmamentV2SemanticHoleTerminationKind.DrillPoint)+ { diagnostics.Add($"{HoleConstructionPlaneExtentUnsupported}: a drill point is admitted on Hole<Shaft> only; blind {variant} holes are flat (Termination: Flat)."); return null; }+ }+ else if (compatibilityStock is null && termination?.Kind == FirmamentV2SemanticHoleEndKind.Depth && variant == FirmamentV2SemanticHoleVariant.Shaft)+ tip = new(FirmamentV2SemanticHoleTerminationKind.DrillPoint, 118d);double? cbDiameter = null, cbDepth = null, csDiameter = null, csAngle = null;if (variant == FirmamentV2SemanticHoleVariant.Counterbore) { cbDiameter = Diameter("CounterboreDiameter", "Counterbore"); cbDepth = f.Number("CounterboreDepth", "mm"); }if (variant == FirmamentV2SemanticHoleVariant.Countersink) { csDiameter = Diameter("CountersinkDiameter", "Countersink");@@ -452,7 +467,24 @@ public static partial class FirmamentV2Parserif (csDiameter is not null && (!(csDiameter > diameter) || !(csAngle > 0 && csAngle < 180))) { diagnostics.Add(HoleCountersinkInvalid); return null; }face ??= FirmamentV2FaceTarget.Direct(axis);return new(d.Name.Text, variant, face, new(center[0], center[1], FirmamentV2FaceLocalPoint2D.ConventionFor(axis)), diameter, termination,- cbDiameter, cbDepth, csDiameter, csAngle, SourceSpan: d.Span, AuthoredFields: f.AuthoredFields);+ cbDiameter, cbDepth, csDiameter, csAngle, SourceSpan: d.Span, AuthoredFields: f.AuthoredFields, Termination: tip);+ }++ /// <summary>Termination: Flat | DrillPoint | DrillPoint { PointAngle: 135deg }.</summary>+ internal static FirmamentV2SemanticHoleTermination? BindHoleTermination(ExpressionSyntax expression, List<string> diagnostics)+ {+ if (FirmamentSyntaxValues.Reference(expression) is "Flat" or "FlatBottom") return new(FirmamentV2SemanticHoleTerminationKind.FlatBottom);+ if (FirmamentSyntaxValues.Reference(expression) == "DrillPoint") return new(FirmamentV2SemanticHoleTerminationKind.DrillPoint, 118d);+ if (expression is ObjectSyntax { Type: ReferenceSyntax { Name.Text: "DrillPoint" } } point)+ {+ var angleField = point.Body.Statements.OfType<FieldSyntax>().SingleOrDefault(field => FirmamentSyntaxFields.SameField(field.Name.Text, "PointAngle"));+ if (point.Body.Statements.Count == 1 && angleField is not null && FirmamentSyntaxValues.TryMeasure(angleField.Value, "deg", out var angle) && angle > 0 && angle < 180)+ return new(FirmamentV2SemanticHoleTerminationKind.DrillPoint, angle);+ diagnostics.Add($"{HoleDrillPointAngleInvalid}: DrillPoint takes one field, PointAngle, between 0deg and 180deg (118deg when omitted).");+ return null;+ }+ diagnostics.Add($"{HoleConstructionPlaneExtentUnsupported}: Termination is Flat, DrillPoint or DrillPoint {{ PointAngle: ... }}.");+ return null;}private static string? MechanicalFinishKind(FirmamentSyntaxFields fields, List<string> diagnostics)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.csindex eb8f8f46..395a46b4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs@@ -57,7 +57,10 @@ internal static class FirmamentV2SemanticHoleLowering{FirmamentV2SemanticHoleVariant.Counterbore => AirHoleFeature.CreateCounterbore(hole.Name, $"{modify.TargetSolid}.{hole.Name}", modify.TargetSolid, placement, axis, shaft, endCondition, new AirHoleCounterboreComponent(Required(hole.CounterboreDiameter, "CounterboreDiameter"), Required(hole.CounterboreDepth, "CounterboreDepth")), provenance),FirmamentV2SemanticHoleVariant.Countersink => AirHoleFeature.CreateCountersink(hole.Name, $"{modify.TargetSolid}.{hole.Name}", modify.TargetSolid, placement, axis, shaft, endCondition, new AirHoleCountersinkComponent(Required(hole.CountersinkDiameter, "CountersinkDiameter"), Required(hole.CountersinkAngleDegrees, "CountersinkAngle")), provenance),- _ => AirHoleFeature.CreateSimpleShaft(hole.Name, $"{modify.TargetSolid}.{hole.Name}", modify.TargetSolid, placement, axis, shaft, endCondition, provenance)+ _ => hole.Termination is { Kind: FirmamentV2SemanticHoleTerminationKind.DrillPoint } tip+ ? AirHoleFeature.CreateSimpleShaft(hole.Name, $"{modify.TargetSolid}.{hole.Name}", modify.TargetSolid, placement, axis, shaft, endCondition, provenance)+ with { Termination = new AirHoleTermination.DrillPoint(tip.PointAngleDegrees ?? AirHoleTermination.DrillPoint.DefaultPointAngleDegrees) }+ : AirHoleFeature.CreateSimpleShaft(hole.Name, $"{modify.TargetSolid}.{hole.Name}", modify.TargetSolid, placement, axis, shaft, endCondition, provenance)};}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 869124a0..a28ac2c7 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -540,6 +540,32 @@ public static class ProfileAuthoringParser_ => double.NaN};+ /// <summary>+ /// The plane a straight Path step sweeps when its closed Path is extruded along the sketch normal, written as+ /// the explicit Concept plane an author would declare: origin at the foot of the sketch origin on the step's line,+ /// normal pointing into the material (to the left of a counter-clockwise loop), up along +Z. It is computed from+ /// source alone, so the plane moves with the Path and never refers to a body face.+ /// </summary>+ internal static bool TryDerivePathStepPlane(string source, string path, string step, out ConceptIrPlaneValue? plane, out string? diagnostic)+ {+ plane = null; diagnostic = null;+ var diagnostics = new List<string>();+ var paths = BindPaths(source, new(StringComparer.Ordinal), new(StringComparer.Ordinal), diagnostics);+ if (!paths.TryGetValue(path, out var bound)) { diagnostic = $"path-step-plane-path-unknown:{path}.{step}: '{path}' is not a Path in this model."; return false; }+ var boundStep = bound.Steps.FirstOrDefault(s => s.Name == step);+ if (boundStep is null) { diagnostic = $"path-step-plane-step-unknown:{path}.{step}: Path '{path}' has no step '{step}'."; return false; }+ if (boundStep.Curves is not [LineArcLineSegment2D line]) { diagnostic = $"path-step-plane-not-straight:{path}.{step}: only a straight Line step sweeps a plane."; return false; }+ var curves = bound.Steps.SelectMany(s => s.Curves).ToArray();+ if (!IsClosed(curves)) { diagnostic = $"path-step-plane-path-open:{path}.{step}: the Path must be closed for its inside to be known."; return false; }+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length = Math.Sqrt(dx * dx + dy * dy);+ dx /= length; dy /= length;+ var inward = SignedArea(curves) > 0 ? (X: -dy, Y: dx) : (X: dy, Y: -dx);+ var along = -(line.Start.X * dx + line.Start.Y * dy);+ var foot = (X: line.Start.X + dx * along, Y: line.Start.Y + dy * along);+ plane = new ConceptIrPlaneValue($"path-step:{path}.{step}", new(foot.X, foot.Y, 0d), new(inward.X, inward.Y, 0d), $"derived from Path step {path}.{step}", new(0d, 0d, 1d));+ return true;+ }+private static IReadOnlyDictionary<string, BoundPath> BindPaths(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics){var result = new Dictionary<string, BoundPath>(StringComparer.Ordinal);diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.csindex 0c344812..f715935c 100644--- a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs@@ -109,6 +109,8 @@ internal static class AirHoleSimpleShaftMaterializer{if (feature.ConstructionPlanePlacement is { } constructionPlacement)return ExecuteConstructionPlaneThroughAll(feature, host, constructionPlacement);+ if (TopFaceDrillPoint(feature, host) is { } drilled)+ return ExecuteConstructionPlaneThroughAll(drilled, host, drilled.ConstructionPlanePlacement!);var footprint = AirHoleFootprint.Classify(feature, host, FootprintTolerance);if (footprint.Contact is AirHoleFootprintContact.Tangent or AirHoleFootprintContact.Misses)@@ -174,6 +176,30 @@ internal static class AirHoleSimpleShaftMaterializerreturn new(AirHoleSimpleShaftMaterializationStatus.Succeeded, planResult.Plan, execution.Body, diagnostics, correspondence);}+ /// <summary>+ /// A blind drilled hole on the top face is the same construction as a drill from a plane coincident with that+ /// face: the plane is derived from the host, never a reference to its face. The frame is right-handed (X, -Y, -Z)+ /// at the top centre, so the face-local (U, V) maps to local (U, -V) and the drill enters along -Z.+ /// </summary>+ private static AirHoleFeature? TopFaceDrillPoint(AirHoleFeature feature, AirHoleSimpleShaftHost host)+ {+ if (feature.Placement is not AirFaceLocalHolePlacement { FaceName: "top" } face+ || feature.Termination is not AirHoleTermination.DrillPoint+ || feature.EndCondition is not AirHoleEndCondition.Depth depth+ || feature.Stack.Kind != AirHoleStackKind.SimpleShaft) return null;+ var placement = new AirConstructionPlaneHolePlacement($"derived:{feature.TargetBodyId}.top", $"derived:{feature.TargetBodyId}.top",+ new Aetheris.Kernel.Core.Math.Point3D(0d, 0d, host.ZMax),+ Direction3D.Create(new Vector3D(1d, 0d, 0d)), Direction3D.Create(new Vector3D(0d, -1d, 0d)), Direction3D.Create(new Vector3D(0d, 0d, -1d)),+ face.U, -face.V, "", "top-face-derived-plane");+ return feature with+ {+ Placement = placement,+ Axis = new AirHoleAxis(placement.AxisZ, false),+ EndCondition = new AirHoleEndCondition.ShaftDepth(depth.Value),+ Stack = AirHoleStack.SimpleShaft(feature.Shaft, new AirHoleEndCondition.ShaftDepth(depth.Value))+ };+ }+public static AirHoleSimpleShaftMaterializationResult TryCreatePlan(AirHoleFeature feature, AirHoleSimpleShaftHost host){var diagnostics = new List<string> { "air-hole-x2 semantic hole planner started." };diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 0f08cbb5..ff9840aa 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -221,8 +221,9 @@ public static class PrismaticProfileCompositionParserprivate static readonly Regex HoleCounterboreDepth = new(@"\bCounterboreDepth\s*:\s*(?<d>[-+.\d]+)mm", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex HoleOn = new(@"\bOn\s*:\s*(?<face>[+-][XYZ]|[A-Za-z_]\w*)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex HoleEnd = new(@"\bEnd\s*:\s*(?<end>\w+)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- private static readonly Regex HoleDepthEnd = new(@"\bEnd\s*:\s*(?<kind>ShaftDepth|TotalDepth)\s*\(\s*(?<depth>[-+.\d]+)mm\s*\)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- private static readonly Regex HoleFrom = new(@"\bFrom\s*:\s*(?<plane>\w+)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);+ // "Blind 45mm" is the shaft depth: drawings dimension a drilled hole's full-diameter depth, excluding the point.+ private static readonly Regex HoleDepthEnd = new(@"\bEnd\s*:\s*(?:(?<kind>ShaftDepth|TotalDepth)\s*\(\s*(?<depth>[-+.\d]+)mm\s*\)|(?<kind>Blind)\s+(?<depth>[-+.\d]+)mm)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);+ private static readonly Regex HoleFrom = new(@"\bFrom\s*:\s*(?<plane>\w+(?:\.\w+)?)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex HoleTermination = new(@"\bTermination\s*:\s*DrillPoint\b(?:\s*\{\s*PointAngle\s*:\s*(?<angle>[-+.\d]+)deg\s*\})?", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex HoleRole = new(@"\bRole\s*:\s*(?<role>\w+)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex SlotHeader = new(@"\bSlot\s*<\s*(?<variant>\w+)\s*>\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);@@ -678,14 +679,23 @@ public static class PrismaticProfileCompositionParserfields.Complete();if (from.Success){+ if (Regex.IsMatch(body, @"\bTermination\s*:\s*Flat", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))+ { diagnostics.Add($"compose-construction-plane-blind-hole-invalid-contract:{name}: A hole drilled from a Construction Plane ends in a drill point; a flat floor from a plane is not supported."); continue; }+ // A blind drilled hole has a 118° point unless Termination says otherwise.if (!string.Equals((FirmamentSyntaxValues.Reference(declaration.Type.Arguments.FirstOrDefault()?.Value) ?? ""), "Shaft", StringComparison.OrdinalIgnoreCase)- || !depthEnd.Success || !termination.Success)- { diagnostics.Add($"compose-construction-plane-blind-hole-invalid-contract:{name}"); continue; }+ || !depthEnd.Success || !termination.Success && Regex.IsMatch(body, @"\bTermination\s*:", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))+ { diagnostics.Add($"compose-construction-plane-blind-hole-invalid-contract:{name}: A Hole<Shaft> From a Construction Plane needs End: Blind <depth>, ShaftDepth(...) or TotalDepth(...), and optionally Termination: DrillPoint {{ PointAngle: ... }}."); continue; }if (!center.Success || !diameter.Success) { diagnostics.Add($"compose-construction-plane-blind-hole-missing-center-or-diameter:{name}"); continue; }- var trace = ResolveConstructionPlaneTrace(source, from.Groups["plane"].Value);+ // From: Outline.FrontMiddle names the plane a straight Path step sweeps; From: Work names a Construction Plane.+ var fromName = from.Groups["plane"].Value;+ var pathStep = fromName.Split('.');string? planeDiagnostic = null; string? frameDiagnostic = null;- if (trace is null || !ConceptIrResolver.TryResolvePlane(source, trace, out var conceptPlane, out planeDiagnostic)- || conceptPlane is null+ ConceptIrPlaneValue? conceptPlane = null;+ var trace = pathStep.Length == 2 ? null : ResolveConstructionPlaneTrace(source, fromName);+ var resolved = pathStep.Length == 2+ ? ProfileAuthoringParser.TryDerivePathStepPlane(source, pathStep[0], pathStep[1], out conceptPlane, out planeDiagnostic)+ : trace is not null && ConceptIrResolver.TryResolvePlane(source, trace, out conceptPlane, out planeDiagnostic);+ if (!resolved || conceptPlane is null|| !ConstructionPlane.TryTrace($"construction:{from.Groups["plane"].Value}", conceptPlane, $"offset:{declaration.Span.Start}", out var plane, out frameDiagnostic)){ diagnostics.Add(planeDiagnostic ?? frameDiagnostic ?? $"compose-construction-plane-not-found:{from.Groups["plane"].Value}"); continue; }var localX = N(center, "x"); var localY = N(center, "y"); var localDiameter = N(diameter, "d"); var declaredDepth = N(depthEnd, "depth");diff --git a/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs b/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.csindex 967749c5..9e10ac9f 100644--- a/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs+++ b/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs@@ -73,7 +73,7 @@ internal static class SectionStackBlindDrillCavityPlannerif (d.Count != 0) { diagnostics = d; return null; }var mouthHostFaceId = input.MouthHostFaceIds[0];- var mapping = source!.FaceMappings.SingleOrDefault(x => x.FaceId == mouthHostFaceId && x.Kind == "PrismaticSide");+ var mapping = source!.FaceMappings.SingleOrDefault(x => x.FaceId == mouthHostFaceId && x.Kind is "PrismaticSide" or "HostFaceReplacement");if (mapping is null) d.Add("SectionStackBlindDrillMouthFaceProvenanceMissing");if (!source.Topology.TryGetFace(mouthHostFaceId, out var originalFace) || originalFace is null) d.Add("SectionStackBlindDrillMouthFaceMissing");SurfaceGeometry? originalSurface = null;@@ -92,7 +92,7 @@ internal static class SectionStackBlindDrillCavityPlannerif (d.Count != 0) { diagnostics = d; return null; }var topology = CopyTopologyExceptShells(source.Topology, mouthHostFaceId);- var geometry = CopyGeometry(source.Geometry); var bindings = CopyBindings(source.Bindings);+ var geometry = CopyGeometry(source.Geometry); var bindings = CopyBindings(source.Bindings, mouthHostFaceId);var points = source.VertexPoints.ToDictionary(x => x.Key, x => x.Value);var nextVertex = source.Topology.Vertices.Max(x => x.Id.Value) + 1;var nextEdge = source.Topology.Edges.Max(x => x.Id.Value) + 1;@@ -229,7 +229,7 @@ internal static class SectionStackBlindDrillCavityPlannerif (t0 <= Tol || t1 >= seamLength - Tol || t1 - t0 <= Tol) { diagnostics = ["SectionStackMouthArcOwnershipAmbiguous"]; return null; }var topology = CopyTopologyExceptShells(source.Topology, faceIds);- var geometry = CopyGeometry(source.Geometry); var resultBindings = CopyBindings(source.Bindings);+ var geometry = CopyGeometry(source.Geometry); var resultBindings = CopyBindings(source.Bindings, faceIds);var points = source.VertexPoints.ToDictionary(x => x.Key, x => x.Value);var nextVertex = source.Topology.Vertices.Max(x => x.Id.Value) + 1;var nextEdge = source.Topology.Edges.Max(x => x.Id.Value) + 1;@@ -319,7 +319,8 @@ internal static class SectionStackBlindDrillCavityPlannerprivate static TopologyModel CopyTopologyExceptShells(TopologyModel source, params FaceId[] excludedFaces){ var excluded = excludedFaces.ToHashSet(); var copy = new TopologyModel(); foreach (var x in source.Vertices) copy.AddVertex(x); foreach (var x in source.Edges) copy.AddEdge(x); foreach (var x in source.Coedges) copy.AddCoedge(x); foreach (var x in source.Loops) copy.AddLoop(x); foreach (var x in source.Faces.Where(x => !excluded.Contains(x.Id))) copy.AddFace(x); return copy; }private static BrepGeometryStore CopyGeometry(BrepGeometryStore source) { var copy = new BrepGeometryStore(); foreach (var x in source.Curves) copy.AddCurve(x.Key, x.Value); foreach (var x in source.Surfaces) copy.AddSurface(x.Key, x.Value); return copy; }- private static BrepBindingModel CopyBindings(BrepBindingModel source) { var copy = new BrepBindingModel(); foreach (var x in source.EdgeBindings) copy.AddEdgeBinding(x); foreach (var x in source.FaceBindings) copy.AddFaceBinding(x); return copy; }+ // Bindings of replaced faces are dropped with the faces; a binding to a missing face fails STEP preflight.+ private static BrepBindingModel CopyBindings(BrepBindingModel source, params FaceId[] excludedFaces) { var excluded = excludedFaces.ToHashSet(); var copy = new BrepBindingModel(); foreach (var x in source.EdgeBindings) copy.AddEdgeBinding(x); foreach (var x in source.FaceBindings.Where(x => !excluded.Contains(x.FaceId))) copy.AddFaceBinding(x); return copy; }}/// <summary>@@ -341,8 +342,32 @@ public static class SectionStackBlindDrillComposeBridgevar declarations = stack.Feature.ConstructionPlaneBlindDrills ?? [];evidence = null;if (declarations.Count == 0) { diagnostics = d; return hostPlan; }- if (declarations.Count != 1) { diagnostics = ["SectionStackBlindDrillOnlyOneFeatureIsAdmitted"]; return null; }- var declaration = declarations[0];+ // Several drills apply one after another to the same exact plan. Each corridor is proven against the+ // stack's own material; disjoint tool envelopes make the order irrelevant.+ var applied = new List<(string FeatureId, Point3D Mouth, Vector3D Axis, double Depth, double Radius)>();+ var plan = hostPlan;+ foreach (var declaration in declarations)+ {+ // A failing drill reports its own diagnostics, not the progress markers of the drills before it.+ var local = new List<string>();+ plan = TryApplyOne(stack, plan, declaration, applied, local, out evidence);+ if (plan is null) { diagnostics = local; return null; }+ d.AddRange(local);+ }++ diagnostics = d;+ return plan;+ }++ private static PrismaticSectionStackBrepPlan? TryApplyOne(+ PrismaticSectionStackConstruction stack,+ PrismaticSectionStackBrepPlan hostPlan,+ PrismaticConstructionPlaneBlindDrillFeature declaration,+ List<(string FeatureId, Point3D Mouth, Vector3D Axis, double Depth, double Radius)> applied,+ List<string> d,+ out BlindDrillToolCorridorEvidence? evidence)+ {+ evidence = null;var placement = new AirConstructionPlaneHolePlacement(declaration.ConstructionPlaneId, declaration.SourceConceptPlaneId,declaration.FrameOrigin, declaration.AxisX, declaration.AxisY, declaration.AxisZ, declaration.LocalCenterX, declaration.LocalCenterY,declaration.SourceSpan, declaration.Provenance);@@ -358,29 +383,95 @@ public static class SectionStackBlindDrillComposeBridgevar corridor = TransverseBlindDrillToolCorridor.Prove(feature, stack, placement);evidence = corridor;if (corridor.Classification != BlindDrillToolCorridorClassification.CorridorProven)- { d.AddRange(corridor.Diagnostics); d.Add("SectionStackBlindDrillClearanceContractRejected"); diagnostics = d; return null; }+ { d.AddRange(corridor.Diagnostics); d.Add("SectionStackBlindDrillClearanceContractRejected"); return null; }++ var mouth = placement.WorldMouthCenter; var axis = placement.AxisZ.ToVector(); var depth = corridor.ShaftDepth + corridor.TipLength;+ foreach (var other in applied)+ {+ // Conservative: full-radius cylinders through each total depth are disjoint when their axis+ // segments stay farther apart than the sum of the radii.+ if (SegmentDistance(mouth, mouth + axis * depth, other.Mouth, other.Mouth + other.Axis * other.Depth) <= feature.Shaft.Radius + other.Radius + Tol)+ { d.Add($"SectionStackBlindDrillToolEnvelopesIntersect:{other.FeatureId}:{feature.FeatureId}"); return null; }+ }var faces = FindMouthFaces(hostPlan.TopologyPlan!, placement, feature.Shaft.Radius, d);- if (faces is null) { diagnostics = d; return null; }+ if (faces is null) return null;var cavity = SectionStackBlindDrillCavityPlanner.TryPlan(new(stack, hostPlan, feature, placement, corridor, faces), out var cavityDiagnostics);d.AddRange(cavityDiagnostics);- if (cavity is null) { diagnostics = d; return null; }+ if (cavity is null) return null;d.Add("SectionStackBlindDrillComposeBridge");- diagnostics = d;+ applied.Add((feature.FeatureId, mouth, axis, depth, feature.Shaft.Radius));return cavity.ReplacementHostPlan;}+ private static double SegmentDistance(Point3D p0, Point3D p1, Point3D q0, Point3D q1)+ {+ var u = p1 - p0; var v = q1 - q0; var w = p0 - q0;+ double a = u.Dot(u), b = u.Dot(v), c = v.Dot(v), dd = u.Dot(w), e = v.Dot(w);+ var denominator = a * c - b * b;+ var s = denominator < 1e-12 ? 0 : Math.Clamp((b * e - c * dd) / denominator, 0, 1);+ var t = c < 1e-12 ? 0 : Math.Clamp((b * s + e) / c, 0, 1);+ s = a < 1e-12 ? 0 : Math.Clamp((b * t - dd) / a, 0, 1);+ return ((p0 + u * s) - (q0 + v * t)).Length;+ }++ private enum DiskContainment { Inside, Crossing, Outside }++ /// <summary>+ /// Where the mouth disk lies relative to one straight-edged planar host face, in the hole's frame:+ /// wholly inside, crossing the boundary, or wholly outside. A face that is not a straight-edged single+ /// loop reports Crossing so it stays a candidate for the existing seam rules.+ /// </summary>+ private static DiskContainment DiskInsideFace(PrismaticSectionStackTopologyPlan plan, FaceId faceId, AirConstructionPlaneHolePlacement placement, double radius)+ {+ // The first loop is the outer boundary; inner loops are earlier holes' mouths, which the pairwise+ // tool-envelope check already keeps clear of this one.+ if (!plan.Topology.TryGetFace(faceId, out var face) || face is null || face.LoopIds.Count == 0) return DiskContainment.Crossing;+ var loop = plan.Topology.Loops.Single(l => l.Id == face.LoopIds[0]);+ var u = placement.AxisX.ToVector(); var v = placement.AxisY.ToVector(); var mouth = placement.WorldMouthCenter;+ var polygon = new List<(double U, double V)>();+ foreach (var coedgeId in loop.CoedgeIds)+ {+ var coedge = plan.Topology.Coedges.Single(c => c.Id == coedgeId);+ var edge = plan.Topology.Edges.Single(e => e.Id == coedge.EdgeId);+ if (!plan.Bindings.TryGetEdgeBinding(edge.Id, out var binding) || !plan.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve)+ || curve?.Kind != CurveGeometryKind.Line3) return DiskContainment.Crossing;+ var p = plan.VertexPoints[coedge.IsReversed ? edge.EndVertexId : edge.StartVertexId] - mouth;+ polygon.Add((p.Dot(u), p.Dot(v)));+ }++ var inside = false;+ var nearest = double.PositiveInfinity;+ for (var i = 0; i < polygon.Count; i++)+ {+ var a = polygon[i]; var b = polygon[(i + 1) % polygon.Count];+ if ((a.V > 0) != (b.V > 0) && 0 < a.U + (0 - a.V) * (b.U - a.U) / (b.V - a.V)) inside = !inside;+ var du = b.U - a.U; var dv = b.V - a.V; var lengthSquared = du * du + dv * dv;+ var t = lengthSquared <= 0 ? 0 : Math.Clamp(-(a.U * du + a.V * dv) / lengthSquared, 0, 1);+ nearest = Math.Min(nearest, Math.Sqrt(Math.Pow(a.U + t * du, 2) + Math.Pow(a.V + t * dv, 2)));+ }++ // A disk tangent to a face's boundary from outside still touches it: it stays a candidate so the+ // tangency rules can reject it, rather than being filtered away as unrelated.+ if (inside) return nearest >= radius - Tol ? DiskContainment.Inside : DiskContainment.Crossing;+ return nearest > radius + Tol ? DiskContainment.Outside : DiskContainment.Crossing;+ }+private static IReadOnlyList<FaceId>? FindMouthFaces(PrismaticSectionStackTopologyPlan plan, AirConstructionPlaneHolePlacement placement, double radius, List<string> diagnostics){var mouth = placement.WorldMouthCenter; var axis = placement.AxisZ.ToVector();- var compatible = plan.FaceMappings.Where(x => x.Kind == "PrismaticSide")+ var compatible = plan.FaceMappings.Where(x => x.Kind is "PrismaticSide" or "HostFaceReplacement").Where(x => plan.Bindings.TryGetFaceBinding(x.FaceId, out var binding)&& plan.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var surface)&& surface is { Kind: SurfaceGeometryKind.Plane, Plane: { } plane }&& Math.Abs(Math.Abs(plane.Normal.ToVector().Dot(axis)) - 1d) <= Tol&& Math.Abs((mouth - plane.Origin).Dot(plane.Normal.ToVector())) <= Tol).ToArray();- var candidates = compatible.Where(x => x.SlabFrom is { } from && x.SlabTo is { } to && mouth.Z - radius >= from - Tol && mouth.Z + radius <= to + Tol).ToArray();+ // Coplanar side faces of one slab (an edge interrupted by notches) share plane and Z range; the+ // mouth belongs to the one whose own boundary encloses the mouth disk.+ compatible = compatible.Where(x => DiskInsideFace(plan, x.FaceId, placement, radius) != DiskContainment.Outside).ToArray();+ var candidates = compatible.Where(x => x.SlabFrom is { } from && x.SlabTo is { } to && mouth.Z - radius >= from - Tol && mouth.Z + radius <= to + Tol+ && DiskInsideFace(plan, x.FaceId, placement, radius) == DiskContainment.Inside).ToArray();if (candidates.Length == 1){var tangent = compatible.Any(x => x.FaceId != candidates[0].FaceIddiff --git a/docs/development/reports/2026-11/CTC-01-DECOMPILE.md b/docs/development/reports/2026-11/CTC-01-DECOMPILE.mdindex 1f9f368c..3d1155e3 100644--- a/docs/development/reports/2026-11/CTC-01-DECOMPILE.md+++ b/docs/development/reports/2026-11/CTC-01-DECOMPILE.md@@ -103,6 +103,41 @@ steps, but none are in the public docs. `Notch` is rectangular with sharp cornerCTC-01's notches still need a corner radius, and its V-notches a V form with a tip radius. Item 3 isbetter framed as extending these steps than as new path primitives.+## Follow-up: drilled holes (item 1)++Plane-hosted holes already existed as `Hole<Shaft> { From: <Construction Plane>; End: ShaftDepth(...);+Termination: DrillPoint }`. The public docs said they were unsupported. On CTC-01 they failed for reasons+that were bugs and limits, not missing design:++- **Mouth-face selection matched only plane and Z slab.** The front edge is three coplanar faces split by the+ V-notches, so the match was ambiguous. A mouth host must now enclose the mouth disk inside its own boundary.+ Faces the disk merely touches stay candidates, so tangency is still refused.+- **Only one drill per body.** Drills now apply in sequence to the exact plan. A pairwise check (segment+ distance against the sum of radii, through total depth) refuses touching tool envelopes, and an+ already-drilled face can host another mouth.+- **The drilled face's geometry binding was copied after the face was removed.** STEP preflight rejected the+ dangling binding in the composed-chamfer route.+- **The composed-chamfer route re-emitted the stack without its drills.** Both routes now apply drills through+ one helper.++New behaviour:++- **Blind means drilled.** A blind `Hole<Shaft>` ends in a 118° point. `termination: DrillPoint { pointAngle }`+ changes the angle and `termination: Flat` keeps a flat floor. `End: Blind <d>` is the full-diameter depth.+ On Box stock, the top-face drill is built in a plane derived from the box (X, −Y, −Z at the top centre).+- **`From: Outline.FrontMiddle`** names the plane a straight Path step sweeps. It is computed from source as+ the Concept plane an author would write. Right-handedness forces its u axis to run against the step for a+ counter-clockwise outline, the same frame an explicit plane with that normal and up gets.+- The canonical blind-hole example, the Learn lesson and the reference describe the new default. The+ all-edge rounding witness states `termination: Flat`.++CTC-01 now drills both side holes as `from: Outline.FrontMiddle; end: Blind 45mm` plus a mirror. Carriers are+75/85 with 0 extra, and IoU is 0.9989. Everything still missing is fillet: the lug underside R10 and the hex+foot R5.++`analyze compare --shape` also skips rays with an odd crossing count, near cone apexes and seams, on both+sides. It used to read them as empty, which showed about 1100 mm³ of false difference per drill tip.+## VerdictMeaningful progression. CTC-01 builds with every feature Firmament can express, and the comparisondiff --git a/docs/public/learn/01-first-part.md b/docs/public/learn/01-first-part.mdindex 64dc34c5..6d1e30bc 100644--- a/docs/public/learn/01-first-part.md+++ b/docs/public/learn/01-first-part.md@@ -102,7 +102,9 @@ opens the part in Cadmata.## Try it- Move the hole to `Point2(25mm, 10mm)` and rebuild.-- Change `end: ThroughAll` to `end: Blind 5mm` for a 5 mm deep blind hole.+- Change `end: ThroughAll` to `end: Blind 5mm` for a 5 mm deep drilled hole. It+ ends in a 118° drill point below the 5 mm of full diameter; add+ `termination: Flat` for a flat floor.The [hole fixtures](../../../fixtures/Canonical/Features/Holes/) show everyform.- Make the hole 60 mm wide, wider than the plate, and read the diagnostic: thediff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.mdindex edbc4f9e..a15c1587 100644--- a/docs/public/reference/language/solids-and-features.md+++ b/docs/public/reference/language/solids-and-features.md@@ -104,6 +104,58 @@ This bounded stack rejects arbitrary placements, mismatched joining radii, radia`end` is `ThroughAll` or `Blind <depth>`, for example `end: Blind 10mm`. A fieldfrom another variant, such as `counterboreDepth` on a Shaft hole, is an error.+A blind `Hole<Shaft>` is a drilled hole. It ends in a 118° drill point, and its+depth is the full-diameter depth, excluding the point, as drawings dimension it.+`termination` changes the end:++| `termination` | End of the hole |+| --- | --- |+| omitted, or `DrillPoint` | 118° drill point |+| `DrillPoint { pointAngle: 135deg }` | drill point with that included angle |+| `Flat` | flat floor (a flat-bottom drill or end mill) |++`termination` applies to blind holes only. Blind counterbores and countersinks+have flat floors; a drill point on them is rejected. On Box stock, the top-face+drill point is built in a plane derived from the box, never from a face+reference.++### Holes from a plane++`from` replaces `on` to drill from a plane instead of a host face. Name an+explicit `Construction Plane` (Box and Compose bodies), or, on a Compose body, a+straight step of a closed Path, normally the Path its Profile is traced from:++```firmament+Hole<Shaft> SideDrill { from: Outline.FrontMiddle; center: Point2(-30mm, -25mm); diameter: 20mm; end: Blind 45mm }+Mirrored Feature SideDrillMirror from SideDrill { across: CenterPlane }+```++`Outline.FrontMiddle` is shorthand for the plane that step sweeps when the Path is+extruded. It is computed from the Path alone, so it moves when the Path changes+and never refers to a body face. Written out, it is+`Plane { origin: <foot of the sketch origin on the step's line>; normal: <into the material>; up: [0, 0, 1] }`.+`center` is in that plane's frame: v runs along the extrusion (+Z), the hole runs+into the material, and u completes a right-handed frame. For a counter-clockwise+outline, u therefore runs against the step's direction; on a front edge stepped+along +X, u is world −X. The+[CTC-01 reconstruction](../../../../fixtures/Regression/Decompile/ctc-01.firmament)+uses this form.++Rules:++- `end` is `Blind <depth>`, `ShaftDepth(<depth>)` or `TotalDepth(<depth>)`+ (depth including the point). The hole ends in a drill point; `termination:+ Flat` from a plane is rejected.+- The mouth must lie wholly inside one planar side face of the body, which must+ coincide with the plane. Coplanar faces separated by notches are told apart by+ their own boundaries.+- On Box stock the plane's axes must be signed world axes. On a Compose body the+ drill direction is ±X or ±Y. The full-radius tool+ envelope through the point must stay in material, and envelopes of different+ drills must not touch.+- A Path-step plane needs a straight `Line` step of a closed Path in the XY+ sketch.+In a Compose body, all three variants are supported on the `+Z` support with`end: ThroughAll`:@@ -114,8 +166,8 @@ In a Compose body, all three variants are supported on the `+Z` support withslots. Overlapping or tangent entries and breakouts through a wall reject.- A counterbore or countersink must leave a positive length of plain shaft belowit. A countersink is an exact cone.-- Holes on other supports of a Compose body, and blind counterbores or- countersinks there, are not supported.+- Blind holes on `+Z` of a Compose body, and holes on its other faces through+ `on`, are not supported; drill side holes with `from`.## Edge finishesdiff --git a/fixtures/Invalid/Hole/drill-envelopes-touch.firmament b/fixtures/Invalid/Hole/drill-envelopes-touch.firmamentnew file mode 100644index 00000000..3b9887b0--- /dev/null+++ b/fixtures/Invalid/Hole/drill-envelopes-touch.firmament@@ -0,0 +1,11 @@+Model DrillEnvelopesTouch {+ units: mm+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [60mm, 30mm] }+ Compose Body { Base Stock { profile: Plate; from: -10mm; to: 0mm; role: Stock } }+ Concept Struct Datums { Front: Plane { origin: [0mm, -15mm, 0mm]; normal: [0, 1, 0]; up: [0, 0, 1] } }+ Construction Plane FrontFace { trace: Datums.Front }+ Modify Body {+ Hole<Shaft> A { from: FrontFace; center: Point2(0mm, -5mm); diameter: 4mm; end: Blind 8mm }+ Hole<Shaft> B { from: FrontFace; center: Point2(3mm, -5mm); diameter: 4mm; end: Blind 8mm }+ }+}diff --git a/fixtures/Invalid/Hole/plane-drill-flat.firmament b/fixtures/Invalid/Hole/plane-drill-flat.firmamentnew file mode 100644index 00000000..91444f77--- /dev/null+++ b/fixtures/Invalid/Hole/plane-drill-flat.firmament@@ -0,0 +1,10 @@+Model PlaneDrillFlat {+ units: mm+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [60mm, 30mm] }+ Compose Body { Base Stock { profile: Plate; from: -10mm; to: 0mm; role: Stock } }+ Concept Struct Datums { Front: Plane { origin: [0mm, -15mm, 0mm]; normal: [0, 1, 0]; up: [0, 0, 1] } }+ Construction Plane FrontFace { trace: Datums.Front }+ Modify Body {+ Hole<Shaft> A { from: FrontFace; center: Point2(0mm, -5mm); diameter: 4mm; end: Blind 8mm; termination: Flat }+ }+}diff --git a/fixtures/Regression/Decompile/ctc-01.firmament b/fixtures/Regression/Decompile/ctc-01.firmamentindex ae7dceb7..4c8bd991 100644--- a/fixtures/Regression/Decompile/ctc-01.firmament+++ b/fixtures/Regression/Decompile/ctc-01.firmament@@ -3,8 +3,6 @@// notches in the long edges. Compare against the original with// aetheris analyze compare <original.stp> <this.step> --shape// Not expressible yet, and therefore absent here:-// - two horizontal Ø20 blind drilled holes with 118° points entering the -Y face at x = ±30, z = -25-// (Compose holes are +Z through holes only);// - the R5 fillet at the hex boss's foot (a second finish on the body, and a concave boss foot);// - R10 fillets where the lugs' inner walls meet the plate underside (no selection of individual// concave edges).@@ -132,6 +130,10 @@ Model Ctc01 {Mirrored Feature LugHoleBackRight from LugHoleBackLeft { across: CenterPlane }Mirrored Feature LugHoleFrontLeft from LugHoleBackLeft { across: MidPlane }Mirrored Feature LugHoleFrontRight from LugHoleBackRight { across: MidPlane }+ // Two Ø20 blind drilled holes into the front face, 45 mm full-diameter depth with the default 118° point.+ // The plane is the one the Outline's FrontMiddle step sweeps; its u axis runs along world -X.+ Hole<Shaft> SideDrillRight { from: Outline.FrontMiddle; center: Point2(-30mm, -25mm); diameter: 20mm; end: Blind 45mm }+ Mirrored Feature SideDrillLeft from SideDrillRight { across: CenterPlane }EdgeFinish<Chamfer> HexTop { on: Top; target: HexBoss.Outer; distance: 5mm }}}diff --git a/fixtures/Regression/Hole/valid/blind-drillpoint-angle.firmament b/fixtures/Regression/Hole/valid/blind-drillpoint-angle.firmamentnew file mode 100644index 00000000..205d5722--- /dev/null+++ b/fixtures/Regression/Hole/valid/blind-drillpoint-angle.firmament@@ -0,0 +1,8 @@+// A top-face blind hole with an explicit 135° drill point.+Model BlindDrillPointAngle {+ units: mm+ Box Base { size: [60mm, 40mm, 20mm] }+ Modify Base {+ Hole<Shaft> Steep { on: +Z; center: Point2(-15mm, 5mm); diameter: 8mm; end: Blind 10mm; termination: DrillPoint { pointAngle: 135deg } }+ }+}diff --git a/fixtures/Regression/Hole/valid/blind-drillpoint-default.firmament b/fixtures/Regression/Hole/valid/blind-drillpoint-default.firmamentnew file mode 100644index 00000000..4604d658--- /dev/null+++ b/fixtures/Regression/Hole/valid/blind-drillpoint-default.firmament@@ -0,0 +1,8 @@+// A top-face blind hole on Box stock: Blind ends in the default 118° drill point.+Model BlindDrillPointDefault {+ units: mm+ Box Base { size: [60mm, 40mm, 20mm] }+ Modify Base {+ Hole<Shaft> Default { on: +Z; center: Point2(-15mm, 5mm); diameter: 8mm; end: Blind 10mm }+ }+}diff --git a/fixtures/Regression/Hole/valid/blind-flat-floor.firmament b/fixtures/Regression/Hole/valid/blind-flat-floor.firmamentnew file mode 100644index 00000000..3852074e--- /dev/null+++ b/fixtures/Regression/Hole/valid/blind-flat-floor.firmament@@ -0,0 +1,8 @@+// A top-face blind hole whose flat floor is stated explicitly.+Model BlindFlatFloor {+ units: mm+ Box Base { size: [60mm, 40mm, 20mm] }+ Modify Base {+ Hole<Shaft> Flat { on: +Z; center: Point2(-15mm, 5mm); diameter: 8mm; end: Blind 10mm; termination: Flat }+ }+}diff --git a/fixtures/Regression/Hole/valid/path-step-plane-drills.firmament b/fixtures/Regression/Hole/valid/path-step-plane-drills.firmamentnew file mode 100644index 00000000..5461e919--- /dev/null+++ b/fixtures/Regression/Hole/valid/path-step-plane-drills.firmament@@ -0,0 +1,25 @@+// Three blind drilled holes from Path-step planes. The front edge is split by a notch, so FrontLeft and FrontRight+// are coplanar faces of the same slab; each drill must land in its own face. Default 118° points.+Model PathStepPlaneDrills {+ units: mm+ Path Outline {+ start: Point2(-30mm, -15mm)+ heading: 0deg+ Line FrontLeft { length: 20mm }+ Line NotchIn { turn: 90deg; length: 5mm }+ Line NotchFloor { turn: -90deg; length: 20mm }+ Line NotchOut { turn: -90deg; length: 5mm }+ Line FrontRight { turn: 90deg; length: 20mm }+ Line Right { turn: 90deg; length: 30mm }+ Line Back { turn: 90deg; length: 60mm }+ Close Left+ }+ Profile Plate from Outline+ Compose Body { Base Stock { profile: Plate; from: -10mm; to: 0mm; role: Stock } }+ Modify Body {+ // u runs against each step's direction: world -X on the front edge, +X on the back edge.+ Hole<Shaft> FrontLeftDrill { from: Outline.FrontLeft; center: Point2(20mm, -5mm); diameter: 4mm; end: Blind 8mm }+ Hole<Shaft> FrontRightDrill { from: Outline.FrontRight; center: Point2(-20mm, -5mm); diameter: 4mm; end: Blind 8mm }+ Hole<Shaft> BackDrill { from: Outline.Back; center: Point2(0mm, -5mm); diameter: 4mm; end: Blind 8mm }+ }+}diff --git a/fixtures/Regression/UniformRounding/blind-hole-rounded.firmament b/fixtures/Regression/UniformRounding/blind-hole-rounded.firmamentindex 10c70f63..f1060911 100644--- a/fixtures/Regression/UniformRounding/blind-hole-rounded.firmament+++ b/fixtures/Regression/UniformRounding/blind-hole-rounded.firmament@@ -2,7 +2,7 @@ Model RoundedBlindHole {units: mmBox Base { size: [60mm, 40mm, 20mm] }Modify Base {- Hole<Shaft> BlindMount { on: +Z; center: Point2(0mm, 0mm); diameter: 8mm; end: Blind 10mm }+ Hole<Shaft> BlindMount { on: +Z; center: Point2(0mm, 0mm); diameter: 8mm; end: Blind 10mm; termination: Flat }EdgeFinish<Fillet> Round { target: AllEdges; radius: 0.5mm }}}