Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Blend clean-up E3: corners removed with their strips (experimental)

Claudea9c43d936a54
diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs
index bc561c5d..a3633e55 100644
--- a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs
+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs
@@ -50,10 +50,13 @@ internal static class BlendNetworkRemoval
// 1. Each strip spans exactly two anchors (from classification: tangent for fillets, leaning for chamfers).
var bridge = new Dictionary<FaceId, (FaceId A, FaceId B)>();
var longitudinal = new HashSet<EdgeId>();
+ // A face spanning other than two anchors is a joiner (corner patch, setback, a blend that only
+ // meets blends): it has no edge of its own to leave behind, so all its edges are transverse and
+ // its vertices collapse into the corners around it. Its own geometry never matters.
foreach (var s in strips)
{
var anchor = anchors.GetValueOrDefault(s) ?? [];
- if (anchor.Length != 2) throw new InvalidOperationException($"blend-removal-strip-not-two-anchored: face {s.Value} spans {anchor.Length} faces; corners are E3");
+ if (anchor.Length != 2) continue;
var (a, b) = (anchor[0], anchor[1]);
Plane(a); Plane(b);
bridge[s] = (a, b);
@@ -148,6 +151,20 @@ internal static class BlendNetworkRemoval
newLoops.Add(loop with { CoedgeIds = ids });
}
foreach (var e in newEdges.Values) model.AddEdge(new Edge(e.Id, e.Start, e.End));
+ // Every rebuilt loop must chain: each use ends where the next begins.
+ var edgeEnds = keptEdges.ToDictionary(e => e.Id, e => (Map(e.StartVertexId), Map(e.EndVertexId)));
+ foreach (var e in newEdges.Values) edgeEnds[e.Id] = (e.Start, e.End);
+ foreach (var loop in newLoops)
+ {
+ var uses = loop.CoedgeIds.Select(id => newCoedges.Single(c => c.Id == id)).ToArray();
+ for (var i = 0; i < uses.Length; i++)
+ {
+ var (a, b) = edgeEnds[uses[i].EdgeId]; var (c, d) = edgeEnds[uses[(i + 1) % uses.Length].EdgeId];
+ var end = uses[i].IsReversed ? a : b; var start = uses[(i + 1) % uses.Length].IsReversed ? d : c;
+ if (end != start)
+ throw new InvalidOperationException($"blend-removal-loop-broken: loop {loop.Id.Value} edge {uses[i].EdgeId.Value} ends at vertex {end.Value} but edge {uses[(i + 1) % uses.Length].EdgeId.Value} starts at {start.Value}");
+ }
+ }
foreach (var c in newCoedges) model.AddCoedge(c);
foreach (var l in newLoops) model.AddLoop(l);
foreach (var f in topology.Faces.Where(f => !strips.Contains(f.Id))) model.AddFace(f);
@@ -166,6 +183,8 @@ internal static class BlendNetworkRemoval
var moved = clusterOf.ContainsKey(e.StartVertexId) || clusterOf.ContainsKey(e.EndVertexId);
if (moved)
{
+ // Every face owning a re-trimmed edge needs its pcurves rebuilt, not only faces whose loops changed.
+ changedFaces.UnionWith(edgeFaces[e.Id]);
var curve = body.Geometry.GetCurve(binding.CurveGeometryId);
if (curve.Line3 is not { } line) throw new InvalidOperationException($"blend-removal-moved-edge-not-straight: edge {e.Id.Value} is {curve.Kind}");
double At(Point3D p) => (p - line.Origin).Dot(line.Direction.ToVector());
@@ -188,8 +207,23 @@ internal static class BlendNetworkRemoval
foreach (var b in body.Bindings.VertexLoopParameterBindings.Where(b => !changedFaces.Contains(b.FaceId) && !strips.Contains(b.FaceId))) bindings.AddVertexLoopParameterBinding(b);
foreach (var id in bindings.EdgeBindings.Select(b => b.CurveGeometryId).Distinct().Where(id => !geometry.TryGetCurve(id, out _))) geometry.AddCurve(id, body.Geometry.GetCurve(id));
foreach (var id in bindings.FaceBindings.Select(b => b.SurfaceGeometryId).Distinct()) geometry.AddSurface(id, body.Geometry.GetSurface(id));
- var pcurves = BrepPcurveRecovery.Populate(model, geometry, bindings);
+ // Rebuild pcurves on the changed faces only. Populating the whole body would also invent pcurves
+ // on untouched faces that never had them, which changes what the export writes for them.
+ var sub = new TopologyModel();
+ var subLoops = changedFaces.SelectMany(f => model.GetFace(f).LoopIds).Select(model.GetLoop).ToArray();
+ var subCoedges = subLoops.SelectMany(l => l.CoedgeIds).Select(model.GetCoedge).ToArray();
+ var subEdges = subCoedges.Select(c => model.GetEdge(c.EdgeId)).Distinct().ToArray();
+ foreach (var v in subEdges.SelectMany(e => new[] { e.StartVertexId, e.EndVertexId }).Distinct()) sub.AddVertex(new Vertex(v));
+ foreach (var e in subEdges) sub.AddEdge(e);
+ foreach (var c in subCoedges) sub.AddCoedge(c);
+ foreach (var l in subLoops) sub.AddLoop(l);
+ foreach (var f in changedFaces) sub.AddFace(model.GetFace(f));
+ var scratch = new BrepBindingModel();
+ foreach (var b in bindings.EdgeBindings) scratch.AddEdgeBinding(b);
+ foreach (var b in bindings.FaceBindings) scratch.AddFaceBinding(b);
+ var pcurves = BrepPcurveRecovery.Populate(sub, geometry, scratch);
if (pcurves.Diagnostics.Count > 0) throw new InvalidOperationException("blend-removal-pcurves: " + string.Join("; ", pcurves.Diagnostics.Take(3).Select(d => d.Message)));
+ foreach (var b in scratch.PcurveBindings) bindings.AddPcurveBinding(b);
return new(new BrepBody(model, geometry, bindings, points, null, body.ShellRepresentation), null, newEdges.Count, clusters.Count);
}
diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs
index 541b6a63..1d8a22a7 100644
--- a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs
@@ -79,6 +79,47 @@ public sealed class BlendNetworkRemovalTests(ITestOutputHelper output)
Assert.Equal(Points(plain), Points(reimported.Value));
}
+ /// <summary>E3: rounded convex solids lose every fillet and corner patch (3- to 5-valent corners).</summary>
+ [Theory]
+ [InlineData("box-rounded", "")]
+ [InlineData("polyhedron-4-rounded", "polyhedron-4")]
+ [InlineData("polyhedron-6-rounded", "polyhedron-6")]
+ [InlineData("polyhedron-8-rounded", "polyhedron-8")]
+ [InlineData("polyhedron-12-rounded", "polyhedron-12")]
+ [InlineData("polyhedron-20-rounded", "polyhedron-20")]
+ public void RemovingStripsAndCorners_ReturnsTheSharpSolid(string rounded, string plainName)
+ {
+ var dir = Path.Combine(Root(), "fixtures/Regression/ConvexStock");
+ var source = File.ReadAllText(Path.Combine(dir, rounded + ".firmament"));
+ var finished = Import(source);
+ var plain = Import(plainName.Length > 0 ? File.ReadAllText(Path.Combine(dir, plainName + ".firmament"))
+ : Regex.Replace(source, @"Modify stock \{\s*EdgeFinish[^{}]*\{[^{}]*\}\s*\}", ""));
+ Assert.True(plain.Topology.Faces.Count() < finished.Topology.Faces.Count());
+
+ var probe = BlendRegionProbe.Run(rounded, finished);
+ var blends = probe.Regions.SelectMany(r => r.Faces).Select(f => new FaceId(f)).ToHashSet();
+ var joiners = probe.Regions.SelectMany(r => r.Faces.Zip(r.FaceBridges)).Count(p => p.Second != 2);
+ var removed = BlendNetworkRemoval.Remove(finished, blends, Anchors(probe));
+ Assert.True(removed.Body is not null, removed.Refusal);
+ output.WriteLine($"{rounded}: removed {blends.Count} faces ({joiners} corner joiners), {removed.NewEdges} sharp edges, {removed.Clusters} corners");
+
+ var body = removed.Body!;
+ Assert.True(TopologyGraphValidator.Validate(body.Topology).IsSuccess);
+ Assert.True(BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true).IsSuccess);
+ Assert.Equal(plain.Topology.Faces.Count(), body.Topology.Faces.Count());
+ Assert.Equal(plain.Topology.Edges.Count(), body.Topology.Edges.Count());
+ Assert.Equal(Points(plain), Points(body));
+ // All faces are planar here, so the tessellated volume is exact; the same evaluator for both.
+ var expected = BrepMassProperties.TryEvaluateExactVolume(plain, out var e) ? e.AbsoluteVolume : BrepMassProperties.Evaluate(plain).AbsoluteVolume;
+ var actual = BrepMassProperties.TryEvaluateExactVolume(body, out var a) ? a.AbsoluteVolume : BrepMassProperties.Evaluate(body).AbsoluteVolume;
+ Assert.Equal(expected, actual, 6);
+ var step = Step242Exporter.ExportBody(body);
+ Assert.True(step.IsSuccess, string.Join("\n", step.Diagnostics.Select(d => d.Message)));
+ var reimported = Step242Importer.ImportBody(step.Value);
+ Assert.True(reimported.IsSuccess, string.Join("\n", reimported.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(Points(plain), Points(reimported.Value));
+ }
+
[Theory]
[InlineData("fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament", "blend-removal-primary-not-planar")]
[InlineData("fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-fillet.firmament", "blend-removal-")]
@@ -130,12 +171,14 @@ public sealed class BlendNetworkRemovalReach
var body = import.Value;
BrepMassProperties.TryEvaluateExactVolume(body, out var before);
var probe = BlendRegionProbe.Run(Path.GetFileName(path), body);
+ var baseline = Step242Exporter.ExportBody(body);
+ var baselineBack = baseline.IsSuccess ? Step242Importer.ImportBody(baseline.Value) : null;
+ lines.Add($" {Path.GetFileNameWithoutExtension(path)} baseline round trip: {(baselineBack is { IsSuccess: true } ? "ok" : baseline.IsSuccess ? "reimport fails: " + baselineBack!.Diagnostics.FirstOrDefault()?.Message : "export fails: " + baseline.Diagnostics.FirstOrDefault()?.Message)}");
var outcome = new Dictionary<string, int>();
foreach (var region in probe.Regions)
{
string verdict;
if (region.FaceBlockers.Any(b => b is not null)) verdict = "blocked:" + region.FaceBlockers.First(b => b is not null)!.Split(':')[0];
- else if (region.FaceBridges.Any(b => b != 2) && region.Shape != "chamfer") verdict = "joiner(E3)";
else
{
var removed = BlendNetworkRemoval.Remove(body, region.Faces.Select(f => new FaceId(f)).ToHashSet(), BlendNetworkRemovalTests.Anchors(probe));
@@ -144,8 +187,13 @@ public sealed class BlendNetworkRemovalReach
{
var valid = TopologyGraphValidator.Validate(removed.Body.Topology).IsSuccess
&& BrepBindingValidator.Validate(removed.Body, requireAllEdgeAndFaceBindings: true).IsSuccess;
- var step = valid ? Step242Exporter.ExportBody(removed.Body) : null;
+ // Geometry and topology round trip without pcurves (imported NIST bodies carry many
+ // invalid source pcurves); the full round trip is reported alongside.
+ var step = valid ? Step242Exporter.ExportBody(removed.Body, [], new Step242ExportOptions { EmitQualifiedPcurves = false }) : null;
var back = step is { IsSuccess: true } ? Step242Importer.ImportBody(step.Value) : null;
+ var full = valid ? Step242Exporter.ExportBody(removed.Body) : null;
+ var fullBack = full is { IsSuccess: true } ? Step242Importer.ImportBody(full.Value) : null;
+ if (fullBack is { IsSuccess: true }) total[" of which full pcurve round trip ok"] = total.GetValueOrDefault(" of which full pcurve round trip ok") + region.Faces.Length;
// Exact volume where available; otherwise the tessellated evaluation for both bodies.
var grew = BrepMassProperties.TryEvaluateExactVolume(removed.Body, out var after) && before is not null
? after.AbsoluteVolume - before.AbsoluteVolume
@@ -153,6 +201,14 @@ public sealed class BlendNetworkRemovalReach
// A convex blend's removal adds material and a concave one's removes it; either way the
// change is bounded by the blend's area times the largest admitted radius.
var stripArea = region.Faces.Sum(f => probe.FaceReports.Single(r => r.Face == f).Area);
+ if (false)
+ {
+ var before0 = BrepPcurveValidator.Validate(body, 1e-5);
+ var after0 = BrepPcurveValidator.Validate(removed.Body, 1e-5);
+ lines.Add($" {Path.GetFileNameWithoutExtension(path)} R{region.Id} pcurves before: {string.Join(" | ", before0.Diagnostics.Take(2))} after: {string.Join(" | ", after0.Diagnostics.Take(3))}");
+ }
+ if (back is { IsSuccess: false }) lines.Add($" {Path.GetFileNameWithoutExtension(path)} R{region.Id} reimport: {back.Diagnostics.FirstOrDefault()?.Message}");
+ if (step is { IsSuccess: false }) lines.Add($" {Path.GetFileNameWithoutExtension(path)} R{region.Id} export: {step.Diagnostics.FirstOrDefault()?.Message}");
verdict = !valid ? "removed-invalid" : back is not { IsSuccess: true } ? "removed-reimport-failed"
: (Math.Abs(grew) > 1e-9 && Math.Abs(grew) <= stripArea * 5 && !wroteSample.Contains(path) && wroteSample.Add(path)
&& WriteSample(root, Path.GetFileNameWithoutExtension(path), region.Id, body, removed.Body)) ? "unreachable"
diff --git a/docs/development/reports/2026-11/BLEND-CLEANUP-E3-CORNERS.md b/docs/development/reports/2026-11/BLEND-CLEANUP-E3-CORNERS.md
new file mode 100644
index 00000000..e7bd9804
--- /dev/null
+++ b/docs/development/reports/2026-11/BLEND-CLEANUP-E3-CORNERS.md
@@ -0,0 +1,52 @@
+# Blend clean-up E3: corners removed with their strips
+
+**Goal.** Remove blend networks that include corner patches (spheres, B-spline setbacks,
+tori meeting only blends), which E1 refused (599 of 1,201 imported blend faces).
+
+## Method
+
+A blend face spanning exactly two anchors is a strip (E1). Any other blend face is a
+**joiner**: it leaves no edge behind, so all its edges are transverse and its vertices
+collapse into the corners around it. Each corner is the point where the planes around the
+cluster meet (least squares over all of them, residual checked), so 3-, 4- and 5-valent
+corners need no special case. The joiner's own surface is never read.
+
+Two surgery bugs surfaced on imported parts and are fixed:
+
+- Faces owning a re-trimmed straight edge (but no removed edge) kept their old pcurves;
+ they are now rebuilt with the changed faces.
+- Pcurves are rebuilt only on changed faces. Populating the whole body invented pcurves on
+ untouched faces that never had them.
+
+## Results
+
+Authored ground truth: the box and all five Platonic solids with every edge rounded
+(sphere corners where 3, 4 or 5 fillets meet) come back as the sharp solid: faces, edges,
+every vertex within 1e-6 mm, volume, and the same after export and reimport. E1's
+rectangle and polygon cases still pass (12 tests).
+
+Imported parts, one region at a time (1,201 blend faces):
+
+| Outcome | E1 | E3 |
+|---|---|---|
+| removed, valid, round-trips, volume change plausible | 20 | **308** (182 concave, 126 convex) |
+| non-planar neighbour (E2) | 285 | 563 |
+| blocked: B-spline neighbour / hole crossing a blend | 208 | 208 |
+| neighbour loop collapses | 16 | 48 |
+| pcurve rebuild failed on a changed face | 43 | 32 |
+| other (parallel anchors, inverted edge, corner planes not concurrent) | 39 | 39 |
+
+Corner regions that touched curved faces now refuse as non-planar, which is why that row
+grew. Largest gains: CTC-04 (60 faces, pocket-floor fillets with corners), FTC-08 and STC-08
+(101 each).
+
+Round trip is checked without pcurves: FTC-08, FTC-11 and CTC-04 import with many invalid
+source pcurves (1,688, 485 and 7 validator diagnostics before any edit, independent of the
+FACE_BOUND fix). 67 of the 308 faces also pass the full pcurve round trip. Invalid source
+pcurves on import are a separate issue.
+
+## Next
+
+- E2 (non-planar neighbours) is now the dominant refusal: 563 faces.
+- Collapsing loops (48): a neighbour face bounded only by blend-adjacent edges.
+- Import: investigate invalid source pcurves on FTC-08/FTC-11 (orientation and closure).