Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add SectionChain CLI and strengthen pcurve validation
Yuechen Li82a9ccf43ed3
diff --git a/Aetheris.CLI.Tests/SectionChainCliTests.cs b/Aetheris.CLI.Tests/SectionChainCliTests.csnew file mode 100644index 00000000..8af91991--- /dev/null+++ b/Aetheris.CLI.Tests/SectionChainCliTests.cs@@ -0,0 +1,60 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class SectionChainCliTests+{+ [Fact]+ public void FirmamentFileBuildInspectAndValidateUseTheSameSectionChainPipeline()+ {+ var input = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Canonical/SectionChain/two-section-ruled.firmament"));+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-section-chain-authored-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ try+ {+ var output = Path.Combine(directory, "authored.step");+ var buildOut = new StringWriter(); var buildErr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["section-chain", "build", input, "--out", output, "--json"], buildOut, buildErr));+ Assert.Equal(string.Empty, buildErr.ToString());+ using var built = JsonDocument.Parse(buildOut.ToString());+ Assert.Equal("TwoSectionRuled", built.RootElement.GetProperty("sectionChain").GetProperty("stableId").GetString());+ Assert.True(built.RootElement.GetProperty("pcurves").GetProperty("loopClosureValid").GetBoolean());++ foreach (var operation in new[] { "inspect", "validate" })+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["section-chain", operation, input, "--json"], stdout, stderr));+ using var report = JsonDocument.Parse(stdout.ToString());+ Assert.True(report.RootElement.GetProperty("success").GetBoolean());+ Assert.Equal(2, report.RootElement.GetProperty("sections").GetArrayLength());+ }+ }+ finally { Directory.Delete(directory, recursive: true); }+ }++ [Fact]+ public void FlagshipBuildWritesStepAndStructuredChainEvidence()+ {+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-section-chain-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ try+ {+ var output = Path.Combine(directory, "flagship.step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exit = CliRunner.Run(["section-chain", "build", "flagship", "--out", output, "--json"], stdout, stderr);+ Assert.Equal(0, exit);+ Assert.Equal(string.Empty, stderr.ToString());+ Assert.True(File.Exists(output));+ Assert.True(File.Exists(Path.ChangeExtension(output, ".evidence.json")));+ using var report = JsonDocument.Parse(stdout.ToString());+ Assert.Equal(8, report.RootElement.GetProperty("sectionChain").GetProperty("sectionCount").GetInt32());+ Assert.Equal(7, report.RootElement.GetProperty("sectionChain").GetProperty("transitionCount").GetInt32());+ Assert.Equal(0, report.RootElement.GetProperty("rationalProductSurfaces").GetInt32());+ Assert.True(report.RootElement.GetProperty("stepReimport").GetProperty("success").GetBoolean());+ }+ finally+ {+ Directory.Delete(directory, recursive: true);+ }+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 4fcb4cfc..785cf316 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -166,6 +166,7 @@ public static class CliRunnerprivate const string SheetMetalUsage = "Usage: aetheris sheetmetal recognize <part.step> [--plan <recognition.json>] [--json] | aetheris sheetmetal recover-flat <part.step> --out-dir <directory> [--recognition-plan <recognition.json>] [--json] | aetheris sheetmetal compare-flat <recovered-flat.json> <native.firmament> [--semantic] [--json] | aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--semantic] [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";private const string ExperimentalLoopChamferCorpusUsage = "Usage: aetheris experimental loop-chamfer-corpus --out-dir <dir> [--json]";private const string SculptureUsage = "Usage: aetheris sculpture build <sol-1.sculpture.json> [--out <sol-1.step>] [--evidence <sol-1.evidence.json>] [--preview <sol-1.preview.svg>] [--json]";+ private const string SectionChainUsage = "Usage: aetheris section-chain <build|inspect|validate> <file.firmament|flagship|twist|two-profile> [--out <model.step>] [--json]";internal static readonly JsonSerializerOptions JsonOptions = new(){@@ -229,6 +230,7 @@ public static class CliRunner"modules" => RunModules(args.Skip(1).ToArray(), stdout, stderr),"sheetmetal" => RunSheetMetal(args.Skip(1).ToArray(), stdout, stderr),"sculpture" => RunSculpture(args.Skip(1).ToArray(), stdout, stderr),+ "section-chain" => RunSectionChain(args.Skip(1).ToArray(), stdout, stderr),"reconstruct" => ReconstructionCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),_ => UnknownCommand(args[0], stderr)};@@ -533,6 +535,115 @@ public static class CliRunnerreturn 0;}+ private static int RunSectionChain(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || IsHelpFlag(args[0]))+ {+ stdout.WriteLine("Materialize an ordered semantic SectionChain through ruled pairwise transitions.");+ stdout.WriteLine(SectionChainUsage);+ return args.Length == 0 ? 1 : 0;+ }+ if (args.Length < 2 || args[0] is not ("build" or "inspect" or "validate")) { stderr.WriteLine(SectionChainUsage); return 1; }+ var operation = args[0]; var witness = args[1]; string? output = null; var json = false;+ for (var index = 2; index < args.Length; index++)+ {+ if (args[index] == "--json") json = true;+ else if (args[index] == "--out" && index + 1 < args.Length) output = Path.GetFullPath(args[++index]);+ else { stderr.WriteLine(SectionChainUsage); return 1; }+ }+ SectionChainMaterializationResult materialized;+ SectionChain chain;+ if (File.Exists(witness))+ {+ var authored = SectionChainAuthoringParser.Compile(File.ReadAllText(witness));+ if (!authored.IsSuccess || authored.Chain is null || authored.Materialization is null)+ {+ var failure = new { command = $"section-chain {operation}", success = false, input = Path.GetFullPath(witness), diagnostics = authored.Diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions)); else foreach (var diagnostic in authored.Diagnostics) stderr.WriteLine("error: " + diagnostic);+ return 1;+ }+ chain = authored.Chain; materialized = authored.Materialization;+ }+ else+ {+ chain = witness switch+ {+ "flagship" => SectionChainTemplates.ErgonomicFairing(),+ "twist" => SectionChainTemplates.TwistWitness(),+ "two-profile" => SectionChainTemplates.TwoProfileRuled(),+ _ => throw new ArgumentException($"Unknown SectionChain witness '{witness}'.")+ };+ materialized = SectionChainMaterializer.Materialize(chain);+ }+ output ??= Path.GetFullPath(Path.Combine("artifacts", "local", "surf-x3", chain.StableId + ".step"));+ if (!materialized.IsSuccess)+ {+ var failure = new { command = "section-chain build", success = false, witness, diagnostics = materialized.Diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions));+ else foreach (var diagnostic in materialized.Diagnostics) stderr.WriteLine($"error: {diagnostic.Code}: {diagnostic.Message}");+ return 1;+ }+ if (operation is "inspect" or "validate")+ {+ var inspection = new+ {+ command = $"section-chain {operation}", success = true, chain.StableId,+ sections = chain.Sections.Select(section => new { section.SectionId, section.Frame, profile = section.Profile.StableId, spans = section.Profile.Spans.Select(span => span.SpanId), seam = section.Profile.SeamSpanId }),+ chain.Correspondence,+ resolvedCorrespondence = Enumerable.Range(0, chain.Sections.Count - 1).Select(index => new+ {+ source = chain.Sections[index].SectionId, target = chain.Sections[index + 1].SectionId,+ resolution = chain.Correspondence.Any(item => item.SourceSectionId == chain.Sections[index].SectionId && item.TargetSectionId == chain.Sections[index + 1].SectionId) ? "Explicit" : "InferredSemanticIdentity",+ spans = chain.Sections[index].Profile.Spans.Select((span, spanIndex) => new { source = span.SpanId, target = chain.Sections[index + 1].Profile.Spans[spanIndex].SpanId })+ }),+ chain.TransitionPolicy, chain.StartTermination, chain.EndTermination,+ transitions = materialized.Transitions, pcurves = materialized.Pcurves, selfIntersection = materialized.SelfIntersection,+ diagnostics = materialized.Diagnostics+ };+ stdout.WriteLine(JsonSerializer.Serialize(inspection, JsonOptions));+ return 0;+ }+ var export = Step242Exporter.ExportBody(materialized.Body!, options: new Step242ExportOptions { ProductName = chain.StableId });+ if (!export.IsSuccess)+ {+ foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}");+ return 1;+ }+ Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Value);+ var reimport = Step242Importer.ImportBody(export.Value);+ var surfaces = materialized.Body!.Geometry.Surfaces.Select(item => item.Value.Kind).GroupBy(kind => kind)+ .ToDictionary(group => group.Key.ToString(), group => group.Count(), StringComparer.Ordinal);+ var report = new+ {+ command = "section-chain build", success = true, witness, output, sha256 = Hash(export.Value),+ sectionChain = new+ {+ chain.StableId, sectionCount = chain.Sections.Count, transitionCount = materialized.Transitions.Count,+ sections = chain.Sections.Select(section => new { section.SectionId, frame = section.Frame, profile = section.Profile.StableId, spans = section.Profile.Spans.Select(span => span.SpanId), seam = section.Profile.SeamSpanId }),+ correspondence = chain.Correspondence,+ resolvedCorrespondence = Enumerable.Range(0, chain.Sections.Count - 1).Select(index => new+ {+ source = chain.Sections[index].SectionId, target = chain.Sections[index + 1].SectionId,+ resolution = chain.Correspondence.Any(item => item.SourceSectionId == chain.Sections[index].SectionId && item.TargetSectionId == chain.Sections[index + 1].SectionId) ? "Explicit" : "InferredSemanticIdentity",+ spans = chain.Sections[index].Profile.Spans.Select((span, spanIndex) => new { source = span.SpanId, target = chain.Sections[index + 1].Profile.Spans[spanIndex].SpanId })+ }),+ transitionPolicy = chain.TransitionPolicy,+ startTermination = chain.StartTermination, endTermination = chain.EndTermination,+ structure = materialized.StructureKind, transitions = materialized.Transitions+ },+ topology = new { bodies = materialized.Body.Topology.Bodies.Count(), shells = materialized.Body.Topology.Shells.Count(), faces = materialized.Body.Topology.Faces.Count(), edges = materialized.Body.Topology.Edges.Count(), vertices = materialized.Body.Topology.Vertices.Count() },+ surfaceInventory = surfaces, rationalProductSurfaces = 0, facetedProductFallback = 0, pcurves = materialized.Pcurves,+ selfIntersection = materialized.SelfIntersection,+ stepReimport = new { success = reimport.IsSuccess, diagnostics = reimport.Diagnostics.Select(item => item.Message) },+ timingsMilliseconds = materialized.Timing+ };+ var evidencePath = Path.ChangeExtension(output, ".evidence.json");+ File.WriteAllText(evidencePath, JsonSerializer.Serialize(report, JsonOptions));+ if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));+ else stdout.WriteLine($"Built SectionChain '{chain.StableId}' ({chain.Sections.Count} sections, {materialized.Transitions.Count} transitions).\nSTEP: {output}\nEvidence: {evidencePath}\nSHA-256: {Hash(export.Value)}\nSTEP reimport: {(reimport.IsSuccess ? "succeeded" : "failed")}");+ return reimport.IsSuccess ? 0 : 1;+ }+private static int RunSculptingBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr){var compile = SculptingAuthoring.CompileFile(sourcePath);@@ -4194,6 +4305,7 @@ Model CanonicalPanel {stdout.WriteLine(" modules Inspect built-in engineering Modules and capabilities.");stdout.WriteLine(" sheetmetal Inspect/recover sheet semantics and generate manufacturing flat-pattern SVG.");stdout.WriteLine(" sculpture Build bounded non-manufacturing virtual sculpture artifacts.");+ stdout.WriteLine(" section-chain Build bounded ruled SectionChain qualification artifacts.");stdout.WriteLine(" verify Build/reimport and verify a model.");stdout.WriteLine(" reconstruct Experimentally reconstruct a structured mesh from triangle PLY input.");stdout.WriteLine();@@ -4211,6 +4323,7 @@ Model CanonicalPanel {stdout.WriteLine(" aetheris asm inspect bearing-module.firmament --json");stdout.WriteLine(" aetheris sheetmetal flatten bracket.firmament --step bracket-flat.step --svg bracket-flat.svg --json");stdout.WriteLine(" aetheris sculpture build fixtures/Canonical/VirtualSculpture/sol-1.sculpture.json");+ stdout.WriteLine(" aetheris section-chain build flagship --json");stdout.WriteLine(" aetheris reconstruct mesh scan.ply --mode fast --out scan-remesh.obj --report scan-report.json");stdout.WriteLine();stdout.WriteLine("Run 'aetheris <command> --help' for command-specific usage.");diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.csindex b2865738..cd72c0e8 100644--- a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs@@ -10,7 +10,12 @@ public sealed record BrepPcurveEvidence(double MaximumReconstructionDeviation,bool DomainValid,bool OrientationConsistent,- IReadOnlyList<string> Diagnostics);+ IReadOnlyList<string> Diagnostics)+{+ public bool LoopClosureValid { get; init; }+ public double MaximumUvLoopClosure { get; init; }+ public double RootMeanSquareReconstructionDeviation { get; init; }+}/// <summary>Independently samples face-local pcurves against their shared 3D edge geometry.</summary>public static class BrepPcurveValidator@@ -24,6 +29,10 @@ public static class BrepPcurveValidatorvar maximum = 0d;var domainValid = true;var orientationValid = true;+ var loopClosureValid = true;+ var maximumUvClosure = 0d;+ var squaredResidual = 0d;+ var residualSamples = 0;foreach (var coedge in body.Topology.Coedges.OrderBy(item => item.Id.Value)){@@ -60,6 +69,12 @@ public static class BrepPcurveValidatorvar parameter = interval.Start + ((interval.End - interval.Start) * fraction);var curveParameter = binding.SameSense ? parameter : interval.End - ((parameter - interval.Start));var uv = binding.Pcurve.Evaluate(curveParameter);+ if (!WithinSurfaceDomain(surface, uv, tolerance))+ {+ domainValid = false;+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:surface-domain:u={uv.U:R}:v={uv.V:R}");+ break;+ }var onSurface = Evaluate(surface, uv);var onCurve = Evaluate(curve, parameter);if (onSurface is null || onCurve is null)@@ -68,6 +83,8 @@ public static class BrepPcurveValidatorbreak;}coedgeMaximum = double.Max(coedgeMaximum, (onSurface.Value - onCurve.Value).Length);+ squaredResidual += (onSurface.Value - onCurve.Value).LengthSquared;+ residualSamples++;}maximum = double.Max(maximum, coedgeMaximum);if (coedgeMaximum > tolerance)@@ -84,11 +101,68 @@ public static class BrepPcurveValidatordiagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:orientation");}}++ var edge = body.Topology.GetEdge(coedge.EdgeId);+ var endVertex = coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId;+ if (body.TryGetVertexPoint(endVertex, out var endPoint))+ {+ var parameter = coedge.IsReversed ? interval.Start : interval.End;+ var uv = binding.Pcurve.Evaluate(binding.SameSense ? parameter : interval.End - (parameter - interval.Start));+ var reconstructed = Evaluate(surface, uv);+ if (reconstructed is null || (reconstructed.Value - endPoint).Length > tolerance)+ {+ orientationValid = false;+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:end-orientation");+ }+ }++ var next = body.Topology.GetCoedge(coedge.NextCoedgeId);+ if (body.Bindings.TryGetPcurveBinding(next.Id, out var nextBinding)+ && body.Bindings.TryGetEdgeBinding(next.EdgeId, out var nextEdgeBinding)+ && nextEdgeBinding.TrimInterval is { } nextInterval)+ {+ var currentLoopParameter = coedge.IsReversed ? interval.Start : interval.End;+ var nextLoopParameter = next.IsReversed ? nextInterval.End : nextInterval.Start;+ var currentUv = binding.Pcurve.Evaluate(binding.SameSense ? currentLoopParameter : interval.End - (currentLoopParameter - interval.Start));+ var nextUv = nextBinding.Pcurve.Evaluate(nextBinding.SameSense ? nextLoopParameter : nextInterval.End - (nextLoopParameter - nextInterval.Start));+ var closure = UvDistance(surface, currentUv, nextUv);+ maximumUvClosure = double.Max(maximumUvClosure, closure);+ if (closure > tolerance)+ {+ loopClosureValid = false;+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:uv-loop-closure={closure:R}:tolerance={tolerance:R}");+ }+ }}var count = body.Bindings.PcurveBindings.Count();- var valid = diagnostics.Count == 0 && maximum <= tolerance && domainValid && orientationValid;- return new(valid, body.Topology.Edges.Count(), count, maximum, domainValid, orientationValid, diagnostics);+ var valid = diagnostics.Count == 0 && maximum <= tolerance && domainValid && orientationValid && loopClosureValid;+ return new(valid, body.Topology.Edges.Count(), count, maximum, domainValid, orientationValid, diagnostics)+ {+ LoopClosureValid = loopClosureValid,+ MaximumUvLoopClosure = maximumUvClosure,+ RootMeanSquareReconstructionDeviation = residualSamples == 0 ? 0d : double.Sqrt(squaredResidual / residualSamples)+ };+ }++ private static bool WithinSurfaceDomain(SurfaceGeometry surface, SurfaceParameterPoint uv, double tolerance)+ {+ if (!double.IsFinite(uv.U) || !double.IsFinite(uv.V)) return false;+ if (surface.BSplineSurfaceWithKnots is not { } spline) return true;+ return uv.U >= spline.DomainStartU - tolerance && uv.U <= spline.DomainEndU + tolerance+ && uv.V >= spline.DomainStartV - tolerance && uv.V <= spline.DomainEndV + tolerance;+ }++ private static double UvDistance(SurfaceGeometry surface, SurfaceParameterPoint a, SurfaceParameterPoint b)+ {+ var du = a.U - b.U;+ if (surface.Kind == SurfaceGeometryKind.Cylinder)+ {+ while (du > double.Pi) du -= 2d * double.Pi;+ while (du < -double.Pi) du += 2d * double.Pi;+ }+ var dv = a.V - b.V;+ return double.Sqrt((du * du) + (dv * dv));}private static bool FiniteOrdered(ParameterInterval interval) => double.IsFinite(interval.Start) && double.IsFinite(interval.End) && interval.End >= interval.Start;diff --git a/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.csnew file mode 100644index 00000000..50698a27--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.cs@@ -0,0 +1,58 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Surfacing;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class SectionChainAuthoringTests+{+ [Theory]+ [InlineData("two-section-ruled.firmament", 2, SectionTermination.Cap, SectionTermination.Cap)]+ [InlineData("six-section-ergonomic.firmament", 6, SectionTermination.Cap, SectionTermination.Cap)]+ [InlineData("eight-section-ergonomic.firmament", 8, SectionTermination.Cap, SectionTermination.Cap)]+ [InlineData("open-chain.firmament", 2, SectionTermination.Open, SectionTermination.Open)]+ public void CanonicalFixtureCorpusQualifies(string name, int count, SectionTermination start, SectionTermination end)+ {+ var result = SectionChainAuthoringParser.Compile(FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/" + name));+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics));+ Assert.Equal(count, result.Chain!.Sections.Count);+ Assert.Equal(start, result.Chain.StartTermination);+ Assert.Equal(end, result.Chain.EndTermination);+ }++ [Fact]+ public void InvalidFoldoverFixtureFailsBeforeAnyStepArtifact()+ {+ var result = SectionChainAuthoringParser.Compile(FirmamentCorpusHarness.ReadFixtureText("fixtures/Invalid/SectionChain/transition-foldover.firmament"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.StartsWith("section-chain-transition-foldover:A->B/", StringComparison.Ordinal));+ Assert.Null(result.Materialization?.Body);+ }++ [Fact]+ public void CanonicalConceptPathsLowerThroughSemanticSectionChainIrAndMaterialize()+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/two-section-ruled.firmament");+ var result = SectionChainAuthoringParser.Compile(source);++ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics));+ Assert.Equal("TwoSectionRuled", result.Chain!.StableId);+ Assert.Equal(2, result.Chain.Sections.Count);+ Assert.All(result.Chain.Sections, section => Assert.Equal(["Bottom", "Right", "Top", "Left"], section.Profile.Spans.Select(span => span.SpanId)));+ Assert.Equal(SectionTermination.Cap, result.Chain.StartTermination);+ Assert.Equal(SectionTermination.Cap, result.Chain.EndTermination);+ Assert.NotNull(result.Materialization?.Body);+ Assert.Equal(result.Materialization!.Body!.Topology.Coedges.Count(), result.Materialization.Pcurves!.PcurveCount);+ Assert.True(result.Materialization.Pcurves.LoopClosureValid);+ }++ [Fact]+ public void DuplicateExplicitTargetCorrespondenceFailsBeforeMaterialization()+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/two-section-ruled.firmament")+ .Replace("Start: Cap", "Correspond Bad {\n From: Start\n To: End\n Bottom -> Bottom\n Right -> Bottom\n Top -> Top\n Left -> Left\n }\n Start: Cap", StringComparison.Ordinal);+ var result = SectionChainAuthoringParser.Compile(source);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Contains("section-chain-correspondence-duplicate:Start:End:Bottom", StringComparison.Ordinal));+ Assert.Null(result.Materialization);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 600212bd..04b2637a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -138,6 +138,9 @@ public static class ProfileAuthoringParserreturn profiles;}+ internal static ConstructionPlane? ResolveNamedConstructionPlane(string source, string frame, List<string> diagnostics)+ => ResolveConstructionPlane(source, frame, diagnostics);+private static void AddOrdinaryGuides(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics){foreach (Match match in Point.Matches(source))diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.csnew file mode 100644index 00000000..5fe418b4--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs@@ -0,0 +1,135 @@+using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Surfacing;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record SectionChainAuthoringResult(+ bool IsSuccess,+ SectionChain? Chain,+ SectionChainMaterializationResult? Materialization,+ IReadOnlyList<string> Diagnostics);++/// <summary>+/// Domain binder for Firmament SectionChain declarations. Profiles remain ordinary+/// Concept Path-derived Profiles; this layer only associates them with ordered frames,+/// seams, correspondence, transition law, and termination intent.+/// </summary>+public static class SectionChainAuthoringParser+{+ public static bool IsSectionChainSource(string source) =>+ Regex.IsMatch(source, @"\bSectionChain\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);++ public static SectionChainAuthoringResult Compile(string source, bool materialize = true)+ {+ ArgumentNullException.ThrowIfNull(source);+ var diagnostics = new List<string>();+ if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))+ diagnostics.Add("section-chain-units-invalid:millimetres-required");+ var declarations = Blocks(source, "SectionChain").ToArray();+ if (declarations.Length != 1)+ return Fail(diagnostics.Append($"section-chain-count-invalid:expected=1:actual={declarations.Length}"));++ var declaration = declarations[0];+ var profiles = ProfileAuthoringParser.BindPathDerivedProfiles(source, diagnostics);+ var transitionText = Field(declaration.Body, "Transition") ?? "Ruled";+ if (!Enum.TryParse<SectionTransitionPolicy>(transitionText, false, out var transition))+ diagnostics.Add($"section-chain-transition-policy-invalid:{transitionText}");+ var startText = Field(declaration.Body, "Start") ?? "Open";+ var endText = Field(declaration.Body, "End") ?? "Open";+ if (!Enum.TryParse<SectionTermination>(startText, false, out var start))+ diagnostics.Add($"section-chain-termination-invalid:Start:{startText}");+ if (!Enum.TryParse<SectionTermination>(endText, false, out var end))+ diagnostics.Add($"section-chain-termination-invalid:End:{endText}");++ var sections = new List<Section>();+ foreach (var authored in Blocks(declaration.Body, "Section"))+ {+ var frameName = Field(authored.Body, "Frame");+ var profileName = Field(authored.Body, "Profile");+ var seam = Field(authored.Body, "Seam");+ if (frameName is null) diagnostics.Add($"section-chain-frame-missing:{authored.Name}");+ ResolvedProfile2D? profile = null;+ if (profileName is null || !profiles.TryGetValue(profileName ?? string.Empty, out profile))+ diagnostics.Add($"section-chain-profile-unresolved:{authored.Name}:{profileName ?? "<missing>"}");+ var plane = frameName is null ? null : ProfileAuthoringParser.ResolveNamedConstructionPlane(source, frameName, diagnostics);+ if (frameName is not null && plane is null) diagnostics.Add($"section-chain-frame-unresolved:{authored.Name}:{frameName}");+ if (plane is null || profile is null) continue;+ var outer = profile.Loops.Single(loop => loop.IsOuter);+ if (profile.Loops.Count != 1) diagnostics.Add($"section-chain-profile-loop-count-invalid:{authored.Name}");+ var spans = outer.Segments.Select(segment => Convert(segment, diagnostics, authored.Name)).Where(item => item is not null).Cast<SectionProfileSpan>().ToArray();+ var seamId = seam ?? spans.FirstOrDefault()?.SpanId ?? string.Empty;+ sections.Add(new(authored.Name, new(plane.Origin, plane.AxisX, plane.AxisY, plane.AxisZ), new(profile.Name, spans, seamId)));+ }+ if (sections.Count < 2) diagnostics.Add("section-chain-section-count-invalid:minimum=2");++ var correspondence = new List<AdjacentSectionCorrespondence>();+ foreach (var authored in Blocks(declaration.Body, "Correspond"))+ {+ var from = Field(authored.Body, "From"); var to = Field(authored.Body, "To");+ if (from is null || to is null) { diagnostics.Add($"section-chain-correspondence-endpoint-missing:{authored.Name}"); continue; }+ var mappings = Regex.Matches(authored.Body, @"(?m)^\s*(?<a>[A-Za-z_]\w*)\s*->\s*(?<b>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant)+ .Cast<Match>().Select(match => new SectionSpanCorrespondence(match.Groups["a"].Value, match.Groups["b"].Value)).ToArray();+ foreach (var duplicate in mappings.GroupBy(item => item.TargetSpanId, StringComparer.Ordinal).Where(group => group.Count() > 1))+ diagnostics.Add($"section-chain-correspondence-duplicate:{from}:{to}:{duplicate.Key}");+ correspondence.Add(new(from, to, mappings));+ }++ if (diagnostics.Count != 0) return Fail(diagnostics);+ var chain = new SectionChain(declaration.Name, sections, correspondence, transition, start, end);+ if (!materialize) return new(true, chain, null, []);+ var result = SectionChainMaterializer.Materialize(chain);+ if (!result.IsSuccess)+ diagnostics.AddRange(result.Diagnostics.Select(item => $"{item.Code}:{item.Message}"));+ return new(result.IsSuccess, chain, result, diagnostics);++ SectionChainAuthoringResult Fail(IEnumerable<string> items) => new(false, null, null, items.Distinct(StringComparer.Ordinal).ToArray());+ }++ private static SectionProfileSpan? Convert(ResolvedProfileSegment2D segment, List<string> diagnostics, string section) => segment.Geometry switch+ {+ LineArcLineSegment2D line => new(segment.Name, new SectionProfileCurve.Line(new(line.Start.X, line.Start.Y), new(line.End.X, line.End.Y))),+ LineArcCircularArc2D arc => new(segment.Name, new SectionProfileCurve.Arc(new(arc.Center.X, arc.Center.Y), arc.Radius, arc.StartAngleRadians, arc.SweepAngleRadians)),+ _ => Unsupported(segment, diagnostics, section)+ };++ private static IEnumerable<Block> Blocks(string source, string keyword)+ {+ var regex = new Regex($@"\b{Regex.Escape(keyword)}(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{{", RegexOptions.CultureInvariant);+ for (var offset = 0; offset < source.Length;)+ {+ var match = regex.Match(source, offset); if (!match.Success) yield break;+ var open = source.IndexOf('{', match.Index + match.Length - 1); var close = MatchingBrace(source, open);+ if (close < 0) yield break;+ yield return new(match.Groups["name"].Success ? match.Groups["name"].Value : keyword, source[(open + 1)..close]);+ offset = close + 1;+ }+ }++ private static int MatchingBrace(string source, int open)+ {+ var depth = 0; var quoted = false;+ for (var index = open; index < source.Length; index++)+ {+ if (source[index] == '"' && (index == 0 || source[index - 1] != '\\')) quoted = !quoted;+ if (quoted) continue;+ if (source[index] == '{') depth++;+ else if (source[index] == '}' && --depth == 0) return index;+ }+ return -1;+ }++ private static string? Field(string body, string name)+ {+ var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(name)}\s*:\s*(?<value>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant);+ return match.Success ? match.Groups["value"].Value : null;+ }++ private static SectionProfileSpan? Unsupported(ResolvedProfileSegment2D segment, List<string> diagnostics, string section)+ {+ diagnostics.Add($"section-chain-profile-curve-unsupported:{section}:{segment.Name}:{segment.Geometry.GetType().Name}");+ return null;+ }++ private sealed record Block(string Name, string Body);+}diff --git a/Aetheris.Modules.Tests/SurfX3SectionChainTests.cs b/Aetheris.Modules.Tests/SurfX3SectionChainTests.csnew file mode 100644index 00000000..97904762--- /dev/null+++ b/Aetheris.Modules.Tests/SurfX3SectionChainTests.cs@@ -0,0 +1,155 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Surfacing;+using Xunit;++namespace Aetheris.Modules.Tests;++public sealed class SurfX3SectionChainTests+{+ [Fact]+ public void FlagshipMaterializesEightOrderedSectionsAsOneDeterministicClosedBody()+ {+ var first = SectionChainMaterializer.Materialize(SectionChainTemplates.ErgonomicFairing());+ var second = SectionChainMaterializer.Materialize(SectionChainTemplates.ErgonomicFairing());++ Assert.True(first.IsSuccess, string.Join("; ", first.Diagnostics.Select(item => $"{item.Code}: {item.Message}")));+ Assert.Equal(8, first.Chain.Sections.Count);+ Assert.Equal(7, first.Transitions.Count);+ Assert.Equal(SectionChainStructureKind.ClosedSolid, first.StructureKind);+ Assert.Equal(30, first.Body!.Topology.Faces.Count());+ Assert.All(first.Body.Topology.Coedges.GroupBy(coedge => coedge.EdgeId), uses => Assert.Equal(2, uses.Count()));+ Assert.NotNull(first.Pcurves);+ Assert.Equal(first.Body.Topology.Coedges.Count(), first.Pcurves!.PcurveCount);+ Assert.True(first.Pcurves.LoopClosureValid);+ Assert.True(first.SelfIntersection!.Passed);++ var exportedA = Step242Exporter.ExportBody(first.Body);+ var exportedB = Step242Exporter.ExportBody(second.Body!);+ Assert.True(exportedA.IsSuccess, string.Join("; ", exportedA.Diagnostics.Select(item => item.Message)));+ Assert.Equal(Hash(exportedA.Value), Hash(exportedB.Value));+ Assert.Contains("B_SPLINE_SURFACE_WITH_KNOTS", exportedA.Value);+ Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", exportedA.Value);+ Assert.True(Step242Importer.ImportBody(exportedA.Value).IsSuccess);+ }++ [Fact]+ public void MixedLineToSplineSpanUsesExactNonRationalRuledSurface()+ {+ var result = SectionChainMaterializer.Materialize(SectionChainTemplates.ErgonomicFairing());+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(item => item.Message)));+ var mixedTransition = result.Transitions[1];+ Assert.All(mixedTransition.Surfaces, surface =>+ {+ Assert.Equal(SurfaceGeometryKind.BSplineSurfaceWithKnots, surface.SurfaceClass);+ Assert.Equal(SurfaceMaterializationKind.ExactPolynomialBSpline, surface.MaterializationKind);+ });+ }++ [Fact]+ public void PlanarLinePairsAreRecognizedAsAnalyticPlanes()+ {+ var result = SectionChainMaterializer.Materialize(SectionChainTemplates.TwoProfileRuled());+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(item => item.Message)));+ Assert.All(result.Transitions.SelectMany(transition => transition.Surfaces),+ surface => Assert.Equal(SurfaceGeometryKind.Plane, surface.SurfaceClass));+ }++ [Fact]+ public void TwistIsFrameDrivenAndDeterministic()+ {+ var first = SectionChainMaterializer.Materialize(SectionChainTemplates.TwistWitness());+ var second = SectionChainMaterializer.Materialize(SectionChainTemplates.TwistWitness());+ Assert.True(first.IsSuccess, string.Join("; ", first.Diagnostics.Select(item => item.Message)));+ Assert.Equal(first.Transitions.Select(Canonical), second.Transitions.Select(Canonical));+ Assert.NotEqual(first.Chain.Sections[0].Frame.XAxis, first.Chain.Sections[^1].Frame.XAxis);+ }++ [Fact]+ public void ReplacingInteriorSectionRebuildsOnlyAdjacentTransitions()+ {+ var source = SectionChainTemplates.ErgonomicFairing();+ var old = source.Sections[3];+ var replacement = old with { Frame = old.Frame with { Origin = old.Frame.Origin + new Vector3D(0, 2, 0) } };+ var edited = SectionChainEditor.ReplaceSection(source, replacement);++ Assert.Equal(["PalmFront->Rise", "Rise->Peak"], edited.Delta.RebuiltTransitions);+ Assert.Equal(5, edited.Delta.PreservedTransitions.Count);+ Assert.Equal(["StartTermination", "EndTermination"], edited.Delta.PreservedTerminations);+ Assert.True(SectionChainMaterializer.Materialize(edited.Chain).IsSuccess);+ }++ [Fact]+ public void MissingSemanticCorrespondenceAndClockwiseProfileAreActionableFailures()+ {+ var source = SectionChainTemplates.TwoProfileRuled();+ var renamedSpans = source.Sections[1].Profile.Spans.Select((span, index) => span with { SpanId = $"Other{index}" }).ToArray();+ var missing = source with+ {+ Sections = [source.Sections[0], source.Sections[1] with { Profile = source.Sections[1].Profile with { Spans = renamedSpans, SeamSpanId = "Other0" } }],+ Correspondence = []+ };+ var result = SectionChainMaterializer.Materialize(missing);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, item => item.Code == "section-chain-correspondence-missing");++ var clockwise = source.Sections[0].Profile.Spans.Reverse().Select(span => span.Curve is SectionProfileCurve.Line line+ ? span with { Curve = new SectionProfileCurve.Line(line.End, line.Start) }+ : span).ToArray();+ var inverted = source with+ {+ Sections = [source.Sections[0] with { Profile = source.Sections[0].Profile with { Spans = clockwise, SeamSpanId = clockwise[0].SpanId } }, source.Sections[1]],+ Correspondence = []+ };+ var orientation = SectionChainMaterializer.Materialize(inverted);+ Assert.Contains(orientation.Diagnostics, item => item.Code == "section-chain-profile-orientation-mismatch");+ }++ [Fact]+ public void ExtremeTwistThatCollapsesRuledJacobiansIsRejected()+ {+ var source = SectionChainTemplates.TwoProfileRuled();+ var top = source.Sections[1];+ var invertedFrame = SectionFrame.Create(top.Frame.Origin, new Vector3D(-1, 0, 0), new Vector3D(0, -1, 0));+ var invalid = source with { Sections = [source.Sections[0], top with { Frame = invertedFrame }] };+ var result = SectionChainMaterializer.Materialize(invalid);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, item => item.Code == "section-chain-transition-foldover");+ }++ [Fact]+ public void CappedBodyPassesBindingAndStepPreflight()+ {+ var result = SectionChainMaterializer.Materialize(SectionChainTemplates.ErgonomicFairing());+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(item => item.Message)));+ Assert.True(BrepBindingValidator.Validate(result.Body!, true).IsSuccess);+ var preflight = BrepExportPreflight.Validate(result.Body!);+ Assert.True(preflight.IsValid, string.Join("; ", preflight.Diagnostics.Select(item => $"{item.Code}: {item.Message}")));+ }++ [Fact]+ public void NonNeighborTransitionCrossingFailsWithTypedConservativeEvidence()+ {+ var seed = SectionChainTemplates.TwoProfileRuled().Sections[0];+ var origins = new[] { 0d, 20d, 0d, 20d };+ var sections = origins.Select((z, index) => seed with+ {+ SectionId = $"S{index}", Frame = seed.Frame with { Origin = new Point3D(0, 0, z) },+ Profile = seed.Profile with { StableId = $"S{index}.Profile" }+ }).ToArray();+ var maps = Enumerable.Range(0, 3).Select(index => new AdjacentSectionCorrespondence($"S{index}", $"S{index + 1}",+ seed.Profile.Spans.Select(span => new SectionSpanCorrespondence(span.SpanId, span.SpanId)).ToArray())).ToArray();+ var result = SectionChainMaterializer.Materialize(new("self-crossing", sections, maps, SectionTransitionPolicy.Ruled, SectionTermination.Cap, SectionTermination.Cap));++ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, item => item.Code == "section-chain-self-intersection" && item.Message.Contains("S0->S1", StringComparison.Ordinal));+ }++ private static string Hash(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text)));+ private static string Canonical(SectionTransitionEvidence transition) => $"{transition.TransitionId}|" + string.Join(';',+ transition.Surfaces.Select(surface => $"{surface.SpanId}:{surface.SurfaceClass}:{surface.MaterializationKind}"));+}diff --git a/Aetheris.Surfacing/RuledSurfaceLowering.cs b/Aetheris.Surfacing/RuledSurfaceLowering.csindex 9505089a..ed44e02f 100644--- a/Aetheris.Surfacing/RuledSurfaceLowering.cs+++ b/Aetheris.Surfacing/RuledSurfaceLowering.cs@@ -32,6 +32,9 @@ public static class RuledSurfaceLoweringvar developability=ClassifyDevelopability(evaluateA!,evaluateB!,tangentA!,tangentB!);if (ir.BoundaryA is RuledBoundary.Line a && ir.BoundaryB is RuledBoundary.Line b){+ if (TryPlane(a, b, out var plane))+ return Success(ir, SurfaceGeometry.FromPlane(plane), Evaluate, developability,+ SurfaceMaterializationKind.ExactAnalytic, null);var surface = Bilinear(a.Start, a.End, b.Start, b.End);return Success(ir, SurfaceGeometry.FromBSplineSurfaceWithKnots(surface), Evaluate,developability,SurfaceMaterializationKind.ExactPolynomialBSpline,null);}@@ -57,6 +60,9 @@ public static class RuledSurfaceLowering}return Success(ir, exact, Evaluate,developability,SurfaceMaterializationKind.ExactAnalytic,null);}+ if (TryCompatiblePolynomialRuled(ir.BoundaryA, ir.BoundaryB, out var exactRuled))+ return Success(ir, SurfaceGeometry.FromBSplineSurfaceWithKnots(exactRuled), Evaluate, developability,+ SurfaceMaterializationKind.ExactPolynomialBSpline, null);var approximation=MaterializeRuled(ir.StableId,Evaluate,9);return Success(ir,SurfaceGeometry.FromBSplineSurfaceWithKnots(approximation.Surface),Evaluate,developability,SurfaceMaterializationKind.ApproximatedNonRationalBSpline,approximation.Certificate);@@ -73,6 +79,77 @@ public static class RuledSurfaceLoweringinternal static BSplineSurfaceWithKnots Bilinear(Point3D a0, Point3D a1, Point3D b0, Point3D b1) =>new(1, 1, [[a0, b0], [a1, b1]], "RULED_SURFACE", false, false, false, [2, 2], [2, 2], [0, 1], [0, 1], "UNSPECIFIED");++ private static bool TryPlane(RuledBoundary.Line a, RuledBoundary.Line b, out PlaneSurface plane)+ {+ var u = a.End - a.Start;+ var candidates = new[] { b.Start - a.Start, b.End - a.Start, b.End - b.Start };+ foreach (var candidate in candidates)+ {+ var cross = u.Cross(candidate);+ if (!cross.TryNormalize(out var normal)) continue;+ if (double.Abs((b.Start - a.Start).Dot(normal)) > 1e-10+ || double.Abs((b.End - a.Start).Dot(normal)) > 1e-10) continue;+ plane = new PlaneSurface(a.Start, Direction3D.Create(normal), Direction3D.Create(u));+ return true;+ }+ plane = default;+ return false;+ }++ private static bool TryCompatiblePolynomialRuled(RuledBoundary a, RuledBoundary b, out BSplineSurfaceWithKnots surface)+ {+ var spline = a as RuledBoundary.BSpline ?? b as RuledBoundary.BSpline;+ if (spline is null)+ {+ surface = null!;+ return false;+ }++ var basis = spline.Curve;+ if (!TryControls(a, basis, out var controlsA) || !TryControls(b, basis, out var controlsB))+ {+ surface = null!;+ return false;+ }++ var controls = controlsA.Select((point, index) => new[] { point, controlsB[index] }).ToArray();+ surface = new BSplineSurfaceWithKnots(basis.Degree, 1, controls, "RULED_SURFACE", false, false, false,+ basis.KnotMultiplicities, [2, 2], basis.KnotValues, [0d, 1d], "UNSPECIFIED");+ return true;++ static bool TryControls(RuledBoundary boundary, BSpline3Curve basis, out IReadOnlyList<Point3D> controls)+ {+ switch (boundary)+ {+ case RuledBoundary.BSpline candidate when Compatible(candidate.Curve, basis):+ controls = candidate.Curve.ControlPoints;+ return true;+ case RuledBoundary.Line line:+ var fullKnots = basis.FullKnots;+ var domain = basis.DomainEnd - basis.DomainStart;+ controls = Enumerable.Range(0, basis.ControlPoints.Count).Select(index =>+ {+ var greville = Enumerable.Range(1, basis.Degree)+ .Average(offset => fullKnots[index + offset]);+ var parameter = (greville - basis.DomainStart) / domain;+ return Lerp(line.Start, line.End, parameter);+ }).ToArray();+ return true;+ default:+ controls = [];+ return false;+ }+ }++ static bool Compatible(BSpline3Curve candidate, BSpline3Curve basis) =>+ candidate.Degree == basis.Degree+ && candidate.ControlPoints.Count == basis.ControlPoints.Count+ && candidate.KnotMultiplicities.SequenceEqual(basis.KnotMultiplicities)+ && candidate.KnotValues.SequenceEqual(basis.KnotValues)+ && double.Abs(candidate.DomainStart - basis.DomainStart) <= 1e-12+ && double.Abs(candidate.DomainEnd - basis.DomainEnd) <= 1e-12;+ }private static Vector3D CircleOffset(RuledBoundary.Circle c, double u) => ArcOffset(c.Normal,c.ReferenceAxis,c.Radius,u*2d*double.Pi);private static Vector3D ArcOffset(Direction3D normal,Direction3D reference,double radius,double angle) =>reference.ToVector()*(radius*double.Cos(angle))+normal.ToVector().Cross(reference.ToVector())*(radius*double.Sin(angle));diff --git a/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs b/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.csnew file mode 100644index 00000000..c5f80c1c--- /dev/null+++ b/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs@@ -0,0 +1,152 @@+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++internal sealed record SectionChainValidationPatch(int TransitionIndex, string TransitionId, string SpanId, RuledSurfacePatch Patch);+internal sealed record SectionChainSelfIntersectionValidationResult(bool Passed, SectionChainSelfIntersectionEvidence Evidence, string Detail);++/// <summary>+/// Deterministic validation-only proxy. It detects proper/coplanar crossings between+/// non-neighbouring transitions and between terminal caps and remote transitions.+/// The authoritative product remains the exact structured BRep.+/// </summary>+internal static class SectionChainSelfIntersectionValidator+{+ private const double Tolerance = 1e-6;+ private const int UDivisions = 24;+ private const int VDivisions = 6;++ public static SectionChainSelfIntersectionValidationResult Validate(SectionChain chain, IReadOnlyList<SectionChainValidationPatch> patches)+ {+ var proxies = patches.SelectMany(Triangulate).ToList();+ if (chain.StartTermination == SectionTermination.Cap) proxies.AddRange(Cap(chain.Sections[0], -1, "StartTermination"));+ if (chain.EndTermination == SectionTermination.Cap) proxies.AddRange(Cap(chain.Sections[^1], chain.Sections.Count - 1, "EndTermination"));+ var candidates = 0; var qualified = 0;+ for (var left = 0; left < proxies.Count; left++) for (var right = left + 1; right < proxies.Count; right++)+ {+ var a = proxies[left]; var b = proxies[right];+ if (SameOrAuthorizedNeighbor(a, b)) continue;+ if (!a.Bounds.Expanded(Tolerance).Intersects(b.Bounds.Expanded(Tolerance))) continue;+ candidates++;+ if (!TrianglesIntersect(a, b, Tolerance)) { qualified++; continue; }+ var detail = $"{a.Owner}:{a.Span} intersects {b.Owner}:{b.Span}; validation-only proxy={UDivisions}x{VDivisions}, tolerance={Tolerance:R}.";+ return Result(false, candidates, qualified, detail);+ }+ return Result(true, candidates, qualified,+ $"No non-neighbour transition or remote cap crossings were detected by the deterministic {UDivisions}x{VDivisions} ruled-surface proxy.");++ static bool SameOrAuthorizedNeighbor(Triangle a, Triangle b)+ {+ if (a.Owner == b.Owner) return true;+ if (a.IsCap || b.IsCap)+ {+ var cap = a.IsCap ? a : b; var transition = a.IsCap ? b : a;+ return cap.TransitionIndex == -1 ? transition.TransitionIndex == 0 : transition.TransitionIndex == cap.TransitionIndex - 1;+ }+ return Math.Abs(a.TransitionIndex - b.TransitionIndex) <= 1;+ }+ }++ private static SectionChainSelfIntersectionValidationResult Result(bool passed, int candidates, int qualified, string detail) =>+ new(passed, new("DeterministicBroadphasePlusTriangleProxy", passed, Tolerance,+ "Closed single-loop X3 chains; profile crossings and adjacent foldover are checked separately; tessellation is validation-only and is not a global proof.",+ candidates, qualified), detail);++ private static IEnumerable<Triangle> Triangulate(SectionChainValidationPatch patch)+ {+ for (var u = 0; u < UDivisions; u++) for (var v = 0; v < VDivisions; v++)+ {+ var u0 = u / (double)UDivisions; var u1 = (u + 1d) / UDivisions;+ var v0 = v / (double)VDivisions; var v1 = (v + 1d) / VDivisions;+ var a = patch.Patch.Evaluate(u0, v0); var b = patch.Patch.Evaluate(u1, v0);+ var c = patch.Patch.Evaluate(u1, v1); var d = patch.Patch.Evaluate(u0, v1);+ yield return Triangle.Create(patch.TransitionIndex, patch.TransitionId, patch.SpanId, false, a, b, c);+ yield return Triangle.Create(patch.TransitionIndex, patch.TransitionId, patch.SpanId, false, a, c, d);+ }+ }++ private static IEnumerable<Triangle> Cap(Section section, int transitionIndex, string owner)+ {+ var points = SampleProfile(section).ToArray();+ var center = new Point3D(points.Average(point => point.X), points.Average(point => point.Y), points.Average(point => point.Z));+ for (var index = 0; index < points.Length; index++)+ yield return Triangle.Create(transitionIndex, owner, section.SectionId, true, center, points[index], points[(index + 1) % points.Length]);+ }++ private static IEnumerable<Point3D> SampleProfile(Section section)+ {+ foreach (var span in section.Profile.Spans)+ {+ var count = span.Curve is SectionProfileCurve.Line ? 1 : 24;+ for (var index = 0; index < count; index++) yield return section.Frame.Transform(Evaluate(span.Curve, index / (double)count));+ }+ }++ private static SectionPoint2D Evaluate(SectionProfileCurve curve, double t) => curve switch+ {+ SectionProfileCurve.Line line => new(line.Start.X + (line.End.X - line.Start.X) * t, line.Start.Y + (line.End.Y - line.Start.Y) * t),+ SectionProfileCurve.Arc arc => new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + t * arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + t * arc.SweepAngleRadians)),+ SectionProfileCurve.PolynomialBSpline spline => Spline(spline, t),+ _ => default+ };++ private static SectionPoint2D Spline(SectionProfileCurve.PolynomialBSpline spline, double t)+ {+ var curve = new BSpline3Curve(spline.Degree, spline.ControlPoints.Select(point => new Point3D(point.X, point.Y, 0)).ToArray(), spline.KnotMultiplicities, spline.KnotValues, "UNSPECIFIED", false, false, "UNSPECIFIED");+ var point = curve.Evaluate(curve.DomainStart + t * (curve.DomainEnd - curve.DomainStart)); return new(point.X, point.Y);+ }++ private static bool TrianglesIntersect(Triangle a, Triangle b, double tolerance)+ {+ var ae = new[] { (a.A, a.B), (a.B, a.C), (a.C, a.A) }; var be = new[] { (b.A, b.B), (b.B, b.C), (b.C, b.A) };+ if (ae.Any(edge => SegmentTriangle(edge.Item1, edge.Item2, b, tolerance)) || be.Any(edge => SegmentTriangle(edge.Item1, edge.Item2, a, tolerance))) return true;+ var an = (a.B - a.A).Cross(a.C - a.A); var bn = (b.B - b.A).Cross(b.C - b.A);+ return an.TryNormalize(out var au) && bn.TryNormalize(out var bu) && Math.Abs(au.Dot(bu)) > 1d - 1e-8+ && Math.Abs((b.A - a.A).Dot(au)) <= tolerance && CoplanarOverlap(a, b, au);+ }++ private static bool SegmentTriangle(Point3D start, Point3D end, Triangle triangle, double tolerance)+ {+ var direction = end - start; var e1 = triangle.B - triangle.A; var e2 = triangle.C - triangle.A;+ var p = direction.Cross(e2); var determinant = e1.Dot(p);+ if (Math.Abs(determinant) <= tolerance) return false;+ var inverse = 1d / determinant; var s = start - triangle.A; var u = s.Dot(p) * inverse;+ if (u < -tolerance || u > 1d + tolerance) return false;+ var q = s.Cross(e1); var v = direction.Dot(q) * inverse;+ if (v < -tolerance || u + v > 1d + tolerance) return false;+ var t = e2.Dot(q) * inverse; return t >= -tolerance && t <= 1d + tolerance;+ }++ private static bool CoplanarOverlap(Triangle a, Triangle b, Vector3D normal)+ {+ var axis = Math.Abs(normal.X) > Math.Abs(normal.Y) ? (Math.Abs(normal.X) > Math.Abs(normal.Z) ? 0 : 2) : (Math.Abs(normal.Y) > Math.Abs(normal.Z) ? 1 : 2);+ var ap = new[] { Project(a.A, axis), Project(a.B, axis), Project(a.C, axis) }; var bp = new[] { Project(b.A, axis), Project(b.B, axis), Project(b.C, axis) };+ for (var i = 0; i < 3; i++) for (var j = 0; j < 3; j++) if (Segments2(ap[i], ap[(i + 1) % 3], bp[j], bp[(j + 1) % 3])) return true;+ return Inside(ap[0], bp) || Inside(bp[0], ap);+ }++ private static (double X, double Y) Project(Point3D point, int drop) => drop switch { 0 => (point.Y, point.Z), 1 => (point.X, point.Z), _ => (point.X, point.Y) };+ private static bool Segments2((double X, double Y) a, (double X, double Y) b, (double X, double Y) c, (double X, double Y) d)+ {+ static double O((double X, double Y) p, (double X, double Y) q, (double X, double Y) r) => (q.X - p.X) * (r.Y - p.Y) - (q.Y - p.Y) * (r.X - p.X);+ return O(a, b, c) * O(a, b, d) <= 0 && O(c, d, a) * O(c, d, b) <= 0;+ }+ private static bool Inside((double X, double Y) p, IReadOnlyList<(double X, double Y)> t)+ {+ var a = Sign(p, t[0], t[1]); var b = Sign(p, t[1], t[2]); var c = Sign(p, t[2], t[0]);+ return !(a < 0 || b < 0 || c < 0) || !(a > 0 || b > 0 || c > 0);+ static double Sign((double X, double Y) p1, (double X, double Y) p2, (double X, double Y) p3) => (p1.X - p3.X) * (p2.Y - p3.Y) - (p2.X - p3.X) * (p1.Y - p3.Y);+ }++ private readonly record struct Bounds(double MinX, double MinY, double MinZ, double MaxX, double MaxY, double MaxZ)+ {+ public Bounds Expanded(double amount) => new(MinX - amount, MinY - amount, MinZ - amount, MaxX + amount, MaxY + amount, MaxZ + amount);+ public bool Intersects(Bounds other) => MinX <= other.MaxX && MaxX >= other.MinX && MinY <= other.MaxY && MaxY >= other.MinY && MinZ <= other.MaxZ && MaxZ >= other.MinZ;+ }+ private sealed record Triangle(int TransitionIndex, string Owner, string Span, bool IsCap, Point3D A, Point3D B, Point3D C, Bounds Bounds)+ {+ public static Triangle Create(int index, string owner, string span, bool cap, Point3D a, Point3D b, Point3D c) => new(index, owner, span, cap, a, b, c,+ new(Math.Min(a.X, Math.Min(b.X, c.X)), Math.Min(a.Y, Math.Min(b.Y, c.Y)), Math.Min(a.Z, Math.Min(b.Z, c.Z)), Math.Max(a.X, Math.Max(b.X, c.X)), Math.Max(a.Y, Math.Max(b.Y, c.Y)), Math.Max(a.Z, Math.Max(b.Z, c.Z))));+ }+}diff --git a/Aetheris.Surfacing/SectionChainTemplates.cs b/Aetheris.Surfacing/SectionChainTemplates.csnew file mode 100644index 00000000..2342dae1--- /dev/null+++ b/Aetheris.Surfacing/SectionChainTemplates.cs@@ -0,0 +1,81 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++public static class SectionChainTemplates+{+ private static readonly string[] SpanIds = ["South", "East", "North", "West"];++ /// <summary>Eight changing, explicitly framed stations for the SURF-X3 flagship fairing.</summary>+ public static SectionChain ErgonomicFairing(string stableId = "surf-x3-section-chain-ergonomic-body")+ {+ var stations = new[]+ {+ Station("Nose", new(0, 0, 0), 5, 3.5, 0.0, 0, 0),+ Station("Front", new(0, 0, 10), 12, 7.0, 0.0, 0, 1),+ Station("PalmFront", new(0, 0, 26), 23, 12.0, 3.5, 1, 2),+ Station("Rise", new(0, 1, 43), 28, 15.0, 5.0, 2, 4),+ Station("Peak", new(0, 2, 59), 30, 16.5, 6.0, 2, 5),+ Station("PalmRear", new(0, 1, 75), 26, 14.0, 5.0, 1, 3),+ Station("Rear", new(0, 0, 89), 17, 9.0, 3.0, -1, 1),+ Station("Tail", new(0, 0, 100), 6, 4.0, 0.0, -1, 0),+ };+ return new(stableId, stations, ExplicitCorrespondence(stations), SectionTransitionPolicy.Ruled,+ SectionTermination.Cap, SectionTermination.Cap);+ }++ public static SectionChain TwistWitness(string stableId = "section-chain-twist")+ {+ var stations = new[]+ {+ Station("S0", new(0, 0, 0), 10, 7, 2, 0, 0),+ Station("S1", new(0, 0, 18), 11, 7, 2, 10, 0),+ Station("S2", new(0, 0, 36), 10, 6, 2, 20, 0),+ };+ return new(stableId, stations, ExplicitCorrespondence(stations), SectionTransitionPolicy.Ruled,+ SectionTermination.Cap, SectionTermination.Cap);+ }++ public static SectionChain TwoProfileRuled(string stableId = "section-chain-two-profile-ruled")+ {+ var stations = new[]+ {+ Station("Base", new(0, 0, 0), 10, 8, 0, 0, 0),+ Station("Top", new(0, 0, 20), 7, 5, 0, 0, 0),+ };+ return new(stableId, stations, ExplicitCorrespondence(stations), SectionTransitionPolicy.Ruled,+ SectionTermination.Cap, SectionTermination.Cap);+ }++ private static Section Station(string id, Point3D origin, double halfWidth, double halfHeight, double roundness,+ double clockDegrees, double tiltDegrees)+ {+ var clock = clockDegrees * Math.PI / 180d; var tilt = tiltDegrees * Math.PI / 180d;+ var x = new Vector3D(Math.Cos(clock) * Math.Cos(tilt), Math.Sin(clock) * Math.Cos(tilt), -Math.Sin(tilt));+ var normal = new Vector3D(Math.Cos(clock) * Math.Sin(tilt), Math.Sin(clock) * Math.Sin(tilt), Math.Cos(tilt));+ var y = normal.Cross(x);+ var frame = SectionFrame.Create(origin, x, y);+ return new(id, frame, Profile(id + ".Profile", halfWidth, halfHeight, roundness));+ }++ private static SectionProfile Profile(string id, double w, double h, double roundness)+ {+ var corners = new[] { new SectionPoint2D(-w, -h), new SectionPoint2D(w, -h), new SectionPoint2D(w, h), new SectionPoint2D(-w, h) };+ var controls = new[]+ {+ new[] { corners[0], new(-w / 3, -h - roundness), new(w / 3, -h - roundness), corners[1] },+ new[] { corners[1], new(w + roundness, -h / 3), new(w + roundness, h / 3), corners[2] },+ new[] { corners[2], new(w / 3, h + roundness), new(-w / 3, h + roundness), corners[3] },+ new[] { corners[3], new(-w - roundness, h / 3), new(-w - roundness, -h / 3), corners[0] },+ };+ var spans = Enumerable.Range(0, 4).Select(index => new SectionProfileSpan(SpanIds[index], roundness <= 0+ ? new SectionProfileCurve.Line(corners[index], corners[(index + 1) % 4])+ : new SectionProfileCurve.PolynomialBSpline(3, controls[index], [4, 4], [0d, 1d]) as SectionProfileCurve)).ToArray();+ return new(id, spans, SpanIds[0]);+ }++ private static IReadOnlyList<AdjacentSectionCorrespondence> ExplicitCorrespondence(IReadOnlyList<Section> sections) =>+ Enumerable.Range(0, sections.Count - 1).Select(index => new AdjacentSectionCorrespondence(+ sections[index].SectionId, sections[index + 1].SectionId,+ SpanIds.Select(span => new SectionSpanCorrespondence(span, span)).ToArray())).ToArray();+}diff --git a/Aetheris.Surfacing/SectionChains.cs b/Aetheris.Surfacing/SectionChains.csnew file mode 100644index 00000000..c6934cc3--- /dev/null+++ b/Aetheris.Surfacing/SectionChains.cs@@ -0,0 +1,588 @@+using System.Diagnostics;+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.Topology;++namespace Aetheris.Surfacing;++public readonly record struct SectionPoint2D(double X, double Y);++/// <summary>A complete, right-handed station frame. Profile coordinates are measured along XAxis/YAxis.</summary>+public sealed record SectionFrame(Point3D Origin, Direction3D XAxis, Direction3D YAxis, Direction3D Normal)+{+ public static SectionFrame Create(Point3D origin, Vector3D xAxis, Vector3D yAxis)+ {+ var x = Direction3D.Create(xAxis);+ var yProjected = yAxis - x.ToVector() * yAxis.Dot(x.ToVector());+ var y = Direction3D.Create(yProjected);+ var normal = Direction3D.Create(x.ToVector().Cross(y.ToVector()));+ return new(origin, x, y, normal);+ }++ public Point3D Transform(SectionPoint2D point) => Origin + XAxis.ToVector() * point.X + YAxis.ToVector() * point.Y;+}++public abstract record SectionProfileCurve+{+ public sealed record Line(SectionPoint2D Start, SectionPoint2D End) : SectionProfileCurve;+ public sealed record Arc(SectionPoint2D Center, double Radius, double StartAngleRadians, double SweepAngleRadians) : SectionProfileCurve;+ public sealed record PolynomialBSpline(+ int Degree,+ IReadOnlyList<SectionPoint2D> ControlPoints,+ IReadOnlyList<int> KnotMultiplicities,+ IReadOnlyList<double> KnotValues) : SectionProfileCurve;+}++public sealed record SectionProfileSpan(string SpanId, SectionProfileCurve Curve);+public sealed record SectionProfile(string StableId, IReadOnlyList<SectionProfileSpan> Spans, string SeamSpanId);+public sealed record Section(string SectionId, SectionFrame Frame, SectionProfile Profile);+public sealed record SectionSpanCorrespondence(string SourceSpanId, string TargetSpanId);+public sealed record AdjacentSectionCorrespondence(+ string SourceSectionId,+ string TargetSectionId,+ IReadOnlyList<SectionSpanCorrespondence> Spans,+ string Resolution = "Explicit");++public enum SectionTransitionPolicy { Ruled }+public enum SectionTermination { Cap, Open }+public enum SectionChainStructureKind { ClosedSolid, OpenShell }++public sealed record SectionChain(+ string StableId,+ IReadOnlyList<Section> Sections,+ IReadOnlyList<AdjacentSectionCorrespondence> Correspondence,+ SectionTransitionPolicy TransitionPolicy,+ SectionTermination StartTermination,+ SectionTermination EndTermination);++public sealed record SectionTransitionSurfaceEvidence(+ string SpanId,+ string SourceBoundaryId,+ string TargetBoundaryId,+ SurfaceGeometryKind SurfaceClass,+ SurfaceMaterializationKind MaterializationKind);++public sealed record SectionTransitionEvidence(+ string TransitionId,+ string SourceSectionId,+ string TargetSectionId,+ IReadOnlyList<SectionTransitionSurfaceEvidence> Surfaces);++public sealed record SectionChainTiming(+ double ProfilePreparationMilliseconds,+ double CorrespondenceResolutionMilliseconds,+ double PairwiseTransitionMilliseconds,+ double StitchingAndTerminationMilliseconds,+ double ValidationMilliseconds);++public sealed record SectionChainPcurveEvidence(+ int PcurveCount,+ int EdgeCount,+ double MaximumReconstructionDeviation,+ bool DomainValid,+ bool OrientationConsistent,+ bool LoopClosureValid,+ double Tolerance);++public sealed record SectionChainSelfIntersectionEvidence(+ string Method,+ bool Passed,+ double Tolerance,+ string AdmittedScope,+ int CandidatePairs,+ int QualifiedPairs);++public sealed record SectionChainMaterializationResult(+ SectionChain Chain,+ BrepBody? Body,+ SectionChainStructureKind StructureKind,+ IReadOnlyList<SectionTransitionEvidence> Transitions,+ IReadOnlyList<SurfacingDiagnostic> Diagnostics,+ SectionChainTiming Timing)+{+ public bool IsSuccess => Body is not null && Diagnostics.Count == 0;+ public SectionChainPcurveEvidence? Pcurves { get; init; }+ public SectionChainSelfIntersectionEvidence? SelfIntersection { get; init; }+}++public sealed record SectionChainEditDelta(+ string ReplacedSection,+ IReadOnlyList<string> RebuiltTransitions,+ IReadOnlyList<string> PreservedTransitions,+ IReadOnlyList<string> PreservedTerminations);++public static class SectionChainEditor+{+ public static (SectionChain Chain, SectionChainEditDelta Delta) ReplaceSection(SectionChain source, Section replacement)+ {+ var index = source.Sections.ToList().FindIndex(section => section.SectionId == replacement.SectionId);+ if (index < 0) throw new ArgumentException($"Section '{replacement.SectionId}' does not exist.", nameof(replacement));+ var sections = source.Sections.ToArray();+ sections[index] = replacement;+ var rebuilt = new List<string>();+ if (index > 0) rebuilt.Add(TransitionId(sections[index - 1].SectionId, sections[index].SectionId));+ if (index < sections.Length - 1) rebuilt.Add(TransitionId(sections[index].SectionId, sections[index + 1].SectionId));+ var preserved = Enumerable.Range(0, sections.Length - 1)+ .Select(i => TransitionId(sections[i].SectionId, sections[i + 1].SectionId))+ .Where(id => !rebuilt.Contains(id, StringComparer.Ordinal)).ToArray();+ return (source with { Sections = sections }, new(replacement.SectionId, rebuilt, preserved,+ ["StartTermination", "EndTermination"]));+ }++ internal static string TransitionId(string source, string target) => $"{source}->{target}";+}++/// <summary>+/// Materializes the bounded X3 lane: one closed outer loop, ordered one-to-one semantic spans,+/// ruled adjacent transitions, and Cap/Open terminals. Every internal section edge is allocated+/// once and reused by both neighbouring transition faces.+/// </summary>+public static class SectionChainMaterializer+{+ private const double Tolerance = 1e-8;++ public static SectionChainMaterializationResult Materialize(SectionChain chain)+ {+ ArgumentNullException.ThrowIfNull(chain);+ var profileStarted = Stopwatch.GetTimestamp();+ var prepared = chain.Sections.Select(Prepare).ToArray();+ var profileMs = Stopwatch.GetElapsedTime(profileStarted).TotalMilliseconds;++ var correspondenceStarted = Stopwatch.GetTimestamp();+ var diagnostics = Validate(chain, prepared).ToList();+ var resolved = diagnostics.Count == 0 ? ResolveCorrespondence(chain) : [];+ var correspondenceMs = Stopwatch.GetElapsedTime(correspondenceStarted).TotalMilliseconds;+ if (diagnostics.Count > 0)+ return Failure(chain, diagnostics, profileMs, correspondenceMs);++ var transitionStarted = Stopwatch.GetTimestamp();+ var transitionPatches = new List<(PreparedTransition Transition, RuledSurfacePatch[] Patches)>();+ for (var transitionIndex = 0; transitionIndex < chain.Sections.Count - 1; transitionIndex++)+ {+ var source = prepared[transitionIndex];+ var target = prepared[transitionIndex + 1];+ var map = resolved[transitionIndex];+ var patches = new RuledSurfacePatch[source.Boundaries.Length];+ for (var spanIndex = 0; spanIndex < source.Boundaries.Length; spanIndex++)+ {+ var targetIndex = map[spanIndex];+ var transitionId = SectionChainEditor.TransitionId(source.Section.SectionId, target.Section.SectionId);+ var ir = new RuledSurfaceIr($"{chain.StableId}:{transitionId}:{source.Section.Profile.Spans[spanIndex].SpanId}",+ RuledConstructionKind.RuledTransition, source.Boundaries[spanIndex], target.Boundaries[targetIndex],+ new(source.Boundaries[spanIndex].StableId, source.Section.SectionId, "source-section-span"),+ new(target.Boundaries[targetIndex].StableId, target.Section.SectionId, "target-section-span"));+ var lowered = RuledSurfaceLowering.Lower(ir);+ if (!lowered.IsSuccess || lowered.Patch is null)+ foreach (var item in lowered.Diagnostics)+ diagnostics.Add(new SurfacingDiagnostic("section-chain-transition-invalid",+ $"{transitionId}/{source.Section.Profile.Spans[spanIndex].SpanId}: {item.Message}"));+ else patches[spanIndex] = lowered.Patch;+ if (lowered.Patch is { } patch && HasFoldover(patch))+ diagnostics.Add(new("section-chain-transition-foldover",+ $"{transitionId}/{source.Section.Profile.Spans[spanIndex].SpanId}: sampled ruled Jacobian is singular or reverses orientation."));+ }+ if (diagnostics.Count == 0)+ transitionPatches.Add((new(transitionIndex, source, target, map), patches));+ }+ var transitionMs = Stopwatch.GetElapsedTime(transitionStarted).TotalMilliseconds;+ if (diagnostics.Count > 0)+ return Failure(chain, diagnostics, profileMs, correspondenceMs, transitionMs);++ var selfIntersection = SectionChainSelfIntersectionValidator.Validate(chain,+ transitionPatches.SelectMany(entry => entry.Patches.Select((patch, span) =>+ new SectionChainValidationPatch(entry.Transition.Index,+ SectionChainEditor.TransitionId(entry.Transition.Source.Section.SectionId, entry.Transition.Target.Section.SectionId),+ entry.Transition.Source.Section.Profile.Spans[span].SpanId, patch))).ToArray());+ if (!selfIntersection.Passed)+ {+ diagnostics.Add(new("section-chain-self-intersection", selfIntersection.Detail));+ return Failure(chain, diagnostics, profileMs, correspondenceMs, transitionMs);+ }++ var stitchStarted = Stopwatch.GetTimestamp();+ BrepBody? body = null;+ IReadOnlyList<SectionTransitionEvidence> evidence = [];+ try+ {+ (body, evidence) = BuildBody(chain, prepared, transitionPatches);+ }+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException)+ {+ diagnostics.Add(new("section-chain-materialization-failed", exception.Message));+ }+ var stitchMs = Stopwatch.GetElapsedTime(stitchStarted).TotalMilliseconds;++ var validationStarted = Stopwatch.GetTimestamp();+ SectionChainPcurveEvidence? pcurveEvidence = null;+ if (body is not null)+ {+ var bindings = BrepBindingValidator.Validate(body, true);+ if (!bindings.IsSuccess)+ foreach (var item in bindings.Diagnostics)+ diagnostics.Add(new SurfacingDiagnostic("section-chain-brep-invalid", item.Message));+ var edgeUseCounts = body.Topology.Coedges.GroupBy(coedge => coedge.EdgeId).ToDictionary(group => group.Key, group => group.Count());+ int? expectedUses = chain.StartTermination == SectionTermination.Cap && chain.EndTermination == SectionTermination.Cap ? 2 : null;+ if (expectedUses is not null && edgeUseCounts.Any(pair => pair.Value != expectedUses.Value))+ diagnostics.Add(new("section-chain-shared-topology-invalid", "A capped chain must use every edge exactly twice."));+ var pcurves = BrepPcurveValidator.Validate(body, 1e-5d, requireEveryCoedge: true);+ pcurveEvidence = new(pcurves.PcurveCount, pcurves.EdgeCount, pcurves.MaximumReconstructionDeviation,+ pcurves.DomainValid, pcurves.OrientationConsistent,+ pcurves.LoopClosureValid, 1e-5d);+ if (!pcurves.IsValid)+ foreach (var item in pcurves.Diagnostics)+ diagnostics.Add(new("section-chain-pcurve-error", item));+ }+ var validationMs = Stopwatch.GetElapsedTime(validationStarted).TotalMilliseconds;+ if (diagnostics.Count > 0) body = null;+ return new(chain, body, Structure(chain), evidence, diagnostics,+ new(profileMs, correspondenceMs, transitionMs, stitchMs, validationMs))+ { Pcurves = pcurveEvidence, SelfIntersection = selfIntersection.Evidence };+ }++ private static IReadOnlyList<SurfacingDiagnostic> Validate(SectionChain chain, IReadOnlyList<PreparedSection> sections)+ {+ var diagnostics = new List<SurfacingDiagnostic>();+ if (string.IsNullOrWhiteSpace(chain.StableId)) diagnostics.Add(new("section-chain-id-invalid", "SectionChain requires a stable identity."));+ if (chain.TransitionPolicy != SectionTransitionPolicy.Ruled) diagnostics.Add(new("section-chain-transition-policy-invalid", "X3 qualifies Ruled transitions only."));+ if (sections.Count < 2) diagnostics.Add(new("section-chain-section-count-invalid", "SectionChain requires at least two ordered sections."));+ if (sections.Select(section => section.Section.SectionId).Distinct(StringComparer.Ordinal).Count() != sections.Count)+ diagnostics.Add(new("section-chain-section-id-duplicate", "Section identities must be unique."));++ foreach (var prepared in sections)+ {+ var section = prepared.Section;+ var frame = section.Frame;+ var x = frame.XAxis.ToVector(); var y = frame.YAxis.ToVector(); var n = frame.Normal.ToVector();+ if (double.Abs(x.Dot(y)) > Tolerance || double.Abs(x.Dot(n)) > Tolerance || double.Abs(y.Dot(n)) > Tolerance+ || x.Cross(y).Dot(n) < 1d - Tolerance)+ diagnostics.Add(new("section-chain-frame-invalid", $"Section '{section.SectionId}' frame must be orthonormal and right-handed."));+ if (section.Profile.Spans.Count == 0)+ diagnostics.Add(new("section-chain-profile-empty", $"Section '{section.SectionId}' profile has no spans."));+ if (!section.Profile.Spans.Any(span => span.SpanId == section.Profile.SeamSpanId))+ diagnostics.Add(new("section-chain-profile-seam-ambiguous", $"Section '{section.SectionId}' seam '{section.Profile.SeamSpanId}' is not a profile span."));+ if (section.Profile.Spans.Select(span => span.SpanId).Distinct(StringComparer.Ordinal).Count() != section.Profile.Spans.Count)+ diagnostics.Add(new("section-chain-profile-span-duplicate", $"Section '{section.SectionId}' span identities must be unique."));+ for (var index = 0; index < prepared.StartPoints.Length; index++)+ {+ var next = (index + 1) % prepared.StartPoints.Length;+ if ((prepared.EndPoints[index] - prepared.StartPoints[next]).Length > Tolerance)+ diagnostics.Add(new("section-chain-profile-open", $"Section '{section.SectionId}' spans {index + 1} and {next + 1} do not form a closed loop."));+ if ((prepared.EndPoints[index] - prepared.StartPoints[index]).Length <= Tolerance)+ diagnostics.Add(new("section-chain-profile-span-degenerate", $"Section '{section.SectionId}' span '{section.Profile.Spans[index].SpanId}' is degenerate."));+ }+ if (SignedArea(section.Profile) <= Tolerance)+ diagnostics.Add(new("section-chain-profile-orientation-mismatch", $"Section '{section.SectionId}' profile must be counter-clockwise in its frame and use a stable seam."));+ if (ProfileSelfIntersects(section.Profile))+ diagnostics.Add(new("section-chain-profile-self-intersection", $"Section '{section.SectionId}' profile intersects itself."));+ }++ if (sections.Count > 1)+ {+ var count = sections[0].Section.Profile.Spans.Count;+ foreach (var section in sections.Skip(1))+ if (section.Section.Profile.Spans.Count != count)+ diagnostics.Add(new("section-chain-correspondence-topology-mismatch", "X3 requires the same semantic span count in every section."));+ }++ for (var index = 0; index < sections.Count - 1; index++)+ {+ var source = sections[index]; var target = sections[index + 1];+ if ((target.Section.Frame.Origin - source.Section.Frame.Origin).Length <= Tolerance)+ diagnostics.Add(new("section-chain-section-spacing-invalid", $"Sections '{source.Section.SectionId}' and '{target.Section.SectionId}' are coincident."));+ var correspondence = chain.Correspondence.SingleOrDefault(item => item.SourceSectionId == source.Section.SectionId && item.TargetSectionId == target.Section.SectionId);+ var semanticIdentity = source.Section.Profile.Spans.Select(span => span.SpanId).SequenceEqual(target.Section.Profile.Spans.Select(span => span.SpanId));+ if (correspondence is null && !semanticIdentity)+ diagnostics.Add(new("section-chain-correspondence-missing", $"{source.Section.SectionId}:{target.Section.SectionId}: explicit span correspondence is required."));+ if (correspondence is not null)+ {+ if (correspondence.Spans.Count != source.Section.Profile.Spans.Count)+ diagnostics.Add(new("section-chain-correspondence-incomplete", $"{source.Section.SectionId}:{target.Section.SectionId}: expected {source.Section.Profile.Spans.Count} span mappings."));+ for (var span = 0; span < Math.Min(correspondence.Spans.Count, source.Section.Profile.Spans.Count); span++)+ {+ if (correspondence.Spans[span].SourceSpanId != source.Section.Profile.Spans[span].SpanId+ || correspondence.Spans[span].TargetSpanId != target.Section.Profile.Spans[span].SpanId)+ diagnostics.Add(new("section-chain-correspondence-order-invalid", $"{source.Section.SectionId}:{target.Section.SectionId}: mapping must preserve ordered seam-relative span topology."));+ }+ }+ }+ return diagnostics;+ }++ private static IReadOnlyList<int[]> ResolveCorrespondence(SectionChain chain)+ {+ var result = new List<int[]>();+ for (var index = 0; index < chain.Sections.Count - 1; index++)+ {+ var source = chain.Sections[index]; var target = chain.Sections[index + 1];+ var explicitMap = chain.Correspondence.SingleOrDefault(item => item.SourceSectionId == source.SectionId && item.TargetSectionId == target.SectionId);+ result.Add(explicitMap is null+ ? Enumerable.Range(0, source.Profile.Spans.Count).ToArray()+ : explicitMap.Spans.Select(mapping => target.Profile.Spans.ToList().FindIndex(span => span.SpanId == mapping.TargetSpanId)).ToArray());+ }+ return result;+ }++ private static (BrepBody Body, IReadOnlyList<SectionTransitionEvidence> Evidence) BuildBody(+ SectionChain chain,+ IReadOnlyList<PreparedSection> sections,+ IReadOnlyList<(PreparedTransition Transition, RuledSurfacePatch[] Patches)> transitions)+ {+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();+ var points = new Dictionary<VertexId, Point3D>(); var nextCurve = 1; var nextSurface = 1;+ var vertices = new VertexId[sections.Count][]; var profileEdges = new EdgeId[sections.Count][];+ for (var sectionIndex = 0; sectionIndex < sections.Count; sectionIndex++)+ {+ var section = sections[sectionIndex]; var count = section.Boundaries.Length;+ vertices[sectionIndex] = new VertexId[count]; profileEdges[sectionIndex] = new EdgeId[count];+ for (var span = 0; span < count; span++)+ {+ vertices[sectionIndex][span] = builder.AddVertex();+ points[vertices[sectionIndex][span]] = section.StartPoints[span];+ }+ for (var span = 0; span < count; span++)+ {+ profileEdges[sectionIndex][span] = builder.AddEdge(vertices[sectionIndex][span], vertices[sectionIndex][(span + 1) % count]);+ BindBoundary(profileEdges[sectionIndex][span], section.Boundaries[span]);+ }+ }++ var faces = new List<FaceId>(); var transitionEvidence = new List<SectionTransitionEvidence>();+ foreach (var entry in transitions)+ {+ var transition = entry.Transition; var sourceIndex = transition.Index; var targetIndex = sourceIndex + 1;+ var longitudinal = new EdgeId[transition.Source.Boundaries.Length];+ for (var vertex = 0; vertex < longitudinal.Length; vertex++)+ {+ longitudinal[vertex] = builder.AddEdge(vertices[sourceIndex][vertex], vertices[targetIndex][vertex]);+ BindLine(longitudinal[vertex], points[vertices[sourceIndex][vertex]], points[vertices[targetIndex][vertex]]);+ }+ var surfaces = new List<SectionTransitionSurfaceEvidence>();+ for (var span = 0; span < transition.Source.Boundaries.Length; span++)+ {+ var next = (span + 1) % longitudinal.Length;+ var face = AddFace(builder,+ [(profileEdges[sourceIndex][span], false), (longitudinal[next], false),+ (profileEdges[targetIndex][transition.Map[span]], true), (longitudinal[span], true)]);+ var surfaceId = new SurfaceGeometryId(nextSurface++);+ geometry.AddSurface(surfaceId, entry.Patches[span].ExactSurface);+ bindings.AddFaceBinding(new(face, surfaceId)); faces.Add(face);+ surfaces.Add(new(transition.Source.Section.Profile.Spans[span].SpanId,+ transition.Source.Boundaries[span].StableId, transition.Target.Boundaries[transition.Map[span]].StableId,+ entry.Patches[span].ExactSurface.Kind, entry.Patches[span].MaterializationKind));+ }+ transitionEvidence.Add(new(SectionChainEditor.TransitionId(transition.Source.Section.SectionId, transition.Target.Section.SectionId),+ transition.Source.Section.SectionId, transition.Target.Section.SectionId, surfaces));+ }++ if (chain.StartTermination == SectionTermination.Cap)+ {+ var face = AddFace(builder, profileEdges[0].Reverse().Select(edge => (edge, true)).ToArray());+ var surfaceId = new SurfaceGeometryId(nextSurface++);+ geometry.AddSurface(surfaceId, SurfaceGeometry.FromPlane(new PlaneSurface(sections[0].Section.Frame.Origin,+ Direction3D.Create(-sections[0].Section.Frame.Normal.ToVector()), sections[0].Section.Frame.XAxis)));+ bindings.AddFaceBinding(new(face, surfaceId)); faces.Add(face);+ }+ if (chain.EndTermination == SectionTermination.Cap)+ {+ var last = sections.Count - 1;+ var face = AddFace(builder, profileEdges[last].Select(edge => (edge, false)).ToArray());+ var surfaceId = new SurfaceGeometryId(nextSurface++);+ geometry.AddSurface(surfaceId, SurfaceGeometry.FromPlane(new PlaneSurface(sections[last].Section.Frame.Origin,+ sections[last].Section.Frame.Normal, sections[last].Section.Frame.XAxis)));+ bindings.AddFaceBinding(new(face, surfaceId)); faces.Add(face);+ }+ var shell = builder.AddShell(faces); builder.AddBody([shell]);+ var pcurves = BoundedPcurveBuilder.Populate(builder.Model, geometry, bindings, 1e-5d);+ if (!pcurves.IsSuccess)+ throw new InvalidOperationException("SectionChain face-local pcurve construction failed: "+ + string.Join(" | ", pcurves.Diagnostics.Select(item => $"{item.Code}:{item.Entity}:{item.Message}")));+ return (new BrepBody(builder.Model, geometry, bindings, points), transitionEvidence);++ void BindBoundary(EdgeId edge, RuledBoundary boundary)+ {+ var curveId = new CurveGeometryId(nextCurve++);+ switch (boundary)+ {+ case RuledBoundary.Line line:+ var delta = line.End - line.Start;+ geometry.AddCurve(curveId, CurveGeometry.FromLine(new Line3Curve(line.Start, Direction3D.Create(delta))));+ bindings.AddEdgeBinding(new(edge, curveId, new(0, delta.Length)));+ break;+ case RuledBoundary.Arc arc when arc.SweepAngleRadians > 0:+ geometry.AddCurve(curveId, CurveGeometry.FromCircle(new Circle3Curve(arc.Center, arc.Normal, arc.Radius, arc.ReferenceAxis)));+ bindings.AddEdgeBinding(new(edge, curveId, new(arc.StartAngleRadians, arc.StartAngleRadians + arc.SweepAngleRadians)));+ break;+ case RuledBoundary.Circle circle:+ geometry.AddCurve(curveId, CurveGeometry.FromCircle(new Circle3Curve(circle.Center, circle.Normal, circle.Radius, circle.ReferenceAxis)));+ bindings.AddEdgeBinding(new(edge, curveId, new(0, 2d * Math.PI)));+ break;+ case RuledBoundary.BSpline spline:+ geometry.AddCurve(curveId, CurveGeometry.FromBSpline(spline.Curve));+ bindings.AddEdgeBinding(new(edge, curveId, new(spline.Curve.DomainStart, spline.Curve.DomainEnd)));+ break;+ default: throw new InvalidOperationException($"Boundary '{boundary.StableId}' cannot be bound as a forward profile edge.");+ }+ }+ void BindLine(EdgeId edge, Point3D start, Point3D end)+ {+ var curveId = new CurveGeometryId(nextCurve++); var delta = end - start;+ geometry.AddCurve(curveId, CurveGeometry.FromLine(new Line3Curve(start, Direction3D.Create(delta))));+ bindings.AddEdgeBinding(new(edge, curveId, new(0, delta.Length)));+ }+ }++ private static PreparedSection Prepare(Section section)+ {+ var boundaries = section.Profile.Spans.Select(span => Boundary(section, span)).ToArray();+ return new(section, boundaries, boundaries.Select(Start).ToArray(), boundaries.Select(End).ToArray());+ }++ private static RuledBoundary Boundary(Section section, SectionProfileSpan span)+ {+ var frame = section.Frame; var id = $"{section.SectionId}.{span.SpanId}";+ return span.Curve switch+ {+ SectionProfileCurve.Line line => new RuledBoundary.Line(id, frame.Transform(line.Start), frame.Transform(line.End)),+ SectionProfileCurve.Arc arc => new RuledBoundary.Arc(id, frame.Transform(arc.Center), frame.Normal, arc.Radius,+ frame.XAxis, arc.StartAngleRadians, arc.SweepAngleRadians),+ SectionProfileCurve.PolynomialBSpline spline => new RuledBoundary.BSpline(id, new BSpline3Curve(spline.Degree,+ spline.ControlPoints.Select(frame.Transform).ToArray(), spline.KnotMultiplicities, spline.KnotValues,+ "UNSPECIFIED", false, false, "UNSPECIFIED")),+ _ => throw new InvalidOperationException($"Profile span '{span.SpanId}' has no admitted curve representation.")+ };+ }++ private static Point3D Start(RuledBoundary boundary) => boundary switch+ {+ RuledBoundary.Line line => line.Start,+ RuledBoundary.Arc arc => arc.Center + ArcOffset(arc, arc.StartAngleRadians),+ RuledBoundary.Circle circle => circle.Center + circle.ReferenceAxis.ToVector() * circle.Radius,+ RuledBoundary.BSpline spline => spline.Curve.Evaluate(spline.Curve.DomainStart),+ _ => throw new InvalidOperationException()+ };++ private static Point3D End(RuledBoundary boundary) => boundary switch+ {+ RuledBoundary.Line line => line.End,+ RuledBoundary.Arc arc => arc.Center + ArcOffset(arc, arc.StartAngleRadians + arc.SweepAngleRadians),+ RuledBoundary.Circle circle => circle.Center + circle.ReferenceAxis.ToVector() * circle.Radius,+ RuledBoundary.BSpline spline => spline.Curve.Evaluate(spline.Curve.DomainEnd),+ _ => throw new InvalidOperationException()+ };++ private static Vector3D ArcOffset(RuledBoundary.Arc arc, double angle) =>+ arc.ReferenceAxis.ToVector() * (arc.Radius * Math.Cos(angle))+ + arc.Normal.ToVector().Cross(arc.ReferenceAxis.ToVector()) * (arc.Radius * Math.Sin(angle));++ private static double SignedArea(SectionProfile profile)+ {+ var points = Sample(profile, 12); var area = 0d;+ for (var i = 0; i < points.Count; i++)+ {+ var next = points[(i + 1) % points.Count];+ area += points[i].X * next.Y - next.X * points[i].Y;+ }+ return area / 2d;+ }++ private static bool ProfileSelfIntersects(SectionProfile profile)+ {+ var points = Sample(profile, 16);+ for (var i = 0; i < points.Count; i++)+ {+ var a = points[i]; var b = points[(i + 1) % points.Count];+ for (var j = i + 2; j < points.Count; j++)+ {+ if (i == 0 && j == points.Count - 1) continue;+ var c = points[j]; var d = points[(j + 1) % points.Count];+ if (SegmentsIntersect(a, b, c, d)) return true;+ }+ }+ return false;+ }++ private static IReadOnlyList<SectionPoint2D> Sample(SectionProfile profile, int curveSamples)+ {+ var result = new List<SectionPoint2D>();+ foreach (var span in profile.Spans)+ {+ var count = span.Curve is SectionProfileCurve.Line ? 1 : curveSamples;+ for (var i = 0; i < count; i++) result.Add(Evaluate(span.Curve, i / (double)count));+ }+ return result;+ }++ private static SectionPoint2D Evaluate(SectionProfileCurve curve, double parameter) => curve switch+ {+ SectionProfileCurve.Line line => Lerp(line.Start, line.End, parameter),+ SectionProfileCurve.Arc arc => new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + parameter * arc.SweepAngleRadians),+ arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + parameter * arc.SweepAngleRadians)),+ SectionProfileCurve.PolynomialBSpline spline => EvaluateSpline(spline, parameter),+ _ => default+ };++ private static SectionPoint2D EvaluateSpline(SectionProfileCurve.PolynomialBSpline spline, double parameter)+ {+ var curve = new BSpline3Curve(spline.Degree, spline.ControlPoints.Select(point => new Point3D(point.X, point.Y, 0)).ToArray(),+ spline.KnotMultiplicities, spline.KnotValues, "UNSPECIFIED", false, false, "UNSPECIFIED");+ var point = curve.Evaluate(curve.DomainStart + Math.Clamp(parameter, 0, 1) * (curve.DomainEnd - curve.DomainStart));+ return new(point.X, point.Y);+ }++ private static bool SegmentsIntersect(SectionPoint2D a, SectionPoint2D b, SectionPoint2D c, SectionPoint2D d)+ {+ static double Orientation(SectionPoint2D p, SectionPoint2D q, SectionPoint2D r) =>+ (q.X - p.X) * (r.Y - p.Y) - (q.Y - p.Y) * (r.X - p.X);+ var o1 = Orientation(a, b, c); var o2 = Orientation(a, b, d); var o3 = Orientation(c, d, a); var o4 = Orientation(c, d, b);+ return o1 * o2 < -Tolerance && o3 * o4 < -Tolerance;+ }++ private static bool HasFoldover(RuledSurfacePatch patch)+ {+ var normals = new Vector3D[17, 5];+ for (var uIndex = 0; uIndex <= 16; uIndex++)+ {+ var u = uIndex / 16d;+ for (var vIndex = 0; vIndex <= 4; vIndex++)+ {+ var v = vIndex / 4d; const double h = 1e-5;+ var du = patch.Evaluate(Math.Min(1, u + h), v) - patch.Evaluate(Math.Max(0, u - h), v);+ var dv = patch.Evaluate(u, Math.Min(1, v + h)) - patch.Evaluate(u, Math.Max(0, v - h));+ if (!du.TryNormalize(out var tangentU) || !dv.TryNormalize(out var tangentV)) return true;+ var jacobian = tangentU.Cross(tangentV);+ if (!jacobian.TryNormalize(out var normal)) return true;+ normals[uIndex, vIndex] = normal;+ if (uIndex > 0 && normals[uIndex - 1, vIndex].Dot(normal) < -0.05d) return true;+ if (vIndex > 0 && normals[uIndex, vIndex - 1].Dot(normal) < -0.05d) return true;+ }+ }+ return false;+ }++ private static SectionPoint2D Lerp(SectionPoint2D a, SectionPoint2D b, double t) =>+ new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t);++ 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 index = 0; index < ids.Length; index++)+ builder.AddCoedge(new Coedge(ids[index], uses[index].Edge, loop, ids[(index + 1) % ids.Length],+ ids[(index + ids.Length - 1) % ids.Length], uses[index].Reversed));+ builder.AddLoop(new Loop(loop, ids));+ return builder.AddFace([loop]);+ }++ private static SectionChainStructureKind Structure(SectionChain chain) =>+ chain.StartTermination == SectionTermination.Cap && chain.EndTermination == SectionTermination.Cap+ ? SectionChainStructureKind.ClosedSolid : SectionChainStructureKind.OpenShell;++ private static SectionChainMaterializationResult Failure(SectionChain chain, IReadOnlyList<SurfacingDiagnostic> diagnostics,+ double profileMs, double correspondenceMs, double transitionMs = 0) =>+ new(chain, null, Structure(chain), [], diagnostics, new(profileMs, correspondenceMs, transitionMs, 0, 0));++ private sealed record PreparedSection(Section Section, RuledBoundary[] Boundaries, Point3D[] StartPoints, Point3D[] EndPoints);+ private sealed record PreparedTransition(int Index, PreparedSection Source, PreparedSection Target, int[] Map);+}diff --git a/Aetheris.Surfacing/SurfacingModule.cs b/Aetheris.Surfacing/SurfacingModule.csindex 2bea0104..627b934a 100644--- a/Aetheris.Surfacing/SurfacingModule.cs+++ b/Aetheris.Surfacing/SurfacingModule.cs@@ -14,6 +14,7 @@ public static class SurfacingModulepublic const string PanelCapability = "Surfacing.Panel";public const string BoundedSculptingCapability = "Surfacing.BoundedSculpting";public const string JudgedBlendCapability = "Surfacing.JudgedBlend";+ public const string SectionChainCapability = "Surfacing.SectionChain";public static AetherisModule Definition { get; } = new(Id, "Surfacing", Version,@@ -24,7 +25,8 @@ public static class SurfacingModulenew(BoundaryPatchCapability,Id,Version,"Four-boundary G0 patch preserving boundary intent."),new(PanelCapability,Id,Version,"Bounded oriented engineering surface with ordered semantic boundary edges and developability evidence."),new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion and trimmed ReplaceRegion authority, qualified intersection-derived boundaries, face-local pcurves, inner openings, imported-face grafting, mixed G0/G1/G2 contracts, persistent associations, and inspectable GeometricDelta evidence."),- new(JudgedBlendCapability,Id,Version,"Qualified crown-to-planar-shoulder BlendBoundary with exact polynomial G1/G2 candidates, validity-before-utility fairness judgment, deterministic trace, and rational-free STEP realization.")],+ new(JudgedBlendCapability,Id,Version,"Qualified crown-to-planar-shoulder BlendBoundary with exact polynomial G1/G2 candidates, validity-before-utility fairness judgment, deterministic trace, and rational-free STEP realization."),+ new(SectionChainCapability,Id,Version,"Ordered framed profiles with explicit semantic one-to-one span correspondence, ruled adjacent transitions, shared-section topology, and Cap/Open termination.")],["Surfacing.PanelConcept", "Surfacing.SurfacePatchConcept"], ["Surfacing.RuledCanopyPanel","Surfacing.HyperbolicParaboloid","Surfacing.ParabolicCylinder","Surfacing.EllipticParaboloid","Surfacing.Helicoid"],["Surface construction -> PanelIR -> semantic edges", "Panel edge Interface/Mate -> deterministic G0 evidence", "PanelIR -> bounded BRep-backed STEP export envelope"],["panel-incomplete-boundary", "panel-boundary-orientation-inconsistent","panel-mate-endpoint-mismatch","panel-mate-g0-failure","panel-mate-g1-failure","panel-mate-g1-unknown","panel-mate-g2-failure","panel-mate-g2-unknown","surfacing-panel-thickness-invalid","sculpt-outside-authorized-region","sculpt-preservation-failed","sculpt-self-intersection","surf-boundary-g0-violation","surf-boundary-g1-violation","surf-boundary-g2-violation","surf-blend-g2-unsatisfied","surf-blend-no-eligible-candidates","surf-blend-locality-violation","surf-selector-target-replaced","surf-surface-export-normalization-failed"],diff --git a/docs/public/README.md b/docs/public/README.mdindex 9827ade2..d09705c2 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -4,7 +4,7 @@ This directory is the only authoritative in-repository guide to behavior shippedStart with [Getting Started](getting-started.md), then use these guides:-- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [bounded mathematical sculpting](firmament/sculpting.md), [PlasticShell](firmament/plastic-shell.md), [Circular Sweep](firmament/sweep.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)+- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [bounded mathematical sculpting](firmament/sculpting.md), [Section chains](firmament/section-chains.md), [PlasticShell](firmament/plastic-shell.md), [Circular Sweep](firmament/sweep.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)- Non-manufacturing work: [Virtual Sculpture and Sol 1](virtual-sculpture.md)- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)- Interoperability: [Forge Host Protocol v1](forge/interop.md)diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.mdindex 78dbfb89..311d3108 100644--- a/docs/public/firmament/sculpting.md+++ b/docs/public/firmament/sculpting.md@@ -199,4 +199,4 @@ The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. The X1 flagship add## Current limits-The admitted X2 materializer is limited to one rectangular housing crown transitioning to its coplanar analytic shoulder through the exact polynomial family above. It does not provide arbitrary intersection networks, general Plane/Cylinder or Cylinder/Cylinder blends, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, variable blend laws, a free control-net optimizer, N-way junctions, Loft, Shell, Draft, or arbitrary patch networks. Existing exact Fillet and Chamfer authoring and materializers are unchanged: a fillet is conceptually a constrained blend specialization, while a planar chamfer should remain planar rather than being forced through freeform machinery.+The admitted X2 materializer is limited to one rectangular housing crown transitioning to its coplanar analytic shoulder through the exact polynomial family above. It does not provide arbitrary intersection networks, general Plane/Cylinder or Cylinder/Cylinder blends, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, variable blend laws, a free control-net optimizer, N-way junctions, Shell, Draft, or arbitrary patch networks. [SectionChain](section-chains.md) now has standalone Firmament text authoring and a ruled-loft materialization path, but BodyState `AddSectionChain`/`RemoveSectionChain` remain unqualified. Existing exact Fillet and Chamfer authoring and materializers are unchanged: a fillet is conceptually a constrained blend specialization, while a planar chamfer should remain planar rather than being forced through freeform machinery.diff --git a/docs/public/firmament/section-chains.md b/docs/public/firmament/section-chains.mdnew file mode 100644index 00000000..b9cbc909--- /dev/null+++ b/docs/public/firmament/section-chains.md@@ -0,0 +1,94 @@+# Section chains++A SectionChain builds a surface or closed body from an ordered sequence of framed profiles. It is the low-level ruled-loft substrate for cases where the profile itself changes from station to station.++```text+Section0 -> Section1 -> Section2 -> Section3+```++Each `Section` owns a stable `SectionId`, a complete right-handed frame (`Origin`, `XAxis`, `YAxis`, `Normal`), and one closed outer `SectionProfile`. A profile is an ordered loop of semantic spans such as `South`, `East`, `North`, and `West`; its declared seam identifies the first span. X3's qualified profile curves are line, circular arc, and non-rational polynomial B-spline.++Adjacent sections use one-to-one semantic span correspondence. Matching IDs may establish strong semantic identity, while explicit `AdjacentSectionCorrespondence` records the mapping in the flagship. Aetheris does not silently use nearest points, nearest edges, or tessellated vertex indices to define topology. The X3 lane requires the same span count and seam-relative order on both sides of a transition.++`Ruled` is the only qualified transition policy. Each matched pair is sent through the existing `RuledSurfaceIr` lowering path, so there is one mathematical ruled implementation. Exact planar line pairs become `PLANE`; compatible line/B-spline and B-spline/B-spline pairs become exact non-rational `B_SPLINE_SURFACE_WITH_KNOTS`; coaxial compatible circles retain existing cylinder/cone recognition. Rational product surfaces are prohibited.++Every internal section edge is allocated once. The preceding and following transition faces use that same edge, curve, vertices, and parameter direction. Editing one section therefore rebuilds only its two adjacent transition identities; distant transitions and terminal conditions remain preserved in `SectionChainEditDelta`.++Every transition and cap coedge also owns a face-local pcurve. Aetheris builds these through the same bounded Plane/Cylinder/non-rational-B-spline machinery used by trimmed SURF faces, then independently checks reconstruction deviation, surface-domain containment, both oriented endpoints, and UV loop closure. The two faces meeting at an internal section therefore share one authoritative 3D edge while retaining separate local 2D representations.++The terminal vocabulary is `Cap` and `Open`. `Cap/Cap` closes the two planar profile loops and yields a closed solid. Any open terminal is truthfully classified as `OpenShell`; the general STEP command currently emits only the capped witnesses.++## Sweep relationship++A Sweep transports one profile through a trajectory. A SectionChain allows the profile itself to change at explicitly framed stations. Both use ordered geometry and stable parameter correspondence, but the current circular Sweep keeps its specialized line/arc-path materializer. That path preserves Paperclip's exact cylinders and tori, planar transported-frame policy, and sweep-specific clearance checks; forcing it through generic ruled faces would weaken the representation.++## Firmament authoring++SectionChain authoring reuses ordinary `Concept Path` and `Profile` declarations. A `Section` associates that reusable 2D profile with a named right-handed `Construction Plane`; it does not expose vertices, faces, or raw BRep surfaces.++```firmament+Concept Path NoseOutline {+ Start: Point2(-5mm, -3mm)+ Heading: 0deg+ Line Bottom { Length: 10mm }+ Line Right { Turn: 90deg; Length: 6mm }+ Line Top { Turn: 90deg; Length: 10mm }+ Close Left+}+Profile NoseProfile From NoseOutline++SectionChain Fairing {+ Transition: Ruled+ Section Nose {+ Frame: NoseFrame+ Profile: NoseProfile+ Seam: Bottom+ }+ Section Front {+ Frame: FrontFrame+ Profile: FrontProfile+ Seam: Bottom+ }+ Start: Cap+ End: Cap+}+```++Equal ordered span identities infer correspondence. When identities differ, author a `Correspond` block with `From`, `To`, and explicit `Source -> Target` rows. Missing, incomplete, reordered, or duplicate mappings fail before BRep construction. `Ruled`, `Cap`, and `Open` are the only currently qualified transition/termination vocabulary.++```firmament+Correspond NoseToFront {+ From: Nose+ To: Front+ Bottom -> South+ Right -> East+ Top -> North+ Left -> West+}+```++Profile coordinates use the construction plane's local axes: profile X follows frame `XAxis`, profile Y follows `YAxis`, and the chain progresses between section origins/normals. If one Profile is referenced by several Sections, editing it changes each of those yielded states; locality is the union of their adjacent transitions. The current CLI reports one compiled state but does not yet compare two authored files or serialize `SectionChainEditDelta`.++A SectionChain is useful as a geometric generator: each framed profile is an ordered state, and Aetheris materializes the transition between adjacent yielded states. This is a mental model, not a general-purpose iterator language.++## CLI++Generate and inspect the eight-section flagship through the production BRep/STEP path:++```powershell+aetheris section-chain validate fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament --json+aetheris section-chain inspect fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament --json+aetheris section-chain build fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament --out artifacts/local/surf-x3a/fairing.step --json+```++On a source checkout where the tool is not installed, replace `aetheris` with `dotnet run --project Aetheris.CLI -c Release --`.++The compatibility command also supports the generated `flagship`, `twist`, and `two-profile` witnesses. A build writes sibling `.evidence.json` containing section frames, spans, correspondence, transition classes, terminations, topology, pcurve qualification, conservative intersection evidence, timings, SHA-256, rational-surface count, and STEP reimport evidence.++`AddSectionChain` and `RemoveSectionChain` are not yet qualified BodyState operations. The current kernel's bounded Boolean families do not admit arbitrary changing ruled/B-spline tools, and the existing housing state rebuild would erase an attached chain during a downstream feature. A future admitted lane must construct a single shared-topology shell, retain chain history, enforce an authorized region and preservation contracts, and fail transactionally. These operations must not be represented publicly as arbitrary Boolean authoring.++## Current limits++The admitted lane has one closed outer loop, no holes, same-topology one-to-one correspondence, ruled transitions, and Cap/Open terminals. It checks frame handedness, loop closure and orientation, sampled profile self-intersection, section spacing, semantic mapping order, sampled transition Jacobian foldover, non-neighbour transition crossings, and remote cap penetration using a deterministic validation-only triangle proxy. The proxy is conservative detection evidence, not a global proof. It does not claim general smooth lofting, rails, topology-changing correspondence, globally proven intersection freedom, or production arbitrary sculpt attachment/subtraction. Invalid chains fail closed rather than producing a faceted product fallback.++Stable diagnostic families include `section-chain-correspondence-missing`, `section-chain-correspondence-duplicate`, `section-chain-profile-orientation-mismatch`, `section-chain-transition-foldover`, `section-chain-self-intersection`, and `section-chain-pcurve-error`. `section-chain validate` returns a nonzero exit status and emits no STEP when any of these blocks materialization. Transition identities are formatted `SourceSection->TargetSection` in structured evidence and diagnostic detail.diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex 2f452b35..041be734 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -12,6 +12,7 @@ Primary public commands:| `fea <file> --out-dir dir [--json]` | Compile and solve the bounded linear-elastic analysis || `sheetmetal ...` | Inspect, recognize, recover, compare, or flatten Sheet Metal || `sculpture build <source> ...` | Build the bounded non-manufacturing Sol 1 AP242 artwork, evidence, and SVG preview |+| `section-chain <build\|inspect\|validate> <file.firmament\|flagship\|twist\|two-profile> ...` | Lower authored profiles into SectionChain IR and report frames, spans, correspondence, pcurves, conservative intersection qualification, STEP, and reimport evidence || `asm ...` | Inspect/execute/import/export assemblies |Run `aetheris <command> --help` for exact options. JSON is a public automation surface, but its root is command-specific: process exit status is authoritative, `validate` reports `firmamentV2Validation.status`, and materializing/analysis commands report `success` where documented. Diagnostics are structured; artifact paths are explicit; Sheet Metal reports regions, bends, and lowered features separately; FEA reports requested/result artifacts; sculpting builds report every `BodyState`, `GeometricDelta`, validation evidence, surface-family inventory, and the sibling `.delta.json` path; other builds report emitted features and PMI export evidence. Counts describe semantic items at the stated layer, not arbitrary STEP entity counts.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 252f5fdc..e3c6172d 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -10,6 +10,7 @@| Virtual Sculpture | Bounded (ART-X0) | The explicit `Mode: Virtual` Sol 1 flagship: deterministic golden-angle/Fibonacci 3D lattice, analytic toroidal frame and eye, exact closed-body AP242 assembly, evidence/preview output, and zero rational product surfaces. This is not manufacturing geometry and does not extend Firmament engineering domains. See [Virtual Sculpture](../virtual-sculpture.md). || Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring || Circular Sweep | Bounded (X0) | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep |+| SectionChain ruled loft substrate | Experimental (SURF-X3a progression) | Firmament Concept Path/Profile authoring lowers into ordered framed, same-topology semantic SectionChain IR; one-to-one ruled transitions; shared internal edges; Cap/Open; strict face-local pcurves; deterministic validation-only non-neighbour/cap intersection detection; exact Plane and non-rational B-spline STEP with reimport. BodyState Add/Remove is not yet qualified. See [Section chains](../firmament/section-chains.md). || Structural / weldment | Bounded (X2) | Explicit 3D nodes and straight paths; identifiable members; square/rectangular/round tube, angle, flat/round bar; orientation; catalog material; two-member butt and polygonal miter joints; semantic fillet welds; AP242 member assembly and deterministic JSON Cut List. No coping, curved routing, multi-member miter, connection design, weld analysis, or structural FEA. See [guide](../firmament/structural.md). || Semantic piping / routing | Bounded (X3a) | Logical connections; equipment-owned port Interfaces and hollow nozzle stubs; target-port-scoped owner KeepOut exemptions; coincident endpoint mates; explicit orthogonal 3D routes; deterministic A* proposals; editable accepted routes; 90-degree elbows; bounded local rerouting; AP242 assembly, BOM, and pipe Cut List. No freeform, stress-, flow-, slope-, or plant-scale routing. See [guide](../firmament/piping.md). || Boss | Bounded | First-class connected finite `On: Top` profile addition on an admitted Compose host; positive height; lowers through existing `Add`; no arbitrary solid union |@@ -31,7 +32,7 @@| Platform qualification | Supported | Windows x64 bundle; NativeAOT Forge Host on `win-x64` || Linux/macOS release binaries | Not in Preview 3 | Framework logic tests do not constitute binary qualification || Post-Preview-3 feature families | X0 exception | Circular Sweep and Standard Products Paperclip are the bounded X0 additions; other new geometry/PMI/FEA/Forge families remain frozen |-| General loft, helix, and freeform surface features | Not in Preview 3 | The bounded SURF-X1a housing `ReplaceRegion` and imported `ADVANCED_FACE` graft are not a general Loft, arbitrary dumb-solid editor, or surface-network route. |+| General smooth/rail/topology-changing loft, helix, and freeform surface features | Not in Preview 3 | The experimental ruled SectionChain substrate does not qualify arbitrary smooth loft, guide rails, topology-changing correspondence, arbitrary dumb-solid editing, or surface networks. || Through profile removal | Bounded semantic operations | Use qualified `Hole`, `Slot`, or another documented opening feature; Pocket never means through-all || Arbitrary solid Boolean subtraction / hemispherical cavity | Not in Preview 3 | No public `Union`, `Subtract`, `Intersect`, CSG tree, Sphere-from-Block subtraction, or hemisphere special case |diff --git a/docs/release/SURF-X3-SECTION-CHAIN-LOFT.md b/docs/release/SURF-X3-SECTION-CHAIN-LOFT.mdnew file mode 100644index 00000000..a47327a4--- /dev/null+++ b/docs/release/SURF-X3-SECTION-CHAIN-LOFT.md@@ -0,0 +1,77 @@+# SURF-X3 — Section Chain / Loft consolidation++## Executive verdict++**Meaningful progression.** Aetheris now materializes a useful standalone general 3D body from an ordered semantic chain of changing, fully framed profiles. The real BRep/STEP path preserves shared internal section topology, exact/non-rational representation, deterministic correspondence, local edit identity, and successful STEP reimport. The complete SURF-X3 milestone is not accepted because Firmament text authoring, BodyState `AddSectionChain`/`RemoveSectionChain`, authorized-region/preservation enforcement for those sculpt operations, and a general chain self-intersection proof remain unimplemented.++## Audit and consolidation result++The existing ruled implementation is `RuledSurfaceIr` plus `RuledSurfaceLowering`. It already owns normalized boundary parameter correspondence, line/arc/circle/non-rational-B-spline evaluation, circle-to-cylinder/cone recognition, developability evidence, and the non-rational fallback. SectionChain uses that implementation for every adjacent semantic span; no second ruled formula was introduced.++The ruled path was strengthened in place:++- coplanar line pairs now emit exact `PlaneSurface`;+- compatible polynomial B-spline pairs emit an exact degree `(p,1)` non-rational ruled surface;+- line-to-B-spline uses the B-spline basis' Greville control positions to represent the line exactly in the compatible basis;+- prior saddle and ruled-panel behavior remains on the same lowering path.++Circular Sweep remains intentionally specialized. Its Concept Path parser, planar tangent frame, bend-radius/clearance validation, and analytic segment realization produce exact cylinders for lines and tori for arcs. A generic section-face realization would turn the Paperclip into weaker geometry. Sweep and SectionChain share the ordered-correspondence design law, but not a runtime god-object or a forced BRep emitter.++## SectionChain semantics++`SectionChain` contains ordered `Section` values, adjacent correspondence, `Ruled` transition policy, and explicit start/end termination. Every section contains `SectionId`, `SectionFrame`, and `SectionProfile`. Every profile contains stable semantic spans and an explicit seam span. X3 admits one CCW closed outer loop made from line, positive circular arc, or non-rational polynomial B-spline spans.++Correspondence is strong semantic identity or explicit one-to-one mapping. The qualified mapping preserves seam-relative span order; nearest-geometry inference and topology branching are rejected. Internal profile edges are allocated once and reused by both adjacent transition faces.++`SectionChainEditor.ReplaceSection` records the replaced section, the two rebuilt adjacent transition IDs, distant preserved transitions, and preserved terminations. The flagship edit of `Rise` rebuilds only `PalmFront->Rise` and `Rise->Peak`; five distant transitions remain preserved.++## Surface realization and flagship++The flagship `surf-x3-section-chain-ergonomic-body` has eight stations:++```text+Nose -> Front -> PalmFront -> Rise -> Peak -> PalmRear -> Rear -> Tail+```++Width, height, side roundness, origin, clocking, and plane tilt vary across the chain. `Front -> PalmFront` proves exact line-to-cubic-B-spline semantic span transitions. A separate three-section witness applies 0°, 10°, and 20° frame clocking. A 180° collapse witness is rejected with `section-chain-transition-foldover`.++Fresh CLI artifact evidence from `aetheris section-chain build flagship`:++| Evidence | Result |+|---|---:|+| Sections | 8 |+| Transitions | 7 |+| Bodies / shells | 1 / 1 |+| Faces / edges / vertices | 30 / 60 / 32 |+| Plane surfaces | 4 |+| Non-rational B-spline surfaces | 26 |+| Rational product surfaces | 0 |+| Structural assessment after STEP reimport | enclosed-manifold |+| STEP reimport | succeeded |+| SHA-256 | `5e1a382f4869466269903262c45cacddd5efefe8d7dde07e65bffce7c15a4ec6` |++The generated artifact is local by policy at `artifacts/local/surf-x3/surf-x3-section-chain-ergonomic-body.step`, with sibling structured evidence. Reproduce it with:++```powershell+dotnet run --project Aetheris.CLI -c Release -- section-chain build flagship --out artifacts/local/surf-x3/surf-x3-section-chain-ergonomic-body.step --json+dotnet run --project Aetheris.CLI -c Release -- analyze artifacts/local/surf-x3/surf-x3-section-chain-ergonomic-body.step --json+```++Manual inspection should check the overall silhouette, section flow, unexpected twist, seams, flat spots, foldovers, nose/tail caps, and whether the body reads as an intentionally lofted fairing.++## Validation evidence++Targeted tests cover the eight-section closed body, deterministic export and reimport, exact mixed line/B-spline realization, analytic planar recognition, 20° twist, local section edit identity, shared-edge incidence, profile correspondence failure, profile orientation failure, extreme-twist foldover rejection, BRep binding, export preflight, and CLI artifact evidence. Paperclip's five kernel Sweep tests and CLI semantic-route regression pass unchanged.++The Release solution build completed with zero warnings and zero errors. The full serial .NET run passed 3,170 tests across 17 test assemblies; the FrictionLab assembly currently reports no discoverable tests and did not fail the run. The web client passed 82 tests, TypeScript/Vite production build, and ESLint. The VS Code extension passed TSPack typecheck, 13 tests, bundle build, and VSIX packaging. A freshly packed and locally installed `Aetheris.CLI` tool built and reimported the analytic two-profile witness. The repository layout guard and `git diff --check` pass.++## Remaining acceptance blockers++- A Firmament parser/binder/lowering declaration for arbitrary authored SectionChain values.+- Canonical and invalid Firmament fixture corpus plus fresh-agent A–F qualification.+- `AddSectionChain` and `RemoveSectionChain` against `BodyState`, including attachment/penetration, authorized envelope, preservation, failure atomicity, downstream selector behavior, and actual bounded composition.+- General chain-to-chain self-intersection validation beyond per-profile and per-transition foldover checks.+- Face-local pcurves for the newly emitted SectionChain faces.+- Add/remove flagship artifacts and downstream current-state feature witnesses.++These are real system boundaries, not documentation omissions. The standalone ruled-loft substrate removes the first blocker without pretending the sculpt milestone is complete.diff --git a/docs/release/SURF-X3A-SECTION-CHAIN-SCULPT.md b/docs/release/SURF-X3A-SECTION-CHAIN-SCULPT.mdnew file mode 100644index 00000000..de0fa77a--- /dev/null+++ b/docs/release/SURF-X3A-SECTION-CHAIN-SCULPT.md@@ -0,0 +1,117 @@+# SURF-X3a — SectionChain sculpt integration++## Executive verdict++**Meaningful progression.** SectionChain is now a real Firmament-authored, inspectable, pcurve-complete, deterministic standalone SURF primitive with conservative non-neighbour/cap intersection detection. It is not yet a first-class `AddSectionChain`/`RemoveSectionChain` BodyState sculpt primitive, so the requested final verdict cannot honestly be Accepted.++The remaining blocker is structural, not syntactic: `BrepBoolean` admits bounded axis-aligned/prismatic/analytic-hole families and classifies an arbitrary changing ruled/non-rational-B-spline SectionChain tool as an unsupported general case. `BodyState` also retains only a `HousingConstruction` recipe; every downstream safe feature rebuilds that recipe and would erase a grafted chain. A correct implementation therefore needs a retained SectionChain construction history plus a bounded shared-topology housing/attachment builder (or a general topology editor). Routing the request through public arbitrary Boolean authoring would violate the milestone's meaning and would not converge.++## X3 audit++X3 already guaranteed ordered full frames, closed single-loop semantic spans, stable seams, explicit or strong-identity one-to-one correspondence, Ruled transitions, Cap/Open terminations, shared internal section edges, deterministic local edit identities, exact planes, compatible polynomial ruled B-splines, foldover/profile checks, rational-free STEP, and deterministic reimport.++It deliberately did not guarantee smooth/rail-guided lofts, topology-changing correspondence, multiple loops, global intersection proof, or arbitrary BodyState composition. SectionChain bypassed BodyState by materializing directly from a generated C# template in the CLI. Its faces had 3D edge bindings but no face-local pcurves. Its intersection checks were limited to sampled profile crossings and per-patch Jacobian/normal foldover.++X3a reuses the SURF-X1a `BoundedPcurveBuilder`, `BrepPcurveValidator`, AP242 `SURFACE_CURVE`/`PCURVE` writer, and existing Concept Path/Profile binder. No second profile grammar, ruled formula, pcurve inverter, or mesh product representation was introduced.++## X3 blocker closure++| X3 blocker | X3a result | Evidence |+| --- | --- | --- |+| Firmament text authoring | Closed for standalone SectionChain | `SectionChainAuthoringParser`; Concept Path/Profile reuse; canonical 2/6/8-section and open fixtures; build/inspect/validate CLI |+| Fixture corpus | Partially closed | Four canonical fixtures plus typed foldover invalid fixture; Add/Remove and several requested negative fixtures remain blocked with the sculpt path |+| AddSectionChain | Blocked | Arbitrary changing ruled/B-spline union is outside admitted Boolean families; no retained construction history/shared-topology attachment builder |+| RemoveSectionChain | Blocked | Same Boolean boundary; no bounded one-body duct topology builder, no-op/split qualification, or retained history |+| Self-intersection qualification | Closed for the admitted standalone validation contract | profile test + foldover test + deterministic AABB/triangle proxy for non-neighbour transitions and remote caps; explicit non-proof evidence |+| Face-local pcurves | Closed | every transition/cap coedge populated; independent domain, endpoint, orientation, UV closure, max/RMS reconstruction qualification; STEP reimport |++## Firmament and CLI++The semantic route is:++```text+Concept Path / Profile / Construction Plane+ -> SectionChain semantic IR+ -> RuledSurfaceIr transition lowering+ -> shared-topology BRep with face-local pcurves+ -> AP242 STEP+```++Sections retain authored section, frame, profile, span, seam, transition, and termination identities. Equal ordered span identities produce `InferredSemanticIdentity`; otherwise a `Correspond` block provides explicit source/target rows. Ambiguous, reordered, missing, or duplicate correspondence fails before BRep construction.++`section-chain build|inspect|validate <file.firmament>` reports the semantic IR rather than only face counts, including resolved correspondence, transition surface classes, pcurve evidence, conservative intersection method, representation inventory, and reimport.++## Pcurves++The eight-section authored flagship has 28 transition faces and 2 planar caps. Its 60 shared edges create 120 face-local coedge pcurves. Independent qualification reports:++| Evidence | Result |+| --- | ---: |+| Pcurves / coedges | 120 / 120 |+| Maximum 3D reconstruction deviation | `1.475552811121985E-14 mm` |+| Tolerance | `1E-05 mm` |+| Surface-domain containment | passed |+| Oriented start/end reconstruction | passed |+| UV loop closure | passed |+| STEP reimport | passed |++An internal section still owns one 3D edge. Each adjacent transition face owns its own pcurve for that edge; no duplicate near-coincident seam is introduced. Planar cap pcurves use the same plane projection machinery.++## Self-intersection qualification++The admitted pipeline checks profile self-intersection, adjacent ruled Jacobian/normal foldover, non-neighbour transition crossings, coplanar overlap, and remote cap penetration. The latter checks use a deterministic validation-only `24 x 6` triangle proxy per ruled patch, expanded AABB broadphase, triangle/triangle narrowphase, and topology-aware exclusion of intended adjacent seams.++This is detection evidence, not a global proof or a certified Hausdorff enclosure. The structured method name is `DeterministicBroadphasePlusTriangleProxy`; the topology tolerance is `1E-06`. A four-section non-neighbour overlap witness is rejected as `section-chain-self-intersection`, and a 180-degree framed-profile inversion is rejected as `section-chain-transition-foldover`. Product geometry remains structured BRep; faceted product fallback is zero.++## Locality++`SectionChainEditor.ReplaceSection` still identifies only the two adjacent transition identities. The X3 witness that changes `Rise` rebuilds `PalmFront->Rise` and `Rise->Peak`, preserves five distant transitions, and preserves both terminations. This is semantic and realized deterministic-geometry preservation; the current implementation does not cache/splice BRep subgraphs and therefore does not claim that a full materializer invocation avoided recomputing distant patches. BodyState/GeometricDelta locality remains part of the blocked sculpt integration.++## Representation and artifact++The re-authored flagship is `fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament` and produces:++| Evidence | Result |+| --- | ---: |+| SHA-256 | `03ba8872e1daea585d16c2a54ffb02aeead26633e4e6f3fc13e87c7ab1c41f97` |+| Sections / transitions | 8 / 7 |+| Bodies / shells | 1 / 1 |+| Faces / edges / vertices | 30 / 60 / 32 |+| Planes | 30 |+| Non-rational B-splines | 0 |+| Rational product surfaces | 0 |+| Faceted product fallback | 0 |+| Pcurves | 120 |+| Self-intersection proxy | passed |+| Structural reimport assessment | enclosed-manifold |+| STEP reimport | passed |++Two exports produced the same hash. The artifact is `artifacts/local/surf-x3a/surf-x3a-section-chain-ergonomic-body.step`; a sibling `.evidence.json` records the complete report.++The requested Add grip and Remove duct artifacts are not generated because no correct Add/Remove BodyState result exists. Producing standalone chain bodies with those filenames would misrepresent the capability.++## Fresh-agent qualification++- A passed for eight-profile authoring using only public docs and canonical fixtures.+- F passed through the real CLI path and independently reproduced the flagship hash and representation evidence.+- D could author a centered 8 mm middle-profile width increase and infer the union of adjacent transitions, but found no public predecessor/successor compare command.+- E could author a 180-degree frame inversion and now has a canonical invalid fixture plus stable foldover diagnostic documentation.+- B and C stopped correctly: public docs expose no Add/Remove syntax and explicitly prohibit substituting arbitrary Difference.++The exercise also found stale public statements and missing resolved inferred correspondence in CLI JSON; both were corrected in place.++## Validation++- Release solution build: passed, 0 warnings, 0 errors.+- Full serial .NET suite: passed, 3,179 tests across 17 test-bearing assemblies; FrictionLab reports no discoverable tests.+- SectionChain geometry suite: 9 passed.+- Firmament authoring/fixture suite: parser, lowering, termination, pcurve, invalid correspondence, and foldover cases passed.+- CLI authored build/inspect/validate: passed.+- Paperclip kernel and CLI semantic-route regressions: passed; Sweep remains specialized.+- Deterministic double export and STEP reimport: passed.+- Freshly packed/local-tool SectionChain validation smoke: passed.+- `git diff --check`: passed (line-ending notices only).++## Required next architecture++Acceptance requires a narrow planar-housing attachment/removal construction that directly emits one connected shared-topology shell, retains ordered SectionChain sculpt history in `BodyState`, verifies realized diffs against an authorized envelope, preserves existing semantic associations, proves volume direction and connectedness, and supports downstream safe features without erasing the chain. Only after that real path exists should `AddSectionChain` and `RemoveSectionChain` be exposed in Firmament and canonical Add/Remove artifacts be published.diff --git a/fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament b/fixtures/Canonical/SectionChain/eight-section-ergonomic.firmamentnew file mode 100644index 00000000..4a024840--- /dev/null+++ b/fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament@@ -0,0 +1,58 @@+Model EightSectionErgonomic {+ Units: mm+ Concept Struct Stations {+ D0: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D1: Plane { Origin: [12mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D2: Plane { Origin: [27mm,1mm,1mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D3: Plane { Origin: [43mm,2mm,2mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D4: Plane { Origin: [59mm,2mm,2mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D5: Plane { Origin: [75mm,1mm,1mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D6: Plane { Origin: [89mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D7: Plane { Origin: [100mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ }+ Construction Plane F0 { Trace: Stations.D0 }+ Construction Plane F1 { Trace: Stations.D1 }+ Construction Plane F2 { Trace: Stations.D2 }+ Construction Plane F3 { Trace: Stations.D3 }+ Construction Plane F4 { Trace: Stations.D4 }+ Construction Plane F5 { Trace: Stations.D5 }+ Construction Plane F6 { Trace: Stations.D6 }+ Construction Plane F7 { Trace: Stations.D7 }+ Concept Path Small { Start: Point2(-4mm,-3mm) Heading: 0deg Line Bottom { Length: 8mm } Line Right { Turn: 90deg; Length: 6mm } Line Top { Turn: 90deg; Length: 8mm } Close Left }+ Concept Path Medium { Start: Point2(-10mm,-7mm) Heading: 0deg Line Bottom { Length: 20mm } Line Right { Turn: 90deg; Length: 14mm } Line Top { Turn: 90deg; Length: 20mm } Close Left }+ Concept Path Large { Start: Point2(-14mm,-10mm) Heading: 0deg Line Bottom { Length: 28mm } Line Right { Turn: 90deg; Length: 20mm } Line Top { Turn: 90deg; Length: 28mm } Close Left }+ Concept Path Peak { Start: Point2(-16mm,-11mm) Heading: 0deg Line Bottom { Length: 32mm } Line Right { Turn: 90deg; Length: 22mm } Line Top { Turn: 90deg; Length: 32mm } Close Left }+ Profile PSmall From Small+ Profile PMedium From Medium+ Profile PLarge From Large+ Profile PPeak From Peak+ SectionChain EightSectionErgonomic {+ Transition: Ruled+ Section Nose { Frame: F0+ Profile: PSmall+ Seam: Bottom }+ Section Front { Frame: F1+ Profile: PMedium+ Seam: Bottom }+ Section PalmFront { Frame: F2+ Profile: PLarge+ Seam: Bottom }+ Section Rise { Frame: F3+ Profile: PPeak+ Seam: Bottom }+ Section Peak { Frame: F4+ Profile: PPeak+ Seam: Bottom }+ Section PalmRear { Frame: F5+ Profile: PLarge+ Seam: Bottom }+ Section Rear { Frame: F6+ Profile: PMedium+ Seam: Bottom }+ Section Tail { Frame: F7+ Profile: PSmall+ Seam: Bottom }+ Start: Cap+ End: Cap+ }+}diff --git a/fixtures/Canonical/SectionChain/open-chain.firmament b/fixtures/Canonical/SectionChain/open-chain.firmamentnew file mode 100644index 00000000..7919871f--- /dev/null+++ b/fixtures/Canonical/SectionChain/open-chain.firmament@@ -0,0 +1,22 @@+Model OpenSectionChain {+ Units: mm+ Concept Struct Stations {+ A: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ B: Plane { Origin: [20mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ }+ Construction Plane FA { Trace: Stations.A }+ Construction Plane FB { Trace: Stations.B }+ Concept Path Outline { Start: Point2(-5mm,-4mm) Heading: 0deg Line Bottom { Length: 10mm } Line Right { Turn: 90deg; Length: 8mm } Line Top { Turn: 90deg; Length: 10mm } Close Left }+ Profile P From Outline+ SectionChain OpenSectionChain {+ Transition: Ruled+ Section A { Frame: FA+ Profile: P+ Seam: Bottom }+ Section B { Frame: FB+ Profile: P+ Seam: Bottom }+ Start: Open+ End: Open+ }+}diff --git a/fixtures/Canonical/SectionChain/six-section-ergonomic.firmament b/fixtures/Canonical/SectionChain/six-section-ergonomic.firmamentnew file mode 100644index 00000000..6322e61d--- /dev/null+++ b/fixtures/Canonical/SectionChain/six-section-ergonomic.firmament@@ -0,0 +1,54 @@+Model SixSectionErgonomic {+ Units: mm+ Concept Struct Stations {+ P0: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ P1: Plane { Origin: [14mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ P2: Plane { Origin: [30mm,1mm,1mm]; Normal: [1,0,0]; Up: [0,0,1] }+ P3: Plane { Origin: [48mm,2mm,2mm]; Normal: [1,0,0]; Up: [0,0,1] }+ P4: Plane { Origin: [66mm,1mm,1mm]; Normal: [1,0,0]; Up: [0,0,1] }+ P5: Plane { Origin: [82mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ }+ Construction Plane F0 { Trace: Stations.P0 }+ Construction Plane F1 { Trace: Stations.P1 }+ Construction Plane F2 { Trace: Stations.P2 }+ Construction Plane F3 { Trace: Stations.P3 }+ Construction Plane F4 { Trace: Stations.P4 }+ Construction Plane F5 { Trace: Stations.P5 }++ Concept Path O0 { Start: Point2(-4mm,-3mm) Heading: 0deg Line Bottom { Length: 8mm } Line Right { Turn: 90deg; Length: 6mm } Line Top { Turn: 90deg; Length: 8mm } Close Left }+ Concept Path O1 { Start: Point2(-9mm,-6mm) Heading: 0deg Line Bottom { Length: 18mm } Line Right { Turn: 90deg; Length: 12mm } Line Top { Turn: 90deg; Length: 18mm } Close Left }+ Concept Path O2 { Start: Point2(-13mm,-9mm) Heading: 0deg Line Bottom { Length: 26mm } Line Right { Turn: 90deg; Length: 18mm } Line Top { Turn: 90deg; Length: 26mm } Close Left }+ Concept Path O3 { Start: Point2(-15mm,-10mm) Heading: 0deg Line Bottom { Length: 30mm } Line Right { Turn: 90deg; Length: 20mm } Line Top { Turn: 90deg; Length: 30mm } Close Left }+ Concept Path O4 { Start: Point2(-11mm,-7mm) Heading: 0deg Line Bottom { Length: 22mm } Line Right { Turn: 90deg; Length: 14mm } Line Top { Turn: 90deg; Length: 22mm } Close Left }+ Concept Path O5 { Start: Point2(-5mm,-3.5mm) Heading: 0deg Line Bottom { Length: 10mm } Line Right { Turn: 90deg; Length: 7mm } Line Top { Turn: 90deg; Length: 10mm } Close Left }+ Profile R0 From O0+ Profile R1 From O1+ Profile R2 From O2+ Profile R3 From O3+ Profile R4 From O4+ Profile R5 From O5++ SectionChain SixSectionErgonomic {+ Transition: Ruled+ Section Nose { Frame: F0+ Profile: R0+ Seam: Bottom }+ Section Front { Frame: F1+ Profile: R1+ Seam: Bottom }+ Section PalmFront { Frame: F2+ Profile: R2+ Seam: Bottom }+ Section Peak { Frame: F3+ Profile: R3+ Seam: Bottom }+ Section PalmRear { Frame: F4+ Profile: R4+ Seam: Bottom }+ Section Tail { Frame: F5+ Profile: R5+ Seam: Bottom }+ Start: Cap+ End: Cap+ }+}diff --git a/fixtures/Canonical/SectionChain/two-section-ruled.firmament b/fixtures/Canonical/SectionChain/two-section-ruled.firmamentnew file mode 100644index 00000000..d7567d09--- /dev/null+++ b/fixtures/Canonical/SectionChain/two-section-ruled.firmament@@ -0,0 +1,45 @@+Model TwoSectionRuled {+ Units: mm++ Concept Struct Stations {+ StartDatum: Plane { Origin: [0mm, 0mm, 0mm]; Normal: [1, 0, 0]; Up: [0, 0, 1] }+ EndDatum: Plane { Origin: [30mm, 0mm, 0mm]; Normal: [1, 0, 0]; Up: [0, 0, 1] }+ }+ Construction Plane StartFrame { Trace: Stations.StartDatum }+ Construction Plane EndFrame { Trace: Stations.EndDatum }++ Concept Path StartOutline {+ Start: Point2(-10mm, -6mm)+ Heading: 0deg+ Line Bottom { Length: 20mm }+ Line Right { Turn: 90deg; Length: 12mm }+ Line Top { Turn: 90deg; Length: 20mm }+ Close Left+ }+ Concept Path EndOutline {+ Start: Point2(-8mm, -5mm)+ Heading: 0deg+ Line Bottom { Length: 16mm }+ Line Right { Turn: 90deg; Length: 10mm }+ Line Top { Turn: 90deg; Length: 16mm }+ Close Left+ }+ Profile StartProfile From StartOutline+ Profile EndProfile From EndOutline++ SectionChain TwoSectionRuled {+ Transition: Ruled+ Section Start {+ Frame: StartFrame+ Profile: StartProfile+ Seam: Bottom+ }+ Section End {+ Frame: EndFrame+ Profile: EndProfile+ Seam: Bottom+ }+ Start: Cap+ End: Cap+ }+}diff --git a/fixtures/Invalid/SectionChain/transition-foldover.firmament b/fixtures/Invalid/SectionChain/transition-foldover.firmamentnew file mode 100644index 00000000..9ec9fa06--- /dev/null+++ b/fixtures/Invalid/SectionChain/transition-foldover.firmament@@ -0,0 +1,22 @@+Model InvalidSectionChainFoldover {+ Units: mm+ Concept Struct Stations {+ A: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ B: Plane { Origin: [20mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,-1] }+ }+ Construction Plane FA { Trace: Stations.A }+ Construction Plane FB { Trace: Stations.B }+ Concept Path Outline { Start: Point2(-5mm,-4mm) Heading: 0deg Line Bottom { Length: 10mm } Line Right { Turn: 90deg; Length: 8mm } Line Top { Turn: 90deg; Length: 10mm } Close Left }+ Profile P From Outline+ SectionChain InvalidFoldover {+ Transition: Ruled+ Section A { Frame: FA+ Profile: P+ Seam: Bottom }+ Section B { Frame: FB+ Profile: P+ Seam: Bottom }+ Start: Cap+ End: Cap+ }+}