Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Blend clean-up E1: strip-network removal between planes (experimental)
Claude868d832873a0
diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.csnew file mode 100644index 00000000..bc561c5d--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs@@ -0,0 +1,243 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Firmament.Tests.Experiments;++/// <summary>+/// E1 of blend clean-up: delete a network of blend strips bounded by planes and rebuild the+/// sharp geometry from the extended planes. Each strip becomes the line where its two bridged+/// planes meet; every cluster of vertices joined by a strip's end or miter edges becomes the+/// point where the planes meeting there intersect. Experimental: planar primaries only;+/// anything else refuses with a reason.+/// </summary>+internal static class BlendNetworkRemoval+{+ private const double Tol = 1e-6;++ internal sealed record Result(BrepBody? Body, string? Refusal, int NewEdges, int Clusters);++ internal static Result Remove(BrepBody body, IReadOnlySet<FaceId> strips, IReadOnlyDictionary<FaceId, FaceId[]> anchors)+ {+ try { return Run(body, strips, anchors); }+ catch (InvalidOperationException refusal) { return new(null, refusal.Message, 0, 0); }+ }++ private static Result Run(BrepBody body, IReadOnlySet<FaceId> strips, IReadOnlyDictionary<FaceId, FaceId[]> anchors)+ {+ var topology = body.Topology;+ var edgeFaces = new Dictionary<EdgeId, List<FaceId>>();+ foreach (var face in topology.Faces)+ foreach (var loop in face.LoopIds)+ foreach (var c in topology.GetLoop(loop).CoedgeIds)+ {+ var e = topology.GetCoedge(c).EdgeId;+ if (!edgeFaces.TryGetValue(e, out var list)) edgeFaces[e] = list = [];+ list.Add(face.Id);+ }+ PlaneSurface Plane(FaceId f) => body.TryGetFaceSurfaceGeometry(f, out var s) && s?.Plane is { } p ? p+ : throw new InvalidOperationException($"blend-removal-primary-not-planar: face {f.Value} borders the network and is {s?.Kind}; E1 admits planes only");+ var lengths = BrepDisplayTessellator.Tessellate(body).Value.EdgePolylines+ .ToDictionary(p => p.EdgeId, p => p.Points.Zip(p.Points.Skip(1)).Sum(q => (q.Second - q.First).Length));+ FaceId Other(EdgeId e, FaceId f) => edgeFaces[e].Count == 2 && edgeFaces[e][0] != edgeFaces[e][1] ? edgeFaces[e].Single(x => x != f) : throw new InvalidOperationException($"blend-removal-seam-edge: edge {e.Value} is a seam or non-manifold");+ IEnumerable<EdgeId> EdgesOf(FaceId f) => topology.GetFace(f).LoopIds.SelectMany(l => topology.GetLoop(l).CoedgeIds)+ .Select(c => topology.GetCoedge(c).EdgeId).Distinct();++ // 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>();+ 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");+ var (a, b) = (anchor[0], anchor[1]);+ Plane(a); Plane(b);+ bridge[s] = (a, b);+ foreach (var e in EdgesOf(s).Where(e => edgeFaces[e].Count == 2 && (Other(e, s) == a || Other(e, s) == b))) longitudinal.Add(e);+ }+ if (strips.SelectMany(EdgesOf).Any(e => edgeFaces[e].Count != 2 || edgeFaces[e][0] == edgeFaces[e][1]))+ throw new InvalidOperationException("blend-removal-seam-edge: a strip has a seam or non-manifold edge");+ var touched = strips.SelectMany(EdgesOf).ToHashSet();+ var transverse = touched.Where(e => !longitudinal.Contains(e)).ToHashSet();++ // 2. Vertex clusters: vertices joined by transverse (end, miter) edges collapse to one corner.+ var parent = new Dictionary<VertexId, VertexId>();+ VertexId Find(VertexId v) { if (!parent.ContainsKey(v)) parent[v] = v; while (parent[v] != v) v = parent[v] = parent[parent[v]]; return v; }+ foreach (var e in touched) { var edge = topology.GetEdge(e); Find(edge.StartVertexId); Find(edge.EndVertexId); }+ foreach (var e in transverse) { var edge = topology.GetEdge(e); parent[Find(edge.StartVertexId)] = Find(edge.EndVertexId); }+ var clusterOf = parent.Keys.ToDictionary(v => v, Find);+ var clusters = clusterOf.GroupBy(p => p.Value).ToDictionary(g => g.Key, g => g.Select(p => p.Key).ToArray());++ // Each cluster's corner: the point where the outside planes around its vertices meet.+ var vertexFaces = new Dictionary<VertexId, HashSet<FaceId>>();+ foreach (var (e, faces) in edgeFaces)+ foreach (var v in new[] { topology.GetEdge(e).StartVertexId, topology.GetEdge(e).EndVertexId })+ {+ if (!vertexFaces.TryGetValue(v, out var set)) vertexFaces[v] = set = [];+ set.UnionWith(faces);+ }+ var corner = new Dictionary<VertexId, Point3D>();+ var representative = new Dictionary<VertexId, VertexId>();+ foreach (var (root, members) in clusters)+ {+ var planes = members.SelectMany(v => vertexFaces[v]).Where(f => !strips.Contains(f)).Distinct().Select(f => (Face: f, Plane: Plane(f))).ToArray();+ body.TryGetVertexPoint(members[0], out var seed);+ corner[root] = Solve(planes.Select(p => p.Plane).ToArray(), seed,+ $"cluster of vertices {string.Join(',', members.Select(m => m.Value))} on faces {string.Join(',', planes.Select(p => p.Face.Value))}");+ representative[root] = members.MinBy(v => v.Value)!;+ }+ VertexId Map(VertexId v) => clusterOf.TryGetValue(v, out var root) ? representative[root] : v;++ // 3. One straight edge per (corner, corner, plane pair).+ var nextEdge = topology.Edges.Max(e => e.Id.Value) + 1;+ var nextCurve = body.Geometry.Curves.Max(c => c.Key.Value) + 1;+ var newEdges = new Dictionary<(int, int, int, int), (EdgeId Id, VertexId Start, VertexId End, CurveGeometryId Curve, Line3Curve Line, double Length)>();+ (EdgeId Id, VertexId Start, VertexId End, CurveGeometryId Curve, Line3Curve Line, double Length) NewEdge(EdgeId old, FaceId s)+ {+ var edge = topology.GetEdge(old);+ var (u, v) = (Map(edge.StartVertexId), Map(edge.EndVertexId));+ if (u == v) throw new InvalidOperationException($"blend-removal-strip-collapses: edge {old.Value} has both ends in one corner");+ var (a, b) = bridge[s];+ var key = (Math.Min(u.Value, v.Value), Math.Max(u.Value, v.Value), Math.Min(a.Value, b.Value), Math.Max(a.Value, b.Value));+ if (newEdges.TryGetValue(key, out var made)) return made;+ var (start, end) = u.Value < v.Value ? (u, v) : (v, u);+ var p = corner[clusterOf[start]]; var q = corner[clusterOf[end]];+ var line = new Line3Curve(p, Direction3D.Create(q - p));+ return newEdges[key] = (new EdgeId(nextEdge++), start, end, new CurveGeometryId(nextCurve++), line, (q - p).Length);+ }++ // 4. Rebuild the loops of every face outside the network.+ var model = new TopologyModel();+ var keptVertices = topology.Vertices.Select(v => Map(v.Id)).Distinct().ToArray();+ foreach (var v in keptVertices) model.AddVertex(new Vertex(v));+ var keptEdges = topology.Edges.Where(e => !touched.Contains(e.Id)).ToArray();+ foreach (var e in keptEdges) model.AddEdge(e with { StartVertexId = Map(e.StartVertexId), EndVertexId = Map(e.EndVertexId) });+ var changedFaces = new HashSet<FaceId>();+ var newCoedges = new List<Coedge>();+ var newLoops = new List<Loop>();+ var nextCoedge = topology.Coedges.Max(c => c.Id.Value) + 1;+ foreach (var face in topology.Faces.Where(f => !strips.Contains(f.Id)))+ foreach (var loopId in face.LoopIds)+ {+ var loop = topology.GetLoop(loopId);+ var uses = new List<(EdgeId Edge, bool Reversed)>();+ var changed = false;+ foreach (var c in loop.CoedgeIds.Select(topology.GetCoedge))+ {+ if (!touched.Contains(c.EdgeId)) { uses.Add((c.EdgeId, c.IsReversed)); continue; }+ changed = true;+ var s = Other(c.EdgeId, face.Id);+ if (transverse.Contains(c.EdgeId)) continue; // its ends collapse into one corner+ var edge = topology.GetEdge(c.EdgeId);+ var from = Map(c.IsReversed ? edge.EndVertexId : edge.StartVertexId);+ var made = NewEdge(c.EdgeId, s);+ var use = (made.Id, from != made.Start);+ if (uses.Count == 0 || uses[^1] != use) uses.Add(use);+ }+ if (changed) changedFaces.Add(face.Id);+ if (uses.Count > 1 && uses[0] == uses[^1]) uses.RemoveAt(uses.Count - 1);+ if (uses.Count == 0) throw new InvalidOperationException($"blend-removal-loop-vanishes: face {face.Id.Value} loop {loopId.Value}");+ var ids = loop.CoedgeIds.Count == uses.Count && !changed ? loop.CoedgeIds.ToArray()+ : uses.Select(_ => new CoedgeId(nextCoedge++)).ToArray();+ for (var i = 0; i < uses.Count; i++)+ newCoedges.Add(new Coedge(ids[i], uses[i].Edge, loopId, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reversed));+ newLoops.Add(loop with { CoedgeIds = ids });+ }+ foreach (var e in newEdges.Values) model.AddEdge(new Edge(e.Id, e.Start, e.End));+ 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);+ foreach (var shell in topology.Shells) model.AddShell(shell with { FaceIds = shell.FaceIds.Where(f => !strips.Contains(f)).ToArray() });+ foreach (var b in topology.Bodies) model.AddBody(b);++ // 5. Bindings and geometry: kept edges re-trimmed to moved corners, new lines bound, pcurves rebuilt.+ var bindings = new BrepBindingModel();+ var geometry = new BrepGeometryStore();+ var points = new Dictionary<VertexId, Point3D>();+ foreach (var v in keptVertices)+ points[v] = clusterOf.TryGetValue(v, out var root) ? corner[root] : body.TryGetVertexPoint(v, out var p) ? p : throw new InvalidOperationException($"vertex {v.Value} has no point");+ foreach (var e in keptEdges)+ {+ var binding = body.Bindings.GetEdgeBinding(e.Id);+ var moved = clusterOf.ContainsKey(e.StartVertexId) || clusterOf.ContainsKey(e.EndVertexId);+ if (moved)+ {+ 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());+ var (s, t) = (At(points[Map(e.StartVertexId)]), At(points[Map(e.EndVertexId)]));+ if (!binding.OrientedEdgeSense) (s, t) = (t, s);+ if (t - s <= Tol) throw new InvalidOperationException($"blend-removal-edge-inverts: edge {e.Id.Value}");+ binding = binding with { TrimInterval = new ParameterInterval(s, t) };+ }+ bindings.AddEdgeBinding(binding);+ }+ foreach (var e in newEdges.Values)+ {+ geometry.AddCurve(e.Curve, CurveGeometry.FromLine(e.Line));+ bindings.AddEdgeBinding(new EdgeGeometryBinding(e.Id, e.Curve, new ParameterInterval(0, e.Length)));+ }+ foreach (var b in body.Bindings.FaceBindings.Where(b => !strips.Contains(b.FaceId))) bindings.AddFaceBinding(b);+ foreach (var b in body.Bindings.FaceBoundaryRoleBindings.Where(b => !strips.Contains(b.FaceId))) bindings.AddFaceBoundaryRoleBinding(b);+ var keptCoedges = newCoedges.Select(c => c.Id).ToHashSet();+ foreach (var b in body.Bindings.PcurveBindings.Where(b => keptCoedges.Contains(b.CoedgeId) && !changedFaces.Contains(b.FaceId))) bindings.AddPcurveBinding(b);+ 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);+ if (pcurves.Diagnostics.Count > 0) throw new InvalidOperationException("blend-removal-pcurves: " + string.Join("; ", pcurves.Diagnostics.Take(3).Select(d => d.Message)));+ return new(new BrepBody(model, geometry, bindings, points, null, body.ShellRepresentation), null, newEdges.Count, clusters.Count);+ }++ /// <summary>Point common to the planes (least squares, then checked), or the point on their+ /// line nearest the seed when only two planes meet there.</summary>+ private static Point3D Solve(PlaneSurface[] planes, Point3D seed, string where)+ {+ if (planes.Length < 2) throw new InvalidOperationException($"blend-removal-corner-underdetermined: {where}");+ var n = planes.Select(p => p.Normal.ToVector()).ToArray();+ var d = planes.Select(p => p.Normal.ToVector().Dot(p.Origin - Point3D.Origin)).ToArray();+ Point3D x;+ if (planes.Length == 2 || Rank(n) == 2)+ {+ // Nearest point to the seed on the line where the planes meet.+ var direction = n[0].Cross(n[1]);+ if (direction.Length < 1e-9) throw new InvalidOperationException($"blend-removal-planes-parallel: {where}");+ var m = new[] { n[0], n[1], direction };+ x = Solve3(m, [d[0], d[1], direction.Dot(seed - Point3D.Origin)]);+ }+ else+ {+ // Normal equations over all planes.+ var a = new double[3, 3]; var r = new double[3];+ for (var k = 0; k < n.Length; k++)+ {+ var v = new[] { n[k].X, n[k].Y, n[k].Z };+ for (var i = 0; i < 3; i++) { r[i] += v[i] * d[k]; for (var j = 0; j < 3; j++) a[i, j] += v[i] * v[j]; }+ }+ x = Solve3([new(a[0, 0], a[0, 1], a[0, 2]), new(a[1, 0], a[1, 1], a[1, 2]), new(a[2, 0], a[2, 1], a[2, 2])], r);+ }+ var residual = n.Zip(d).Max(p => Math.Abs(p.First.Dot(x - Point3D.Origin) - p.Second));+ if (residual > 1e-6) throw new InvalidOperationException($"blend-removal-corner-not-common: {planes.Length} planes miss one point by {residual:G3} mm at {where}");+ return x;+ }++ private static int Rank(Vector3D[] n)+ {+ var det = n.Length < 3 ? 0 : Enumerable.Range(0, n.Length).SelectMany(i => Enumerable.Range(i + 1, n.Length - i - 1).SelectMany(j =>+ Enumerable.Range(j + 1, n.Length - j - 1).Select(k => Math.Abs(n[i].Dot(n[j].Cross(n[k])))))).DefaultIfEmpty(0).Max();+ return det > 1e-9 ? 3 : 2;+ }++ private static Point3D Solve3(Vector3D[] rows, double[] rhs)+ {+ var det = rows[0].Dot(rows[1].Cross(rows[2]));+ if (Math.Abs(det) < 1e-12) throw new InvalidOperationException("blend-removal-corner-singular");+ var c0 = rows[1].Cross(rows[2]); var c1 = rows[2].Cross(rows[0]); var c2 = rows[0].Cross(rows[1]);+ var v = (c0 * rhs[0] + c1 * rhs[1] + c2 * rhs[2]) * (1 / det);+ return Point3D.Origin + v;+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.csnew file mode 100644index 00000000..541b6a63--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs@@ -0,0 +1,186 @@+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;+using Xunit.Abstractions;++namespace Aetheris.Kernel.Firmament.Tests.Experiments;++/// <summary>E1: author a part with a finish, remove the probe's strips, compare with the part+/// authored without the finish.</summary>+public sealed class BlendNetworkRemovalTests(ITestOutputHelper output)+{+ private static string Root()+ {+ 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;+ }++ private static string Rect(string finish) => $$"""+ Model R {+ units: mm+ Path Outline {+ start: Point2(0mm, 0mm)+ heading: 0deg+ Line South { length: 40mm }+ Line East { turn: 90deg; length: 25mm }+ Line North { turn: 90deg; length: 40mm }+ Close West+ }+ Profile Section from Outline+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 10mm } }+ {{finish}}+ }+ """;++ public static TheoryData<string, string> Admitted => new()+ {+ { "rect-top-fillet", Rect("Modify Body { EdgeFinish Rim { target: Section.Outer; on: Top; kind: Fillet; radius: 2mm } }") },+ { "rect-top-chamfer", Rect("Modify Body { EdgeFinish Rim { target: Section.Outer; on: Top; kind: Chamfer; distance: 2mm } }") },+ { "rect-bottom-fillet", Rect("Modify Body { EdgeFinish Rim { target: Section.Outer; on: Bottom; kind: Fillet; radius: 3mm } }") },+ { "polygon-rim-fillet", "fixtures/Regression/EdgeFinishRobustness/polygon-rim-fillet.firmament" },+ };++ [Theory]+ [MemberData(nameof(Admitted))]+ public void RemovingTheStrips_ReturnsThePartWithoutTheFinish(string name, string sourceOrPath)+ {+ var source = sourceOrPath.StartsWith("fixtures/", StringComparison.Ordinal) ? File.ReadAllText(Path.Combine(Root(), sourceOrPath)) : sourceOrPath;+ var finished = Import(source);+ var stripped = Regex.Replace(source, @"Modify Body \{\s*EdgeFinish[^{}]*\{[^{}]*\}\s*\}", "");+ Assert.DoesNotContain("EdgeFinish", stripped);+ var plain = Import(Regex.Replace(source, @"Modify Body \{\s*EdgeFinish[^{}]*\{[^{}]*\}\s*\}", ""));++ var probe = BlendRegionProbe.Run(name, finished);+ var strips = probe.Regions.SelectMany(r => r.Faces).Select(f => new FaceId(f)).ToHashSet();+ Assert.NotEmpty(strips);+ var removed = BlendNetworkRemoval.Remove(finished, strips, Anchors(probe));+ Assert.True(removed.Body is not null, removed.Refusal);+ output.WriteLine($"{name}: removed {strips.Count} faces, {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(plain.Topology.Vertices.Count(), body.Topology.Vertices.Count());+ Assert.Equal(Points(plain), Points(body));++ Assert.True(BrepMassProperties.TryEvaluateExactVolume(plain, out var expected));+ Assert.True(BrepMassProperties.TryEvaluateExactVolume(body, out var actual), actual?.Status.ToString());+ Assert.Equal(expected.AbsoluteVolume, actual.AbsoluteVolume, 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-")]+ public void CurvedNeighbours_Refuse_WithAReason(string path, string code)+ {+ var finished = Import(File.ReadAllText(Path.Combine(Root(), path)));+ var probe = BlendRegionProbe.Run(path, finished);+ var removed = BlendNetworkRemoval.Remove(finished, probe.Regions.SelectMany(r => r.Faces).Select(f => new FaceId(f)).ToHashSet(), Anchors(probe));+ Assert.Null(removed.Body);+ Assert.StartsWith(code, removed.Refusal);+ output.WriteLine(removed.Refusal);+ }++ internal static Dictionary<FaceId, FaceId[]> Anchors(BlendRegionProbe.Report probe) => probe.Regions+ .SelectMany(r => r.Faces.Zip(r.FaceAnchors)).ToDictionary(p => new FaceId(p.First), p => p.Second.Select(a => new FaceId(a)).ToArray());++ private static BrepBody Import(string source)+ {+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var body = Step242Importer.ImportBody(built.Value.StepText);+ Assert.True(body.IsSuccess);+ return body.Value;+ }++ private static string[] Points(BrepBody body) => body.Topology.Vertices+ .Select(v => { body.TryGetVertexPoint(v.Id, out var p); return $"{Math.Round(p.X, 6) + 0.0:F6},{Math.Round(p.Y, 6) + 0.0:F6},{Math.Round(p.Z, 6) + 0.0:F6}"; })+ .Order(StringComparer.Ordinal).ToArray();+}++/// <summary>E1 reach over imported parts, one region at a time. AETHERIS_EXPERIMENTS=1.</summary>+public sealed class BlendNetworkRemovalReach+{+ [Fact]+ public void E1_Reach()+ {+ if (Environment.GetEnvironmentVariable("AETHERIS_EXPERIMENTS") != "1") return;+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ var root = directory!.FullName;+ var lines = new List<string>();+ var total = new Dictionary<string, int>();+ var wroteSample = new HashSet<string>();+ foreach (var path in Directory.GetFiles(Path.Combine(root, "testdata/step242/nist"), "*.stp", SearchOption.AllDirectories).Order()+ .Concat(Directory.GetFiles(Path.Combine(root, "testdata/step242/community"), "*.step", SearchOption.AllDirectories)))+ {+ var import = Step242Importer.ImportBody(File.ReadAllText(path));+ if (!import.IsSuccess || path.Contains("-tg")) continue;+ var body = import.Value;+ BrepMassProperties.TryEvaluateExactVolume(body, out var before);+ var probe = BlendRegionProbe.Run(Path.GetFileName(path), body);+ 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));+ if (removed.Body is null) { verdict = "refused:" + removed.Refusal!.Split(':')[0]; lines.Add($" {Path.GetFileNameWithoutExtension(path)} R{region.Id}: {removed.Refusal}"); }+ else+ {+ var valid = TopologyGraphValidator.Validate(removed.Body.Topology).IsSuccess+ && BrepBindingValidator.Validate(removed.Body, requireAllEdgeAndFaceBindings: true).IsSuccess;+ var step = valid ? Step242Exporter.ExportBody(removed.Body) : null;+ var back = step is { IsSuccess: true } ? Step242Importer.ImportBody(step.Value) : null;+ // 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+ : BrepMassProperties.Evaluate(removed.Body).AbsoluteVolume - BrepMassProperties.Evaluate(body).AbsoluteVolume;+ // 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);+ 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"+ : !(Math.Abs(grew) > 1e-9 && Math.Abs(grew) <= stripArea * 5) ? $"removed-volume-implausible(d={grew:G4},bound={stripArea * 5:G4},faces={string.Join(' ', region.Faces)})" : grew > 0 ? "removed-ok(convex)" : "removed-ok(concave)";+ }+ }+ outcome[verdict] = outcome.GetValueOrDefault(verdict) + region.Faces.Length;+ total[verdict] = total.GetValueOrDefault(verdict) + region.Faces.Length;+ }+ lines.Add($"{Path.GetFileNameWithoutExtension(path),-32} " + string.Join(", ", outcome.OrderByDescending(p => p.Value).Select(p => $"{p.Key}={p.Value}")));+ }+ lines.Add("TOTAL (faces) " + string.Join(", ", total.OrderByDescending(p => p.Value).Select(p => $"{p.Key}={p.Value}")));+ Directory.CreateDirectory(Path.Combine(root, "artifacts/local/blend-probe"));+ File.WriteAllLines(Path.Combine(root, "artifacts/local/blend-probe/e1-reach.txt"), lines);+ }++ private static bool WriteSample(string root, string name, int region, BrepBody before, BrepBody after)+ {+ // Before/after probe reports (with meshes) for review; never changes the verdict.+ foreach (var (tag, b) in new[] { ("before", before), ("after", after) })+ {+ var report = BlendRegionProbe.Run($"e1-{name}-R{region}-{tag}", b);+ File.WriteAllText(Path.Combine(root, "artifacts/local/blend-probe", report.Name + ".json"), System.Text.Json.JsonSerializer.Serialize(new+ {+ report.Name, report.Faces, report.Secondaries, report.FaceReports, report.Regions,+ Mesh = report.Mesh.ToDictionary(p => p.Key.ToString(), p => new { positions = p.Value.Positions, indices = p.Value.Indices }),+ }));+ }+ return false;+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendRegionProbe.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendRegionProbe.csindex 919961f2..c6026043 100644--- a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendRegionProbe.cs+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendRegionProbe.cs@@ -24,7 +24,7 @@ internal static class BlendRegionProbeint TangentEdges, int SharpEdges, int InnerLoops, bool ConcaveRound);internal sealed record RegionReport(int Id, string Shape, int[] Faces, string[] FaceKinds, int[] TangentPrimaries,- string[] TangentPrimaryKinds, int[] SharpNeighbours, string[] Blockers, int[] FaceBridges, string?[] FaceBlockers);+ string[] TangentPrimaryKinds, int[] SharpNeighbours, string[] Blockers, int[] FaceBridges, string?[] FaceBlockers, int[][] FaceAnchors);internal sealed record Report(string Name, int Faces, int Secondaries, FaceReport[] FaceReports, RegionReport[] Regions,Dictionary<int, (float[] Positions, int[] Indices)> Mesh);@@ -152,12 +152,16 @@ internal static class BlendRegionProbevar anchors = isChamfer ? sharp.Length : tangentPrimaries.Length;var shape = isChamfer ? "chamfer" : anchors switch { 2 => "chain", 3 => "corner", < 2 => "underanchored", _ => "complex" };// Per member: distinct primaries it is tangent to (2 = strip, 3 = corner, 0-1 = blend meeting blends).- var bridges = members.OrderBy(f => f.Value).Select(f => faceEdges[f].Where(e => e.Tangent)- .Select(e => e.Faces[0] == f ? e.Faces[1] : e.Faces[0]).Where(n => reports[n].Role == "primary").Distinct().Count()).ToArray();+ // Anchors: the primaries a blend face actually spans. A fillet's are its tangent neighbours;+ // a chamfer's are the neighbours it leans 20-70° against (its end caps meet it near 90°).+ var faceAnchors = members.OrderBy(f => f.Value).Select(f => faceEdges[f]+ .Where(e => reports[f].Reason == "chamfer-strip" ? e.MaxAngleDegrees is > 20 and < 70 : e.Tangent)+ .Select(e => e.Faces[0] == f ? e.Faces[1] : e.Faces[0]).Where(n => reports[n].Role == "primary").Distinct().Select(n => n.Value).Order().ToArray()).ToArray();+ var bridges = faceAnchors.Select(a => a.Length).ToArray();regions.Add(new(regions.Count + 1, shape, members.Select(f => f.Value).Order().ToArray(),members.OrderBy(f => f.Value).Select(f => reports[f].Kind).ToArray(),tangentPrimaries.Select(f => f.Value).ToArray(), tangentPrimaries.Select(f => reports[f].Kind).ToArray(),- sharp.Select(f => f.Value).ToArray(), blockers.Distinct().ToArray(), bridges, faceBlockers));+ sharp.Select(f => f.Value).ToArray(), blockers.Distinct().ToArray(), bridges, faceBlockers, faceAnchors));}var mesh = patches.ToDictionary(p => p.Key.Value, p =>diff --git a/docs/development/reports/2026-11/BLEND-CLEANUP-E1-STRIP-REMOVAL.md b/docs/development/reports/2026-11/BLEND-CLEANUP-E1-STRIP-REMOVAL.mdnew file mode 100644index 00000000..1deb5c09--- /dev/null+++ b/docs/development/reports/2026-11/BLEND-CLEANUP-E1-STRIP-REMOVAL.md@@ -0,0 +1,63 @@+# Blend clean-up E1: strip-network removal between planes++**Goal.** Delete blend strips classified by E0 and rebuild the sharp geometry from the+extended neighbouring planes, verified against parts authored without the finish.++**Code.** `Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemoval.cs` (experimental),+tests in `BlendNetworkRemovalTests.cs`; reach run `BlendNetworkRemovalReach` with+`AETHERIS_EXPERIMENTS=1`, output `artifacts/local/blend-probe/e1-reach.txt`.++## Method++- Each strip spans exactly two **anchors** from classification: its tangent neighbours+ (fillet) or the neighbours it leans 20–70° against (chamfer). A first version guessed+ anchors by longest shared boundary and picked a thin part's parallel top and bottom faces+ instead of the walls a vertical fillet blends.+- Vertices joined by a strip's transverse edges (end arcs, miters) collapse into one corner,+ placed where the planes around them meet (checked to 1e-6 mm; two planes give their line's+ point nearest the original vertex).+- Each strip becomes one straight edge along its anchors' intersection; neighbouring loops+ are rewired, kept straight edges re-trimmed to the moved corners, pcurves rebuilt.+- Anything else refuses with a code: non-planar neighbour, corner patch, seam edge, planes+ not meeting, loop collapsing, pcurve rebuild failing.++## Results++Authored ground truth (finish removed by surgery vs part authored without it): rectangle+top fillet, top chamfer, bottom fillet, angled polygon rim fillet. Face, edge and vertex+counts equal; every vertex within 1e-6 mm; exact volume equal to 6 decimals; same after+export and reimport. D-profile (cylindrical neighbour) and chimera (corner joiner) refuse.++Imported parts (17 NIST + SO-101, 1,201 classified blend faces), one region at a time:++| Outcome | Faces |+|---|---|+| removed, valid, reimports, volume change plausible | 20 (12 concave, 8 convex) |+| region contains corner joiners (E3) | 599 |+| non-planar neighbour (E2) | 285 |+| blocked: B-spline neighbour | 123 |+| blocked: hole crosses blend | 85 |+| pcurve rebuild failed on a curved neighbour's loop | 43 |+| strip spans other than two anchors | 27 |+| a neighbour loop collapses | 16 |+| corner planes not concurrent | 3 |++Removals land on CTC-03, FTC-09 and STC-09. Volume is exact where available, otherwise the+tessellated evaluation; a concave blend's removal lowers volume, a convex one raises it.++## Findings++1. **Strip surgery is sound where it is admitted.** Exact on authored parts, valid on the+ NIST regions it touches.+2. **Real parts are corners and curved neighbours.** Half the blend faces sit in regions+ with joiners and a quarter border cylinders, cones or tori. E1 alone reaches 2% of+ imported blend faces; E2 and E3 decide usefulness.+3. **Anchors must come from classification, not size.** Shared-boundary length misled on+ thin parts; tangency (fillet) and lean angle (chamfer) do not.++## Next++- E2: extend non-planar neighbours (plane–cylinder, coaxial cylinders, plane–cone); new+ edges become circles, lines or conics; rebuild pcurves on curved faces (the 43 failures).+- E3: corner joiners: delete them with their strips; corners from three neighbours.+- Investigate the 16 collapsing loops (a neighbour face made only of blend-adjacent edges).