Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add deterministic CIR-T4 contour stitching chains

Yuechen Li48b23e288580
diff --git a/Aetheris.Kernel.Firmament.Tests/SurfaceTrimContourStitcherTests.cs b/Aetheris.Kernel.Firmament.Tests/SurfaceTrimContourStitcherTests.cs
new file mode 100644
index 00000000..3533bb3c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/SurfaceTrimContourStitcherTests.cs
@@ -0,0 +1,83 @@
+using Aetheris.Kernel.Core.Cir;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Execution;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class SurfaceTrimContourStitcherTests
+{
+ [Fact]
+ public void ContourStitch_BoxFaceVsCylinder_ProducesClosedLoop()
+ {
+ var (field, grid) = CreateGrid(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirCylinderNode(2, 20)), 65);
+ var extraction = RestrictedFieldMarchingSquaresExtractor.Extract(grid, field.Parameterization);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ Assert.True(stitched.Chains.Any(c => c.Status == SurfaceTrimContourChainStatus.ClosedLoop || c.Status == SurfaceTrimContourChainStatus.BoundaryTouching));
+ Assert.False(stitched.AnalyticSnapImplemented);
+ Assert.False(stitched.BRepTopologyImplemented);
+ Assert.False(stitched.ExactExportAvailable);
+ }
+
+ [Fact]
+ public void ContourStitch_BoxFaceVsSphere_ProducesClosedLoop()
+ {
+ var (field, grid) = CreateGrid(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(6)), 65);
+ var extraction = RestrictedFieldMarchingSquaresExtractor.Extract(grid, field.Parameterization);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ Assert.Contains(stitched.Chains, c => c.Status == SurfaceTrimContourChainStatus.ClosedLoop || c.Status == SurfaceTrimContourChainStatus.BoundaryTouching);
+ }
+
+ [Fact]
+ public void ContourStitch_BoxFaceVsTorus_StitchesOrReportsPrecisely()
+ {
+ var (field, grid) = CreateGrid(new CirSubtractNode(new CirBoxNode(12, 12, 12), new CirTorusNode(4, 1)), 65);
+ var extraction = RestrictedFieldMarchingSquaresExtractor.Extract(grid, field.Parameterization);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ if (extraction.SegmentCount == 0) Assert.Contains("contour-stitching-empty-input", stitched.Diagnostics);
+ else Assert.True(stitched.Chains.Count > 0);
+ }
+
+ [Fact]
+ public void ContourStitch_OpenBoundaryChain_ClassifiedBoundaryTouching()
+ {
+ var seg = new SurfaceTrimContourSegment2D(0, 0, new(0d, 0.25d), new(0.4d, 0.4d), RestrictedFieldCellClassification.Mixed, []);
+ var extraction = new SurfaceTrimContourExtractionResult(true, RestrictedFieldContourExtractionMethod.MarchingSquares, 1, [seg], []);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ Assert.Equal(SurfaceTrimContourChainStatus.BoundaryTouching, stitched.Chains.Single().Status);
+ }
+
+ [Fact]
+ public void ContourStitch_AmbiguousBranch_Diagnosed()
+ {
+ var c = new SurfaceTrimContourPoint2D(0.5, 0.5);
+ var segs = new[]
+ {
+ new SurfaceTrimContourSegment2D(0,0,c,new(0.6,0.5),RestrictedFieldCellClassification.Mixed,[]),
+ new SurfaceTrimContourSegment2D(0,1,c,new(0.5,0.6),RestrictedFieldCellClassification.Mixed,[]),
+ new SurfaceTrimContourSegment2D(1,0,c,new(0.4,0.5),RestrictedFieldCellClassification.Mixed,[]),
+ };
+ var extraction = new SurfaceTrimContourExtractionResult(true, RestrictedFieldContourExtractionMethod.MarchingSquares, segs.Length, segs, []);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ Assert.Equal(SurfaceTrimContourChainStatus.Ambiguous, stitched.Chains.Single().Status);
+ Assert.Contains(stitched.Diagnostics, d => d.StartsWith("contour-stitching-ambiguous-cluster-count:", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ContourStitch_DeterministicOrdering()
+ {
+ var (field, grid) = CreateGrid(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(6)), 33);
+ var extraction = RestrictedFieldMarchingSquaresExtractor.Extract(grid, field.Parameterization);
+ var a = SurfaceTrimContourStitcher.Stitch(extraction);
+ var b = SurfaceTrimContourStitcher.Stitch(extraction);
+ Assert.Equal(a.Chains.Count, b.Chains.Count);
+ Assert.Equal(a.Chains.Select(c => (c.Status, c.OrderingKey, c.Points.Count)), b.Chains.Select(c => (c.Status, c.OrderingKey, c.Points.Count)));
+ }
+
+ private static (SurfaceRestrictedField field, RestrictedFieldSampleGrid grid) CreateGrid(CirSubtractNode root, int resolution)
+ {
+ var source = Assert.Single(SourceSurfaceExtractor.Extract(root.Left).Descriptors.Where(d => d.ParameterPayloadReference == "top"));
+ var field = SurfaceRestrictedFieldFactory.ForSubtractSource(root, source, SubtractOperandSide.Left);
+ var grid = RestrictedFieldGridSampler.Sample(field, new RestrictedFieldGridOptions(resolution, resolution));
+ return (field, grid);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Execution/SurfaceTrimContourStitcher.cs b/Aetheris.Kernel.Firmament/Execution/SurfaceTrimContourStitcher.cs
new file mode 100644
index 00000000..012bd62c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Execution/SurfaceTrimContourStitcher.cs
@@ -0,0 +1,302 @@
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Numerics;
+
+namespace Aetheris.Kernel.Firmament.Execution;
+
+internal enum SurfaceTrimContourChainStatus
+{
+ ClosedLoop,
+ OpenChain,
+ BoundaryTouching,
+ Ambiguous,
+ Degenerate,
+ Empty,
+}
+
+internal sealed record SurfaceTrimContourChainPoint2D(
+ double U,
+ double V,
+ int SourceSegmentIndex,
+ string SourceEndpoint,
+ Point3D? Point3D = null);
+
+internal sealed record SurfaceTrimContourChain2D(
+ int ChainId,
+ SurfaceTrimContourChainStatus Status,
+ IReadOnlyList<SurfaceTrimContourChainPoint2D> Points,
+ IReadOnlyList<int> SourceSegmentIndices,
+ bool Closed,
+ bool BoundaryTouching,
+ IReadOnlyList<string> Diagnostics,
+ string OrderingKey);
+
+internal sealed record SurfaceTrimContourStitchResult(
+ bool Success,
+ IReadOnlyList<SurfaceTrimContourChain2D> Chains,
+ int ClosedLoopCount,
+ int OpenChainCount,
+ int BoundaryTouchingCount,
+ int AmbiguousCount,
+ int DegenerateCount,
+ IReadOnlyList<string> Diagnostics,
+ bool AnalyticSnapImplemented = false,
+ bool BRepTopologyImplemented = false,
+ bool ExactExportAvailable = false);
+
+internal static class SurfaceTrimContourStitcher
+{
+ internal static SurfaceTrimContourStitchResult Stitch(SurfaceTrimContourExtractionResult extraction, ToleranceContext? tolerance = null)
+ {
+ ArgumentNullException.ThrowIfNull(extraction);
+ var tol = tolerance ?? ToleranceContext.Default;
+ var diagnostics = new List<string>
+ {
+ "contour-stitching-started",
+ $"contour-stitching-input-segment-count:{extraction.Segments.Count}",
+ };
+
+ if (extraction.Segments.Count == 0)
+ {
+ diagnostics.Add("contour-stitching-empty-input");
+ diagnostics.Add("contour-analytic-snap-not-implemented");
+ diagnostics.Add("contour-brep-topology-not-implemented");
+ diagnostics.Add("contour-exact-export-not-available");
+ return new SurfaceTrimContourStitchResult(true, [], 0, 0, 0, 0, 0, diagnostics);
+ }
+
+ var endpoints = new List<(int segmentIndex, string endpoint, SurfaceTrimContourPoint2D point, SurfaceTrimContourPoint3D? point3D)>();
+ for (var i = 0; i < extraction.Segments.Count; i++)
+ {
+ endpoints.Add((i, "A", extraction.Segments[i].A, extraction.Segments[i].A3D));
+ endpoints.Add((i, "B", extraction.Segments[i].B, extraction.Segments[i].B3D));
+ }
+
+ var orderedEndpoints = endpoints
+ .OrderBy(e => e.point.V)
+ .ThenBy(e => e.point.U)
+ .ThenBy(e => e.segmentIndex)
+ .ThenBy(e => e.endpoint, StringComparer.Ordinal)
+ .ToList();
+
+ var clusterCenters = new List<(double u, double v)>();
+ var endpointToCluster = new Dictionary<(int segmentIndex, string endpoint), int>();
+
+ foreach (var endpoint in orderedEndpoints)
+ {
+ var assigned = -1;
+ for (var i = 0; i < clusterCenters.Count; i++)
+ {
+ var c = clusterCenters[i];
+ var du = endpoint.point.U - c.u;
+ var dv = endpoint.point.V - c.v;
+ if ((du * du) + (dv * dv) <= (tol.Linear * tol.Linear))
+ {
+ assigned = i;
+ break;
+ }
+ }
+
+ if (assigned < 0)
+ {
+ assigned = clusterCenters.Count;
+ clusterCenters.Add((endpoint.point.U, endpoint.point.V));
+ }
+
+ endpointToCluster[(endpoint.segmentIndex, endpoint.endpoint)] = assigned;
+ }
+
+ var clusterToEdges = new Dictionary<int, List<int>>();
+ for (var i = 0; i < extraction.Segments.Count; i++)
+ {
+ var a = endpointToCluster[(i, "A")];
+ var b = endpointToCluster[(i, "B")];
+ if (!clusterToEdges.ContainsKey(a)) clusterToEdges[a] = [];
+ if (!clusterToEdges.ContainsKey(b)) clusterToEdges[b] = [];
+ clusterToEdges[a].Add(i);
+ clusterToEdges[b].Add(i);
+ }
+
+ var ambiguousClusters = clusterToEdges.Where(kv => kv.Value.Count > 2).Select(kv => kv.Key).OrderBy(i => i).ToArray();
+ diagnostics.Add($"contour-stitching-endpoint-cluster-count:{clusterCenters.Count}");
+ diagnostics.Add($"contour-stitching-ambiguous-cluster-count:{ambiguousClusters.Length}");
+
+ var visited = new bool[extraction.Segments.Count];
+ var chains = new List<SurfaceTrimContourChain2D>();
+ var chainId = 0;
+
+ foreach (var segIndex in Enumerable.Range(0, extraction.Segments.Count))
+ {
+ if (visited[segIndex])
+ {
+ continue;
+ }
+
+ var component = CollectComponent(segIndex, endpointToCluster, clusterToEdges, extraction.Segments.Count, visited);
+ var componentEdges = component.OrderBy(i => i).ToList();
+ var componentClusters = componentEdges
+ .SelectMany(i => new[] { endpointToCluster[(i, "A")], endpointToCluster[(i, "B")] })
+ .Distinct()
+ .OrderBy(i => i)
+ .ToList();
+
+ var hasAmbiguous = componentClusters.Any(c => clusterToEdges[c].Count > 2);
+ var oddDegree = componentClusters.Where(c => clusterToEdges[c].Count % 2 != 0).ToList();
+ var endpointsOpen = componentClusters.Where(c => clusterToEdges[c].Count == 1).ToList();
+
+ var diagnosticsLocal = new List<string>();
+ if (hasAmbiguous) diagnosticsLocal.Add("ambiguous-branch-node-degree-gt2");
+
+ var orderedPoints = BuildOrderedPoints(componentEdges, endpointToCluster, clusterToEdges, extraction.Segments);
+ var totalLen = ChainLength(orderedPoints);
+ var start = orderedPoints.FirstOrDefault();
+ var end = orderedPoints.LastOrDefault();
+ var closedByDistance = orderedPoints.Count > 2 && start is not null && end is not null &&
+ DistanceSquared(start.U, start.V, end.U, end.V) <= (tol.Linear * tol.Linear);
+
+ var boundaryTouching = endpointsOpen.Any(c => IsBoundary(clusterCenters[c], tol));
+ var status = SurfaceTrimContourChainStatus.OpenChain;
+ if (orderedPoints.Count == 0)
+ {
+ status = SurfaceTrimContourChainStatus.Empty;
+ }
+ else if (totalLen <= tol.Linear || componentEdges.Count == 0 || orderedPoints.Select(p => (p.U, p.V)).Distinct().Count() < 2)
+ {
+ status = SurfaceTrimContourChainStatus.Degenerate;
+ }
+ else if (hasAmbiguous || oddDegree.Count > 0 && oddDegree.Count != 2)
+ {
+ status = SurfaceTrimContourChainStatus.Ambiguous;
+ }
+ else if (endpointsOpen.Count == 0 || closedByDistance)
+ {
+ status = SurfaceTrimContourChainStatus.ClosedLoop;
+ }
+ else if (boundaryTouching)
+ {
+ status = SurfaceTrimContourChainStatus.BoundaryTouching;
+ }
+
+ chains.Add(new SurfaceTrimContourChain2D(
+ chainId++,
+ status,
+ orderedPoints,
+ componentEdges,
+ status == SurfaceTrimContourChainStatus.ClosedLoop,
+ boundaryTouching,
+ diagnosticsLocal,
+ $"{orderedPoints.FirstOrDefault()?.V:R}:{orderedPoints.FirstOrDefault()?.U:R}:{componentEdges.FirstOrDefault()}"));
+ }
+
+ chains = chains.OrderBy(c => c.OrderingKey, StringComparer.Ordinal).ThenBy(c => c.ChainId).ToList();
+ for (var i = 0; i < chains.Count; i++) chains[i] = chains[i] with { ChainId = i };
+
+ var closed = chains.Count(c => c.Status == SurfaceTrimContourChainStatus.ClosedLoop);
+ var open = chains.Count(c => c.Status == SurfaceTrimContourChainStatus.OpenChain);
+ var boundary = chains.Count(c => c.Status == SurfaceTrimContourChainStatus.BoundaryTouching);
+ var ambiguous = chains.Count(c => c.Status == SurfaceTrimContourChainStatus.Ambiguous);
+ var degenerate = chains.Count(c => c.Status == SurfaceTrimContourChainStatus.Degenerate);
+
+ diagnostics.Add($"contour-stitching-closed-loop-count:{closed}");
+ diagnostics.Add($"contour-stitching-open-chain-count:{open}");
+ diagnostics.Add($"contour-stitching-boundary-touching-count:{boundary}");
+ diagnostics.Add($"contour-stitching-ambiguous-count:{ambiguous}");
+ diagnostics.Add($"contour-stitching-degenerate-count:{degenerate}");
+ diagnostics.Add("contour-analytic-snap-not-implemented");
+ diagnostics.Add("contour-brep-topology-not-implemented");
+ diagnostics.Add("contour-exact-export-not-available");
+
+ return new SurfaceTrimContourStitchResult(true, chains, closed, open, boundary, ambiguous, degenerate, diagnostics);
+ }
+
+ private static List<int> CollectComponent(int seed, Dictionary<(int segmentIndex, string endpoint), int> endpointToCluster, Dictionary<int, List<int>> clusterToEdges, int segmentCount, bool[] visited)
+ {
+ var list = new List<int>();
+ var q = new Queue<int>();
+ q.Enqueue(seed);
+ visited[seed] = true;
+ while (q.Count > 0)
+ {
+ var s = q.Dequeue();
+ list.Add(s);
+ var a = endpointToCluster[(s, "A")];
+ var b = endpointToCluster[(s, "B")];
+ foreach (var n in clusterToEdges[a].Concat(clusterToEdges[b]).Distinct().OrderBy(i => i))
+ {
+ if (n >= 0 && n < segmentCount && !visited[n])
+ {
+ visited[n] = true;
+ q.Enqueue(n);
+ }
+ }
+ }
+
+ return list;
+ }
+
+ private static List<SurfaceTrimContourChainPoint2D> BuildOrderedPoints(List<int> componentEdges, Dictionary<(int segmentIndex, string endpoint), int> endpointToCluster, Dictionary<int, List<int>> clusterToEdges, IReadOnlyList<SurfaceTrimContourSegment2D> segments)
+ {
+ var ordered = new List<SurfaceTrimContourChainPoint2D>();
+ var unvisited = new HashSet<int>(componentEdges);
+ if (componentEdges.Count == 0) return ordered;
+
+ var startEdge = componentEdges[0];
+ var ends = componentEdges.SelectMany(e => new[] { endpointToCluster[(e, "A")], endpointToCluster[(e, "B")] });
+ var startNode = ends.GroupBy(n => n).Where(g => clusterToEdges[g.Key].Count == 1).Select(g => g.Key).OrderBy(i => i).FirstOrDefault();
+ var currentNode = startNode;
+ var currentEdge = startEdge;
+
+ while (unvisited.Count > 0)
+ {
+ if (!unvisited.Contains(currentEdge))
+ {
+ currentEdge = unvisited.OrderBy(i => i).First();
+ }
+
+ var seg = segments[currentEdge];
+ var aNode = endpointToCluster[(currentEdge, "A")];
+ var bNode = endpointToCluster[(currentEdge, "B")];
+ var forward = currentNode == aNode || (currentNode != bNode && aNode <= bNode);
+ if (forward)
+ {
+ ordered.Add(new SurfaceTrimContourChainPoint2D(seg.A.U, seg.A.V, currentEdge, "A", seg.A3D?.Point));
+ ordered.Add(new SurfaceTrimContourChainPoint2D(seg.B.U, seg.B.V, currentEdge, "B", seg.B3D?.Point));
+ currentNode = bNode;
+ }
+ else
+ {
+ ordered.Add(new SurfaceTrimContourChainPoint2D(seg.B.U, seg.B.V, currentEdge, "B", seg.B3D?.Point));
+ ordered.Add(new SurfaceTrimContourChainPoint2D(seg.A.U, seg.A.V, currentEdge, "A", seg.A3D?.Point));
+ currentNode = aNode;
+ }
+
+ unvisited.Remove(currentEdge);
+ var next = clusterToEdges[currentNode].Where(e => unvisited.Contains(e)).OrderBy(i => i).FirstOrDefault(-1);
+ if (next < 0 && unvisited.Count > 0) next = unvisited.OrderBy(i => i).First();
+ if (next < 0) break;
+ currentEdge = next;
+ }
+
+ return ordered;
+ }
+
+ private static bool IsBoundary((double u, double v) p, ToleranceContext tol)
+ => double.Abs(p.u - 0d) <= tol.Linear || double.Abs(p.u - 1d) <= tol.Linear || double.Abs(p.v - 0d) <= tol.Linear || double.Abs(p.v - 1d) <= tol.Linear;
+
+ private static double ChainLength(IReadOnlyList<SurfaceTrimContourChainPoint2D> points)
+ {
+ var len = 0d;
+ for (var i = 1; i < points.Count; i++)
+ {
+ len += double.Sqrt(DistanceSquared(points[i - 1].U, points[i - 1].V, points[i].U, points[i].V));
+ }
+
+ return len;
+ }
+
+ private static double DistanceSquared(double ua, double va, double ub, double vb)
+ {
+ var du = ua - ub;
+ var dv = va - vb;
+ return (du * du) + (dv * dv);
+ }
+}
diff --git a/docs/cir-t4-contour-stitching.md b/docs/cir-t4-contour-stitching.md
new file mode 100644
index 00000000..8ea2e390
--- /dev/null
+++ b/docs/cir-t4-contour-stitching.md
@@ -0,0 +1,61 @@
+# CIR-T4 — deterministic contour stitching into chains/loops
+
+## Purpose
+
+CIR-T4 consumes CIR-T3 marching-squares contour segments and deterministically stitches them into UV contour chains with conservative closure/ambiguity classification.
+
+## Input and non-goals
+
+Input is only `SurfaceTrimContourExtractionResult` from T3; no resampling and no rerun of marching squares.
+
+Still deferred:
+- analytic snap / exact curve recognition,
+- BRep topology emission,
+- STEP export changes,
+- seam-wrapped parameter domains.
+
+## Endpoint clustering policy
+
+- Endpoints are processed in stable order (`V`, then `U`, then source segment/index endpoint label).
+- Endpoints within tolerance are clustered into one node.
+- Tolerance policy: use provided `ToleranceContext`; otherwise `ToleranceContext.Default.Linear` in UV-space.
+- Nodes with degree >2 are diagnosed as ambiguous branch nodes.
+
+## Graph traversal policy
+
+- Node = endpoint cluster; edge = contour segment.
+- Connected components are collected deterministically from ascending segment index.
+- Chain point ordering is deterministic and stable for repeated runs on identical input.
+- Ambiguous branching is not force-resolved into “clean loops”; the chain is marked ambiguous.
+
+## Classification policy
+
+- `ClosedLoop`: no open endpoints (or start/end re-close within tolerance), no branch ambiguity.
+- `BoundaryTouching`: open chain and at least one open endpoint lies on domain boundary (`u=0|1` or `v=0|1` within tolerance).
+- `OpenChain`: open chain not touching domain boundary.
+- `Ambiguous`: degree>2 branch or odd-degree topology inconsistent with clean chain semantics.
+- `Degenerate`: insufficient distinct points or near-zero length.
+- `Empty`: no chain points (empty input path).
+
+Classification is intentionally conservative.
+
+## Diagnostics
+
+Stitching diagnostics include:
+- stitching start/input segment count,
+- endpoint cluster count,
+- ambiguous cluster count,
+- closed/open/boundary/ambiguous/degenerate counts,
+- explicit deferred flags for analytic snap, BRep topology, exact export.
+
+## Numerical status
+
+This remains numerical UV polyline stitching only; it does not claim exact analytic contour identity.
+
+## SEM-A0 status
+
+CIR-T4 adds no generated topology naming and no selector/provenance expansion; SEM-A0 guardrails remain preserved.
+
+## Next (CIR-T5)
+
+Add bounded analytic snap candidates (circle/line/etc.) over stitched chains with explicit admissibility/rejection diagnostics while keeping topology/export behavior unchanged.