Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Import;
using Aetheris.Kernel.Core.Judgment;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
using System.Threading;
namespace Aetheris.Kernel.Core.Step242;
public static class Step242Importer
{
/// <summary>
/// Imports every exact rigid B-rep root without assigning part or assembly semantics.
/// This is the inspection boundary for compound serialization; <see cref="ImportBody(string)"/>
/// deliberately remains strict about its single-part contract.
/// </summary>
public static KernelResult<IReadOnlyList<Step242RigidRootBody>> ImportRigidRoots(string stepText)
{
ArgumentNullException.ThrowIfNull(stepText);
var parsed = Step242SubsetParser.Parse(stepText);
if (!parsed.IsSuccess || parsed.Value is null)
return KernelResult<IReadOnlyList<Step242RigidRootBody>>.Failure(parsed.Diagnostics);
var classification = Step242RigidRootClassifier.Classify(parsed.Value);
if (classification.Kind == Step242RigidRootClassificationKind.MissingRigidRoot)
return Step242ImportSharedUtilities.NotImplementedFailure<IReadOnlyList<Step242RigidRootBody>>(
"Missing MANIFOLD_SOLID_BREP or BREP_WITH_VOIDS root entity.",
"Importer.TopologyRoot");
var roots = new List<Step242RigidRootBody>(classification.RigidRoots.Count);
var diagnostics = new List<KernelDiagnostic>();
foreach (var root in classification.RigidRoots.OrderBy(entity => entity.Id))
{
var imported = ImportExactBrepCore(parsed.Value, root.Id, includeOrphanPlanarFaces: classification.RigidRoots.Count == 1);
diagnostics.AddRange(imported.Diagnostics);
if (!imported.IsSuccess || imported.Value is null)
return KernelResult<IReadOnlyList<Step242RigidRootBody>>.Failure(diagnostics);
roots.Add(new Step242RigidRootBody(root.Id, root.Name, imported.Value));
}
return KernelResult<IReadOnlyList<Step242RigidRootBody>>.Success(roots, diagnostics);
}
private const double AreaEps = 1e-8d;
private const double PointOnSurfaceEps = 1e-5d;
private const double TinyCoedgeGapSnapEps = 2.5e-5d;
private const double AngleUnwrapEps = 1e-8d;
private const double ContainmentEps = 1e-8d;
private const string PlanarCrossingInsideRecoveryCandidate = "planar_crossing_inside_recover_as_inner";
private const string PlanarNearCoincidentRecoveryCandidate = "planar_near_coincident_declared_inner";
private const string PlanarCrossingInsideRejectCandidate = "planar_crossing_inside_reject";
private static readonly AsyncLocal<ICollection<LoopRoleCircularSamplingDiagnostic>?> CircularSamplingDiagnosticsSink = new();
private static readonly AsyncLocal<ICollection<LoopRoleCoedgeGapDiagnostic>?> CoedgeGapDiagnosticsSink = new();
private static readonly AsyncLocal<ICollection<LoopRoleCylinderProjectionDiagnostic>?> CylinderProjectionDiagnosticsSink = new();
private static readonly AsyncLocal<ICollection<LoopRoleTorusProjectionDiagnostic>?> TorusProjectionDiagnosticsSink = new();
private static readonly AsyncLocal<ICollection<PlanarMultiBoundJudgmentDiagnostic>?> PlanarMultiBoundJudgmentDiagnosticsSink = new();
private static readonly AsyncLocal<bool> PreserveRationalSurfacesFlag = new();
/// <summary>
/// Debug escape hatch: keeps rational surfaces exactly as the file stated them, instead of reducing the ones no
/// analytic primitive covers to the non-rational form the kernel otherwise guarantees. Export writes whatever the
/// body holds, so this is also what puts RATIONAL_B_SPLINE_SURFACE back into an Aetheris file. It exists to give a
/// degenerate legacy surface somewhere to land while it is being diagnosed, and is off by default.
/// </summary>
public static IDisposable PreserveRationalSurfaces()
{
var previous = PreserveRationalSurfacesFlag.Value;
PreserveRationalSurfacesFlag.Value = true;
return new PreserveRationalSurfacesScope(previous);
}
internal static bool RationalSurfacesArePreserved => PreserveRationalSurfacesFlag.Value;
public static IDisposable CaptureLoopRoleCircularSamplingDiagnostics(ICollection<LoopRoleCircularSamplingDiagnostic> sink)
{
var previous = CircularSamplingDiagnosticsSink.Value;
CircularSamplingDiagnosticsSink.Value = sink;
return new CircularSamplingDiagnosticsScope(previous);
}
public static IDisposable CaptureLoopRoleCoedgeGapDiagnostics(ICollection<LoopRoleCoedgeGapDiagnostic> sink)
{
var previous = CoedgeGapDiagnosticsSink.Value;
CoedgeGapDiagnosticsSink.Value = sink;
return new CoedgeGapDiagnosticsScope(previous);
}
public static IDisposable CaptureLoopRoleCylinderProjectionDiagnostics(ICollection<LoopRoleCylinderProjectionDiagnostic> sink)
{
var previous = CylinderProjectionDiagnosticsSink.Value;
CylinderProjectionDiagnosticsSink.Value = sink;
return new CylinderProjectionDiagnosticsScope(previous);
}
public static IDisposable CaptureLoopRoleTorusProjectionDiagnostics(ICollection<LoopRoleTorusProjectionDiagnostic> sink)
{
var previous = TorusProjectionDiagnosticsSink.Value;
TorusProjectionDiagnosticsSink.Value = sink;
return new TorusProjectionDiagnosticsScope(previous);
}
public static IDisposable CapturePlanarMultiBoundJudgmentDiagnostics(ICollection<PlanarMultiBoundJudgmentDiagnostic> sink)
{
var previous = PlanarMultiBoundJudgmentDiagnosticsSink.Value;
PlanarMultiBoundJudgmentDiagnosticsSink.Value = sink;
return new PlanarMultiBoundJudgmentDiagnosticsScope(previous);
}
public static KernelResult<BrepBody> ImportBody(string stepText, ImportPolicy? policy = null)
{
using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("step.import-body");
// BUILD-PERF-M2: one build reimports the same canonical STEP several times (export
// validation, volume assertions, the assembly definition). Import is a pure function of the
// text and policy (a value record) unless a diagnostics capture or rational preservation is in
// effect, so a recent successful import is replayed as an independent clone of the same body.
var memoizable = !RationalSurfacesArePreserved && CircularSamplingDiagnosticsSink.Value is null
&& CoedgeGapDiagnosticsSink.Value is null && CylinderProjectionDiagnosticsSink.Value is null
&& TorusProjectionDiagnosticsSink.Value is null && PlanarMultiBoundJudgmentDiagnosticsSink.Value is null;
if (memoizable)
{
lock (RecentImports)
{
for (var i = RecentImports.Count - 1; i >= 0; i--)
{
var (text, recentPolicy, body, diagnostics) = RecentImports[i];
if (!Equals(recentPolicy, policy) || text.Length != stepText.Length || !string.Equals(text, stepText, StringComparison.Ordinal)) continue;
return KernelResult<BrepBody>.Success(body.Clone(), diagnostics);
}
}
}
var orchestrator = ImportOrchestrator.CreateDefault();
var result = orchestrator.Import(new ImportRequest(stepText, policy)).BodyResult;
if (result.IsSuccess && result.Value is not null)
result.Value.SourceStepTextHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(stepText)));
if (memoizable && result.IsSuccess && result.Value is not null)
{
var retained = result.Value.Clone();
lock (RecentImports)
{
RecentImports.Add((stepText, policy, retained, result.Diagnostics));
if (RecentImports.Count > RecentImportCapacity) RecentImports.RemoveAt(0);
}
}
return result;
}
private const int RecentImportCapacity = 8;
private static readonly List<(string Text, ImportPolicy? Policy, BrepBody Body, IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> Diagnostics)> RecentImports = [];
private static KernelResult<BrepBody> ImportAuto(Step242ParsedDocument document)
{
if (Step242TessellatedImportLane.HasTessellatedRoot(document))
{
return Step242TessellatedImportLane.ImportFromParsedDocument(document);
}
return Step242ExactBRepImportLane.ImportExactBrep(document);
}
internal static KernelResult<BrepBody> ImportExactBrepCore(Step242ParsedDocument document)
{
var rigidRootClassification = Step242RigidRootClassifier.Classify(document);
if (rigidRootClassification.Kind == Step242RigidRootClassificationKind.MissingRigidRoot)
{
return Step242ImportSharedUtilities.NotImplementedFailure<BrepBody>(
"Missing MANIFOLD_SOLID_BREP or BREP_WITH_VOIDS root entity.",
"Importer.TopologyRoot");
}
if (rigidRootClassification.Kind == Step242RigidRootClassificationKind.AssemblyLikeMultipleRigidRoots)
{
return Step242ImportSharedUtilities.NotImplementedFailure<BrepBody>(
$"STEP input is assembly-like: detected {rigidRootClassification.RigidRoots.Count} exact BRep rigid roots (MANIFOLD_SOLID_BREP/BREP_WITH_VOIDS). Single-part exact BRep import accepts exactly one rigid root; route this input through assembly extraction/import.",
"Importer.AssemblyLike.StepMultiRoot");
}
return ImportExactBrepCore(document, rigidRootClassification.SingleRigidRoot.Id, includeOrphanPlanarFaces: true);
}
internal static KernelResult<BrepBody> ImportExactBrepCore(Step242ParsedDocument document, int rigidRootEntityId, bool includeOrphanPlanarFaces = false)
{
var brepResult = document.TryGetEntity(rigidRootEntityId);
if (!brepResult.IsSuccess) return KernelResult<BrepBody>.Failure(brepResult.Diagnostics);
var brepEntity = brepResult.Value;
if (!string.Equals(brepEntity.Name, "MANIFOLD_SOLID_BREP", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(brepEntity.Name, "BREP_WITH_VOIDS", StringComparison.OrdinalIgnoreCase))
return Step242ImportSharedUtilities.NotImplementedFailure<BrepBody>($"Entity #{rigidRootEntityId} is not an exact rigid BRep root.", "Importer.Assembly.ProductDefinitionGeometry");
var shellRoleDiagnostics = new List<KernelDiagnostic>();
var importRepairs = new List<Aetheris.Kernel.Core.Import.ImportQualificationReason>();
// Surface binding reports what it did with each spline face (recovered as a primitive, or retained); those
// findings are the record of how faithfully the file was read, so they travel with the imported body.
var surfaceBindingDiagnostics = new List<KernelDiagnostic>();
var shellFaceEntityIds = new List<IReadOnlyList<int>>();
var isBrepWithVoids = string.Equals(brepEntity.Name, "BREP_WITH_VOIDS", StringComparison.OrdinalIgnoreCase);
var outerShellRefResult = Step242SubsetDecoder.ReadReference(brepEntity, 1, isBrepWithVoids ? "BREP_WITH_VOIDS outer shell" : "MANIFOLD_SOLID_BREP shell");
if (!outerShellRefResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(outerShellRefResult.Diagnostics);
}
var outerShellFacesResult = ReadShellFaceIds(document, outerShellRefResult.Value.TargetId, "outer", shellRoleDiagnostics);
if (!outerShellFacesResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(outerShellFacesResult.Diagnostics);
}
shellFaceEntityIds.Add(outerShellFacesResult.Value);
if (isBrepWithVoids)
{
var voidShellRefsResult = Step242SubsetDecoder.ReadReferenceList(brepEntity, 2, "BREP_WITH_VOIDS void shells");
if (!voidShellRefsResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(voidShellRefsResult.Diagnostics);
}
if (voidShellRefsResult.Value.Count == 0)
{
return Step242ImportSharedUtilities.ValidationFailure<BrepBody>("BREP_WITH_VOIDS must reference at least one void shell.", "Importer.TopologyRoot.BrepWithVoids");
}
foreach (var voidShellRef in voidShellRefsResult.Value)
{
var voidShellFacesResult = ReadShellFaceIds(document, voidShellRef.TargetId, "void", shellRoleDiagnostics);
if (!voidShellFacesResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(voidShellFacesResult.Diagnostics);
}
shellFaceEntityIds.Add(voidShellFacesResult.Value);
}
}
var faceEntityIds = shellFaceEntityIds.SelectMany(ids => ids).ToList();
if (includeOrphanPlanarFaces) AppendSupportedOrphanPlanarFaces(document, faceEntityIds);
var builder = new TopologyBuilder();
var geometry = new BrepGeometryStore();
var bindings = new BrepBindingModel();
var vertexMap = new Dictionary<int, (VertexId VertexId, Point3D Point)>();
var edgeMap = new Dictionary<int, EdgeId>();
var coedges = new List<Coedge>();
var nextCurveGeometryId = 1;
var nextSurfaceGeometryId = 1;
var faceIds = new List<FaceId>();
var faceEntityToFaceId = new Dictionary<int, FaceId>();
var importedFacePatches = new List<ImportedFacePatch>();
var supportAlignedBoundary = new Dictionary<FaceId, bool>();
var supportAlignedLoopBoundary = new Dictionary<LoopId, bool>();
foreach (var faceEntityId in faceEntityIds)
{
var faceEntityResult = document.TryGetEntity(faceEntityId, "ADVANCED_FACE");
if (!faceEntityResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(faceEntityResult.Diagnostics);
}
var faceEntity = faceEntityResult.Value;
var advancedFaceOffset = faceEntity.Arguments.Count >= 4
&& (faceEntity.Arguments[0] is Step242StringValue || faceEntity.Arguments[0] is Step242OmittedValue)
? 1
: 0;
var surfaceResult = Step242SubsetDecoder.ReadEntityRefOrInlineConstructor(faceEntity, advancedFaceOffset + 1, "ADVANCED_FACE surface");
if (!surfaceResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(surfaceResult.Diagnostics);
}
Step242ParsedEntity? surfaceEntity = null;
string surfaceName;
IReadOnlyList<Step242Value>? inlineSurfaceArguments = null;
if (surfaceResult.Value.IsReference)
{
var surfaceEntityResult = document.TryGetEntity(surfaceResult.Value.ReferenceId!.Value);
if (!surfaceEntityResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(surfaceEntityResult.Diagnostics);
}
surfaceEntity = surfaceEntityResult.Value;
surfaceName = surfaceEntityResult.Value.Name;
}
else
{
surfaceName = surfaceResult.Value.InlineName!;
inlineSurfaceArguments = surfaceResult.Value.InlineArguments;
}
var isSphericalFace = string.Equals(surfaceName, "SPHERICAL_SURFACE", StringComparison.OrdinalIgnoreCase);
var isConicalFace = string.Equals(surfaceName, "CONICAL_SURFACE", StringComparison.OrdinalIgnoreCase);
var boundRefsResult = Step242SubsetDecoder.ReadAdvancedFaceBounds(faceEntity, advancedFaceOffset, "ADVANCED_FACE bounds");
if (!boundRefsResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(boundRefsResult.Diagnostics);
}
if (boundRefsResult.Value.Count == 0 && !isSphericalFace)
{
return Failure("ADVANCED_FACE without bounds is unsupported in M23 subset.", $"Entity:{faceEntity.Id}");
}
var faceSameSenseResult = Step242SubsetDecoder.ReadBoolean(faceEntity, advancedFaceOffset + 2, "ADVANCED_FACE same_sense");
if (!faceSameSenseResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(faceSameSenseResult.Diagnostics);
}
var bindSurfaceResult = DecodeSurfaceGeometry(document, surfaceEntity, surfaceName, inlineSurfaceArguments, nextSurfaceGeometryId, faceEntity.Id);
if (!bindSurfaceResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(bindSurfaceResult.Diagnostics);
}
surfaceBindingDiagnostics.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);
if (!boundEntityResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(boundEntityResult.Diagnostics);
}
var boundEntity = boundEntityResult.Value;
var isFaceBound = string.Equals(boundEntity.Name, "FACE_BOUND", StringComparison.OrdinalIgnoreCase)
|| string.Equals(boundEntity.Name, "FACE_OUTER_BOUND", StringComparison.OrdinalIgnoreCase);
if (!isFaceBound)
{
return Failure($"Entity '{boundEntity.Name}' is unsupported in M23 import subset.", $"Entity:{boundEntity.Id}");
}
var loopRefResult = Step242SubsetDecoder.ReadReference(boundEntity, 1, "FACE_BOUND loop");
if (!loopRefResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(loopRefResult.Diagnostics);
}
var boundOrientationResult = Step242SubsetDecoder.ReadBoolean(boundEntity, 2, "FACE_BOUND orientation");
if (!boundOrientationResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(boundOrientationResult.Diagnostics);
}
var boundAgreesWithLoop = boundOrientationResult.Value;
var isDeclaredOuter = string.Equals(boundEntity.Name, "FACE_OUTER_BOUND", StringComparison.OrdinalIgnoreCase);
var loopEntityResult = document.TryGetEntity(loopRefResult.Value.TargetId);
if (!loopEntityResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(loopEntityResult.Diagnostics);
}
if (string.Equals(loopEntityResult.Value.Name, "VERTEX_LOOP", StringComparison.OrdinalIgnoreCase))
{
var vertexLoopRefResult = Step242SubsetDecoder.ReadReference(loopEntityResult.Value, 1, "VERTEX_LOOP vertex");
if (!vertexLoopRefResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(vertexLoopRefResult.Diagnostics);
}
var vertexResult = EnsureVertex(document, vertexLoopRefResult.Value.TargetId, builder, vertexMap);
if (!vertexResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(vertexResult.Diagnostics);
}
var isConeApex = isConicalFace
&& bindSurfaceResult.Value.SurfaceGeometry.Cone is ConeSurface cone
&& (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))
{
return Failure($"FACE_BOUND loop type '{loopEntityResult.Value.Name}' is unsupported in M23 import subset.", $"Entity:{loopEntityResult.Value.Id}");
}
var orientedEdgeRefsResult = Step242SubsetDecoder.ReadReferenceList(loopEntityResult.Value, 1, "EDGE_LOOP coedges");
if (!orientedEdgeRefsResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(orientedEdgeRefsResult.Diagnostics);
}
if (orientedEdgeRefsResult.Value.Count == 0)
{
return Failure("EDGE_LOOP must contain at least one ORIENTED_EDGE.", $"Entity:{loopEntityResult.Value.Id}");
}
var loopId = builder.AllocateLoopId();
var coedgeIds = new List<CoedgeId>(orientedEdgeRefsResult.Value.Count);
for (var i = 0; i < orientedEdgeRefsResult.Value.Count; i++)
{
coedgeIds.Add(builder.AllocateCoedgeId());
}
var loopCoedges = new List<Coedge>(orientedEdgeRefsResult.Value.Count);
var loopPcurveCandidates = new Dictionary<CoedgeId, IReadOnlyList<ImportedStepPcurve>>();
var loopSamples = new List<Point3D>();
var hasDisconnectedCoedgeGap = false;
for (var i = 0; i < orientedEdgeRefsResult.Value.Count; i++)
{
var orientedEdgeEntityResult = document.TryGetEntity(orientedEdgeRefsResult.Value[i].TargetId, "ORIENTED_EDGE");
if (!orientedEdgeEntityResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(orientedEdgeEntityResult.Diagnostics);
}
var orientedEdgeEntity = orientedEdgeEntityResult.Value;
var edgeCurveRefResult = Step242SubsetDecoder.ReadReference(orientedEdgeEntity, 3, "ORIENTED_EDGE edge element");
if (!edgeCurveRefResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(edgeCurveRefResult.Diagnostics);
}
var edgeCurveEntityResult = document.TryGetEntity(edgeCurveRefResult.Value.TargetId, "EDGE_CURVE");
if (!edgeCurveEntityResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(edgeCurveEntityResult.Diagnostics);
}
var edgeIdResult = EnsureEdge(
document,
edgeCurveEntityResult.Value,
builder,
geometry,
bindings,
vertexMap,
edgeMap,
ref nextCurveGeometryId);
if (!edgeIdResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(edgeIdResult.Diagnostics);
}
var orientedSenseResult = Step242SubsetDecoder.ReadBoolean(orientedEdgeEntity, 4, "ORIENTED_EDGE orientation");
if (!orientedSenseResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(orientedSenseResult.Diagnostics);
}
// ORIENTED_EDGE orientation is relative to EDGE_CURVE's
// topology vertices. EDGE_CURVE same_sense instead relates
// curve parameter direction to those vertices and is stored
// on the edge binding by EnsureEdge. Combining both here
// reverses a coedge twice when same_sense is false.
var isReversed = !orientedSenseResult.Value;
var coedge = new Coedge(
coedgeIds[i],
edgeIdResult.Value,
loopId,
coedgeIds[(i + 1) % coedgeIds.Count],
coedgeIds[(i + coedgeIds.Count - 1) % coedgeIds.Count],
IsReversed: 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,
coedge.IsReversed,
faceEntity.Id,
loopId.Value,
coedge.Id.Value,
edgeIdResult.Value.Value);
if (!sampleResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(sampleResult.Diagnostics);
}
var boundaryClassification = AppendLoopSamples(
loopSamples,
sampleResult.Value,
bindSurfaceResult.Value.SurfaceGeometry,
faceEntity.Id,
loopId.Value,
coedge.Id.Value,
loopCoedges.Count > 1 ? loopCoedges[^2].Id.Value : (int?)null);
if (boundaryClassification == LoopCoedgeGapClassification.Disconnected)
{
hasDisconnectedCoedgeGap = true;
}
}
if (hasDisconnectedCoedgeGap && TryOrderUniqueDirectedCycle(loopCoedges, builder.Model, out var ordered))
{
loopCoedges = ordered;
loopSamples.Clear(); hasDisconnectedCoedgeGap = false;
for (var i = 0; i < loopCoedges.Count; i++)
{
var coedge = loopCoedges[i];
var sample = SampleCoedgePoints(bindings.GetEdgeBinding(coedge.EdgeId), geometry, coedge.IsReversed,
faceEntity.Id, loopId.Value, coedge.Id.Value, coedge.EdgeId.Value);
if (!sample.IsSuccess) return KernelResult<BrepBody>.Failure(sample.Diagnostics);
hasDisconnectedCoedgeGap |= AppendLoopSamples(loopSamples, sample.Value, bindSurfaceResult.Value.SurfaceGeometry,
faceEntity.Id, loopId.Value, coedge.Id.Value, i > 0 ? loopCoedges[i - 1].Id.Value : null) == LoopCoedgeGapClassification.Disconnected;
}
var message = $"EDGE_LOOP #{loopEntityResult.Value.Id} reordered by its unique directed vertex cycle; no vertices, edges or edge senses changed.";
importRepairs.Add(new("step-import-loop-order-recovered", message, StepEntityId: faceEntity.Id));
shellRoleDiagnostics.Add(new(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info,
"step-import-loop-order-recovered: " + message, $"Entity:{faceEntity.Id}"));
}
// FACE_BOUND orientation .F. means the face uses its EDGE_LOOP reversed (ISO 10303-42).
// Dropping it left the loop running against the face, which reversed spherical caps
// (a concave corner drew as the rest of its sphere) and was written back out on export.
if (!boundAgreesWithLoop)
{
loopCoedges.Reverse();
var count = loopCoedges.Count;
loopCoedges = loopCoedges.Select((c, index) => c with
{
IsReversed = !c.IsReversed,
NextCoedgeId = loopCoedges[(index + 1) % count].Id,
PrevCoedgeId = loopCoedges[(index + count - 1) % count].Id,
}).ToList();
loopSamples.Reverse();
}
var closingGap = ClassifyCoedgeGap(loopSamples[^1], loopSamples[0], bindSurfaceResult.Value.SurfaceGeometry);
ReportCoedgeGapDiagnostic(new LoopRoleCoedgeGapDiagnostic(
FaceEntityId: faceEntity.Id,
LoopId: loopId.Value,
PreviousCoedgeId: loopCoedges[^1].Id.Value,
NextCoedgeId: loopCoedges[0].Id.Value,
Gap3d: closingGap.Gap3d,
Gap2d: closingGap.Gap2d,
PreviousEdgeGeometryKind: DescribeCurveKind(bindings.GetEdgeBinding(loopCoedges[^1].EdgeId), geometry),
NextEdgeGeometryKind: DescribeCurveKind(bindings.GetEdgeBinding(loopCoedges[0].EdgeId), geometry),
Classification: closingGap.Classification,
WithinPointOnSurfaceEps: closingGap.Gap3d <= PointOnSurfaceEps,
WithinContainmentEps: closingGap.Gap3d <= ContainmentEps,
WouldCreateGhostSegmentWithoutNormalization: closingGap.Gap3d > PointOnSurfaceEps));
if (closingGap.Classification == LoopCoedgeGapClassification.TinyNormalizable)
{
loopSamples[0] = loopSamples[^1];
}
else if (closingGap.Classification == LoopCoedgeGapClassification.Disconnected)
{
hasDisconnectedCoedgeGap = true;
}
loopData.Add(new LoopBuildData(loopId, loopCoedges, loopSamples, hasDisconnectedCoedgeGap, isDeclaredOuter, boundEntity.Id, loopPcurveCandidates));
}
var classifyResult = ClassifyAndNormalizeFaceLoops(faceEntity.Id, loopData, bindSurfaceResult.Value.SurfaceGeometry,
document.AllowBoundedNearCoincidentInnerLoop ? document.RecoveryToleranceMillimetres : 0d);
if (!classifyResult.IsSuccess)
{
return KernelResult<BrepBody>.Failure(classifyResult.Diagnostics);
}
// A face bound is authored topology. Normalization may adjust
// winding/order, but it must never silently remove a declared loop
// (for example a closed single-edge circular bound whose sampling
// is currently outside the admitted normalization subset).
if (classifyResult.Value.Count != loopData.Count)
{
return Failure(
$"FACE #{faceEntity.Id} normalization would discard {loopData.Count - classifyResult.Value.Count} declared bound(s); import is deferred until every bound can be represented.",
"Importer.LoopRole.NormalizationDiscardedBound");
}
foreach (var loop in classifyResult.Value)
{
builder.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)
.Concat(vertexLoopData.Select(loop => loop.LoopId)).ToList();
var faceId = builder.AddFace(faceLoopIds);
faceIds.Add(faceId);
faceEntityToFaceId[faceEntityId] = faceId;
var (surfaceGeometryId, surfaceGeometry) = bindSurfaceResult.Value;
nextSurfaceGeometryId++;
geometry.AddSurface(surfaceGeometryId, surfaceGeometry);
// Preserve interchange identity as provenance. Semantic associations such as
// GEOMETRIC_ITEM_SPECIFIC_USAGE refer to the ADVANCED_FACE entity number;
// consumers must not guess this relationship from allocation order.
bindings.AddFaceBinding(new FaceGeometryBinding(
faceId,
surfaceGeometryId,
ResolvedFaceOrientation.Aligned,
SourceStepEntityId: faceEntity.Id));
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];
var role = hasDeclaredOuter
? loop.IsDeclaredOuter ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner
: 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,
new SourceFaceOrientationEvidence(
faceSameSenseResult.Value,
faceEntity.Id,
surfaceResult.Value.ReferenceId)));
var loopOrientation = DeriveSupportAlignedBoundaries(classifyResult.Value, surfaceGeometry, faceSameSenseResult.Value);
supportAlignedBoundary[faceId] = loopOrientation.FaceAligned;
foreach (var pair in loopOrientation.Loops) supportAlignedLoopBoundary[pair.Key] = pair.Value;
}
foreach (var coedge in coedges)
{
builder.AddCoedge(coedge);
}
var shellIds = new List<ShellId>(shellFaceEntityIds.Count);
var assignedFaceIds = new HashSet<FaceId>();
var referencedFaceIds = new HashSet<FaceId>(
shellFaceEntityIds
.SelectMany(faceSet => faceSet)
.Where(faceEntityToFaceId.ContainsKey)
.Select(faceEntityId => faceEntityToFaceId[faceEntityId]));
foreach (var shellFaceSet in shellFaceEntityIds)
{
var shellFaceIds = new List<FaceId>(shellFaceSet.Count);
foreach (var shellFaceEntityId in shellFaceSet)
{
if (!faceEntityToFaceId.TryGetValue(shellFaceEntityId, out var shellFaceId))
{
return Failure($"Shell references unknown face entity #{shellFaceEntityId}.", "Importer.TopologyRoot.BrepWithVoids");
}
shellFaceIds.Add(shellFaceId);
assignedFaceIds.Add(shellFaceId);
}
if (shellIds.Count == 0)
{
foreach (var faceId in faceIds)
{
if (assignedFaceIds.Contains(faceId) || referencedFaceIds.Contains(faceId))
{
continue;
}
shellFaceIds.Add(faceId);
assignedFaceIds.Add(faceId);
}
}
shellIds.Add(builder.AddShell(shellFaceIds));
}
builder.AddBody(shellIds);
BrepBodyShellRepresentation? shellRepresentation = null;
if (shellIds.Count > 0)
{
shellRepresentation = new BrepBodyShellRepresentation(shellIds[0], shellIds.Skip(1).ToArray());
}
var body = new BrepBody(builder.Model, geometry, bindings, vertexMap.Values.ToDictionary(entry => entry.VertexId, entry => entry.Point), shellRepresentation: shellRepresentation);
KernelResult<BrepBody> orientation;
using (BuildPerfTrace.Phase("step.orientation-qualification"))
orientation = StepFaceOrientationResolver.Resolve(body, importedFacePatches, supportAlignedBoundary, supportAlignedLoopBoundary);
if (!orientation.IsSuccess)
{
return KernelResult<BrepBody>.Failure(shellRoleDiagnostics
.Concat(surfaceBindingDiagnostics)
.Concat(orientation.Diagnostics));
}
BrepPcurveEvidence? qualificationEvidence = null;
if (orientation.Value.Bindings.PcurveBindings.Any())
{
var pcurveTolerance = double.Max(1e-6d, document.SourceDistanceAccuracyMillimetres ?? 0d);
var pcurveEvidence = BrepPcurveValidator.Validate(orientation.Value, pcurveTolerance,
sourceTopology: document.SourceDistanceAccuracyMillimetres is > 0d and var sourceAccuracy
? new BrepPcurveTopologyEvidence(orientation.Value.Topology.Vertices.ToDictionary(v => v.Id, _ => sourceAccuracy), new HashSet<(CoedgeId, CoedgeId)>())
: null);
qualificationEvidence = pcurveEvidence;
if (!pcurveEvidence.IsValid)
{
return KernelResult<BrepBody>.Failure(pcurveEvidence.Diagnostics.Select(message => new KernelDiagnostic(
KernelDiagnosticCode.ValidationFailed,
KernelDiagnosticSeverity.Error,
message,
"Importer.Pcurve.Consistency")).ToArray());
}
}
// Pcurves describe face-local edge uses, including exact geometry. Geometry
// recovery provenance must not decide whether those bindings are populated.
if (orientation.Value.Topology.Coedges.Any(coedge =>
!orientation.Value.Bindings.TryGetPcurveBinding(coedge.Id, out _)))
{
using var recoveryPhase = BuildPerfTrace.Phase("step.pcurve-recovery-and-qualification");
// Tolerant edges: accept a measured curve-surface gap up to the file's declared accuracy, or 10 µm
// when it declares none. Beyond that the source is wrong and the edge stays unqualified.
var recovery = BrepPcurveRecovery.Populate(
orientation.Value.Topology, orientation.Value.Geometry, orientation.Value.Bindings,
tolerance: document.PcurveQualificationToleranceMillimetres,
sourceTolerance: document.SourceDistanceAccuracyMillimetres is > 0d and var declared ? declared : 0.01d);
// Vertices only need to lie within the source's declared distance accuracy of their curves.
var sourceVertexTolerance = document.SourceDistanceAccuracyMillimetres is > 0d and var accuracy
? new BrepPcurveTopologyEvidence(orientation.Value.Topology.Vertices.ToDictionary(v => v.Id, _ => accuracy), new HashSet<(CoedgeId, CoedgeId)>())
: null;
var pcurveEvidence = BrepPcurveValidator.Validate(orientation.Value,
document.PcurveQualificationToleranceMillimetres, requireEveryCoedge: true, sourceTopology: sourceVertexTolerance);
qualificationEvidence = pcurveEvidence;
orientation.Value.PcurveRecoveryReport = pcurveEvidence.IsValid ? recovery : recovery with
{
IsSuccess = false,
Diagnostics = recovery.Diagnostics.Concat(pcurveEvidence.Diagnostics.Select(message =>
new BrepPcurveRecoveryDiagnostic("surf-pcurve-invalid", message))).ToArray()
};
}
var validation = BrepBindingValidator.Validate(orientation.Value, requireAllEdgeAndFaceBindings: true);
if (!validation.IsSuccess)
{
return KernelResult<BrepBody>.Failure(validation.Diagnostics
.Concat(shellRoleDiagnostics)
.Concat(surfaceBindingDiagnostics)
.Concat(orientation.Diagnostics));
}
orientation.Value.ImportQualification = BrepImportQualification.Evaluate(orientation.Value, faceEntityIds.Count,
document.SourceDistanceAccuracyMillimetres, document.PcurveQualificationToleranceMillimetres, qualificationEvidence) with { Repairs = importRepairs };
return KernelResult<BrepBody>.Success(orientation.Value, validation.Diagnostics
.Concat(shellRoleDiagnostics)
.Concat(surfaceBindingDiagnostics)
.Concat(orientation.Diagnostics)
.ToArray());
}
private static KernelResult<IReadOnlyList<int>> ReadShellFaceIds(Step242ParsedDocument document, int shellEntityId, string role, ICollection<KernelDiagnostic> diagnostics)
{
var shellEntityResult = document.TryGetEntity(shellEntityId);
if (!shellEntityResult.IsSuccess)
{
return KernelResult<IReadOnlyList<int>>.Failure(shellEntityResult.Diagnostics);
}
var shellEntity = shellEntityResult.Value;
if (string.Equals(shellEntity.Name, "ORIENTED_CLOSED_SHELL", StringComparison.OrdinalIgnoreCase))
{
var orientedRefResult = Step242SubsetDecoder.ReadReference(shellEntity, 1, "ORIENTED_CLOSED_SHELL shell");
if (!orientedRefResult.IsSuccess)
{
return KernelResult<IReadOnlyList<int>>.Failure(orientedRefResult.Diagnostics);
}
diagnostics.Add(new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Info, $"Resolved oriented {role} shell reference #{shellEntity.Id} -> #{orientedRefResult.Value.TargetId}.", "Importer.TopologyRoot.BrepWithVoids"));
return ReadShellFaceIds(document, orientedRefResult.Value.TargetId, role, diagnostics);
}
if (!string.Equals(shellEntity.Name, "CLOSED_SHELL", StringComparison.OrdinalIgnoreCase))
{
return Step242ImportSharedUtilities.NotImplementedFailure<IReadOnlyList<int>>($"Unsupported {role} shell entity '{shellEntity.Name}' (expected CLOSED_SHELL or ORIENTED_CLOSED_SHELL).", "Importer.TopologyRoot.BrepWithVoids");
}
var faceRefsResult = Step242SubsetDecoder.ReadReferenceList(shellEntity, 1, $"CLOSED_SHELL {role} faces");
if (!faceRefsResult.IsSuccess)
{
return KernelResult<IReadOnlyList<int>>.Failure(faceRefsResult.Diagnostics);
}
return KernelResult<IReadOnlyList<int>>.Success(faceRefsResult.Value.Select(r => r.TargetId).ToArray());
}
private static void AppendSupportedOrphanPlanarFaces(Step242ParsedDocument document, IList<int> faceEntityIds)
{
var known = new HashSet<int>(faceEntityIds);
// An auxiliary OPEN_SHELL (often a datum/annotation surface model) owns
// its faces independently. Such faces are not orphans of the selected
// solid and must never be appended to its closed material shell.
foreach (var shell in document.Entities.Where(e => e.Name is "OPEN_SHELL" or "CLOSED_SHELL"))
{
var faces = Step242SubsetDecoder.ReadReferenceList(shell, 1, "auxiliary shell faces");
if (faces.IsSuccess) known.UnionWith(faces.Value.Select(r => r.TargetId));
}
foreach (var entity in document.Entities)
{
if (!string.Equals(entity.Name, "ADVANCED_FACE", StringComparison.OrdinalIgnoreCase) || known.Contains(entity.Id))
{
continue;
}
var advancedFaceOffset = entity.Arguments.Count >= 4
&& (entity.Arguments[0] is Step242StringValue || entity.Arguments[0] is Step242OmittedValue)
? 1
: 0;
var surfaceResult = Step242SubsetDecoder.ReadEntityRefOrInlineConstructor(entity, advancedFaceOffset + 1, "ADVANCED_FACE surface");
if (!surfaceResult.IsSuccess)
{
continue;
}
string surfaceName;
if (surfaceResult.Value.IsReference)
{
var surfaceEntityResult = document.TryGetEntity(surfaceResult.Value.ReferenceId!.Value);
if (!surfaceEntityResult.IsSuccess)
{
continue;
}
surfaceName = surfaceEntityResult.Value.Name;
}
else
{
surfaceName = surfaceResult.Value.InlineName ?? string.Empty;
}
if (!string.Equals(surfaceName, "PLANE", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var boundRefsResult = Step242SubsetDecoder.ReadAdvancedFaceBounds(entity, advancedFaceOffset, "ADVANCED_FACE bounds");
if (!boundRefsResult.IsSuccess || boundRefsResult.Value.Count == 0)
{
continue;
}
var allEdgeLoops = true;
foreach (var boundRef in boundRefsResult.Value)
{
var boundEntityResult = document.TryGetEntity(boundRef.TargetId);
if (!boundEntityResult.IsSuccess)
{
allEdgeLoops = false;
break;
}
var loopRefResult = Step242SubsetDecoder.ReadReference(boundEntityResult.Value, 1, "FACE_BOUND loop");
if (!loopRefResult.IsSuccess)
{
allEdgeLoops = false;
break;
}
var loopEntityResult = document.TryGetEntity(loopRefResult.Value.TargetId);
if (!loopEntityResult.IsSuccess || !string.Equals(loopEntityResult.Value.Name, "EDGE_LOOP", StringComparison.OrdinalIgnoreCase))
{
allEdgeLoops = false;
break;
}
}
if (!allEdgeLoops)
{
continue;
}
faceEntityIds.Add(entity.Id);
known.Add(entity.Id);
}
}
private static KernelResult<EdgeId> EnsureEdge(
Step242ParsedDocument document,
Step242ParsedEntity edgeCurveEntity,
TopologyBuilder builder,
BrepGeometryStore geometry,
BrepBindingModel bindings,
IDictionary<int, (VertexId VertexId, Point3D Point)> vertexMap,
IDictionary<int, EdgeId> edgeMap,
ref int nextCurveGeometryId)
{
if (edgeMap.TryGetValue(edgeCurveEntity.Id, out var existingEdgeId))
{
return KernelResult<EdgeId>.Success(existingEdgeId);
}
var startRefResult = Step242SubsetDecoder.ReadReference(edgeCurveEntity, 1, "EDGE_CURVE start");
if (!startRefResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(startRefResult.Diagnostics);
}
var endRefResult = Step242SubsetDecoder.ReadReference(edgeCurveEntity, 2, "EDGE_CURVE end");
if (!endRefResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(endRefResult.Diagnostics);
}
var lineRefResult = Step242SubsetDecoder.ReadReference(edgeCurveEntity, 3, "EDGE_CURVE geometry");
if (!lineRefResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(lineRefResult.Diagnostics);
}
var sameSenseResult = Step242SubsetDecoder.ReadBoolean(edgeCurveEntity, 4, "EDGE_CURVE same_sense");
if (!sameSenseResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(sameSenseResult.Diagnostics);
}
var edgeSameSense = sameSenseResult.Value;
var startVertexResult = EnsureVertex(document, startRefResult.Value.TargetId, builder, vertexMap);
if (!startVertexResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(startVertexResult.Diagnostics);
}
var endVertexResult = EnsureVertex(document, endRefResult.Value.TargetId, builder, vertexMap);
if (!endVertexResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(endVertexResult.Diagnostics);
}
var curveEntityResult = document.TryGetEntity(lineRefResult.Value.TargetId);
if (!curveEntityResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(curveEntityResult.Diagnostics);
}
var edgeId = builder.AddEdge(startVertexResult.Value.VertexId, endVertexResult.Value.VertexId);
edgeMap.Add(edgeCurveEntity.Id, edgeId);
var curveGeometryId = new CurveGeometryId(nextCurveGeometryId++);
var bindCurveResult = DecodeCurveGeometry(
document,
curveEntityResult.Value,
startVertexResult.Value.Point,
endVertexResult.Value.Point,
edgeSameSense,
edgeCurveEntity.Id);
if (!bindCurveResult.IsSuccess)
{
return KernelResult<EdgeId>.Failure(bindCurveResult.Diagnostics);
}
geometry.AddCurve(curveGeometryId, bindCurveResult.Value.CurveGeometry);
bindings.AddEdgeBinding(new EdgeGeometryBinding(edgeId, curveGeometryId, bindCurveResult.Value.TrimInterval, edgeSameSense) { SourceStepEntityId = edgeCurveEntity.Id });
return KernelResult<EdgeId>.Success(edgeId);
}
private static KernelResult<(VertexId VertexId, Point3D Point)> EnsureVertex(
Step242ParsedDocument document,
int vertexPointEntityId,
TopologyBuilder builder,
IDictionary<int, (VertexId VertexId, Point3D Point)> vertexMap)
{
if (vertexMap.TryGetValue(vertexPointEntityId, out var existingVertex))
{
return KernelResult<(VertexId VertexId, Point3D Point)>.Success(existingVertex);
}
var pointResult = Step242SubsetDecoder.ReadVertexPoint(document, vertexPointEntityId);
if (!pointResult.IsSuccess)
{
return KernelResult<(VertexId VertexId, Point3D Point)>.Failure(pointResult.Diagnostics);
}
var vertex = (builder.AddVertex(), pointResult.Value);
vertexMap.Add(vertexPointEntityId, vertex);
return KernelResult<(VertexId VertexId, Point3D Point)>.Success(vertex);
}
private static KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)> DecodeCurveGeometry(
Step242ParsedDocument document,
Step242ParsedEntity curveEntity,
Point3D startPoint,
Point3D endPoint,
bool edgeSameSense,
int edgeCurveEntityId)
{
ParameterInterval? explicitTrim = null;
var surfaceCurveConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "SURFACE_CURVE")
?? Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "SEAM_CURVE");
if (surfaceCurveConstructor is not null)
{
if (surfaceCurveConstructor.Arguments.ElementAtOrDefault(1) is not Step242EntityReference curve3dReference)
return FailureCurveBinding("SURFACE_CURVE/SEAM_CURVE must reference its authoritative 3D curve.", SourceFor(edgeCurveEntityId, "Importer.Geometry.SurfaceCurve"));
var curve3dResult = document.TryGetEntity(curve3dReference.TargetId);
if (!curve3dResult.IsSuccess)
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(curve3dResult.Diagnostics);
curveEntity = curve3dResult.Value;
}
var trimmedConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "TRIMMED_CURVE");
if (trimmedConstructor is not null)
{
if (trimmedConstructor.Arguments.Count != 6
|| trimmedConstructor.Arguments[1] is not Step242EntityReference basisReference)
{
return FailureCurveBinding("TRIMMED_CURVE must provide a basis curve and two parameter trims.", SourceFor(edgeCurveEntityId, "Importer.Geometry.TrimmedCurve"));
}
var trimResult = ReadParameterTrim(trimmedConstructor.Arguments[2], trimmedConstructor.Arguments[3], trimmedConstructor.Arguments[4], edgeCurveEntityId);
if (!trimResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
}
var basisResult = document.TryGetEntity(basisReference.TargetId);
if (!basisResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(basisResult.Diagnostics);
}
curveEntity = basisResult.Value;
explicitTrim = trimResult.Value;
}
var lineConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "LINE");
if (lineConstructor is not null)
{
var lineResult = Step242SubsetDecoder.ReadLineCurve(document, WithConstructor(curveEntity, lineConstructor));
if (!lineResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(lineResult.Diagnostics);
}
var startParameter = ComputeLineParameter(lineResult.Value, startPoint);
var endParameter = ComputeLineParameter(lineResult.Value, endPoint);
if (endParameter < startParameter)
{
if (edgeSameSense)
{
return FailureCurveBinding("EDGE_CURVE line parameterization is opposite to vertex ordering.", SourceFor(edgeCurveEntityId, "Importer.Geometry.EdgeCurveParameters"));
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromLine(lineResult.Value),
new ParameterInterval(endParameter, startParameter)));
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromLine(lineResult.Value),
new ParameterInterval(startParameter, endParameter)));
}
var circleConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "CIRCLE");
if (circleConstructor is not null)
{
var circleResult = Step242SubsetDecoder.ReadCircleCurve(document, WithConstructor(curveEntity, circleConstructor));
if (!circleResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(circleResult.Diagnostics);
}
var trimResult = explicitTrim is { } specified
? KernelResult<ParameterInterval>.Success(specified)
: ComputeCircleTrim(circleResult.Value, startPoint, endPoint, edgeSameSense, document.SourceDistanceAccuracyMillimetres ?? 0d);
if (!trimResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromCircle(circleResult.Value),
trimResult.Value));
}
var ellipseConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "ELLIPSE");
if (ellipseConstructor is not null)
{
var ellipseResult = Step242SubsetDecoder.ReadEllipseCurve(document, WithConstructor(curveEntity, ellipseConstructor));
if (!ellipseResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(ellipseResult.Diagnostics);
}
var trimResult = ComputeEllipseTrim(ellipseResult.Value, startPoint, endPoint, edgeSameSense, document.SourceDistanceAccuracyMillimetres ?? 0d);
if (!trimResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromEllipse(ellipseResult.Value),
trimResult.Value));
}
var hyperbolaConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "HYPERBOLA");
if (hyperbolaConstructor is not null)
{
var hyperbolaResult = Step242SubsetDecoder.ReadHyperbolaCurve(document, WithConstructor(curveEntity, hyperbolaConstructor));
if (!hyperbolaResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(hyperbolaResult.Diagnostics);
}
var trimResult = explicitTrim is { } specified
? KernelResult<ParameterInterval>.Success(specified)
: ComputeHyperbolaTrim(hyperbolaResult.Value, startPoint, endPoint, edgeSameSense);
if (!trimResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromHyperbola(hyperbolaResult.Value),
trimResult.Value));
}
var splineEntity = ResolveBSplineCurveEntity(curveEntity);
if (splineEntity is not null)
{
var splineResult = Step242SubsetDecoder.ReadBSplineCurveWithKnots(document, splineEntity);
if (!splineResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(splineResult.Diagnostics);
}
var rationalConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "RATIONAL_B_SPLINE_CURVE");
if (rationalConstructor is not null)
{
var rationalEntity = WithConstructor(curveEntity, rationalConstructor);
var weightsResult = Step242SubsetDecoder.ReadRationalBSplineCurveWeights(rationalEntity);
if (!weightsResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(weightsResult.Diagnostics);
}
var weights = weightsResult.Value;
if (weights.Count != splineResult.Value.ControlPoints.Count
|| weights.Any(w => !double.IsFinite(w) || w <= 0d))
return FailureCurveBinding($"RATIONAL_B_SPLINE_CURVE #{curveEntity.Id} has invalid weights: expected one positive finite weight per control point.",
SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineCurve"));
// Uniform weights cancel in the rational quotient, even when their common value is not one.
var hasMaterialRationalWeights = weights.Any(w => double.Abs(w / weights[0] - 1d) > 1e-12d);
if (!hasMaterialRationalWeights)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromBSpline(splineResult.Value),
explicitTrim ?? InferSplineEdgeTrim(splineResult.Value, startPoint, endPoint, edgeSameSense)));
}
var recoveryDecision = Step242BsplineCurveRecoveryLane.Decide(curveEntity, splineResult.Value, weights);
if (recoveryDecision.RecoveredCurve is CurveGeometry recoveredCurve)
{
var trimResult = recoveredCurve.Kind == CurveGeometryKind.Circle3 && recoveredCurve.Circle3 is Circle3Curve recoveredCircle
? ComputeCircleTrim(recoveredCircle, startPoint, endPoint, edgeSameSense)
: KernelResult<ParameterInterval>.Success(new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd));
if (!trimResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((recoveredCurve, trimResult.Value));
}
if (BSplineCurveRationalReduction.TryReduce(splineResult.Value, weights,
document.RecoveryToleranceMillimetres, out var reduced, out var deviation, out var reductionReason))
{
var provenance = new SplineRecoveryProvenance("RATIONAL_B_SPLINE_CURVE", "AdaptiveCubic",
document.RecoveryToleranceMillimetres, deviation, true, recoveryDecision.Reason);
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromRecoveredBSpline(reduced, provenance),
explicitTrim ?? new ParameterInterval(reduced.DomainStart, reduced.DomainEnd)),
[new KernelDiagnostic(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info,
$"Rational curve #{curveEntity.Id}: analytic recognition failed; generic spline recovered. {reductionReason}",
SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineRecovered"))]);
}
return FailureCurveBinding(
$"RATIONAL_B_SPLINE_CURVE #{curveEntity.Id}: analytic recognition failed ({recoveryDecision.Reason}); generic recovery failed: {reductionReason}",
SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineCurve"));
}
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromBSpline(splineResult.Value),
explicitTrim ?? InferSplineEdgeTrim(splineResult.Value, startPoint, endPoint, edgeSameSense)));
}
if (string.Equals(curveEntity.Name, "AETHERIS_PLANAR_UNSUPPORTED_CURVE", StringComparison.OrdinalIgnoreCase))
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromUnsupported(curveEntity.Name),
new ParameterInterval(0d, 1d)));
}
return FailureCurveBinding($"EDGE_CURVE geometry '{curveEntity.Name}' is unsupported.", SourceFor(curveEntity.Id, "Importer.EntityFamily"));
}
private static bool TryOrderUniqueDirectedCycle(IReadOnlyList<Coedge> source, TopologyModel topology, out List<Coedge> ordered)
{
ordered = [];
var outgoing = source.GroupBy(c => DirectedEdgeUse.Resolve(topology.GetEdge(c.EdgeId), c).StartVertexId).ToArray();
if (outgoing.Any(group => group.Count() != 1)) return false;
var byStart = outgoing.ToDictionary(group => group.Key, group => group.Single());
var used = new HashSet<CoedgeId>(); var next = source[0];
while (used.Add(next.Id))
{
ordered.Add(next);
if (!byStart.TryGetValue(DirectedEdgeUse.Resolve(topology.GetEdge(next.EdgeId), next).EndVertexId, out next!)) return false;
}
if (next.Id != source[0].Id || ordered.Count != source.Count || ordered.Select(c => c.Id).SequenceEqual(source.Select(c => c.Id))) return false;
for (var i = 0; i < ordered.Count; i++) ordered[i] = ordered[i] with {
NextCoedgeId = ordered[(i + 1) % ordered.Count].Id, PrevCoedgeId = ordered[(i + ordered.Count - 1) % ordered.Count].Id };
return true;
}
// EDGE_CURVE vertices trim a basis spline even without a TRIMMED_CURVE wrapper.
// Accept only unique, measured endpoint inverses; unresolved cases stay importable
// with their original interval and are rejected by enforced export preflight.
private static ParameterInterval InferSplineEdgeTrim(BSpline3Curve curve, Point3D start, Point3D end, bool sameSense)
{
var domain = new ParameterInterval(curve.DomainStart, curve.DomainEnd);
const double tolerance = 1e-6;
if (!Find(sameSense ? start : end, domain.Start, out var a)
|| !Find(sameSense ? end : start, domain.End, out var b) || b <= a) return domain;
return new(a, b);
bool Find(Point3D point, double preferred, out double parameter)
{
parameter = preferred;
if ((curve.Evaluate(preferred) - point).Length <= tolerance) return true;
var candidates = new List<double>();
double Error(double t) => (curve.Evaluate(t) - point).Length;
foreach (var span in curve.GetNonZeroKnotSpans(domain))
{
const int divisions = 16;
var samples = Enumerable.Range(0, divisions + 1).Select(i => span.Start + (span.End - span.Start) * i / divisions).ToArray();
var errors = samples.Select(Error).ToArray();
for (var i = 0; i <= divisions; i++)
{
if (i > 0 && errors[i] > errors[i - 1] || i < divisions && errors[i] > errors[i + 1]) continue;
var lo = samples[System.Math.Max(0, i - 1)]; var hi = samples[System.Math.Min(divisions, i + 1)];
const double ratio = .6180339887498949;
var l = hi - (hi - lo) * ratio; var r = lo + (hi - lo) * ratio;
for (var iteration = 0; iteration < 64; iteration++)
if (Error(l) <= Error(r)) { hi = r; r = l; l = hi - (hi - lo) * ratio; }
else { lo = l; l = r; r = lo + (hi - lo) * ratio; }
var t = (lo + hi) / 2;
if (Error(t) <= tolerance && !candidates.Any(c => double.Abs(c - t) <= (domain.End - domain.Start) * 1e-7)) candidates.Add(t);
}
}
if (candidates.Count != 1) return false;
parameter = candidates[0]; return true;
}
}
private static KernelResult<ParameterInterval> ReadParameterTrim(
Step242Value startValue,
Step242Value endValue,
Step242Value senseValue,
int edgeCurveEntityId)
{
static bool TryReadParameter(Step242Value value, out double parameter)
{
parameter = double.NaN;
if (value is not Step242ListValue { Items.Count: 1 } list
|| list.Items[0] is not Step242TypedValue { Name: var typeName, Arguments.Count: 1 } typed
|| !string.Equals(typeName, "PARAMETER_VALUE", StringComparison.OrdinalIgnoreCase)
|| typed.Arguments[0] is not Step242NumberValue number
|| !double.IsFinite(number.Value))
{
return false;
}
parameter = number.Value;
return true;
}
if (!TryReadParameter(startValue, out var start) || !TryReadParameter(endValue, out var end)
|| senseValue is not Step242BooleanValue { Value: var sameSense })
{
var failure = FailureCurveBinding("TRIMMED_CURVE parameter trim is malformed.", SourceFor(edgeCurveEntityId, "Importer.Geometry.TrimmedCurve"));
return KernelResult<ParameterInterval>.Failure(failure.Diagnostics);
}
if (!sameSense) (start, end) = (end, start);
if (end < start || !double.IsFinite(start) || !double.IsFinite(end))
{
var failure = FailureCurveBinding("TRIMMED_CURVE parameter interval is invalid.", SourceFor(edgeCurveEntityId, "Importer.Geometry.TrimmedCurve"));
return KernelResult<ParameterInterval>.Failure(failure.Diagnostics);
}
return KernelResult<ParameterInterval>.Success(new(start, end));
}
internal static Step242ParsedEntity? ResolveBSplineCurveEntity(Step242ParsedEntity curveEntity)
{
var splineWithKnotsConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "B_SPLINE_CURVE_WITH_KNOTS");
if (splineWithKnotsConstructor is null)
{
return null;
}
if (splineWithKnotsConstructor.Arguments.Count >= 9)
{
return WithConstructor(curveEntity, splineWithKnotsConstructor);
}
var splineConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "B_SPLINE_CURVE");
if (splineConstructor is null || splineConstructor.Arguments.Count < 5 || splineWithKnotsConstructor.Arguments.Count < 3)
{
return null;
}
var normalizedArguments = new List<Step242Value>(9)
{
Step242OmittedValue.Instance,
splineConstructor.Arguments[0],
splineConstructor.Arguments[1],
splineConstructor.Arguments[2],
splineConstructor.Arguments[3],
splineConstructor.Arguments[4],
splineWithKnotsConstructor.Arguments[0],
splineWithKnotsConstructor.Arguments[1],
splineWithKnotsConstructor.Arguments[2]
};
var normalizedConstructor = new Step242EntityConstructor("B_SPLINE_CURVE_WITH_KNOTS", normalizedArguments);
return WithConstructor(curveEntity, normalizedConstructor);
}
private static Step242ParsedEntity WithConstructor(Step242ParsedEntity entity, Step242EntityConstructor constructor) =>
new(entity.Id, new Step242SimpleEntityInstance(constructor));
private static KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)> DecodeSurfaceGeometry(
Step242ParsedDocument document,
Step242ParsedEntity? surfaceEntity,
string surfaceName,
IReadOnlyList<Step242Value>? inlineSurfaceArguments,
int nextSurfaceGeometryId,
int faceEntityId)
{
var normalizedName = surfaceName.ToUpperInvariant();
var surfaceToDecodeResult = surfaceEntity is null
? BuildInlineSurfaceEntity(faceEntityId, normalizedName, inlineSurfaceArguments)
: KernelResult<Step242ParsedEntity>.Success(surfaceEntity);
if (!surfaceToDecodeResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(surfaceToDecodeResult.Diagnostics);
}
var surfaceToDecode = surfaceToDecodeResult.Value;
var geometryId = new SurfaceGeometryId(nextSurfaceGeometryId);
if (string.Equals(normalizedName, "PLANE", StringComparison.Ordinal))
{
var planeResult = Step242SubsetDecoder.ReadPlaneSurface(document, surfaceToDecode);
if (!planeResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(planeResult.Diagnostics);
}
// ADVANCED_FACE.same_sense is not folded into the stored surface. It used to be, for planes only, which
// made planes the one surface kind whose stored normal already carried the face sense while the binding
// recorded it as well - so every consumer that honoured the binding flipped a plane twice, and a plane
// face with same_sense=.F. inverted its normal on every export/import cycle. The stored surface is now
// exactly what the file stated for every kind. The shell solver records source orientation separately
// and projects one ResolvedFaceOrientation. A cylinder normal cannot be negated without
// flipping its axis, which would change the parameterization the trim intervals are written against.
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId, SurfaceGeometry.FromPlane(planeResult.Value)));
}
if (string.Equals(normalizedName, "CYLINDRICAL_SURFACE", StringComparison.Ordinal))
{
var cylinderResult = Step242SubsetDecoder.ReadCylindricalSurface(document, surfaceToDecode);
if (!cylinderResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(cylinderResult.Diagnostics);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId, SurfaceGeometry.FromCylinder(cylinderResult.Value)));
}
if (string.Equals(normalizedName, "SPHERICAL_SURFACE", StringComparison.Ordinal))
{
var sphereResult = Step242SubsetDecoder.ReadSphericalSurface(document, surfaceToDecode);
if (!sphereResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(sphereResult.Diagnostics);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId, SurfaceGeometry.FromSphere(sphereResult.Value)));
}
if (string.Equals(normalizedName, "CONICAL_SURFACE", StringComparison.Ordinal))
{
var coneResult = Step242SubsetDecoder.ReadConicalSurface(document, surfaceToDecode);
if (!coneResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(coneResult.Diagnostics);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId, SurfaceGeometry.FromCone(coneResult.Value)));
}
if (string.Equals(normalizedName, "TOROIDAL_SURFACE", StringComparison.Ordinal))
{
var torusResult = Step242SubsetDecoder.ReadToroidalSurface(document, surfaceToDecode);
if (!torusResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(torusResult.Diagnostics);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId, SurfaceGeometry.FromTorus(torusResult.Value)));
}
if (string.Equals(normalizedName, "SURFACE_OF_LINEAR_EXTRUSION", StringComparison.Ordinal))
{
var linearExtrusionResult = Step242SubsetDecoder.ReadLinearExtrusionSurface(document, surfaceToDecode);
if (!linearExtrusionResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(linearExtrusionResult.Diagnostics);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((
geometryId,
SurfaceGeometry.FromLinearExtrusion(linearExtrusionResult.Value)));
}
if (string.Equals(normalizedName, "SURFACE_OF_REVOLUTION", StringComparison.Ordinal))
{
var surfaceOfRevolutionResult = Step242SubsetDecoder.ReadSurfaceOfRevolution(document, surfaceToDecode);
if (!surfaceOfRevolutionResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(surfaceOfRevolutionResult.Diagnostics);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((
geometryId,
SurfaceGeometry.FromSurfaceOfRevolution(surfaceOfRevolutionResult.Value)));
}
var bSplineSurfaceEntity = ResolveBSplineSurfaceEntity(surfaceToDecode);
if (bSplineSurfaceEntity is not null)
{
var surfaceResult = Step242SubsetDecoder.ReadBSplineSurfaceWithKnots(document, bSplineSurfaceEntity);
if (!surfaceResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(surfaceResult.Diagnostics);
}
var bSplineSurface = surfaceResult.Value;
var rationalSurface = Step242SubsetDecoder.TryGetConstructor(surfaceToDecode.Instance, "RATIONAL_B_SPLINE_SURFACE");
if (rationalSurface is not null)
{
// The weights have to be read before recovery runs: dropping them turns a NURBS face into a
// different polynomial surface, and recovery would then be judging geometry the file never stated.
var weightsResult = Step242SubsetDecoder.ReadRationalBSplineSurfaceWeights(WithConstructor(surfaceToDecode, rationalSurface));
if (!weightsResult.IsSuccess)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(weightsResult.Diagnostics);
}
try
{
bSplineSurface = bSplineSurface.WithWeights(weightsResult.Value);
}
catch (ArgumentException ex)
{
return FailureSurfaceBinding($"RATIONAL_B_SPLINE_SURFACE weights are inconsistent with the control net: {ex.Message}", SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineSurface"));
}
}
var recoveryDecision = Step242BsplineSurfaceRecoveryLane.Decide(bSplineSurface, document.SourceDistanceAccuracyMillimetres);
if (recoveryDecision.RecoveredSurface is { } recoveredSurface)
{
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(
(geometryId, recoveredSurface),
[new KernelDiagnostic(
KernelDiagnosticCode.Unknown,
KernelDiagnosticSeverity.Info,
$"Spline surface #{surfaceToDecode.Id} was recovered as an analytic {recoveredSurface.Kind}: {recoveryDecision.Reason}",
SourceFor(surfaceToDecode.Id, "Importer.Geometry.BsplineSurfaceRecovery"))]);
}
// What is left is a genuine free-form blend. It still must not enter the kernel as a NURBS, so it is
// reduced to a non-rational spline that follows it well inside the accuracy the source file declares.
if (bSplineSurface.IsRational && !RationalSurfacesArePreserved)
{
var sourceReductionTolerance = BSplineSurfaceRationalReduction.ResolveTolerance(
bSplineSurface, document.SourceDistanceAccuracyMillimetres);
// Source accuracies that would drive this approximate interchange conversion below
// 10 nm can require pathological control-net growth. Keep established source-accuracy
// behavior for ordinary files, and use the caller's engineering budget for that case.
var reductionTolerance = sourceReductionTolerance < 1e-5d
? document.RecoveryToleranceMillimetres
: double.Min(document.RecoveryToleranceMillimetres, sourceReductionTolerance);
if (BSplineSurfaceRationalReduction.TryReduce(bSplineSurface, reductionTolerance, out var reducedSurface, out var deviation, out var reductionReason)
&& reducedSurface is not null)
{
var provenance = new SplineRecoveryProvenance("RATIONAL_B_SPLINE_SURFACE", "AdaptiveGreville",
document.RecoveryToleranceMillimetres, deviation, true, recoveryDecision.Reason);
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(
(geometryId, SurfaceGeometry.FromRecoveredBSplineSurfaceWithKnots(reducedSurface, provenance)),
[new KernelDiagnostic(
KernelDiagnosticCode.Unknown,
KernelDiagnosticSeverity.Info,
$"Spline surface #{surfaceToDecode.Id} is a free-form blend that no analytic primitive covers ({recoveryDecision.Reason}), and was reduced to a non-rational spline that {reductionReason}.",
SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineReduced"))]);
}
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(
(geometryId, SurfaceGeometry.FromBSplineSurfaceWithKnots(bSplineSurface)),
[new KernelDiagnostic(
KernelDiagnosticCode.Unknown,
KernelDiagnosticSeverity.Warning,
$"Spline surface #{surfaceToDecode.Id} stays a rational B-spline: no analytic primitive verified ({recoveryDecision.Reason}), and reduction to a non-rational spline {reductionReason}.",
SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineRetained"))]);
}
var retentionDiagnostics = bSplineSurface.IsRational
? new[]
{
new KernelDiagnostic(
KernelDiagnosticCode.Unknown,
KernelDiagnosticSeverity.Info,
$"Spline surface #{surfaceToDecode.Id} is retained as a rational B-spline because rational surfaces are preserved for this import: {recoveryDecision.Reason}",
SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplinePreserved"))
}
: [];
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((
geometryId,
SurfaceGeometry.FromBSplineSurfaceWithKnots(bSplineSurface)),
retentionDiagnostics);
}
return FailureSurfaceBinding($"ADVANCED_FACE surface '{surfaceName}' is unsupported.", SourceFor(surfaceToDecode.Id, "Importer.EntityFamily"));
}
private static Step242ParsedEntity? ResolveBSplineSurfaceEntity(Step242ParsedEntity surfaceEntity)
{
var splineWithKnots = Step242SubsetDecoder.TryGetConstructor(surfaceEntity.Instance, "B_SPLINE_SURFACE_WITH_KNOTS");
if (splineWithKnots is null)
{
return null;
}
if (splineWithKnots.Arguments.Count >= 13)
{
return WithConstructor(surfaceEntity, splineWithKnots);
}
var splineSurface = Step242SubsetDecoder.TryGetConstructor(surfaceEntity.Instance, "B_SPLINE_SURFACE");
if (splineSurface is null || splineSurface.Arguments.Count < 7 || splineWithKnots.Arguments.Count < 5)
{
return null;
}
var normalized = new List<Step242Value>(13)
{
Step242OmittedValue.Instance,
splineSurface.Arguments[0],
splineSurface.Arguments[1],
splineSurface.Arguments[2],
splineSurface.Arguments[3],
splineSurface.Arguments[4],
splineSurface.Arguments[5],
splineSurface.Arguments[6],
splineWithKnots.Arguments[0],
splineWithKnots.Arguments[1],
splineWithKnots.Arguments[2],
splineWithKnots.Arguments[3],
splineWithKnots.Arguments[4]
};
return WithConstructor(surfaceEntity, new Step242EntityConstructor("B_SPLINE_SURFACE_WITH_KNOTS", normalized));
}
private static KernelResult<Step242ParsedEntity> BuildInlineSurfaceEntity(int faceEntityId, string surfaceName, IReadOnlyList<Step242Value>? inlineArguments)
{
if (inlineArguments is null)
{
return FailureInlineSurface<Step242ParsedEntity>("ADVANCED_FACE surface: inline constructor arguments are required.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (!string.Equals(surfaceName, "PLANE", StringComparison.Ordinal)
&& !string.Equals(surfaceName, "CYLINDRICAL_SURFACE", StringComparison.Ordinal)
&& !string.Equals(surfaceName, "CONICAL_SURFACE", StringComparison.Ordinal)
&& !string.Equals(surfaceName, "SPHERICAL_SURFACE", StringComparison.Ordinal)
&& !string.Equals(surfaceName, "TOROIDAL_SURFACE", StringComparison.Ordinal)
&& !string.Equals(surfaceName, "SURFACE_OF_LINEAR_EXTRUSION", StringComparison.Ordinal)
&& !string.Equals(surfaceName, "SURFACE_OF_REVOLUTION", StringComparison.Ordinal))
{
return FailureInlineSurface<Step242ParsedEntity>($"ADVANCED_FACE surface: inline constructor '{surfaceName}' is not supported in this subset.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
var normalizedArgumentsResult = NormalizeInlineSurfaceArguments(surfaceName, inlineArguments, faceEntityId);
if (!normalizedArgumentsResult.IsSuccess)
{
return KernelResult<Step242ParsedEntity>.Failure(normalizedArgumentsResult.Diagnostics);
}
return KernelResult<Step242ParsedEntity>.Success(new Step242ParsedEntity(
faceEntityId,
new Step242SimpleEntityInstance(new Step242EntityConstructor(surfaceName, normalizedArgumentsResult.Value))));
}
private static KernelResult<IReadOnlyList<Step242Value>> NormalizeInlineSurfaceArguments(string surfaceName, IReadOnlyList<Step242Value> inlineArguments, int faceEntityId)
{
if (string.Equals(surfaceName, "PLANE", StringComparison.Ordinal))
{
if (inlineArguments.Count == 1)
{
if (inlineArguments[0] is not Step242EntityReference)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("ADVANCED_FACE surface: inline PLANE constructor expects PLANE(#axis2_placement_3d).", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0]
]);
}
if (inlineArguments.Count == 2)
{
if (inlineArguments[0] is not Step242OmittedValue || inlineArguments[1] is not Step242EntityReference)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("ADVANCED_FACE surface: inline PLANE constructor expects PLANE(#axis2_placement_3d).", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("ADVANCED_FACE surface: inline PLANE constructor expects PLANE(#axis2_placement_3d).", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (string.Equals(surfaceName, "CYLINDRICAL_SURFACE", StringComparison.Ordinal))
{
if (inlineArguments.Count == 2)
{
if (inlineArguments[0] is not Step242EntityReference || inlineArguments[1] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'CYLINDRICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0],
inlineArguments[1]
]);
}
if (inlineArguments.Count == 3)
{
if (inlineArguments[0] is not Step242OmittedValue || inlineArguments[1] is not Step242EntityReference || inlineArguments[2] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'CYLINDRICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'CYLINDRICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (string.Equals(surfaceName, "CONICAL_SURFACE", StringComparison.Ordinal))
{
if (inlineArguments.Count == 3)
{
if (inlineArguments[0] is not Step242EntityReference
|| inlineArguments[1] is not Step242NumberValue
|| inlineArguments[2] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'CONICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0],
inlineArguments[1],
inlineArguments[2]
]);
}
if (inlineArguments.Count == 4)
{
if (inlineArguments[0] is not Step242OmittedValue
|| inlineArguments[1] is not Step242EntityReference
|| inlineArguments[2] is not Step242NumberValue
|| inlineArguments[3] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'CONICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'CONICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (string.Equals(surfaceName, "SPHERICAL_SURFACE", StringComparison.Ordinal))
{
if (inlineArguments.Count == 2)
{
if (inlineArguments[0] is not Step242EntityReference || inlineArguments[1] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SPHERICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0],
inlineArguments[1]
]);
}
if (inlineArguments.Count == 3)
{
if (inlineArguments[0] is not Step242OmittedValue || inlineArguments[1] is not Step242EntityReference || inlineArguments[2] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SPHERICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SPHERICAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (string.Equals(surfaceName, "TOROIDAL_SURFACE", StringComparison.Ordinal))
{
if (inlineArguments.Count == 3)
{
if (inlineArguments[0] is not Step242EntityReference
|| inlineArguments[1] is not Step242NumberValue
|| inlineArguments[2] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'TOROIDAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0],
inlineArguments[1],
inlineArguments[2]
]);
}
if (inlineArguments.Count == 4)
{
if (inlineArguments[0] is not Step242OmittedValue
|| inlineArguments[1] is not Step242EntityReference
|| inlineArguments[2] is not Step242NumberValue
|| inlineArguments[3] is not Step242NumberValue)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'TOROIDAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'TOROIDAL_SURFACE' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (string.Equals(surfaceName, "SURFACE_OF_LINEAR_EXTRUSION", StringComparison.Ordinal))
{
if (inlineArguments.Count == 2)
{
if (inlineArguments[0] is not Step242EntityReference || inlineArguments[1] is not Step242EntityReference)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SURFACE_OF_LINEAR_EXTRUSION' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0],
inlineArguments[1]
]);
}
if (inlineArguments.Count == 3)
{
if (inlineArguments[0] is not Step242OmittedValue
|| inlineArguments[1] is not Step242EntityReference
|| inlineArguments[2] is not Step242EntityReference)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SURFACE_OF_LINEAR_EXTRUSION' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SURFACE_OF_LINEAR_EXTRUSION' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
if (string.Equals(surfaceName, "SURFACE_OF_REVOLUTION", StringComparison.Ordinal))
{
if (inlineArguments.Count == 2)
{
if (inlineArguments[0] is not Step242EntityReference || inlineArguments[1] is not Step242EntityReference)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SURFACE_OF_REVOLUTION' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success([
Step242OmittedValue.Instance,
inlineArguments[0],
inlineArguments[1]
]);
}
if (inlineArguments.Count == 3)
{
if (inlineArguments[0] is not Step242OmittedValue
|| inlineArguments[1] is not Step242EntityReference
|| inlineArguments[2] is not Step242EntityReference)
{
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SURFACE_OF_REVOLUTION' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
return FailureInlineSurface<IReadOnlyList<Step242Value>>("Inline ADVANCED_FACE.surface constructor 'SURFACE_OF_REVOLUTION' has unsupported argument shape.", SourceFor(faceEntityId, "Importer.StepSyntax.InlineEntity"));
}
return KernelResult<IReadOnlyList<Step242Value>>.Success(inlineArguments);
}
private static KernelResult<T> FailureInlineSurface<T>(string message, string source)
=> KernelResult<T>.Failure([
new KernelDiagnostic(
KernelDiagnosticCode.NotImplemented,
KernelDiagnosticSeverity.Error,
message,
source)
]);
internal static KernelResult<ParameterInterval> ComputeEllipseTrim(Ellipse3Curve ellipse, Point3D startPoint, Point3D endPoint, bool edgeSameSense, double sourceAccuracy = 0d)
{
var tolerance = ComputeEllipseTrimTolerance(ellipse, startPoint, endPoint);
// A vertex need only lie within the source's declared distance accuracy of its curve. That widens the
// projection only; empty and full spans keep the geometric tolerance.
var projection = double.Max(tolerance, sourceAccuracy);
var startAngleResult = ProjectPointToEllipseAngle(ellipse, startPoint, projection);
if (!startAngleResult.IsSuccess)
{
return KernelResult<ParameterInterval>.Failure(startAngleResult.Diagnostics);
}
var endAngleResult = ProjectPointToEllipseAngle(ellipse, endPoint, projection);
if (!endAngleResult.IsSuccess)
{
return KernelResult<ParameterInterval>.Failure(endAngleResult.Diagnostics);
}
var intervalResult = CanonicalizeCircleTrimInterval(startAngleResult.Value, endAngleResult.Value, tolerance, edgeSameSense);
if (!intervalResult.IsSuccess)
{
return FailureEllipseTrim(intervalResult.Diagnostics[0].Message, intervalResult.Diagnostics[0].Source);
}
return intervalResult;
}
private static KernelResult<double> ProjectPointToEllipseAngle(Ellipse3Curve ellipse, Point3D point, double tolerance)
{
var centerToPoint = point - ellipse.Center;
var normal = ellipse.Normal.ToVector();
var normalComponent = centerToPoint.Dot(normal);
if (double.Abs(normalComponent) > tolerance)
{
return FailureEllipseTrimAngle($"Unable to project elliptical trim point: off-ellipse plane deviation {double.Abs(normalComponent):G17} exceeds tolerance {tolerance:G17}.", "Importer.Geometry.EllipseTrim.OffPlane");
}
var inPlane = centerToPoint - (normal * normalComponent);
var majorComponent = inPlane.Dot(ellipse.XAxis.ToVector());
var minorComponent = inPlane.Dot(ellipse.YAxis.ToVector());
var normalizedMajor = majorComponent / ellipse.MajorRadius;
var normalizedMinor = minorComponent / ellipse.MinorRadius;
var radialError = double.Abs((normalizedMajor * normalizedMajor) + (normalizedMinor * normalizedMinor) - 1d);
if (radialError > System.Math.Max(1e-8d, tolerance / System.Math.Max(1d, ellipse.MajorRadius)))
{
return FailureEllipseTrimAngle($"Unable to project elliptical trim point: normalized radial deviation {radialError:G17} exceeds tolerance.", "Importer.Geometry.EllipseTrim.OffRadius");
}
return KernelResult<double>.Success(double.Atan2(normalizedMinor, normalizedMajor));
}
private static double ComputeEllipseTrimTolerance(Ellipse3Curve ellipse, Point3D startPoint, Point3D endPoint)
{
var scale = System.Math.Max(ellipse.MajorRadius, System.Math.Max((startPoint - ellipse.Center).Length, (endPoint - ellipse.Center).Length));
return System.Math.Max(1e-6d, scale * 1e-8d);
}
internal static KernelResult<ParameterInterval> ComputeCircleTrim(Circle3Curve circle, Point3D startPoint, Point3D endPoint, bool edgeSameSense, double sourceAccuracy = 0d)
{
var tolerance = ComputeCircleTrimTolerance(circle, startPoint, endPoint);
// Vertices within the source's declared accuracy of the circle project; spans keep the geometric tolerance.
var projection = double.Max(tolerance, sourceAccuracy);
if ((startPoint - endPoint).Length <= tolerance)
{
// A closed circular edge starts wherever its vertex sits (CAD exporters frequently put the seam
// vertex away from the circle's parameter origin), so the full-circle trim must begin at that angle or
// the curve's trim endpoints no longer coincide with the edge's vertices.
var seamAngle = ProjectPointToCircleAngle(circle, startPoint, projection);
if (seamAngle.IsSuccess && seamAngle.Value > 1e-9d && seamAngle.Value < (2d * double.Pi) - 1e-9d)
{
return KernelResult<ParameterInterval>.Success(new ParameterInterval(seamAngle.Value, seamAngle.Value + (2d * double.Pi)));
}
return KernelResult<ParameterInterval>.Success(new ParameterInterval(0d, 2d * double.Pi));
}
var startAngleResult = ProjectPointToCircleAngle(circle, startPoint, projection);
if (!startAngleResult.IsSuccess)
{
return KernelResult<ParameterInterval>.Failure(startAngleResult.Diagnostics);
}
var endAngleResult = ProjectPointToCircleAngle(circle, endPoint, projection);
if (!endAngleResult.IsSuccess)
{
return KernelResult<ParameterInterval>.Failure(endAngleResult.Diagnostics);
}
// The tolerance is a linear distance. Coincident endpoints were already treated as a full circle above, so the
// angular threshold for "empty" or "full" spans must be that distance divided by the radius; using the raw
// linear value made every arc shorter than ~0.0123 rad on a 25 mm circle (gear-tooth sub-arcs) look like a full circle.
var intervalResult = CanonicalizeCircleTrimInterval(startAngleResult.Value, endAngleResult.Value, tolerance / double.Max(circle.Radius, tolerance), edgeSameSense);
if (!intervalResult.IsSuccess)
{
return KernelResult<ParameterInterval>.Failure(intervalResult.Diagnostics);
}
return KernelResult<ParameterInterval>.Success(intervalResult.Value);
}
private static KernelResult<double> ProjectPointToCircleAngle(Circle3Curve circle, Point3D point, double tolerance)
{
var radial = point - circle.Center;
var normalComponent = radial.Dot(circle.Normal.ToVector());
var inPlane = radial - (circle.Normal.ToVector() * normalComponent);
var inPlaneLength = inPlane.Length;
if (double.Abs(normalComponent) > tolerance)
{
return FailureCircleTrimAngle($"Unable to project circular trim point: off-circle plane deviation {double.Abs(normalComponent):G17} exceeds tolerance {tolerance:G17}.", "Importer.Geometry.CircleTrim.OffPlane");
}
if (double.Abs(inPlaneLength - circle.Radius) > tolerance)
{
return FailureCircleTrimAngle($"Unable to project circular trim point: radial deviation {double.Abs(inPlaneLength - circle.Radius):G17} exceeds tolerance {tolerance:G17}.", "Importer.Geometry.CircleTrim.OffRadius");
}
if (inPlaneLength <= tolerance)
{
return FailureCircleTrimAngle("Unable to project circular trim point: projected in-plane radius is degenerate.", "Importer.Geometry.CircleTrim.DegeneratePoint");
}
var projected = inPlane * (circle.Radius / inPlaneLength);
var x = projected.Dot(circle.XAxis.ToVector());
var y = projected.Dot(circle.YAxis.ToVector());
var angle = double.Atan2(y, x);
if (angle < 0d)
{
angle += 2d * double.Pi;
}
return KernelResult<double>.Success(angle);
}
private static double ComputeCircleTrimTolerance(Circle3Curve circle, Point3D startPoint, Point3D endPoint)
{
const double baseTolerance = 1e-6d;
// Circle-trim projection tolerance is intentionally bounded and geometry-scale-aware:
// - lower-bounded by baseTolerance to avoid denorm/zero-scale instability,
// - scaled by local circle/endpoint size to absorb exporter drift observed in AP242 corpus files,
// - scoped to circle-trim recovery only (not a global tolerance loosening knob).
const double scaleFactor = 5e-4d;
var startRadius = (startPoint - circle.Center).Length;
var endRadius = (endPoint - circle.Center).Length;
var scale = double.Max(1d, double.Max(circle.Radius, double.Max(startRadius, endRadius)));
return double.Max(baseTolerance, scale * scaleFactor);
}
private static KernelResult<ParameterInterval> CanonicalizeCircleTrimInterval(double startAngle, double endAngle, double tolerance, bool edgeSameSense)
{
var start = NormalizeAngle(startAngle);
var end = NormalizeAngle(endAngle);
var canonicalStart = edgeSameSense ? start : end;
var canonicalEnd = edgeSameSense ? end : start;
var span = NormalizePositiveAngle(canonicalEnd - canonicalStart);
var angleTolerance = tolerance;
if (span <= angleTolerance)
{
return KernelResult<ParameterInterval>.Success(new ParameterInterval(0d, 2d * double.Pi));
}
if (span >= (2d * double.Pi) - angleTolerance)
{
return KernelResult<ParameterInterval>.Success(new ParameterInterval(0d, 2d * double.Pi));
}
// A start on the seam reads as 2pi-e or +e depending on how the coordinates were rounded, so the trim
// would land a whole turn apart for the same file written twice. Keep it on the turn that starts at 0;
// face traces written against this trim (Step242Exporter's period shift) rely on that.
if (canonicalStart >= (2d * double.Pi) - angleTolerance) canonicalStart -= 2d * double.Pi;
var normalizedEnd = canonicalStart + span;
if (normalizedEnd <= canonicalStart)
{
return FailureCircleTrim("Unable to compute circle trim interval with a positive span after canonicalization.", "Importer.Geometry.CircleTrim.Interval");
}
return KernelResult<ParameterInterval>.Success(new ParameterInterval(canonicalStart, normalizedEnd));
}
private static double NormalizeAngle(double angle)
{
var period = 2d * double.Pi;
var normalized = angle % period;
if (normalized < 0d)
{
normalized += period;
}
if (normalized >= period)
{
normalized -= period;
}
return normalized;
}
private static double NormalizePositiveAngle(double angle)
{
var period = 2d * double.Pi;
var normalized = angle % period;
if (normalized < 0d)
{
normalized += period;
}
return normalized;
}
private static double ComputeLineParameter(Line3Curve line, Point3D point)
{
var offset = point - line.Origin;
return offset.Dot(line.Direction.ToVector());
}
private static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizeFaceLoops(
int faceEntityId,
IReadOnlyList<LoopBuildData> loops,
SurfaceGeometry surface,
double nearCoincidentTolerance)
{
if (loops.Count <= 1)
{
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops);
}
// STEP carries loop role explicitly: FACE_OUTER_BOUND is not a hint to be
// replaced by an area/winding heuristic. Reordering or reversing a
// declared EDGE_LOOP here loses source topology and can turn a void into
// material after a round trip. The legacy classifier is used only as a
// derivative validator when a declared outer bound exists; its rewritten
// traversal is never substituted for the imported evidence.
var declaredOuterCount = loops.Count(loop => loop.IsDeclaredOuter);
if (declaredOuterCount == 1)
{
if (surface.Kind == SurfaceGeometryKind.Sphere)
{
// A spherical lattice node uses multiple trim loops as source
// topology rather than a planar material-region-with-hole. It
// has an explicit outer-bound declaration, so retain that
// evidence without inventing a planar containment model.
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops);
}
// Keep the declared traversal authoritative, but still run the
// established geometric classifier as a *derivative validator*.
// Besides rejecting a declared hole outside its outer bound, this
// retains the periodic-surface projection diagnostics used by the
// corpus tests. Its normalized output is deliberately discarded:
// import must not silently reorder or reverse STEP evidence.
var validation = surface.Kind switch
{
SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value, nearCoincidentTolerance),
SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),
SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),
SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),
// A non-rational B-spline has no universal planar containment projection.
// Preserve the explicit FACE_OUTER_BOUND/FACE_BOUND contract; pcurve and
// curve-on-surface qualification is handled independently by the BRep layer.
SurfaceGeometryKind.BSplineSurfaceWithKnots => KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops),
_ => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
$"Multi-loop hole classification is unsupported for surface type '{surface.Kind}'.",
$"Importer.LoopRole.UnsupportedSurfaceForHoles.{surface.Kind}")
};
return validation.IsSuccess
? KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops)
: KernelResult<IReadOnlyList<LoopBuildData>>.Failure(validation.Diagnostics);
}
if (declaredOuterCount > 1)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
$"FACE has {declaredOuterCount} FACE_OUTER_BOUND declarations; exactly one is required.",
$"Importer.LoopRole.DuplicateDeclaredOuter.Face:{faceEntityId}");
}
return surface.Kind switch
{
SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value, nearCoincidentTolerance),
SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),
SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),
SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),
SurfaceGeometryKind.Sphere => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
"Multi-loop spherical faces require an explicit FACE_OUTER_BOUND declaration.",
"Importer.LoopRole.UnsupportedSurfaceForHoles.Sphere"),
_ => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
$"Multi-loop hole classification is unsupported for surface type '{surface.Kind}'.",
$"Importer.LoopRole.UnsupportedSurfaceForHoles.{surface.Kind}")
};
}
private static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizePlanarLoops(
IReadOnlyList<LoopBuildData> loops,
PlaneSurface plane,
double nearCoincidentTolerance)
{
var infos = new List<PlanarLoopInfo>(loops.Count);
foreach (var loop in loops)
{
var projected = SimplifyClosedPolygon(ProjectLoopToPlane(loop.Samples, plane), ContainmentEps);
var uniqueCount = CountUniquePoints(projected, ContainmentEps);
var area = ComputeSignedArea(projected);
if (uniqueCount < 3 || double.Abs(area) <= AreaEps)
{
continue;
}
infos.Add(new PlanarLoopInfo(loop, projected, area));
}
if (infos.Count == 0)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Loop projection is degenerate and no non-degenerate boundary remained.", "Importer.LoopRole.DegenerateLoop");
}
var containmentTolerance = ComputeContainmentTolerance(infos.SelectMany(i => i.ProjectedPoints));
var areaTolerance = ComputeAreaTolerance(infos.SelectMany(i => i.ProjectedPoints));
var infosWithSamples = new List<PlanarLoopInfoWithSample>(infos.Count);
foreach (var info in infos)
{
var testPointResult = ChooseContainmentPoint(info.ProjectedPoints, containmentTolerance);
if (!testPointResult.IsSuccess)
{
return KernelResult<IReadOnlyList<LoopBuildData>>.Failure(testPointResult.Diagnostics);
}
infosWithSamples.Add(new PlanarLoopInfoWithSample(info, testPointResult.Value));
}
var orderedByContainmentThenArea = infosWithSamples
.Select(candidate =>
{
var containmentCount = infosWithSamples.Count(other => other.Info.Loop.LoopId != candidate.Info.Loop.LoopId
&& IsLoopContainedByOuter(other.Info.ProjectedPoints, candidate.Info.ProjectedPoints, containmentTolerance));
return new PlanarLoopOuterCandidate(candidate.Info, candidate.SamplePoint, containmentCount);
})
.OrderByDescending(c => c.ContainmentCount)
.ThenByDescending(c => double.Abs(c.Info.SignedArea))
.ThenBy(c => c.Info.Loop.LoopId.Value)
.ToList();
var outer = orderedByContainmentThenArea[0];
if (orderedByContainmentThenArea.Count > 1
&& outer.ContainmentCount == orderedByContainmentThenArea[1].ContainmentCount
&& double.Abs(double.Abs(outer.Info.SignedArea) - double.Abs(orderedByContainmentThenArea[1].Info.SignedArea)) <= areaTolerance)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Unable to choose a unique outer loop.", "Importer.LoopRole.AmbiguousOuter");
}
var containedInners = new List<PlanarLoopInfo>();
var declaredOuterCount = infosWithSamples.Count(i => i.Info.Loop.IsDeclaredOuter);
foreach (var candidate in infosWithSamples.Where(i => i.Info.Loop.LoopId != outer.Info.Loop.LoopId))
{
var containment = EvaluateContainment(candidate.Info.ProjectedPoints, outer.Info.ProjectedPoints, containmentTolerance);
var intersectionCount = CountPolygonIntersections(candidate.Info.ProjectedPoints, outer.Info.ProjectedPoints, containmentTolerance);
var intersectsOuter = intersectionCount > 0;
if ((!intersectsOuter && containment.OutsideCount == 0)
|| (intersectsOuter
&& containment.OutsideCount == 0
&& containment.MinDistanceToOuter > (containmentTolerance * 8d)))
{
containedInners.Add(candidate.Info);
continue;
}
if (double.Abs(candidate.Info.SignedArea) <= areaTolerance * 4d
|| IsPointNearPolygonEdge(candidate.SamplePoint, outer.Info.ProjectedPoints, containmentTolerance * 4d))
{
continue;
}
if (intersectsOuter
&& TryRecoverPlanarCrossingInnerWithJudgmentEngine(candidate.Info, outer.Info, containment, intersectionCount,
containmentTolerance, loops.Count, declaredOuterCount, nearCoincidentTolerance))
{
containedInners.Add(candidate.Info);
continue;
}
var failure = BuildInnerContainmentFailure(candidate.Info, outer.Info, containmentTolerance, areaTolerance, intersectionCount, candidate.Info.Loop.HasDisconnectedCoedgeGap || outer.Info.Loop.HasDisconnectedCoedgeGap);
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>(failure.Message, failure.Source);
}
var innerLoops = containedInners;
for (var i = 0; i < innerLoops.Count; i++)
{
for (var j = i + 1; j < innerLoops.Count; j++)
{
if (LoopsOverlap(innerLoops[i], innerLoops[j], containmentTolerance))
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Inner loops {innerLoops[i].Loop.LoopId.Value} and {innerLoops[j].Loop.LoopId.Value} overlap or are nested.", "Importer.LoopRole.InnerOverlap");
}
}
}
var normalizedOuter = NormalizeLoopWinding(outer.Info.Loop, outer.Info.SignedArea, shouldBePositive: true);
var normalizedInners = innerLoops
.OrderByDescending(i => double.Abs(i.SignedArea))
.ThenBy(i => i.Loop.LoopId.Value)
.Select(i => NormalizeLoopWinding(i.Loop, i.SignedArea, shouldBePositive: false))
.ToList();
var ordered = new List<LoopBuildData>(1 + normalizedInners.Count) { normalizedOuter };
ordered.AddRange(normalizedInners);
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(ordered);
}
private static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizeCylindricalLoops(
int faceEntityId,
IReadOnlyList<LoopBuildData> loops,
CylinderSurface cylinder)
{
const string nonNormalizableSource = "Importer.LoopRole.CylinderNonNormalizableDegenerateProjection";
const string ambiguousOuterSource = "Importer.LoopRole.CylinderAmbiguousOuter";
const string containmentSource = "Importer.LoopRole.CylinderInnerContainmentFailed";
var infos = new List<CylindricalLoopInfo>(loops.Count);
var degenerate = new List<(LoopBuildData Loop, CylinderProjectionAnalysis Analysis)>(loops.Count);
var maxUniqueCount = 0;
var maxAbsArea = 0d;
foreach (var loop in loops)
{
var projected = ProjectLoopToCylinder(loop.Samples, cylinder);
var uniqueCount = CountUniquePoints(projected, ContainmentEps);
var area = ComputeSignedArea(projected);
var analysis = AnalyzeCylindricalProjection(uniqueCount, area, projected);
maxUniqueCount = System.Math.Max(maxUniqueCount, uniqueCount);
maxAbsArea = System.Math.Max(maxAbsArea, double.Abs(area));
ReportCylinderProjectionDiagnostic(new LoopRoleCylinderProjectionDiagnostic(
FaceEntityId: faceEntityId,
LoopId: loop.LoopId.Value,
PointCount: projected.Count,
UniquePointCount: uniqueCount,
SignedArea: area,
AngularSpan: analysis.AngularSpan,
AxialSpan: analysis.AxialSpan,
SeamCrossings: analysis.SeamCrossings,
RepeatedSeamPointCount: analysis.RepeatedSeamPointCount,
Degeneracy: analysis.Degeneracy.ToString()));
if (uniqueCount < 3 || double.Abs(area) <= AreaEps)
{
degenerate.Add((loop, analysis));
continue;
}
infos.Add(new CylindricalLoopInfo(loop, projected, area, ComputePolygonCentroid(projected)));
}
var fullRevolutionConstantAxial = degenerate
.Where(d => d.Analysis.Degeneracy == CylinderProjectionDegeneracy.FullRevolutionConstantAxial)
.OrderBy(d => d.Loop.LoopId.Value)
.ToArray();
var otherDegenerate = degenerate
.Where(d => d.Analysis.Degeneracy != CylinderProjectionDegeneracy.FullRevolutionConstantAxial)
.OrderBy(d => d.Loop.LoopId.Value)
.ToArray();
if (fullRevolutionConstantAxial.Length > 0 && (otherDegenerate.Length > 0 || infos.Count > 0))
{
var normalizedMixedInners = infos
.OrderByDescending(i => double.Abs(i.SignedArea))
.ThenBy(i => i.Loop.LoopId.Value)
.Select(i => NormalizeLoopWinding(i.Loop, i.SignedArea, shouldBePositive: false));
var mixedOrdered = new List<LoopBuildData>(fullRevolutionConstantAxial.Length + otherDegenerate.Length + infos.Count);
mixedOrdered.AddRange(fullRevolutionConstantAxial.Select(d => d.Loop));
mixedOrdered.AddRange(otherDegenerate.Select(d => d.Loop));
mixedOrdered.AddRange(normalizedMixedInners);
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(mixedOrdered);
}
if (infos.Count == 0)
{
if (degenerate.All(d => d.Analysis.Degeneracy == CylinderProjectionDegeneracy.FullRevolutionConstantAxial))
{
var canonical = degenerate
.OrderBy(d => d.Loop.LoopId.Value)
.Select(d => d.Loop)
.ToArray();
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(canonical);
}
var primary = degenerate
.OrderByDescending(d => (int)d.Analysis.Degeneracy)
.ThenBy(d => d.Loop.LoopId.Value)
.FirstOrDefault();
var explicitSource = primary.Analysis.Degeneracy switch
{
CylinderProjectionDegeneracy.DegenerateAngularSpan => "Importer.LoopRole.CylinderDegenerateAngularSpan",
CylinderProjectionDegeneracy.DegenerateAxialSpan => "Importer.LoopRole.CylinderDegenerateAxialSpan",
CylinderProjectionDegeneracy.RepeatedSeamProjectionCollapse => "Importer.LoopRole.CylinderRepeatedSeamProjectionCollapse",
_ => nonNormalizableSource
};
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Cylinder loop normalization failed: all {loops.Count} loop(s) projected degenerate (maxUnique={maxUniqueCount}, maxAbsArea={maxAbsArea:E6}, faceId={faceEntityId}, primaryLoopId={primary.Loop.LoopId.Value}, primaryDegeneracy={primary.Analysis.Degeneracy}).", explicitSource);
}
var orderedByArea = infos
.OrderByDescending(i => double.Abs(i.SignedArea))
.ThenBy(i => i.Loop.LoopId.Value)
.ToArray();
var outer = orderedByArea[0];
if (orderedByArea.Length > 1)
{
var areaTolerance = ComputeAreaTolerance(orderedByArea.SelectMany(i => i.ProjectedPoints));
if (double.Abs(double.Abs(outer.SignedArea) - double.Abs(orderedByArea[1].SignedArea)) <= areaTolerance)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Unable to choose a unique cylindrical outer loop.", ambiguousOuterSource);
}
}
var containmentTolerance = ComputeContainmentTolerance(outer.ProjectedPoints);
var containedInners = new List<CylindricalLoopInfo>();
foreach (var candidate in infos.Where(i => i.Loop.LoopId != outer.Loop.LoopId))
{
var alignedCandidate = AlignPolygonToReference(candidate.ProjectedPoints, candidate.Centroid.X, outer.Centroid.X);
var sampleResult = ChooseContainmentPoint(alignedCandidate, containmentTolerance);
if (!sampleResult.IsSuccess)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Unable to classify cylindrical inner loop containment.", containmentSource);
}
if (!IsPointInPolygon(sampleResult.Value, outer.ProjectedPoints, containmentTolerance))
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Cylindrical inner loop {candidate.Loop.LoopId.Value} could not be normalized inside selected outer loop {outer.Loop.LoopId.Value}.", containmentSource);
}
containedInners.Add(candidate with { ProjectedPoints = alignedCandidate, Centroid = ComputePolygonCentroid(alignedCandidate) });
}
var normalizedOuter = NormalizeLoopWinding(outer.Loop, outer.SignedArea, shouldBePositive: true);
var normalizedInners = containedInners
.OrderByDescending(i => double.Abs(i.SignedArea))
.ThenBy(i => i.Loop.LoopId.Value)
.Select(i => NormalizeLoopWinding(i.Loop, i.SignedArea, shouldBePositive: false))
.ToList();
var ordered = new List<LoopBuildData>(1 + normalizedInners.Count) { normalizedOuter };
ordered.AddRange(normalizedInners);
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(ordered);
}
private static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizeConicalLoops(
int faceEntityId,
IReadOnlyList<LoopBuildData> loops,
ConeSurface cone)
{
const string nonNormalizableSource = "Importer.LoopRole.ConeNonNormalizableDegenerateProjection";
var degenerate = loops
.Select(loop =>
{
var projected = ProjectLoopToCone(loop.Samples, cone);
var uniqueCount = CountUniquePoints(projected, ContainmentEps);
var area = ComputeSignedArea(projected);
return (Loop: loop, Analysis: AnalyzeConicalProjection(uniqueCount, area, projected));
})
.OrderBy(d => d.Loop.LoopId.Value)
.ToArray();
if (degenerate.All(d => d.Analysis.Degeneracy == ConeProjectionDegeneracy.FullRevolutionConstantAxial))
{
var preservedUses = degenerate
.OrderByDescending(d => d.Analysis.AxialMean)
.ThenBy(d => d.Loop.LoopId.Value)
.Select(d => d.Loop)
.ToArray();
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(preservedUses);
}
var primary = degenerate
.OrderByDescending(d => (int)d.Analysis.Degeneracy)
.ThenBy(d => d.Loop.LoopId.Value)
.First();
var explicitSource = primary.Analysis.Degeneracy switch
{
ConeProjectionDegeneracy.DegenerateAngularSpan => "Importer.LoopRole.ConeDegenerateAngularSpan",
ConeProjectionDegeneracy.DegenerateAxialSpan => "Importer.LoopRole.ConeDegenerateAxialSpan",
ConeProjectionDegeneracy.RepeatedSeamProjectionCollapse => "Importer.LoopRole.ConeRepeatedSeamProjectionCollapse",
_ => nonNormalizableSource
};
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
$"Cone loop normalization failed: faceId={faceEntityId}, apex=({cone.Apex.X:G17},{cone.Apex.Y:G17},{cone.Apex.Z:G17}), placementRadius={cone.PlacementRadius:G17}, semiAngle={cone.SemiAngleRadians:G17}, loopCount={loops.Count}, primaryLoopId={primary.Loop.LoopId.Value}, primaryDegeneracy={primary.Analysis.Degeneracy}.",
explicitSource);
}
private static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizeToroidalLoops(
int faceEntityId,
IReadOnlyList<LoopBuildData> loops,
TorusSurface torus)
{
const string degenerateSource = "Importer.LoopRole.TorusDegenerateProjection";
const string ambiguousOuterSource = "Importer.LoopRole.TorusAmbiguousOuter";
const string containmentSource = "Importer.LoopRole.TorusInnerContainmentFailed";
const string degenerateMajorSpanSource = "Importer.LoopRole.TorusDegenerateMajorSpan";
const string degenerateMinorSpanSource = "Importer.LoopRole.TorusDegenerateMinorSpan";
const string repeatedSeamSource = "Importer.LoopRole.TorusRepeatedSeamProjectionCollapse";
const string repeatedMajorMinorSeamSource = "Importer.LoopRole.TorusRepeatedMajorMinorSeamProjectionCollapse";
const string majorSeamUnwrapSource = "Importer.LoopRole.TorusMajorSeamUnwrapFailure";
const string minorSeamUnwrapSource = "Importer.LoopRole.TorusMinorSeamUnwrapFailure";
var infos = new List<CylindricalLoopInfo>(loops.Count);
var maxUniqueCount = 0;
var maxAbsArea = 0d;
var degenerateAnalyses = new List<(LoopBuildData Loop, TorusProjectionAnalysis Analysis)>();
foreach (var loop in loops)
{
var projectedRaw = ProjectLoopToTorus(loop.Samples, torus);
var uniqueCountRaw = CountUniquePoints(projectedRaw, ContainmentEps);
var areaRaw = ComputeSignedArea(projectedRaw);
var analysisRaw = AnalyzeToroidalProjection(uniqueCountRaw, areaRaw, projectedRaw);
var projected = DeduplicateToroidalSeamSamples(SimplifyClosedPolygon(projectedRaw, ContainmentEps));
var uniqueCount = CountUniquePoints(projected, ContainmentEps);
var area = ComputeSignedArea(projected);
var analysis = AnalyzeToroidalProjection(uniqueCount, area, projected);
maxUniqueCount = System.Math.Max(maxUniqueCount, uniqueCount);
maxAbsArea = System.Math.Max(maxAbsArea, double.Abs(area));
if (analysis.Degeneracy != TorusProjectionDegeneracy.None)
{
var recovered = TryRecoverToroidalProjectionFromCyclicUnwrap(loop.Samples, torus);
if (recovered is not null)
{
projected = DeduplicateToroidalSeamSamples(SimplifyClosedPolygon(recovered.Value.Projected, ContainmentEps));
uniqueCount = recovered.Value.UniquePointCount;
area = recovered.Value.SignedArea;
analysis = recovered.Value.Analysis;
}
}
var majorRingCandidate = IsToroidalFullMajorRevolutionConstantMinor(analysis);
ReportTorusProjectionDiagnostic(new LoopRoleTorusProjectionDiagnostic(
FaceEntityId: faceEntityId,
LoopId: loop.LoopId.Value,
PointCount: projected.Count,
UniquePointCount: uniqueCount,
SignedArea: area,
MajorSpan: analysis.MajorSpan,
MinorSpan: analysis.MinorSpan,
MajorSeamCrossings: analysis.MajorSeamCrossings,
MinorSeamCrossings: analysis.MinorSeamCrossings,
RepeatedMajorSeamPointCount: analysis.RepeatedMajorSeamPointCount,
RepeatedMinorSeamPointCount: analysis.RepeatedMinorSeamPointCount,
Degeneracy: analysis.Degeneracy.ToString(),
InitialDegeneracy: analysisRaw.Degeneracy.ToString(),
InitialSignedArea: areaRaw,
FullMajorSpanNearConstantMinorCandidate: majorRingCandidate));
if (uniqueCount < 3 || double.Abs(area) <= AreaEps)
{
degenerateAnalyses.Add((loop, analysis));
continue;
}
infos.Add(new CylindricalLoopInfo(loop, projected, area, ComputePolygonCentroid(projected)));
}
if (infos.Count == 0)
{
if (degenerateAnalyses.Count > 0 && degenerateAnalyses.All(d => IsToroidalFullMajorRevolutionConstantMinor(d.Analysis)))
{
var preservedUses = degenerateAnalyses
.OrderBy(d => d.Loop.LoopId.Value)
.Select(d => d.Loop)
.ToArray();
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(preservedUses);
}
var primary = degenerateAnalyses
.OrderByDescending(d => (int)d.Analysis.Degeneracy)
.ThenBy(d => d.Loop.LoopId.Value)
.FirstOrDefault();
var explicitSource = primary.Analysis.Degeneracy switch
{
TorusProjectionDegeneracy.DegenerateMajorSpan => degenerateMajorSpanSource,
TorusProjectionDegeneracy.DegenerateMinorSpan => degenerateMinorSpanSource,
TorusProjectionDegeneracy.RepeatedSeamProjectionCollapse when primary.Analysis.RepeatedMajorSeamPointCount > 0 && primary.Analysis.RepeatedMinorSeamPointCount > 0 => repeatedMajorMinorSeamSource,
TorusProjectionDegeneracy.RepeatedSeamProjectionCollapse => repeatedSeamSource,
TorusProjectionDegeneracy.MajorPeriodSeamUnwrapFailure => majorSeamUnwrapSource,
TorusProjectionDegeneracy.MinorPeriodSeamUnwrapFailure => minorSeamUnwrapSource,
_ => degenerateSource
};
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Toroidal loop normalization failed: all {loops.Count} loop(s) projected degenerate (maxUnique={maxUniqueCount}, maxAbsArea={maxAbsArea:E6}, faceId={faceEntityId}, primaryLoopId={primary.Loop.LoopId.Value}, primaryDegeneracy={primary.Analysis.Degeneracy}).", explicitSource);
}
var orderedByArea = infos
.OrderByDescending(i => double.Abs(i.SignedArea))
.ThenBy(i => i.Loop.LoopId.Value)
.ToArray();
var outer = orderedByArea[0];
if (orderedByArea.Length > 1)
{
var areaTolerance = ComputeAreaTolerance(orderedByArea.SelectMany(i => i.ProjectedPoints));
if (double.Abs(double.Abs(outer.SignedArea) - double.Abs(orderedByArea[1].SignedArea)) <= areaTolerance)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Unable to choose a unique toroidal outer loop.", ambiguousOuterSource);
}
}
var containmentTolerance = ComputeContainmentTolerance(outer.ProjectedPoints);
var containedInners = new List<CylindricalLoopInfo>();
foreach (var candidate in infos.Where(i => i.Loop.LoopId != outer.Loop.LoopId))
{
var alignedCandidate = AlignPolygonToReference(candidate.ProjectedPoints, candidate.Centroid.X, outer.Centroid.X);
alignedCandidate = AlignPolygonToReferenceY(alignedCandidate, candidate.Centroid.Y, outer.Centroid.Y);
var sampleResult = ChooseContainmentPoint(alignedCandidate, containmentTolerance);
if (!sampleResult.IsSuccess)
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Unable to classify toroidal inner loop containment.", containmentSource);
}
if (!IsPointInPolygon(sampleResult.Value, outer.ProjectedPoints, containmentTolerance))
{
return LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Toroidal inner loop {candidate.Loop.LoopId.Value} could not be normalized inside selected outer loop {outer.Loop.LoopId.Value}.", containmentSource);
}
containedInners.Add(candidate with { ProjectedPoints = alignedCandidate, Centroid = ComputePolygonCentroid(alignedCandidate) });
}
var normalizedOuter = NormalizeLoopWinding(outer.Loop, outer.SignedArea, shouldBePositive: true);
var normalizedInners = containedInners
.OrderByDescending(i => double.Abs(i.SignedArea))
.ThenBy(i => i.Loop.LoopId.Value)
.Select(i => NormalizeLoopWinding(i.Loop, i.SignedArea, shouldBePositive: false))
.ToList();
var ordered = new List<LoopBuildData>(1 + normalizedInners.Count) { normalizedOuter };
ordered.AddRange(normalizedInners);
return KernelResult<IReadOnlyList<LoopBuildData>>.Success(ordered);
}
private static (bool FaceAligned, IReadOnlyDictionary<LoopId, bool> Loops) DeriveSupportAlignedBoundaries(
IReadOnlyList<LoopBuildData> loops,
SurfaceGeometry surface,
bool sourceSameSense)
{
if (loops.Count == 0) return (true, new Dictionary<LoopId, bool>());
// One loop on a sphere splits it into two caps, and the loop alone cannot say which is the face: the small cap
// traversed one way and the large cap the other wind identically. STEP's same_sense with the loop's direction
// can, since the loop runs counter-clockwise about the face's outward normal.
if (surface.Kind == SurfaceGeometryKind.Sphere && loops.Count == 1)
return (sourceSameSense, new Dictionary<LoopId, bool> { [loops[0].LoopId] = sourceSameSense });
IReadOnlyList<UvPoint>? Project(LoopBuildData loop) => surface.Kind switch
{
SurfaceGeometryKind.Plane => SimplifyClosedPolygon(ProjectLoopToPlane(loop.Samples, surface.Plane!.Value), ContainmentEps),
SurfaceGeometryKind.Cylinder => ProjectLoopToCylinder(loop.Samples, surface.Cylinder!.Value),
SurfaceGeometryKind.Cone => ProjectLoopToCone(loop.Samples, surface.Cone!.Value),
SurfaceGeometryKind.Sphere => ProjectLoopToSphere(loop.Samples, surface.Sphere!.Value),
SurfaceGeometryKind.Torus => ProjectLoopToTorus(loop.Samples, surface.Torus!.Value),
_ => null,
};
var projections = loops.ToDictionary(loop => loop.LoopId, Project);
// The material side follows from the loops' winding, not from which one carries FACE_OUTER_BOUND. Some writers
// put that label on a hole (NIST STC-06 does, on 23 planar faces), so on a plane the loop enclosing the most
// area is the outer boundary whatever it is called.
var outer = surface.Kind == SurfaceGeometryKind.Plane && loops.Count > 1 && loops.All(loop => projections[loop.LoopId] is { Count: >= 3 })
? loops.MaxBy(loop => double.Abs(ComputeSignedArea(projections[loop.LoopId]!)))!
: loops.SingleOrDefault(loop => loop.IsDeclaredOuter) ?? loops[0];
// Likewise two circles running round a torus bound two bands, the short way round the tube and the long way.
if (surface.Kind == SurfaceGeometryKind.Torus && loops.All(loop => projections[loop.LoopId] is { } p
&& TryDeriveFullPeriodTraversalAlignment(p, SurfacePeriodicity.Of(surface), out _)))
return (sourceSameSense, loops.ToDictionary(loop => loop.LoopId, _ => sourceSameSense));
var resolved = new Dictionary<LoopId, bool>();
foreach (var loop in loops)
{
var isOuter = loop.LoopId == outer.LoopId;
var projected = projections[loop.LoopId];
var signedArea = projected is null ? 0d : ComputeSignedArea(projected);
var periodicity = SurfacePeriodicity.Of(surface);
var boundaryAligned = surface.Kind == SurfaceGeometryKind.Sphere
&& TryDeriveSupportAlignmentFromBoundaryNormal(loop.Samples, surface, out var sphericalAligned)
? sphericalAligned
: surface.Kind != SurfaceGeometryKind.Sphere
&& projected is not null
&& TryDeriveFullPeriodTraversalAlignment(projected, periodicity, out var periodicAligned)
? FullTurnLoopAlignment(loop, projected, periodicAligned, isOuter)
: surface.Kind == SurfaceGeometryKind.Cone
&& TryDeriveSupportAlignmentFromBoundaryNormal(loop.Samples, surface, out var conicalAligned)
? conicalAligned
: projected is not null && double.Abs(signedArea) > ComputeAreaTolerance(projected)
? signedArea > 0d
// A free-form face can turn through more than a right angle (a swept tube), where the loop's
// polygon normal says nothing about the side; the source's same_sense with the loop's direction does.
: surface.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots
? isOuter == sourceSameSense
: TryDeriveSupportAlignmentFromBoundaryNormal(loop.Samples, surface, out var aligned)
? aligned
: isOuter;
resolved[loop.LoopId] = isOuter ? boundaryAligned : !boundaryAligned;
}
return (resolved[outer.LoopId], resolved);
// A loop running once round a cylinder or cone says nothing by itself about which side the face lies on. When the
// face has another loop, the face lies between them; a lone loop on a cone bounds the side holding the apex: a loop with the face on its +v side bounds an aligned face
// when it runs +u. The answer is the face's, so an inner loop reports it negated, as the caller expects.
bool FullTurnLoopAlignment(LoopBuildData loop, IReadOnlyList<UvPoint> projected, bool runsPositiveU, bool isOuter)
{
if (surface.Kind is not (SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone)) return runsPositiveU;
var others = loops.Where(other => other.LoopId != loop.LoopId).Select(other => projections[other.LoopId]).Where(p => p is { Count: > 0 }).ToArray();
// Alone on a cone (a drill point), the loop bounds the finite side: the face runs to the apex, where v is 0.
if (others.Length == 0 && surface.Kind != SurfaceGeometryKind.Cone) return runsPositiveU;
var side = (others.Length == 0 ? 0d : others.Average(p => p!.Average(point => point.Y))) - projected.Average(point => point.Y);
if (double.Abs(side) <= ContainmentEps) return runsPositiveU;
var faceAligned = (side > 0d) == runsPositiveU;
return isOuter ? faceAligned : !faceAligned;
}
}
private static bool TryDeriveFullPeriodTraversalAlignment(
IReadOnlyList<UvPoint> projected,
SurfacePeriodicity periodicity,
out bool aligned)
{
aligned = true;
if (!periodicity.IsPeriodic || projected.Count < 2) return false;
var endIndex = projected.Count - 1;
if (SegmentLengthSquared(projected[0], projected[endIndex]) <= ContainmentEps * ContainmentEps)
endIndex--;
if (endIndex <= 0) return false;
var active = projected.Take(endIndex + 1).ToArray();
var uSpan = active[^1].X - active[0].X;
var vSpan = active[^1].Y - active[0].Y;
var uRange = active.Max(point => point.X) - active.Min(point => point.X);
var vRange = active.Max(point => point.Y) - active.Min(point => point.Y);
var constantAxisTolerance = ContainmentEps * 8d;
if (periodicity.UPeriod is { } uPeriod
&& double.Abs(uSpan) >= uPeriod - AngleUnwrapEps
&& SurfacePeriodicity.EquivalentModuloPeriod(active[0].X, active[^1].X, uPeriod, AngleUnwrapEps)
&& vRange <= constantAxisTolerance)
{
aligned = uSpan > 0d;
return true;
}
if (periodicity.VPeriod is { } vPeriod
&& double.Abs(vSpan) >= vPeriod - AngleUnwrapEps
&& SurfacePeriodicity.EquivalentModuloPeriod(active[0].Y, active[^1].Y, vPeriod, AngleUnwrapEps)
&& uRange <= constantAxisTolerance)
{
aligned = vSpan > 0d;
return true;
}
return false;
}
private static bool TryDeriveSupportAlignmentFromBoundaryNormal(
IReadOnlyList<Point3D> samples,
SurfaceGeometry surface,
out bool aligned)
{
aligned = true;
var points = samples
.Where((point, index) => index == 0 || (point - samples[index - 1]).Length > ContainmentEps)
.ToArray();
if (points.Length < 3) return false;
var boundaryNormal = Vector3D.Zero;
for (var index = 0; index < points.Length; index++)
{
var current = points[index];
var next = points[(index + 1) % points.Length];
boundaryNormal += new Vector3D(
(current.Y - next.Y) * (current.Z + next.Z),
(current.Z - next.Z) * (current.X + next.X),
(current.X - next.X) * (current.Y + next.Y));
}
if (!boundaryNormal.TryNormalize(out var normalizedBoundary)) return false;
var center = new Point3D(points.Average(point => point.X), points.Average(point => point.Y), points.Average(point => point.Z));
Vector3D supportNormal;
switch (surface.Kind)
{
case SurfaceGeometryKind.Plane:
supportNormal = surface.Plane!.Value.Normal.ToVector();
break;
case SurfaceGeometryKind.Cylinder:
{
var cylinder = surface.Cylinder!.Value;
var delta = center - cylinder.Origin;
supportNormal = delta - (cylinder.Axis.ToVector() * delta.Dot(cylinder.Axis.ToVector()));
break;
}
case SurfaceGeometryKind.Sphere:
supportNormal = center - surface.Sphere!.Value.Center;
break;
case SurfaceGeometryKind.Cone:
{
var cone = surface.Cone!.Value;
var axis = cone.Axis.ToVector();
Vector3D Radial(Point3D p) { var d = p - cone.Apex; return d - axis * d.Dot(axis); }
var radial = Radial(center);
var reach = points.Average(p => Radial(p).Length);
// A loop running right round the cone (a drill point's rim with its seam) has its centroid on the
// axis, where the radial direction means nothing: there the cone's normal averaged round the loop
// is the reference, whose radial parts cancel and leave the axial one.
if (radial.Length < 0.25d * reach)
{
supportNormal = Vector3D.Zero;
foreach (var p in points)
if (Radial(p).TryNormalize(out var r)) supportNormal += r - axis * double.Tan(cone.SemiAngleRadians);
if (supportNormal.Length <= 1e-12d) return false;
break;
}
if (!radial.TryNormalize(out var radialDirection)) return false;
supportNormal = radialDirection - (axis * double.Tan(cone.SemiAngleRadians));
break;
}
case SurfaceGeometryKind.Torus:
{
var torus = surface.Torus!.Value;
var delta = center - torus.Center;
var planar = delta - (torus.Axis.ToVector() * delta.Dot(torus.Axis.ToVector()));
if (!planar.TryNormalize(out var majorDirection)) return false;
var tubeCenter = torus.Center + (majorDirection * torus.MajorRadius);
supportNormal = center - tubeCenter;
break;
}
case SurfaceGeometryKind.BSplineSurfaceWithKnots:
{
var spline = surface.BSplineSurfaceWithKnots!;
var u = (spline.DomainStartU + spline.DomainEndU) * 0.5d;
var v = (spline.DomainStartV + spline.DomainEndV) * 0.5d;
var du = System.Math.Max((spline.DomainEndU - spline.DomainStartU) * 1e-5d, 1e-8d);
var dv = System.Math.Max((spline.DomainEndV - spline.DomainStartV) * 1e-5d, 1e-8d);
supportNormal = (spline.Evaluate(u + du, v) - spline.Evaluate(u - du, v))
.Cross(spline.Evaluate(u, v + dv) - spline.Evaluate(u, v - dv));
break;
}
default:
return false;
}
if (!supportNormal.TryNormalize(out var normalizedSupport)) return false;
var agreement = normalizedBoundary.Dot(normalizedSupport);
// An equatorial spherical boundary lies in a plane through the centre.
// Its centroid radial direction is perpendicular to the boundary normal;
// the sign of a near-zero dot product is rounding noise, not orientation
// evidence. Fall through to UV winding/the deterministic loop-role baseline
// so shared-edge adjacency and the shell volume solve retain authority.
if (surface.Kind == SurfaceGeometryKind.Sphere && double.Abs(agreement) <= 1e-8d) return false;
aligned = agreement > 0d;
return true;
}
private static LoopBuildData NormalizeLoopWinding(LoopBuildData loop, double signedArea, bool shouldBePositive)
{
// STEP EDGE_LOOP order is topology, not presentation. Classification
// may diagnose winding, but it must never mutate declared coedge
// traversal: face SameSense governs material orientation separately.
_ = signedArea;
_ = shouldBePositive;
return loop;
}
private static KernelResult<ParameterInterval> ComputeHyperbolaTrim(Hyperbola3Curve hyperbola, Point3D startPoint, Point3D endPoint, bool edgeSameSense)
{
var scale = System.Math.Max(hyperbola.SemiAxisA, System.Math.Max(hyperbola.SemiAxisB, System.Math.Max((startPoint - hyperbola.Center).Length, (endPoint - hyperbola.Center).Length)));
var tolerance = System.Math.Max(1e-7d, scale * 1e-8d);
var startResult = ProjectPointToHyperbolaParameter(hyperbola, startPoint, tolerance);
if (!startResult.IsSuccess) return KernelResult<ParameterInterval>.Failure(startResult.Diagnostics);
var endResult = ProjectPointToHyperbolaParameter(hyperbola, endPoint, tolerance);
if (!endResult.IsSuccess) return KernelResult<ParameterInterval>.Failure(endResult.Diagnostics);
var start = startResult.Value;
var end = endResult.Value;
if (end < start)
{
if (edgeSameSense)
{
return FailureHyperbolaTrim("EDGE_CURVE hyperbola parameterization is opposite to vertex ordering.", "Importer.Geometry.HyperbolaTrim.Direction");
}
return KernelResult<ParameterInterval>.Success(new ParameterInterval(end, start));
}
return KernelResult<ParameterInterval>.Success(new ParameterInterval(start, end));
}
private static KernelResult<double> ProjectPointToHyperbolaParameter(Hyperbola3Curve hyperbola, Point3D point, double tolerance)
{
var delta = point - hyperbola.Center;
var normalError = double.Abs(delta.Dot(hyperbola.PlaneNormal.ToVector()));
if (normalError > tolerance)
{
return FailureHyperbolaTrimParameter($"HYPERBOLA endpoint is off its support plane by {normalError:G17}.", "Importer.Geometry.HyperbolaEndpointMismatch");
}
var u = delta.Dot(hyperbola.AxisU.ToVector());
var v = delta.Dot(hyperbola.AxisV.ToVector());
if ((u * hyperbola.BranchSign) < hyperbola.SemiAxisA - tolerance)
{
return FailureHyperbolaTrimParameter("HYPERBOLA endpoint lies on the opposite branch or inside the vertex line.", "Importer.Geometry.HyperbolaBranchAmbiguous");
}
var parameter = double.Asinh(v / hyperbola.SemiAxisB);
var expected = hyperbola.Evaluate(parameter);
if ((expected - point).Length > tolerance)
{
return FailureHyperbolaTrimParameter("HYPERBOLA endpoint does not lie on the analytic support.", "Importer.Geometry.HyperbolaEndpointMismatch");
}
return KernelResult<double>.Success(parameter);
}
private static bool LoopsOverlap(PlanarLoopInfo a, PlanarLoopInfo b, double containmentTolerance)
{
var aPoint = ChooseContainmentPoint(a.ProjectedPoints, containmentTolerance);
var bPoint = ChooseContainmentPoint(b.ProjectedPoints, containmentTolerance);
if (!aPoint.IsSuccess || !bPoint.IsSuccess)
{
return true;
}
return IsPointInPolygon(aPoint.Value, b.ProjectedPoints, containmentTolerance) || IsPointInPolygon(bPoint.Value, a.ProjectedPoints, containmentTolerance);
}
private static ContainmentFailure BuildInnerContainmentFailure(
PlanarLoopInfo inner,
PlanarLoopInfo outer,
double containmentTolerance,
double areaTolerance,
int intersectionCount,
bool hasDisconnectedCoedges)
{
var containment = EvaluateContainment(inner.ProjectedPoints, outer.ProjectedPoints, containmentTolerance);
var crossingOuter = intersectionCount > 0;
var areaRatio = double.Abs(outer.SignedArea) <= areaTolerance
? 0d
: double.Abs(inner.SignedArea) / double.Abs(outer.SignedArea);
var reason = crossingOuter
? (containment.OutsideCount == 0 ? "crosses_outer_boundary_with_all_vertices_inside" : "crosses_outer_boundary_with_outside_vertices")
: (containment.OutsideCount == containment.VertexCount ? "disjoint" : "partially_outside");
var source = reason switch
{
"crosses_outer_boundary_with_all_vertices_inside" => "Importer.LoopRole.InnerBoundaryIntersectionWithContainedVerticesAfterNormalization",
"crosses_outer_boundary_with_outside_vertices" when hasDisconnectedCoedges => "Importer.LoopRole.DisconnectedCoedges",
"crosses_outer_boundary_with_outside_vertices" => "Importer.LoopRole.InnerBoundaryIntersectionWithOutsideVerticesAfterNormalization",
"disjoint" => "Importer.LoopRole.InnerDisjointAfterNormalization",
_ => "Importer.LoopRole.InnerPartiallyOutsideAfterNormalization"
};
var message = source == "Importer.LoopRole.DisconnectedCoedges"
? $"Planar loop contains disconnected consecutive coedges and cannot be normalized safely. innerLoopId={inner.Loop.LoopId.Value}, outerLoopId={outer.Loop.LoopId.Value}, outsideVertices={containment.OutsideCount}/{containment.VertexCount}, nearestOuterDistance={containment.MinDistanceToOuter:E6}, areaRatio={areaRatio:E6}, intersections={intersectionCount}."
: $"Inner loop could not be normalized: {reason}. innerLoopId={inner.Loop.LoopId.Value}, outerLoopId={outer.Loop.LoopId.Value}, outsideVertices={containment.OutsideCount}/{containment.VertexCount}, nearestOuterDistance={containment.MinDistanceToOuter:E6}, maximumOutsideDistance={containment.MaxOutsideDistanceToOuter:E6}, areaRatio={areaRatio:E6}, intersections={intersectionCount}.";
return new ContainmentFailure(message, source);
}
private static bool TryRecoverPlanarCrossingInnerWithJudgmentEngine(
PlanarLoopInfo inner,
PlanarLoopInfo outer,
ContainmentEvaluation containment,
int intersectionCount,
double containmentTolerance,
int loopCount,
int declaredOuterCount,
double nearCoincidentTolerance)
{
var context = BuildPlanarCrossingInsideRecoveryContext(inner, outer, containment, intersectionCount,
containmentTolerance, loopCount, declaredOuterCount, nearCoincidentTolerance);
var engine = new JudgmentEngine<PlanarCrossingInsideRecoveryContext>();
var result = engine.Evaluate(context, BuildPlanarCrossingInsideRecoveryCandidates());
var selected = result.Selection?.Candidate.Name ?? PlanarCrossingInsideRejectCandidate;
ReportPlanarMultiBoundJudgmentDiagnostic(new PlanarMultiBoundJudgmentDiagnostic(
FaceLoopCount: context.LoopCount,
OuterLoopId: context.OuterLoopId,
InnerLoopId: context.InnerLoopId,
OuterArea: context.OuterArea,
InnerArea: context.InnerArea,
AreaRatio: context.AreaRatio,
ContainedVertexCount: context.ContainedVertexCount,
VertexCount: context.VertexCount,
IntersectionCount: context.IntersectionCount,
MinDistanceToOuter: context.MinDistanceToOuter,
HasDisconnectedCoedgeGap: context.HasDisconnectedCoedgeGap,
HasSingleDeclaredOuterLoop: context.HasSingleDeclaredOuterLoop,
SelectedCandidate: selected,
CandidateRejections: string.Join(" | ", result.Rejections.Select(rejection => $"{rejection.CandidateName}:{rejection.Reason}"))));
return selected is PlanarCrossingInsideRecoveryCandidate or PlanarNearCoincidentRecoveryCandidate;
}
private static PlanarCrossingInsideRecoveryContext BuildPlanarCrossingInsideRecoveryContext(
PlanarLoopInfo inner,
PlanarLoopInfo outer,
ContainmentEvaluation containment,
int intersectionCount,
double containmentTolerance,
int loopCount,
int declaredOuterCount,
double nearCoincidentTolerance)
{
var outerArea = double.Abs(outer.SignedArea);
var innerArea = double.Abs(inner.SignedArea);
var areaRatio = outerArea <= AreaEps ? 0d : innerArea / outerArea;
var hasDisconnectedCoedgeGap = inner.Loop.HasDisconnectedCoedgeGap || outer.Loop.HasDisconnectedCoedgeGap;
return new PlanarCrossingInsideRecoveryContext(
InnerLoopId: inner.Loop.LoopId.Value,
OuterLoopId: outer.Loop.LoopId.Value,
LoopCount: loopCount,
InnerArea: innerArea,
OuterArea: outerArea,
AreaRatio: areaRatio,
IntersectionCount: intersectionCount,
ContainedVertexCount: containment.VertexCount - containment.OutsideCount,
VertexCount: containment.VertexCount,
MinDistanceToOuter: containment.MinDistanceToOuter,
HasDisconnectedCoedgeGap: hasDisconnectedCoedgeGap,
HasSingleDeclaredOuterLoop: declaredOuterCount == 1,
IsNearBoundaryContact: containment.MinDistanceToOuter <= containmentTolerance * 8d,
MaximumOutsideDistance: containment.MaxOutsideDistanceToOuter,
NearCoincidentTolerance: nearCoincidentTolerance);
}
private static IReadOnlyList<JudgmentCandidate<PlanarCrossingInsideRecoveryContext>> BuildPlanarCrossingInsideRecoveryCandidates()
{
return
[
new JudgmentCandidate<PlanarCrossingInsideRecoveryContext>(
Name: PlanarCrossingInsideRecoveryCandidate,
IsAdmissible: When.All<PlanarCrossingInsideRecoveryContext>(
context => context.LoopCount >= 2,
context => context.IntersectionCount > 0,
context => context.ContainedVertexCount == context.VertexCount,
context => !context.HasDisconnectedCoedgeGap,
context => context.AreaRatio > 0d && context.AreaRatio < 0.98d,
context => context.IsNearBoundaryContact || context.HasSingleDeclaredOuterLoop),
Score: context => (100d - context.IntersectionCount) + ((1d - context.AreaRatio) * 10d),
RejectionReason: context =>
$"requires bounded planar crossing-all-inside recovery facts (loopCount={context.LoopCount}, intersections={context.IntersectionCount}, contained={context.ContainedVertexCount}/{context.VertexCount}, disconnected={context.HasDisconnectedCoedgeGap}, areaRatio={context.AreaRatio:E6}, nearBoundary={context.IsNearBoundaryContact}, singleDeclaredOuter={context.HasSingleDeclaredOuterLoop})",
TieBreakerPriority: 0),
new JudgmentCandidate<PlanarCrossingInsideRecoveryContext>(
Name: PlanarNearCoincidentRecoveryCandidate,
IsAdmissible: When.All<PlanarCrossingInsideRecoveryContext>(
context => context.NearCoincidentTolerance > 0d,
context => context.LoopCount == 2 && context.IntersectionCount > 0,
context => context.ContainedVertexCount < context.VertexCount,
context => context.HasSingleDeclaredOuterLoop && !context.HasDisconnectedCoedgeGap,
context => context.AreaRatio > 0d && context.AreaRatio < 1d,
context => context.MaximumOutsideDistance <= context.NearCoincidentTolerance),
Score: context => 50d - context.MaximumOutsideDistance / context.NearCoincidentTolerance,
RejectionReason: context =>
$"requires explicit bounded near-coincident inner-loop policy (outside={context.MaximumOutsideDistance:E6}, limit={context.NearCoincidentTolerance:E6}, areaRatio={context.AreaRatio:E6}, intersections={context.IntersectionCount})",
TieBreakerPriority: 1),
new JudgmentCandidate<PlanarCrossingInsideRecoveryContext>(
Name: PlanarCrossingInsideRejectCandidate,
IsAdmissible: _ => true,
Score: _ => -1d,
RejectionReason: _ => "bounded planar crossing-all-inside recovery candidate is not admissible",
TieBreakerPriority: 2)
];
}
private static ContainmentEvaluation EvaluateContainment(
IReadOnlyList<UvPoint> inner,
IReadOnlyList<UvPoint> outer,
double containmentTolerance)
{
var outsideCount = 0;
var vertexCount = 0;
var minDistanceToOuter = double.MaxValue;
var maxOutsideDistanceToOuter = 0d;
for (var i = 0; i < inner.Count - 1; i++)
{
var point = inner[i];
vertexCount++;
minDistanceToOuter = double.Min(minDistanceToOuter, DistancePointToPolygon(point, outer));
if (!IsPointInPolygon(point, outer, containmentTolerance))
{
outsideCount++;
maxOutsideDistanceToOuter = double.Max(maxOutsideDistanceToOuter, DistancePointToPolygon(point, outer));
}
}
if (double.IsPositiveInfinity(minDistanceToOuter) || minDistanceToOuter == double.MaxValue)
{
minDistanceToOuter = 0d;
}
return new ContainmentEvaluation(outsideCount, vertexCount, minDistanceToOuter, maxOutsideDistanceToOuter);
}
private static bool IsLoopContainedByOuter(
IReadOnlyList<UvPoint> inner,
IReadOnlyList<UvPoint> outer,
double containmentTolerance)
{
if (CountPolygonIntersections(inner, outer, containmentTolerance) > 0)
{
return false;
}
var containment = EvaluateContainment(inner, outer, containmentTolerance);
return containment.OutsideCount == 0;
}
private static double DistancePointToPolygon(UvPoint point, IReadOnlyList<UvPoint> polygon)
{
var minDistance = double.MaxValue;
for (var i = 0; i < polygon.Count - 1; i++)
{
minDistance = double.Min(minDistance, DistancePointToSegment(point, polygon[i], polygon[i + 1]));
}
return minDistance;
}
private static int CountPolygonIntersections(IReadOnlyList<UvPoint> a, IReadOnlyList<UvPoint> b, double tolerance)
{
var intersections = 0;
for (var i = 0; i < a.Count - 1; i++)
{
if (SegmentLengthSquared(a[i], a[i + 1]) <= (tolerance * tolerance))
{
continue;
}
for (var j = 0; j < b.Count - 1; j++)
{
if (SegmentLengthSquared(b[j], b[j + 1]) <= (tolerance * tolerance))
{
continue;
}
if (SegmentsIntersect(a[i], a[i + 1], b[j], b[j + 1], tolerance))
{
intersections++;
}
}
}
return intersections;
}
private static bool SegmentsIntersect(UvPoint a0, UvPoint a1, UvPoint b0, UvPoint b1, double tolerance)
{
var o1 = Orientation(a0, a1, b0);
var o2 = Orientation(a0, a1, b1);
var o3 = Orientation(b0, b1, a0);
var o4 = Orientation(b0, b1, a1);
if (IsProperStraddle(o1, o2, tolerance) && IsProperStraddle(o3, o4, tolerance))
{
return true;
}
return (double.Abs(o1) <= tolerance && IsPointOnSegment(b0, a0, a1, tolerance))
|| (double.Abs(o2) <= tolerance && IsPointOnSegment(b1, a0, a1, tolerance))
|| (double.Abs(o3) <= tolerance && IsPointOnSegment(a0, b0, b1, tolerance))
|| (double.Abs(o4) <= tolerance && IsPointOnSegment(a1, b0, b1, tolerance));
}
private static bool IsProperStraddle(double a, double b, double tolerance)
=> (a > tolerance && b < -tolerance) || (a < -tolerance && b > tolerance);
private static bool IsPointOnSegment(UvPoint p, UvPoint a, UvPoint b, double tolerance)
{
var minX = double.Min(a.X, b.X) - tolerance;
var maxX = double.Max(a.X, b.X) + tolerance;
var minY = double.Min(a.Y, b.Y) - tolerance;
var maxY = double.Max(a.Y, b.Y) + tolerance;
return p.X >= minX && p.X <= maxX && p.Y >= minY && p.Y <= maxY;
}
private static double SegmentLengthSquared(UvPoint a, UvPoint b)
{
var delta = b - a;
return delta.Dot(delta);
}
private static double Orientation(UvPoint a, UvPoint b, UvPoint c)
=> ((b.X - a.X) * (c.Y - a.Y)) - ((b.Y - a.Y) * (c.X - a.X));
private static KernelResult<UvPoint> ChooseContainmentPoint(IReadOnlyList<UvPoint> polygon, double containmentTolerance)
{
if (polygon.Count < 4)
{
return LoopRoleFailure<UvPoint>("Unable to choose a containment sample point.", "Importer.LoopRole.DegenerateLoop");
}
var centroid = ComputePolygonCentroid(polygon);
if (!IsPointNearPolygonEdge(centroid, polygon, containmentTolerance) && IsPointInPolygon(centroid, polygon, containmentTolerance))
{
return KernelResult<UvPoint>.Success(centroid);
}
for (var i = 0; i < polygon.Count - 1; i++)
{
var start = polygon[i];
var end = polygon[i + 1];
var midpoint = new UvPoint((start.X + end.X) * 0.5d, (start.Y + end.Y) * 0.5d);
var towardCentroid = centroid - midpoint;
var candidate = midpoint + (towardCentroid * 0.125d);
if (!IsPointNearPolygonEdge(candidate, polygon, containmentTolerance) && IsPointInPolygon(candidate, polygon, containmentTolerance))
{
return KernelResult<UvPoint>.Success(candidate);
}
}
return LoopRoleFailure<UvPoint>("Unable to choose a containment sample point.", "Importer.LoopRole.DegenerateLoop");
}
private static UvPoint ComputePolygonCentroid(IReadOnlyList<UvPoint> polygon)
{
var sumX = 0d;
var sumY = 0d;
var count = 0;
for (var i = 0; i < polygon.Count - 1; i++)
{
sumX += polygon[i].X;
sumY += polygon[i].Y;
count++;
}
if (count == 0)
{
return new UvPoint(0d, 0d);
}
return new UvPoint(sumX / count, sumY / count);
}
private static bool IsPointNearPolygonEdge(UvPoint point, IReadOnlyList<UvPoint> polygon, double containmentTolerance)
{
for (var i = 0; i < polygon.Count - 1; i++)
{
if (DistancePointToSegment(point, polygon[i], polygon[i + 1]) <= containmentTolerance)
{
return true;
}
}
return false;
}
private static double DistancePointToSegment(UvPoint p, UvPoint a, UvPoint b)
{
var ab = b - a;
var ap = p - a;
var denom = ab.Dot(ab);
if (denom <= AreaEps)
{
return (p - a).Length;
}
var t = ap.Dot(ab) / denom;
if (t < 0d)
{
t = 0d;
}
else if (t > 1d)
{
t = 1d;
}
var closest = a + (ab * t);
return (p - closest).Length;
}
private static bool IsPointInPolygon(UvPoint point, IReadOnlyList<UvPoint> polygon, double containmentTolerance)
{
var inside = false;
for (var i = 0; i < polygon.Count - 1; i++)
{
var a = polygon[i];
var b = polygon[i + 1];
if (DistancePointToSegment(point, a, b) <= containmentTolerance)
{
return true;
}
var intersects = ((a.Y > point.Y) != (b.Y > point.Y))
&& (point.X < ((b.X - a.X) * (point.Y - a.Y) / ((b.Y - a.Y) + AngleUnwrapEps)) + a.X);
if (intersects)
{
inside = !inside;
}
}
return inside;
}
private static int CountUniquePoints(IReadOnlyList<UvPoint> points, double tolerance)
{
var unique = new List<UvPoint>();
foreach (var point in points)
{
if (unique.Any(u => (u - point).Length <= tolerance))
{
continue;
}
unique.Add(point);
}
return unique.Count;
}
private static List<UvPoint> SimplifyClosedPolygon(IReadOnlyList<UvPoint> polygon, double tolerance)
{
var simplified = new List<UvPoint>(polygon.Count + 1);
foreach (var point in polygon)
{
if (simplified.Count > 0 && (simplified[^1] - point).Length <= tolerance)
{
continue;
}
simplified.Add(point);
}
if (simplified.Count == 0)
{
return simplified;
}
if ((simplified[0] - simplified[^1]).Length > tolerance)
{
simplified.Add(simplified[0]);
}
else
{
simplified[^1] = simplified[0];
}
return simplified;
}
private static List<UvPoint> ProjectLoopToPlane(IReadOnlyList<Point3D> samples, PlaneSurface plane)
{
var uv = new List<UvPoint>(samples.Count + 1);
foreach (var sample in samples)
{
var offset = sample - plane.Origin;
uv.Add(new UvPoint(offset.Dot(plane.UAxis.ToVector()), offset.Dot(plane.VAxis.ToVector())));
}
if (uv.Count > 0 && (uv[0] - uv[^1]).Length > ContainmentEps)
{
uv.Add(uv[0]);
}
return 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,
candidate.DeclaredQualificationToleranceMillimetres is double declaredTolerance
? new PcurveQualification(PcurveBindingOrigin.SourceValidated, 0d, declaredTolerance,
67, "source-qualified", surface.Kind.ToString()) : null));
}
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();
var xAxis = cylinder.XAxis.ToVector();
var yAxis = cylinder.YAxis.ToVector();
var uv = new List<UvPoint>(samples.Count + 1);
double? previous = null;
var revolutions = 0d;
foreach (var sample in samples)
{
var offset = sample - cylinder.Origin;
var axial = offset.Dot(axis);
var radial = offset - (axis * axial);
var angle = NormalizeToZeroTwoPi(double.Atan2(radial.Dot(yAxis), radial.Dot(xAxis)));
if (previous.HasValue)
{
var delta = angle - previous.Value;
if (delta > double.Pi)
{
revolutions -= 2d * double.Pi;
}
else if (delta < -double.Pi)
{
revolutions += 2d * double.Pi;
}
}
uv.Add(new UvPoint(angle + revolutions, axial));
previous = angle;
}
if (uv.Count > 0 && (uv[0] - uv[^1]).Length > ContainmentEps)
{
uv.Add(uv[0]);
}
return uv;
}
private static List<UvPoint> ProjectLoopToSphere(IReadOnlyList<Point3D> samples, SphereSurface sphere)
{
var uv = new List<UvPoint>(samples.Count + 1);
var previousAngle = 0d;
var revolutions = 0d;
var hasPrevious = false;
foreach (var sample in samples)
{
var offset = sample - sphere.Center;
var radial = offset.Length;
if (!double.IsFinite(radial) || radial <= PointOnSurfaceEps) continue;
var normalized = offset / radial;
var angle = double.Atan2(
normalized.Dot(sphere.YAxis.ToVector()),
normalized.Dot(sphere.XAxis.ToVector()));
if (hasPrevious)
{
var delta = angle - previousAngle;
if (delta > double.Pi) revolutions -= 2d * double.Pi;
else if (delta < -double.Pi) revolutions += 2d * double.Pi;
}
var elevation = double.Asin(double.Clamp(normalized.Dot(sphere.Axis.ToVector()), -1d, 1d));
uv.Add(new UvPoint(angle + revolutions, elevation));
previousAngle = angle;
hasPrevious = true;
}
if (uv.Count > 0 && SegmentLengthSquared(uv[0], uv[^1]) > ContainmentEps * ContainmentEps)
uv.Add(uv[0]);
return uv;
}
private static List<UvPoint> ProjectLoopToTorus(IReadOnlyList<Point3D> samples, TorusSurface torus)
{
var axis = torus.Axis.ToVector();
var xAxis = torus.XAxis.ToVector();
var yAxis = torus.YAxis.ToVector();
var uv = new List<UvPoint>(samples.Count + 1);
double? previousU = null;
var uRevolutions = 0d;
double? previousV = null;
var vRevolutions = 0d;
foreach (var sample in samples)
{
var offset = sample - torus.Center;
var axial = offset.Dot(axis);
var inPlane = offset - (axis * axial);
var radial = inPlane.Length;
var u = NormalizeToZeroTwoPi(double.Atan2(inPlane.Dot(yAxis), inPlane.Dot(xAxis)));
if (previousU.HasValue)
{
var deltaU = u - previousU.Value;
if (deltaU > double.Pi)
{
uRevolutions -= 2d * double.Pi;
}
else if (deltaU < -double.Pi)
{
uRevolutions += 2d * double.Pi;
}
}
var v = NormalizeToZeroTwoPi(double.Atan2(axial, radial - torus.MajorRadius));
if (previousV.HasValue)
{
var deltaV = v - previousV.Value;
if (deltaV > double.Pi)
{
vRevolutions -= 2d * double.Pi;
}
else if (deltaV < -double.Pi)
{
vRevolutions += 2d * double.Pi;
}
}
uv.Add(new UvPoint(u + uRevolutions, v + vRevolutions));
previousU = u;
previousV = v;
}
if (uv.Count > 0 && (uv[0] - uv[^1]).Length > ContainmentEps)
{
uv.Add(uv[0]);
}
return uv;
}
private static List<UvPoint> ProjectLoopToCone(IReadOnlyList<Point3D> samples, ConeSurface cone)
{
var axis = cone.Axis.ToVector();
var reference = cone.ReferenceAxis.ToVector();
var projectedReference = reference - (axis * reference.Dot(axis));
var xAxis = Direction3D.Create(projectedReference).ToVector();
var yAxis = Direction3D.Create(axis.Cross(xAxis)).ToVector();
var uv = new List<UvPoint>(samples.Count + 1);
double? previous = null;
var revolutions = 0d;
foreach (var sample in samples)
{
var offset = sample - cone.Apex;
var axial = offset.Dot(axis);
var radial = offset - (axis * axial);
var angle = NormalizeToZeroTwoPi(double.Atan2(radial.Dot(yAxis), radial.Dot(xAxis)));
if (previous.HasValue)
{
var delta = angle - previous.Value;
if (delta > double.Pi)
{
revolutions -= 2d * double.Pi;
}
else if (delta < -double.Pi)
{
revolutions += 2d * double.Pi;
}
}
uv.Add(new UvPoint(angle + revolutions, axial));
previous = angle;
}
if (uv.Count > 0 && (uv[0] - uv[^1]).Length > ContainmentEps)
{
uv.Add(uv[0]);
}
return uv;
}
private static (IReadOnlyList<UvPoint> Projected, int UniquePointCount, double SignedArea, TorusProjectionAnalysis Analysis)? TryRecoverToroidalProjectionFromCyclicUnwrap(
IReadOnlyList<Point3D> samples,
TorusSurface torus)
{
if (samples.Count < 4)
{
return null;
}
var best = default((IReadOnlyList<UvPoint> Projected, int UniquePointCount, double SignedArea, TorusProjectionAnalysis Analysis)?);
var bestScore = double.NegativeInfinity;
var bodyCount = samples.Count - 1;
var loopBody = samples.Take(bodyCount).ToArray();
for (var start = 0; start < bodyCount; start++)
{
var rotated = new Point3D[bodyCount];
for (var i = 0; i < bodyCount; i++)
{
rotated[i] = loopBody[(i + start) % bodyCount];
}
var projected = DeduplicateToroidalSeamSamples(SimplifyClosedPolygon(ProjectLoopToTorus(rotated, torus), ContainmentEps));
var unique = CountUniquePoints(projected, ContainmentEps);
var area = ComputeSignedArea(projected);
var analysis = AnalyzeToroidalProjection(unique, area, projected);
var score = unique * 1_000_000d + double.Abs(area);
if (analysis.Degeneracy == TorusProjectionDegeneracy.None && score > bestScore)
{
best = (projected, unique, area, analysis);
bestScore = score;
}
}
return best;
}
private static List<UvPoint> DeduplicateToroidalSeamSamples(IReadOnlyList<UvPoint> projected)
{
if (projected.Count <= 1)
{
return projected.ToList();
}
var deduplicated = new List<UvPoint>(projected.Count);
deduplicated.Add(projected[0]);
for (var i = 1; i < projected.Count; i++)
{
var current = projected[i];
var previous = deduplicated[^1];
if (IsRepeatedToroidalSeamSample(previous, current))
{
continue;
}
deduplicated.Add(current);
}
if (deduplicated.Count > 1 && IsRepeatedToroidalSeamSample(deduplicated[^1], deduplicated[0]))
{
deduplicated.RemoveAt(deduplicated.Count - 1);
}
if (deduplicated.Count > 0 && (deduplicated[0] - deduplicated[^1]).Length > ContainmentEps)
{
deduplicated.Add(deduplicated[0]);
}
return deduplicated;
}
private static bool IsRepeatedToroidalSeamSample(UvPoint a, UvPoint b)
{
if ((a - b).Length <= ContainmentEps)
{
return true;
}
var aU = NormalizeToZeroTwoPi(a.X);
var bU = NormalizeToZeroTwoPi(b.X);
var aV = NormalizeToZeroTwoPi(a.Y);
var bV = NormalizeToZeroTwoPi(b.Y);
var nearMajorSeam = (aU <= 1e-6d || aU >= (2d * double.Pi) - 1e-6d) && (bU <= 1e-6d || bU >= (2d * double.Pi) - 1e-6d);
if (nearMajorSeam && double.Abs(a.Y - b.Y) <= ContainmentEps)
{
return true;
}
var nearMinorSeam = (aV <= 1e-6d || aV >= (2d * double.Pi) - 1e-6d) && (bV <= 1e-6d || bV >= (2d * double.Pi) - 1e-6d);
return nearMinorSeam && double.Abs(a.X - b.X) <= ContainmentEps;
}
private static CylinderProjectionAnalysis AnalyzeCylindricalProjection(int uniqueCount, double signedArea, IReadOnlyList<UvPoint> projected)
{
if (projected.Count == 0)
{
return new CylinderProjectionAnalysis(0d, 0d, 0, 0, CylinderProjectionDegeneracy.InsufficientUniquePoints);
}
var minX = projected.Min(p => p.X);
var maxX = projected.Max(p => p.X);
var minY = projected.Min(p => p.Y);
var maxY = projected.Max(p => p.Y);
var angularSpan = maxX - minX;
var axialSpan = maxY - minY;
var seamCrossings = 0;
var repeatedSeamPointCount = 0;
for (var i = 1; i < projected.Count; i++)
{
var delta = projected[i].X - projected[i - 1].X;
if (double.Abs(delta) > double.Pi)
{
seamCrossings++;
}
var a = NormalizeToZeroTwoPi(projected[i - 1].X);
var b = NormalizeToZeroTwoPi(projected[i].X);
var nearSeam = (a <= 1e-6d || a >= (2d * double.Pi) - 1e-6d) && (b <= 1e-6d || b >= (2d * double.Pi) - 1e-6d);
if (nearSeam && double.Abs(projected[i].Y - projected[i - 1].Y) <= ContainmentEps)
{
repeatedSeamPointCount++;
}
}
var degeneracy = CylinderProjectionDegeneracy.None;
if (uniqueCount < 3)
{
degeneracy = CylinderProjectionDegeneracy.InsufficientUniquePoints;
}
else if (double.Abs(signedArea) <= AreaEps)
{
if (axialSpan <= ContainmentEps && angularSpan >= (2d * double.Pi) - 1e-3d)
{
degeneracy = CylinderProjectionDegeneracy.FullRevolutionConstantAxial;
}
else if (repeatedSeamPointCount > 0)
{
degeneracy = CylinderProjectionDegeneracy.RepeatedSeamProjectionCollapse;
}
else if (angularSpan <= 1e-6d)
{
degeneracy = CylinderProjectionDegeneracy.DegenerateAngularSpan;
}
else if (axialSpan <= ContainmentEps)
{
degeneracy = CylinderProjectionDegeneracy.DegenerateAxialSpan;
}
else
{
degeneracy = CylinderProjectionDegeneracy.NearZeroArea;
}
}
return new CylinderProjectionAnalysis(angularSpan, axialSpan, seamCrossings, repeatedSeamPointCount, degeneracy);
}
private static bool IsToroidalFullMajorRevolutionConstantMinor(TorusProjectionAnalysis analysis)
{
var almostFullMajorTurn = analysis.MajorSpan >= (2d * double.Pi) - 1e-3d
|| analysis.MajorSeamCrossings > 0;
var nearConstantMinor = analysis.MinorSpan <= 1e-6d;
var supportedDegeneracy = analysis.Degeneracy == TorusProjectionDegeneracy.RepeatedSeamProjectionCollapse
|| analysis.Degeneracy == TorusProjectionDegeneracy.DegenerateMinorSpan;
// Major-ring/band boundaries are non-contractible loops that can project as near-zero-area
// traces in toroidal UV despite being valid topological boundaries on the surface.
return almostFullMajorTurn
&& nearConstantMinor
&& supportedDegeneracy;
}
private static TorusProjectionAnalysis AnalyzeToroidalProjection(int uniqueCount, double signedArea, IReadOnlyList<UvPoint> projected)
{
if (projected.Count == 0)
{
return new TorusProjectionAnalysis(0d, 0d, 0, 0, 0, 0, TorusProjectionDegeneracy.InsufficientUniquePoints);
}
var minU = projected.Min(p => p.X);
var maxU = projected.Max(p => p.X);
var minV = projected.Min(p => p.Y);
var maxV = projected.Max(p => p.Y);
var majorSpan = maxU - minU;
var minorSpan = maxV - minV;
var majorSeamCrossings = 0;
var minorSeamCrossings = 0;
var repeatedMajorSeamPointCount = 0;
var repeatedMinorSeamPointCount = 0;
for (var i = 1; i < projected.Count; i++)
{
var deltaU = projected[i].X - projected[i - 1].X;
var deltaV = projected[i].Y - projected[i - 1].Y;
if (double.Abs(deltaU) > double.Pi)
{
majorSeamCrossings++;
}
if (double.Abs(deltaV) > double.Pi)
{
minorSeamCrossings++;
}
var aU = NormalizeToZeroTwoPi(projected[i - 1].X);
var bU = NormalizeToZeroTwoPi(projected[i].X);
var nearMajorSeam = (aU <= 1e-6d || aU >= (2d * double.Pi) - 1e-6d) && (bU <= 1e-6d || bU >= (2d * double.Pi) - 1e-6d);
if (nearMajorSeam && double.Abs(projected[i].Y - projected[i - 1].Y) <= ContainmentEps)
{
repeatedMajorSeamPointCount++;
}
var aV = NormalizeToZeroTwoPi(projected[i - 1].Y);
var bV = NormalizeToZeroTwoPi(projected[i].Y);
var nearMinorSeam = (aV <= 1e-6d || aV >= (2d * double.Pi) - 1e-6d) && (bV <= 1e-6d || bV >= (2d * double.Pi) - 1e-6d);
if (nearMinorSeam && double.Abs(projected[i].X - projected[i - 1].X) <= ContainmentEps)
{
repeatedMinorSeamPointCount++;
}
}
var degeneracy = TorusProjectionDegeneracy.None;
if (uniqueCount < 3)
{
degeneracy = TorusProjectionDegeneracy.InsufficientUniquePoints;
}
else if (double.Abs(signedArea) <= AreaEps)
{
if ((repeatedMajorSeamPointCount + repeatedMinorSeamPointCount) > 0)
{
degeneracy = TorusProjectionDegeneracy.RepeatedSeamProjectionCollapse;
}
else if (majorSpan <= 1e-6d)
{
degeneracy = TorusProjectionDegeneracy.DegenerateMajorSpan;
}
else if (minorSpan <= 1e-6d)
{
degeneracy = TorusProjectionDegeneracy.DegenerateMinorSpan;
}
else if (majorSeamCrossings > 0 && minorSeamCrossings == 0)
{
degeneracy = TorusProjectionDegeneracy.MajorPeriodSeamUnwrapFailure;
}
else if (minorSeamCrossings > 0 && majorSeamCrossings == 0)
{
degeneracy = TorusProjectionDegeneracy.MinorPeriodSeamUnwrapFailure;
}
else
{
degeneracy = TorusProjectionDegeneracy.NearZeroArea;
}
}
return new TorusProjectionAnalysis(
majorSpan,
minorSpan,
majorSeamCrossings,
minorSeamCrossings,
repeatedMajorSeamPointCount,
repeatedMinorSeamPointCount,
degeneracy);
}
private static ConeProjectionAnalysis AnalyzeConicalProjection(int uniqueCount, double signedArea, IReadOnlyList<UvPoint> projected)
{
if (projected.Count == 0)
{
return new ConeProjectionAnalysis(0d, 0d, 0, 0, 0d, ConeProjectionDegeneracy.InsufficientUniquePoints);
}
var minU = projected.Min(p => p.X);
var maxU = projected.Max(p => p.X);
var minV = projected.Min(p => p.Y);
var maxV = projected.Max(p => p.Y);
var angularSpan = maxU - minU;
var axialSpan = maxV - minV;
var seamCrossings = 0;
var repeatedSeamPointCount = 0;
var axialMean = projected.Average(p => p.Y);
for (var i = 1; i < projected.Count; i++)
{
var delta = projected[i].X - projected[i - 1].X;
if (double.Abs(delta) > double.Pi)
{
seamCrossings++;
}
var a = NormalizeToZeroTwoPi(projected[i - 1].X);
var b = NormalizeToZeroTwoPi(projected[i].X);
var nearSeam = (a <= 1e-6d || a >= (2d * double.Pi) - 1e-6d) && (b <= 1e-6d || b >= (2d * double.Pi) - 1e-6d);
if (nearSeam && double.Abs(projected[i].Y - projected[i - 1].Y) <= ContainmentEps)
{
repeatedSeamPointCount++;
}
}
var degeneracy = ConeProjectionDegeneracy.None;
if (uniqueCount < 3)
{
degeneracy = ConeProjectionDegeneracy.InsufficientUniquePoints;
}
else if (double.Abs(signedArea) <= AreaEps)
{
if (axialSpan <= ContainmentEps && angularSpan >= (2d * double.Pi) - 1e-3d)
{
degeneracy = ConeProjectionDegeneracy.FullRevolutionConstantAxial;
}
else if (repeatedSeamPointCount > 0)
{
degeneracy = ConeProjectionDegeneracy.RepeatedSeamProjectionCollapse;
}
else if (angularSpan <= 1e-6d)
{
degeneracy = ConeProjectionDegeneracy.DegenerateAngularSpan;
}
else if (axialSpan <= ContainmentEps)
{
degeneracy = ConeProjectionDegeneracy.DegenerateAxialSpan;
}
else
{
degeneracy = ConeProjectionDegeneracy.NearZeroArea;
}
}
return new ConeProjectionAnalysis(angularSpan, axialSpan, seamCrossings, repeatedSeamPointCount, axialMean, degeneracy);
}
private static IReadOnlyList<UvPoint> AlignPolygonToReference(IReadOnlyList<UvPoint> polygon, double currentX, double referenceX)
{
var twoPi = 2d * double.Pi;
var delta = referenceX - currentX;
var turns = double.Round(delta / twoPi);
var shift = turns * twoPi;
if (double.Abs(shift) <= AngleUnwrapEps)
{
return polygon;
}
return polygon.Select(p => new UvPoint(p.X + shift, p.Y)).ToArray();
}
private static IReadOnlyList<UvPoint> AlignPolygonToReferenceY(IReadOnlyList<UvPoint> polygon, double currentY, double referenceY)
{
var twoPi = 2d * double.Pi;
var delta = referenceY - currentY;
var turns = double.Round(delta / twoPi);
var shift = turns * twoPi;
if (double.Abs(shift) <= AngleUnwrapEps)
{
return polygon;
}
return polygon.Select(p => new UvPoint(p.X, p.Y + shift)).ToArray();
}
private static double NormalizeToZeroTwoPi(double angle)
{
var twoPi = 2d * double.Pi;
var normalized = angle % twoPi;
if (normalized < 0d)
{
normalized += twoPi;
}
return normalized;
}
private static double ComputeSignedArea(IReadOnlyList<UvPoint> polygon)
{
var area = 0d;
for (var i = 0; i < polygon.Count - 1; i++)
{
var p0 = polygon[i];
var p1 = polygon[i + 1];
area += (p0.X * p1.Y) - (p1.X * p0.Y);
}
return 0.5d * area;
}
private static double ComputeContainmentTolerance(IEnumerable<UvPoint> points)
{
var array = points.ToArray();
if (array.Length == 0)
{
return ContainmentEps;
}
var minX = array.Min(p => p.X);
var maxX = array.Max(p => p.X);
var minY = array.Min(p => p.Y);
var maxY = array.Max(p => p.Y);
var diagonal = double.Sqrt(((maxX - minX) * (maxX - minX)) + ((maxY - minY) * (maxY - minY)));
return System.Math.Max(ContainmentEps, diagonal * 1e-6d);
}
private static double ComputeAreaTolerance(IEnumerable<UvPoint> points)
{
var array = points.ToArray();
if (array.Length == 0)
{
return AreaEps;
}
var minX = array.Min(p => p.X);
var maxX = array.Max(p => p.X);
var minY = array.Min(p => p.Y);
var maxY = array.Max(p => p.Y);
var extentArea = (maxX - minX) * (maxY - minY);
return System.Math.Max(AreaEps, extentArea * 1e-8d);
}
private static void AppendLoopSamples(IList<Point3D> loopSamples, IReadOnlyList<Point3D> edgeSamples)
{
_ = AppendLoopSamples(loopSamples, edgeSamples, null, -1, -1, -1, null);
}
private static LoopCoedgeGapClassification AppendLoopSamples(
IList<Point3D> loopSamples,
IReadOnlyList<Point3D> edgeSamples,
SurfaceGeometry? surface,
int faceEntityId,
int loopId,
int coedgeId,
int? previousCoedgeId)
{
var normalizedEdgeSamples = edgeSamples.ToList();
var boundaryClassification = LoopCoedgeGapClassification.Negligible;
if (loopSamples.Count > 0 && normalizedEdgeSamples.Count > 0)
{
var previousPoint = loopSamples[^1];
var currentPoint = normalizedEdgeSamples[0];
var gap = ClassifyCoedgeGap(previousPoint, currentPoint, surface);
boundaryClassification = gap.Classification;
ReportCoedgeGapDiagnostic(new LoopRoleCoedgeGapDiagnostic(
FaceEntityId: faceEntityId,
LoopId: loopId,
PreviousCoedgeId: previousCoedgeId,
NextCoedgeId: coedgeId,
Gap3d: gap.Gap3d,
Gap2d: gap.Gap2d,
PreviousEdgeGeometryKind: null,
NextEdgeGeometryKind: null,
Classification: gap.Classification,
WithinPointOnSurfaceEps: gap.Gap3d <= PointOnSurfaceEps,
WithinContainmentEps: gap.Gap3d <= ContainmentEps,
WouldCreateGhostSegmentWithoutNormalization: gap.Gap3d > PointOnSurfaceEps));
if (gap.Classification == LoopCoedgeGapClassification.TinyNormalizable)
{
normalizedEdgeSamples[0] = previousPoint;
}
}
foreach (var point in normalizedEdgeSamples)
{
if (loopSamples.Count > 0)
{
var last = loopSamples[^1];
if ((last - point).Length <= PointOnSurfaceEps)
{
continue;
}
}
loopSamples.Add(point);
}
return boundaryClassification;
}
private static KernelResult<IReadOnlyList<Point3D>> SampleCoedgePoints(
EdgeGeometryBinding edgeBinding,
BrepGeometryStore geometry,
bool isReversed,
int faceEntityId,
int loopId,
int coedgeId,
int edgeId)
{
if (!geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null)
{
return LoopRoleFailure<IReadOnlyList<Point3D>>("Missing edge curve geometry for loop sampling.", "Importer.LoopRole.WindingConflict");
}
List<Point3D> points;
switch (curve.Kind)
{
case CurveGeometryKind.Line3:
var line = curve.Line3!.Value;
var lineRange = edgeBinding.TrimInterval ?? new ParameterInterval(0d, 1d);
points = [line.Evaluate(lineRange.Start), line.Evaluate(lineRange.End)];
break;
case CurveGeometryKind.Circle3:
var circle = curve.Circle3!.Value;
var trim = edgeBinding.TrimInterval ?? new ParameterInterval(0d, 2d * double.Pi);
var span = trim.End - trim.Start;
var isFullCircle = double.Abs(span - (2d * double.Pi)) <= AngleUnwrapEps;
var legacyPointCount = isFullCircle ? 5 : 3;
var segmentCount = ComputeAdaptiveCircleSegmentCount(span);
points = SampleCircularTrim(circle, trim, segmentCount);
ReportCircularSamplingDiagnostic(new LoopRoleCircularSamplingDiagnostic(
FaceEntityId: faceEntityId,
LoopId: loopId,
CoedgeId: coedgeId,
EdgeId: edgeId,
TrimStart: trim.Start,
TrimEnd: trim.End,
TrimSpan: span,
IsFullCircle: isFullCircle,
LegacyPointCount: legacyPointCount,
AdaptivePointCount: points.Count));
break;
case CurveGeometryKind.Ellipse3:
var ellipse = curve.Ellipse3!.Value;
var ellipseTrim = edgeBinding.TrimInterval ?? new ParameterInterval(0d, 2d * double.Pi);
var ellipseSpan = ellipseTrim.End - ellipseTrim.Start;
var ellipseSegmentCount = ComputeAdaptiveCircleSegmentCount(ellipseSpan);
points = SampleEllipticalTrim(ellipse, ellipseTrim, ellipseSegmentCount);
break;
case CurveGeometryKind.Hyperbola3:
var hyperbola = curve.Hyperbola3!.Value;
var hyperbolaTrim = edgeBinding.TrimInterval ?? new ParameterInterval(-1d, 1d);
points = SampleHyperbolicTrim(hyperbola, hyperbolaTrim, ComputeAdaptiveCircleSegmentCount(hyperbolaTrim.End - hyperbolaTrim.Start));
break;
case CurveGeometryKind.BSpline3:
var spline = curve.BSpline3!.Value;
var splineTrim = edgeBinding.TrimInterval ?? new ParameterInterval(spline.DomainStart, spline.DomainEnd);
// A start/mid/end polyline cuts corners of any curved B-spline by up to ~1e-2 mm, which is enough to
// make a hole loop that hugs its outer loop look like it crosses it. Sample densely enough that the
// classification polygon follows the curve.
const int splineClassificationSegments = 32;
points = new List<Point3D>(splineClassificationSegments + 1);
for (var i = 0; i <= splineClassificationSegments; i++)
{
var t = i == splineClassificationSegments
? splineTrim.End
: splineTrim.Start + ((splineTrim.End - splineTrim.Start) * i / splineClassificationSegments);
points.Add(spline.Evaluate(t));
}
break;
default:
points = [];
break;
}
// Samples above run in curve-parameter order. ORIENTED_EDGE orientation is relative to the edge's vertex
// order, and EDGE_CURVE same_sense says whether the curve parameter runs with or against that order, so the
// traversal direction is the XOR of both. Ignoring same_sense=.F. reversed the samples of those edges and
// produced huge fake gaps between consecutive coedges.
if (isReversed ^ !edgeBinding.OrientedEdgeSense)
{
points.Reverse();
}
return KernelResult<IReadOnlyList<Point3D>>.Success(points);
}
private static int ComputeAdaptiveCircleSegmentCount(double span)
{
// Classification polygon only; exact edge geometry is retained. The former
// two-chord quarter arc falsely rejected close polynomial inner trims.
const double maxSegmentAngle = double.Pi / 64d;
var normalizedSpan = double.Abs(span);
var segmentCount = (int)double.Ceiling(normalizedSpan / maxSegmentAngle);
return System.Math.Max(2, segmentCount);
}
private static List<Point3D> SampleCircularTrim(Circle3Curve circle, ParameterInterval trim, int segmentCount)
{
var points = new List<Point3D>(segmentCount + 1);
var step = (trim.End - trim.Start) / segmentCount;
for (var i = 0; i <= segmentCount; i++)
{
points.Add(circle.Evaluate(trim.Start + (step * i)));
}
return points;
}
private static List<Point3D> SampleEllipticalTrim(Ellipse3Curve ellipse, ParameterInterval trim, int segmentCount)
{
var points = new List<Point3D>(segmentCount + 1);
var step = (trim.End - trim.Start) / segmentCount;
for (var i = 0; i <= segmentCount; i++)
{
points.Add(ellipse.Evaluate(trim.Start + (step * i)));
}
return points;
}
private static List<Point3D> SampleHyperbolicTrim(Hyperbola3Curve hyperbola, ParameterInterval trim, int segmentCount)
{
var points = new List<Point3D>(segmentCount + 1);
var step = (trim.End - trim.Start) / segmentCount;
for (var i = 0; i <= segmentCount; i++) points.Add(hyperbola.Evaluate(trim.Start + (step * i)));
return points;
}
private static void ReportCircularSamplingDiagnostic(LoopRoleCircularSamplingDiagnostic diagnostic)
{
var sink = CircularSamplingDiagnosticsSink.Value;
sink?.Add(diagnostic);
}
private static void ReportCoedgeGapDiagnostic(LoopRoleCoedgeGapDiagnostic diagnostic)
{
var sink = CoedgeGapDiagnosticsSink.Value;
sink?.Add(diagnostic);
}
private static void ReportCylinderProjectionDiagnostic(LoopRoleCylinderProjectionDiagnostic diagnostic)
{
var sink = CylinderProjectionDiagnosticsSink.Value;
sink?.Add(diagnostic);
}
private static void ReportTorusProjectionDiagnostic(LoopRoleTorusProjectionDiagnostic diagnostic)
{
var sink = TorusProjectionDiagnosticsSink.Value;
sink?.Add(diagnostic);
}
private static void ReportPlanarMultiBoundJudgmentDiagnostic(PlanarMultiBoundJudgmentDiagnostic diagnostic)
{
var sink = PlanarMultiBoundJudgmentDiagnosticsSink.Value;
sink?.Add(diagnostic);
}
private static (double Gap3d, double Gap2d, LoopCoedgeGapClassification Classification) ClassifyCoedgeGap(
Point3D previousEnd,
Point3D nextStart,
SurfaceGeometry? surface)
{
var gap3d = (previousEnd - nextStart).Length;
var gap2d = gap3d;
if (surface is not null)
{
gap2d = surface.Kind switch
{
SurfaceGeometryKind.Plane => ComputePlanarGap(previousEnd, nextStart, surface.Plane!.Value),
_ => gap3d
};
}
var classification = gap3d <= PointOnSurfaceEps
? LoopCoedgeGapClassification.Negligible
: gap3d <= TinyCoedgeGapSnapEps
? LoopCoedgeGapClassification.TinyNormalizable
: LoopCoedgeGapClassification.Disconnected;
return (gap3d, gap2d, classification);
}
private static double ComputePlanarGap(Point3D a, Point3D b, PlaneSurface plane)
{
var delta = b - a;
var du = delta.Dot(plane.UAxis.ToVector());
var dv = delta.Dot(plane.VAxis.ToVector());
return double.Sqrt((du * du) + (dv * dv));
}
private static string? DescribeCurveKind(EdgeGeometryBinding edgeBinding, BrepGeometryStore geometry)
{
if (!geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null)
{
return null;
}
return curve.Kind.ToString();
}
public sealed record LoopRoleCircularSamplingDiagnostic(
int FaceEntityId,
int LoopId,
int CoedgeId,
int EdgeId,
double TrimStart,
double TrimEnd,
double TrimSpan,
bool IsFullCircle,
int LegacyPointCount,
int AdaptivePointCount);
public sealed record LoopRoleCoedgeGapDiagnostic(
int FaceEntityId,
int LoopId,
int? PreviousCoedgeId,
int? NextCoedgeId,
double Gap3d,
double Gap2d,
string? PreviousEdgeGeometryKind,
string? NextEdgeGeometryKind,
LoopCoedgeGapClassification Classification,
bool WithinPointOnSurfaceEps,
bool WithinContainmentEps,
bool WouldCreateGhostSegmentWithoutNormalization);
public enum LoopCoedgeGapClassification
{
Negligible,
TinyNormalizable,
Disconnected
}
public sealed record LoopRoleCylinderProjectionDiagnostic(
int FaceEntityId,
int LoopId,
int PointCount,
int UniquePointCount,
double SignedArea,
double AngularSpan,
double AxialSpan,
int SeamCrossings,
int RepeatedSeamPointCount,
string Degeneracy);
public sealed record LoopRoleTorusProjectionDiagnostic(
int FaceEntityId,
int LoopId,
int PointCount,
int UniquePointCount,
double SignedArea,
double MajorSpan,
double MinorSpan,
int MajorSeamCrossings,
int MinorSeamCrossings,
int RepeatedMajorSeamPointCount,
int RepeatedMinorSeamPointCount,
string Degeneracy,
string InitialDegeneracy,
double InitialSignedArea,
bool FullMajorSpanNearConstantMinorCandidate);
public sealed record PlanarMultiBoundJudgmentDiagnostic(
int FaceLoopCount,
int OuterLoopId,
int InnerLoopId,
double OuterArea,
double InnerArea,
double AreaRatio,
int ContainedVertexCount,
int VertexCount,
int IntersectionCount,
double MinDistanceToOuter,
bool HasDisconnectedCoedgeGap,
bool HasSingleDeclaredOuterLoop,
string SelectedCandidate,
string CandidateRejections);
private enum CylinderProjectionDegeneracy
{
None = 0,
InsufficientUniquePoints = 1,
NearZeroArea = 2,
FullRevolutionConstantAxial = 3,
DegenerateAngularSpan = 4,
DegenerateAxialSpan = 5,
RepeatedSeamProjectionCollapse = 6
}
private sealed record CylinderProjectionAnalysis(
double AngularSpan,
double AxialSpan,
int SeamCrossings,
int RepeatedSeamPointCount,
CylinderProjectionDegeneracy Degeneracy);
private enum TorusProjectionDegeneracy
{
None = 0,
InsufficientUniquePoints = 1,
NearZeroArea = 2,
DegenerateMajorSpan = 3,
DegenerateMinorSpan = 4,
RepeatedSeamProjectionCollapse = 5,
MajorPeriodSeamUnwrapFailure = 6,
MinorPeriodSeamUnwrapFailure = 7
}
private sealed record TorusProjectionAnalysis(
double MajorSpan,
double MinorSpan,
int MajorSeamCrossings,
int MinorSeamCrossings,
int RepeatedMajorSeamPointCount,
int RepeatedMinorSeamPointCount,
TorusProjectionDegeneracy Degeneracy);
private enum ConeProjectionDegeneracy
{
None = 0,
InsufficientUniquePoints = 1,
NearZeroArea = 2,
FullRevolutionConstantAxial = 3,
DegenerateAngularSpan = 4,
DegenerateAxialSpan = 5,
RepeatedSeamProjectionCollapse = 6
}
private sealed record ConeProjectionAnalysis(
double AngularSpan,
double AxialSpan,
int SeamCrossings,
int RepeatedSeamPointCount,
double AxialMean,
ConeProjectionDegeneracy Degeneracy);
private sealed class CircularSamplingDiagnosticsScope(ICollection<LoopRoleCircularSamplingDiagnostic>? previous) : IDisposable
{
public void Dispose()
{
CircularSamplingDiagnosticsSink.Value = previous;
}
}
private sealed class CoedgeGapDiagnosticsScope(ICollection<LoopRoleCoedgeGapDiagnostic>? previous) : IDisposable
{
public void Dispose()
{
CoedgeGapDiagnosticsSink.Value = previous;
}
}
private sealed class CylinderProjectionDiagnosticsScope(ICollection<LoopRoleCylinderProjectionDiagnostic>? previous) : IDisposable
{
public void Dispose()
{
CylinderProjectionDiagnosticsSink.Value = previous;
}
}
private sealed class TorusProjectionDiagnosticsScope(ICollection<LoopRoleTorusProjectionDiagnostic>? previous) : IDisposable
{
public void Dispose()
{
TorusProjectionDiagnosticsSink.Value = previous;
}
}
private sealed class PlanarMultiBoundJudgmentDiagnosticsScope(ICollection<PlanarMultiBoundJudgmentDiagnostic>? previous) : IDisposable
{
public void Dispose()
{
PlanarMultiBoundJudgmentDiagnosticsSink.Value = previous;
}
}
private sealed class PreserveRationalSurfacesScope(bool previous) : IDisposable
{
public void Dispose()
{
PreserveRationalSurfacesFlag.Value = previous;
}
}
private static KernelResult<T> LoopRoleFailure<T>(string message, string source) =>
KernelResult<T>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source)]);
private static KernelResult<BrepBody> Failure(string message, string source) =>
Step242ImportSharedUtilities.NotImplementedFailure<BrepBody>(message, source);
private static KernelResult<EdgeId> FailureEdge(string message, string source) =>
Step242ImportSharedUtilities.NotImplementedFailure<EdgeId>(message, source);
private static KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)> FailureCurveBinding(string message, string source) =>
Step242ImportSharedUtilities.NotImplementedFailure<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>(message, source);
private static KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)> FailureSurfaceBinding(string message, string source) =>
Step242ImportSharedUtilities.NotImplementedFailure<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>(message, source);
private static KernelResult<ParameterInterval> FailureCircleTrim(string message, string source) =>
Step242ImportSharedUtilities.ValidationFailure<ParameterInterval>(message, source);
private static KernelResult<double> FailureCircleTrimAngle(string message, string source) =>
Step242ImportSharedUtilities.ValidationFailure<double>(message, source);
private static KernelResult<ParameterInterval> FailureEllipseTrim(string message, string? source) =>
Step242ImportSharedUtilities.ValidationFailure<ParameterInterval>(message, source ?? "Importer.Geometry.EllipseTrim");
private static KernelResult<double> FailureEllipseTrimAngle(string message, string source) =>
Step242ImportSharedUtilities.ValidationFailure<double>(message, source);
private static KernelResult<ParameterInterval> FailureHyperbolaTrim(string message, string source) =>
Step242ImportSharedUtilities.ValidationFailure<ParameterInterval>(message, source);
private static KernelResult<double> FailureHyperbolaTrimParameter(string message, string source) =>
Step242ImportSharedUtilities.ValidationFailure<double>(message, source);
private static KernelResult<T> OrientationFailure<T>(string message, string source) =>
KernelResult<T>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source)]);
private static string SourceFor(int _entityId, string stableSource) => stableSource;
private sealed record LoopBuildData(
LoopId LoopId,
IReadOnlyList<Coedge> Coedges,
IReadOnlyList<Point3D> Samples,
bool HasDisconnectedCoedgeGap = false,
bool IsDeclaredOuter = false,
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);
private sealed record PlanarLoopInfoWithSample(PlanarLoopInfo Info, UvPoint SamplePoint);
private sealed record PlanarLoopOuterCandidate(PlanarLoopInfo Info, UvPoint SamplePoint, int ContainmentCount);
private sealed record CylindricalLoopInfo(LoopBuildData Loop, IReadOnlyList<UvPoint> ProjectedPoints, double SignedArea, UvPoint Centroid);
private sealed record ContainmentEvaluation(int OutsideCount, int VertexCount, double MinDistanceToOuter,
double MaxOutsideDistanceToOuter);
private sealed record ContainmentFailure(string Message, string Source);
private sealed record PlanarCrossingInsideRecoveryContext(
int InnerLoopId,
int OuterLoopId,
int LoopCount,
double InnerArea,
double OuterArea,
double AreaRatio,
int IntersectionCount,
int ContainedVertexCount,
int VertexCount,
double MinDistanceToOuter,
bool HasDisconnectedCoedgeGap,
bool HasSingleDeclaredOuterLoop,
bool IsNearBoundaryContact,
double MaximumOutsideDistance,
double NearCoincidentTolerance);
private readonly record struct UvPoint(double X, double Y)
{
public static UvPoint operator +(UvPoint a, UvPoint b) => new(a.X + b.X, a.Y + b.Y);
public static UvPoint operator -(UvPoint a, UvPoint b) => new(a.X - b.X, a.Y - b.Y);
public static UvPoint operator *(UvPoint a, double s) => new(a.X * s, a.Y * s);
public double Dot(UvPoint other) => (X * other.X) + (Y * other.Y);
public double Length => double.Sqrt((X * X) + (Y * Y));
}
}