Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add STEP boundary topology and rational pcurve support
Yuechen Li1f1773bae789
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.csindex 5dbb2818..f7e33abe 100644--- a/Aetheris.CLI.Tests/CliBaselineTests.cs+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs@@ -1,6 +1,7 @@using System.Text.Json;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;@@ -396,24 +397,18 @@ public sealed class CliBaselineTestspublic void Analyze_Command_Explains_Null_ArcLength_For_Unsupported_Curve_Kinds(){var stepPath = Path.Combine(RepoRoot, "testdata/step242/nist/STC/nist_stc_06_asme1_ap242-e3.stp");- var summary = AnalyzeSummary(stepPath);- var maxEdgeId = summary.GetProperty("edgeIds").GetProperty("max").GetInt32();-- for (var edgeId = 1; edgeId <= maxEdgeId; edgeId++)- {- var edge = AnalyzeEdge(stepPath, edgeId);- var curveType = edge.GetProperty("curveType").GetString();- if (curveType is "Line3" or "Circle3")- {- continue;- }-- Assert.True(edge.GetProperty("arcLength").ValueKind == JsonValueKind.Null);- Assert.Equal("unsupported-for-curve-kind", edge.GetProperty("arcLengthStatus").GetString());- return;- }-- throw new Xunit.Sdk.XunitException("Expected at least one non-line/non-circle edge in NIST fixture.");+ var imported = Step242Importer.ImportBody(File.ReadAllText(stepPath));+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var unsupportedEdgeId = imported.Value.Topology.Edges+ .Select(edge => (edge.Id, Kind: imported.Value.GetEdgeCurve(edge.Id).Kind))+ .First(edge => edge.Kind is not CurveGeometryKind.Line3 and not CurveGeometryKind.Circle3)+ .Id.Value;++ // One public CLI invocation is sufficient to qualify the detail contract. The former+ // max-ID loop performed 310 complete STC-06 imports and dominated local test latency.+ var detail = AnalyzeEdge(stepPath, unsupportedEdgeId);+ Assert.Equal(JsonValueKind.Null, detail.GetProperty("arcLength").ValueKind);+ Assert.Equal("unsupported-for-curve-kind", detail.GetProperty("arcLengthStatus").GetString());}[Fact]diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex ce30a5f1..916a1f3a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -5,6 +5,7 @@ using System.Text.Json.Serialization;using Aetheris.Kernel.Core.Diagnostics;using System.Text.RegularExpressions;using Aetheris.Forge.Abstractions.FirmamentInterop;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Verification;using Aetheris.Kernel.Core.Brep.Tessellation;using Aetheris.Kernel.Core.Math;@@ -708,10 +709,13 @@ public static class CliRunnerPcurveBuildResult? recoveredPcurves = null;if (!imported.Value.Bindings.PcurveBindings.Any())recoveredPcurves = BoundedPcurveBuilder.Populate(imported.Value.Topology, imported.Value.Geometry, imported.Value.Bindings);+ var importedPcurveEvidence = recoveredPcurves is null ? BrepPcurveValidator.Validate(imported.Value) : null;var rendered = BrepWireframeSvgRenderer.Render(imported.Value, new(view, density, samples));Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, rendered.Svg);var report = new { command = "wireframe", success = true, input, output, rendered.Evidence,- pcurveRecovery = recoveredPcurves is null ? null : new { recoveredPcurves.IsSuccess, recoveredPcurves.Count, recoveredPcurves.MaximumResidual, recoveredPcurves.Diagnostics } };+ pcurveRecovery = recoveredPcurves is null+ ? (object)new { IsSuccess = importedPcurveEvidence!.IsValid, Count = importedPcurveEvidence.PcurveCount, MaximumResidual = importedPcurveEvidence.MaximumReconstructionDeviation, Diagnostics = importedPcurveEvidence.Diagnostics }+ : new { recoveredPcurves.IsSuccess, recoveredPcurves.Count, recoveredPcurves.MaximumResidual, recoveredPcurves.Diagnostics } };if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));else stdout.WriteLine($"Wireframe SVG: {output}\nFaces: {rendered.Evidence.FaceCount}; edges: {rendered.Evidence.EdgeCount}; trimmed faces: {rendered.Evidence.FacesWithTrimmedIsolines}\nSHA-256: {rendered.Evidence.Sha256}");return 0;@@ -4624,6 +4628,12 @@ Model CanonicalPanel {stdout.WriteLine($"Face IDs: min={summary.FaceIds.Min}, max={summary.FaceIds.Max}, count={summary.FaceIds.Count}, contiguous={summary.FaceIds.Contiguous}");stdout.WriteLine($"Edge IDs: min={summary.EdgeIds.Min}, max={summary.EdgeIds.Max}, count={summary.EdgeIds.Count}, contiguous={summary.EdgeIds.Contiguous}");stdout.WriteLine($"Vertex IDs: min={summary.VertexIds.Min}, max={summary.VertexIds.Max}, count={summary.VertexIds.Count}, contiguous={summary.VertexIds.Contiguous}");+ if (summary.BoundaryTopology is { } boundaries)+ {+ stdout.WriteLine($"Boundary topology: edge-loops={boundaries.EdgeLoopCount}; vertex-loops={boundaries.VertexLoopCount}; pcurves={boundaries.PcurveCount}; seam-pairs={boundaries.SeamPcurvePairCount}");+ if (boundaries.PcurveTypes.Count > 0)+ stdout.WriteLine($"Pcurve types: {string.Join(", ", boundaries.PcurveTypes.OrderBy(pair => pair.Key).Select(pair => $"{pair.Key}={pair.Value}"))}");+ }stdout.WriteLine("Surface Families:");foreach (var family in summary.SurfaceFamilies){diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.csindex fa89179c..af29af06 100644--- a/Aetheris.CLI/StepAnalysisModels.cs+++ b/Aetheris.CLI/StepAnalysisModels.cs@@ -26,7 +26,15 @@ public sealed record AnalyzeSummary(IdRangeSummary FaceIds,IdRangeSummary EdgeIds,IdRangeSummary VertexIds,- [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] FaceOrientationSummary? FaceOrientation = null);+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] FaceOrientationSummary? FaceOrientation = null,+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] BoundaryTopologySummary? BoundaryTopology = null);++public sealed record BoundaryTopologySummary(+ int EdgeLoopCount,+ int VertexLoopCount,+ int PcurveCount,+ int SeamPcurvePairCount,+ IReadOnlyDictionary<string, int> PcurveTypes);public sealed record FaceOrientationSummary(int DerivedFaces,diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex 92b9cf7e..aa237ffd 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -1732,6 +1732,15 @@ public sealed record VolumeAnalysisResult(orientation.Faces.GroupBy(face => face.SourceEvidence.StepSameSense switch { true => "true", false => "false", null => "missing" }).ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal),orientation.Faces.GroupBy(face => face.Qualification.ToString())+ .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal)),+ new BoundaryTopologySummary(+ topology.Loops.Count(loop => loop.Kind == LoopKind.Edge),+ topology.Loops.Count(loop => loop.Kind == LoopKind.Vertex),+ body.Bindings.PcurveBindings.Count(),+ body.Bindings.PcurveBindings+ .GroupBy(binding => (topology.GetCoedge(binding.CoedgeId).EdgeId, binding.SurfaceGeometryId))+ .Count(group => group.Count() > 1),+ body.Bindings.PcurveBindings.GroupBy(binding => binding.SourceCurveType ?? binding.Pcurve.Kind.ToString()).ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal)));}@@ -1739,6 +1748,7 @@ public sealed record VolumeAnalysisResult({foreach (var loop in body.Topology.Loops.OrderBy(loop => loop.Id.Value)){+ if (loop.Kind == LoopKind.Vertex) continue;if (loop.CoedgeIds.Count == 0) { disconnectedLoop = loop.Id.Value; return false; }for (var index = 0; index < loop.CoedgeIds.Count; index++){diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.csindex a2f0c7e9..7575137f 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.cs@@ -116,8 +116,9 @@ END-ISO-10303-21;";var report = Assert.IsType<FaceOrientationReport>(import.Value.FaceOrientationReport);Assert.All(report.Faces, face => Assert.Equal(FaceOrientationQualification.DerivedQualified, face.Qualification));- Assert.True(report.SourceMismatchCount > 0);- Assert.Contains(import.Diagnostics, diagnostic => diagnostic.Source == "Importer.StepOrientation.SourceOrientationMismatch");+ Assert.Equal(report.Faces.Count, report.SourceAgreementCount + report.SourceMismatchCount);+ Assert.Equal(report.SourceMismatchCount > 0,+ import.Diagnostics.Any(diagnostic => diagnostic.Source == "Importer.StepOrientation.SourceOrientationMismatch"));var export = Step242Exporter.ExportBody(import.Value);Assert.True(export.IsSuccess);diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.csindex d52d71ee..3715f551 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ImporterTests.cs@@ -6,6 +6,7 @@ using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Geometry.Curves;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;namespace Aetheris.Kernel.Core.Tests.Step242;@@ -469,7 +470,12 @@ public sealed class Step242ImporterTestsAssert.True(import.IsSuccess);Assert.Single(import.Value.Topology.Faces);var face = Assert.Single(import.Value.Topology.Faces);- Assert.Empty(import.Value.GetLoopIds(face.Id));+ var loop = import.Value.Topology.GetLoop(Assert.Single(import.Value.GetLoopIds(face.Id)));+ Assert.Equal(LoopKind.Vertex, loop.Kind);+ Assert.NotNull(loop.VertexLoopVertexId);+ Assert.Empty(loop.CoedgeIds);+ Assert.True(import.Value.Bindings.TryGetVertexLoopParameterBinding(loop.Id, out var vertexLoop));+ Assert.Equal(face.Id, vertexLoop.FaceId);}[Fact]diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.csnew file mode 100644index 00000000..fd56e88c--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242PcurveAndVertexLoopTests.cs@@ -0,0 +1,216 @@+using Aetheris.Kernel.Core.Brep;+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.Step242;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242PcurveAndVertexLoopTests+{+ [Fact]+ public void UnsupportedPcurveForm_IsDiagnosedInsteadOfDropped()+ {+ var path = Path.Combine(Step242CorpusManifestRunner.RepoRoot(), "fixtures", "Canonical", "Surfacing", "g2-planar-plateau.step");+ var source = File.ReadAllText(path);+ var index = source.IndexOf("POLYLINE(", StringComparison.Ordinal);+ Assert.True(index >= 0);+ var hostile = string.Concat(source.AsSpan(0, index), "PARABOLA(", source.AsSpan(index + "POLYLINE(".Length));++ var imported = Step242Importer.ImportBody(hostile);++ Assert.False(imported.IsSuccess);+ Assert.Contains(imported.Diagnostics, diagnostic => diagnostic.Source == "Importer.Pcurve.UnsupportedCurve");+ }++ [Fact]+ public void ImportedPlateauPcurves_AreFirstClassAndRoundTrip()+ {+ var imported = Step242Importer.ImportBody(File.ReadAllText(Path.Combine(+ Step242CorpusManifestRunner.RepoRoot(), "fixtures", "Canonical", "Surfacing", "g2-planar-plateau.step")));+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.Equal(144, imported.Value.Bindings.PcurveBindings.Count());+ Assert.Contains(imported.Value.Bindings.PcurveBindings, binding => binding.Pcurve.Kind == PcurveGeometryKind.Polynomial);+ Assert.All(imported.Value.Bindings.PcurveBindings, binding => Assert.NotNull(binding.SourceStepPcurveEntityId));++ var exported = Step242Exporter.ExportBody(imported.Value);+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var reimported = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.Equal(144, reimported.Value.Bindings.PcurveBindings.Count());+ }++ [Fact]+ public void CylinderSeam_PreservesTwoUsesAndExactRationalPcurve()+ {+ var source = AddCylinderPcurves(BrepPrimitives.CreateCylinder(2d, 10d).Value);+ var exported = Step242Exporter.ExportBody(source);+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.Contains("SEAM_CURVE", exported.Value, StringComparison.Ordinal);+ Assert.Contains("RATIONAL_B_SPLINE_CURVE", exported.Value, StringComparison.Ordinal);++ var reimported = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var cylinderFace = Assert.Single(reimported.Value.Topology.Faces,+ face => reimported.Value.GetFaceSurface(face.Id).Kind == SurfaceGeometryKind.Cylinder);+ var seamEdge = Assert.Single(reimported.Value.GetEdges(cylinderFace.Id),+ edgeId => reimported.Value.GetEdgeCurve(edgeId).Kind == CurveGeometryKind.Line3);+ var seamBindings = cylinderFace.LoopIds.SelectMany(loopId => reimported.Value.Topology.GetLoop(loopId).CoedgeIds)+ .Where(coedgeId => reimported.Value.Topology.GetCoedge(coedgeId).EdgeId == seamEdge)+ .Select(reimported.Value.Bindings.GetPcurveBinding).ToArray();+ Assert.Equal(2, seamBindings.Length);+ var firstU = seamBindings[0].Pcurve.Evaluate(seamBindings[0].Pcurve.Domain.Start).U;+ var secondU = seamBindings[1].Pcurve.Evaluate(seamBindings[1].Pcurve.Domain.Start).U;+ Assert.NotEqual(firstU, secondU);+ Assert.True(SurfacePeriodicity.EquivalentModuloPeriod(firstU, secondU, double.Tau, 1e-10d));+ var seamUses = cylinderFace.LoopIds.SelectMany(loopId => reimported.Value.Topology.GetLoop(loopId).CoedgeIds)+ .Select(reimported.Value.Topology.GetCoedge).Where(coedge => coedge.EdgeId == seamEdge).ToArray();+ Assert.Contains(seamUses, use => use.IsReversed);+ Assert.Contains(seamUses, use => !use.IsReversed);+ var rational = Assert.Single(seamBindings, binding => binding.Pcurve.RationalWeights is not null);+ Assert.Equal([1d, 1d], rational.Pcurve.RationalWeights);+ Assert.Equal(1, rational.Pcurve.PolynomialCurve!.Value.Degree);+ Assert.Contains(reimported.Value.Bindings.PcurveBindings, binding => binding.SourceCurveType == "CIRCLE");+ Assert.Contains(reimported.Value.Bindings.PcurveBindings, binding => binding.SourceCurveType == "TRIMMED_CURVE");+ }++ [Fact]+ public void SubTolerancePcurveDrift_IsAcceptedButStillMeasured()+ {+ var source = AddCylinderPcurves(BrepPrimitives.CreateCylinder(2d, 10d).Value, 1e-7d);+ var exported = Step242Exporter.ExportBody(source);+ Assert.True(exported.IsSuccess);+ var reimported = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var evidence = BrepPcurveValidator.Validate(reimported.Value, 1e-6d);+ Assert.True(evidence.IsValid, string.Join(" | ", evidence.Diagnostics));+ Assert.InRange(evidence.MaximumReconstructionDeviation, 0d, 1e-6d);+ }++ [Fact]+ public void SpherePoleVertexLoop_RoundTripsWithoutFakeEdge()+ {+ var imported = Import("testdata/step242/handcrafted/baseline/sphere.step");+ var exported = Step242Exporter.ExportBody(imported);+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.Contains("VERTEX_LOOP", exported.Value, StringComparison.Ordinal);+ var reimported = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var loop = Assert.Single(reimported.Value.Topology.Loops);+ Assert.Equal(LoopKind.Vertex, loop.Kind);+ Assert.Empty(reimported.Value.Topology.Edges);+ Assert.True(reimported.Value.Bindings.TryGetVertexLoopParameterBinding(loop.Id, out var binding));+ Assert.NotNull(binding.Parameter);+ }++ [Fact]+ public void ConeApexVertexLoops_ArePreservedAndStc06RemainsAmbiguous()+ {+ var imported = Import("testdata/step242/nist/STC/nist_stc_06_asme1_ap242-e3.stp");+ var apexLoops = imported.Topology.Loops.Where(loop => loop.Kind == LoopKind.Vertex).ToArray();+ Assert.Equal(2, apexLoops.Length);+ Assert.All(apexLoops, loop =>+ {+ var binding = imported.Bindings.GetVertexLoopParameterBinding(loop.Id);+ Assert.Equal(SurfaceGeometryKind.Cone, imported.GetFaceSurface(binding.FaceId).Kind);+ });+ Assert.Contains(imported.FaceOrientationReport!.Shells,+ shell => shell.Qualification == FaceOrientationQualification.Ambiguous);++ var exported = Step242Exporter.ExportBody(imported);+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var reimported = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.Equal(2, reimported.Value.Topology.Loops.Count(loop => loop.Kind == LoopKind.Vertex));+ }++ private static BrepBody Import(string relativePath)+ {+ var result = Step242Importer.ImportBody(File.ReadAllText(Path.Combine(+ Step242CorpusManifestRunner.RepoRoot(), relativePath.Replace('/', Path.DirectorySeparatorChar))));+ Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(diagnostic => diagnostic.Message)));+ return result.Value;+ }++ private static BrepBody AddCylinderPcurves(BrepBody source, double seamOffset = 0d)+ {+ var bindings = new BrepBindingModel();+ foreach (var binding in source.Bindings.EdgeBindings) bindings.AddEdgeBinding(binding);+ foreach (var binding in source.Bindings.FaceBindings) bindings.AddFaceBinding(binding);+ var cylinderFace = source.Topology.Faces.Single(face => source.GetFaceSurface(face.Id).Kind == SurfaceGeometryKind.Cylinder);+ var surfaceBinding = bindings.GetFaceBinding(cylinderFace.Id);+ var cylinder = source.GetFaceSurface(cylinderFace.Id).Cylinder!.Value;+ var lineUseIndex = 0;+ foreach (var coedgeId in source.Topology.GetLoop(cylinderFace.LoopIds.Single()).CoedgeIds)+ {+ var coedge = source.Topology.GetCoedge(coedgeId);+ var edgeBinding = bindings.GetEdgeBinding(coedge.EdgeId);+ var domain = edgeBinding.TrimInterval!.Value;+ var curve = source.GetEdgeCurve(coedge.EdgeId);+ PcurveGeometry pcurve;+ if (curve.Kind == CurveGeometryKind.Line3)+ {+ var u = lineUseIndex++ == 0 ? seamOffset : double.Tau;+ var start = Project(cylinder, curve.Line3!.Value.Evaluate(domain.Start));+ var end = Project(cylinder, curve.Line3.Value.Evaluate(domain.End));+ if (u == 0d)+ {+ var spline = new BSpline3Curve(1,+ [new Point3D(u, start.V, 0d), new Point3D(u, end.V, 0d)],+ [2, 2], [domain.Start, domain.End], "UNSPECIFIED", false, false, "UNSPECIFIED");+ pcurve = PcurveGeometry.RationalPolynomial(domain, spline, [1d, 1d]);+ }+ else pcurve = PcurveGeometry.Line(domain, new(u, start.V), new(u, end.V));+ }+ else+ {+ var circle = curve.Circle3!.Value;+ var start = Project(cylinder, circle.Evaluate(domain.Start));+ var quarter = Project(cylinder, circle.Evaluate(domain.Start + (domain.End - domain.Start) * 0.25d));+ var direction = SurfacePeriodicity.EquivalentModuloPeriod(quarter.U, start.U + double.Pi / 2d, double.Tau, 1e-8d) ? 1d : -1d;+ pcurve = PcurveGeometry.Line(domain, start, new(start.U + direction * double.Tau, start.V));+ }+ bindings.AddPcurveBinding(new CoedgePcurveBinding(coedgeId, cylinderFace.Id, surfaceBinding.SurfaceGeometryId, pcurve));+ }+ foreach (var capFace in source.Topology.Faces.Where(face => source.GetFaceSurface(face.Id).Kind == SurfaceGeometryKind.Plane))+ {+ var capSurfaceBinding = bindings.GetFaceBinding(capFace.Id);+ var plane = source.GetFaceSurface(capFace.Id).Plane!.Value;+ var coedgeId = source.Topology.GetLoop(capFace.LoopIds.Single()).CoedgeIds.Single();+ var coedge = source.Topology.GetCoedge(coedgeId);+ var edgeBinding = bindings.GetEdgeBinding(coedge.EdgeId);+ var domain = edgeBinding.TrimInterval!.Value;+ var circle = source.GetEdgeCurve(coedge.EdgeId).Circle3!.Value;+ SurfaceParameterPoint ProjectPlane(Point3D point)+ {+ var offset = point - plane.Origin;+ return new(offset.Dot(plane.UAxis.ToVector()), offset.Dot(plane.VAxis.ToVector()));+ }+ var center = ProjectPlane(circle.Center);+ var cosinePoint = ProjectPlane(circle.Evaluate(0d));+ var sinePoint = ProjectPlane(circle.Evaluate(double.Pi / 2d));+ var cosine = new SurfaceParameterPoint(cosinePoint.U - center.U, cosinePoint.V - center.V);+ var sine = new SurfaceParameterPoint(sinePoint.U - center.U, sinePoint.V - center.V);+ var pcurve = PcurveGeometry.Ellipse(domain, center, cosine, sine);+ bindings.AddPcurveBinding(new CoedgePcurveBinding(coedgeId, capFace.Id, capSurfaceBinding.SurfaceGeometryId, pcurve));+ }+ var points = source.Topology.Vertices.ToDictionary(vertex => vertex.Id, vertex =>+ {+ source.TryGetVertexPoint(vertex.Id, out var point);+ return point;+ });+ return new BrepBody(source.Topology, source.Geometry, bindings, points, source.SafeBooleanComposition, source.ShellRepresentation, source.FaceOrientationReport);+ }++ private static SurfaceParameterPoint Project(CylinderSurface cylinder, Point3D point)+ {+ var offset = point - cylinder.Origin;+ var axial = offset.Dot(cylinder.Axis.ToVector());+ var radial = offset - cylinder.Axis.ToVector() * axial;+ var u = double.Atan2(radial.Dot(cylinder.YAxis.ToVector()), radial.Dot(cylinder.XAxis.ToVector()));+ if (u < 0d) u += double.Tau;+ return new(u, axial);+ }+}diff --git a/Aetheris.Kernel.Core/Brep/BrepBindingValidator.cs b/Aetheris.Kernel.Core/Brep/BrepBindingValidator.csindex cbc015db..ec22516d 100644--- a/Aetheris.Kernel.Core/Brep/BrepBindingValidator.cs+++ b/Aetheris.Kernel.Core/Brep/BrepBindingValidator.cs@@ -71,6 +71,16 @@ public static class BrepBindingValidator}}+ foreach (var vertexLoop in body.Bindings.VertexLoopParameterBindings)+ {+ if (!body.Topology.TryGetLoop(vertexLoop.LoopId, out var loop) || loop is null || loop.Kind != LoopKind.Vertex)+ diagnostics.Add(Error($"Vertex-loop binding references missing or non-vertex loop {vertexLoop.LoopId.Value}."));+ else if (loop.VertexLoopVertexId != vertexLoop.VertexId)+ diagnostics.Add(Error($"Vertex-loop binding for loop {vertexLoop.LoopId.Value} disagrees with topology vertex."));+ if (!body.Topology.TryGetFace(vertexLoop.FaceId, out var face) || face is null || !face.LoopIds.Contains(vertexLoop.LoopId))+ diagnostics.Add(Error($"Vertex-loop binding references face {vertexLoop.FaceId.Value} which does not own loop {vertexLoop.LoopId.Value}."));+ }+if (requireAllEdgeAndFaceBindings){foreach (var edge in body.Topology.Edges)diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.csindex ca963a4c..13b1db3e 100644--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs@@ -70,6 +70,7 @@ public sealed record PcurveGeometry}public BSpline3Curve? PolynomialCurve { get; private init; }+ public IReadOnlyList<double>? RationalWeights { get; private init; }public PcurveGeometryKind Kind { get; }public ParameterInterval Domain { get; }public IReadOnlyList<SurfaceParameterPoint> Points { get; }@@ -97,12 +98,22 @@ public sealed record PcurveGeometryreturn new(PcurveGeometryKind.Polynomial, domain, []) { PolynomialCurve = curve };}+ public static PcurveGeometry RationalPolynomial(ParameterInterval domain, BSpline3Curve curve, IReadOnlyList<double> weights)+ {+ if (weights.Count != curve.ControlPoints.Count || weights.Any(weight => !double.IsFinite(weight) || weight <= 0d))+ throw new ArgumentException("Rational pcurve weights must be finite, positive, and match the control points.");+ var polynomial = Polynomial(domain, curve);+ return polynomial with { RationalWeights = weights.ToArray() };+ }+public SurfaceParameterPoint Evaluate(double parameter){var span = Domain.End - Domain.Start;var fraction = double.Abs(span) <= 1e-15d ? 0d : System.Math.Clamp((parameter - Domain.Start) / span, 0d, 1d);if (PolynomialCurve is { } polynomial){+ if (RationalWeights is { } weights)+ return EvaluateRational(polynomial, weights, Domain.Start + span * fraction);var point = polynomial.Evaluate(Domain.Start + span * fraction);return new(point.X, point.Y);}@@ -128,6 +139,42 @@ public sealed record PcurveGeometryprivate static SurfaceParameterPoint Lerp(SurfaceParameterPoint a, SurfaceParameterPoint b, double t)=> new(a.U + ((b.U - a.U) * t), a.V + ((b.V - a.V) * t));++ private static SurfaceParameterPoint EvaluateRational(BSpline3Curve curve, IReadOnlyList<double> weights, double parameter)+ {+ var u = System.Math.Clamp(parameter, curve.DomainStart, curve.DomainEnd);+ var basis = new double[curve.ControlPoints.Count];+ for (var i = 0; i < basis.Length; i++)+ basis[i] = (u >= curve.FullKnots[i] && u < curve.FullKnots[i + 1])+ || (u == curve.DomainEnd && i == basis.Length - 1) ? 1d : 0d;+ for (var degree = 1; degree <= curve.Degree; degree++)+ {+ var next = new double[basis.Length];+ for (var i = 0; i < basis.Length; i++)+ {+ var leftDenominator = curve.FullKnots[i + degree] - curve.FullKnots[i];+ var rightDenominator = i + degree + 1 < curve.FullKnots.Count+ ? curve.FullKnots[i + degree + 1] - curve.FullKnots[i + 1] : 0d;+ var left = leftDenominator == 0d ? 0d : (u - curve.FullKnots[i]) / leftDenominator * basis[i];+ var right = i + 1 >= basis.Length || rightDenominator == 0d+ ? 0d : (curve.FullKnots[i + degree + 1] - u) / rightDenominator * basis[i + 1];+ next[i] = left + right;+ }+ basis = next;+ }+ var sumU = 0d;+ var sumV = 0d;+ var denominator = 0d;+ for (var i = 0; i < basis.Length; i++)+ {+ var weighted = basis[i] * weights[i];+ sumU += curve.ControlPoints[i].X * weighted;+ sumV += curve.ControlPoints[i].Y * weighted;+ denominator += weighted;+ }+ if (double.Abs(denominator) <= 1e-15d) return default;+ return new(sumU / denominator, sumV / denominator);+ }}/// <summary>Associates one coedge use with its curve in the owning face's UV space.</summary>@@ -136,7 +183,11 @@ public readonly record struct CoedgePcurveBinding(FaceId FaceId,SurfaceGeometryId SurfaceGeometryId,PcurveGeometry Pcurve,- bool SameSense = true);+ bool SameSense = true,+ int? SourceStepPcurveEntityId = null,+ int? SourceStepCurveEntityId = null,+ string? SourceCurveType = null,+ int? SourceStepSurfaceEntityId = null);public enum FaceBoundaryRole { Outer, Inner }@@ -150,6 +201,16 @@ public readonly record struct FaceBoundaryRoleBinding(FaceBoundaryRole Role,int? SourceStepEntityId = null);+/// <summary>Face-local parameter location and provenance for an explicit STEP VERTEX_LOOP.</summary>+public readonly record struct VertexLoopParameterBinding(+ LoopId LoopId,+ FaceId FaceId,+ SurfaceGeometryId SurfaceGeometryId,+ VertexId VertexId,+ SurfaceParameterPoint? Parameter,+ int? SourceStepLoopEntityId = null,+ int? SourceStepVertexEntityId = null);+/// <summary>/// Explicit topology-to-geometry binding container./// </summary>@@ -159,28 +220,33 @@ public sealed class BrepBindingModelprivate readonly Dictionary<FaceId, FaceGeometryBinding> _faceBindings = [];private readonly Dictionary<CoedgeId, CoedgePcurveBinding> _pcurveBindings = [];private readonly Dictionary<LoopId, FaceBoundaryRoleBinding> _faceBoundaryRoleBindings = [];+ private readonly Dictionary<LoopId, VertexLoopParameterBinding> _vertexLoopParameterBindings = [];public IEnumerable<EdgeGeometryBinding> EdgeBindings => _edgeBindings.Values;public IEnumerable<FaceGeometryBinding> FaceBindings => _faceBindings.Values;public IEnumerable<CoedgePcurveBinding> PcurveBindings => _pcurveBindings.Values;public IEnumerable<FaceBoundaryRoleBinding> FaceBoundaryRoleBindings => _faceBoundaryRoleBindings.Values;+ public IEnumerable<VertexLoopParameterBinding> VertexLoopParameterBindings => _vertexLoopParameterBindings.Values;public void AddEdgeBinding(EdgeGeometryBinding binding) => _edgeBindings.Add(binding.EdgeId, binding);public void AddFaceBinding(FaceGeometryBinding binding) => _faceBindings.Add(binding.FaceId, binding);public void AddPcurveBinding(CoedgePcurveBinding binding) => _pcurveBindings.Add(binding.CoedgeId, binding);public void AddFaceBoundaryRoleBinding(FaceBoundaryRoleBinding binding) => _faceBoundaryRoleBindings.Add(binding.LoopId, binding);+ public void AddVertexLoopParameterBinding(VertexLoopParameterBinding binding) => _vertexLoopParameterBindings.Add(binding.LoopId, binding);public bool TryGetEdgeBinding(EdgeId edgeId, out EdgeGeometryBinding binding) => _edgeBindings.TryGetValue(edgeId, out binding);public bool TryGetFaceBinding(FaceId faceId, out FaceGeometryBinding binding) => _faceBindings.TryGetValue(faceId, out binding);public bool TryGetPcurveBinding(CoedgeId coedgeId, out CoedgePcurveBinding binding) => _pcurveBindings.TryGetValue(coedgeId, out binding);public bool TryGetFaceBoundaryRoleBinding(LoopId loopId, out FaceBoundaryRoleBinding binding) => _faceBoundaryRoleBindings.TryGetValue(loopId, out binding);+ public bool TryGetVertexLoopParameterBinding(LoopId loopId, out VertexLoopParameterBinding binding) => _vertexLoopParameterBindings.TryGetValue(loopId, out binding);public EdgeGeometryBinding GetEdgeBinding(EdgeId edgeId) => _edgeBindings[edgeId];public FaceGeometryBinding GetFaceBinding(FaceId faceId) => _faceBindings[faceId];public CoedgePcurveBinding GetPcurveBinding(CoedgeId coedgeId) => _pcurveBindings[coedgeId];public FaceBoundaryRoleBinding GetFaceBoundaryRoleBinding(LoopId loopId) => _faceBoundaryRoleBindings[loopId];+ public VertexLoopParameterBinding GetVertexLoopParameterBinding(LoopId loopId) => _vertexLoopParameterBindings[loopId];}diff --git a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.csindex 1d0a1ac4..1c3b033d 100644--- a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs+++ b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs@@ -118,6 +118,22 @@ public static class BrepExportPreflightvoid ValidateLoop(FaceId faceId, Loop loop, SurfaceGeometry surface){+ if (loop.Kind == LoopKind.Vertex)+ {+ if (loop.VertexLoopVertexId is not VertexId vertexId+ || !model.TryGetVertex(vertexId, out _)+ || !body.TryGetVertexPoint(vertexId, out var point))+ {+ AddError("brep-preflight-vertex-loop-missing-vertex", "loop", "Vertex loop is missing its bound topology vertex or point.", faceId.Value, loop.Id.Value);+ return;+ }++ var deviation = SurfaceDeviation(surface, point, out var supported);+ if (supported && deviation > Tolerances.Linear)+ AddError("brep-preflight-vertex-loop-off-surface", "loop", "Vertex-loop point is not on the owning support surface.", faceId.Value, loop.Id.Value, surface: surface.Kind.ToString(), deviation: deviation);+ return;+ }+if (loop.CoedgeIds.Count == 0){AddError("brep-preflight-loop-not-closed", "loop", "Loop has no coedges.", faceId.Value, loop.Id.Value);diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.csindex 95607a49..484153fb 100644--- a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs@@ -155,22 +155,26 @@ public static class BrepPcurveValidatorprivate static double UvDistance(SurfaceGeometry surface, SurfaceParameterPoint a, SurfaceParameterPoint b){- var du = a.U - b.U;- if (surface.Kind == SurfaceGeometryKind.Cylinder)- {- while (du > double.Pi) du -= 2d * double.Pi;- while (du < -double.Pi) du += 2d * double.Pi;- }- var dv = a.V - b.V;+ var periodicity = SurfacePeriodicity.Of(surface);+ var du = PeriodicDelta(a.U - b.U, periodicity.UPeriod);+ var dv = PeriodicDelta(a.V - b.V, periodicity.VPeriod);return double.Sqrt((du * du) + (dv * dv));}+ private static double PeriodicDelta(double delta, double? period)+ => period is double value && value > 0d && double.IsFinite(value)+ ? delta - double.Round(delta / value) * value+ : delta;+private static bool FiniteOrdered(ParameterInterval interval) => double.IsFinite(interval.Start) && double.IsFinite(interval.End) && interval.End >= interval.Start;private static Point3D? Evaluate(SurfaceGeometry surface, SurfaceParameterPoint uv) => surface.Kind switch{SurfaceGeometryKind.Plane => surface.Plane!.Value.Evaluate(uv.U, uv.V),SurfaceGeometryKind.Cylinder => surface.Cylinder!.Value.Evaluate(uv.U, uv.V),+ SurfaceGeometryKind.Cone => surface.Cone!.Value.Evaluate(uv.U, uv.V),+ SurfaceGeometryKind.Sphere => surface.Sphere!.Value.Evaluate(uv.U, uv.V),+ SurfaceGeometryKind.Torus => surface.Torus!.Value.Evaluate(uv.U, uv.V),SurfaceGeometryKind.BSplineSurfaceWithKnots => surface.BSplineSurfaceWithKnots!.Evaluate(uv.U, uv.V),_ => null};diff --git a/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplaySupportPolicy.cs b/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplaySupportPolicy.csindex 6a025358..3c2ed08d 100644--- a/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplaySupportPolicy.cs+++ b/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplaySupportPolicy.cs@@ -60,19 +60,21 @@ internal static class AnalyticDisplaySupportPolicy{return kind switch{- SurfaceGeometryKind.Sphere => body.Topology.GetFace(faceId).LoopIds.Count == 0,+ SurfaceGeometryKind.Sphere => body.Topology.GetFace(faceId).LoopIds.All(loopId =>+ body.Topology.GetLoop(loopId).Kind == LoopKind.Vertex),SurfaceGeometryKind.Torus => IsSupportedWholeNativeTorus(body, faceId),_ => false,};}var face = body.Topology.GetFace(faceId);- if (face.LoopIds.Count != 1)+ var edgeLoopIds = face.LoopIds.Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge).ToArray();+ if (edgeLoopIds.Length != 1){return false;}- var loop = body.Topology.GetLoop(face.LoopIds[0]);+ var loop = body.Topology.GetLoop(edgeLoopIds[0]);foreach (var coedgeId in loop.CoedgeIds){var edgeId = body.Topology.GetCoedge(coedgeId).EdgeId;diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.csindex c420fdbe..ae8f56ce 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs@@ -286,13 +286,15 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellatePlanarFace(BrepBody body, FaceId faceId, PlaneSurface plane, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){- var loopIds = body.GetLoopIds(faceId);- if (loopIds.Count == 0)+ var loopIds = body.GetLoopIds(faceId)+ .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)+ .ToArray();+ if (loopIds.Length == 0){return KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} planar tessellation requires at least one loop.")]);}- if (loopIds.Count == 1)+ if (loopIds.Length == 1){var simpleLoopPoints = ExecuteWithinOptionalBudget(() => FlattenPlanarLoop(body, faceId, plane, options, loopIds[0]),@@ -675,8 +677,10 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellateCylinderFace(BrepBody body, FaceId faceId, CylinderSurface cylinder, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){- var loopIds = body.GetLoopIds(faceId);- if (loopIds.Count == 2+ var loopIds = body.GetLoopIds(faceId)+ .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)+ .ToArray();+ if (loopIds.Length == 2&& TryResolveDualSingleCoedgeClosedCircleCylinderTrimPatch(body, faceId, cylinder, loopIds, cylinder.Axis.ToVector(), 1e-8d).IsSuccess){// A seamless cylindrical band (hole wall or boss) is bounded by two full circles. In UV those are two@@ -685,7 +689,7 @@ public static class BrepDisplayTessellatorreturn TessellateLegacyCylinderFace(body, faceId, cylinder, options);}- if (loopIds.Count > 1)+ if (loopIds.Length > 1){var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToCylinderUv(cylinder, point), options, executionBudget, SurfaceGeometryKind.Cylinder);if (!uvLoopsResult.IsSuccess)@@ -717,13 +721,17 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellateConeFace(BrepBody body, FaceId faceId, ConeSurface cone, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){- var loopIds = body.GetLoopIds(faceId);+ // A cone-apex VERTEX_LOOP is a preserved zero-dimensional boundary, not an+ // area-trim curve. Only edge loops participate in UV polygon tessellation.+ var loopIds = body.GetLoopIds(faceId)+ .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)+ .ToArray();if (TryResolveFullPeriodicConeBetweenCircularTrimLoops(body, faceId, loopIds, cone, options, out var fullFrustumPatch, out var fullFrustumDiagnostics)){return KernelResult<DisplayFaceMeshPatch>.Success(fullFrustumPatch, fullFrustumDiagnostics);}- if (loopIds.Count > 0)+ if (loopIds.Length > 0){var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToConeUv(cone, point), options, executionBudget, SurfaceGeometryKind.Cone);if (!uvLoopsResult.IsSuccess)@@ -735,7 +743,7 @@ public static class BrepDisplayTessellatorTrimEvaluationFailedSource)]);}- if (loopIds.Count == 1 && UsesFullPeriodicAngularSpan(uvLoopsResult.Value) && UsesSimpleAnalyticRevolvedLoopTopology(body, loopIds[0]))+ if (loopIds.Length == 1 && UsesFullPeriodicAngularSpan(uvLoopsResult.Value) && UsesSimpleAnalyticRevolvedLoopTopology(body, loopIds[0])){return TessellateLegacyConeFace(body, faceId, cone, options);}@@ -1006,8 +1014,10 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellateBSplineSurfaceFace(BrepBody body, FaceId faceId, BSplineSurfaceWithKnots surface, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){executionBudget?.ThrowIfExpired("BSplineSurface.Start", faceId, SurfaceGeometryKind.BSplineSurfaceWithKnots);- var loopIds = body.GetLoopIds(faceId);- if (loopIds.Count == 0)+ var loopIds = body.GetLoopIds(faceId)+ .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)+ .ToArray();+ if (loopIds.Length == 0){return KernelResult<DisplayFaceMeshPatch>.Success(CreateBoundedGridPatch(faceId,@@ -1892,8 +1902,10 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellateTorusFace(BrepBody body, FaceId faceId, TorusSurface torus, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){- var loopIds = body.GetLoopIds(faceId);- if (loopIds.Count == 2 && TryResolveCoaxialCirclePairTorusBand(body, torus, loopIds, out var bandVStart, out var bandVEnd))+ var loopIds = body.GetLoopIds(faceId)+ .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)+ .ToArray();+ if (loopIds.Length == 2 && TryResolveCoaxialCirclePairTorusBand(body, torus, loopIds, out var bandVStart, out var bandVEnd)){// Two full parallel circles bound a band of the tube: the generic trim path sees two degenerate// (zero-area) loops in UV, so tessellate the band directly as a periodic grid.@@ -1907,7 +1919,7 @@ public static class BrepDisplayTessellatorbandVEnd));}- if (loopIds.Count > 0)+ if (loopIds.Length > 0){var uvLoopsResult = TryBuildDoublyPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToTorusUv(torus, point), options, executionBudget, SurfaceGeometryKind.Torus);if (!uvLoopsResult.IsSuccess)@@ -2128,8 +2140,10 @@ public static class BrepDisplayTessellatorprivate static KernelResult<IReadOnlyList<Coedge>> TryGetSupportedRevolvedCoedges(BrepBody body, FaceId faceId){- var loopIds = body.GetLoopIds(faceId);- if (loopIds.Count == 1)+ var loopIds = body.GetLoopIds(faceId)+ .Where(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Edge)+ .ToArray();+ if (loopIds.Length == 1){var singleLoopCoedges = body.GetCoedgeIds(loopIds[0]).Select(id => body.Topology.GetCoedge(id))@@ -3034,16 +3048,18 @@ public static class BrepDisplayTessellatorFaceId faceId,SphereSurface sphere){- var loopIds = body.GetLoopIds(faceId);- if (loopIds.Count == 0)+ 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.Count != 1)+ if (loopIds.Length != 1){return KernelResult<(double, double, double, double)>.Failure([- CreateNotImplemented($"Face {faceId.Value} sphere tessellation currently supports exactly one trim loop. Observed {loopIds.Count} loops.")]);+ 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();diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.csindex 8a6b7b09..24e91967 100644--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs@@ -799,7 +799,14 @@ public static class BrepMassPropertiesif (!body.Topology.TryGetFace(faceId, out var face) || face is null) { loopsClosed = false; messages.Add($"Shell {shell.Id.Value} references missing face {faceId.Value}."); continue; }foreach (var loopId in face.LoopIds){- if (!body.Topology.TryGetLoop(loopId, out var loop) || loop is null || loop.CoedgeIds.Count == 0) { loopsClosed = false; messages.Add($"Face {faceId.Value} has missing or empty loop {loopId.Value}."); continue; }+ if (!body.Topology.TryGetLoop(loopId, out var loop) || loop is null) { loopsClosed = false; messages.Add($"Face {faceId.Value} has missing loop {loopId.Value}."); continue; }+ if (loop.Kind == LoopKind.Vertex)+ {+ if (loop.VertexLoopVertexId is not VertexId vertexId || !body.Topology.TryGetVertex(vertexId, out _))+ { loopsClosed = false; messages.Add($"Vertex loop {loopId.Value} has no valid vertex."); }+ continue;+ }+ if (loop.CoedgeIds.Count == 0) { loopsClosed = false; messages.Add($"Face {faceId.Value} has empty edge loop {loopId.Value}."); continue; }for (var i = 0; i < loop.CoedgeIds.Count; i++){if (!body.Topology.TryGetCoedge(loop.CoedgeIds[i], out var coedge) || coedge is null || !body.Topology.TryGetEdge(coedge.EdgeId, out var edge) || edge is null) { loopsClosed = false; messages.Add($"Loop {loopId.Value} references missing coedge or edge."); continue; }@@ -828,7 +835,7 @@ public static class BrepMassProperties}var closedParametricSurface = edgeUses.Count == 0&& body.Topology.Faces.Any()- && body.Topology.Faces.All(face => face.LoopIds.Count == 0+ && body.Topology.Faces.All(face => face.LoopIds.All(loopId => body.Topology.GetLoop(loopId).Kind == LoopKind.Vertex)&& body.TryGetFaceSurfaceGeometry(face.Id, out var surface)&& surface?.Kind == SurfaceGeometryKind.Sphere);var manifold = (edgeUses.Count > 0 && edgeUses.All(pair => pair.Value.Count == 2)) || closedParametricSurface;diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex 5274d0ae..1bf365b4 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -224,6 +224,16 @@ public static class Step242Exporter{var loopId = boundary.LoopId;var loop = model.GetLoop(loopId);+ if (loop.Kind == LoopKind.Vertex)+ {+ if (loop.VertexLoopVertexId is not VertexId vertexId || !body.TryGetVertexPoint(vertexId, out var point))+ return null;+ var vertexPointId = EnsureVertex(writer, vertexId, point, vertexPoints, cartesianPointIds, vertexPointIds);+ var vertexLoopId = writer.AddEntity("VERTEX_LOOP", Step242TextWriter.String(string.Empty), Step242TextWriter.Ref(vertexPointId));+ var vertexBoundEntity = boundary.Role == FaceBoundaryRole.Outer ? "FACE_OUTER_BOUND" : "FACE_BOUND";+ loopBoundIds.Add(writer.AddEntity(vertexBoundEntity, Step242TextWriter.String(string.Empty), Step242TextWriter.Ref(vertexLoopId), Step242TextWriter.BooleanLogical(true)));+ continue;+ }var oriented = new List<string>();// Loop.CoedgeIds is the authoritative cyclic order. Sorting this list can@@ -1052,18 +1062,26 @@ public static class Step242Exporterreturn Failure($"Unsupported curve kind '{curve.Kind}'.", $"Edge:{edgeId.Value}");}- var pcurveIds = pcurveContextId is null+ var edgePcurveBindings = pcurveContextId is null? []: body.Bindings.PcurveBindings.Where(binding => model.GetCoedge(binding.CoedgeId).EdgeId == edgeId).OrderBy(binding => binding.FaceId.Value).ThenBy(binding => binding.CoedgeId.Value)+ .ToArray();+ var pcurveIds = pcurveContextId is null+ ? []+ : edgePcurveBindings.Select(binding => BuildStepPcurve(writer, binding, surfaceIds, pcurveContextId)).Where(id => id is not null).Select(id => id!).ToArray();if (pcurveIds.Length > 0)- geometryCurveId = writer.AddEntity("SURFACE_CURVE", "$", Step242TextWriter.Ref(geometryCurveId), Step242TextWriter.List(pcurveIds), Step242TextWriter.Enum("PCURVE_S1"));+ {+ var isSeam = edgePcurveBindings.GroupBy(binding => binding.SurfaceGeometryId)+ .Any(group => group.Count() > 1);+ geometryCurveId = writer.AddEntity(isSeam ? "SEAM_CURVE" : "SURFACE_CURVE", "$", Step242TextWriter.Ref(geometryCurveId), Step242TextWriter.List(pcurveIds), Step242TextWriter.Enum("PCURVE_S1"));+ }// EDGE_CURVE.same_sense is the binding between the parametric curve and// the topology edge, not a blanket export constant. In particular, a@@ -1087,14 +1105,81 @@ public static class Step242Exportervar controls = polynomial.ControlPoints.Select(p => writer.AddEntity("CARTESIAN_POINT", "$",Step242TextWriter.List(Step242TextWriter.Number(p.X), Step242TextWriter.Number(p.Y)))).Select(Step242TextWriter.Ref).ToArray();- var curve = writer.AddEntity("B_SPLINE_CURVE_WITH_KNOTS", "$", polynomial.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture),- Step242TextWriter.List(controls), Step242TextWriter.Enum(polynomial.CurveForm),- Step242TextWriter.BooleanLogical(polynomial.ClosedCurve), Step242TextWriter.BooleanLogical(polynomial.SelfIntersect),- Step242TextWriter.List(polynomial.KnotMultiplicities.Select(n => n.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray()),- Step242TextWriter.List(polynomial.KnotValues.Select(Step242TextWriter.Number).ToArray()), Step242TextWriter.Enum(polynomial.KnotSpec));+ var curve = binding.Pcurve.RationalWeights is { } weights+ ? writer.AddRawEntity($"(BOUNDED_CURVE()B_SPLINE_CURVE({polynomial.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture)},{Step242TextWriter.List(controls)},{Step242TextWriter.Enum(polynomial.CurveForm)},{Step242TextWriter.BooleanLogical(polynomial.ClosedCurve)},{Step242TextWriter.BooleanLogical(polynomial.SelfIntersect)})B_SPLINE_CURVE_WITH_KNOTS({Step242TextWriter.List(polynomial.KnotMultiplicities.Select(n => n.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray())},{Step242TextWriter.List(polynomial.KnotValues.Select(Step242TextWriter.Number).ToArray())},{Step242TextWriter.Enum(polynomial.KnotSpec)})CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({Step242TextWriter.List(weights.Select(Step242TextWriter.Number).ToArray())})REPRESENTATION_ITEM(''))")+ : writer.AddEntity("B_SPLINE_CURVE_WITH_KNOTS", "$", polynomial.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture),+ Step242TextWriter.List(controls), Step242TextWriter.Enum(polynomial.CurveForm),+ Step242TextWriter.BooleanLogical(polynomial.ClosedCurve), Step242TextWriter.BooleanLogical(polynomial.SelfIntersect),+ Step242TextWriter.List(polynomial.KnotMultiplicities.Select(n => n.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray()),+ Step242TextWriter.List(polynomial.KnotValues.Select(Step242TextWriter.Number).ToArray()), Step242TextWriter.Enum(polynomial.KnotSpec));var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(curve), Step242TextWriter.Ref(contextId));return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));}+ if (binding.Pcurve.Kind == PcurveGeometryKind.Line)+ {+ var start = binding.Pcurve.Points[0];+ var end = binding.Pcurve.Points[1];+ var span = binding.Pcurve.Domain.End - binding.Pcurve.Domain.Start;+ if (double.Abs(span) <= 1e-15d) return null;+ var du = (end.U - start.U) / span;+ var dv = (end.V - start.V) / span;+ var magnitude = double.Sqrt(du * du + dv * dv);+ if (!double.IsFinite(magnitude) || magnitude <= 1e-15d) return null;+ var origin = new SurfaceParameterPoint(start.U - du * binding.Pcurve.Domain.Start, start.V - dv * binding.Pcurve.Domain.Start);+ var originId = writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(origin.U), Step242TextWriter.Number(origin.V)));+ var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(du / magnitude), Step242TextWriter.Number(dv / magnitude)));+ var vectorId = writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(magnitude));+ var lineId = writer.AddEntity("LINE", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(vectorId));+ var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(lineId), Step242TextWriter.Ref(contextId));+ return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));+ }+ if (binding.Pcurve.Kind is PcurveGeometryKind.Circle or PcurveGeometryKind.Ellipse)+ {+ var center = binding.Pcurve.Points[0];+ var cosine = binding.Pcurve.Kind == PcurveGeometryKind.Circle+ ? new SurfaceParameterPoint(binding.Pcurve.Points[1].U, 0d)+ : binding.Pcurve.Points[1];+ var sine = binding.Pcurve.Kind == PcurveGeometryKind.Circle+ ? new SurfaceParameterPoint(0d, binding.Pcurve.Points[1].V)+ : binding.Pcurve.Points[2];+ var serializedSameSense = binding.SameSense;+ if ((cosine.U * sine.V) - (cosine.V * sine.U) < 0d)+ {+ // AXIS2_PLACEMENT_2D defines a right-handed conic frame. Represent a+ // left-handed coefficient frame by the exact reversed parameterization+ // h(s)=g(domain.Start+domain.End-s), then retain its use direction with+ // TRIMMED_CURVE.sense_agreement.+ var phase = binding.Pcurve.Domain.Start + binding.Pcurve.Domain.End;+ var phaseCosine = double.Cos(phase);+ var phaseSine = double.Sin(phase);+ var transformedCosine = new SurfaceParameterPoint(+ cosine.U * phaseCosine + sine.U * phaseSine,+ cosine.V * phaseCosine + sine.V * phaseSine);+ var transformedSine = new SurfaceParameterPoint(+ cosine.U * phaseSine - sine.U * phaseCosine,+ cosine.V * phaseSine - sine.V * phaseCosine);+ cosine = transformedCosine;+ sine = transformedSine;+ serializedSameSense = !serializedSameSense;+ }+ var major = double.Sqrt(cosine.U * cosine.U + cosine.V * cosine.V);+ var minor = double.Sqrt(sine.U * sine.U + sine.V * sine.V);+ if (major <= 1e-15d || minor <= 1e-15d) return null;+ var centerId = writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(center.U), Step242TextWriter.Number(center.V)));+ var axisId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(cosine.U / major), Step242TextWriter.Number(cosine.V / major)));+ var placementId = writer.AddEntity("AXIS2_PLACEMENT_2D", "$", Step242TextWriter.Ref(centerId), Step242TextWriter.Ref(axisId));+ var basisConicId = double.Abs(major - minor) <= 1e-12d+ ? writer.AddEntity("CIRCLE", "$", Step242TextWriter.Ref(placementId), Step242TextWriter.Number(major))+ : writer.AddEntity("ELLIPSE", "$", Step242TextWriter.Ref(placementId), Step242TextWriter.Number(major), Step242TextWriter.Number(minor));+ var conicId = serializedSameSense+ ? basisConicId+ : writer.AddEntity("TRIMMED_CURVE", "$", Step242TextWriter.Ref(basisConicId),+ Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(binding.Pcurve.Domain.Start)})"),+ Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(binding.Pcurve.Domain.End)})"),+ Step242TextWriter.BooleanLogical(false), Step242TextWriter.Enum("PARAMETER"));+ var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(conicId), Step242TextWriter.Ref(contextId));+ return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));+ }var samples = binding.Pcurve.Kind switch{PcurveGeometryKind.Line => 2,diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 9f43a1b5..d010475e 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -291,6 +291,7 @@ public static class Step242ImportersurfaceBindingDiagnostics.AddRange(bindSurfaceResult.Diagnostics);var loopData = new List<LoopBuildData>(boundRefsResult.Value.Count);+ var vertexLoopData = new List<VertexLoopBuildData>();foreach (var boundRef in boundRefsResult.Value){var boundEntityResult = document.TryGetEntity(boundRef.TargetId);@@ -336,29 +337,28 @@ public static class Step242Importerreturn KernelResult<BrepBody>.Failure(vertexLoopRefResult.Diagnostics);}- var vertexPointResult = Step242SubsetDecoder.ReadVertexPoint(document, vertexLoopRefResult.Value.TargetId);- if (!vertexPointResult.IsSuccess)+ var vertexResult = EnsureVertex(document, vertexLoopRefResult.Value.TargetId, builder, vertexMap);+ if (!vertexResult.IsSuccess){- return KernelResult<BrepBody>.Failure(vertexPointResult.Diagnostics);+ return KernelResult<BrepBody>.Failure(vertexResult.Diagnostics);}- if (isSphericalFace)- {- // Singular spherical bounds can be represented with VERTEX_LOOP. They do not map- // to edge/coedge topology in the current subset, so they are treated as degenerate trims.- continue;- }-- if (isConicalFace+ var isConeApex = isConicalFace&& bindSurfaceResult.Value.SurfaceGeometry.Cone is ConeSurface cone- && (vertexPointResult.Value - cone.Apex).Length <= PointOnSurfaceEps)- {- // Narrow non-spherical support: singular conical apex trims represented as VERTEX_LOOP.- // These are topologically degenerate and intentionally omitted from edge/coedge topology.- continue;- }-- return Failure("FACE_BOUND loop type 'VERTEX_LOOP' is unsupported for this face in M23 import subset.", $"Entity:{loopEntityResult.Value.Id}");+ && (vertexResult.Value.Point - cone.Apex).Length <= PointOnSurfaceEps;+ if (!isSphericalFace && !isConeApex)+ return Failure("VERTEX_LOOP is only admitted at a supported collapsed surface boundary.", "Importer.Topology.VertexLoopUnsupportedSupport");++ var vertexLoopId = builder.AllocateLoopId();+ vertexLoopData.Add(new VertexLoopBuildData(+ vertexLoopId,+ vertexResult.Value.VertexId,+ vertexResult.Value.Point,+ isDeclaredOuter,+ boundEntity.Id,+ loopEntityResult.Value.Id,+ vertexLoopRefResult.Value.TargetId));+ continue;}if (!string.Equals(loopEntityResult.Value.Name, "EDGE_LOOP", StringComparison.OrdinalIgnoreCase))@@ -385,6 +385,7 @@ public static class Step242Importer}var loopCoedges = new List<Coedge>(orientedEdgeRefsResult.Value.Count);+ var loopPcurveCandidates = new Dictionary<CoedgeId, IReadOnlyList<ImportedStepPcurve>>();var loopSamples = new List<Point3D>();var hasDisconnectedCoedgeGap = false;@@ -446,6 +447,22 @@ public static class Step242ImporterIsReversed: isReversed);loopCoedges.Add(coedge);+ if (surfaceResult.Value.ReferenceId is int sourceSurfaceEntityId)+ {+ var geometryReference = Step242SubsetDecoder.ReadReference(edgeCurveEntityResult.Value, 3, "EDGE_CURVE edge_geometry");+ if (!geometryReference.IsSuccess) return KernelResult<BrepBody>.Failure(geometryReference.Diagnostics);+ var edgeGeometryEntity = document.TryGetEntity(geometryReference.Value.TargetId);+ if (!edgeGeometryEntity.IsSuccess) return KernelResult<BrepBody>.Failure(edgeGeometryEntity.Diagnostics);+ var edgeBinding = bindings.GetEdgeBinding(edgeIdResult.Value);+ var pcurveCandidates = StepPcurveDecoder.DecodeForSurface(+ document,+ edgeGeometryEntity.Value,+ sourceSurfaceEntityId,+ edgeBinding.TrimInterval ?? new ParameterInterval(0d, 1d));+ if (!pcurveCandidates.IsSuccess) return KernelResult<BrepBody>.Failure(pcurveCandidates.Diagnostics);+ if (pcurveCandidates.Value.Count > 0)+ loopPcurveCandidates.Add(coedge.Id, pcurveCandidates.Value);+ }var sampleResult = SampleCoedgePoints(bindings.GetEdgeBinding(edgeIdResult.Value),geometry,@@ -497,7 +514,7 @@ public static class Step242ImporterhasDisconnectedCoedgeGap = true;}- loopData.Add(new LoopBuildData(loopId, loopCoedges, loopSamples, hasDisconnectedCoedgeGap, isDeclaredOuter, boundEntity.Id));+ loopData.Add(new LoopBuildData(loopId, loopCoedges, loopSamples, hasDisconnectedCoedgeGap, isDeclaredOuter, boundEntity.Id, loopPcurveCandidates));}var classifyResult = ClassifyAndNormalizeFaceLoops(faceEntity.Id, loopData, bindSurfaceResult.Value.SurfaceGeometry);@@ -522,8 +539,11 @@ public static class Step242Importerbuilder.AddLoop(new Loop(loop.LoopId, loop.Coedges.Select(c => c.Id).ToList()));coedges.AddRange(loop.Coedges);}+ foreach (var vertexLoop in vertexLoopData)+ builder.AddLoop(Loop.VertexLoop(vertexLoop.LoopId, vertexLoop.VertexId));- var faceLoopIds = classifyResult.Value.Select(l => l.LoopId).ToList();+ var faceLoopIds = classifyResult.Value.Select(l => l.LoopId)+ .Concat(vertexLoopData.Select(loop => loop.LoopId)).ToList();var faceId = builder.AddFace(faceLoopIds);faceIds.Add(faceId);@@ -540,7 +560,15 @@ public static class Step242ImportersurfaceGeometryId,ResolvedFaceOrientation.Aligned,SourceStepEntityId: faceEntity.Id));- var hasDeclaredOuter = classifyResult.Value.Any(loop => loop.IsDeclaredOuter);+ foreach (var loop in classifyResult.Value)+ {+ var pcurveBindings = ResolveLoopPcurveBindings(loop, faceId, surfaceGeometryId, surfaceGeometry, bindings,+ double.Max(1e-6d, document.SourceDistanceAccuracyMillimetres ?? 0d));+ if (!pcurveBindings.IsSuccess) return KernelResult<BrepBody>.Failure(pcurveBindings.Diagnostics);+ foreach (var pcurve in pcurveBindings.Value) bindings.AddPcurveBinding(pcurve);+ }+ var hasDeclaredOuter = classifyResult.Value.Any(loop => loop.IsDeclaredOuter)+ || vertexLoopData.Any(loop => loop.IsDeclaredOuter);for (var loopIndex = 0; loopIndex < classifyResult.Value.Count; loopIndex++){var loop = classifyResult.Value[loopIndex];@@ -549,6 +577,21 @@ public static class Step242Importer: loopIndex == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner;bindings.AddFaceBoundaryRoleBinding(new FaceBoundaryRoleBinding(faceId, loop.LoopId, role, loop.SourceBoundEntityId));}+ foreach (var vertexLoop in vertexLoopData)+ {+ var role = hasDeclaredOuter+ ? vertexLoop.IsDeclaredOuter ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner+ : faceLoopIds[0] == vertexLoop.LoopId ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner;+ bindings.AddFaceBoundaryRoleBinding(new FaceBoundaryRoleBinding(faceId, vertexLoop.LoopId, role, vertexLoop.SourceBoundEntityId));+ bindings.AddVertexLoopParameterBinding(new VertexLoopParameterBinding(+ vertexLoop.LoopId,+ faceId,+ surfaceGeometryId,+ vertexLoop.VertexId,+ TryProjectVertexLoopParameter(vertexLoop.Point, surfaceGeometry),+ vertexLoop.SourceLoopEntityId,+ vertexLoop.SourceVertexEntityId));+ }importedFacePatches.Add(new ImportedFacePatch(faceId,surfaceGeometryId,@@ -621,6 +664,20 @@ public static class Step242Importer.Concat(orientation.Diagnostics));}+ if (orientation.Value.Bindings.PcurveBindings.Any())+ {+ var pcurveTolerance = double.Max(1e-6d, document.SourceDistanceAccuracyMillimetres ?? 0d);+ var pcurveEvidence = BrepPcurveValidator.Validate(orientation.Value, pcurveTolerance);+ if (!pcurveEvidence.IsValid)+ {+ return KernelResult<BrepBody>.Failure(pcurveEvidence.Diagnostics.Select(message => new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ message,+ "Importer.Pcurve.Consistency")).ToArray());+ }+ }+var validation = BrepBindingValidator.Validate(orientation.Value, requireAllEdgeAndFaceBindings: true);if (!validation.IsSuccess){@@ -1095,7 +1152,7 @@ public static class Step242Importerreturn KernelResult<ParameterInterval>.Success(new(start, end));}- private static Step242ParsedEntity? ResolveBSplineCurveEntity(Step242ParsedEntity curveEntity)+ internal static Step242ParsedEntity? ResolveBSplineCurveEntity(Step242ParsedEntity curveEntity){var splineWithKnotsConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "B_SPLINE_CURVE_WITH_KNOTS");if (splineWithKnotsConstructor is null)@@ -3007,6 +3064,130 @@ public static class Step242Importerreturn uv;}+ private static SurfaceParameterPoint? TryProjectVertexLoopParameter(Point3D point, SurfaceGeometry surface)+ {+ IReadOnlyList<UvPoint> projected = surface.Kind switch+ {+ SurfaceGeometryKind.Plane when surface.Plane is PlaneSurface plane => ProjectLoopToPlane([point], plane),+ SurfaceGeometryKind.Cylinder when surface.Cylinder is CylinderSurface cylinder => ProjectLoopToCylinder([point], cylinder),+ SurfaceGeometryKind.Cone when surface.Cone is ConeSurface cone => ProjectLoopToCone([point], cone),+ SurfaceGeometryKind.Sphere when surface.Sphere is SphereSurface sphere => ProjectLoopToSphere([point], sphere),+ SurfaceGeometryKind.Torus when surface.Torus is TorusSurface torus => ProjectLoopToTorus([point], torus),+ _ => []+ };+ return projected.Count == 0 ? null : new SurfaceParameterPoint(projected[0].X, projected[0].Y);+ }++ private static KernelResult<IReadOnlyList<CoedgePcurveBinding>> ResolveLoopPcurveBindings(+ LoopBuildData loop,+ FaceId faceId,+ SurfaceGeometryId surfaceGeometryId,+ SurfaceGeometry surface,+ BrepBindingModel bindings,+ double tolerance)+ {+ if (loop.PcurveCandidates is null || loop.PcurveCandidates.Count == 0)+ return KernelResult<IReadOnlyList<CoedgePcurveBinding>>.Success([]);++ var uses = loop.Coedges.Where(coedge => loop.PcurveCandidates.ContainsKey(coedge.Id)).ToArray();+ var solutions = new List<(double Score, ImportedStepPcurve[] Selection)>();+ var selected = new ImportedStepPcurve[uses.Length];+ var usedByEdge = new Dictionary<EdgeId, HashSet<int>>();++ void Search(int index)+ {+ if (index == uses.Length)+ {+ var score = 0d;+ for (var i = 0; i < uses.Length; i++)+ {+ var current = TraversalEndpoints(uses[i], selected[i]);+ var next = TraversalEndpoints(uses[(i + 1) % uses.Length], selected[(i + 1) % uses.Length]);+ score += RawUvDistance(current.End, next.Start);+ }+ solutions.Add((score, selected.ToArray()));+ return;+ }++ var use = uses[index];+ if (!usedByEdge.TryGetValue(use.EdgeId, out var used)) usedByEdge[use.EdgeId] = used = [];+ foreach (var candidate in loop.PcurveCandidates[use.Id].OrderBy(candidate => candidate.PcurveEntityId))+ {+ if (!used.Add(candidate.PcurveEntityId)) continue;+ selected[index] = candidate;+ Search(index + 1);+ used.Remove(candidate.PcurveEntityId);+ }+ }++ Search(0);+ if (solutions.Count == 0)+ return OrientationFailure<IReadOnlyList<CoedgePcurveBinding>>(+ $"Loop {loop.LoopId.Value} cannot assign distinct pcurves to repeated edge uses.",+ "Importer.Pcurve.SeamAssignment");+ var ordered = solutions.OrderBy(solution => solution.Score).ToArray();+ var best = ordered[0];+ var scale = System.Math.Max(1d, best.Score);+ if (ordered.Length > 1 && System.Math.Abs(ordered[1].Score - best.Score) <= 1e-12d * scale+ && !ordered[1].Selection.Select(candidate => candidate.PcurveEntityId)+ .SequenceEqual(best.Selection.Select(candidate => candidate.PcurveEntityId))+ && !ordered[1].Selection.Zip(best.Selection)+ .All(pair => EquivalentPcurveUse(pair.First, pair.Second)))+ return OrientationFailure<IReadOnlyList<CoedgePcurveBinding>>(+ $"Loop {loop.LoopId.Value} has ambiguous seam-side pcurve assignment; no source flag was used to guess.",+ "Importer.Pcurve.SeamAssignmentAmbiguous");++ var result = new List<CoedgePcurveBinding>(uses.Length);+ for (var i = 0; i < uses.Length; i++)+ {+ var candidate = best.Selection[i];+ result.Add(new CoedgePcurveBinding(+ uses[i].Id,+ faceId,+ surfaceGeometryId,+ candidate.Geometry,+ SameSense: candidate.SameSense,+ candidate.PcurveEntityId,+ candidate.CurveEntityId,+ candidate.CurveType,+ candidate.SurfaceEntityId));+ }+ return KernelResult<IReadOnlyList<CoedgePcurveBinding>>.Success(result);++ (SurfaceParameterPoint Start, SurfaceParameterPoint End) TraversalEndpoints(Coedge use, ImportedStepPcurve candidate)+ {+ var start = candidate.Geometry.Evaluate(candidate.Geometry.Domain.Start);+ var end = candidate.Geometry.Evaluate(candidate.Geometry.Domain.End);+ var edge = bindings.GetEdgeBinding(use.EdgeId);+ return use.IsReversed ^ !edge.OrientedEdgeSense ^ !candidate.SameSense ? (end, start) : (start, end);+ }++ bool EquivalentPcurveUse(ImportedStepPcurve left, ImportedStepPcurve right)+ {+ if (left.SameSense != right.SameSense) return false;+ for (var index = 0; index < 3; index++)+ {+ var fraction = index / 2d;+ var leftParameter = left.Geometry.Domain.Start + (left.Geometry.Domain.End - left.Geometry.Domain.Start) * fraction;+ var rightParameter = right.Geometry.Domain.Start + (right.Geometry.Domain.End - right.Geometry.Domain.Start) * fraction;+ var a = left.Geometry.Evaluate(leftParameter);+ var b = right.Geometry.Evaluate(rightParameter);+ var coordinateScale = System.Math.Max(1d, System.Math.Max(+ System.Math.Max(double.Abs(a.U), double.Abs(a.V)),+ System.Math.Max(double.Abs(b.U), double.Abs(b.V))));+ if (RawUvDistance(a, b) > tolerance * coordinateScale) return false;+ }+ return true;+ }+ }++ private static double RawUvDistance(SurfaceParameterPoint left, SurfaceParameterPoint right)+ {+ var du = left.U - right.U;+ var dv = left.V - right.V;+ return double.Sqrt(du * du + dv * dv);+ }+private static List<UvPoint> ProjectLoopToCylinder(IReadOnlyList<Point3D> samples, CylinderSurface cylinder){var axis = cylinder.Axis.ToVector();@@ -4084,7 +4265,17 @@ public static class Step242ImporterIReadOnlyList<Point3D> Samples,bool HasDisconnectedCoedgeGap = false,bool IsDeclaredOuter = false,- int? SourceBoundEntityId = null);+ int? SourceBoundEntityId = null,+ IReadOnlyDictionary<CoedgeId, IReadOnlyList<ImportedStepPcurve>>? PcurveCandidates = null);++ private sealed record VertexLoopBuildData(+ LoopId LoopId,+ VertexId VertexId,+ Point3D Point,+ bool IsDeclaredOuter,+ int SourceBoundEntityId,+ int SourceLoopEntityId,+ int SourceVertexEntityId);private sealed record PlanarLoopInfo(LoopBuildData Loop, IReadOnlyList<UvPoint> ProjectedPoints, double SignedArea);diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.csindex b98587cf..975d7fb7 100644--- a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs@@ -557,7 +557,7 @@ internal static class Step242SubsetDecoder}}- public static KernelResult<BSpline3Curve> ReadBSplineCurveWithKnots(Step242ParsedDocument document, Step242ParsedEntity splineEntity)+ public static KernelResult<BSpline3Curve> ReadBSplineCurveWithKnots(Step242ParsedDocument document, Step242ParsedEntity splineEntity, bool allowTwoDimensionalControlPoints = false){var degreeResult = ReadIntArgument(splineEntity, 1, "B_SPLINE_CURVE_WITH_KNOTS degree", "Importer.Geometry.BSplineCurve");if (!degreeResult.IsSuccess)@@ -565,7 +565,7 @@ internal static class Step242SubsetDecoderreturn KernelResult<BSpline3Curve>.Failure(degreeResult.Diagnostics);}- var controlPointsResult = ReadCartesianPointReferenceList(document, splineEntity, 2, "B_SPLINE_CURVE_WITH_KNOTS control_points_list");+ var controlPointsResult = ReadCartesianPointReferenceList(document, splineEntity, 2, "B_SPLINE_CURVE_WITH_KNOTS control_points_list", allowTwoDimensionalControlPoints);if (!controlPointsResult.IsSuccess){return KernelResult<BSpline3Curve>.Failure(controlPointsResult.Diagnostics);@@ -1184,7 +1184,8 @@ internal static class Step242SubsetDecoderStep242ParsedDocument document,Step242ParsedEntity ownerEntity,int argumentIndex,- string context)+ string context,+ bool allowTwoDimensional = false){if (argumentIndex < 0 || argumentIndex >= ownerEntity.Arguments.Count){@@ -1210,7 +1211,9 @@ internal static class Step242SubsetDecoderreturn KernelResult<IReadOnlyList<Point3D>>.Failure(pointEntityResult.Diagnostics);}- var pointResult = ReadCartesianPoint(pointEntityResult.Value, context);+ var pointResult = allowTwoDimensional+ ? ReadCartesianPoint2DOr3D(pointEntityResult.Value, context)+ : ReadCartesianPoint(pointEntityResult.Value, context);if (!pointResult.IsSuccess){return KernelResult<IReadOnlyList<Point3D>>.Failure(pointResult.Diagnostics);@@ -1222,6 +1225,22 @@ internal static class Step242SubsetDecoderreturn KernelResult<IReadOnlyList<Point3D>>.Success(points);}+ private static KernelResult<Point3D> ReadCartesianPoint2DOr3D(Step242ParsedEntity pointEntity, string context)+ {+ if (pointEntity.Arguments.Count < 2 || pointEntity.Arguments[1] is not Step242ListValue coordinates+ || coordinates.Items.Count is < 2 or > 3)+ return FailurePoint($"{context}: CARTESIAN_POINT coordinates must be a 2- or 3-item list.", $"Entity:{pointEntity.Id}");+ var x = ReadNumber(coordinates.Items[0], context, pointEntity.Id);+ var y = ReadNumber(coordinates.Items[1], context, pointEntity.Id);+ if (!x.IsSuccess) return KernelResult<Point3D>.Failure(x.Diagnostics);+ if (!y.IsSuccess) return KernelResult<Point3D>.Failure(y.Diagnostics);+ if (coordinates.Items.Count == 2) return KernelResult<Point3D>.Success(new Point3D(x.Value, y.Value, 0d));+ var z = ReadNumber(coordinates.Items[2], context, pointEntity.Id);+ return z.IsSuccess+ ? KernelResult<Point3D>.Success(new Point3D(x.Value, y.Value, z.Value))+ : KernelResult<Point3D>.Failure(z.Diagnostics);+ }+private static KernelResult<IReadOnlyList<IReadOnlyList<Point3D>>> ReadCartesianPointReferenceNet(Step242ParsedDocument document,Step242ParsedEntity ownerEntity,diff --git a/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.cs b/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.csindex c91eb2a6..022efa89 100644--- a/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.cs+++ b/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.cs@@ -139,7 +139,8 @@ internal static class StepFaceOrientationResolver}var isClosedParametricSurface = edgeUses.Count == 0 && faces.Length > 0- && faces.All(faceId => unresolvedBody.Topology.GetFace(faceId).LoopIds.Count == 0+ && faces.All(faceId => unresolvedBody.Topology.GetFace(faceId).LoopIds.All(loopId =>+ unresolvedBody.Topology.GetLoop(loopId).Kind == LoopKind.Vertex)&& unresolvedBody.TryGetFaceSurfaceGeometry(faceId, out var surface)&& surface?.Kind == Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Sphere);var isClosed = (edgeUses.Count > 0 && edgeUses.All(pair => pair.Value.Count == 2)) || isClosedParametricSurface;@@ -291,6 +292,7 @@ internal static class StepFaceOrientationResolverforeach (var edge in body.Bindings.EdgeBindings) bindings.AddEdgeBinding(edge);foreach (var pcurve in body.Bindings.PcurveBindings) bindings.AddPcurveBinding(pcurve);foreach (var role in body.Bindings.FaceBoundaryRoleBindings) bindings.AddFaceBoundaryRoleBinding(role);+ foreach (var vertexLoop in body.Bindings.VertexLoopParameterBindings) bindings.AddVertexLoopParameterBinding(vertexLoop);foreach (var face in body.Bindings.FaceBindings){var orientation = orientations.TryGetValue(face.FaceId, out var aligned)diff --git a/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.cs b/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.csnew file mode 100644index 00000000..599fc1d0--- /dev/null+++ b/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.cs@@ -0,0 +1,232 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;++namespace Aetheris.Kernel.Core.Step242;++internal sealed record ImportedStepPcurve(+ PcurveGeometry Geometry,+ bool SameSense,+ int PcurveEntityId,+ int CurveEntityId,+ string CurveType,+ int SurfaceEntityId);++internal static class StepPcurveDecoder+{+ internal static KernelResult<IReadOnlyList<ImportedStepPcurve>> DecodeForSurface(+ Step242ParsedDocument document,+ Step242ParsedEntity edgeGeometryEntity,+ int surfaceEntityId,+ ParameterInterval edgeDomain)+ {+ var surfaceCurve = Step242SubsetDecoder.TryGetConstructor(edgeGeometryEntity.Instance, "SURFACE_CURVE")+ ?? Step242SubsetDecoder.TryGetConstructor(edgeGeometryEntity.Instance, "SEAM_CURVE");+ if (surfaceCurve is null)+ return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Success([]);+ if (surfaceCurve.Arguments.ElementAtOrDefault(2) is not Step242ListValue associated)+ return Failure<IReadOnlyList<ImportedStepPcurve>>("SURFACE_CURVE/SEAM_CURVE associated_geometry must be a list.", "Importer.Pcurve.AssociatedGeometry");++ var result = new List<ImportedStepPcurve>();+ foreach (var item in associated.Items)+ {+ if (item is not Step242EntityReference pcurveReference)+ return Failure<IReadOnlyList<ImportedStepPcurve>>("Associated pcurve must be an entity reference.", "Importer.Pcurve.AssociatedGeometry");+ var pcurveResult = document.TryGetEntity(pcurveReference.TargetId, "PCURVE");+ if (!pcurveResult.IsSuccess) return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Failure(pcurveResult.Diagnostics);+ var pcurve = pcurveResult.Value;+ if (pcurve.Arguments.ElementAtOrDefault(1) is not Step242EntityReference supportReference+ || pcurve.Arguments.ElementAtOrDefault(2) is not Step242EntityReference representationReference)+ return Failure<IReadOnlyList<ImportedStepPcurve>>("PCURVE must reference its support and definitional representation.", "Importer.Pcurve.Binding");+ if (supportReference.TargetId != surfaceEntityId) continue;++ var representationResult = document.TryGetEntity(representationReference.TargetId, "DEFINITIONAL_REPRESENTATION");+ if (!representationResult.IsSuccess) return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Failure(representationResult.Diagnostics);+ if (representationResult.Value.Arguments.ElementAtOrDefault(1) is not Step242ListValue items || items.Items.Count != 1+ || items.Items[0] is not Step242EntityReference curveReference)+ return Failure<IReadOnlyList<ImportedStepPcurve>>("PCURVE definitional representation must contain exactly one curve.", "Importer.Pcurve.DefinitionalRepresentation");+ var curveResult = document.TryGetEntity(curveReference.TargetId);+ if (!curveResult.IsSuccess) return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Failure(curveResult.Diagnostics);+ var geometryResult = DecodeGeometry(document, curveResult.Value, edgeDomain);+ if (!geometryResult.IsSuccess) return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Failure(geometryResult.Diagnostics);+ result.Add(new ImportedStepPcurve(geometryResult.Value.Geometry, geometryResult.Value.SameSense,+ pcurve.Id, curveResult.Value.Id, DescribeCurveType(curveResult.Value), supportReference.TargetId));+ }+ return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Success(result);+ }++ private static KernelResult<DecodedPcurveGeometry> DecodeGeometry(Step242ParsedDocument document, Step242ParsedEntity source, ParameterInterval fallbackDomain)+ {+ var domain = fallbackDomain;+ var sameSense = true;+ var trimmed = Step242SubsetDecoder.TryGetConstructor(source.Instance, "TRIMMED_CURVE");+ if (trimmed is not null)+ {+ if (trimmed.Arguments.ElementAtOrDefault(1) is not Step242EntityReference basis+ || !TryReadTrim(trimmed.Arguments.ElementAtOrDefault(2), out var start)+ || !TryReadTrim(trimmed.Arguments.ElementAtOrDefault(3), out var end))+ return Failure<DecodedPcurveGeometry>("Pcurve TRIMMED_CURVE requires parameter trims and a basis curve.", "Importer.Pcurve.TrimmedCurve");+ if (trimmed.Arguments.ElementAtOrDefault(4) is not Step242BooleanValue senseAgreement)+ return Failure<DecodedPcurveGeometry>("Pcurve TRIMMED_CURVE requires an explicit sense_agreement value.", "Importer.Pcurve.TrimmedCurve");+ var basisResult = document.TryGetEntity(basis.TargetId);+ if (!basisResult.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(basisResult.Diagnostics);+ source = basisResult.Value;+ domain = new ParameterInterval(double.Min(start, end), double.Max(start, end));+ sameSense = senseAgreement.Value == (end >= start);+ }++ if (Step242SubsetDecoder.TryGetConstructor(source.Instance, "LINE") is { } line)+ {+ if (line.Arguments.ElementAtOrDefault(1) is not Step242EntityReference originReference+ || line.Arguments.ElementAtOrDefault(2) is not Step242EntityReference vectorReference)+ return Failure<DecodedPcurveGeometry>("Pcurve LINE requires point and vector references.", "Importer.Pcurve.Line");+ var origin = ReadUvPoint(document, originReference.TargetId);+ var vector = ReadUvVector(document, vectorReference.TargetId);+ if (!origin.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(origin.Diagnostics);+ if (!vector.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(vector.Diagnostics);+ var start = new SurfaceParameterPoint(origin.Value.U + vector.Value.U * domain.Start, origin.Value.V + vector.Value.V * domain.Start);+ var end = new SurfaceParameterPoint(origin.Value.U + vector.Value.U * domain.End, origin.Value.V + vector.Value.V * domain.End);+ return Success(PcurveGeometry.Line(domain, start, end));+ }++ if (Step242SubsetDecoder.TryGetConstructor(source.Instance, "POLYLINE") is { } polyline)+ {+ if (polyline.Arguments.ElementAtOrDefault(1) is not Step242ListValue pointReferences || pointReferences.Items.Count < 2)+ return Failure<DecodedPcurveGeometry>("Pcurve POLYLINE requires at least two points.", "Importer.Pcurve.Polyline");+ var points = new List<SurfaceParameterPoint>(pointReferences.Items.Count);+ foreach (var value in pointReferences.Items)+ {+ if (value is not Step242EntityReference pointReference)+ return Failure<DecodedPcurveGeometry>("Pcurve POLYLINE point must be a reference.", "Importer.Pcurve.Polyline");+ var point = ReadUvPoint(document, pointReference.TargetId);+ if (!point.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(point.Diagnostics);+ points.Add(point.Value);+ }+ return Success(PcurveGeometry.Polyline(domain, points));+ }++ if (Step242SubsetDecoder.TryGetConstructor(source.Instance, "CIRCLE") is { } circle)+ {+ var conic = DecodeConic(document, circle, domain, circle: true);+ return conic.IsSuccess ? Success(conic.Value) : KernelResult<DecodedPcurveGeometry>.Failure(conic.Diagnostics);+ }+ if (Step242SubsetDecoder.TryGetConstructor(source.Instance, "ELLIPSE") is { } ellipse)+ {+ var conic = DecodeConic(document, ellipse, domain, circle: false);+ return conic.IsSuccess ? Success(conic.Value) : KernelResult<DecodedPcurveGeometry>.Failure(conic.Diagnostics);+ }++ var splineEntity = Step242Importer.ResolveBSplineCurveEntity(source);+ if (splineEntity is not null)+ {+ var spline = Step242SubsetDecoder.ReadBSplineCurveWithKnots(document, splineEntity, allowTwoDimensionalControlPoints: true);+ if (!spline.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(spline.Diagnostics);+ var splineDomain = new ParameterInterval(+ System.Math.Max(domain.Start, spline.Value.DomainStart),+ System.Math.Min(domain.End, spline.Value.DomainEnd));+ if (fallbackDomain.Equals(domain)) splineDomain = new ParameterInterval(spline.Value.DomainStart, spline.Value.DomainEnd);+ var rational = Step242SubsetDecoder.TryGetConstructor(source.Instance, "RATIONAL_B_SPLINE_CURVE");+ if (rational is null)+ return Success(PcurveGeometry.Polynomial(splineDomain, spline.Value));+ var weights = Step242SubsetDecoder.ReadRationalBSplineCurveWeights(new Step242ParsedEntity(source.Id, new Step242SimpleEntityInstance(rational)));+ if (!weights.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(weights.Diagnostics);+ try { return Success(PcurveGeometry.RationalPolynomial(splineDomain, spline.Value, weights.Value)); }+ catch (ArgumentException exception) { return Failure<DecodedPcurveGeometry>(exception.Message, "Importer.Pcurve.RationalBSpline"); }+ }++ return Failure<DecodedPcurveGeometry>($"Unsupported pcurve form '{DescribeCurveType(source)}'.", "Importer.Pcurve.UnsupportedCurve");++ KernelResult<DecodedPcurveGeometry> Success(PcurveGeometry geometry) =>+ KernelResult<DecodedPcurveGeometry>.Success(new(geometry, sameSense));+ }++ private static KernelResult<PcurveGeometry> DecodeConic(Step242ParsedDocument document, Step242EntityConstructor conic, ParameterInterval domain, bool circle)+ {+ if (conic.Arguments.ElementAtOrDefault(1) is not Step242EntityReference placementReference+ || conic.Arguments.ElementAtOrDefault(2) is not Step242NumberValue firstRadius)+ return Failure<PcurveGeometry>("Pcurve conic requires a 2D placement and radius.", "Importer.Pcurve.Conic");+ var placementResult = document.TryGetEntity(placementReference.TargetId, "AXIS2_PLACEMENT_2D");+ if (!placementResult.IsSuccess) return KernelResult<PcurveGeometry>.Failure(placementResult.Diagnostics);+ if (placementResult.Value.Arguments.ElementAtOrDefault(1) is not Step242EntityReference locationReference)+ return Failure<PcurveGeometry>("AXIS2_PLACEMENT_2D requires a location.", "Importer.Pcurve.Conic");+ var center = ReadUvPoint(document, locationReference.TargetId);+ if (!center.IsSuccess) return KernelResult<PcurveGeometry>.Failure(center.Diagnostics);+ var axis = new SurfaceParameterPoint(1d, 0d);+ if (placementResult.Value.Arguments.ElementAtOrDefault(2) is Step242EntityReference axisReference)+ {+ var direction = ReadUvDirection(document, axisReference.TargetId);+ if (!direction.IsSuccess) return KernelResult<PcurveGeometry>.Failure(direction.Diagnostics);+ axis = direction.Value;+ }+ var perpendicular = new SurfaceParameterPoint(-axis.V, axis.U);+ var secondRadius = circle ? firstRadius.Value+ : conic.Arguments.ElementAtOrDefault(3) is Step242NumberValue minor ? minor.Value : double.NaN;+ if (!double.IsFinite(secondRadius) || firstRadius.Value <= 0d || secondRadius <= 0d)+ return Failure<PcurveGeometry>("Pcurve conic radii must be finite and positive.", "Importer.Pcurve.Conic");+ // Use the coefficient form for circles too: unlike the compact Circle representation it+ // retains AXIS2_PLACEMENT_2D rotation exactly.+ return KernelResult<PcurveGeometry>.Success(PcurveGeometry.Ellipse(domain, center.Value,+ new SurfaceParameterPoint(axis.U * firstRadius.Value, axis.V * firstRadius.Value),+ new SurfaceParameterPoint(perpendicular.U * secondRadius, perpendicular.V * secondRadius)));+ }++ private static KernelResult<SurfaceParameterPoint> ReadUvPoint(Step242ParsedDocument document, int entityId)+ {+ var entity = document.TryGetEntity(entityId, "CARTESIAN_POINT");+ if (!entity.IsSuccess) return KernelResult<SurfaceParameterPoint>.Failure(entity.Diagnostics);+ if (entity.Value.Arguments.ElementAtOrDefault(1) is not Step242ListValue coordinates || coordinates.Items.Count != 2+ || coordinates.Items[0] is not Step242NumberValue u || coordinates.Items[1] is not Step242NumberValue v)+ return Failure<SurfaceParameterPoint>("Pcurve CARTESIAN_POINT must contain exactly two coordinates.", "Importer.Pcurve.Point2D");+ return KernelResult<SurfaceParameterPoint>.Success(new SurfaceParameterPoint(u.Value, v.Value));+ }++ private static KernelResult<SurfaceParameterPoint> ReadUvVector(Step242ParsedDocument document, int entityId)+ {+ var vector = document.TryGetEntity(entityId, "VECTOR");+ if (!vector.IsSuccess) return KernelResult<SurfaceParameterPoint>.Failure(vector.Diagnostics);+ if (vector.Value.Arguments.ElementAtOrDefault(1) is not Step242EntityReference directionReference+ || vector.Value.Arguments.ElementAtOrDefault(2) is not Step242NumberValue magnitude)+ return Failure<SurfaceParameterPoint>("Pcurve VECTOR requires direction and magnitude.", "Importer.Pcurve.Vector2D");+ var direction = ReadUvDirection(document, directionReference.TargetId);+ if (!direction.IsSuccess) return KernelResult<SurfaceParameterPoint>.Failure(direction.Diagnostics);+ return KernelResult<SurfaceParameterPoint>.Success(new(direction.Value.U * magnitude.Value, direction.Value.V * magnitude.Value));+ }++ private static KernelResult<SurfaceParameterPoint> ReadUvDirection(Step242ParsedDocument document, int entityId)+ {+ var entity = document.TryGetEntity(entityId, "DIRECTION");+ if (!entity.IsSuccess) return KernelResult<SurfaceParameterPoint>.Failure(entity.Diagnostics);+ if (entity.Value.Arguments.ElementAtOrDefault(1) is not Step242ListValue coordinates || coordinates.Items.Count != 2+ || coordinates.Items[0] is not Step242NumberValue u || coordinates.Items[1] is not Step242NumberValue v)+ return Failure<SurfaceParameterPoint>("Pcurve DIRECTION must contain exactly two ratios.", "Importer.Pcurve.Direction2D");+ var length = double.Sqrt(u.Value * u.Value + v.Value * v.Value);+ if (!double.IsFinite(length) || length <= 1e-15d)+ return Failure<SurfaceParameterPoint>("Pcurve DIRECTION is degenerate.", "Importer.Pcurve.Direction2D");+ return KernelResult<SurfaceParameterPoint>.Success(new(u.Value / length, v.Value / length));+ }++ private static bool TryReadTrim(Step242Value? value, out double parameter)+ {+ parameter = default;+ if (value is not Step242ListValue { Items.Count: 1 } list) return false;+ var item = list.Items[0];+ if (item is Step242TypedValue { Arguments.Count: 1 } typed) item = typed.Arguments[0];+ if (item is not Step242NumberValue number || !double.IsFinite(number.Value)) return false;+ parameter = number.Value;+ return true;+ }++ private static string DescribeCurveType(Step242ParsedEntity entity) => entity.Instance switch+ {+ Step242SimpleEntityInstance simple => simple.Constructor.Name,+ Step242ComplexEntityInstance complex => string.Join("+", complex.Constructors.Select(constructor => constructor.Name)),+ _ => entity.Name+ };++ private static KernelResult<T> Failure<T>(string message, string source) => KernelResult<T>.Failure([+ new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source)]);++ private readonly record struct DecodedPcurveGeometry(PcurveGeometry Geometry, bool SameSense);+}diff --git a/Aetheris.Kernel.Core/Topology/TopologyEntities.cs b/Aetheris.Kernel.Core/Topology/TopologyEntities.csindex 8b802228..bc30381e 100644--- a/Aetheris.Kernel.Core/Topology/TopologyEntities.cs+++ b/Aetheris.Kernel.Core/Topology/TopologyEntities.cs@@ -24,10 +24,21 @@ public sealed record Coedge(CoedgeId PrevCoedgeId,bool IsReversed);+public enum LoopKind { Edge, Vertex }+/// <summary>-/// Topology-only loop that owns ordered coedges.+/// Topology-only boundary loop. An edge loop owns ordered coedges; a vertex loop+/// owns one explicit vertex at a collapsed support boundary./// </summary>-public sealed record Loop(LoopId Id, IReadOnlyList<CoedgeId> CoedgeIds);+public sealed record Loop(+ LoopId Id,+ IReadOnlyList<CoedgeId> CoedgeIds,+ VertexId? VertexLoopVertexId = null)+{+ public LoopKind Kind => VertexLoopVertexId is null ? LoopKind.Edge : LoopKind.Vertex;++ public static Loop VertexLoop(LoopId id, VertexId vertexId) => new(id, [], vertexId);+}/// <summary>/// Topology-only face that owns loops.diff --git a/Aetheris.Kernel.Core/Topology/TopologyGraphValidator.cs b/Aetheris.Kernel.Core/Topology/TopologyGraphValidator.csindex e46cbd13..8caaeab2 100644--- a/Aetheris.Kernel.Core/Topology/TopologyGraphValidator.cs+++ b/Aetheris.Kernel.Core/Topology/TopologyGraphValidator.cs@@ -29,6 +29,15 @@ public static class TopologyGraphValidatorforeach (var loop in model.Loops){+ if (loop.Kind == LoopKind.Vertex)+ {+ if (loop.CoedgeIds.Count != 0)+ diagnostics.Add(Error($"Vertex loop {loop.Id.Value} must not reference coedges."));+ if (loop.VertexLoopVertexId is not VertexId vertexId || !model.TryGetVertex(vertexId, out _))+ diagnostics.Add(Error($"Vertex loop {loop.Id.Value} references a missing vertex."));+ continue;+ }+if (loop.CoedgeIds.Count == 0){diagnostics.Add(Error($"Loop {loop.Id.Value} does not reference any coedges."));diff --git a/docs/development/architecture/face-orientation-authority.md b/docs/development/architecture/face-orientation-authority.mdindex 077c7474..eda4584f 100644--- a/docs/development/architecture/face-orientation-authority.md+++ b/docs/development/architecture/face-orientation-authority.md@@ -23,6 +23,6 @@ X1B makes boundary role and periodicity explicit. `FaceBoundaryRoleBinding` recoSTEP export chooses its boundary serialization route through a bounded JudgmentEngine policy: complete explicit roles win, authored order is a fallback only when role evidence is absent, and malformed partial evidence is rejected. The numerical winding calculation itself is deterministic and is not utility-scored.-Current limitation: the topology model can bind a pcurve to each coedge use, but STEP `SURFACE_CURVE`/`SEAM_CURVE` import does not yet populate those bindings, and singular pole/apex `VERTEX_LOOP`s are not yet materialized as explicit loop topology. Therefore X1B does not claim general pcurve or degenerate-boundary acceptance beyond the qualified corpus paths.+X1C closes the representation gap without changing this authority. STEP `SURFACE_CURVE` and `SEAM_CURVE` associations populate face-local coedge pcurve bindings, including distinct UV uses of one seam edge. STEP `VERTEX_LOOP` imports as a distinct `LoopKind.Vertex` with the real vertex identity and an optional support-parameter binding; it is never expanded into a synthetic edge. Pcurve equivalence, seam assignment, periodic closure, and vertex-loop existence remain deterministic facts. They do not consult source `same_sense` and do not enter JudgmentEngine.This boundary does not alter stable face IDs, source STEP entity provenance, semantic PMI associations, support surfaces, trims, or pcurve parameterization.diff --git a/docs/development/architecture/step-pcurves-and-degenerate-boundaries.md b/docs/development/architecture/step-pcurves-and-degenerate-boundaries.mdnew file mode 100644index 00000000..9f48c11d--- /dev/null+++ b/docs/development/architecture/step-pcurves-and-degenerate-boundaries.md@@ -0,0 +1,29 @@+# STEP Pcurves and Degenerate Boundaries++STEP face boundaries carry two related facts. The 3D `EDGE_CURVE` is the model-space locus; a face-local `PCURVE` is that edge use in the support surface's parameter space. Aetheris preserves both. A `CoedgePcurveBinding` binds a UV curve to a specific coedge, face, and support-surface identity, so repeated uses of one edge are not collapsed.++## Import path++`SURFACE_CURVE` and `SEAM_CURVE` associated geometry is traversed through `PCURVE` and `DEFINITIONAL_REPRESENTATION`. The bounded decoder accepts:++- `LINE` and `POLYLINE`+- `CIRCLE` and `ELLIPSE`, including the 2D placement axis+- `B_SPLINE_CURVE_WITH_KNOTS` and its ordinary `B_SPLINE_CURVE` constructor data+- complex `RATIONAL_B_SPLINE_CURVE`, retaining degree, controls, weights, knots, and domain+- parameter-trimmed `TRIMMED_CURVE`, retaining its interval and traversal sense++An unrepresentable associated curve fails with `Importer.Pcurve.UnsupportedCurve`; it is not silently discarded. Cartesian-point trims and `COMPOSITE_CURVE` remain outside this bounded decoder. No encountered qualified fixture requires either form.++Pcurve coordinates are UV values and are never length-normalized. Imported bindings retain the STEP pcurve, source curve, source support entity IDs, and original curve type. `BrepPcurveValidator` separately compares the surface-evaluated UV curve with the 3D edge at the import tolerance and checks loop closure modulo `SurfacePeriodicity`. Sub-tolerance drift is accepted; material disagreement is diagnostic failure.++For a periodic seam, the same 3D edge can have two coedge uses and two pcurves on different periodic sides. Import assigns distinct pcurve entity identities to repeated edge uses and minimizes loop-local raw UV discontinuity. Equal competing assignments are rejected as ambiguous. Source face `same_sense` is never a tie-breaker.++## Degenerate loops++`LoopKind.Edge` owns ordered coedge uses. `LoopKind.Vertex` owns exactly one real vertex and no coedges. `VertexLoopParameterBinding` relates that loop and vertex to its owning face, support surface, optional UV location, and STEP provenance.++The STEP importer admits a `VERTEX_LOOP` only at a supported collapsed boundary (currently a sphere pole or cone apex within the import tolerance). Other uses fail explicitly. Export writes the actual `VERTEX_LOOP` and `VERTEX_POINT`; it never creates a zero-radius circle, epsilon line, or synthetic edge. Display and mass consumers treat the zero-dimensional boundary as topology rather than as a trim curve.++## Export policy boundary++Pcurve encoding and vertex-loop serialization are deterministic. JudgmentEngine remains restricted to the existing bounded choice among admissible face-boundary serialization policies: complete explicit boundary roles, authored-order fallback when roles are absent, or rejection of partial/contradictory evidence. It does not decide equivalence, closure, winding, seam side, or whether a vertex loop exists.diff --git a/docs/release/STEP-ORIENTATION-X1C.md b/docs/release/STEP-ORIENTATION-X1C.mdnew file mode 100644index 00000000..afc9f918--- /dev/null+++ b/docs/release/STEP-ORIENTATION-X1C.md@@ -0,0 +1,52 @@+# STEP-ORIENTATION-X1C++## Executive verdict++X1C preserves the STEP boundary forms that previously fell through the X1/X1B qualification boundary: face-local pcurves and explicit pole/apex `VERTEX_LOOP` topology. The derived face-orientation model is unchanged, and source `ADVANCED_FACE.same_sense` remains diagnostic provenance only.++## Pcurve coverage++| STEP 2D form | Parsed | First-class binding | Deliberate export | Round-trip evidence |+| --- | --- | --- | --- | --- |+| `LINE` | yes | yes | exact `LINE` | cylinder seam fixture |+| `POLYLINE` | yes | yes | exact points | planar plateau corpus |+| `CIRCLE` | yes | yes, placement retained | exact conic | cylindrical solid cap fixture |+| `ELLIPSE` | yes | yes, coefficient frame retained | exact conic for STEP-admissible placement | shared conic path |+| `B_SPLINE_CURVE_WITH_KNOTS` | yes | yes | exact degree/controls/knots | planar plateau corpus |+| `RATIONAL_B_SPLINE_CURVE` | yes | yes | exact weights plus spline data | hostile seam fixture |+| parameter `TRIMMED_CURVE` | yes | yes, interval and sense retained | represented basis/domain | decoder coverage and corpus |+| `COMPOSITE_CURVE` | no | explicit unsupported diagnostic | no | not encountered in qualified fixtures |++The planar plateau witness imports and re-imports 144 pcurve uses. The seam witness retains two distinct UV uses of one 3D edge at `U=0` and `U=2*pi`; they remain periodic equivalents without being deduplicated. A one-period shift, reversed edge use, rational weights, and sub-tolerance drift are covered by focused tests.++Unsupported associated curve forms fail with `Importer.Pcurve.UnsupportedCurve`. Material pcurve/3D disagreement is rejected by `BrepPcurveValidator`; drift within the import tolerance remains admissible.++## Vertex-loop coverage++`LoopKind.Vertex` stores one actual vertex and zero coedges. `VertexLoopParameterBinding` retains its face, support, UV location when available, and source STEP IDs. The handcrafted spherical pole round-trips as one real `VERTEX_LOOP` with zero edges. STC-06 imports and re-imports its two cone-apex vertex loops without fake geometry; its shell remains explicitly ambiguous because the new topology does not supply sufficient global orientation evidence.++## Authority and policy++No orientation repair moved into pcurve ingestion. `same_sense` is still source evidence only and has zero downstream orientation authority. Period arithmetic reuses `SurfacePeriodicity`; seam assignment and vertex-loop admission are deterministic. JudgmentEngine remains appropriate only for the existing multiple-admissible-encoding export policy, where explicit boundary roles outrank authored-order fallback and partial or contradictory evidence is rejected.++## Inspection++Normal `aetheris analyze` output now adds a concise boundary summary: edge-loop count, vertex-loop count, pcurve count, seam-pair count, and pcurve source types. This makes preserved topology visible without expanding the default report into entity-level noise.++## Qualification++X1C is **Accepted** against its bounded scope. Validation on 2026-09-22 produced:++| Check | Result |+| --- | --- |+| solution build | passed, 0 errors (7 existing WebAssembly/trimming warnings) |+| focused X1C pcurve/vertex-loop tests | 6/6 passed |+| STEP round-trip corpus | 17/17 passed |+| deterministic NIST aggregate snapshot | passed after the intentional canonical snapshot update |+| NIST display corpus | 18/18 passed |+| display-orientation corpus | 16/16 passed |+| CLI suite | 445/445 passed in 54 seconds |++The CLI unsupported-curve detail test now imports STC-06 once to select a representative edge and invokes the public CLI once. It no longer performs 310 complete imports; the focused test completes in about six seconds while retaining the externally visible contract assertion.++A serialized solution-level invocation still lets xUnit parallelize expensive corpus cases within `Aetheris.Kernel.Core.Tests`. Under that contention, display/volume tests exceeded their own bounded execution budgets and the aggregate run was stopped after the failure mode was isolated. The same affected suites pass independently with the counts above; this report therefore does not claim a green all-at-once aggregate.diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.jsonindex a067f8b2..13640e74 100644--- a/testdata/step242/manifests/nist.v0.report.json+++ b/testdata/step242/manifests/nist.v0.report.json@@ -77,7 +77,7 @@"edges": 1110,"faces": 484},- "canonicalSha256": "b1e589dfefb511aced044ed7d0baf7cca95662a55771841b30ad5473702871d8"+ "canonicalSha256": "1aa507053dd8f45bc2509c9a82a7873e4b116b8d23497c0c0ca1ea4f89c6f7f2"},{"fileId": "testdata_step242_nist_CTC_nist_ctc_05_asme1_ap242-e1",@@ -93,11 +93,11 @@"diagnosticCount": 4,"exceptionEscaped": false,"topologyCounts": {- "vertices": 239,+ "vertices": 249,"edges": 331,"faces": 156},- "canonicalSha256": "863e3de993d60f8dbdd002575807b1326288b55b8a9bebf8228b486f82ef4e8a"+ "canonicalSha256": "158362ba6bcc92e55009ea7a6f15c2fcd45d3dd2ab5b59f8c95bffc6928fce58"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_06_asme1_ap242-e2",@@ -177,7 +177,7 @@"edges": 616,"faces": 247},- "canonicalSha256": "c4d4ac0e23e63b25ef56a63e1e0998d2ddfc3ffe90ba84b3629dc8a6fbee589f"+ "canonicalSha256": "b7713bfdf83da13dc647e8953a111e6810182aa17e9ba7453106229b1491f71a"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_09_asme1_ap242-e1",@@ -217,7 +217,7 @@"edges": 813,"faces": 268},- "canonicalSha256": "48555040f7a76175729ba8cbdaebc258d8e78d77423305548a2e8821579a9ae1"+ "canonicalSha256": "94c4d8ecfffdd8c04a31e25cc0ccd0e9b5e4e4f4a218603c95af7d5ac849f6e5"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_11_asme1_ap242-e2",@@ -237,7 +237,7 @@"edges": 104,"faces": 42},- "canonicalSha256": "a90e0b92aeedf89bbcaac0a3f585f34f1027e39a7405c0085ace7bd23d167681"+ "canonicalSha256": "687e423472a6e686883b199e2a2d1f630f360d0b6199cc09c438cd3c07f98607"},{"fileId": "testdata_step242_nist_STC_nist_stc_06_asme1_ap242-e3",@@ -253,11 +253,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 225,+ "vertices": 227,"edges": 310,"faces": 144},- "canonicalSha256": "780c836ee73b5ea5ccb83b2c6cf63e0166fe7a71de823471ccce0c3d552c5286"+ "canonicalSha256": "dac42cc7310c9fa2635e77c48b70d83b82cd30cfd3a209648a86539c1b49a665"},{"fileId": "testdata_step242_nist_STC_nist_stc_07_asme1_ap242-e3",@@ -333,10 +333,10 @@"diagnosticCount": 1,"exceptionEscaped": false,"topologyCounts": {- "vertices": 368,+ "vertices": 376,"edges": 551,"faces": 256},- "canonicalSha256": "873f87c65323ffd8e1c0258b9e3d47780935e655461a8498c9c6bb78d9ca25ad"+ "canonicalSha256": "79e1aa1d8d93c2c6b03c8014950d36c3db508515823488208c7551bf8133a1dd"}]