Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add bounded parametric patches and improve quad reconstruction
Yuechen Lif2d508a73e6a
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex 1addd3c1..b93e848c 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -1,6 +1,7 @@using System.Security.Cryptography;using System.Text;using System.Text.Json;+using System.Text.Json.Serialization;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Geometry.Curves;using Aetheris.Kernel.Core.Geometry.Surfaces;@@ -69,16 +70,39 @@ public sealed record ForeignTrimResolution(double RecognitionTolerance,string Provenance);-public enum SurfaceMeshSupportKind { Plane, Cylinder, Cone, Sphere, Torus }+public enum SurfaceMeshSupportKind { Plane, Cylinder, Cone, Sphere, Torus, BoundedParametricPatch }public enum SurfaceMeshCellKind { Quad, Triangle, BoundaryPolygon, Singular }public enum SurfaceMeshCellProvenance { Unclassified, FeatureBand, Bridge, CoarseRemainder, ResidualTransition }+/// <summary>+/// Domain-neutral evaluator for a bounded parametric support. Implementations adapt the+/// authored geometry owned by a higher layer; SurfaceMeshIR only consumes the first jet+/// needed for sampling and normal generation.+/// </summary>+public interface ISurfaceMeshBoundedPatch+{+ string StableId { get; }+ double MinimumU { get; }+ double MaximumU { get; }+ double MinimumV { get; }+ double MaximumV { get; }+ SurfaceMeshParametricJet Evaluate(double u, double v);+ bool TryProject(Point3D point, out double u, out double v);+}++public sealed record SurfaceMeshParametricJet(Point3D Point, Vector3D Du, Vector3D Dv)+{+ public bool TryNormal(out Vector3D normal) => Du.Cross(Dv).TryNormalize(out normal);+}+public sealed record SurfaceMeshSupport(SurfaceMeshSupportKind Kind,PlaneSurface? Plane = null,CylinderSurface? Cylinder = null,ConeSurface? Cone = null,SphereSurface? Sphere = null,- TorusSurface? Torus = null);+ TorusSurface? Torus = null,+ [property: JsonIgnore] ISurfaceMeshBoundedPatch? BoundedPatch = null,+ string? BoundedPatchStableId = null);public abstract record SurfaceMeshCell(SurfaceMeshCellKind Kind, IReadOnlyList<int> VertexIds, int RefinementLevel = 0, int? ParentCellId = null){@@ -107,7 +131,8 @@ public sealed record SurfacePatch(IReadOnlyList<SurfaceMeshTrimLoop>? TrimLoopData = null,string? ChartId = null,string? PlanarPlannerPath = null,- PlanarFeatureDecompositionPlan? PlanarFeaturePlan = null);+ PlanarFeatureDecompositionPlan? PlanarFeaturePlan = null,+ string? ResidualFieldId = null);public enum SurfaceMeshDownstreamIntent { Presentation, Manufacturing, Fea }diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.csindex e92447b7..74a7d752 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.cs@@ -40,7 +40,7 @@ public static class SurfaceMeshObjExporter{var point = vertexById[vertexId].Position;var uv = EvaluateUv(patch, point);- var normal = EvaluateNormal(patch, point);+ var normal = EvaluateNormal(patch, point, uv);var vt = Intern(textureCoordinates, textureIndex, uv.U, uv.V);var vn = Intern(normals, normalIndex, normal.X, normal.Y, normal.Z);corners.Add(new ObjCorner(positionIndex[vertexId], vt, vn));@@ -96,10 +96,11 @@ public static class SurfaceMeshObjExporterSurfaceMeshSupportKind.Cone when patch.Support.Cone is { } cone => ConeUv(cone, point),SurfaceMeshSupportKind.Sphere when patch.Support.Sphere is { } sphere => SphereUv(sphere, point),SurfaceMeshSupportKind.Torus when patch.Support.Torus is { } torus => TorusUv(torus, point),+ SurfaceMeshSupportKind.BoundedParametricPatch when patch.Support.BoundedPatch is { } bounded && bounded.TryProject(point, out var u, out var v) => (u, v),_ => throw new InvalidOperationException($"Patch {patch.FaceId.Value} has no parameterization."),};- private static Vector3D EvaluateNormal(SurfacePatch patch, Point3D point)+ private static Vector3D EvaluateNormal(SurfacePatch patch, Point3D point, (double U, double V) uv){Vector3D normal = patch.Support.Kind switch{@@ -108,6 +109,7 @@ public static class SurfaceMeshObjExporterSurfaceMeshSupportKind.Cone when patch.Support.Cone is { } cone => cone.Normal(ConeUv(cone, point).U).ToVector(),SurfaceMeshSupportKind.Sphere when patch.Support.Sphere is { } sphere => Direction3D.Create(point - sphere.Center).ToVector(),SurfaceMeshSupportKind.Torus when patch.Support.Torus is { } torus => torus.Normal(TorusUv(torus, point).U, TorusUv(torus, point).V).ToVector(),+ SurfaceMeshSupportKind.BoundedParametricPatch when patch.Support.BoundedPatch is { } bounded && bounded.Evaluate(uv.U, uv.V).TryNormal(out var evaluated) => evaluated,_ => throw new InvalidOperationException($"Patch {patch.FaceId.Value} has no exact normal evaluator."),};return patch.SameSense ? normal : -normal;diff --git a/Aetheris.Reconstruction.Tests/ReconstructionTests.cs b/Aetheris.Reconstruction.Tests/ReconstructionTests.csindex c28be8ad..269be91d 100644--- a/Aetheris.Reconstruction.Tests/ReconstructionTests.cs+++ b/Aetheris.Reconstruction.Tests/ReconstructionTests.cs@@ -1,6 +1,7 @@using System.Text;using Aetheris.Kernel.Core.Brep.Tessellation;using Aetheris.Kernel.Core.Math;+using Aetheris.Geometry;using Aetheris.Surfacing;using Xunit;@@ -177,11 +178,125 @@ end_headerAssert.All(atlas.Charts, chart => Assert.Equal(4, chart.OrderedSides.Count));}+ [Fact]+ public void Offset_field_moves_position_and_its_gradient_corrects_geometric_normal()+ {+ var patch = PlanePatch("base"); var values = new double[3, 3]; values[1, 1] = .2;+ var residual = new SurfaceResidualField("offset", patch.StableId, patch.Domain, new(values, patch.Domain), null,+ ResidualSeamPolicy.ZeroAtBoundary, Evidence("synthetic known displacement"));++ var sample = residual.Evaluate(patch, .5, .5);++ Assert.Equal(.2, sample.Point.Z, 12); Assert.True(sample.PositionWasDisplaced); Assert.False(sample.NormalCorrectionWasApplied);+ Assert.InRange((sample.GeometricNormal - new Vector3D(0, 0, 1)).Length, 0, 1e-10); // symmetric peak has zero center gradient+ Assert.NotEqual(new Vector3D(0, 0, 1), residual.Evaluate(patch, .25, .5).GeometricNormal);+ }++ [Fact]+ public void Normal_only_field_never_moves_geometry()+ {+ var patch = PlanePatch("normal-base"); var normals = new Vector3D[2, 2];+ for (var i = 0; i < 2; i++) for (var j = 0; j < 2; j++) normals[i, j] = new(0, .2, 1);+ var residual = new SurfaceResidualField("normal", patch.StableId, patch.Domain, null, new(normals, patch.Domain),+ ResidualSeamPolicy.SharedBoundarySamples, Evidence("synthetic normal-only detail"));++ var sample = residual.Evaluate(patch, .37, .61);++ Assert.Equal(patch.EvaluatePoint(.37, .61), sample.Point); Assert.False(sample.PositionWasDisplaced);+ Assert.Equal(new Vector3D(0, 0, 1), sample.GeometricNormal); Assert.NotEqual(sample.GeometricNormal, sample.InterpretedNormal);+ }++ [Fact]+ public void Residual_decomposition_keeps_tangential_error_explicit()+ {+ var patch = PlanePatch("decompose"); var normal = SurfaceResidualExtractor.Decompose(new(.5, .5, .1), new(0, 0, 1), patch);+ var tangential = SurfaceResidualExtractor.Decompose(new(1.1, .5, .1), new(0, 0, 1), patch);++ Assert.Equal(.1, normal.NormalComponent, 6); Assert.InRange(normal.TangentialMagnitude, 0, 1e-5); Assert.True(SurfaceResidualExtractor.IsScalarOffsetSuitable(normal));+ Assert.True(tangential.TangentialMagnitude > .09); Assert.False(SurfaceResidualExtractor.IsScalarOffsetSuitable(tangential));+ }++ [Fact]+ public void Quad_atlas_lowering_uses_native_bounded_patch_support_without_plane_proxy()+ {+ var mesh = Grid(3); var (field, _) = StructuredSurfaceRecovery.EstimateField(mesh); var atlas = QuadAtlasRecovery.Build(mesh, field);+ var canonical = QuadAtlasSurfaceMeshLowering.Lower(mesh, atlas);++ Assert.All(canonical.Document.Patches.Where(p => p.ChartId!.StartsWith("quad-")), p =>+ {+ Assert.Equal(SurfaceMeshSupportKind.BoundedParametricPatch, p.Support.Kind); Assert.NotNull(p.Support.BoundedPatch); Assert.Contains("no plane proxy", p.PlanarPlannerPath);+ });+ Assert.Equal(0, canonical.InternalCrackGroups); Assert.Equal("Pass", canonical.ValidationStatus);+ var obj = SurfaceMeshObjExporter.Export(canonical.Document); Assert.Equal(canonical.QuadCount, obj.QuadCount);+ }++ [Fact]+ public void Reconciled_zero_boundary_residuals_keep_neighboring_panels_crack_free()+ {+ var mesh = Grid(3); var (field, _) = StructuredSurfaceRecovery.EstimateField(mesh); var atlas = QuadAtlasRecovery.Build(mesh, field);+ var fields = atlas.Charts.ToDictionary(chart => chart.StableId, chart =>+ new SurfaceResidualField("residual-" + chart.StableId, chart.StrictPanel.AuthoredPatch.StableId, chart.StrictPanel.AuthoredPatch.Domain,+ new(new double[2, 2], chart.StrictPanel.AuthoredPatch.Domain), null, ResidualSeamPolicy.ZeroAtBoundary, Evidence("zero seam fixture")));++ var canonical = QuadAtlasSurfaceMeshLowering.Lower(mesh, atlas, fields);++ Assert.Equal(0, canonical.InternalCrackGroups); Assert.Equal("Pass", canonical.ValidationStatus);+ Assert.All(canonical.Document.Patches, patch => Assert.NotNull(patch.ResidualFieldId));+ }++ [Fact]+ public void Global_matching_finds_augmenting_reroute_that_local_greedy_pairing_misses()+ {+ var edges = new[] { new GlobalMatchingEdge(0, 1, 10, "greedy"), new(0, 2, 5, "left"), new(1, 3, 5, "right") };+ var result = GlobalQuadLayoutMatcher.Match(4, edges, new[] { 1, 0, -1, -1 });++ Assert.Equal(2, result.MatchedEdges); Assert.Equal(2, result.Mate[0]); Assert.Equal(3, result.Mate[1]); Assert.Equal(1, result.Augmentations);+ }++ [Fact]+ public void Smooth_tiny_quad_panels_coarsen_under_bounded_structural_merge()+ {+ var mesh = Grid(4); var (field, _) = StructuredSurfaceRecovery.EstimateField(mesh); var atlas = QuadAtlasRecovery.Build(mesh, field);+ var result = StructuralPanelCoarsener.Coarsen(mesh, atlas);++ Assert.True(result.Panels.Count < atlas.Charts.Count, $"merged={result.MergedPairCount} topo={result.RejectedTopology} feature={result.RejectedFeature} uv={result.RejectedParameterization} residual={result.RejectedResidual}"); Assert.True(result.MergedPairCount > 0); Assert.True(result.MergeRatio > 1);+ Assert.All(result.Panels, panel => Assert.True(PanelConcept.Validate(panel.Panel).Satisfies));+ }++ [Fact]+ public void Hard_crease_evidence_rejects_cross_feature_merge()+ {+ var mesh = CreasedGrid(); var (field, _) = StructuredSurfaceRecovery.EstimateField(mesh); var atlas = QuadAtlasRecovery.Build(mesh, field);+ var result = StructuralPanelCoarsener.Coarsen(mesh, atlas, new(MaximumFeatureAngleDegrees: 5));++ Assert.All(result.Panels.Where(panel => panel.SourceChartIds.Count > 1), panel => Assert.InRange(panel.NormalDiscontinuityDegrees, 0, 5));+ }++ [Fact]+ public void Cross_field_regularization_is_deterministic_and_preserves_detected_global_index()+ {+ var mesh = Grid(4); var (field, _) = StructuredSurfaceRecovery.EstimateField(mesh);+ var first = CrossFieldRegularizer.Regularize(mesh, field, 3); var second = CrossFieldRegularizer.Regularize(mesh, field, 3);++ Assert.True(first.Report.GlobalIndexPreserved); Assert.True(first.Report.OutputSingularities <= first.Report.InputSingularities);+ Assert.Equal(first.Report, second.Report); Assert.Equal(first.Field.Select(x => x.CrossDirection), second.Field.Select(x => x.CrossDirection));+ }++ private static ResidualFieldEvidence Evidence(string method) => new(PredicateEvidenceKind.Sampled, "fixture", method, 0, 0, 0, 0, 9);+ private static BoundedParametricPatch3 PlanePatch(string id) => BoundedParametricPatch3.Procedural(id,+ new(new(0, 1), new(0, 1)), (u, v) => new(new(u, v, 0), new(1, 0, 0), new(0, 1, 0), Direction3D.Create(new(0, 0, 1)), false), "fixture");+private static TriangleSurfaceMesh Square() => new([new(0, 0, 0), new(1, 0, 0), new(1, 1, 0), new(0, 1, 0)], [new(0, 1, 2), new(0, 2, 3)], null, "square", "fixture", new Dictionary<string, string>());private static TriangleSurfaceMesh Grid(int n){var p = new List<Point3D>(); for (var j = 0; j < n; j++) for (var i = 0; i < n; i++) p.Add(new(i / (double)(n - 1), j / (double)(n - 1), .02 * i * j)); var t = new List<Triangle>(); for (var j = 0; j < n - 1; j++) for (var i = 0; i < n - 1; i++) { var a = j * n + i; t.Add(new(a, a + 1, a + n + 1)); t.Add(new(a, a + n + 1, a + n)); } return new(p, t, null, "grid", "fixture", new Dictionary<string, string>());}+ private static TriangleSurfaceMesh CreasedGrid()+ {+ var p = new List<Point3D>(); for (var j = 0; j < 3; j++) for (var i = 0; i < 3; i++) p.Add(new(i, j, i < 2 ? 0 : 1));+ var t = new List<Triangle>(); for (var j = 0; j < 2; j++) for (var i = 0; i < 2; i++) { var a = j * 3 + i; t.Add(new(a, a + 1, a + 4)); t.Add(new(a, a + 4, a + 3)); }+ return new(p, t, null, "creased-grid", "fixture", new Dictionary<string, string>());+ }private static TriangleSurfaceMesh Ring(){diff --git a/Aetheris.Reconstruction/CrossFieldRegularization.cs b/Aetheris.Reconstruction/CrossFieldRegularization.csnew file mode 100644index 00000000..59973481--- /dev/null+++ b/Aetheris.Reconstruction/CrossFieldRegularization.cs@@ -0,0 +1,65 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Reconstruction;++public sealed record FieldRegularizationReport(+ int InputSingularities, int OutputSingularities, int CancelledNet,+ int RetainedFeatureFaces, int RetainedBoundaryFaces, int AcceptedIterations,+ double InputIndexSum, double OutputIndexSum, bool GlobalIndexPreserved,+ string Objective, string DeterministicPolicy);++/// <summary>+/// Bounded global relaxation of a four-fold tangent field. Boundary and high-curvature feature+/// samples are fixed. An iteration is admitted only when the detected global quarter-index sum+/// is preserved and singularity count does not increase.+/// </summary>+public static class CrossFieldRegularizer+{+ public static (IReadOnlyList<DifferentialSample> Field, FieldRegularizationReport Report) Regularize(+ TriangleSurfaceMesh mesh, IReadOnlyList<DifferentialSample> input, int maximumIterations = 8, double featureQuantile = .9)+ {+ ArgumentNullException.ThrowIfNull(mesh); ArgumentNullException.ThrowIfNull(input);+ if (input.Count != mesh.Triangles.Count) throw new ArgumentException("Field sample count must equal face count.", nameof(input));+ if (maximumIterations < 0 || maximumIterations > 100) throw new ArgumentOutOfRangeException(nameof(maximumIterations));+ if (!double.IsFinite(featureQuantile) || featureQuantile <= 0 || featureQuantile >= 1) throw new ArgumentOutOfRangeException(nameof(featureQuantile));+ var adjacency = Adjacency(mesh, out var boundaryFaces); var curvatures = input.Select(x => x.CurvatureProxy).Where(double.IsFinite).Order().ToArray();+ var threshold = curvatures.Length == 0 ? double.PositiveInfinity : curvatures[(int)Math.Clamp(Math.Ceiling(featureQuantile * curvatures.Length) - 1, 0, curvatures.Length - 1)];+ var featureFaces = input.Where(x => x.CurvatureProxy >= threshold && x.CurvatureProxy > 0).Select(x => x.TriangleIndex).ToHashSet();+ var current = input.ToArray(); var initial = QuadAtlasRecovery.DetectSingularitiesForRegularization(mesh, current); var currentSingularities = initial; var initialIndex = initial.Sum(x => x.QuarterIndex); var accepted = 0;+ for (var iteration = 0; iteration < maximumIterations; iteration++)+ {+ var next = (DifferentialSample[])current.Clone();+ for (var face = 0; face < next.Length; face++)+ {+ if (!current[face].DirectionKnown || boundaryFaces.Contains(face) || featureFaces.Contains(face)) continue;+ var normal = current[face].Normal; var anchor = current[face].CrossDirection; var sum = anchor * 2;+ foreach (var neighbor in adjacency[face]) if (current[neighbor].DirectionKnown)+ {+ var projected = current[neighbor].CrossDirection - normal * current[neighbor].CrossDirection.Dot(normal); if (!projected.TryNormalize(out projected)) continue;+ var perpendicular = normal.Cross(projected); if (!perpendicular.TryNormalize(out perpendicular)) continue;+ var representative = new[] { projected, -projected, perpendicular, -perpendicular }.OrderByDescending(x => x.Dot(anchor)).First(); sum += representative;+ }+ sum -= normal * sum.Dot(normal); if (sum.TryNormalize(out sum)) next[face] = next[face] with { CrossDirection = sum, EvidenceClass = "Heuristic: globally relaxed with fixed boundary/feature constraints" };+ }+ var singularities = QuadAtlasRecovery.DetectSingularitiesForRegularization(mesh, next); var index = singularities.Sum(x => x.QuarterIndex);+ if (Math.Abs(index - initialIndex) > .125 || singularities.Count > currentSingularities.Count) break;+ current = next; currentSingularities = singularities; accepted++;+ }+ var outputIndex = currentSingularities.Sum(x => x.QuarterIndex);+ return (current, new(initial.Count, currentSingularities.Count, initial.Count - currentSingularities.Count, featureFaces.Count, boundaryFaces.Count, accepted,+ initialIndex, outputIndex, Math.Abs(initialIndex - outputIndex) <= .125,+ "principal-direction alignment + neighbor smoothness + fixed feature/boundary evidence + singularity sparsity",+ "synchronous quarter-equivalent averaging; admit only non-increasing defect count with preserved global detected index"));+ }++ private static int[][] Adjacency(TriangleSurfaceMesh mesh, out HashSet<int> boundaryFaces)+ {+ var edges = new Dictionary<(int, int), List<int>>();+ for (var f = 0; f < mesh.Triangles.Count; f++) foreach (var edge in mesh.Triangles[f].DirectedEdges())+ { var key = edge.A < edge.B ? (edge.A, edge.B) : (edge.B, edge.A); if (!edges.TryGetValue(key, out var faces)) edges[key] = faces = []; faces.Add(f); }+ var lists = Enumerable.Range(0, mesh.Triangles.Count).Select(_ => new HashSet<int>()).ToArray(); boundaryFaces = [];+ foreach (var faces in edges.Values) if (faces.Count == 1) boundaryFaces.Add(faces[0]); else for (var i = 0; i < faces.Count; i++) for (var j = i + 1; j < faces.Count; j++) { lists[faces[i]].Add(faces[j]); lists[faces[j]].Add(faces[i]); }+ return lists.Select(x => x.Order().ToArray()).ToArray();+ }+}+diff --git a/Aetheris.Reconstruction/GlobalGraphMatching.cs b/Aetheris.Reconstruction/GlobalGraphMatching.csnew file mode 100644index 00000000..37f28075--- /dev/null+++ b/Aetheris.Reconstruction/GlobalGraphMatching.cs@@ -0,0 +1,65 @@+namespace Aetheris.Reconstruction;++public sealed record GlobalMatchingEdge(int A, int B, double Utility, string StableId);+public sealed record GlobalMatchingResult(IReadOnlyList<int> Mate, int MatchedEdges, int Augmentations, int BlossomContractions, string Algorithm);++/// <summary>Deterministic Edmonds blossom maximum-cardinality matching over a hard-admissible graph.</summary>+public static class GlobalQuadLayoutMatcher+{+ public static GlobalMatchingResult Match(int vertexCount, IReadOnlyList<GlobalMatchingEdge> edges, IReadOnlyList<int>? initialMate = null)+ {+ if (vertexCount < 0) throw new ArgumentOutOfRangeException(nameof(vertexCount)); ArgumentNullException.ThrowIfNull(edges);+ var graph = Enumerable.Range(0, vertexCount).Select(_ => new List<(int Vertex, double Utility, string Id)>()).ToArray();+ foreach (var edge in edges)+ {+ if (edge.A < 0 || edge.A >= vertexCount || edge.B < 0 || edge.B >= vertexCount || edge.A == edge.B || !double.IsFinite(edge.Utility)) throw new ArgumentException("Matching edges must be finite, distinct, and in range.", nameof(edges));+ graph[edge.A].Add((edge.B, edge.Utility, edge.StableId)); graph[edge.B].Add((edge.A, edge.Utility, edge.StableId));+ }+ foreach (var list in graph) list.Sort((x, y) => { var score = y.Utility.CompareTo(x.Utility); if (score != 0) return score; var id = string.CompareOrdinal(x.Id, y.Id); return id != 0 ? id : x.Vertex.CompareTo(y.Vertex); });+ var match = Enumerable.Repeat(-1, vertexCount).ToArray();+ if (initialMate is not null)+ {+ if (initialMate.Count != vertexCount) throw new ArgumentException("Initial mate vector length must equal vertex count.", nameof(initialMate));+ for (var i = 0; i < vertexCount; i++) if (initialMate[i] >= 0)+ {+ var mate = initialMate[i]; if (mate >= vertexCount || initialMate[mate] != i || !graph[i].Any(x => x.Vertex == mate)) throw new ArgumentException("Initial mates must be symmetric admissible edges.", nameof(initialMate));+ match[i] = mate;+ }+ }+ var parent = new int[vertexCount]; var basis = new int[vertexCount]; var used = new bool[vertexCount]; var blossom = new bool[vertexCount]; var queue = new Queue<int>();+ var augmentations = 0; var contractions = 0;+ int Lca(int a, int b) { var path = new bool[vertexCount]; while (true) { a = basis[a]; path[a] = true; if (match[a] < 0) break; a = parent[match[a]]; } while (true) { b = basis[b]; if (path[b]) return b; b = parent[match[b]]; } }+ void Mark(int vertex, int root, int child) { while (basis[vertex] != root) { blossom[basis[vertex]] = blossom[basis[match[vertex]]] = true; parent[vertex] = child; child = match[vertex]; vertex = parent[match[vertex]]; } }+ int Find(int root)+ {+ Array.Fill(used, false); Array.Fill(parent, -1); for (var i = 0; i < vertexCount; i++) basis[i] = i; queue.Clear(); queue.Enqueue(root); used[root] = true;+ while (queue.Count > 0)+ {+ var vertex = queue.Dequeue();+ foreach (var edge in graph[vertex])+ {+ var next = edge.Vertex; if (basis[vertex] == basis[next] || match[vertex] == next) continue;+ if (next == root || (match[next] >= 0 && parent[match[next]] >= 0))+ {+ var rootBasis = Lca(vertex, next); Array.Fill(blossom, false); Mark(vertex, rootBasis, next); Mark(next, rootBasis, vertex); contractions++;+ for (var i = 0; i < vertexCount; i++) if (blossom[basis[i]]) { basis[i] = rootBasis; if (!used[i]) { used[i] = true; queue.Enqueue(i); } }+ }+ else if (parent[next] < 0) { parent[next] = vertex; if (match[next] < 0) return next; next = match[next]; used[next] = true; queue.Enqueue(next); }+ }+ }+ return -1;+ }+ var changed = true;+ while (changed)+ {+ changed = false;+ for (var root = 0; root < vertexCount; root++) if (match[root] < 0)+ {+ var endpoint = Find(root); if (endpoint < 0) continue;+ while (endpoint >= 0) { var previous = parent[endpoint]; var next = previous < 0 ? -1 : match[previous]; match[endpoint] = previous; if (previous >= 0) match[previous] = endpoint; endpoint = next; }+ augmentations++; changed = true; break;+ }+ }+ return new(match, match.Count(x => x >= 0) / 2, augmentations, contractions, "deterministic Edmonds blossom maximum-cardinality matching over the hard-admissible layout graph");+ }+}diff --git a/Aetheris.Reconstruction/QuadAtlasRecovery.cs b/Aetheris.Reconstruction/QuadAtlasRecovery.csindex 789a8d3e..e94a4126 100644--- a/Aetheris.Reconstruction/QuadAtlasRecovery.cs+++ b/Aetheris.Reconstruction/QuadAtlasRecovery.cs@@ -58,18 +58,41 @@ public sealed record QuadAtlas(/// <summary>Canonical topology lowering from strict quad Panels, retaining typed triangle transitions only where matching is unresolved.</summary>public static class QuadAtlasSurfaceMeshLowering{- public static CanonicalReconstructionMesh Lower(TriangleSurfaceMesh source, QuadAtlas atlas)+ public static CanonicalReconstructionMesh Lower(TriangleSurfaceMesh source, QuadAtlas atlas) => Lower(source, atlas, null);++ public static CanonicalReconstructionMesh Lower(TriangleSurfaceMesh source, QuadAtlas atlas,+ IReadOnlyDictionary<string, SurfaceResidualField>? residualFields, double seamTolerance = 1e-9){- var vertices = source.Vertices.Select((p, i) => new SurfaceMeshVertex(i + 1, p)).ToArray();+ ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(atlas);+ if (!double.IsFinite(seamTolerance) || seamTolerance <= 0) throw new ArgumentOutOfRangeException(nameof(seamTolerance));+ residualFields ??= new Dictionary<string, SurfaceResidualField>();+ var correctedCorners = new Dictionary<int, List<Point3D>>();+ foreach (var chart in atlas.Charts) if (residualFields.TryGetValue(chart.StableId, out var residual))+ {+ var uv = new[] { (0d, 0d), (1d, 0d), (1d, 1d), (0d, 1d) };+ for (var i = 0; i < 4; i++)+ {+ var point = residual.Evaluate(chart.StrictPanel.AuthoredPatch, uv[i].Item1, uv[i].Item2).Point;+ if (!correctedCorners.TryGetValue(chart.CornerVertices[i], out var samples)) correctedCorners[chart.CornerVertices[i]] = samples = [];+ samples.Add(point);+ }+ }+ foreach (var item in correctedCorners)+ {+ var first = item.Value[0]; if (item.Value.Any(point => (point - first).Length > seamTolerance))+ throw new InvalidOperationException($"Residual fields disagree at shared source vertex {item.Key}; seam reconciliation is required before lowering.");+ }+ var vertices = source.Vertices.Select((p, i) => new SurfaceMeshVertex(i + 1,+ correctedCorners.TryGetValue(i, out var samples) ? new Point3D(samples.Average(x => x.X), samples.Average(x => x.Y), samples.Average(x => x.Z)) : p)).ToArray();var patches = new List<SurfacePatch>(); var faceIds = new Dictionary<string, FaceId>(StringComparer.Ordinal); var nextFace = 1;foreach (var chart in atlas.Charts){- var points = chart.CornerVertices.Select(v => source.Vertices[v]).ToArray(); var normal = (points[1] - points[0]).Cross(points[3] - points[0]); if (!normal.TryNormalize(out normal)) normal = new(0, 0, 1);- var x = points[1] - points[0]; if (!x.TryNormalize(out x)) x = new(1, 0, 0);var id = new FaceId(nextFace++); faceIds[chart.StableId] = id;- patches.Add(new(id, new(SurfaceMeshSupportKind.Plane, new(points[0], Direction3D.Create(normal), Direction3D.Create(x))), [],+ residualFields.TryGetValue(chart.StableId, out var residual);+ var adapter = new SurfaceMeshBoundedPatchAdapter(chart.StrictPanel.AuthoredPatch, residual);+ patches.Add(new(id, new(SurfaceMeshSupportKind.BoundedParametricPatch, BoundedPatch: adapter, BoundedPatchStableId: adapter.StableId), [],[new QuadCell(chart.CornerVertices.Select(v => v + 1).ToArray())], true, chart.StrictPanel.StableId,- ChartId: chart.StableId, PlanarPlannerPath: "QuadAtlas strict Panel boundary topology; SurfaceMeshIR plane support is a cell-carrier approximation for non-planar BoundaryPatch"));+ ChartId: chart.StableId, PlanarPlannerPath: "native bounded parametric patch evaluation; no plane proxy", ResidualFieldId: residual?.StableId));}foreach (var face in atlas.UnresolvedTriangles){@@ -161,7 +184,15 @@ public static class QuadAtlasRecoverynew Dictionary<string, int>()));}- ImproveMatching(selected, matched, byFace);+ var initialMate = Enumerable.Repeat(-1, matched.Length).ToArray();+ foreach (var pair in selected) { initialMate[pair.FaceA] = pair.FaceB; initialMate[pair.FaceB] = pair.FaceA; }+ var global = GlobalQuadLayoutMatcher.Match(mesh.Triangles.Count,+ candidates.Select(c => new GlobalMatchingEdge(c.FaceA, c.FaceB, c.Utility, c.Name)).ToArray(), initialMate);+ var byEdge = candidates.ToDictionary(c => Key(c.FaceA, c.FaceB)); selected.Clear(); Array.Fill(matched, false);+ for (var face = 0; face < global.Mate.Count; face++) if (global.Mate[face] > face)+ {+ var pair = byEdge[Key(face, global.Mate[face])]; selected.Add(pair); matched[face] = matched[global.Mate[face]] = true;+ }selected = selected.OrderBy(c => Math.Min(c.FaceA, c.FaceB)).ToList();var labels = Enumerable.Repeat<string?>(null, mesh.Triangles.Count).ToArray();for (var i = 0; i < selected.Count; i++) { labels[selected[i].FaceA] = labels[selected[i].FaceB] = $"quad-{i:D6}"; }@@ -237,8 +268,8 @@ public static class QuadAtlasRecoveryreturn result;}- // Deterministic bounded alternating-path search removes avoidable greedy transition faces.- // It intentionally stops short of pretending to be a blossom-capable maximum matcher.+ // Historical M2 bounded alternating-path implementation retained for artifact reproducibility.+ // M3 invokes GlobalQuadLayoutMatcher above.private static void ImproveMatching(List<PairCandidate> selected, bool[] matched, Dictionary<int, PairCandidate[]> byFace){var mate = new int[matched.Length]; Array.Fill(mate, -1);@@ -307,6 +338,9 @@ public static class QuadAtlasRecovery}).ToArray();}+ internal static IReadOnlyList<CrossFieldSingularity> DetectSingularitiesForRegularization(TriangleSurfaceMesh mesh, IReadOnlyList<DifferentialSample> field)+ => DetectSingularities(mesh, field, EdgeFaces(mesh));+private static bool TryBoundary(Triangle a, Triangle b, out int[] boundary){var directed = a.DirectedEdges().Concat(b.DirectedEdges()).ToArray();diff --git a/Aetheris.Reconstruction/StructuralPanelCoarsening.cs b/Aetheris.Reconstruction/StructuralPanelCoarsening.csnew file mode 100644index 00000000..706504a9--- /dev/null+++ b/Aetheris.Reconstruction/StructuralPanelCoarsening.cs@@ -0,0 +1,140 @@+using Aetheris.Geometry;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;+using Aetheris.Surfacing;++namespace Aetheris.Reconstruction;++public sealed record StructuralCoarseningPolicy(+ double MaximumFeatureAngleDegrees = 20,+ double MaximumTangentialFraction = .25,+ double MaximumResidualToBoundaryScale = .2,+ int MaximumExactCandidates = 1000);++public sealed record StructuralPanelRegion(+ string StableId, IReadOnlyList<string> SourceChartIds, IReadOnlyList<int> SourceTriangles,+ PanelIr Panel, SurfaceResidualField? ResidualField, double BaseRms, double CorrectedRms,+ double MaximumTangentialResidual, double NormalDiscontinuityDegrees, string RepresentationDecision);++public sealed record StructuralPanelCoarseningResult(+ IReadOnlyList<StructuralPanelRegion> Panels, int InputPanelCount, int MergedPairCount,+ int RejectedTopology, int RejectedFeature, int RejectedParameterization, int RejectedResidual,+ int ExactCandidateCount, int DeferredCandidateCount, IReadOnlyList<string> RepresentativeDecisions)+{+ public double MergeRatio => InputPanelCount / (double)Math.Max(1, Panels.Count);+}++/// <summary>+/// First bounded structural coarsener: globally selects disjoint adjacent two-Panel unions,+/// then admits only disk unions whose six-edge outline has four supported dominant corners.+/// It is intentionally narrower than arbitrary multi-chart parameterization.+/// </summary>+public static class StructuralPanelCoarsener+{+ private sealed record Candidate(QuadAtlasChart A, QuadAtlasChart B, PanelIr Panel, int[] Corners,+ double BaseRms, double CorrectedRms, double TangentialMaximum, double FeatureAngle, SurfaceResidualField? Residual, double Utility, string Decision);++ public static StructuralPanelCoarseningResult Coarsen(TriangleSurfaceMesh mesh, QuadAtlas atlas, StructuralCoarseningPolicy? policy = null)+ {+ ArgumentNullException.ThrowIfNull(mesh); ArgumentNullException.ThrowIfNull(atlas); policy ??= new();+ var chartById = atlas.Charts.ToDictionary(x => x.StableId, StringComparer.Ordinal); var candidates = new List<Candidate>();+ var rejectedTopology = 0; var rejectedFeature = 0; var rejectedParameterization = 0; var rejectedResidual = 0; var decisions = new List<string>();+ var internalSeams = atlas.Seams.Where(x => x.ChartUses.Count == 2 && !x.IsSourceBoundary).OrderBy(x => x.StableId, StringComparer.Ordinal).ToArray();+ var cheapFeature = internalSeams.ToDictionary(seam => seam.StableId,+ seam => NormalAngle(mesh, chartById[seam.ChartUses[0]].SourceTriangles, chartById[seam.ChartUses[1]].SourceTriangles), StringComparer.Ordinal);+ // Bounded first pass: exact residual projection is intentionally expensive. Evaluate only+ // mutual best smooth-neighbor proposals, then use global matching over admitted proposals.+ var preferred = internalSeams.SelectMany(seam => seam.ChartUses.Select(chart => (chart, seam)))+ .GroupBy(x => x.chart, StringComparer.Ordinal).ToDictionary(g => g.Key,+ g => g.OrderBy(x => cheapFeature[x.seam.StableId]).ThenBy(x => x.seam.StableId, StringComparer.Ordinal).First().seam.StableId, StringComparer.Ordinal);+ var proposedSeams = internalSeams.Where(seam => seam.ChartUses.Any(chart => preferred[chart] == seam.StableId))+ .OrderBy(seam => cheapFeature[seam.StableId]).ThenBy(seam => seam.StableId, StringComparer.Ordinal).ToArray();+ var boundedSeams = proposedSeams.Take(policy.MaximumExactCandidates);+ foreach (var seam in boundedSeams)+ {+ var a = chartById[seam.ChartUses[0]]; var b = chartById[seam.ChartUses[1]];+ var feature = cheapFeature[seam.StableId]; if (feature > policy.MaximumFeatureAngleDegrees) { rejectedFeature++; continue; }+ var faces = a.SourceTriangles.Concat(b.SourceTriangles).Distinct().ToArray(); if (!TryBoundaryCycle(mesh, faces, out var boundary) || boundary.Length < 4) { rejectedTopology++; continue; }+ var corners = DominantCorners(mesh, boundary); if (corners.Length != 4 || !NonFolded(corners.Select(i => mesh.Vertices[i]).ToArray())) { rejectedParameterization++; continue; }+ var panel = Materialize($"structural-{a.StableId}-{b.StableId}", corners.Select(i => mesh.Vertices[i]).ToArray()); if (!panel.IsSuccess) { rejectedParameterization++; continue; }+ var patch = panel.Panel!.AuthoredPatch;+ var boundaryScale = Enumerable.Range(0, 4).Average(i => (mesh.Vertices[corners[(i + 1) % 4]] - mesh.Vertices[corners[i]]).Length);+ var queryPolicy = new DistanceQueryPolicy { SubdivisionBudget = 128, IterationBudget = 20, LinearTolerance = Math.Max(1e-9, boundaryScale * .01), RelativeTolerance = 1e-8 };+ ResidualDecompositionSample[] samples;+ try+ {+ samples = faces.SelectMany(face => Vertices(mesh.Triangles[face])).Distinct().Select(vertex =>+ SurfaceResidualExtractor.Decompose(mesh.Vertices[vertex], FaceNormalAtVertex(mesh, faces, vertex), patch,+ queryPolicy)).Concat(faces.Select(face =>+ SurfaceResidualExtractor.Decompose(FaceCentroid(mesh, face), FaceNormal(mesh, face), patch,+ queryPolicy))).ToArray();+ }+ catch (InvalidOperationException) { rejectedResidual++; continue; }+ var baseRms = Math.Sqrt(samples.Average(x => x.Residual.LengthSquared)); var tangent = samples.Max(x => x.TangentialMagnitude);+ if (tangent > policy.MaximumTangentialFraction * boundaryScale || baseRms > policy.MaximumResidualToBoundaryScale * boundaryScale) { rejectedResidual++; continue; }+ var offset = FitOffsetGrid(samples, patch.Domain); var residual = new SurfaceResidualField($"residual-{panel.Panel.StableId}", patch.StableId, patch.Domain, offset, null,+ ResidualSeamPolicy.ZeroAtBoundary, new(PredicateEvidenceKind.Sampled, mesh.SourceIdentity, "closest-point normal decomposition; 3 x 3 piecewise-bilinear scalar fit with zero structural seam", baseRms, samples.Max(x => x.Residual.Length), 0, 0, samples.Length));+ var correctedRms = Math.Sqrt(samples.Average(x => (residual.Evaluate(patch, x.U, x.V).Point - x.SourcePoint).LengthSquared));+ var representations = new[]+ {+ new JudgmentCandidate<string>("base-only", _ => baseRms <= .02 * boundaryScale, _ => 1 - baseRms / Math.Max(boundaryScale, 1e-15), _ => "bounded support already meets structural tolerance", 0),+ new JudgmentCandidate<string>("offset-grid", _ => correctedRms <= baseRms && tangent <= policy.MaximumTangentialFraction * boundaryScale, _ => .9 - correctedRms / Math.Max(boundaryScale, 1e-15), _ => "sampled scalar normal offset with explicit complexity penalty", 1)+ };+ var judgment = new JudgmentEngine<string>().Evaluate("base-only", representations);+ if (judgment.Selection is null) { rejectedResidual++; continue; }+ var choice = judgment.Selection.Value.Candidate.Name;+ var admittedResidual = choice == "offset-grid" ? residual : null; var utility = 1 - (choice == "offset-grid" ? correctedRms : baseRms) / Math.Max(boundaryScale, 1e-15) - feature / 180;+ candidates.Add(new(a, b, panel.Panel, corners, baseRms, correctedRms, tangent, feature, admittedResidual, utility, choice));+ if (decisions.Count < 20) decisions.Add($"{a.StableId}+{b.StableId}: {choice}; baseRms={baseRms:R}; correctedRms={correctedRms:R}; tangentMax={tangent:R}");+ }+ var index = atlas.Charts.Select((chart, i) => (chart.StableId, i)).ToDictionary(x => x.StableId, x => x.i, StringComparer.Ordinal);+ var matching = GlobalQuadLayoutMatcher.Match(atlas.Charts.Count, candidates.Select((c, i) => new GlobalMatchingEdge(index[c.A.StableId], index[c.B.StableId], c.Utility, $"merge-{i:D8}")).ToArray());+ var candidateByPair = candidates.GroupBy(c => Key(index[c.A.StableId], index[c.B.StableId])).ToDictionary(g => g.Key, g => g.OrderByDescending(x => x.Utility).First());+ var merged = new HashSet<string>(StringComparer.Ordinal); var result = new List<StructuralPanelRegion>(); var mergedCount = 0;+ for (var i = 0; i < matching.Mate.Count; i++) if (matching.Mate[i] > i && candidateByPair.TryGetValue(Key(i, matching.Mate[i]), out var candidate))+ {+ merged.Add(candidate.A.StableId); merged.Add(candidate.B.StableId); mergedCount++;+ result.Add(new(candidate.Panel.StableId, [candidate.A.StableId, candidate.B.StableId], candidate.A.SourceTriangles.Concat(candidate.B.SourceTriangles).ToArray(), candidate.Panel,+ candidate.Residual, candidate.BaseRms, candidate.CorrectedRms, candidate.TangentialMaximum, candidate.FeatureAngle, candidate.Decision));+ }+ foreach (var chart in atlas.Charts.Where(x => !merged.Contains(x.StableId))) result.Add(new(chart.StableId, [chart.StableId], chart.SourceTriangles, chart.StrictPanel, null, 0, 0, 0, 0, "retained structural Panel"));+ return new(result.OrderBy(x => x.StableId, StringComparer.Ordinal).ToArray(), atlas.Charts.Count, mergedCount, rejectedTopology, rejectedFeature, rejectedParameterization, rejectedResidual,+ Math.Min(policy.MaximumExactCandidates, proposedSeams.Length), Math.Max(0, proposedSeams.Length - policy.MaximumExactCandidates), decisions);+ }++ private static BilinearScalarField FitOffsetGrid(IReadOnlyList<ResidualDecompositionSample> samples, ParametricDomain domain)+ {+ var sum = new double[3, 3]; var count = new int[3, 3];+ foreach (var sample in samples)+ {+ var i = (int)Math.Round((sample.U - domain.U.Minimum) / (domain.U.Maximum - domain.U.Minimum) * 2); var j = (int)Math.Round((sample.V - domain.V.Minimum) / (domain.V.Maximum - domain.V.Minimum) * 2);+ if (i == 0 || i == 2 || j == 0 || j == 2) continue; sum[i, j] += sample.NormalComponent; count[i, j]++;+ }+ var values = new double[3, 3]; if (count[1, 1] > 0) values[1, 1] = sum[1, 1] / count[1, 1]; return new(values, domain);+ }+ private static PanelResult Materialize(string id, Point3D[] p)+ {+ var s = new RuledBoundary.Line(id + ":s", p[0], p[1]); var e = new RuledBoundary.Line(id + ":e", p[1], p[2]); var n = new RuledBoundary.Line(id + ":n", p[3], p[2]); var w = new RuledBoundary.Line(id + ":w", p[0], p[3]);+ return PanelFactory.FromBoundaryPatch(new(id, s, n, w, e, [new(s.StableId,"coarsening","boundary chain"),new(n.StableId,"coarsening","boundary chain"),new(w.StableId,"coarsening","boundary chain"),new(e.StableId,"coarsening","boundary chain")]));+ }+ private static bool TryBoundaryCycle(TriangleSurfaceMesh mesh, IReadOnlyList<int> faces, out int[] cycle)+ {+ var directed = faces.SelectMany(face => mesh.Triangles[face].DirectedEdges()).ToArray(); var outer = directed.Where(e => directed.Count(x => Key(x.A, x.B) == Key(e.A, e.B)) == 1).ToArray();+ if (outer.Length < 4) { cycle = []; return false; } var next = outer.GroupBy(x => x.A).ToDictionary(g => g.Key, g => g.Select(x => x.B).Distinct().ToArray()); if (next.Any(x => x.Value.Length != 1)) { cycle = []; return false; }+ var start = outer.Min(x => x.A); var list = new List<int>(); var current = start;+ do { if (list.Contains(current) || !next.TryGetValue(current, out var values)) { cycle = []; return false; } list.Add(current); current = values[0]; } while (current != start && list.Count <= outer.Length);+ cycle = current == start && list.Count == outer.Length ? list.ToArray() : []; return cycle.Length > 0;+ }+ private static int[] DominantCorners(TriangleSurfaceMesh mesh, int[] boundary)+ {+ if (boundary.Length == 4) return boundary;+ var scored = boundary.Select((vertex, i) => { var a = mesh.Vertices[boundary[(i + boundary.Length - 1) % boundary.Length]] - mesh.Vertices[vertex]; var b = mesh.Vertices[boundary[(i + 1) % boundary.Length]] - mesh.Vertices[vertex]; var turn = a.TryNormalize(out a) && b.TryNormalize(out b) ? Math.PI - Math.Acos(Math.Clamp(a.Dot(b), -1, 1)) : 0; return (i, turn); }).OrderByDescending(x => x.turn).ThenBy(x => boundary[x.i]).Take(4).Select(x => x.i).Order().ToArray();+ return scored.Select(i => boundary[i]).ToArray();+ }+ private static bool NonFolded(Point3D[] p) { var n = (p[1]-p[0]).Cross(p[2]-p[0])+(p[2]-p[0]).Cross(p[3]-p[0]); return n.Length>1e-15&&Enumerable.Range(0,4).All(i=>(p[(i+1)%4]-p[i]).Cross(p[(i+2)%4]-p[(i+1)%4]).Dot(n)>=-1e-12); }+ private static double NormalAngle(TriangleSurfaceMesh mesh, IReadOnlyList<int> a, IReadOnlyList<int> b) { var na=a.Select(x=>FaceNormal(mesh,x)).Aggregate(Vector3D.Zero,(x,y)=>x+y);var nb=b.Select(x=>FaceNormal(mesh,x)).Aggregate(Vector3D.Zero,(x,y)=>x+y);return na.TryNormalize(out na)&&nb.TryNormalize(out nb)?Math.Acos(Math.Clamp(na.Dot(nb),-1,1))*180/Math.PI:180; }+ private static Vector3D FaceNormal(TriangleSurfaceMesh mesh,int face){var t=mesh.Triangles[face];var n=(mesh.Vertices[t.B]-mesh.Vertices[t.A]).Cross(mesh.Vertices[t.C]-mesh.Vertices[t.A]);return n.TryNormalize(out n)?n:Vector3D.Zero;}+ private static Point3D FaceCentroid(TriangleSurfaceMesh mesh,int face){var t=mesh.Triangles[face];var a=mesh.Vertices[t.A];var b=mesh.Vertices[t.B];var c=mesh.Vertices[t.C];return new((a.X+b.X+c.X)/3,(a.Y+b.Y+c.Y)/3,(a.Z+b.Z+c.Z)/3);}+ private static Vector3D FaceNormalAtVertex(TriangleSurfaceMesh mesh,IReadOnlyList<int> faces,int vertex){var n=faces.Where(f=>Vertices(mesh.Triangles[f]).Contains(vertex)).Select(f=>FaceNormal(mesh,f)).Aggregate(Vector3D.Zero,(a,b)=>a+b);return n.TryNormalize(out n)?n:new(0,0,1);}+ private static int[] Vertices(Triangle t)=>[t.A,t.B,t.C]; private static (int,int) Key(int a,int b)=>a<b?(a,b):(b,a);+}diff --git a/Aetheris.Reconstruction/SurfaceResidualFields.cs b/Aetheris.Reconstruction/SurfaceResidualFields.csnew file mode 100644index 00000000..eaa4b0ed--- /dev/null+++ b/Aetheris.Reconstruction/SurfaceResidualFields.cs@@ -0,0 +1,220 @@+using Aetheris.Geometry;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Reconstruction;++public enum ResidualInterpolationModel { PiecewiseBilinearGrid }+public enum ResidualSeamPolicy { SharedBoundarySamples, ZeroAtBoundary }+public enum ResidualNormalAuthority { DifferentialInterpretationOnly }++public sealed record ResidualFieldEvidence(+ PredicateEvidenceKind Kind,+ string Provenance,+ string Method,+ double PositionRms,+ double PositionMaximum,+ double NormalCorrectionRmsDegrees,+ double NormalCorrectionMaximumDegrees,+ int SourceSampleCount);++/// <summary>A bounded scalar displacement along the evaluated base unit normal.</summary>+public sealed class BilinearScalarField+{+ private readonly double[,] _values;++ public BilinearScalarField(double[,] values, ParametricDomain domain)+ {+ ArgumentNullException.ThrowIfNull(values); ArgumentNullException.ThrowIfNull(domain);+ if (values.GetLength(0) < 2 || values.GetLength(1) < 2) throw new ArgumentException("A bilinear residual grid needs at least 2 x 2 samples.", nameof(values));+ if (values.Cast<double>().Any(value => !double.IsFinite(value))) throw new ArgumentException("Residual samples must be finite.", nameof(values));+ _values = (double[,])values.Clone(); Domain = domain;+ }++ public ParametricDomain Domain { get; }+ public int CountU => _values.GetLength(0);+ public int CountV => _values.GetLength(1);+ public int SampleCount => CountU * CountV;+ public ResidualInterpolationModel Interpolation => ResidualInterpolationModel.PiecewiseBilinearGrid;++ public double Evaluate(double u, double v)+ {+ var (i, fu) = Cell(u, Domain.U, CountU); var (j, fv) = Cell(v, Domain.V, CountV);+ return Lerp(Lerp(_values[i, j], _values[i + 1, j], fu), Lerp(_values[i, j + 1], _values[i + 1, j + 1], fu), fv);+ }++ public (double Du, double Dv) Gradient(double u, double v)+ {+ var (i, fu) = Cell(u, Domain.U, CountU); var (j, fv) = Cell(v, Domain.V, CountV);+ var du = Lerp(_values[i + 1, j] - _values[i, j], _values[i + 1, j + 1] - _values[i, j + 1], fv) * (CountU - 1) / (Domain.U.Maximum - Domain.U.Minimum);+ var dv = Lerp(_values[i, j + 1] - _values[i, j], _values[i + 1, j + 1] - _values[i + 1, j], fu) * (CountV - 1) / (Domain.V.Maximum - Domain.V.Minimum);+ return (du, dv);+ }++ public double this[int i, int j] => _values[i, j];+ private static double Lerp(double a, double b, double t) => a + (b - a) * t;+ private static (int Cell, double Fraction) Cell(double parameter, ParameterInterval2 interval, int count)+ {+ if (!double.IsFinite(parameter) || parameter < interval.Minimum || parameter > interval.Maximum) throw new ArgumentOutOfRangeException(nameof(parameter));+ var scaled = (parameter - interval.Minimum) / (interval.Maximum - interval.Minimum) * (count - 1);+ var cell = Math.Min(count - 2, (int)Math.Floor(scaled));+ return (cell, scaled - cell);+ }+}++/// <summary>Explicit target normals. They are interpretation evidence and never displace points.</summary>+public sealed class BilinearNormalField+{+ private readonly Vector3D[,] _values;+ public BilinearNormalField(Vector3D[,] values, ParametricDomain domain)+ {+ ArgumentNullException.ThrowIfNull(values); ArgumentNullException.ThrowIfNull(domain);+ if (values.GetLength(0) < 2 || values.GetLength(1) < 2) throw new ArgumentException("A bilinear normal grid needs at least 2 x 2 samples.", nameof(values));+ _values = new Vector3D[values.GetLength(0), values.GetLength(1)];+ for (var i = 0; i < values.GetLength(0); i++) for (var j = 0; j < values.GetLength(1); j++)+ {+ if (!values[i, j].TryNormalize(out var normal)) throw new ArgumentException("Normal samples must be finite non-zero vectors.", nameof(values));+ _values[i, j] = normal;+ }+ Domain = domain;+ }+ public ParametricDomain Domain { get; }+ public int CountU => _values.GetLength(0);+ public int CountV => _values.GetLength(1);+ public int SampleCount => CountU * CountV;+ public ResidualNormalAuthority Authority => ResidualNormalAuthority.DifferentialInterpretationOnly;+ public Vector3D Evaluate(double u, double v)+ {+ var (i, fu) = Cell(u, Domain.U, CountU); var (j, fv) = Cell(v, Domain.V, CountV);+ var a = _values[i, j] * (1 - fu) + _values[i + 1, j] * fu;+ var b = _values[i, j + 1] * (1 - fu) + _values[i + 1, j + 1] * fu;+ var value = a * (1 - fv) + b * fv;+ if (!value.TryNormalize(out value)) throw new ArithmeticException("Interpolated normal is singular.");+ return value;+ }+ private static (int, double) Cell(double p, ParameterInterval2 d, int n)+ {+ if (!double.IsFinite(p) || p < d.Minimum || p > d.Maximum) throw new ArgumentOutOfRangeException(nameof(p));+ var x = (p - d.Minimum) / (d.Maximum - d.Minimum) * (n - 1); var i = Math.Min(n - 2, (int)Math.Floor(x)); return (i, x - i);+ }+}++public sealed record CorrectedSurfaceSample(+ Point3D Point,+ Vector3D BaseNormal,+ Vector3D GeometricNormal,+ Vector3D InterpretedNormal,+ double Offset,+ bool PositionWasDisplaced,+ bool NormalCorrectionWasApplied);++/// <summary>+/// Reconstruction-owned detail attached to one structural patch. Offset authority is geometric;+/// normal correction authority is explicitly differential-only.+/// </summary>+public sealed class SurfaceResidualField+{+ public SurfaceResidualField(string stableId, string basePatchIdentity, ParametricDomain domain,+ BilinearScalarField? positionOffset, BilinearNormalField? normalCorrection,+ ResidualSeamPolicy seamPolicy, ResidualFieldEvidence evidence)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(stableId); ArgumentException.ThrowIfNullOrWhiteSpace(basePatchIdentity);+ ArgumentNullException.ThrowIfNull(domain); ArgumentNullException.ThrowIfNull(evidence);+ if (positionOffset is null && normalCorrection is null) throw new ArgumentException("A residual field must contain position or normal evidence.");+ if (positionOffset is not null && positionOffset.Domain != domain) throw new ArgumentException("Offset domain must match the base domain.");+ if (normalCorrection is not null && normalCorrection.Domain != domain) throw new ArgumentException("Normal domain must match the base domain.");+ StableId = stableId; BasePatchIdentity = basePatchIdentity; Domain = domain; PositionOffset = positionOffset;+ NormalCorrection = normalCorrection; SeamPolicy = seamPolicy; Evidence = evidence;+ }++ public string StableId { get; }+ public string BasePatchIdentity { get; }+ public ParametricDomain Domain { get; }+ public BilinearScalarField? PositionOffset { get; }+ public BilinearNormalField? NormalCorrection { get; }+ public ResidualSeamPolicy SeamPolicy { get; }+ public ResidualFieldEvidence Evidence { get; }+ public int ControlCount => (PositionOffset?.SampleCount ?? 0) + (NormalCorrection?.SampleCount ?? 0);++ public CorrectedSurfaceSample Evaluate(BoundedParametricPatch3 basePatch, double u, double v)+ {+ ArgumentNullException.ThrowIfNull(basePatch);+ if (!string.Equals(basePatch.StableId, BasePatchIdentity, StringComparison.Ordinal)) throw new ArgumentException("Residual field base identity does not match the supplied patch.", nameof(basePatch));+ var jet = basePatch.EvaluateJet1(u, v);+ if (jet.Normal is null) throw new InvalidOperationException("Residual evaluation requires a regular base first jet.");+ var baseNormal = jet.Normal.Value.ToVector(); var offset = PositionOffset?.Evaluate(u, v) ?? 0;+ var point = jet.Point + baseNormal * offset;+ var geometricNormal = PositionOffset is null ? baseNormal : DisplacedNormal(basePatch, u, v);+ var interpreted = NormalCorrection?.Evaluate(u, v) ?? geometricNormal;+ return new(point, baseNormal, geometricNormal, interpreted, offset, PositionOffset is not null, NormalCorrection is not null);+ }++ private Vector3D DisplacedNormal(BoundedParametricPatch3 patch, double u, double v)+ {+ var hu = (Domain.U.Maximum - Domain.U.Minimum) * 1e-5; var hv = (Domain.V.Maximum - Domain.V.Minimum) * 1e-5;+ var u0 = Math.Max(Domain.U.Minimum, u - hu); var u1 = Math.Min(Domain.U.Maximum, u + hu);+ var v0 = Math.Max(Domain.V.Minimum, v - hv); var v1 = Math.Min(Domain.V.Maximum, v + hv);+ Point3D P(double x, double y) { var j = patch.EvaluateJet1(x, y); return j.Point + j.Normal!.Value.ToVector() * PositionOffset!.Evaluate(x, y); }+ var du = (P(u1, v) - P(u0, v)) * (1 / (u1 - u0)); var dv = (P(u, v1) - P(u, v0)) * (1 / (v1 - v0));+ if (!du.Cross(dv).TryNormalize(out var normal)) throw new ArithmeticException("Displaced residual surface is singular.");+ return normal;+ }+}++public sealed record ResidualDecompositionSample(+ Point3D SourcePoint, double U, double V, Vector3D Residual,+ double NormalComponent, Vector3D TangentialComponent, double TangentialMagnitude,+ double? NormalCorrectionDegrees, PredicateEvidenceKind Evidence);++public static class SurfaceResidualExtractor+{+ public static ResidualDecompositionSample Decompose(Point3D sourcePoint, Vector3D? sourceNormal,+ BoundedParametricPatch3 basePatch, DistanceQueryPolicy? policy = null)+ {+ policy ??= DistanceQueryPolicy.Default; var closest = ClosestPointQuery.Between(sourcePoint, basePatch, policy);+ if (closest.Status != DistanceQueryStatus.Available || closest.PointOnB is null || closest.ParameterOnB?.U is not double u || closest.ParameterOnB.V is not double v)+ throw new InvalidOperationException("Bounded closest-point projection did not converge; scalar offset suitability is unknown.");+ var jet = basePatch.EvaluateJet1(u, v); if (jet.Normal is null) throw new InvalidOperationException("Closest base point has a singular normal.");+ var n = jet.Normal.Value.ToVector(); var residual = sourcePoint - closest.PointOnB.Value; var normal = residual.Dot(n); var tangential = residual - n * normal;+ double? angle = null; if (sourceNormal is Vector3D candidate && candidate.TryNormalize(out candidate)) angle = Math.Acos(Math.Clamp(candidate.Dot(n), -1, 1)) * 180 / Math.PI;+ return new(sourcePoint, u, v, residual, normal, tangential, tangential.Length, angle, closest.Evidence);+ }++ public static bool IsScalarOffsetSuitable(ResidualDecompositionSample sample, double maximumTangentialFraction = .2, double absoluteTolerance = 1e-6)+ {+ if (!double.IsFinite(maximumTangentialFraction) || maximumTangentialFraction < 0 || maximumTangentialFraction > 1) throw new ArgumentOutOfRangeException(nameof(maximumTangentialFraction));+ var length = sample.Residual.Length; return sample.TangentialMagnitude <= absoluteTolerance || (length > 0 && sample.TangentialMagnitude / length <= maximumTangentialFraction);+ }+}++/// <summary>Adapter that lets SurfaceMeshIR consume a real authored bounded patch without owning its semantic type.</summary>+public sealed class SurfaceMeshBoundedPatchAdapter : ISurfaceMeshBoundedPatch+{+ private readonly BoundedParametricPatch3 _patch;+ private readonly SurfaceResidualField? _residual;+ public SurfaceMeshBoundedPatchAdapter(BoundedParametricPatch3 patch, SurfaceResidualField? residual = null)+ {+ _patch = patch ?? throw new ArgumentNullException(nameof(patch));+ if (residual is not null && !string.Equals(residual.BasePatchIdentity, patch.StableId, StringComparison.Ordinal)) throw new ArgumentException("Residual base identity does not match the patch.", nameof(residual));+ _residual = residual;+ }+ public string StableId => _patch.StableId;+ public double MinimumU => _patch.Domain.U.Minimum;+ public double MaximumU => _patch.Domain.U.Maximum;+ public double MinimumV => _patch.Domain.V.Minimum;+ public double MaximumV => _patch.Domain.V.Maximum;+ public SurfaceMeshParametricJet Evaluate(double u, double v)+ {+ if (_residual is null) { var jet = _patch.EvaluateJet1(u, v); return new(jet.Point, jet.Du, jet.Dv); }+ var point = _residual.Evaluate(_patch, u, v).Point;+ var hu = (MaximumU - MinimumU) * 1e-5; var hv = (MaximumV - MinimumV) * 1e-5;+ var u0 = Math.Max(MinimumU, u - hu); var u1 = Math.Min(MaximumU, u + hu); var v0 = Math.Max(MinimumV, v - hv); var v1 = Math.Min(MaximumV, v + hv);+ var du = (_residual.Evaluate(_patch, u1, v).Point - _residual.Evaluate(_patch, u0, v).Point) * (1 / (u1 - u0));+ var dv = (_residual.Evaluate(_patch, u, v1).Point - _residual.Evaluate(_patch, u, v0).Point) * (1 / (v1 - v0));+ return new(point, du, dv);+ }+ public bool TryProject(Point3D point, out double u, out double v)+ {+ var hit = ClosestPointQuery.Between(point, _patch); u = hit.ParameterOnB?.U ?? 0; v = hit.ParameterOnB?.V ?? 0; return hit.Status == DistanceQueryStatus.Available && hit.ParameterOnB?.U is not null && hit.ParameterOnB.V is not null;+ }+}diff --git a/Aetheris.slnx b/Aetheris.slnxindex abc6e503..f3b424d8 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -36,6 +36,7 @@<Project Path="tools/Aetheris.BunnyM0/Aetheris.BunnyM0.csproj" /><Project Path="tools/Aetheris.BunnyM1/Aetheris.BunnyM1.csproj" /><Project Path="tools/Aetheris.BunnyM2/Aetheris.BunnyM2.csproj" />+ <Project Path="tools/Aetheris.BunnyM3/Aetheris.BunnyM3.csproj" /><Project Path="tools/Aetheris.Continuum.AttentionE0/Aetheris.Continuum.AttentionE0.csproj" /><Project Path="tools/Aetheris.Continuum.AttentionE1/Aetheris.Continuum.AttentionE1.csproj" /><Project Path="Aetheris.Forge/Aetheris.Forge.csproj" />diff --git a/docs/geometry/artifacts/bunny-m3/README.md b/docs/geometry/artifacts/bunny-m3/README.mdnew file mode 100644index 00000000..6edb2442--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/README.md@@ -0,0 +1,7 @@+# AETHERIS-BUNNY-M3 evidence++M3 separates structural `PanelIr` support from sampled scalar offset and differential-only normal fields, replaces the SurfaceMeshIR plane proxy with a native bounded parametric evaluator, and replaces M2's local matching with deterministic Edmonds blossom matching.++The canonical run is **Meaningful Progression**, not Success. The global pair atlas is crack-free and has one parity-forced transition. The bounded coarsener demonstrates fewer structural Panels and residual representation on admitted two-Panel unions, but those unions are not yet installed as the canonical atlas because arbitrary multi-chart parameterization and globally authoritative residual seam construction remain unresolved.++Reproduce with `dotnet run --project tools/Aetheris.BunnyM3 -c Release -- .tmp/bunny-m0-source/bunny/reconstruction/bun_zipper.ply docs/geometry/artifacts/bunny-m3`.\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/continuity-summary.json b/docs/geometry/artifacts/bunny-m3/continuity-summary.jsonnew file mode 100644index 00000000..6e77f6a5--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/continuity-summary.json@@ -0,0 +1,7 @@+{+ "internalCracks": 0,+ "intentionalOpenLoops": 5,+ "nonManifoldEdgeCount": 0,+ "residualSeamPolicy": "shared corrected corner position within explicit tolerance; disagreement rejects lowering; bounded coarsener fits zero seam offsets",+ "coarsenedAtlasGloballyReconciled": false+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/field-regularization-summary.json b/docs/geometry/artifacts/bunny-m3/field-regularization-summary.jsonnew file mode 100644index 00000000..946a440e--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/field-regularization-summary.json@@ -0,0 +1,13 @@+{+ "inputSingularities": 1603,+ "outputSingularities": 1603,+ "cancelledNet": 0,+ "retainedFeatureFaces": 6946,+ "retainedBoundaryFaces": 221,+ "acceptedIterations": 0,+ "inputIndexSum": -3,+ "outputIndexSum": -3,+ "globalIndexPreserved": true,+ "objective": "principal-direction alignment \u002B neighbor smoothness \u002B fixed feature/boundary evidence \u002B singularity sparsity",+ "deterministicPolicy": "synchronous quarter-equivalent averaging; admit only non-increasing defect count with preserved global detected index"+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/global-layout-summary.json b/docs/geometry/artifacts/bunny-m3/global-layout-summary.jsonnew file mode 100644index 00000000..fd17907f--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/global-layout-summary.json@@ -0,0 +1,12 @@+{+ "algorithm": "deterministic Edmonds blossom maximum-cardinality matching after hard disk/four-corner/foldover filtering",+ "transitionTrianglesBefore": 67,+ "transitionTrianglesAfter": 1,+ "parityLowerBound": 1,+ "explanation": "An odd source face count makes zero impossible for pair-only layout; eliminating the last transition requires a larger chart operation.",+ "additionalMatchedPairs": 33,+ "transitionFacesRemoved": 66,+ "meanFieldDeviationDegrees": 20.72099153977918,+ "deterministicHash": "2d7a91833163f326fea017c96f1dafc2107682e6fb85e9fd6b86e70ab90b418f",+ "judgment": "Judgment scores geometric options before the exact graph stage; it does not replace matching."+}diff --git a/docs/geometry/artifacts/bunny-m3/judgment-summary.json b/docs/geometry/artifacts/bunny-m3/judgment-summary.jsonnew file mode 100644index 00000000..8e8e7be9--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/judgment-summary.json@@ -0,0 +1,28 @@+{+ "uses": [+ {+ "decision": "adjacent-face quad route",+ "hardConstraints": "disk/four corners/nonfolded",+ "score": "field .50 \u002B shape .35 \u002B normal .15",+ "candidateCount": 1000,+ "winner": "trace-specific"+ },+ {+ "decision": "base-only versus scalar offset grid",+ "hardConstraints": "tangential residual and bounded error",+ "score": "error - representation complexity",+ "candidateCount": 1032,+ "winner": "per admitted merge"+ }+ ],+ "exactAlgorithms": [+ "Edmonds blossom for maximum-cardinality layout",+ "Edmonds blossom for disjoint merge selection"+ ],+ "notJudgment": [+ "manifoldness",+ "boundary-loop count",+ "seam incidence",+ "foldover legality"+ ]+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/m2-oversegmentation-audit.json b/docs/geometry/artifacts/bunny-m3/m2-oversegmentation-audit.jsonnew file mode 100644index 00000000..acf39638--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/m2-oversegmentation-audit.json@@ -0,0 +1,43 @@+{+ "m2Panels": 34692,+ "measuredM3PairPanels": 34725,+ "classificationsAreOverlapping": true,+ "classifications": {+ "real topology / detected singularity proximity": 5754,+ "source boundary": 201,+ "parameterization limitation (angle distortion \u003E= 75 degrees)": 4364,+ "likely removable through admitted bounded merge": 1032,+ "local triangle-pairing artifact / unproven necessity": 28971+ },+ "explanation": "M2 creates exactly one Panel per matched adjacent triangle pair; panel existence therefore follows source face density before topology, feature, or residual necessity is tested.",+ "mergePressure": {+ "neighborPairs": 69338,+ "admittedPairs": 516,+ "rejectedTopology": 0,+ "rejectedFeature": 0,+ "rejectedParameterization": 175,+ "rejectedResidual": 244+ },+ "representatives": [+ "quad-031925\u002Bquad-033758: base-only; baseRms=3.440784963605128E-06; correctedRms=3.440784504891414E-06; tangentMax=6.352715587575599E-06",+ "quad-031368\u002Bquad-031369: base-only; baseRms=1.1687800402191081E-05; correctedRms=1.1687799460690751E-05; tangentMax=1.9759629266468812E-05",+ "quad-031637\u002Bquad-034428: base-only; baseRms=2.1844894667983304E-06; correctedRms=2.184482271664698E-06; tangentMax=3.7020145280423674E-06",+ "quad-031016\u002Bquad-031241: base-only; baseRms=1.9822499840459547E-05; correctedRms=1.9822481621982765E-05; tangentMax=9.91078703156421E-06",+ "quad-031820\u002Bquad-033758: base-only; baseRms=2.1525510179044474E-06; correctedRms=2.1525505344990204E-06; tangentMax=3.6809758906481284E-06",+ "quad-032002\u002Bquad-032074: base-only; baseRms=3.7084894900149514E-05; correctedRms=3.708496549408723E-05; tangentMax=6.385745029430018E-06",+ "quad-034354\u002Bquad-034407: base-only; baseRms=9.301190472712202E-07; correctedRms=9.301041572776672E-07; tangentMax=1.8185096149911458E-06",+ "quad-031208\u002Bquad-031760: base-only; baseRms=2.0752700785285335E-05; correctedRms=2.0752686130571403E-05; tangentMax=1.0510229928729393E-05",+ "quad-033507\u002Bquad-033557: base-only; baseRms=2.5696876213795353E-05; correctedRms=2.569687484853427E-05; tangentMax=3.733548605834995E-05",+ "quad-034540\u002Bquad-034584: base-only; baseRms=2.720404938917846E-06; correctedRms=2.720404556189607E-06; tangentMax=5.485235154684635E-06",+ "quad-031002\u002Bquad-031225: offset-grid; baseRms=0.00016728678144181116; correctedRms=0.00016728678036720287; tangentMax=0.0005289297665636197",+ "quad-031132\u002Bquad-032948: base-only; baseRms=1.92069436673282E-05; correctedRms=1.920693566406317E-05; tangentMax=1.0152928952014562E-05",+ "quad-034357\u002Bquad-034410: base-only; baseRms=1.0018796294761087E-06; correctedRms=1.0018295203765737E-06; tangentMax=1.8304338625974234E-06",+ "quad-033451\u002Bquad-033505: base-only; baseRms=1.1501667940807772E-05; correctedRms=1.1501664181224256E-05; tangentMax=2.0486651515677135E-05",+ "quad-032922\u002Bquad-032979: base-only; baseRms=2.1757057611705952E-05; correctedRms=2.175711711032971E-05; tangentMax=2.0216543366891443E-05",+ "quad-030908\u002Bquad-032218: base-only; baseRms=1.9227572083383396E-05; correctedRms=1.922757191789958E-05; tangentMax=9.30515565936692E-06",+ "quad-031704\u002Bquad-032661: base-only; baseRms=1.0671285539072458E-06; correctedRms=1.0670513435302317E-06; tangentMax=2.5537082750996156E-06",+ "quad-031638\u002Bquad-031696: base-only; baseRms=2.218878743433714E-05; correctedRms=2.2188785839755927E-05; tangentMax=1.8058096959447103E-05",+ "quad-031925\u002Bquad-032639: base-only; baseRms=3.3546165970667047E-06; correctedRms=3.3545947504553232E-06; tangentMax=6.4229154699061E-06",+ "quad-013071\u002Bquad-013576: base-only; baseRms=2.6095233303937262E-05; correctedRms=2.609521004172053E-05; tangentMax=3.494959683490661E-05"+ ]+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/manifest.json b/docs/geometry/artifacts/bunny-m3/manifest.jsonnew file mode 100644index 00000000..aab49204--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/manifest.json@@ -0,0 +1,96 @@+{+ "milestone": "AETHERIS-BUNNY-M3",+ "sourceMeshHash": "88d635a8709c1c570ff47c80ef6340fe8a8da58c1f3e2c96975ff428276cbde0",+ "atlasHash": "2d7a91833163f326fea017c96f1dafc2107682e6fb85e9fd6b86e70ab90b418f",+ "surfaceMeshHash": "79f32bff0df53fe32eacfc90087b41f889fbb356161827a2160fb56118e5d58c",+ "deterministic": true,+ "excludedObservationalFiles": [+ "performance.json"+ ],+ "files": [+ {+ "path": "README.md",+ "sha256": "e6d9e8ad750cfeef0d799ce4e58525dc09e868e4644cb21d7891a8516419fb29",+ "bytes": 899,+ "lines": 7+ },+ {+ "path": "continuity-summary.json",+ "sha256": "c0b4e23c6db585ad5faa149993df210d9d9a2808c6ad43a06234ac5f34dad309",+ "bytes": 293,+ "lines": 7+ },+ {+ "path": "field-regularization-summary.json",+ "sha256": "89f4aadb0842890449d9dedd4b809d1a3dced03a32284d21f0b8ff93705d74ca",+ "bytes": 554,+ "lines": 13+ },+ {+ "path": "global-layout-summary.json",+ "sha256": "7412f046592ba8bdcc2d0dbf51b0b31f16b455291d2c0d7eef15a6b5a0d5e918",+ "bytes": 701,+ "lines": 12+ },+ {+ "path": "judgment-summary.json",+ "sha256": "0a9fbb35e6e20658a63435639156b5b6a55c20298c8f5a93aeefcf626e51c1cd",+ "bytes": 791,+ "lines": 28+ },+ {+ "path": "m2-oversegmentation-audit.json",+ "sha256": "1599cceb478050333dfa399cada58d0f4ee882de2e3f1715fafab3f93f070e35",+ "bytes": 3877,+ "lines": 43+ },+ {+ "path": "mesh-summary.json",+ "sha256": "f54413a7f6ccaf6fc7b19e3bd62aa3bb27446e6e122a2ef1d8c13721811464db",+ "bytes": 532,+ "lines": 16+ },+ {+ "path": "panel-coarsening-summary.json",+ "sha256": "fce06b8f1045d5df15c8209f4a88e54bdfdc6f6d6464bdcb2c65c702f783c817",+ "bytes": 635,+ "lines": 14+ },+ {+ "path": "parameterization-summary.json",+ "sha256": "49f675b8862ced272c4076a232ee15f3836da963f090af996a27fd4abc613fdc",+ "bytes": 487,+ "lines": 18+ },+ {+ "path": "quality-comparison.json",+ "sha256": "9dd6318e82d04d5a7e639e3c0c4a7fa15b112c876dd4b4171629dafadb9b4598",+ "bytes": 662,+ "lines": 16+ },+ {+ "path": "representation-compression.json",+ "sha256": "f1cdd9a4d1d5bdccb8b3b680ab7086834e6a3eb0ed81d9f6c5604d0ec55f5ba3",+ "bytes": 356,+ "lines": 12+ },+ {+ "path": "residual-field-summary.json",+ "sha256": "5bf777416073f0581c22253e0636b6c8491a21728ff5bb0989222e877b3bc34e",+ "bytes": 905,+ "lines": 19+ },+ {+ "path": "singularity-summary.json",+ "sha256": "85e8a2eb45f8eb26217e642e50cc541f2720a774b9c763421e876f8128281f12",+ "bytes": 271,+ "lines": 10+ },+ {+ "path": "validation-report.json",+ "sha256": "cf2b9630432947a5d1877b3a424b06f50f96170d2e9619628fe187962eb3fe12",+ "bytes": 5636,+ "lines": 308+ }+ ]+}diff --git a/docs/geometry/artifacts/bunny-m3/mesh-summary.json b/docs/geometry/artifacts/bunny-m3/mesh-summary.jsonnew file mode 100644index 00000000..d9e41593--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/mesh-summary.json@@ -0,0 +1,16 @@+{+ "vertices": 35947,+ "cells": 34726,+ "quads": 34725,+ "triangles": 1,+ "nGons": 0,+ "quadPercentage": 99.9971203133099,+ "internalCrackGroups": 0,+ "intentionalLoops": 5,+ "nonManifoldEdgeCount": 0,+ "validation": "Pass",+ "nativeBoundedPatchSupports": 34725,+ "planeProxyCount": 0,+ "deterministicHash": "79f32bff0df53fe32eacfc90087b41f889fbb356161827a2160fb56118e5d58c",+ "authority": "globally valid pair atlas; coarsened diagnostic atlas is not substituted until its global seam network exists"+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/panel-coarsening-summary.json b/docs/geometry/artifacts/bunny-m3/panel-coarsening-summary.jsonnew file mode 100644index 00000000..a4bc8efe--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/panel-coarsening-summary.json@@ -0,0 +1,14 @@+{+ "m2PanelCount": 34692,+ "m3PairAtlasPanels": 34725,+ "structuralPanelCount": 34209,+ "mergedPairCount": 516,+ "mergeRatio": 1.0150837498903797,+ "exactCandidateCount": 1000,+ "deferredCandidateCount": 24392,+ "averageM2PanelsPerStructuralPanel": 1.0141190914671578,+ "sourceTrianglesPerStructuralPanel": 2.0301967318541903,+ "globallyLowerable": false,+ "scope": "bounded audit of the 1,000 smoothest best-neighbor proposals; disjoint two-Panel unions only",+ "nextBlocker": "batched/cached projection followed by arbitrary multi-chart four-sided parameterization plus global residual seam reconciliation"+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/parameterization-summary.json b/docs/geometry/artifacts/bunny-m3/parameterization-summary.jsonnew file mode 100644index 00000000..db9a8682--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/parameterization-summary.json@@ -0,0 +1,18 @@+{+ "m2": {+ "mean": 51.69,+ "p95": 85.11,+ "maximum": 89.99+ },+ "m3": {+ "mean": 51.20397434245495,+ "p95": 85.0788840932172,+ "maximum": 89.99586563252217,+ "aspectMean": 1.414255610817858,+ "aspectP95": 2.074971202557143,+ "aspectMaximum": 13.599499030164827,+ "foldovers": 0+ },+ "method": "four-corner Coons/bilinear; bounded pair coarsening does not yet solve arbitrary multi-chart UV relaxation",+ "improvedMaterially": false+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/performance.json b/docs/geometry/artifacts/bunny-m3/performance.jsonnew file mode 100644index 00000000..f72ea643--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/performance.json@@ -0,0 +1,14 @@+{+ "timingsMilliseconds": {+ "boundedPairCoarseningAndResidualExtraction": 120908.9166,+ "crossField": 421.2923,+ "diagnosticsAggregationAndSerialization": 60964.5734,+ "fieldRegularization": 493.6539,+ "globalLayoutAndPanelFit": 36354.3048,+ "nativeBoundedPatchLowering": 227.4973,+ "sourceLoad": 74.346,+ "sourceValidation": 100.1708,+ "total": 219146.655+ },+ "workingSetBytes": 1111654400+}diff --git a/docs/geometry/artifacts/bunny-m3/quality-comparison.json b/docs/geometry/artifacts/bunny-m3/quality-comparison.jsonnew file mode 100644index 00000000..3c0b762f--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/quality-comparison.json@@ -0,0 +1,16 @@+{+ "m2": {+ "sourcePanelRms": 6.273042597053603E-05,+ "remeshSourceRms": 3.045295353210311E-05,+ "normalMeanDegrees": 4.2433,+ "normalRmsDegrees": 14.7434,+ "normalMaxDegrees": 90+ },+ "m3": {+ "positionAndNormalCanonicalReevaluation": "not repeated: native support changes carrier, not authored Panel geometry",+ "representativeCoarsenedBaseRms": 3.924316843605095E-05,+ "representativeCoarsenedCorrectedRms": 3.908451864622847E-05,+ "maximumTangentialResidual": 0.0005605357303746075+ },+ "honesty": "No improved global normal-tail or Hausdorff claim is made without a residual-aware globally coarsened remesh."+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/representation-compression.json b/docs/geometry/artifacts/bunny-m3/representation-compression.jsonnew file mode 100644index 00000000..e463f675--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/representation-compression.json@@ -0,0 +1,12 @@+{+ "sourceTriangles": 69451,+ "m2Panels": 34692,+ "m3PairAtlasPanels": 34725,+ "m3StructuralCandidates": 34209,+ "residualControls": 414,+ "derivedCanonicalCells": 34726,+ "sourceTrianglesPerStructuralPanel": 2.0301967318541903,+ "m2PanelsPerM3Panel": 1.0141190914671578,+ "sourceMeshBytes": 3033195,+ "m3ResidualBytesEstimate": 3312+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/residual-field-summary.json b/docs/geometry/artifacts/bunny-m3/residual-field-summary.jsonnew file mode 100644index 00000000..e53d5e86--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/residual-field-summary.json@@ -0,0 +1,19 @@+{+ "offsetType": "bounded 3 x 3 piecewise-bilinear scalar grid along base unit normal",+ "normalType": "bounded piecewise-bilinear explicit target-normal grid; differential-only authority",+ "domain": "authored base Panel rectangular ParametricDomain",+ "evidence": "Sampled closest-point projection with explicit normal/tangential decomposition",+ "seamPolicy": "zero scalar offset at structural seams in the bounded coarsening stage",+ "residualMappedPanels": 46,+ "controls": 414,+ "storageBytesEstimate": 3312,+ "baseRms": 0.00011796580274291358,+ "correctedRms": 0.00011752668947007265,+ "offsetRms": 9.273715938744762E-06,+ "offsetMaximum": 8.100835810594908E-05,+ "maximumTangentialResidual": 0.0005605357303746075,+ "authority": {+ "offset": "moves reconstructed geometry",+ "normal": "never moves geometry; interpreted differential/shading normal only"+ }+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/singularity-summary.json b/docs/geometry/artifacts/bunny-m3/singularity-summary.jsonnew file mode 100644index 00000000..498253ac--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/singularity-summary.json@@ -0,0 +1,10 @@+{+ "m2": 1603,+ "m3": 1603,+ "cancelled": 0,+ "retainedFeatureFaces": 6946,+ "retainedBoundaryFaces": 221,+ "globalIndexPreserved": true,+ "uncertainCases": 1603,+ "note": "Retained cases remain heuristic winding evidence; no certification is claimed."+}\ No newline at end of filediff --git a/docs/geometry/artifacts/bunny-m3/validation-report.json b/docs/geometry/artifacts/bunny-m3/validation-report.jsonnew file mode 100644index 00000000..445ab537--- /dev/null+++ b/docs/geometry/artifacts/bunny-m3/validation-report.json@@ -0,0 +1,308 @@+{+ "milestone": "AETHERIS-BUNNY-M3",+ "status": "MeaningfulProgression",+ "source": {+ "vertexCount": 35947,+ "triangleCount": 69451,+ "connectedComponents": 1,+ "boundaryEdgeCount": 223,+ "boundaryLoopCount": 5,+ "nonManifoldEdgeCount": 0,+ "degenerateTriangleCount": 0,+ "duplicateTriangleCount": 0,+ "inconsistentlyOrientedEdgeCount": 0,+ "nonFiniteVertexCount": 0,+ "surfaceArea": 0.05712878347791955,+ "signedVolume": 0.0007700565241248492,+ "bounds": {+ "minimum": {+ "x": -0.0946899,+ "y": 0.0329874,+ "z": -0.0618736+ },+ "maximum": {+ "x": 0.0610091,+ "y": 0.187321,+ "z": 0.0587997+ },+ "size": {+ "x": 0.15569899999999998,+ "y": 0.1543336,+ "z": 0.12067330000000001,+ "lengthSquared": 0.06262308402285,+ "length": 0.2502460469674796+ },+ "center": {+ "x": -0.0168404,+ "y": 0.1101542,+ "z": -0.0015369499999999987+ }+ },+ "orientationConsistent": true,+ "boundaryLoops": [+ [+ 1884,+ 18288,+ 18839,+ 20618,+ 21207,+ 1969,+ 18741,+ 18740,+ 13564,+ 21116,+ 21115,+ 21114,+ 21113,+ 19910,+ 34384,+ 34521,+ 34649,+ 34777,+ 34907,+ 35036,+ 35165,+ 18299,+ 1884+ ],+ [+ 31771,+ 31772,+ 31879,+ 31880,+ 31982,+ 31983,+ 32084,+ 32085,+ 32186,+ 32187,+ 32188,+ 32290,+ 32291,+ 32395,+ 32396,+ 32502,+ 32503,+ 32613,+ 32728,+ 32841,+ 32950,+ 33057,+ 33056,+ 32949,+ 32840,+ 32727,+ 32612,+ 32611,+ 32501,+ 32500,+ 32394,+ 32393,+ 32289,+ 32288,+ 32287,+ 32185,+ 32184,+ 32083,+ 32082,+ 31981,+ 31980,+ 31878,+ 31771+ ],+ [+ 31822,+ 31823,+ 31824,+ 31825,+ 31826,+ 31827,+ 31828,+ 31829,+ 31928,+ 31929,+ 31930,+ 32028,+ 32029,+ 32127,+ 32228,+ 32330,+ 32434,+ 32541,+ 32653,+ 32774,+ 32773,+ 32772,+ 32771,+ 32770,+ 32769,+ 32768,+ 32767,+ 32652,+ 32651,+ 32650,+ 32540,+ 32539,+ 32433,+ 32329,+ 32227,+ 32126,+ 32026,+ 32027,+ 31927,+ 31822+ ],+ [+ 32710,+ 32711,+ 32712,+ 32713,+ 32714,+ 32715,+ 32716,+ 32717,+ 32830,+ 32831,+ 32832,+ 32941,+ 32942,+ 33049,+ 33155,+ 33260,+ 33370,+ 33483,+ 33601,+ 33727,+ 33726,+ 33725,+ 33724,+ 33857,+ 33856,+ 33855,+ 33854,+ 33853,+ 33852,+ 33723,+ 33722,+ 33600,+ 33482,+ 33369,+ 33259,+ 33154,+ 33048,+ 32940,+ 32828,+ 32829,+ 32710+ ],+ [+ 33772,+ 33773,+ 33774,+ 33775,+ 33908,+ 33907,+ 33906,+ 34040,+ 34039,+ 34174,+ 34173,+ 34172,+ 34309,+ 34308,+ 34307,+ 34444,+ 34443,+ 34442,+ 34578,+ 34577,+ 34576,+ 34703,+ 34702,+ 34701,+ 34828,+ 34827,+ 34826,+ 34825,+ 34824,+ 34823,+ 34822,+ 34821,+ 34820,+ 34819,+ 34818,+ 34817,+ 34688,+ 34687,+ 34686,+ 34557,+ 34556,+ 34418,+ 34417,+ 34278,+ 34279,+ 34280,+ 34419,+ 34420,+ 34558,+ 34559,+ 34560,+ 34689,+ 34690,+ 34691,+ 34692,+ 34693,+ 34694,+ 34695,+ 34696,+ 34697,+ 34698,+ 34699,+ 34700,+ 34573,+ 34574,+ 34575,+ 34439,+ 34440,+ 34441,+ 34304,+ 34305,+ 34306,+ 34169,+ 34170,+ 34171,+ 34036,+ 34037,+ 34038,+ 33904,+ 33905,+ 33772+ ]+ ],+ "diagnostics": [+ {+ "code": 6,+ "severity": "Evidence",+ "message": "Source has 223 open boundary edges.",+ "sourceElement": null,+ "evidenceClass": "Sampled"+ }+ ]+ },+ "globalPairAtlas": {+ "panels": 34725,+ "transitions": 1,+ "cracks": 0,+ "loops": 5,+ "nonManifold": 0,+ "valid": "Pass"+ },+ "nativeBoundedPatchPlaneProxyClosed": true,+ "residualAuthorityFixtures": true,+ "coarsenedAtlas": {+ "panels": 34209,+ "globallyLowered": false+ },+ "success": false,+ "nextBlocker": "general multi-Panel chart parameterization and authoritative shared residual-boundary construction; the current bounded pair coarsener cannot yet replace the globally valid pair atlas"+}\ No newline at end of filediff --git a/docs/geometry/surface-reconstruction.md b/docs/geometry/surface-reconstruction.mdindex fe24d00f..69791263 100644--- a/docs/geometry/surface-reconstruction.md+++ b/docs/geometry/surface-reconstruction.md@@ -16,6 +16,8 @@ Separatrix / Quad Layout GraphQuadAtlas↓ transfinite [0,1]² parameterizationStrict BoundaryPatch Panel Network+ ↓ structural support + admitted offset/normal residual fields+Residual-aware bounded patch evaluation↓ shared seam samplingSurfaceMeshIR```@@ -53,19 +55,39 @@ This makes the residual/complexity trade explicit and deterministic. Candidate sM2 also uses `JudgmentEngine` when one triangle has multiple admissible dual-graph routes into a four-sided chart. Hard rejection establishes two distinct faces, four distinct corners, a closed disk boundary, finite positive area, and a non-folded center before utility is considered. Admissible routes use dimensionless cross-field alignment (0.50), boundary shape quality (0.35), and source-normal compatibility (0.15). Boundary-loop preservation, seam incidence, four-side closure, and foldover rejection remain deterministic invariants; scoring cannot override them.+M3 uses exact Edmonds blossom matching after those geometric hard filters. Judgment continues to rank geometric alternatives; it does not replace the graph algorithm. Structural merge representation is a separate Judgment decision between base support and a sampled scalar offset grid after closest-point residual decomposition. Manifoldness, source-loop preservation, foldovers, and seam incidence remain hard invariants.+## Segmentation is not an atlas> Geometric chart segmentation and quadrilateral surface parameterization are separate problems. M0 solved the former approximately; M2 introduces the latter.The 333 Bunny M0 regions answer which triangles share a geometric fit. Only 78 have four connected boundary-side components; the others cannot truthfully populate `South/East/North/West`. `QuadAtlas` instead owns four ordered seam uses, four corners, disk topology, a non-folded rectangular parameterization, singularity evidence, and source-boundary correspondence. `PanelIr` is unchanged: an unresolved triangle remains a typed transition rather than an arbitrary N-sided Panel.-## M2 convergence status+## Structural support and residual detail++M3 introduces reconstruction-owned `SurfaceResidualField`. Its scalar `BilinearScalarField` stores bounded piecewise-bilinear displacement along the base unit normal and has positional authority for reconstructed geometry. `BilinearNormalField` stores explicit target normals with `DifferentialInterpretationOnly` authority and cannot move a point. Both carry an authored parameter domain, evidence kind, provenance, error statistics, and an explicit seam policy; neither uses an image texture as authority.++Residual extraction calls the bounded Geometry closest-point query, retains the base `(u,v)`, and decomposes the source residual into signed normal and explicit tangential components. Scalar offset admission is rejected when tangential residual is too large. Corrected geometric normals come from displaced surface derivatives; a normal-only correction remains a separate interpreted normal.++`SurfaceMeshIR` now has a domain-neutral `ISurfaceMeshBoundedPatch` first-jet adapter. Quad-atlas lowering carries the actual authored `BoundaryPatch` through that adapter instead of manufacturing a plane support. An optional residual identity is retained on `SurfacePatch`. Shared corrected corners must agree within an explicit tolerance or lowering rejects them; it does not weld disagreements.++## M3 convergence status++M3 removes two M2 blockers completely. Deterministic blossom matching reduces Bunny transitions from 67 to one; because the source contains 69,451 triangles, one unmatched face is the mathematical lower bound for pair-only matching. The canonical native-bounded-patch `SurfaceMeshDocument` has 34,725 quads, one typed transition, zero internal cracks, five intentional holes, zero non-manifold edges, and passes validation. All strict quad cells use the real bounded patch carrier; the plane-proxy count is zero.++The residual model, extraction semantics, corrected evaluation, zero/shared seam policies, normal-only authority separation, merge/crease fixtures, and residual-aware lowering are implemented and tested. A bounded Bunny merge-pressure audit exactly projects the 1,000 smoothest best-neighbor proposals. It admits 516 disjoint two-Panel unions, giving 34,209 structural candidates in this deliberately partial pass; 24,392 proposals are explicitly deferred. Forty-six admitted unions choose residual grids. This is evidence that coarsening works, not a claim that the final compact atlas has been recovered.++Cross-field relaxation preserved the detected global index but admitted no Bunny smoothing iteration because the first proposal did not reduce the 1,603 detected defects under the hard acceptance rule. Parameter distortion likewise remains essentially M2-level. Therefore M3 is **Meaningful Progression**, not Success: the coarsened candidates are not installed as the canonical atlas, and the singularity count has not improved.++The next blocker is batched/cached projection and general multi-Panel four-sided parameterization that constructs one authoritative global seam network, including reconciled residual boundary samples. Without that, repeatedly merging local pairs would either be prohibitively slow or risk inventing incompatible chart boundaries. Canonical compact evidence is in [the Bunny M3 artifact directory](artifacts/bunny-m3/README.md).++## M2 convergence status (historical)M2 recovers discrete cross-field singularity evidence by quarter-turn winding around ordered incident-face loops and consolidates adjacent same-sign candidates through source-edge adjacency. A deterministic field-scored matching of the triangle dual graph creates genuine four-sided charts; bounded alternating paths improve coverage without making a false maximum-matching claim. Straight source-edge authorities feed a Coons boundary patch, which reduces to a bilinear non-rational support and maps coherently to `[0,1]²` without foldovers.On the canonical Bunny, this produces 34,692 strict four-boundary `PanelIr` objects and a 99.807% quad mesh. The complete mixed lowering has zero internal cracks, preserves all five intentional holes, has zero non-manifold edges, and passes `SurfaceMeshIR` validation. Sixty-seven source triangles remain explicit residual transitions. Consequently the milestone is **Meaningful Progression**, not full success: the canonical document still includes those transitions and is not yet exclusively `QuadAtlas → strict Panel network → SurfaceMeshIR`.-The next blocker is a globally complete cross-field layout optimizer (in matching terms, blossom-capable/global rerouting rather than longer local augmenting paths), followed by a richer `SurfaceMeshIR` support carrier for non-planar `BoundaryPatch` geometry. Current `SurfaceMeshIR` stores a plane support proxy for each non-planar strict Panel cell and records that approximation in `PlanarPlannerPath`; the strict `PanelIr` remains the geometry authority.+At M2, the next blockers were a blossom-capable layout optimizer and a richer `SurfaceMeshIR` support carrier for non-planar `BoundaryPatch` geometry. M3 closes both: the statement below is retained only as historical context for the M2 artifact.Canonical compact evidence is in [the Bunny M2 artifact directory](artifacts/bunny-m2/README.md).diff --git a/tools/Aetheris.BunnyM3/Aetheris.BunnyM3.csproj b/tools/Aetheris.BunnyM3/Aetheris.BunnyM3.csprojnew file mode 100644index 00000000..46402252--- /dev/null+++ b/tools/Aetheris.BunnyM3/Aetheris.BunnyM3.csproj@@ -0,0 +1,4 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>+ <ItemGroup><ProjectReference Include="..\..\Aetheris.Reconstruction\Aetheris.Reconstruction.csproj" /><ProjectReference Include="..\..\Aetheris.Geometry\Aetheris.Geometry.csproj" /></ItemGroup>+</Project>diff --git a/tools/Aetheris.BunnyM3/Program.cs b/tools/Aetheris.BunnyM3/Program.csnew file mode 100644index 00000000..39374f28--- /dev/null+++ b/tools/Aetheris.BunnyM3/Program.cs@@ -0,0 +1,63 @@+using System.Diagnostics;+using System.Security.Cryptography;+using System.Text.Json;+using Aetheris.Geometry;+using Aetheris.Reconstruction;++var root = FindRoot();+var sourcePath = Path.GetFullPath(args.Length > 0 ? args[0] : Path.Combine(root, ".tmp", "bunny-m0-source", "bunny", "reconstruction", "bun_zipper.ply"));+var output = Path.GetFullPath(args.Length > 1 ? args[1] : Path.Combine(root, "docs", "geometry", "artifacts", "bunny-m3"));+if (!File.Exists(sourcePath)) throw new FileNotFoundException("Canonical Stanford Bunny PLY was not found.", sourcePath);+Directory.CreateDirectory(output); var total = Stopwatch.StartNew(); var watch = Stopwatch.StartNew(); var timings = new SortedDictionary<string, double>();+await using var stream = File.OpenRead(sourcePath); var mesh = PlyTriangleSurfaceLoader.LoadAscii(stream, "bunny/reconstruction/bun_zipper.ply", new Dictionary<string,string>{{"path",sourcePath}}); timings["sourceLoad"] = Lap();+var sourceValidation = TriangleSurfaceValidator.Validate(mesh); timings["sourceValidation"] = Lap();+var (rawField, rawSummary) = StructuredSurfaceRecovery.EstimateField(mesh); timings["crossField"] = Lap();+var (field, regularization) = CrossFieldRegularizer.Regularize(mesh, rawField, 8); timings["fieldRegularization"] = Lap();+var atlas = QuadAtlasRecovery.Build(mesh, field); timings["globalLayoutAndPanelFit"] = Lap();+var canonical = QuadAtlasSurfaceMeshLowering.Lower(mesh, atlas); timings["nativeBoundedPatchLowering"] = Lap();+var coarsening = StructuralPanelCoarsener.Coarsen(mesh, atlas); timings["boundedPairCoarseningAndResidualExtraction"] = Lap();++var boundaryPanels = atlas.Charts.Count(chart => chart.OrderedSides.Any(use => atlas.Seams.Single(seam => seam.StableId == use.SeamId).IsSourceBoundary));+var singularVertices = atlas.Singularities.SelectMany(x => x.SourceVertices).ToHashSet(); var topologyPanels = atlas.Charts.Count(chart => chart.CornerVertices.Any(singularVertices.Contains));+var parameterPanels = atlas.Charts.Count(chart => chart.AngleDistortionDegrees >= 75); var mergeSourcePanels = coarsening.MergedPairCount * 2;+var classifications = new Dictionary<string,int>+{+ ["real topology / detected singularity proximity"] = topologyPanels,+ ["source boundary"] = boundaryPanels,+ ["parameterization limitation (angle distortion >= 75 degrees)"] = parameterPanels,+ ["likely removable through admitted bounded merge"] = mergeSourcePanels,+ ["local triangle-pairing artifact / unproven necessity"] = Math.Max(0, atlas.Charts.Count - new[]{topologyPanels,boundaryPanels,parameterPanels,mergeSourcePanels}.Max())+};+Write("m2-oversegmentation-audit.json", new { m2Panels=34692, measuredM3PairPanels=atlas.Charts.Count, classificationsAreOverlapping=true, classifications, explanation="M2 creates exactly one Panel per matched adjacent triangle pair; panel existence therefore follows source face density before topology, feature, or residual necessity is tested.", mergePressure=new{neighborPairs=atlas.Seams.Count(x=>x.ChartUses.Count==2),admittedPairs=coarsening.MergedPairCount,coarsening.RejectedTopology,coarsening.RejectedFeature,coarsening.RejectedParameterization,coarsening.RejectedResidual}, representatives=coarsening.RepresentativeDecisions.Take(20)});+Write("field-regularization-summary.json", regularization);+Write("singularity-summary.json", new { m2=1603,m3=regularization.OutputSingularities,cancelled=regularization.CancelledNet,regularization.RetainedFeatureFaces,regularization.RetainedBoundaryFaces,regularization.GlobalIndexPreserved,uncertainCases=regularization.OutputSingularities, note="Retained cases remain heuristic winding evidence; no certification is claimed." });+Write("global-layout-summary.json", new { algorithm="deterministic Edmonds blossom maximum-cardinality matching after hard disk/four-corner/foldover filtering",transitionTrianglesBefore=67,transitionTrianglesAfter=atlas.UnresolvedTriangles.Count,parityLowerBound=mesh.Triangles.Count%2,explanation="An odd source face count makes zero impossible for pair-only layout; eliminating the last transition requires a larger chart operation.",additionalMatchedPairs=atlas.Charts.Count-34692,transitionFacesRemoved=67-atlas.UnresolvedTriangles.Count,meanFieldDeviationDegrees=Mean(atlas.Seams.Select(x=>x.FieldDeviationDegrees)),atlas.DeterministicHash,judgment="Judgment scores geometric options before the exact graph stage; it does not replace matching."});+Write("panel-coarsening-summary.json", new { m2PanelCount=34692,m3PairAtlasPanels=atlas.Charts.Count,structuralPanelCount=coarsening.Panels.Count,coarsening.MergedPairCount,coarsening.MergeRatio,coarsening.ExactCandidateCount,coarsening.DeferredCandidateCount,averageM2PanelsPerStructuralPanel=34692d/coarsening.Panels.Count,sourceTrianglesPerStructuralPanel=mesh.Triangles.Count/(double)coarsening.Panels.Count,globallyLowerable=false,scope="bounded audit of the 1,000 smoothest best-neighbor proposals; disjoint two-Panel unions only",nextBlocker="batched/cached projection followed by arbitrary multi-chart four-sided parameterization plus global residual seam reconciliation" });+var mapped = coarsening.Panels.Where(x=>x.ResidualField is not null).ToArray();+Write("residual-field-summary.json", new { offsetType="bounded 3 x 3 piecewise-bilinear scalar grid along base unit normal",normalType="bounded piecewise-bilinear explicit target-normal grid; differential-only authority",domain="authored base Panel rectangular ParametricDomain",evidence="Sampled closest-point projection with explicit normal/tangential decomposition",seamPolicy="zero scalar offset at structural seams in the bounded coarsening stage",residualMappedPanels=mapped.Length,controls=mapped.Sum(x=>x.ResidualField!.ControlCount),storageBytesEstimate=mapped.Sum(x=>x.ResidualField!.ControlCount)*sizeof(double),baseRms=Rms(mapped.Select(x=>x.BaseRms)),correctedRms=Rms(mapped.Select(x=>x.CorrectedRms)),offsetRms=Rms(mapped.SelectMany(x=>GridValues(x.ResidualField!.PositionOffset!))),offsetMaximum=Max(mapped.SelectMany(x=>GridValues(x.ResidualField!.PositionOffset!))),maximumTangentialResidual=Max(mapped.Select(x=>x.MaximumTangentialResidual)),authority=new{offset="moves reconstructed geometry",normal="never moves geometry; interpreted differential/shading normal only"} });+var m2Parameter = new { mean=51.69,p95=85.11,maximum=89.99 }; var m3Angles=atlas.Charts.Select(x=>x.AngleDistortionDegrees).ToArray();+Write("parameterization-summary.json", new { m2=m2Parameter,m3=new{mean=Mean(m3Angles),p95=P(m3Angles,.95),maximum=Max(m3Angles),aspectMean=Mean(atlas.Charts.Select(x=>x.AspectRatio)),aspectP95=P(atlas.Charts.Select(x=>x.AspectRatio),.95),aspectMaximum=Max(atlas.Charts.Select(x=>x.AspectRatio)),foldovers=atlas.Charts.Sum(x=>x.Foldovers)},method="four-corner Coons/bilinear; bounded pair coarsening does not yet solve arbitrary multi-chart UV relaxation",improvedMaterially=false });+Write("continuity-summary.json", new { internalCracks=canonical.InternalCrackGroups,intentionalOpenLoops=canonical.IntentionalOpenBoundaryLoops,canonical.NonManifoldEdgeCount,residualSeamPolicy="shared corrected corner position within explicit tolerance; disagreement rejects lowering; bounded coarsener fits zero seam offsets",coarsenedAtlasGloballyReconciled=false });+Write("mesh-summary.json", new { vertices=canonical.Document.Vertices.Count,cells=canonical.QuadCount+canonical.TriangleCount,quads=canonical.QuadCount,triangles=canonical.TriangleCount,nGons=0,quadPercentage=100d*canonical.QuadCount/(canonical.QuadCount+canonical.TriangleCount),canonical.InternalCrackGroups,intentionalLoops=canonical.IntentionalOpenBoundaryLoops,canonical.NonManifoldEdgeCount,validation=canonical.ValidationStatus,nativeBoundedPatchSupports=canonical.Document.Patches.Count(x=>x.Support.Kind==Aetheris.Kernel.Core.Brep.Tessellation.SurfaceMeshSupportKind.BoundedParametricPatch),planeProxyCount=canonical.Document.Patches.Count(x=>x.ChartId?.StartsWith("quad-")==true&&x.Support.Kind==Aetheris.Kernel.Core.Brep.Tessellation.SurfaceMeshSupportKind.Plane),canonical.DeterministicHash,authority="globally valid pair atlas; coarsened diagnostic atlas is not substituted until its global seam network exists" });+Write("quality-comparison.json", new { m2=new{sourcePanelRms=.00006273042597053603,remeshSourceRms=.000030452953532103108,normalMeanDegrees=4.2433,normalRmsDegrees=14.7434,normalMaxDegrees=90},m3=new{positionAndNormalCanonicalReevaluation="not repeated: native support changes carrier, not authored Panel geometry",representativeCoarsenedBaseRms=Rms(coarsening.Panels.Where(x=>x.SourceChartIds.Count>1).Select(x=>x.BaseRms)),representativeCoarsenedCorrectedRms=Rms(coarsening.Panels.Where(x=>x.SourceChartIds.Count>1).Select(x=>x.CorrectedRms)),maximumTangentialResidual=Max(coarsening.Panels.Select(x=>x.MaximumTangentialResidual))},honesty="No improved global normal-tail or Hausdorff claim is made without a residual-aware globally coarsened remesh." });+Write("representation-compression.json", new { sourceTriangles=mesh.Triangles.Count,m2Panels=34692,m3PairAtlasPanels=atlas.Charts.Count,m3StructuralCandidates=coarsening.Panels.Count,residualControls=mapped.Sum(x=>x.ResidualField!.ControlCount),derivedCanonicalCells=canonical.QuadCount+canonical.TriangleCount,sourceTrianglesPerStructuralPanel=mesh.Triangles.Count/(double)coarsening.Panels.Count,m2PanelsPerM3Panel=34692d/coarsening.Panels.Count,sourceMeshBytes=new FileInfo(sourcePath).Length,m3ResidualBytesEstimate=mapped.Sum(x=>x.ResidualField!.ControlCount)*sizeof(double) });+Write("judgment-summary.json", new { uses=new[]{new{decision="adjacent-face quad route",hardConstraints="disk/four corners/nonfolded",score="field .50 + shape .35 + normal .15",candidateCount=atlas.JudgmentTraces.Sum(x=>x.CandidateCount),winner="trace-specific"},new{decision="base-only versus scalar offset grid",hardConstraints="tangential residual and bounded error",score="error - representation complexity",candidateCount=2*coarsening.MergedPairCount,winner="per admitted merge"}},exactAlgorithms=new[]{"Edmonds blossom for maximum-cardinality layout","Edmonds blossom for disjoint merge selection"},notJudgment=new[]{"manifoldness","boundary-loop count","seam incidence","foldover legality"} });+timings["diagnosticsAggregationAndSerialization"] = Lap(); timings["total"] = total.Elapsed.TotalMilliseconds; Write("performance.json",new{timingsMilliseconds=timings,workingSetBytes=Environment.WorkingSet});+var success = false; Write("validation-report.json",new{milestone="AETHERIS-BUNNY-M3",status="MeaningfulProgression",source=sourceValidation,globalPairAtlas=new{panels=atlas.Charts.Count,transitions=atlas.UnresolvedTriangles.Count,cracks=canonical.InternalCrackGroups,loops=canonical.IntentionalOpenBoundaryLoops,nonManifold=canonical.NonManifoldEdgeCount,valid=canonical.ValidationStatus},nativeBoundedPatchPlaneProxyClosed=canonical.Document.Patches.Where(x=>x.ChartId?.StartsWith("quad-")==true).All(x=>x.Support.Kind==Aetheris.Kernel.Core.Brep.Tessellation.SurfaceMeshSupportKind.BoundedParametricPatch),residualAuthorityFixtures=true,coarsenedAtlas=new{panels=coarsening.Panels.Count,globallyLowered=false},success,nextBlocker="general multi-Panel chart parameterization and authoritative shared residual-boundary construction; the current bounded pair coarsener cannot yet replace the globally valid pair atlas"});+File.WriteAllText(Path.Combine(output,"README.md"),"""+# AETHERIS-BUNNY-M3 evidence++M3 separates structural `PanelIr` support from sampled scalar offset and differential-only normal fields, replaces the SurfaceMeshIR plane proxy with a native bounded parametric evaluator, and replaces M2's local matching with deterministic Edmonds blossom matching.++The canonical run is **Meaningful Progression**, not Success. The global pair atlas is crack-free and has one parity-forced transition. The bounded coarsener demonstrates fewer structural Panels and residual representation on admitted two-Panel unions, but those unions are not yet installed as the canonical atlas because arbitrary multi-chart parameterization and globally authoritative residual seam construction remain unresolved.++Reproduce with `dotnet run --project tools/Aetheris.BunnyM3 -c Release -- .tmp/bunny-m0-source/bunny/reconstruction/bun_zipper.ply docs/geometry/artifacts/bunny-m3`.+""");+var files=Directory.GetFiles(output).Where(x=>Path.GetFileName(x)!="manifest.json"&&Path.GetFileName(x)!="performance.json").OrderBy(Path.GetFileName,StringComparer.Ordinal).Select(x=>new{path=Path.GetFileName(x),sha256=Sha(File.ReadAllBytes(x)),bytes=new FileInfo(x).Length,lines=File.ReadLines(x).Count()}).ToArray();+Write("manifest.json",new{milestone="AETHERIS-BUNNY-M3",sourceMeshHash=mesh.DeterministicHash,atlasHash=atlas.DeterministicHash,surfaceMeshHash=canonical.DeterministicHash,deterministic=true,excludedObservationalFiles=new[]{"performance.json"},files});+Console.WriteLine(JsonSerializer.Serialize(new{status="MeaningfulProgression",atlasPanels=atlas.Charts.Count,structuralCandidates=coarsening.Panels.Count,residualMapped=mapped.Length,transitions=atlas.UnresolvedTriangles.Count,singularities=regularization.OutputSingularities,loops=canonical.IntentionalOpenBoundaryLoops,cracks=canonical.InternalCrackGroups,nonManifold=canonical.NonManifoldEdgeCount,totalMilliseconds=total.Elapsed.TotalMilliseconds}));++double Lap(){var value=watch.Elapsed.TotalMilliseconds;watch.Restart();return value;} void Write(string name,object value)=>File.WriteAllText(Path.Combine(output,name),JsonSerializer.Serialize(value,new JsonSerializerOptions{WriteIndented=true,PropertyNamingPolicy=JsonNamingPolicy.CamelCase,IncludeFields=true}));+static double Mean(IEnumerable<double> values){var a=values.ToArray();return a.Length==0?0:a.Average();} static double Rms(IEnumerable<double> values){var a=values.ToArray();return a.Length==0?0:Math.Sqrt(a.Average(x=>x*x));} static double Max(IEnumerable<double> values)=>values.DefaultIfEmpty(0).Max(); static double P(IEnumerable<double> values,double p){var a=values.Order().ToArray();return a.Length==0?0:a[(int)Math.Clamp(Math.Ceiling(p*a.Length)-1,0,a.Length-1)];}+static IEnumerable<double> GridValues(BilinearScalarField field){for(var i=0;i<field.CountU;i++)for(var j=0;j<field.CountV;j++)yield return field[i,j];} static string Sha(byte[] bytes)=>Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();+static string FindRoot(){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??Directory.GetCurrentDirectory();}