Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Improve threaded HexBolt repair and STEP geometry sharing

Yuechen Li6e6a5d678740
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index a9654a5d..7ebb17c6 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -2769,7 +2769,8 @@ Model CanonicalPanel {
}
var exportOptions = canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata
- ? Aetheris.Kernel.Core.Step242.Step242ExportOptions.FromSourceMetadata(Aetheris.Kernel.Core.Step242.Step242SourceMetadataReader.Read(stepText))
+ ? Aetheris.Kernel.Core.Step242.Step242ExportOptions.FromSourceMetadata(Aetheris.Kernel.Core.Step242.Step242SourceMetadataReader.Read(stepText),
+ Aetheris.Kernel.Core.Step242.BrepExportPreflightPolicy.TrustedProductionRoute)
: new Aetheris.Kernel.Core.Step242.Step242ExportOptions();
var exportResult = Aetheris.Kernel.Core.Step242.Step242Exporter.ExportBody(importResult.Value, exportOptions);
@@ -4725,6 +4726,8 @@ Model CanonicalPanel {
stdout.WriteLine($"Input file: {analysis.StepPath}");
stdout.WriteLine("Success: yes");
stdout.WriteLine($"Structural assessment: {summary.StructuralAssessment} ({summary.StructuralAssessmentBasis})");
+ if (summary.ImportQualification is { } qualification)
+ stdout.WriteLine($"Import qualification: {qualification.Status}; geometry={qualification.GeometryStatus}; display not assessed; missing pcurves={qualification.MissingPcurves}.");
stdout.WriteLine($"Length unit: {summary.LengthUnit} ({summary.LengthUnitBasis})");
stdout.WriteLine($"Bodies: {summary.BodyCount}");
stdout.WriteLine($"Shells: {summary.ShellCount}");
@@ -4875,6 +4878,11 @@ Model CanonicalPanel {
minimum = new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) },
maximum = new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) }
},
+ importStatus = structure.Definitions.Where(d => d.Geometry is not null)
+ .Select(d => d.Geometry!.ImportQualification?.Status ?? Aetheris.Kernel.Core.Import.ImportQualificationStatus.Inspectable)
+ .DefaultIfEmpty(Aetheris.Kernel.Core.Import.ImportQualificationStatus.Failed).Max().ToString(),
+ importQualifications = structure.Definitions.Where(d => d.Geometry is not null)
+ .Select(d => new { d.StableId, Qualification = d.Geometry!.ImportQualification }),
performance = structure.Performance,
semanticPmi = Step242SemanticPmiInspector.Inspect(stepText),
definitions = structure.Definitions.Select(item => new { item.StableId, item.Name, hasGeometry = item.Geometry is not null, item.ProductDefinitionEntityId }).ToArray(),
diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.cs
index 3ced652b..5c5a4f43 100644
--- a/Aetheris.CLI/StepAnalysisModels.cs
+++ b/Aetheris.CLI/StepAnalysisModels.cs
@@ -29,7 +29,8 @@ public sealed record AnalyzeSummary(
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] FaceOrientationSummary? FaceOrientation = null,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] BoundaryTopologySummary? BoundaryTopology = null,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SplineRecoverySummary? SplineRecovery = null,
- [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PcurveQualificationSummary? PcurveQualification = null);
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PcurveQualificationSummary? PcurveQualification = null,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] Aetheris.Kernel.Core.Import.BrepImportQualificationReport? ImportQualification = null);
public sealed record PcurveQualificationSummary(
string Status,
@@ -117,7 +118,8 @@ public sealed record AnalyzeResult(
EdgeDetail? Edge,
VertexDetail? Vertex,
IReadOnlyList<string> Notes,
- Step242SemanticPmiInspectionResult? SemanticPmi = null);
+ Step242SemanticPmiInspectionResult? SemanticPmi = null,
+ string? Schema = null);
public sealed record CompoundSolidInspection(
int Ordinal,
@@ -129,7 +131,8 @@ public sealed record CompoundSolidInspection(
bool VolumeExact,
IReadOnlyDictionary<string, int> SurfaceFamilies,
Point3D PlacementCenter,
- Vector3D OffsetFromFirst);
+ Vector3D OffsetFromFirst,
+ Aetheris.Kernel.Core.Import.BrepImportQualificationReport? ImportQualification = null);
public sealed record CompoundAnalysisResult(
string StepPath,
diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.cs
index 79b85d77..5232d1b0 100644
--- a/Aetheris.CLI/StepAnalyzer.cs
+++ b/Aetheris.CLI/StepAnalyzer.cs
@@ -42,7 +42,8 @@ public sealed record VolumeAnalysisResult(
var stepText = File.ReadAllText(fullPath);
var analysis = AnalyzeImportedBody(body, fullPath, faceId, edgeId, vertexId) with
{
- SemanticPmi = Step242SemanticPmiInspector.Inspect(stepText)
+ SemanticPmi = Step242SemanticPmiInspector.Inspect(stepText),
+ Schema = Step242SourceMetadataReader.Read(stepText).FileSchema
};
if (analysis.Face is null) return analysis;
@@ -75,7 +76,7 @@ public sealed record VolumeAnalysisResult(
var exact = mass.Status != Aetheris.Kernel.Core.Brep.Verification.BrepMassPropertiesStatus.Unavailable
&& mass.IsEnclosed && mass.IsOrientationConsistent;
entries.Add(new(index + 1, root.StepEntityId, root.StepEntityKind, root.Body.Topology.Bodies.Count(), summary.BoundingBox,
- exact ? mass.AbsoluteVolume : null, exact, summary.SurfaceFamilies, center, center - firstCenter.Value));
+ exact ? mass.AbsoluteVolume : null, exact, summary.SurfaceFamilies, center, center - firstCenter.Value, root.Body.ImportQualification));
if (!exact) notes.Add($"Root #{root.StepEntityId} exact volume unavailable: {mass.Status}.");
}
var boxes = entries.Where(entry => entry.BoundingBox is not null).Select(entry => entry.BoundingBox!.Value).ToArray();
@@ -1771,7 +1772,7 @@ public sealed record VolumeAnalysisResult(
new SplineRecoverySummary(analyticEntities, exactSplineEntities, recoveredCurves + recoveredSurfaces,
unsupportedEntities, recoveredCurves, recoveredSurfaces,
recoveredCurves + recoveredSurfaces == 0 ? null : worstDeviation, recoveryTolerance),
- BuildPcurveQualificationSummary(body));
+ BuildPcurveQualificationSummary(body), body.ImportQualification);
}
private static PcurveQualificationSummary BuildPcurveQualificationSummary(BrepBody body)
diff --git a/Aetheris.Kernel.Core.Tests/Brep/BrepHollowRadialCutPatternTests.cs b/Aetheris.Kernel.Core.Tests/Brep/BrepHollowRadialCutPatternTests.cs
index f9485882..cb8ae133 100644
--- a/Aetheris.Kernel.Core.Tests/Brep/BrepHollowRadialCutPatternTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Brep/BrepHollowRadialCutPatternTests.cs
@@ -27,7 +27,8 @@ public sealed class BrepHollowRadialCutPatternTests
Assert.All(tori, torus => Assert.Equal(48, torus.MajorRadius, 8));
Assert.Equal(thickness, tori.Max(t => t.MinorRadius) - tori.Min(t => t.MinorRadius), 8);
var mass = BrepMassProperties.Evaluate(body);
- Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent && mass.SignedVolume > 0);
+ Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent && mass.SignedVolume > 0,
+ $"{mass.Status}; volume={mass.SignedVolume:R}; {string.Join(" | ", mass.Diagnostics)}");
var step = Step242Exporter.ExportBody(body);
Assert.True(step.IsSuccess, string.Join(" | ", step.Diagnostics.Select(d => d.Message)));
var imported = Step242Importer.ImportBody(step.Value);
@@ -73,7 +74,8 @@ public sealed class BrepHollowRadialCutPatternTests
Assert.Equal(7, body.Topology.Faces.Count());
Assert.Equal(4, result.Value.TopologyMap.Loops.Count);
var mass = BrepMassProperties.Evaluate(body);
- Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent && mass.SignedVolume > 0);
+ Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent && mass.SignedVolume > 0,
+ $"{mass.Status}; volume={mass.SignedVolume:R}; {string.Join(" | ", mass.Diagnostics)}");
var step = Step242Exporter.ExportBody(body);
Assert.True(step.IsSuccess, string.Join(" | ", step.Diagnostics.Select(d => d.Message)));
var imported = Step242Importer.ImportBody(step.Value);
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs
index 37ec00e3..4d242b21 100644
--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs
@@ -294,6 +294,11 @@ public sealed class BrepDisplayTessellatorTests
var patch = Assert.Single(result.Value.FacePatches);
Assert.Empty(patch.Positions);
Assert.Empty(patch.TriangleIndices);
+
+ var partial = BrepDisplayTessellator.TessellateBoundedPartial(body);
+ Assert.Empty(Assert.Single(partial.FacePatches).TriangleIndices);
+ Assert.Contains(partial.FaceDiagnostics!, d => d.Code == "Viewer.Tessellation.TrimEvaluationFailed"
+ && d.FaceId == patch.FaceId);
}
[Fact]
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/GeneralTrimMaterializationTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/GeneralTrimMaterializationTests.cs
new file mode 100644
index 00000000..03d365aa
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/GeneralTrimMaterializationTests.cs
@@ -0,0 +1,131 @@
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;
+
+public sealed class GeneralTrimMaterializationTests
+{
+ [Fact]
+ public void GeneralIrBoundaryWithoutLocalChart_RejectsRatherThanInventingAnAverageCentre()
+ {
+ var points = new[] { new Point3D(1, 0, 0), new Point3D(0, 1, 0), new Point3D(-1, 0, 0),
+ new Point3D(0, -1, 0), new Point3D(1, 0, 1) };
+ var vertices = points.Select((p, i) => new SurfaceMeshVertex(i, p)).ToArray();
+ var cylinder = new CylinderSurface(Point3D.Origin, Direction3D.Create(new Vector3D(0, 0, 1)),
+ 1, Direction3D.Create(new Vector3D(1, 0, 0)));
+ var patch = new SurfacePatch(new FaceId(9), new(SurfaceMeshSupportKind.Cylinder, Cylinder: cylinder), [],
+ [new BoundaryPolygonCell([0, 1, 2, 3, 4])], true);
+ var document = new SurfaceMeshDocument(vertices, [patch], [], new(1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, ""));
+ Assert.False(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out _));
+ Assert.Empty(mesh.TriangleIndices);
+ Assert.Equal(points.Length, mesh.Positions.Count);
+ }
+
+ [Fact]
+ public void DisplayClassification_IsIndependentOfSupportAndEngineeringQualification()
+ {
+ Assert.Equal(BoundaryConformingTrimTessellator.TrimClass.RectangularGridLike,
+ BoundaryConformingTrimTessellator.Classify([new() { (0, 0), (1, 0), (1, 1), (0, 1) }], 0));
+ Assert.Equal(BoundaryConformingTrimTessellator.TrimClass.SimpleConvex,
+ BoundaryConformingTrimTessellator.Classify([new() { (0, 0), (1, 0), (.5, 1) }], 0));
+ Assert.Equal(BoundaryConformingTrimTessellator.TrimClass.SimpleConcave,
+ BoundaryConformingTrimTessellator.Classify([new() { (0, 0), (2, 0), (1, .1), (2, 1), (0, 1) }], 0));
+ Assert.Equal(BoundaryConformingTrimTessellator.TrimClass.Pathological,
+ BoundaryConformingTrimTessellator.Classify([new() { (0, 0), (.5, .5), (1, 1) }], 0));
+ }
+
+ [Fact]
+ public void ConcaveCylinderChartAcrossAngularSeam_HasNoCrossingOrDuplicateRegion()
+ {
+ List<(double U, double V)> loop = [(6.2, 0), (6.5, 0), (6.5, 1), (6.35, 1), (6.35, .5), (6.2, .5)];
+ var patch = BoundaryConformingTrimTessellator.TryTessellate(new FaceId(3), [loop], 0,
+ (u, v) => new Point3D(double.Cos(u), double.Sin(u), v),
+ (u, _) => new Vector3D(double.Cos(u), double.Sin(u), 0), .025, .1,
+ DisplayTessellationOptions.Default, null, out var incomplete,
+ grid: (Lines(6.2, 6.5, 12), Lines(0, 1, 10)));
+ Assert.NotNull(patch); Assert.False(incomplete);
+ var area = 0d;
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ {
+ var p = patch.TriangleIndices.Skip(i).Take(3).Select(n => patch.Positions[n]).ToArray();
+ Assert.All(p, point => Assert.InRange(point.X, .976, 1));
+ Assert.InRange((p[1] - p[0]).Length, 0, .11);
+ area += (p[1] - p[0]).Cross(p[2] - p[0]).Length * .5;
+ }
+ Assert.InRange(area, .224, .226); // Exact cylindrical area .225, no duplicated/fill region.
+ }
+
+ [Theory]
+ [InlineData(false, false)]
+ [InlineData(true, false)]
+ [InlineData(false, true)]
+ [InlineData(true, true)]
+ public void LocalDecomposition_PreservesConcavityHoleAreaAndWinding(bool reversed, bool hole)
+ {
+ List<(double U, double V)> outer = [(0, 0), (4, 0), (4, 1), (1, 1), (1, 4), (0, 4)];
+ List<(double U, double V)> inner = [(.2, .2), (.8, .2), (.8, .8), (.2, .8)];
+ if (reversed) { outer.Reverse(); inner.Reverse(); }
+ List<List<(double U, double V)>> loops = [outer];
+ if (hole) loops.Add(inner);
+ var patch = BoundaryConformingTrimTessellator.TryTessellate(new FaceId(42), loops, 0,
+ (u, v) => new Point3D(u, v, 0), (_, _) => new Vector3D(0, 0, 1), .25, .25,
+ DisplayTessellationOptions.Default, null, out var incomplete,
+ grid: (Lines(0, 4, 16), Lines(0, 4, 16)));
+ Assert.NotNull(patch); Assert.False(incomplete); Assert.Equal(new FaceId(42), patch.FaceId);
+ var area = 0d;
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ {
+ var a = patch.Positions[patch.TriangleIndices[i]];
+ var b = patch.Positions[patch.TriangleIndices[i + 1]];
+ var c = patch.Positions[patch.TriangleIndices[i + 2]];
+ var cross = (b - a).Cross(c - a);
+ Assert.True(cross.Z < 0); // Common UV convention; wrapper applies resolved BRep orientation.
+ area += cross.Length * .5;
+ var x = (a.X + b.X + c.X) / 3; var y = (a.Y + b.Y + c.Y) / 3;
+ Assert.False(x > 1 && y > 1);
+ if (hole) Assert.False(x > .2 && x < .8 && y > .2 && y < .8);
+ }
+ Assert.Equal(hole ? 6.64 : 7, area, 8);
+ }
+
+ [Fact]
+ public void WindingStrip_LocalKnotCellsPreventWholeTurnAliasing()
+ {
+ // Redistributable witness: the real failure class is a many-turn support
+ // with a concave almost-rectangular trim, not a vendor-specific solid.
+ List<(double U, double V)> outer = [(0, 0), (1, 0), (1, 1), (.6, 1), (.6, .95), (.4, .95), (.4, 1), (0, 1)];
+ Point3D At(double u, double v) => new((2 + u) * double.Cos(24 * double.Pi * v),
+ (2 + u) * double.Sin(24 * double.Pi * v), 20 * v);
+ var patch = BoundaryConformingTrimTessellator.TryTessellate(new FaceId(7), [outer], 0, At,
+ (_, v) => new Vector3D(double.Cos(24 * double.Pi * v), double.Sin(24 * double.Pi * v), 0),
+ 1d / 12, 1d / 192, DisplayTessellationOptions.Default, null, out var incomplete,
+ maximumTriangles: 65_536, perceptualNormals: true,
+ grid: (Lines(0, 1, 12), Lines(0, 1, 192)));
+ Assert.NotNull(patch); Assert.False(incomplete);
+ Assert.InRange(patch.TriangleIndices.Count / 3, 1, 65_536);
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ {
+ var p = patch.TriangleIndices.Skip(i).Take(3).Select(n => patch.Positions[n]).ToArray();
+ Assert.InRange(p.Max(x => x.Z) - p.Min(x => x.Z), 0, 20d / 192 + 1e-10);
+ }
+ }
+
+ [Fact]
+ public void SelfCrossedAndCollapsedPolygons_AreRejected()
+ {
+ foreach (var loop in new List<(double U, double V)>[] {
+ [(0, 0), (1, 1), (0, 1), (1, 0)], [(0, 0), (.5, .5), (1, 1)] })
+ {
+ string? reason = null;
+ var patch = BoundaryConformingTrimTessellator.TryTessellate(new FaceId(1), [loop], 0,
+ (u, v) => new Point3D(u, v, 0), (_, _) => new Vector3D(0, 0, 1), .1, .1,
+ DisplayTessellationOptions.Default, null, out _, reportFailure: r => reason = r);
+ Assert.Null(patch); Assert.False(string.IsNullOrWhiteSpace(reason));
+ }
+ }
+
+ private static List<double> Lines(double start, double end, int count) =>
+ Enumerable.Range(0, count + 1).Select(i => start + (end - start) * i / count).ToList();
+}
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/RecoveredCylinderTrimMaterializationTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/RecoveredCylinderTrimMaterializationTests.cs
new file mode 100644
index 00000000..ea9874ef
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/RecoveredCylinderTrimMaterializationTests.cs
@@ -0,0 +1,104 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;
+
+public sealed class RecoveredCylinderTrimMaterializationTests
+{
+ [Fact]
+ public void SingleBoundedSector_WithEquivalentPcurveCharts_DoesNotFillTheCylinder()
+ {
+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
+ var support = new CylinderSurface(Point3D.Origin, Direction3D.Create(new Vector3D(0, 0, 1)),
+ 1, Direction3D.Create(new Vector3D(1, 0, 0)));
+ var uv = new[] { (6.2, 0d), (6.4, 0d), (6.4, 2d), (6.2, 2d) };
+ var points = new Dictionary<VertexId, Point3D>();
+ var vertices = uv.Select(p => { var id = builder.AddVertex(); points[id] = support.Evaluate(p.Item1, p.Item2); return id; }).ToArray();
+ var loop = builder.AllocateLoopId(); var uses = uv.Select(_ => builder.AllocateCoedgeId()).ToArray();
+ for (var i = 0; i < 4; i++)
+ {
+ var j = (i + 1) % 4; var edge = builder.AddEdge(vertices[i], vertices[j]);
+ var curveId = new CurveGeometryId(i + 1);
+ var controls = Enumerable.Range(0, 17).Select(k => support.Evaluate(
+ uv[i].Item1 + (uv[j].Item1 - uv[i].Item1) * k / 16d,
+ uv[i].Item2 + (uv[j].Item2 - uv[i].Item2) * k / 16d)).ToArray();
+ geometry.AddCurve(curveId, CurveGeometry.FromBSpline(new BSpline3Curve(1, controls,
+ Enumerable.Range(0, 17).Select(k => k == 0 || k == 16 ? 2 : 1).ToArray(),
+ Enumerable.Range(0, 17).Select(k => k / 16d).ToArray(), "UNSPECIFIED", false, false, "UNSPECIFIED")));
+ bindings.AddEdgeBinding(new(edge, curveId, new ParameterInterval(0, 1)));
+ builder.AddCoedge(new(uses[i], edge, loop, uses[j], uses[(i + 3) % 4], false));
+ }
+ builder.AddLoop(new Loop(loop, uses)); var face = builder.AddFace([loop]); builder.AddBody([builder.AddShell([face])]);
+ var surface = new SurfaceGeometryId(1); geometry.AddSurface(surface, SurfaceGeometry.FromCylinder(support));
+ bindings.AddFaceBinding(new(face, surface));
+ for (var i = 0; i < 4; i++)
+ {
+ var j = (i + 1) % 4;
+ var offset = i is 1 or 2 ? 2d * double.Pi : 0d;
+ bindings.AddPcurveBinding(new(uses[i], face, surface, PcurveGeometry.Line(new(0, 1),
+ new(uv[i].Item1 - offset, uv[i].Item2), new(uv[j].Item1 - offset, uv[j].Item2))));
+ }
+ var body = new BrepBody(builder.Model, geometry, bindings, points);
+ var before = bindings.PcurveBindings.ToArray();
+ var result = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(result.IsSuccess);
+ var patch = Assert.Single(result.Value.FacePatches); Assert.NotEmpty(patch.TriangleIndices);
+ Assert.All(patch.Positions, p => { Assert.True(p.X > .99); Assert.InRange(p.Y, -.084, .117); });
+ Assert.Equal(before, bindings.PcurveBindings.ToArray());
+ }
+
+ [Theory]
+ [InlineData(true, .05, true)]
+ [InlineData(false, .05, false)]
+ [InlineData(true, .02, false)]
+ public void RecoveredBoundaryProjection_IsBoundedByMeasuredDeviationAndDisplayBudget(bool recovered, double chord, bool visible)
+ {
+ var body = CylinderWithHole(recovered);
+ var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body, DisplayTessellationOptions.Default with { ChordTolerance = chord });
+ var patch = Assert.Single(mesh.FacePatches);
+ Assert.Equal(visible, patch.TriangleIndices.Count > 0);
+ Assert.Empty(body.Bindings.PcurveBindings);
+ if (visible)
+ {
+ Assert.All(patch.Positions, p => Assert.InRange(double.Sqrt(p.X * p.X + p.Y * p.Y), 1 - 1e-10, 1 + 1e-10));
+ Assert.All(body.Geometry.Curves, c => Assert.Equal(.04, c.Value.RecoveryProvenance!.MeasuredMaxDeviationMillimetres));
+ }
+ else Assert.Contains(mesh.FaceDiagnostics!, d => d.Message.Contains("could not project"));
+ }
+
+ private static BrepBody CylinderWithHole(bool recovered)
+ {
+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
+ var points = new Dictionary<VertexId, Point3D>(); var loops = new List<LoopId>(); var edgeNumber = 0;
+ foreach (var uv in new[] { new[] { (0d, 0d), (1d, 0d), (1d, 2d), (0d, 2d) },
+ new[] { (.2d, .5d), (.2d, 1.5d), (.4d, 1.5d), (.4d, .5d) } })
+ {
+ var vertices = uv.Select(p => { var id = builder.AddVertex(); points[id] = Point(p.Item1, p.Item2); return id; }).ToArray();
+ var loop = builder.AllocateLoopId(); loops.Add(loop); var uses = uv.Select(_ => builder.AllocateCoedgeId()).ToArray();
+ for (var i = 0; i < 4; i++)
+ {
+ var j = (i + 1) % 4; var edge = builder.AddEdge(vertices[i], vertices[j]);
+ var controls = Enumerable.Range(0, 33).Select(k => Point(uv[i].Item1 + (uv[j].Item1 - uv[i].Item1) * k / 32d,
+ uv[i].Item2 + (uv[j].Item2 - uv[i].Item2) * k / 32d)).ToArray();
+ var spline = new BSpline3Curve(1, controls, Enumerable.Range(0, 33).Select(k => k == 0 || k == 32 ? 2 : 1).ToArray(),
+ Enumerable.Range(0, 33).Select(k => k / 32d).ToArray(), "UNSPECIFIED", false, false, "UNSPECIFIED");
+ var curve = new CurveGeometryId(++edgeNumber);
+ geometry.AddCurve(curve, recovered ? CurveGeometry.FromRecoveredBSpline(spline,
+ new("synthetic rational edge", "bounded fixture", .1, .04, true, "free-form")) : CurveGeometry.FromBSpline(spline));
+ bindings.AddEdgeBinding(new(edge, curve, new ParameterInterval(0, 1)));
+ builder.AddCoedge(new(uses[i], edge, loop, uses[j], uses[(i + 3) % 4], false));
+ }
+ builder.AddLoop(new Loop(loop, uses));
+ }
+ var face = builder.AddFace(loops); builder.AddBody([builder.AddShell([face])]);
+ var surface = new SurfaceGeometryId(1); geometry.AddSurface(surface, SurfaceGeometry.FromCylinder(new CylinderSurface(
+ Point3D.Origin, Direction3D.Create(new Vector3D(0, 0, 1)), 1, Direction3D.Create(new Vector3D(1, 0, 0)))));
+ bindings.AddFaceBinding(new(face, surface)); return new(builder.Model, geometry, bindings, points);
+ static Point3D Point(double u, double v) => new(1.03 * double.Cos(u), 1.03 * double.Sin(u), v);
+ }
+}
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SphericalTrimMaterializationTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SphericalTrimMaterializationTests.cs
new file mode 100644
index 00000000..ca5ec1a7
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SphericalTrimMaterializationTests.cs
@@ -0,0 +1,128 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;
+
+public sealed class SphericalTrimMaterializationTests
+{
+ private static readonly SphereSurface Sphere = new(Point3D.Origin, Direction3D.Create(new Vector3D(0, 0, 1)), 2, Direction3D.Create(new Vector3D(1, 0, 0)));
+
+ [Theory]
+ [InlineData(0.0, 2)]
+ [InlineData(0.5, 1)]
+ public void EquatorialHemisphereAndLatitudeCap_MaterializeThroughBoundCoedges(double latitude, int arcs)
+ {
+ var body = CapBody(latitude, arcs);
+ if (arcs == 1)
+ {
+ var recovered = BrepPcurveRecovery.Populate(body.Topology, body.Geometry, body.Bindings, 1e-3);
+ Assert.True(recovered.IsSuccess, string.Join(";", recovered.Diagnostics.Select(d => d.Message)));
+ }
+ var mesh = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(mesh.IsSuccess, string.Join(";", mesh.Diagnostics.Select(d => d.Message)));
+ var patch = Assert.Single(mesh.Value.FacePatches);
+ Assert.NotEmpty(patch.TriangleIndices);
+ Assert.All(patch.Positions, p => Assert.InRange(p.Z, 2 * double.Sin(latitude) - 1e-8, 2 + 1e-8));
+ AssertExactSupportAndFinite(patch);
+ }
+
+ [Fact]
+ public void SphericalBand_PreservesInnerLatitudeHole()
+ {
+ var patch = Materialize([Circle(.1), Circle(.6).Reverse().ToArray()]);
+ AssertExactSupportAndFinite(patch);
+ foreach (var (a, b, c) in Triangles(patch))
+ {
+ var middle = ((a - Point3D.Origin) + (b - Point3D.Origin) + (c - Point3D.Origin)) * (1d / 3d);
+ var latitude = double.Asin(middle.Z / middle.Length);
+ Assert.InRange(latitude, .1 - .01, .6 + .01);
+ }
+ }
+
+ [Fact]
+ public void LongitudeSeamCrossingTrim_StaysInItsSmallNativeDomain()
+ {
+ var patch = Materialize([Rectangle(5.8, 6.5, .1, .6)]);
+ AssertExactSupportAndFinite(patch);
+ Assert.All(patch.Positions, p => {
+ var u = double.Atan2(p.Y, p.X); if (u < 0) u += 2 * double.Pi;
+ if (u < 1) u += 2 * double.Pi;
+ Assert.InRange(u, 5.8 - .01, 6.5 + .01);
+ });
+ }
+
+ [Fact]
+ public void PoleTouchingTrim_CollapsesRepeatedPoleSamplesWithoutInventingArea()
+ {
+ var patch = Materialize([Rectangle(0, .7, .8, double.Pi / 2)]);
+ AssertExactSupportAndFinite(patch);
+ Assert.All(patch.Positions, p => Assert.True(p.Z >= 2 * double.Sin(.8) - .01));
+ Assert.Contains(patch.Positions, p => (p - new Point3D(0, 0, 2)).Length < 1e-8);
+ }
+
+ [Fact]
+ public void TruePointBoundary_DoesNotBecomeASphericalCap()
+ {
+ var pole = Sphere.Evaluate(0, double.Pi / 2);
+ var result = SphericalTrimTessellator.Tessellate(new FaceId(1), Sphere, [new[] { pole, pole, pole, pole }],
+ 0, true, DisplayTessellationOptions.Default, null);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Message.Contains("collapsed boundary"));
+ }
+
+ private static DisplayFaceMeshPatch Materialize(IReadOnlyList<IReadOnlyList<Point3D>> loops)
+ {
+ var result = SphericalTrimTessellator.Tessellate(new FaceId(1), Sphere, loops, 0, true, DisplayTessellationOptions.Default, null);
+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));
+ Assert.NotEmpty(result.Value.TriangleIndices);
+ return result.Value;
+ }
+
+ private static Point3D[] Circle(double v) => Enumerable.Range(0, 65).Select(i => Sphere.Evaluate(2 * double.Pi * i / 64, v)).ToArray();
+
+ private static Point3D[] Rectangle(double u0, double u1, double v0, double v1)
+ {
+ var points = new List<Point3D>();
+ foreach (var (a, b) in new[] { ((u0, v0), (u1, v0)), ((u1, v0), (u1, v1)), ((u1, v1), (u0, v1)), ((u0, v1), (u0, v0)) })
+ for (var i = 0; i < 24; i++) points.Add(Sphere.Evaluate(a.Item1 + (b.Item1 - a.Item1) * i / 24, a.Item2 + (b.Item2 - a.Item2) * i / 24));
+ return points.ToArray();
+ }
+
+ private static BrepBody CapBody(double latitude, int arcCount)
+ {
+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
+ var points = new Dictionary<VertexId, Point3D>();
+ var vertices = Enumerable.Range(0, arcCount).Select(i => { var id = builder.AddVertex(); points[id] = Sphere.Evaluate(2 * double.Pi * i / arcCount, latitude); return id; }).ToArray();
+ var loop = builder.AllocateLoopId(); var uses = Enumerable.Range(0, arcCount).Select(_ => builder.AllocateCoedgeId()).ToArray();
+ for (var i = 0; i < arcCount; i++)
+ {
+ var edge = builder.AddEdge(vertices[i], vertices[(i + 1) % arcCount]); var curve = new CurveGeometryId(i + 1);
+ geometry.AddCurve(curve, CurveGeometry.FromCircle(new Circle3Curve(new Point3D(0, 0, 2 * double.Sin(latitude)),
+ Direction3D.Create(new Vector3D(0, 0, 1)), 2 * double.Cos(latitude), Direction3D.Create(new Vector3D(1, 0, 0)))));
+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edge, curve, new ParameterInterval(2 * double.Pi * i / arcCount, 2 * double.Pi * (i + 1) / arcCount)));
+ builder.AddCoedge(new Coedge(uses[i], edge, loop, uses[(i + 1) % arcCount], uses[(i + arcCount - 1) % arcCount], false));
+ }
+ builder.AddLoop(new Loop(loop, uses)); var face = builder.AddFace([loop]); builder.AddBody([builder.AddShell([face])]);
+ var surface = new SurfaceGeometryId(1); geometry.AddSurface(surface, SurfaceGeometry.FromSphere(Sphere));
+ bindings.AddFaceBinding(new FaceGeometryBinding(face, surface));
+ bindings.AddFaceBoundaryRoleBinding(new FaceBoundaryRoleBinding(face, loop, FaceBoundaryRole.Outer));
+ return new BrepBody(builder.Model, geometry, bindings, points);
+ }
+
+ private static void AssertExactSupportAndFinite(DisplayFaceMeshPatch patch)
+ {
+ Assert.All(patch.Positions, p => Assert.InRange((p - Point3D.Origin).Length, 2 - 1e-10, 2 + 1e-10));
+ Assert.All(patch.Normals, n => Assert.True(double.IsFinite(n.Length) && n.Length > .99));
+ }
+
+ private static IEnumerable<(Point3D A, Point3D B, Point3D C)> Triangles(DisplayFaceMeshPatch patch)
+ {
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ yield return (patch.Positions[patch.TriangleIndices[i]], patch.Positions[patch.TriangleIndices[i + 1]], patch.Positions[patch.TriangleIndices[i + 2]]);
+ }
+}
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SplineTrimMaterializationTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SplineTrimMaterializationTests.cs
new file mode 100644
index 00000000..6bede3db
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SplineTrimMaterializationTests.cs
@@ -0,0 +1,163 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;
+
+public sealed class SplineTrimMaterializationTests
+{
+ [Fact]
+ public void TwoCurvedCoedges_EncloseFiniteSplinePatchInNativeDomain()
+ {
+ var body = CreateLens();
+ var result = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));
+ var patch = Assert.Single(result.Value.FacePatches); Assert.NotEmpty(patch.TriangleIndices);
+ Assert.All(patch.Positions, p => { Assert.InRange(p.X, 0, 2); Assert.InRange(p.Y, -.501, .501); Assert.Equal(0, p.Z, 9); });
+ }
+
+ [Fact]
+ public void SubBudgetLens_WithCollapsedRecoveredPcurves_DisplaysActualBoundaryWithoutChangingBindings()
+ {
+ var body = CreateLens(.001);
+ var face = Assert.Single(body.Topology.Faces);
+ var surfaceId = body.Bindings.GetFaceBinding(face.Id).SurfaceGeometryId;
+ foreach (var coedge in body.Topology.Coedges)
+ {
+ var pc = coedge.Id.Value == 1 ? PcurveGeometry.Line(new(7, 9), new(2, 12), new(4, 12))
+ : PcurveGeometry.Line(new(7, 9), new(4, 12), new(2, 12));
+ body.Bindings.AddPcurveBinding(new(coedge.Id, face.Id, surfaceId, pc,
+ Qualification: new(PcurveBindingOrigin.RecoveredSpline, .0005, .001, 67, "Line", "BSplineSurfaceWithKnots")));
+ }
+ var bindings = body.Bindings.PcurveBindings.ToArray();
+ var before = BrepPcurveValidator.Validate(body, .001, requireEveryCoedge: true);
+ Assert.True(before.IsValid, string.Join(";", before.Diagnostics));
+ var result = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(result.IsSuccess);
+ var patch = Assert.Single(result.Value.FacePatches);
+ Assert.NotEmpty(patch.TriangleIndices);
+ Assert.Contains(patch.Positions, p => p.Y > .0002);
+ Assert.Contains(patch.Positions, p => p.Y < -.0002);
+ Assert.Equal(bindings, body.Bindings.PcurveBindings.ToArray());
+ var after = BrepPcurveValidator.Validate(body, .001, requireEveryCoedge: true);
+ Assert.True(after.IsValid);
+ Assert.Equal(before.MaximumReconstructionDeviation, after.MaximumReconstructionDeviation);
+ }
+
+ private static BrepBody CreateLens(double height = 1)
+ {
+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
+ var a = builder.AddVertex(); var b = builder.AddVertex(); var loop = builder.AllocateLoopId();
+ var c0 = builder.AllocateCoedgeId(); var c1 = builder.AllocateCoedgeId();
+ var curves = new[] { new[] { new Point3D(0, 0, 0), new Point3D(1, height, 0), new Point3D(2, 0, 0) },
+ new[] { new Point3D(2, 0, 0), new Point3D(1, -height, 0), new Point3D(0, 0, 0) } };
+ var uses = new[] { c0, c1 };
+ for (var i = 0; i < 2; i++)
+ {
+ var edge = builder.AddEdge(i == 0 ? a : b, i == 0 ? b : a); var id = new CurveGeometryId(i + 1);
+ geometry.AddCurve(id, CurveGeometry.FromBSpline(new BSpline3Curve(2, curves[i], [3, 3], [7d, 9d], "UNSPECIFIED", false, false, "UNSPECIFIED")));
+ bindings.AddEdgeBinding(new(edge, id, new ParameterInterval(7, 9)));
+ builder.AddCoedge(new(uses[i], edge, loop, uses[1 - i], uses[1 - i], false));
+ }
+ builder.AddLoop(new Loop(loop, uses)); var face = builder.AddFace([loop]); builder.AddBody([builder.AddShell([face])]);
+ var support = new BSplineSurfaceWithKnots(1, 1,
+ [new[] { new Point3D(0, -height, 0), new Point3D(0, height, 0) }, new[] { new Point3D(2, -height, 0), new Point3D(2, height, 0) }],
+ "UNSPECIFIED", false, false, false, [2, 2], [2, 2], [2d, 4d], [10d, 14d], "UNSPECIFIED");
+ var surface = new SurfaceGeometryId(1); geometry.AddSurface(surface, SurfaceGeometry.FromBSplineSurfaceWithKnots(support));
+ bindings.AddFaceBinding(new(face, surface));
+ return new BrepBody(builder.Model, geometry, bindings, new Dictionary<VertexId, Point3D> { [a] = curves[0][0], [b] = curves[1][0] });
+ }
+
+ [Fact]
+ public void RectangularSpline_WithRepeatedInteriorTurning_UsesKnotAwareAdaptiveRefinement()
+ {
+ var net = Enumerable.Range(0, 2).Select(row => (IReadOnlyList<Point3D>)Enumerable.Range(0, 33)
+ .Select(i => new Point3D(row, i / 32d, i % 2 == 0 ? 0 : 1)).ToArray()).ToArray();
+ var support = new BSplineSurfaceWithKnots(1, 1, net, "UNSPECIFIED", false, false, false,
+ [2, 2], Enumerable.Range(0, 33).Select(i => i == 0 || i == 32 ? 2 : 1).ToArray(),
+ [2d, 4d], Enumerable.Range(0, 33).Select(i => 10d + i / 320d).ToArray(), "UNSPECIFIED");
+ var patch = TrimmedSurfaceTessellator.Tessellate(new FaceId(1),
+ [new[] { (2d, 10d), (4d, 10d), (4d, 10.1d), (2d, 10.1d) }], support.Evaluate,
+ (_, _) => new Vector3D(0, 0, 1), DisplayTessellationOptions.Default,
+ 2, 4, 10, 10.1, Warning, surfaceKind: SurfaceGeometryKind.BSplineSurfaceWithKnots, splineSupport: support);
+ Assert.True(patch.IsSuccess); Assert.Empty(patch.Diagnostics);
+ var p = patch.Value;
+ for (var i = 0; i < p.TriangleIndices.Count; i += 3)
+ {
+ var points = p.TriangleIndices.Skip(i).Take(3).Select(n => p.Positions[n]).ToArray();
+ var center = new Point3D(points.Average(x => x.X), points.Average(x => x.Y), points.Average(x => x.Z));
+ Assert.InRange((support.Evaluate(2 + 2 * center.X, 10 + .1 * center.Y) - center).Length, 0, .051);
+ }
+ }
+
+ [Fact]
+ public void RectangularSpline_RetainsPhysicalQuadsBeforeFinalTriangleLowering()
+ {
+ var support = new BSplineSurfaceWithKnots(1, 1,
+ [new[] { new Point3D(0, 0, 0), new Point3D(0, 1, 0) }, new[] { new Point3D(20, 0, 0), new Point3D(20, 1, 0) }],
+ "UNSPECIFIED", false, false, false, [2, 2], [2, 2], [0d, 1d], [0d, 1d], "UNSPECIFIED");
+ var patch = SplineRectangleTessellator.Tessellate(new FaceId(1), support, 0, 1, 0, 1,
+ (_, _) => new Vector3D(0, 0, 1), DisplayTessellationOptions.Default, null, 65_536, out var limited);
+ Assert.NotNull(patch); Assert.False(limited); Assert.NotNull(patch.Cells);
+ Assert.Equal(patch.Cells.Count * 6, patch.TriangleIndices.Count);
+ Assert.All(patch.Cells, cell =>
+ {
+ Assert.IsType<QuadCell>(cell);
+ var points = cell.VertexIds.Select(i => patch.Positions[i]).ToArray();
+ var edges = Enumerable.Range(0, 4).Select(i => (points[(i + 1) % 4] - points[i]).Length).ToArray();
+ Assert.InRange(edges.Max() / edges.Min(), 1, 4);
+ });
+ // Full rectangle remains covered; balancing changes display sampling only.
+ double area = 0;
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ {
+ var a = patch.Positions[patch.TriangleIndices[i]];
+ var b = patch.Positions[patch.TriangleIndices[i + 1]];
+ var c = patch.Positions[patch.TriangleIndices[i + 2]];
+ area += (b - a).Cross(c - a).Length * .5d;
+ }
+ Assert.Equal(20d, area, 8);
+ }
+
+ [Fact]
+ public void ClosedSplineTrim_UsesNativePeriodAndOriginAtSeam()
+ {
+ var row = new[] { new Point3D(1, 0, 0), new Point3D(0, 1, 0), new Point3D(-1, 0, 0), new Point3D(0, -1, 0), new Point3D(1, 0, 0) };
+ var surface = new BSplineSurfaceWithKnots(1, 1, row.Select(p => (IReadOnlyList<Point3D>)new[] { p, p + new Vector3D(0, 0, 1) }).ToArray(),
+ "UNSPECIFIED", true, false, false, [2, 1, 1, 1, 2], [2, 2], [2d, 4d, 6d, 8d, 10d], [3d, 7d], "UNSPECIFIED");
+ var points = new[] { (2d, 3d), (9d, 3d), (6d, 3d), (6d, 7d), (9d, 7d), (10d, 7d) };
+ var loop = Assert.Single(BrepDisplayTessellator.NormalizeClosedSplineLoops(surface, [points]));
+ Assert.All(loop, p => Assert.InRange(p.U, 6, 10));
+ for (var i = 0; i < points.Length; i++)
+ Assert.InRange((surface.Evaluate(points[i].Item1, points[i].Item2) - surface.Evaluate(loop[i].U, loop[i].V)).Length, 0, 1e-10);
+ }
+
+ [Fact]
+ public void CollapsedPcurveLoop_ReportsZeroAreaWithoutInventingTriangles()
+ {
+ var result = TrimmedSurfaceTessellator.Tessellate(new FaceId(1),
+ [new[] { (0d, 0d), (.5d, .5d), (1d, 1d) }], (u, v) => new Point3D(u, v, 0),
+ (_, _) => new Vector3D(0, 0, 1), DisplayTessellationOptions.Default, 0, 1, 0, 1, Warning);
+ Assert.True(result.IsSuccess); Assert.Empty(result.Value.TriangleIndices);
+ Assert.Contains(result.Diagnostics, d => d.Source == "Viewer.Tessellation.TrimEvaluationFailed"
+ && d.Message.Contains("zero triangles") && d.Message.Contains("signed UV area=0"));
+ }
+
+ [Fact]
+ public void AdaptiveBudgetExhaustion_IsExplicitInsteadOfSilentFidelitySuccess()
+ {
+ var mesh = BoundaryConformingTrimTessellator.TryTessellate(new FaceId(1),
+ [new() { (0, 0), (1, 0), (1, 1), (0, 1) }], 0,
+ (u, v) => new Point3D(u, v, double.Sin(15 * u) * double.Sin(15 * v)),
+ (_, _) => new Vector3D(0, 0, 1), .01, .01, DisplayTessellationOptions.Default, null,
+ out var incomplete, refineRectangles: true, maximumTriangles: 32);
+ Assert.NotNull(mesh); Assert.True(incomplete);
+ }
+
+ private static KernelDiagnostic Warning(string message, string source) => new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning, message, source);
+}
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.cs
index df396d78..efaf8c62 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.cs
@@ -10,6 +10,29 @@ namespace Aetheris.Kernel.Core.Tests.Step242;
public sealed class Step242PcurveAndVertexLoopTests
{
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void ReparameterizedPolynomialLinePcurve_PreservesExactDomainEndpointsAndUvLocus(bool rational)
+ {
+ var source = new ParameterInterval(52.4560164915884, 100.21060533511107);
+ var target = new ParameterInterval(0, 44.594180686074665);
+ var curve = new BSpline3Curve(1, [new(1, 2, 0), new(4, 7, 0)], [2, 2],
+ [source.Start, source.End], "UNSPECIFIED", false, false, "UNSPECIFIED");
+ var pcurve = rational ? PcurveGeometry.RationalPolynomial(source, curve, [1, 2]) : PcurveGeometry.Polynomial(source, curve);
+ var remapped = Step242Exporter.ReparameterizeLinePcurve(pcurve, target);
+ Assert.Equal(target.Start, remapped.PolynomialCurve!.Value.DomainStart);
+ Assert.Equal(target.End, remapped.PolynomialCurve.Value.DomainEnd);
+ Assert.Equal(pcurve.RationalWeights, remapped.RationalWeights);
+ for (var index = 0; index <= 32; index++)
+ {
+ var fraction = index / 32d;
+ var before = pcurve.Evaluate(source.Start + fraction * (source.End - source.Start));
+ var after = remapped.Evaluate(target.Start + fraction * (target.End - target.Start));
+ Assert.True(double.Abs(before.U - after.U) < 1e-12 && double.Abs(before.V - after.V) < 1e-12);
+ }
+ }
+
[Fact]
public void UnsupportedPcurveForm_IsDiagnosedInsteadOfDropped()
{
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ProductionRationalGuardTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ProductionRationalGuardTests.cs
index 1172cc6d..9d9c5698 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ProductionRationalGuardTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ProductionRationalGuardTests.cs
@@ -9,6 +9,54 @@ namespace Aetheris.Kernel.Core.Tests.Step242;
public sealed class Step242ProductionRationalGuardTests
{
+ [Fact]
+ public void ExplicitProductionBudget_RecoversOnCopyAndPreservesTopologyThroughRoundtrip()
+ {
+ var box = Step242Importer.ImportBody(Step242Exporter.ExportBody(BrepPrimitives.CreateBox(10, 10, 10).Value).Value).Value;
+ var id = box.Bindings.FaceBindings.First().SurfaceGeometryId;
+ var plane = box.Geometry.GetSurface(id).Plane!.Value;
+ var vertices = box.Topology.Vertices.Select(v => { box.TryGetVertexPoint(v.Id, out var p); return p; }).ToArray();
+ var us = vertices.Select(p => (p - plane.Origin).Dot(plane.UAxis.ToVector())).ToArray();
+ var vs = vertices.Select(p => (p - plane.Origin).Dot(plane.VAxis.ToVector())).ToArray();
+ var rational = new BSplineSurfaceWithKnots(1, 1,
+ new IReadOnlyList<Point3D>[] {
+ [plane.Evaluate(us.Min(), vs.Min()), plane.Evaluate(us.Min(), vs.Max())],
+ [plane.Evaluate(us.Max(), vs.Min()), plane.Evaluate(us.Max(), vs.Max())]
+ }, "UNSPECIFIED", false, false, false, [2, 2], [2, 2], [0d, 1d], [0d, 1d], "UNSPECIFIED",
+ new IReadOnlyList<double>[] { [1d, 1.2d], [1d, 1.2d] });
+ var geometry = new BrepGeometryStore();
+ foreach (var c in box.Geometry.Curves) geometry.AddCurve(c.Key, c.Value);
+ foreach (var s in box.Geometry.Surfaces) geometry.AddSurface(s.Key,
+ s.Key == id ? SurfaceGeometry.FromBSplineSurfaceWithKnots(rational) : s.Value);
+ var points = box.Topology.Vertices.ToDictionary(v => v.Id, v => { box.TryGetVertexPoint(v.Id, out var p); return p; });
+ var bindings = new BrepBindingModel();
+ foreach (var e in box.Bindings.EdgeBindings) bindings.AddEdgeBinding(e);
+ foreach (var f in box.Bindings.FaceBindings) bindings.AddFaceBinding(f);
+ var source = new BrepBody(box.Topology, geometry, bindings, points, faceOrientationReport: box.FaceOrientationReport);
+ var prepared = Step242ProductionNormalization.Prepare(source, .1);
+ Assert.True(prepared.IsSuccess, string.Join(" | ", prepared.Diagnostics.Select(d => d.Message)));
+ Assert.Same(source.Topology, prepared.Value.Topology);
+ Assert.Empty(source.Bindings.PcurveBindings);
+ Assert.True(source.Geometry.GetSurface(id).BSplineSurfaceWithKnots!.IsRational);
+ Assert.False(prepared.Value.Geometry.GetSurface(id).BSplineSurfaceWithKnots!.IsRational);
+ Assert.True(BrepPcurveValidator.Validate(prepared.Value, 1e-3, requireEveryCoedge: true).IsValid);
+ for (var u = 0; u <= 23; u++) for (var v = 0; v <= 31; v++)
+ Assert.InRange((rational.Evaluate(u / 23d, v / 31d) -
+ prepared.Value.Geometry.GetSurface(id).BSplineSurfaceWithKnots!.Evaluate(u / 23d, v / 31d)).Length, 0, .1);
+ var exported = Step242Exporter.ExportBody(source, new Step242ExportOptions {
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ ImportedRecoveryToleranceMillimetres = .1
+ });
+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(d => d.Message)));
+ Assert.Contains(exported.Diagnostics, d => d.Source == "Step242.ProductionNormalization");
+ Assert.DoesNotContain("RATIONAL_B_SPLINE", exported.Value, StringComparison.Ordinal);
+ var reimport = Step242Importer.ImportBody(exported.Value);
+ Assert.True(reimport.IsSuccess);
+ Assert.Equal(source.Topology.Faces.Count(), reimport.Value.Topology.Faces.Count());
+ Assert.Equal(source.Topology.Edges.Count(), reimport.Value.Topology.Edges.Count());
+ }
+
[Fact]
public void TrustedProductionRouteRejectsRationalSurfaceBeforeSerialization()
{
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.cs
index 13338e9c..af23fe3a 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.cs
@@ -141,6 +141,23 @@ public sealed class Step242RationalSurfaceReductionTests
Assert.Equal(5e-4d, BSplineSurfaceRationalReduction.ResolveTolerance(rational, 5e-3d), 12);
}
+ [Fact]
+ public void LowDegreeRationalDirection_RefinesAnisotropicallyWithinExistingControlNetCap()
+ {
+ var source = new BSplineSurfaceWithKnots(3, 1,
+ Enumerable.Range(0, 4).Select(i => (IReadOnlyList<Point3D>)new[] {
+ new Point3D(i / 3d, 0, i * i / 20d), new Point3D(i / 3d, 1, i * i / 20d)
+ }).ToArray(), "UNSPECIFIED", false, false, false, [4, 4], [2, 2], [0d, 1d], [0d, 1d], "UNSPECIFIED",
+ Enumerable.Range(0, 4).Select(_ => (IReadOnlyList<double>)new[] { 1d, 1.2d }).ToArray());
+ Assert.True(BSplineSurfaceRationalReduction.TryReduce(source, 1e-5, out var reduced, out var error, out var reason), reason);
+ Assert.False(reduced!.IsRational);
+ Assert.Equal(4, reduced.ControlPoints.Count);
+ Assert.InRange(reduced.ControlPoints[0].Count, 34, 256);
+ Assert.InRange(error, 0, 1e-5);
+ for (var i = 0; i <= 17; i++) for (var j = 0; j <= 257; j++)
+ Assert.InRange((source.Evaluate(i / 17d, j / 257d) - reduced.Evaluate(i / 17d, j / 257d)).Length, 0, 1e-5);
+ }
+
private static int CountRationalSurfaces(Aetheris.Kernel.Core.Brep.BrepBody body)
=> body.Geometry.Surfaces.Count(surface => surface.Value.BSplineSurfaceWithKnots is { IsRational: true });
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242SphericalShellRoundtripTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242SphericalShellRoundtripTests.cs
new file mode 100644
index 00000000..1b8d8ec9
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242SphericalShellRoundtripTests.cs
@@ -0,0 +1,90 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Import;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242SphericalShellRoundtripTests
+{
+ [Theory]
+ [InlineData(0, 0, 0)]
+ [InlineData(7.0364833422123, 5.6114082167286, 0)]
+ [InlineData(-9.14, 3.19, 2.1)]
+ public void ComplementaryHemispheres_RetainOutwardOrientationAcrossRepeatedSerialization(double x, double y, double z)
+ {
+ var center = new Point3D(x, y, z);
+ var sphere = new SphereSurface(center, Direction3D.Create(new Vector3D(-.6234898018587, .781831482468, 0)),
+ 2.19931404045, Direction3D.Create(new Vector3D(.781831482468, .6234898018587, 0)));
+ var body = CreateSplitSphere(sphere);
+ for (var round = 0; round < 3; round++)
+ {
+ var export = Step242Exporter.ExportBody(body);
+ Assert.True(export.IsSuccess, string.Join(";", export.Diagnostics.Select(d => d.Message)));
+ var import = Step242Importer.ImportBody(export.Value);
+ Assert.True(import.IsSuccess);
+ body = import.Value;
+ Assert.Equal(ImportQualificationStatus.Qualified, body.ImportQualification!.Status);
+ Assert.All(body.Bindings.FaceBindings, f => Assert.True(f.Orientation.IsAlignedWithSurface));
+ Assert.Equal(2, body.Topology.Faces.Count());
+ Assert.True(BrepPcurveValidator.Validate(body, 1e-3, requireEveryCoedge: true).IsValid);
+ var mesh = BrepDisplayTessellator.Tessellate(body).Value;
+ Assert.Equal(2, mesh.FacePatches.Count);
+ var signedVolume = 0d;
+ foreach (var patch in mesh.FacePatches)
+ {
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ {
+ var a = patch.Positions[patch.TriangleIndices[i]] - center;
+ var b = patch.Positions[patch.TriangleIndices[i + 1]] - center;
+ var c = patch.Positions[patch.TriangleIndices[i + 2]] - center;
+ var cross = (b - a).Cross(c - a);
+ Assert.True(cross.Dot(a + b + c) > 0, "Every triangle must face outward, on both hemispheres.");
+ signedVolume += a.Dot(b.Cross(c)) / 6;
+ }
+ }
+ var exactVolume = 4 * double.Pi * double.Pow(sphere.Radius, 3) / 3;
+ Assert.InRange(signedVolume, exactVolume * .94, exactVolume * 1.01);
+ }
+ }
+
+ private static BrepBody CreateSplitSphere(SphereSurface sphere)
+ {
+ var builder = new TopologyBuilder();
+ var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
+ var a = builder.AddVertex(); var b = builder.AddVertex();
+ var edge1 = builder.AddEdge(a, b); var edge2 = builder.AddEdge(a, b);
+ var circle = new Circle3Curve(sphere.Center, Direction3D.Create(-sphere.Axis.ToVector()), sphere.Radius, sphere.XAxis);
+ var opposite = new Circle3Curve(sphere.Center, sphere.Axis, sphere.Radius, Direction3D.Create(-sphere.XAxis.ToVector()));
+ // Opposite semicircles with a shared endpoint direction and a wrap-crossing
+ // native interval reproduce the vendor topology without vendor source data.
+ var interval = new ParameterInterval(4.7123889803847, 7.8539816339745);
+ geometry.AddCurve(new(1), CurveGeometry.FromCircle(circle));
+ geometry.AddCurve(new(2), CurveGeometry.FromCircle(opposite));
+ bindings.AddEdgeBinding(new(edge1, new(1), interval));
+ bindings.AddEdgeBinding(new(edge2, new(2), interval));
+ var surface = new SurfaceGeometryId(1); geometry.AddSurface(surface, SurfaceGeometry.FromSphere(sphere));
+ var faces = new List<FaceId>();
+ foreach (var reverse in new[] { false, true })
+ {
+ var loop = builder.AllocateLoopId();
+ var c1 = builder.AllocateCoedgeId(); var c2 = builder.AllocateCoedgeId();
+ builder.AddCoedge(new(c1, reverse ? edge2 : edge1, loop, c2, c2, true));
+ builder.AddCoedge(new(c2, reverse ? edge1 : edge2, loop, c1, c1, false));
+ builder.AddLoop(new Loop(loop, [c1, c2]));
+ var face = builder.AddFace([loop]); faces.Add(face);
+ bindings.AddFaceBinding(new(face, surface));
+ bindings.AddFaceBoundaryRoleBinding(new(face, loop, FaceBoundaryRole.Outer));
+ }
+ builder.AddBody([builder.AddShell(faces)]);
+ var body = new BrepBody(builder.Model, geometry, bindings,
+ new Dictionary<VertexId, Point3D> { [a] = circle.Evaluate(interval.Start), [b] = circle.Evaluate(interval.End) });
+ Assert.True(BrepPcurveRecovery.Populate(body.Topology, geometry, bindings, 1e-3).IsSuccess);
+ return body;
+ }
+}
diff --git a/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs b/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
new file mode 100644
index 00000000..4ebd64ea
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
@@ -0,0 +1,107 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Import;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class StepLegacyQualificationTests
+{
+ [Fact]
+ public void ExactImportedBox_GainsAnalyticallyDerivedPcurvesWithoutGeometryRecovery()
+ {
+ var imported = Step242Importer.ImportBody(Step242FixtureCorpus.CanonicalBoxGolden);
+ Assert.True(imported.IsSuccess);
+ var body = imported.Value;
+ Assert.Equal(0, body.ImportQualification!.MissingPcurves);
+ Assert.True(BrepPcurveValidator.Validate(body, 1e-3, requireEveryCoedge: true).IsValid);
+ Assert.All(body.Bindings.PcurveBindings, binding => Assert.Equal(PcurveBindingOrigin.DerivedAnalytic, binding.Qualification!.Origin));
+ Assert.All(body.Geometry.Surfaces, support => Assert.Null(support.Value.RecoveryProvenance));
+ Assert.All(body.Geometry.Curves, curve => Assert.Null(curve.Value.RecoveryProvenance));
+ Assert.Equal(Step242FixtureCorpus.CanonicalBoxGolden, Step242Exporter.ExportBody(body).Value);
+ }
+
+ [Fact]
+ public void DisplayRefinementWarning_DoesNotDegradeAuthoritativeGeometry()
+ {
+ var body = Box.Value;
+ var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body) with {
+ FaceDiagnostics = [new(null, "BSplineSurfaceWithKnots", "FaceTessellation", "Viewer.Tessellation.RefinementIncomplete", "Display budget reached.")]
+ };
+ var report = BrepImportQualification.WithDisplay(body, mesh);
+ Assert.Equal(ImportQualificationStatus.Qualified, report.Status);
+ Assert.Equal(ImportDisplayStatus.RefinementLimited, report.DisplayStatus);
+ Assert.Empty(report.Reasons);
+ Assert.Single(report.DisplayReasons);
+ }
+ private static readonly Lazy<BrepBody> Box = new(() => {
+ var authored = BrepPrimitives.CreateBox(2, 2, 2).Value;
+ Assert.True(BrepPcurveRecovery.Populate(authored.Topology, authored.Geometry, authored.Bindings, 1e-3).IsSuccess);
+ var imported = Step242Importer.ImportBody(Step242Exporter.ExportBody(authored).Value);
+ Assert.True(imported.IsSuccess);
+ return imported.Value;
+ });
+
+ [Fact]
+ public void ClosedQualifiedGeometry_DoesNotClaimDisplayUntilActualMeshIsAssessed()
+ {
+ var body = Box.Value;
+ Assert.Equal(ImportQualificationStatus.Qualified, body.ImportQualification!.GeometryStatus);
+ Assert.Equal(ImportQualificationStatus.Qualified, body.ImportQualification.Status);
+ Assert.Equal(ImportDisplayStatus.NotAssessed, body.ImportQualification.DisplayStatus);
+ Assert.Null(body.ImportQualification.DisplayedFaces);
+ var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body);
+ var report = BrepImportQualification.WithDisplay(body, mesh);
+ Assert.Equal(ImportQualificationStatus.Qualified, report.Status);
+ Assert.Equal(6, report.DisplayedFaces);
+ Assert.Empty(report.Reasons);
+ }
+
+ [Fact]
+ public void MissingDisplayPatch_IsSeparateFromEngineering_WithSourceFaceIdentity()
+ {
+ var body = Box.Value;
+ var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body);
+ var omitted = mesh.FacePatches[0];
+ var partial = mesh with { FacePatches = mesh.FacePatches.Skip(1).ToArray() };
+ var report = BrepImportQualification.WithDisplay(body, partial);
+ Assert.Equal(ImportQualificationStatus.Qualified, report.Status);
+ Assert.Equal(ImportDisplayStatus.Partial, report.DisplayStatus);
+ Assert.Equal(6, report.BoundFaces);
+ Assert.Equal(5, report.DisplayedFaces);
+ var reason = Assert.Single(report.DisplayReasons, r => r.Code == "missing-display-face");
+ Assert.Equal(omitted.FaceId.Value, reason.FaceId);
+ Assert.Equal(body.Bindings.GetFaceBinding(omitted.FaceId).SourceStepEntityId, reason.StepEntityId);
+ Assert.Equal(ImportQualificationStatus.Qualified, body.ImportQualification!.Status);
+ Assert.Equal(6, body.Topology.Faces.Count());
+ }
+
+ [Fact]
+ public void ClosedGeometryWithoutPcurves_RemainsInspectableAfterCompleteDisplay()
+ {
+ var original = Box.Value;
+ var bindings = new BrepBindingModel();
+ foreach (var e in original.Bindings.EdgeBindings) bindings.AddEdgeBinding(e);
+ foreach (var f in original.Bindings.FaceBindings) bindings.AddFaceBinding(f);
+ var points = original.Topology.Vertices.ToDictionary(v => v.Id, v => { original.TryGetVertexPoint(v.Id, out var p); return p; });
+ var body = new BrepBody(original.Topology, original.Geometry, bindings, points, faceOrientationReport: original.FaceOrientationReport);
+ body.ImportQualification = BrepImportQualification.Evaluate(body, 6, null, 1e-3);
+ Assert.Equal(24, body.ImportQualification.MissingPcurves);
+ var report = BrepImportQualification.WithDisplay(body, BrepDisplayTessellator.TessellateBoundedPartial(body));
+ Assert.Equal(ImportQualificationStatus.Inspectable, report.Status);
+ Assert.Contains(report.Reasons, r => r.Code == "missing-pcurve");
+ }
+
+ [Fact]
+ public void SolidRootWithOpenShell_IsRetainedButNeverQualified()
+ {
+ var result = Step242Importer.ImportBody(Step242FixtureCorpus.PlanarFaceWithRectangularHole);
+ Assert.True(result.IsSuccess);
+ var report = result.Value.ImportQualification!;
+ Assert.Equal(ImportQualificationStatus.Degraded, report.Status);
+ Assert.Equal(8, Assert.Single(report.Shells).BoundaryEdges);
+ Assert.Contains(report.Reasons, r => r.Code == "incomplete-shell");
+ Assert.Equal(ImportQualificationStatus.Degraded,
+ BrepImportQualification.WithDisplay(result.Value, BrepDisplayTessellator.TessellateBoundedPartial(result.Value)).Status);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
index 4e45ec17..3632b76a 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
@@ -190,7 +190,7 @@ public readonly record struct CoedgePcurveBinding(
int? SourceStepSurfaceEntityId = null,
PcurveQualification? Qualification = null);
-public enum PcurveBindingOrigin { SourceValidated, RecoveredAnalytic, RecoveredSpline }
+public enum PcurveBindingOrigin { SourceValidated, RecoveredAnalytic, RecoveredSpline, DerivedAnalytic }
/// <summary>Measured edge-to-surface-lift evidence for one face-local trim.</summary>
public sealed record PcurveQualification(
diff --git a/Aetheris.Kernel.Core/Brep/BrepBody.cs b/Aetheris.Kernel.Core/Brep/BrepBody.cs
index af2bb687..40a9bd45 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBody.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBody.cs
@@ -54,6 +54,9 @@ public sealed class BrepBody
/// <summary>Present when an interchange body required reconstructed trim bindings.</summary>
public BrepPcurveRecoveryResult? PcurveRecoveryReport { get; internal set; }
+ /// <summary>Source BRep evidence; display completeness is assessed separately.</summary>
+ public Aetheris.Kernel.Core.Import.BrepImportQualificationReport? ImportQualification { get; internal set; }
+
public bool TryGetVertexPoint(VertexId vertexId, out Point3D point) => _vertexPoints.TryGetValue(vertexId, out point);
public bool TryGetEdgeCurveGeometry(EdgeId edgeId, out CurveGeometry? curve)
diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
index a1f0ecf3..016e0d38 100644
--- a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
@@ -61,8 +61,10 @@ public static class BrepPcurveRecovery
coedge.Id.Value.ToString()));
continue;
}
- var origin = surface.BSplineSurfaceWithKnots is null
- ? PcurveBindingOrigin.RecoveredAnalytic : PcurveBindingOrigin.RecoveredSpline;
+ var exactPlanarProjection = surface.Plane is not null
+ && (curve.Kind is CurveGeometryKind.Line3 or CurveGeometryKind.Circle3 || curve.BSpline3 is not null);
+ var origin = exactPlanarProjection ? PcurveBindingOrigin.DerivedAnalytic
+ : surface.BSplineSurfaceWithKnots is null ? PcurveBindingOrigin.RecoveredAnalytic : PcurveBindingOrigin.RecoveredSpline;
bindings.AddPcurveBinding(new(coedge.Id, face.Id, faceBinding.SurfaceGeometryId, built.Pcurve,
Qualification: new(origin, liftResidual, qualificationTolerance, liftSamples,
built.Pcurve.Kind.ToString(), surface.Kind.ToString())));
@@ -130,8 +132,8 @@ public static class BrepPcurveRecovery
if (surface.BSplineSurfaceWithKnots is not { } spline)
return (null, double.PositiveInfinity, $"Surface family {surface.Kind} is outside the qualified pcurve matrix.");
- var startInverse = Invert(spline, EvaluateCurve(curve, interval.Start), null, tolerance);
- var endInverse = Invert(spline, EvaluateCurve(curve, interval.End), startInverse.Success ? startInverse.Uv : null, tolerance);
+ var startInverse = ProjectSplinePoint(spline, EvaluateCurve(curve, interval.Start), null, tolerance);
+ var endInverse = ProjectSplinePoint(spline, EvaluateCurve(curve, interval.End), startInverse.Success ? startInverse.Uv : null, tolerance);
if (startInverse.Success && endInverse.Success)
{
var lineCandidate = PcurveGeometry.Line(interval, startInverse.Uv, endInverse.Uv);
@@ -148,7 +150,7 @@ public static class BrepPcurveRecovery
for (var index = 0; index < inverseSamples; index++)
{
var t = interval.Start + ((interval.End - interval.Start) * index / (inverseSamples - 1d));
- var inverse = Invert(spline, EvaluateCurve(curve, t), seed, tolerance);
+ var inverse = ProjectSplinePoint(spline, EvaluateCurve(curve, t), seed, tolerance);
if (!inverse.Success)
{
bestResidual = double.Min(bestResidual, inverse.Residual);
@@ -168,7 +170,7 @@ public static class BrepPcurveRecovery
$"Spline pcurve inversion/refinement exceeded 4097 samples; best lifted residual={bestResidual:R} mm, tolerance={tolerance:R} mm.");
}
- private static (bool Success, SurfaceParameterPoint Uv, double Residual) Invert(BSplineSurfaceWithKnots spline, Point3D target, SurfaceParameterPoint? prior, double tolerance)
+ internal static (bool Success, SurfaceParameterPoint Uv, double Residual) ProjectSplinePoint(BSplineSurfaceWithKnots spline, Point3D target, SurfaceParameterPoint? prior, double tolerance)
{
// Intersection traces are parameter-continuous, so the preceding inverse is
// the deterministic seed after the first sample. Avoiding a fresh global grid
@@ -362,10 +364,10 @@ public static class BrepPcurveRecovery
return (null, best, $"{surface.Kind} pcurve refinement could not meet {tolerance:R} mm (best sampled lift residual {best:R} mm).");
}
- private static double UnwrapNear(double value, double reference)
+ internal static double UnwrapNear(double value, double reference, double period = 2d * double.Pi)
{
- while (value - reference > double.Pi) value -= 2d * double.Pi;
- while (value - reference < -double.Pi) value += 2d * double.Pi;
+ while (value - reference > period / 2d) value -= period;
+ while (value - reference < -period / 2d) value += period;
return value;
}
private static void UnwrapAngles(SurfaceParameterPoint[] points, bool unwrapV)
diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
index 323aef55..63c2d4b7 100644
--- a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
@@ -208,7 +208,7 @@ public static class BrepPcurveValidator
_ => null
};
- private static Point3D? Evaluate(CurveGeometry curve, double parameter) => curve.Kind switch
+ internal static Point3D? Evaluate(CurveGeometry curve, double parameter) => curve.Kind switch
{
CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(parameter),
CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(parameter),
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs
index 84a10d6b..39c73d00 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs
@@ -10,7 +10,8 @@ namespace Aetheris.Kernel.Core.Brep.Tessellation;
/// cells that lie (almost) entirely inside the trim loops. That leaves a staircase along every trim curve and a gap
/// of up to one cell width between adjacent faces, which is very visible on narrow B-spline patches such as gear
/// flanks. This tessellator instead triangulates the trim loops themselves (so every triangle edge along the
-/// boundary is a real boundary sample) and then refines the interior by conforming longest-edge bisection until the
+/// boundary is a real boundary sample). Dense spline trims first decompose that region in a native-knot-aware,
+/// physically balanced grid; local ear clipping removes long seed diagonals. It then refines by conforming bisection until the
/// triangles satisfy the chord and angular tolerances of the display options (edge-midpoint sag, triangle-centre
/// sag and normal deviation), with a coarse cell-size cap as a safety net.
/// </para>
@@ -19,8 +20,28 @@ namespace Aetheris.Kernel.Core.Brep.Tessellation;
/// </summary>
internal static class BoundaryConformingTrimTessellator
{
- // Soft cap: refinement stops (leaving a valid, conforming, slightly coarser mesh) once a face reaches this size,
- // so dense B-spline faces cannot consume the whole display budget.
+ internal enum TrimClass { RectangularGridLike, SimpleConvex, SimpleConcave, WithHoles, Pathological }
+
+ internal static TrimClass Classify(IReadOnlyList<List<(double U, double V)>> loops, int outerIndex)
+ {
+ if (loops.Count == 0 || outerIndex < 0 || outerIndex >= loops.Count
+ || loops.Any(l => l.Count < 3 || l.Any(p => !double.IsFinite(p.U) || !double.IsFinite(p.V))))
+ return TrimClass.Pathological;
+ if (loops.Count > 1) return TrimClass.WithHoles;
+ var loop = loops[outerIndex];
+ if (IsAxisAlignedRectangle(loop)) return TrimClass.RectangularGridLike;
+ var positive = false; var negative = false;
+ for (var i = 0; i < loop.Count; i++)
+ {
+ var a = loop[i]; var b = loop[(i + 1) % loop.Count]; var c = loop[(i + 2) % loop.Count];
+ var cross = (b.U - a.U) * (c.V - b.V) - (b.V - a.V) * (c.U - b.U);
+ positive |= cross > 0; negative |= cross < 0;
+ }
+ return positive && negative ? TrimClass.SimpleConcave
+ : positive || negative ? TrimClass.SimpleConvex : TrimClass.Pathological;
+ }
+ // Default cap for direct callers. TrimmedSurfaceTessellator supplies the display-options budget;
+ // exhaustion retains a conforming mesh but reports incomplete fidelity explicitly.
private const int MaxTriangles = 12_000;
// Never split edges shorter than this fraction of a nominal grid cell (guarantees termination).
private const double MinimumSplitLength = 0.125d;
@@ -38,15 +59,25 @@ internal static class BoundaryConformingTrimTessellator
double cellV,
DisplayTessellationOptions options,
Action? checkBudget,
- double maximumCellLength = MaximumCellLength)
+ out bool refinementIncomplete,
+ double maximumCellLength = MaximumCellLength,
+ bool refineRectangles = false,
+ int maximumTriangles = MaxTriangles,
+ bool perceptualNormals = false,
+ (List<double> U, List<double> V)? grid = null,
+ Action<string>? reportFailure = null)
{
+ refinementIncomplete = false;
if (!(cellU > 0d) || !(cellV > 0d) || !double.IsFinite(cellU) || !double.IsFinite(cellV))
{
+ reportFailure?.Invoke("Nonfinite or nonpositive display cell size.");
return null;
}
+ var trimClass = Classify(loops, outerLoopIndex);
+ if (trimClass == TrimClass.Pathological) { reportFailure?.Invoke("Degenerate or nonfinite trim polygon."); return null; }
var outer = loops[outerLoopIndex];
- if (loops.Count == 1 && IsAxisAlignedRectangle(outer))
+ if (!refineRectangles && trimClass == TrimClass.RectangularGridLike)
{
// The uniform grid is built from the loop bounds, so a lone axis-aligned rectangle is already
// reproduced exactly by the mask tessellator; there is no staircase to remove.
@@ -68,6 +99,7 @@ internal static class BoundaryConformingTrimTessellator
{
if (!IsStrictlyInside(outer, hole[0]))
{
+ reportFailure?.Invoke("Inner bound is outside the normalized outer chart.");
return null;
}
}
@@ -78,6 +110,7 @@ internal static class BoundaryConformingTrimTessellator
{
if (i != j && IsStrictlyInside(holes[j], holes[i][0]))
{
+ reportFailure?.Invoke("Nested inner bounds do not form an outer-minus-holes region.");
return null;
}
}
@@ -108,33 +141,77 @@ internal static class BoundaryConformingTrimTessellator
else if (triangulationFailure != PlanarPolygonTriangulationFailure.TriangulationFailed
|| !EarCutTriangulator.TryTriangulate(outerScaled, holesScaled, out seedPoints, out seedIndices))
{
+ reportFailure?.Invoke($"Constrained trim triangulation rejected input ({triangulationFailure}); secondary ear clipping did not produce a complete region.");
return null;
}
- var mesh = new RefinableMesh(cellU, cellV, evaluate, evaluateNormal, options.ChordTolerance, options.AngularToleranceRadians, maximumCellLength);
+ var mesh = new RefinableMesh(cellU, cellV, evaluate, evaluateNormal, options.ChordTolerance, options.AngularToleranceRadians, maximumCellLength, perceptualNormals, grid.HasValue);
var pointMap = new int[seedPoints.Count];
for (var i = 0; i < seedPoints.Count; i++)
{
pointMap[i] = mesh.AddVertex(seedPoints[i].X * cellU, seedPoints[i].Y * cellV);
}
- for (var i = 0; i + 2 < seedIndices.Count; i += 3)
+ if (grid is { } localGrid)
{
- var a = pointMap[seedIndices[i]];
- var b = pointMap[seedIndices[i + 1]];
- var c = pointMap[seedIndices[i + 2]];
- if (a == b || b == c || a == c)
+ for (var v = 0; v + 1 < localGrid.V.Count; v++) for (var u = 0; u + 1 < localGrid.U.Count; u++)
{
- continue;
+ checkBudget?.Invoke();
+ var u0 = localGrid.U[u]; var u1 = localGrid.U[u + 1];
+ var v0 = localGrid.V[v]; var v1 = localGrid.V[v + 1];
+ List<(double U, double V)> InCell(IReadOnlyList<(double U, double V)> polygon) =>
+ Clip(Clip(Clip(Clip(polygon, u0, true, true), u1, true, false), v0, false, true), v1, false, false);
+ var cellOuter = InCell(outer);
+ if (cellOuter.Count < 3) continue;
+ var cellHoles = holes.Select(h => InCell(h)).Where(h => h.Count >= 3).ToList();
+ List<(double X, double Y)> Local(IReadOnlyList<(double U, double V)> polygon) =>
+ polygon.Select(p => ((p.U - u0) / (u1 - u0), (p.V - v0) / (v1 - v0))).ToList();
+ // Clipping a concave loop can yield disconnected components joined by
+ // zero-width boundary bridges. Earcut cures those locally. Its area
+ // guard rejects an incomplete region; then clip the validated global
+ // seed triangles in this exceptional cell only.
+ if (EarCutTriangulator.TryTriangulate(Local(cellOuter),
+ cellHoles.Select(h => (IReadOnlyList<(double X, double Y)>)Local(h)).ToList(),
+ out var points, out var triangles))
+ {
+ var map = points.Select(p => mesh.AddVertex(u0 + p.X * (u1 - u0), v0 + p.Y * (v1 - v0))).ToArray();
+ for (var p = 0; p < triangles.Count; p += 3)
+ mesh.AddTriangle(map[triangles[p]], map[triangles[p + 1]], map[triangles[p + 2]]);
+ }
+ else
+ {
+ for (var i = 0; i + 2 < seedIndices.Count; i += 3)
+ {
+ var polygon = InCell(new[] { mesh.Vertex(pointMap[seedIndices[i]]),
+ mesh.Vertex(pointMap[seedIndices[i + 1]]), mesh.Vertex(pointMap[seedIndices[i + 2]]) });
+ if (polygon.Count < 3) continue;
+ var anchor = mesh.AddVertex(polygon[0].U, polygon[0].V);
+ for (var p = 1; p + 1 < polygon.Count; p++)
+ {
+ var x = polygon[p]; var y = polygon[p + 1]; var z = polygon[0];
+ var area = (x.U - z.U) * (y.V - z.V) - (x.V - z.V) * (y.U - z.U);
+ if (double.Abs(area / (cellU * cellV)) <= 1e-14d) continue;
+ // Only this convex intersection may use an anchor fan.
+ mesh.AddTriangle(anchor, mesh.AddVertex(x.U, x.V), mesh.AddVertex(y.U, y.V));
+ }
+ }
+ }
+ if (mesh.AliveTriangleCount > maximumTriangles)
+ {
+ reportFailure?.Invoke($"Local trim decomposition exceeded its {maximumTriangles} seed-triangle budget.");
+ return null;
+ }
}
-
- mesh.AddTriangle(a, b, c);
}
+ else for (var i = 0; i + 2 < seedIndices.Count; i += 3)
+ mesh.AddTriangle(pointMap[seedIndices[i]], pointMap[seedIndices[i + 1]], pointMap[seedIndices[i + 2]]);
- if (!mesh.Refine(checkBudget))
+ if (!mesh.Refine(checkBudget, maximumTriangles))
{
+ reportFailure?.Invoke("Conforming refinement exceeded its propagation guard.");
return null;
}
+ refinementIncomplete = mesh.RefinementIncomplete;
var positions = new List<Point3D>(mesh.VertexCount);
var normals = new List<Vector3D>(mesh.VertexCount);
@@ -173,12 +250,38 @@ internal static class BoundaryConformingTrimTessellator
if (indices.Count == 0)
{
+ reportFailure?.Invoke("Constrained trim triangulation produced no nondegenerate triangles.");
return null;
}
return new DisplayFaceMeshPatch(faceId, positions, normals, indices);
}
+ private static List<(double U, double V)> Clip(IReadOnlyList<(double U, double V)> input,
+ double line, bool alongU, bool keepGreater)
+ {
+ var output = new List<(double U, double V)>(input.Count + 1);
+ if (input.Count == 0) return output;
+ var previous = input[^1]; var previousValue = alongU ? previous.U : previous.V;
+ var previousInside = keepGreater ? previousValue >= line : previousValue <= line;
+ foreach (var point in input)
+ {
+ var value = alongU ? point.U : point.V;
+ var inside = keepGreater ? value >= line : value <= line;
+ if (inside != previousInside)
+ {
+ var fraction = (line - previousValue) / (value - previousValue);
+ // Pin the clipped coordinate to the grid line. Support vertices stay
+ // on the original chart; no averaged off-surface centre is introduced.
+ output.Add(alongU ? (line, previous.V + fraction * (point.V - previous.V))
+ : (previous.U + fraction * (point.U - previous.U), line));
+ }
+ if (inside) output.Add(point);
+ previous = point; previousValue = value; previousInside = inside;
+ }
+ return output;
+ }
+
private static List<(double X, double Y)> ToScaled(IReadOnlyList<(double U, double V)> loop, double cellU, double cellV)
{
var points = new List<(double X, double Y)>(loop.Count);
@@ -190,7 +293,7 @@ internal static class BoundaryConformingTrimTessellator
return points;
}
- private static bool IsAxisAlignedRectangle(IReadOnlyList<(double U, double V)> loop)
+ internal static bool IsAxisAlignedRectangle(IReadOnlyList<(double U, double V)> loop)
{
if (loop.Count != 4)
{
@@ -239,6 +342,8 @@ internal static class BoundaryConformingTrimTessellator
private readonly double _chordTolerance;
private readonly double _angularTolerance;
private readonly double _maximumCellLength;
+ private readonly bool _perceptualNormals;
+ private readonly bool _mergeClippingRoundoff;
private readonly List<Point3D?> _positions = new();
private readonly List<Vector3D?> _normals = new();
private readonly List<(double U, double V)> _vertices = new();
@@ -246,7 +351,7 @@ internal static class BoundaryConformingTrimTessellator
private readonly List<int> _triangles = new();
private readonly List<bool> _alive = new();
private readonly Dictionary<long, List<int>> _edgeTriangles = new();
- private readonly Stack<int> _work = new();
+ private readonly Queue<int> _work = new();
private int _aliveCount;
public RefinableMesh(
@@ -256,7 +361,9 @@ internal static class BoundaryConformingTrimTessellator
Func<double, double, Vector3D> evaluateNormal,
double chordTolerance,
double angularTolerance,
- double maximumCellLength)
+ double maximumCellLength,
+ bool perceptualNormals,
+ bool mergeClippingRoundoff)
{
_cellU = cellU;
_cellV = cellV;
@@ -265,6 +372,8 @@ internal static class BoundaryConformingTrimTessellator
_chordTolerance = chordTolerance;
_angularTolerance = angularTolerance;
_maximumCellLength = maximumCellLength;
+ _perceptualNormals = perceptualNormals;
+ _mergeClippingRoundoff = mergeClippingRoundoff;
}
public Point3D Position(int index)
@@ -301,7 +410,13 @@ internal static class BoundaryConformingTrimTessellator
public int AddVertex(double u, double v)
{
- var key = (BitConverter.DoubleToUInt64Bits(u), BitConverter.DoubleToUInt64Bits(v));
+ // Adjacent clips compute the same intersection in different arithmetic
+ // orders. Join at one billionth of a display cell to prevent numerical
+ // zero-width slivers and broken refinement adjacency. The first exact
+ // chart coordinate is retained; no support/trim binding is modified.
+ var keyU = _mergeClippingRoundoff ? double.Round(u / _cellU, 9) : u;
+ var keyV = _mergeClippingRoundoff ? double.Round(v / _cellV, 9) : v;
+ var key = (BitConverter.DoubleToUInt64Bits(keyU == 0 ? 0 : keyU), BitConverter.DoubleToUInt64Bits(keyV == 0 ? 0 : keyV));
if (_vertexLookup.TryGetValue(key, out var existing))
{
return existing;
@@ -317,6 +432,7 @@ internal static class BoundaryConformingTrimTessellator
public int AddTriangle(int a, int b, int c)
{
+ if (a == b || b == c || a == c) return -1;
var id = _alive.Count;
_triangles.Add(a);
_triangles.Add(b);
@@ -326,7 +442,7 @@ internal static class BoundaryConformingTrimTessellator
LinkEdge(a, b, id);
LinkEdge(b, c, id);
LinkEdge(c, a, id);
- _work.Push(id);
+ _work.Enqueue(id);
return id;
}
@@ -341,7 +457,7 @@ internal static class BoundaryConformingTrimTessellator
}
}
- public bool Refine(Action? checkBudget)
+ public bool Refine(Action? checkBudget, int maximumTriangles)
{
var iterations = 0;
while (_work.Count > 0)
@@ -351,12 +467,13 @@ internal static class BoundaryConformingTrimTessellator
checkBudget?.Invoke();
}
- if (_alive.Count > MaxTriangles)
+ if (_aliveCount > maximumTriangles)
{
+ RefinementIncomplete = true;
return true;
}
- var t = _work.Pop();
+ var t = _work.Dequeue();
if (!_alive[t] || !NeedsSplit(t))
{
continue;
@@ -386,13 +503,15 @@ internal static class BoundaryConformingTrimTessellator
if (_alive[t])
{
- _work.Push(t);
+ _work.Enqueue(t);
}
}
return true;
}
+ public bool RefinementIncomplete { get; private set; }
+
private bool NeedsSplit(int triangle)
{
var longest = LongestEdgeLength(triangle);
@@ -436,7 +555,12 @@ internal static class BoundaryConformingTrimTessellator
if (lp > 1e-12d && lq > 1e-12d)
{
var cosine = double.Clamp(np.Dot(nq) / (lp * lq), -1d, 1d);
- if (double.Acos(cosine) > _angularTolerance)
+ var angle = double.Acos(cosine);
+ // Normal variation over a visually negligible edge does not
+ // warrant further subdivision. This is a display-space sag
+ // estimate, independent of any engineering/recovery tolerance.
+ if (angle > _angularTolerance && (!_perceptualNormals
+ || (pp - pq).Length * double.Sin(angle * .25d) > _chordTolerance))
{
return true;
}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index b77255fd..a512922f 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -26,11 +26,6 @@ public static class BrepDisplayTessellator
private const string CylinderTrimDualSingleCoedgeClosedCircleSource = "Viewer.Tessellation.CylinderTrim.DualSingleCoedgeClosedCircle";
private const string CurvedTopologyUnsupportedSource = "Viewer.Tessellation.CurvedTopologyUnsupported";
private const string BSplineSurfaceTrimUnsupportedSource = "Viewer.Tessellation.BSplineSurfaceTrimUnsupported";
- private const string SphereTrimSingleCoedgeLatitudeCapSource = "Viewer.Tessellation.SphereTrim.SingleCoedgeLatitudeCap";
- private const string SphereTrimSingleCoedgeUnsupportedSource = "Viewer.Tessellation.SphereTrim.SingleCoedgeUnsupported";
- private const string SphereTrimTwoCoedgeBiArcLuneSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeBiArcLune";
- private const string SphereTrimTwoCoedgeBsplineBiArcSurrogateSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeBsplineBiArcSurrogate";
- private const string SphereTrimTwoCoedgeUnsupportedSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeUnsupported";
private const string PlanarMultiLoopTriangulationSkippedSource = "Viewer.Tessellation.PlanarMultiLoopTriangulationSkipped";
private const string TrimEvaluationFailedSource = "Viewer.Tessellation.TrimEvaluationFailed";
@@ -81,12 +76,6 @@ public static class BrepDisplayTessellator
surfaceKind,
executionBudget.Remaining + TimeSpan.FromMilliseconds(250));
- if (faceResult.IsSuccess)
- {
- facePatches.Add(faceResult.Value);
- continue;
- }
-
foreach (var diagnostic in faceResult.Diagnostics)
{
faceDiagnostics.Add(new DisplayFaceMaterializationDiagnostic(
@@ -96,6 +85,10 @@ public static class BrepDisplayTessellator
diagnostic.Source ?? diagnostic.Code.ToString(),
diagnostic.Message));
}
+ // A successful partial result can be an empty patch with a trim
+ // rejection warning. Keep that warning alongside the retained mesh.
+ if (faceResult.IsSuccess)
+ facePatches.Add(faceResult.Value);
}
catch (DisplayTessellationTimeoutException ex)
{
@@ -272,10 +265,10 @@ public static class BrepDisplayTessellator
{
return surface.Kind switch
{
- SurfaceGeometryKind.Plane => TessellatePlanarFace(body, faceId, surface.Plane!.Value, options, executionBudget),
+ SurfaceGeometryKind.Plane => TessellatePlanarFaceWithSamplingRetry(body, faceId, surface.Plane!.Value, options, executionBudget),
SurfaceGeometryKind.Cylinder => TessellateCylinderFace(body, faceId, surface.Cylinder!.Value, options, executionBudget),
SurfaceGeometryKind.Cone => TessellateConeFace(body, faceId, surface.Cone!.Value, options, executionBudget),
- SurfaceGeometryKind.Sphere => TessellateSphereFace(body, faceId, surface.Sphere!.Value, options),
+ SurfaceGeometryKind.Sphere => TessellateSphereFace(body, faceId, surface.Sphere!.Value, options, executionBudget),
SurfaceGeometryKind.Torus => TessellateTorusFace(body, faceId, surface.Torus!.Value, options, executionBudget),
SurfaceGeometryKind.BSplineSurfaceWithKnots => TessellateBSplineSurfaceFace(body, faceId, surface.BSplineSurfaceWithKnots!, options, executionBudget),
SurfaceGeometryKind.LinearExtrusion when surface.LinearExtrusion!.Value.Directrix.BSpline3 is { } curve
@@ -288,6 +281,19 @@ public static class BrepDisplayTessellator
};
}
+ private static KernelResult<DisplayFaceMeshPatch> TessellatePlanarFaceWithSamplingRetry(BrepBody body, FaceId faceId,
+ PlaneSurface plane, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? budget)
+ {
+ var patch = TessellatePlanarFace(body, faceId, plane, options, budget);
+ if (options.ChordTolerance <= DisplayTessellationOptions.Default.ChordTolerance
+ || patch.IsSuccess && patch.Value.TriangleIndices.Count > 0) return patch;
+ // Coarse display chords can cross a narrow valid trim. One bounded retry
+ // samples the same authoritative curves more finely; it does not heal loops.
+ return TessellatePlanarFace(body, faceId, plane, options with {
+ ChordTolerance = DisplayTessellationOptions.Default.ChordTolerance
+ }, budget);
+ }
+
private static KernelResult<DisplayFaceMeshPatch> TessellatePlanarFace(BrepBody body, FaceId faceId, PlaneSurface plane, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
var loopIds = body.GetLoopIds(faceId)
@@ -684,10 +690,20 @@ public static class BrepDisplayTessellator
var loopIds = body.GetLoopIds(faceId)
.Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)
.ToArray();
- // A one-loop helical gap is a narrow diagonal strip in cylinder UV.
- // Its bounding rectangle covers the rib footprint and is not a valid
- // display patch. Use the authored pcurves for this bounded trim family.
- if (loopIds.Length == 1 && body.GetCoedgeIds(loopIds[0]).Any(id =>
+ var recoveryAllowance = body.GetLoopIds(faceId).SelectMany(body.GetCoedgeIds)
+ .Select(id => body.GetEdgeCurve(body.Topology.GetCoedge(id).EdgeId).RecoveryProvenance)
+ .Where(p => p is not null)
+ .Select(p => double.Min(options.ChordTolerance,
+ double.Min(p!.RecoveryToleranceMillimetres, p.MeasuredMaxDeviationMillimetres)))
+ .DefaultIfEmpty(0d).Max();
+ // A bounded one-loop face can be a helical strip, a toothed skirt, or a
+ // narrow rectangular sector. Its bounding cylinder is not the trim.
+ // Prefer the complete bound parameter trace, retaining legacy dispatch
+ // for closed-circle/seam families without a polygonal pcurve boundary.
+ if (loopIds.Length == 1 && (body.GetCoedgeIds(loopIds[0]).Count >= 3
+ && body.GetCoedgeIds(loopIds[0]).Select(id => body.Topology.GetCoedge(id).EdgeId).Distinct().Count() == body.GetCoedgeIds(loopIds[0]).Count
+ && body.GetCoedgeIds(loopIds[0]).All(id => body.Bindings.TryGetPcurveBinding(id, out var pc) && pc.FaceId == faceId)
+ || body.GetCoedgeIds(loopIds[0]).Any(id =>
{
if (!body.Bindings.TryGetPcurveBinding(id, out var binding) || binding.FaceId != faceId)
return false;
@@ -695,10 +711,10 @@ public static class BrepDisplayTessellator
var start = binding.Pcurve.Evaluate(domain.Start);
var end = binding.Pcurve.Evaluate(domain.End);
return double.Abs(end.U - start.U) > 1e-8d && double.Abs(end.V - start.V) > 1e-8d;
- }))
+ })))
{
var uvLoops = TryBuildTrimmedSurfaceUvLoops(body, faceId, loopIds,
- point => TryProjectPointToCylinderUv(cylinder, point), options, executionBudget,
+ point => TryProjectPointToCylinderUv(cylinder, point, recoveryAllowance), options, executionBudget,
SurfaceGeometryKind.Cylinder);
if (!uvLoops.IsSuccess)
return KernelResult<DisplayFaceMeshPatch>.Failure(uvLoops.Diagnostics);
@@ -720,7 +736,7 @@ public static class BrepDisplayTessellator
if (loopIds.Length > 1)
{
- var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToCylinderUv(cylinder, point), options, executionBudget, SurfaceGeometryKind.Cylinder);
+ var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToCylinderUv(cylinder, point, recoveryAllowance), options, executionBudget, SurfaceGeometryKind.Cylinder);
if (!uvLoopsResult.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Success(
@@ -1060,26 +1076,20 @@ public static class BrepDisplayTessellator
surface.DomainEndV));
}
- var uvLoopsResult = TryBuildTrimmedSurfaceUvLoops(
- body,
- faceId,
- loopIds,
- new BSplineUvProjector(surface).Project,
- options,
- executionBudget,
- SurfaceGeometryKind.BSplineSurfaceWithKnots);
+ var projector = new BSplineUvProjector(surface);
+ var uvLoopsResult = BuildSplineDisplayTrim(body, faceId, loopIds, projector, options, executionBudget);
if (!uvLoopsResult.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Success(
CreateEmptyPlanarPatch(faceId),
[CreateValidationWarning(
- $"Face {faceId.Value} BSpline trim evaluation failed ({string.Join(" | ", uvLoopsResult.Diagnostics.Select(diagnostic => diagnostic.Message))}); skipping face patch to avoid misleading untrimmed geometry.",
+ $"Face {faceId.Value} BSpline trim evaluation failed ({string.Join(" | ", uvLoopsResult.Diagnostics.Select(diagnostic => diagnostic.Message))}); projection residual={projector.LastResidual:R} mm, candidate UV={projector.LastCandidate}, native domain=[{surface.DomainStartU:R},{surface.DomainEndU:R}]x[{surface.DomainStartV:R},{surface.DomainEndV:R}]; skipping face patch to avoid misleading untrimmed geometry.",
TrimEvaluationFailedSource)]);
}
return TrimmedSurfaceTessellator.Tessellate(
faceId,
- uvLoopsResult.Value,
+ NormalizeClosedSplineLoops(surface, uvLoopsResult.Value),
(u, v) => surface.Evaluate(u, v),
(u, v) => EvaluateBSplineNormal(surface, u, v),
options,
@@ -1089,177 +1099,109 @@ public static class BrepDisplayTessellator
surface.DomainEndV,
CreateValidationWarning,
executionBudget,
- SurfaceGeometryKind.BSplineSurfaceWithKnots);
+ SurfaceGeometryKind.BSplineSurfaceWithKnots,
+ splineSupport: surface);
}
- /// <summary>
- /// Projects 3D loop samples onto a B-spline surface. One instance serves all samples of a face: the coarse seed
- /// grid is evaluated once, and consecutive samples along a trim loop are near each other, so each projection first
- /// refines from the previous result and only falls back to the grid search when that fails.
- /// </summary>
- private sealed class BSplineUvProjector
+ /// <summary>Display projection reuses the qualified pcurve inverter, with a separate display budget.</summary>
+ internal static KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>> InspectSplineTrim(BrepBody body, FaceId faceId)
{
- private readonly BSplineSurfaceWithKnots _surface;
- private readonly int _coarseSegments;
- private readonly double _tolerance;
- private Point3D[]? _grid;
- private (double U, double V)? _last;
+ body.TryGetFaceSurface(faceId, out var surface);
+ var support = surface?.BSplineSurfaceWithKnots
+ ?? throw new ArgumentException("Face is not spline-supported.", nameof(faceId));
+ var input = BuildSplineDisplayTrim(body, faceId,
+ body.GetLoopIds(faceId).Where(id => body.Topology.GetLoop(id).Kind == LoopKind.Edge).ToArray(),
+ new BSplineUvProjector(support), DisplayTessellationOptions.ForViewport(body), null);
+ return input.IsSuccess ? KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Success(
+ NormalizeClosedSplineLoops(support, input.Value)) : input;
+ }
- public BSplineUvProjector(BSplineSurfaceWithKnots surface)
- {
- _surface = surface;
- // Coarse grid seed. Scale with the control net so long, thin or heavily curved patches
- // (e.g. gear tooth flanks) still seed inside the correct basin.
- var controlRows = surface.ControlPoints.Count;
- var controlColumns = controlRows > 0 ? surface.ControlPoints[0].Count : 0;
- _coarseSegments = System.Math.Clamp(System.Math.Max(controlRows, controlColumns) * 4, 16, 32);
- _tolerance = ComputeBSplineProjectionTolerance(surface);
- }
+ private static KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>> BuildSplineDisplayTrim(
+ BrepBody body, FaceId faceId, IReadOnlyList<LoopId> loopIds, BSplineUvProjector projector,
+ DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget)
+ {
+ var input = TryBuildTrimmedSurfaceUvLoops(body, faceId, loopIds, projector.Project,
+ options, executionBudget, SurfaceGeometryKind.BSplineSurfaceWithKnots);
+ if (!input.IsSuccess || !input.Value.Any(IsCollapsedSplineLoop)
+ || !loopIds.SelectMany(body.GetCoedgeIds).All(id =>
+ body.Bindings.TryGetPcurveBinding(id, out var binding)
+ && binding.Qualification?.Origin == PcurveBindingOrigin.RecoveredSpline)) return input;
+ // A recovered parameter trace may flatten a feature smaller than its lift
+ // budget. Display samples the actual bounded edges onto the existing support;
+ // retained source pcurves, BRep bindings and export remain unchanged.
+ return TryBuildTrimmedSurfaceUvLoops(body, faceId, loopIds, projector.Project, options with {
+ MinimumSegments = System.Math.Min(options.MaximumSegments, System.Math.Max(64, options.MinimumSegments))
+ }, executionBudget, SurfaceGeometryKind.BSplineSurfaceWithKnots, preferBoundPcurves: false);
+ }
- public (double U, double V)? Project(Point3D point)
+ private static bool IsCollapsedSplineLoop(IReadOnlyList<(double U, double V)> loop)
+ {
+ if (loop.Count < 3) return true;
+ var width = loop.Max(p => p.U) - loop.Min(p => p.U);
+ var height = loop.Max(p => p.V) - loop.Min(p => p.V);
+ var origin = loop[0];
+ var twiceArea = 0d;
+ for (var i = 0; i < loop.Count; i++)
{
- if (_last is { } seed)
- {
- var warm = Refine(seed.U, seed.V, point);
- if (warm.HasValue)
- {
- _last = warm;
- return warm;
- }
- }
-
- var cold = SeedFromGrid(point);
- var result = Refine(cold.U, cold.V, point);
- if (result.HasValue)
- {
- _last = result;
- }
-
- return result;
+ var a = loop[i]; var b = loop[(i + 1) % loop.Count];
+ twiceArea += (a.U - origin.U) * (b.V - origin.V) - (b.U - origin.U) * (a.V - origin.V);
}
+ return width <= 0d || height <= 0d || double.Abs(twiceArea) <= width * height * 1e-10d;
+ }
- private (double U, double V) SeedFromGrid(Point3D point)
+ internal static IReadOnlyList<IReadOnlyList<(double U, double V)>> NormalizeClosedSplineLoops(
+ BSplineSurfaceWithKnots surface, IReadOnlyList<IReadOnlyList<(double U, double V)>> loops)
+ {
+ return loops.Select(loop =>
{
- var surface = _surface;
- var n = _coarseSegments;
- var uStart = surface.DomainStartU;
- var vStart = surface.DomainStartV;
- var uStep = (surface.DomainEndU - uStart) / n;
- var vStep = (surface.DomainEndV - vStart) / n;
- if (_grid is null)
- {
- var grid = new Point3D[(n + 1) * (n + 1)];
- for (var iu = 0; iu <= n; iu++)
- {
- for (var iv = 0; iv <= n; iv++)
- {
- grid[(iu * (n + 1)) + iv] = surface.Evaluate(uStart + (uStep * iu), vStart + (vStep * iv));
- }
- }
-
- _grid = grid;
- }
+ var points = loop.ToArray();
+ Normalize(surface.UClosed, surface.DomainStartU, surface.DomainEndU, true);
+ Normalize(surface.VClosed, surface.DomainStartV, surface.DomainEndV, false);
+ return (IReadOnlyList<(double U, double V)>)points;
- var bestU = uStart;
- var bestV = vStart;
- var bestDistanceSquared = double.PositiveInfinity;
- for (var iu = 0; iu <= n; iu++)
+ void Normalize(bool closed, double start, double end, bool alongU)
{
- for (var iv = 0; iv <= n; iv++)
+ if (!closed || points.Length == 0) return;
+ var period = end - start;
+ for (var i = 1; i < points.Length; i++)
{
- var delta = _grid[(iu * (n + 1)) + iv] - point;
- var distanceSquared = delta.Dot(delta);
- if (distanceSquared < bestDistanceSquared)
- {
- bestDistanceSquared = distanceSquared;
- bestU = uStart + (uStep * iu);
- bestV = vStart + (vStep * iv);
- }
+ var p = points[i];
+ points[i] = alongU
+ ? (BrepPcurveRecovery.UnwrapNear(p.U, points[i - 1].U, period), p.V)
+ : (p.U, BrepPcurveRecovery.UnwrapNear(p.V, points[i - 1].V, period));
}
+ var minimum = points.Min(p => alongU ? p.U : p.V);
+ var shift = double.Floor((minimum - start + period * 1e-8d) / period) * period;
+ for (var i = 0; i < points.Length; i++)
+ points[i] = alongU ? (points[i].U - shift, points[i].V) : (points[i].U, points[i].V - shift);
}
+ }).ToArray();
+ }
- return (bestU, bestV);
- }
-
- // Levenberg-Marquardt refinement of |S(u,v) - P|^2, clamped to the surface domain. The previous
- // fixed 6-step pattern search only resolved ~1/640 of the domain, which left residuals above the
- // acceptance tolerance for perfectly valid boundary samples and dropped whole faces.
- private (double U, double V)? Refine(double startU, double startV, Point3D point)
- {
- var surface = _surface;
- var uStart = surface.DomainStartU;
- var uEnd = surface.DomainEndU;
- var vStart = surface.DomainStartV;
- var vEnd = surface.DomainEndV;
- var uSpan = uEnd - uStart;
- var vSpan = vEnd - vStart;
- var bestU = startU;
- var bestV = startV;
- var startDelta = surface.Evaluate(bestU, bestV) - point;
- var bestDistanceSquared = startDelta.Dot(startDelta);
- var lambda = 1e-3d;
- var done = false;
- for (var iteration = 0; iteration < 60 && !done; iteration++)
- {
- var uPlus = System.Math.Min(bestU + (uSpan * 1e-6d), uEnd);
- var uMinus = System.Math.Max(bestU - (uSpan * 1e-6d), uStart);
- var vPlus = System.Math.Min(bestV + (vSpan * 1e-6d), vEnd);
- var vMinus = System.Math.Max(bestV - (vSpan * 1e-6d), vStart);
- if (uPlus - uMinus <= 0d || vPlus - vMinus <= 0d)
- {
- break;
- }
-
- var tangentU = (surface.Evaluate(uPlus, bestV) - surface.Evaluate(uMinus, bestV)) * (1d / (uPlus - uMinus));
- var tangentV = (surface.Evaluate(bestU, vPlus) - surface.Evaluate(bestU, vMinus)) * (1d / (vPlus - vMinus));
- var residualVector = surface.Evaluate(bestU, bestV) - point;
- var a11 = tangentU.Dot(tangentU);
- var a12 = tangentU.Dot(tangentV);
- var a22 = tangentV.Dot(tangentV);
- var b1 = -tangentU.Dot(residualVector);
- var b2 = -tangentV.Dot(residualVector);
-
- var accepted = false;
- for (var attempt = 0; attempt < 10 && !accepted; attempt++)
- {
- var m11 = (a11 * (1d + lambda)) + 1e-30d;
- var m22 = (a22 * (1d + lambda)) + 1e-30d;
- var determinant = (m11 * m22) - (a12 * a12);
- if (!(System.Math.Abs(determinant) > 1e-300d))
- {
- lambda *= 10d;
- continue;
- }
-
- var stepU = ((b1 * m22) - (a12 * b2)) / determinant;
- var stepV = ((m11 * b2) - (a12 * b1)) / determinant;
- var candidateU = System.Math.Clamp(bestU + stepU, uStart, uEnd);
- var candidateV = System.Math.Clamp(bestV + stepV, vStart, vEnd);
- var candidateDelta = surface.Evaluate(candidateU, candidateV) - point;
- var candidateDistanceSquared = candidateDelta.Dot(candidateDelta);
- if (candidateDistanceSquared < bestDistanceSquared)
- {
- done = System.Math.Abs(candidateU - bestU) <= uSpan * 1e-13d
- && System.Math.Abs(candidateV - bestV) <= vSpan * 1e-13d;
- bestU = candidateU;
- bestV = candidateV;
- bestDistanceSquared = candidateDistanceSquared;
- lambda = System.Math.Max(lambda * 0.3d, 1e-12d);
- accepted = true;
- }
- else
- {
- lambda *= 10d;
- }
- }
+ private sealed class BSplineUvProjector
+ {
+ private readonly BSplineSurfaceWithKnots _surface;
+ private readonly double _tolerance;
+ private SurfaceParameterPoint? _last;
+ public double LastResidual { get; private set; }
+ public (double U, double V) LastCandidate { get; private set; }
- if (!accepted)
- {
- break;
- }
- }
+ public BSplineUvProjector(BSplineSurfaceWithKnots surface)
+ {
+ _surface = surface;
+ _tolerance = ComputeBSplineProjectionTolerance(surface);
+ }
- return System.Math.Sqrt(bestDistanceSquared) > _tolerance ? null : (bestU, bestV);
+ public (double U, double V)? Project(Point3D point)
+ {
+ var result = BrepPcurveRecovery.ProjectSplinePoint(_surface, point, _last, _tolerance);
+ if (!result.Success && _last is not null)
+ result = BrepPcurveRecovery.ProjectSplinePoint(_surface, point, null, _tolerance);
+ LastResidual = result.Residual;
+ LastCandidate = (result.Uv.U, result.Uv.V);
+ if (!result.Success) return null;
+ _last = result.Uv;
+ return LastCandidate;
}
}
@@ -1634,7 +1576,7 @@ public static class BrepDisplayTessellator
// 1e-3 mm off the analytic surface. UV projection here is for display, so accept anything below visual resolution.
private const double AnalyticProjectionDeviationFloor = 1e-2d;
- private static (double U, double V)? TryProjectPointToCylinderUv(CylinderSurface cylinder, Point3D point)
+ private static (double U, double V)? TryProjectPointToCylinderUv(CylinderSurface cylinder, Point3D point, double recoveryAllowance = 0d)
{
var axis = cylinder.Axis.ToVector();
var xAxis = cylinder.XAxis.ToVector();
@@ -1643,7 +1585,10 @@ public static class BrepDisplayTessellator
var axial = offset.Dot(axis);
var radial = offset - (axis * axial);
var radialLength = radial.Length;
- var tolerance = System.Math.Max(AnalyticProjectionDeviationFloor, cylinder.Radius * 1e-4d);
+ // A measured recovered edge can depart from its exact cylindrical support by more than
+ // the analytic floor. Bound this face-local display projection by its recorded recovery
+ // deviation and the display chord budget; pcurve and kernel budgets remain independent.
+ var tolerance = System.Math.Max(recoveryAllowance, System.Math.Max(AnalyticProjectionDeviationFloor, cylinder.Radius * 1e-4d));
if (!double.IsFinite(radialLength) || System.Math.Abs(radialLength - cylinder.Radius) > tolerance)
{
return null;
@@ -1697,13 +1642,14 @@ public static class BrepDisplayTessellator
Func<Point3D, (double U, double V)?> projectPointToUv,
DisplayTessellationOptions options,
DisplayTessellationExecutionBudget? executionBudget = null,
- SurfaceGeometryKind? surfaceKind = null)
+ SurfaceGeometryKind? surfaceKind = null,
+ bool preferBoundPcurves = true)
{
var uvLoops = new List<IReadOnlyList<(double U, double V)>>(loopIds.Count);
foreach (var loopId in loopIds.OrderBy(id => id.Value))
{
executionBudget?.ThrowIfExpired("TrimLoopDispatch", faceId, surfaceKind);
- var uvLoop = TryBuildTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options, executionBudget, surfaceKind);
+ var uvLoop = TryBuildTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options, executionBudget, surfaceKind, preferBoundPcurves);
if (!uvLoop.IsSuccess)
{
return KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Failure(uvLoop.Diagnostics);
@@ -1722,14 +1668,15 @@ public static class BrepDisplayTessellator
Func<Point3D, (double U, double V)?> projectPointToUv,
DisplayTessellationOptions options,
DisplayTessellationExecutionBudget? executionBudget = null,
- SurfaceGeometryKind? surfaceKind = null)
+ SurfaceGeometryKind? surfaceKind = null,
+ bool preferBoundPcurves = true)
{
var coedges = body.GetCoedgeIds(loopId).Select(id => body.Topology.GetCoedge(id)).ToArray();
- if (coedges.Length < 3)
+ if (coedges.Length == 0)
{
return KernelResult<IReadOnlyList<(double U, double V)>>.Failure([
CreateNotImplemented(
- $"Face {faceId.Value} parametric trim loop must contain at least three coedges. Observed {coedges.Length}.",
+ $"Face {faceId.Value} parametric trim loop has no coedges.",
BSplineSurfaceTrimUnsupportedSource)]);
}
@@ -1745,17 +1692,27 @@ public static class BrepDisplayTessellator
executionBudget?.ThrowIfExpired("TrimLoopSampling", faceId, surfaceKind);
// Consume the bound face-space authority when available. Numerical 3D
// reprojection is only the legacy fallback for bodies without pcurves.
- if (body.Bindings.TryGetPcurveBinding(coedge.Id, out var pc) && pc.FaceId == faceId)
+ if (preferBoundPcurves && body.Bindings.TryGetPcurveBinding(coedge.Id, out var pc) && pc.FaceId == faceId)
{
var edge = body.Bindings.GetEdgeBinding(coedge.EdgeId);
var reversed = coedge.IsReversed ^ !edge.OrientedEdgeSense ^ !pc.SameSense;
- var segments = pc.Pcurve.Kind == PcurveGeometryKind.Line ? 1 : System.Math.Max(32, options.MinimumSegments);
+ var segments = pc.Pcurve.Kind == PcurveGeometryKind.Line ? 2 : System.Math.Max(32, options.MinimumSegments);
+ // Imported analytic pcurves may use different equivalent angular
+ // charts on neighbouring edges. Translate the whole coedge by an
+ // integral turn at its join; preserve its authored sweep internally.
+ // Pointwise wrapping would erase legitimate multi-turn helices.
+ var angularOffset = 0d;
+ if (uvPoints.Count > 0 && surfaceKind is SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone)
+ {
+ var first = pc.Pcurve.Evaluate(reversed ? pc.Pcurve.Domain.End : pc.Pcurve.Domain.Start);
+ angularOffset = 2d * double.Pi * double.Round((uvPoints[^1].U - first.U) / (2d * double.Pi));
+ }
for (var i = 0; i <= segments; i++)
{
var fraction = (double)i / segments;
if (reversed) fraction = 1 - fraction;
var uv = pc.Pcurve.Evaluate(pc.Pcurve.Domain.Start + fraction * (pc.Pcurve.Domain.End - pc.Pcurve.Domain.Start));
- AppendUniqueUvPoint(uvPoints, (uv.U, uv.V));
+ AppendUniqueUvPoint(uvPoints, (uv.U + angularOffset, uv.V));
}
continue;
}
@@ -1903,16 +1860,52 @@ public static class BrepDisplayTessellator
return normalized;
}
- private static KernelResult<DisplayFaceMeshPatch> TessellateSphereFace(BrepBody body, FaceId faceId, SphereSurface sphere, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellateSphereFace(BrepBody body, FaceId faceId, SphereSurface sphere, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
- var trimPatchResult = TryResolveSphereTrimPatch(body, faceId, sphere);
- if (!trimPatchResult.IsSuccess)
+ var edgeLoops = body.GetLoopIds(faceId).Where(id => body.Topology.GetLoop(id).Kind == LoopKind.Edge).ToArray();
+ if (edgeLoops.Length > 0)
{
- return KernelResult<DisplayFaceMeshPatch>.Failure(trimPatchResult.Diagnostics);
+ var sampledLoops = new List<(LoopId Id, IReadOnlyList<Point3D> Points)>();
+ foreach (var loopId in edgeLoops)
+ {
+ var coedges = body.GetCoedgeIds(loopId).Select(body.Topology.GetCoedge).ToArray();
+ var vertices = BuildLoopVertexPointLookup(body, coedges, faceId);
+ if (!vertices.IsSuccess) return KernelResult<DisplayFaceMeshPatch>.Failure(vertices.Diagnostics);
+ var points = new List<Point3D>();
+ foreach (var coedge in coedges)
+ {
+ var sampled = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertices.Value, options, executionBudget, SurfaceGeometryKind.Sphere);
+ if (!sampled.IsSuccess) return KernelResult<DisplayFaceMeshPatch>.Failure(sampled.Diagnostics);
+ var boundarySamples = sampled.Value;
+ var edge = body.Topology.GetEdge(coedge.EdgeId);
+ if (body.Bindings.TryGetPcurveBinding(coedge.Id, out var pc) && pc.FaceId == faceId)
+ {
+ var binding = body.Bindings.GetEdgeBinding(edge.Id);
+ var reversed = coedge.IsReversed ^ !binding.OrientedEdgeSense ^ !pc.SameSense;
+ var count = System.Math.Max(32, boundarySamples.Count - 1);
+ boundarySamples = Enumerable.Range(0, count + 1).Select(i =>
+ {
+ var t = reversed ? 1d - (double)i / count : (double)i / count;
+ var uv = pc.Pcurve.Evaluate(pc.Pcurve.Domain.Start + t * (pc.Pcurve.Domain.End - pc.Pcurve.Domain.Start));
+ return sphere.Evaluate(uv.U, uv.V);
+ }).ToArray();
+ }
+ // Endpoint matching cannot determine a closed edge's direction.
+ // The spherical chart needs directed winding to choose the cap;
+ // consume the existing coedge/curve sense for that singular case.
+ else if (edge.StartVertexId == edge.EndVertexId && (coedge.IsReversed ^ !body.Bindings.GetEdgeBinding(edge.Id).OrientedEdgeSense))
+ boundarySamples = boundarySamples.Reverse().ToArray();
+ points.AddRange(boundarySamples.Skip(points.Count > 0 ? 1 : 0));
+ }
+ sampledLoops.Add((loopId, points));
+ }
+ var outerIndex = Array.FindIndex(edgeLoops, id => body.Bindings.TryGetFaceBoundaryRoleBinding(id, out var role) && role.Role == FaceBoundaryRole.Outer);
+ return SphericalTrimTessellator.Tessellate(faceId, sphere, sampledLoops.Select(l => l.Points).ToArray(),
+ outerIndex < 0 ? 0 : outerIndex, body.Bindings.GetFaceBinding(faceId).Orientation.IsAlignedWithSurface,
+ options, executionBudget);
}
-
- var trimPatch = trimPatchResult.Value;
- var angularSegments = CalculateSegmentCount(trimPatch.USpan, sphere.Radius, options);
+ // With no edge boundary, retained vertex loops are zero-dimensional punctures of the support.
+ var angularSegments = CalculateSegmentCount(2d * double.Pi, sphere.Radius, options);
var elevationSegments = System.Math.Max(2, System.Math.Clamp(angularSegments / 2, options.MinimumSegments / 2, options.MaximumSegments));
return KernelResult<DisplayFaceMeshPatch>.Success(CreateBoundedGridPatch(
@@ -1921,11 +1914,10 @@ public static class BrepDisplayTessellator
elevationSegments,
(u, v) => sphere.Evaluate(u, v),
(u, v) => sphere.Normal(u, v).ToVector(),
- trimPatch.UStart,
- trimPatch.UStart + trimPatch.USpan,
- trimPatch.VStart,
- trimPatch.VEnd),
- trimPatchResult.Diagnostics);
+ 0d,
+ 2d * double.Pi,
+ -double.Pi / 2d,
+ double.Pi / 2d));
}
@@ -3072,296 +3064,6 @@ public static class BrepDisplayTessellator
return new DisplayFaceMeshPatch(faceId, positions, normals, indices);
}
- private static KernelResult<(double UStart, double USpan, double VStart, double VEnd)> TryResolveSphereTrimPatch(
- BrepBody body,
- FaceId faceId,
- SphereSurface sphere)
- {
- var loopIds = body.GetLoopIds(faceId)
- .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)
- .ToArray();
- if (loopIds.Length == 0)
- {
- return KernelResult<(double, double, double, double)>.Success((0d, 2d * double.Pi, -double.Pi / 2d, double.Pi / 2d));
- }
-
- if (loopIds.Length != 1)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} sphere tessellation currently supports exactly one edge trim loop. Observed {loopIds.Length} edge loops.")]);
- }
-
- var coedges = body.GetCoedgeIds(loopIds[0]).Select(id => body.Topology.GetCoedge(id)).ToArray();
- if (coedges.Length == 1)
- {
- var singleCoedgeResolution = TryResolveSingleCoedgeSphereTrimPatch(body, faceId, sphere, coedges[0]);
- if (singleCoedgeResolution.IsSuccess)
- {
- return singleCoedgeResolution;
- }
-
- return KernelResult<(double, double, double, double)>.Failure(singleCoedgeResolution.Diagnostics);
- }
-
- if (coedges.Length == 2)
- {
- var twoCoedgeResolution = TryResolveTwoCoedgeSphereTrimPatch(body, faceId, sphere, coedges);
- if (twoCoedgeResolution.IsSuccess)
- {
- return twoCoedgeResolution;
- }
-
- return KernelResult<(double, double, double, double)>.Failure(twoCoedgeResolution.Diagnostics);
- }
-
- if (coedges.Length < 3)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} spherical trim loop must contain at least three coedges. Observed {coedges.Length}.")]);
- }
-
- return TryResolveGeneralSphereTrimPatch(body, faceId, sphere, coedges);
- }
-
- private static KernelResult<(double UStart, double USpan, double VStart, double VEnd)> TryResolveTwoCoedgeSphereTrimPatch(
- BrepBody body,
- FaceId faceId,
- SphereSurface sphere,
- IReadOnlyList<Coedge> coedges)
- {
- if (coedges.Count != 2)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} spherical two-coedge trim resolver expected exactly two coedges. Observed {coedges.Count}.", SphereTrimTwoCoedgeUnsupportedSource)]);
- }
-
- var firstCurve = body.GetEdgeCurve(coedges[0].EdgeId);
- var secondCurve = body.GetEdgeCurve(coedges[1].EdgeId);
- var isBiArcCircleLune = firstCurve.Kind == CurveGeometryKind.Circle3 && secondCurve.Kind == CurveGeometryKind.Circle3;
- var isBsplineBiArcSurrogate = firstCurve.Kind == CurveGeometryKind.BSpline3 && secondCurve.Kind == CurveGeometryKind.BSpline3;
- if (!isBiArcCircleLune && !isBsplineBiArcSurrogate)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical two-coedge trim classified as unsupported subfamily (requires bi-arc circle pair or bspline bi-arc surrogate pair; observed edge kinds '{firstCurve.UnsupportedKind ?? firstCurve.Kind.ToString()}' and '{secondCurve.UnsupportedKind ?? secondCurve.Kind.ToString()}').",
- SphereTrimTwoCoedgeUnsupportedSource)]);
- }
-
- if (!body.TryGetEdgeVertices(coedges[0].EdgeId, out var firstStartVertexId, out var firstEndVertexId)
- || !body.TryGetEdgeVertices(coedges[1].EdgeId, out var secondStartVertexId, out var secondEndVertexId))
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical two-coedge trim classified as unsupported subfamily (missing edge vertex topology).",
- SphereTrimTwoCoedgeUnsupportedSource)]);
- }
-
- var uniqueVertexIds = new HashSet<VertexId> { firstStartVertexId, firstEndVertexId, secondStartVertexId, secondEndVertexId };
- if (uniqueVertexIds.Count != 2)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical two-coedge trim classified as unsupported subfamily (expected two shared vertices; observed {uniqueVertexIds.Count}).",
- SphereTrimTwoCoedgeUnsupportedSource)]);
- }
-
- var generalResolution = TryResolveGeneralSphereTrimPatch(body, faceId, sphere, coedges);
- if (!generalResolution.IsSuccess)
- {
- return generalResolution;
- }
-
- if (isBiArcCircleLune)
- {
- return KernelResult<(double, double, double, double)>.Success(
- generalResolution.Value,
- [CreateClassificationInfo(
- $"Face {faceId.Value} spherical two-coedge trim classified as bi-arc circle lune with two shared vertices (edges {coedges[0].EdgeId.Value}/{coedges[1].EdgeId.Value}).",
- SphereTrimTwoCoedgeBiArcLuneSource)]);
- }
-
- return KernelResult<(double, double, double, double)>.Success(
- generalResolution.Value,
- [CreateClassificationInfo(
- $"Face {faceId.Value} spherical two-coedge trim classified as bspline bi-arc surrogate pair with two shared vertices (edges {coedges[0].EdgeId.Value}/{coedges[1].EdgeId.Value}).",
- SphereTrimTwoCoedgeBsplineBiArcSurrogateSource)]);
- }
-
- private static KernelResult<(double UStart, double USpan, double VStart, double VEnd)> TryResolveGeneralSphereTrimPatch(
- BrepBody body,
- FaceId faceId,
- SphereSurface sphere,
- IReadOnlyList<Coedge> coedges)
- {
- const double minAngularSpan = 1e-6d;
- const double minElevationSpan = 1e-6d;
-
- var vertexPointsResult = BuildLoopVertexPointLookup(body, coedges, faceId);
- if (!vertexPointsResult.IsSuccess)
- {
- return KernelResult<(double, double, double, double)>.Failure(vertexPointsResult.Diagnostics);
- }
-
- var allAzimuths = new List<double>();
- var allElevations = new List<double>();
-
- foreach (var coedge in coedges)
- {
- var curve = body.GetEdgeCurve(coedge.EdgeId);
- if (curve.Kind != CurveGeometryKind.Circle3
- && curve.Kind != CurveGeometryKind.BSpline3
- && curve.Kind != CurveGeometryKind.Ellipse3
- && curve.Kind != CurveGeometryKind.Line3)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} spherical trim tessellation supports only line/circle/ellipse/bspline loop edges in this milestone. Observed curve kind '{curve.UnsupportedKind ?? curve.Kind.ToString()}'.")]);
- }
-
- var endpoints = GetEdgeEndpoints(body, coedge.EdgeId, coedge.IsReversed, vertexPointsResult.Value);
- if (!endpoints.IsSuccess)
- {
- return KernelResult<(double, double, double, double)>.Failure(endpoints.Diagnostics);
- }
-
- AppendSphereUv(allAzimuths, allElevations, sphere, endpoints.Value.Start);
- AppendSphereUv(allAzimuths, allElevations, sphere, endpoints.Value.End);
-
- var edgePolyline = TessellateEdge(body, coedge.EdgeId, options: DisplayTessellationOptions.Default);
- if (edgePolyline.IsSuccess)
- {
- var edgePoints = coedge.IsReversed
- ? edgePolyline.Value.Points.Reverse().ToArray()
- : edgePolyline.Value.Points;
-
- foreach (var point in edgePoints)
- {
- AppendSphereUv(allAzimuths, allElevations, sphere, point);
- }
- }
- }
-
- if (allAzimuths.Count == 0 || allElevations.Count == 0)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} spherical trim tessellation could not derive loop parameter samples.")]);
- }
-
- var angularBounds = ResolveAngularBounds(allAzimuths);
- if (!angularBounds.IsSuccess || angularBounds.Value.Span <= minAngularSpan)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} spherical trim tessellation derived a degenerate azimuth span.")]);
- }
-
- var vStart = allElevations.Min();
- var vEnd = allElevations.Max();
- if ((vEnd - vStart) <= minElevationSpan)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} spherical trim tessellation derived a degenerate elevation span.")]);
- }
-
- vStart = System.Math.Clamp(vStart, -double.Pi / 2d, double.Pi / 2d);
- vEnd = System.Math.Clamp(vEnd, -double.Pi / 2d, double.Pi / 2d);
-
- return KernelResult<(double, double, double, double)>.Success((angularBounds.Value.Start, angularBounds.Value.Span, vStart, vEnd));
- }
-
- private static KernelResult<(double UStart, double USpan, double VStart, double VEnd)> TryResolveSingleCoedgeSphereTrimPatch(
- BrepBody body,
- FaceId faceId,
- SphereSurface sphere,
- Coedge coedge)
- {
- const double fullWrapTolerance = 1e-3d;
- const double axisAlignmentTolerance = 1e-4d;
- const double axisOffsetTolerance = 1e-4d;
- const double circleRadiusTolerance = 1e-4d;
- const double minElevationSpan = 1e-6d;
-
- var curve = body.GetEdgeCurve(coedge.EdgeId);
- if (curve.Kind != CurveGeometryKind.Circle3)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim supports only closed full-circle latitude loops. Observed curve kind '{curve.UnsupportedKind ?? curve.Kind.ToString()}'.",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- if (!body.TryGetEdgeVertices(coedge.EdgeId, out var startVertexId, out var endVertexId) || startVertexId != endVertexId)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim expected a closed edge use. Observed edge {coedge.EdgeId.Value} with distinct vertices {startVertexId.Value}->{endVertexId.Value}.",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- if (!body.Bindings.TryGetEdgeBinding(coedge.EdgeId, out var edgeBinding)
- || edgeBinding.TrimInterval is not ParameterInterval trimInterval
- || !double.IsFinite(trimInterval.Start)
- || !double.IsFinite(trimInterval.End)
- || double.Abs((trimInterval.End - trimInterval.Start) - (2d * double.Pi)) > fullWrapTolerance)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim expected a full-circle edge trim interval. Observed trim [{edgeBinding.TrimInterval?.Start:R}, {edgeBinding.TrimInterval?.End:R}].",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- var circle = curve.Circle3!.Value;
- var axisDot = circle.Normal.ToVector().Dot(sphere.Axis.ToVector());
- if (double.Abs(double.Abs(axisDot) - 1d) > axisAlignmentTolerance)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim classified as unsupported subfamily (edge={coedge.EdgeId.Value}, axisAlignment={axisDot:R}); expected circle normal parallel to sphere axis.",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- var centerOffset = circle.Center - sphere.Center;
- var axialDistance = centerOffset.Dot(sphere.Axis.ToVector());
- var radialOffsetVector = centerOffset - (sphere.Axis.ToVector() * axialDistance);
- var radialOffset = radialOffsetVector.Length;
- if (radialOffset > (sphere.Radius * axisOffsetTolerance))
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim classified as unsupported subfamily (edge={coedge.EdgeId.Value}, circle-center-axis-offset={radialOffset:R}); expected latitude circle centered on sphere axis.",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- var latitude = double.Asin(System.Math.Clamp(axialDistance / sphere.Radius, -1d, 1d));
- var expectedCircleRadius = sphere.Radius * double.Cos(latitude);
- var circleRadiusDelta = double.Abs(circle.Radius - expectedCircleRadius);
- if (circleRadiusDelta > (sphere.Radius * circleRadiusTolerance))
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim classified as unsupported subfamily (edge={coedge.EdgeId.Value}, circleRadius={circle.Radius:R}, expectedLatitudeRadius={expectedCircleRadius:R}); expected latitude circle.",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- var positivePoleDistance = double.Abs((double.Pi / 2d) - latitude);
- var negativePoleDistance = double.Abs((-double.Pi / 2d) - latitude);
- var pole = positivePoleDistance <= negativePoleDistance ? (double.Pi / 2d) : (-double.Pi / 2d);
-
- var vStart = System.Math.Min(latitude, pole);
- var vEnd = System.Math.Max(latitude, pole);
- if ((vEnd - vStart) <= minElevationSpan)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented(
- $"Face {faceId.Value} spherical single-coedge trim collapsed at a pole (latitude {latitude:R}).",
- SphereTrimSingleCoedgeUnsupportedSource)]);
- }
-
- return KernelResult<(double, double, double, double)>.Success(
- (0d, 2d * double.Pi, vStart, vEnd),
- [CreateClassificationInfo(
- $"Face {faceId.Value} spherical single-coedge trim classified as closed full-wrap constant-latitude cap (edge {coedge.EdgeId.Value}, latitude {latitude:R}, pole {(pole > 0d ? "+pi/2" : "-pi/2")}).",
- SphereTrimSingleCoedgeLatitudeCapSource)]);
- }
-
private static KernelResult<(double UStart, double UEnd, double VStart, double VEnd)> TryResolveCylinderTrimPatch(
BrepBody body,
FaceId faceId,
@@ -4257,23 +3959,6 @@ public static class BrepDisplayTessellator
return normalized;
}
- private static void AppendSphereUv(List<double> azimuths, List<double> elevations, SphereSurface sphere, Point3D point)
- {
- var fromCenter = point - sphere.Center;
- var radial = fromCenter.Length;
- if (!double.IsFinite(radial) || radial <= 1e-9d)
- {
- return;
- }
-
- var normalized = fromCenter / radial;
- var x = normalized.Dot(sphere.XAxis.ToVector());
- var y = normalized.Dot(sphere.YAxis.ToVector());
- var z = normalized.Dot(sphere.Axis.ToVector());
- azimuths.Add(double.Atan2(y, x));
- elevations.Add(System.Math.Asin(System.Math.Clamp(z, -1d, 1d)));
- }
-
private static int FindNextCoedgeIndex(
IReadOnlyList<(Point3D Start, Point3D End)> endpoints,
IReadOnlyList<bool> used,
@@ -4673,10 +4358,6 @@ public static class BrepDisplayTessellator
private static KernelDiagnostic CreateValidationError(string message, string source)
=> new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source);
- // A successful, informational classification of a trim (not a skipped or degraded face): must not surface as a warning.
- private static KernelDiagnostic CreateClassificationInfo(string message, string source)
- => new(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info, message, source);
-
private static KernelDiagnostic CreateValidationWarning(string message, string source)
=> new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning, message, source);
}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationOptions.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationOptions.cs
index bf6c8544..8365ca52 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationOptions.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationOptions.cs
@@ -15,6 +15,24 @@ public sealed record DisplayTessellationOptions(
MinimumSegments: 12,
MaximumSegments: 256);
+ /// <summary>Automatic static viewport quality for a fitted model, independent of STEP and mesh-export budgets.</summary>
+ public static DisplayTessellationOptions ForViewport(BrepBody body)
+ {
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? (Math.Point3D?)p : null)
+ .Where(p => p.HasValue).Select(p => p!.Value)
+ .Concat(body.Geometry.Surfaces.SelectMany(s => s.Value.BSplineSurfaceWithKnots?.ControlPoints
+ .SelectMany(row => row) ?? []))
+ .Concat(body.Geometry.Curves.SelectMany(c => c.Value.BSpline3?.ControlPoints ?? []))
+ .ToArray();
+ if (points.Length < 2) return Default;
+ var diagonal = new Math.Vector3D(points.Max(p => p.X) - points.Min(p => p.X),
+ points.Max(p => p.Y) - points.Min(p => p.Y), points.Max(p => p.Z) - points.Min(p => p.Z)).Length;
+ if (!(diagonal > 0d) || !double.IsFinite(diagonal)) return Default;
+ // A bounded fitted-preview budget. Large imported
+ // models have a bounded coarser budget; small parts retain finer silhouettes.
+ return Default with { ChordTolerance = double.Clamp(diagonal / 300d, .01d, .25d), MaximumSegments = 1024 };
+ }
+
public static KernelResult<DisplayTessellationOptions> Create(
double angularToleranceRadians,
double chordTolerance,
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationResult.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationResult.cs
index 6c889dcc..64dfb851 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationResult.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationResult.cs
@@ -30,7 +30,8 @@ public sealed record DisplayFaceMeshPatch(
IReadOnlyList<Vector3D> Normals,
IReadOnlyList<int> TriangleIndices,
DisplayFaceMeshSource Source = DisplayFaceMeshSource.Tessellator,
- string? ScaffoldRejectionReason = null);
+ string? ScaffoldRejectionReason = null,
+ IReadOnlyList<SurfaceMeshCell>? Cells = null);
public sealed record DisplayEdgePolyline(
EdgeId EdgeId,
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/EarCutTriangulator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/EarCutTriangulator.cs
index 1cc26ab0..3ef51db3 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/EarCutTriangulator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/EarCutTriangulator.cs
@@ -1,3 +1,4 @@
+// Adapted from Mapbox Earcut, ISC license. See THIRD_PARTY_NOTICES.md.
namespace Aetheris.Kernel.Core.Brep.Tessellation;
/// <summary>
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SphericalTrimTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SphericalTrimTessellator.cs
new file mode 100644
index 00000000..984be1dc
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SphericalTrimTessellator.cs
@@ -0,0 +1,81 @@
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep.Tessellation;
+
+/// <summary>
+/// A stereographic chart removes the native longitude seam and latitude poles
+/// from a bounded spherical face. Its inverse evaluates the exact sphere;
+/// triangulation and chord/normal refinement remain shared with other supports.
+/// Source loops, including holes, are never replaced by their UV bounding box.
+/// </summary>
+internal static class SphericalTrimTessellator
+{
+ public static KernelResult<DisplayFaceMeshPatch> Tessellate(FaceId faceId, SphereSurface sphere,
+ IReadOnlyList<IReadOnlyList<Point3D>> loops, int outerIndex, bool aligned,
+ DisplayTessellationOptions options, DisplayTessellationExecutionBudget? budget)
+ {
+ KernelDiagnostic Warning(string message, string source) => new(KernelDiagnosticCode.ValidationFailed,
+ KernelDiagnosticSeverity.Warning, message, source);
+ KernelResult<DisplayFaceMeshPatch> Fail(string reason) => KernelResult<DisplayFaceMeshPatch>.Failure([
+ new(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error,
+ $"Face {faceId.Value} spherical trim: {reason}", "Viewer.Tessellation.SphereTrim.ChartUnsupported")]);
+
+ var directions = new List<IReadOnlyList<Vector3D>>();
+ foreach (var loop in loops)
+ {
+ if (loop.Count < 3) return Fail("fewer than three boundary samples");
+ var points = new List<Vector3D>();
+ foreach (var point in loop)
+ {
+ var offset = point - sphere.Center;
+ var residual = double.Abs(offset.Length - sphere.Radius);
+ if (!double.IsFinite(residual) || residual > options.ChordTolerance)
+ return Fail($"boundary support residual={residual:R} mm exceeds display chord budget={options.ChordTolerance:R} mm");
+ var direction = offset * (1d / offset.Length);
+ if (points.Count == 0 || (direction - points[^1]).Length > 1e-10) points.Add(direction);
+ }
+ if (points.Count > 1 && (points[0] - points[^1]).Length <= 1e-10) points.RemoveAt(points.Count - 1);
+ if (points.Count < 3) return Fail("collapsed boundary has no two-dimensional region");
+ directions.Add(points);
+ }
+ var outer = directions[outerIndex];
+ // The directed vector area, rather than a sample centroid, picks the
+ // material-side interior. A nonuniformly sampled great circle has an
+ // in-plane centroid and would put the chart singularity on its boundary.
+ var center = new Vector3D(0, 0, 0);
+ for (var i = 0; i < outer.Count; i++) center += outer[i].Cross(outer[(i + 1) % outer.Count]);
+ if (!aligned) center = -center;
+ if (center.Length <= 1e-10) return Fail("outer boundary does not determine a bounded chart");
+ center *= 1d / center.Length;
+ var reference = double.Abs(center.Dot(sphere.Axis.ToVector())) < .9 ? sphere.Axis.ToVector() : sphere.XAxis.ToVector();
+ var x = reference - center * reference.Dot(center);
+ x *= 1d / x.Length;
+ var y = center.Cross(x);
+ var chartLoops = new List<IReadOnlyList<(double U, double V)>>();
+ foreach (var loop in directions)
+ {
+ var projected = new List<(double U, double V)>();
+ foreach (var point in loop)
+ {
+ var denominator = 1d + point.Dot(center);
+ if (denominator <= 1e-8) return Fail("boundary crosses the excluded stereographic chart pole");
+ projected.Add((point.Dot(x) / denominator, point.Dot(y) / denominator));
+ }
+ chartLoops.Add(projected);
+ }
+ Vector3D Direction(double u, double v)
+ {
+ var squared = u * u + v * v;
+ return (center * (1d - squared) + x * (2d * u) + y * (2d * v)) * (1d / (1d + squared));
+ }
+ return TrimmedSurfaceTessellator.Tessellate(faceId, chartLoops,
+ (u, v) => sphere.Center + Direction(u, v) * sphere.Radius, Direction, options,
+ double.NegativeInfinity, double.PositiveInfinity, double.NegativeInfinity, double.PositiveInfinity,
+ Warning, budget, SurfaceGeometryKind.Sphere, outerIndex);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SplineRectangleTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SplineRectangleTessellator.cs
new file mode 100644
index 00000000..23a2cd24
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SplineRectangleTessellator.cs
@@ -0,0 +1,161 @@
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep.Tessellation;
+
+/// <summary>Bounded display sampling for rectangular spline trims; native knots prevent periodic aliasing.</summary>
+internal static class SplineRectangleTessellator
+{
+ public static DisplayFaceMeshPatch? Tessellate(FaceId faceId, BSplineSurfaceWithKnots support,
+ double uStart, double uEnd, double vStart, double vEnd,
+ Func<double, double, Vector3D> normal, DisplayTessellationOptions options,
+ Action? checkBudget, int maximumTriangles, out bool incomplete)
+ {
+ var grid = PlanGrid(support, uStart, uEnd, vStart, vEnd, options, checkBudget, maximumTriangles, out incomplete);
+ if (grid is null) return null;
+ var us = grid.Value.U; var vs = grid.Value.V;
+ var positions = new List<Point3D>(us.Count * vs.Count);
+ var normals = new List<Vector3D>(us.Count * vs.Count);
+ var indices = new List<int>((us.Count - 1) * (vs.Count - 1) * 6);
+ var cells = new List<SurfaceMeshCell>((us.Count - 1) * (vs.Count - 1));
+ foreach (var v in vs)
+ {
+ checkBudget?.Invoke();
+ foreach (var u in us) { positions.Add(support.Evaluate(u, v)); normals.Add(normal(u, v)); }
+ }
+ for (var j = 0; j < vs.Count - 1; j++) for (var i = 0; i < us.Count - 1; i++)
+ {
+ var a = j * us.Count + i; var b = a + 1; var c = a + us.Count; var d = c + 1;
+ cells.Add(new QuadCell([a, c, d, b]));
+ }
+ foreach (var cell in cells)
+ SurfaceMeshIrTessellator.AppendQuadTriangles(positions, cell.VertexIds, indices);
+ return new(faceId, positions, normals, indices, Cells: cells);
+ }
+
+ // Shared by rectangles and local decomposition of nonrectangular trims.
+ internal static (List<double> U, List<double> V)? PlanGrid(BSplineSurfaceWithKnots support,
+ double uStart, double uEnd, double vStart, double vEnd,
+ DisplayTessellationOptions options, Action? checkBudget, int maximumTriangles, out bool incomplete)
+ {
+ var us = Seeds(support.KnotValuesU, uStart, uEnd, true);
+ var vs = Seeds(support.KnotValuesV, vStart, vEnd, false);
+ if (us.Count - 1 > options.MaximumSegments || vs.Count - 1 > options.MaximumSegments
+ || (long)(us.Count - 1) * (vs.Count - 1) * 2 > maximumTriangles)
+ { incomplete = true; return null; }
+ // Inspect across every original knot span, not just the opposite axis midpoint.
+ // A long helicoidal support can return to the same point between coarse samples.
+ var crossU = CrossSamples(us); var crossV = CrossSamples(vs);
+ var limited = false;
+ Refine(us, crossV, true);
+ Refine(vs, crossU, false);
+ // UV units can be arbitrarily stretched. Balance physical cell edges after
+ // chord refinement, preserving native knot lines and the same work limits.
+ for (var pass = 0; pass < 8; pass++)
+ {
+ var uLengths = SpanLengths(us, true); var vLengths = SpanLengths(vs, false);
+ var changed = Balance(us, uLengths, Median(vLengths), true);
+ changed |= Balance(vs, vLengths, Median(uLengths), false);
+ if (!changed) break;
+ }
+ incomplete = limited;
+ return (us, vs);
+
+ double[] SpanLengths(List<double> values, bool alongU)
+ {
+ var otherStart = alongU ? vStart : uStart; var otherEnd = alongU ? vEnd : uEnd;
+ return values.Zip(values.Skip(1), (start, end) =>
+ {
+ checkBudget?.Invoke();
+ return new[] { .25d, .5d, .75d }.Max(fraction =>
+ {
+ var other = otherStart + (otherEnd - otherStart) * fraction;
+ return (alongU ? support.Evaluate(end, other) - support.Evaluate(start, other)
+ : support.Evaluate(other, end) - support.Evaluate(other, start)).Length;
+ });
+ }).ToArray();
+ }
+
+ double Median(double[] lengths)
+ {
+ var valid = lengths.Where(length => length > options.ChordTolerance * .01d).Order().ToArray();
+ return valid.Length == 0 ? 0d : valid[valid.Length / 2];
+ }
+
+ bool Balance(List<double> values, double[] lengths, double transverse, bool alongU)
+ {
+ if (transverse <= 0d) return false;
+ var changed = false;
+ for (var i = lengths.Length - 1; i >= 0; i--)
+ {
+ if (lengths[i] <= System.Math.Max(options.ChordTolerance, transverse * 4d)) continue;
+ var otherCount = alongU ? vs.Count : us.Count;
+ if (values.Count > options.MaximumSegments || (long)values.Count * (otherCount - 1) * 2 > maximumTriangles)
+ { limited = true; continue; }
+ values.Insert(i + 1, (values[i] + values[i + 1]) * .5d); changed = true;
+ }
+ return changed;
+ }
+
+ List<double> Seeds(IReadOnlyList<double> knots, double start, double end, bool alongU)
+ {
+ var sorted = knots.Where(k => k > start && k < end)
+ .Concat(Enumerable.Range(0, options.MinimumSegments + 1).Select(i => start + (end - start) * i / options.MinimumSegments))
+ .Append(start).Append(end).Distinct().Order().ToList();
+ // Uniform seeds can land within rounding distance of a native knot.
+ // Merge only nearly coincident lines with sampled physical separation
+ // below one ten-thousandth of the display chord budget. Kernel knots
+ // remain untouched; this avoids vanishing-width display cell rows.
+ var merged = new List<double> { start };
+ foreach (var value in sorted.Skip(1))
+ {
+ if (value - merged[^1] <= (end - start) * 1e-6d
+ && new[] { 0d, .5d, 1d }.All(fraction =>
+ {
+ var other = alongU ? vStart + (vEnd - vStart) * fraction : uStart + (uEnd - uStart) * fraction;
+ return (alongU ? support.Evaluate(value, other) - support.Evaluate(merged[^1], other)
+ : support.Evaluate(other, value) - support.Evaluate(other, merged[^1])).Length <= options.ChordTolerance * 1e-4d;
+ }))
+ {
+ if (value == end) merged[^1] = end;
+ continue;
+ }
+ merged.Add(value);
+ }
+ return merged;
+ }
+
+ static double[] CrossSamples(List<double> values) => values.Concat(values.Zip(values.Skip(1), (a, b) => (a + b) * .5d)).Order().ToArray();
+
+ void Refine(List<double> values, double[] cross, bool alongU)
+ {
+ for (var i = 0; i < values.Count - 1;)
+ {
+ checkBudget?.Invoke();
+ var start = values[i]; var end = values[i + 1];
+ var failed = cross.Any(other => NeedsSplit(start, end, other, alongU));
+ if (!failed) { i++; continue; }
+ var otherCount = alongU ? vs.Count : us.Count;
+ if (values.Count > options.MaximumSegments || (long)values.Count * (otherCount - 1) * 2 > maximumTriangles
+ || end - start <= (alongU ? uEnd - uStart : vEnd - vStart) * 1e-9d)
+ { limited = true; i++; continue; }
+ values.Insert(i + 1, (start + end) * .5d);
+ }
+ }
+
+ bool NeedsSplit(double start, double end, double other, bool alongU)
+ {
+ Point3D At(double t) => alongU ? support.Evaluate(t, other) : support.Evaluate(other, t);
+ var a = At(start); var b = At(end);
+ foreach (var fraction in new[] { .25d, .5d, .75d })
+ {
+ var p = At(start + (end - start) * fraction);
+ var chord = a + (b - a) * fraction;
+ // Half the display budget per direction reserves error for mixed-cell diagonals.
+ if ((p - chord).Length > options.ChordTolerance * .5d) return true;
+ }
+ return false;
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs
index 6b245d0a..fb0fd3fd 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs
@@ -302,7 +302,7 @@ public static class SurfaceMeshIrTessellator
}
else
{
- if (patch.Support.Plane is { } plane && PlanarPolygonTriangulator.TryTriangulate(ids.Select(id => vertexById[id].Position).ToArray(), plane.Normal.ToVector(), out var localIndices, out _))
+ if (TryTriangulateBoundaryCell(patch, ids, vertexById, out var localIndices))
{
for (var i = 0; i < localIndices.Count; i += 3)
{
@@ -312,13 +312,11 @@ public static class SurfaceMeshIrTessellator
}
else
{
- var center = new Point3D(ids.Average(id => vertexById[id].Position.X), ids.Average(id => vertexById[id].Position.Y), ids.Average(id => vertexById[id].Position.Z));
- var centerIndex = positions.Count; positions.Add(center); normals.Add(exactNormal(center));
- for (var i = 0; i < ids.Count; i++)
- {
- var a = indexById[ids[i]]; var b = indexById[ids[(i + 1) % ids.Count]];
- indices.AddRange([centerIndex, a, b]); normals[a] = exactNormal(positions[a]); normals[b] = exactNormal(positions[b]);
- }
+ // No general centre fan: an untriangulable cell rejects this
+ // optional IR route, allowing the caller's diagnostic fallback.
+ mesh = new TriangleMesh(positions, normals, [], new HashSet<(int, int)>(), "");
+ report = new(false, false, false, 0, 0, 0, 0, 0, positions.Count, 0);
+ return false;
}
}
}
@@ -1828,30 +1826,53 @@ public static class SurfaceMeshIrTessellator
if (cell.Kind == SurfaceMeshCellKind.Quad)
{
var a = Add(ids[0]); var b = Add(ids[1]); var c = Add(ids[2]); var d = Add(ids[3]);
- var ac = (positions[a] - positions[c]).Length; var bd = (positions[b] - positions[d]).Length;
- var acValid = TriangleAreaMagnitude(positions[a], positions[b], positions[c]) > Epsilon && TriangleAreaMagnitude(positions[a], positions[c], positions[d]) > Epsilon;
- var bdValid = TriangleAreaMagnitude(positions[a], positions[b], positions[d]) > Epsilon && TriangleAreaMagnitude(positions[b], positions[c], positions[d]) > Epsilon;
- if (acValid && (!bdValid || ac <= bd)) { indices.AddRange([a, b, c, a, c, d]); } else { indices.AddRange([a, b, d, b, c, d]); }
+ AppendQuadTriangles(positions, [a, b, c, d], indices);
}
else if (cell.Kind == SurfaceMeshCellKind.Triangle) indices.AddRange([Add(ids[0]), Add(ids[1]), Add(ids[2])]);
else if (ids.Count >= 3)
{
- if (patch.Support.Plane is { } plane && PlanarPolygonTriangulator.TryTriangulate(ids.Select(id => vertexById[id].Position).ToArray(), plane.Normal.ToVector(), out var localIndices, out _))
+ if (TryTriangulateBoundaryCell(patch, ids, vertexById, out var localIndices))
{
for (var i = 0; i < localIndices.Count; i += 3)
indices.AddRange([Add(ids[localIndices[i]]), Add(ids[localIndices[i + 1]]), Add(ids[localIndices[i + 2]])]);
}
else
{
- var center = new Point3D(ids.Average(id => vertexById[id].Position.X), ids.Average(id => vertexById[id].Position.Y), ids.Average(id => vertexById[id].Position.Z));
- var centerIndex = positions.Count; positions.Add(center); normals.Add(normal(center));
- for (var i = 0; i < ids.Count; i++) indices.AddRange([centerIndex, Add(ids[i]), Add(ids[(i + 1) % ids.Count])]);
+ throw new InvalidOperationException($"Face {patch.FaceId.Value} has an untriangulable boundary cell; no centre fan is permitted.");
}
}
}
return new DisplayFaceMeshPatch(patch.FaceId, positions, normals, indices, DisplayFaceMeshSource.SurfaceMeshIr);
}
+ private static bool TryTriangulateBoundaryCell(SurfacePatch patch, IReadOnlyList<int> ids,
+ IReadOnlyDictionary<int, SurfaceMeshVertex> vertices, out IReadOnlyList<int> indices)
+ {
+ indices = [];
+ var points = ids.Select(id => vertices[id]).ToArray();
+ if (patch.Support.Plane is { } plane)
+ return PlanarPolygonTriangulator.TryTriangulate(points.Select(p => p.Position).ToArray(),
+ patch.IsAlignedWithSupport ? plane.Normal.ToVector() : -plane.Normal.ToVector(), out indices, out _);
+ if (points.Any(p => p.U is null || p.V is null)) return false;
+ var uv = points.Select(p => new Point3D(p.U!.Value, p.V!.Value, 0)).ToArray();
+ var area = Enumerable.Range(0, uv.Length).Sum(i => uv[i].X * uv[(i + 1) % uv.Length].Y - uv[(i + 1) % uv.Length].X * uv[i].Y);
+ // Cell order already carries resolved face orientation. Preserve it in the
+ // local chart rather than reinterpreting STEP source SAME_SENSE.
+ return PlanarPolygonTriangulator.TryTriangulate(uv, new Vector3D(0, 0, area >= 0 ? 1 : -1), out indices, out _);
+ }
+
+ // Shared final lowering for retained quad cells. Prefer the shorter valid diagonal;
+ // ties are deterministic and no vertex is introduced away from the support.
+ internal static void AppendQuadTriangles(IReadOnlyList<Point3D> positions, IReadOnlyList<int> ids, List<int> indices)
+ {
+ var a = ids[0]; var b = ids[1]; var c = ids[2]; var d = ids[3];
+ var ac = (positions[a] - positions[c]).Length; var bd = (positions[b] - positions[d]).Length;
+ var acValid = TriangleAreaMagnitude(positions[a], positions[b], positions[c]) > Epsilon && TriangleAreaMagnitude(positions[a], positions[c], positions[d]) > Epsilon;
+ var bdValid = TriangleAreaMagnitude(positions[a], positions[b], positions[d]) > Epsilon && TriangleAreaMagnitude(positions[b], positions[c], positions[d]) > Epsilon;
+ if (acValid && (!bdValid || ac <= bd)) indices.AddRange([a, b, c, a, c, d]);
+ else indices.AddRange([a, b, d, b, c, d]);
+ }
+
private static Func<Point3D, Vector3D> ResolvePatchNormal(SurfaceMeshDocument document, SurfacePatch patch, IReadOnlyDictionary<int, SurfaceMeshVertex> vertices)
{
return patch.Support.Kind switch
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
index 4842ca88..e2f64aff 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
@@ -1,5 +1,6 @@
using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
@@ -25,7 +26,9 @@ internal static class TrimmedSurfaceTessellator
double vDomainEnd,
Func<string, string, KernelDiagnostic> createWarning,
DisplayTessellationExecutionBudget? executionBudget = null,
- SurfaceGeometryKind? surfaceKind = null)
+ SurfaceGeometryKind? surfaceKind = null,
+ int? explicitOuterLoopIndex = null,
+ BSplineSurfaceWithKnots? splineSupport = null)
{
executionBudget?.ThrowIfExpired("TrimmedSurface.Start", faceId, surfaceKind);
if (uvLoops.Count == 0)
@@ -49,7 +52,7 @@ internal static class TrimmedSurfaceTessellator
normalizedLoops.Add(normalized);
}
- var outerLoopIndex = SelectOuterLoop(normalizedLoops);
+ var outerLoopIndex = explicitOuterLoopIndex ?? SelectOuterLoop(normalizedLoops);
var trimContext = TrimEvaluationContext.Create(normalizedLoops, outerLoopIndex);
var (uStartRaw, uEndRaw, vStartRaw, vEndRaw) = trimContext.OuterLoop.Bounds;
@@ -77,18 +80,55 @@ internal static class TrimmedSurfaceTessellator
// isotropic in UV although the surface only curves in one direction (a cone or cylinder), every needed split
// across the curved direction also forces the same number of splits along the straight one. Size the cells
// from the surface's actual turning in each direction instead.
- // Free-form B-spline patches can curve anywhere between the sampled iso-curves, so they keep the uniform
- // seed grid; the estimate is only trusted for analytic surfaces whose curvature is constant per direction.
+ // Free-form B-splines use native knot spans below; sparse turning estimates are trusted only for analytic
+ // surfaces, since a spline can complete several turns between the sampled iso-curves.
var (curvedU, curvedV) = surfaceKind == SurfaceGeometryKind.BSplineSurfaceWithKnots
? (uSegments, vSegments)
: EstimateCurvatureSegments(evaluate, evaluateNormal, uStart, uEnd, vStart, vEnd, options);
+ var refineRectangle = false;
+ if (splineSupport is { } spline)
+ {
+ // A free-form surface can turn several times between uniform samples. Native knot spans
+ // bound the refinement cell size so midpoint tests do not alias a whole coil/profile period.
+ var nativeU = KnotSegments(spline.KnotValuesU, uStart, uEnd);
+ var nativeV = KnotSegments(spline.KnotValuesV, vStart, vEnd);
+ refineRectangle = nativeU > uSegments || nativeV > vSegments;
+ curvedU = System.Math.Max(curvedU, nativeU);
+ curvedV = System.Math.Max(curvedV, nativeV);
+ }
// Sampled straight trim edges (cone generators, cylinder rulings) arrive as many UV-collinear points. They
// add nothing but sliver triangles, so drop vertices that lie exactly on the segment between their neighbours.
var cellUForSimplify = (uEnd - uStart) / curvedU;
var cellVForSimplify = (vEnd - vStart) / curvedV;
var simplifiedLoops = normalizedLoops
- .Select(loop => RemoveCollinearVertices(loop, cellUForSimplify, cellVForSimplify))
+ .Select(loop => RemoveCollinearVertices(loop, cellUForSimplify, cellVForSimplify,
+ splineSupport is null ? null : evaluate, options.ChordTolerance * 1e-3d))
.ToList();
+ // Keep adaptive work bounded by the existing display grid's maximum axis budget,
+ // rather than truncating a long surface midway through it. This raises no sampling
+ // density or tolerance: only failed chord/normal tests request a subdivision.
+ var maximumTriangles = (int)System.Math.Clamp((long)options.MaximumSegments * options.MaximumSegments, 12_000, 65_536);
+ if (refineRectangle && splineSupport is { } rectangleSupport && simplifiedLoops.Count == 1
+ && IsDisplayRectangle(simplifiedLoops[0]))
+ {
+ var rectangle = SplineRectangleTessellator.Tessellate(faceId, rectangleSupport,
+ uStart, uEnd, vStart, vEnd, evaluateNormal, options,
+ () => executionBudget?.ThrowIfExpired("TrimmedSurface.SplineRectangle", faceId, surfaceKind),
+ maximumTriangles, out var limited);
+ if (rectangle is not null) return KernelResult<DisplayFaceMeshPatch>.Success(rectangle, limited ? [createWarning(
+ $"Face {faceId.Value} knot-aligned display sampling reached its axis/triangle budget; retained rectangular patch covers the complete trim with limited fidelity.",
+ "Viewer.Tessellation.RefinementIncomplete")] : []);
+ }
+ if (!refineRectangle && splineSupport is not null && simplifiedLoops.Count == 1
+ && IsDisplayRectangle(simplifiedLoops[0]))
+ simplifiedLoops[0] = [(uStart, vStart), (uEnd, vStart), (uEnd, vEnd), (uStart, vEnd)];
+ (List<double> U, List<double> V)? localGrid = null;
+ var gridIncomplete = false;
+ if (refineRectangle && splineSupport is { } trimSupport)
+ localGrid = SplineRectangleTessellator.PlanGrid(trimSupport, uStart, uEnd, vStart, vEnd,
+ options, () => executionBudget?.ThrowIfExpired("TrimmedSurface.SplineGrid", faceId, surfaceKind),
+ maximumTriangles / 2, out gridIncomplete);
+ string? conformingFailure = null;
var conformingPatch = BoundaryConformingTrimTessellator.TryTessellate(
faceId,
simplifiedLoops,
@@ -98,10 +138,23 @@ internal static class TrimmedSurfaceTessellator
(uEnd - uStart) / curvedU,
(vEnd - vStart) / curvedV,
options,
- () => executionBudget?.ThrowIfExpired("TrimmedSurface.Conforming", faceId, surfaceKind));
+ () => executionBudget?.ThrowIfExpired("TrimmedSurface.Conforming", faceId, surfaceKind),
+ out var refinementIncomplete,
+ refineRectangles: refineRectangle,
+ maximumTriangles: maximumTriangles,
+ perceptualNormals: splineSupport is not null,
+ grid: localGrid,
+ reportFailure: reason => conformingFailure = reason);
if (conformingPatch is not null)
{
- return KernelResult<DisplayFaceMeshPatch>.Success(conformingPatch);
+ var qualityWarnings = new List<KernelDiagnostic>();
+ if (refinementIncomplete) qualityWarnings.Add(createWarning(
+ $"Face {faceId.Value} adaptive surface refinement reached its {maximumTriangles} live-triangle budget before satisfying display chord/normal criteria; retained mesh is incomplete in fidelity.",
+ "Viewer.Tessellation.RefinementIncomplete"));
+ if (gridIncomplete) qualityWarnings.Add(createWarning(
+ $"Face {faceId.Value} local knot-grid planning reached its axis/cell budget; the full trim remains covered with limited display chord/edge balance fidelity.",
+ "Viewer.Tessellation.RefinementIncomplete"));
+ return KernelResult<DisplayFaceMeshPatch>.Success(conformingPatch, qualityWarnings);
}
var positions = new List<Point3D>((uSegments + 1) * (vSegments + 1));
@@ -140,7 +193,47 @@ internal static class TrimmedSurfaceTessellator
}
}
- return KernelResult<DisplayFaceMeshPatch>.Success(new DisplayFaceMeshPatch(faceId, positions, normals, indices));
+ return KernelResult<DisplayFaceMeshPatch>.Success(new DisplayFaceMeshPatch(faceId, positions, normals, indices),
+ indices.Count == 0 ? [createWarning(
+ $"Face {faceId.Value} trim triangulation rejected the loop set and native-domain clipping retained zero triangles; outer loop has {normalizedLoops[outerLoopIndex].Count} samples, signed UV area={ComputeSignedArea(normalizedLoops[outerLoopIndex]):R}, U=[{uStart:R},{uEnd:R}], V=[{vStart:R},{vEnd:R}]. No substitute surface was added.",
+ "Viewer.Tessellation.TrimEvaluationFailed")]
+ // Existing periodic/non-simple charts deliberately use native-grid masking;
+ // declining an outer-minus-holes strategy is normal dispatch there. Warn
+ // when the new knot-local spline strategy itself had to be abandoned.
+ : conformingFailure is null || localGrid is null ? [] : [createWarning(
+ $"Face {faceId.Value} boundary-conforming trim strategy failed: {conformingFailure} Retained conservative grid clipping has limited boundary fidelity; no fan or substitute support was added.",
+ "Viewer.Tessellation.RefinementIncomplete")]);
+
+ int KnotSegments(IReadOnlyList<double> knots, double start, double end)
+ {
+ var minimum = end - start;
+ for (var i = 1; i < knots.Count; i++)
+ {
+ var span = System.Math.Min(end, knots[i]) - System.Math.Max(start, knots[i - 1]);
+ if (span > 0d) minimum = System.Math.Min(minimum, span);
+ }
+
+ return (int)double.Clamp(double.Ceiling((end - start) / minimum), 1, options.MaximumSegments);
+ }
+
+ bool IsDisplayRectangle(IReadOnlyList<(double U, double V)> loop)
+ {
+ var area = (uEnd - uStart) * (vEnd - vStart);
+ if (area <= 0d || double.Abs(ComputeSignedArea(loop)) < area * .999d) return false;
+ foreach (var p in loop)
+ {
+ var candidates = new[] { (U: uStart, p.V), (U: uEnd, p.V), (p.U, V: vStart), (p.U, V: vEnd) };
+ var nearest = candidates.OrderBy(q => double.Abs(q.Item1 - p.U) / (uEnd - uStart)
+ + double.Abs(q.Item2 - p.V) / (vEnd - vStart)).First();
+ if (double.Abs(nearest.Item1 - p.U) > (uEnd - uStart) * 1e-6d
+ || double.Abs(nearest.Item2 - p.V) > (vEnd - vStart) * 1e-6d
+ || (evaluate(p.U, p.V) - evaluate(nearest.Item1, nearest.Item2)).Length > options.ChordTolerance * .1d)
+ return false;
+ }
+ // Numerical pcurve noise is snapped only in this disposable display
+ // rectangle; the engineering trim and native parameter map are retained.
+ return true;
+ }
void TryAppendTriangle(int ia, int ib, int ic)
{
@@ -353,7 +446,8 @@ internal static class TrimmedSurfaceTessellator
return (Estimate(alongU: true), Estimate(alongU: false));
}
- private static List<(double U, double V)> RemoveCollinearVertices(List<(double U, double V)> loop, double cellU, double cellV)
+ private static List<(double U, double V)> RemoveCollinearVertices(List<(double U, double V)> loop, double cellU, double cellV,
+ Func<double, double, Point3D>? evaluate = null, double physicalTolerance = 0d)
{
if (loop.Count <= 3 || !(cellU > 0d) || !(cellV > 0d))
{
@@ -384,7 +478,13 @@ internal static class TrimmedSurfaceTessellator
var along = ((ax * bx) + (ay * by)) / chordLengthSquared;
var deviation = double.Abs((ax * by) - (ay * bx)) / double.Sqrt(chordLengthSquared);
- if (along > 0d && along < 1d && deviation <= 1e-7d)
+ var collinear = deviation <= 1e-7d;
+ // Numerical inversion leaves tiny UV noise on exact spline iso-curves. Avoid sliver seeds
+ // only when the projected segment also agrees in 3D to one thousandth of the display budget.
+ if (!collinear && evaluate is not null && deviation <= 1e-5d)
+ collinear = (evaluate(current.U, current.V) - evaluate(
+ previous.U + along * (next.U - previous.U), previous.V + along * (next.V - previous.V))).Length <= physicalTolerance;
+ if (along > 0d && along < 1d && collinear)
{
kept.RemoveAt(i);
i--;
diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs
index d91b78df..8e528f35 100644
--- a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs
+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs
@@ -7,9 +7,9 @@ namespace Aetheris.Kernel.Core.Geometry.Surfaces;
/// <para>
/// Aetheris carries analytic geometry, and a spline face that is really a primitive is recovered as one. What is left
/// over are genuine free-form blends: variable-radius fillets and vertex blends that no primitive describes. Those
-/// still must not enter the kernel as NURBS, because a second surface representation costs every later stage a second
-/// code path. Since a circular section is not polynomial, the reduction is an approximation by construction, and the
-/// only honest way to run it is against a budget the source file itself sets.
+/// may remain rational import/display evidence, but production export requires non-rational authority. Since a
+/// circular section is not polynomial, reduction is an approximation by construction. Its budget comes from
+/// source accuracy during import or an explicit bounded engineering allowance during production normalization.
/// </para>
/// <para>
/// The reduction refines the knot vectors inside the existing domain and interpolates the rational surface at the
@@ -33,7 +33,9 @@ public static class BSplineSurfaceRationalReduction
/// cap keeps a pathological surface from growing an enormous control net instead of failing honestly.
/// </summary>
private const int MaximumSpanSubdivision = 32;
- private const int MaximumControlPointsPerAxis = 256;
+ // Long, narrow vendor nets can already contain hundreds of knots. The total bound still
+ // limits allocation; admitting those existing spans does not authorize unlimited refinement.
+ private const int MaximumControlPointsPerAxis = 1024;
private const int MaximumControlPoints = 8192;
private const int DeviationSamplesPerSpan = 3;
@@ -76,10 +78,12 @@ public static class BSplineSurfaceRationalReduction
}
var best = double.PositiveInfinity;
+ var lastDeviation = double.PositiveInfinity;
var controlLimitReached = false;
BSplineSurfaceWithKnots? Attempt(int subdivisionU, int subdivisionV)
{
+ lastDeviation = double.PositiveInfinity;
var refinedU = Subdivide(surface.KnotValuesU, surface.KnotMultiplicitiesU, subdivisionU);
var refinedV = Subdivide(surface.KnotValuesV, surface.KnotMultiplicitiesV, subdivisionV);
var countU = refinedU.Multiplicities.Sum() - surface.DegreeU - 1;
@@ -96,6 +100,7 @@ public static class BSplineSurfaceRationalReduction
}
var measured = MaximumDeviation(surface, attempt);
+ lastDeviation = measured;
best = double.Min(best, measured);
return measured <= tolerance ? attempt : null;
}
@@ -104,26 +109,52 @@ public static class BSplineSurfaceRationalReduction
// directions that actually carry the rational sections need the extra spans, and a control net refined
// where it did not need to be costs every later evaluation and every exported point for nothing.
var uniform = 0;
+ var lastFiniteSubdivision = 0;
+ var lastFiniteDeviation = double.PositiveInfinity;
for (var subdivision = 1; subdivision <= MaximumSpanSubdivision; subdivision *= 2)
{
- if (Attempt(subdivision, subdivision) is not null)
+ var attempt = Attempt(subdivision, subdivision);
+ if (double.IsFinite(lastDeviation)) { lastFiniteSubdivision = subdivision; lastFiniteDeviation = lastDeviation; }
+ if (attempt is not null)
{
uniform = subdivision;
break;
}
}
+ var subdivisionU = uniform;
+ var subdivisionV = uniform;
+ if (uniform == 0 && lastFiniteSubdivision > 0)
+ {
+ // Low-degree rational sections can need many spans in one direction
+ // while the other direction is already accurate. Doubling both would
+ // exhaust the control-net budget unnecessarily. Continue a bounded
+ // numerical refinement, choosing the axis that reduces measured error.
+ subdivisionU = lastFiniteSubdivision;
+ subdivisionV = lastFiniteSubdivision;
+ var currentDeviation = lastFiniteDeviation;
+ for (var step = 0; step < 4; step++)
+ {
+ var nextU = subdivisionU < 128 ? Attempt(subdivisionU * 2, subdivisionV) : null;
+ var errorU = subdivisionU < 128 ? lastDeviation : double.PositiveInfinity;
+ var nextV = subdivisionV < 128 ? Attempt(subdivisionU, subdivisionV * 2) : null;
+ var errorV = subdivisionV < 128 ? lastDeviation : double.PositiveInfinity;
+ if (double.Min(errorU, errorV) >= currentDeviation) break;
+ if (errorU <= errorV) { subdivisionU *= 2; currentDeviation = errorU; }
+ else { subdivisionV *= 2; currentDeviation = errorV; }
+ if (nextU is not null || nextV is not null) { uniform = 1; break; }
+ }
+ }
+
if (uniform == 0)
{
deviation = best;
- reason = $"no refinement up to {MaximumSpanSubdivision} spans per knot interval followed the rational surface to {tolerance:G4} mm (closest {best:G4} mm)" +
+ reason = $"bounded uniform/anisotropic refinement did not follow the rational surface to {tolerance:G4} mm (closest {best:G4} mm)" +
(controlLimitReached ? $"; control-net cap {MaximumControlPointsPerAxis} per axis/{MaximumControlPoints} total reached" : string.Empty);
return false;
}
- var subdivisionU = uniform;
- var subdivisionV = uniform;
- for (var trial = uniform / 2; trial >= 1; trial /= 2)
+ for (var trial = subdivisionU / 2; trial >= 1; trial /= 2)
{
if (Attempt(trial, subdivisionV) is null)
{
@@ -133,7 +164,7 @@ public static class BSplineSurfaceRationalReduction
subdivisionU = trial;
}
- for (var trial = uniform / 2; trial >= 1; trial /= 2)
+ for (var trial = subdivisionV / 2; trial >= 1; trial /= 2)
{
if (Attempt(subdivisionU, trial) is null)
{
@@ -261,7 +292,7 @@ public static class BSplineSurfaceRationalReduction
}
}
- /// <summary>Largest gap between the two surfaces at the same parameters, which also bounds the parameter drift.</summary>
+ /// <summary>Largest sampled gap at matched parameters; this is measured evidence, not a rigorous supremum.</summary>
private static double MaximumDeviation(BSplineSurfaceWithKnots surface, BSplineSurfaceWithKnots candidate)
{
var samplesU = SampleCount(candidate.KnotValuesU.Count);
diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/SphereSurface.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/SphereSurface.cs
index 97e3b559..918445f0 100644
--- a/Aetheris.Kernel.Core/Geometry/Surfaces/SphereSurface.cs
+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/SphereSurface.cs
@@ -6,6 +6,10 @@ namespace Aetheris.Kernel.Core.Geometry.Surfaces;
/// Sphere parameterization:
/// S(u,v) = Center + Radius * (cos(v) * cos(u) * XAxis + cos(v) * sin(u) * YAxis + sin(v) * Axis),
/// where u is azimuth around Axis and v is elevation from the equatorial plane.
+/// U has period 2*pi; V is in [-pi/2, pi/2]. The poles are Center +/- Radius*Axis;
+/// all U values agree at a pole. XAxis is the projected reference direction and
+/// YAxis=Axis cross XAxis. The frame defines outward support normals; resolved
+/// FaceOrientation controls material-side winding independently of source SAME_SENSE.
/// </summary>
public readonly record struct SphereSurface
{
diff --git a/Aetheris.Kernel.Core/Import/BrepImportQualification.cs b/Aetheris.Kernel.Core/Import/BrepImportQualification.cs
new file mode 100644
index 00000000..8e10b24b
--- /dev/null
+++ b/Aetheris.Kernel.Core/Import/BrepImportQualification.cs
@@ -0,0 +1,130 @@
+using System.Text.Json.Serialization;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Import;
+
+[JsonConverter(typeof(JsonStringEnumConverter<ImportQualificationStatus>))]
+public enum ImportQualificationStatus { Qualified, Inspectable, Degraded, Failed }
+
+[JsonConverter(typeof(JsonStringEnumConverter<ImportDisplayStatus>))]
+public enum ImportDisplayStatus { NotAssessed, Complete, RefinementLimited, Partial }
+
+public sealed record ImportQualificationReason(string Code, string Message, int? FaceId = null, int? StepEntityId = null);
+public sealed record ImportedShellQualification(int ShellId, int FaceCount, int ConnectedComponents, int BoundaryEdges, int NonManifoldEdges, bool Enclosed);
+public sealed record BrepImportQualificationReport(
+ ImportQualificationStatus Status,
+ ImportQualificationStatus GeometryStatus,
+ int ExpectedFaces,
+ int BoundFaces,
+ int? DisplayedFaces,
+ int MissingPcurves,
+ double? SourceDistanceAccuracyMillimetres,
+ double PcurveToleranceMillimetres,
+ BrepPcurveEvidence PcurveEvidence,
+ IReadOnlyList<ImportedShellQualification> Shells,
+ IReadOnlyList<ImportQualificationReason> Reasons)
+{
+ public ImportDisplayStatus DisplayStatus { get; init; } = ImportDisplayStatus.NotAssessed;
+ public IReadOnlyList<ImportQualificationReason> DisplayReasons { get; init; } = [];
+}
+
+/// <summary>Import evidence is separate from parser success and from display preparation.</summary>
+public static class BrepImportQualification
+{
+ internal static BrepImportQualificationReport Evaluate(BrepBody body, int expectedFaces,
+ double? sourceAccuracy, double pcurveTolerance, BrepPcurveEvidence? pcurveEvidence = null)
+ {
+ var reasons = new List<ImportQualificationReason>();
+ var topology = body.Topology;
+ var faces = topology.Faces.ToArray();
+ var faceByLoop = faces.SelectMany(f => f.LoopIds.Select(l => (Loop: l, Face: f.Id))).ToDictionary(p => p.Loop, p => p.Face);
+ var uses = topology.Coedges.GroupBy(c => c.EdgeId).ToDictionary(g => g.Key, g => g.Select(c => faceByLoop[c.LoopId]).ToArray());
+ var shells = new List<ImportedShellQualification>();
+ foreach (var shell in topology.Shells.OrderBy(s => s.Id.Value))
+ {
+ var set = shell.FaceIds.ToHashSet();
+ var adjacency = set.ToDictionary(f => f, _ => new HashSet<FaceId>());
+ var boundary = 0;
+ var nonManifold = 0;
+ foreach (var incidence in uses.Values)
+ {
+ var local = incidence.Where(set.Contains).ToArray();
+ if (local.Length == 0) continue;
+ if (local.Length == 1) boundary++;
+ if (local.Length > 2) nonManifold++;
+ foreach (var a in local) foreach (var b in local) if (a != b) adjacency[a].Add(b);
+ }
+ var unseen = set.ToHashSet();
+ var components = 0;
+ while (unseen.Count > 0)
+ {
+ components++;
+ var queue = new Queue<FaceId>();
+ var first = unseen.First();
+ unseen.Remove(first); queue.Enqueue(first);
+ while (queue.TryDequeue(out var current))
+ foreach (var next in adjacency[current]) if (unseen.Remove(next)) queue.Enqueue(next);
+ }
+ var resolved = body.FaceOrientationReport?.Shells.SingleOrDefault(s => s.ShellId == shell.Id);
+ var enclosed = set.Count > 0 && components == 1 && boundary == 0 && nonManifold == 0 && resolved?.IsClosedManifold == true;
+ shells.Add(new(shell.Id.Value, set.Count, components, boundary, nonManifold, enclosed));
+ if (!enclosed) reasons.Add(new("incomplete-shell", $"Shell {shell.Id.Value}: components={components}, boundaryEdges={boundary}, nonManifoldEdges={nonManifold}, orientationEnclosed={resolved?.IsClosedManifold}."));
+ if (resolved?.Qualification != FaceOrientationQualification.DerivedQualified)
+ reasons.Add(new("unqualified-orientation", $"Shell {shell.Id.Value}: {resolved?.Qualification.ToString() ?? "not-assessed"}."));
+ }
+ if (faces.Length != expectedFaces) reasons.Add(new("face-count-mismatch", $"Expected {expectedFaces} faces; bound {faces.Length}."));
+ foreach (var face in faces)
+ if (!body.TryGetFaceSurface(face.Id, out var surface) || surface is null)
+ reasons.Add(new("unbound-face", $"Face {face.Id.Value} has no support geometry.", face.Id.Value));
+ // Distinct coincident vertex IDs are legal interchange topology. Measure the
+ // directed gap without mutating vertices or broadening the recovery budget.
+ var closureTolerance = double.Max(1e-6, sourceAccuracy ?? 0d);
+ foreach (var loop in topology.Loops.Where(l => l.Kind == LoopKind.Edge))
+ {
+ for (var i = 0; i < loop.CoedgeIds.Count; i++)
+ {
+ var c = topology.GetCoedge(loop.CoedgeIds[i]);
+ var n = topology.GetCoedge(loop.CoedgeIds[(i + 1) % loop.CoedgeIds.Count]);
+ var e = topology.GetEdge(c.EdgeId); var ne = topology.GetEdge(n.EdgeId);
+ var end = DirectedEdgeUse.Resolve(e, c).EndVertexId;
+ var start = DirectedEdgeUse.Resolve(ne, n).StartVertexId;
+ if (end == start) continue;
+ var gap = body.TryGetVertexPoint(end, out var p) && body.TryGetVertexPoint(start, out var q) ? (p - q).Length : double.PositiveInfinity;
+ if (gap > closureTolerance) reasons.Add(new("trim-loop-not-closed", $"Loop {loop.Id.Value}, coedges {c.Id.Value}->{n.Id.Value}: gap={gap:R} mm, tolerance={closureTolerance:R} mm.", faceByLoop[loop.Id].Value));
+ }
+ }
+ var evidence = pcurveEvidence ?? BrepPcurveValidator.Validate(body, pcurveTolerance);
+ var missing = topology.Coedges.Count(c => !body.Bindings.TryGetPcurveBinding(c.Id, out _));
+ foreach (var message in evidence.Diagnostics) reasons.Add(new("invalid-pcurve", message));
+ foreach (var d in body.PcurveRecoveryReport?.Diagnostics ?? []) reasons.Add(new("pcurve-recovery-failed", d.Message));
+ var degraded = reasons.Count > 0;
+ if (missing > 0) reasons.Add(new("missing-pcurve", $"{missing} coedges lack qualified face-local trim bindings."));
+ var geometryStatus = faces.Length == 0 ? ImportQualificationStatus.Failed : degraded ? ImportQualificationStatus.Degraded
+ : missing > 0 ? ImportQualificationStatus.Inspectable : ImportQualificationStatus.Qualified;
+ return new(geometryStatus,
+ geometryStatus, expectedFaces, faces.Length, null, missing, sourceAccuracy, pcurveTolerance, evidence, shells, reasons);
+ }
+
+ /// <summary>Projects actual display evidence; it never repairs or adds geometry.</summary>
+ public static BrepImportQualificationReport WithDisplay(BrepBody body, DisplayTessellationResult mesh)
+ {
+ var report = body.ImportQualification ?? Evaluate(body, body.Topology.Faces.Count(), null, 1e-3);
+ var displayed = mesh.FacePatches.Where(p => p.TriangleIndices.Count > 0).Select(p => p.FaceId).ToHashSet();
+ var reasons = new List<ImportQualificationReason>();
+ foreach (var face in body.Topology.Faces.Where(f => !displayed.Contains(f.Id)))
+ {
+ body.Bindings.TryGetFaceBinding(face.Id, out var binding);
+ body.TryGetFaceSurface(face.Id, out var support);
+ reasons.Add(new("missing-display-face", $"Face {face.Id.Value} ({support?.Kind}) produced no display triangles.", face.Id.Value, binding.SourceStepEntityId));
+ }
+ foreach (var d in mesh.FaceDiagnostics ?? [])
+ reasons.Add(new(d.Code, d.Message, d.FaceId?.Value,
+ d.FaceId is { } faceId && body.Bindings.TryGetFaceBinding(faceId, out var binding) ? binding.SourceStepEntityId : null));
+ var displayStatus = displayed.Count < report.BoundFaces ? ImportDisplayStatus.Partial
+ : reasons.Count > 0 ? ImportDisplayStatus.RefinementLimited : ImportDisplayStatus.Complete;
+ return report with { Status = report.GeometryStatus, DisplayedFaces = displayed.Count,
+ DisplayStatus = displayStatus, DisplayReasons = reasons };
+ }
+}
diff --git a/Aetheris.Kernel.Core/Properties/InternalsVisibleTo.cs b/Aetheris.Kernel.Core/Properties/InternalsVisibleTo.cs
index ae7c32b3..81d3e953 100644
--- a/Aetheris.Kernel.Core/Properties/InternalsVisibleTo.cs
+++ b/Aetheris.Kernel.Core/Properties/InternalsVisibleTo.cs
@@ -9,3 +9,4 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("aetheris")]
[assembly: InternalsVisibleTo("Aetheris.Continuum")]
[assembly: InternalsVisibleTo("Aetheris.Continuum.Tests")]
+[assembly: InternalsVisibleTo("Aetheris.StepLegacyCorpus")]
diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
index a2600950..b0235e5c 100644
--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
@@ -55,12 +55,15 @@ public sealed class Step242ExportOptions
/// <summary>Emit qualified coedge pcurves; false leaves STEP trim binding to the importer.</summary>
public bool EmitQualifiedPcurves { get; init; } = true;
- public static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata)
+ public static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata,
+ BrepExportPreflightPolicy preflightPolicy = BrepExportPreflightPolicy.LegacyRoute)
{
static string Coalesce(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value!;
return new Step242ExportOptions
{
+ BrepExportPreflightPolicy = preflightPolicy,
+ ImportedRecoveryToleranceMillimetres = preflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute ? .1d : null,
ProductName = Coalesce(metadata.ProductName, "AetherisBody"),
ProductDescription = Coalesce(metadata.ProductDescription, string.Empty),
ApplicationName = Coalesce(metadata.Organization, "Aetheris"),
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 134bee3f..28c72876 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -20,6 +20,17 @@ public static class Step242Exporter
Step242ExportOptions? options = null)
{
options ??= new Step242ExportOptions();
+ IReadOnlyList<KernelDiagnostic> normalizationDiagnostics = [];
+ if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute
+ && options.ImportedRecoveryToleranceMillimetres is { } normalizationBudget
+ && (body.Geometry.Surfaces.Any(s => s.Value.BSplineSurfaceWithKnots?.IsRational == true)
+ || body.Bindings.PcurveBindings.Any(p => p.Pcurve.RationalWeights is not null)))
+ {
+ var normalized = Step242ProductionNormalization.Prepare(body, double.Min(.1d, normalizationBudget));
+ if (!normalized.IsSuccess) return KernelResult<string>.Failure(normalized.Diagnostics);
+ body = normalized.Value;
+ normalizationDiagnostics = normalized.Diagnostics;
+ }
// The legacy interchange route still supports rational evidence for
// compatibility and debugging. Trusted production routes must first
@@ -87,9 +98,13 @@ public static class Step242Exporter
var surfaceIds = new Dictionary<SurfaceGeometryId, string>();
var advancedFaceIds = new Dictionary<FaceId, string>();
// Keep source pcurves, but do not publish a partial recovered trim set.
+ // Pure exact planar projections are deterministically derivable from the
+ // emitted geometry. Preserve the compact canonical legacy normal form when
+ // no source/recovered parameter trace needs serialization.
var pcurveContextId = options.EmitQualifiedPcurves && body.Bindings.PcurveBindings.Any(binding =>
- body.PcurveRecoveryReport is not { IsSuccess: false }
- || binding.SourceStepPcurveEntityId is not null)
+ binding.Qualification?.Origin != PcurveBindingOrigin.DerivedAnalytic
+ && (body.PcurveRecoveryReport is not { IsSuccess: false }
+ || binding.SourceStepPcurveEntityId is not null))
? writer.AddEntity("REPRESENTATION_CONTEXT", Step242TextWriter.String("2D"), Step242TextWriter.String("parameter space"))
: null;
@@ -149,7 +164,7 @@ public static class Step242Exporter
return KernelResult<string>.Success(
writer.Build(options.HeaderMetadata),
- preflight is null ? null : ToKernelDiagnostics(preflight, errorsAsWarnings: true));
+ normalizationDiagnostics.Concat(preflight is null ? [] : ToKernelDiagnostics(preflight, errorsAsWarnings: true)).ToArray());
}
private static void EmitAuxiliaryVertexPointForVertexlessAnalyticBody(Step242TextWriter writer, BrepBody body, TopologyModel model)
@@ -1009,7 +1024,13 @@ public static class Step242Exporter
// analytic edge, rather than relying on a viewer to infer it from a wire.
var trim = edgeBinding.TrimInterval.Value;
var isFullCircle = double.Abs((trim.End - trim.Start) - (2d * double.Pi)) <= 1e-12d;
- geometryCurveId = isFullCircle && !emitFullCircleTrimmedCurves
+ // A qualified pcurve is parameter-bound. Reconstructing a full-circle
+ // seam from an approximate source vertex can change its angular origin
+ // even though the circle geometry is unchanged. Keep the native interval
+ // whenever face-local bindings depend on it.
+ var hasPcurves = pcurveContextId is not null
+ && body.Bindings.PcurveBindings.Any(binding => model.GetCoedge(binding.CoedgeId).EdgeId == edgeId);
+ geometryCurveId = isFullCircle && !emitFullCircleTrimmedCurves && !hasPcurves
? circleId
: writer.AddEntity("TRIMMED_CURVE", "$", Step242TextWriter.Ref(circleId),
Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(trim.Start)})"),
@@ -1105,7 +1126,7 @@ public static class Step242Exporter
: edgePcurveBindings
.Select(binding => BuildStepPcurve(writer, binding, surfaceIds, pcurveContextId,
curve.Kind == CurveGeometryKind.Line3 && binding.Qualification is
- { Origin: PcurveBindingOrigin.RecoveredAnalytic or PcurveBindingOrigin.RecoveredSpline }
+ { Origin: PcurveBindingOrigin.RecoveredAnalytic or PcurveBindingOrigin.RecoveredSpline or PcurveBindingOrigin.DerivedAnalytic }
? new ParameterInterval(0d, (endPoint - startPoint).Length) : null))
.Where(id => id is not null)
.Select(id => id!)
@@ -1139,24 +1160,7 @@ public static class Step242Exporter
? $"aetheris-qualified-pcurve:{Step242TextWriter.Number(qualification.QualificationToleranceMillimetres)}"
: "pcurve";
if (reparameterizedLineDomain is { } lineDomain)
- {
- var sourceDomain = binding.Pcurve.Domain;
- if (binding.Pcurve.PolynomialCurve is { } sourcePolynomial)
- {
- var span = sourceDomain.End - sourceDomain.Start;
- var knots = sourcePolynomial.KnotValues.Select(value => lineDomain.Start
- + (value - sourceDomain.Start) * (lineDomain.End - lineDomain.Start) / span).ToArray();
- var remapped = new BSpline3Curve(sourcePolynomial.Degree, sourcePolynomial.ControlPoints,
- sourcePolynomial.KnotMultiplicities, knots, sourcePolynomial.CurveForm,
- sourcePolynomial.ClosedCurve, sourcePolynomial.SelfIntersect, sourcePolynomial.KnotSpec);
- binding = binding with { Pcurve = PcurveGeometry.Polynomial(lineDomain, remapped) };
- }
- else if (binding.Pcurve.Kind == PcurveGeometryKind.Line)
- binding = binding with { Pcurve = PcurveGeometry.Line(lineDomain,
- binding.Pcurve.Points[0], binding.Pcurve.Points[1]) };
- else if (binding.Pcurve.Kind == PcurveGeometryKind.Polyline)
- binding = binding with { Pcurve = PcurveGeometry.Polyline(lineDomain, binding.Pcurve.Points) };
- }
+ binding = binding with { Pcurve = ReparameterizeLinePcurve(binding.Pcurve, lineDomain) };
if (binding.Pcurve.PolynomialCurve is { } polynomial)
{
var controls = polynomial.ControlPoints.Select(p => writer.AddEntity("CARTESIAN_POINT", "$",
@@ -1254,6 +1258,30 @@ public static class Step242Exporter
return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representationId));
}
+ internal static PcurveGeometry ReparameterizeLinePcurve(PcurveGeometry pcurve, ParameterInterval lineDomain)
+ {
+ if (pcurve.PolynomialCurve is { } polynomial)
+ {
+ var source = pcurve.Domain;
+ var span = source.End - source.Start;
+ // Preserve exact endpoints of the affine map. Evaluating the formula
+ // there can round one ULP outside the mapped spline's trim domain.
+ var knots = polynomial.KnotValues.Select(value => value == source.Start ? lineDomain.Start
+ : value == source.End ? lineDomain.End : lineDomain.Start
+ + (value - source.Start) * (lineDomain.End - lineDomain.Start) / span).ToArray();
+ var remapped = new BSpline3Curve(polynomial.Degree, polynomial.ControlPoints,
+ polynomial.KnotMultiplicities, knots, polynomial.CurveForm,
+ polynomial.ClosedCurve, polynomial.SelfIntersect, polynomial.KnotSpec);
+ return pcurve.RationalWeights is { } weights ? PcurveGeometry.RationalPolynomial(lineDomain, remapped, weights)
+ : PcurveGeometry.Polynomial(lineDomain, remapped);
+ }
+ return pcurve.Kind switch {
+ PcurveGeometryKind.Line => PcurveGeometry.Line(lineDomain, pcurve.Points[0], pcurve.Points[1]),
+ PcurveGeometryKind.Polyline => PcurveGeometry.Polyline(lineDomain, pcurve.Points),
+ _ => pcurve
+ };
+ }
+
private static string EnsureVertex(
Step242TextWriter writer,
VertexId vertexId,
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index d244f48f..2fbed82b 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -666,10 +666,12 @@ public static class Step242Importer
.Concat(orientation.Diagnostics));
}
+ BrepPcurveEvidence? qualificationEvidence = null;
if (orientation.Value.Bindings.PcurveBindings.Any())
{
var pcurveTolerance = double.Max(1e-6d, document.SourceDistanceAccuracyMillimetres ?? 0d);
var pcurveEvidence = BrepPcurveValidator.Validate(orientation.Value, pcurveTolerance);
+ qualificationEvidence = pcurveEvidence;
if (!pcurveEvidence.IsValid)
{
return KernelResult<BrepBody>.Failure(pcurveEvidence.Diagnostics.Select(message => new KernelDiagnostic(
@@ -680,14 +682,17 @@ public static class Step242Importer
}
}
- if (orientation.Value.Geometry.Curves.Any(curve => curve.Value.RecoveryProvenance is not null)
- || orientation.Value.Geometry.Surfaces.Any(surface => surface.Value.RecoveryProvenance is not null))
+ // Pcurves describe face-local edge uses, including exact geometry. Geometry
+ // recovery provenance must not decide whether those bindings are populated.
+ if (orientation.Value.Topology.Coedges.Any(coedge =>
+ !orientation.Value.Bindings.TryGetPcurveBinding(coedge.Id, out _)))
{
var recovery = BrepPcurveRecovery.Populate(
orientation.Value.Topology, orientation.Value.Geometry, orientation.Value.Bindings,
tolerance: document.PcurveQualificationToleranceMillimetres);
var pcurveEvidence = BrepPcurveValidator.Validate(orientation.Value,
document.PcurveQualificationToleranceMillimetres, requireEveryCoedge: true);
+ qualificationEvidence = pcurveEvidence;
orientation.Value.PcurveRecoveryReport = pcurveEvidence.IsValid ? recovery : recovery with
{
IsSuccess = false,
@@ -705,6 +710,8 @@ public static class Step242Importer
.Concat(orientation.Diagnostics));
}
+ orientation.Value.ImportQualification = BrepImportQualification.Evaluate(orientation.Value, faceEntityIds.Count,
+ document.SourceDistanceAccuracyMillimetres, document.PcurveQualificationToleranceMillimetres, qualificationEvidence);
return KernelResult<BrepBody>.Success(orientation.Value, validation.Diagnostics
.Concat(shellRoleDiagnostics)
.Concat(surfaceBindingDiagnostics)
@@ -2626,7 +2633,14 @@ public static class Step242Importer
return false;
}
if (!supportNormal.TryNormalize(out var normalizedSupport)) return false;
- aligned = normalizedBoundary.Dot(normalizedSupport) > 0d;
+ var agreement = normalizedBoundary.Dot(normalizedSupport);
+ // An equatorial spherical boundary lies in a plane through the centre.
+ // Its centroid radial direction is perpendicular to the boundary normal;
+ // the sign of a near-zero dot product is rounding noise, not orientation
+ // evidence. Fall through to UV winding/the deterministic loop-role baseline
+ // so shared-edge adjacency and the shell volume solve retain authority.
+ if (surface.Kind == SurfaceGeometryKind.Sphere && double.Abs(agreement) <= 1e-8d) return false;
+ aligned = agreement > 0d;
return true;
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.cs b/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.cs
new file mode 100644
index 00000000..c15c4e3d
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.cs
@@ -0,0 +1,70 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Import;
+using Aetheris.Kernel.Core.Results;
+
+namespace Aetheris.Kernel.Core.Step242;
+
+/// <summary>Bounded non-rational authority for production export; never consumes display geometry.</summary>
+public static class Step242ProductionNormalization
+{
+ public static KernelResult<BrepBody> Prepare(BrepBody source, double maximumDeviationMillimetres)
+ {
+ ArgumentNullException.ThrowIfNull(source);
+ if (!double.IsFinite(maximumDeviationMillimetres) || maximumDeviationMillimetres is <= 0d or > .1d)
+ throw new ArgumentOutOfRangeException(nameof(maximumDeviationMillimetres));
+ if (source.ImportQualification is { GeometryStatus: not ImportQualificationStatus.Qualified })
+ return Failure("Source engineering geometry is not qualified for production normalization.");
+ var geometry = new BrepGeometryStore();
+ var changed = new HashSet<SurfaceGeometryId>();
+ var diagnostics = new List<KernelDiagnostic>();
+ foreach (var curve in source.Geometry.Curves) geometry.AddCurve(curve.Key, curve.Value);
+ foreach (var entry in source.Geometry.Surfaces)
+ {
+ if (entry.Value.BSplineSurfaceWithKnots is not { IsRational: true } rational)
+ { geometry.AddSurface(entry.Key, entry.Value); continue; }
+ if (!BSplineSurfaceRationalReduction.TryReduce(rational, maximumDeviationMillimetres,
+ out var reduced, out var deviation, out var reason) || reduced is null)
+ return Failure($"Surface {entry.Key.Value}, source net {rational.ControlPoints.Count}x{rational.ControlPoints[0].Count}: {reason}");
+ geometry.AddSurface(entry.Key, SurfaceGeometry.FromRecoveredBSplineSurfaceWithKnots(reduced,
+ new("RATIONAL_B_SPLINE_SURFACE", "AdaptiveGreville", maximumDeviationMillimetres, deviation, true, reason)));
+ changed.Add(entry.Key);
+ diagnostics.Add(new(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info,
+ $"Surface {entry.Key.Value}: production non-rational recovery {deviation:R} mm within {maximumDeviationMillimetres:R} mm; {reason}",
+ "Step242.ProductionNormalization"));
+ }
+ var bindings = new BrepBindingModel();
+ foreach (var binding in source.Bindings.EdgeBindings) bindings.AddEdgeBinding(binding);
+ foreach (var binding in source.Bindings.FaceBindings) bindings.AddFaceBinding(binding);
+ foreach (var binding in source.Bindings.FaceBoundaryRoleBindings) bindings.AddFaceBoundaryRoleBinding(binding);
+ foreach (var binding in source.Bindings.VertexLoopParameterBindings) bindings.AddVertexLoopParameterBinding(binding);
+ foreach (var binding in source.Bindings.PcurveBindings)
+ if (!changed.Contains(binding.SurfaceGeometryId) && binding.Pcurve.RationalWeights is null)
+ bindings.AddPcurveBinding(binding);
+ var points = source.Topology.Vertices.Where(v => source.TryGetVertexPoint(v.Id, out _))
+ .ToDictionary(v => v.Id, v => { source.TryGetVertexPoint(v.Id, out var point); return point; });
+ var body = new BrepBody(source.Topology, geometry, bindings, points, source.SafeBooleanComposition,
+ source.ShellRepresentation, source.FaceOrientationReport);
+ var tolerance = source.ImportQualification?.PcurveToleranceMillimetres ?? 1e-3d;
+ body.PcurveRecoveryReport = BrepPcurveRecovery.Populate(body.Topology, geometry, bindings, tolerance);
+ var evidence = BrepPcurveValidator.Validate(body, tolerance, requireEveryCoedge: true);
+ if (!body.PcurveRecoveryReport.IsSuccess || !evidence.IsValid)
+ return Failure("Normalized engineering pcurves failed: " + string.Join("; ",
+ body.PcurveRecoveryReport.Diagnostics.Select(d => d.Message).Concat(evidence.Diagnostics).Take(8)));
+ if (source.ImportQualification is { } report)
+ {
+ body.ImportQualification = BrepImportQualification.Evaluate(body, report.ExpectedFaces,
+ report.SourceDistanceAccuracyMillimetres, tolerance, evidence);
+ if (body.ImportQualification.GeometryStatus != ImportQualificationStatus.Qualified)
+ return Failure("Normalized engineering topology did not remain qualified.");
+ }
+ return KernelResult<BrepBody>.Success(body, diagnostics);
+ }
+
+ private static KernelResult<BrepBody> Failure(string message) => KernelResult<BrepBody>.Failure([
+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ "step-production-normalization-unsupported: " + message, "Step242.ProductionNormalization")
+ ]);
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SourceMetadata.cs b/Aetheris.Kernel.Core/Step242/Step242SourceMetadata.cs
index a1c0d36b..f667a7d4 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SourceMetadata.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SourceMetadata.cs
@@ -9,7 +9,8 @@ public sealed record Step242SourceMetadata(
string? OriginatingSystem,
string? Authorization,
string? ProductName,
- string? ProductDescription)
+ string? ProductDescription,
+ string? FileSchema = null)
{
public static Step242SourceMetadata Empty { get; } = new(null, null, null, null, null, null, null, null, null);
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SourceMetadataReader.cs b/Aetheris.Kernel.Core/Step242/Step242SourceMetadataReader.cs
index e77f5698..57021cf6 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SourceMetadataReader.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SourceMetadataReader.cs
@@ -21,7 +21,14 @@ public static class Step242SourceMetadataReader
fileName?.OriginatingSystem,
fileName?.Authorization,
product?.Name,
- product?.Description);
+ product?.Description,
+ ReadFileSchema(stepText));
+ }
+
+ private static string? ReadFileSchema(string text)
+ {
+ var match = Regex.Match(text, @"FILE_SCHEMA\s*\(\s*\((?<items>[^)]*)\)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
+ return match.Success ? FirstString(match.Groups["items"].Value) : null;
}
private static FileNameMetadata? MatchFileName(string text)
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 8d60c516..4dde84dc 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -54,6 +54,9 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.Equal("shared", scene.Occurrences.Single(item => item.StableId == "two").DefinitionStableId);
Assert.Equal(25, scene.Occurrences.Single(item => item.StableId == "two").WorldTransform[12]);
Assert.NotEmpty(scene.Definitions[0].FacePatches);
+ Assert.Equal("Qualified", imported.Data.ImportStatus);
+ Assert.NotNull(scene.Definitions[0].ImportQualification);
+ Assert.Equal(6, scene.Definitions[0].ImportQualification!.DisplayedFaces);
}
private readonly HttpClient _client;
@@ -215,6 +218,9 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
var prepared = await PrepareDisplayAsync(document.Data.DocumentId, box.Data!.BodyId);
Assert.Equal("analytic-only", prepared.Data!.Lane);
+ Assert.Null(prepared.Data.TessellationFallback);
+ Assert.Equal(12, prepared.Data.TopologyEdges!.Count);
+ Assert.All(prepared.Data.Faces!, face => Assert.Equal(4, face.Source!.EdgeIds.Count));
var planarFace = prepared.Data.AnalyticPacket.AnalyticFaces.FirstOrDefault(face =>
face.SurfaceKind == "Plane"
&& face.PlaneGeometry is not null
@@ -692,6 +698,9 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.NotNull(imported.Data);
Assert.NotEqual(box.Data.DefinitionId, imported.Data!.DefinitionId);
Assert.NotEqual(box.Data.BodyId, imported.Data.OccurrenceId);
+ Assert.Equal("Qualified", imported.Data.ImportStatus);
+ Assert.NotEmpty(imported.Data.ImportQualifications!);
+ Assert.Null(imported.Data.ImportQualifications![0].DisplayedFaces);
var tessellationResponse = await _client.PostAsJsonAsync(
$"/api/v1/documents/{document.Data.DocumentId}/bodies/{imported.Data.OccurrenceId}/tessellate",
diff --git a/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs b/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs
index 44fa9403..fbb21fc8 100644
--- a/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs
+++ b/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs
@@ -30,6 +30,19 @@ public sealed class StepAssemblyDisplayTests
Assert.True(built, error);
Assert.NotNull(packet);
Assert.Single(packet.Definitions);
+ var edges = Assert.Single(packet.Definitions).EdgePolylines!;
+ Assert.Equal(body.Topology.Edges.Count(), edges.Count);
+ Assert.Equal(imported.Value.Definitions.Single(d => d.Geometry is not null).Geometry!.Topology.Edges.Select(e => e.Id.Value).Order(),
+ edges.Select(e => e.EdgeId).Order());
+ var geometry = imported.Value.Definitions.Single(d => d.Geometry is not null).Geometry!;
+ Assert.Equal(geometry.Topology.Faces.Count(), packet.Definitions[0].FaceSources!.Count);
+ foreach (var sourceFace in packet.Definitions[0].FaceSources!)
+ {
+ var faceId = new Aetheris.Kernel.Core.Topology.FaceId(sourceFace.FaceId);
+ Assert.Equal(geometry.Bindings.GetFaceBinding(faceId).SourceStepEntityId, sourceFace.SourceStepEntityId);
+ Assert.Equal(geometry.GetLoopIds(faceId).SelectMany(geometry.GetCoedgeIds)
+ .Select(id => geometry.Topology.GetCoedge(id).EdgeId.Value).Distinct().Order(), sourceFace.EdgeIds.Order());
+ }
Assert.Equal(4, packet.Occurrences.Count);
Assert.Equal("sub", packet.Occurrences.Single(item => item.StableId == "first").ParentStableId);
Assert.Equal("part-def", packet.Occurrences.Single(item => item.StableId == "second").DefinitionStableId);
diff --git a/Aetheris.Server/Api/AssemblyDisplayService.cs b/Aetheris.Server/Api/AssemblyDisplayService.cs
index 7dfd2560..9fa42973 100644
--- a/Aetheris.Server/Api/AssemblyDisplayService.cs
+++ b/Aetheris.Server/Api/AssemblyDisplayService.cs
@@ -1,7 +1,9 @@
using System.Diagnostics;
+using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Import;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament;
using Aetheris.Server.Contracts;
@@ -10,21 +12,25 @@ namespace Aetheris.Server.Api;
public static class AssemblyDisplayService
{
+ internal static DisplayFaceSourceDto FaceSource(Aetheris.Kernel.Core.Brep.BrepBody body, Aetheris.Kernel.Core.Topology.FaceId faceId)
+ => new(faceId.Value, body.Bindings.GetFaceBinding(faceId).SourceStepEntityId, body.GetFaceSurface(faceId).Kind.ToString(),
+ body.GetLoopIds(faceId).SelectMany(body.GetCoedgeIds).Select(id => body.Topology.GetCoedge(id).EdgeId.Value).Distinct().ToArray());
+
public static bool TryBuildStep(Step242ProductStructure structure, out AssemblyDisplayPacketDto? packet, out string error)
{
packet = null; error = string.Empty;
var watch = Stopwatch.StartNew();
var definitions = new List<AssemblyDisplayDefinitionDto>();
+ var displayDiagnostics = new List<DisplayDiagnosticDto>();
foreach (var definition in structure.Definitions.Where(item => item.Geometry is not null).OrderBy(item => item.StableId, StringComparer.Ordinal))
{
- var mesh = BrepDisplayTessellator.TessellateBounded(definition.Geometry!);
- if (!mesh.IsSuccess)
- {
- error = $"STEP definition '{definition.Name}' (#{definition.ProductDefinitionEntityId}) could not be prepared for display: "
- + string.Join("; ", mesh.Diagnostics.Select(item => item.Message));
- return false;
- }
- definitions.Add(new(definition.StableId, definition.Name, ApiMappings.ToTessellationResponse(mesh.Value).FacePatches));
+ var mesh = BrepDisplayTessellator.TessellateBoundedPartial(definition.Geometry!, DisplayTessellationOptions.ForViewport(definition.Geometry!));
+ var qualification = BrepImportQualification.WithDisplay(definition.Geometry!, mesh);
+ displayDiagnostics.AddRange(qualification.Reasons.Concat(qualification.DisplayReasons).Select(reason => new DisplayDiagnosticDto(
+ reason.Code, reason.Message, reason.FaceId, null, "step-import", "Inspect definition " + definition.StableId + ", STEP entity " + reason.StepEntityId)));
+ var tessellation = ApiMappings.ToTessellationResponse(mesh);
+ definitions.Add(new(definition.StableId, definition.Name, tessellation.FacePatches, qualification, tessellation.EdgePolylines,
+ definition.Geometry!.Topology.Faces.Select(face => FaceSource(definition.Geometry!, face.Id)).ToArray()));
}
var byDefinition = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
var byOccurrence = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
@@ -67,7 +73,7 @@ public static class AssemblyDisplayService
["occurrenceCount"] = occurrences.Count - 1
};
packet = new("aetheris/cadmata-assembly-display/m3", occurrences[0].Name, rootId, definitions, occurrences,
- [], [], new(minimum, maximum), [], performance);
+ [], [], new(minimum, maximum), displayDiagnostics, performance);
return true;
}
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index 6082afb6..fe69e8cb 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -241,7 +241,10 @@ public static class KernelEndpoints
return ApiMappings.NotFound($"Definition '{definitionId}' was not found.", "documents.definitions.export.step");
}
- var exportResult = Step242Exporter.ExportBody(definitionBody);
+ var exportResult = Step242Exporter.ExportBody(definitionBody, new Step242ExportOptions {
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ ImportedRecoveryToleranceMillimetres = .1d
+ });
if (!exportResult.IsSuccess)
{
return ApiMappings.KernelFailure(exportResult.Diagnostics);
@@ -265,8 +268,11 @@ public static class KernelEndpoints
{
if (!AssemblyDisplayService.TryBuildStep(assemblyResult.Value, out var assemblyPacket, out var displayError))
return ApiMappings.BadRequestFromMessage(displayError, "documents.import.step.assembly.display");
+ var qualifications = assemblyPacket!.Definitions.Select(d => d.ImportQualification!).ToArray();
+ var status = qualifications.Length == 0 ? "Failed" : qualifications.Max(q => q.Status).ToString();
return ApiMappings.Ok(new StepImportResponseDto(documentId, Guid.Empty, Guid.Empty,
- assemblyPacket!.Name, [], AssemblyPresentation: assemblyPacket));
+ assemblyPacket.Name, assemblyResult.Diagnostics.Select(ApiMappings.ToDiagnostic).ToArray(), AssemblyPresentation: assemblyPacket,
+ ImportStatus: status, ImportQualifications: qualifications));
}
if (assemblyResult.Diagnostics.All(diagnostic => diagnostic.Source != "Importer.Assembly.ProductStructure"))
return ApiMappings.KernelFailure(assemblyResult.Diagnostics);
@@ -288,8 +294,10 @@ public static class KernelEndpoints
imported.DefinitionId,
imported.OccurrenceId,
occurrenceName,
- [],
- semanticPresentation));
+ importResult.Diagnostics.Select(ApiMappings.ToDiagnostic).ToArray(),
+ semanticPresentation,
+ ImportStatus: importResult.Value.ImportQualification?.Status.ToString() ?? "Inspectable",
+ ImportQualifications: importResult.Value.ImportQualification is { } qualification ? [qualification] : []));
}));
documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/transform", (Guid documentId, Guid bodyId, TranslateBodyRequestDto request, KernelDocumentStore store) =>
@@ -341,7 +349,8 @@ public static class KernelEndpoints
if (lane is not "analytic-only" || needsTrimmedAnalyticFallback)
{
- var options = ApiMappings.BuildTessellationOptions(request?.TessellationOptions);
+ var options = request?.TessellationOptions is null ? DisplayTessellationOptions.ForViewport(body)
+ : ApiMappings.BuildTessellationOptions(request.TessellationOptions);
var completeBoundedMesh = DisplayPreparationFallbackBuilder.Build(body, options);
boundedMeshResult = completeBoundedMesh.IsSuccess
? completeBoundedMesh.Value
@@ -415,7 +424,8 @@ public static class KernelEndpoints
analyticFace,
canUseWireFallback ? wirePatch : null,
materializationLane,
- combinedDiagnostics);
+ combinedDiagnostics,
+ AssemblyDisplayService.FaceSource(body, face.Id));
}).ToArray();
var status = faces.All(face => face.Status is "DiagnosticOnly" or "Omitted") ? "DiagnosticOnly" :
@@ -460,6 +470,17 @@ public static class KernelEndpoints
}
var lanes = displayLanes.Select(displayLane => displayLane.Kind).ToArray();
+ // Boundary sampling is available even when every support takes the analytic lane.
+ // Mesh fallback is not the authority for whether topology lines exist.
+ var topologyTransform = document.TryGetBodyTransform(bodyId, out var edgeTransform) ? edgeTransform : Transform3D.Identity;
+ var topologyEdges = tessellationFallback?.EdgePolylines ?? wireByFace.Values.SelectMany(wire => wire.Loops).SelectMany(loop => loop.Edges)
+ .DistinctBy(edge => edge.EdgeId).Select(edge => {
+ var bound = body.Topology.GetEdge(new EdgeId(edge.EdgeId));
+ return new EdgePolylineDto(edge.EdgeId, edge.Points.Select(point => {
+ var world = topologyTransform.Apply(new Point3D(point.X, point.Y, point.Z));
+ return new Point3Dto(world.X, world.Y, world.Z);
+ }).ToArray(), bound.StartVertexId == bound.EndVertexId);
+ }).ToArray();
return ApiMappings.Ok(new DisplayPreparationResponseDto(
lane,
analyticDto,
@@ -470,7 +491,8 @@ public static class KernelEndpoints
lanes,
faces,
displayDiagnostics,
- displayLanes));
+ displayLanes,
+ topologyEdges));
}));
documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/pick", (Guid documentId, Guid bodyId, PickRequestDto request, KernelDocumentStore store) =>
diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.cs
index 2e652418..9e0a6d55 100644
--- a/Aetheris.Server/Contracts/ApiContracts.cs
+++ b/Aetheris.Server/Contracts/ApiContracts.cs
@@ -51,7 +51,9 @@ public sealed record StepImportResponseDto(
string? Name,
IReadOnlyList<DiagnosticDto> Diagnostics,
CadmataVisualizationArtifactDto? SemanticPresentation = null,
- AssemblyDisplayPacketDto? AssemblyPresentation = null);
+ AssemblyDisplayPacketDto? AssemblyPresentation = null,
+ string ImportStatus = "Inspectable",
+ IReadOnlyList<Aetheris.Kernel.Core.Import.BrepImportQualificationReport>? ImportQualifications = null);
public sealed record ExtrudeRequestDto(
IReadOnlyList<ProfilePoint2Dto> Profile,
@@ -171,7 +173,8 @@ public sealed record DisplayPreparationResponseDto(
IReadOnlyList<string>? Lanes = null,
IReadOnlyList<DisplayFaceDto>? Faces = null,
IReadOnlyList<DisplayDiagnosticDto>? Diagnostics = null,
- IReadOnlyList<DisplayLaneDto>? DisplayLanes = null);
+ IReadOnlyList<DisplayLaneDto>? DisplayLanes = null,
+ IReadOnlyList<EdgePolylineDto>? TopologyEdges = null);
public sealed record DisplayFaceDto(
int FaceId,
@@ -183,7 +186,8 @@ public sealed record DisplayFaceDto(
AnalyticDisplayFaceDto? AnalyticPatch,
DisplayWirePatchDto? WirePatch,
string? MaterializationLane,
- IReadOnlyList<DisplayDiagnosticDto> Diagnostics);
+ IReadOnlyList<DisplayDiagnosticDto> Diagnostics,
+ DisplayFaceSourceDto? Source = null);
public sealed record DisplayWirePatchDto(
string Kind,
@@ -223,7 +227,11 @@ public sealed record DisplayDiagnosticDto(
string? SuggestedNextAction);
public sealed record AssemblyDisplayRequestDto(string Path);
-public sealed record AssemblyDisplayDefinitionDto(string StableId, string DefinitionIdentity, IReadOnlyList<FacePatchDto> FacePatches);
+public sealed record DisplayFaceSourceDto(int FaceId, int? SourceStepEntityId, string SurfaceKind, IReadOnlyList<int> EdgeIds);
+public sealed record AssemblyDisplayDefinitionDto(string StableId, string DefinitionIdentity, IReadOnlyList<FacePatchDto> FacePatches,
+ Aetheris.Kernel.Core.Import.BrepImportQualificationReport? ImportQualification = null,
+ IReadOnlyList<EdgePolylineDto>? EdgePolylines = null,
+ IReadOnlyList<DisplayFaceSourceDto>? FaceSources = null);
public sealed record AssemblyDisplayPublicSemanticDto(string Name, string Type, IReadOnlyList<string> Capabilities, IReadOnlyList<string> BindingKinds, string? InternalImplementationPath);
public sealed record AssemblyDisplayModuleDefinitionDto(string StableId, string DefinitionIdentity, string TemplateName, string SpecializationIdentity, IReadOnlyList<string> Provenance, IReadOnlyList<AssemblyDisplayPublicSemanticDto> PublicSemantics, double LocalSolveMilliseconds);
public sealed record AssemblyDisplayOccurrenceDto(string StableId, string Name, string InstancePath, string? ParentStableId, string? DefinitionStableId, string Kind, IReadOnlyList<double> WorldTransform, string PlacementAuthority, IReadOnlyList<string>? SelectionMembers = null);
diff --git a/Aetheris.Web.Runtime/telos/README.md b/Aetheris.Web.Runtime/telos/README.md
index 21cf1de5..26def981 100644
--- a/Aetheris.Web.Runtime/telos/README.md
+++ b/Aetheris.Web.Runtime/telos/README.md
@@ -33,6 +33,37 @@ World-space meshes and lines accept explicit `depthMode`: `depth-tested`, `depth
`overlayId` carries product-owned pick identity. DOM buttons receive their own DOM events; GPU picking prioritizes always-on-top authoring meshes, dynamic overlay leaders, construction lines/surfaces and then model geometry. Hidden or depth-occluded overlays do not steal geometry picks. This supplies graphics interaction identity, not CAD selector authority.
+## Native presentation
+
+`setPresentation(TelosPresentation)` supplies a static procedural backdrop,
+key/fill/hemisphere mesh lighting, roughness highlights, coloured rim light,
+selection accent and physically spaced minor/major reference-grid palettes.
+Backdrop/grid colours are display encoded; lighting colours are linear.
+`background.wgsl` and the mesh shader are real packaged source assets. One
+fullscreen triangle renders the backdrop without writing authoritative depth;
+one pipeline per sample/attachment configuration serves every preset.
+Presentation never changes camera, topology or source selection. An update
+resets optional temporal history and requests an on-demand frame. Unthemed
+callers retain the prior mesh lighting. CIR field shaders keep their existing ABI.
+No HDR bloom, shadow maps or physically simulated atmosphere are claimed.
+See `docs/public/firmament/viewport-themes.md` for the product choices.
+
+## Surface inspection
+
+`inspectSurfaces(scene, mode, isolatedFace?)` is the shared Cadmata/Helios inspection
+projection. Modes are `normal`, `surfaces`, `wire`, `overlay` and `patches`.
+`surfaceInspectionFaces(scene)` enumerates source faces from individual meshes,
+packed definition ranges and retained field proxies. Isolation keys contain both
+occurrence and face identity. Projection never modifies the camera or source scene.
+Packed faces share complete immutable geometry and GPU buffers; `triangleRange`
+restricts drawing and picking while retaining original definition triangle indices.
+
+Whole-model views keep actual fields. Per-face field inspection uses the retained
+BRep proxy explicitly; products must label that distinction. Source edge IDs stay
+authoritative. If face-edge adjacency is absent, isolated wire shows occurrence
+edges rather than guessing adjacency from triangles. See the repository's
+`docs/public/firmament/surface-inspection.md` for human controls and capture usage.
+
## Experimental temporal AA
`SpatialOnly` is the production default: four-sample MSAA shares one multisampled color/depth pair across surfaces, topology and overlays, then resolves once to the canvas. Lines also retain derivative coverage. Field shaders execute their existing center-ray ABI; MSAA does not qualify analytic field silhouette coverage. `None` uses one sample. `host.setAA("TAA")` enables a single-sample fixed-weight temporal experiment; `host.setAA("TAAUtility")` enables its generated Copeland utility policy. Both remain disabled by default. See `docs/release/TELOS-TAA-X0.md` for the temporal silhouette blocker and `docs/release/VIEWPORT-FINISH-X0.md` for product qualification.
diff --git a/Aetheris.Web.Runtime/telos/src/contracts.ts b/Aetheris.Web.Runtime/telos/src/contracts.ts
index 6118cc84..7a9808b5 100644
--- a/Aetheris.Web.Runtime/telos/src/contracts.ts
+++ b/Aetheris.Web.Runtime/telos/src/contracts.ts
@@ -42,6 +42,8 @@ export interface TelosMesh {
visible?: boolean;
depthMode?: TelosDepthMode;
unlit?: boolean;
+ /** Draw/pick a source triangle range while sharing the complete immutable geometry. */
+ triangleRange?: { startTriangle: number; triangleCount: number };
}
export interface TelosLine {
/** Fade finite reference-grid endpoints without changing engineering edge coverage. */
diff --git a/Aetheris.Web.Runtime/telos/src/host.ts b/Aetheris.Web.Runtime/telos/src/host.ts
index 81058177..9aaedf40 100644
--- a/Aetheris.Web.Runtime/telos/src/host.ts
+++ b/Aetheris.Web.Runtime/telos/src/host.ts
@@ -9,6 +9,7 @@ import {
type TelosAADebug,
} from "./temporal.js";
import { telosPipeline } from "./pipelines.js";
+import { presentationUniform, type TelosPresentation } from "./presentation.js";
import type {
TelosScene,
TelosMesh,
@@ -40,6 +41,7 @@ const meshKey = (item: TelosMesh) =>
item.identity.occurrenceId,
item.identity.overlayId,
item.definition.id,
+ item.triangleRange?.startTriangle,
]);
const emptyScene = (): TelosScene => ({ meshes: [], lines: [], fields: [] });
const matrix = (values?: NumericArray) =>
@@ -66,6 +68,19 @@ export class TelosHost {
scene = emptyScene();
background: GPUColor = [0.08, 0.1, 0.09, 1];
grid = false;
+ presentation?: TelosPresentation;
+ private presentationKey = "";
+ private backdropDraw?: Draw<null>;
+ /** Presentation updates retain geometry, logical camera and source picking. */
+ setPresentation(value: TelosPresentation) {
+ const key = JSON.stringify(value);
+ if (key === this.presentationKey) return;
+ this.presentationKey = key;
+ this.presentation = value;
+ this.gridKey = "";
+ this.temporal?.reset("presentation");
+ this.invalidate();
+ }
temporal?: TelosTemporal;
aaMode: TelosAAMode = "SpatialOnly";
aaDebug: TelosAADebug = "color";
@@ -163,7 +178,7 @@ export class TelosHost {
this.picker.dynamicLines = items;
this.metrics.dynamicLineUpdateMs = performance.now() - started;
}
- private gridDraw?: Draw<TelosLine>;
+ private gridDraws: Draw<TelosLine>[] = [];
private gridKey = "";
private raf = 0;
private disposed = false;
@@ -356,6 +371,9 @@ export class TelosHost {
return {
fields: this.fields.length,
meshSurfaces: this.meshes.filter((d) => !d.item.overlay).length,
+ topologyLines: this.lines.filter((d) => d.item.identity.edgeId !== undefined).length,
+ topologyOccurrences: [...new Set(this.lines.filter((d) => d.item.identity.edgeId !== undefined)
+ .map(d => d.item.identity.occurrenceId))],
proxies: this.requestedScene.fields.filter((f) => f.proxy).length,
shaders: [...this.fieldStates],
definitions: this.requestedScene.projectionDiagnostics,
@@ -496,10 +514,10 @@ export class TelosHost {
const draw =
old?.pipeline === pipeline
? old
- : this.draw(item, pipeline, 224, geometry.count);
+ : this.draw(item, pipeline, 384, geometry.count);
oldMeshes.delete(meshKey(item));
draw.item = item;
- draw.count = geometry.count;
+ draw.count = item.triangleRange ? item.triangleRange.triangleCount * 3 : geometry.count;
retained.add(draw);
draw.geometry = geometry;
this.meshes.push(draw);
@@ -646,7 +664,7 @@ export class TelosHost {
}
private updateMesh(draw: Draw<TelosMesh>) {
const model = matrix(draw.item.transform);
- const data = new Float32Array(56);
+ const data = new Float32Array(96);
data.set(
draw.item.overlay
? this.camera.viewProjection.elements
@@ -655,20 +673,35 @@ export class TelosHost {
data.set(model.elements, 16);
data.set(model.clone().invert().transpose().elements, 32);
const material = draw.item.material;
- data.set(surfaceColor(material, draw.item.selected, draw.item.hovered), 48);
+ data.set(this.themedSurfaceColor(material, draw.item.selected, draw.item.hovered), 48);
data.set(
[material.roughness, material.metallic, draw.item.unlit ? 1 : 0, 0],
52,
);
+ if (this.presentation) {
+ const l = this.presentation.lighting;
+ data.set([...this.camera.position.toArray(), 0], 56);
+ data.set([...l.key, l.keyIntensity], 60); data.set([...l.keyColor, 0], 64);
+ data.set([...l.fill, l.fillIntensity], 68); data.set([...l.fillColor, 0], 72);
+ data.set([...l.sky, l.hemisphere], 76); data.set([...l.ground, 0], 80);
+ data.set([...l.rim, l.rimIntensity], 84);
+ data.set([l.ambient, l.exposure, 0, 1], 88);
+ data.set([...this.camera.up.toArray(),0],92);
+ }
this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
}
+ private themedSurfaceColor(material: TelosMaterial, selected?: boolean, hovered?: boolean) {
+ if (!this.presentation || !(selected || hovered)) return surfaceColor(material, selected, hovered);
+ const strength = selected ? 0.52 : 0.16;
+ return [...material.baseColor.slice(0,3).map((c,i) => c*(1-strength)+this.presentation!.lighting.selection[i]*strength), material.opacity];
+ }
private updateLine(draw: Draw<TelosLine>) {
const data = new Float32Array(44);
data.set(this.camera.viewProjection.elements);
data.set(matrix(draw.item.transform).elements, 16);
data.set(
draw.item.selected
- ? [1, 0.75, 0.2, 1]
+ ? [...(this.presentation?.lighting.selection ?? [1, 0.75, 0.2]), 1]
: (draw.item.color ?? [0.15, 0.18, 0.16, 1]),
32,
);
@@ -743,7 +776,7 @@ export class TelosHost {
);
this.owner.device.queue.writeBuffer(draw.vertices!, 0, vertices);
const data = new Float32Array(8);
- data.set(surfaceColor(draw.item.material, draw.item.selected), 0);
+ data.set(this.themedSurfaceColor(draw.item.material, draw.item.selected), 0);
data[4] = draw.item.material.roughness;
this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
}
@@ -756,14 +789,15 @@ export class TelosHost {
this.camera.span,
this.camera.width,
this.camera.height,
+ this.presentation?.grid,
]);
if (key === this.gridKey) return;
this.gridKey = key;
- if (this.gridDraw) {
- this.owner.resources.release(this.gridDraw.uniform);
- this.owner.resources.release(this.gridDraw.vertices!);
- this.gridDraw = undefined;
+ for (const draw of this.gridDraws) {
+ this.owner.resources.release(draw.uniform);
+ this.owner.resources.release(draw.vertices!);
}
+ this.gridDraws = [];
if (!this.grid) return;
const axis = this.gridPlane === "xy" ? "z" : "y",
points: Vector3[] = [];
@@ -787,7 +821,8 @@ export class TelosHost {
span * 20,
Math.max(span, ...points.map((p) => p.distanceTo(this.camera.target))),
);
- const desired = span / 12;
+ const style = this.presentation?.grid;
+ const desired = span / (style?.targetCells ?? 12);
const decade = Math.pow(10, Math.floor(Math.log10(desired)));
const step =
decade * (desired / decade < 2 ? 2 : desired / decade < 5 ? 5 : 10);
@@ -798,37 +833,66 @@ export class TelosHost {
? this.camera.target.y
: this.camera.target.z) / step,
) * step;
- const count = Math.min(32, Math.ceil(extent / step));
- const segments: number[] = [];
+ const count = Math.min(style?.maxLines ?? 32, Math.ceil(extent * (style?.extentScale ?? 1) / step));
+ const minor: number[] = [], major: number[] = [];
const point = (x: number, y: number) =>
- this.gridPlane === "xy" ? [x, y, 0] : [x, 0, y];
+ this.gridPlane === "xy" ? [x, y, style?.offset ?? 0] : [x, style?.offset ?? 0, y];
for (let i = -count; i <= count; i++) {
- segments.push(
+ const stepCount = style?.majorStep ?? 5;
+ const vertical = Math.round(centerX / step + i) % stepCount === 0 ? major : minor;
+ const horizontal = Math.round(centerY / step + i) % stepCount === 0 ? major : minor;
+ vertical.push(
...point(centerX + i * step, centerY - count * step),
...point(centerX + i * step, centerY + count * step),
);
- segments.push(
+ horizontal.push(
...point(centerX - count * step, centerY + i * step),
...point(centerX + count * step, centerY + i * step),
);
}
- this.gridDraw = this.draw(
+ for (const [segments, color, opacity, width] of [
+ [minor, style?.minor ?? [0.45,0.48,0.46], style?.minorOpacity ?? 0.12, 0.65],
+ [major, style?.major ?? [0.6,0.62,0.6], style?.majorOpacity ?? 0.24, 1.05],
+ ] as [number[], readonly number[], number, number][]) {
+ if (!segments.length) continue;
+ const draw = this.draw(
{
id: "reference-grid",
fadeEnds: true,
points: segments,
identity: { occurrenceId: "reference-grid" },
- widthPixels: 0.7,
- color: [0.45, 0.48, 0.46, 0.18],
+ widthPixels: width,
+ color: [...color, opacity],
},
telosPipeline(this.owner, "line"),
176,
segments.length / 6,
);
- this.gridDraw.vertices = this.owner.resources.buffer(
+ draw.vertices = this.owner.resources.buffer(
new Float32Array(segments),
GPUBufferUsage.VERTEX,
);
+ this.gridDraws.push(draw);
+ }
+ }
+ private drawBackdrop() {
+ if (!this.presentation) return;
+ const pipeline = this.owner.resources.pipeline(JSON.stringify(["telos-backdrop/1",this.owner.format,this.owner.sampleCount]), () => {
+ const module = this.owner.resources.module("telos-backdrop/1", this.owner.shaders.background);
+ return this.owner.device.createRenderPipeline({ layout:"auto", vertex:{module,entryPoint:"vertex"},
+ fragment:{module,entryPoint:"fragment",targets:[{format:this.owner.format}]},
+ multisample:{count:this.owner.sampleCount}, primitive:{topology:"triangle-list"},
+ depthStencil:{format:"depth32float",depthWriteEnabled:false,depthCompare:"always"} });
+ });
+ if (this.backdropDraw?.pipeline !== pipeline) {
+ if (this.backdropDraw) this.owner.resources.release(this.backdropDraw.uniform);
+ this.backdropDraw = this.draw(null,pipeline,64,3);
+ }
+ this.owner.device.queue.writeBuffer(this.backdropDraw.uniform,0,presentationUniform(this.presentation,this.frame.width,this.frame.height));
+ const pass = this.frame.pass("ThemeBackdrop");
+ pass.setPipeline(pipeline); pass.setBindGroup(0,this.backdropDraw.binding); pass.draw(3); pass.end();
+ this.owner.canvas.dataset.telosPresentation = JSON.stringify({id:this.presentation.id,backdrop:this.presentation.backdrop.kind,
+ gridGroups:this.gridDraws.length, sampleCount:this.owner.sampleCount});
}
render() {
if (this.owner.stopped || this.disposed) return;
@@ -848,16 +912,19 @@ export class TelosHost {
this.aaDebug,
);
this.frame.begin(this.background, source);
+ this.drawBackdrop();
this.metrics.draws = 0;
this.metrics.fieldDraws = 0;
const drawGrid = () => {
- if (!this.gridDraw) return;
+ if (!this.gridDraws.length) return;
const grid = this.frame.pass("ReferenceGrid");
- this.updateLine(this.gridDraw);
- grid.setPipeline(this.gridDraw.pipeline);
- grid.setBindGroup(0, this.gridDraw.binding);
- grid.setVertexBuffer(0, this.gridDraw.vertices!);
- grid.draw(6, this.gridDraw.count);
+ for (const draw of this.gridDraws) {
+ this.updateLine(draw);
+ grid.setPipeline(draw.pipeline);
+ grid.setBindGroup(0,draw.binding);
+ grid.setVertexBuffer(0,draw.vertices!);
+ grid.draw(6,draw.count);
+ }
grid.end();
};
const drawMesh = (pass: GPURenderPassEncoder, draw: Draw<TelosMesh>) => {
@@ -868,7 +935,7 @@ export class TelosHost {
pass.setVertexBuffer(0, draw.geometry!.positions);
pass.setVertexBuffer(1, draw.geometry!.normals);
pass.setIndexBuffer(draw.geometry!.indices, "uint32");
- pass.drawIndexed(draw.count);
+ pass.drawIndexed(draw.count, 1, (draw.item.triangleRange?.startTriangle ?? 0) * 3);
this.metrics.draws++;
};
let pass = this.frame.pass("MeshOpaque");
diff --git a/Aetheris.Web.Runtime/telos/src/index.ts b/Aetheris.Web.Runtime/telos/src/index.ts
index ac0e46e9..6524c464 100644
--- a/Aetheris.Web.Runtime/telos/src/index.ts
+++ b/Aetheris.Web.Runtime/telos/src/index.ts
@@ -5,5 +5,7 @@ export * from "./device.js";
export * from "./pick.js";
export * from "./host.js";
export * from "./adapters.js";
+export * from "./inspection.js";
+export * from "./presentation.js";
export * from "./temporal.js";
diff --git a/Aetheris.Web.Runtime/telos/src/inspection.ts b/Aetheris.Web.Runtime/telos/src/inspection.ts
new file mode 100644
index 00000000..a32ddaa1
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/inspection.ts
@@ -0,0 +1,71 @@
+import type { TelosScene, TelosMesh } from "./contracts.js";
+
+export type SurfaceInspectionMode = "normal" | "surfaces" | "wire" | "overlay" | "patches";
+export interface SurfaceInspectionFace {
+ key: string;
+ occurrenceId: string;
+ faceId: string | number;
+ sourceStepEntityId?: number | null;
+ surfaceKind?: string | null;
+ /** Omit when the source packet does not transport face-edge adjacency. */
+ edgeIds?: readonly (number | string)[];
+}
+export const inspectionFaceKey = (occurrence: string, face: string | number) => JSON.stringify([occurrence, face]);
+
+/** Enumerate source faces, including packed SDK ranges and retained field proxies. */
+export function surfaceInspectionFaces(scene: TelosScene): SurfaceInspectionFace[] {
+ const faces = new Map<string, SurfaceInspectionFace>();
+ for (const item of [...scene.meshes, ...scene.fields]) {
+ if ("overlay" in item && item.overlay) continue;
+ const geometry = "definition" in item ? item.definition : item.proxy;
+ const ids = item.identity.faceId !== undefined ? [item.identity.faceId] : geometry?.ranges?.map(r => r.faceId) ?? [];
+ for (const faceId of ids) {
+ const occurrenceId = item.identity.occurrenceId;
+ const key = inspectionFaceKey(occurrenceId, faceId);
+ faces.set(key, { key, occurrenceId, faceId });
+ }
+ }
+ return [...faces.values()];
+}
+
+function faceMeshes(mesh: TelosMesh): TelosMesh[] {
+ if (mesh.overlay || mesh.identity.faceId !== undefined || !mesh.definition.ranges?.length) return [mesh];
+ return mesh.definition.ranges.map(range => ({ ...mesh, triangleRange: range,
+ identity: { ...mesh.identity, faceId: range.faceId } }));
+}
+
+/** Diagnostic projection only: immutable buffers, engineering identities and camera stay unchanged. */
+export function inspectSurfaces(scene: TelosScene, mode: SurfaceInspectionMode,
+ isolated?: SurfaceInspectionFace): TelosScene {
+ if (mode === "normal" && !isolated) return scene;
+ const included = (identity: { occurrenceId: string; faceId?: string | number }) => !isolated ||
+ identity.occurrenceId === isolated.occurrenceId && identity.faceId === isolated.faceId;
+ // A field has no per-face shader mask. Face inspection explicitly uses its retained
+ // BRep proxy; whole-model surface/overlay views continue to draw the actual field.
+ const proxyFields = scene.fields.filter(field => field.proxy && (isolated || mode === "patches"));
+ const meshes: TelosMesh[] = [...scene.meshes, ...proxyFields.map(field => ({ definition: field.proxy!,
+ identity: field.identity, transform: field.transform, material: field.material, visible: field.visible }))];
+ return {
+ ...scene,
+ meshes: meshes.flatMap(mesh => isolated || mode === "patches" ? faceMeshes(mesh) : [mesh]).map(mesh => {
+ if (mesh.overlay) return mesh;
+ const key = inspectionFaceKey(mesh.identity.occurrenceId, mesh.identity.faceId ?? mesh.definition.id);
+ let hash = 0; for (const c of key) hash = (Math.imul(hash, 31) + c.charCodeAt(0)) | 0;
+ const color = [0, 8, 16].map(shift => .25 + ((hash >>> shift) & 255) / 255 * .65);
+ return { ...mesh, visible: mesh.visible !== false && included(mesh.identity) && mode !== "wire",
+ material: { ...mesh.material, baseColor: mode === "normal" ? mesh.material.baseColor : mode === "patches" ? color : [0.25, 0.55, 0.85],
+ opacity: mode === "overlay" ? .2 : mesh.material.opacity }, selected: false, hovered: false };
+ }),
+ fields: scene.fields.map(field => ({ ...field, visible: !proxyFields.includes(field) && field.visible !== false && included(field.identity) && mode !== "wire",
+ material: { ...field.material, opacity: mode === "overlay" ? .2 : field.material.opacity } })),
+ lines: scene.lines.map(line => {
+ if (line.identity.edgeId === undefined) return line;
+ const boundary = !isolated || line.identity.occurrenceId === isolated.occurrenceId &&
+ (isolated.edgeIds?.some(id => String(id) === String(line.identity.edgeId)) ??
+ (line.identity.faceId === undefined || line.identity.faceId === isolated.faceId));
+ return { ...line, visible: line.visible !== false && boundary && mode !== "surfaces",
+ color: [1, .18, .08, 1], widthPixels: 1.5, selected: false,
+ depthMode: mode === "overlay" || mode === "wire" ? "always-on-top" as const : line.depthMode };
+ }),
+ };
+}
diff --git a/Aetheris.Web.Runtime/telos/src/pick.ts b/Aetheris.Web.Runtime/telos/src/pick.ts
index f9f2b86d..b5dab232 100644
--- a/Aetheris.Web.Runtime/telos/src/pick.ts
+++ b/Aetheris.Web.Runtime/telos/src/pick.ts
@@ -34,12 +34,21 @@ export class TelosPick {
this.raycaster = new Raycaster();
}
setScene(scene: TelosScene) {
+ // Per-face draw ranges require separate geometries, but not copies of an
+ // entire body's CPU buffers for every face or repeated occurrence.
+ const buffers = new Map<TelosGeometry, { position: BufferAttribute; index: BufferAttribute }>();
+ for (const mesh of this.proxies)
+ buffers.set(mesh.userData.definition, {
+ position: mesh.geometry.getAttribute("position") as BufferAttribute,
+ index: mesh.geometry.index!,
+ });
const previous = new Map(
this.proxies.map((mesh) => [
JSON.stringify([
mesh.userData.item.identity.occurrenceId,
mesh.userData.item.identity.overlayId,
mesh.userData.definition.id,
+ mesh.userData.item.triangleRange?.startTriangle,
]),
mesh,
]),
@@ -55,6 +64,7 @@ export class TelosPick {
item.identity.occurrenceId,
item.identity.overlayId,
definition.id,
+ "triangleRange" in item ? item.triangleRange?.startTriangle : undefined,
]);
let mesh = previous.get(key);
if (
@@ -65,16 +75,20 @@ export class TelosPick {
mesh = undefined;
if (!mesh) {
const geometry = new BufferGeometry();
- geometry.setAttribute(
- "position",
- new BufferAttribute(Float32Array.from(definition.positions), 3),
- );
- geometry.setIndex(
- new BufferAttribute(Uint32Array.from(definition.indices), 1),
- );
+ let shared = buffers.get(definition);
+ if (!shared) {
+ shared = { position: new BufferAttribute(Float32Array.from(definition.positions), 3),
+ index: new BufferAttribute(Uint32Array.from(definition.indices), 1) };
+ buffers.set(definition, shared);
+ }
+ geometry.setAttribute("position", shared.position);
+ geometry.setIndex(shared.index);
mesh = new Mesh(geometry, new MeshBasicMaterial({ side: DoubleSide }));
} else previous.delete(key);
mesh.matrixAutoUpdate = false;
+ const range = "triangleRange" in item ? item.triangleRange : undefined;
+ mesh.geometry.setDrawRange(range ? range.startTriangle * 3 : 0,
+ range ? range.triangleCount * 3 : Infinity);
mesh.matrix.fromArray(item.transform ?? new Matrix4().elements);
mesh.updateMatrixWorld(true);
mesh.userData = { item, definition };
diff --git a/Aetheris.Web.Runtime/telos/src/presentation.ts b/Aetheris.Web.Runtime/telos/src/presentation.ts
new file mode 100644
index 00000000..c95dd100
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/presentation.ts
@@ -0,0 +1,24 @@
+import type { Vec3 } from "./contracts.js";
+
+export const TELOS_BACKDROPS = ["studio", "paper", "mars", "sirius", "singularity", "aeons", "blueprint", "aurora"] as const;
+/** Display presentation only. No model transforms, topology or camera commands. */
+export interface TelosPresentation {
+ id: string;
+ backdrop: { kind: typeof TELOS_BACKDROPS[number]; base: Vec3; accent: Vec3; intensity: number; vignette: number };
+ lighting: {
+ ambient: number; exposure: number;
+ sky: Vec3; ground: Vec3; hemisphere: number;
+ key: Vec3; keyColor: Vec3; keyIntensity: number;
+ fill: Vec3; fillColor: Vec3; fillIntensity: number;
+ rim: Vec3; rimIntensity: number;
+ selection: Vec3;
+ };
+ grid: { minor: Vec3; major: Vec3; minorOpacity: number; majorOpacity: number;
+ majorStep: number; targetCells: number; maxLines: number; extentScale: number; offset: number };
+}
+
+/** Background/grid colours are display encoded; lighting colours are linear. */
+export function presentationUniform(presentation: TelosPresentation, width: number, height: number): Float32Array<ArrayBuffer> {
+ return new Float32Array([width, height, TELOS_BACKDROPS.indexOf(presentation.backdrop.kind), presentation.backdrop.intensity,
+ ...presentation.backdrop.base, 1, ...presentation.backdrop.accent, 1, presentation.backdrop.vignette, 0, 0, 0]);
+}
diff --git a/Aetheris.Web.Runtime/telos/src/shaderSources.ts b/Aetheris.Web.Runtime/telos/src/shaderSources.ts
index 3e8f94fe..2febe310 100644
--- a/Aetheris.Web.Runtime/telos/src/shaderSources.ts
+++ b/Aetheris.Web.Runtime/telos/src/shaderSources.ts
@@ -1,6 +1,7 @@
export interface TelosShaderSources {
mesh: string;
line: string;
+ background: string;
temporal?: string;
}
@@ -16,14 +17,15 @@ async function loadShader(url: URL): Promise<string> {
/** Static asset URLs work in native ESM and are rewritten by browser bundlers. */
export async function loadTelosShaders(): Promise<TelosShaderSources> {
- const [mesh, line] = await Promise.all([
+ const [mesh, line, background] = await Promise.all([
loadShader(new URL("./shaders/mesh.wgsl", import.meta.url)),
loadShader(new URL("./shaders/line.wgsl", import.meta.url)),
+ loadShader(new URL("./shaders/background.wgsl", import.meta.url)),
]);
// Optional temporal assets never gate the existing viewport path.
const temporal = await Promise.all([
loadShader(new URL("./shaders/temporal-policy.wgsl", import.meta.url)),
loadShader(new URL("./shaders/temporal-resolve.wgsl", import.meta.url)),
]).then(parts => parts.join("\n")).catch(() => undefined);
- return { mesh, line, temporal };
+ return { mesh, line, background, temporal };
}
diff --git a/Aetheris.Web.Runtime/telos/src/shaders/background.wgsl b/Aetheris.Web.Runtime/telos/src/shaders/background.wgsl
new file mode 100644
index 00000000..8bfa1805
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/shaders/background.wgsl
@@ -0,0 +1,85 @@
+struct State { viewport: vec4<f32>, base: vec4<f32>, accent: vec4<f32>, settings: vec4<f32> }
+@group(0) @binding(0) var<uniform> state: State;
+struct Output { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> }
+@vertex fn vertex(@builtin(vertex_index) index: u32) -> Output {
+ let corners = array<vec2<f32>, 3>(vec2(-1,-1), vec2(3,-1), vec2(-1,3));
+ let p = corners[index]; return Output(vec4(p,0.99999,1), p * 0.5 + 0.5);
+}
+fn hash(p: vec2<f32>) -> f32 {
+ var q = fract(p * vec2(123.34,456.21)); q += vec2(dot(q,q + vec2(45.32))); return fract(q.x*q.y);
+}
+fn noise(p: vec2<f32>) -> f32 {
+ let i = floor(p); let f = fract(p); let u = f*f*(vec2(3.0)-2.0*f);
+ return mix(mix(hash(i),hash(i+vec2(1,0)),u.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),u.x),u.y);
+}
+fn fbm(p: vec2<f32>) -> f32 { return noise(p)*0.55 + noise(p*2.03+vec2(11.7))*0.28 + noise(p*4.11+vec2(27.2))*0.17; }
+fn ring(p: vec2<f32>, radius: f32, width: f32) -> f32 { return exp(-abs(length(p)-radius)/width); }
+fn stars(uv: vec2<f32>) -> f32 {
+ let cell = uv*state.viewport.xy/3.0; let h = hash(floor(cell));
+ return smoothstep(0.995,1.0,h) * exp(-length(fract(cell)-vec2(0.5))*5.0);
+}
+@fragment fn fragment(input: Output) -> @location(0) vec4<f32> {
+ let uv = input.uv; var p = uv*2.0-1.0; p.x *= state.viewport.x/max(state.viewport.y,1.0);
+ let mode = u32(state.viewport.z); let accent = state.accent.rgb;
+ var color = state.base.rgb;
+ switch mode {
+ case 0u: { // A graphite cyclorama: quiet centre, crisp silhouette.
+ color += accent*exp(-dot(p-vec2(-0.3,0.5),p-vec2(-0.3,0.5))*0.65)*0.10;
+ color *= 0.8+0.2*uv.y;
+ }
+ case 1u: { // Warm gallery paper, restrained grain.
+ color = mix(color*0.88, color+accent*0.12, uv.y);
+ color += vec3((hash(floor(uv*state.viewport.xy))-0.5)*0.006);
+ }
+ case 2u: { // Mars: low amber sun above eroded copper strata.
+ color += vec3(0.23,0.055,0.02)*smoothstep(0.15,0.95,uv.y);
+ let sun = p-vec2(-0.98,0.52);
+ color += accent*(exp(-length(sun)*5.0)*0.35 + (1.0-smoothstep(0.047,0.054,length(sun)))*1.2);
+ let strata = pow(0.5+0.5*sin(p.y*100.0+fbm(p*2.5)*9.0),16.0);
+ color += vec3(0.19,0.047,0.02)*strata*(1.0-smoothstep(-0.8,0.0,p.y));
+ color += accent*exp(-abs(p.y+0.56)*10.0)*0.18;
+ }
+ case 3u: { // Sirius: spectral star, diffraction rays and glacial nebula.
+ color += vec3(0.008,0.021,0.055)*uv.y + accent*stars(uv)*0.6;
+ let q = p-vec2(1.08,0.58); let r = length(q);
+ let rays = exp(-abs(q.x)*95.0)+exp(-abs(q.y)*95.0);
+ color += accent*(exp(-r*6.0)*0.3+exp(-r*60.0)*2.0+rays*exp(-r*12.0)*0.5);
+ color += vec3(0.015,0.03,0.08)*fbm(p*2.0+vec2(3.0))*smoothstep(0.4,1.5,length(p));
+ color += accent*ring(q*vec2(1,1.3),0.27,0.002)*0.16;
+ }
+ case 4u: { // Singular accretion composition, deliberately outside the model centre.
+ let q = (p-vec2(1.10,0.42))*vec2(1,1.45); let r = length(q); let a = atan2(q.y,q.x);
+ let disc = ring(q,0.28,0.016)*(0.7+0.3*sin(a));
+ color += mix(vec3(0.45,0.055,0.16),accent,0.5+0.5*sin(a))*disc;
+ color += vec3(1.0,0.87,0.6)*ring(q,0.273,0.003)*0.85;
+ color += vec3(0.15,0.055,0.21)*(ring(q,0.39,0.009)+ring(q,0.51,0.005)*0.5);
+ let warp = pow(0.5+0.5*sin(log(r+0.025)*43.0+a*3.0),12.0);
+ color += accent*warp*exp(-abs(r-0.31)*8.0)*0.12;
+ color *= smoothstep(0.21,0.245,r); color += vec3(0.22,0.16,0.28)*stars(uv)*0.18;
+ }
+ case 5u: { // Aeons: engraved observatory arcs in violet haze.
+ let q = p-vec2(-1.10,-0.74);
+ color += accent*(ring(q,0.80,0.002)+ring(q,1.0,0.004)*0.6+ring(q,1.23,0.002)*0.4)*0.35;
+ color += vec3(0.08,0.035,0.13)*exp(-abs(length(q)-1.05)*5.0);
+ color += accent*stars(uv)*0.35;
+ let r = p-vec2(1.0,0.70); let a = atan2(r.y,r.x);
+ color += accent*pow(abs(sin(a*12.0)),90.0)*exp(-length(r)*9.0)*0.25;
+ }
+ case 6u: { // Drafting blueprint: square paper coordinates, no invented model edges.
+ color += accent*exp(-dot(p,p)*0.4)*0.04;
+ let g = abs(fract(uv*state.viewport.xy/48.0)-0.5);
+ let line = smoothstep(0.48,0.5,max(g.x,g.y));
+ color += accent*line*0.026;
+ }
+ default: { // Aurora: layered static curtains, mint light above an indigo horizon.
+ let y = p.y-0.45; let wave = sin(p.x*2.0+fbm(vec2(p.x*2.4,1.7))*2.0)*0.20;
+ let curtain = exp(-abs(y-wave)*8.0)*(0.25+0.75*fbm(vec2(p.x*14.0,p.y*0.5)));
+ color += mix(vec3(0.15,0.07,0.35),accent,0.5+0.5*sin(p.x*2.0))*curtain*0.55;
+ color += accent*ring((p-vec2(-1.1,0.55))*vec2(1,1.7),0.1,0.012)*0.3;
+ color += vec3(0.35,0.46,0.65)*stars(uv)*0.45;
+ color += vec3(0.014,0.02,0.06)*exp(-abs(p.y+0.5)*5.0);
+ }
+ }
+ let vignette = 1.0 - clamp(dot(uv-vec2(0.5),uv-vec2(0.5))*state.settings.x*1.2,0.0,0.5);
+ return vec4(clamp(color*state.viewport.w*vignette,vec3(0),vec3(1)),1);
+}
diff --git a/Aetheris.Web.Runtime/telos/src/shaders/mesh.wgsl b/Aetheris.Web.Runtime/telos/src/shaders/mesh.wgsl
index 4c089b80..80545797 100644
--- a/Aetheris.Web.Runtime/telos/src/shaders/mesh.wgsl
+++ b/Aetheris.Web.Runtime/telos/src/shaders/mesh.wgsl
@@ -1,11 +1,27 @@
-struct State { vp: mat4x4<f32>, model: mat4x4<f32>, normal: mat4x4<f32>, color: vec4<f32>, parameters: vec4<f32> }
+struct State { vp: mat4x4<f32>, model: mat4x4<f32>, normal: mat4x4<f32>, color: vec4<f32>, parameters: vec4<f32>,
+ camera: vec4<f32>, key: vec4<f32>, keyColor: vec4<f32>, fill: vec4<f32>, fillColor: vec4<f32>,
+ sky: vec4<f32>, ground: vec4<f32>, rim: vec4<f32>, tuning: vec4<f32>, up: vec4<f32> }
@group(0) @binding(0) var<uniform> state: State;
-struct Output { @builtin(position) position: vec4<f32>, @location(0) normal: vec3<f32> }
+struct Output { @builtin(position) position: vec4<f32>, @location(0) normal: vec3<f32>, @location(1) world: vec3<f32> }
@vertex fn vertex(@location(0) position: vec3<f32>, @location(1) normal: vec3<f32>) -> Output {
var out: Output; out.position = state.vp * state.model * vec4(position, 1);
- out.normal = (state.normal * vec4(normal, 0)).xyz; return out;
+ out.normal = (state.normal * vec4(normal, 0)).xyz; out.world = (state.model * vec4(position,1)).xyz; return out;
}
-@fragment fn fragment(input: Output) -> @location(0) vec4<f32> {
+@fragment fn fragment(input: Output, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
+ if (state.tuning.w > 0.5 && state.parameters.z < 0.5) {
+ let n = select(-normalize(input.normal),normalize(input.normal),front);
+ let v = normalize(state.camera.xyz-input.world); let key = normalize(state.key.xyz); let fill = normalize(state.fill.xyz);
+ let roughness = clamp(state.parameters.x,0.08,1.0); let metallic = clamp(state.parameters.y,0.0,1.0);
+ let hemisphere = mix(state.ground.rgb,state.sky.rgb,dot(n,state.up.xyz)*0.5+0.5)*state.sky.w*0.5;
+ let light = hemisphere + vec3(state.tuning.x) + state.keyColor.rgb*max(dot(n,key),0.0)*state.key.w*0.5
+ + state.fillColor.rgb*max(dot(n,fill),0.0)*state.fill.w*0.6;
+ let spec = pow(max(dot(n,normalize(key+v)),0.0),mix(120.0,4.0,roughness))*mix(0.10,0.55,metallic)*state.key.w;
+ let rim = pow(1.0-max(dot(n,v),0.0),3.0)*state.rim.w*0.32;
+ let reflectance = mix(vec3(1),state.color.rgb,metallic);
+ let c = (state.color.rgb*light + reflectance*state.keyColor.rgb*spec + state.rim.rgb*rim)*state.tuning.y;
+ let mapped = clamp((c*(2.51*c+vec3(0.03)))/(c*(2.43*c+vec3(0.59))+vec3(0.14)),vec3(0),vec3(1));
+ return vec4(pow(mapped,vec3(1.0/2.2)),state.color.a);
+ }
let n = normalize(input.normal); let light = normalize(vec3<f32>(0.3, 0.8, 0.6));
let diffuse = 0.28 + 0.72 * abs(dot(n, light));
let roughness = clamp(state.parameters.x, 0.04, 1.0); let metallic = clamp(state.parameters.y, 0.0, 1.0);
diff --git a/Aetheris.Web.Runtime/telos/tests/inspection.test.ts b/Aetheris.Web.Runtime/telos/tests/inspection.test.ts
new file mode 100644
index 00000000..8b38081a
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tests/inspection.test.ts
@@ -0,0 +1,42 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { inspectSurfaces, surfaceInspectionFaces, TelosCamera, TelosPick, materialFromAppearance } from "../dist/index.js";
+import type { TelosScene } from "../dist/index.js";
+
+test("packed face inspection retains original triangle picking and occurrence identity", () => {
+ const definition = { id: "body", positions: [-1,-1,0, 1,-1,0, -1,1,0, 1,1,0],
+ normals: [0,0,1, 0,0,1, 0,0,1, 0,0,1], indices: [0,1,2, 2,1,3],
+ ranges: [{ startTriangle: 0, triangleCount: 1, faceId: "first" }, { startTriangle: 1, triangleCount: 1, faceId: "second" }] };
+ const scene: TelosScene = { meshes: ["a", "b"].map(occurrenceId => ({ definition,
+ identity: { occurrenceId, definitionId: "body" }, material: materialFromAppearance() })), lines: [], fields: [] };
+ const face = surfaceInspectionFaces(scene).find(face => face.occurrenceId === "a" && face.faceId === "second")!;
+ const projected = inspectSurfaces(scene, "patches", face);
+ assert.equal(projected.meshes.filter(mesh => mesh.visible).length, 1);
+ assert.equal(projected.meshes[1].definition.positions, definition.positions);
+ assert.equal(projected.meshes[1].definition.indices, inspectSurfaces(scene, "overlay", face).meshes[1].definition.indices);
+ const camera = new TelosCamera(); camera.resize(800,600); camera.mode = "orthographic";
+ camera.position.set(0,0,5); camera.target.set(0,0,0); camera.span = 4; camera.update();
+ const pick = new TelosPick(camera); pick.setScene(projected);
+ assert.equal(pick.proxies[0].geometry.getAttribute("position"), pick.proxies[1].geometry.getAttribute("position"));
+ assert.equal(pick.proxies[0].geometry.index, pick.proxies[1].geometry.index);
+ const hit = pick.pick([450,250]);
+ assert.equal(hit?.faceId, "second"); assert.equal(hit?.triangleIndex, 1);
+ assert.equal(hit?.definitionId, "body"); assert.equal(hit?.occurrenceId, "a");
+ assert.equal(inspectSurfaces(scene,"normal"), scene);
+ assert.equal(definition.indices.length, 6); pick.dispose();
+});
+
+test("whole field comparison draws the field; face inspection explicitly projects the retained proxy", () => {
+ const material = materialFromAppearance();
+ const proxy = { id: "proxy", positions: [0,0,0,1,0,0,0,1,0], normals: [0,0,1,0,0,1,0,0,1],
+ indices: [0,1,2], ranges: [{ startTriangle:0, triangleCount:1, faceId:7 }] };
+ const scene: TelosScene = { meshes:[], lines:[], fields:[{ identity:{ occurrenceId:"field", definitionId:"proxy" },
+ material, proxy, bounds:{ minimum:[0,0,0], maximum:[1,1,1] },
+ artifact:{ shaderId:"field", wgsl:"", vertexEntryPoint:"vs", fragmentEntryPoint:"fs", bindings:[], capabilities:[], sourceIdentity:"x" } }] };
+ assert.equal(inspectSurfaces(scene,"surfaces").fields[0].visible,true);
+ assert.equal(inspectSurfaces(scene,"surfaces").meshes.length,0);
+ const isolated = inspectSurfaces(scene,"overlay",surfaceInspectionFaces(scene)[0]);
+ assert.equal(isolated.fields[0].visible,false);
+ assert.equal(isolated.meshes[0].identity.faceId,7);
+ assert.equal(isolated.meshes[0].definition.positions,proxy.positions);
+});
diff --git a/Aetheris.slnx b/Aetheris.slnx
index c084f969..6e608956 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -1,4 +1,5 @@
<Solution>
+ <Project Path="test-support/Aetheris.StepLegacyCorpus/Aetheris.StepLegacyCorpus.csproj" />
<Project Path="Aetheris.Cadmata.Desktop/Aetheris.Cadmata.Desktop.csproj" />
<Project Path="Aetheris.Server/Aetheris.Server.csproj" />
<Project Path="Aetheris.Drawing/Aetheris.Drawing.csproj" />
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 78176ac3..28eaf6e9 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -4,6 +4,29 @@ Aetheris source code is licensed separately under the GNU Affero General
Public License v3.0 (`AGPL-3.0`). The assets below retain their respective
licenses, terms, and provenance and are not relicensed as Aetheris source code.
+## Earcut polygon triangulation
+
+`Aetheris.Kernel.Core/Brep/Tessellation/EarCutTriangulator.cs` adapts the
+Mapbox Earcut algorithm. X4 reuses this existing C# utility; it adds no binary
+geometry dependency. Upstream source and license:
+https://github.com/mapbox/earcut (ISC).
+
+ISC License
+
+Copyright (c) 2026, Mapbox
+
+Permission to use, copy, modify, and/or distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright notice
+and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+
## Antonia Polygon original base figure
The HUMANOID-X1 adoption candidate is based on **Antonia Polygon** by
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 22ebf164..bc067cee 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -565,6 +565,8 @@ function App() {
}
const imported = await importStep(documentId, stepText, fileName);
+ const qualificationStatus = imported.importStatus ?? "Inspectable";
+ setDiagnostics(imported.diagnostics);
if (imported.assemblyPresentation) {
setAssemblyPacket(imported.assemblyPresentation);
setSelectedAssemblyOccurrenceId(null);
@@ -577,7 +579,7 @@ function App() {
setStatus("success");
setStatusMessage(`Assembly loaded: ${imported.assemblyPresentation.name}`);
setImportStatus("success");
- setImportStatusMessage(`Assembly ready: ${imported.assemblyPresentation.occurrences.length - 1} occurrences, ${imported.assemblyPresentation.definitions.length} definitions.`);
+ setImportStatusMessage(`${qualificationStatus}: ${imported.assemblyPresentation.occurrences.length - 1} occurrences, ${imported.assemblyPresentation.definitions.length} definitions. ${qualificationStatus === "Degraded" ? "Engineering checks are incomplete; see diagnostics." : qualificationStatus === "Inspectable" ? "Import qualification is incomplete." : ""}`);
dispatchDocumentEvent({ type: "LoadSucceeded", documentId });
return;
}
@@ -592,8 +594,12 @@ function App() {
imported.occurrenceId,
true,
);
- const exported = await exportDefinitionStep(documentId, imported.definitionId);
- setStepCanonicalHash(exported.canonicalHash);
+ setStepCanonicalHash(null);
+ const displayComplete = !displayRefresh.error && displayRefresh.preparation?.status === "Complete";
+ if (qualificationStatus === "Qualified" && displayComplete) {
+ const exported = await exportDefinitionStep(documentId, imported.definitionId);
+ setStepCanonicalHash(exported.canonicalHash);
+ }
setPickStatus("idle");
setPickMessage(`Imported occurrence ${imported.occurrenceId} is now active.`);
setPickDiagnostics([]);
@@ -605,15 +611,16 @@ function App() {
setStatusMessage(
`View materialization failed after import: ${displayRefresh.error.message}`,
);
- setDiagnostics(displayRefresh.error.diagnostics);
+ setDiagnostics([...imported.diagnostics, ...displayRefresh.error.diagnostics]);
setImportStatus("success");
- setImportStatusMessage("Import complete. View materialization failed.");
+ setImportStatusMessage("Degraded: import retained. View materialization failed.");
} else {
+ setDiagnostics(imported.diagnostics);
setStatus("success");
setStatusMessage("Import STEP complete.");
setImportStatus("success");
setImportStatusMessage(
- createDisplayStatusSummary(displayRefresh.preparation)?.summary ?? "Import complete.",
+ `${displayComplete ? qualificationStatus : "Degraded"}: ${createDisplayStatusSummary(displayRefresh.preparation)?.summary ?? "Import retained."}`,
);
}
dispatchDocumentEvent({ type: "LoadSucceeded", documentId });
diff --git a/aetheris.client/src/__tests__/App.test.tsx b/aetheris.client/src/__tests__/App.test.tsx
index 85a4dfc4..ffa5734b 100644
--- a/aetheris.client/src/__tests__/App.test.tsx
+++ b/aetheris.client/src/__tests__/App.test.tsx
@@ -74,6 +74,7 @@ function setupDocumentApiMocks(): void {
apiMocks.tessellateBody.mockResolvedValue({ facePatches: [], edgePolylines: [] });
apiMocks.prepareBodyDisplay.mockResolvedValue({
lane: "fallback-only",
+ status: "Complete",
analyticPacket: {
bodyId: 1,
analyticFaces: [],
@@ -240,6 +241,7 @@ describe("App STEP file upload flow", () => {
it("keeps canonical hash visible from viewer inspector", async () => {
apiMocks.importStep.mockResolvedValue({
+ importStatus: "Qualified",
documentId: "doc-1",
definitionId: "def-2",
occurrenceId: "occ-2",
@@ -431,6 +433,7 @@ describe("App STEP file upload flow", () => {
it("calls importStep with file contents and refreshes canonical hash", async () => {
apiMocks.importStep.mockResolvedValue({
+ importStatus: "Qualified",
documentId: "doc-1",
definitionId: "def-2",
occurrenceId: "occ-2",
@@ -527,7 +530,8 @@ describe("App STEP file upload flow", () => {
await screen.findByText("ftc06.stp");
fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));
- await screen.findByText("Import complete. Display: mixed analytic + bounded mesh fallback.");
+ await screen.findByText("Inspectable: Import complete. Display: mixed analytic + bounded mesh fallback.");
+ expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
expect(screen.queryByText("Import failed")).toBeNull();
});
@@ -742,7 +746,9 @@ describe("App STEP file upload flow", () => {
)
).length,
).toBeGreaterThan(0);
- await screen.findByText("hash-123");
+ await screen.findByText("Degraded: Import complete. Display partial: 0 wire-only face(s), 1 diagnostic-only face(s).");
+ expect(screen.queryByText("hash-123")).toBeNull();
+ expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
expect(screen.queryByText("Import failed")).toBeNull();
});
@@ -862,12 +868,13 @@ describe("App STEP file upload flow", () => {
fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));
- await screen.findByText("Import complete. View materialization failed.");
+ await screen.findByText("Degraded: import retained. View materialization failed.");
await screen.findByText(
"[Error] ValidationFailed: Display tessellation exceeded the bounded execution budget.",
);
expect(screen.queryByText("Import failed")).toBeNull();
- await screen.findByText("hash-123");
+ expect(screen.queryByText("hash-123")).toBeNull();
+ expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
});
it("preserves ApiError diagnostics from canonical download failure", async () => {
diff --git a/aetheris.client/src/__tests__/cadmataTelos.test.ts b/aetheris.client/src/__tests__/cadmataTelos.test.ts
index 256328cc..9a43cbdd 100644
--- a/aetheris.client/src/__tests__/cadmataTelos.test.ts
+++ b/aetheris.client/src/__tests__/cadmataTelos.test.ts
@@ -1,8 +1,32 @@
import { describe, it, expect } from "vitest";
import { cadmataTelosScene } from "../viewer/cadmataTelos";
import type { DisplayScene } from "../viewer/displayRenderables";
+import type { AssemblyDisplayPacketDto } from "../api/aetherisApi";
describe("Cadmata Telos packet adapter", () => {
+ it("shares kernel edge buffers across occurrence transforms and selection changes", () => {
+ const first = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 5, 0, 0, 1];
+ const second = [...first]; second[12] = 9;
+ const packet: AssemblyDisplayPacketDto = {
+ schema: "test", name: "fixture", rootOccurrenceStableId: "first",
+ definitions: [{ stableId: "part", definitionIdentity: "part", facePatches: [],
+ edgePolylines: [{ edgeId: 31, points: [{ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }], isClosed: false }] }],
+ occurrences: [first, second].map((worldTransform, i) => ({ stableId: i ? "second" : "first", name: "part",
+ instancePath: String(i), parentStableId: null, definitionStableId: "part", kind: "Part", worldTransform,
+ placementAuthority: "ImportedOccurrence" })),
+ mates: [], toleranceStackups: [], bounds: { minimum: [0, 0, 0], maximum: [10, 1, 1] }, diagnostics: [], performance: {},
+ };
+ const before = cadmataTelosScene({ assemblyPacket: packet, showAxisGuide: false });
+ const after = cadmataTelosScene({ assemblyPacket: packet, showAxisGuide: false, selectedAssemblyOccurrenceId: "first" });
+ expect(before.lines).toHaveLength(2);
+ expect(before.lines[0].identity).toEqual({ occurrenceId: "first", edgeId: 31 });
+ expect(before.lines[0].transform).toBe(first);
+ expect(before.lines[1].transform).toBe(second);
+ expect(before.lines[0].points).toBe(before.lines[1].points);
+ expect(after.lines[0].points).toBe(before.lines[0].points);
+ expect(after.lines[0].selected).toBe(true);
+ expect(after.lines[1].selected).toBe(false);
+ });
it("preserves mesh face and kernel edge identity with highlight state", () => {
const scene: DisplayScene = {
status: "Complete",
diff --git a/aetheris.client/src/__tests__/displayRenderables.test.ts b/aetheris.client/src/__tests__/displayRenderables.test.ts
index fa3445c4..84665ee6 100644
--- a/aetheris.client/src/__tests__/displayRenderables.test.ts
+++ b/aetheris.client/src/__tests__/displayRenderables.test.ts
@@ -14,6 +14,17 @@ const diagnostic = {
suggestedNextAction: null,
};
+it("keeps authoritative boundary lines on the analytic-only route without a mesh fallback", () => {
+ const preparation = prepWithFaces([]);
+ preparation.lane = "analytic-only";
+ preparation.topologyEdges = [{ edgeId: 7, points: [{ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }], isClosed: false }];
+ const scene = mapDisplayPreparationToDisplayScene(preparation);
+ if (!scene) throw new Error("Preparation must produce a display scene");
+ expect(scene.topologyEdges).toHaveLength(1);
+ expect(scene.topologyEdges![0].edgeId).toBe(7);
+ expect(Array.from(scene.topologyEdges![0].points)).toEqual([0, 0, 0, 1, 0, 0]);
+});
+
function prepWithFaces(
faces: DisplayPreparationResponseDto["faces"],
): DisplayPreparationResponseDto {
diff --git a/aetheris.client/src/__tests__/surfaceInspection.test.ts b/aetheris.client/src/__tests__/surfaceInspection.test.ts
new file mode 100644
index 00000000..8e87209f
--- /dev/null
+++ b/aetheris.client/src/__tests__/surfaceInspection.test.ts
@@ -0,0 +1,30 @@
+import { expect, it } from "vitest";
+import type { TelosScene } from "@aetheris/three-telos";
+import { inspectSurfaces } from "../viewer/surfaceInspection";
+
+it("compares disposable surfaces and authoritative edges without changing buffers or occurrence identities", () => {
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
+ const material = { baseColor: [.5, .5, .5], opacity: 1, roughness: .6, metallic: 0 };
+ const scene: TelosScene = {
+ meshes: ["first", "second"].map(occurrenceId => ({ identity: { occurrenceId, faceId: 7 }, material,
+ definition: { id: occurrenceId, positions, normals: positions, indices: [0, 1, 2] } })),
+ lines: ["first", "second"].map(occurrenceId => ({ id: occurrenceId, identity: { occurrenceId, edgeId: 11 }, points: positions })),
+ fields: [],
+ };
+ expect(inspectSurfaces(scene, "normal")).toBe(scene);
+ const wire = inspectSurfaces(scene, "wire");
+ expect(wire.meshes.every(m => m.visible === false)).toBe(true);
+ expect(wire.lines.every(l => l.visible && l.depthMode === "always-on-top")).toBe(true);
+ const surface = inspectSurfaces(scene, "surfaces");
+ expect(surface.meshes.every(m => m.visible)).toBe(true);
+ expect(surface.lines.every(l => l.visible === false)).toBe(true);
+ const overlay = inspectSurfaces(scene, "overlay", { key: "first", occurrenceId: "first", faceId: 7, edgeIds: [11] });
+ expect(overlay.meshes[0].material.opacity).toBe(.2);
+ expect(overlay.meshes[1].visible).toBe(false);
+ expect(overlay.lines[0].visible).toBe(true);
+ expect(overlay.lines[1].visible).toBe(false);
+ expect(overlay.meshes[0].definition.positions).toBe(positions);
+ expect(overlay.meshes[0].identity).toBe(scene.meshes[0].identity);
+ expect(scene.meshes[0].visible).toBeUndefined();
+ expect(scene.meshes[0].material.opacity).toBe(1);
+});
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index 5bb907c4..c3d54673 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -67,6 +67,8 @@ export interface StepImportResponseDto {
diagnostics: DiagnosticDto[];
semanticPresentation?: unknown | null;
assemblyPresentation?: AssemblyDisplayPacketDto | null;
+ importStatus?: "Qualified" | "Inspectable" | "Degraded" | "Failed";
+ importQualifications?: unknown[];
}
export interface PaperclipDemoRequestDto {
@@ -149,10 +151,18 @@ export interface StartupStepDto {
kind?: "step" | "assembly";
}
+export interface DisplayFaceSourceDto {
+ faceId: number;
+ sourceStepEntityId: number | null;
+ surfaceKind: string;
+ edgeIds: number[];
+}
export interface AssemblyDisplayDefinitionDto {
stableId: string;
definitionIdentity: string;
facePatches: FacePatchDto[];
+ edgePolylines?: EdgePolylineDto[];
+ faceSources?: DisplayFaceSourceDto[];
}
export interface AssemblyDisplayOccurrenceDto {
stableId: string;
@@ -321,6 +331,7 @@ export interface DisplayEdgeDto {
}
export interface DisplayFaceDto {
+ source?: DisplayFaceSourceDto | null;
faceId: number;
shellId: number | null;
surfaceKind: string | null;
@@ -366,6 +377,7 @@ export interface DisplayLaneDto {
}
export interface DisplayPreparationResponseDto {
+ topologyEdges?: EdgePolylineDto[] | null;
lane: "analytic-only" | "mixed-fallback" | "fallback-only" | string;
analyticPacket: AnalyticDisplayPacketDto;
tessellationFallback: TessellationResponseDto | null;
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index 1d8a04b6..acb390ba 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -1,4 +1,4 @@
-import { lazy, Suspense, useEffect, useRef, useState } from "react";
+import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
import { TelosHost, clearColor } from "@aetheris/three-telos";
import type { AetherisViewportProps } from "./viewportProps";
import { PmiAnnotationLayer } from "./PmiAnnotationLayer";
@@ -9,6 +9,8 @@ const LegacyAetherisViewport = lazy(() =>
})),
);
import { cadmataTelosScene } from "./cadmataTelos";
+import { inspectSurfaces, inspectionFaceKey, type SurfaceInspectionFace, type SurfaceInspectionMode } from "./surfaceInspection";
+import { telosPresentation } from "./telosPresentation";
import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
import { reportDesktopDiagnostic } from "../desktopDiagnostics";
export type { AetherisViewportProps } from "./viewportProps";
@@ -56,6 +58,27 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
const latest = useRef(props);
const [diagnostic, setDiagnostic] = useState<string | null>(null);
const [labelHost, setLabelHost] = useState<TelosHost | null>(null);
+ const [inspectionMode, setInspectionMode] = useState<SurfaceInspectionMode>("normal");
+ const [isolatedFaceKey, setIsolatedFaceKey] = useState("");
+ const inspectionFaces = useMemo(() => {
+ const scene = cadmataTelosScene(props);
+ const faces = new Map<string, SurfaceInspectionFace>();
+ for (const item of [...scene.meshes, ...scene.fields]) {
+ if (item.identity.faceId === undefined || ("overlay" in item && item.overlay)) continue;
+ const { occurrenceId, faceId } = item.identity;
+ const occurrence = props.assemblyPacket?.occurrences.find(o => o.stableId === occurrenceId);
+ const source = props.assemblyPacket?.definitions.find(d => d.stableId === occurrence?.definitionStableId)
+ ?.faceSources?.find(f => f.faceId === faceId)
+ ?? props.displayScene?.renderables.find(f => f.faceId === faceId)?.source;
+ const key = inspectionFaceKey(occurrenceId, faceId);
+ faces.set(key, { key, occurrenceId, faceId, sourceStepEntityId: source?.sourceStepEntityId,
+ surfaceKind: source?.surfaceKind, edgeIds: source?.edgeIds });
+ }
+ return [...faces.values()];
+ }, [props]);
+ const isolatedFace = inspectionFaces.find(f => f.key === isolatedFaceKey);
+ const inspection = useRef({ mode: inspectionMode, face: isolatedFace });
+ inspection.current = { mode: inspectionMode, face: isolatedFace };
const lastModel = useRef<unknown>(undefined);
const apply = () => {
const current = host.current;
@@ -63,7 +86,8 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
const value = latest.current,
theme = value.theme ?? ATELIER_VIEWPORT_THEME;
current.setAA(value.aaMode ?? "SpatialOnly", value.aaDebug ?? "color");
- current.setScene(cadmataTelosScene(value));
+ current.setPresentation(telosPresentation(theme));
+ current.setScene(inspectSurfaces(cadmataTelosScene(value), inspection.current.mode, inspection.current.face));
current.background = clearColor(theme.sceneBackground);
current.grid = value.showGrid !== false && theme.gridStyle.enabled;
const model = value.assemblyPacket ?? value.displayScene;
@@ -71,6 +95,11 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
lastModel.current = model;
current.fit();
}
+ canvas.current?.setAttribute("data-surface-inspection", JSON.stringify({ mode: inspection.current.mode,
+ isolatedFace: inspection.current.face ?? null,
+ camera: { position: current.camera.position.toArray(), target: current.camera.target.toArray(), span: current.camera.span },
+ visibleMeshes: current.scene.meshes.filter(m => !m.overlay && m.visible !== false).length,
+ visibleEdges: current.scene.lines.filter(l => l.identity.edgeId !== undefined && l.visible !== false).length }));
current.invalidate();
};
useEffect(() => {
@@ -87,6 +116,9 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
event.clientY - rect.top,
];
const hit = current.picker.pick(pixel);
+ element.setAttribute("data-surface-inspection-pick", JSON.stringify(hit ?? null));
+ if (inspection.current.mode !== "normal" && hit?.faceId !== undefined)
+ setIsolatedFaceKey(inspectionFaceKey(hit.occurrenceId, hit.faceId));
if (hit?.overlayId) {
latest.current.onCadmataSelect?.(hit.overlayId);
return;
@@ -159,7 +191,8 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
useEffect(() => {
latest.current = props;
apply();
- }, [props]);
+ }, [props, inspectionMode, isolatedFaceKey]);
+ useEffect(() => { setIsolatedFaceKey(""); }, [props.assemblyPacket, props.displayScene]);
return (
<div
ref={container}
@@ -173,6 +206,32 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
aria-label="Engineering WebGPU viewport"
style={{ display: "block", width: "100%", height: "100%" }}
/>
+ {inspectionFaces.length > 0 && (
+ <details style={{ position: "absolute", left: 12, bottom: 12, zIndex: 3,
+ background: (props.theme ?? ATELIER_VIEWPORT_THEME).annotation.background,
+ color: (props.theme ?? ATELIER_VIEWPORT_THEME).annotation.text, padding: 8, maxWidth: 420 }}>
+ <summary>Surface / trim inspection</summary>
+ <label>View <select aria-label="Surface inspection view" value={inspectionMode}
+ onChange={event => setInspectionMode(event.target.value as SurfaceInspectionMode)}>
+ <option value="normal">Normal</option><option value="surfaces">Surfaces only</option>
+ <option value="wire">BRep wire only</option><option value="overlay">Translucent + BRep wire</option>
+ <option value="patches">Face colors + BRep wire</option>
+ </select></label>
+ <div><label>Patch <select aria-label="Isolated display face" value={isolatedFaceKey}
+ style={{ maxWidth: 300 }} onChange={event => setIsolatedFaceKey(event.target.value)}>
+ <option value="">All faces</option>
+ {inspectionFaces.map(face => <option key={face.key} value={face.key}>
+ Face {face.faceId}{face.sourceStepEntityId ? ` / STEP #${face.sourceStepEntityId}` : ""}
+ {face.surfaceKind ? ` / ${face.surfaceKind}` : ""} / {face.occurrenceId}
+ </option>)}
+ </select></label></div>
+ {isolatedFace && <div>Face {isolatedFace.faceId} · STEP #{isolatedFace.sourceStepEntityId ?? "unknown"}
+ {` · ${isolatedFace.surfaceKind ?? "unknown support"} · ${isolatedFace.edgeIds?.length ?? 0} boundary edges`}</div>}
+ <small>{cadmataTelosScene(props).fields.length ? "Mesh / SDF display" : "BRep mesh display; no SDF field"}.
+ {inspectionMode === "overlay" || inspectionMode === "wire" ? " Red BRep edges show through surfaces." : " Red lines are BRep edges."}
+ {inspectionMode !== "normal" ? " Click a surface to isolate its patch." : ""}</small>
+ </details>
+ )}
{!!props.assemblyPacket?.display?.cameras?.length && (
<select
aria-label="Scene camera"
diff --git a/aetheris.client/src/viewer/cadmataTelos.ts b/aetheris.client/src/viewer/cadmataTelos.ts
index 02d6e1eb..ce77a521 100644
--- a/aetheris.client/src/viewer/cadmataTelos.ts
+++ b/aetheris.client/src/viewer/cadmataTelos.ts
@@ -13,13 +13,14 @@ import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
import {
mapFacePatchToRenderFacePatch,
type RenderFacePatch,
+ type RenderEdgePolyline,
} from "./tessellationMapper";
import type { AssemblyDisplayPacketDto } from "../api/aetherisApi";
// Definitions are immutable within a packet. Selection updates reuse both CPU arrays and GPU buffers.
const assemblyGeometry = new WeakMap<
AssemblyDisplayPacketDto,
- Map<string, RenderFacePatch[]>
+ Map<string, { faces: RenderFacePatch[]; edges: RenderEdgePolyline[] }>
>();
/** Product packet interpretation only. Camera, drawing and engineering picking live in Telos. */
@@ -109,6 +110,18 @@ export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
props.highlightedEdgeId === edge.edgeId),
});
}
+ const wireIds = new Set(lines.map(line => line.identity.edgeId));
+ for (const edge of props.displayScene?.topologyEdges ?? []) {
+ if (wireIds.has(edge.edgeId)) continue;
+ const selected = props.highlightedEdgeIds?.has(edge.edgeId) ?? props.highlightedEdgeId === edge.edgeId;
+ lines.push({
+ id: "edge:" + edge.edgeId, points: edge.points,
+ identity: { occurrenceId: "part", edgeId: edge.edgeId },
+ color: materialFromAppearance({ color: selected ? theme.edgeStyle.selectedColor : theme.edgeStyle.color }).baseColor.concat(1),
+ widthPixels: selected ? theme.edgeStyle.selectedWidth : theme.edgeStyle.width,
+ selected, depthMode: "depth-biased",
+ });
+ }
const packet = props.assemblyPacket;
if (packet) {
let definitions = assemblyGeometry.get(packet);
@@ -116,7 +129,9 @@ export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
definitions = new Map(
packet.definitions.map((definition) => [
definition.stableId,
- definition.facePatches.map(mapFacePatchToRenderFacePatch),
+ { faces: definition.facePatches.map(mapFacePatchToRenderFacePatch),
+ edges: (definition.edgePolylines ?? []).map(edge => ({ edgeId: edge.edgeId,
+ points: new Float32Array(edge.points.flatMap(p => [p.x, p.y, p.z])) })) },
]),
);
assemblyGeometry.set(packet, definitions);
@@ -127,8 +142,8 @@ export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
)?.selectionMembers ?? [props.selectedAssemblyOccurrenceId],
);
for (const occurrence of packet.occurrences)
- if (occurrence.definitionStableId)
- for (const patch of definitions.get(occurrence.definitionStableId) ??
+ if (occurrence.definitionStableId) {
+ for (const patch of definitions.get(occurrence.definitionStableId)?.faces ??
[]) {
addFace(
patch,
@@ -138,6 +153,21 @@ export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
selection.has(occurrence.stableId),
);
}
+ for (const edge of definitions.get(occurrence.definitionStableId)?.edges ?? []) {
+ const selected = selection.has(occurrence.stableId)
+ || (props.highlightedEdgeIds?.has(edge.edgeId) ?? props.highlightedEdgeId === edge.edgeId);
+ lines.push({
+ id: occurrence.stableId + ":edge:" + edge.edgeId,
+ points: edge.points,
+ transform: occurrence.worldTransform,
+ identity: { occurrenceId: occurrence.stableId, edgeId: edge.edgeId },
+ color: materialFromAppearance({ color: selected ? theme.edgeStyle.selectedColor : theme.edgeStyle.color }).baseColor.concat(1),
+ widthPixels: selected ? theme.edgeStyle.selectedWidth : theme.edgeStyle.width,
+ selected,
+ depthMode: "depth-biased",
+ });
+ }
+ }
}
if (props.showAxisGuide !== false)
for (const [axis, color] of [
diff --git a/aetheris.client/src/viewer/displayRenderables.ts b/aetheris.client/src/viewer/displayRenderables.ts
index 0693aa0c..08591c65 100644
--- a/aetheris.client/src/viewer/displayRenderables.ts
+++ b/aetheris.client/src/viewer/displayRenderables.ts
@@ -14,6 +14,7 @@ import {
export type DisplayRenderableKind = "AnalyticPatch" | "MeshPatch" | "WirePatch" | "DiagnosticPatch";
export interface DisplayRenderableBase {
+ source?: import("../api/aetherisApi").DisplayFaceSourceDto | null;
kind: DisplayRenderableKind;
faceId: number;
surfaceKind: string | null;
@@ -54,6 +55,8 @@ export interface DisplayScene {
displayAuthority: string | null;
lanes: DisplayLaneDto[];
renderables: DisplayRenderable[];
+ /** Disposable samples of authoritative kernel edges, independent of mesh triangle connectivity. */
+ topologyEdges?: RenderEdgePolyline[];
diagnostics: DisplayDiagnosticDto[];
legacyCompatibility?: {
source: "tessellationFallback";
@@ -64,6 +67,7 @@ export interface DisplayScene {
function base(face: DisplayFaceDto): Omit<DisplayRenderableBase, "kind"> {
return {
+ source: face.source,
faceId: face.faceId,
surfaceKind: face.surfaceKind,
status: face.status,
@@ -172,5 +176,9 @@ export function mapDisplayPreparationToDisplayScene(
mapDisplayFaceToRenderable(face, fallbackMeshByFaceId.get(face.faceId) ?? null),
),
diagnostics: preparation.diagnostics ?? [],
+ topologyEdges: (preparation.topologyEdges ?? preparation.tessellationFallback?.edgePolylines ?? []).map(edge => ({
+ edgeId: edge.edgeId,
+ points: new Float32Array(edge.points.flatMap(p => [p.x, p.y, p.z])),
+ })),
};
}
diff --git a/aetheris.client/src/viewer/surfaceInspection.ts b/aetheris.client/src/viewer/surfaceInspection.ts
new file mode 100644
index 00000000..2125fa68
--- /dev/null
+++ b/aetheris.client/src/viewer/surfaceInspection.ts
@@ -0,0 +1,2 @@
+export { inspectSurfaces, inspectionFaceKey, surfaceInspectionFaces } from "@aetheris/three-telos";
+export type { SurfaceInspectionMode, SurfaceInspectionFace } from "@aetheris/three-telos";
diff --git a/aetheris.client/src/viewer/telosPresentation.ts b/aetheris.client/src/viewer/telosPresentation.ts
new file mode 100644
index 00000000..035266c5
--- /dev/null
+++ b/aetheris.client/src/viewer/telosPresentation.ts
@@ -0,0 +1,27 @@
+import { Color } from "three";
+import type { TelosPresentation, Vec3 } from "@aetheris/three-telos";
+import type { ViewportTheme } from "./viewportTheme";
+
+const linear = (value: string) => new Color(value).toArray() as unknown as Vec3;
+const encoded = (value: string) => new Color(value).convertLinearToSRGB().toArray() as unknown as Vec3;
+const cache = new WeakMap<ViewportTheme, TelosPresentation>();
+/** Project the existing product theme into the shared WebGPU presentation contract. */
+export function telosPresentation(theme: ViewportTheme): TelosPresentation {
+ let value = cache.get(theme);
+ if (value) return value;
+ const l = theme.lights, g = theme.gridStyle;
+ const kind = theme.id === "blueprint" || theme.id === "aurora" ? theme.id
+ : theme.id === "monument" ? "paper" : theme.background.kind === "flat" ? "studio" : theme.background.kind;
+ value = { id: theme.id,
+ backdrop: { kind, base: encoded(theme.sceneBackground), accent: encoded(theme.background.accent),
+ intensity: theme.background.kind === "flat" ? 1 : theme.background.intensity, vignette: theme.postProcess.vignette },
+ lighting: { ambient:l.ambient, exposure:theme.environment.toneMappingExposure,
+ sky:linear(l.hemisphereSky), ground:linear(l.hemisphereGround), hemisphere:l.hemisphereIntensity,
+ key:l.keyPosition, keyColor:linear(l.keyColor), keyIntensity:l.keyIntensity,
+ fill:l.fillPosition, fillColor:linear(l.fillColor), fillIntensity:l.fillIntensity,
+ rim:linear(l.rimColor), rimIntensity:l.rimIntensity, selection:linear(theme.selectedMaterial.color) },
+ grid:{ minor:encoded(g.minorColor), major:encoded(g.majorColor), minorOpacity:g.minorOpacity, majorOpacity:g.majorOpacity,
+ majorStep:g.majorStep, targetCells:g.targetCellCount, maxLines:g.maxLinesPerAxis, extentScale:g.extentScale, offset:g.yOffset },
+ };
+ cache.set(theme,value); return value;
+}
diff --git a/aetheris.client/src/viewer/viewportTheme.ts b/aetheris.client/src/viewer/viewportTheme.ts
index a5c1f5e5..eeed9f6b 100644
--- a/aetheris.client/src/viewer/viewportTheme.ts
+++ b/aetheris.client/src/viewer/viewportTheme.ts
@@ -5,6 +5,8 @@ export const VIEWPORT_THEME_IDS = [
"sirius",
"singularity",
"aeons",
+ "blueprint",
+ "aurora",
] as const;
export type ViewportThemeId = (typeof VIEWPORT_THEME_IDS)[number];
@@ -419,6 +421,25 @@ export const VIEWPORT_THEMES: readonly ViewportTheme[] = [
SIRIUS_VIEWPORT_THEME,
SINGULARITY_VIEWPORT_THEME,
AEONS_VIEWPORT_THEME,
+ { ...ATELIER_VIEWPORT_THEME, id:"blueprint", label:"Blueprint",
+ description:"Cobalt drafting desk with porcelain surfaces, white topology and a measured cyan grid.",
+ sceneBackground:"#0c2344", background:{kind:"flat",fallback:"#0c2344",accent:"#72b9ed",intensity:1},
+ objectMaterial:{color:"#c3dcf1",roughness:0.85,metalness:0.02},
+ edgeStyle:{color:"#4d86b9",width:1.2,selectedColor:"#ffda7b",selectedWidth:3.2},
+ gridStyle:{...ATELIER_VIEWPORT_THEME.gridStyle,minorColor:"#4274a0",majorColor:"#84c4ee",minorOpacity:0.13,majorOpacity:0.33},
+ lights:{...ATELIER_VIEWPORT_THEME.lights,hemisphereSky:"#c8e4ff",hemisphereGround:"#253656",keyColor:"#eaf7ff",keyIntensity:2.0,fillColor:"#65a8dc",fillIntensity:0.65},
+ annotation:{...ATELIER_VIEWPORT_THEME.annotation,background:"#102c4eed",text:"#e6f4ff",dimension:"#ffda7b"},
+ axis:{x:"#ef8e83",y:"#8dd8c0",z:"#a0c9f3",label:"#d6edff"},
+ },
+ { ...SIRIUS_VIEWPORT_THEME, id:"aurora", label:"Aurora",
+ description:"Titanium beneath mint aurora curtains, violet fill light and a cool luminous rim.",
+ sceneBackground:"#070d20",background:{kind:"sirius",fallback:"#070d20",accent:"#5ff0bd",intensity:1},
+ objectMaterial:{color:"#aeb9c5",roughness:0.34,metalness:0.65},
+ gridStyle:{...SIRIUS_VIEWPORT_THEME.gridStyle,minorColor:"#263651",majorColor:"#63b7bd",minorOpacity:0.04,majorOpacity:0.17},
+ lights:{...SIRIUS_VIEWPORT_THEME.lights,keyColor:"#d9fff0",keyIntensity:2.8,fillColor:"#7057b5",fillIntensity:1.3,rimColor:"#53efc1",rimIntensity:1.8},
+ annotation:{...SIRIUS_VIEWPORT_THEME.annotation,background:"#0b1728ee",datum:"#5ff0bd",dimension:"#e7cbff"},
+ postProcess:{...SIRIUS_VIEWPORT_THEME.postProcess,vignette:0.36,bloom:0},
+ },
];
export const VIEWPORT_THEME_REGISTRY: ReadonlyMap<ViewportThemeId, ViewportTheme> = new Map(
diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.md
index 727906c6..de5b208d 100644
--- a/docs/public/firmament/step-import.md
+++ b/docs/public/firmament/step-import.md
@@ -1,10 +1,24 @@
# STEP import and inlineSTEP
+Use [surface and trim inspection](surface-inspection.md) in Cadmata or Helios to compare filled geometry, BRep wire, translucent overlays and isolated source faces without changing the camera.
+
Use `aetheris analyze part.step --json` to inspect STEP topology, analytic surface families, bounds, manifold assessment, and semantic PMI. When a part is easiest to understand by its manufacturing section, inspect it first with `aetheris analyze section part.step --xy|--xz|--yz --offset value --json`; use `--origin x,y,z --normal x,y,z` for an arbitrary construction plane and `--out section.svg` for deterministic visual evidence. This section-first path preserves analytic line/arc trims and reports closed-loop nesting instead of asking a tessellated view to carry design intent. Use `aetheris sheetmetal recognize` for bounded Sheet Metal recognition rather than treating generic topology analysis as manufacturing intent.
`analyze --json` also reports `splineRecovery`: counts of analytic, exact spline, recovered spline, and unsupported edge/face geometry; the worst measured recovery deviation; and the requested engineering tolerance. The default `ImportPolicy.RecoveryToleranceMillimetres` is 0.1 mm after STEP unit normalization. Rational curves and surfaces are recognized as analytic geometry where qualified; otherwise the importer attempts bounded generic spline recovery and records provenance on recovered geometry. The maximum deviation is sampled evidence.
-For recovered geometry, `pcurveQualification` reports the face-edge use count, source and reconstructed pcurves, failed uses, worst sampled 3D lift deviation, and surface-family counts. `qualified` means every coedge is bound and the independent pcurve validator accepts edge/surface agreement, endpoint sense, and loop closure. `inspectable-unqualified` means the body can still be inspected, but its recovered pcurves do not form a complete qualified trim set; STEP export then omits that partial set while retaining valid source pcurves. `ImportPolicy.PcurveQualificationToleranceMillimetres` defaults to 0.001 mm. A recovered curve or support can use a larger local allowance based on its measured geometry-recovery deviations, capped by the separate 0.1 mm geometry recovery budget. The CLI reports the observed lift deviation separately from geometry recovery deviation.
+For bound geometry, `pcurveQualification` reports the face-edge use count, source and reconstructed pcurves, failed uses, worst sampled 3D lift deviation, and surface-family counts. `qualified` means every coedge is bound and the independent pcurve validator accepts edge/surface agreement, endpoint sense, and loop closure. `inspectable-unqualified` means the body can still be inspected, but its recovered pcurves do not form a complete qualified trim set; STEP export then omits that partial set while retaining valid source pcurves. `ImportPolicy.PcurveQualificationToleranceMillimetres` defaults to 0.001 mm. A recovered curve or support can use a larger local allowance based on its measured geometry-recovery deviations, capped by the separate 0.1 mm geometry recovery budget. The CLI reports the observed lift deviation separately from geometry recovery deviation.
+
+`summary.importQualification` distinguishes `Qualified`, `Inspectable`, `Degraded`, and `Failed` from authoritative BRep evidence. Parser/API success means geometry was retained; it is not a qualification verdict. `status` and `geometryStatus` report engineering qualification independently of the viewport. `displayStatus` separately reports `NotAssessed`, `Complete`, `RefinementLimited`, or `Partial`, with display reasons and missing face identities. Missing trim bindings remain `Inspectable`; detected invalid trims or incomplete intended solid shells are `Degraded` even when a useful preview is complete. Exact faces can receive derived face-local pcurves without being classified as recovered geometry.
+
+Legacy AP203/AP214 import uses the same topology and geometry path. Viewport quality is chosen automatically from model scale and bounded adaptive sampling. Viewport triangles are disposable approximations: STEP export, topology selection, and engineering qualification consume BRep directly. A convincing preview cannot qualify invalid engineering geometry. The frozen 26-file McMaster corpus and the original closeout evidence are recorded in [STEP-LEGACY-CLOSEOUT-X2](../../release/STEP-LEGACY-CLOSEOUT-X2.md); the subsequent visual investigation and ball roundtrip repair are in [STEP-LEGACY-FINAL-X3](../../release/STEP-LEGACY-FINAL-X3.md). Vendor files and generated meshes stay local; the tracked manifest retains the X0 baseline metadata and outcomes.
+
+In Cadmata, expand **Surface / trim inspection** in the viewport. Compare **Surfaces only**, **BRep wire only**, **Translucent + BRep wire**, and **Face colors + BRep wire** without changing the camera. Red lines carry kernel edge identities; the wire and translucent views show them through surfaces. Select a patch from the list, or click a surface in an inspection view, to isolate its occurrence and face with the source STEP entity, support family, and boundary edges. STEP imports currently display BRep meshes, with no SDF field. These diagnostic controls change presentation only.
+
+Dense rectangular spline trims retain native parameter grid cells as the existing `QuadCell` IR before final triangle lowering. Physical span lengths balance the grid rather than assuming equal U/V units mean equal lengths. Nearly coincident grid lines are merged only within a small sampled fraction of the display budget. Each retained quad is split along a deterministic valid diagonal. Axis and triangle caps can limit cell proportions; this path is bounded to rectangular trims and does not turn arbitrary trim bounding boxes into filled surfaces.
+
+Dense nonrectangular spline trims reuse that knot-aware grid to decompose the actual outer-minus-holes region into local polygons. Existing constrained ear clipping triangulates each region before bounded chord/normal refinement. Only convex intersections of already validated seed triangles may use an anchor fan; general polygons never use an averaged centre. Periodic charts are normalized upstream, and display subdivision retains the original face and occurrence identity for picking. Quality limits remain explicit in display diagnostics. See [STEP-TRIM-TRIANGULATION-X4](../../release/STEP-TRIM-TRIANGULATION-X4.md) for the corpus and product evidence.
+
+Rational source supports may be evaluated and displayed. Production AP242 uses analytic or non-rational geometry, with bounded recovery on a copy of the imported BRep and independent trim validation. Ordinary imported parts can use an explicit recovery allowance of at most 0.1 mm; tighter source and application requirements still matter for small features. Recovery reports sampled deviation rather than claiming an exact mathematical error bound. Unsupported normalization fails explicitly. Display mesh quality never supplies export evidence.
Firmament `inlineSTEP` consumes Aetheris-canonical AP242 on the bounded production path. Imported faces are selected by source entity identity, for example `body.face(#170)`, and recognized regions may supply stable semantic aliases. [`inline-step-cantilever.firmament`](../../../fixtures/Canonical/FEA/inline-step-cantilever.firmament) demonstrates FEA on a checked-in canonical STEP resource.
diff --git a/docs/public/firmament/surface-inspection.md b/docs/public/firmament/surface-inspection.md
new file mode 100644
index 00000000..ddbcfe39
--- /dev/null
+++ b/docs/public/firmament/surface-inspection.md
@@ -0,0 +1,29 @@
+# Surface and trim inspection
+
+Choose a practical [viewport theme](viewport-themes.md) for inspection, or a presentation theme for sharing the same model.
+
+Cadmata and Helios expose **Surface / trim inspection** in the WebGPU viewport. It compares the displayed geometry with source BRep curves using the same camera, occurrence transforms and renderer. Orbit, pan and zoom work throughout inspection.
+
+Choose **Surfaces only** to see the filled mesh or field, **BRep wire only** to see source curves, **Translucent + wire** to expose curves through the surface, or **Face colours + wire** to distinguish adjacent source faces. Red lines are BRep edges, including trim boundaries where transported; they are not triangle edges. These views help distinguish filled holes, excess surface coverage, long facets and mismatched boundaries.
+
+Choose a face in **Isolated display face**, or click a surface while an inspection view is active. Isolation uses occurrence plus source face identity, so repeated parts remain distinguishable. Choose **All faces** to restore the complete model. Cadmata additionally shows the source STEP entity, support family and face boundary edges when available. Changing the view or isolated face preserves the camera; loading a new model resets isolation.
+
+Helios SDK packets currently carry source face ranges and occurrence edges without face-edge adjacency. Its isolated wire therefore shows all edges of that occurrence, and the control states this limitation. Cadmata's richer imported-face packet can restrict wire to the isolated face's boundary edges.
+
+Whole-model surface and translucent views retain the actual CIR/SDF field when active. A field shader has no per-face trim mask. Face colours and face isolation explicitly show its retained BRep mesh proxy, with a notice in Helios. Proxy pixels must not be mistaken for proof of the field's silhouette. Compare the whole field with the proxy to investigate a discrepancy.
+
+The reusable API is exported by `@aetheris/three-telos`:
+
+```ts
+import { inspectSurfaces, surfaceInspectionFaces } from "@aetheris/three-telos";
+
+const faces = surfaceInspectionFaces(sourceScene);
+host.setScene(inspectSurfaces(sourceScene, "overlay", faces[0]));
+// Use the same host/camera for the next comparison; do not call fit here.
+host.setScene(inspectSurfaces(sourceScene, "wire", faces[0]));
+host.setScene(inspectSurfaces(sourceScene, "normal"));
+```
+
+Projection keeps engineering authority in the source scene. Packed faces share the complete immutable geometry and GPU buffers; triangle draw ranges preserve original triangle indices for source selection. It never reconstructs BRep edges from tessellation or changes export geometry. Products own controls, source metadata and screenshots; Three Telos owns drawing, camera and picking.
+
+For reproducible corpus review, `scripts/inspect-step-legacy-cadmata.mts` captures five matched-camera views, face inventories and optional orbit/zoom/source-face click witnesses through real STEP upload. Outputs belong under ignored `artifacts/local/`. The canvas `data-surface-inspection` and `data-surface-inspection-pick` attributes expose the active projection and actual hit for automation. Contact sheets are review evidence, not engineering qualification or human signoff. See [X4 qualification](../../release/STEP-TRIM-TRIANGULATION-X4.md).
diff --git a/docs/public/firmament/viewport-themes.md b/docs/public/firmament/viewport-themes.md
new file mode 100644
index 00000000..85d5925f
--- /dev/null
+++ b/docs/public/firmament/viewport-themes.md
@@ -0,0 +1,26 @@
+# Telos viewport themes
+
+Use **THEME** in Cadmata's viewport toolbar. The choice is remembered locally; `?theme=aurora` (or another theme ID) also selects a theme when opening Cadmata. Switching themes keeps the current camera, geometry, source identities and inspection selection.
+
+| Theme | Treatment | Best use |
+|---|---|---|
+| Atelier | Graphite desk, neutral metal, balanced task lighting | General engineering work |
+| Monument | Warm paper, clay surfaces, soft gallery lighting | Form, architecture and light-background screenshots |
+| Blueprint | Cobalt drafting desk, porcelain blue surfaces, measured cyan grid | Topology and trim inspection |
+| Mars | Amber low sun, copper strata, oxidized metal | Dramatic warm presentation |
+| Sirius | Blue-white star, spectral halo, cold polished hardware | Cool hardware presentation |
+| Singularity | Off-centre accretion rings, black stage, ember rim | High-contrast presentation |
+| Aeons | Violet observatory, engraved gold arcs, antique metal | Quiet cosmic presentation |
+| Aurora | Mint curtains, violet fill, titanium highlights | Colourful presentation |
+
+All eight are static, on-demand WebGPU presentations. There is no continuous animation loop for decoration. Native standalone WGSL supplies one fullscreen backdrop pass; the existing Telos color/depth attachments still own the frame. Mesh lighting includes key/fill directions, hemisphere light, a roughness-dependent highlight, a coloured silhouette rim and tone mapping. It is an artistic lighting approximation, not an environment-map PBR renderer or a physical lighting simulation. Glow is drawn in the procedural background; no HDR bloom, shadow-map or fog postprocessing is claimed.
+
+Minor and major grid lines follow the product palette and retain physical world spacing. The grid is a reference overlay, not a new model boundary. **GRID** still toggles it; Singularity intentionally starts without it. Source BRep edges, selection accents, axes and annotation panels use their product theme colours. Imported standalone parts use the chosen display material; authored assembly material facts remain in the source packet. CIR/SDF fields retain their compiler-generated shading ABI and authored materials, while sharing the theme backdrop, grid and selection treatment. The new mesh lighting does not imply new field shader lighting support.
+
+Helios retains its Mars/Sirius product choices and now projects both into the same native Telos presentation API. The WebGL fallback retains its older, simpler presentation; the eight-look qualification is for WebGPU.
+
+For surface comparison, use [Surface and trim inspection](surface-inspection.md). Its wire and face-isolation modes remain available under every theme. Prefer Atelier, Monument or Blueprint when assessing small details; presentation themes intentionally use stronger colour contrast.
+
+Reusable configuration lives in `@aetheris/three-telos`: `host.setPresentation(TelosPresentation)`. Product adapters project palette and light settings into that contract. Backdrop/grid colours are display encoded, lighting colours are linear. `setPresentation` resets temporal history after an appearance change, retains geometry and camera, and requests an on-demand frame. Each backdrop shares one pipeline per attachment/sample configuration; changing palette does not generate shader programs.
+
+`scripts/qualify-viewport-themes.mts` records actual Cadmata uploads, matched-camera images, stable source-face clicks and bounded pipeline cycling. Supply the Playwright module, local McMaster directory, ignored output directory, host URL and specimen ID. Generated captures belong under `artifacts/local/viewport-themes/`.
diff --git a/docs/release/STEP-LEGACY-CLOSEOUT-X2.md b/docs/release/STEP-LEGACY-CLOSEOUT-X2.md
new file mode 100644
index 00000000..3194ce99
--- /dev/null
+++ b/docs/release/STEP-LEGACY-CLOSEOUT-X2.md
@@ -0,0 +1,73 @@
+# STEP-LEGACY-CLOSEOUT-X2
+
+Verdict: **Meaningful progression**, pending human visual review and four isolated spherical-shell orientation failures on AP242 reimport. This is not Preview 4 acceptance.
+
+Continuation: [STEP-LEGACY-FINAL-X3](STEP-LEGACY-FINAL-X3.md) repairs the four spherical reimports, adds actual viewport trim comparison, fixes cylindrical sector/chart overfill, and records the remaining suspicious/broken spline threads. The X2 measurements below remain historical evidence, not current visual acceptance.
+
+## Authority and tolerance
+
+BRep, its topology, bound geometry, trim evidence, and engineering recovery provenance own interchange correctness. Viewport triangles and Telos buffers are disposable projections. Engineering `Status`/`GeometryStatus` are independent of `DisplayStatus` (`NotAssessed`, `Complete`, `RefinementLimited`, `Partial`) and `DisplayReasons`. A good preview never promotes a degraded BRep.
+
+The user's ordinary-part recovery allowance is at most **0.1 mm**, using sampled evidence rather than exact rational mathematics. Production normalization operates on a copy of authoritative geometry and bindings, keeps topology and resolved orientation identities, and rederives pcurves when supports change. The base pcurve tolerance remains 0.001 mm; existing measured-recovery local allowances remain bounded by the separate engineering recovery budget. Display chord tolerance cannot enter this path.
+
+Rational input may be retained, evaluated, and displayed. Trusted production export requires admitted analytic/non-rational supports and pcurves; failed recovery produces `step-production-normalization-unsupported`. Compatibility/debug export remains a distinct legacy route. The Cadmata STEP export and CLI production metadata-preserving canonical route select the trusted policy. Production tests cover rejection without an explicit budget, copy preservation, independent pcurve validation, non-rational output, and topology roundtrip.
+
+## Display repairs
+
+The U-joint's final missing patch is source face **#12119**, root **7851**, imported face **67**, a degree-1/degree-3 spline support with a 2×18 net. Two distinct 3D edges (213 and 197) had recovered linear pcurves with coincident UV endpoints. Their lifted residuals were 0.000562/0.000366 mm, but their UV polygon collapsed. Projection of the authoritative edge samples onto the existing support exposes a finite narrow lens, with approximately 0.000212 mm residual.
+
+For collapsed loops composed entirely of recovered spline pcurves, the display sampler locally oversamples the actual bounded 3D edges and projects them onto the retained support. Source pcurves are never overridden. Engineering geometry, pcurves, and qualification remain unchanged. Face isolation now produces 60 triangles; the U-joint displays **209/209** faces and remains engineering Degraded for its separate reported trim/orientation findings. No missing face was capped or fabricated.
+
+High-knot rectangular spline supports use bounded anisotropic sampling seeded by native knots. Quarter/mid/three-quarter sag checks refine the direction that needs it, across the original opposite-axis knot spans. Negligible normal-only changes do not force excessive subdivision. Rectangle snapping requires measured insignificant trim noise. The grid retains the existing 65,536-triangle patch cap and falls back to the bounded conforming path when its initial grid cannot fit. Default viewport chord quality follows fitted model scale (including spline control nets), bounded between 0.01 and 0.25 mm; mesh export policy remains independent. This is static scale-aware preview quality, not a camera-dependent pixel guarantee.
+
+The spring improves from approximately **77,883 triangles with a refinement-limit warning** to **13,872 triangles**, **77.67 ms** materialization in the final sweep, complete with no display warning. The actual Cadmata capture shows separated helical turns and attached boundary lines. Before/after product captures are retained locally. Display improvements do not provide manufacturing evidence.
+
+Coarser automatic preview sampling exposed a planar mounted-bearing boundary sampling failure at source face #5836. A failed coarse planar sampling attempt retries the same authoritative curves once at the established default chord. The mounted bearing remains **349/349** displayed.
+
+## Exact pcurves and connector normalization
+
+Pcurve population now admits exact/non-recovery faces with missing coedge bindings. Valid source pcurves remain preferred, followed by exact analytic derivation and bounded recovery. Exact derivation has `DerivedAnalytic` provenance and does not claim recovered 3D geometry. Unsupported derivation stays explicitly unqualified. The pure analytic box retains its compact byte-exact canonical golden.
+
+The connector's original 0.007–0.009 mm reimport mismatch came from a full circle whose native trim interval was reconstructed from an approximate source seam vertex. Export with pcurve evidence now retains the declared circular interval. The source support reductions fit within their existing 0.0000254 mm target (measured errors about 0.00001879 and 0.00002383 mm). Its non-rational AP242 reimport is Qualified: **97 faces, 263 edges, 168 vertices** unchanged; **263** matched edges; worst sampled edge gap **0.00017728 mm**; bounds gap **1.36e-14 mm**. The base pcurve tolerance was not raised.
+
+Low-degree rational directions use bounded anisotropic continuation rather than refining both directions blindly. The control-net cap is 1,024 per axis and 8,192 total, with bounded span subdivision. This admits existing long, narrow vendor nets: the threaded screw's 2×657 support recovers with approximately **0.02358 mm** sampled deviation within 0.1 mm. It normalizes successfully with all **147 faces / 405 edges / 268 vertices** retained.
+
+## Final corpus and remaining engineering boundary
+
+The frozen vendor corpus remains unchanged: **26 files, 25 AP203 / 1 AP214, 58 roots, 5,552 parsed/bound/displayed faces, zero missing display faces**. Whole-file engineering status is **8 Qualified / 18 Degraded**. The stricter findings exposed by exact-face pcurve population are not hidden by display completeness: **473 missing coedge pcurves** remain in explicitly unqualified bodies. By root, **45 Complete / 13 RefinementLimited** display reports retain bounded warnings while covering every face.
+
+Of **31 engineering-qualified body normalization attempts, 27 pass and four fail**. Every successful candidate contains no rational B-spline STEP entities. All four failures are in the bearing (mcm-12), roots **1044, 4327, 4420, 4460**. Each retains 2 faces / 2 edges / 2 vertices, bounds and sampled edges agree within approximately 1.1e-13 mm, and reimported pcurves validate. Reimport nevertheless reports `unqualified-orientation: Shell 1: Ambiguous` / `step-orientation-shell-ambiguous`: the canonical resolver cannot establish a nonzero material-side signed-volume witness for this two-face spherical trim representation.
+
+These are orientation failures, not rational recovery failures or tolerance failures. Their reimported bodies remain Degraded and normalization results remain failed. No source `SAME_SENSE` value or screenshot is promoted to material-side authority. A minimal isolated reproduction is retained at `artifacts/local/step-closeout-x2/sphere-roundtrip/`; the exported bearing body is `final-current/mcm-12/normalized-1044.step`. The next engineering task is canonical spherical trim/orientation roundtrip qualification, with independent evidence for complementary hemisphere regions. Further tolerance relaxation would not address this failure.
+
+Normalization comparisons use topology counts, bounds, independent reimport qualification and 33 native-parameter samples per endpoint-matched edge. They do not constitute a universal surface-interior proof. Support recovery has its own sampled matched-parameter checks and explicit provenance; synthetic production regression checks additional interior samples independently.
+
+## Actual viewport and review
+
+The real current-source Cadmata frontend/server, using Edge WebGPU, passed upload, orbit redraw, selection and authoritative edge submission for bearing, U-joint, spring, connector, threaded screw, mounted bearing and collar. Submitted line counts are respectively **374 / 540 / 6 / 263 / 405 / 848 / 557**. Compound lines carry stable BRep edge and occurrence IDs with the same transforms as face buffers; cached geometry buffers are reused across occurrences and selection updates. Picking identity does not depend on triangle numbering. Existing PMI regression coverage remains separate; these vendor witnesses do not establish new PMI semantics.
+
+Thirty browser animation-frame intervals after orbit measured about 8.1 ms p95 on this machine. This is browser cadence evidence, not a GPU benchmark. Larger parts remain expensive: U-joint 736,959 triangles / 2.724 s; connector 169,834 / 1.110 s; screw 630,945 / 1.526 s; collar 1,214,561 / 3.908 s. Those costs are retained explicitly rather than claiming universal preview performance.
+
+Agent inspection found the spring and principal U-joint silhouettes coherent. Collar/thread detail remains a visual review focus; diagnostic double-sided flat shading can emphasize internal overlapping surfaces. Such observations are not human acceptance. Vendor reference images were not supplied or independently fetched. The final contact sheet was presented to the user with the required **Looks Correct / Suspicious / Broken** classification request. Human review remains pending; no classifications are fabricated. Actual topology captures also require visual alignment sign-off.
+
+## Evidence and reproduction
+
+Generated evidence is ignored under `artifacts/local/step-closeout-x2/`:
+
+- `final-current/corpus-summary.json`, per-specimen diagnostics, meshes, normalized STEP, two views per specimen and `contact-sheet.png`.
+- `comparison/` and `u-joint-final/`: isolated U-joint before/after, support/UV/edge/triangulation inputs.
+- `product-current/`: seven production viewport and orbit/selection captures with `product-summary.json`.
+- `spring-before-after.png`, `u-joint-before-after.png`, `connector-normalization.json`, `human-review.json` and `closeout-summary.json`.
+- CLI inspection JSON for connector, spring and U-joint.
+
+Reproduce the corpus with `scripts/qualify-step-legacy.ps1 -CorpusDirectory <local McMaster directory> -OutputDirectory artifacts/local/step-closeout-x2/final-current`; render via `scripts/render-step-legacy.py`. The Cadmata qualification script consumes the real upload UI against a foreground host; it installs no service. Raw vendor files are not redistributed. The tracked manifest preserves the X0 baseline.
+
+## Regression and cleanup
+
+Final Release solution build passed (10 existing warnings, zero errors). Fast kernel iteration passed **1,042** tests. The full serial solution gate passed **4,366 .NET tests, zero failures/skips**, including SlowCorpus, NIST, orientation, assembly, recovered-bolt and AP242 roundtrip coverage. Frontend typecheck/build passed; **87 frontend tests** and **12 Telos tests** passed with zero failures/skips. Actual Cadmata qualification passed **7/7** witnesses. Repository layout and whitespace checks passed.
+
+Three NIST canonical SHA entries were deliberately refreshed after pcurve serialization changed; topology counts, qualification and diagnostic snapshots were unchanged. The canonical box golden remains unchanged. Existing source evidence and earlier X0/X1 changes were preserved. Frozen legacy Zig was skipped because neither its compiler nor build/test infrastructure changed.
+
+Cleanup audited independent tolerance use, bounded allocation/refinement, rational export guards, BRep immutability, stable overlay identity and absence of specimen-specific dispatch. Public import documentation now states the authority split. The repository information-architecture guard and whitespace check passed. The full suite's generated ellipse production fixture is restored after validation. No background service, startup hook, commit, or raw vendor content is introduced.
+
+Acceptance remains withheld for the four precisely isolated orientation roundtrip failures and required human visual review.
diff --git a/docs/release/STEP-LEGACY-FINAL-X3.md b/docs/release/STEP-LEGACY-FINAL-X3.md
new file mode 100644
index 00000000..9324b157
--- /dev/null
+++ b/docs/release/STEP-LEGACY-FINAL-X3.md
@@ -0,0 +1,103 @@
+# STEP-LEGACY-FINAL-X3
+
+Verdict: **Meaningful progression. Corpus acceptance withheld.** The four ball reimports are repaired, the actual Cadmata viewport now supports matched-camera trim inspection, and the oversized gear sleeves have a bounded display fix. General trimmed spline threads still show poor triangulation. The rectangular quad path is implemented and demonstrated on the spring; it is not a general trimmed-surface remesher.
+
+## Ball reimports
+
+Isolated normalized bearing roots **1044, 4327, 4420, 4460** each retain two faces, two edges, and two vertices. The ambiguity was not harmless symmetry: an equatorial boundary centroid gives a nearly perpendicular radial support normal. Taking the sign of that rounding-level dot product could choose incompatible hemisphere orientations after serialization, collapse the displayed shell, and cancel signed volume.
+
+`Step242Importer.TryDeriveSupportAlignmentFromBoundaryNormal` now declines the sphere hint when the normalized dot product has magnitude at most `1e-8`. The existing winding, shared-edge adjacency, and signed-volume derivation resolve orientation. Source `SAME_SENSE` remains provenance, and no topology or engineering tolerance changes.
+
+All four original normalized files now reimport as **Qualified**, with complete valid pcurves and both hemisphere orientations aligned. Three synthetic translated-sphere tests verify three repeated export/reimport cycles, outward triangle winding, preserved counts, and positive near-analytic volume. Removing the guard made two tests fail; restoring it made all three pass. CLI JSON and before/after diagnostic captures are under `artifacts/local/step-final-x3/balls*`.
+
+## Surface and trim inspection
+
+The production Cadmata viewport has Normal, Surfaces only, BRep wire only, Translucent + BRep wire, and Face colors + BRep wire modes. Mode changes and face isolation preserve the camera. Each selectable patch carries occurrence identity, kernel face ID, STEP entity ID, support family, and boundary edge IDs. Red lines are actual kernel edge projections. Legacy STEP uses BRep mesh display; these specimens have no SDF field.
+
+`scripts/inspect-step-legacy-cadmata.mts` uploads the real files into the current server, captures all modes through Edge/WebGPU, verifies equal camera states, verifies mesh/edge visibility, and checks isolated faces retain exactly one mesh and their boundary curves. All 26 passed these diagnostic assertions without browser runtime errors. This is automated browser evidence plus Codex pixel review, not human signoff or a new orbit/selection qualification. The earlier all-26 product selection scan had six sparse-hit misses and one missing analytic-only edge overlay; those failures are retained in the earlier artifacts and are not reclassified as passes.
+
+The analytic-only route now exposes topology lines even without a mesh fallback. When a fallback exists, its denser authoritative edge samples are reused rather than replacing them with the coarse wire-patch samples. Geometry and selection authority remain in the existing kernel/Telos path.
+
+## Bounded gear repair
+
+On `mcm-04`, root **4926**, face **21 / STEP #5885** previously filled a cylindrical region outside its toothed boundary. Face **38 / STEP #1863** filled a complete cylinder although its five boundary edges enclose a narrow sector. The same sleeve defect appears in `mcm-05` through `mcm-07`.
+
+Complete single-loop cylinder pcurve polygons now use the existing trim materializer. Reused-seam/full-circle families retain their dedicated route. Neighboring cylinder/cone pcurves are translated by integral angular turns at each coedge join, preserving the authored sweep within each coedge. This repairs chart discontinuities without changing stored pcurves or forcing a full cylinder. The synthetic equivalent-chart sector test checks bounded positions and immutable bindings; the existing periodic closed-cylinder test remains green. Actual before/after isolated views show the spurious sleeves removed and surfaces following their trim wires.
+
+## Quad cells before triangles
+
+The existing `QuadCell` surface IR is reused by `SplineRectangleTessellator`. Native knot-aware chord refinement runs first. Physical span lengths then balance the grid, aiming at about 4:1 or better across most cells rather than treating arbitrary U/V units as equal physical distances. Nearly coincident grid lines are merged only when the parameter spacing is tiny and their sampled separation is at most one ten-thousandth of the display chord budget. Kernel knots remain unchanged.
+
+Cells are retained on `DisplayFaceMeshPatch.Cells` and are lowered only afterward through the same shorter-valid-diagonal helper used by SurfaceMeshIR. A stretched planar spline test checks cell proportions, complete area, and two triangles per retained quad. Axis/triangle budgets remain bounded. This applies to the existing dense rectangular spline route; general trim loops still require boundary-conforming clipping, and their bounding boxes are never treated as valid filled quads.
+
+The real spring has **12,000 retained quads**, **24,000 triangles** on its two spline faces, plus **44 planar end triangles**. Its sampled cell edge ratios are:
+
+| Face | Quads | Median | 95th percentile | Worst |
+|---|---:|---:|---:|---:|
+| 1 | 6,144 | 2.962 | 3.997 | 5.542 |
+| 2 | 5,856 | 2.548 | 4.119 | 6.762 |
+
+This is sampled display evidence, not an exact rational-surface error bound. It removes numerically vanishing grid rows and gives predictable interior cells without claiming every curved cell is square.
+
+## Review of all 26
+
+Review scope: current-source fitted surface/wire/overlay/face-color captures, with isolated gear and thread patches. **Visually correct** means no obvious mismatch in the reviewed views; it does not promote an engineering `Degraded` specimen. **Suspicious** means a local artifact remains unresolved. **Broken** means visible display damage remains. These are Codex assessments. Current result: **23 visually correct, 2 suspicious, 1 broken**.
+
+| ID | Part | Visual result | Evidence / remaining concern |
+|---|---|---|---|
+| mcm-01 | Bevel pinion | Visually correct | Tooth and bore outlines correspond in overlay. |
+| mcm-02 | Bevel gear | Visually correct | Flanks and hub correspond; some fitted-view faceting. |
+| mcm-03 | Taper-lock sprocket | Visually correct | Outer teeth, bore, and tapped opening correspond. |
+| mcm-04 | Long spur gear, no threads | Visually correct | Chart/sector repair removes sleeves; isolated #5885 and #1863 reviewed. |
+| mcm-05 | Spur gear, no threads | Visually correct | Oversized cylindrical tooth sleeves removed. |
+| mcm-06 | Spur gear | Visually correct | Repaired tooth sectors follow wires. |
+| mcm-07 | Spur gear | Visually correct | Repaired tooth sectors follow wires. |
+| mcm-08 | Internal gear, fusion | Visually correct | Ring and internal tooth contours correspond. |
+| mcm-09 | Internal gear | Visually correct | Ring and internal tooth contours correspond. |
+| mcm-10 | Two-piece shaft collar | Suspicious | Small chip-like patch beside exposed screw threads remains. |
+| mcm-11 | Steel worm | Suspicious | Isolated face 28 / #2647 retains long fan facets at refinement limit. |
+| mcm-12 | Ball bearing | Visually correct | Assembly capture corresponds; four ball reimports independently qualified. |
+| mcm-13 | Pawl | Visually correct | Perimeter, thickness, and hole correspond. |
+| mcm-14 | Ratchet gear | Visually correct | Teeth and bore correspond. |
+| mcm-15 | U-joint, no threads | Visually correct | Visible joint and ends correspond; engineering degradation remains. |
+| mcm-16 | Miter gear | Visually correct | Tooth flanks and bore correspond. |
+| mcm-17 | Signal-power connector | Visually correct | Tabs, stem, and tip correspond. |
+| mcm-18 | Mounted ball bearing | Visually correct | Housing, mounting holes, and bearing contours correspond. |
+| mcm-19 | Hex nut, no threads | Visually correct | Hex perimeter and bore correspond. |
+| mcm-20 | Threaded hex nut | Visually correct | Visible bore thread and perimeter correspond in fitted view. |
+| mcm-21 | Threaded hex screw | Broken | Flake-like triangular damage remains along shaft; faces 143–145 reach refinement limit. |
+| mcm-22 | Hex screw, no threads | Visually correct | Shaft, head, and marking correspond. |
+| mcm-23 | Lathe center point | Visually correct | Tip pattern and stepped shaft correspond. |
+| mcm-24 | Compression spring | Visually correct | Coil/ends correspond; retained quad cell metrics above. |
+| mcm-25 | Slotted spring pin | Visually correct | Slot and end chamfers correspond; analytic-only wire now present. |
+| mcm-26 | Clevis pin | Visually correct | Shaft/head and visible cross-hole correspond. |
+
+## Remaining blocker and acceptance boundary
+
+The next bounded problem is **quad interiors with correctly clipped boundary cells on nonrectangular spline trims**. Worm face **28 / #2647** has one loop with **13 coedges**, reaches the approximately 65k triangle budget (65,538 final triangles), and still has conspicuous fan facets. Screw face **143 / #10869** has one loop with **87 coedges**, finishes with 65,537 triangles and a `RefinementIncomplete` diagnostic; faces **144 / #3300** and **145 / #2345** have the same budget limitation. The corresponding isolated browser captures and sampled UV loops are retained. Raising the triangle cap or filling the UV rectangle would not establish correct trim materialization.
+
+No unconditional corpus or Preview 4 acceptance is granted. The sphere failure and cylinder chart/sector blocker are removed; irregular spline trim materialization is now isolated with source identities and actual pixel evidence. Engineering totals remain **8 Qualified / 18 Degraded**, **473 missing pcurves**, despite complete displayed face counts. Engineering rational recovery remains bounded at the user's **0.1 mm** allowance with sampled evidence; the base pcurve policy remains **0.001 mm**.
+
+## Validation and artifacts
+
+- Current solution build passed. Known WebAssembly SQLite calling-convention warnings remain.
+- Fast core lane: **1,047 passed**.
+- Full serial .NET lane: **4,371 passed, zero failures/skips** across 20 suites.
+- Frontend typecheck/build passed; **89 tests passed**.
+- A final test-only cleanup removed ignored tuple names and an unused local; its project build passed without warnings and all four cylinder materialization tests passed afterward. Production code is unchanged from the full gate.
+- Telos: **12 tests passed**.
+- Frozen Zig lanes skipped because no Zig compiler/build/test infrastructure changed.
+- Frozen corpus: **26 imports, 58 rigid roots, 5,552/5,552 faces displayed**; all hashes verified.
+- Qualified-root production normalization: **32 attempts, 32 passed**; engineering status is checked independently of display.
+
+All generated/vendor-bearing evidence stays ignored under `artifacts/local/step-final-x3/`:
+
+- `review-current/corpus-summary.json`: final import, display, and normalization evidence.
+- `inspection-current/`: all 26 matched-camera captures, source-face inventories, and seven reviewed contact sheets.
+- `isolation-cylinder/` and `isolation-current/`: before/after gear patch evidence.
+- `threads-current/`, `screw-isolation-current/`, `worm-face-2647/`, `screw-face-10869/`: isolated remaining blockers.
+- `balls/`, `balls-fixed/`: isolated roundtrip diagnostics, CLI evidence, and deterministic two-sided mesh captures; these captures are not GPU witnesses.
+- `quad-spring/cell-metrics.json`: retained quad metrics.
+- `final-build.log`, `final-fast.log`, `final-full.log`, frontend and Telos logs: final checks.
+
+Earlier failed iterations are retained separately, including the regression from widening the rectangle route and the interrupted test/build overlap. They do not supply final passing evidence. The widening was reverted and the final build/full gate completed afterward. Existing uncommitted milestone work is preserved; no commit, service, or external file change was made.
diff --git a/docs/release/STEP-LEGACY-IMPORT-X0.md b/docs/release/STEP-LEGACY-IMPORT-X0.md
new file mode 100644
index 00000000..97bf8d1f
--- /dev/null
+++ b/docs/release/STEP-LEGACY-IMPORT-X0.md
@@ -0,0 +1,92 @@
+# STEP-LEGACY-IMPORT-X0
+
+Verdict: **Meaningful progression; Preview 4 legacy STEP fidelity is not accepted.**
+
+The local user-provided McMaster corpus contains 26 specimens: 25 AP203 and one AP214. No vendor STEP data is redistributed. The tracked inventory is `testdata/step242/manifests/mcmaster-legacy-x0.json`; it records names, hashes, schemas, categories, and outcomes. All raw CAD and generated reports/captures stay local. Eleven sources use inches (`25.4 mm/unit`); fifteen use millimetres. Units are read from STEP rather than guessed from bounds. No AP242 control files were supplied; existing AP242/NIST tests provide regression coverage.
+
+The baseline imported every specimen before geometry/importer changes and generated isometric and opposite-isometric captures of the actual Aetheris display mesh. These diagnostic images are independent of the Cadmata product witness and do not substitute for human review. All source face entities bound, but 39 faces across five specimens produced no display triangles. Enclosed topology did not prevent visibly distorted spline materialization, including the compression spring.
+
+## Changes
+
+- Body-level qualification now records expected/bound faces, shell connected components, boundary/non-manifold edges, ordered loop closure, pcurve evidence, and explicit reasons. Parser/API success retains useful geometry; it does not imply qualification. Geometry and display assessment remain distinct.
+- CLI JSON exposes qualification and source schema. Cadmata STEP assembly/compound responses retain partial display geometry with per-definition qualification and source face identities, and the UI shows a compact status.
+- Partial tessellation no longer discards trim rejection warnings attached to successful empty patches. No geometry is added or repaired in the renderer.
+- Polynomial pcurve export preserves exact endpoints during line parameter remapping, avoiding an out-of-domain floating-point exception. Rational weights survive the same remap. The real pawl is an import/export/reimport witness with preserved topology and bounds and sampled edge deviation near `1e-12 mm`.
+
+## Recorded outcomes
+
+`Qualified` in the machine report means the implemented BRep and display-completeness checks passed. It is a candidate for normalization and visual review, **not** a completed fidelity or release acceptance claim. `Inspectable` retains useful geometry with incomplete evidence; `Degraded` records detected contradictions or missing display faces; `Failed` produces no usable imported body. Normalization failures and pending human review are recorded separately in the manifest. The single-body upload remains Inspectable until display assessment; the compound/assembly upload includes that assessment.
+
+| Metric | Baseline | Final |
+|---|---:|---:|
+| Files imported | 26 | 26 |
+| Source / bound faces | 5,552 / 5,552 | 5,552 / 5,552 |
+| Unbound source faces | 0 | 0 |
+| Displayed faces | 5,513 | 5,513 |
+| Missing display faces | 39 | 39 |
+| Structurally enclosed/manifold rigid roots | 58 | 58 |
+| Structurally open rigid roots | 0 | 0 |
+
+Final mechanical outcomes are **3 Qualified candidates, 14 Inspectable, 9 Degraded, 0 Failed**. No missing-face geometry repair is claimed. Baseline did not have the new structured qualification API, so the old harness's status labels are not treated as a before/after fidelity metric. Human visual review remains pending; the distorted spring is an observed machine-inspection failure, not a human-reviewed pass.
+
+The missing-display cluster is `mcm-05` (2), `mcm-10` (2), `mcm-12` (28), `mcm-15` (3), and `mcm-18` (4). Other degraded specimens have failed trim recovery/validation or unqualified orientation evidence despite nonempty display patches. The new report consumes the existing resolved face-orientation authority and does not reinterpret `SAME_SENSE`.
+
+| Repaired cluster | Before | Cause / change | After |
+|---|---|---|---|
+| Empty-patch diagnostics: gear, collar, U-joint, mounted bearing | A successful empty patch lost its trim warning; display completeness was not explicit | Preserve success diagnostics and project actual per-face display coverage | Source face IDs and missing-patch reasons survive; compound geometry is retained and visibly Degraded in Cadmata |
+| Pawl AP242 export (`mcm-13`) | Export threw a polynomial-pcurve domain exception | Affine endpoint arithmetic rounded one ULP beyond the domain; preserve exact mapped endpoints and rational weights | Export/reimport succeeds: 22 faces, 54 edges, bounds deviation `5.03e-15 mm`, sampled edge deviation `1.03e-12 mm` |
+
+The recurring sphere and spline geometry failures remain isolated in per-file JSON. They require support/trim materialization work beyond this verified exporter and qualification change. Broad tolerance increases, schema/vendor exceptions, and renderer face repairs were rejected as routes to acceptance.
+
+## AP242 normalization
+
+Six mechanically qualified body/display candidates were attempted; five passed the bounded counts/bounds/edge comparison. This is body-level evidence, not normalization of an entire degraded multibody product.
+
+| Source | Candidate bodies | Passed | Result |
+|---|---:|---:|---|
+| Pawl `mcm-13` | 1 | 1 | Whole specimen: preserved counts, bounds, and 54 sampled edges |
+| Connector `mcm-17` | 1 | 0 | AP242 reimport rejects four face-local pcurves; explicit failed candidate |
+| Threaded screw `mcm-21` | 1 | 1 | Whole specimen: 147 faces, 405 edges; bounds `4.00e-14 mm`, sampled edges `7.56e-11 mm` |
+| Collar `mcm-10` | 2 | 2 | Qualified sub-bodies only; whole specimen remains Degraded |
+| Mounted bearing `mcm-18` | 1 | 1 | Qualified sub-body only; whole specimen remains Degraded |
+
+Comparison budgets are `1e-5 mm` for bounds/vertex endpoint matching and `1e-3 mm` for 33 native-domain samples per matched edge. Samples compare both directions and consume matches bijectively. No serialization-ID, absolute-parameter, or rounded-coordinate equality assumption is used. Surface interiors, independent external CAD opening, and mass/volume equivalence were not qualified. The connector failure therefore prevents treating all three machine-Qualified specimens as normalized, fidelity-accepted examples.
+
+## Remaining failure classes
+
+| Class | Evidence / next work |
+|---|---|
+| Missing face-local pcurves | Numerous analytic/exact-spline vendor bodies never enter the existing recovery-only population branch. They remain Inspectable rather than being silently Qualified. |
+| Failed pcurve recovery / validation | Recovery diagnostics and measured lift/closure residuals remain Degraded. The base 0.001 mm pcurve and 0.1 mm geometry budgets are unchanged. |
+| Spherical trims | Ball bearing: 166 bound faces, 138 displayed. Explicit failures include two-loop sphere trims and degenerate elevation spans. |
+| Spline trim materialization | Gear, collar, U-joint, and mounted bearing contain empty patches; the detailed report retains loops, directed edges, vertices, and UV endpoints. |
+| Spline interior materialization | The spring's existing pcurve recovery validates its trims, but the resulting display remains distorted. Recovery alone is not a fix. |
+| Normalized source pcurve mismatch | The connector's AP242 reimport rejects four spline-support bindings with 0.007–0.009 mm lift error against a 0.001 mm allowance. This remains an explicit failed normalization witness. |
+
+The corpus contains multibody products, including the U-joint and bearings, but no `NEXT_ASSEMBLY_USAGE_OCCURRENCE` hierarchy. It cannot qualify external AP203/AP214 assembly transforms or definition sharing. Existing authored assembly regression fixtures cover that separate path. The sole AP214 specimen remains Inspectable; no qualified AP214 normalization claim is made.
+
+## Reproduction
+
+Run from the repository root with the .NET 10 SDK:
+
+```powershell
+pwsh -File scripts/qualify-step-legacy.ps1 -CorpusDirectory '<local McMaster directory>' -OutputDirectory artifacts/local/step-legacy-x0/final
+python scripts/render-step-legacy.py artifacts/local/step-legacy-x0/final
+```
+
+The runner checks manifest hashes, reports missing local specimens explicitly, contains each import/display/normalization in a separate process, and continues after a per-file timeout/failure. Normalization is attempted only for mechanically qualified body/display candidates. Its comparison matches edge endpoints and samples each curve in its own parameter domain; it does not assume serialized entity IDs or parameter origins survive. Surface interiors, independent external opening, and human visual review remain separate unqualified gates.
+
+Run data lives under ignored `artifacts/local/step-legacy-x0/`: `baseline/`, `final/`, `before-after/summary.md` and `.json`, `probes/`, `normalization-probes/`, and `product-final/`. Baseline and final each contain 52 two-angle specimen PNGs plus a contact sheet. Final product evidence contains real upload responses, WebGPU screenshots, orbit comparisons, and selection hits for the pawl, connector, threaded screw, U-joint, and spring. All five upload/orbit/selection checks passed with zero browser page errors. Representative screenshots are `product-final/mcm-13-product.png`, `product-final/mcm-15-product.png`, and `product-final/mcm-24-product.png`. Topology overlay and human review are explicitly unqualified. Helios was not changed or qualified in this repository-scoped task.
+
+To reproduce the product witness, build the frontend with `tspack run build --root .`, then build `Aetheris.Server -c Release -m:1` so its static frontend is current. Run its DLL in a foreground terminal with `--urls http://127.0.0.1:5087 --no-browser`, then invoke `node scripts/qualify-step-legacy-cadmata.mts <playwright-index.mjs> <local-corpus-directory> artifacts/local/step-legacy-x0/product`. The script uses local Edge and does not install/start a service.
+
+## Validation
+
+- Full Release solution build: passed, 0 errors (2 existing warnings). Final runner and product builds: passed, 0 warnings/errors.
+- Fast Core lane baseline: 1,017 passed. Focused qualification/export/empty-patch tests: 7 passed.
+- Required full serial solution lane: **4,347 passed, 0 failed, 0 skipped**, across 20 test assemblies, including NIST, orientation, assembly, and recovered McMaster bolt coverage. FrictionLab currently discovers no tests.
+- Frontend typecheck/build: passed; frontend suite: **86 passed**.
+- Repository content-location guard: passed. Missing-source runner check: all 26 explicitly reported `MissingLocalSpecimen`, without attempting import.
+- Corpus import latency on this machine: `0.21–9.68 s`, mean `2.43 s`; all workers completed within the 180 s containment budget. This is measured timing, not a performance guarantee.
+
+The executive answer is bounded: Aetheris now exposes degraded legacy imports and removes a demonstrated normalization exception, but the representative corpus still contains incomplete/distorted display geometry and a failed normalized pcurve family. Preview 4 legacy STEP acceptance remains blocked.
diff --git a/docs/release/STEP-SURFACE-MATERIALIZATION-X1.md b/docs/release/STEP-SURFACE-MATERIALIZATION-X1.md
new file mode 100644
index 00000000..5debe821
--- /dev/null
+++ b/docs/release/STEP-SURFACE-MATERIALIZATION-X1.md
@@ -0,0 +1,100 @@
+# STEP-SURFACE-MATERIALIZATION-X1
+
+Verdict: **Meaningful progression. Preview 4 legacy STEP fidelity is not accepted.**
+
+The frozen McMaster corpus reproduces the inherited 39-missing-face baseline. This pass restores 38 of those faces, including all 28 missing spherical bearing faces. The gear, collar and mounted bearing now display every bound face. One U-joint face still has a collapsed recovered UV trim. The spring has coherent coils in current Cadmata captures, but one rational spline patch exhausts adaptive refinement and remains Degraded. Exact-face pcurve population, connector remapping, topology overlay and human review remain open gates.
+
+## Scope and baseline
+
+The specimen set and SHA-256 values in `testdata/step242/manifests/mcmaster-legacy-x0.json` are unchanged: 26 local specimens, 25 AP203 and one AP214, 58 rigid roots, 5,552 source faces and 5,552 bound faces. No vendor CAD was committed. The existing X0 manifest outcomes remain a historical baseline rather than being overwritten with X1 claims.
+
+Before geometry edits, `artifacts/local/step-surface-x1/baseline-copy/` reproduced 5,513 displayed faces and 39 missing faces. All rigid roots remained structurally enclosed. There is no actual `NEXT_ASSEMBLY_USAGE_OCCURRENCE` hierarchy in this corpus; existing authored assembly tests qualify that separate path.
+
+## Materialization repairs
+
+Spherical faces previously used a rectangular longitude/elevation envelope. That discarded inner loops and rejected equatorial hemispheres because every boundary sample had the same elevation. The new bounded stereographic chart triangulates the directed outer boundary and its holes, then evaluates the exact sphere through the chart inverse. Directed vector area selects the chart interior; resolved canonical face orientation supplies material-side polarity. Explicit outer-bound metadata wins over loop order. Repeated pole samples collapse without inventing area; a true point boundary and a boundary crossing the excluded chart pole fail with named diagnostics. No bounding-box cap replaces a trim.
+
+The native sphere convention is documented on `SphereSurface`: U is azimuth around Axis, with period 2π; V is elevation in [-π/2, π/2]. X is the projected reference axis, Y=Axis×X, and poles are Center±Radius×Axis. Retained face-local pcurves are sampled through this same evaluator when present. Source `SAME_SENSE` remains provenance; downstream winding consumes the canonical orientation authority. The obsolete sphere-envelope resolvers and their duplicate parameter projection were removed.
+
+The spline trim path required at least three coedges even when two curved edges enclosed a finite region. It now validates the sampled polygon. Numerical display projection also reuses the existing qualified spline inverter: a sparse duplicate seed grid had selected the wrong branch on narrow native domains and long closed profiles. Native spline domains, degrees, knots and rational weights remain intact. The display projection budget is separate from pcurve qualification.
+
+Closed spline boundary projection now unwraps with the actual native period and origin. The spring's U=0/U=1 aliases had been connected across the whole support. Source pcurves remain preferred; even line pcurves retain a midpoint so a full native-period span is not mistaken for a seam jump.
+
+Rectangular free-form trims previously bypassed geometric refinement. When native knot spans require finer sampling than the established grid, they now use the shared boundary-conforming adaptive materializer. Ordinary low-complexity rectangles retain their established scaffold path. Native knot spans constrain refinement cells; subdivision still depends on chord/normal error. Refinement visits the region fairly and counts live triangles rather than discarded records. The options-derived work cap is bounded at 65,536 live triangles, below the existing maximum grid's triangle budget. Exhaustion emits `Viewer.Tessellation.RefinementIncomplete`; it never implies fidelity success. Display chord tolerance remains 0.05 mm and angular tolerance remains π/12. Geometrically checked removal of inversion noise is limited to one thousandth of the display chord allowance.
+
+Mounted-bearing source face #9760 exposed a separate recovered-edge display gate. Its 31.8 mm cylinder has three recovered boundaries departing radially by up to 0.0340962 mm. Recorded curve-recovery deviations are 0.0271561–0.0381652 mm, but display projection used a fixed 0.01 mm floor. Cylinder projection now admits a face-local allowance bounded by recorded deviation, the recovery budget and the current display chord budget. Exact edges retain the existing gate. Synthetic tests reject the same departure without provenance and when the display budget is only 0.02 mm. This changes display projection, not source geometry or pcurve qualification.
+
+## Face-level results
+
+| Specimen | Bound | Baseline displayed | Final displayed | Source faces restored |
+|---|---:|---:|---:|---|
+| mcm-05 gear | 210 | 208 | 210 | #8204, #6502 |
+| mcm-10 collar | 200 | 198 | 200 | #26224, #22518 |
+| mcm-12 bearing | 166 | 138 | 166 | All 28 spherical faces below |
+| mcm-15 U-joint | 209 | 206 | 208 | #8211, #4515; #12119 remains empty |
+| mcm-18 mounted bearing | 349 | 345 | 349 | #2996, #17004, #9668, #9760 |
+| Whole corpus | 5,552 | 5,513 | 5,551 | 38 restored; one still missing |
+
+The bearing hemisphere pairs are #3892/#5001, #3779/#444, #3346/#1654, #1639/#3888, #4722/#2379, #3951/#5071 and #758/#2790. The two-loop spherical faces are #3604, #3673, #1331, #3806, #1121, #697, #2069, #65, #373, #3148, #111, #3247, #5003 and #2284. Every one now has nonempty display geometry.
+
+Full 26-file sweeps were recorded after the sphere repair, spline trim repair and spline interior work, and again after cleanup and the recovered-cylinder repair. Missing counts progressed 39 → 11 → 4 → 2 → 1. No unrelated specimen lost display coverage.
+
+## Remaining blockers and qualification
+
+The U-joint's rigid root #7851, kernel face 67, source face #12119 is supported by a degree-(1,3), 2×18 spline. Its two recovered line pcurves collapse to a polygon with signed UV area approximately -2.71e-20. The materializer reports the four input samples, U=[6.19e-16,0.0010174085], V=[0.4968757963,0.4999999148], triangulation rejection and zero retained triangles. A feature-aware trim approximation is needed at the pcurve owner; adding triangles to this collapsed trim would fabricate area. The body remains Degraded.
+
+Spring source face #2370, kernel face 1, retains a rational degree-(3,3), 7×142 support with native U/V domains [0,1], closed U and nonuniform V knots. It still reaches the 65,536 live-triangle limit before all refinement criteria pass. The whole spring mesh has 77,883 triangles versus 924 at baseline. This is a substantial interior improvement, not a completed fidelity qualification. Its exact support, sampled boundaries, normalized trim and isolated triangulation are saved in `face-debug/spring-final/`. Further work should improve knot-span seeding and refinement conditioning rather than repeatedly increasing the cap. This is the bounded spline-interior stop for this pass.
+
+Machine qualification is deliberately independent of counts. Existing shell, pcurve and orientation reasons remain; newly exposed incomplete-refinement reasons can downgrade a previously silent candidate. Human visual review is pending for all 26 specimens. Complete display coverage does not establish manufacturing fidelity.
+
+## Pcurve population and normalization
+
+The importer still invokes population only when curve/support recovery provenance is present. This exact/non-recovery population gap was audited but not changed after the spline-interior stop. Existing explicit pcurves remain retained and preferred. The base pcurve allowance is still 0.001 mm; geometry recovery is still 0.1 mm, with existing measured local qualification allowances. No global budget was loosened.
+
+All currently mechanically qualified body/display candidates were retried through AP242 export/reimport. Pawl root #2 passes with 22 faces, 54 edges, bounds deviation 5.03e-15 mm and sampled edge deviation 1.02e-12 mm. Connector root #1060 **fails normalization**: spline-support faces 43, 44, 48 and 49 reject Circle3/Polyline pcurve lift residuals of 0.00864634, 0.00699945, 0.00699945 and 0.00864634 mm against 0.001 mm. The serialization/remapping cause was not repaired or newly root-caused in this pass. Interior equivalence across normalization is not claimed. X0's five passing body candidates remain historical evidence, not an X1 pass for candidates that no longer qualify under current display evidence.
+
+## Product and visual evidence
+
+Current-source Cadmata served its production frontend to local Edge WebGPU. Bearing, U-joint, spring, gear, collar, connector and the repaired mounted bearing all passed actual file upload, framing, orbit pixel change and selection-hit checks, with zero page errors. The final `product-current/` contains seven initial captures, seven orbit/selection captures, HTTP/UI evidence and `product-summary.json`; `product-direct/` retains the preceding six-case run. Rendering telemetry includes submitted empty patches; it is not the displayed-face metric. The corpus runner counts only patches containing triangles.
+
+The browser harness initially failed on the large U-joint/collar replies when relaying them as base64 through DevTools. Direct browser HTTP fixed that harness issue; no product geometry or renderer workaround was introduced. Each specimen now runs in its own browser lifecycle. The successful final product run used normal Edge settings, not the optional software-GPU diagnostic run.
+
+The standalone diagnostic renderer produced isometric/opposite-isometric captures for all 26 specimens and a contact sheet. Its two-sided shading aids inspection and is not product fidelity evidence. The actual Cadmata spring capture shows coherent coils; the retained refinement warning still blocks qualification. `contact-sheet/human-review.json` leaves every human decision pending with the requested choices: visually correct, suspicious or visibly broken. No vendor reference thumbnails were supplied. No human review is asserted.
+
+Topology overlay remains unqualified. STEP compound definitions currently project face patches through `AssemblyDisplayService`; their packet does not retain the kernel edge-polylines needed for this overlay. That contract projection requires a separate closeout. No renderer face caps, imported CIR conversion or triangle-derived substitute topology were added.
+
+## Reproduction and debug artifacts
+
+Run from the repository root:
+
+```powershell
+pwsh -File scripts/qualify-step-legacy.ps1 -CorpusDirectory '<local McMaster directory>' -OutputDirectory artifacts/local/step-surface-x1/final
+python scripts/render-step-legacy.py artifacts/local/step-surface-x1/final
+dotnet test-support/Aetheris.StepLegacyCorpus/bin/Release/net10.0/Aetheris.StepLegacyCorpus.dll '<specimen STEP path>' artifacts/local/step-surface-x1/face-debug/one-face --face-step <ADVANCED_FACE entity id>
+```
+
+`--face-step` isolates the selected face in the display mesh and dumps support geometry, native domains/knots/weights, resolved orientation, directed coedges, 3D edge samples, retained pcurves and samples, normalized spline UV triangulation input, output indices/positions and rejection diagnostics. Empty faces remain empty in the isolated output. The CLI compound analysis also records the bearing's real rigid-root structure without assigning assembly semantics.
+
+Local ignored evidence lives under `artifacts/local/step-surface-x1/`: `baseline-copy/`, `sphere/`, `spline-trim/`, `spline-interior/`, `pcurve/`, `normalization/`, `final/`, `face-debug/`, `contact-sheet/` and `product-direct/`. Exploratory stages are retained separately and are not final acceptance evidence. The corpus worker records import/materialization timing and retains its per-file 180-second containment budget.
+
+For product reproduction, build the frontend and `Aetheris.Server` using the established X0 commands, run the server DLL in a foreground terminal, then invoke:
+
+```powershell
+node scripts/qualify-step-legacy-cadmata.mts <playwright-index.mjs> <local-corpus-directory> artifacts/local/step-surface-x1/product-direct http://127.0.0.1:5087 mcm-12,mcm-15,mcm-24,mcm-05,mcm-10,mcm-17
+```
+
+## Validation and closeout
+
+Synthetic source tests cover hemisphere/cap boundaries through BRep coedges, spherical bands with holes, longitude seams, pole-touching trims, collapsed pole points, two-curved-edge spline lenses, non-unit native domains, repeated spline interior turning, native closed-spline periods, collapsed pcurve polygons, explicit refinement exhaustion and bounded recovered-cylinder projection. Existing NIST, orientation, assembly, recovered-bolt and authored AP242 lanes remain required.
+
+The final sweep imports all 26 hash-matched specimens: **2 Qualified machine candidates, 13 Inspectable, 11 Degraded, 0 Failed**. The histogram is not a fidelity promotion. Import time is 0.202–8.776 s, mean 2.698 s; complete worker time is 0.292–13.190 s, mean 4.320 s on this machine. Dense adaptive meshes remain a performance limit; this is not a broad optimization or timing guarantee.
+
+- Full Release solution build: passed, zero errors; existing compiler/platform warnings are retained in the log. Corpus runner build: passed.
+- Fast Core lane: 1,037 passed, zero failures/skips. Focused synthetic materialization lane: 14 passed.
+- Required full serial solution lane: **4,361 passed, zero failures/skips**, across 20 test assemblies, including NIST, canonical orientation, authored assemblies, recovered McMaster bolt and AP242 roundtrips. FrictionLab discovers no tests.
+- Focused NIST/materialization regression lane: 31 passed before the final recovered-cylinder change; the final full lane includes those tests again.
+- Frontend typecheck: passed. Frontend suite: 86 passed across 18 files.
+- Actual Cadmata product witnesses: seven upload/frame/orbit/selection passes, zero page errors.
+- Repository content-location guard and whitespace diff check: passed. No raw vendor geometry or generated meshes were staged. Frozen legacy Zig suites were skipped because no Zig compiler/build infrastructure changed.
+
+Preview 4 acceptance remains blocked by the named trim/interior/pcurve/normalization/overlay/human-review gates; this pass ends with verified materialization progress rather than a claim of universal legacy STEP support.
diff --git a/docs/release/STEP-TRIM-TRIANGULATION-X4.md b/docs/release/STEP-TRIM-TRIANGULATION-X4.md
new file mode 100644
index 00000000..6c81b56b
--- /dev/null
+++ b/docs/release/STEP-TRIM-TRIANGULATION-X4.md
@@ -0,0 +1,140 @@
+# STEP-TRIM-TRIANGULATION-X4
+
+Verdict: **Success — visual closeout accepted.** The broken screw and suspicious worm now have continuous local thread surfaces through the real Cadmata path. Codex reviewed all 26 matched-camera capture sets as Looks Correct. On 2026-10-07 the user reviewed all seven contact sheets and signed off all 26: “fantastic, everything looks good to me.” Engineering qualification remains independently 8 Qualified / 18 Degraded; visual acceptance does not promote degraded engineering imports.
+
+## Actual failure and reproduction
+
+The primary witness is `mcm-21`, `91280A546_Medium-Strength Class 8.8 Steel Hex Head Screw.STEP`, SHA-256 `e2770630a4bcd5e2d3623725a78105fe73466738b98f0a10e199489cb6acf088`. Rigid root 532 has 147 faces. Faces 143 / STEP #10869, 144 / #3300, and 145 / #2345 are nonrectangular spline thread supports.
+
+Before editing, the current worker reproduced face 143 and production Cadmata captured the screw, worm and collar. Face 143 has one loop, 87 coedges, 2,664 sampled UV points, U `[0, 0.923627822598334]`, V `[0.014645322186259978, 0.9925395615913511]`. Its concave region covers about 96.38% of its UV bounding rectangle. The support is degree 1 by 2, has 2 U and 329 V knot values, and is not marked closed in either direction. It winds many times physically; it is not an angular seam-crossing cylinder or an invalid centre-fan polygon.
+
+**Correction to the brief's premise:** the active path already used `PlanarPolygonTriangulator`, with the existing `EarCutTriangulator` as its bounded secondary strategy. There was no fan centre in this path. Ear-clipped diagonals crossed many native spline spans. Midpoint tests could alias repeated turning, and refinement using globally normalized UV edge lengths consumed the live-triangle cap before completing local quality. The visual result looked like a fan: flakes, long facets and incomplete thread regions. The original screw had 347,805 triangles; each of the three main spline faces reached approximately 65,536 triangles with fidelity warnings.
+
+Evidence is local under `artifacts/local/step-trim-x4/before/`: exact support, ordered pcurves, UV loops, triangle output, timings and actual GPU pixels. `screw-cli.json` records CLI ground-truth inspection. Vendor sources are neither copied into fixtures nor committed.
+
+## Bounded strategy
+
+The display classifier distinguishes rectangular grid-like, convex, concave, holes and pathological input. It is deterministic dispatch, not competing interpretation, so it does not require a JudgmentEngine policy. Non-simple input is still checked by the shared triangulator. Periodic chart normalization remains upstream and is not reinterpreted as engineering topology.
+
+Dense rectangular spline trims keep the X3 `QuadCell` path. `SplineRectangleTessellator.PlanGrid` now exposes its existing native-knot and physical-edge planning to nonrectangular spline trims. The rectangular algorithm and output remain unchanged.
+
+For a dense nonrectangular spline:
+
+1. Validate and triangulate the complete outer-minus-holes region with the existing utilities.
+2. Clip the original loops into bounded knot-aligned cells and triangulate the local regions with Earcut. Its area guard rejects incomplete local triangulation.
+3. If a clipped cell has awkward disconnected components or zero-width boundary bridges that the local utility declines, intersect the already validated global seed triangles with that cell. Only these convex intersections may use an anchor fan.
+4. Evaluate vertices on the original support and run the existing bounded chord, centre-sag and normal checks. Bisection remains conforming and does not invent a support centre.
+5. Join clipping roundoff at one billionth of a normalized display cell, retaining the first exact evaluated chart coordinate. Repeated vertex triangles are rejected. This affects disposable mesh adjacency only.
+
+The first experiment clipped every global seed triangle across every grid cell. It retained far too many internal diagonals and exceeded the screw's 30-second budget, displaying only 142/147 faces. That experiment was rejected and its sweep interrupted; its diagnostics remain local. Direct local-region triangulation removed this allocation/refinement explosion. The subsequent complete corpus sweeps recovered all 5,552 faces.
+
+No new polygon dependency was added. The existing Earcut port's upstream [ISC license](https://github.com/mapbox/earcut/blob/main/LICENSE) is now recorded in `THIRD_PARTY_NOTICES.md`. The planar triangulator remains the primary input validator.
+
+## Holes, seams, orientation and identity
+
+Inner bounds participate in each local outer-minus-holes region. Exceptional-cell fallback intersects valid seed triangles, so it cannot fill an excluded hole. Focused tests check concavity, a hole crossing several cells, winding, a many-turn support, a concave cylinder chart crossing 2π, classification and rejected self-crossed/collapsed input. Existing cylinder and closed-spline chart tests also remain in the gate.
+
+Cylinder/cone coedges retain authored angular sweeps with integral-turn chart translation at joins. Closed spline normalization uses the support's native period and origin. Subdivision may duplicate seam locations for display; it never merges authoritative seam pcurves or changes BRep incidence. This is bounded support for the existing chart families, not universal repair of arbitrary periodic surfaces.
+
+Generated triangles remain in one `DisplayFaceMeshPatch` with the original face ID. The existing canonical orientation projection is applied once by the owning display path. STEP source `SAME_SENSE` is not an orientation authority here. Cadmata click tests compare occurrence and BRep face identity, never triangle index, and exercise actual uploaded geometry.
+
+The optional SurfaceMeshIR lowerers no longer fall back to an average-3D-centre fan for arbitrary boundary polygons. They use planar/local-chart polygon triangulation or reject the optional route. Existing structured cone-apex and regular support primitives retain their constrained construction; they are not a general trim fallback.
+
+## The two suspicious parts
+
+`mcm-11` worm, root 4950, face 28 / STEP #2647: the long ear-clipped facets and visible gaps were display defects. Local knot decomposition produces continuous helical surfaces aligned with the boundary overlay. Actual Cadmata orbit, close zoom and source-face click succeed.
+
+`mcm-10` collar: face 72 / STEP #10166 on root 7849 is a spline thread surface, not an anonymous floating triangle. Outer cylinder face 37 / STEP #6094 has four loops: three inner bounds with 32, 4 and 33 coedges, plus the four-coedge outer bound. Its source boundaries explicitly describe the scalloped thread openings through the outer cylinder. An independent audit projects all 5,920 display triangle centres to that exact cylinder: zero centres lie in any of the three inner bounds, and all lie in the outer bound. This centroid audit is supporting evidence, not a proof about every complete triangle. Isolated solid and wire captures show the thread following those openings. Codex classifies the remaining chip-like appearance as source trim geometry rather than a detached tessellation flake. Human review should explicitly confirm this interpretation.
+
+## Corpus, performance and regression evidence
+
+All **26/26** files display all **5,552/5,552** bound faces. Engineering status remains **8 Qualified / 18 Degraded**; display improvements do not erase the existing 473 missing engineering pcurves. All **32/32** eligible rigid-root normalizations succeed with non-rational STEP, preserved topology counts and valid reimport pcurves. The four ball roots (1044, 4327, 4420, 4460) remain Qualified with zero orientation ambiguities and enclosed manifold incidence. The screw and connector normalization witnesses remain valid.
+
+The final diagnostic-only cleanup was checked against the prior capture geometry: all 26 `mesh.json` files are byte-identical. Final code was additionally exercised by fresh production Cadmata captures for the three motivating parts. Raw output remains under ignored `artifacts/local/step-trim-x4/`; no generated diagnostic dump is promoted into source control.
+
+| Part | Display ms before / after | Triangles before / after | Fidelity warnings before / after |
+|---|---:|---:|---:|
+| mcm-01 bevel pinion | 583 / 1,034 | 237,550 / 163,088 | 0 / 0 |
+| mcm-10 collar | 3,538 / 2,874 | 1,000,455 / 430,599 | 12 / 2 |
+| mcm-11 worm | 3,285 / 2,539 | 711,326 / 310,846 | 8 / 4 |
+| mcm-21 screw | 1,224 / 2,329 | 347,805 / 228,571 | 3 / 3 |
+| mcm-24 spring | 102 / 111 | 24,044 / 24,044 | 0 / 0 |
+
+These are recorded worker wall times, including concurrent qualification activity, not a controlled microbenchmark. The largest observed changes stay within a few seconds, not two orders of magnitude. The screw's three remaining warnings describe bounded knot-grid planning, not the old exhausted 65,536-triangle refinement on each principal thread face. Worm warnings remain on other bounded spline faces; principal face 28 has none.
+
+| Source face | Triangles | p95 / maximum 3D edge, mm | p95 longest/shortest edge ratio | Worst raw ratio |
+|---|---:|---:|---:|---:|
+| Screw 143 / #10869 | 26,248 | 1.457 / 1.702 | 19.32 | 2.29e9 |
+| Screw 144 / #3300 | 24,575 | 1.247 / 1.292 | 95.79 | 5.51e6 |
+| Screw 145 / #2345 | 26,554 | 1.448 / 1.580 | 19.20 | 2.30e9 |
+| Worm 28 / #2647 | 12,835 | 0.539 / 0.633 | 3.80 | 1.02e3 |
+| Collar 72 / #10166 | 12,333 | 0.173 / 0.218 | 3.98 | 1.40e9 |
+
+**Quality limit:** this is not a globally shape-optimal mesh and not every sliver is removed. Near-coincident trim/grid intersections still create tiny boundary edges with very large raw ratios; the thin screw crest also needs elongated cells. The repaired main surfaces no longer have the large whole-turn diagonals and missing strips visible before X4. Reported physical edge sizes, raw aspect outliers and explicit budget warnings are retained rather than calling all triangles well-shaped. No arbitrary sliver deletion changes the source trim.
+
+The spring remains 6,144 + 5,856 = **12,000 quads**, 24,000 spline triangles plus 44 end-face triangles, with no fidelity warning. Its grid, counts and sampled aspect statistics match X3. Gear sleeve repair and four ball roundtrips remain independent of the new path. All eligible normalized roots must preserve topology, valid pcurves and non-rational AP242 output. Engineering recovery remains bounded by the existing policy, at most 0.1 mm for the applicable ordinary imported parts; display quality never supplies export evidence.
+
+Spring quad edge-ratio median / p95 / worst is 2.962 / 3.997 / 5.542 on face 1 and 2.548 / 4.119 / 6.762 on face 2, unchanged from X3.
+
+The nine focused general-trim tests and all 18 NIST display cases pass (27/27 together). A late diagnostic-only attempt to warn whenever outer-minus-holes triangulation declined caused six NIST failures: established periodic charts intentionally use the existing native-grid mask. The warning was narrowed to abandonment of the new knot-local spline strategy; established periodic dispatch remains unchanged, and all 18 regressions pass without relaxing tests.
+
+Validation: the current serial full-solution gate passes **4,380 tests across 20 populated test projects, zero failures and zero skips**, recorded in `full-gated.log`. The FrictionLab test project currently discovers no tests. Fast core lane passes 1,056/1,056. Solution build passes with zero errors and two existing SQLite WASM warnings. Frontend typecheck and build pass; 89 tests across 19 files pass. Shared Telos has 14 passing tests, including packed-face source picking and explicit field/proxy projection. Helios has 29 passing tests, successful TypeScript/development build and one real WebGPU/WASM inspection browser test. Helios's ordinary production build explicitly stops because the installed local SDK is the development package; its existing AOT SDK distribution gate was not bypassed or qualified by this work. Frozen Zig was skipped because its compiler/build infrastructure did not change.
+
+## Supported Cadmata and Helios capability
+
+The inspection projection now lives in `@aetheris/three-telos`, exported as `inspectSurfaces`, `surfaceInspectionFaces`, `inspectionFaceKey` and typed mode/face contracts. Cadmata consumes it through a compatibility re-export, and Helios consumes the same implementation in its actual `Viewport`. Both expose human controls for normal, surfaces, BRep wire, translucent overlay, face colours and occurrence-aware isolation. Camera and original source selection survive switching views.
+
+Packed SDK meshes use triangle draw ranges sharing original GPU geometry; CPU picking keeps original triangle indices. Whole-model views show actual CIR/SDF fields. Isolated field faces and face colours explicitly use the retained BRep proxy. Helios labels that distinction and the absence of face-edge adjacency; its isolated wire shows occurrence edges. Cadmata's richer STEP metadata restricts wire to the isolated source face's edges.
+
+`helios-inspection/` records the actual Helios wrapper with compiled Firmament WASM, five rendered modes, six source faces, matching cameras and a real click resolving `Body:occurrence / face:2 / original triangle 2`. The persistent `HeliosCAD/tests/surface-inspection.spec.ts` verifies the product control and source selection. `product-formalized/` records fresh current production Cadmata upload/orbit/zoom/isolation/click evidence. The human guide is [Surface and trim inspection](../public/firmament/surface-inspection.md). Screenshot/corpus capture remains a TypeScript harness through real product controls, with deterministic output under ignored artifacts, not another renderer.
+
+## Visual review and exact human handoff
+
+The final all-part capture folder is `artifacts/local/step-trim-x4/inspection-cleanup/`. Seven `contact-sheet-N.png` files cover all 26 parts in surfaces, wire, translucent overlay and face-colour overlay. Each specimen also has five full-resolution PNGs and its camera/source-face inventory. Before/after images are `mcm-21-before-after.png`, `mcm-11-before-after.png`, and `mcm-10-before-after.png`. `product-formalized/` contains fresh current close, orbit, isolated and picked source-face captures for the three motivating parts.
+
+Codex's per-part review is recorded below and in `visual-review.json`.
+
+| Specimen | Part | Codex visual classification | Evidence note |
+|---|---|---|---|
+| mcm-01 | Metal Bevel Pinion | Looks Correct | Bore, hub and bevel teeth align with source boundaries. |
+| mcm-02 | Metal Bevel Gear | Looks Correct | Bevel tooth ring and stepped hub are continuous. |
+| mcm-03 | Steel Taper-Lock Bushing-Bore Sprocket | Looks Correct | Sprocket teeth, taper bore and bolt openings remain open. |
+| mcm-04 | NO THREADS_Metal Gear - 20 Degree Pressure Angle | Looks Correct | Sleeve and tooth tips follow source wire; no detached face. |
+| mcm-05 | NO THREADS_Metal Gear - 20 Degree Pressure Angle | Looks Correct | Stepped sleeve and tooth-root transitions remain joined. |
+| mcm-06 | Metal Gear - 20 Degree Pressure Angle | Looks Correct | Gear teeth and cylindrical hub follow the wire. |
+| mcm-07 | Metal Gear - 20 Degree Pressure Angle | Looks Correct | Hub, teeth and radial opening match the source curves. |
+| mcm-08 | Metal Internal Gear - 20 Degree Pressure Angle fusion | Looks Correct | Fusion internal gear has an open central bore and continuous ring. |
+| mcm-09 | Metal Internal Gear - 20 Degree Pressure Angle | Looks Correct | Legacy internal gear has consistent internal teeth and open centre. |
+| mcm-10 | Clamping Two-Piece Shaft Collar | Looks Correct | Thread breakthrough matches source inner bounds; isolated cylinder/thread audit supports source geometry. Human collar confirmation required. |
+| mcm-11 | Steel Worm | Looks Correct | Repaired helix is continuous; long facets and missing strips are removed. |
+| mcm-12 | Steel Ball Bearing | Looks Correct | Bearing races and spherical ball silhouettes remain plausible; four ball roundtrips independently valid. |
+| mcm-13 | Pawl for 6 mm Wide Face Metal Ratcheting Gear | Looks Correct | Pawl outline and pivot hole match the trim wire. |
+| mcm-14 | Metal Ratchet Gear | Looks Correct | Ratchet teeth and bore remain continuous and open. |
+| mcm-15 | NO THREADS_Single U-Joint | Looks Correct | U-joint ends, yokes and pivots align with source curves. |
+| mcm-16 | Metal Miter Gear | Looks Correct | Miter teeth, hub and bore remain coherent. |
+| mcm-17 | Compact Push-In Signal-Power Connector | Looks Correct | Connector lance and contact details align with source wire. |
+| mcm-18 | Mounted Steel Ball Bearing with Cast Iron Housing | Looks Correct | Housing mounting holes and bearing races remain open and coherent. |
+| mcm-19 | NO THREADS_Zinc-Plated Steel Hex Nut | Looks Correct | Unthreaded nut bore and hex flats match source geometry. |
+| mcm-20 | Zinc-Plated Steel Hex Nut | Looks Correct | Internal nut helix and bore remain visible. |
+| mcm-21 | Medium-Strength Class 8.8 Steel Hex Head Screw | Looks Correct | Repaired screw helix is continuous; no detached flakes in orbit/close/isolation views. |
+| mcm-22 | NO THREADS_Medium-Strength Class 8.8 Steel Hex Head Screw | Looks Correct | Unthreaded screw shaft and maker-mark head remain coherent. |
+| mcm-23 | Interchangeable Point Lathe Center Point | Looks Correct | Lathe centre tip facets and shaft shoulder follow source topology. |
+| mcm-24 | Compression Spring | Looks Correct | Spring coils and ends remain continuous; 12000-quad grid is unchanged. |
+| mcm-25 | 1050-1095 Spring Steel Slotted Spring Pin | Looks Correct | Spring pin slot and open bore remain intact. |
+| mcm-26 | Carbon Steel Clevis Pin | Looks Correct | Clevis pin head, shaft and cross hole remain coherent. |
+
+**Human review completed on 2026-10-07:** the user reviewed the seven contact sheets showing all 26 models and accepted every model. The original review checklist below is retained for reproduction:
+
+- Review all seven sheets; assign each specimen Looks Correct / Suspicious / Broken and record reviewer/date.
+- Open the full-size screw and worm before/after and close views. Confirm continuous helix, no detached flakes, no filled trim region or large boundary crossing.
+- Check collar cylinder #6094 and thread #10166 in the isolated views; confirm the source scalloped openings explain the exposed thread rather than accepting an unexplained chip.
+- Confirm gear sleeves, spring coils/end trims, ball-bearing shapes, connector detail and visible holes remain plausible against the wire.
+- Record any objection with specimen, occurrence, face/STEP entity and capture name. A Broken qualified specimen blocks acceptance.
+
+The human visual gate is now closed. X4 visual closeout is **Accepted** with the mesh-quality limits above documented. Machine geometry/normalization qualification remains separately reported.
+
+## Reproduction
+
+Build the solution with `dotnet build Aetheris.slnx -c Release -m:1`. Run `scripts/qualify-step-legacy.ps1 -CorpusDirectory <local-McMaster-folder> -OutputDirectory artifacts/local/step-trim-x4/final-gated -NoBuild`.
+
+For the actual product captures, run the current server DLL in the foreground on port 5087 with `--no-browser`, then invoke `scripts/inspect-step-legacy-cadmata.mts` with the Playwright module, corpus directory, ignored output directory, host URL, comma-separated specimen IDs and optional source STEP face IDs. Supply empty probe points and `product` as the final argument for orbit/zoom/click witnesses. The script installs no service. Stop the host after capturing.
diff --git a/scripts/inspect-step-legacy-cadmata.mts b/scripts/inspect-step-legacy-cadmata.mts
new file mode 100644
index 00000000..7e07cd73
--- /dev/null
+++ b/scripts/inspect-step-legacy-cadmata.mts
@@ -0,0 +1,102 @@
+import assert from "node:assert/strict";
+import { readFile, writeFile, mkdir } from "node:fs/promises";
+import { resolve, join } from "node:path";
+import { pathToFileURL } from "node:url";
+
+// Matched-camera diagnostic captures through the actual production upload/viewer.
+// Start a foreground Cadmata host separately; this script installs no service.
+const [playwrightPath, corpus, output, address = "http://127.0.0.1:5087", ids = "mcm-04", faceSteps = "", probePoints = "", productWitness = ""] = process.argv.slice(2);
+assert(playwrightPath && corpus && output, "Usage: node inspect-step-legacy-cadmata.mts <playwright-index.mjs> <corpus> <output> [host] [ids] [isolated-STEP-ids]");
+const { chromium } = await import(pathToFileURL(resolve(playwrightPath)).href);
+const manifest = JSON.parse(await readFile("testdata/step242/manifests/mcmaster-legacy-x0.json", "utf8"));
+await mkdir(output, { recursive: true });
+for (const id of ids.split(",")) {
+ const browser = await chromium.launch({ executablePath: "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true, args: ["--js-flags=--max-old-space-size=8192"] });
+ try {
+ const specimen = manifest.specimens.find((s: { id: string }) => s.id === id);
+ assert(specimen, id);
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1050 } });
+ const errors: string[] = []; page.on("pageerror", (error: Error) => errors.push(String(error)));
+ await page.goto(address);
+ await page.locator('input[type="file"]').setInputFiles(join(corpus, specimen.filename));
+ const response = page.waitForResponse((r: any) => r.url().endsWith("/import/step"), { timeout: 120000 });
+ await page.getByRole("button", { name: "Import STEP 242", exact: true }).click();
+ assert((await response).ok(), "Real STEP upload must succeed");
+ await page.waitForFunction(() => {
+ const state = JSON.parse(document.querySelector("canvas")?.getAttribute("data-telos-display") ?? "{}");
+ return state.meshSurfaces > 0 || state.fields > 0;
+ }, undefined, { timeout: 120000 });
+ await page.getByText("Surface / trim inspection", { exact: true }).click();
+ const canvas = page.getByLabel("Engineering WebGPU viewport");
+ const faces = await page.getByLabel("Isolated display face").locator("option").evaluateAll((options: any[]) =>
+ options.slice(1).map(o => ({ key: o.value, label: o.textContent })));
+ const captures: any[] = [];
+ async function capture(mode: string, suffix = mode, matched = true) {
+ await page.getByLabel("Surface inspection view").selectOption(mode);
+ await page.waitForFunction((mode: string) => JSON.parse(document.querySelector("canvas")?.getAttribute("data-surface-inspection") ?? "{}").mode === mode, mode);
+ await page.evaluate(async () => { await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame); });
+ const state = JSON.parse(await canvas.getAttribute("data-surface-inspection") ?? "{}");
+ if (matched && captures.length) assert.deepEqual(state.camera, captures[0].camera, "Inspection must preserve the camera");
+ assert(mode !== "wire" || state.visibleMeshes === 0, "Wire-only must hide filled patches");
+ assert(mode !== "surfaces" || state.visibleEdges === 0, "Surfaces-only must hide BRep curves");
+ await canvas.screenshot({ path: join(output, `${id}-${suffix}.png`) });
+ captures.push({ ...state, image: `${id}-${suffix}.png` });
+ }
+ for (const mode of ["normal", "surfaces", "wire", "overlay", "patches"]) await capture(mode);
+ for (const point of probePoints.split(",").filter(Boolean)) {
+ await page.getByLabel("Isolated display face").selectOption("");
+ await page.getByLabel("Surface inspection view").selectOption("surfaces");
+ const [x, y] = point.split(":").map(Number);
+ const box = await canvas.boundingBox(); assert(box);
+ await canvas.click({ position: { x: x * box.width, y: y * box.height } });
+ await page.evaluate(async () => { await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame); });
+ await capture("overlay", `probe-${point.replace(":", "-")}`);
+ }
+ for (const step of faceSteps.split(",").filter(Boolean)) {
+ const face = faces.find((f: any) => f.label.includes(`STEP #${step} /`));
+ if (!face) continue;
+ await page.getByLabel("Isolated display face").selectOption(face.key);
+ await capture("overlay", `face-${step}`);
+ assert.equal(captures.at(-1).visibleMeshes, 1, "Isolation must retain exactly one occurrence/face");
+ assert(captures.at(-1).visibleEdges > 0, "Isolated source face must expose its boundary curves");
+ }
+ const interactions: any[] = [];
+ if (productWitness === "product") {
+ await page.getByLabel("Isolated display face").selectOption("");
+ const box = await canvas.boundingBox(); assert(box);
+ const before = await canvas.screenshot();
+ await page.mouse.move(box.x + box.width * .65, box.y + box.height * .4);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * .65 + 90, box.y + box.height * .4 + 35, { steps: 12 });
+ await page.mouse.up();
+ await capture("surfaces", "orbit", false);
+ assert(!before.equals(await canvas.screenshot()), "Orbit must change real pixels");
+ await page.mouse.wheel(0, -600);
+ await capture("overlay", "close-overlay", false);
+ assert(captures.at(-1).camera.span < captures[0].camera.span, "Close zoom must reduce fitted span");
+ for (const step of faceSteps.split(",").filter(Boolean)) {
+ const face = faces.find((f: any) => f.label.includes(`STEP #${step} /`));
+ if (!face) continue;
+ await page.getByLabel("Isolated display face").selectOption(face.key);
+ await capture("surfaces", `close-face-${step}`, false);
+ const expected = JSON.parse(face.key);
+ let picked: any = null;
+ // A bounded scan through the actual canvas picker. A preselected dropdown
+ // is not evidence of a click; inspect the hit emitted by the click handler.
+ scan: for (let y = .25; y <= .75; y += .05) for (let x = .2; x <= .8; x += .05) {
+ await canvas.click({ position: { x: box.width * x, y: box.height * y } });
+ picked = JSON.parse(await canvas.getAttribute("data-surface-inspection-pick") ?? "null");
+ if (picked?.faceId === expected[1] && picked?.occurrenceId === expected[0]) break scan;
+ }
+ assert(picked?.faceId === expected[1] && picked?.occurrenceId === expected[0], `Click must retain ${face.label}`);
+ interactions.push({ step, expectedFace: face, picked });
+ await capture("overlay", `selected-face-${step}`, false);
+ }
+ }
+ assert.deepEqual(errors, [], "Browser must have no runtime errors");
+ await writeFile(join(output, `${id}-inspection.json`), JSON.stringify({ id, filename: specimen.filename,
+ path: "production Cadmata / Edge WebGPU / real upload", faces, captures, interactions, errors }, null, 2));
+ console.log(id, "matched camera", captures.length, "views", faces.length, "source faces");
+ } finally { await browser.close(); }
+}
diff --git a/scripts/qualify-step-legacy-cadmata.mts b/scripts/qualify-step-legacy-cadmata.mts
new file mode 100644
index 00000000..f82ae0de
--- /dev/null
+++ b/scripts/qualify-step-legacy-cadmata.mts
@@ -0,0 +1,104 @@
+import assert from "node:assert/strict";
+import { readFile, writeFile, mkdir } from "node:fs/promises";
+import { resolve, join } from "node:path";
+import { pathToFileURL } from "node:url";
+
+// Invoke against a foreground, current-source Cadmata host. No host/service is
+// installed or started by this script. CAD files enter through the real upload UI.
+const [playwrightPath, corpus, output, address = "http://127.0.0.1:5087", witnessIds = "mcm-13,mcm-17,mcm-21,mcm-15,mcm-24"] = process.argv.slice(2);
+assert(playwrightPath && corpus && output, "Usage: node scripts/qualify-step-legacy-cadmata.mts <playwright-index.mjs> <corpus-directory> <output-directory> [host-url]");
+const { chromium } = await import(pathToFileURL(resolve(playwrightPath)).href);
+const manifest = JSON.parse(await readFile("testdata/step242/manifests/mcmaster-legacy-x0.json", "utf8"));
+await mkdir(output, { recursive: true });
+const reports: unknown[] = [];
+ for (const id of witnessIds.split(",")) {
+ const browser = await chromium.launch({ executablePath: "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", headless: true,
+ args: ["--js-flags=--max-old-space-size=8192", ...(process.env.CADMATA_WITNESS_SOFTWARE_GPU === "1"
+ ? ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--enable-unsafe-webgpu"] : [])] });
+ try {
+ const specimen = manifest.specimens.find((s: { id: string }) => s.id === id);
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1050 } });
+ page.setDefaultTimeout(45000);
+ const errors: string[] = [];
+ // Let the browser receive large STEP replies directly over HTTP. Relaying them
+ // through Fetch.fulfillRequest base64 can exceed the DevTools transport limit.
+ // Record HTTP success and the status/display evidence consumed by the real UI.
+ page.on("pageerror", (e: Error) => errors.push(String(e)));
+ const report: Record<string, unknown> = { id, filename: specimen.filename, path: "current-source production Cadmata frontend / Edge WebGPU", humanReview: "not-performed" };
+ try {
+ await page.goto(address);
+ await page.locator('input[type="file"]').setInputFiles(join(corpus, specimen.filename));
+ const responsePromise = page.waitForResponse((response: { url(): string }) => response.url().endsWith("/import/step"), { timeout: 120000 });
+ await page.getByRole("button", { name: "Import STEP 242", exact: true }).click();
+ const response = await responsePromise;
+ report.uploadHttpStatus = response.status();
+ assert(response.ok(), "Actual browser upload must succeed over HTTP");
+ await page.waitForFunction(() => document.querySelector(".import-status-box")?.textContent?.includes(":"), undefined, { timeout: 120000 });
+ await page.waitForFunction(() => {
+ const canvas = document.querySelector("canvas");
+ const display = JSON.parse(canvas?.getAttribute("data-telos-display") ?? "{}");
+ return display.meshSurfaces > 0 || display.fields > 0;
+ }, undefined, { timeout: 120000 });
+ const canvas = page.getByLabel("Engineering WebGPU viewport");
+ const box = await canvas.boundingBox();
+ assert(box, "Viewport must be framed");
+ report.visibleStatus = await page.locator(".import-status-box").innerText();
+ report.importStatus = String(report.visibleStatus).match(/\b(Qualified|Inspectable|Degraded|Failed):/)?.[1];
+ report.display = JSON.parse(await canvas.getAttribute("data-telos-display") ?? "{}");
+ await writeFile(join(output, id + "-import.json"), JSON.stringify({
+ uploadHttpStatus: report.uploadHttpStatus, visibleStatus: report.visibleStatus, display: report.display,
+ responsePath: "direct browser HTTP; UI consumed actual server reply; full BRep evidence is in corpus diagnostics",
+ }, null, 2));
+ await page.screenshot({ path: join(output, id + "-product.png") });
+ const before = await canvas.screenshot();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2 + 80, box.y + box.height / 2 + 25, { steps: 12 });
+ await page.mouse.up();
+ await page.waitForTimeout(200);
+ report.orbitChangedPixels = !before.equals(await canvas.screenshot());
+ assert(report.orbitChangedPixels, "Orbit must redraw imported geometry");
+ report.frameCadence = await page.evaluate(async () => {
+ const intervals: number[] = [];
+ let previous = await new Promise<number>(resolve => requestAnimationFrame(resolve));
+ for (let i = 0; i < 30; i++) {
+ const next = await new Promise<number>(resolve => requestAnimationFrame(resolve));
+ intervals.push(next - previous); previous = next;
+ }
+ intervals.sort((a, b) => a - b);
+ return { samples: intervals.length, medianMilliseconds: intervals[15], p95Milliseconds: intervals[28],
+ basis: "browser requestAnimationFrame cadence after orbit; not a GPU benchmark" };
+ });
+ const pickResponses: unknown[] = [];
+ page.on("response", async (response: { url(): string; json(): Promise<unknown> }) => {
+ if (response.url().endsWith("/pick")) pickResponses.push(await response.json());
+ });
+ for (const [x, y] of [[.5, .5], [.4, .5], [.6, .5], [.5, .4], [.5, .6]]) {
+ await canvas.click({ position: { x: box.width * x, y: box.height * y } });
+ await page.waitForTimeout(300);
+ if (await page.locator('[aria-label="Assembly product tree"] .active-row').count() > 0
+ || pickResponses.some((r: any) => r.data?.hits?.length > 0)) break;
+ }
+ await page.screenshot({ path: join(output, id + "-orbit-selection.png") });
+ report.selectionHitVerified = await page.locator('[aria-label="Assembly product tree"] .active-row').count() > 0
+ || pickResponses.some((r: any) => r.data?.hits?.length > 0);
+ assert(report.selectionHitVerified, "Selection must hit imported geometry");
+ report.pickResponses = pickResponses;
+ report.topologyOverlay = Number((report.display as { topologyLines?: number }).topologyLines) > 0
+ ? "kernel-edge-lines-submitted; visual human review pending" : "missing";
+ assert.notEqual(report.topologyOverlay, "missing", "Imported topology edges must reach the actual Telos display host");
+ if (id === "mcm-15") assert.equal(report.importStatus, "Degraded", "Incomplete U-joint must be visibly degraded");
+ report.success = true;
+ } catch (e) {
+ report.success = false;
+ report.failure = String(e);
+ report.visibleText = await page.locator("body").innerText().then((text: string) => text.slice(-4000)).catch(() => "page unavailable");
+ await page.screenshot({ path: join(output, id + "-failure.png") }).catch(() => undefined);
+ }
+ report.pageErrors = errors;
+ reports.push(report);
+ await writeFile(join(output, "product-summary.json"), JSON.stringify(reports, null, 2));
+ console.log(id, report.success, report.importStatus, report.failure ?? "");
+ await page.close().catch(() => undefined);
+ } finally { await browser.close().catch(() => undefined); }
+ }
diff --git a/scripts/qualify-step-legacy.ps1 b/scripts/qualify-step-legacy.ps1
new file mode 100644
index 00000000..9c9a310c
--- /dev/null
+++ b/scripts/qualify-step-legacy.ps1
@@ -0,0 +1,59 @@
+param(
+ [Parameter(Mandatory = $true)][string]$CorpusDirectory,
+ [string]$OutputDirectory = 'artifacts/local/step-legacy-x0/baseline',
+ [string]$Manifest = 'testdata/step242/manifests/mcmaster-legacy-x0.json',
+ [ValidateRange(1, 2147483)][int]$TimeoutSeconds = 180,
+ [switch]$NoBuild
+)
+$ErrorActionPreference = 'Stop'
+$repo = Split-Path $PSScriptRoot -Parent
+$project = Join-Path $repo 'test-support/Aetheris.StepLegacyCorpus'
+if (-not $NoBuild) {
+ & dotnet build $project -c Release -m:1
+ if ($LASTEXITCODE -ne 0) { throw 'Corpus runner build failed.' }
+}
+$runner = Join-Path $project 'bin/Release/net10.0/Aetheris.StepLegacyCorpus.dll'
+$out = [IO.Path]::GetFullPath($(if ([IO.Path]::IsPathRooted($OutputDirectory)) { $OutputDirectory } else { Join-Path $repo $OutputDirectory }))
+[IO.Directory]::CreateDirectory($out) | Out-Null
+$manifestPath = if ([IO.Path]::IsPathRooted($Manifest)) { $Manifest } else { Join-Path $repo $Manifest }
+$specimens = (Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json).specimens
+$results = @()
+foreach ($specimen in $specimens) {
+ $path = Join-Path $CorpusDirectory $specimen.filename
+ $destination = Join-Path $out $specimen.id
+ [IO.Directory]::CreateDirectory($destination) | Out-Null
+ if (-not (Test-Path -LiteralPath $path)) {
+ $results += [pscustomobject]@{ SpecimenId = $specimen.id; Filename = $specimen.filename; ImportStatus = 'MissingLocalSpecimen' }
+ continue
+ }
+ $hash = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
+ if ($hash -ne $specimen.sha256) {
+ $results += [pscustomobject]@{ SpecimenId = $specimen.id; Filename = $specimen.filename; ImportStatus = 'HashMismatch'; ActualSha256 = $hash }
+ continue
+ }
+ $start = [Diagnostics.ProcessStartInfo]::new('dotnet')
+ $start.UseShellExecute = $false
+ $start.CreateNoWindow = $true
+ $start.ArgumentList.Add($runner)
+ $start.ArgumentList.Add($path)
+ $start.ArgumentList.Add($destination)
+ $process = [Diagnostics.Process]::Start($start)
+ if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
+ $process.Kill($true)
+ $process.WaitForExit()
+ $results += [pscustomobject]@{ SpecimenId = $specimen.id; Filename = $specimen.filename; ImportStatus = 'Failed'; Failure = "Timeout after $TimeoutSeconds seconds" }
+ } elseif ($process.ExitCode -ne 0 -or -not (Test-Path (Join-Path $destination 'diagnostics.json'))) {
+ $results += [pscustomobject]@{ SpecimenId = $specimen.id; Filename = $specimen.filename; ImportStatus = 'Failed'; Failure = "Worker exit $($process.ExitCode)" }
+ } else {
+ $result = Get-Content (Join-Path $destination 'diagnostics.json') -Raw | ConvertFrom-Json
+ $result | Add-Member SpecimenId $specimen.id
+ $results += $result
+ }
+ $process.Dispose()
+ # Preserve each completed specimen even if the caller interrupts the sweep.
+ $results | ConvertTo-Json -Depth 80 | Set-Content (Join-Path $out 'corpus-summary.json') -Encoding utf8
+}
+$results | ConvertTo-Json -Depth 80 | Set-Content (Join-Path $out 'corpus-summary.json') -Encoding utf8
+$table = @('# STEP legacy corpus', '', '| Specimen | Schema | Import status | Bound / parsed / displayed faces |', '|---|---|---|---|')
+foreach ($result in $results) { $table += "| $($result.SpecimenId) | $($result.Schema) | $($result.ImportStatus) | $($result.BoundFaces) / $($result.ParsedFaces) / $($result.DisplayedFaces) |" }
+$table | Set-Content (Join-Path $out 'corpus-summary.md') -Encoding utf8
diff --git a/scripts/qualify-viewport-themes.mts b/scripts/qualify-viewport-themes.mts
new file mode 100644
index 00000000..b91013d7
--- /dev/null
+++ b/scripts/qualify-viewport-themes.mts
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import { readFile, writeFile, mkdir } from "node:fs/promises";
+import { join, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+
+const [playwrightPath, corpus, output, address="http://127.0.0.1:5087", specimenId="mcm-01"] = process.argv.slice(2);
+assert(playwrightPath && corpus && output,"Pass Playwright module, local McMaster corpus and ignored output directory.");
+const { chromium } = await import(pathToFileURL(resolve(playwrightPath)).href);
+await mkdir(output,{recursive:true});
+const manifest = JSON.parse(await readFile("testdata/step242/manifests/mcmaster-legacy-x0.json","utf8"));
+const specimen=manifest.specimens.find((s:{id:string})=>s.id===specimenId);assert(specimen);
+const browser=await chromium.launch({executablePath:"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",headless:true});
+try {
+ const page=await browser.newPage({viewport:{width:1440,height:1050}});
+ const errors:string[]=[];page.on("pageerror",(e:Error)=>errors.push(String(e)));
+ await page.goto(address);
+ await page.locator('input[type="file"]').setInputFiles(join(corpus,specimen.filename));
+ const response=page.waitForResponse((r:any)=>r.url().endsWith("/import/step"),{timeout:120000});
+ await page.getByRole("button",{name:"Import STEP 242",exact:true}).click();assert((await response).ok());
+ const canvas=page.getByLabel("Engineering WebGPU viewport");
+ await page.waitForFunction(()=>JSON.parse(document.querySelector("canvas")?.getAttribute("data-telos-display")??"{}").meshSurfaces>0,undefined,{timeout:120000});
+ const themes=await page.getByLabel("Viewport theme").locator("option").evaluateAll((options:HTMLOptionElement[])=>options.map(o=>({id:o.value,label:o.textContent})));
+ const captures:any[]=[];
+ for(const theme of themes) {
+ await page.getByLabel("Viewport theme").selectOption(theme.id);
+ await page.waitForFunction(id=>JSON.parse(document.querySelector("canvas")?.getAttribute("data-telos-presentation")??"{}").id===id,theme.id);
+ await page.evaluate(async()=>{await new Promise(requestAnimationFrame);await new Promise(requestAnimationFrame)});
+ assert.equal(await page.getByRole("alert").count(),0,"GPU shader validation must succeed");
+ const presentation=JSON.parse(await canvas.getAttribute("data-telos-presentation")??"{}");
+ const state=JSON.parse(await canvas.getAttribute("data-surface-inspection")??"{}");
+ const display=JSON.parse(await canvas.getAttribute("data-telos-display")??"{}");
+ if(captures.length){assert.deepEqual(state.camera,captures[0].camera,"Themes preserve camera");assert.equal(display.meshSurfaces,captures[0].display.meshSurfaces);assert.equal(display.topologyLines,captures[0].display.topologyLines)}
+ await canvas.screenshot({path:join(output,`${specimenId}-${theme.id}.png`)});
+ captures.push({...theme,presentation,camera:state.camera,display});
+ }
+ // Exercise real selection against every palette at the same pixel.
+ const box=await canvas.boundingBox();assert(box);
+ const picks:any[]=[];
+ for(const theme of themes) {
+ await page.getByLabel("Viewport theme").selectOption(theme.id);
+ await canvas.click({position:{x:box.width*.48,y:box.height*.45}});
+ const hit=JSON.parse(await canvas.getAttribute("data-surface-inspection-pick")??"null");
+ assert(hit?.faceId!==undefined,"A source face must be pickable");
+ if(picks.length){assert.equal(hit.faceId,picks[0].hit.faceId);assert.equal(hit.occurrenceId,picks[0].hit.occurrenceId)}
+ await canvas.screenshot({path:join(output,`${specimenId}-${theme.id}-selected.png`)});picks.push({theme:theme.id,hit});
+ }
+ const pipelineCount=JSON.parse(await canvas.getAttribute("data-telos-display")??"{}").pipelines;
+ for(let i=0;i<3;i++)for(const theme of themes)await page.getByLabel("Viewport theme").selectOption(theme.id);
+ await page.evaluate(async()=>{await new Promise(requestAnimationFrame);await new Promise(requestAnimationFrame)});
+ assert.equal(JSON.parse(await canvas.getAttribute("data-telos-display")??"{}").pipelines,pipelineCount,"Theme cycling must not grow GPU pipelines");
+ assert.equal(errors.length,0,errors.join("\n"));
+ await writeFile(join(output,`${specimenId}-themes.json`),JSON.stringify({specimenId,captures,picks,pipelineCount,errors},null,2));
+ console.log(`${specimenId}: ${themes.length} rendered themes, same camera/source face, bounded pipeline cache`);
+} finally {await browser.close()}
diff --git a/scripts/render-step-legacy.py b/scripts/render-step-legacy.py
new file mode 100644
index 00000000..56dc3394
--- /dev/null
+++ b/scripts/render-step-legacy.py
@@ -0,0 +1,63 @@
+"""Deterministic two-sided diagnostic captures of Aetheris display meshes.
+
+These captures do not substitute for Cadmata orbit/selection qualification.
+No surfaces are added, healed, culled, or reconstructed by this renderer.
+"""
+import json
+import sys
+from pathlib import Path
+import numpy as np
+from PIL import Image, ImageDraw
+
+root = Path(sys.argv[1])
+tiles = []
+for directory in sorted(p for p in root.iterdir() if p.is_dir()):
+ report_path = directory / "diagnostics.json"
+ report = json.loads(report_path.read_text(encoding="utf-8-sig")) if report_path.exists() else {}
+ mesh_path = directory / "mesh.json"
+ patches = json.loads(mesh_path.read_text()) if mesh_path.exists() else []
+ vertices, triangles = [], []
+ for patch in patches:
+ offset = len(vertices)
+ vertices.extend(patch["Positions"])
+ indices = patch["TriangleIndices"]
+ triangles.extend([[offset + n for n in indices[i:i+3]] for i in range(0, len(indices), 3)])
+ for name, direction in [("iso", [1., -1.3, .9]), ("opposite-iso", [-1., 1.3, -.9])]:
+ canvas = Image.new("RGB", (900, 800), (240, 243, 248))
+ draw = ImageDraw.Draw(canvas)
+ draw.text((20, 15), directory.name + " / " + name, fill=(25, 30, 40))
+ draw.text((20, 35), report.get("ImportStatus", "Failed") + " / " + report.get("Filename", "worker failed"), fill=(40, 45, 55))
+ if triangles:
+ points = np.asarray(vertices)
+ tri = np.asarray(triangles)
+ view = np.asarray(direction)
+ view /= np.linalg.norm(view)
+ right = np.cross(view, [0., 0., 1.])
+ right /= np.linalg.norm(right)
+ up = np.cross(view, right)
+ centered = points - (points.min(axis=0) + points.max(axis=0)) / 2
+ projected = np.column_stack((centered @ right, centered @ up, centered @ view))
+ scale = min(780 / max(np.ptp(projected[:, 0]), 1e-9), 650 / max(np.ptp(projected[:, 1]), 1e-9))
+ xy = np.column_stack((450 + projected[:, 0] * scale, 425 - projected[:, 1] * scale))
+ verts = points[tri]
+ normal = np.cross(verts[:, 1] - verts[:, 0], verts[:, 2] - verts[:, 0])
+ length = np.linalg.norm(normal, axis=1)
+ valid = length > 1e-13
+ normal[valid] /= length[valid, None]
+ brightness = .3 + .7 * np.abs(normal @ view)
+ order = np.where(valid)[0]
+ order = order[np.argsort(projected[tri[order], 2].mean(axis=1), kind="stable")]
+ for index in order:
+ shade = brightness[index]
+ draw.polygon([tuple(xy[n]) for n in tri[index]], fill=tuple(int(c * shade) for c in (140, 168, 198)))
+ else:
+ draw.text((80, 350), "NO IMPORTED DISPLAY GEOMETRY - see diagnostics", fill=(180, 30, 30))
+ canvas.save(directory / (name + ".png"))
+ if name == "iso":
+ canvas.thumbnail((360, 320))
+ tiles.append(canvas)
+ print(directory.name, len(triangles), "triangles")
+contact = Image.new("RGB", (360 * 4, 320 * ((len(tiles) + 3) // 4)), "white")
+for index, tile in enumerate(tiles):
+ contact.paste(tile, ((index % 4) * 360, (index // 4) * 320))
+contact.save(root / "contact-sheet.png")
diff --git a/test-support/Aetheris.StepLegacyCorpus/Aetheris.StepLegacyCorpus.csproj b/test-support/Aetheris.StepLegacyCorpus/Aetheris.StepLegacyCorpus.csproj
new file mode 100644
index 00000000..e23e9253
--- /dev/null
+++ b/test-support/Aetheris.StepLegacyCorpus/Aetheris.StepLegacyCorpus.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="../../Aetheris.CLI/Aetheris.CLI.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/test-support/Aetheris.StepLegacyCorpus/Program.cs b/test-support/Aetheris.StepLegacyCorpus/Program.cs
new file mode 100644
index 00000000..cc27ef49
--- /dev/null
+++ b/test-support/Aetheris.StepLegacyCorpus/Program.cs
@@ -0,0 +1,267 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Text.RegularExpressions;
+using Aetheris.CLI;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Import;
+using Aetheris.Kernel.Core.Step242;
+
+// One specimen per process: the outer runner contains hangs and allocation failures.
+if (args.Length is < 2 or > 4 || args.Length == 3 && args[2] is not ("--probe-pcurves" or "--probe-spheres") || args.Length == 4 && args[2] != "--face-step")
+ throw new ArgumentException("Usage: Aetheris.StepLegacyCorpus <source.step> <output-directory> [--probe-pcurves | --probe-spheres | --face-step <entity-id>]");
+int? debugFaceStepId = args.Length == 4 ? int.Parse(args[3], CultureInfo.InvariantCulture) : null;
+var source = Path.GetFullPath(args[0]);
+var output = Path.GetFullPath(args[1]);
+Directory.CreateDirectory(output);
+var json = new JsonSerializerOptions { WriteIndented = true, Converters = { new JsonStringEnumConverter() } };
+var watch = Stopwatch.StartNew();
+var text = File.ReadAllText(source);
+var schema = Regex.Match(text, @"FILE_SCHEMA\s*\(\s*\((.*?)\)\s*\)", RegexOptions.Singleline).Groups[1].Value;
+var diagnostics = new List<KernelDiagnostic>();
+var bodies = new List<(string Id, BrepBody Body)>();
+var instances = new List<(string Definition, Transform3D World)>();
+object? structureEvidence = null;
+string? failure = null;
+var parsed = Step242SubsetParser.Parse(text);
+var entities = parsed.IsSuccess ? parsed.Value.Entities.ToArray() : [];
+var assembly = entities.Any(e => e.Name == "NEXT_ASSEMBLY_USAGE_OCCURRENCE");
+try
+{
+ if (assembly)
+ {
+ var imported = Step242AssemblyImporter.Import(text);
+ diagnostics.AddRange(imported.Diagnostics);
+ if (imported.IsSuccess)
+ {
+ var structure = imported.Value;
+ bodies.AddRange(structure.Definitions.Where(d => d.Geometry is not null).Select(d => (d.StableId, d.Geometry!)));
+ var byId = structure.Occurrences.ToDictionary(o => o.StableId);
+ var worlds = new Dictionary<string, Transform3D>();
+ Transform3D World(string id)
+ {
+ if (worlds.TryGetValue(id, out var cached)) return cached;
+ var occurrence = byId[id];
+ var local = Transform3D.FromRowMajor(occurrence.LocalTransform);
+ return worlds[id] = occurrence.ParentStableId is null ? local : local * World(occurrence.ParentStableId);
+ }
+ instances.AddRange(structure.Occurrences.Select(o => (o.DefinitionStableId, World(o.StableId))));
+ structureEvidence = new { structure.RootDefinitionStableId, Definitions = structure.Definitions.Select(d => new { d.StableId, d.Name, d.RigidRootEntityId }), structure.Occurrences, structure.Provenance };
+ }
+ else failure = "Assembly import failed";
+ }
+ else
+ {
+ var imported = Step242Importer.ImportRigidRoots(text);
+ diagnostics.AddRange(imported.Diagnostics);
+ if (imported.IsSuccess)
+ {
+ bodies.AddRange(imported.Value.Select(r => (r.StepEntityId.ToString(CultureInfo.InvariantCulture), r.Body)));
+ instances.AddRange(bodies.Select(b => (b.Id, Transform3D.Identity)));
+ }
+ else failure = "Rigid-root import failed";
+ }
+}
+catch (Exception ex) { failure = ex.ToString(); }
+var importMilliseconds = watch.Elapsed.TotalMilliseconds;
+var reports = new List<object>();
+var patches = new List<object>();
+var displayedFaces = 0;
+var boundFaces = 0;
+var qualifications = new List<BrepImportQualificationReport>();
+var normalization = new List<object>();
+foreach (var (id, body) in bodies)
+{
+ try
+ {
+ object? probe = null;
+ if (args.Length == 3 && args[2] == "--probe-pcurves")
+ {
+ var recovered = BrepPcurveRecovery.Populate(body.Topology, body.Geometry, body.Bindings, tolerance: 1e-3);
+ probe = new { Recovery = recovered, Evidence = BrepPcurveValidator.Validate(body, 1e-3, requireEveryCoedge: true) };
+ }
+ var summary = StepAnalyzer.AnalyzeImportedBody(body, source).Summary;
+ var displayOptions = DisplayTessellationOptions.ForViewport(body);
+ var displayWatch = Stopwatch.StartNew();
+ var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body, displayOptions, TimeSpan.FromSeconds(30));
+ var displayMilliseconds = displayWatch.Elapsed.TotalMilliseconds;
+ var visible = mesh.FacePatches.Where(p => p.TriangleIndices.Count > 0).Select(p => p.FaceId).Distinct().ToHashSet();
+ var missing = body.Topology.Faces.Where(f => !visible.Contains(f.Id)).Select(f => f.Id.Value).ToArray();
+ var qualification = BrepImportQualification.WithDisplay(body, mesh);
+ qualifications.Add(qualification);
+ boundFaces += summary.FaceCount;
+ displayedFaces += visible.Count;
+ var rejectedDisplayFaces = body.Topology.Faces.Where(f => !visible.Contains(f.Id)
+ || body.Bindings.GetFaceBinding(f.Id).SourceStepEntityId == debugFaceStepId
+ || args.Length == 3 && args[2] == "--probe-spheres" && body.GetFaceSurface(f.Id).Kind == Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Sphere).Select(f => new {
+ FaceId = f.Id.Value, StepEntityId = body.Bindings.GetFaceBinding(f.Id).SourceStepEntityId,
+ Surface = body.Geometry.Surfaces.Single(s => s.Key == body.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Value.Kind.ToString(),
+ Support = body.Geometry.Surfaces.Single(s => s.Key == body.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Value,
+ Orientation = body.Bindings.GetFaceBinding(f.Id).Orientation,
+ FaceBinding = body.Bindings.GetFaceBinding(f.Id),
+ TriangulationInput = body.Geometry.Surfaces.Single(s => s.Key == body.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Value.BSplineSurfaceWithKnots is not null
+ ? SplineTrimInput(body, f.Id) : null,
+ TriangulationOutput = mesh.FacePatches.Where(p => p.FaceId == f.Id)
+ .Select(p => new { p.Positions, p.TriangleIndices }),
+ Loops = f.LoopIds.Select(l => new { LoopId = l.Value, body.Topology.GetLoop(l).Kind,
+ Coedges = body.Topology.GetLoop(l).CoedgeIds.Select(c => {
+ var coedge = body.Topology.GetCoedge(c); var edge = body.Topology.GetEdge(coedge.EdgeId);
+ body.TryGetVertexPoint(edge.StartVertexId, out var start); body.TryGetVertexPoint(edge.EndVertexId, out var end);
+ var hasPcurve = body.Bindings.TryGetPcurveBinding(c, out var pc);
+ return new { CoedgeId = c.Value, EdgeId = edge.Id.Value, coedge.IsReversed, Start = start, End = end,
+ EdgeBinding = body.Bindings.GetEdgeBinding(edge.Id), PcurveSameSense = hasPcurve ? pc.SameSense : (bool?)null,
+ Curve = body.GetEdgeCurve(edge.Id), body.Bindings.GetEdgeBinding(edge.Id).TrimInterval,
+ EdgeSamples = DebugEdgeSamples(body, edge.Id),
+ ProjectedEdgeSamples = DebugProjectedEdgeSamples(body, f.Id, edge.Id),
+ PcurveQualification = hasPcurve ? pc.Qualification : null,
+ Pcurve = hasPcurve ? pc.Pcurve : null,
+ PcurveSamples = hasPcurve ? Enumerable.Range(0, 33).Select(i => pc.Pcurve.Evaluate(
+ i == 32 ? pc.Pcurve.Domain.End : pc.Pcurve.Domain.Start + i / 32d * (pc.Pcurve.Domain.End - pc.Pcurve.Domain.Start))) : null,
+ PcurveStart = hasPcurve ? pc.Pcurve.Evaluate(pc.Pcurve.Domain.Start) : (Aetheris.Kernel.Core.Brep.SurfaceParameterPoint?)null,
+ PcurveEnd = hasPcurve ? pc.Pcurve.Evaluate(pc.Pcurve.Domain.End) : (Aetheris.Kernel.Core.Brep.SurfaceParameterPoint?)null };
+ }) })
+ });
+ reports.Add(new { Id = id, Summary = summary, Qualification = qualification, DisplayedFaces = visible.Count,
+ DisplayMilliseconds = displayMilliseconds, DisplayOptions = displayOptions,
+ TriangleCount = mesh.FacePatches.Sum(p => p.TriangleIndices.Count / 3),
+ MissingDisplayFaceIds = missing, RejectedDisplayFaces = rejectedDisplayFaces, mesh.FaceDiagnostics, PcurveProbe = probe });
+ foreach (var instance in instances.Where(i => i.Definition == id))
+ foreach (var patch in mesh.FacePatches)
+ if (debugFaceStepId is null || body.Bindings.GetFaceBinding(patch.FaceId).SourceStepEntityId == debugFaceStepId)
+ patches.Add(new { Definition = id, FaceId = patch.FaceId.Value, Positions = patch.Positions.Select(p => { var w = instance.World.Apply(p); return new[] { w.X, w.Y, w.Z }; }), patch.TriangleIndices,
+ QuadCells = patch.Cells?.OfType<QuadCell>().Select(cell => cell.VertexIds).ToArray() });
+ if (qualification.GeometryStatus == ImportQualificationStatus.Qualified && args.Length == 2)
+ {
+ try
+ {
+ // The corpus uses the importer-qualified engineering recovery budget,
+ // never a display tolerance. Exact geometry keeps the stricter trim
+ // budget; recovered ordinary parts remain bounded by 0.1 mm.
+ var normalizationTolerance = double.Min(.1d, double.Max(qualification.PcurveToleranceMillimetres,
+ body.Geometry.Curves.Select(c => c.Value.RecoveryProvenance?.RecoveryToleranceMillimetres ?? 0d)
+ .Concat(body.Geometry.Surfaces.Select(s => s.Value.RecoveryProvenance?.RecoveryToleranceMillimetres ?? 0d)).DefaultIfEmpty(0d).Max()));
+ var exported = Step242Exporter.ExportBody(body, new Step242ExportOptions {
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ ImportedRecoveryToleranceMillimetres = normalizationTolerance,
+ ImportedSourceVertexTolerancesMillimetres = body.Topology.Vertices.ToDictionary(v => v.Id,
+ _ => normalizationTolerance)
+ });
+ if (!exported.IsSuccess) normalization.Add(new { Id = id, Success = false, Diagnostics = exported.Diagnostics });
+ else
+ {
+ File.WriteAllText(Path.Combine(output, $"normalized-{id}.step"), exported.Value);
+ var reimport = Step242Importer.ImportBody(exported.Value);
+ if (!reimport.IsSuccess) normalization.Add(new { Id = id, Success = false, Diagnostics = reimport.Diagnostics });
+ else
+ {
+ var after = StepAnalyzer.AnalyzeImportedBody(reimport.Value, "normalized").Summary;
+ var beforeCounts = new[] { summary.BodyCount, summary.ShellCount, summary.FaceCount, summary.EdgeCount, summary.VertexCount };
+ var afterCounts = new[] { after.BodyCount, after.ShellCount, after.FaceCount, after.EdgeCount, after.VertexCount };
+ var boundsDeviation = summary.BoundingBox is { } a && after.BoundingBox is { } b
+ ? double.Max((a.Min - b.Min).Length, (a.Max - b.Max).Length) : double.PositiveInfinity;
+ // Serialization reallocates IDs and can rebuild curve parameter
+ // origins. Match geometric endpoints, then compare directed
+ // fractions in each curve's own native trim domain.
+ var restoredEdges = EdgeSamples(reimport.Value).ToList();
+ var deviation = 0d;
+ var matched = 0;
+ foreach (var original in EdgeSamples(body))
+ {
+ // Rounded coordinate keys can straddle a quantization
+ // boundary even when the vertices agree well within the
+ // comparison budget. Compare actual endpoint distances.
+ var candidates = restoredEdges.Where(candidate =>
+ ((original.Start - candidate.Start).Length <= normalizationTolerance && (original.End - candidate.End).Length <= normalizationTolerance) ||
+ ((original.Start - candidate.End).Length <= normalizationTolerance && (original.End - candidate.Start).Length <= normalizationTolerance)).ToArray();
+ if (candidates.Length == 0) { deviation = double.PositiveInfinity; break; }
+ var distances = candidates.Select(candidate => {
+ var forward = original.Points.Zip(candidate.Points).Max(pair => (pair.First - pair.Second).Length);
+ var reverse = original.Points.Zip(candidate.Points.Reverse()).Max(pair => (pair.First - pair.Second).Length);
+ return (Candidate: candidate, Distance: double.Min(forward, reverse));
+ }).OrderBy(d => d.Distance).ToArray();
+ deviation = double.Max(deviation, distances[0].Distance);
+ restoredEdges.Remove(distances[0].Candidate);
+ matched++;
+ }
+ var success = beforeCounts.SequenceEqual(afterCounts) && boundsDeviation <= normalizationTolerance && deviation <= normalizationTolerance
+ && after.ImportQualification?.GeometryStatus == ImportQualificationStatus.Qualified;
+ normalization.Add(new { Id = id, Success = success, BeforeCounts = beforeCounts, AfterCounts = afterCounts,
+ BoundsDeviationMillimetres = boundsDeviation, SampledEdgeDeviationMillimetres = double.IsFinite(deviation) ? deviation : (double?)null,
+ MatchedEdges = matched, EngineeringToleranceMillimetres = normalizationTolerance,
+ NonRationalStep = !exported.Value.Contains("RATIONAL_B_SPLINE", StringComparison.Ordinal),
+ ExportRecovery = exported.Diagnostics.Where(d => d.Source == "Step242.ProductionNormalization"),
+ ComparisonBasis = "33 samples per edge; endpoint-matched, native parameter fractions; interiors not sampled", After = after });
+ }
+ }
+ }
+ catch (Exception ex) { normalization.Add(new { Id = id, Success = false, Failure = ex.ToString() }); }
+ }
+ }
+ catch (Exception ex) { reports.Add(new { Id = id, Failure = ex.ToString() }); }
+}
+var parsedFaces = entities.Count(e => e.Name == "ADVANCED_FACE");
+// Inspectable remains a candidate, never a claim that visual review/normalization passed.
+var status = bodies.Count == 0 ? "Failed" : qualifications.Count != bodies.Count || boundFaces != parsedFaces ? "Degraded"
+ : qualifications.Select(q => q.Status).DefaultIfEmpty(ImportQualificationStatus.Failed).Max().ToString();
+File.WriteAllText(Path.Combine(output, "mesh.json"), JsonSerializer.Serialize(patches, json));
+File.WriteAllText(Path.Combine(output, "diagnostics.json"), JsonSerializer.Serialize(new {
+ Filename = Path.GetFileName(source), Sha256 = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(source))),
+ Bytes = new FileInfo(source).Length, Schema = schema, SourceMillimetresPerUnit = parsed.IsSuccess ? parsed.Value.SourceMillimetresPerUnit : (double?)null,
+ ProductCount = entities.Count(e => e.Name == "PRODUCT"), AssemblyUsageCount = entities.Count(e => e.Name == "NEXT_ASSEMBLY_USAGE_OCCURRENCE"),
+ RigidRootCount = entities.Count(e => e.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS"),
+ ImportedDefinitions = bodies.Count, Occurrences = instances.Count, ParsedFaces = parsedFaces, BoundFaces = boundFaces, DisplayedFaces = displayedFaces,
+ ImportStatus = status, ImportMilliseconds = importMilliseconds, TotalMilliseconds = watch.Elapsed.TotalMilliseconds,
+ Failure = failure, Diagnostics = diagnostics, Bodies = reports, Structure = structureEvidence,
+ VisualReview = "pending", Normalization = normalization
+}, json));
+Console.WriteLine($"{Path.GetFileName(source)}: {status}; faces {boundFaces}/{parsedFaces}, displayed {displayedFaces}; {importMilliseconds:F0}ms");
+
+static object? DebugProjectedEdgeSamples(BrepBody body, Aetheris.Kernel.Core.Topology.FaceId face, Aetheris.Kernel.Core.Topology.EdgeId edge)
+{
+ if (!body.TryGetFaceSurface(face, out var support) || support?.BSplineSurfaceWithKnots is not { } spline) return null;
+ SurfaceParameterPoint? previous = null;
+ return DebugEdgeSamples(body, edge).Select(point => {
+ var result = BrepPcurveRecovery.ProjectSplinePoint(spline, point, previous, 1e-8);
+ previous = result.Uv;
+ return new { result.Success, result.Uv, result.Residual };
+ }).ToArray();
+}
+
+static IEnumerable<(Point3D Start, Point3D End, Point3D[] Points)> EdgeSamples(BrepBody body)
+{
+ foreach (var edge in body.Topology.Edges)
+ {
+ body.TryGetVertexPoint(edge.StartVertexId, out var a); body.TryGetVertexPoint(edge.EndVertexId, out var b);
+ var binding = body.Bindings.GetEdgeBinding(edge.Id);
+ var curve = body.GetEdgeCurve(edge.Id);
+ var interval = binding.TrimInterval!.Value;
+ var points = Enumerable.Range(0, 33).Select(index => {
+ var fraction = binding.OrientedEdgeSense ? index / 32d : 1d - index / 32d;
+ return BrepPcurveValidator.Evaluate(curve, interval.Start + (interval.End - interval.Start) * fraction)
+ ?? throw new NotSupportedException($"Edge sample evaluator unavailable for {curve.Kind}");
+ }).ToArray();
+ yield return (a, b, points);
+ }
+}
+
+static object SplineTrimInput(BrepBody body, Aetheris.Kernel.Core.Topology.FaceId face)
+{
+ var input = BrepDisplayTessellator.InspectSplineTrim(body, face);
+ return new { input.IsSuccess, input.Diagnostics,
+ Loops = input.IsSuccess ? input.Value.Select(l => l.Select(p => new { p.U, p.V }).ToArray()).ToArray() : null };
+}
+
+static Point3D[] DebugEdgeSamples(BrepBody body, Aetheris.Kernel.Core.Topology.EdgeId edge)
+{
+ if (body.Bindings.GetEdgeBinding(edge).TrimInterval is not { } interval) return [];
+ var curve = body.GetEdgeCurve(edge);
+ return Enumerable.Range(0, 65).Select(i => BrepPcurveValidator.Evaluate(curve,
+ i == 64 ? interval.End : interval.Start + i / 64d * (interval.End - interval.Start)))
+ .Where(p => p.HasValue).Select(p => p!.Value).ToArray();
+}
diff --git a/testdata/step242/manifests/mcmaster-legacy-x0.json b/testdata/step242/manifests/mcmaster-legacy-x0.json
new file mode 100644
index 00000000..d59879c4
--- /dev/null
+++ b/testdata/step242/manifests/mcmaster-legacy-x0.json
@@ -0,0 +1,579 @@
+{
+ "milestone": "STEP-LEGACY-IMPORT-X0",
+ "redistribution": "Raw vendor CAD remains local; no redistribution permission asserted.",
+ "specimens": [
+ {
+ "id": "mcm-01",
+ "filename": "2515N333_Metal Bevel Pinion.STEP",
+ "sha256": "0e2b1cebef1d52b04ccfaf445db72c68407baa02c1be833cef0e556ac7899a88",
+ "bytes": 1224884,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Bevel Pinion",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 211,
+ "bound": 211,
+ "displayed": 211
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-02",
+ "filename": "2515N337_Metal Bevel Gear.STEP",
+ "sha256": "b266a1cde5142897d9d153463b7a536f9a45d64ac7d38d4f0ad8e03d99cb4fe0",
+ "bytes": 2651882,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Bevel Gear",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 467,
+ "bound": 467,
+ "displayed": 467
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-03",
+ "filename": "2590K26_Steel Taper-Lock Bushing-Bore Sprocket.STEP",
+ "sha256": "09a62cabebf1c2dba1e9e8414dca5551827199fbf98c92324977ca9707b9ee46",
+ "bytes": 10899573,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Steel Taper-Lock Bushing-Bore Sprocket",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 667,
+ "bound": 667,
+ "displayed": 667
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-04",
+ "filename": "2664N313_NO THREADS_Metal Gear - 20 Degree Pressure Angle.STEP",
+ "sha256": "7ddde9c0b6cf6ed652b8ece52a3692b2823b753e21e60a451d920bff5fa1aaed",
+ "bytes": 718337,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "NO THREADS_Metal Gear - 20 Degree Pressure Angle",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 266,
+ "bound": 266,
+ "displayed": 266
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-05",
+ "filename": "2664N353_NO THREADS_Metal Gear - 20 Degree Pressure Angle.STEP",
+ "sha256": "025ae2ffdd47153ed793ec2bc71536bf57b00acc72a8cbef8c232c738af9e100",
+ "bytes": 893149,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "NO THREADS_Metal Gear - 20 Degree Pressure Angle",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 210,
+ "bound": 210,
+ "displayed": 208
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-06",
+ "filename": "2664N539_Metal Gear - 20 Degree Pressure Angle.STEP",
+ "sha256": "e7729e3e32dea7c40a97662638c15651144865aa84502e960f784676390d2572",
+ "bytes": 508673,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Gear - 20 Degree Pressure Angle",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 185,
+ "bound": 185,
+ "displayed": 185
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-07",
+ "filename": "2664N545_Metal Gear - 20 Degree Pressure Angle.STEP",
+ "sha256": "feb6a9bfb5494889487f48722f053c35f16b93c831ed0d5d4bde9d64993c9ff3",
+ "bytes": 732872,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Gear - 20 Degree Pressure Angle",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 266,
+ "bound": 266,
+ "displayed": 266
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-08",
+ "filename": "2696N15_Metal Internal Gear - 20 Degree Pressure Angle fusion.step",
+ "sha256": "0a34c93193dcfe67728745309913d454f851a75b7d463407815ecd58241299cc",
+ "bytes": 2803722,
+ "schema": "'AUTOMOTIVE_DESIGN { 1 0 10303 214 3 1 1 }'",
+ "category": "Metal Internal Gear - 20 Degree Pressure Angle fusion",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 605,
+ "bound": 605,
+ "displayed": 605
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-09",
+ "filename": "2696N15_Metal Internal Gear - 20 Degree Pressure Angle.STEP",
+ "sha256": "67935e3cff408145cb3d2f9ecaff699a91246d9ae61a8dc637bd24a6be713565",
+ "bytes": 3280838,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Internal Gear - 20 Degree Pressure Angle",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 610,
+ "bound": 610,
+ "displayed": 610
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-10",
+ "filename": "3357K11_Clamping Two-Piece Shaft Collar.STEP",
+ "sha256": "66ca16c7075da6def62814a86e57ca51aa59a235f0ce4847699dbe80508bbc66",
+ "bytes": 4012079,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Clamping Two-Piece Shaft Collar",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 200,
+ "bound": 200,
+ "displayed": 198
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 2,
+ "successfulBodies": 2,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-11",
+ "filename": "57545K631_Steel Worm.STEP",
+ "sha256": "9222c920192a44dbc214f10d7d869f1fc92d8b57ddb81229664f3988017520e8",
+ "bytes": 912012,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Steel Worm",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 45,
+ "bound": 45,
+ "displayed": 45
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-12",
+ "filename": "5972K94_Steel Ball Bearing.STEP",
+ "sha256": "d184e15d8e2db396df18c2732e4754caf5f24e6f36d3116eeff598ed1bd846c7",
+ "bytes": 419580,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Steel Ball Bearing",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 166,
+ "bound": 166,
+ "displayed": 138
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-13",
+ "filename": "6283K72_Pawl for 6 mm Wide Face Metal Ratcheting Gear.STEP",
+ "sha256": "1af98eab618c833ff4fa246012abff0417b85edb3e133597a79d18570bed756c",
+ "bytes": 52902,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Pawl for 6 mm Wide Face Metal Ratcheting Gear",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Qualified",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 22,
+ "bound": 22,
+ "displayed": 22
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 1,
+ "successfulBodies": 1,
+ "wholeSpecimen": "PassedCountsBoundsAndSampledEdges"
+ }
+ },
+ {
+ "id": "mcm-14",
+ "filename": "6283K75_Metal Ratchet Gear.STEP",
+ "sha256": "af95f5aa1f78aecf554d55355cf20d9ecdef5f8ef9e3436b424643cb7562a19b",
+ "bytes": 808841,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Ratchet Gear",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 308,
+ "bound": 308,
+ "displayed": 308
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-15",
+ "filename": "6443K211_NO THREADS_Single U-Joint.STEP",
+ "sha256": "e1842bf66bef1c474263f586d2dacaec6236c8f24ee556c47287a7a9482e78ae",
+ "bytes": 1643771,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "NO THREADS_Single U-Joint",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 209,
+ "bound": 209,
+ "displayed": 206
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-16",
+ "filename": "6529K57_Metal Miter Gear.STEP",
+ "sha256": "c1195f67f6b78113793e40e398c561b03143af0d62b294a7807e3a01bd887d45",
+ "bytes": 589028,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Metal Miter Gear",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 134,
+ "bound": 134,
+ "displayed": 134
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-17",
+ "filename": "69295K23_Compact Push-In Signal-Power Connector.STEP",
+ "sha256": "632c75c0f07b1baceb25f4e5fe116df1186f37e25ffd8697300c207e8e23d6a8",
+ "bytes": 293780,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Compact Push-In Signal-Power Connector",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Qualified",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 97,
+ "bound": 97,
+ "displayed": 97
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 1,
+ "successfulBodies": 0,
+ "wholeSpecimen": "Failed"
+ }
+ },
+ {
+ "id": "mcm-18",
+ "filename": "7835T51_Mounted Steel Ball Bearing with Cast Iron Housing.STEP",
+ "sha256": "02cba6aa7fd99cd805dba79042f23ee162514b597a7edd2d2c17ddd8121fc524",
+ "bytes": 1950971,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Mounted Steel Ball Bearing with Cast Iron Housing",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 349,
+ "bound": 349,
+ "displayed": 345
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 1,
+ "successfulBodies": 1,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-19",
+ "filename": "90591A335_NO THREADS_Zinc-Plated Steel Hex Nut.STEP",
+ "sha256": "2f747f238e0df3cacf418257db70c1e71e794c5b4e69cd6d83b6ed253374deb7",
+ "bytes": 90652,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "NO THREADS_Zinc-Plated Steel Hex Nut",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 32,
+ "bound": 32,
+ "displayed": 32
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-20",
+ "filename": "90591A335_Zinc-Plated Steel Hex Nut.STEP",
+ "sha256": "bdb13f405ba05b059f2ade03135bf288e36bc8a9abf86ce1ea775a11f4ecd685",
+ "bytes": 276678,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Zinc-Plated Steel Hex Nut",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 44,
+ "bound": 44,
+ "displayed": 44
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-21",
+ "filename": "91280A546_Medium-Strength Class 8.8 Steel Hex Head Screw.STEP",
+ "sha256": "e2770630a4bcd5e2d3623725a78105fe73466738b98f0a10e199489cb6acf088",
+ "bytes": 1619930,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Medium-Strength Class 8.8 Steel Hex Head Screw",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Qualified",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 147,
+ "bound": 147,
+ "displayed": 147
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 1,
+ "successfulBodies": 1,
+ "wholeSpecimen": "PassedCountsBoundsAndSampledEdges"
+ }
+ },
+ {
+ "id": "mcm-22",
+ "filename": "91280A546_NO THREADS_Medium-Strength Class 8.8 Steel Hex Head Screw.STEP",
+ "sha256": "eb3594e3fdf2b3b6ba60bfefb567bcdca30a139d2a8986eb2c89d010ce808eac",
+ "bytes": 395046,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "NO THREADS_Medium-Strength Class 8.8 Steel Hex Head Screw",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 62,
+ "bound": 62,
+ "displayed": 62
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-23",
+ "filename": "9448N17_Interchangeable Point Lathe Center Point.STEP",
+ "sha256": "43f742e374150233f22c86b734183c5b97107138425068928b8db0e1302c7da9",
+ "bytes": 437757,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Interchangeable Point Lathe Center Point",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Degraded",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 215,
+ "bound": 215,
+ "displayed": 215
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-24",
+ "filename": "9657K236_Compression Spring.STEP",
+ "sha256": "fc5d050d37caf44d786340bc94c82ec1e67b378db6c64ee248e5257b1a3b6746",
+ "bytes": 344255,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Compression Spring",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 4,
+ "bound": 4,
+ "displayed": 4
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-25",
+ "filename": "98296A015_1050-1095 Spring Steel Slotted Spring Pin.STEP",
+ "sha256": "fe487255f5bba16f77028ee4dc5679ca0c8afe79263743b8a86fdcc3ddba9d8d",
+ "bytes": 31122,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "1050-1095 Spring Steel Slotted Spring Pin",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 12,
+ "bound": 12,
+ "displayed": 12
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ },
+ {
+ "id": "mcm-26",
+ "filename": "98306A316_Carbon Steel Clevis Pin.STEP",
+ "sha256": "153d11f23390b374b9c0fa5573747c0cf477f127d5eca4965ce9c4a5b1704277",
+ "bytes": 155030,
+ "schema": " 'CONFIG_CONTROL_DESIGN' ",
+ "category": "Carbon Steel Clevis Pin",
+ "vendor": "McMaster-Carr",
+ "source": "user-provided local download",
+ "qualification": "Inspectable",
+ "visualReview": "pending-human-review",
+ "faceCounts": {
+ "parsed": 19,
+ "bound": 19,
+ "displayed": 19
+ },
+ "normalization": {
+ "qualifiedBodyAttempts": 0,
+ "successfulBodies": 0,
+ "wholeSpecimen": "NotQualifiedSpecimen"
+ }
+ }
+ ],
+ "qualificationBasis": "Mechanical BRep/display checks only. Normalization and human visual fidelity gates are separate; Preview 4 legacy corpus is not accepted."
+}
diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.json
index f3f26492..a687d656 100644
--- a/testdata/step242/manifests/nist.v0.report.json
+++ b/testdata/step242/manifests/nist.v0.report.json
@@ -57,7 +57,7 @@
"edges": 354,
"faces": 120
},
- "canonicalSha256": "346db4eedf0b1ee9e69e5116278d723fd643328f92c2a980327ce8155d6eb163"
+ "canonicalSha256": "f4e479c33d5d01e311ff7456598e91fb8043237a41e93d6904e7afa2742a697d"
},
{
"fileId": "testdata_step242_nist_CTC_nist_ctc_04_asme1_ap242-e1",
@@ -197,7 +197,7 @@
"edges": 458,
"faces": 159
},
- "canonicalSha256": "eab5333dab3ae40f636c110d8f1fa23983c51c890f104c936f8e09a7a1bf2fbe"
+ "canonicalSha256": "ebb4cbea28ee39bc30f51e7fb51e14c7920b92c3494e90a732cff7b443e51099"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_10_asme1_ap242-e2",
@@ -317,7 +317,7 @@
"edges": 392,
"faces": 125
},
- "canonicalSha256": "91788d0964d571b573fae9551ab91486b7231a0ceb0d8cdbb4b0a73e9ac423d4"
+ "canonicalSha256": "1de645b35facd9e0e5abd502df4839e1aa7ef2228d187fc319f895d41d2ccc9d"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_10_asme1_ap242-e2",