Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Firmament: junction fillets (EdgeFinish<Fillet> { where: A meets B }); exact mitres in local rounding

Claudeeecc1e7418d6
diff --git a/Aetheris.CLI.Tests/JunctionFilletCliTests.cs b/Aetheris.CLI.Tests/JunctionFilletCliTests.cs
new file mode 100644
index 00000000..270a3646
--- /dev/null
+++ b/Aetheris.CLI.Tests/JunctionFilletCliTests.cs
@@ -0,0 +1,102 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+/// <summary><c>EdgeFinish&lt;Fillet&gt; { where: A meets B }</c>: the edges where two Compose operations meet, rounded by
+/// one ball, with exact cylinders along straight edges and quarter-ellipse mitres where they turn a corner.</summary>
+public sealed class JunctionFilletCliTests
+{
+ private static readonly string RepoRoot = FindRepoRoot();
+
+ [Fact]
+ public void HexBossFootIsSixCylindersMitredByEllipses()
+ {
+ var body = BuildAndImport("fixtures/Regression/JunctionFillet/hex-boss-foot.firmament");
+ var cylinders = body.Topology.Faces.Select(f => body.TryGetFaceSurface(f.Id, out var s) ? s?.Cylinder : null).OfType<Aetheris.Kernel.Core.Geometry.Surfaces.CylinderSurface>().ToArray();
+ Assert.Equal(6, cylinders.Length);
+ foreach (var cylinder in cylinders)
+ {
+ Assert.Equal(5d, cylinder.Radius, 9);
+ // Each axis runs 5 mm above the plate and 5 mm out from a hex flat (50 mm from the centre).
+ var axis = cylinder.Axis.ToVector();
+ Assert.Equal(0d, axis.Z, 9);
+ var origin = cylinder.Origin;
+ Assert.Equal(5d, origin.Z, 9);
+ var normal = new Aetheris.Kernel.Core.Math.Vector3D(axis.Y, -axis.X, 0);
+ Assert.Equal(55d, double.Abs(normal.Dot(origin - Aetheris.Kernel.Core.Math.Point3D.Origin)), 9);
+ }
+ var ellipses = body.Topology.Edges.Count(e => body.Bindings.TryGetEdgeBinding(e.Id, out var b) && body.Geometry.TryGetCurve(b.CurveGeometryId, out var c) && c?.Kind == CurveGeometryKind.Ellipse3);
+ Assert.Equal(6, ellipses);
+ Assert.Equal(19, body.Topology.Faces.Count());
+ }
+
+ [Fact]
+ public void FilletAddsTheMitredPrismVolume()
+ {
+ var filleted = Build("fixtures/Regression/JunctionFillet/hex-boss-foot.firmament");
+ var plain = Build("fixtures/Regression/JunctionFillet/hex-boss-foot.firmament", s => s.Replace("EdgeFinish<Fillet> HexFoot { where: Hex meets Stock; radius: 5mm }", "", StringComparison.Ordinal));
+ var result = StepShapeComparison.Compare(plain, filleted);
+ // The concave fillet's cross-section, r²(1 - π/4), swept along its centroid's path, which the mitres keep
+ // straight between the bisector planes.
+ var r = 5d; var side = 100d / Math.Sqrt(3);
+ var area = r * r * (1 - Math.PI / 4);
+ var centroid = (r * r * r / 2 - Math.PI * r * r / 4 * (r - 4 * r / (3 * Math.PI))) / area;
+ var expected = 6 * area * (side + 2 * centroid * Math.Tan(Math.PI / 6));
+ Assert.Equal(expected, result.Overlap.CandidateVolume - result.Overlap.ReferenceVolume, expected * 0.02);
+ Assert.Empty(result.Carriers.MissingFromCandidate);
+ Assert.Equal(6, result.Carriers.ExtraInCandidate.Count);
+ }
+
+ [Theory]
+ [InlineData("unknown-operand.firmament", "'Plinth' is not an operation of Compose Body; it has Stock, Hex")]
+ [InlineData("unknown-role.firmament", "'role Pad' is not a role of Compose Body")]
+ [InlineData("chamfer-kind.firmament", "'where' selects edges for EdgeFinish<Fillet> only")]
+ [InlineData("where-not-junction.firmament", "write where: A meets B")]
+ [InlineData("too-large.firmament", "the largest that fits is under 19.28")]
+ public void UnsupportedJunctionsAreRefused(string fixture, string expected)
+ {
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+ var exit = CliRunner.Run(["validate", Path.Combine(RepoRoot, "fixtures/Invalid/JunctionFillet", 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 messages = report.GetProperty("diagnostics").EnumerateArray().Select(d => d.GetProperty("message").GetString()).ToArray();
+ Assert.Contains(messages, m => m!.Contains(expected, StringComparison.Ordinal));
+ }
+
+ private static BrepBody BuildAndImport(string fixture)
+ {
+ var import = Step242Importer.ImportBody(File.ReadAllText(Build(fixture)));
+ Assert.True(import.IsSuccess, string.Join("; ", import.Diagnostics.Select(d => d.Message)));
+ return import.Value;
+ }
+
+ private static string Build(string fixture, Func<string, string>? edit = null)
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-junction-fillet", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ var source = Path.Combine(RepoRoot, fixture);
+ if (edit is not null)
+ {
+ var copy = Path.Combine(directory, Path.GetFileName(fixture));
+ File.WriteAllText(copy, edit(File.ReadAllText(source)));
+ source = copy;
+ }
+ var step = Path.Combine(directory, Path.GetFileNameWithoutExtension(fixture) + ".step");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+ Assert.True(CliRunner.Run(["build", source, "--out", step], stdout, stderr) == 0, $"{fixture}: {stderr}{stdout}");
+ return step;
+ }
+
+ 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.cs
index b9d606cc..d46b2f69 100644
--- a/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs
+++ b/Aetheris.CLI.Tests/ShapeComparisonCliTests.cs
@@ -53,16 +53,14 @@ 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.9985, $"IoU {result.Overlap.IntersectionOverUnion}");
- Assert.True(result.Carriers.MatchedCarrierCount >= 75, $"matched {result.Carriers.MatchedCarrierCount}");
+ Assert.True(result.Overlap.IntersectionOverUnion >= 0.999, $"IoU {result.Overlap.IntersectionOverUnion}");
+ Assert.True(result.Carriers.MatchedCarrierCount >= 81, $"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(
- IsHexFootFillet(carrier) || IsLugUndersideFillet(carrier),
- $"Unexpected missing carrier: {carrier.Description}");
+ Assert.True(IsLugUndersideFillet(carrier), $"Unexpected missing carrier: {carrier.Description}");
}
}
@@ -110,9 +108,6 @@ public sealed class ShapeComparisonCliTests
Assert.True(shape.GetProperty("overlap").GetProperty("candidateOnlyVolume").GetDouble() > 0);
}
- 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;
-
private static bool IsLugUndersideFillet(StepShapeComparison.CarrierGroup c)
=> c.Kind == "Cylinder" && c.Description.Contains("r=10 ", StringComparison.Ordinal)
&& c.BoundsMin is { } lo && c.BoundsMax is { } hi && lo[2] >= -60.01 && hi[2] <= -49.99;
diff --git a/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.cs b/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.cs
index e607f60c..dbfee39c 100644
--- a/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.cs
+++ b/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.cs
@@ -115,22 +115,29 @@ internal static class LocalRounding
}
}
- /// <summary>An edge's shape from its start to its end: a segment, or an arc about a normal (right-handed).</summary>
- private sealed record Shape(Point3D Start, Point3D End, Point3D? Center, Vector3D Normal, double Sweep)
+ /// <summary>An edge's shape from its start to its end: a segment, an arc about a normal (right-handed), or a
+ /// quarter ellipse about <see cref="Mitre"/> whose two semi-axes run to its ends (a mitre between two strips).</summary>
+ private sealed record Shape(Point3D Start, Point3D End, Point3D? Center, Vector3D Normal, double Sweep, Point3D? Mitre = null)
{
public bool Arc => Center is not null;
- public Point3D At(double t) => !Arc ? Start + (End - Start) * t : Rotate(Start, Center!.Value, Normal, Sweep * t);
+ public Point3D At(double t) => Mitre is { } m
+ ? m + (Start - m) * double.Cos(t * double.Pi / 2) + (End - m) * double.Sin(t * double.Pi / 2)
+ : !Arc ? Start + (End - Start) * t : Rotate(Start, Center!.Value, Normal, Sweep * t);
public Vector3D Tangent(Point3D p) => !Arc ? Unit(End - Start) : Unit(Normal.Cross(p - Center!.Value));
public IEnumerable<Point3D> Points(int arcSegments) =>
- Arc ? Enumerable.Range(0, arcSegments + 1).Select(i => At(i / (double)arcSegments)) : [Start, End];
+ Arc || Mitre is not null ? Enumerable.Range(0, arcSegments + 1).Select(i => At(i / (double)arcSegments)) : [Start, End];
}
/// <summary>Which edges a pass rounds: every sharp edge, or only the concave ones (the first pass where convex
/// and concave edges meet at a corner: fillets before rounds).</summary>
- internal enum Pass { All, ConcaveOnly }
+ internal enum Pass { All, ConcaveOnly, Selected }
+
+ /// <summary>A sharp edge offered to a selective rounding: its midpoint, a point just inside each of its two faces
+ /// with that face's surface, and whether it is concave.</summary>
+ internal sealed record EdgeQuery(Point3D Midpoint, Point3D InsideA, SurfaceGeometry SurfaceA, Point3D InsideB, SurfaceGeometry SurfaceB, bool Concave);
internal const string MixedCode = "uniform-rounding-mixed-vertex-unsupported";
@@ -145,15 +152,18 @@ internal static class LocalRounding
// +1 across a convex edge (the ball inside the material, cutting it away), -1 across a concave one (the ball
// outside, filling the corner).
public required double Side { get; init; }
+ // The ball's radius along this edge.
+ public required double Radius { get; init; }
// Closed circles: the ball centre at the seam's meridian.
public Point3D Centre { get; set; }
}
- private enum VertexKind { Untouched, Corner, End, Junction }
+ private enum VertexKind { Untouched, Corner, End, Junction, Mitre }
/// <summary>What becomes of a vertex: kept; a piece of the ball where three rounded edges meet; the end of a
/// rounded edge's strip on the face across it (the two other edges kept); or two rounded edges whose strips
- /// run on into each other where their faces meet tangentially. One ball centre each.</summary>
+ /// run on into each other where their faces meet tangentially; or two rounded edges on one face mitred where the
+ /// kept edge between their other faces stands square to it. One ball centre each.</summary>
private sealed class Plan
{
public required VertexKind Kind { get; init; }
@@ -163,6 +173,9 @@ internal static class LocalRounding
public FaceId[] Faces { get; init; } = [];
public EdgeId[] Rounded { get; init; } = [];
public double Side { get; init; }
+ // Mitre: where the kept edge leaves the strips (one ball radius off the common face).
+ public Point3D Touch { get; init; }
+ public double Radius { get; init; }
}
/// <summary>Every sharp edge rounded, in one pass, or in two where convex and concave edges meet at a corner:
@@ -176,15 +189,16 @@ internal static class LocalRounding
return filled.Body is null ? filled : Round(filled.Body, radius, Pass.All, trusted: true);
}
- internal static Outcome Round(BrepBody body, double radius, Pass pass = Pass.All, bool trusted = false)
+ internal static Outcome Round(BrepBody body, double radius, Pass pass = Pass.All, bool trusted = false, Func<EdgeQuery, double?>? select = null)
{
+ if (pass == Pass.Selected && select is null) throw new ArgumentNullException(nameof(select));
var topology = body.Topology;
var points = VertexPoints(body);
if (points.Count != topology.Vertices.Count())
return Refuse("uniform-rounding-edge-unsupported", "some vertices of the body have no position");
var extent = points.Values.Max(p => (p - Point3D.Origin).Length);
var tol = double.Max(1e-9, (extent + 1) * 1e-10) * 1e2;
- if (radius <= 1e3 * tol) return Refuse("uniform-rounding-radius-invalid", $"radius {radius:G6} mm is below the construction tolerance");
+ if (pass != Pass.Selected && radius <= 1e3 * tol) return Refuse("uniform-rounding-radius-invalid", $"radius {radius:G6} mm is below the construction tolerance");
// Faces: supports with their outward side. A body this construction built may carry its own blends.
var supports = new Dictionary<FaceId, Support>();
@@ -288,6 +302,8 @@ internal static class LocalRounding
var (na, nb) = (a.Outward(p), b.Outward(p));
if (na.Cross(nb).Length < 1e-7 && na.Dot(nb) > 0)
{
+ // A selective rounding leaves every edge it was not asked for alone, split faces included.
+ if (pass == Pass.Selected) { kept.Add(edgeId, (f0, f1, 0)); continue; }
// Two faces on one plane: one face split in two (some constructions leave a wall cut at a pocket's
// depth). The edge between them is not an edge of the part.
if (a.Kind == SurfaceGeometryKind.Plane && b.Kind == SurfaceGeometryKind.Plane)
@@ -296,9 +312,21 @@ internal static class LocalRounding
}
var side = na.Dot(nb.Cross(shape.Tangent(p) * -1)) < 0 ? 1d : -1d;
if (pass == Pass.ConcaveOnly && side > 0) { kept.Add(edgeId, (f0, f1, side)); continue; }
+ if (pass == Pass.Selected)
+ {
+ // Interiors lie left of each face's walking direction about its outward normal: A walks the edge forward.
+ var t = shape.Tangent(p); var step = 1e-4 * (extent + 1);
+ var query = new EdgeQuery(p, a.Foot(p + Unit(na.Cross(t)) * step), a.Surface, b.Foot(p + Unit(nb.Cross(t * -1)) * step), b.Surface, side < 0);
+ if (select!(query) is not { } chosen) { kept.Add(edgeId, (f0, f1, side)); continue; }
+ if (chosen <= 1e3 * tol) return Refuse("uniform-rounding-radius-invalid", $"radius {chosen:G6} mm is below the construction tolerance");
+ if (!Shares(a, shape, tol) || !Shares(b, shape, tol))
+ return Refuse("uniform-rounding-edge-unsupported", $"edge {edgeId.Value} {(shape.Arc ? "is a circle" : "is a line")} between a {Article(a.Kind)} and a {Article(b.Kind)} face that do not run along it, so the ball's path along it is not a line or a circle");
+ sharp.Add(edgeId, new Sharp { Edge = edge, Shape = shape, A = a, B = b, Side = side, Radius = chosen });
+ continue;
+ }
if (!Shares(a, shape, tol) || !Shares(b, shape, tol))
return Refuse("uniform-rounding-edge-unsupported", $"rounding every edge needs each edge's faces to run along its line or around its circle's axis: edge {edgeId.Value} {(shape.Arc ? "is a circle" : "is a line")} between a {Article(a.Kind)} and a {Article(b.Kind)} face that do not, so the ball's path along it is not a line or a circle");
- sharp.Add(edgeId, new Sharp { Edge = edge, Shape = shape, A = a, B = b, Side = side });
+ sharp.Add(edgeId, new Sharp { Edge = edge, Shape = shape, A = a, B = b, Side = side, Radius = radius });
}
string Kind(EdgeId e) => sharp.TryGetValue(e, out var s) ? s.Side > 0 ? "convex" : "concave" : kept[e].Side > 0 ? "convex" : kept[e].Side < 0 ? "concave" : "tangent";
FaceId[] FacesOf(EdgeId e) => sharp.TryGetValue(e, out var s) ? [s.A.Face, s.B.Face] : [kept[e].F0, kept[e].F1];
@@ -315,27 +343,31 @@ internal static class LocalRounding
var sides = rounded.Select(e => sharp[e].Side).Concat(others.Where(e => kept[e].Side != 0).Select(e => kept[e].Side)).Distinct().ToArray();
var faces = open.SelectMany(e => FacesOf(e.Id)).Distinct().ToArray();
var side = sharp[rounded[0]].Side;
+ // One ball per vertex: edges of different radii do not meet.
+ var r = sharp[rounded[0]].Radius;
+ if (rounded.Any(e => double.Abs(sharp[e].Radius - r) > tol))
+ return Refuse("uniform-rounding-vertex-unsupported", $"vertex {vertex.Id.Value} joins rounded edges of different radii ({string.Join(", ", rounded.Select(e => $"{e.Value}: {sharp[e].Radius:G6} mm"))}); rounds of different radii meeting at a corner are not built yet");
if (rounded.Length == 3 && others.Length == 0 && faces.Length == 3)
{
if (sides.Length > 1)
- return Refuse(MixedCode, $"rounding every edge does not support corners where convex and concave edges meet yet: vertex {vertex.Id.Value} joins edges {joins}");
- var centre = Centre(faces.Select(f => supports[f]).ToArray(), points[vertex.Id], [side * radius, side * radius, side * radius], tol);
- if (centre is null || (centre.Value - points[vertex.Id]).Length > 50 * radius)
- return TooLarge(radius, $"the ball does not fit in the corner at vertex {vertex.Id.Value}");
- plans.Add(vertex.Id, new Plan { Kind = VertexKind.Corner, Centre = centre.Value, Faces = faces, Rounded = rounded, Side = side });
+ return Refuse(MixedCode, $"{(pass == Pass.Selected ? "rounding the selected edges" : "rounding every edge")} does not support corners where convex and concave edges meet yet: vertex {vertex.Id.Value} joins edges {joins}");
+ var centre = Centre(faces.Select(f => supports[f]).ToArray(), points[vertex.Id], [side * r, side * r, side * r], tol);
+ if (centre is null || (centre.Value - points[vertex.Id]).Length > 50 * r)
+ return TooLarge(r, $"the ball does not fit in the corner at vertex {vertex.Id.Value}");
+ plans.Add(vertex.Id, new Plan { Kind = VertexKind.Corner, Centre = centre.Value, Faces = faces, Rounded = rounded, Side = side, Radius = r });
continue;
}
- if (rounded.Length == 1 && others.Length == 2 && faces.Length == 3 && others.All(e => kept[e].Side != 0) && pass == Pass.ConcaveOnly)
+ if (rounded.Length == 1 && others.Length == 2 && faces.Length == 3 && others.All(e => kept[e].Side != 0) && pass is Pass.ConcaveOnly or Pass.Selected)
{
// The strip ends on the face across the vertex, which must stand square to it: the ball's
// cross-section is then where the strip meets that face.
var s = sharp[rounded[0]]; var across = faces.Single(f => f != s.A.Face && f != s.B.Face);
if (s.Shape.Arc || supports[across].Kind != SurfaceGeometryKind.Plane || supports[across].Surface.Plane!.Value.Normal.ToVector().Cross(Unit(s.Shape.End - s.Shape.Start)).Length > 1e-9)
return Refuse("uniform-rounding-vertex-unsupported", $"at vertex {vertex.Id.Value} the concave edge {rounded[0].Value} ends on face {across.Value}, which does not stand square to it; filling it there is not built yet");
- var centre = Centre([s.A, s.B, supports[across]], points[vertex.Id], [side * radius, side * radius, 0], tol);
+ var centre = Centre([s.A, s.B, supports[across]], points[vertex.Id], [side * r, side * r, 0], tol);
if (centre is null || new[] { s.A, s.B }.Any(f => double.Abs(supports[across].Inside(f.Foot(centre.Value))) > tol))
- return TooLarge(radius, $"the ball does not fit where edge {rounded[0].Value} ends at vertex {vertex.Id.Value}");
- plans.Add(vertex.Id, new Plan { Kind = VertexKind.End, Centre = centre.Value, Faces = [s.A.Face, s.B.Face, across], Rounded = rounded, Side = side });
+ return TooLarge(r, $"the ball does not fit where edge {rounded[0].Value} ends at vertex {vertex.Id.Value}");
+ plans.Add(vertex.Id, new Plan { Kind = VertexKind.End, Centre = centre.Value, Faces = [s.A.Face, s.B.Face, across], Rounded = rounded, Side = side, Radius = r });
continue;
}
if (rounded.Length == 2 && others.Length == 1 && kept[others[0]].Side == 0 && faces.Length == 3 && sides.Length == 1)
@@ -348,16 +380,40 @@ internal static class LocalRounding
return Refuse("uniform-rounding-vertex-unsupported", $"vertex {vertex.Id.Value} joins edges {joins}; two strips meeting where faces join tangentially need a straight tangent edge and one common face");
var g = common[0]; var (fa, fb) = (kept[others[0]].F0, kept[others[0]].F1);
var d = Unit(tangent.End - tangent.Start) * (topology.GetEdge(others[0]).StartVertexId == vertex.Id ? 1 : -1);
- var centre = Junction(supports[g], supports[fa], points[vertex.Id], d, side * radius, tol);
- if (centre is null || double.Abs(supports[fb].Inside(centre.Value) - side * radius) > tol * 1e2)
- return TooLarge(radius, $"the ball does not fit where the strips meet at vertex {vertex.Id.Value}");
- plans.Add(vertex.Id, new Plan { Kind = VertexKind.Junction, Centre = centre.Value, Faces = [g, fa, fb], Rounded = rounded, Side = side });
+ var centre = Junction(supports[g], supports[fa], points[vertex.Id], d, side * r, tol);
+ if (centre is null || double.Abs(supports[fb].Inside(centre.Value) - side * r) > tol * 1e2)
+ return TooLarge(r, $"the ball does not fit where the strips meet at vertex {vertex.Id.Value}");
+ plans.Add(vertex.Id, new Plan { Kind = VertexKind.Junction, Centre = centre.Value, Faces = [g, fa, fb], Rounded = rounded, Side = side, Radius = r });
+ continue;
+ }
+ if (rounded.Length == 2 && others.Length == 1 && faces.Length == 3 && kept[others[0]].Side != 0 && pass == Pass.Selected
+ && sharp[rounded[0]].Side == sharp[rounded[1]].Side)
+ {
+ // Two strips on one face (the floor) mitre where the kept edge between their walls stands square to the
+ // floor: the strips' axes cross at the ball touching all three planes, and the strips meet in the
+ // plane bisecting the walls along a quarter ellipse.
+ var (e1, e2) = (sharp[rounded[0]], sharp[rounded[1]]);
+ var common = new[] { e1.A.Face, e1.B.Face }.Intersect([e2.A.Face, e2.B.Face]).ToArray();
+ var edge = shapes[others[0]];
+ if (common.Length != 1 || edge.Arc || faces.Any(f => supports[f].Kind != SurfaceGeometryKind.Plane) || e1.Shape.Arc || e2.Shape.Arc)
+ return Refuse("uniform-rounding-vertex-unsupported", $"vertex {vertex.Id.Value} joins edges {joins}; two rounded edges are mitred only between planes, along straight edges, with one face in common");
+ var floor = common[0]; var walls = faces.Where(f => f != floor).ToArray();
+ var direction = Unit(edge.End - edge.Start);
+ if (supports[floor].Surface.Plane!.Value.Normal.ToVector().Cross(direction).Length > 1e-9)
+ return Refuse("uniform-rounding-vertex-unsupported", $"at vertex {vertex.Id.Value} the kept edge {others[0].Value} does not stand square to face {floor.Value}; mitring the rounded edges {rounded[0].Value} and {rounded[1].Value} there is not built yet");
+ var centre = Centre([supports[floor], supports[walls[0]], supports[walls[1]]], points[vertex.Id], [side * r, side * r, side * r], tol);
+ if (centre is null || (centre.Value - points[vertex.Id]).Length > 50 * r)
+ return TooLarge(r, $"the ball does not fit in the mitre at vertex {vertex.Id.Value}");
+ var touch = edge.Start + direction * direction.Dot(centre.Value - edge.Start);
+ if ((touch - edge.Start).Dot(edge.End - edge.Start) <= tol || (touch - edge.End).Dot(edge.Start - edge.End) <= tol)
+ return TooLarge(r, $"the mitre at vertex {vertex.Id.Value} uses up edge {others[0].Value}");
+ plans.Add(vertex.Id, new Plan { Kind = VertexKind.Mitre, Centre = centre.Value, Faces = [floor, walls[0], walls[1]], Rounded = rounded, Side = side, Touch = touch, Radius = r });
continue;
}
if (sides.Length > 1)
return Refuse(MixedCode, rounded.Length == 2 && pass == Pass.ConcaveOnly
? $"rounding every edge does not support corners where two concave edges and a convex one meet: vertex {vertex.Id.Value} joins edges {joins} (filling the concave edges leaves the convex one between two fills, which does not round to a torus)"
- : $"rounding every edge does not support corners where convex and concave edges meet yet: vertex {vertex.Id.Value} joins edges {joins}");
+ : $"{(pass == Pass.Selected ? "rounding the selected edges" : "rounding every edge")} does not support corners where convex and concave edges meet yet: vertex {vertex.Id.Value} joins edges {joins}");
return Refuse("uniform-rounding-vertex-unsupported", $"vertex {vertex.Id.Value} joins edges {joins}; rounding needs three edges at a corner, or two strips meeting where faces join tangentially");
}
@@ -374,8 +430,8 @@ internal static class LocalRounding
return Refuse("uniform-rounding-edge-unsupported", $"the faces around circle edge {s.Edge.Id.Value} have seams at different angles");
x0 = meridian;
}
- var centre = Meridian(s.A, s.B, c, nu, x0, s.Shape.Start, s.Side * radius, tol, (s.Shape.Start - c).Length);
- if (centre is null) return TooLarge(radius, $"the ball does not fit along circle edge {s.Edge.Id.Value}");
+ var centre = Meridian(s.A, s.B, c, nu, x0, s.Shape.Start, s.Side * s.Radius, tol, (s.Shape.Start - c).Length);
+ if (centre is null) return TooLarge(s.Radius, $"the ball does not fit along circle edge {s.Edge.Id.Value}");
s.Centre = centre.Value;
}
@@ -406,7 +462,26 @@ internal static class LocalRounding
|| shape.Arc && shape.Sweep <= 1e-9)
throw new Degenerate();
var edge = builder.AddEdge(a, b); var id = new CurveGeometryId(geometry.Curves.Count() + 1);
- if (shape.Arc)
+ if (shape.Mitre is { } m)
+ {
+ // A quarter ellipse whose semi-axes run from the centre to the two ends; the longer one is the major.
+ var (u, v) = (shape.Start - m, shape.End - m);
+ if (u.Length <= 1e-12 || v.Length <= 1e-12 || double.Abs(Unit(u).Dot(Unit(v))) > 1e-7) throw new Degenerate();
+ var normal = Unit(u.Cross(v));
+ if (u.Length >= v.Length)
+ {
+ // P(t) = m + u cos t + v sin t, t from 0 to pi/2.
+ geometry.AddCurve(id, CurveGeometry.FromEllipse(new Ellipse3Curve(m, Direction3D.Create(normal), u.Length, v.Length, Direction3D.Create(u))));
+ bindings.AddEdgeBinding(new(edge, id, new(0, double.Pi / 2)));
+ }
+ else
+ {
+ // Major along v, minor axis Y = normal x v = -u: P(t) = m + v cos t - u sin t, start at t = 3pi/2.
+ geometry.AddCurve(id, CurveGeometry.FromEllipse(new Ellipse3Curve(m, Direction3D.Create(normal), v.Length, u.Length, Direction3D.Create(v))));
+ bindings.AddEdgeBinding(new(edge, id, new(1.5 * double.Pi, 2 * double.Pi)));
+ }
+ }
+ else if (shape.Arc)
{
var c = shape.Center!.Value;
geometry.AddCurve(id, CurveGeometry.FromCircle(new Circle3Curve(c, Direction3D.Create(shape.Normal), (shape.Start - c).Length, Direction3D.Create(shape.Start - c))));
@@ -454,6 +529,11 @@ internal static class LocalRounding
case VertexKind.End:
foreach (var face in plan.Faces.Take(2)) contact.Add((vertex, face), NewVertex(supports[face].Foot(plan.Centre)));
break;
+ case VertexKind.Mitre:
+ contact.Add((vertex, plan.Faces[0]), NewVertex(supports[plan.Faces[0]].Foot(plan.Centre)));
+ var touches = NewVertex(plan.Touch);
+ contact.Add((vertex, plan.Faces[1]), touches); contact.Add((vertex, plan.Faces[2]), touches);
+ break;
case VertexKind.Junction:
contact.Add((vertex, plan.Faces[0]), NewVertex(supports[plan.Faces[0]].Foot(plan.Centre)));
var touch = NewVertex(supports[plan.Faces[1]].Foot(plan.Centre));
@@ -483,14 +563,14 @@ internal static class LocalRounding
foreach (var face in new[] { s.A, s.B })
{
var v = ring[(s.Edge.Id, face.Face)]; var p = positions[v]; var centre = c + nu * (p - c).Dot(nu);
- if ((p - centre).Length <= tol) return TooLarge(radius, $"the contact with face {face.Face.Value} along circle edge {s.Edge.Id.Value} shrinks to a point");
+ if ((p - centre).Length <= tol) return TooLarge(s.Radius, $"the contact with face {face.Face.Value} along circle edge {s.Edge.Id.Value} shrinks to a point");
along.Add((s.Edge.Id, face.Face), NewEdge(v, v, new Shape(p, p, centre, nu, Turn)));
}
var (a, b) = (ring[(s.Edge.Id, s.A.Face)], ring[(s.Edge.Id, s.B.Face)]);
section.Add((s.Edge.Id, s.Edge.StartVertexId), NewEdge(a, b, Cross(positions[a], positions[b], s.Centre, Unit(nu.Cross(s.Centre - c)))));
var axisCentre = c + nu * (s.Centre - c).Dot(nu); var major = (s.Centre - axisCentre).Length;
- if (major <= radius + tol) return TooLarge(radius, $"the ball along circle edge {s.Edge.Id.Value} reaches the circle's axis");
- strips.Add((s, SurfaceGeometry.FromTorus(new TorusSurface(axisCentre, Direction3D.Create(nu), major, radius, Direction3D.Create(s.Centre - axisCentre)))));
+ if (major <= s.Radius + tol) return TooLarge(s.Radius, $"the ball along circle edge {s.Edge.Id.Value} reaches the circle's axis");
+ strips.Add((s, SurfaceGeometry.FromTorus(new TorusSurface(axisCentre, Direction3D.Create(nu), major, s.Radius, Direction3D.Create(s.Centre - axisCentre)))));
continue;
}
@@ -500,28 +580,31 @@ internal static class LocalRounding
{
var (v0, v1) = (contact[(start, face.Face)], contact[(end, face.Face)]);
var path = Trimmed(shape, positions[v0], positions[v1], tol);
- if (path is null) return TooLarge(radius, $"the rounding uses up edge {s.Edge.Id.Value} on face {face.Face.Value}");
+ if (path is null) return TooLarge(s.Radius, $"the rounding uses up edge {s.Edge.Id.Value} on face {face.Face.Value}");
along.Add((s.Edge.Id, face.Face), NewEdge(v0, v1, path));
}
foreach (var (vertex, centre) in new[] { (start, c0), (end, c1) })
{
- if (plans[vertex].Kind == VertexKind.Junction && shared.TryGetValue(vertex, out var existing)) { section.Add((s.Edge.Id, vertex), existing); continue; }
+ var joined = plans[vertex].Kind is VertexKind.Junction or VertexKind.Mitre;
+ if (joined && shared.TryGetValue(vertex, out var existing)) { section.Add((s.Edge.Id, vertex), existing); continue; }
var (a, b) = (contact[(vertex, s.A.Face)], contact[(vertex, s.B.Face)]);
- var cut = NewEdge(a, b, Cross(positions[a], positions[b], centre, shape.Tangent(shape.Arc ? Project(centre, shape) : centre)));
+ var cut = NewEdge(a, b, plans[vertex].Kind == VertexKind.Mitre
+ ? new Shape(positions[a], positions[b], null, Vector3D.Zero, 0, centre)
+ : Cross(positions[a], positions[b], centre, shape.Tangent(shape.Arc ? Project(centre, shape) : centre)));
section.Add((s.Edge.Id, vertex), cut);
- if (plans[vertex].Kind == VertexKind.Junction) shared.Add(vertex, cut);
+ if (joined) shared.Add(vertex, cut);
}
if (!shape.Arc)
{
if ((c1 - c0).Dot(shape.End - shape.Start) <= tol || Unit(c1 - c0).Cross(Unit(shape.End - shape.Start)).Length > 1e-7)
- return TooLarge(radius, $"the ball's path along edge {s.Edge.Id.Value} folds back");
- strips.Add((s, SurfaceGeometry.FromCylinder(new CylinderSurface(c0, Direction3D.Create(c1 - c0), radius, Direction3D.Create(positions[contact[(start, s.A.Face)]] - c0)))));
+ return TooLarge(s.Radius, $"the ball's path along edge {s.Edge.Id.Value} folds back");
+ strips.Add((s, SurfaceGeometry.FromCylinder(new CylinderSurface(c0, Direction3D.Create(c1 - c0), s.Radius, Direction3D.Create(positions[contact[(start, s.A.Face)]] - c0)))));
}
else
{
var c = shape.Center!.Value; var nu = shape.Normal; var axisCentre = c + nu * (c0 - c).Dot(nu); var major = (c0 - axisCentre).Length;
- if (major <= radius + tol) return TooLarge(radius, $"the ball along circle edge {s.Edge.Id.Value} reaches the circle's axis");
- strips.Add((s, SurfaceGeometry.FromTorus(new TorusSurface(axisCentre, Direction3D.Create(nu), major, radius, Direction3D.Create(c0 - axisCentre)))));
+ if (major <= s.Radius + tol) return TooLarge(s.Radius, $"the ball along circle edge {s.Edge.Id.Value} reaches the circle's axis");
+ strips.Add((s, SurfaceGeometry.FromTorus(new TorusSurface(axisCentre, Direction3D.Create(nu), major, s.Radius, Direction3D.Create(c0 - axisCentre)))));
}
}
@@ -584,6 +667,11 @@ internal static class LocalRounding
{
// A circle closed on the vertex goes first: otherwise a seam's return would leave it behind.
var next = rest.FindIndex(u => From(u) == To(ordered[^1]) && To(u) == From(u));
+ // Then neither the way back along the edge just walked (a seam is walked both ways, and turning straight
+ // back along it strands the rims beyond it, as on a hole wall whose rims are split into arcs)...
+ // Nor back to the start while other uses remain: the loop would close early around them.
+ if (next < 0 && rest.Count > 1) next = rest.FindIndex(u => From(u) == To(ordered[^1]) && u.Edge != ordered[^1].Item1 && To(u) != From(ordered[0]));
+ if (next < 0) next = rest.FindIndex(u => From(u) == To(ordered[^1]) && u.Edge != ordered[^1].Item1);
if (next < 0) next = rest.FindIndex(u => From(u) == To(ordered[^1]));
if (next < 0) return null;
ordered.Add(rest[next]); rest.RemoveAt(next);
@@ -634,7 +722,7 @@ internal static class LocalRounding
var ordered = Chain(plan.Rounded.Select(e => (section[(e, vertex)], !stripUse[section[(e, vertex)]])).ToList());
if (ordered is null) return Refuse("uniform-rounding-vertex-unsupported", $"the corner at vertex {vertex.Value} does not close");
var axis = Unit(plan.Faces.Aggregate(Vector3D.Zero, (n, f) => n + supports[f].Outward(plan.Centre)));
- NewFace([ordered], SurfaceGeometry.FromSphere(new SphereSurface(plan.Centre, Direction3D.Create(axis), radius, Direction3D.Create(Perpendicular(axis)))), plan.Side > 0);
+ NewFace([ordered], SurfaceGeometry.FromSphere(new SphereSurface(plan.Centre, Direction3D.Create(axis), plan.Radius, Direction3D.Create(Perpendicular(axis)))), plan.Side > 0);
}
// Every edge used once each way (a seam twice by one face).
@@ -726,36 +814,36 @@ internal static class LocalRounding
private static Refusal? Clearance(Dictionary<FaceId, Shape[]> boundaries, double radius, double tol, Dictionary<FaceId, Support> supports,
Dictionary<EdgeId, Sharp> sharp, Dictionary<VertexId, Plan> plans)
{
- IEnumerable<(Point3D Centre, FaceId[] Own, string Where)> Samples()
+ IEnumerable<(Point3D Centre, FaceId[] Own, string Where, double Radius)> Samples()
{
foreach (var s in sharp.Values)
{
if (s.Closed)
{
var c = s.Shape.Center!.Value;
- for (var i = 0; i < 24; i++) yield return (Rotate(s.Centre, c, s.Shape.Normal, Turn * i / 24), [s.A.Face, s.B.Face], $"along edge {s.Edge.Id.Value}");
+ for (var i = 0; i < 24; i++) yield return (Rotate(s.Centre, c, s.Shape.Normal, Turn * i / 24), [s.A.Face, s.B.Face], $"along edge {s.Edge.Id.Value}", s.Radius);
continue;
}
var (p0, p1) = (plans[s.Edge.StartVertexId], plans[s.Edge.EndVertexId]);
- var own = new[] { s.A.Face, s.B.Face }.Concat(new[] { p0, p1 }.Where(p => p.Kind is VertexKind.End or VertexKind.Junction).SelectMany(p => p.Faces)).Distinct().ToArray();
+ var own = new[] { s.A.Face, s.B.Face }.Concat(new[] { p0, p1 }.Where(p => p.Kind is VertexKind.End or VertexKind.Junction or VertexKind.Mitre).SelectMany(p => p.Faces)).Distinct().ToArray();
var (c0, c1) = (p0.Centre, p1.Centre);
for (var i = 1; i < 8; i++)
{
var t = i / 8d;
- yield return (!s.Shape.Arc ? c0 + (c1 - c0) * t : Rotate(c0, s.Shape.Center!.Value, s.Shape.Normal, Angle(c0 - Axial(c0, s.Shape), c1 - Axial(c0, s.Shape), s.Shape.Normal) * t), own, $"along edge {s.Edge.Id.Value}");
+ yield return (!s.Shape.Arc ? c0 + (c1 - c0) * t : Rotate(c0, s.Shape.Center!.Value, s.Shape.Normal, Angle(c0 - Axial(c0, s.Shape), c1 - Axial(c0, s.Shape), s.Shape.Normal) * t), own, $"along edge {s.Edge.Id.Value}", s.Radius);
}
}
- foreach (var (vertex, plan) in plans.Where(p => p.Value.Kind == VertexKind.Corner)) yield return (plan.Centre, plan.Faces, $"at vertex {vertex.Value}");
+ foreach (var (vertex, plan) in plans.Where(p => p.Value.Kind == VertexKind.Corner)) yield return (plan.Centre, plan.Faces, $"at vertex {vertex.Value}", plan.Radius);
}
- foreach (var (centre, own, where) in Samples())
+ foreach (var (centre, own, where, ball) in Samples())
foreach (var (face, support) in supports)
{
if (own.Contains(face)) continue;
var foot = support.Foot(centre);
// Touching counts: a ball that touches a third face leaves a face pinched to nothing there.
- if ((foot - centre).Length > radius + tol) continue;
+ if ((foot - centre).Length > ball + tol) continue;
if (InsideFace(support, boundaries[face], foot))
- return TooLarge(radius, $"the ball {where} reaches face {face.Value}").Refusal;
+ return TooLarge(ball, $"the ball {where} reaches face {face.Value}").Refusal;
}
return null;
}
diff --git a/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs b/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs
index f5615544..8e9f01b0 100644
--- a/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs
+++ b/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs
@@ -37,6 +37,43 @@ public static class UniformRounding
: $"{refusal.Message}; the largest that fits is under {hi:G6} mm");
}
+ /// <summary>A sharp edge offered to <see cref="RoundSelectedEdges"/>: its midpoint, a point just inside each of its
+ /// two faces with that face's surface, and whether it is concave.</summary>
+ public sealed record EdgeCandidate(Point3D Midpoint, Point3D InsideA, SurfaceGeometry SurfaceA, Point3D InsideB, SurfaceGeometry SurfaceB, bool Concave);
+
+ /// <summary>
+ /// Rounds only the sharp edges <paramref name="radiusOf"/> gives a radius, each by a rolling ball of that radius,
+ /// in one construction; every other edge is kept as it is. A rounded edge may end on a face standing square to it,
+ /// and two rounded edges sharing a face mitre where the kept edge between their other faces stands square to that
+ /// face. Edges of different radii must not meet. Radii that do not fit are refused with the largest that do.
+ /// </summary>
+ public static KernelResult<BrepBody> RoundSelectedEdges(BrepBody body, Func<EdgeCandidate, double?> radiusOf)
+ {
+ ArgumentNullException.ThrowIfNull(body);
+ ArgumentNullException.ThrowIfNull(radiusOf);
+ var chosen = new SortedSet<double>();
+ var scale = 1d;
+ double? Select(LocalRounding.EdgeQuery q)
+ {
+ if (radiusOf(new EdgeCandidate(q.Midpoint, q.InsideA, q.SurfaceA, q.InsideB, q.SurfaceB, q.Concave)) is not { } r) return null;
+ chosen.Add(r); return r * scale;
+ }
+ // Each chosen radius is checked against the construction tolerance as it is chosen.
+ LocalRounding.Outcome Attempt(double k) { scale = k; chosen.Clear(); return LocalRounding.Round(body, k, LocalRounding.Pass.Selected, trusted: false, Select); }
+ var outcome = Attempt(1);
+ if (chosen.Any(r => !double.IsFinite(r) || r <= 0)) return Failure("uniform-rounding-radius-invalid", "radius must be finite and positive");
+ if (outcome.Body is not null)
+ return chosen.Count > 0 ? KernelResult<BrepBody>.Success(outcome.Body) : Failure("uniform-rounding-selection-empty", "no edge of the body matches the selection");
+ var refusal = outcome.Refusal!;
+ if (refusal.Code != TooLargeCode) return Failure(refusal.Code, refusal.Message);
+ var radii = chosen.ToArray();
+ var (lo, hi) = (0d, 1d);
+ for (var i = 0; i < 30; i++) { var mid = 0.5 * (lo + hi); if (Attempt(mid).Body is not null) lo = mid; else hi = mid; }
+ return Failure(refusal.Code, radii.Length == 1
+ ? $"{refusal.Message}; the largest that fits is under {hi * radii[0]:G6} mm"
+ : $"{refusal.Message}; scaled together, the radii fit below {string.Join(", ", radii.Select(r => $"{hi * r:G6} mm (for {r:G6})"))}");
+ }
+
public static KernelResult<BrepBody> RoundAllEdges(BrepBody body, double radius)
{
ArgumentNullException.ThrowIfNull(body);
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 6954fa4e..5e1cc875 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -289,6 +289,15 @@ public static partial class FirmamentBuildAndExport
// Its expansion pipeline runs once in the frontend. Unmigrated domain owners
// retain their existing expansion boundary until their own cutover.
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
+ // Fillets where two Compose operations meet (`where: A meets B`): build the body without them, then round the
+ // edges between the two operations' faces.
+ if (JunctionFilletRoute.Find(sourceText) is { } junction)
+ {
+ var filleted = JunctionFilletRoute.Export(junction, stripped => ExportSource(stripped, sourceDirectory, allowV1Compatibility, explicitSchema, resources, authoredSource), sourceDirectory);
+ return filleted.IsSuccess && filleted.Value.RuntimeAdmissionDocument is null && ParseSemanticSource(junction.Stripped, sourceDirectory).Document is { } admittedJunction
+ ? KernelResult<FirmamentStepExportResult>.Success(filleted.Value with { RuntimeAdmissionDocument = admittedJunction }, filleted.Diagnostics)
+ : filleted;
+ }
var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();
var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema, resources);
canonicalParseWatch.Stop();
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
index 96170efe..1b125924 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
@@ -9,6 +9,9 @@ public static class FirmamentBuildAdmissionValidation
public static FirmamentV2ValidationReport Admit(
FirmamentV2ValidationReport report, string source, string? sourceDirectory = null)
{
+ // A junction fillet is validated the way build answers it: the body built without it, then filleted.
+ if (JunctionFilletRoute.Find(source) is { } junction && FirmamentV2Parser.Parse(junction.Stripped, sourceDirectory).IsSuccess)
+ return Rounded(report, source, sourceDirectory, JunctionFilletRoute.Code);
if (report.Status == "invalid" && UniformRoundingRoute.Find(source) is { } rounding
&& FirmamentV2Parser.Parse(rounding.Stripped, sourceDirectory).IsSuccess)
return Rounded(report, source, sourceDirectory);
@@ -33,7 +36,7 @@ public static class FirmamentBuildAdmissionValidation
/// <summary>An AllEdges fillet that is all that stops the source parsing (the stock route refuses it, or the
/// body's construction takes no Modify) is validated the way build answers it: by building the body and
/// rounding it.</summary>
- private static FirmamentV2ValidationReport Rounded(FirmamentV2ValidationReport report, string source, string? sourceDirectory)
+ private static FirmamentV2ValidationReport Rounded(FirmamentV2ValidationReport report, string source, string? sourceDirectory, string route = UniformRoundingRoute.Code)
{
var built = FirmamentBuildAndExport.CompileSource(source, sourceDirectory);
// Only the finish failed the parse, so the parse's diagnostics give way to the build's answer.
@@ -44,7 +47,7 @@ public static class FirmamentBuildAdmissionValidation
{
Status = built.IsSuccess && fatal == 0 ? "valid" : "invalid",
ValidationLevel = built.IsSuccess ? "Built" : "BuildRejected",
- ParserRoute = UniformRoundingRoute.Code,
+ ParserRoute = route,
Diagnostics = diagnostics,
Summary = report.Summary with { FatalDiagnosticCount = fatal, WarningDiagnosticCount = diagnostics.Count(d => d.Severity == "warning") },
};
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/JunctionFilletRoute.cs b/Aetheris.Kernel.Firmament/FirmamentV2/JunctionFilletRoute.cs
new file mode 100644
index 00000000..dfd120f8
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/JunctionFilletRoute.cs
@@ -0,0 +1,240 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Blends;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// <c>EdgeFinish&lt;Fillet&gt; { where: A meets B; radius: r }</c> on a Compose body: the edges where the faces of
+/// operation A meet the faces of operation B, rounded by a ball of radius r. Operands are Compose operations by name
+/// (Base, Add, Boss, Pocket) or every operation with a role (<c>role Pad</c>). The body is built without these
+/// finishes through the ordinary pipeline; each face of the result is then attributed to the operations whose prism
+/// it lies on (a cap inside the profile, or a side on its outline within its heights), and an edge is selected when
+/// one face belongs to A and not B and the other to B and not A. Faces both operations share, such as a pad's wall
+/// flush with the plate's, select nothing. The selected edges are rounded with <see cref="UniformRounding.RoundSelectedEdges"/>.
+/// </summary>
+internal static class JunctionFilletRoute
+{
+ internal const string Code = "firmament-junction-fillet";
+
+ internal sealed record Operand(string Name, bool Role);
+
+ internal sealed record Finish(string Name, Operand Left, Operand Right, double Radius, FirmamentV2SourceSpan Span);
+
+ internal sealed record Request(string Stripped, IReadOnlyList<Finish> Finishes, IReadOnlyList<(string Message, FirmamentV2SourceSpan Span)> Errors, string? Host);
+
+ /// <summary>Every edge finish with a <c>where</c> field, and the source without them; null when there is none.</summary>
+ internal static Request? Find(string source)
+ {
+ var document = FirmamentSyntaxParser.Parse(source).Document;
+ var declarations = FirmamentSyntaxTraversal.Declarations(document).ToArray();
+ var finishes = declarations.Where(d => d.Type.Name.Text == "EdgeFinish" && Field(d, "Where") is not null).ToArray();
+ if (finishes.Length == 0) return null;
+ var found = new List<Finish>();
+ var errors = new List<(string, FirmamentV2SourceSpan)>();
+ foreach (var finish in finishes)
+ {
+ var name = finish.Name?.Text ?? "EdgeFinish";
+ var generic = finish.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(finish.Type.Arguments[0].Value) : null;
+ var kind = generic ?? FirmamentSyntaxValues.Reference(Field(finish, "Kind"));
+ var where = Field(finish, "Where") as JunctionSyntax;
+ var fields = finish.Body?.Statements.OfType<FieldSyntax>().ToArray() ?? [];
+ var extra = fields.Select(f => f.Name.Text).FirstOrDefault(f => !new[] { "Where", "Radius", "Kind" }.Any(n => FirmamentSyntaxFields.SameField(f, n)));
+ if (kind != "Fillet")
+ errors.Add(($"{Code}-kind:{name}: 'where' selects edges for EdgeFinish<Fillet> only; '{name}' is {(kind is null ? "missing its kind" : $"a {kind}")}.", finish.Span));
+ else if (where is null)
+ errors.Add(($"{Code}-where-invalid:{name}: 'where' takes a junction: write where: A meets B, where A and B are Compose operations by name or 'role Name' for every operation with that role.", finish.Span));
+ else if (extra is not null)
+ errors.Add(($"{Code}-field-unknown:{name}: '{extra}' does not combine with where; a junction fillet takes where and radius.", finish.Span));
+ else if (!FirmamentSyntaxValues.TryMeasure(Field(finish, "Radius"), "mm", out var radius) || !(radius > 0))
+ errors.Add(($"{Code}-radius-invalid:{name}: a junction fillet needs a positive radius.", finish.Span));
+ else
+ found.Add(new(name, new(where!.Left.Name.Text, where.Left.Role), new(where.Right.Name.Text, where.Right.Role), radius, finish.Span));
+ }
+ // Remove the finishes, last first; a Modify left empty goes with them.
+ var removals = new List<FirmamentV2SourceSpan>();
+ foreach (var owner in declarations.Where(d => d.Type.Name.Text == "Modify" && d.Body is not null))
+ {
+ var mine = owner.Body!.Statements.Where(s => finishes.Contains(s)).ToArray();
+ if (mine.Length == 0) continue;
+ if (mine.Length == owner.Body.Statements.Count) removals.Add(owner.Span); else removals.AddRange(mine.Select(m => m.Span));
+ }
+ var stripped = removals.OrderByDescending(r => r.Start).Aggregate(source, (text, span) => text.Remove(span.Start, span.Length));
+ var host = declarations.FirstOrDefault(d => d.Type.Name.Text == "Modify" && d.Body?.Statements.Any(s => finishes.Contains(s)) == true)?.Name?.Text;
+ return new(stripped, found, errors, host);
+ }
+
+ internal static KernelResult<FirmamentStepExportResult> Export(Request request, Func<string, KernelResult<FirmamentStepExportResult>> build, string? sourceDirectory)
+ {
+ if (request.Errors.Count > 0)
+ return KernelResult<FirmamentStepExportResult>.Failure(request.Errors.Select(e => Error(e.Message, e.Span)).ToArray());
+ var unfinished = build(request.Stripped);
+ if (!unfinished.IsSuccess) return unfinished;
+ // The Compose operations as the build bound them (the regex reader is the fallback for sources the V2 parser
+ // does not bind).
+ var composition = FirmamentV2Parser.Parse(request.Stripped, sourceDirectory).BoundComposition ?? PrismaticProfileCompositionParser.Parse(request.Stripped);
+ if (composition.Feature is not { } feature)
+ return Refuse(request.Finishes[0], "a junction fillet selects edges between the operations of a Compose body, and this source has none"
+ + (composition.Diagnostics.Count > 0 ? $" ({string.Join("; ", composition.Diagnostics.Take(3))})" : ""));
+ var body = unfinished.Value.RuntimeBody;
+ if (body is null)
+ {
+ var imported = Step242Importer.ImportBody(unfinished.Value.StepText);
+ if (!imported.IsSuccess) return Refuse(request.Finishes[0], "the body before filleting could not be read back: " + string.Join("; ", imported.Diagnostics.Select(d => d.Message)));
+ body = imported.Value;
+ }
+ // Every finish's edges are rounded in one construction, each by its own radius: a later finish never has
+ // to round a body an earlier one already rounded.
+ var sides = new List<(Finish Finish, IReadOnlyList<Prism> Left, IReadOnlyList<Prism> Right)>();
+ foreach (var finish in request.Finishes)
+ {
+ var left = Prisms(feature, composition.Profiles, finish.Left, out var leftError);
+ var right = Prisms(feature, composition.Profiles, finish.Right, out var rightError);
+ if ((leftError ?? rightError) is { } error) return Refuse(finish, error);
+ sides.Add((finish, left!, right!));
+ }
+ var claimed = sides.ToDictionary(s => s.Finish, _ => 0);
+ Finish? conflict = null;
+ var rounded = UniformRounding.RoundSelectedEdges(body, edge =>
+ {
+ static bool In(IReadOnlyList<Prism> side, Point3D p, SurfaceGeometry s) => side.Any(prism => prism.Holds(p, s));
+ double? radius = null;
+ foreach (var (finish, left, right) in sides)
+ {
+ var (aL, aR, bL, bR) = (In(left, edge.InsideA, edge.SurfaceA), In(right, edge.InsideA, edge.SurfaceA), In(left, edge.InsideB, edge.SurfaceB), In(right, edge.InsideB, edge.SurfaceB));
+ if (!(aL && !aR && bR && !bL || aR && !aL && bL && !bR)) continue;
+ if (radius is not null && radius != finish.Radius) conflict = finish;
+ radius ??= finish.Radius; claimed[finish]++;
+ }
+ return radius;
+ });
+ if (conflict is not null) return Refuse(conflict, "an edge it selects is also selected by another finish with a different radius");
+ // Edges are offered before anything is built, so a finish that claimed none is reported as such even when
+ // the construction refuses later.
+ if (sides.FirstOrDefault(s => claimed[s.Finish] == 0).Finish is { } empty)
+ return Refuse(empty, "no edge of the body lies where these operations meet");
+ if (!rounded.IsSuccess) return Refuse(request.Finishes[0], string.Join("; ", rounded.Diagnostics.Select(d => d.Message)), all: request.Finishes);
+ body = rounded.Value;
+ var receipts = request.Finishes.Select(f => new FirmamentFeatureReceipt(request.Host ?? unfinished.Value.ExportedFeatureId, "EdgeFinish", f.Name)).ToList();
+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { ProductName = unfinished.Value.ExportedFeatureId });
+ if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ return KernelResult<FirmamentStepExportResult>.Success(unfinished.Value with
+ {
+ StepText = step.Value,
+ RuntimeBody = body,
+ // Correspondence and retained CIR described the body before filleting; they no longer hold.
+ RuntimeCorrespondence = null,
+ Cir = null,
+ MaterializedFeatures = [.. unfinished.Value.MaterializedFeatures ?? [], .. receipts],
+ }, unfinished.Diagnostics);
+ }
+
+ /// <summary>One Compose operation's prism: its profile's region swept between two heights along +Z.</summary>
+ private sealed class Prism(ResolvedProfile2D profile, double from, double to)
+ {
+ private const double Tol = 1e-6;
+ private readonly List<List<(double X, double Y)>> loops = profile.Loops.Select(l => l.Segments.SelectMany(s => Sample(s.Geometry)).ToList()).ToList();
+
+ public bool Holds(Point3D p, SurfaceGeometry surface)
+ {
+ var scale = double.Max(1d, double.Max(double.Abs(from), double.Abs(to)));
+ if (surface.Plane is { } plane && double.Abs(double.Abs(plane.Normal.ToVector().Z) - 1d) < 1e-9)
+ return (double.Abs(p.Z - from) < Tol * scale || double.Abs(p.Z - to) < Tol * scale) && Inside(p.X, p.Y) && Boundary(p.X, p.Y) > Tol * scale;
+ var vertical = surface.Plane is { } wall ? double.Abs(wall.Normal.ToVector().Z) < 1e-9
+ : surface.Cylinder is { } cylinder && double.Abs(double.Abs(cylinder.Axis.ToVector().Z) - 1d) < 1e-9;
+ return vertical && p.Z > from - Tol * scale && p.Z < to + Tol * scale && Boundary(p.X, p.Y) < 1e-5 * scale;
+ }
+
+ private bool Inside(double x, double y)
+ {
+ // Even-odd over every loop: inner loops are holes.
+ var inside = false;
+ foreach (var loop in loops)
+ for (int i = 0, j = loop.Count - 1; i < loop.Count; j = i++)
+ if (loop[i].Y > y != loop[j].Y > y && x < (loop[j].X - loop[i].X) * (y - loop[i].Y) / (loop[j].Y - loop[i].Y) + loop[i].X) inside = !inside;
+ return inside;
+ }
+
+ private double Boundary(double x, double y) => profile.Loops.SelectMany(l => l.Segments).Min(s => Distance(s.Geometry, x, y));
+
+ private static double Distance(LineArcProfileCurve2D curve, double x, double y)
+ {
+ switch (curve)
+ {
+ case LineArcLineSegment2D line:
+ {
+ var (dx, dy) = (line.End.X - line.Start.X, line.End.Y - line.Start.Y);
+ var t = double.Clamp(((x - line.Start.X) * dx + (y - line.Start.Y) * dy) / (dx * dx + dy * dy), 0, 1);
+ return double.Hypot(x - line.Start.X - t * dx, y - line.Start.Y - t * dy);
+ }
+ case LineArcCircularArc2D arc:
+ {
+ var angle = double.Atan2(y - arc.Center.Y, x - arc.Center.X);
+ var offset = Wrap((angle - arc.StartAngleRadians) * double.Sign(arc.SweepAngleRadians));
+ if (offset <= double.Abs(arc.SweepAngleRadians)) return double.Abs(double.Hypot(x - arc.Center.X, y - arc.Center.Y) - arc.Radius);
+ var ends = new[] { arc.StartAngleRadians, arc.StartAngleRadians + arc.SweepAngleRadians };
+ return ends.Min(t => double.Hypot(x - arc.Center.X - arc.Radius * double.Cos(t), y - arc.Center.Y - arc.Radius * double.Sin(t)));
+ }
+ case LineArcFullCircle2D circle:
+ return double.Abs(double.Hypot(x - circle.Center.X, y - circle.Center.Y) - circle.Radius);
+ default:
+ return Sample(curve).Zip(Sample(curve).Skip(1)).Min(s => Distance(new LineArcLineSegment2D(s.First, s.Second), x, y));
+ }
+ }
+
+ private static double Wrap(double a) { var t = a % (2 * double.Pi); return t < 0 ? t + 2 * double.Pi : t; }
+
+ private static IEnumerable<(double X, double Y)> Sample(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => [line.Start],
+ LineArcCircularArc2D arc => Enumerable.Range(0, 64).Select(i => arc.StartAngleRadians + arc.SweepAngleRadians * i / 64)
+ .Select(t => (arc.Center.X + arc.Radius * double.Cos(t), arc.Center.Y + arc.Radius * double.Sin(t))),
+ LineArcFullCircle2D circle => Enumerable.Range(0, 128).Select(i => 2 * double.Pi * i / 128)
+ .Select(t => (circle.Center.X + circle.Radius * double.Cos(t), circle.Center.Y + circle.Radius * double.Sin(t))),
+ _ => throw new NotSupportedException($"profile curve {curve.GetType().Name} is not supported by a junction fillet"),
+ };
+ }
+
+ private static IReadOnlyList<Prism>? Prisms(PrismaticProfileCompositionFeature feature, IReadOnlyDictionary<string, ResolvedProfile2D> profiles, Operand operand, out string? error)
+ {
+ error = null;
+ var operations = feature.Operations.Where(o => operand.Role
+ ? string.Equals(o.SemanticRole, operand.Name, StringComparison.OrdinalIgnoreCase)
+ : string.Equals(o.Name, operand.Name, StringComparison.Ordinal)).ToArray();
+ if (operations.Length == 0)
+ {
+ var known = operand.Role ? feature.Operations.Select(o => o.SemanticRole).Distinct() : feature.Operations.Select(o => o.Name);
+ error = $"'{(operand.Role ? "role " : "")}{operand.Name}' is not {(operand.Role ? "a role" : "an operation")} of Compose {feature.Name}; it has {string.Join(", ", known)}";
+ return null;
+ }
+ if (feature.Axis != "+Z" || operations.Any(o => !profiles.TryGetValue(o.ProfileReference, out var p) || p.ConstructionPlane is { } plane && !WorldXy(plane)))
+ {
+ var o = operations.First(); profiles.TryGetValue(o.ProfileReference, out var p0);
+ error = $"a junction fillet needs operations whose profiles lie on XY and extrude along +Z; '{operand.Name}' does not (axis {feature.Axis}, profile '{o.ProfileReference}' on {p0?.PlaneFrame ?? "unknown"})";
+ return null;
+ }
+ return operations.Select(o => new Prism(profiles[o.ProfileReference], double.Min(o.From, o.To), double.Max(o.From, o.To))).ToArray();
+ }
+
+ private static bool WorldXy(ConstructionPlane plane) =>
+ (plane.Origin - Point3D.Origin).Length < 1e-12 && plane.AxisX.ToVector().X > 1 - 1e-12 && plane.AxisZ.ToVector().Z > 1 - 1e-12;
+
+ private static KernelResult<FirmamentStepExportResult> Refuse(Finish finish, string reason, IReadOnlyList<Finish>? all = null) =>
+ KernelResult<FirmamentStepExportResult>.Failure([Error(all is { Count: > 1 }
+ ? $"{Code}:{string.Join(",", all.Select(f => f.Name))}: {reason}"
+ : $"{Code}:{finish.Name}: where {Describe(finish.Left)} meets {Describe(finish.Right)}: {reason}", finish.Span)]);
+
+ private static string Describe(Operand operand) => (operand.Role ? "role " : "") + operand.Name;
+
+ private static KernelDiagnostic Error(string message, FirmamentV2SourceSpan span) =>
+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.JunctionFillet") { SourceSpan = new(span.Start, span.Length) };
+
+ private static ExpressionSyntax? Field(DeclarationSyntax d, string name) =>
+ d.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, name))?.Value;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
index 5c315b6a..199884d2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
@@ -113,6 +113,10 @@ public sealed record ObjectSyntax(ExpressionSyntax? Type, BlockSyntax Body, Firm
public sealed record WithSyntax(ExpressionSyntax Target, BlockSyntax Body, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record FrameSyntax(ExpressionSyntax Origin, IReadOnlyList<ArgumentSyntax> Axes, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record AliasSyntax(ExpressionSyntax Value, IdentifierSyntax Name, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+/// <summary>One side of a junction: a Compose operation by name, or every operation with a role (<c>role Pad</c>).</summary>
+public sealed record JunctionOperandSyntax(IdentifierSyntax Name, bool Role, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+/// <summary><c>A meets B</c>: where the faces of two Compose operations meet.</summary>
+public sealed record JunctionSyntax(JunctionOperandSyntax Left, JunctionOperandSyntax Right, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record TraceSyntax(ExpressionSyntax Source, ExpressionSyntax? From, ExpressionSyntax? To, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record MemberSetSyntax(ExpressionSyntax Target, IReadOnlyList<ArgumentSyntax> Members, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record TypedValueSyntax(ExpressionSyntax Type, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
index e7dd23c1..4c9fa5d3 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
@@ -488,6 +488,19 @@ public static class FirmamentSyntaxParser
left = new ToleranceSyntax(left, plus, minus, Span(toleranceStart), Span(start));
continue;
}
+ // `A meets B`, `role X meets B`: the junction of two Compose operations (or every operation with a role).
+ if (left is ReferenceSyntax { Name.Text: "role" } && Current.Kind == SyntaxTokenKind.Identifier && Peek(1).Text == "meets")
+ { left = new JunctionOperandSyntax(Identifier(), true, Span(start)); continue; }
+ if (Current.Text == "meets" && Peek(1).Text != ":" && left is ReferenceSyntax or JunctionOperandSyntax)
+ {
+ at++;
+ var rightStart = Current.Span.Start;
+ var role = Is("role") && Peek(1).Kind == SyntaxTokenKind.Identifier;
+ if (role) at++;
+ var right = new JunctionOperandSyntax(Identifier(), role, Span(rightStart));
+ var first = left as JunctionOperandSyntax ?? new JunctionOperandSyntax(((ReferenceSyntax)left).Name, false, left.Span);
+ left = new JunctionSyntax(first, right, Span(start)); continue;
+ }
if (Current.Text is "As" or "as" && Peek(1).Text != ":") { at++; left = new AliasSyntax(left, Identifier(), Span(start)); continue; }
if (Current.Text is "From" or "from" or "To" or "to" && Peek(1).Text != ":")
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs
index c7b46d7a..3c8cd3a6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs
@@ -60,6 +60,8 @@ internal sealed class FirmamentSyntaxWriter(string? source = null)
WithSyntax w => WriteExpression(w.Target) + " with " + WriteBlock(w.Body),
FrameSyntax f => WriteExpression(f.Origin) + " " + string.Join(" ", f.Axes.Select(a => a.Name!.Text + WriteExpression(a.Value))),
AliasSyntax a => WriteExpression(a.Value) + " as " + a.Name.Text,
+ JunctionOperandSyntax j => (j.Role ? "role " : "") + j.Name.Text,
+ JunctionSyntax j => WriteExpression(j.Left) + " meets " + WriteExpression(j.Right),
TraceSyntax t => WriteExpression(t.Source) + (t.From is null ? "" : " from " + WriteExpression(t.From)) + (t.To is null ? "" : " to " + WriteExpression(t.To)),
MemberSetSyntax m => WriteExpression(m.Target) + ".[" + WriteArguments(m.Members) + "]",
TypedValueSyntax t => WriteExpression(t.Type) + " = " + WriteExpression(t.Value),
diff --git a/docs/development/reports/2026-11/CTC-01-DECOMPILE.md b/docs/development/reports/2026-11/CTC-01-DECOMPILE.md
index 6fdbdea6..bf13b6e5 100644
--- a/docs/development/reports/2026-11/CTC-01-DECOMPILE.md
+++ b/docs/development/reports/2026-11/CTC-01-DECOMPILE.md
@@ -193,6 +193,38 @@ Evidence:
and arc/arc corners: tangency and continuity at both joins.
- The full parallel lane is green.
+## Follow-up: junction fillets (`where: A meets B`)
+
+`EdgeFinish<Fillet> HexFoot { where: Hex meets PlateStock; radius: 5mm }` fillets the hex boss's foot.
+
+What changed:
+- **Syntax:** `A meets B` and `role X` are expressions (`JunctionSyntax`).
+- **Route:** `JunctionFilletRoute` strips the `where` finishes, builds the body, and attributes each face to the
+ Compose operations whose prisms it lies on. It then rounds the edges between A-only and B-only faces with
+ `UniformRounding.RoundSelectedEdges`.
+- **Kernel:** `LocalRounding` gains:
+ - a `Selected` pass with a radius per edge, so all junction finishes are built in one construction;
+ - a `Mitre` vertex: two strips on one floor meeting where the kept edge between their walls stands square
+ to it. The strips' axes cross at the ball touching all three planes, and the section is an exact quarter
+ `Ellipse3`.
+- **Fixed in passing:** `LocalRounding`'s loop walk turned back along a seam on hole walls whose rims are split
+ into arcs, which strands the rims. Rounding any body with such a hole hit it.
+
+Evidence:
+- **CTC-01:** 81/85 carriers, 0 extra, IoU 0.999029 (from 0.998904). The six R5 cylinders match the
+ original's axes, through-points and bounds exactly.
+- **Standalone hex foot:** 19 faces, 6 cylinders, 6 ellipse edges, manifold. The added volume is within the
+ sampling error of the analytic mitred prism (1900.0 mm³).
+- **Refusals:** five invalid fixtures, each naming its cause. A radius that does not fit reports the largest
+ that does (19.28 mm, where the offset hexagon's corner reaches the plate's edge).
+
+The lug R10 fillets are the honest stop. `where: role Pad meets PlateStock` selects the right edges. But each
+lug's inner root edge ends at the point where the plate underside's boundary runs tangentially into an R25 waist
+wall (`uniform-rounding-mixed-vertex-unsupported`, naming the vertex). The original ends those fillets against
+the waist cylinder carried down through the lug. That end edge is a cylinder–cylinder intersection, a true
+spline. Closing it needs a general intersection curve and a rule for where a strip ends against a curved wall.
+That is a feature of its own, not a patch to this one.
+
## Verdict
Meaningful progression. CTC-01 builds with every feature Firmament can express, and the comparison
diff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.md
index 7f7be45b..2eda9497 100644
--- a/docs/public/reference/language/solids-and-features.md
+++ b/docs/public/reference/language/solids-and-features.md
@@ -194,6 +194,38 @@ Model Plate {
}
```
+### Fillets where two operations meet
+
+`where: A meets B` selects the edges where the faces of two Compose operations
+meet, and rounds them with one ball:
+
+```text
+EdgeFinish<Fillet> HexFoot { where: Hex meets Stock; radius: 5mm }
+```
+
+[`hex-boss-foot.firmament`](../../../../fixtures/Regression/JunctionFillet/hex-boss-foot.firmament)
+rounds a hexagonal boss's foot this way.
+
+- `A` and `B` name Compose operations (`Base`, `Add`, `Boss`, `Pocket`), or
+ `role Name` for every operation with that role (`where: role Pad meets Plate`).
+- A face belongs to an operation when it lies on that operation's prism: a cap
+ inside its profile at one of its heights, or a side on its outline. An edge is
+ selected when one of its faces belongs to `A` but not `B` and the other to `B`
+ but not `A`. A wall that two operations share, such as a pad flush with the
+ plate's side, selects nothing.
+- Straight edges become exact cylinders and circular ones tori. Where two rounded
+ edges on one face turn a corner and the edge between their walls stands square
+ to that face, as at a boss's foot, they meet in an exact quarter-ellipse mitre.
+ A rounded edge may also end on a face standing square to it.
+- Several `where` finishes on one body are built together, each with its own
+ radius, after the body's other construction (holes and another finish
+ included). Edges of different radii must not meet.
+- Rejected: `where` on a chamfer; operations that are not on XY along +Z; names
+ that are not operations or roles of the Compose body; a junction with no edges;
+ a rounded edge that ends where its face's edge runs on tangentially into a
+ curved wall, or at a corner of convex and concave edges other than a mitre; and
+ a radius that does not fit, which is refused with the largest that does.
+
What you can select depends on the body:
| Body | Selection |
@@ -207,7 +239,8 @@ The details that trip people up:
- **One finish per construction.** Several finish requests on one Profile or
Compose body reject, rather than building only the first. Uncalled Feature and
- Template definitions do not count.
+ Template definitions do not count. `where` fillets are the exception: any number
+ of them can sit alongside one other finish.
- **Box rim with holes.** One Box top-rim chamfer or fillet can sit with top
`ThroughAll` holes in the same Modify, if the hole entries stay strictly inside
the inset top face. Blind and side holes sharing a rim finish are not supported.
diff --git a/fixtures/Invalid/JunctionFillet/chamfer-kind.firmament b/fixtures/Invalid/JunctionFillet/chamfer-kind.firmament
new file mode 100644
index 00000000..f0682ddc
--- /dev/null
+++ b/fixtures/Invalid/JunctionFillet/chamfer-kind.firmament
@@ -0,0 +1,15 @@
+// A junction is selected for fillets only.
+Model HexBossFoot {
+ units: mm
+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [200mm, 160mm] }
+ Profile HexBoss = RegularPolygon2<6> { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ Struct Part {
+ Compose Body {
+ Base Stock { profile: Plate; from: -20mm; to: 0mm; role: Stock }
+ Boss Hex { on: Top; profile: HexBoss; height: 30mm }
+ }
+ }
+ Modify Body {
+ EdgeFinish<Chamfer> HexFoot { where: Hex meets Stock; distance: 5mm }
+ }
+}
diff --git a/fixtures/Invalid/JunctionFillet/too-large.firmament b/fixtures/Invalid/JunctionFillet/too-large.firmament
new file mode 100644
index 00000000..917ee99c
--- /dev/null
+++ b/fixtures/Invalid/JunctionFillet/too-large.firmament
@@ -0,0 +1,15 @@
+// A 40 mm ball does not fit at the hex corners next to the 30 mm boss.
+Model HexBossFoot {
+ units: mm
+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [200mm, 160mm] }
+ Profile HexBoss = RegularPolygon2<6> { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ Struct Part {
+ Compose Body {
+ Base Stock { profile: Plate; from: -20mm; to: 0mm; role: Stock }
+ Boss Hex { on: Top; profile: HexBoss; height: 30mm }
+ }
+ }
+ Modify Body {
+ EdgeFinish<Fillet> HexFoot { where: Hex meets Stock; radius: 40mm }
+ }
+}
diff --git a/fixtures/Invalid/JunctionFillet/unknown-operand.firmament b/fixtures/Invalid/JunctionFillet/unknown-operand.firmament
new file mode 100644
index 00000000..cdfd9cb8
--- /dev/null
+++ b/fixtures/Invalid/JunctionFillet/unknown-operand.firmament
@@ -0,0 +1,15 @@
+// Plinth is not an operation of the Compose body.
+Model HexBossFoot {
+ units: mm
+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [200mm, 160mm] }
+ Profile HexBoss = RegularPolygon2<6> { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ Struct Part {
+ Compose Body {
+ Base Stock { profile: Plate; from: -20mm; to: 0mm; role: Stock }
+ Boss Hex { on: Top; profile: HexBoss; height: 30mm }
+ }
+ }
+ Modify Body {
+ EdgeFinish<Fillet> HexFoot { where: Hex meets Plinth; radius: 5mm }
+ }
+}
diff --git a/fixtures/Invalid/JunctionFillet/unknown-role.firmament b/fixtures/Invalid/JunctionFillet/unknown-role.firmament
new file mode 100644
index 00000000..6ed8a560
--- /dev/null
+++ b/fixtures/Invalid/JunctionFillet/unknown-role.firmament
@@ -0,0 +1,15 @@
+// No operation has the role Pad.
+Model HexBossFoot {
+ units: mm
+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [200mm, 160mm] }
+ Profile HexBoss = RegularPolygon2<6> { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ Struct Part {
+ Compose Body {
+ Base Stock { profile: Plate; from: -20mm; to: 0mm; role: Stock }
+ Boss Hex { on: Top; profile: HexBoss; height: 30mm }
+ }
+ }
+ Modify Body {
+ EdgeFinish<Fillet> HexFoot { where: role Pad meets Stock; radius: 5mm }
+ }
+}
diff --git a/fixtures/Invalid/JunctionFillet/where-not-junction.firmament b/fixtures/Invalid/JunctionFillet/where-not-junction.firmament
new file mode 100644
index 00000000..4c245a59
--- /dev/null
+++ b/fixtures/Invalid/JunctionFillet/where-not-junction.firmament
@@ -0,0 +1,15 @@
+// where needs a junction, A meets B.
+Model HexBossFoot {
+ units: mm
+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [200mm, 160mm] }
+ Profile HexBoss = RegularPolygon2<6> { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ Struct Part {
+ Compose Body {
+ Base Stock { profile: Plate; from: -20mm; to: 0mm; role: Stock }
+ Boss Hex { on: Top; profile: HexBoss; height: 30mm }
+ }
+ }
+ Modify Body {
+ EdgeFinish<Fillet> HexFoot { where: Hex; radius: 5mm }
+ }
+}
diff --git a/fixtures/Regression/Decompile/ctc-01.firmament b/fixtures/Regression/Decompile/ctc-01.firmament
index 279544e8..382b3003 100644
--- a/fixtures/Regression/Decompile/ctc-01.firmament
+++ b/fixtures/Regression/Decompile/ctc-01.firmament
@@ -2,10 +2,9 @@
// a dog-bone plate (two rounded ends and a bridge) with four lugs underneath, a hexagonal boss on top,
// through holes, slots, side drills, and 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:
-// - 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).
+// Not expressible yet, and therefore absent here: the R10 fillets where the lugs' inner walls meet the plate
+// underside. Each ends where the underside's edge runs tangentially into an R25 waist wall; the original ends it
+// against that wall's cylinder carried down through the lug, which leaves a spline edge.
Model Ctc01 {
units: mm
@@ -170,5 +169,6 @@ Model Ctc01 {
Hole<Shaft> SideDrillRight { from: Plate.Front; 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 }
+ EdgeFinish<Fillet> HexFoot { where: Hex meets PlateStock; radius: 5mm }
}
}
diff --git a/fixtures/Regression/JunctionFillet/hex-boss-foot.firmament b/fixtures/Regression/JunctionFillet/hex-boss-foot.firmament
new file mode 100644
index 00000000..6f99f922
--- /dev/null
+++ b/fixtures/Regression/JunctionFillet/hex-boss-foot.firmament
@@ -0,0 +1,15 @@
+// An R5 fillet where a hexagonal boss meets the plate it stands on.
+Model HexBossFoot {
+ units: mm
+ Profile Plate = Rect2 { center: [0mm, 0mm]; size: [200mm, 160mm] }
+ Profile HexBoss = RegularPolygon2<6> { center: [0mm, 0mm]; acrossFlats: 100mm; rotation: 30deg }
+ Struct Part {
+ Compose Body {
+ Base Stock { profile: Plate; from: -20mm; to: 0mm; role: Stock }
+ Boss Hex { on: Top; profile: HexBoss; height: 30mm }
+ }
+ }
+ Modify Body {
+ EdgeFinish<Fillet> HexFoot { where: Hex meets Stock; radius: 5mm }
+ }
+}