Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

99.3 KB
Raw Blame
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.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;

namespace Aetheris.Kernel.Core.Step242;

public static class Step242Exporter
{
    public static KernelResult<string> ExportBody(BrepBody body, Step242ExportOptions? options = null)
        => ExportBody(body, semanticPmi: null, options);

    public static KernelResult<string> ExportBody(
        BrepBody body,
        IReadOnlyList<Step242SemanticPmi>? semanticPmi,
        Step242ExportOptions? options = null)
    {
        options ??= new Step242ExportOptions();
        var declaredDatums = (semanticPmi ?? []).OfType<Step242SemanticPmiDatum>().Select(d => d.Label).ToHashSet(StringComparer.OrdinalIgnoreCase);
        if ((options.ImportedPmi?.DatumLabels ?? []).Any(declaredDatums.Contains))
            return Failure("pmi-source-datum-conflict: Authored datum labels must not shadow retained source datums.", "Step242.Pmi");
        declaredDatums.UnionWith(options.ImportedPmi?.DatumLabels ?? []);
        foreach (var control in (semanticPmi ?? []).OfType<Step242SemanticPmiGeometricTolerance>())
        {
            if (Step242GeometricToleranceKinds.Validate(control, declaredDatums) is { } problem)
                return Failure($"pmi-geometric-tolerance-invalid: '{control.Name}': {problem}", "Step242.Pmi");
            if (control.GeometricFaceIds.Count == 0 || control.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
                return Failure($"pmi-geometric-target-unresolved: '{control.Name}' requires proved face associations.", "Step242.Pmi");
        }
        // A projected dimension must stay attached to the geometry it measures.
        foreach (var dimension in (semanticPmi ?? []).OfType<Step242SemanticPmiDimension>().Where(d => d.StandardKind is not null || d.FeatureId.StartsWith("compose:", StringComparison.Ordinal)))
            if (dimension.GeometricFaceIds.Count == 0 || dimension.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
                return Failure($"pmi-dimension-target-unresolved: '{dimension.Name}' does not resolve to faces of the exported body.", "Step242.Pmi");
        // A datum feature without its face is a label with nothing to contact; never export one unattached.
        foreach (var datum in (semanticPmi ?? []).OfType<Step242SemanticPmiDatum>().Where(d => d.RequiresFaceAssociation))
            if (datum.GeometricFaceIds.Count == 0 || datum.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
                return Failure($"pmi-datum-target-unresolved: Datum '{datum.Label}' does not resolve to a face of the exported body. Use a face that bounds the part in that direction, or name the face of a Compose operation such as face(stock.Top).", "Step242.Pmi");
        IReadOnlyList<KernelDiagnostic> normalizationDiagnostics = [];
        if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute)
        {
            var bindings = BrepBindingValidator.Validate(body);
            if (!bindings.IsSuccess) return KernelResult<string>.Failure(bindings.Diagnostics);
        }
        if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute
            && options.ImportedRecoveryToleranceMillimetres is { } normalizationBudget
            && (body.Geometry.Surfaces.Any(s => s.Value.BSplineSurfaceWithKnots?.IsRational == true)
                || body.Bindings.PcurveBindings.Any(p => p.Pcurve.RationalWeights is not null)))
        {
            var normalized = Step242ProductionNormalization.Prepare(body, double.Min(.1d, normalizationBudget));
            if (!normalized.IsSuccess) return KernelResult<string>.Failure(normalized.Diagnostics);
            body = normalized.Value;
            normalizationDiagnostics = normalized.Diagnostics;
        }

        // The legacy interchange route still supports rational evidence for
        // compatibility and debugging. Trusted production routes must first
        // recover a canonical analytic or non-rational representation.
        if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute)
        {
            foreach (var face in body.Bindings.FaceBindings)
            {
                if (body.Geometry.TryGetSurface(face.SurfaceGeometryId, out var support)
                    && support?.BSplineSurfaceWithKnots?.IsRational == true)
                    return RationalGeometryNotCanonical($"Face:{face.FaceId.Value}", "rational B-spline surface");
            }
            foreach (var pcurve in body.Bindings.PcurveBindings)
            {
                if (pcurve.Pcurve.RationalWeights is not null)
                    return RationalGeometryNotCanonical($"Coedge:{pcurve.CoedgeId.Value}", "rational B-spline pcurve");
            }
        }

        foreach (var binding in body.Bindings.PcurveBindings)
            if (body.TryGetFaceSurfaceGeometry(binding.FaceId, out var support) && support?.Ellipsoid is not null)
                return Failure("EllipsoidPcurveProjectionUnsupported: native angular pcurves must be remapped to the rational STEP patch domain before export. The ellipsoid primitive exports its exact 3D edge curves without pcurves.", $"Face:{binding.FaceId.Value}");

        var preflight = options.BrepExportPreflightMode == BrepExportPreflightMode.Disabled
            ? null
            : BrepExportPreflight.Validate(body, options.ImportedRecoveryToleranceMillimetres,
                options.ImportedSourceVertexTolerancesMillimetres);
        if (preflight is { IsValid: false } && options.BrepExportPreflightMode == BrepExportPreflightMode.Enforce)
        {
            return KernelResult<string>.Failure(ToKernelDiagnostics(preflight, errorsAsWarnings: false));
        }

        var model = body.Topology;
        var bodyNodes = model.Bodies.OrderBy(b => b.Id.Value).ToArray();
        if (bodyNodes.Length != 1)
        {
            return Failure("Only single-body export is supported.", "Topology.Bodies");
        }

        var rootDecision = StepSolidRootExportPlanner.Decide(body);
        var shellRepresentation = body.ShellRepresentation;
        if (rootDecision.Kind == StepSolidRootExportKind.Unsupported)
        {
            var plannerReason = rootDecision.Evaluations
                .FirstOrDefault(e => e.PolicyName == "UnsupportedShellTopologyPolicy")?
                .Diagnostics.FirstOrDefault() ?? "Unsupported shell topology for STEP solid root export.";
            return Failure(plannerReason, "Topology.Shells");
        }

        if (shellRepresentation is null)
        {
            var shellIds = bodyNodes[0].ShellIds.OrderBy(s => s.Value).ToArray();
            shellRepresentation = new BrepBodyShellRepresentation(shellIds[0], []);
        }

        var writer = new Step242TextWriter();

        var vertexPointIds = new Dictionary<VertexId, string>();
        var cartesianPointIds = new Dictionary<VertexId, string>();
        var vertexPoints = new Dictionary<VertexId, Point3D>();

        var edgeCurveIds = new Dictionary<EdgeId, string>();
        var orientedEdgeIds = new Dictionary<CoedgeId, string>();
        var lineIds = new Dictionary<EdgeId, string>();
        var circleIds = new Dictionary<EdgeId, string>();
        var bsplineIds = new Dictionary<EdgeId, string>();
        var ellipseIds = new Dictionary<EdgeId, string>();
        var hyperbolaIds = new Dictionary<EdgeId, string>();
        var surfaceIds = new Dictionary<SurfaceGeometryId, string>();
        var advancedFaceIds = new Dictionary<FaceId, string>();
        // Keep source pcurves, but do not publish a partial recovered trim set.
        // Pure exact planar projections are deterministically derivable from the
        // emitted geometry. Preserve the compact canonical legacy normal form when
        // no source/recovered parameter trace needs serialization.
        // UV traces are optional STEP acceleration data. Never serialize a failed
        // recovered set as authority over a valid 3D boundary. Edits which require
        // those traces are admitted separately by their operation owners.
        var omitUnqualifiedPcurves = options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute
            && (body.PcurveRecoveryReport is { IsSuccess: false }
                || body.Bindings.PcurveBindings.Any() && !BrepPcurveValidator.Validate(body,
                    options.ImportedRecoveryToleranceMillimetres ?? 1e-6).IsValid);
        var pcurveContextId = options.EmitQualifiedPcurves && !omitUnqualifiedPcurves && body.Bindings.PcurveBindings.Any(binding =>
            binding.Qualification?.Origin != PcurveBindingOrigin.DerivedAnalytic
            && (body.PcurveRecoveryReport is not { IsSuccess: false }
            || binding.SourceStepPcurveEntityId is not null))
            ? writer.AddEntity("REPRESENTATION_CONTEXT", Step242TextWriter.String("2D"), Step242TextWriter.String("parameter space"))
            : null;

        var orientationDiagnostics = new List<KernelDiagnostic>();
        var outerClosedShellId = BuildClosedShell(writer, body, model, shellRepresentation.OuterShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, advancedFaceIds, pcurveContextId, orientationDiagnostics);
        EmitAuxiliaryVertexPointForVertexlessAnalyticBody(writer, body, model);
        if (outerClosedShellId is null)
        {
            return Failure($"Shell {shellRepresentation.OuterShellId.Value} could not be exported.", $"Shell:{shellRepresentation.OuterShellId.Value}");
        }

        string brepId;
        if (rootDecision.Kind == StepSolidRootExportKind.ManifoldSolidBrep)
        {
            brepId = writer.AddEntity("MANIFOLD_SOLID_BREP", Step242TextWriter.String(options.ProductName), Step242TextWriter.Ref(outerClosedShellId));
        }
        else
        {
            var orientedVoidShellIds = new List<string>();
            foreach (var innerShellId in shellRepresentation.InnerShellIds.OrderBy(id => id.Value))
            {
                var innerClosedShellId = BuildClosedShell(writer, body, model, innerShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, advancedFaceIds, pcurveContextId, orientationDiagnostics);
                if (innerClosedShellId is null)
                {
                    return Failure($"Shell {innerShellId.Value} could not be exported.", $"Shell:{innerShellId.Value}");
                }

                var orientedClosedShellId = writer.AddEntity(
                    "ORIENTED_CLOSED_SHELL",
                    "$",
                    Step242TextWriter.Ref(innerClosedShellId),
                    Step242TextWriter.BooleanLogical(false));

                orientedVoidShellIds.Add(orientedClosedShellId);
            }

            brepId = writer.AddEntity(
                "BREP_WITH_VOIDS",
                Step242TextWriter.String(options.ProductName),
                Step242TextWriter.Ref(outerClosedShellId),
                Step242TextWriter.List(orientedVoidShellIds.ToArray()));
        }

        var appContextId = writer.AddEntity("APPLICATION_CONTEXT", Step242TextWriter.String("mechanical design"));
        var productContextId = writer.AddEntity("PRODUCT_CONTEXT", Step242TextWriter.String(""), Step242TextWriter.Ref(appContextId), Step242TextWriter.String("mechanical"));
        var productId = writer.AddEntity("PRODUCT", Step242TextWriter.String(options.ProductId), Step242TextWriter.String(options.ProductName), Step242TextWriter.String(options.ProductDescription), Step242TextWriter.List(productContextId));
        var formationId = writer.AddEntity("PRODUCT_DEFINITION_FORMATION", Step242TextWriter.String(""), Step242TextWriter.String(""), Step242TextWriter.Ref(productId));
        var definitionContextId = writer.AddEntity("PRODUCT_DEFINITION_CONTEXT", Step242TextWriter.String("design"), Step242TextWriter.Ref(appContextId), Step242TextWriter.String("design"));
        var definitionId = writer.AddEntity("PRODUCT_DEFINITION", Step242TextWriter.String(""), Step242TextWriter.String(""), Step242TextWriter.Ref(formationId), Step242TextWriter.Ref(definitionContextId));
        var shapeId = writer.AddEntity("PRODUCT_DEFINITION_SHAPE", Step242TextWriter.String(""), Step242TextWriter.String(""), Step242TextWriter.Ref(definitionId));
        var lengthUnitId = writer.AddRawEntity("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");
        var planeAngleUnitId = writer.AddRawEntity("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
        var solidAngleUnitId = writer.AddRawEntity("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
        var uncertaintyContext = string.Empty;
        // A body with tolerant edges must not claim more precision than its worst measured gap.
        var tolerantFloor = body.Bindings.PcurveBindings
            .Where(b => b.Qualification?.RecoveryMethod.StartsWith(BrepPcurveRecovery.SourceTolerantMethod, StringComparison.Ordinal) == true)
            .Select(b => b.Qualification!.QualificationToleranceMillimetres).DefaultIfEmpty(0d).Max();
        var declaredAccuracy = tolerantFloor > 0d ? double.Max(options.DistanceAccuracyMillimetres ?? 0d, tolerantFloor) : options.DistanceAccuracyMillimetres;
        if (declaredAccuracy is { } accuracy)
        {
            if (!double.IsFinite(accuracy) || accuracy <= 0)
                return Failure("DistanceAccuracyMillimetres must be positive and finite.", "Exporter.DistanceAccuracy");
            var uncertainty = writer.AddEntity("UNCERTAINTY_MEASURE_WITH_UNIT",
                "LENGTH_MEASURE(" + accuracy.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + ")",
                lengthUnitId, "'distance_accuracy_value'", "'Declared accuracy of retained source geometry'");
            uncertaintyContext = $"GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT(({uncertainty}))";
        }
        var repContextId = writer.AddRawEntity($"(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT(({lengthUnitId},{planeAngleUnitId},{solidAngleUnitId})){uncertaintyContext}REPRESENTATION_CONTEXT('3','3D'))");
        var shapeRepresentationId = writer.AddEntity("SHAPE_REPRESENTATION", Step242TextWriter.String(options.ProductName), Step242TextWriter.List(brepId), Step242TextWriter.Ref(repContextId));
        writer.AddEntity("SHAPE_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(shapeId), Step242TextWriter.Ref(shapeRepresentationId));
        IReadOnlyList<KernelDiagnostic> importedPmiDiagnostics = [];
        IReadOnlyDictionary<string, string>? importedDatumEntities = null;
        if (options.ImportedPmi is { } importedPmi)
        {
            var transferred = importedPmi.Emit(writer, body, shapeId, shapeRepresentationId, repContextId, lengthUnitId, brepId, advancedFaceIds, edgeCurveIds,
                options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute, out importedDatumEntities);
            if (!transferred.IsSuccess) return KernelResult<string>.Failure(transferred.Diagnostics);
            importedPmiDiagnostics = transferred.Diagnostics;
        }
        EmitSemanticPmi(writer, shapeId, shapeRepresentationId, repContextId, lengthUnitId, advancedFaceIds, semanticPmi, importedDatumEntities);

        var repairDiagnostics = options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute
            ? (body.ImportQualification?.Repairs ?? []).Select(repair => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,
                KernelDiagnosticSeverity.Warning, repair.Code + ": " + repair.Message, $"Step242.Import.Entity:{repair.StepEntityId}")) : [];
        IReadOnlyList<KernelDiagnostic> trimDiagnostics = omitUnqualifiedPcurves
            ? [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,
                "step-export-recovered-pcurves-omitted: Unqualified UV traces were not emitted; STEP boundaries use their 3D curves and vertices. Source trim qualification has not been promoted.", "Step242.Export")]
            : [];
        return KernelResult<string>.Success(
            writer.Build(options.HeaderMetadata),
            normalizationDiagnostics.Concat(orientationDiagnostics).Concat(importedPmiDiagnostics).Concat(repairDiagnostics).Concat(trimDiagnostics).Concat(preflight is null ? [] : ToKernelDiagnostics(preflight, errorsAsWarnings: true)).ToArray());
    }

    private static void EmitAuxiliaryVertexPointForVertexlessAnalyticBody(Step242TextWriter writer, BrepBody body, TopologyModel model)
    {
        if (model.Vertices.Any()) return;

        foreach (var face in model.Faces.OrderBy(f => f.Id.Value))
        {
            if (!body.TryGetFaceSurface(face.Id, out var surface) || surface is null) continue;
            Point3D? point = surface.Kind switch
            {
                SurfaceGeometryKind.Sphere when surface.Sphere is SphereSurface sphere => sphere.Evaluate(0d, 0d),
                SurfaceGeometryKind.Torus when surface.Torus is TorusSurface torus => torus.Evaluate(0d, 0d),
                _ => null
            };
            if (point is null) continue;
            var pointId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(point.Value));
            writer.AddEntity("VERTEX_POINT", "$", Step242TextWriter.Ref(pointId));
            return;
        }
    }

    private static string? BuildClosedShell(
        Step242TextWriter writer,
        BrepBody body,
        TopologyModel model,
        ShellId shellId,
        Dictionary<VertexId, Point3D> vertexPoints,
        Dictionary<VertexId, string> cartesianPointIds,
        Dictionary<VertexId, string> vertexPointIds,
        Dictionary<EdgeId, string> edgeCurveIds,
        Dictionary<CoedgeId, string> orientedEdgeIds,
        Dictionary<EdgeId, string> lineIds,
        Dictionary<EdgeId, string> circleIds,
        Dictionary<EdgeId, string> bsplineIds,
        Dictionary<EdgeId, string> ellipseIds,
        Dictionary<EdgeId, string> hyperbolaIds,
        Dictionary<SurfaceGeometryId, string> surfaceIds,
        Dictionary<FaceId, string> advancedFaceIds,
        string? pcurveContextId,
        List<KernelDiagnostic> orientationDiagnostics)
    {
        if (!model.TryGetShell(shellId, out var shell) || shell is null)
        {
            return null;
        }

        // Pcurves for an edge may reference both adjacent supports, including a face
        // visited later in shell order, so materialize every support first. Retain
        // the legacy lazy ordering when no pcurves exist so canonical exports stay
        // byte-for-byte stable.
        foreach (var face in pcurveContextId is null
                     ? []
                     : shell.FaceIds.OrderBy(id => id.Value).Select(model.GetFace))
        {
            if (!body.Bindings.TryGetFaceBinding(face.Id, out var binding)
                || !body.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var support) || support is null) return null;
            if (surfaceIds.ContainsKey(binding.SurfaceGeometryId)) continue;
            var built = BuildSurface(writer, support, face.Id);
            if (!built.IsSuccess) return null;
            surfaceIds[binding.SurfaceGeometryId] = built.Value;
        }

        var loopUses = shell.FaceIds.Select(model.GetFace).SelectMany(face => face.LoopIds).Select(model.GetLoop)
            .Where(loop => loop.Kind == LoopKind.Edge)
            .ToDictionary(loop => loop.Id, loop => (IReadOnlyList<(Coedge, bool)>)ResolveConnectedLoopUses(body, model, loop).Select(use => (use.Coedge, use.IsReversed)).ToArray());
        var reversedLoops = StepLoopOrientation.ReversedLoops(body, loopUses);
        var inverted = StepLoopOrientation.FacesAgainstTheirLoops(body, loopUses, reversedLoops).Where(shell.FaceIds.Contains).ToArray();
        if (inverted.Length > 0)
            orientationDiagnostics.Add(new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,
                $"step-export-face-normal-inverted: planar faces {string.Join(",", inverted.Select(f => f.Value))} declare an outward normal against the shell's loops; the builder bound them the wrong way round.",
                "Step242.Export.LoopOrientation"));

        var faceIds = new List<string>();
        foreach (var face in shell.FaceIds.OrderBy(id => id.Value).Select(model.GetFace))
        {
            if (!body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding))
            {
                return null;
            }

            if (!body.Geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface is null)
            {
                return null;
            }

            if (face.LoopIds.Count == 0 && !CanExportLooplessFace(body, face, surface))
            {
                return null;
            }

            if (!surfaceIds.TryGetValue(faceBinding.SurfaceGeometryId, out var surfaceEntityId))
            {
                var surfaceIdResult = BuildSurface(writer, surface, face.Id);
                if (!surfaceIdResult.IsSuccess) return null;
                surfaceEntityId = surfaceIdResult.Value;
                surfaceIds[faceBinding.SurfaceGeometryId] = surfaceEntityId;
            }

            var loopBoundIds = new List<string>();
            var boundaryDecision = StepFaceBoundaryExportPolicy.Decide(body, face);
            if (boundaryDecision is null) return null;
            foreach (var boundary in boundaryDecision.Boundaries)
            {
                var loopId = boundary.LoopId;
                var loop = model.GetLoop(loopId);
                if (loop.Kind == LoopKind.Vertex)
                {
                    if (loop.VertexLoopVertexId is not VertexId vertexId || !body.TryGetVertexPoint(vertexId, out var point))
                        return null;
                    var vertexPointId = EnsureVertex(writer, vertexId, point, vertexPoints, cartesianPointIds, vertexPointIds);
                    var vertexLoopId = writer.AddEntity("VERTEX_LOOP", Step242TextWriter.String(string.Empty), Step242TextWriter.Ref(vertexPointId));
                    var vertexBoundEntity = boundary.Role == FaceBoundaryRole.Outer ? "FACE_OUTER_BOUND" : "FACE_BOUND";
                    loopBoundIds.Add(writer.AddEntity(vertexBoundEntity, Step242TextWriter.String(string.Empty), Step242TextWriter.Ref(vertexLoopId), Step242TextWriter.BooleanLogical(true)));
                    continue;
                }
                var oriented = new List<string>();

                // Loop.CoedgeIds is the authoritative cyclic order. Sorting this list can
                // silently turn a coherent loop into a disconnected STEP EDGE_LOOP.
                var traversal = ResolveConnectedLoopUses(body, model, loop);
                if (reversedLoops.Contains(loop.Id)) traversal = traversal.Reverse().Select(use => use with { IsReversed = !use.IsReversed }).ToArray();
                foreach (var loopUse in traversal)
                {
                    var coedge = loopUse.Coedge;

                    if (!edgeCurveIds.TryGetValue(coedge.EdgeId, out var edgeCurveId))
                    {
                        var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, vertexPoints, cartesianPointIds, vertexPointIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, pcurveContextId);
                        if (!edgeResult.IsSuccess)
                        {
                            return null;
                        }

                        edgeCurveId = edgeResult.Value;
                        edgeCurveIds[coedge.EdgeId] = edgeCurveId;
                    }

                    var orientedEdgeId = writer.AddEntity(
                        "ORIENTED_EDGE",
                        "$",
                        "$",
                        "$",
                        Step242TextWriter.Ref(edgeCurveId),
                        Step242TextWriter.BooleanLogical(!loopUse.IsReversed));

                    orientedEdgeIds[coedge.Id] = orientedEdgeId;
                    oriented.Add(orientedEdgeId);
                }

                var edgeLoopId = writer.AddEntity("EDGE_LOOP", "$", Step242TextWriter.List(oriented.ToArray()));
                var boundEntity = boundary.Role == FaceBoundaryRole.Outer ? "FACE_OUTER_BOUND" : "FACE_BOUND";
                var boundId = writer.AddEntity(boundEntity, Step242TextWriter.String(string.Empty), Step242TextWriter.Ref(edgeLoopId), Step242TextWriter.BooleanLogical(true));
                loopBoundIds.Add(boundId);
            }

            var advancedFaceId = writer.AddEntity(
                "ADVANCED_FACE",
                Step242TextWriter.String(string.Empty),
                Step242TextWriter.List(loopBoundIds.ToArray()),
                Step242TextWriter.Ref(surfaceEntityId),
                Step242TextWriter.BooleanLogical(faceBinding.Orientation.IsAlignedWithSurface));

            advancedFaceIds[face.Id] = advancedFaceId;
            faceIds.Add(advancedFaceId);
        }

        return writer.AddEntity("CLOSED_SHELL", "$", Step242TextWriter.List(faceIds.ToArray()));
    }

    private static IReadOnlyList<StepLoopUse> ResolveConnectedLoopUses(BrepBody body, TopologyModel model, Loop loop)
    {
        var authored = loop.CoedgeIds
            .Select(model.GetCoedge)
            .Select(coedge => new StepLoopUse(coedge, coedge.IsReversed))
            .ToArray();
        if (IsConnectedCycle(body, model, authored))
        {
            return authored;
        }

        // Some valid analytic constructions intentionally use distinct seam vertices
        // at the same point. A malformed authored ordering must never be emitted as a
        // disconnected STEP EDGE_LOOP, so reconnect it by geometric endpoint identity.
        // Keep the repair bounded: unusually large malformed loops are rejected by the
        // normal export preflight instead of spending factorial time searching a cycle.
        if (authored.Length > 16)
        {
            return authored;
        }

        for (var startIndex = 0; startIndex < authored.Length; startIndex++)
        {
            foreach (var startReversed in OrderedDirections(authored[startIndex]))
            {
                var candidate = new List<StepLoopUse>(authored.Length)
                {
                    authored[startIndex] with { IsReversed = startReversed }
                };
                var used = new bool[authored.Length];
                used[startIndex] = true;
                if (TryBuildConnectedCycle(body, model, authored, used, candidate))
                {
                    return candidate;
                }
            }
        }

        // Keep the exact authored sequence when no geometrically closed traversal
        // exists. Export preflight will then reject the body rather than disguising it.
        return authored;
    }

    private static bool TryBuildConnectedCycle(
        BrepBody body,
        TopologyModel model,
        IReadOnlyList<StepLoopUse> authored,
        bool[] used,
        List<StepLoopUse> candidate)
    {
        if (candidate.Count == authored.Count)
        {
            return VerticesCoincide(body, EndVertex(model, candidate[^1]), StartVertex(model, candidate[0]));
        }

        var requiredStart = EndVertex(model, candidate[^1]);
        for (var index = 0; index < authored.Count; index++)
        {
            if (used[index])
            {
                continue;
            }

            foreach (var reversed in OrderedDirections(authored[index]))
            {
                var next = authored[index] with { IsReversed = reversed };
                if (!VerticesCoincide(body, requiredStart, StartVertex(model, next)))
                {
                    continue;
                }

                used[index] = true;
                candidate.Add(next);
                if (TryBuildConnectedCycle(body, model, authored, used, candidate))
                {
                    return true;
                }

                candidate.RemoveAt(candidate.Count - 1);
                used[index] = false;
            }
        }

        return false;
    }

    private static IEnumerable<bool> OrderedDirections(StepLoopUse use)
    {
        yield return use.IsReversed;
        yield return !use.IsReversed;
    }

    private static bool IsConnectedCycle(BrepBody body, TopologyModel model, IReadOnlyList<StepLoopUse> uses)
    {
        for (var index = 0; index < uses.Count; index++)
        {
            if (!VerticesCoincide(body, EndVertex(model, uses[index]), StartVertex(model, uses[(index + 1) % uses.Count])))
            {
                return false;
            }
        }

        return true;
    }

    private static VertexId StartVertex(TopologyModel model, StepLoopUse use)
    {
        var edge = model.GetEdge(use.Coedge.EdgeId);
        return use.IsReversed ? edge.EndVertexId : edge.StartVertexId;
    }

    private static VertexId EndVertex(TopologyModel model, StepLoopUse use)
    {
        var edge = model.GetEdge(use.Coedge.EdgeId);
        return use.IsReversed ? edge.StartVertexId : edge.EndVertexId;
    }

    private static bool VerticesCoincide(BrepBody body, VertexId left, VertexId right)
    {
        if (left == right)
        {
            return true;
        }

        return body.TryGetVertexPoint(left, out var a)
            && body.TryGetVertexPoint(right, out var b)
            && (a - b).Length <= 1e-9d;
    }

    private sealed record StepLoopUse(Coedge Coedge, bool IsReversed);

    private static void EmitSemanticPmi(
        Step242TextWriter writer,
        string shapeId,
        string shapeRepresentationId,
        string repContextId,
        string lengthUnitId,
        IReadOnlyDictionary<FaceId, string> advancedFaceIds,
        IReadOnlyList<Step242SemanticPmi>? semanticPmi, IReadOnlyDictionary<string, string>? importedDatums = null)
    {
        if (semanticPmi is null || semanticPmi.Count == 0) return;

        var datumEntities = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        foreach (var imported in importedDatums ?? new Dictionary<string, string>()) datumEntities.Add(imported.Key, imported.Value);
        var datumAspects = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        foreach (var datum in semanticPmi.OfType<Step242SemanticPmiDatum>())
        {
            datumEntities[datum.Label] = EmitDatumSemanticPmi(writer, shapeId, datum, out var featureAspect);
            datumAspects[datum.Label] = featureAspect;
        }

        foreach (var item in semanticPmi)
        {
            string? boundAspect = item is Step242SemanticPmiDatum d ? datumAspects[d.Label] : null;
            switch (item)
            {
                case Step242SemanticPmiDatum:
                    break;
                case Step242SemanticPmiHole hole:
                    boundAspect = EmitHoleSemanticPmi(writer, shapeId, repContextId, lengthUnitId, hole);
                    break;
                case Step242SemanticPmiDimension dimension:
                    if (dimension.LocationFaces is { } ends)
                    {
                        // Each end of a location is its own shape aspect bound to its faces.
                        string End(IReadOnlyList<int> faces, string role)
                        {
                            var end = writer.AddEntity("SHAPE_ASPECT", Step242TextWriter.String($"firmament-location-{role}:{dimension.Name}"),
                                Step242TextWriter.String($"location {role} {dimension.Name}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(true));
                            EmitGeometricItemAssociations(writer, shapeId, shapeRepresentationId, advancedFaceIds, dimension with { GeometricFaceIds = faces }, end);
                            return end;
                        }
                        dimension = dimension with { Location = (End(ends.From, "origin"), End(ends.To, "target")) };
                    }
                    boundAspect = EmitDimensionSemanticPmi(writer, shapeId, repContextId, lengthUnitId, dimension);
                    break;
                case Step242SemanticPmiNote note:
                    EmitNoteSemanticPmi(writer.AddEntity, Step242TextWriter.Ref(shapeId), note);
                    break;
                case Step242SemanticPmiGeometricTolerance tolerance:
                    boundAspect = EmitGeometricToleranceSemanticPmi(writer, shapeId, lengthUnitId, tolerance, datumEntities);
                    break;
            }
            EmitGeometricItemAssociations(writer, shapeId, shapeRepresentationId, advancedFaceIds, item, boundAspect);
        }
    }

    private static void EmitGeometricItemAssociations(
        Step242TextWriter writer,
        string shapeId,
        string shapeRepresentationId,
        IReadOnlyDictionary<FaceId, string> advancedFaceIds,
        Step242SemanticPmi item, string? boundAspect = null)
    {
        if (item.GeometricFaceIds.Count == 0) return;
        var target = item switch
        {
            Step242SemanticPmiDatum datum => datum.Target,
            Step242SemanticPmiNote note => note.Target,
            _ => item.FeatureId
        };
        var aspectId = boundAspect ?? writer.AddEntity(
            "SHAPE_ASPECT",
            Step242TextWriter.String($"firmament-geometric-target:{target}"),
            Step242TextWriter.String($"semantic geometry binding target={target}"),
            Step242TextWriter.Ref(shapeId),
            Step242TextWriter.BooleanLogical(true));
        foreach (var faceId in item.GeometricFaceIds.Distinct().OrderBy(id => id))
        {
            if (!advancedFaceIds.TryGetValue(new FaceId(faceId), out var advancedFaceId)) continue;
            writer.AddEntity(
                "GEOMETRIC_ITEM_SPECIFIC_USAGE",
                Step242TextWriter.String("firmament semantic target"),
                Step242TextWriter.String($"target={target}"),
                Step242TextWriter.Ref(aspectId),
                Step242TextWriter.Ref(shapeRepresentationId),
                Step242TextWriter.Ref(advancedFaceId));
        }
    }

    private static string EmitHoleSemanticPmi(
        Step242TextWriter writer,
        string shapeId,
        string repContextId,
        string lengthUnitId,
        Step242SemanticPmiHole hole)
    {
        var featureShapeAspectId = writer.AddEntity(
            "SHAPE_ASPECT",
            Step242TextWriter.String($"firmament-feature:{hole.FeatureId}"),
            Step242TextWriter.String($"semantic cylindrical sheet feature target={hole.FeatureId}"),
            Step242TextWriter.Ref(shapeId),
            Step242TextWriter.BooleanLogical(true));
        var propertyDefinitionId = writer.AddEntity(
            "PROPERTY_DEFINITION",
            Step242TextWriter.String($"diameter:{hole.FeatureId}"),
            Step242TextWriter.String(hole.Name is null ? "semantic PMI diameter" : $"semantic PMI diameter name={hole.Name}"),
            Step242TextWriter.Ref(featureShapeAspectId));
        var measureItemId = writer.AddEntity(
            "MEASURE_REPRESENTATION_ITEM",
            Step242TextWriter.String("diameter"),
            Step242TextWriter.PmiNumber(hole.Diameter),
            Step242TextWriter.Ref(lengthUnitId));
        var representationId = writer.AddEntity(
            "SHAPE_DIMENSION_REPRESENTATION",
            Step242TextWriter.String($"diameter:{hole.FeatureId}"),
            Step242TextWriter.List(measureItemId),
            Step242TextWriter.Ref(repContextId));
        writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyDefinitionId), Step242TextWriter.Ref(representationId));
        EmitBilateralToleranceRepresentation(writer, featureShapeAspectId, repContextId, lengthUnitId, $"diameter_tolerance:{hole.FeatureId}", hole.TolerancePlus, hole.ToleranceMinus);
        EmitStandardSize(writer, featureShapeAspectId, repContextId, lengthUnitId, "diameter", hole.Diameter, hole.TolerancePlus, hole.ToleranceMinus);
        EmitQuantitySemanticPmi(writer, featureShapeAspectId, hole.FeatureId, hole.Quantity);

        if (hole.Depth.HasValue)
        {
            var depthItemId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("depth"), Step242TextWriter.PmiNumber(hole.Depth.Value), Step242TextWriter.Ref(lengthUnitId));
            var depthRepId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String($"depth:{hole.FeatureId}"), Step242TextWriter.List(depthItemId), Step242TextWriter.Ref(repContextId));
            var depthPropertyDefinitionId = writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"depth:{hole.FeatureId}"), Step242TextWriter.String("semantic PMI depth"), Step242TextWriter.Ref(featureShapeAspectId));
            writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(depthPropertyDefinitionId), Step242TextWriter.Ref(depthRepId));
        }
        return featureShapeAspectId;
    }

    private static string EmitDatumSemanticPmi(Step242TextWriter writer, string shapeId, Step242SemanticPmiDatum datum, out string featureAspect)
    {
        // Retain the established generic SHAPE_ASPECT contract for existing AP242
        // consumers while also emitting the formal AP242 datum entities below.
        var semanticAspectId = writer.AddEntity(
            "SHAPE_ASPECT",
            Step242TextWriter.String($"firmament-datum:{datum.Label}"),
            Step242TextWriter.String($"semantic datum {datum.DatumKind} target={datum.Target}"),
            Step242TextWriter.Ref(shapeId),
            Step242TextWriter.BooleanLogical(true));
        var featureId = writer.AddEntity(
            "DATUM_FEATURE",
            Step242TextWriter.String($"firmament-datum:{datum.Label}"),
            Step242TextWriter.String($"semantic datum {datum.DatumKind} target={datum.Target}"),
            Step242TextWriter.Ref(shapeId),
            Step242TextWriter.BooleanLogical(true));
        featureAspect = featureId;
        var datumId = writer.AddEntity(
            "DATUM",
            Step242TextWriter.String($"firmament-datum-reference:{datum.Label}"),
            "$",
            Step242TextWriter.Ref(shapeId),
            Step242TextWriter.BooleanLogical(false),
            Step242TextWriter.String(datum.Label));
        writer.AddEntity("SHAPE_ASPECT_RELATIONSHIP", Step242TextWriter.String("firmament formal datum feature"), Step242TextWriter.String($"target={datum.Target}"), Step242TextWriter.Ref(semanticAspectId), Step242TextWriter.Ref(featureId));
        writer.AddEntity("SHAPE_ASPECT_RELATIONSHIP", Step242TextWriter.String("firmament datum feature association"), Step242TextWriter.String($"target={datum.Target}"), Step242TextWriter.Ref(featureId), Step242TextWriter.Ref(datumId));
        writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"datum:{datum.Label}:{datum.FeatureId}"), Step242TextWriter.String($"semantic datum {datum.DatumKind}"), Step242TextWriter.Ref(semanticAspectId));
        return datumId;
    }

    private static string EmitDimensionSemanticPmi(
        Step242TextWriter writer,
        string shapeId,
        string repContextId,
        string lengthUnitId,
        Step242SemanticPmiDimension dimension)
    {
        var aspectId = writer.AddEntity("SHAPE_ASPECT", Step242TextWriter.String($"firmament-feature:{dimension.FeatureId}"), Step242TextWriter.String($"semantic {dimension.DimensionKind} dimension target={dimension.FeatureId}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(true));
        var propertyId = writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"dimension:{dimension.Name}:{dimension.FeatureId}"), Step242TextWriter.String($"semantic PMI {dimension.DimensionKind} dimension"), Step242TextWriter.Ref(aspectId));
        var valueId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String(dimension.DimensionKind.ToLowerInvariant()), Step242TextWriter.PmiNumber(dimension.Value), Step242TextWriter.Ref(lengthUnitId));
        var representationId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String($"dimension:{dimension.Name}"), Step242TextWriter.List(valueId), Step242TextWriter.Ref(repContextId));
        writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyId), Step242TextWriter.Ref(representationId));
        EmitBilateralToleranceRepresentation(writer, aspectId, repContextId, lengthUnitId, $"dimension_tolerance:{dimension.Name}", dimension.TolerancePlus, dimension.ToleranceMinus);
        if (dimension.StandardKind is { } standard && standard != "unresolved")
            EmitStandardSize(writer, aspectId, repContextId, lengthUnitId, standard, dimension.Value, dimension.TolerancePlus, dimension.ToleranceMinus, dimension.Location);
        EmitQuantitySemanticPmi(writer, aspectId, dimension.FeatureId, dimension.Quantity);
        return aspectId;
    }

    /// <summary>
    /// The same size in the standard AP242 form other CAD and inspection software reads
    /// (CAx-IF semantic PMI): DIMENSIONAL_SIZE on the feature's shape aspect, its nominal
    /// value, and a PLUS_MINUS_TOLERANCE with signed limits. Written alongside the
    /// established Aetheris property records, which existing consumers read.
    /// </summary>
    private static void EmitStandardSize(Step242TextWriter writer, string aspectId, string repContextId, string lengthUnitId,
        string kind, double nominal, double? tolerancePlus, double? toleranceMinus, (string From, string To)? location = null)
    {
        string Measure(double value, string role) => writer.AddRawEntity(
            $"(LENGTH_MEASURE_WITH_UNIT()MEASURE_REPRESENTATION_ITEM()MEASURE_WITH_UNIT(LENGTH_MEASURE({Step242TextWriter.PmiNumber(value)}),{lengthUnitId})REPRESENTATION_ITEM({Step242TextWriter.String(role)}))");
        var dimension = location is { } ends
            ? writer.AddEntity("DIMENSIONAL_LOCATION", Step242TextWriter.String(kind), Step242TextWriter.String($"firmament-native:{aspectId}"), ends.From, ends.To)
            : writer.AddEntity("DIMENSIONAL_SIZE", aspectId, Step242TextWriter.String(kind));
        var value = Measure(nominal, "nominal value");
        var representation = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String(""), Step242TextWriter.List(value), repContextId);
        writer.AddEntity("DIMENSIONAL_CHARACTERISTIC_REPRESENTATION", dimension, representation);
        if (!tolerancePlus.HasValue && !toleranceMinus.HasValue) return;
        var plus = tolerancePlus ?? toleranceMinus!.Value;
        var minus = toleranceMinus ?? tolerancePlus!.Value;
        var limits = writer.AddEntity("TOLERANCE_VALUE", Measure(-minus, "lower limit"), Measure(plus, "upper limit"));
        writer.AddEntity("PLUS_MINUS_TOLERANCE", limits, dimension);
    }

    private static void EmitBilateralToleranceRepresentation(
        Step242TextWriter writer,
        string aspectId,
        string repContextId,
        string lengthUnitId,
        string stableName,
        double? tolerancePlus,
        double? toleranceMinus)
    {
        if (!tolerancePlus.HasValue && !toleranceMinus.HasValue) return;
        var plus = tolerancePlus ?? toleranceMinus!.Value;
        var minus = toleranceMinus ?? tolerancePlus!.Value;
        var plusId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("tolerance_plus"), Step242TextWriter.PmiNumber(plus), Step242TextWriter.Ref(lengthUnitId));
        var minusId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("tolerance_minus"), Step242TextWriter.PmiNumber(minus), Step242TextWriter.Ref(lengthUnitId));
        var representationId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String(stableName), Step242TextWriter.List(plusId, minusId), Step242TextWriter.Ref(repContextId));
        var propertyId = writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String(stableName), Step242TextWriter.String("semantic PMI bilateral tolerance"), Step242TextWriter.Ref(aspectId));
        writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyId), Step242TextWriter.Ref(representationId));
    }

    private static void EmitQuantitySemanticPmi(Step242TextWriter writer, string aspectId, string target, int? quantity)
    {
        if (!quantity.HasValue) return;
        writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"quantity:{target}"), Step242TextWriter.String(quantity.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)), Step242TextWriter.Ref(aspectId));
    }

    private static string EmitGeometricToleranceSemanticPmi(
        Step242TextWriter writer,
        string shapeId,
        string lengthUnitId,
        Step242SemanticPmiGeometricTolerance tolerance,
        IReadOnlyDictionary<string, string> datumEntities)
    {
        var kind = Step242GeometricToleranceKinds.Find(tolerance.ToleranceKind)!; // Validated before serialization.
        var targetAspectId = writer.AddEntity("COMPOSITE_SHAPE_ASPECT", Step242TextWriter.String($"firmament-target:{tolerance.FeatureId}"), Step242TextWriter.String($"semantic target quantity={tolerance.Quantity?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unspecified"}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(true));
        var magnitudeId = writer.AddRawEntity($"(LENGTH_MEASURE_WITH_UNIT()MEASURE_REPRESENTATION_ITEM()MEASURE_WITH_UNIT(LENGTH_MEASURE({Step242TextWriter.PmiNumber(tolerance.Value)}),{lengthUnitId})REPRESENTATION_ITEM({Step242TextWriter.String(kind.Name + " tolerance")}))");
        var compartments = new List<string>();
        foreach (var label in tolerance.DatumReferences)
        {
            if (!datumEntities.TryGetValue(label, out var datumId)) continue;
            compartments.Add(writer.AddEntity("DATUM_REFERENCE_COMPARTMENT", Step242TextWriter.String(""), "$", Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(false), Step242TextWriter.Ref(datumId), "$"));
        }
        var datumClause = "";
        if (compartments.Count > 0)
        {
            var datumSystemId = writer.AddEntity("DATUM_SYSTEM", Step242TextWriter.String($"firmament-datum-system:{tolerance.Name}"), "$", Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(false), Step242TextWriter.List(compartments.ToArray()));
            datumClause = $"GEOMETRIC_TOLERANCE_WITH_DATUM_REFERENCE(({datumSystemId}))";
        }
        var modifiers = tolerance.Modifiers.Count == 0 ? "" : "GEOMETRIC_TOLERANCE_WITH_MODIFIERS((" + string.Join(",", tolerance.Modifiers.Select(m => Step242TextWriter.Enum(Step242GeometricToleranceKinds.Modifiers[m]))) + "))";
        var components = new[] { $"GEOMETRIC_TOLERANCE({Step242TextWriter.String(tolerance.Name)},{Step242TextWriter.String($"semantic {kind.Name} target={tolerance.FeatureId}")},{magnitudeId},{targetAspectId})", datumClause, modifiers, kind.Entity + "()" }.Where(s => s.Length > 0).Order(StringComparer.Ordinal);
        var controlId = writer.AddRawEntity("(" + string.Concat(components) + ")");
        if (tolerance.ZoneForm is { } zone)
        {
            var formId = writer.AddEntity("TOLERANCE_ZONE_FORM", Step242TextWriter.String(Step242GeometricToleranceKinds.ZoneForms[zone]));
            writer.AddEntity("TOLERANCE_ZONE", "''", "$", shapeId, ".F.", Step242TextWriter.List(controlId), formId);
        }
        EmitQuantitySemanticPmi(writer, targetAspectId, tolerance.FeatureId, tolerance.Quantity);
        return targetAspectId;
    }

    internal static void EmitNoteSemanticPmi(Func<string, string[], string> addEntity, string shapeReference, Step242SemanticPmiNote note)
    {
        var aspectId = addEntity("SHAPE_ASPECT", [Step242TextWriter.String($"firmament-note:{note.FeatureId}"), Step242TextWriter.String($"semantic note target={note.Target}"), shapeReference, Step242TextWriter.BooleanLogical(false)]);
        addEntity("PROPERTY_DEFINITION", [Step242TextWriter.String($"note:{note.FeatureId}"), Step242TextWriter.String(note.Text), Step242TextWriter.Ref(aspectId)]);
    }

    private static string BuildPlane(Step242TextWriter writer, PlaneSurface plane)
    {
        var originId = writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(plane.Origin.X), Step242TextWriter.Number(plane.Origin.Y), Step242TextWriter.Number(plane.Origin.Z)));
        var normal = plane.Normal.ToVector();
        var uAxis = plane.UAxis.ToVector();
        var normalId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(normal.X), Step242TextWriter.Number(normal.Y), Step242TextWriter.Number(normal.Z)));
        var refDirId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(uAxis.X), Step242TextWriter.Number(uAxis.Y), Step242TextWriter.Number(uAxis.Z)));
        var axisPlacementId = writer.AddEntity("AXIS2_PLACEMENT_3D", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(normalId), Step242TextWriter.Ref(refDirId));
        return writer.AddEntity("PLANE", "$", Step242TextWriter.Ref(axisPlacementId));
    }


    private static string BuildCylinder(Step242TextWriter writer, CylinderSurface cylinder)
    {
        var axisPlacementId = BuildAxisPlacement(writer, cylinder.Origin, cylinder.Axis, cylinder.XAxis);
        return writer.AddEntity("CYLINDRICAL_SURFACE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(cylinder.Radius));
    }

    private static string BuildCone(Step242TextWriter writer, ConeSurface cone)
    {
        var axisPlacementId = BuildAxisPlacement(writer, cone.PlacementOrigin, cone.Axis, cone.ReferenceAxis);
        return writer.AddEntity("CONICAL_SURFACE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(cone.PlacementRadius), Step242TextWriter.Number(cone.SemiAngleRadians));
    }

    private static string BuildSphere(Step242TextWriter writer, SphereSurface sphere)
    {
        var axisPlacementId = BuildAxisPlacement(writer, sphere.Center, sphere.Axis, sphere.XAxis);
        return writer.AddEntity("SPHERICAL_SURFACE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(sphere.Radius));
    }

    private static string BuildTorus(Step242TextWriter writer, TorusSurface torus)
    {
        var axisPlacementId = BuildAxisPlacement(writer, torus.Center, torus.Axis, torus.XAxis);
        return writer.AddEntity("TOROIDAL_SURFACE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(torus.MajorRadius), Step242TextWriter.Number(torus.MinorRadius));
    }

    private static KernelResult<string> BuildLinearExtrusionSurface(Step242TextWriter writer, LinearExtrusionSurface surface)
    {
        var directrixIdResult = BuildSurfaceCurve(writer, surface.Directrix, "Surface.Directrix.LinearExtrusion");
        if (!directrixIdResult.IsSuccess)
        {
            return directrixIdResult;
        }

        var extrusionAxisResult = BuildVector(writer, surface.ExtrusionVector, "Surface.ExtrusionVector");
        if (!extrusionAxisResult.IsSuccess)
        {
            return extrusionAxisResult;
        }

        return KernelResult<string>.Success(writer.AddEntity(
            "SURFACE_OF_LINEAR_EXTRUSION",
            "$",
            Step242TextWriter.Ref(directrixIdResult.Value),
            Step242TextWriter.Ref(extrusionAxisResult.Value)));
    }

    private static KernelResult<string> BuildSurfaceOfRevolutionSurface(Step242TextWriter writer, SurfaceOfRevolutionSurface surface)
    {
        var directrixIdResult = BuildSurfaceCurve(writer, surface.Directrix, "Surface.Directrix.SurfaceOfRevolution");
        if (!directrixIdResult.IsSuccess)
        {
            return directrixIdResult;
        }

        var axisPlacementId = BuildAxis1Placement(writer, surface.AxisOrigin, surface.AxisDirection);
        return KernelResult<string>.Success(writer.AddEntity(
            "SURFACE_OF_REVOLUTION",
            "$",
            Step242TextWriter.Ref(directrixIdResult.Value),
            Step242TextWriter.Ref(axisPlacementId)));
    }

    private static string BuildBSplineSurfaceWithKnots(Step242TextWriter writer, BSplineSurfaceWithKnots surface)
    {
        var controlPointRows = surface.ControlPoints
            .Select(row =>
            {
                var rowPointIds = row
                    .Select(point => writer.AddEntity("CARTESIAN_POINT", "$", PointList(point)))
                    .Select(Step242TextWriter.Ref)
                    .ToArray();
                return Step242TextWriter.List(rowPointIds);
            })
            .ToArray();

        var multiplicitiesU = surface.KnotMultiplicitiesU
            .Select(multiplicity => multiplicity.ToString(System.Globalization.CultureInfo.InvariantCulture))
            .ToArray();
        var multiplicitiesV = surface.KnotMultiplicitiesV
            .Select(multiplicity => multiplicity.ToString(System.Globalization.CultureInfo.InvariantCulture))
            .ToArray();
        var knotValuesU = surface.KnotValuesU.Select(Step242TextWriter.Number).ToArray();
        var knotValuesV = surface.KnotValuesV.Select(Step242TextWriter.Number).ToArray();

        if (surface.Weights is { } weights)
        {
            // Rational surfaces are a complex entity; the weights must survive the round trip or the face changes shape.
            var degreeU = surface.DegreeU.ToString(System.Globalization.CultureInfo.InvariantCulture);
            var degreeV = surface.DegreeV.ToString(System.Globalization.CultureInfo.InvariantCulture);
            var weightRows = weights.Select(row => Step242TextWriter.List(row.Select(Step242TextWriter.Number).ToArray())).ToArray();
            var pointNet = Step242TextWriter.List(controlPointRows);
            var flags = $"{Step242TextWriter.Enum(surface.SurfaceForm)},{Step242TextWriter.BooleanLogical(surface.UClosed)},{Step242TextWriter.BooleanLogical(surface.VClosed)},{Step242TextWriter.BooleanLogical(surface.SelfIntersect)}";
            return writer.AddRawEntity(
                "(BOUNDED_SURFACE()"
                + $"B_SPLINE_SURFACE({degreeU},{degreeV},{pointNet},{flags})"
                + $"B_SPLINE_SURFACE_WITH_KNOTS({Step242TextWriter.List(multiplicitiesU)},{Step242TextWriter.List(multiplicitiesV)},{Step242TextWriter.List(knotValuesU)},{Step242TextWriter.List(knotValuesV)},{Step242TextWriter.Enum(surface.KnotSpec)})"
                + "GEOMETRIC_REPRESENTATION_ITEM()"
                + $"RATIONAL_B_SPLINE_SURFACE({Step242TextWriter.List(weightRows)})"
                + "REPRESENTATION_ITEM('')SURFACE())");
        }

        return writer.AddEntity(
            "B_SPLINE_SURFACE_WITH_KNOTS",
            "$",
            surface.DegreeU.ToString(System.Globalization.CultureInfo.InvariantCulture),
            surface.DegreeV.ToString(System.Globalization.CultureInfo.InvariantCulture),
            Step242TextWriter.List(controlPointRows),
            Step242TextWriter.Enum(surface.SurfaceForm),
            Step242TextWriter.BooleanLogical(surface.UClosed),
            Step242TextWriter.BooleanLogical(surface.VClosed),
            Step242TextWriter.BooleanLogical(surface.SelfIntersect),
            Step242TextWriter.List(multiplicitiesU),
            Step242TextWriter.List(multiplicitiesV),
            Step242TextWriter.List(knotValuesU),
            Step242TextWriter.List(knotValuesV),
            Step242TextWriter.Enum(surface.KnotSpec));
    }

    private static KernelResult<string> BuildSurface(Step242TextWriter writer, SurfaceGeometry surface, FaceId faceId)
    {
        return surface.Kind switch
        {
            SurfaceGeometryKind.Plane when surface.Plane is PlaneSurface plane => KernelResult<string>.Success(BuildPlane(writer, plane)),
            SurfaceGeometryKind.Cylinder when surface.Cylinder is CylinderSurface cylinder => KernelResult<string>.Success(BuildCylinder(writer, cylinder)),
            SurfaceGeometryKind.Cone when surface.Cone is ConeSurface cone => KernelResult<string>.Success(BuildCone(writer, cone)),
            SurfaceGeometryKind.Sphere when surface.Sphere is SphereSurface sphere => KernelResult<string>.Success(BuildSphere(writer, sphere)),
            SurfaceGeometryKind.Torus when surface.Torus is TorusSurface torus => KernelResult<string>.Success(BuildTorus(writer, torus)),
            SurfaceGeometryKind.LinearExtrusion when surface.LinearExtrusion is LinearExtrusionSurface linearExtrusion => BuildLinearExtrusionSurface(writer, linearExtrusion),
            SurfaceGeometryKind.SurfaceOfRevolution when surface.SurfaceOfRevolution is SurfaceOfRevolutionSurface surfaceOfRevolution => BuildSurfaceOfRevolutionSurface(writer, surfaceOfRevolution),
            SurfaceGeometryKind.Ellipsoid when surface.Ellipsoid is { } ellipsoid => KernelResult<string>.Success(BuildBSplineSurfaceWithKnots(writer, ellipsoid.ToStepPatch())),
            SurfaceGeometryKind.BSplineSurfaceWithKnots when surface.BSplineSurfaceWithKnots is BSplineSurfaceWithKnots bSplineSurface => KernelResult<string>.Success(BuildBSplineSurfaceWithKnots(writer, bSplineSurface)),
            _ => Failure($"Unsupported surface kind '{surface.Kind}'.", $"Face:{faceId.Value}")
        };
    }

    private static bool CanExportLooplessFace(BrepBody _, Face face, SurfaceGeometry surface) =>
        surface.Kind == SurfaceGeometryKind.Sphere
        && face.LoopIds.Count == 0;

    private static string BuildAxisPlacement(Step242TextWriter writer, Point3D origin, Direction3D axis, Direction3D referenceAxis)
    {
        var originId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(origin));
        var axisVector = axis.ToVector();
        var axisId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(axisVector.X), Step242TextWriter.Number(axisVector.Y), Step242TextWriter.Number(axisVector.Z)));
        var referenceVector = referenceAxis.ToVector();
        var referenceId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(referenceVector.X), Step242TextWriter.Number(referenceVector.Y), Step242TextWriter.Number(referenceVector.Z)));
        return writer.AddEntity("AXIS2_PLACEMENT_3D", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(axisId), Step242TextWriter.Ref(referenceId));
    }

    private static string BuildAxis1Placement(Step242TextWriter writer, Point3D origin, Direction3D axis)
    {
        var originId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(origin));
        var axisVector = axis.ToVector();
        var axisId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(
            Step242TextWriter.Number(axisVector.X),
            Step242TextWriter.Number(axisVector.Y),
            Step242TextWriter.Number(axisVector.Z)));
        return writer.AddEntity("AXIS1_PLACEMENT", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(axisId));
    }

    private static KernelResult<string> BuildVector(Step242TextWriter writer, Vector3D vector, string source)
    {
        if (!vector.TryNormalize(out var direction))
        {
            return Failure("Vector must be non-zero.", source);
        }

        var magnitude = vector.Length;
        if (!double.IsFinite(magnitude) || magnitude <= 0d)
        {
            return Failure("Vector magnitude must be finite and greater than zero.", source);
        }

        var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(
            Step242TextWriter.Number(direction.X),
            Step242TextWriter.Number(direction.Y),
            Step242TextWriter.Number(direction.Z)));
        return KernelResult<string>.Success(writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(magnitude)));
    }

    private static KernelResult<string> BuildSurfaceCurve(Step242TextWriter writer, CurveGeometry curve, string source)
    {
        if (curve.Kind == CurveGeometryKind.Line3 && curve.Line3 is Line3Curve line)
        {
            var originId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(line.Origin));
            var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(
                Step242TextWriter.Number(line.Direction.X),
                Step242TextWriter.Number(line.Direction.Y),
                Step242TextWriter.Number(line.Direction.Z)));
            var vectorId = writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(1d));
            return KernelResult<string>.Success(writer.AddEntity("LINE", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(vectorId)));
        }

        if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is Circle3Curve circle)
        {
            var axisPlacementId = BuildAxisPlacement(writer, circle.Center, circle.Normal, circle.XAxis);
            return KernelResult<string>.Success(writer.AddEntity("CIRCLE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(circle.Radius)));
        }

        if (curve.Kind == CurveGeometryKind.Ellipse3 && curve.Ellipse3 is Ellipse3Curve ellipse)
        {
            var axisPlacementId = BuildAxisPlacement(writer, ellipse.Center, ellipse.Normal, ellipse.XAxis);
            return KernelResult<string>.Success(writer.AddEntity("ELLIPSE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(ellipse.MajorRadius), Step242TextWriter.Number(ellipse.MinorRadius)));
        }

        if (curve.Kind == CurveGeometryKind.Hyperbola3 && curve.Hyperbola3 is Hyperbola3Curve hyperbola)
        {
            var exportedAxisU = hyperbola.Branch == HyperbolaBranch.PositiveAxisU ? hyperbola.AxisU : Direction3D.Create(-hyperbola.AxisU.ToVector());
            var exportedNormal = hyperbola.Branch == HyperbolaBranch.PositiveAxisU ? hyperbola.PlaneNormal : Direction3D.Create(-hyperbola.PlaneNormal.ToVector());
            var axisPlacementId = BuildAxisPlacement(writer, hyperbola.Center, exportedNormal, exportedAxisU);
            return KernelResult<string>.Success(writer.AddEntity("HYPERBOLA", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(hyperbola.SemiAxisA), Step242TextWriter.Number(hyperbola.SemiAxisB)));
        }

        if (curve.Kind == CurveGeometryKind.BSpline3 && curve.BSpline3 is BSpline3Curve spline)
        {
            var controlPointIds = spline.ControlPoints
                .Select(point => writer.AddEntity("CARTESIAN_POINT", "$", PointList(point)))
                .Select(Step242TextWriter.Ref)
                .ToArray();
            return KernelResult<string>.Success(writer.AddEntity(
                "B_SPLINE_CURVE_WITH_KNOTS",
                "$",
                spline.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture),
                Step242TextWriter.List(controlPointIds),
                Step242TextWriter.Enum(spline.CurveForm),
                Step242TextWriter.BooleanLogical(spline.ClosedCurve),
                Step242TextWriter.BooleanLogical(spline.SelfIntersect),
                Step242TextWriter.List(spline.KnotMultiplicities.Select(value => value.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray()),
                Step242TextWriter.List(spline.KnotValues.Select(Step242TextWriter.Number).ToArray()),
                Step242TextWriter.Enum(spline.KnotSpec)));
        }

        return Failure($"Unsupported swept directrix curve kind '{curve.Kind}'.", source);
    }

    private static KernelResult<string> BuildEdgeCurve(
        BrepBody body,
        TopologyModel model,
        Step242TextWriter writer,
        EdgeId edgeId,
        IDictionary<VertexId, Point3D> vertexPoints,
        IDictionary<VertexId, string> cartesianPointIds,
        IDictionary<VertexId, string> vertexPointIds,
        IDictionary<EdgeId, string> lineIds,
        IDictionary<EdgeId, string> circleIds,
        IDictionary<EdgeId, string> bsplineIds,
        IDictionary<EdgeId, string> ellipseIds,
        IDictionary<EdgeId, string> hyperbolaIds,
        IReadOnlyDictionary<SurfaceGeometryId, string> surfaceIds,
        string? pcurveContextId)
    {
        var edge = model.GetEdge(edgeId);

        if (!body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding))
        {
            return Failure("Edge is missing curve binding.", $"Edge:{edgeId.Value}");
        }

        if (!body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null)
        {
            return Failure("Edge curve geometry was not found.", $"Curve:{edgeBinding.CurveGeometryId.Value}");
        }

        if (curve.Kind != CurveGeometryKind.Line3
            && curve.Kind != CurveGeometryKind.Circle3
            && curve.Kind != CurveGeometryKind.BSpline3
            && curve.Kind != CurveGeometryKind.Ellipse3
            && curve.Kind != CurveGeometryKind.Hyperbola3)
        {
            return Failure($"Unsupported curve kind '{curve.Kind}'.", $"Edge:{edgeId.Value}");
        }

        if (edgeBinding.TrimInterval is null)
        {
            return Failure("Edge must provide trim interval for vertex mapping.", $"Edge:{edgeId.Value}");
        }

        var startPointResult = ResolveVertexPoint(body, model, edge.StartVertexId, vertexPoints);
        if (!startPointResult.IsSuccess)
        {
            return KernelResult<string>.Failure(startPointResult.Diagnostics);
        }

        var endPointResult = ResolveVertexPoint(body, model, edge.EndVertexId, vertexPoints);
        if (!endPointResult.IsSuccess)
        {
            return KernelResult<string>.Failure(endPointResult.Diagnostics);
        }

        var startPoint = startPointResult.Value;
        var endPoint = endPointResult.Value;

        var startVertexId = EnsureVertex(writer, edge.StartVertexId, startPoint, vertexPoints, cartesianPointIds, vertexPointIds);
        var endVertexId = EnsureVertex(writer, edge.EndVertexId, endPoint, vertexPoints, cartesianPointIds, vertexPointIds);

        string geometryCurveId;
        // EDGE_CURVE.same_sense relates the curve that is actually written to the vertex order that is actually
        // written. Most kinds are emitted exactly as stored, so the stored flag still describes them; a line is not.
        var emittedSameSense = edgeBinding.OrientedEdgeSense;
        if (curve.Kind == CurveGeometryKind.Line3 && curve.Line3 is Line3Curve line)
        {
            if (!lineIds.TryGetValue(edgeId, out var lineId))
            {
                var edgeVector = endPoint - startPoint;
                if (edgeVector.LengthSquared <= 1e-24d || !edgeVector.TryNormalize(out var endpointDirection))
                {
                    return Failure("Edge endpoints resolve to a degenerate line direction.", $"Edge:{edgeId.Value}");
                }

                var direction = endpointDirection;
                var curveDirection = line.Direction.ToVector();
                if (curveDirection.TryNormalize(out var normalizedCurveDirection))
                {
                    var alignment = normalizedCurveDirection.Dot(endpointDirection);
                    if (alignment >= 0.999999999999d)
                    {
                        direction = normalizedCurveDirection;
                    }
                }

                var originId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(startPoint));
                var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(direction.X), Step242TextWriter.Number(direction.Y), Step242TextWriter.Number(direction.Z)));
                var vectorId = writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(1d));
                lineId = writer.AddEntity("LINE", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(vectorId));
                lineIds[edgeId] = lineId;
            }

            // The line above is rebuilt from the endpoints: it starts at the start vertex and runs towards the end
            // vertex, in both branches, because the stored direction is kept only when it already agrees. So the
            // emitted curve agrees with the vertex order by construction, whatever the stored flag said. Writing the
            // stored flag here told a reader that a curve running start-to-end actually ran end-to-start, and the
            // reader then walked those edges backwards - which is what made a re-imported loop's consecutive coedges
            // land an edge-length apart.
            emittedSameSense = true;
            geometryCurveId = lineId;
        }
        else if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is Circle3Curve circle)
        {
            if (!circleIds.TryGetValue(edgeId, out var circleId))
            {
                var axisPlacementId = BuildAxisPlacement(writer, circle.Center, circle.Normal, circle.XAxis);
                circleId = writer.AddEntity("CIRCLE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(circle.Radius));
                circleIds[edgeId] = circleId;
            }

            // ADVANCED_FACE requires an admitted basis curve, not TRIMMED_CURVE.
            // Edge vertices and same_sense bound the arc; face-local pcurves
            // retain periodic trim information without wrapping the 3D basis.
            geometryCurveId = circleId;
        }
        else if (curve.Kind == CurveGeometryKind.BSpline3 && curve.BSpline3 is BSpline3Curve spline)
        {
            if (!bsplineIds.TryGetValue(edgeId, out var bsplineId))
            {
                var controlPointIds = spline.ControlPoints
                    .Select(point => writer.AddEntity("CARTESIAN_POINT", "$", PointList(point)))
                    .Select(Step242TextWriter.Ref)
                    .ToArray();

                var multiplicities = spline.KnotMultiplicities.Select(multiplicity => multiplicity.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray();
                var knotValues = spline.KnotValues.Select(Step242TextWriter.Number).ToArray();

                bsplineId = writer.AddEntity(
                    "B_SPLINE_CURVE_WITH_KNOTS",
                    "$",
                    spline.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture),
                    Step242TextWriter.List(controlPointIds),
                    Step242TextWriter.Enum(spline.CurveForm),
                    Step242TextWriter.BooleanLogical(spline.ClosedCurve),
                    Step242TextWriter.BooleanLogical(spline.SelfIntersect),
                    Step242TextWriter.List(multiplicities),
                    Step242TextWriter.List(knotValues),
                    Step242TextWriter.Enum(spline.KnotSpec));

                bsplineIds[edgeId] = bsplineId;
            }

            var trim = edgeBinding.TrimInterval.Value;
            geometryCurveId = double.Abs(trim.Start - spline.DomainStart) <= 1e-12d
                && double.Abs(trim.End - spline.DomainEnd) <= 1e-12d
                ? bsplineId
                : writer.AddEntity("TRIMMED_CURVE", "$", Step242TextWriter.Ref(bsplineId),
                    Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(trim.Start)})"),
                    Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(trim.End)})"),
                    Step242TextWriter.BooleanLogical(true), Step242TextWriter.Enum("PARAMETER"));
        }
        else if (curve.Kind == CurveGeometryKind.Ellipse3 && curve.Ellipse3 is Ellipse3Curve ellipse)
        {
            if (!ellipseIds.TryGetValue(edgeId, out var ellipseId))
            {
                var axisPlacementId = BuildAxisPlacement(writer, ellipse.Center, ellipse.Normal, ellipse.XAxis);
                ellipseId = writer.AddEntity("ELLIPSE", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(ellipse.MajorRadius), Step242TextWriter.Number(ellipse.MinorRadius));
                ellipseIds[edgeId] = ellipseId;
            }

            geometryCurveId = ellipseId;
        }
        else if (curve.Kind == CurveGeometryKind.Hyperbola3 && curve.Hyperbola3 is Hyperbola3Curve hyperbola)
        {
            if (!hyperbolaIds.TryGetValue(edgeId, out var hyperbolaId))
            {
                // STEP HYPERBOLA represents its one exported branch through AXIS2_PLACEMENT_3D.
                // Encode the branch in the support frame (rather than approximating it as a spline).
                var exportedAxisU = hyperbola.Branch == HyperbolaBranch.PositiveAxisU
                    ? hyperbola.AxisU
                    : Direction3D.Create(-hyperbola.AxisU.ToVector());
                var exportedNormal = hyperbola.Branch == HyperbolaBranch.PositiveAxisU
                    ? hyperbola.PlaneNormal
                    : Direction3D.Create(-hyperbola.PlaneNormal.ToVector());
                var axisPlacementId = BuildAxisPlacement(writer, hyperbola.Center, exportedNormal, exportedAxisU);
                hyperbolaId = writer.AddEntity("HYPERBOLA", "$", Step242TextWriter.Ref(axisPlacementId), Step242TextWriter.Number(hyperbola.SemiAxisA), Step242TextWriter.Number(hyperbola.SemiAxisB));
                hyperbolaIds[edgeId] = hyperbolaId;
            }

            geometryCurveId = hyperbolaId;
        }
        else
        {
            return Failure($"Unsupported curve kind '{curve.Kind}'.", $"Edge:{edgeId.Value}");
        }

        var edgePcurveBindings = pcurveContextId is null
            ? []
            : body.Bindings.PcurveBindings
                .Where(binding => model.GetCoedge(binding.CoedgeId).EdgeId == edgeId
                    && (body.PcurveRecoveryReport is not { IsSuccess: false }
                        || binding.SourceStepPcurveEntityId is not null))
                .OrderBy(binding => binding.FaceId.Value)
                .ThenBy(binding => binding.CoedgeId.Value)
                .ToArray();
        // A circle or ellipse is written untrimmed, so a reader derives its trim from the vertices and lands on
        // its own turn, which may differ from the stored trim by whole turns (SO-101 stores [2pi, 5pi/2]). Analytic
        // conic traces are periodic and survive that. Line, polyline and spline traces are not: SO-101 stores a
        // straight UV trace on a B-spline face over [2pi, 2pi+0.43], which, read against [0, 0.43], started at
        // U -14.7 on a [0, 1] surface. So those traces move by the same whole turns.
        var periodShift = 0d;
        if (edgeBinding.TrimInterval is { } storedTrim && curve.Kind is CurveGeometryKind.Circle3 or CurveGeometryKind.Ellipse3)
        {
            var readerTrim = curve.Kind == CurveGeometryKind.Circle3
                ? Step242Importer.ComputeCircleTrim(curve.Circle3!.Value, startPoint, endPoint, emittedSameSense, 0.01d)
                : Step242Importer.ComputeEllipseTrim(curve.Ellipse3!.Value, startPoint, endPoint, emittedSameSense, 0.01d);
            if (readerTrim.IsSuccess)
                periodShift = double.Round((readerTrim.Value.Start - storedTrim.Start) / (2d * double.Pi)) * 2d * double.Pi;
        }
        var pcurveIds = pcurveContextId is null
            ? []
            : edgePcurveBindings
                .Select(binding => periodShift != 0d && (binding.Pcurve.PolynomialCurve is not null
                        || binding.Pcurve.Kind is PcurveGeometryKind.Line or PcurveGeometryKind.Polyline)
                    ? binding with { Pcurve = ReparameterizeLinePcurve(binding.Pcurve,
                        new ParameterInterval(binding.Pcurve.Domain.Start + periodShift, binding.Pcurve.Domain.End + periodShift)) }
                    : binding)
                .Select(binding => BuildStepPcurve(writer, binding, surfaceIds, pcurveContextId,
                    curve.Kind == CurveGeometryKind.Line3 && binding.Qualification is
                        { Origin: PcurveBindingOrigin.RecoveredAnalytic or PcurveBindingOrigin.RecoveredSpline or PcurveBindingOrigin.DerivedAnalytic or PcurveBindingOrigin.ConstructedBoundary }
                        ? new ParameterInterval(0d, (endPoint - startPoint).Length) : null,
                    // The rewritten line starts at the start vertex. That vertex is the stored trim's end when
                    // the edge runs against its curve, and the pcurve may itself run against the edge curve.
                    reverseLineDomain: edgeBinding.OrientedEdgeSense != binding.SameSense))
                .Where(id => id is not null)
                .Select(id => id!)
                .ToArray();
        if (pcurveIds.Length > 0)
        {
            var isSeam = edgePcurveBindings.GroupBy(binding => binding.SurfaceGeometryId)
                .Any(group => group.Count() > 1);
            geometryCurveId = writer.AddEntity(isSeam ? "SEAM_CURVE" : "SURFACE_CURVE", "$", Step242TextWriter.Ref(geometryCurveId), Step242TextWriter.List(pcurveIds), Step242TextWriter.Enum("PCURVE_S1"));
        }

        // EDGE_CURVE.same_sense is the binding between the parametric curve and
        // the topology edge, not a blanket export constant. In particular, a
        // clockwise Profile arc has an increasing trim interval whose geometric
        // direction is opposite the edge's authored start/end vertices. Writing
        // .T. here inverted that relation for downstream CAD, so cylindrical
        // faces at reflex arcs were trimmed through the complementary sweep.
        var edgeCurveId = writer.AddEntity("EDGE_CURVE", "$", Step242TextWriter.Ref(startVertexId), Step242TextWriter.Ref(endVertexId), Step242TextWriter.Ref(geometryCurveId), Step242TextWriter.BooleanLogical(emittedSameSense));
        return KernelResult<string>.Success(edgeCurveId);
    }

    private static string? BuildStepPcurve(
        Step242TextWriter writer,
        CoedgePcurveBinding binding,
        IReadOnlyDictionary<SurfaceGeometryId, string> surfaceIds,
        string contextId,
        ParameterInterval? reparameterizedLineDomain,
        bool reverseLineDomain = false)
    {
        if (!surfaceIds.TryGetValue(binding.SurfaceGeometryId, out var surfaceId)) return null;
        var representationName = binding.Qualification is { } qualification
            ? $"aetheris-qualified-pcurve:{Step242TextWriter.Number(qualification.QualificationToleranceMillimetres)}"
            : "pcurve";
        if (reparameterizedLineDomain is { } lineDomain)
            binding = binding with { Pcurve = ReparameterizeLinePcurve(binding.Pcurve, lineDomain, reverseLineDomain), SameSense = true };
        if (binding.Pcurve.PolynomialCurve is { } polynomial)
        {
            var controls = polynomial.ControlPoints.Select(p => writer.AddEntity("CARTESIAN_POINT", "$",
                Step242TextWriter.List(Step242TextWriter.Number(p.X), Step242TextWriter.Number(p.Y))))
                .Select(Step242TextWriter.Ref).ToArray();
            var curve = binding.Pcurve.RationalWeights is { } weights
                ? writer.AddRawEntity($"(BOUNDED_CURVE()B_SPLINE_CURVE({polynomial.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture)},{Step242TextWriter.List(controls)},{Step242TextWriter.Enum(polynomial.CurveForm)},{Step242TextWriter.BooleanLogical(polynomial.ClosedCurve)},{Step242TextWriter.BooleanLogical(polynomial.SelfIntersect)})B_SPLINE_CURVE_WITH_KNOTS({Step242TextWriter.List(polynomial.KnotMultiplicities.Select(n => n.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray())},{Step242TextWriter.List(polynomial.KnotValues.Select(Step242TextWriter.Number).ToArray())},{Step242TextWriter.Enum(polynomial.KnotSpec)})CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({Step242TextWriter.List(weights.Select(Step242TextWriter.Number).ToArray())})REPRESENTATION_ITEM(''))")
                : writer.AddEntity("B_SPLINE_CURVE_WITH_KNOTS", "$", polynomial.Degree.ToString(System.Globalization.CultureInfo.InvariantCulture),
                    Step242TextWriter.List(controls), Step242TextWriter.Enum(polynomial.CurveForm),
                    Step242TextWriter.BooleanLogical(polynomial.ClosedCurve), Step242TextWriter.BooleanLogical(polynomial.SelfIntersect),
                    Step242TextWriter.List(polynomial.KnotMultiplicities.Select(n => n.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray()),
                    Step242TextWriter.List(polynomial.KnotValues.Select(Step242TextWriter.Number).ToArray()), Step242TextWriter.Enum(polynomial.KnotSpec));
            var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(curve), Step242TextWriter.Ref(contextId));
            return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));
        }
        if (binding.Pcurve.Kind == PcurveGeometryKind.Line)
        {
            var start = binding.Pcurve.Points[0];
            var end = binding.Pcurve.Points[1];
            var span = binding.Pcurve.Domain.End - binding.Pcurve.Domain.Start;
            if (double.Abs(span) <= 1e-15d) return null;
            var du = (end.U - start.U) / span;
            var dv = (end.V - start.V) / span;
            var magnitude = double.Sqrt(du * du + dv * dv);
            if (!double.IsFinite(magnitude) || magnitude <= 1e-15d) return null;
            var origin = new SurfaceParameterPoint(start.U - du * binding.Pcurve.Domain.Start, start.V - dv * binding.Pcurve.Domain.Start);
            var originId = writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(origin.U), Step242TextWriter.Number(origin.V)));
            var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(du / magnitude), Step242TextWriter.Number(dv / magnitude)));
            var vectorId = writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(magnitude));
            var lineId = writer.AddEntity("LINE", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(vectorId));
            var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(lineId), Step242TextWriter.Ref(contextId));
            return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));
        }
        if (binding.Pcurve.Kind is PcurveGeometryKind.Circle or PcurveGeometryKind.Ellipse)
        {
            var center = binding.Pcurve.Points[0];
            var cosine = binding.Pcurve.Kind == PcurveGeometryKind.Circle
                ? new SurfaceParameterPoint(binding.Pcurve.Points[1].U, 0d)
                : binding.Pcurve.Points[1];
            var sine = binding.Pcurve.Kind == PcurveGeometryKind.Circle
                ? new SurfaceParameterPoint(0d, binding.Pcurve.Points[1].V)
                : binding.Pcurve.Points[2];
            var serializedSameSense = binding.SameSense;
            if ((cosine.U * sine.V) - (cosine.V * sine.U) < 0d)
            {
                // AXIS2_PLACEMENT_2D defines a right-handed conic frame. Represent a
                // left-handed coefficient frame by the exact reversed parameterization
                // h(s)=g(domain.Start+domain.End-s), then retain its use direction with
                // TRIMMED_CURVE.sense_agreement.
                var phase = binding.Pcurve.Domain.Start + binding.Pcurve.Domain.End;
                var phaseCosine = double.Cos(phase);
                var phaseSine = double.Sin(phase);
                var transformedCosine = new SurfaceParameterPoint(
                    cosine.U * phaseCosine + sine.U * phaseSine,
                    cosine.V * phaseCosine + sine.V * phaseSine);
                var transformedSine = new SurfaceParameterPoint(
                    cosine.U * phaseSine - sine.U * phaseCosine,
                    cosine.V * phaseSine - sine.V * phaseCosine);
                cosine = transformedCosine;
                sine = transformedSine;
                serializedSameSense = !serializedSameSense;
            }
            var major = double.Sqrt(cosine.U * cosine.U + cosine.V * cosine.V);
            var minor = double.Sqrt(sine.U * sine.U + sine.V * sine.V);
            if (major <= 1e-15d || minor <= 1e-15d) return null;
            var centerId = writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(center.U), Step242TextWriter.Number(center.V)));
            var axisId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(cosine.U / major), Step242TextWriter.Number(cosine.V / major)));
            var placementId = writer.AddEntity("AXIS2_PLACEMENT_2D", "$", Step242TextWriter.Ref(centerId), Step242TextWriter.Ref(axisId));
            var basisConicId = double.Abs(major - minor) <= 1e-12d
                ? writer.AddEntity("CIRCLE", "$", Step242TextWriter.Ref(placementId), Step242TextWriter.Number(major))
                : writer.AddEntity("ELLIPSE", "$", Step242TextWriter.Ref(placementId), Step242TextWriter.Number(major), Step242TextWriter.Number(minor));
            var conicId = serializedSameSense
                ? basisConicId
                : writer.AddEntity("TRIMMED_CURVE", "$", Step242TextWriter.Ref(basisConicId),
                    Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(binding.Pcurve.Domain.Start)})"),
                    Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(binding.Pcurve.Domain.End)})"),
                    Step242TextWriter.BooleanLogical(false), Step242TextWriter.Enum("PARAMETER"));
            var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(conicId), Step242TextWriter.Ref(contextId));
            return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));
        }
        var samples = binding.Pcurve.Kind switch
        {
            PcurveGeometryKind.Line => 2,
            PcurveGeometryKind.Polyline => binding.Pcurve.Points.Count,
            _ => 1025
        };
        var points = Enumerable.Range(0, samples).Select(index =>
        {
            var parameter = binding.Pcurve.Domain.Start + ((binding.Pcurve.Domain.End - binding.Pcurve.Domain.Start) * index / (samples - 1d));
            return binding.Pcurve.Evaluate(parameter);
        }).Select(point => writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(point.U), Step242TextWriter.Number(point.V))))
          .ToArray();
        var curve2dId = writer.AddEntity("POLYLINE", "$", Step242TextWriter.List(points));
        var representationId = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(curve2dId), Step242TextWriter.Ref(contextId));
        return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representationId));
    }

    internal static PcurveGeometry ReparameterizeLinePcurve(PcurveGeometry pcurve, ParameterInterval lineDomain, bool reverse = false)
    {
        if (reverse) pcurve = Reversed(pcurve);
        if (pcurve.PolynomialCurve is { } polynomial)
        {
            var source = pcurve.Domain;
            var span = source.End - source.Start;
            // Preserve exact endpoints of the affine map. Evaluating the formula
            // there can round one ULP outside the mapped spline's trim domain.
            var knots = polynomial.KnotValues.Select(value => value == source.Start ? lineDomain.Start
                : value == source.End ? lineDomain.End : lineDomain.Start
                + (value - source.Start) * (lineDomain.End - lineDomain.Start) / span).ToArray();
            var remapped = new BSpline3Curve(polynomial.Degree, polynomial.ControlPoints,
                polynomial.KnotMultiplicities, knots, polynomial.CurveForm,
                polynomial.ClosedCurve, polynomial.SelfIntersect, polynomial.KnotSpec);
            return pcurve.RationalWeights is { } weights ? PcurveGeometry.RationalPolynomial(lineDomain, remapped, weights)
                : PcurveGeometry.Polynomial(lineDomain, remapped);
        }
        return pcurve.Kind switch {
            PcurveGeometryKind.Line => PcurveGeometry.Line(lineDomain, pcurve.Points[0], pcurve.Points[1]),
            PcurveGeometryKind.Polyline => PcurveGeometry.Polyline(lineDomain, pcurve.Points),
            _ => pcurve
        };
    }

    /// <summary>The same trace traversed the other way over the same domain: t maps to Start + End - t.</summary>
    private static PcurveGeometry Reversed(PcurveGeometry pcurve)
    {
        var d = pcurve.Domain;
        if (pcurve.PolynomialCurve is { } polynomial)
        {
            var knots = polynomial.KnotValues.Reverse().Select(k => k == d.Start ? d.End : k == d.End ? d.Start : d.Start + d.End - k).ToArray();
            var reversed = new BSpline3Curve(polynomial.Degree, polynomial.ControlPoints.Reverse().ToArray(),
                polynomial.KnotMultiplicities.Reverse().ToArray(), knots, polynomial.CurveForm,
                polynomial.ClosedCurve, polynomial.SelfIntersect, polynomial.KnotSpec);
            return pcurve.RationalWeights is { } weights ? PcurveGeometry.RationalPolynomial(d, reversed, weights.Reverse().ToArray())
                : PcurveGeometry.Polynomial(d, reversed);
        }
        return pcurve.Kind switch
        {
            PcurveGeometryKind.Line => PcurveGeometry.Line(d, pcurve.Points[1], pcurve.Points[0]),
            PcurveGeometryKind.Polyline => PcurveGeometry.Polyline(d, pcurve.Points.Reverse().ToArray()),
            _ => throw new InvalidOperationException($"A {pcurve.Kind} pcurve on a straight edge cannot be reversed for export."),
        };
    }

    private static string EnsureVertex(
        Step242TextWriter writer,
        VertexId vertexId,
        Point3D point,
        IDictionary<VertexId, Point3D> vertexPoints,
        IDictionary<VertexId, string> cartesianPointIds,
        IDictionary<VertexId, string> vertexPointIds)
    {
        const double tolerance = 1e-9;
        if (vertexPoints.TryGetValue(vertexId, out var existingPoint))
        {
            var delta = existingPoint - point;
            if (delta.LengthSquared > tolerance * tolerance)
            {
#if DEBUG
                throw new InvalidOperationException($"Vertex {vertexId.Value} point inconsistency detected during STEP export.");
#endif
            }
        }
        else
        {
            vertexPoints[vertexId] = point;
        }

        if (!cartesianPointIds.TryGetValue(vertexId, out var pointId))
        {
            pointId = writer.AddEntity("CARTESIAN_POINT", "$", PointList(point));
            cartesianPointIds[vertexId] = pointId;
        }

        if (!vertexPointIds.TryGetValue(vertexId, out var vertexPointId))
        {
            vertexPointId = writer.AddEntity("VERTEX_POINT", "$", Step242TextWriter.Ref(pointId));
            vertexPointIds[vertexId] = vertexPointId;
        }

        return vertexPointId;
    }

    private static KernelResult<Point3D> ResolveVertexPoint(
        BrepBody body,
        TopologyModel model,
        VertexId vertexId,
        IDictionary<VertexId, Point3D> vertexPoints)
    {
        if (vertexPoints.TryGetValue(vertexId, out var resolved))
        {
            return KernelResult<Point3D>.Success(resolved);
        }

        var preferEdgeEndpoint = VertexTouchesNonPlanarFace(body, model, vertexId);
        if (!preferEdgeEndpoint)
        {
            var fromPlanes = ResolveVertexFromIncidentPlanes(body, model, vertexId);
            if (fromPlanes.IsSuccess)
            {
                vertexPoints[vertexId] = fromPlanes.Value;
                return fromPlanes;
            }
        }

        foreach (var edge in model.Edges.OrderBy(e => e.Id.Value))
        {
            var useStart = false;
            if (edge.StartVertexId == vertexId)
            {
                useStart = true;
            }
            else if (edge.EndVertexId != vertexId)
            {
                continue;
            }

            var pointResult = EvaluateEdgeEndpoint(body, edge.Id, useStart);
            if (!pointResult.IsSuccess)
            {
                continue;
            }

            vertexPoints[vertexId] = pointResult.Value;
            return KernelResult<Point3D>.Success(pointResult.Value);
        }

        return FailurePoint($"Vertex {vertexId.Value} cannot be resolved to a geometric point for STEP export.", $"Vertex:{vertexId.Value}");
    }

    private static bool VertexTouchesNonPlanarFace(BrepBody body, TopologyModel model, VertexId vertexId)
    {
        foreach (var face in model.Faces.OrderBy(f => f.Id.Value))
        {
            var touchesVertex = false;
            foreach (var loopId in face.LoopIds)
            {
                var loop = model.GetLoop(loopId);
                foreach (var coedgeId in loop.CoedgeIds)
                {
                    var coedge = model.GetCoedge(coedgeId);
                    var edge = model.GetEdge(coedge.EdgeId);
                    if (edge.StartVertexId == vertexId || edge.EndVertexId == vertexId)
                    {
                        touchesVertex = true;
                        break;
                    }
                }

                if (touchesVertex)
                {
                    break;
                }
            }

            if (!touchesVertex || !body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding))
            {
                continue;
            }

            if (!body.Geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface is null)
            {
                continue;
            }

            if (surface.Kind != SurfaceGeometryKind.Plane)
            {
                return true;
            }
        }

        return false;
    }

    private static KernelResult<Point3D> ResolveVertexFromIncidentPlanes(BrepBody body, TopologyModel model, VertexId vertexId)
    {
        var planes = new List<PlaneSurface>();
        foreach (var face in model.Faces.OrderBy(f => f.Id.Value))
        {
            var touchesVertex = false;
            foreach (var loopId in face.LoopIds)
            {
                var loop = model.GetLoop(loopId);
                foreach (var coedgeId in loop.CoedgeIds)
                {
                    var coedge = model.GetCoedge(coedgeId);
                    var edge = model.GetEdge(coedge.EdgeId);
                    if (edge.StartVertexId == vertexId || edge.EndVertexId == vertexId)
                    {
                        touchesVertex = true;
                        break;
                    }
                }

                if (touchesVertex)
                {
                    break;
                }
            }

            if (!touchesVertex || !body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding))
            {
                continue;
            }

            if (!body.Geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface?.Plane is null)
            {
                continue;
            }

            planes.Add(surface.Plane.Value);
        }

        for (var i = 0; i < planes.Count; i++)
        {
            for (var j = i + 1; j < planes.Count; j++)
            {
                for (var k = j + 1; k < planes.Count; k++)
                {
                    if (TryIntersectPlanes(planes[i], planes[j], planes[k], out var intersection))
                    {
                        return KernelResult<Point3D>.Success(intersection);
                    }
                }
            }
        }

        return FailurePoint($"Vertex {vertexId.Value} cannot be resolved from incident face planes.", $"Vertex:{vertexId.Value}");
    }

    private static bool TryIntersectPlanes(PlaneSurface a, PlaneSurface b, PlaneSurface c, out Point3D point)
    {
        var n1 = a.Normal.ToVector();
        var n2 = b.Normal.ToVector();
        var n3 = c.Normal.ToVector();
        var denominator = n1.Dot(n2.Cross(n3));
        if (double.Abs(denominator) <= 1e-12d)
        {
            point = Point3D.Origin;
            return false;
        }

        var d1 = n1.Dot(new Vector3D(a.Origin.X, a.Origin.Y, a.Origin.Z));
        var d2 = n2.Dot(new Vector3D(b.Origin.X, b.Origin.Y, b.Origin.Z));
        var d3 = n3.Dot(new Vector3D(c.Origin.X, c.Origin.Y, c.Origin.Z));

        var numerator = (n2.Cross(n3) * d1) + (n3.Cross(n1) * d2) + (n1.Cross(n2) * d3);
        point = new Point3D(numerator.X / denominator, numerator.Y / denominator, numerator.Z / denominator);
        return double.IsFinite(point.X) && double.IsFinite(point.Y) && double.IsFinite(point.Z);
    }

    private static KernelResult<Point3D> EvaluateEdgeEndpoint(BrepBody body, EdgeId edgeId, bool useStart)
    {
        if (!body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding))
        {
            return FailurePoint("Edge is missing curve binding.", $"Edge:{edgeId.Value}");
        }

        if (edgeBinding.TrimInterval is null)
        {
            return FailurePoint("Edge must provide trim interval for vertex mapping.", $"Edge:{edgeId.Value}");
        }

        if (!body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null)
        {
            return FailurePoint("Edge curve geometry was not found.", $"Curve:{edgeBinding.CurveGeometryId.Value}");
        }

        var useTrimStart = useStart == edgeBinding.OrientedEdgeSense;
        var parameter = useTrimStart ? edgeBinding.TrimInterval.Value.Start : edgeBinding.TrimInterval.Value.End;
        return curve.Kind switch
        {
            CurveGeometryKind.Line3 when curve.Line3 is Line3Curve line => KernelResult<Point3D>.Success(line.Evaluate(parameter)),
            CurveGeometryKind.Circle3 when curve.Circle3 is Circle3Curve circle => KernelResult<Point3D>.Success(circle.Evaluate(parameter)),
            CurveGeometryKind.BSpline3 when curve.BSpline3 is BSpline3Curve spline => KernelResult<Point3D>.Success(spline.Evaluate(parameter)),
            CurveGeometryKind.Ellipse3 when curve.Ellipse3 is Ellipse3Curve ellipse => KernelResult<Point3D>.Success(ellipse.Evaluate(parameter)),
            CurveGeometryKind.Hyperbola3 when curve.Hyperbola3 is Hyperbola3Curve hyperbola => KernelResult<Point3D>.Success(hyperbola.Evaluate(parameter)),
            _ => FailurePoint($"Unsupported curve kind '{curve.Kind}'.", $"Edge:{edgeId.Value}")
        };
    }

    private static string PointList(Point3D point) => Step242TextWriter.List(
        Step242TextWriter.Number(point.X),
        Step242TextWriter.Number(point.Y),
        Step242TextWriter.Number(point.Z));

    private static KernelResult<string> Failure(string message, string source) =>
        KernelResult<string>.Failure([
            new KernelDiagnostic(
                KernelDiagnosticCode.NotImplemented,
                KernelDiagnosticSeverity.Error,
                message,
                source)
        ]);

    private static KernelResult<string> RationalGeometryNotCanonical(string source, string kind) =>
        KernelResult<string>.Failure([
            new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed,
                KernelDiagnosticSeverity.Error,
                $"RationalGeometryNotCanonical: trusted production STEP cannot emit {kind}; recover a qualified canonical carrier first.",
                source)
        ]);

    private static IEnumerable<KernelDiagnostic> ToKernelDiagnostics(BrepExportPreflightResult result, bool errorsAsWarnings) =>
        result.Diagnostics.Select(diagnostic => new KernelDiagnostic(
            KernelDiagnosticCode.ValidationFailed,
            errorsAsWarnings && diagnostic.Severity == BrepExportPreflightSeverity.Error
                ? KernelDiagnosticSeverity.Warning
                : diagnostic.Severity == BrepExportPreflightSeverity.Error
                    ? KernelDiagnosticSeverity.Error
                    : KernelDiagnosticSeverity.Warning,
            $"{diagnostic.Code}: {diagnostic.Message}",
            diagnostic.Context));

    private static KernelResult<Point3D> FailurePoint(string message, string source) =>
        KernelResult<Point3D>.Failure([
            new KernelDiagnostic(
                KernelDiagnosticCode.NotImplemented,
                KernelDiagnosticSeverity.Error,
                message,
                source)
        ]);
}