Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

49.1 KB
Raw Blame
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Numerics;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using Aetheris.Kernel.StandardLibrary.Materials;

namespace Aetheris.Kernel.Firmament.Materializer;

/// <summary>Deterministic local state consumed and produced by every WireForm operation.</summary>
public sealed record WireState(Point3D Position, Direction3D Tangent, Direction3D Up, double AccumulatedLengthMm)
{
    public Direction3D Right => Direction3D.Create(WireFormAuthoring.Cross(Tangent.ToVector(), Up.ToVector()));
}

public abstract record WireFormOperationAir(string Name, int Ordinal, WireState Input, WireState Output, double LengthMm)
{
    public string StableId(string wireFormName) => $"wireform:{wireFormName}:operation:{Ordinal}:{Name}";
}

/// <summary>Shared semantic authority for bounded evaluable wire paths. Samples are evidence, never authoring input.</summary>
public abstract record WireEvaluablePathAir(string Name, int Ordinal, WireState Input, WireState Output, double LengthMm,
    double ApproximationToleranceMm) : WireFormOperationAir(Name, Ordinal, Input, Output, LengthMm)
{
    public abstract Point3D Evaluate(double parameter);
    public abstract Direction3D Tangent(double parameter);
    public abstract int ApproximationSegmentCount { get; }
    public abstract bool Closed { get; }
    public (double MaxMm, double RmsMm) ApproximationError => WireEvaluablePathGeometry.MeasureCenterlineApproximation(this, ApproximationSegmentCount);
}

public sealed record WireStraightAir(string Name, int Ordinal, double AuthoredLengthMm, WireState Input, WireState Output)
    : WireFormOperationAir(Name, Ordinal, Input, Output, AuthoredLengthMm);

public sealed record WireBendAir(string Name, int Ordinal, double RadiusMm, double AngleRadians, string Plane,
    Direction3D PlaneNormal, Point3D Center, Direction3D StartRadial, WireState Input, WireState Output)
    : WireFormOperationAir(Name, Ordinal, Input, Output, RadiusMm * Math.Abs(AngleRadians));

public enum WireCoilHandedness { RightHanded, LeftHanded }
public enum WireSurfaceSide { Outside, Inside }

/// <summary>An evaluable winding law retained as semantic authority; samples are never authoring input.</summary>
public abstract record WireCoilAir(string Name, int Ordinal, double Turns, WireCoilHandedness Handedness,
    double StartPhaseRadians, WireState Input, WireState Output, double LengthMm, double MinimumSelfClearanceMm,
    double ApproximationToleranceMm) : WireEvaluablePathAir(Name, Ordinal, Input, Output, LengthMm, ApproximationToleranceMm)
{
    public abstract string CoilKind { get; }
    public abstract string ProgressionLaw { get; }
    public virtual double? SupportClearanceMm => null;
    public override int ApproximationSegmentCount => Math.Max(16, (int)Math.Ceiling(Turns * 32d));
    public override bool Closed => false;
}

public sealed record WireAxisCoilAir(string Name, int Ordinal, double RadiusMm, double Turns, double PitchMm,
    double HeightMm, WireCoilHandedness Handedness, double StartPhaseRadians, Point3D AxisOrigin,
    Direction3D Axis, Direction3D StartRadial, WireState Input, WireState Output, double LengthMm,
    double MinimumSelfClearanceMm, double ApproximationToleranceMm)
    : WireCoilAir(Name, Ordinal, Turns, Handedness, StartPhaseRadians, Input, Output, LengthMm,
        MinimumSelfClearanceMm, ApproximationToleranceMm)
{
    public override string CoilKind => "Helix";
    public override string ProgressionLaw => "AxialPitch";
    public override Point3D Evaluate(double t) => WireCoilGeometry.EvaluateAxis(this, t);
    public override Direction3D Tangent(double t) => WireCoilGeometry.TangentAxis(this, t);
}

public sealed record WireSurfaceCoilAir(string Name, int Ordinal, string SupportName, string SupportKind,
    WireSurfaceSide Side, double ClearanceMm, double CenterlineOffsetMm, double Turns, double AxialPitchMm,
    double StartLatitudeRadians, double EndLatitudeRadians, WireCoilHandedness Handedness,
    double StartPhaseRadians, double SupportRadius0Mm, double SupportRadius1Mm, double SupportHeightMm,
    Point3D SupportOrigin, Direction3D SupportAxis, Direction3D StartRadial, Direction3D LongitudeDirection,
    Direction3D LatitudeDirection, WireState Input, WireState Output, double LengthMm,
    double MinimumSelfClearanceMm, double MeasuredSupportClearanceMm, double ApproximationToleranceMm)
    : WireCoilAir(Name, Ordinal, Turns, Handedness, StartPhaseRadians, Input, Output, LengthMm,
        MinimumSelfClearanceMm, ApproximationToleranceMm)
{
    public override string CoilKind => $"SurfaceCoil.{SupportKind}";
    public override string ProgressionLaw => SupportKind == "Sphere" ? "LatitudeProgression" : "AxialPitch";
    public override double? SupportClearanceMm => MeasuredSupportClearanceMm;
    public override Point3D Evaluate(double t) => WireCoilGeometry.EvaluateSurface(this, t);
    public override Direction3D Tangent(double t) => WireCoilGeometry.TangentSurface(this, t);
}

/// <summary>WireForm semantic AIR. Bend radii are centerline radii.</summary>
public sealed record WireFormFeatureAir(string Name, double DiameterMm, string MaterialReference, ResolvedMaterial Material,
    WireState StartState, IReadOnlyList<WireFormOperationAir> Operations, string FrameTransportPolicy,
    IReadOnlyList<WireFormOperationProvenance>? AuthoredOperations = null)
{
    public double WireRadiusMm => DiameterMm / 2d;
    public double TotalStraightLengthMm => Operations.OfType<WireStraightAir>().Sum(x => x.LengthMm);
    public double TotalBendLengthMm => Operations.OfType<WireBendAir>().Sum(x => x.LengthMm);
    public double TotalCoilLengthMm => Operations.OfType<WireCoilAir>().Sum(x => x.LengthMm);
    public double TotalWireLengthMm => Operations.Sum(x => x.LengthMm);
    public WireState EndState => Operations.Count == 0 ? StartState : Operations[^1].Output;
}

public sealed record WireFormOperationProvenance(string Name, FirmamentV2SourceSpan ConstructSpan,
    IReadOnlyList<FirmamentV2AuthoredField> Fields);

public sealed record WireFormBuildResult(WireFormFeatureAir Feature, BrepBody Body, double VolumeMm3,
    double MassKilograms, IReadOnlyList<double> Bounds, IReadOnlyList<string> ValidationEvidence);

/// <summary>Parser and ordered state-machine lowering for the bounded X0 WireForm vocabulary.</summary>
public static class WireFormAuthoring
{
    public const string FrameTransportPolicy = "The authored local Up/Right bend-plane axis is rotated with the tangent through each bend (rotation-minimal rigid transport about the bend normal); Straight preserves the frame.";
    private static readonly Regex Declaration = new(@"\bWireForm\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
    private static readonly Regex Operation = new(@"\b(?<kind>Straight|Bend|Helix|AxisCoil|SurfaceCoil|Coil|Knot)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);

    public static IReadOnlyList<FirmamentAuthoringField> HelixFields => WireCoilAuthoring.AxisFields;

    public static bool IsInsideHelix(string source, int offset)
    {
        foreach (Match wireForm in Declaration.Matches(source))
        {
            var wireOpen = wireForm.Index + wireForm.Length - 1;
            var wireClose = MatchingBrace(source, wireOpen);
            if (offset <= wireOpen || wireClose >= 0 && offset > wireClose) continue;
            foreach (Match match in Operation.Matches(source))
            {
                if (match.Groups["kind"].Value != "Helix") continue;
                var open = match.Index + match.Length - 1;
                if (open <= wireOpen || wireClose >= 0 && open >= wireClose) continue;
                if (offset <= open) continue;
                var close = MatchingBrace(source, open);
                if (close < 0 || offset <= close) return true;
            }
        }
        return false;
    }

    public static bool IsWireFormSource(string source) => FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
        .Any(d => d.Type.Name.Text == "WireForm") || WireRouteAuthoring.IsSource(source);

    internal static void BindConstructionScope(DocumentSyntax syntax, string materialKind, List<string> diagnostics)
    {
        void Bind(IReadOnlyList<StatementSyntax> statements)
        {
            bool Wrapper(DeclarationSyntax d) => d.Type.Name.Text is "Model" or "Struct"
                && !d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template");
            foreach (var wrapper in statements.OfType<DeclarationSyntax>().Where(Wrapper)) Bind(wrapper.Body?.Statements ?? []);
            FirmamentV2Parser.BindMechanicalScope(statements.Where(s => s is not DeclarationSyntax d
                || !(Wrapper(d) || d.Type.Name.Text == materialKind)).ToArray(), diagnostics);
        }
        Bind(syntax.Statements);
    }

    public static KernelResult<WireFormFeatureAir> Parse(string source)
    {
        ArgumentNullException.ThrowIfNull(source);
        var frontend = FirmamentFrontendSchemas.Select(source);
        if (!frontend.IsSuccess) return Fail(frontend.Diagnostics[0].Split(':')[0], string.Join("; ", frontend.Diagnostics));
        source = frontend.Source;
        if (WireRouteAuthoring.IsSource(source)) return WireRouteAuthoring.Parse(source);
        var syntax = FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);
        var scopeDiagnostics = syntax.Diagnostics.Select(d => d.Code + ": " + d.Message).ToList();
        BindConstructionScope(syntax.Document, "WireForm", scopeDiagnostics);
        if (scopeDiagnostics.Count > 0)
            return Fail(scopeDiagnostics[0].Split(':')[0], string.Join("; ", scopeDiagnostics));
        var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).Where(d => d.Type.Name.Text == "WireForm").ToArray();
        if (declarations.Length > 1) return Fail("wireform-multiple-bodies-unsupported", "One WireForm product is admitted per part; place separate Parts in an Assembly. No declared wire may be discarded.");
        var declaration = declarations.FirstOrDefault();
        if (declaration?.Name is null || declaration.Body is null)
            return Fail("wireform-declaration-missing", "Expected WireForm Name { ... }.");
        var name = declaration.Name.Text;
        if (UnsupportedHeader(declaration)) return Fail("wireform-header-unsupported", $"WireForm '{name}' does not admit placement, generic, parameter or initializer clauses; author its StartFrame fields explicitly.");
        foreach (var child in declaration.Body.Statements.OfType<DeclarationSyntax>())
        {
            if (child.Body is null)
                return child.Type.Name.Text == "StartFrame"
                    ? Fail("wireform-start-frame-invalid", "StartFrame requires a body containing Origin, Tangent and Up.")
                    : Fail("wireform-operation-malformed", $"Wire operation '{child.Name?.Text ?? child.Type.Name.Text}' requires a body.");
            if (UnsupportedHeader(child) || child.Type.Name.Text != "StartFrame" && child.Name is null)
                return Fail("wireform-header-unsupported", $"Wire operation '{child.Name?.Text ?? child.Type.Name.Text}' requires a named operation and a field body; placement and parameter clauses are not supported.");
        }
        var body = source.Substring(declaration.Body.ContentSpan.Start, declaration.Body.ContentSpan.Length);
        var wireFields = new WireFormFields("WireForm", body);
        var children = wireFields.Declaration.Body!.Statements.OfType<DeclarationSyntax>()
            .Where(d => d.Type.Name.Text is "StartFrame" or "Straight" or "Bend" or "Helix" or "AxisCoil" or "Coil" or "SurfaceCoil" or "Knot")
            .Cast<StatementSyntax>().ToHashSet();
        var startFrames = children.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "StartFrame").ToArray();
        if (startFrames.Length > 1) return Fail("wireform-start-frame-invalid", "Declare only one StartFrame.");
        // Direct Origin/Tangent/Up fields are an admitted historical spelling.
        // A block and direct fields together leave unconsumed fields and reject.
        var frameFields = wireFields;
        if (startFrames.Length == 1)
        {
            if (startFrames[0].Body is not { } frameBody)
                return Fail("wireform-start-frame-invalid", "StartFrame requires a body containing Origin, Tangent and Up.");
            var frame = frameBody.ContentSpan;
            frameFields = new WireFormFields("StartFrame", ("WireForm {\n" + body + "\n}").Substring(frame.Start, frame.Length));
        }

        if (!TryLength(wireFields.Read("Diameter"), out var diameter) || diameter <= 0d)
            return Fail("wireform-diameter-invalid", $"WireForm '{name}' Diameter must be a finite length greater than zero.");
        var materialReference = (wireFields.Read("Material") ?? "Standard.Materials.StainlessSteel.304_Annealed").Trim('"');
        var material = new MaterialResolver().Resolve(materialReference);
        if (!material.IsSuccess || material.Material is null)
            return Fail("wireform-material-unresolved", material.Message ?? $"Material '{materialReference}' could not be resolved.");

        if (!TryVector(frameFields.Read("Origin"), out var origin, length: true))
            return Fail("wireform-start-frame-invalid", $"WireForm '{name}' requires StartFrame Origin: [x,y,z].");
        if (!TryVector(frameFields.Read("Tangent"), out var tangentVector) || !TryDirection(tangentVector, out var tangent))
            return Fail("wireform-start-frame-invalid", $"WireForm '{name}' requires a nonzero StartFrame Tangent.");
        if (!TryVector(frameFields.Read("Up"), out var upVector))
            return Fail("wireform-start-frame-invalid", $"WireForm '{name}' requires StartFrame Up.");
        var upRejected = upVector - tangent.ToVector() * Dot(upVector, tangent.ToVector());
        if (!TryDirection(upRejected, out var up))
            return Fail("wireform-start-frame-invalid", $"WireForm '{name}' Up must not be parallel to Tangent.");

        if (wireFields.Complete(children) is { } rootError) return Fail("wireform-fields-invalid", rootError);
        if (!ReferenceEquals(frameFields, wireFields) && frameFields.Complete() is { } frameError) return Fail("wireform-fields-invalid", frameError);
        var state = new WireState(new(origin.X, origin.Y, origin.Z), tangent, up, 0d);
        var operations = new List<WireFormOperationAir>();
        var provenance = new List<WireFormOperationProvenance>();
        foreach (var operation in declaration.Body.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text != "StartFrame"))
        {
            var operationBody = source.Substring(operation.Body!.ContentSpan.Start, operation.Body.ContentSpan.Length);
            var operationName = operation.Name!.Text;
            var operationKind = operation.Type.Name.Text;
            var operationFields = new WireFormFields(operationKind, operationBody);
            provenance.Add(new(operationName,
                operation.Span, FirmamentV2Parser.ReadAuthoredFields(operationBody, operation.Body.ContentSpan.Start)));
            var ordinal = operations.Count + 1;
            if (operationKind == "Straight")
            {
                if (!TryLength(operationFields.Read("Length"), out var length) || length <= 0d)
                    return Fail("wireform-straight-length-invalid", $"{operationName}: Length must be finite and greater than zero.");
                if (operationFields.Complete() is { } straightError) return Fail("wireform-fields-invalid", straightError);
                var output = state with { Position = state.Position + state.Tangent.ToVector() * length, AccumulatedLengthMm = state.AccumulatedLengthMm + length };
                operations.Add(new WireStraightAir(operationName, ordinal, length, state, output));
                state = output;
                continue;
            }

            if (operationKind is "Helix" or "AxisCoil" or "Coil")
            {
                var coil = WireCoilAuthoring.CreateAxis(operationName, ordinal, operationBody, state, diameter);
                if (!coil.IsSuccess) return KernelResult<WireFormFeatureAir>.Failure(coil.Diagnostics);
                operations.Add(coil.Value); state = coil.Value.Output; continue;
            }
            if (operationKind == "SurfaceCoil")
            {
                var coil = WireCoilAuthoring.CreateSurface(source, operationName, ordinal, operationBody, state, diameter);
                if (!coil.IsSuccess) return KernelResult<WireFormFeatureAir>.Failure(coil.Diagnostics);
                operations.Add(coil.Value); state = coil.Value.Output; continue;
            }
            if (operationKind == "Knot")
            {
                if (operations.Count != 0 || Operation.Matches(body).Count != 1)
                    return Fail("wireform-knot-composition-unsupported", $"{operationName}: X2 KnotPath must be the sole closed operation in a WireForm.");
                var knotResult = WireKnotAuthoring.Create(operationName, ordinal, operationBody, state, diameter);
                if (!knotResult.IsSuccess) return KernelResult<WireFormFeatureAir>.Failure(knotResult.Diagnostics);
                operations.Add(knotResult.Value); state = knotResult.Value.Output; continue;
            }

            if (!TryLength(operationFields.Read("Radius"), out var radius) || radius <= 0d)
                return Fail("wireform-bend-radius-invalid", $"{operationName}: centerline Radius must be finite and greater than zero.");
            if (radius <= diameter / 2d + ToleranceContext.Default.Linear)
                return Fail("wireform-bend-radius-invalid", $"{operationName}: centerline Radius {radius:G6} mm must exceed wire radius {diameter / 2d:G6} mm (geometric-only policy).");
            if (!TryAngle(operationFields.Read("Angle"), out var angle) || Math.Abs(angle) <= ToleranceContext.Default.Angular || Math.Abs(angle) > Math.PI + ToleranceContext.Default.Angular)
                return Fail("wireform-bend-angle-invalid", $"{operationName}: Angle must be nonzero and no greater than 180 degrees in magnitude.");
            var plane = operationFields.Read("Plane") ?? "Up";
            if (plane is not ("Up" or "Right"))
                return Fail("wireform-bend-plane-invalid", $"{operationName}: Plane must be Up or Right in the current local frame.");
            if (operationFields.Complete() is { } bendError) return Fail("wireform-fields-invalid", bendError);
            var authoredNormal = plane == "Up" ? state.Up : state.Right;
            var axis = angle >= 0d ? authoredNormal : Direction3D.Create(authoredNormal.ToVector() * -1d);
            var sweep = Math.Abs(angle);
            var startRadial = Direction3D.Create(Cross(state.Tangent.ToVector(), axis.ToVector()));
            var center = state.Position - startRadial.ToVector() * radius;
            var endRadial = Rotate(startRadial.ToVector(), axis.ToVector(), sweep);
            var endTangent = Direction3D.Create(Rotate(state.Tangent.ToVector(), axis.ToVector(), sweep));
            var endUp = Direction3D.Create(Rotate(state.Up.ToVector(), axis.ToVector(), sweep));
            var bendLength = radius * sweep;
            var bendOutput = new WireState(center + endRadial * radius, endTangent, endUp, state.AccumulatedLengthMm + bendLength);
            operations.Add(new WireBendAir(operationName, ordinal, radius, angle, plane, axis, center, startRadial, state, bendOutput));
            state = bendOutput;
        }
        if (operations.Count == 0) return Fail("wireform-operations-empty", $"WireForm '{name}' requires at least one Straight, Bend, Helix, SurfaceCoil, or Knot operation.");
        var authoredStart = new WireState(new(origin.X, origin.Y, origin.Z), tangent, up, 0d);
        return KernelResult<WireFormFeatureAir>.Success(new(name, diameter, materialReference, material.Material,
            operations[0] is WireKnotPathAir ? operations[0].Input : authoredStart, operations,
            operations[0] is WireKnotPathAir knot ? knot.FrameClosure.Policy : FrameTransportPolicy, provenance));
    }

    private static bool UnsupportedHeader(DeclarationSyntax declaration) => declaration.Clauses.Count > 0
        || declaration.Modifiers.Count > 0 || declaration.Type.Arguments.Count > 0 || declaration.Parameters.Count > 0
        || declaration.HasParameterList || declaration.Annotation is not null || declaration.ResultType is not null
        || declaration.Initializer is not null || declaration.Occurrence;

    internal static string? Property(string body, string name)
    {
        var match = Regex.Match(body, $@"\b(?:{Regex.Escape(name)}|{Regex.Escape(FirmamentSourceSpelling.PreferredField(name))})\s*:\s*(?<value>\[[^\]]+\]|[^;\r\n}}]+)", RegexOptions.CultureInvariant);
        return match.Success ? match.Groups["value"].Value.Trim() : null;
    }
    internal static bool TryLength(string? text, out double value)
    {
        value = default;
        return text is not null && new BoundedMeasureExpression(text, "mm").TryEvaluate(out value);
    }
    internal static bool TryAngle(string? text, out double value)
    {
        value = default;
        if (!TryUnit(text, "deg", out var degrees)) return false;
        value = degrees * Math.PI / 180d;
        return double.IsFinite(value);
    }
    private static bool TryUnit(string? text, string unit, out double value)
    {
        value = default;
        if (text is null) return false;
        var match = Regex.Match(text, $@"^(?<value>[-+.\deE]+){unit}$", RegexOptions.CultureInvariant);
        return match.Success && double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
    }
    private static bool TryVector(string? text, out Vector3D value, bool length = false)
    {
        value = default;
        if (text is null) return false;
        var parts = text.Trim().TrimStart('[').TrimEnd(']').Split(',', StringSplitOptions.TrimEntries);
        if (parts.Length != 3) return false;
        var values = new double[3];
        for (var i = 0; i < 3; i++)
        {
            var token = length && parts[i].EndsWith("mm", StringComparison.Ordinal) ? parts[i][..^2] : parts[i];
            if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]) || !double.IsFinite(values[i])) return false;
        }
        value = new(values[0], values[1], values[2]); return true;
    }
    private static bool TryDirection(Vector3D vector, out Direction3D direction)
    {
        try { direction = Direction3D.Create(vector); return true; }
        catch (ArgumentException) { direction = default; return false; }
    }
    internal static int MatchingBrace(string source, int open) { var depth = 0; for (var i = open; i >= 0 && i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }
    private static Vector3D Rotate(Vector3D vector, Vector3D axis, double angle) => vector * Math.Cos(angle) + Cross(axis, vector) * Math.Sin(angle) + axis * (Dot(axis, vector) * (1d - Math.Cos(angle)));
    internal static Vector3D Cross(Vector3D a, Vector3D b) => new(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
    internal static double Dot(Vector3D a, Vector3D b) => a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    private sealed class BoundedMeasureExpression(string source, string unit)
    {
        private int index;
        public bool TryEvaluate(out double value) { value = default; index = 0; if (!Expression(out var result) || result.Dimension != 1) return false; Space(); if (index != source.Length || !double.IsFinite(result.Value)) return false; value = result.Value; return true; }
        private bool Expression(out Quantity result) { if (!Term(out result)) return false; while (true) { Space(); if (index >= source.Length || source[index] is not ('+' or '-')) return true; var operation = source[index++]; if (!Term(out var right) || result.Dimension != right.Dimension) return false; result = new(operation == '+' ? result.Value + right.Value : result.Value - right.Value, result.Dimension); } }
        private bool Term(out Quantity result) { if (!Factor(out result)) return false; while (true) { Space(); if (index >= source.Length || source[index] is not ('*' or '/')) return true; var operation = source[index++]; if (!Factor(out var right)) return false; var dimension = operation == '*' ? result.Dimension + right.Dimension : result.Dimension - right.Dimension; if (dimension is < 0 or > 1 || operation == '/' && Math.Abs(right.Value) <= double.Epsilon) return false; result = new(operation == '*' ? result.Value * right.Value : result.Value / right.Value, dimension); } }
        private bool Factor(out Quantity result) { Space(); result = default; if (index >= source.Length) return false; if (source[index] == '(') { index++; if (!Expression(out result)) return false; Space(); return index < source.Length && source[index++] == ')'; } var sign = 1d; if (source[index] is '+' or '-') sign = source[index++] == '-' ? -1d : 1d; Space(); var start = index; while (index < source.Length && (char.IsDigit(source[index]) || source[index] is '.' or 'e' or 'E' || source[index] is '+' or '-' && index > start && source[index - 1] is 'e' or 'E')) index++; if (start == index || !double.TryParse(source[start..index], NumberStyles.Float, CultureInfo.InvariantCulture, out var number)) return false; var dimension = 0; if (source.AsSpan(index).StartsWith(unit, StringComparison.Ordinal)) { index += unit.Length; dimension = 1; } result = new(sign * number, dimension); return true; }
        private void Space() { while (index < source.Length && char.IsWhiteSpace(source[index])) index++; }
        private readonly record struct Quantity(double Value, int Dimension);
    }
    private static KernelResult<WireFormFeatureAir> Fail(string code, string message) => KernelResult<WireFormFeatureAir>.Failure([new(
        Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error, $"{code}: {message}", "FirmamentV2.WireForm")]);
}

/// <summary>Exact circular sweep realization for 3D line/arc WireForm centerlines.</summary>
public static class WireFormBRepMaterializer
{
    private static readonly ToleranceContext Tolerance = ToleranceContext.Default;

    public static KernelResult<WireFormBuildResult> Build(WireFormFeatureAir feature)
    {
        var diagnostics = Validate(feature);
        if (diagnostics.Count > 0) return KernelResult<WireFormBuildResult>.Failure(diagnostics.Select(Error).ToArray());
        if (feature.Operations.Any(operation => operation is WireKnotPathAir))
            return WireKnotBRepMaterializer.Build(feature);
        if (feature.Operations.Any(operation => operation is WireCoilAir))
            return WireCoilBRepMaterializer.Build(feature);
        try
        {
            var count = feature.Operations.Count;
            var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
            var ringVertices = new VertexId[count + 1]; var ringEdges = new EdgeId[count + 1]; var vertexPoints = new Dictionary<VertexId, Point3D>();
            var states = feature.Operations.Select(x => x.Input).Append(feature.EndState).ToArray();
            var nextCurve = 1; var nextSurface = 1;
            for (var i = 0; i < states.Length; i++)
            {
                var state = states[i]; ringVertices[i] = builder.AddVertex();
                vertexPoints[ringVertices[i]] = state.Position + state.Up.ToVector() * feature.WireRadiusMm;
                ringEdges[i] = builder.AddEdge(ringVertices[i], ringVertices[i]);
                var curve = new CurveGeometryId(nextCurve++);
                geometry.AddCurve(curve, CurveGeometry.FromCircle(new Circle3Curve(state.Position, state.Tangent, feature.WireRadiusMm, state.Up)));
                bindings.AddEdgeBinding(new(ringEdges[i], curve, new ParameterInterval(0d, 2d * Math.PI)));
            }
            var faces = new List<FaceId>();
            for (var i = 0; i < count; i++)
            {
                var operation = feature.Operations[i]; var seam = builder.AddEdge(ringVertices[i], ringVertices[i + 1]);
                var seamCurve = new CurveGeometryId(nextCurve++); var surface = new SurfaceGeometryId(nextSurface++);
                if (operation is WireStraightAir straight)
                {
                    geometry.AddCurve(seamCurve, CurveGeometry.FromLine(new Line3Curve(vertexPoints[ringVertices[i]], straight.Input.Tangent)));
                    bindings.AddEdgeBinding(new(seam, seamCurve, new ParameterInterval(0d, straight.LengthMm)));
                    geometry.AddSurface(surface, SurfaceGeometry.FromCylinder(new CylinderSurface(straight.Input.Position, straight.Input.Tangent, feature.WireRadiusMm, straight.Input.Up)));
                }
                else if (operation is WireBendAir bend)
                {
                    var axis = bend.PlaneNormal.ToVector(); var up = bend.Input.Up.ToVector(); var axial = WireFormAuthoring.Dot(up, axis);
                    var seamCenter = bend.Center + axis * (axial * feature.WireRadiusMm);
                    var seamRadial = bend.StartRadial.ToVector() * bend.RadiusMm + (up - axis * axial) * feature.WireRadiusMm;
                    var seamRadius = seamRadial.Length; var seamReference = Direction3D.Create(seamRadial);
                    geometry.AddCurve(seamCurve, CurveGeometry.FromCircle(new Circle3Curve(seamCenter, bend.PlaneNormal, seamRadius, seamReference)));
                    bindings.AddEdgeBinding(new(seam, seamCurve, new ParameterInterval(0d, Math.Abs(bend.AngleRadians))));
                    geometry.AddSurface(surface, SurfaceGeometry.FromTorus(new TorusSurface(bend.Center, bend.PlaneNormal, bend.RadiusMm, feature.WireRadiusMm, bend.StartRadial)));
                }
                else throw new NotSupportedException("WireForm X0 admits Straight and Bend only.");
                // Walk the boundary with the face interior to the left of its
                // outward analytic normal (including both uses of the seam).
                var side = AddFace(builder, [(ringEdges[i], false), (seam, false), (ringEdges[i + 1], true), (seam, true)]);
                bindings.AddFaceBinding(new(side, surface)); faces.Add(side);
            }
            var startSurface = new SurfaceGeometryId(nextSurface++);
            geometry.AddSurface(startSurface, SurfaceGeometry.FromPlane(new PlaneSurface(feature.StartState.Position, Direction3D.Create(feature.StartState.Tangent.ToVector() * -1d), feature.StartState.Up)));
            var startFace = AddFace(builder, [(ringEdges[0], true)]); bindings.AddFaceBinding(new(startFace, startSurface)); faces.Add(startFace);
            var endSurface = new SurfaceGeometryId(nextSurface++);
            geometry.AddSurface(endSurface, SurfaceGeometry.FromPlane(new PlaneSurface(feature.EndState.Position, feature.EndState.Tangent, feature.EndState.Up)));
            var endFace = AddFace(builder, [(ringEdges[^1], false)]); bindings.AddFaceBinding(new(endFace, endSurface)); faces.Add(endFace);
            var shell = builder.AddShell(faces); builder.AddBody([shell]); var body = new BrepBody(builder.Model, geometry, bindings, vertexPoints);
            var bindingValidation = BrepBindingValidator.Validate(body, true);
            if (!bindingValidation.IsSuccess) return KernelResult<WireFormBuildResult>.Failure(bindingValidation.Diagnostics);
            var preflight = BrepExportPreflight.Validate(body);
            if (!preflight.IsValid) return KernelResult<WireFormBuildResult>.Failure(preflight.Diagnostics.Where(x => x.Severity == BrepExportPreflightSeverity.Error).Select(x => Error($"wireform-brep-invalid: {x.Code}: {x.Message}")).ToArray());
            var samples = feature.Operations.SelectMany(x => Sample(x, 64)).ToArray(); var r = feature.WireRadiusMm;
            var bounds = new[] { samples.Min(x => x.X) - r, samples.Min(x => x.Y) - r, samples.Min(x => x.Z) - r,
                samples.Max(x => x.X) + r, samples.Max(x => x.Y) + r, samples.Max(x => x.Z) + r };
            var volume = Math.PI * r * r * feature.TotalWireLengthMm;
            var mass = volume * 1e-9 * feature.Material.Structural!.Density.SiValue;
            return KernelResult<WireFormBuildResult>.Success(new(feature, body, volume, mass, bounds,
                ["wireform-state-replay-deterministic", "wireform-centerline-tangent", "wireform-self-intersection-clear", "wireform-analytic-circular-sweep", "wireform-geometric-minimum-radius"]));
        }
        catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NotSupportedException)
        { return KernelResult<WireFormBuildResult>.Failure([Error("wireform-brep-construction-failed: " + exception.Message)]); }
    }

    public static IReadOnlyList<string> Validate(WireFormFeatureAir feature)
    {
        var diagnostics = new List<string>();
        if (feature.Operations.Count == 0) diagnostics.Add("wireform-operations-empty: at least one operation is required.");
        foreach (var operation in feature.Operations)
        {
            if (operation.LengthMm <= Tolerance.Linear) diagnostics.Add($"wireform-operation-degenerate:{operation.Name}");
            if (operation is WireBendAir bend && bend.RadiusMm <= feature.WireRadiusMm + Tolerance.Linear)
                diagnostics.Add($"wireform-bend-radius-invalid:{bend.Name}: centerline radius must exceed wire radius.");
            if (operation is WireCoilAir coil && coil.MinimumSelfClearanceMm + Tolerance.Linear < 0d)
                diagnostics.Add($"wireform-coil-turn-clearance:{coil.Name}: adjacent turns overlap by {-coil.MinimumSelfClearanceMm:G6} mm.");
            if (operation is WireCoilAir approximated && approximated.ApproximationError.MaxMm > approximated.ApproximationToleranceMm)
                diagnostics.Add($"wireform-coil-approximation-tolerance:{approximated.Name}: measured centerline error {approximated.ApproximationError.MaxMm:G6} mm exceeds {approximated.ApproximationToleranceMm:G6} mm.");
            if (operation is WireKnotPathAir knot)
            {
                if (knot.ApproximationError.MaxMm > knot.ApproximationToleranceMm)
                    diagnostics.Add($"wireform-knot-approximation-limit:{knot.Name}: measured centerline error {knot.ApproximationError.MaxMm:G6} mm exceeds {knot.ApproximationToleranceMm:G6} mm.");
                if (feature.WireRadiusMm + Tolerance.Linear >= knot.Qualification.TubeRadiusLimitMm)
                {
                    var code = knot.Qualification.MinimumCurvatureRadiusMm < knot.Qualification.MinimumNonlocalDistanceMm / 2d
                        ? "wireform-knot-local-curvature-limit" : "wireform-knot-tube-self-intersection";
                    diagnostics.Add($"{code}:{knot.Name}: requested diameter {feature.DiameterMm:G12} mm exceeds the admitted maximum {knot.Qualification.MaximumAdmittedDiameterMm:G12} mm; closest nonlocal parameters t1={knot.Qualification.ClosestParameter1:G9}, t2={knot.Qualification.ClosestParameter2:G9}.");
                }
            }
        }
        var clearance = feature.DiameterMm;
        for (var i = 0; i + 1 < feature.Operations.Count; i++)
        {
            var distance = AdjacentNonlocalDistance(feature.Operations[i], feature.Operations[i + 1], clearance);
            if (distance + Tolerance.Linear < clearance)
                diagnostics.Add($"wireform-self-intersection:{feature.Operations[i].Name}:{feature.Operations[i + 1].Name}: adjacent operations collide away from their intended tangent join; conservative clearance is {distance:G6} mm, required {clearance:G6} mm.");
        }
        for (var i = 0; i < feature.Operations.Count; i++) for (var j = i + 2; j < feature.Operations.Count; j++)
        {
            var distance = ConservativeDistance(feature.Operations[i], feature.Operations[j]);
            if (distance + Tolerance.Linear < clearance)
                diagnostics.Add($"wireform-self-intersection:{feature.Operations[i].Name}:{feature.Operations[j].Name}: centerlines are {distance:G6} mm apart; required clearance is {clearance:G6} mm. Intentional contact is unsupported in X0.");
        }
        return diagnostics;
    }

    private static double AdjacentNonlocalDistance(WireFormOperationAir a, WireFormOperationAir b, double clearance)
    {
        const int count = 192;
        // The arclength exclusion below uses count intervals on both operations.
        // Ordinary Sample represents a straight with only its two endpoints;
        // using that here compared the entire line (including the shared join)
        // against an arc outside the join neighborhood, causing false contact.
        static IReadOnlyList<Point3D> AdjacentSamples(WireFormOperationAir operation) => operation is WireStraightAir line
            ? Enumerable.Range(0, count + 1).Select(i => line.Input.Position + (line.Output.Position - line.Input.Position) * ((double)i / count)).ToArray()
            : Sample(operation, count);
        var aa = AdjacentSamples(a); var bb = AdjacentSamples(b); var best = double.PositiveInfinity;
        // A two-diameter arclength neighborhood around the common endpoint is the
        // intended continuous tube join. Compare every chord pair outside it so
        // adjacent operations cannot retrace/collide elsewhere.
        for (var i = 0; i < aa.Count - 1; i++) for (var j = 0; j < bb.Count - 1; j++)
        {
            var fromJoinA = a.LengthMm * (count - i - 1d) / count;
            var fromJoinB = b.LengthMm * j / count;
            if (fromJoinA < clearance || fromJoinB < clearance) continue;
            best = Math.Min(best, SegmentDistance(aa[i], aa[i + 1], bb[j], bb[j + 1]));
        }
        return double.IsPositiveInfinity(best) ? double.PositiveInfinity : Math.Max(0d, best - Sagitta(a, count) - Sagitta(b, count));
    }

    private static double ConservativeDistance(WireFormOperationAir a, WireFormOperationAir b)
    {
        var aa = Sample(a, 96); var bb = Sample(b, 96); var best = double.PositiveInfinity;
        for (var i = 0; i < aa.Count - 1; i++) for (var j = 0; j < bb.Count - 1; j++) best = Math.Min(best, SegmentDistance(aa[i], aa[i + 1], bb[j], bb[j + 1]));
        // Chords alone can overestimate arc/arc or arc/line clearance. Subtract each
        // arc's maximum chord sagitta so this is a conservative lower bound and the
        // no-contact policy fails closed (at the cost of bounded false positives).
        return Math.Max(0d, best - Sagitta(a, 96) - Sagitta(b, 96));
    }
    private static double Sagitta(WireFormOperationAir operation, int count) => operation is WireBendAir bend
        ? bend.RadiusMm * (1d - Math.Cos(Math.Abs(bend.AngleRadians) / (2d * count))) : 0d;
    internal static IReadOnlyList<Point3D> Sample(WireFormOperationAir operation, int count) => operation switch
    {
        WireStraightAir line => [line.Input.Position, line.Output.Position],
        WireBendAir bend => Enumerable.Range(0, count + 1).Select(i => bend.Center + Rotate(bend.StartRadial.ToVector(), bend.PlaneNormal.ToVector(), Math.Abs(bend.AngleRadians) * i / count) * bend.RadiusMm).ToArray(),
        WireEvaluablePathAir path => Enumerable.Range(0, count + 1).Select(i => path.Evaluate((double)i / count)).ToArray(),
        _ => []
    };
    private static double SegmentDistance(Point3D p1, Point3D q1, Point3D p2, Point3D q2)
    {
        var d1 = q1 - p1; var d2 = q2 - p2; var r = p1 - p2; var a = Dot(d1, d1); var e = Dot(d2, d2); var f = Dot(d2, r); double s, t;
        if (a <= 1e-24 && e <= 1e-24) return (p1 - p2).Length;
        if (a <= 1e-24) { s = 0d; t = Math.Clamp(f / e, 0d, 1d); }
        else { var c = Dot(d1, r); if (e <= 1e-24) { t = 0d; s = Math.Clamp(-c / a, 0d, 1d); } else { var b = Dot(d1, d2); var denominator = a * e - b * b; s = denominator == 0d ? 0d : Math.Clamp((b * f - c * e) / denominator, 0d, 1d); t = (b * s + f) / e; if (t < 0d) { t = 0d; s = Math.Clamp(-c / a, 0d, 1d); } else if (t > 1d) { t = 1d; s = Math.Clamp((b - c) / a, 0d, 1d); } } }
        return (p1 + d1 * s - (p2 + d2 * t)).Length;
    }
    private static Vector3D Rotate(Vector3D vector, Vector3D axis, double angle) => vector * Math.Cos(angle) + WireFormAuthoring.Cross(axis, vector) * Math.Sin(angle) + axis * (Dot(axis, vector) * (1d - Math.Cos(angle)));
    private static double Dot(Vector3D a, Vector3D b) => WireFormAuthoring.Dot(a, b);
    private static FaceId AddFace(TopologyBuilder builder, IReadOnlyList<(EdgeId Edge, bool Reversed)> uses) { var loop = builder.AllocateLoopId(); var ids = uses.Select(_ => builder.AllocateCoedgeId()).ToArray(); for (var i = 0; i < uses.Count; i++) builder.AddCoedge(new(ids[i], uses[i].Edge, loop, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reversed)); builder.AddLoop(new Loop(loop, ids)); return builder.AddFace([loop]); }
    private static Core.Diagnostics.KernelDiagnostic Error(string message) => new(Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.WireForm");
}

public static class WireFormReportFactory
{
    internal static FirmamentWireAxisDatum AxisDatum(WireAxisCoilAir coil, double wireDiameterMm) => new(
        [coil.AxisOrigin.X, coil.AxisOrigin.Y, coil.AxisOrigin.Z],
        [coil.Axis.X, coil.Axis.Y, coil.Axis.Z],
        [coil.StartRadial.X, coil.StartRadial.Y, coil.StartRadial.Z],
        2 * coil.RadiusMm - wireDiameterMm);

    public static FirmamentWireFormReport Create(WireFormBuildResult built, string stepSha256, bool reimportedManifold)
    {
        var feature = built.Feature;
        var surfaces = built.Body.Topology.Faces.Select(face => built.Body.GetFaceSurface(face.Id).Kind).ToArray();
        var operations = feature.Operations.Select(operation => new FirmamentWireOperationReport(
            operation.Ordinal, operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "Helix", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.LengthMm,
            operation is WireBendAir bend ? bend.RadiusMm : null,
            operation is WireBendAir bendAngle ? bendAngle.AngleRadians * 180d / Math.PI : null,
            operation is WireBendAir bendPlane ? bendPlane.Plane : null, operation.StableId(feature.Name),
            State(operation.Input), State(operation.Output), operation switch { WireStraightAir => "LineSegment", WireBendAir => "CircularArc", WireCoilAir => "EvaluableWindingLaw", WireKnotPathAir => "EvaluablePeriodicKnotLaw", _ => "Unknown" },
            operation switch { WireStraightAir => "Cylinder", WireBendAir => "Torus", WireEvaluablePathAir => "NonRationalBSplineTube", _ => "Unknown" },
            operation is WireCoilAir coil ? coil.CoilKind : null, operation is WireCoilAir turns ? turns.Turns : null,
            operation is WireCoilAir handed ? handed.Handedness.ToString() : null,
            operation switch { WireAxisCoilAir axis => axis.PitchMm, WireSurfaceCoilAir surface => surface.AxialPitchMm, _ => null },
            operation is WireAxisCoilAir height ? height.HeightMm : null,
            operation is WireCoilAir phase ? phase.StartPhaseRadians * 180d / Math.PI : null,
            operation is WireSurfaceCoilAir support ? support.SupportName : null,
            operation is WireSurfaceCoilAir side ? side.Side.ToString() : null,
            operation is WireCoilAir progression ? progression.ProgressionLaw : null,
            operation is WireCoilAir self ? self.MinimumSelfClearanceMm : null,
            operation is WireCoilAir supportClearance ? supportClearance.SupportClearanceMm : null,
            operation is WireEvaluablePathAir approximation ? approximation.ApproximationToleranceMm : null,
            operation is WireEvaluablePathAir segmentCount ? segmentCount.ApproximationSegmentCount : null,
            operation is WireEvaluablePathAir maximumError ? maximumError.ApproximationError.MaxMm : null,
            operation is WireEvaluablePathAir rmsError ? rmsError.ApproximationError.RmsMm : null,
            operation is WireKnotPathAir knot ? knot.Family.ToString() : null,
            operation is WireKnotPathAir knotP ? knotP.P : null,
            operation is WireKnotPathAir knotQ ? knotQ.Q : null,
            operation is WireKnotPathAir knotComponents ? knotComponents.ComponentCount : null,
            operation is WireKnotPathAir knotClosed ? knotClosed.Closed : null,
            operation is WireKnotPathAir knotScale ? knotScale.ScaleMm : null,
            operation is WireKnotPathAir knotMajor ? knotMajor.MajorRadiusMm : null,
            operation is WireKnotPathAir knotMinor ? knotMinor.MinorRadiusMm : null,
            operation is WireKnotPathAir knotMinDistance ? knotMinDistance.Qualification.MinimumNonlocalDistanceMm : null,
            operation is WireKnotPathAir knotMinRadius ? knotMinRadius.Qualification.MinimumCurvatureRadiusMm : null,
            operation is WireKnotPathAir knotLimit ? knotLimit.Qualification.TubeRadiusLimitMm : null,
            operation is WireKnotPathAir knotRawFrame ? knotRawFrame.FrameClosure.RawClosureRotationRadians : null,
            operation is WireKnotPathAir knotCorrection ? knotCorrection.FrameClosure.AppliedCorrectionRadians : null,
            operation is WireKnotPathAir knotFinalFrame ? knotFinalFrame.FrameClosure.FinalClosureErrorRadians : null,
            operation is WireKnotPathAir knotError ? knotError.ApproximationError.MaxMm : null,
            operation is WireKnotPathAir knotRms ? knotRms.ApproximationError.RmsMm : null,
            operation is WireKnotPathAir knotT1 ? knotT1.Qualification.ClosestParameter1 : null,
            operation is WireKnotPathAir knotT2 ? knotT2.Qualification.ClosestParameter2 : null,
            operation is WireAxisCoilAir datum ? AxisDatum(datum, feature.DiameterMm) : null)).ToArray();
        return new(feature.Name, feature.DiameterMm, feature.Material.Identity.FirmamentPath, feature.Operations.Count,
            feature.Operations.Count(x => x is WireStraightAir), feature.Operations.Count(x => x is WireBendAir),
            feature.TotalStraightLengthMm, feature.TotalBendLengthMm, feature.TotalWireLengthMm, built.VolumeMm3, built.MassKilograms,
            Terminal("TerminalStart", feature.StartState, feature.DiameterMm), Terminal("TerminalEnd", feature.EndState, feature.DiameterMm),
            feature.Operations.OfType<WireBendAir>().Select(x => x.RadiusMm).DefaultIfEmpty(double.NaN).Min(),
            "CenterlineRadius", "GeometricOnly: centerline bend radius must exceed Diameter/2",
            feature.Operations.Any(x => x is WireKnotPathAir) ? "Closed KnotPath uses deterministic nonlocal periodic separation plus local curvature-radius qualification; excessive tube diameter fails closed." : "Nonadjacent operations use deterministic 3D chord witnesses with arc-sagitta error bounds; contact/overlap fails closed.",
            feature.FrameTransportPolicy, operations, built.Bounds,
            surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Torus),
            surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x is not (SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Torus or SurfaceGeometryKind.Plane)),
            0, 0, true, stepSha256, true, reimportedManifold,
            feature.Operations.Count(x => x is WireCoilAir), feature.TotalCoilLengthMm,
            feature.Operations.OfType<WireCoilAir>().Select(x => (double?)x.MinimumSelfClearanceMm).DefaultIfEmpty(null).Min(),
            surfaces.Count(x => x == SurfaceGeometryKind.BSplineSurfaceWithKnots), feature.Operations.Any(x => x is WireEvaluablePathAir) ? 3 : 0,
            feature.Operations.Any(x => x is WireKnotPathAir) ? "ExactEvaluablePeriodicKnotLaw->ClosureCorrectedDeterministicCubicNonRationalBSplineTube" : feature.Operations.Any(x => x is WireCoilAir) ? "ExactEvaluableWindingLaw->DeterministicCubicNonRationalBSplineTube" : "ExactAnalyticLineArcSweep",
            feature.Operations.Count(x => x is WireKnotPathAir), feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Family.ToString(),
            feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Qualification.MinimumNonlocalDistanceMm,
            feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Qualification.MinimumCurvatureRadiusMm,
            feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Qualification.TubeRadiusLimitMm,
            feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.FrameClosure.FinalClosureErrorRadians,
            built.Body.Topology.Vertices.Count(), built.Body.Topology.Edges.Count(), built.Body.Topology.Faces.Count(),
            built.Body.Bindings.PcurveBindings.Count(), BrepPcurveValidator.Validate(built.Body, 1e-6).MaximumReconstructionDeviation);
    }

    private static FirmamentWireStateReport State(WireState state) => new(V(state.Position), V(state.Tangent), V(state.Up), V(state.Right), state.AccumulatedLengthMm);
    private static FirmamentWireTerminalReport Terminal(string name, WireState state, double diameter) => new(name, V(state.Position), V(state.Tangent), V(state.Up), diameter);
    private static double[] V(Point3D p) => [p.X, p.Y, p.Z];
    private static double[] V(Direction3D d) => [d.X, d.Y, d.Z];
}