Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add Firmament thread export support
Yuechen Li00bf64a47d50
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 16870dd1..c1586918 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -518,6 +518,7 @@ public static class CliRunnerstructural = build.Value.Export.Structural,piping = build.Value.Export.Piping,gear = build.Value.Export.Gear,+ thread = build.Value.Export.Thread,featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0) + (build.Value.Export.Perforation is null ? 0 : 1),inlineStepMigration = build.Value.Export.InlineStepMigration,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,@@ -546,6 +547,8 @@ public static class CliRunnerstdout.WriteLine($"Piping system: {piping.Connections.Count} connections, {piping.Routes.Count} routes, {piping.PipeSegments.Count} pipe segments, {piping.Fittings.Count} fittings, {piping.Nozzles.Count} equipment nozzles, {piping.Mates.Count} endpoint mates; routing report: {piping.RoutingReportArtifactPath}");if (build.Value.Export.Gear is { } gear)stdout.WriteLine($"Gear: {gear.Gears[0].Family} {gear.Gears[0].Name}, {gear.Gears[0].Teeth?.ToString() ?? "n/a"} teeth ({gear.Representation})");+ if (build.Value.Export.Thread is { } thread)+ stdout.WriteLine($"Thread: {thread.MajorDiameterMm:G6} mm major, {thread.RootDiameterMm:G6} mm root, {thread.PitchMm:G6} mm pitch, {thread.Turns} turns");foreach (var diagnostic in build.Diagnostics.Where(diagnostic => diagnostic.Severity == KernelDiagnosticSeverity.Warning))stderr.WriteLine($"- [Warning] {diagnostic.Source}: {diagnostic.Message}");}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.csindex ac48c079..7b9fcc70 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs@@ -8,7 +8,7 @@ public sealed class FirmamentSemanticSchemaTestspublic void GeneratedRegistry_IsStableOptInAndCoversFirstConstructs(){Assert.Equal("firmament-semantic-schema/1", FirmamentSemanticSchemas.Version);- Assert.Equal(["Box", "Concept", "Helix", "Hole", "Loft", "Perforation"], FirmamentSemanticSchemas.All.Select(s => s.Name));+ Assert.Equal(["Box", "Concept", "Helix", "Hole", "Loft", "Perforation", "Thread"], FirmamentSemanticSchemas.All.Select(s => s.Name));var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));var diameter = Assert.Single(hole.Fields, f => f.Name == "Diameter");Assert.Equal("Hole.Diameter", diameter.Id.Value);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.csnew file mode 100644index 00000000..815edc33--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.cs@@ -0,0 +1,280 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;+using System.Diagnostics;+using System.Text;+using System.Text.Json;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentThreadX1Tests+{+ private static string CylinderThread(double radius = 4, double major = 8, double pitch = 1.25,+ double length = 5, double height = 9, double start = 1, string support = "face(Shank.OuterWall)",+ string hand = "Right") => $$"""+ Model ThreadWitness {+ Units: mm+ Cylinder Shank {+ Radius: {{radius}}mm+ Height: {{height}}mm+ }+ Thread MainThread {+ Surface: {{support}}+ MajorDiameter: {{major}}mm+ Pitch: {{pitch}}mm+ Length: {{length}}mm+ StartOffset: {{start}}mm+ Hand: {{hand}}+ }+ }+ """;++ [Fact]+ public void CylinderThreadProducesClosedManifoldStepAndSourceMappedRoles()+ {+ var source = CylinderThread();+ var first = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(first.IsSuccess, string.Join(" | ", first.Diagnostics.Select(d => d.Message)));+ var report = Assert.IsType<FirmamentThreadReport>(first.Value.Thread);+ Assert.Equal(8, report.MajorDiameterMm, 9);+ Assert.Equal(8 - 2 * 17 * Math.Sqrt(3) * 1.25 / 48, report.RootDiameterMm, 9);+ Assert.Equal(1.25, report.PitchMm, 9);+ Assert.Equal(report.PitchMm, report.LeadMm);+ Assert.Equal("Right", report.Hand);+ Assert.Equal("metric-60-degree-truncated", report.ProfileFamily);+ Assert.Equal(5, report.LengthMm);+ Assert.Equal(4, report.Turns);+ var body = Assert.IsType<BrepBody>(first.Value.RuntimeBody);+ var mass = BrepMassProperties.Evaluate(body);+ Assert.True(mass.IsEnclosed, string.Join(" | ", mass.Diagnostics));+ Assert.True(mass.IsOrientationConsistent);+ Assert.Equal(report.Faces, body.Topology.Faces.Count());+ Assert.Equal(report.Edges, body.Topology.Edges.Count());+ Assert.Equal(report.Vertices, body.Topology.Vertices.Count());+ var display = BrepDisplayTessellator.TessellateBounded(body, executionTimeout: TimeSpan.FromSeconds(30));+ Assert.True(display.IsSuccess, string.Join(" | ", display.Diagnostics.Select(d => d.Message)));+ Assert.Equal(report.Faces, display.Value.FacePatches.Count);+ Assert.All(display.Value.FacePatches, patch => Assert.NotEmpty(patch.TriangleIndices));++ var correspondence = Assert.IsType<SemanticTopologyCorrespondence>(first.Value.RuntimeCorrespondence);+ var sourceMap = new GeometrySourceMap(correspondence);+ Assert.True(sourceMap.TryGetSourceSpan(report.FeatureId, out var span));+ Assert.Contains("Thread MainThread", source.Substring(span.Start, span.Length));+ foreach (var role in new[] { SemanticTopologyRole.ThreadLeadingFlank,+ SemanticTopologyRole.ThreadTrailingFlank, SemanticTopologyRole.ThreadCrest,+ SemanticTopologyRole.ThreadRootFace, SemanticTopologyRole.ThreadStartCap,+ SemanticTopologyRole.ThreadEndCap })+ {+ var face = Assert.Single(correspondence.Descendants.Where(item => item.Role == role && item.Face.HasValue).Take(1));+ Assert.True(sourceMap.TryGetByBrepFace(face.Face!.Value, out var mapped));+ Assert.Equal(report.FeatureId, mapped.SourceStableId);+ }+ var edge = Assert.Single(correspondence.Descendants.Where(item => item.Role == SemanticTopologyRole.ThreadBoundaryEdge && item.Edge.HasValue).Take(1));+ Assert.True(sourceMap.TryGetByBrepEdge(edge.Edge!.Value, out _));++ var imported = Step242Importer.ImportBody(first.Value.StepText);+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(d => d.Message)));+ var roundtripMass = BrepMassProperties.Evaluate(imported.Value);+ Assert.True(roundtripMass.IsEnclosed, string.Join(" | ", roundtripMass.Diagnostics));+ Assert.True(roundtripMass.IsOrientationConsistent);++ var second = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(second.IsSuccess);+ Assert.Equal(report.StepSha256, second.Value.Thread!.StepSha256);+ }++ [Fact]+ public void PitchLengthAndDiameterEditsUpdateSemanticGeometry()+ {+ var baseline = FirmamentBuildAndExport.CompileSource(CylinderThread());+ var pitch = FirmamentBuildAndExport.CompileSource(CylinderThread(pitch: 1, length: 5));+ var length = FirmamentBuildAndExport.CompileSource(CylinderThread(length: 6.25, height: 10));+ var diameter = FirmamentBuildAndExport.CompileSource(CylinderThread(radius: 5, major: 10));+ Assert.True(baseline.IsSuccess);+ Assert.True(pitch.IsSuccess, string.Join(" | ", pitch.Diagnostics.Select(d => d.Message)));+ Assert.True(length.IsSuccess, string.Join(" | ", length.Diagnostics.Select(d => d.Message)));+ Assert.True(diameter.IsSuccess, string.Join(" | ", diameter.Diagnostics.Select(d => d.Message)));+ Assert.Equal(4, baseline.Value.Thread!.Turns);+ Assert.Equal(5, pitch.Value.Thread!.Turns);+ Assert.True(pitch.Value.Thread.RootDiameterMm > baseline.Value.Thread.RootDiameterMm);+ Assert.Equal(5, length.Value.Thread!.Turns);+ Assert.Equal(6.25, length.Value.Thread.LengthMm);+ Assert.Equal(10, diameter.Value.Thread!.MajorDiameterMm);+ Assert.Equal(baseline.Value.Thread.RootDiameterMm + 2, diameter.Value.Thread.RootDiameterMm, 8);+ }++ [Fact]+ public void OmittedStartOffsetDerivesAStockMargin()+ {+ var source = CylinderThread().Replace("StartOffset: 1mm", "", StringComparison.Ordinal);+ var result = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => d.Message)));+ Assert.Equal(1 + 5d * 1.25d / 12d, result.Value.Thread!.StartOffsetMm, 9);+ }++ [Theory]+ [InlineData(4, 8, 0, 5, 9, 1, "face(Shank.OuterWall)", "Right", "thread-pitch-invalid")]+ [InlineData(4, 8, -1, 5, 9, 1, "face(Shank.OuterWall)", "Right", "thread-pitch-invalid")]+ [InlineData(4, 8, 1.25, 0, 9, 1, "face(Shank.OuterWall)", "Right", "thread-length-invalid")]+ [InlineData(4, 8, 1.25, 8, 9, 1, "face(Shank.OuterWall)", "Right", "thread-support-bounds")]+ [InlineData(4, 9, 1.25, 5, 9, 1, "face(Shank.OuterWall)", "Right", "thread-major-diameter-incompatible")]+ [InlineData(4, 8, 8, 8, 20, 1, "face(Shank.OuterWall)", "Right", "thread-profile-self-intersection")]+ [InlineData(4, 8, 1.25, 5, 9, 1, "face(Shank.Top)", "Right", "thread-support-not-cylinder")]+ public void InvalidThreadParametersHaveControlledDiagnostics(double radius, double major, double pitch,+ double length, double height, double start, string support, string hand, string code)+ {+ var result = FirmamentBuildAndExport.CompileSource(CylinderThread(radius, major, pitch, length, height, start, support, hand));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.Contains(code, StringComparison.Ordinal));+ }++ [Fact]+ public void UnsupportedHandIsExplicit()+ {+ var result = FirmamentBuildAndExport.CompileSource(CylinderThread(hand: "Left"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, item => item.Message.Contains("thread-hand-unsupported", StringComparison.Ordinal));+ }++ [Fact]+ public void ThreadSchemaAndLanguageCompletionExposeFields()+ {+ var schema = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Thread"));+ Assert.Equal(["Hand", "Length", "MajorDiameter", "Pitch", "StartOffset", "Surface"], schema.Fields.Select(f => f.Name));+ Assert.Contains(schema.Outputs, item => item.Name == "RootDiameter");+ Assert.Contains(schema.Outputs, item => item.Name == "TurnCount");+ var bare = "Model M { Units: mm\n Thr";+ var entry = FirmamentLanguageService.Complete(bare, "thread.firmament", "1", bare.Length);+ Assert.Equal("Thread", Assert.Single(entry.Entries!).Name);+ var partial = "Model M { Units: mm\n Thread T {\n ";+ var fields = FirmamentLanguageService.Complete(partial, "thread.firmament", "1", partial.Length);+ Assert.Equal("Thread", fields.Context);+ Assert.Contains(fields.Fields, field => field.Name == "Surface");+ Assert.Contains(fields.Fields, field => field.Name == "Pitch");+ }++ [Fact]+ public void ExistingHexBoltAndOneThreadProduceOneManifoldStepBody()+ {+ var source = File.ReadAllText(ThreadFixture("hexbolt-threaded.firmament"));+ var result = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => d.Message)));+ var report = Assert.IsType<FirmamentThreadReport>(result.Value.Thread);+ Assert.Equal(38, report.Turns);+ Assert.Equal(8, report.MajorDiameterMm);+ Assert.Equal(6.466413347465057, report.RootDiameterMm, 8);+ Assert.Equal(47.5, report.LengthMm);+ Assert.Equal(0.75, report.StartOffsetMm, 9);+ Assert.Equal(0.95, report.AxialStartMm, 9);+ Assert.Equal(176, report.Faces);+ Assert.Equal(355, report.Edges);+ Assert.Equal(184, report.Vertices);+ var standardPart = Assert.IsType<FirmamentStandardPartReport>(result.Value.StandardPart);+ Assert.Equal("HexBolt", standardPart.Family);+ Assert.Contains(standardPart.SemanticDescendants, item => item.StableId.EndsWith(".Head.TopFlat", StringComparison.Ordinal) && item.FaceId.HasValue);+ Assert.Contains(standardPart.SemanticDescendants, item => item.StableId.EndsWith(".TipFace", StringComparison.Ordinal) && item.FaceId.HasValue);+ Assert.DoesNotContain(standardPart.SemanticDescendants, item => item.StableId.Contains(".ThreadRegion", StringComparison.Ordinal));+ var body = Assert.IsType<BrepBody>(result.Value.RuntimeBody);+ var mass = BrepMassProperties.Evaluate(body);+ Assert.True(mass.IsEnclosed, string.Join(" | ", mass.Diagnostics));+ Assert.True(mass.IsOrientationConsistent);+ var map = Assert.IsType<SemanticTopologyCorrespondence>(result.Value.RuntimeCorrespondence);+ Assert.Contains(map.Descendants, item => item.Role == SemanticTopologyRole.ThreadCrest && item.Face.HasValue);+ Assert.Contains(map.Descendants, item => item.Role == SemanticTopologyRole.ThreadLeadingFlank && item.Face.HasValue);+ Assert.Contains(map.Descendants, item => item.Role == SemanticTopologyRole.ThreadTrailingFlank && item.Face.HasValue);+ Assert.True(new GeometrySourceMap(map).TryGetSourceSpan(report.FeatureId, out var span));+ Assert.Contains("Thread MainThread", source.Substring(span.Start, span.Length));+ var imported = Step242Importer.ImportBody(result.Value.StepText);+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(d => d.Message)));+ var importedMass = BrepMassProperties.Evaluate(imported.Value);+ Assert.True(importedMass.IsEnclosed, string.Join(" | ", importedMass.Diagnostics));+ Assert.True(importedMass.IsOrientationConsistent);+ var repeated = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(repeated.IsSuccess);+ Assert.Equal(report.StepSha256, repeated.Value.Thread!.StepSha256);+ }++ [Fact]+ public void WriteThreadedHexBoltDisplayArtifactWhenRequested()+ {+ var output = Environment.GetEnvironmentVariable("AETHERIS_THREAD_ARTIFACT_DIR");+ if (string.IsNullOrWhiteSpace(output)) return;+ Directory.CreateDirectory(output);+ var source = File.ReadAllText(ThreadFixture("hexbolt-threaded.firmament"));+ var timer = Stopwatch.StartNew();+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join(" | ", built.Diagnostics.Select(d => d.Message)));+ var compileAndBuildMs = timer.Elapsed.TotalMilliseconds;+ timer.Restart();+ var mesh = BrepDisplayTessellator.TessellateBounded(built.Value.RuntimeBody!,+ executionTimeout: TimeSpan.FromSeconds(60));+ Assert.True(mesh.IsSuccess, string.Join(" | ", mesh.Diagnostics.Select(d => d.Message)));+ var tessellationMs = timer.Elapsed.TotalMilliseconds;+ Assert.Equal(built.Value.Thread!.Faces, mesh.Value.FacePatches.Count);+ File.WriteAllText(Path.Combine(output, "threaded-hexbolt.obj"), Obj(mesh.Value));+ File.WriteAllText(Path.Combine(output, "threaded-hexbolt.step"), built.Value.StepText);+ File.WriteAllText(Path.Combine(output, "threaded-hexbolt.json"), JsonSerializer.Serialize(new+ {+ built.Value.Thread,+ compileAndBuildMs,+ tessellationMs,+ triangles = mesh.Value.FacePatches.Sum(patch => patch.TriangleIndices.Count / 3)+ }, new JsonSerializerOptions { WriteIndented = true }));+ }++ [Fact]+ public void WriteThreadCylinderDisplayArtifactWhenRequested()+ {+ var output = Environment.GetEnvironmentVariable("AETHERIS_THREAD_ARTIFACT_DIR");+ if (string.IsNullOrWhiteSpace(output)) return;+ Directory.CreateDirectory(output);+ var source = CylinderThread(length: 30, height: 34);+ var timer = Stopwatch.StartNew();+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join(" | ", built.Diagnostics.Select(d => d.Message)));+ var compileAndBuildMs = timer.Elapsed.TotalMilliseconds;+ timer.Restart();+ var mesh = BrepDisplayTessellator.TessellateBounded(built.Value.RuntimeBody!,+ executionTimeout: TimeSpan.FromSeconds(60));+ Assert.True(mesh.IsSuccess, string.Join(" | ", mesh.Diagnostics.Select(d => d.Message)));+ var tessellationMs = timer.Elapsed.TotalMilliseconds;+ Assert.Equal(built.Value.Thread!.Faces, mesh.Value.FacePatches.Count);+ File.WriteAllText(Path.Combine(output, "thread-cylinder-24.obj"), Obj(mesh.Value));+ File.WriteAllText(Path.Combine(output, "thread-cylinder-24.step"), built.Value.StepText);+ File.WriteAllText(Path.Combine(output, "thread-cylinder-24.json"), JsonSerializer.Serialize(new+ {+ built.Value.Thread,+ compileAndBuildMs,+ tessellationMs,+ triangles = mesh.Value.FacePatches.Sum(patch => patch.TriangleIndices.Count / 3)+ }, new JsonSerializerOptions { WriteIndented = true }));+ }++ private static string Obj(Aetheris.Kernel.Core.Brep.Tessellation.DisplayTessellationResult mesh)+ {+ var obj = new StringBuilder();+ var vertexOffset = 1;+ foreach (var patch in mesh.FacePatches)+ {+ obj.AppendLine($"g Face_{patch.FaceId.Value}");+ foreach (var point in patch.Positions)+ obj.AppendLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)+ obj.AppendLine($"f {vertexOffset + patch.TriangleIndices[i]} {vertexOffset + patch.TriangleIndices[i + 1]} {vertexOffset + patch.TriangleIndices[i + 2]}");+ vertexOffset += patch.Positions.Count;+ }+ return obj.ToString();+ }++ private static string ThreadFixture(string file)+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ root = root.Parent;+ if (root is null) throw new FileNotFoundException("Aetheris repository root was not found for Thread fixture.");+ return Path.Combine(root.FullName, "fixtures", "Thread", file);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/PlanarTextProfilesTests.cs b/Aetheris.Kernel.Firmament.Tests/PlanarTextProfilesTests.csnew file mode 100644index 00000000..8eb1de93--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/PlanarTextProfilesTests.cs@@ -0,0 +1,149 @@+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class PlanarTextProfilesTests+{+ [Fact]+ public void InterUsesOwnedFontAndPreservesOCounterAsExactCurves()+ {+ var text = PlanarTextProfiles.Build("CO", 3, PlanarTextAlignment.Center, featureId: "MakerMark");+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ Assert.Equal(2, text.Glyphs.Count);+ Assert.Equal("CO".Select(c => (int)c), text.Glyphs.Select(g => g.Codepoint));+ Assert.True(text.CounterCount >= 1);+ Assert.Contains(text.Regions, r => r.Name.Contains("Glyph[1]", StringComparison.Ordinal) && r.Loops.Any(l => !l.IsOuter));+ Assert.Contains(text.Regions.SelectMany(r => r.Loops).SelectMany(l => l.Segments),+ s => s.Geometry is LineArcCubicBezier2D);+ Assert.Contains(text.Regions.SelectMany(r => r.Loops).SelectMany(l => l.Segments),+ s => s.Provenance.SourceSpan == "source-char:1..2"+ && s.Provenance.Derivation.Contains("Glyph[1]:U+004F", StringComparison.Ordinal));+ Assert.All(text.Regions, r => Assert.True(ResolvedProfile2DValidator.Validate(r).IsValid,+ string.Join("; ", ResolvedProfile2DValidator.Validate(r).Diagnostics)));+ }++ [Fact]+ public void AdvanceAndHeightAreDeterministic()+ {+ var first = PlanarTextProfiles.Build("CO", 3);+ var second = PlanarTextProfiles.Build("CO", 3);+ var taller = PlanarTextProfiles.Build("CO", 6);+ Assert.True(first.Succeeded, string.Join("; ", first.Diagnostics));+ Assert.Equal(first.Advance, second.Advance);+ Assert.Equal(first.Glyphs.Select(g => g.BaselineX), second.Glyphs.Select(g => g.BaselineX));+ Assert.Equal(first.Advance * 2, taller.Advance, 8);+ Assert.Equal(first.ContourCount, taller.ContourCount);+ }++ [Fact]+ public void InterXSelfCrossingNormalizesToAValidRegion()+ {+ var text = PlanarTextProfiles.Build("X", 3);+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ Assert.True(text.ResolvedIntersections > 0);+ Assert.Single(text.Regions);+ Assert.All(text.Regions, r => Assert.True(ResolvedProfile2DValidator.Validate(r).IsValid));+ }++ [Fact]+ public void InterDOverlapNormalizesWithItsCounter()+ {+ var text = PlanarTextProfiles.Build("D", 3);+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ Assert.True(text.ResolvedIntersections > 0);+ Assert.Single(text.Regions);+ Assert.Equal(1, text.CounterCount);+ Assert.Equal(2, text.Regions[0].Loops.Count);+ }++ [Theory]+ [InlineData("CODEX")]+ [InlineData("AETHERIS")]+ public void FullWordsNormalizeToValidExactProfiles(string word)+ {+ var text = PlanarTextProfiles.Build(word, 3, PlanarTextAlignment.Center);+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ Assert.Equal(word.Length, text.Glyphs.Count);+ Assert.Equal(word.Length, text.Regions.Count);+ Assert.Equal(2, text.CounterCount);+ Assert.Equal(word == "CODEX" ? 7 : 10, text.ContourCount);+ Assert.Equal(word == "CODEX" ? 6 : 9, text.ResolvedIntersections);+ Assert.All(text.Regions, r => Assert.True(ResolvedProfile2DValidator.Validate(r).IsValid,+ string.Join("; ", ResolvedProfile2DValidator.Validate(r).Diagnostics)));+ Assert.Contains(text.Regions.SelectMany(r => r.Loops).SelectMany(l => l.Segments),+ s => s.Geometry is LineArcCubicBezier2D);+ }++ [Fact]+ public void CodexRegionsExtrudeThroughTheExactProfileEmitter()+ {+ var text = PlanarTextProfiles.Build("CODEX", 2.5, PlanarTextAlignment.Center);+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ foreach (var region in text.Regions)+ {+ var extrusion = ResolvedProfile2DValidator.Extrude(region, 0.2);+ Assert.True(extrusion.Status == LineArcProfileExtrudeStatus.Succeeded,+ region.Name + ": " + string.Join("; ", extrusion.Diagnostics));+ Assert.NotNull(extrusion.Body);+ }+ }++ [Theory]+ [InlineData("D", 743589.4166666667)]+ [InlineData("X", 607590.0809529623)]+ public void NormalizedAreaMatchesIndependentSkiaPathOpsOracle(string glyph, double fontUnitsSquared)+ {+ var text = PlanarTextProfiles.Build(glyph, 3);+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ double LoopArea(ResolvedProfileLoop2D loop) => Math.Abs(loop.Segments.Sum(s =>+ ResolvedProfile2DValidator.SignedAreaContribution(s.Geometry)));+ var area = text.Regions.Sum(region => LoopArea(region.Loops.Single(loop => loop.IsOuter))+ - region.Loops.Where(loop => !loop.IsOuter).Sum(LoopArea));+ Assert.Equal(fontUnitsSquared * Math.Pow(3d / 2048d, 2), area, 4);+ }++ [Fact]+ public void DStrokeCounterAndExteriorMatchIndependentFillOracle()+ {+ var region = Assert.Single(PlanarTextProfiles.Build("D", 3).Regions);+ (double X, double Y) Scale(int x, int y) => (x * 3d / 2048d, y * 3d / 2048d);+ Assert.True(GlyphRegionNormalizer.Contains(region, Scale(250, 1000)));+ Assert.False(GlyphRegionNormalizer.Contains(region, Scale(500, 1000)));+ Assert.False(GlyphRegionNormalizer.Contains(region, Scale(-100, 1000)));+ }++ [Fact]+ public void SectionArrangementReportsItsExactCubicBoundary()+ {+ var profile = Assert.Single(PlanarTextProfiles.Build("O", 3).Regions);+ var operation = new PrismaticProfileOperation("Text", PrismaticProfileIntent.Add,+ profile.Name, 0, 0.2, "Text", "test");+ var result = ProfileArrangementBuilder.Compose("XY", [operation],+ new Dictionary<string, ResolvedProfile2D> { [profile.Name] = profile }, "text-profile-probe");+ Assert.Null(result.Region);+ Assert.Contains(result.Arrangement.Diagnostics,+ d => d.Contains("bounded-cubic-section-unsupported", StringComparison.Ordinal));+ }++ [Fact]+ public void OCounterExtrudesThroughExistingExactProfilePath()+ {+ var text = PlanarTextProfiles.Build("O", 3);+ Assert.True(text.Succeeded, string.Join("; ", text.Diagnostics));+ var region = Assert.Single(text.Regions);+ Assert.Equal(2, region.Loops.Count);+ var result = ResolvedProfile2DValidator.Extrude(region, 0.25);+ Assert.Equal(LineArcProfileExtrudeStatus.Succeeded, result.Status);+ Assert.NotNull(result.Body);+ }++ [Fact]+ public void UnicodeAndInvalidInputsHaveControlledResults()+ {+ var accented = PlanarTextProfiles.Build("É", 3);+ Assert.True(accented.Succeeded, string.Join("; ", accented.Diagnostics));+ Assert.Single(accented.Glyphs);+ Assert.Contains("text-height-must-be-positive", PlanarTextProfiles.Build("A", 0).Diagnostics);+ Assert.Contains("text-multiline-unsupported-x0", PlanarTextProfiles.Build("A\nB", 3).Diagnostics);+ }+}diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csprojindex cdb4200b..ed724c37 100644--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj@@ -9,6 +9,7 @@</PropertyGroup><ItemGroup>+ <PackageReference Include="Machina.Typography.OpenFont" Version="1.0.0" /><ProjectReference Include="..\Aetheris.Firmament.SchemaGenerator\Aetheris.Firmament.SchemaGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /><ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex fae049a8..3c73e51e 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -532,6 +532,11 @@ public static class FirmamentBuildAndExportreturn roundedBoxExport;}+ if (TryExportV2ThreadBody(v2Parse.Document) is { } threadExport)+ {+ return threadExport;+ }+if (TryExportV2ExactCoaxialPart(v2Parse.Document) is { } exactCoaxialExport){return exactCoaxialExport;@@ -805,6 +810,191 @@ public static class FirmamentBuildAndExportStandardPart: report));}+ private static KernelResult<FirmamentStepExportResult>? TryExportV2ThreadBody(FirmamentV2Document document)+ {+ if (document.Threads is not { Count: > 0 }) return null;+ KernelResult<FirmamentStepExportResult> Failure(string code, string message) =>+ KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ $"thread-{code}: {message}", "FirmamentV2.Thread")]);+ if (document.Threads.Count != 1 || document.Solids.Count != 1 || (document.ModifyBlocks?.Count ?? 0) != 0)+ return Failure("composition-unsupported", "X1 admits one Thread on one unmodified cylindrical support.");+ var feature = document.Threads[0];+ var solid = document.Solid;+ if (feature.SupportSolid != solid.Name)+ return Failure("support-unresolved", $"Surface refers to '{feature.SupportSolid}', but the authored solid is '{solid.Name}'.");+ if (solid.StandardPart is { } authoredPart && feature.SupportRole == "Shank")+ return TryExportV2HexBoltThread(document, feature, authoredPart);+ if (solid.Cylinder is not { } support || feature.SupportRole != "OuterWall")+ return Failure("support-not-cylinder", "Surface must bind to face(<Cylinder>.OuterWall), an analytic cylindrical support.");+ if (!double.IsFinite(feature.MajorDiameterMm) || feature.MajorDiameterMm <= 0d ||+ double.Abs(feature.MajorDiameterMm - 2d * support.Radius) > 1e-6d)+ return Failure("major-diameter-incompatible", "MajorDiameter must be positive and equal to the cylindrical precursor stock diameter.");+ if (!double.IsFinite(feature.PitchMm) || feature.PitchMm <= 0d)+ return Failure("pitch-invalid", "Pitch must be finite and positive.");+ if (!double.IsFinite(feature.LengthMm) || feature.LengthMm <= 0d)+ return Failure("length-invalid", "Length must be finite and positive.");+ if (feature.StartOffsetMm is { } authoredOffset && (!double.IsFinite(authoredOffset) || authoredOffset < 0d))+ return Failure("start-offset-invalid", "StartOffset must be finite and nonnegative.");++ // External 60-degree truncated profile: root width 5P/6 and crest P/8.+ // Each flank has axial run 17P/48, giving depth 17*sqrt(3)*P/48.+ var rootWidth = 5d * feature.PitchMm / 6d;+ var crestWidth = feature.PitchMm / 8d;+ var depth = (rootWidth - crestWidth) * double.Sqrt(3d) / 2d;+ var rootRadius = feature.MajorDiameterMm / 2d - depth;+ if (rootRadius <= 0d)+ return Failure("profile-self-intersection", "The 60-degree profile depth consumes the support radius.");+ var start = feature.StartOffsetMm ?? rootWidth / 2d + 1d;+ var end = start + feature.LengthMm;+ if (start - rootWidth / 2d <= 1e-6d || end + rootWidth / 2d >= support.Height - 1e-6d)+ return Failure("support-bounds", "Thread footprint requires exposed cylindrical stock before and after its finite span.");+ var buildStart = Stopwatch.GetTimestamp();+ var rib = HelicalRibGeometry.Create(new HelicalRibParameters(Point3D.Origin,+ Direction3D.Create(new Vector3D(0d, 0d, 1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d)),+ 0d, support.Height, rootRadius, feature.MajorDiameterMm / 2d, feature.PitchMm,+ start, end, rootWidth, crestWidth));+ if (!rib.IsSuccess) return Failure("geometry-invalid", string.Join(" | ", rib.Diagnostics.Select(d => d.Message)));+ var built = BrepHelicalRib.Create(rib.Value);+ if (!built.IsSuccess) return Failure("brep-invalid", string.Join(" | ", built.Diagnostics.Select(d => d.Message)));+ var constructionMs = Stopwatch.GetElapsedTime(buildStart).TotalMilliseconds;+ var featureId = $"{solid.Name}.{feature.Name}";+ var exportStart = Stopwatch.GetTimestamp();+ var step = Step242Exporter.ExportBody(built.Value.Body, new Step242ExportOptions+ {+ ProductName = featureId,+ ApplicationName = "Aetheris.Firmament.Thread.External.X1",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce+ });+ if (!step.IsSuccess) return Failure("step-export-failed", string.Join(" | ", step.Diagnostics.Select(d => d.Message)));+ var exportMs = Stopwatch.GetElapsedTime(exportStart).TotalMilliseconds;+ var faceDescendants = built.Value.FaceRoles.Select(pair => new SemanticTopologyDescendant(+ $"{featureId}.Face[{pair.Key.Value}]", "Face", pair.Value switch+ {+ var role when role.StartsWith("LeadingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadLeadingFlank,+ var role when role.StartsWith("TrailingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadTrailingFlank,+ var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,+ "StartCap" => SemanticTopologyRole.ThreadStartCap,+ "EndCap" => SemanticTopologyRole.ThreadEndCap,+ _ => SemanticTopologyRole.ThreadRootFace+ }, featureId, Face: pair.Key, ParentStableId: featureId,+ Addressability: SemanticTopologyAddressability.DerivedStable));+ var edgeDescendants = built.Value.EdgeRoles.Select(pair => new SemanticTopologyDescendant(+ $"{featureId}.Edge[{pair.Key.Value}]", "Edge", SemanticTopologyRole.ThreadBoundaryEdge,+ featureId, Edge: pair.Key, ParentStableId: featureId,+ Addressability: SemanticTopologyAddressability.DerivedStable));+ var descendants = faceDescendants.Concat(edgeDescendants).ToArray();+ var correspondence = new SemanticTopologyCorrespondence(featureId, descendants,+ ["Thread", "HelicalRib", "BrepHelicalRib"],+ new Dictionary<string, FirmamentV2SourceSpan> { [featureId] = feature.SourceSpan });+ var report = new FirmamentThreadReport(featureId, $"face({solid.Name}.{feature.SupportRole})",+ feature.MajorDiameterMm, 2d * rootRadius, feature.PitchMm, feature.PitchMm, feature.LengthMm,+ start, start, feature.Hand, "metric-60-degree-truncated", (int)double.Round(rib.Value.Turns), built.Value.Body.Topology.Faces.Count(),+ built.Value.Body.Topology.Edges.Count(), built.Value.Body.Topology.Vertices.Count(),+ built.Value.SeamSplits, constructionMs, exportMs,+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(+ step.Value, featureId, 0, "thread-external", "metric-60-degree", Thread: report)+ { RuntimeBody = built.Value.Body, RuntimeCorrespondence = correspondence });+ }++ private static KernelResult<FirmamentStepExportResult> TryExportV2HexBoltThread(+ FirmamentV2Document document, FirmamentV2ThreadDecl feature, FirmamentV2StandardPartRecord authoredPart)+ {+ KernelResult<FirmamentStepExportResult> Failure(string code, string message) =>+ KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ $"thread-{code}: {message}", "FirmamentV2.Thread")]);+ if (authoredPart.Family != "HexBolt")+ return Failure("support-not-hexbolt", "face(Bolt.Shank) is admitted only for the HexBolt standard part.");+ var definition = StandardLibraryReusableParts.TryCreate(authoredPart.Family, authoredPart.Parameters);+ if (!definition.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(definition.Diagnostics);+ var bolt = definition.Value.HexBolt!;+ if (!double.IsFinite(feature.MajorDiameterMm) || feature.MajorDiameterMm <= 0d ||+ Math.Abs(feature.MajorDiameterMm - bolt.Spec.NominalDiameter) > 1e-6d)+ return Failure("major-diameter-incompatible", "MajorDiameter must equal the HexBolt precursor shank diameter.");+ if (!double.IsFinite(feature.PitchMm) || feature.PitchMm <= 0d)+ return Failure("pitch-invalid", "Pitch must be finite and positive.");+ if (!double.IsFinite(feature.LengthMm) || feature.LengthMm <= 0d)+ return Failure("length-invalid", "Length must be finite and positive.");+ if (feature.StartOffsetMm is { } authoredOffset && (!double.IsFinite(authoredOffset) || authoredOffset < 0d))+ return Failure("start-offset-invalid", "StartOffset must be finite and nonnegative from the under-head shank start.");+ var rootWidth = 5d * feature.PitchMm / 6d;+ var crestWidth = feature.PitchMm / 8d;+ var depth = (rootWidth - crestWidth) * Math.Sqrt(3d) / 2d;+ var rootRadius = feature.MajorDiameterMm / 2d - depth;+ if (rootRadius <= 0d)+ return Failure("profile-self-intersection", "The 60-degree profile depth consumes the support radius.");+ var supportStart = bolt.Spec.UnderHeadRadius;+ var supportEnd = bolt.Dimensions.TipChamferStartX;+ var start = supportStart + (feature.StartOffsetMm ?? rootWidth / 2d + 1d);+ var end = start + feature.LengthMm;+ if (start - rootWidth / 2d <= supportStart + 1e-6d || end + rootWidth / 2d >= supportEnd - 1e-6d)+ return Failure("support-bounds", "Thread footprint requires stock margins inside the HexBolt shank, before the tip chamfer.");+ var buildStart = Stopwatch.GetTimestamp();+ var rib = HelicalRibGeometry.Create(new HelicalRibParameters(Point3D.Origin,+ Direction3D.Create(new Vector3D(1d, 0d, 0d)), Direction3D.Create(new Vector3D(0d, 1d, 0d)),+ supportStart, supportEnd, rootRadius, feature.MajorDiameterMm / 2d, feature.PitchMm,+ start, end, rootWidth, crestWidth));+ if (!rib.IsSuccess) return Failure("geometry-invalid", string.Join(" | ", rib.Diagnostics.Select(d => d.Message)));+ var built = BrepHelicalRib.Create(rib.Value);+ if (!built.IsSuccess) return Failure("brep-invalid", string.Join(" | ", built.Diagnostics.Select(d => d.Message)));+ HexBoltThreadStitch.Result stitched;+ try { stitched = HexBoltThreadStitch.Create(bolt, built.Value); }+ catch (InvalidOperationException ex) { return Failure("hexbolt-stitch-invalid", ex.Message); }+ var constructionMs = Stopwatch.GetElapsedTime(buildStart).TotalMilliseconds;+ var featureId = $"{document.Solid.Name}.{feature.Name}";+ var exportStart = Stopwatch.GetTimestamp();+ var step = Step242Exporter.ExportBody(stitched.Body, new Step242ExportOptions+ {+ ProductName = featureId,+ ApplicationName = "Aetheris.Firmament.Thread.External.X1",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce+ });+ if (!step.IsSuccess) return Failure("step-export-failed", string.Join(" | ", step.Diagnostics.Select(d => d.Message)));+ var exportMs = Stopwatch.GetElapsedTime(exportStart).TotalMilliseconds;+ var descendants = built.Value.FaceRoles+ .Where(pair => stitched.ThreadFaces.ContainsKey(pair.Key))+ .Select(pair => new SemanticTopologyDescendant(+ $"{featureId}.Face[{pair.Key.Value}]", "Face", pair.Value switch+ {+ var role when role.StartsWith("LeadingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadLeadingFlank,+ var role when role.StartsWith("TrailingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadTrailingFlank,+ var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,+ "StartCap" => SemanticTopologyRole.ThreadStartCap,+ "EndCap" => SemanticTopologyRole.ThreadEndCap,+ _ => SemanticTopologyRole.ThreadRootFace+ }, featureId, Face: stitched.ThreadFaces[pair.Key], ParentStableId: featureId,+ Addressability: SemanticTopologyAddressability.DerivedStable))+ .Concat(built.Value.EdgeRoles.Where(pair => stitched.ThreadEdges.ContainsKey(pair.Key))+ .Select(pair => new SemanticTopologyDescendant(+ $"{featureId}.Edge[{pair.Key.Value}]", "Edge", SemanticTopologyRole.ThreadBoundaryEdge,+ featureId, Edge: stitched.ThreadEdges[pair.Key], ParentStableId: featureId,+ Addressability: SemanticTopologyAddressability.DerivedStable))).ToArray();+ var correspondence = new SemanticTopologyCorrespondence(featureId, descendants,+ ["Thread", "HelicalRib", "HexBoltThreadStitch"],+ new Dictionary<string, FirmamentV2SourceSpan> { [featureId] = feature.SourceSpan });+ var boltSemantics = bolt.Semantics.Descendants+ .Where(item => !item.StableId.Contains(".ThreadRegion", StringComparison.Ordinal)+ && (item.Face is null || stitched.BoltFaces.ContainsKey(item.Face.Value)))+ .Select(item => new FirmamentStandardPartSemanticReport(item.StableId, item.Kind.ToString(),+ item.ParentStableId, item.Face is { } face ? stitched.BoltFaces[face].Value : null,+ item.Metadata)).ToArray();+ var boltReport = new FirmamentStandardPartReport(authoredPart.Family,+ document.StaticAuthoring?.Templates.SingleOrDefault()?.Name,+ bolt.DeterministicSignature, authoredPart.Parameters, boltSemantics);+ var report = new FirmamentThreadReport(featureId, $"face({document.Solid.Name}.Shank)",+ feature.MajorDiameterMm, 2d * rootRadius, feature.PitchMm, feature.PitchMm, feature.LengthMm,+ start - supportStart, start, feature.Hand, "metric-60-degree-truncated", (int)Math.Round(rib.Value.Turns),+ stitched.Body.Topology.Faces.Count(), stitched.Body.Topology.Edges.Count(),+ stitched.Body.Topology.Vertices.Count(), built.Value.SeamSplits, constructionMs, exportMs,+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(+ step.Value, featureId, 0, "thread-external-hexbolt", "metric-60-degree",+ StandardPart: boltReport, Thread: report)+ { RuntimeBody = stitched.Body, RuntimeCorrespondence = correspondence });+ }+private static KernelResult<FirmamentStepExportResult>? TryExportV2ExactCoaxialPart(FirmamentV2Document document){if (document.Solids.Count != 1 || document.Solid.ExactCoaxialPart is not { } authored) return null;diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 2506c257..e864ce16 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -34,7 +34,8 @@ public sealed record FirmamentStepExportResult(FirmamentRevolveReport? Revolve = null,FirmamentGearReport? Gear = null,Aetheris.Kernel.Firmament.FirmamentV2.FirmamentPlateauReport? Plateau = null,- FirmamentPerforationReport? Perforation = null)+ FirmamentPerforationReport? Perforation = null,+ FirmamentThreadReport? Thread = null){// In-process display can use the exact body that was exported to STEP.// It is intentionally absent from CLI/JSON artifact serialization.@@ -42,6 +43,13 @@ public sealed record FirmamentStepExportResult([JsonIgnore] public SemanticTopologyCorrespondence? RuntimeCorrespondence { get; init; }}+public sealed record FirmamentThreadReport(+ string FeatureId, string Support, double MajorDiameterMm, double RootDiameterMm,+ double PitchMm, double LeadMm, double LengthMm, double StartOffsetMm, double AxialStartMm,+ string Hand, string ProfileFamily, int Turns,+ int Faces, int Edges, int Vertices, int SeamSplits,+ double ConstructionMilliseconds, double StepExportMilliseconds, string StepSha256);+public sealed record FirmamentPerforationReport(string FeatureId, string Support, string Layout, double Diameter, double Pitch,double Margin, double MinimumLigament, int InstanceCount,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex 683ef6ed..b1bf5f33 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -26,7 +26,12 @@ public static class FirmamentLanguageServiceIReadOnlyList<FirmamentAuthoringField> fields;string context;- if (IsInsidePerforation(source, offset))+ if (IsInsideThread(source, offset))+ {+ fields = FirmamentSchemaAuthoringFields.For("Thread");+ context = "Thread";+ }+ else if (IsInsidePerforation(source, offset)){fields = FirmamentSchemaAuthoringFields.For("Perforation");context = "Perforation";@@ -40,7 +45,7 @@ public static class FirmamentLanguageServiceelse{var entries = FirmamentSemanticSchemas.All- .Where(item => item.Name is "Helix" or "Loft" or "Perforation" && item.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && item.Entry is not null)+ .Where(item => item.Name is "Helix" or "Loft" or "Perforation" or "Thread" && item.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && item.Entry is not null).Select(item => new FirmamentLanguageEntry(item.Id.Value, item.Name, item.Context ?? string.Empty, item.Entry!)).ToArray();return new(document, revision, entries.Length > 0 ? "ConstructEntry" : "Unsupported",prefixStart, prefix.Length, [], [], entries);@@ -62,4 +67,11 @@ public static class FirmamentLanguageServicevar header = Regex.Matches(prefix, @"\bPerforation\s+[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant).Cast<Match>().LastOrDefault();return header is not null && !prefix[(header.Index + header.Length)..].Contains('}');}++ private static bool IsInsideThread(string source, int offset)+ {+ var prefix = source[..offset];+ var header = Regex.Matches(prefix, @"\bThread\s+[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant).Cast<Match>().LastOrDefault();+ return header is not null && !prefix[(header.Index + header.Length)..].Contains('}');+ }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex c18f43a3..f3222a90 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -3,7 +3,7 @@ using Aetheris.Surfacing;namespace Aetheris.Kernel.Firmament.FirmamentV2;-public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null, IReadOnlyList<FirmamentV2ClosedBoundary2Decl>? Boundaries = null)+public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null, IReadOnlyList<FirmamentV2ClosedBoundary2Decl>? Boundaries = null, IReadOnlyList<FirmamentV2ThreadDecl>? Threads = null){public FirmamentV2SolidBinding Solid => Solids[^1];public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>@@ -15,6 +15,9 @@ public sealed record FirmamentV2Document(string ModelName, string Units, IReadOn}public sealed record FirmamentV2SourceSpan(int Start, int Length);+public sealed record FirmamentV2ThreadDecl(string Name, string SupportSolid, string SupportRole,+ double MajorDiameterMm, double PitchMm, double LengthMm, double? StartOffsetMm,+ string Hand, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2AuthoredField(string Name, FirmamentV2SourceSpan DeclarationSpan, FirmamentV2SourceSpan ValueSpan);public enum FirmamentV2PrimitiveType { Int, Float, Length, Angle, String, Bool }public enum FirmamentV2ToleranceKind { Bilateral, Asymmetric }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex a1680483..d6a4b4f4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -291,6 +291,7 @@ public static class FirmamentV2Parser// binder so a misspelled family can never disappear from a Modify block.private static readonly Regex CanonicalHoleHeaderRegex = new(@"\bHole\s*<\s*(?<variant>[A-Za-z_][A-Za-z0-9_]*)\s*>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex CanonicalPerforationHeaderRegex = new(@"\bPerforation\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex CanonicalThreadHeaderRegex = new(@"\bThread\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex CanonicalEdgeHeaderRegex = new(@"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex CanonicalRecognizeHeaderRegex = new(@"\bRecognize\s+(?<body>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex CanonicalRegionHeaderRegex = new(@"\bRegion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);@@ -983,7 +984,7 @@ public static class FirmamentV2Parservar known = new HashSet<string>(StringComparer.Ordinal){"Box", "Cylinder", "Cone", "Sphere", "Torus", "RoundedBox", "Frustum", "StandardPart", "ExactCoaxialPart", "Point2", "Line2", "Rect2", "Circle2", "Ellipse2Guide", "SmoothRoundedRect2", "Plateau", "Concept", "Struct", "Construction", "Profile", "Span", "Compose", "Boss", "Pocket", "AddOffset", "RemoveOffset", "EdgeFinish",- "Record", "Static", "Template", "template", "ProfileDelta", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert"+ "Record", "Static", "Template", "template", "ProfileDelta", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert", "Thread"};var compatibilityOnly = new HashSet<string>(StringComparer.Ordinal){@@ -1325,7 +1326,10 @@ public static class FirmamentV2Parserprivate static FirmamentV2ParseResult AttachVolumeAssertionsAndSymbols(FirmamentV2ParseResult parsed, string source, FirmamentV2StaticAuthoringDocument? staticAuthoring, List<string> diagnostics){if (parsed.Document is null) return parsed;- var normalized = parsed.Document with { StaticAuthoring = staticAuthoring, VolumeAssertions = ParseCanonicalVolumeAssertions(source, diagnostics) };+ var threads = ParseCanonicalThreads(source, diagnostics);+ if (threads is null)+ return FirmamentV2ParseResult.Failure(parsed.Diagnostics.Concat(diagnostics).Distinct(StringComparer.Ordinal).Order().ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid);+ var normalized = parsed.Document with { StaticAuthoring = staticAuthoring, VolumeAssertions = ParseCanonicalVolumeAssertions(source, diagnostics), Threads = threads };normalized = BindSemanticConstraintProjections(normalized, diagnostics);if (diagnostics.Any(IsFatalDiagnosticCode))return FirmamentV2ParseResult.Failure(parsed.Diagnostics.Concat(diagnostics).Distinct(StringComparer.Ordinal).Order().ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid);@@ -1584,6 +1588,59 @@ public static class FirmamentV2Parserreturn result;}+ private static IReadOnlyList<FirmamentV2ThreadDecl>? ParseCanonicalThreads(string source, List<string> diagnostics)+ {+ var model = CanonicalModelRegex.Match(source);+ var rootOpen = model.Success ? source.IndexOf('{', model.Index) : -1;+ var rootClose = rootOpen >= 0 ? FindMatchingBrace(source, rootOpen) : -1;+ if (rootClose < 0) return [];+ var threads = new List<FirmamentV2ThreadDecl>();+ foreach (Match header in CanonicalThreadHeaderRegex.Matches(source))+ {+ if (header.Index <= rootOpen || header.Index >= rootClose || BraceDepth(source, rootOpen + 1, header.Index) != 0) continue;+ var open = source.IndexOf('{', header.Index);+ var close = FindMatchingBrace(source, open);+ if (close < 0 || close > rootClose) { diagnostics.Add("firmament-v2-thread-malformed"); return null; }+ var body = source[(open + 1)..close];+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (Match field in Regex.Matches(body, @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>[^\r\n}]+)", RegexOptions.CultureInvariant))+ {+ var name = field.Groups["name"].Value;+ if (name is not ("Surface" or "MajorDiameter" or "Pitch" or "Length" or "StartOffset" or "Hand") ||+ !fields.TryAdd(name, field.Groups["value"].Value.Trim().TrimEnd(';').Trim()))+ { diagnostics.Add("firmament-v2-thread-field-invalid:" + name); return null; }+ }+ if (fields.Count == 0 || !fields.TryGetValue("Surface", out var support) ||+ !fields.TryGetValue("MajorDiameter", out var major) ||+ !fields.TryGetValue("Pitch", out var pitch) ||+ !fields.TryGetValue("Length", out var length))+ { diagnostics.Add("firmament-v2-thread-required-fields-missing"); return null; }+ var selector = Regex.Match(support, @"^face\(\s*(?<solid>[A-Za-z_]\w*)\.(?<role>[A-Za-z_+][A-Za-z0-9_+\-]*)\s*\)$", RegexOptions.CultureInvariant);+ if (!selector.Success ||+ !TryLength(major, out var majorMm) || !TryLength(pitch, out var pitchMm) ||+ !TryLength(length, out var lengthMm) ||+ (fields.TryGetValue("StartOffset", out var offset) && !TryLength(offset, out _)))+ { diagnostics.Add("firmament-v2-thread-field-value-invalid"); return null; }+ var startOffset = fields.TryGetValue("StartOffset", out var start)+ ? double.Parse(start[..^2], CultureInfo.InvariantCulture) : (double?)null;+ if (fields.TryGetValue("Hand", out var hand) && hand != "Right")+ { diagnostics.Add("firmament-v2-thread-hand-unsupported:" + hand); return null; }+ if (threads.Any(thread => thread.Name == header.Groups["name"].Value))+ { diagnostics.Add("firmament-v2-thread-name-duplicate:" + header.Groups["name"].Value); return null; }+ threads.Add(new(header.Groups["name"].Value, selector.Groups["solid"].Value,+ selector.Groups["role"].Value, majorMm, pitchMm, lengthMm, startOffset,+ fields.TryGetValue("Hand", out var authoredHand) ? authoredHand : "Right",+ new FirmamentV2SourceSpan(header.Index, close - header.Index + 1)));+ }+ return threads;++ static bool TryLength(string text, out double value)+ {+ var match = Regex.Match(text, @"^(?<number>[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)mm$", RegexOptions.CultureInvariant);+ return double.TryParse(match.Groups["number"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && match.Success && double.IsFinite(value);+ }+ }+private static FirmamentV2PrimitiveRecord? ParseCanonicalPrimitive(string type, string body, List<string> diagnostics){double Number(string field, bool allowZero = false)@@ -2251,7 +2308,7 @@ public static class FirmamentV2Parser|| code.StartsWith(ConceptIrResolver.PointProjectionUnsupported, StringComparison.Ordinal)|| code.StartsWith("firmament-static-", StringComparison.Ordinal);- public static bool IsFatalDiagnosticCode(string code) => code.StartsWith("perforation-", StringComparison.Ordinal) || code.StartsWith("firmament-v2-hole-wall-", StringComparison.Ordinal) || code.StartsWith(RevolveAuthoringParser.Prefix, StringComparison.Ordinal) || code.StartsWith(FirmamentV2FeatureExpansion.Prefix, StringComparison.Ordinal) || code.StartsWith("firmament-pipeline-", StringComparison.Ordinal) || code.StartsWith("firmament-profile-pipeline-", StringComparison.Ordinal) || code.StartsWith("firmament-profile-traceloop-", StringComparison.Ordinal) || code.StartsWith("firmament-profile-segment-", StringComparison.Ordinal) || code.StartsWith("firmament-boss-", StringComparison.Ordinal) || code.StartsWith("firmament-pocket-", StringComparison.Ordinal) || code.StartsWith("feature-support-", StringComparison.Ordinal) || code.StartsWith("compose-role-cardinality:", StringComparison.Ordinal) || code.StartsWith(ModifyTargetNotBoundToActiveCompose, StringComparison.Ordinal) || code.StartsWith("firmament-v2-assert-volume-", StringComparison.Ordinal) || code.StartsWith(SemanticConstraintMalformed, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintUnsupported, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintDimensionMismatch, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintValidationFailed, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnknownRequire, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnsupportedKind, StringComparison.Ordinal) || code.StartsWith(PmiProjectedFieldMustNotOverrideSourceConstraint, StringComparison.Ordinal) || code.StartsWith(AssertVolumeKindUnsupported, StringComparison.Ordinal) || code.StartsWith(CanonicalDeclarationUnknown + ":", StringComparison.Ordinal) || code.StartsWith(CanonicalConstructNotYetSupported + ":", StringComparison.Ordinal) || code.StartsWith(EdgeFinishProfileComposeBoundaryUnsupported, StringComparison.Ordinal) || IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;+ public static bool IsFatalDiagnosticCode(string code) => code.StartsWith("firmament-v2-thread-", StringComparison.Ordinal) || code.StartsWith("perforation-", StringComparison.Ordinal) || code.StartsWith("firmament-v2-hole-wall-", StringComparison.Ordinal) || code.StartsWith(RevolveAuthoringParser.Prefix, StringComparison.Ordinal) || code.StartsWith(FirmamentV2FeatureExpansion.Prefix, StringComparison.Ordinal) || code.StartsWith("firmament-pipeline-", StringComparison.Ordinal) || code.StartsWith("firmament-profile-pipeline-", StringComparison.Ordinal) || code.StartsWith("firmament-profile-traceloop-", StringComparison.Ordinal) || code.StartsWith("firmament-profile-segment-", StringComparison.Ordinal) || code.StartsWith("firmament-boss-", StringComparison.Ordinal) || code.StartsWith("firmament-pocket-", StringComparison.Ordinal) || code.StartsWith("feature-support-", StringComparison.Ordinal) || code.StartsWith("compose-role-cardinality:", StringComparison.Ordinal) || code.StartsWith(ModifyTargetNotBoundToActiveCompose, StringComparison.Ordinal) || code.StartsWith("firmament-v2-assert-volume-", StringComparison.Ordinal) || code.StartsWith(SemanticConstraintMalformed, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintUnsupported, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintDimensionMismatch, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintValidationFailed, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnknownRequire, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnsupportedKind, StringComparison.Ordinal) || code.StartsWith(PmiProjectedFieldMustNotOverrideSourceConstraint, StringComparison.Ordinal) || code.StartsWith(AssertVolumeKindUnsupported, StringComparison.Ordinal) || code.StartsWith(CanonicalDeclarationUnknown + ":", StringComparison.Ordinal) || code.StartsWith(CanonicalConstructNotYetSupported + ":", StringComparison.Ordinal) || code.StartsWith(EdgeFinishProfileComposeBoundaryUnsupported, StringComparison.Ordinal) || IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.csindex 709a0817..156d9fb4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs@@ -35,6 +35,20 @@ public static class HoleSemanticDeclaration[FirmamentOutput("Wall", "Wall", "Face", SourceRole = nameof(Materializer.SemanticTopologyRole.HoleWallFace))]public static class PerforationSemanticDeclaration { }+[FirmamentConstruct("Thread", "Thread", Context = "Model on one cylindrical solid", Entry = "Thread MainThread {\n Surface: face(Shank.OuterWall)\n MajorDiameter: 8mm\n Pitch: 1.25mm\n Length: 30mm\n StartOffset: 1mm\n}", Description = "Modeled right-hand, single-start external metric-style thread on cylindrical stock.")]+[FirmamentField("Surface", "Surface", FirmamentSchemaValueKind.FaceSelector, Required = true, Description = "Semantic cylindrical support, such as face(Shank.OuterWall).")]+[FirmamentField("MajorDiameter", "MajorDiameter", FirmamentSchemaValueKind.Length, Required = true, Description = "Crest envelope diameter.")]+[FirmamentField("Pitch", "Pitch", FirmamentSchemaValueKind.Length, Required = true, Description = "Axial advance per turn; lead equals pitch.")]+[FirmamentField("Length", "Length", FirmamentSchemaValueKind.Length, Required = true, Description = "Finite axial thread span; X1 materialization admits complete turns.")]+[FirmamentField("StartOffset", "StartOffset", FirmamentSchemaValueKind.Length, Description = "Optional thread centerline offset from the support axial start; omission derives a stock margin.")]+[FirmamentField("Hand", "Hand", FirmamentSchemaValueKind.Choice, Default = "Right", Choices = ["Right"], Description = "Right-hand thread in X1.")]+[FirmamentOutput("RootDiameter", "RootDiameter", "Length")]+[FirmamentOutput("TurnCount", "TurnCount", "Count")]+[FirmamentOutput("Crest", "Crest", "Face", SourceRole = "ThreadCrest")]+[FirmamentOutput("LeadingFlank", "LeadingFlank", "Face", SourceRole = "ThreadLeadingFlank")]+[FirmamentOutput("TrailingFlank", "TrailingFlank", "Face", SourceRole = "ThreadTrailingFlank")]+public static class ThreadSemanticDeclaration { }+[FirmamentConstruct("Helix", "Helix", Context = "WireForm", Entry = "Model HelixWitness {\n Units: mm\n WireForm Spring {\n Diameter: 2mm\n Material: Standard.Materials.StainlessSteel.304_Annealed\n StartFrame { Origin: [0mm, 0mm, 0mm]; Tangent: [1, 0, 0]; Up: [0, 0, 1] }\n Helix Winding { Radius: 6mm; Turns: 1; Pitch: 5mm; Handedness: RightHanded; StartPhase: 0deg }\n }\n}\n", CompatibilityAlias = "AxisCoil", Description = "WireForm centerline helix.")][FirmamentField("Radius", "Radius", FirmamentSchemaValueKind.Length, Required = true, Description = "Centerline radius.")][FirmamentField("Turns", "Turns", FirmamentSchemaValueKind.Scalar, Required = true, Description = "Number of winding turns.")]diff --git a/Aetheris.Kernel.Firmament/Materializer/GlyphRegionNormalizer.cs b/Aetheris.Kernel.Firmament/Materializer/GlyphRegionNormalizer.csnew file mode 100644index 00000000..c4aee73d--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/GlyphRegionNormalizer.cs@@ -0,0 +1,301 @@+namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>A bounded non-zero-winding arrangement of one TrueType glyph's line and Bézier contours.</summary>+internal static class GlyphRegionNormalizer+{+ private const double GeometryTolerance = 1e-7;+ private const double VertexTolerance = 1e-6;+ private const double SideOffset = 1e-5;++ internal sealed record Region(IReadOnlyList<LineArcProfileCurve2D> Outer,+ IReadOnlyList<IReadOnlyList<LineArcProfileCurve2D>> Holes);+ internal sealed record Result(IReadOnlyList<Region> Regions, int Intersections,+ IReadOnlyList<string> Diagnostics);+ private sealed record Source(int Contour, int Segment, LineArcProfileCurve2D Curve);+ private sealed record Piece(double From, double To, (double X, double Y) Start, (double X, double Y) End);+ private sealed record Boundary(string Id, LineArcProfileCurve2D Curve);+ private sealed record BoundaryLoop(IReadOnlyList<LineArcProfileCurve2D> Curves, double Area);++ internal static bool Contains(ResolvedProfile2D profile, (double X, double Y) point) =>+ Winding(profile.Loops.SelectMany((loop, index) => loop.Segments.Select((segment, number) =>+ new Source(index, number, segment.Geometry))).ToArray(), point) != 0;++ internal static Result Normalize(IReadOnlyList<IReadOnlyList<LineArcProfileCurve2D>> contours)+ {+ var diagnostics = new List<string>();+ var source = contours.SelectMany((contour, index) => contour.Select((curve, segment) =>+ new Source(index, segment, curve))).ToArray();+ if (source.Any(s => s.Curve is not (LineArcLineSegment2D or LineArcCubicBezier2D)))+ return new([], 0, ["glyph-region-unsupported-curve"]);+ var pieces = source.Select(s => Flatten(s.Curve)).ToArray();+ var splits = source.Select(_ => new List<double> { 0, 1 }).ToArray();+ var intersectionKeys = new HashSet<string>(StringComparer.Ordinal);+ for (var i = 0; i < source.Length; i++)+ for (var j = i + 1; j < source.Length; j++)+ {+ if (!BoxesOverlap(source[i].Curve, source[j].Curve)) continue;+ foreach (var a in pieces[i]) foreach (var b in pieces[j])+ {+ if (!SegmentIntersection(a.Start, a.End, b.Start, b.End, out var u, out var v)) continue;+ var ta = a.From + (a.To - a.From) * u;+ var tb = b.From + (b.To - b.From) * v;+ if (!Refine(source[i].Curve, source[j].Curve, ref ta, ref tb)) continue;+ if (ta < -1e-8 || ta > 1 + 1e-8 || tb < -1e-8 || tb > 1 + 1e-8) continue;+ splits[i].Add(Math.Clamp(ta, 0, 1));+ splits[j].Add(Math.Clamp(tb, 0, 1));+ if (ta > 1e-8 && ta < 1 - 1e-8 && tb > 1e-8 && tb < 1 - 1e-8)+ intersectionKeys.Add($"{i}:{j}:{Math.Round(ta / 1e-7)}:{Math.Round(tb / 1e-7)}");+ }+ }++ var boundary = new List<Boundary>();+ for (var i = 0; i < source.Length; i++)+ {+ var parameters = splits[i].Order().Aggregate(new List<double>(), (list, value) =>+ {+ if (list.Count == 0 || value - list[^1] > 1e-8) list.Add(value);+ return list;+ });+ for (var j = 0; j < parameters.Count - 1; j++)+ {+ var from = parameters[j]; var to = parameters[j + 1];+ if (to - from <= 1e-8) continue;+ var curve = Subcurve(source[i].Curve, from, to);+ if (Distance(At(curve, 0), At(curve, 1)) < GeometryTolerance) continue;+ var mid = At(curve, .5); var tangent = Tangent(curve, .5);+ var length = Math.Sqrt(tangent.X * tangent.X + tangent.Y * tangent.Y);+ if (length < GeometryTolerance) { diagnostics.Add("glyph-region-degenerate-tangent"); continue; }+ var left = (mid.X - tangent.Y * SideOffset / length, mid.Y + tangent.X * SideOffset / length);+ var right = (mid.X + tangent.Y * SideOffset / length, mid.Y - tangent.X * SideOffset / length);+ var leftFilled = Winding(source, left) != 0;+ var rightFilled = Winding(source, right) != 0;+ if (leftFilled == rightFilled) continue;+ boundary.Add(new($"{i}:{j}", leftFilled ? curve : Reverse(curve)));+ }+ }+ var distinct = boundary.GroupBy(b => GeometryKey(b.Curve), StringComparer.Ordinal)+ .Select(group => group.OrderBy(item => item.Id, StringComparer.Ordinal).First())+ .OrderBy(item => item.Id, StringComparer.Ordinal).ToArray();+ var incoming = distinct.GroupBy(b => Key(At(b.Curve, 1))).ToDictionary(g => g.Key, g => g.Count());+ var outgoing = distinct.GroupBy(b => Key(At(b.Curve, 0))).ToDictionary(g => g.Key, g => g.ToArray());+ foreach (var vertex in incoming.Keys.Concat(outgoing.Keys).Distinct())+ if (incoming.GetValueOrDefault(vertex) != 1 || outgoing.GetValueOrDefault(vertex)?.Length != 1)+ diagnostics.Add($"glyph-region-ambiguous-vertex:{vertex}");+ if (diagnostics.Count > 0) return new([], intersectionKeys.Count, diagnostics.Distinct().ToArray());++ var visited = new HashSet<string>(StringComparer.Ordinal);+ var loops = new List<BoundaryLoop>();+ foreach (var seed in distinct)+ {+ if (!visited.Add(seed.Id)) continue;+ var firstKey = Key(At(seed.Curve, 0));+ var current = seed;+ var curves = new List<LineArcProfileCurve2D> { seed.Curve };+ while (Key(At(current.Curve, 1)) != firstKey)+ {+ var nextKey = Key(At(current.Curve, 1));+ if (!outgoing.TryGetValue(nextKey, out var options) || options.Length != 1 ||+ !visited.Add(options[0].Id))+ {+ diagnostics.Add($"glyph-region-open-boundary:{nextKey}"); break;+ }+ current = options[0]; curves.Add(current.Curve);+ }+ if (diagnostics.Count > 0) break;+ var area = curves.Sum(ResolvedProfile2DValidator.SignedAreaContribution);+ if (Math.Abs(area) < GeometryTolerance * GeometryTolerance)+ diagnostics.Add("glyph-region-zero-area-loop");+ else loops.Add(new(curves, area));+ }+ if (diagnostics.Count > 0) return new([], intersectionKeys.Count, diagnostics.Distinct().ToArray());+ var outers = loops.Where(l => l.Area > 0).ToArray();+ var holes = loops.Where(l => l.Area < 0).ToArray();+ var regions = new List<Region>();+ foreach (var outer in outers)+ {+ var nested = holes.Where(h => Winding(outer.Curves.Select(c => new Source(0, 0, c)).ToArray(),+ At(h.Curves[0], 0)) != 0).ToArray();+ regions.Add(new(outer.Curves, nested.Select(h => h.Curves).ToArray()));+ }+ foreach (var hole in holes)+ if (!regions.Any(r => r.Holes.Any(h => ReferenceEquals(h, hole.Curves))))+ diagnostics.Add("glyph-region-uncontained-counter");+ return diagnostics.Count == 0+ ? new(regions, intersectionKeys.Count, [])+ : new([], intersectionKeys.Count, diagnostics.Distinct().ToArray());+ }++ private static IReadOnlyList<Piece> Flatten(LineArcProfileCurve2D curve)+ {+ if (curve is LineArcLineSegment2D line) return [new(0, 1, line.Start, line.End)];+ var result = new List<Piece>();+ void Visit(LineArcCubicBezier2D cubic, double from, double to, int depth)+ {+ var chord = Distance(cubic.Start, cubic.End);+ var flat = chord < GeometryTolerance+ ? Math.Max(Distance(cubic.Control1, cubic.Start), Distance(cubic.Control2, cubic.Start))+ : Math.Max(PointLineDistance(cubic.Control1, cubic.Start, cubic.End),+ PointLineDistance(cubic.Control2, cubic.Start, cubic.End));+ if (flat <= GeometryTolerance / 4 || depth >= 18)+ {+ result.Add(new(from, to, cubic.Start, cubic.End)); return;+ }+ var (left, right) = Divide(cubic, .5);+ var mid = (from + to) / 2;+ Visit(left, from, mid, depth + 1); Visit(right, mid, to, depth + 1);+ }+ Visit((LineArcCubicBezier2D)curve, 0, 1, 0);+ return result;+ }++ private static bool BoxesOverlap(LineArcProfileCurve2D a, LineArcProfileCurve2D b)+ {+ static (double MinX, double MaxX, double MinY, double MaxY) Bounds(LineArcProfileCurve2D c)+ {+ var points = c is LineArcLineSegment2D l ? new[] { l.Start, l.End } :+ c is LineArcCubicBezier2D q ? new[] { q.Start, q.Control1, q.Control2, q.End } : [];+ return (points.Min(p => p.X), points.Max(p => p.X), points.Min(p => p.Y), points.Max(p => p.Y));+ }+ var x = Bounds(a); var y = Bounds(b);+ return x.MinX <= y.MaxX + GeometryTolerance && y.MinX <= x.MaxX + GeometryTolerance &&+ x.MinY <= y.MaxY + GeometryTolerance && y.MinY <= x.MaxY + GeometryTolerance;+ }++ private static bool SegmentIntersection((double X, double Y) a, (double X, double Y) b,+ (double X, double Y) c, (double X, double Y) d, out double u, out double v)+ {+ var r = (b.X - a.X, b.Y - a.Y); var s = (d.X - c.X, d.Y - c.Y);+ var denominator = Cross(r, s);+ if (Math.Abs(denominator) < 1e-14) { u = v = 0; return false; }+ var delta = (c.X - a.X, c.Y - a.Y);+ u = Cross(delta, s) / denominator; v = Cross(delta, r) / denominator;+ return u >= -1e-7 && u <= 1 + 1e-7 && v >= -1e-7 && v <= 1 + 1e-7;+ }++ private static bool Refine(LineArcProfileCurve2D a, LineArcProfileCurve2D b, ref double ta, ref double tb)+ {+ for (var i = 0; i < 12; i++)+ {+ var pa = At(a, ta); var pb = At(b, tb);+ var da = Tangent(a, ta); var db = Tangent(b, tb);+ var det = Cross(da, db);+ if (Math.Abs(det) < 1e-14) break;+ var delta = (pb.X - pa.X, pb.Y - pa.Y);+ ta += Cross(delta, db) / det;+ tb += Cross(delta, da) / det;+ if (ta < -.01 || ta > 1.01 || tb < -.01 || tb > 1.01) return false;+ if (Distance(At(a, ta), At(b, tb)) < 1e-10) break;+ }+ return Distance(At(a, ta), At(b, tb)) < GeometryTolerance / 4;+ }++ private static int Winding(IReadOnlyList<Source> source, (double X, double Y) point)+ {+ var count = 0;+ foreach (var item in source)+ {+ if (item.Curve is LineArcLineSegment2D line)+ {+ if ((line.Start.Y <= point.Y && point.Y < line.End.Y) ||+ (line.End.Y <= point.Y && point.Y < line.Start.Y))+ {+ var x = line.Start.X + (point.Y - line.Start.Y) *+ (line.End.X - line.Start.X) / (line.End.Y - line.Start.Y);+ if (x > point.X) count += Math.Sign(line.End.Y - line.Start.Y);+ }+ continue;+ }+ var cubic = (LineArcCubicBezier2D)item.Curve;+ var a = -cubic.Start.Y + 3 * cubic.Control1.Y - 3 * cubic.Control2.Y + cubic.End.Y;+ var b = 3 * cubic.Start.Y - 6 * cubic.Control1.Y + 3 * cubic.Control2.Y;+ var c = -3 * cubic.Start.Y + 3 * cubic.Control1.Y;+ var intervals = new List<double> { 0, 1 };+ if (Math.Abs(a) < 1e-14)+ {+ if (Math.Abs(b) > 1e-14) intervals.Add(-c / (2 * b));+ }+ else+ {+ var discriminant = b * b - 3 * a * c;+ if (discriminant >= 0)+ {+ var root = Math.Sqrt(discriminant);+ intervals.Add((-b - root) / (3 * a)); intervals.Add((-b + root) / (3 * a));+ }+ }+ var ordered = intervals.Where(t => t >= 0 && t <= 1).Distinct().Order().ToArray();+ for (var k = 0; k < ordered.Length - 1; k++)+ {+ var lo = ordered[k]; var hi = ordered[k + 1];+ var y0 = At(cubic, lo).Y; var y1 = At(cubic, hi).Y;+ if (Math.Abs(y1 - y0) < 1e-14 ||+ point.Y < Math.Min(y0, y1) || point.Y >= Math.Max(y0, y1)) continue;+ for (var iteration = 0; iteration < 48; iteration++)+ {+ var mid = (lo + hi) / 2;+ if ((At(cubic, mid).Y < point.Y) == (y1 > y0)) lo = mid;+ else hi = mid;+ }+ if (At(cubic, (lo + hi) / 2).X > point.X) count += Math.Sign(y1 - y0);+ }+ }+ return count;+ }++ private static LineArcProfileCurve2D Subcurve(LineArcProfileCurve2D curve, double from, double to)+ {+ if (curve is LineArcLineSegment2D) return new LineArcLineSegment2D(At(curve, from), At(curve, to));+ var cubic = (LineArcCubicBezier2D)curve;+ if (from > 0) cubic = Divide(cubic, from).Right;+ if (to < 1) cubic = Divide(cubic, (to - from) / (1 - from)).Left;+ return cubic;+ }++ private static (LineArcCubicBezier2D Left, LineArcCubicBezier2D Right) Divide(LineArcCubicBezier2D c, double t)+ {+ var a = Mix(c.Start, c.Control1, t); var b = Mix(c.Control1, c.Control2, t);+ var d = Mix(c.Control2, c.End, t); var e = Mix(a, b, t); var f = Mix(b, d, t);+ var p = Mix(e, f, t);+ return (new(c.Start, a, e, p), new(p, f, d, c.End));+ }++ private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D l => new LineArcLineSegment2D(l.End, l.Start),+ LineArcCubicBezier2D c => new LineArcCubicBezier2D(c.End, c.Control2, c.Control1, c.Start),+ _ => throw new NotSupportedException()+ };+ private static (double X, double Y) At(LineArcProfileCurve2D curve, double t) => curve switch+ {+ LineArcLineSegment2D l => Mix(l.Start, l.End, t),+ LineArcCubicBezier2D c => Cubic(c, t),+ _ => throw new NotSupportedException()+ };+ private static (double X, double Y) Cubic(LineArcCubicBezier2D c, double t)+ {+ var u = 1 - t;+ return (u*u*u*c.Start.X + 3*u*u*t*c.Control1.X + 3*u*t*t*c.Control2.X + t*t*t*c.End.X,+ u*u*u*c.Start.Y + 3*u*u*t*c.Control1.Y + 3*u*t*t*c.Control2.Y + t*t*t*c.End.Y);+ }+ private static (double X, double Y) Tangent(LineArcProfileCurve2D curve, double t) => curve switch+ {+ LineArcLineSegment2D l => (l.End.X - l.Start.X, l.End.Y - l.Start.Y),+ LineArcCubicBezier2D c => (3*((1-t)*(1-t)*(c.Control1.X-c.Start.X)+2*(1-t)*t*(c.Control2.X-c.Control1.X)+t*t*(c.End.X-c.Control2.X)),+ 3*((1-t)*(1-t)*(c.Control1.Y-c.Start.Y)+2*(1-t)*t*(c.Control2.Y-c.Control1.Y)+t*t*(c.End.Y-c.Control2.Y))),+ _ => throw new NotSupportedException()+ };+ private static (double X, double Y) Mix((double X, double Y) a, (double X, double Y) b, double t)+ => (a.X + (b.X-a.X)*t, a.Y + (b.Y-a.Y)*t);+ private static double Cross((double X, double Y) a, (double X, double Y) b) => a.X*b.Y-a.Y*b.X;+ private static double Distance((double X, double Y) a, (double X, double Y) b)+ => Math.Sqrt((a.X-b.X)*(a.X-b.X)+(a.Y-b.Y)*(a.Y-b.Y));+ private static double PointLineDistance((double X, double Y) p, (double X, double Y) a, (double X, double Y) b)+ => Math.Abs(Cross((b.X-a.X,b.Y-a.Y),(p.X-a.X,p.Y-a.Y))) / Distance(a,b);+ private static string Key((double X, double Y) p) => $"{Math.Round(p.X/VertexTolerance)},{Math.Round(p.Y/VertexTolerance)}";+ private static string GeometryKey(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D l => $"L:{Key(l.Start)}:{Key(l.End)}",+ LineArcCubicBezier2D c => $"C:{Key(c.Start)}:{Key(c.Control1)}:{Key(c.Control2)}:{Key(c.End)}",+ _ => throw new NotSupportedException()+ };+}diff --git a/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadStitch.cs b/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadStitch.csnew file mode 100644index 00000000..8d81ed78--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadStitch.cs@@ -0,0 +1,253 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.StandardLibrary;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>+/// Replaces exactly the two HexBolt shank skin faces with a helical root-stock skin.+/// The original head and tip, the rib skin, and two planar annular shoulders share+/// one shell. This bounded construction does not perform a Boolean union.+/// </summary>+internal static class HexBoltThreadStitch+{+ internal sealed record Result(BrepBody Body, IReadOnlyDictionary<FaceId, FaceId> BoltFaces,+ IReadOnlyDictionary<FaceId, FaceId> ThreadFaces,+ IReadOnlyDictionary<EdgeId, EdgeId> ThreadEdges);++ internal static Result Create(HexBoltDefinition bolt, BrepHelicalRibResult rib)+ {+ var shank = bolt.Semantics.Descendants+ .Where(item => item.StableId.StartsWith(bolt.Semantics.BodyStableId + ".Shank.Face[", StringComparison.Ordinal)+ && item.Face.HasValue)+ .Select(item => item.Face!.Value).ToHashSet();+ if (shank.Count != 2) throw new InvalidOperationException("HexBolt thread stitch requires exactly two cylindrical shank faces.");+ var retainedBolt = bolt.Body.Topology.Faces.Where(face => !shank.Contains(face.Id)).Select(face => face.Id).ToArray();+ var retainedRib = rib.FaceRoles.Where(item => item.Value is not ("Support.BottomCap" or "Support.TopCap"))+ .Select(item => item.Key).ToArray();+ var shell = new ShellCopy();+ var boltCopy = shell.CopyFaces(bolt.Body, retainedBolt);+ var ribCopy = shell.CopyFaces(rib.Body, retainedRib);++ var shankEdges = EdgesOfFaces(bolt.Body, shank).ToHashSet();+ var retainedEdges = EdgesOfFaces(bolt.Body, retainedBolt).ToHashSet();+ var sharedRings = shankEdges.Intersect(retainedEdges).ToArray();+ if (sharedRings.Length != 4) throw new InvalidOperationException("HexBolt shank must meet head and tip at two half-circle rings.");+ var startX = bolt.Spec.UnderHeadRadius;+ var endX = bolt.Dimensions.TipChamferStartX;+ var lowerArcs = sharedRings.Where(edge => AtX(bolt.Body, edge, startX)).Select(edge => boltCopy.Edges[edge]).ToArray();+ var upperArcs = sharedRings.Where(edge => AtX(bolt.Body, edge, endX)).Select(edge => boltCopy.Edges[edge]).ToArray();+ if (lowerArcs.Length != 2 || upperArcs.Length != 2)+ throw new InvalidOperationException("HexBolt shank boundary rings do not match the planned axial interval.");+ var lowerRoot = ribCopy.Edges[AssertRole(rib, "Support.BottomRim")];+ var upperRoot = ribCopy.Edges[AssertRole(rib, "Support.TopRim")];+ shell.Annulus(startX, lowerArcs, lowerRoot, outwardPositive: true);+ shell.Annulus(endX, upperArcs, upperRoot, outwardPositive: false);+ var body = shell.Complete();+ var bindings = BrepBindingValidator.Validate(body, true);+ if (!bindings.IsSuccess)+ throw new InvalidOperationException("HexBolt thread stitch failed geometry bindings: " + string.Join(" | ",+ bindings.Diagnostics.Take(8).Select(item => item.Message)));+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid)+ throw new InvalidOperationException("HexBolt thread stitch failed BRep preflight: " + string.Join(" | ",+ preflight.Diagnostics.Where(item => item.Severity == BrepExportPreflightSeverity.Error)+ .Take(8).Select(item => item.Code + ": " + item.Message)));+ var mass = BrepMassProperties.Evaluate(body);+ if (!mass.IsEnclosed || !mass.IsOrientationConsistent)+ throw new InvalidOperationException("HexBolt thread stitch did not produce an enclosed, consistently oriented body: "+ + string.Join(" | ", mass.Diagnostics));+ return new(body, boltCopy.Faces, ribCopy.Faces, ribCopy.Edges);+ }++ private static EdgeId AssertRole(BrepHelicalRibResult rib, string role) =>+ rib.EdgeRoles.Single(item => item.Value == role).Key;++ private static IEnumerable<EdgeId> EdgesOfFaces(BrepBody body, IEnumerable<FaceId> faces)+ {+ foreach (var faceId in faces)+ foreach (var loopId in body.Topology.GetFace(faceId).LoopIds)+ foreach (var coedgeId in body.Topology.GetLoop(loopId).CoedgeIds)+ yield return body.Topology.GetCoedge(coedgeId).EdgeId;+ }++ private static bool AtX(BrepBody body, EdgeId edgeId, double x)+ {+ var edge = body.Topology.GetEdge(edgeId);+ return body.TryGetVertexPoint(edge.StartVertexId, out var a)+ && body.TryGetVertexPoint(edge.EndVertexId, out var b)+ && Math.Abs(a.X - x) < 1e-7d && Math.Abs(b.X - x) < 1e-7d;+ }++ private sealed class ShellCopy+ {+ private readonly TopologyBuilder topology = new();+ private readonly BrepGeometryStore geometry = new();+ private readonly BrepBindingModel bindings = new();+ private readonly Dictionary<VertexId, Point3D> points = [];+ private readonly List<FaceId> faces = [];+ private int nextCurve = 1;+ private int nextSurface = 1;++ internal sealed record CopyMap(IReadOnlyDictionary<FaceId, FaceId> Faces, IReadOnlyDictionary<EdgeId, EdgeId> Edges);++ internal CopyMap CopyFaces(BrepBody source, IReadOnlyCollection<FaceId> retained)+ {+ var vertexMap = new Dictionary<VertexId, VertexId>();+ var edgeMap = new Dictionary<EdgeId, EdgeId>();+ var curveMap = new Dictionary<CurveGeometryId, CurveGeometryId>();+ var surfaceMap = new Dictionary<SurfaceGeometryId, SurfaceGeometryId>();+ var faceMap = new Dictionary<FaceId, FaceId>();++ VertexId Vertex(VertexId old)+ {+ if (vertexMap.TryGetValue(old, out var mapped)) return mapped;+ if (!source.TryGetVertexPoint(old, out var point)) throw new InvalidOperationException("Unbound stitch vertex.");+ mapped = topology.AddVertex();+ vertexMap.Add(old, mapped);+ points.Add(mapped, point);+ return mapped;+ }++ EdgeId Edge(EdgeId old)+ {+ if (edgeMap.TryGetValue(old, out var mapped)) return mapped;+ var edge = source.Topology.GetEdge(old);+ mapped = topology.AddEdge(Vertex(edge.StartVertexId), Vertex(edge.EndVertexId));+ edgeMap.Add(old, mapped);+ var binding = source.Bindings.GetEdgeBinding(old);+ if (!curveMap.TryGetValue(binding.CurveGeometryId, out var curveId))+ {+ curveId = new CurveGeometryId(nextCurve++);+ curveMap.Add(binding.CurveGeometryId, curveId);+ geometry.AddCurve(curveId, source.Geometry.GetCurve(binding.CurveGeometryId));+ }+ bindings.AddEdgeBinding(binding with { EdgeId = mapped, CurveGeometryId = curveId });+ return mapped;+ }++ SurfaceGeometryId Surface(SurfaceGeometryId old)+ {+ if (surfaceMap.TryGetValue(old, out var mapped)) return mapped;+ mapped = new SurfaceGeometryId(nextSurface++);+ surfaceMap.Add(old, mapped);+ geometry.AddSurface(mapped, source.Geometry.GetSurface(old));+ return mapped;+ }++ foreach (var oldFace in retained.OrderBy(id => id.Value))+ {+ var face = source.Topology.GetFace(oldFace);+ var newLoops = new List<LoopId>();+ var loopMap = new Dictionary<LoopId, LoopId>();+ var oldToNewCoedges = new Dictionary<CoedgeId, CoedgeId>();+ foreach (var oldLoop in face.LoopIds)+ {+ var loop = source.Topology.GetLoop(oldLoop);+ if (loop.Kind != LoopKind.Edge) throw new InvalidOperationException("HexBolt thread stitch requires edge loops.");+ var loopId = topology.AllocateLoopId();+ var coedgeIds = loop.CoedgeIds.Select(_ => topology.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < coedgeIds.Length; i++)+ {+ var oldCoedge = source.Topology.GetCoedge(loop.CoedgeIds[i]);+ topology.AddCoedge(new Coedge(coedgeIds[i], Edge(oldCoedge.EdgeId), loopId,+ coedgeIds[(i + 1) % coedgeIds.Length], coedgeIds[(i + coedgeIds.Length - 1) % coedgeIds.Length],+ oldCoedge.IsReversed));+ oldToNewCoedges.Add(oldCoedge.Id, coedgeIds[i]);+ }+ topology.AddLoop(new Loop(loopId, coedgeIds));+ newLoops.Add(loopId);+ loopMap.Add(oldLoop, loopId);+ }+ var newFace = topology.AddFace(newLoops);+ faces.Add(newFace);+ faceMap.Add(oldFace, newFace);+ var faceBinding = source.Bindings.GetFaceBinding(oldFace);+ var newSurface = Surface(faceBinding.SurfaceGeometryId);+ bindings.AddFaceBinding(faceBinding with { FaceId = newFace, SurfaceGeometryId = newSurface });+ foreach (var loop in loopMap)+ if (source.Bindings.TryGetFaceBoundaryRoleBinding(loop.Key, out var role))+ bindings.AddFaceBoundaryRoleBinding(role with { FaceId = newFace, LoopId = loop.Value });+ foreach (var oldCoedge in oldToNewCoedges)+ if (source.Bindings.TryGetPcurveBinding(oldCoedge.Key, out var pcurve))+ bindings.AddPcurveBinding(pcurve with { CoedgeId = oldCoedge.Value, FaceId = newFace,+ SurfaceGeometryId = Surface(pcurve.SurfaceGeometryId) });+ foreach (var oldLoop in face.LoopIds)+ if (source.Bindings.TryGetVertexLoopParameterBinding(oldLoop, out var parameter))+ throw new InvalidOperationException("HexBolt thread stitch does not admit vertex-loop faces.");+ }+ return new(faceMap, edgeMap);+ }++ internal void Annulus(double x, IReadOnlyList<EdgeId> outerArcs, EdgeId innerCircle, bool outwardPositive)+ {+ var normal = Direction3D.Create(new Vector3D(outwardPositive ? 1d : -1d, 0d, 0d));+ var radial = Direction3D.Create(new Vector3D(0d, 1d, 0d));+ var surfaceId = new SurfaceGeometryId(nextSurface++);+ geometry.AddSurface(surfaceId, SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(x, 0d, 0d), normal, radial)));+ var outer = OrderOppositeUses(outerArcs);+ var inner = OrderOppositeUses([innerCircle]);+ var outerLoop = Loop(outer);+ var innerLoop = Loop(inner);+ var face = topology.AddFace([outerLoop, innerLoop]);+ faces.Add(face);+ bindings.AddFaceBinding(new FaceGeometryBinding(face, surfaceId));+ bindings.AddFaceBoundaryRoleBinding(new(face, outerLoop, FaceBoundaryRole.Outer));+ bindings.AddFaceBoundaryRoleBinding(new(face, innerLoop, FaceBoundaryRole.Inner));+ }++ private (EdgeId Edge, bool Reverse)[] OrderOppositeUses(IReadOnlyList<EdgeId> edges)+ {+ var uses = edges.Select(edge => (Edge: edge, Reverse: !ExistingUse(edge))).ToArray();+ if (uses.Length == 1) return uses;+ var first = uses[0];+ var second = uses[1];+ if (End(first) != Start(second)) (first, second) = (second, first);+ if (End(first) != Start(second) || End(second) != Start(first))+ throw new InvalidOperationException("HexBolt stitch boundary arcs do not form a closed ring.");+ return [first, second];+ }++ private bool ExistingUse(EdgeId edge)+ {+ var uses = topology.Model.Coedges.Where(item => item.EdgeId == edge).ToArray();+ if (uses.Length != 1) throw new InvalidOperationException("Stitch boundary must have one retained coedge use.");+ return uses[0].IsReversed;+ }++ private VertexId Start((EdgeId Edge, bool Reverse) use)+ {+ var edge = topology.Model.GetEdge(use.Edge);+ return use.Reverse ? edge.EndVertexId : edge.StartVertexId;+ }++ private VertexId End((EdgeId Edge, bool Reverse) use)+ {+ var edge = topology.Model.GetEdge(use.Edge);+ return use.Reverse ? edge.StartVertexId : edge.EndVertexId;+ }++ private LoopId Loop(IReadOnlyList<(EdgeId Edge, bool Reverse)> uses)+ {+ var loopId = topology.AllocateLoopId();+ var ids = uses.Select(_ => topology.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < ids.Length; i++)+ topology.AddCoedge(new Coedge(ids[i], uses[i].Edge, loopId,+ ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reverse));+ topology.AddLoop(new Loop(loopId, ids));+ return loopId;+ }++ internal BrepBody Complete()+ {+ var shell = topology.AddShell(faces);+ topology.AddBody([shell]);+ return new BrepBody(topology.Model, geometry, bindings, points);+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs b/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.csnew file mode 100644index 00000000..41e528d8--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs@@ -0,0 +1,210 @@+using System.Text;+using Typography.OpenFont;++namespace Aetheris.Kernel.Firmament.Materializer;++public enum PlanarTextAlignment { Left, Center, Right }++public sealed record PlanarTextGlyph(int Index, int Codepoint, int SourceStart, int SourceLength,+ ushort FontGlyphIndex, double BaselineX, double Advance, int ContourCount);++/// <summary>Exact font curves grouped into one Aetheris profile per material island.</summary>+public sealed record PlanarTextProfileResult(IReadOnlyList<ResolvedProfile2D> Regions,+ IReadOnlyList<PlanarTextGlyph> Glyphs, int ContourCount, int CounterCount,+ double Advance, IReadOnlyList<string> Diagnostics, int ResolvedIntersections = 0)+{+ public bool Succeeded => Diagnostics.Count == 0;+}++/// <summary>+/// X0 single-line outline conversion. Height denotes the font em in millimetres;+/// glyphs retain their baseline and exact line/cubic polynomial boundaries.+/// </summary>+public static class PlanarTextProfiles+{+ private static readonly Lazy<Typeface> DefaultTypeface = new(LoadInter);++ public static PlanarTextProfileResult Build(string content, double height,+ PlanarTextAlignment alignment = PlanarTextAlignment.Left,+ ConstructionPlane? supportFrame = null, string featureId = "Text")+ {+ var diagnostics = new List<string>();+ if (string.IsNullOrEmpty(content)) diagnostics.Add("text-content-empty");+ if (!double.IsFinite(height) || height <= 0) diagnostics.Add("text-height-must-be-positive");+ if (content is not null && content.IndexOfAny(['\r', '\n']) >= 0) diagnostics.Add("text-multiline-unsupported-x0");+ if (diagnostics.Count > 0) return new([], [], 0, 0, 0, diagnostics);+ content ??= string.Empty;++ var typeface = DefaultTypeface.Value;+ var scale = height / typeface.UnitsPerEm;+ var glyphs = new List<PlanarTextGlyph>();+ var outlines = new List<(int GlyphIndex, int Codepoint, int SourceStart, IReadOnlyList<CurveContour> Contours)>();+ var cursor = 0d;+ var sourceStart = 0;+ foreach (var rune in content.EnumerateRunes())+ {+ var glyphIndex = typeface.GetGlyphIndex(rune.Value);+ if (glyphIndex == 0)+ {+ diagnostics.Add($"text-glyph-missing:U+{rune.Value:X4}");+ break;+ }+ var glyph = typeface.GetGlyph(glyphIndex);+ if (glyph.IsCffGlyph)+ {+ diagnostics.Add($"text-cff-glyph-unsupported-x0:U+{rune.Value:X4}");+ break;+ }+ var translator = new OutlineTranslator();+ IGlyphReaderExtensions.Read(translator, glyph.GlyphPoints, glyph.EndPoints);+ var contours = translator.Contours;+ if (contours.Count == 0 && !Rune.IsWhiteSpace(rune))+ {+ diagnostics.Add($"text-glyph-empty-outline:U+{rune.Value:X4}");+ break;+ }+ var advance = typeface.GetAdvanceWidthFromGlyphIndex(glyphIndex) * scale;+ glyphs.Add(new(glyphs.Count, rune.Value, sourceStart, rune.Utf16SequenceLength,+ glyphIndex, cursor, advance, contours.Count));+ outlines.Add((glyphs.Count - 1, rune.Value, sourceStart, contours));+ cursor += advance;+ sourceStart += rune.Utf16SequenceLength;+ }+ if (diagnostics.Count > 0) return new([], glyphs, 0, 0, cursor, diagnostics);++ var shift = alignment switch+ {+ PlanarTextAlignment.Center => -cursor / 2,+ PlanarTextAlignment.Right => -cursor,+ _ => 0d+ };+ var regions = new List<ResolvedProfile2D>();+ var contourCount = 0;+ var counterCount = 0;+ var resolvedIntersections = 0;+ foreach (var item in outlines)+ {+ var placed = item.Contours.Select(c => c.Transform(+ glyphs[item.GlyphIndex].BaselineX + shift, scale)).ToArray();+ contourCount += placed.Length;+ var normalized = GlyphRegionNormalizer.Normalize(placed.Select(c => c.Curves).ToArray());+ resolvedIntersections += normalized.Intersections;+ diagnostics.AddRange(normalized.Diagnostics.Select(d => $"Glyph[{item.GlyphIndex}]:{d}"));+ for (var i = 0; i < normalized.Regions.Count; i++)+ {+ var region = normalized.Regions[i];+ var profileName = $"{featureId}.Glyph[{item.GlyphIndex}].Region[{i}]";+ var loops = new List<ResolvedProfileLoop2D>+ {+ ToLoop(new(region.Outer), true, profileName, "Outer", item.GlyphIndex,+ item.Codepoint, item.SourceStart, glyphs[item.GlyphIndex].SourceLength, supportFrame)+ };+ for (var j = 0; j < region.Holes.Count; j++)+ loops.Add(ToLoop(new(region.Holes[j]), false, profileName, $"Counter[{j}]",+ item.GlyphIndex, item.Codepoint, item.SourceStart,+ glyphs[item.GlyphIndex].SourceLength, supportFrame));+ counterCount += region.Holes.Count;+ var profile = new ResolvedProfile2D(profileName,+ supportFrame?.StableId ?? "XY", loops, supportFrame);+ var validation = ResolvedProfile2DValidator.Validate(profile);+ if (!validation.IsValid) diagnostics.AddRange(validation.Diagnostics);+ regions.Add(profile);+ }+ }+ return new(diagnostics.Count == 0 ? regions : [], glyphs, contourCount, counterCount,+ cursor, diagnostics, resolvedIntersections);+ }++ private static Typeface LoadInter()+ {+ using var stream = typeof(PlanarTextProfiles).Assembly.GetManifestResourceStream("Aetheris.Drawing.Inter.ttf")+ ?? throw new InvalidOperationException("text-default-font-resource-missing");+ return new OpenFontReader().Read(stream);+ }++ private static ResolvedProfileLoop2D ToLoop(CurveContour contour, bool outer, string profile,+ string loopName, int glyphIndex, int codepoint, int sourceStart, int sourceLength,+ ConstructionPlane? frame)+ {+ var curves = contour.SignedArea * (outer ? 1 : -1) > 0+ ? contour.Curves : contour.Curves.AsEnumerable().Reverse().Select(Reverse).ToArray();+ return new(loopName, outer, curves.Select((curve, index) =>+ {+ var id = $"{profile}.{loopName}.Segment[{index}]";+ var provenance = new ProfileSegmentProvenance(id, profile,+ $"source-char:{sourceStart}..{sourceStart + sourceLength}",+ $"font-outline:Glyph[{glyphIndex}]:U+{codepoint:X4}",+ frame?.StableId ?? "XY");+ return new ResolvedProfileSegment2D($"{loopName}.Segment[{index}]", curve, provenance);+ }).ToArray());+ }++ private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start),+ LineArcCubicBezier2D cubic => new LineArcCubicBezier2D(cubic.End, cubic.Control2, cubic.Control1, cubic.Start),+ _ => throw new NotSupportedException("text-outline-curve-unsupported")+ };++ private sealed record CurveContour(IReadOnlyList<LineArcProfileCurve2D> Curves)+ {+ public double SignedArea => Curves.Sum(ResolvedProfile2DValidator.SignedAreaContribution);++ public CurveContour Transform(double offsetX, double scale)+ {+ (double X, double Y) P((double X, double Y) p) => (offsetX + p.X * scale, p.Y * scale);+ return new(Curves.Select(c => c switch+ {+ LineArcLineSegment2D line => (LineArcProfileCurve2D)new LineArcLineSegment2D(P(line.Start), P(line.End)),+ LineArcCubicBezier2D cubic => new LineArcCubicBezier2D(P(cubic.Start), P(cubic.Control1), P(cubic.Control2), P(cubic.End)),+ _ => throw new NotSupportedException("text-outline-curve-unsupported")+ }).ToArray());+ }++ }++ // Copeland's TypographyOutlineConversion.OutlineTranslator is the template here:+ // IGlyphReaderExtensions owns TrueType contour decomposition, including implied points.+ private sealed class OutlineTranslator : IGlyphTranslator+ {+ private readonly List<CurveContour> contours = [];+ private readonly List<LineArcProfileCurve2D> current = [];+ private (double X, double Y)? start;+ private (double X, double Y)? position;+ public IReadOnlyList<CurveContour> Contours => contours;+ public void BeginRead(int contourCount) { }+ public void EndRead() => CloseContour();+ public void MoveTo(float x0, float y0) { CloseContour(); start = position = (x0, y0); }+ public void LineTo(float x1, float y1)+ {+ var end = ((double)x1, (double)y1);+ current.Add(new LineArcLineSegment2D(position ?? throw new InvalidOperationException("text-contour-missing-moveto"), end));+ position = end;+ }+ public void Curve3(float x1, float y1, float x2, float y2)+ {+ var a = position ?? throw new InvalidOperationException("text-contour-missing-moveto");+ var control = ((double)x1, (double)y1); var end = ((double)x2, (double)y2);+ current.Add(new LineArcCubicBezier2D(a,+ (a.X + (control.Item1 - a.X) * 2 / 3, a.Y + (control.Item2 - a.Y) * 2 / 3),+ (end.Item1 + (control.Item1 - end.Item1) * 2 / 3, end.Item2 + (control.Item2 - end.Item2) * 2 / 3), end));+ position = end;+ }+ public void Curve4(float x1, float y1, float x2, float y2, float x3, float y3)+ {+ var a = position ?? throw new InvalidOperationException("text-contour-missing-moveto");+ var end = ((double)x3, (double)y3);+ current.Add(new LineArcCubicBezier2D(a, (x1, y1), (x2, y2), end));+ position = end;+ }+ public void CloseContour()+ {+ if (start is { } first && position is { } last)+ {+ if (first != last) current.Add(new LineArcLineSegment2D(last, first));+ if (current.Count > 0) contours.Add(new([.. current]));+ }+ current.Clear(); start = position = null;+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.csindex d92900ac..9a009503 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs@@ -233,6 +233,16 @@ public static class ProfileArrangementBuilderStableId = source.StableId + $".quarter{i}",Geometry = new LineArcCircularArc2D(circle.Center, circle.Radius, i * Math.PI / 2d, Math.PI / 2d)}) : new[] { source }).ToArray();+ // Cubic profiles are valid exact BRep extrusion input, but the section+ // arrangement below still owns only line/arc intersection and splitting.+ // Reject before its line/arc-only Trim switch can throw or silently omit+ // cubic intersections. The glyph normalizer does not weaken this boundary.+ if (sources.FirstOrDefault(source => source.Geometry is LineArcCubicBezier2D) is { } cubic)+ {+ var diagnostic = $"arrangement-rejected:bounded-cubic-section-unsupported:{cubic.StableId}:context={context}";+ return new(new(frame, sources, [], [], [], 0, [diagnostic],+ TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), null);+ }var diagnostics = new List<string>();var intersectionClock = Stopwatch.StartNew();var parameters = sources.ToDictionary(x => x.StableId, _ => new List<double> { 0d, 1d }, StringComparer.Ordinal);diff --git a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.csindex 5459141c..f7567a8c 100644--- a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs@@ -7,7 +7,7 @@ using Aetheris.Semantics;namespace Aetheris.Kernel.Firmament.Materializer;/// <summary>Stable roles assigned while an authoritative plan is materialized. These are not geometric queries.</summary>-public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, ConvexJunctionPatch, ReflexJunctionPatch, CapContactEdge, SideContactEdge, JunctionToRollA, JunctionToRollB, JunctionCapContact, JunctionSideAContact, JunctionSideBContact, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge, BoxFace, BoxEdge }+public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, ConvexJunctionPatch, ReflexJunctionPatch, CapContactEdge, SideContactEdge, JunctionToRollA, JunctionToRollB, JunctionCapContact, JunctionSideAContact, JunctionSideBContact, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge, BoxFace, BoxEdge, ThreadRootFace, ThreadLeadingFlank, ThreadTrailingFlank, ThreadCrest, ThreadStartCap, ThreadEndCap, ThreadBoundaryEdge }public enum SemanticTopologyAddressability { AuthoredStable, DerivedStable, ImportedStable, RuntimeOnly, Ambiguous, Unstable }public enum SemanticSelectionRequirement { ExactlyOne, OneOrMore, ConnectedChain, ClosedLoop, NonEmptyFaceSet }public enum SemanticSelectionFailure { None, SemanticSourceNotFound, NoMaterializedDescendants, AmbiguousBodyContext, SelectionCardinalityMismatch, DescendantsNotConnected, DescendantsBranch, DescendantsDoNotClose, MixedBoundaryRoles, UnsupportedTopologyChange, SelectionConsumerMismatch }diff --git a/docs/release/TEXT-PLANAR-X0.md b/docs/release/TEXT-PLANAR-X0.mdnew file mode 100644index 00000000..55e3bcc4--- /dev/null+++ b/docs/release/TEXT-PLANAR-X0.md@@ -0,0 +1,104 @@+# TEXT-PLANAR-X0 — qualification status++**Verdict: Meaningful progression.** The owned font dependency is integrated and+its Inter outlines lower to exact Aetheris planar curves. A simple `O` with its+counter passes the existing profile validator and exact extrusion emitter. The+requested engraved `CODEX` bolt, embossed `AETHERIS` plate, STEP witnesses, schema,+and LX authoring are not implemented or qualified.++**Later status:** `TEXT-REGION-NORMALIZE-X1.md` resolves the bundled Inter+`D` overlap and `X` crossing into valid exact CAD profiles. The X0 verdict+below records the earlier qualification state and is retained for history.++## Dependency audit++- Copeland source: `src/ThirdParty/Machina.Typography.OpenFont/`.+- NuGet package and assembly: `Machina.Typography.OpenFont`, version `1.0.0`;+ public namespace: `Typography.OpenFont`.+- The Copeland fork pins LayoutFarm Typography commit+ `5877180c7c5271091379a0eaf9f03ab6ebd256b3`. Its relevant fix preserves+ glyph identity for empty TrueType outlines, so spaces use their own advance.+- Aetheris now uses `OpenFontReader.Read(Stream)`, `Typeface.GetGlyphIndex`,+ `GetGlyph`, `GetAdvanceWidthFromGlyphIndex`, and `IGlyphReaderExtensions.Read`+ with `IGlyphTranslator`. This reuses the package's cmap, outline decomposition,+ and metrics. There is no new font parser or cmap implementation in the text path.+- Copeland's `Machina.Fonts.Generation.Typography.TypographyOutlineConversion`+ translator was inspected and used as the small adapter pattern. Its source was+ not copied because it returns Machina presentation types; Aetheris's adapter+ emits `ResolvedProfile2D` and `LineArcCubicBezier2D` directly.+- The default is Aetheris's existing embedded `Resources/Inter-Regular.ttf`.+ `Resources/Inter-LICENSE.txt` records its SIL Open Font License 1.1. No host+ font lookup or new font asset is involved.++## Implemented profile conversion++`PlanarTextProfiles.Build` accepts a Unicode string, a positive millimetre height,+left/center/right alignment, and an optional `ConstructionPlane` support frame.+Height is the font **em** height. Unicode scalars resolve through the owned+typeface. Advances are scaled from font units and placed on one horizontal+baseline. The parsed immutable typeface is loaded once by `Lazy<Typeface>`.++TrueType lines stay lines. Quadratic curves are degree elevated exactly to cubic+Béziers; cubic outlines stay cubic. Aetheris's existing clamped degree-three+B-spline path materializes the exact polynomial spans. Sampling is used only to+classify contour containment and detect overlap; it is never emitted as CAD+geometry. Nested non-overlapping contours become outer loops and counters, one+`ResolvedProfile2D` per material island. Profile segment provenance includes the+text feature, glyph index, Unicode scalar, and UTF-16 source start.++The qualification tests demonstrate `CO`: two glyphs, three source contours,+two material regions, and one `O` counter. The `O` region with its counter also+extrudes through `ResolvedProfile2DValidator.Extrude` with a 0.25 mm height.+The result is an isolated text solid, not a modification of a support body.++## Isolated blockers++1. The bundled Inter `D` uses overlapping contours. Its contours cross rather+ than nesting as a simple outer/counter pair. The adapter reports+ `text-contour-overlap-requires-arrangement` and returns no profiles.+2. The bundled Inter `X` has a self crossing contour. The existing profile+ validator reports the specific crossing segment pairs. Thus `CODEX` cannot+ yet be a valid profile set.+3. `ProfileArrangement2D` and the Boss/Pocket section stack currently accept+ bounded lines and circular arcs, while font outlines contain cubic Béziers.+ Exact polynomial intersection, splitting, fill classification, and section+ reconstruction would be needed before these profiles can enter that path.+ Flattening to coarse line segments would discard the requested curve quality.++These are geometry authority gaps. The text adapter deliberately does not call+Boss or Pocket, register Firmament `Text` syntax, or advertise schema/LX fields+that would imply materialization works. The intended authoring surface, once the+geometry gaps are closed, remains compact:++```firmament+Text MakerMark {+ Surface: face(Bolt.Head.Top)+ Content: "CODEX"+ Height: 3mm+ Depth: 0.25mm+ Operation: Engrave+ Alignment: Center+}+```++This sketch is **not accepted Firmament source** in this revision.++## Verification and missing witnesses++- `dotnet build Aetheris.slnx -c Release -m:1`: passed.+- `dotnet test Aetheris.Kernel.Firmament.Tests -c Release --filter FullyQualifiedName~PlanarTextProfilesTests -m:1`: six tests passed.+- `dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"`: 1,000 passed.+- `dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1`:+ all 1,670 Firmament tests passed, including the six text tests. The suite+ exited 1 with two CLI failures (HexBolt OBJ vertex count 908 vs expected+ 905; SheetMetal CLI validation) and five SheetMetal failures. These are the+ known unrelated baseline categories named in the mission.+- `dotnet run --no-build --project Aetheris.CLI -c Release -- inspect+ fixtures/Thread/hexbolt-threaded.firmament --json`: parsed the existing+ `ThreadExternalHexBolt` model successfully. No Text feature is authored there.++There is no engraved bolt or embossed plate artifact, so no text topology+counts, manifold judgment, STEP reimport result, display image, or meaningful+end-to-end performance numbers can be claimed. Font load, profile conversion,+solid feature lowering, tessellation, and STEP export have not been separately+profiled for the requested words.diff --git a/docs/release/TEXT-REGION-NORMALIZE-X1.md b/docs/release/TEXT-REGION-NORMALIZE-X1.mdnew file mode 100644index 00000000..58ede857--- /dev/null+++ b/docs/release/TEXT-REGION-NORMALIZE-X1.md@@ -0,0 +1,107 @@+# TEXT-REGION-NORMALIZE-X1++**Verdict: Meaningful progression.** The bundled Inter `D` and `X` now resolve+through Aetheris-owned non-zero-winding fill normalization into clean CAD+profiles. `CODEX` and `AETHERIS` both validate as exact vector profile sets.+Every `CODEX` region also passes the existing exact profile BRep extrusion+emitter. The ordinary Boss/Pocket section-stack path remains blocked on cubic+boundary arrangement and side-surface realization, so there is no engraved+threaded bolt or embossed plate to claim.++## Font asset and dependency++- Production font engine remains Copeland's `Machina.Typography.OpenFont` 1.0.0+ (`Typography.OpenFont` namespace). No parser or shaping replacement was added.+- Asset: `Aetheris.Kernel.Firmament/Resources/Inter-Regular.ttf`, SHA-256+ `FF80BD54C3E443EEFE82A9D282ACC213E441CD71FAE882F75EE1924E9E9119D5`.+ `otfinfo` identifies Inter Regular version `4.001;git-66647c0bb` with a+ `glyf` table and no CFF table. The file is licensed under SIL OFL 1.1, as+ recorded in `Resources/Inter-LICENSE.txt`.+- The TrueType source uses lines and quadratic Bézier segments. The X0 adapter+ degree elevates each quadratic exactly to a cubic, which the existing exact+ profile BRep emitter already supports. This retains the original polynomial+ curve and avoids introducing a second quadratic 3D realization path merely+ for the text milestone.++## Fill normalization++`GlyphRegionNormalizer` accepts the positioned lines and polynomial Béziers+from `PlanarTextProfiles`. The font's TrueType non-zero winding fill determines+material. The normalizer:++1. Builds fine chord pieces **only to find candidate intersections**. Their+ vertices never become output CAD edges.+2. Refines each candidate against the original polynomial curves, then splits+ the source curves at the resulting parameters with de Casteljau subdivision.+3. Evaluates winding on either side of every resulting fragment. Cubic ray+ crossings use monotonic intervals derived from the exact derivative; an+ internal edge between two filled cells is discarded.+4. Walks the remaining directed boundary graph, classifies positive-area+ outer loops and negative-area counters, and emits one `ResolvedProfile2D`+ per filled island. The profile validator remains authoritative.++No raster, polygon, or mesh path is used as production geometry authority.+The implementation is bounded to the bundled Inter TrueType line/quadratic+outlines, represented by exact lines/cubics after degree elevation. It is not+an arbitrary-font or arbitrary-curve planar Boolean API. Intersection search+and parameter refinement are numerical; tangencies and coincident cubic spans+outside the qualified glyphs have not been certified.++| Text | Glyphs | Raw contours | Resolved crossings | CAD regions | Counters |+| --- | ---: | ---: | ---: | ---: | ---: |+| `CODEX` | 5 | 7 | 6 | 5 | 2 (`O`, `D`) |+| `AETHERIS` | 8 | 10 | 9 | 8 | 2 |++The D stroke, D counter, and exterior point classifications agree with the+independent oracle. Its normalized filled areas at 3 mm em height agree to+four decimal places for `D` and `X`. Increasing text height preserves region+topology and scales advance deterministically.++## Independent oracle++FontForge was not installed locally. For debugging only, an ignored local+environment under `artifacts/local/font-oracle/` used FontTools 4.65.0 to draw+Inter glyphs and Skia PathOps 0.9.2 `simplify(..., fix_winding=True)` to+remove overlaps and correct winding. The debug script is+`artifacts/local/font-oracle-check.py`. The oracle reports `D` as two raw and+two normalized contours, with filled area `743589.4166666667` font units²;+`X` is one raw and one normalized contour, with filled area+`607590.0809529623` font units². Aetheris matches those areas after the+2048-units-per-em scale. Neither package is a production dependency.++## Solid-feature boundary++The normalized `O` profile with a counter and all five `CODEX` regions pass+`ResolvedProfile2DValidator.Extrude`, which uses the existing exact profile+BRep planner. The separate `ProfileArrangementBuilder.Compose` path used by+Boss/Pocket currently has line/circular-arc intersection, splitting, point+classification, and reconstruction only. It now reports+`arrangement-rejected:bounded-cubic-section-unsupported` at that boundary+instead of throwing or silently omitting intersections. Beyond arrangement,+`PrismaticSectionStackEmitter.TryPlan` still constructs only line/arc edge+geometry and plane/cylinder side surfaces. A cubic extrusion needs the+existing exact polynomial swept-surface machinery adapted to this shared+section stack, with topology and STEP validation. Font-specific Boss/Pocket+logic would violate the semantic boundary.++The requested compact Firmament `Text` construct, schema, LX completion,+source-linked final faces, support-fit/depth checks, bolt and plate witnesses,+display renders, and STEP roundtrips are deferred until the shared solid+feature path can consume these ordinary profiles. The conceptual maker mark+source in `TEXT-PLANAR-X0.md` remains non-executable.++## Verification++- `dotnet test Aetheris.Kernel.Firmament.Tests -c Release --filter FullyQualifiedName~PlanarTextProfilesTests -m:1`:+ 13 tests pass, including D/X normalization, both words, D fill points,+ independent oracle areas, and all CODEX region extrusions.+- `dotnet build Aetheris.slnx -c Release -m:1`: passed, 0 errors.+- Fast core lane: 1,000 passed. Full suite: all 1,677 Firmament tests passed;+ overall exit code 1 came from the same two CLI and five SheetMetal baseline+ failures recorded in `TEXT-PLANAR-X0.md`.+- `dotnet run --no-build --project Aetheris.CLI -c Release -- inspect+ fixtures/Thread/hexbolt-threaded.firmament --json`: parsed the existing+ threaded HexBolt fixture successfully. Its source and geometry were not+ altered by this milestone.+- No topology counts, manifold result, text STEP size, reimport result, or+ catalogue render can be reported for a bolt or plate that has not been built.diff --git a/docs/release/THREAD-EXTERNAL-X1.md b/docs/release/THREAD-EXTERNAL-X1.mdnew file mode 100644index 00000000..707b0f52--- /dev/null+++ b/docs/release/THREAD-EXTERNAL-X1.md@@ -0,0 +1,52 @@+# THREAD-EXTERNAL-X1 — one Firmament Thread on an existing HexBolt++**Verdict: Accepted for the bounded HexBolt case.** The existing smooth `StandardPart Bolt { Family: HexBolt }` gains one `Thread` declaration and produces one modeled, closed, consistently oriented BRep and production STEP. No generic Boolean, arbitrary sweep, mesh union, or cosmetic thread route was added.++## Authored delta++`fixtures/Thread/hexbolt-smooth.firmament` and `fixtures/Thread/hexbolt-threaded.firmament` use the same 50 mm, 8 mm nominal HexBolt specification. The threaded file adds only:++```firmament+Thread MainThread {+ Surface: face(Bolt.Shank)+ MajorDiameter: 8mm+ Pitch: 1.25mm+ Length: 47.5mm+ StartOffset: 0.75mm+}+```++The existing `ThreadDesignation` and `ThreadLength` standard-part fields remain metadata. The new `Thread` feature owns the modeled thread. Static schema and LX completion expose its support, major diameter, pitch, length, optional start offset, right-hand policy, derived root diameter, turn count, and flank/crest roles. `Thread` carries stable source provenance; representative rib faces and edges map to its source span. Retained head and tip face identities are remapped into the threaded standard-part report.++## Bounded direct stitch++The HexBolt head, under-head blend, and tip come from the existing exact coaxial construction. `HexBoltThreadStitch` replaces only its two cylindrical shank skin faces. It copies the qualified `BrepHelicalRib` root skin, flanks, crest, and start/end caps into the same topology model, omitting the rib's temporary stock end caps. Two planar annular shoulders connect the original HexBolt half-circle boundary rings to the rib's root-stock full-circle rings. Every boundary edge has two opposed uses. The result is one shell, with no coincident cylindrical faces or overlapping volumes.++The rib is additive over the new root stock. The admitted 60-degree truncated profile uses root width `5P/6`, crest width `P/8`, radial depth `17√3 P/48`, and root diameter `D − 17√3 P/24`. For `D=8 mm` and `P=1.25 mm`, the root diameter is `6.466413347 mm`. Lead equals pitch; the 47.5 mm span yields 38 complete right-hand turns. The bolt shank axis is +X. The helical centerline runs from x=0.95 to 48.45 mm; its last flank reaches x≈48.9708 mm, leaving about 0.0917 mm of exposed root stock before the tip chamfer begins at x=49.0625 mm. The annular transition and the existing 0.9375 mm tip chamfer remain visible. They are a deterministic simple end treatment, not a standards-grade runout.++The same `Thread` syntax works on a standalone `Cylinder Shank` through `face(Shank.OuterWall)`. The compiler validates cylindrical support, stock/major-diameter equality, positive pitch and length, finite stock margins, profile depth, complete-turn admission, and handedness. Failure emits an explicit diagnostic and no smooth substitute.++## Supplied McMaster reference++The supplied 91280A546 smooth/threaded STEP pair is dimensional and visual evidence, not topology authority. The threaded source STEP contains weighted rational B-spline curves that the current Aetheris importer cannot qualify. The comparison remains bounded:++| Feature | Supplied reference evidence | Aetheris modeled bolt | Difference / qualification |+| --- | ---: | ---: | --- |+| Major diameter | 8 mm analytic radius-4 records | 8 mm crest envelope | Nominal match |+| Root/minor diameter | 6.37620 mm at one sampled end vertex | 6.466413347 mm derived root | Reference sample is not a certified minimum; exact deviation unqualified |+| Pitch | 1.25 mm inferred from repeated 0.625 mm phase intervals | 1.25 mm | Nominal match; reference pitch remains inferred |+| Thread span | Exact runout bounds unverified | 47.5 mm / 38 turns | No valid axial deviation claim |+| Shank length | 50 mm | 50 mm | Nominal match |+| Head across flats / height | Smooth-reference envelope consistent with 13 / 5.3 mm | 13 / 5.3 mm authored | No head marking |++## BRep, STEP, display, and performance++The threaded bolt has **176 faces, 355 edges, 184 vertices, and 37 deterministic seam splits**. `BrepBindingValidator`, `BrepExportPreflight`, and mass properties accept one enclosed, consistently oriented body. Its STEP exports and reimports through Aetheris as one enclosed-manifold body with the same topology counts and overall bounds x=−5.3 to 50 mm, y=±6.5 mm, z=±7.50555 mm. The STEP uses qualified B-spline flank/crest surfaces plus analytic cylinder, cone, torus, and plane surfaces. The smooth HexBolt's STEP reimport has two source-sense orientation disagreements; the threaded bolt retains that same baseline count, and the imported shell is resolved consistently. External CAD-reader parity was not separately checked.++The BRep display tessellator covers every face and provides a shaded isometric render at `artifacts/local/thread-x1/threaded-hexbolt.png`. The production STEP is `artifacts/local/thread-x1/hexbolt-threaded.step`. The opt-in artifact test records compile/build, tessellation, topology, hash, and file-size measurements in `artifacts/local/thread-x1/threaded-hexbolt.json`. On the measured Windows Release host, compile/build took 3.75 s, including 3.34 s of helical-rib construction and shell stitching; STEP export took 0.28 s. Tessellation took 10.65 s and produced 606,870 display triangles. The deterministic STEP hash is `1A3A80A35F601A1C140777CBBAB1FF57CC788D491AFA517F9D229BA1248F9682`; the production file is about 8.8 MB. CLI STEP reimport took about 11 s including process startup. These are representative measurements, not performance guarantees.++Focused tests cover the plain-cylinder thread, invalid parameters, edits, schema/LX, source mapping, STEP roundtrip, determinism, the HexBolt stitch, and retention of head/tip semantics. The smooth HexBolt fixture still builds. The Release solution builds with zero errors; the fast Core lane passes 1,000 tests. In the full Release lane, Core passes 1,133/1,133 and Firmament passes 1,664/1,664. The full lane remains red on the established unrelated baseline: two CLI tests (HexBolt OBJ polygon count 905 expected versus 908 actual, and SheetMetal validation) and five CTC03 SheetMetal tests. Details are in `artifacts/local/thread-x1/full-test.log`.++## Limits++X1 admits only external, constant-pitch, constant-diameter, single-start, right-hand, complete-turn threads on the supported cylinder/HexBolt shapes. The bolt's planar shoulder transitions and clipped rib ends are valid but simplified. No internal, tapered, left-hand, multi-start, arbitrary profile, standards database, runout, thread relief, or engraved `8.8` head marking is implemented. The supplied threaded STEP cannot yet be used for exact overlay because weighted rational source curves are not imported.diff --git a/fixtures/Thread/external-cylinder.firmament b/fixtures/Thread/external-cylinder.firmamentnew file mode 100644index 00000000..3f80fa4d--- /dev/null+++ b/fixtures/Thread/external-cylinder.firmament@@ -0,0 +1,16 @@+Model ExternalThreadCylinder {+ Units: mm++ Cylinder Shank {+ Radius: 4mm+ Height: 34mm+ }++ Thread MainThread {+ Surface: face(Shank.OuterWall)+ MajorDiameter: 8mm+ Pitch: 1.25mm+ Length: 30mm+ StartOffset: 1mm+ }+}diff --git a/fixtures/Thread/hexbolt-smooth.firmament b/fixtures/Thread/hexbolt-smooth.firmamentnew file mode 100644index 00000000..739907aa--- /dev/null+++ b/fixtures/Thread/hexbolt-smooth.firmament@@ -0,0 +1,19 @@+Model ThreadExternalHexBolt {+ Units: mm+ StandardPart Bolt {+ Family: HexBolt+ StableId: "McMaster91280A546"+ NominalDiameter: 8mm+ Length: 50mm+ HeadAcrossFlats: 13mm+ HeadHeight: 5.3mm+ TopFlatDiameter: 12.35mm+ TopChamferAngle: 25deg+ TipChamferLength: 0.9375mm+ TipDiameter: 6.125mm+ ThreadLength: 47.5mm+ ThreadDesignation: "M8 x 1.25"+ PropertyClass: "8.8"+ UnderHeadRadius: 0.2mm+ }+}diff --git a/fixtures/Thread/hexbolt-threaded.firmament b/fixtures/Thread/hexbolt-threaded.firmamentnew file mode 100644index 00000000..2753fe70--- /dev/null+++ b/fixtures/Thread/hexbolt-threaded.firmament@@ -0,0 +1,26 @@+Model ThreadExternalHexBolt {+ Units: mm+ StandardPart Bolt {+ Family: HexBolt+ StableId: "McMaster91280A546"+ NominalDiameter: 8mm+ Length: 50mm+ HeadAcrossFlats: 13mm+ HeadHeight: 5.3mm+ TopFlatDiameter: 12.35mm+ TopChamferAngle: 25deg+ TipChamferLength: 0.9375mm+ TipDiameter: 6.125mm+ ThreadLength: 47.5mm+ ThreadDesignation: "M8 x 1.25"+ PropertyClass: "8.8"+ UnderHeadRadius: 0.2mm+ }+ Thread MainThread {+ Surface: face(Bolt.Shank)+ MajorDiameter: 8mm+ Pitch: 1.25mm+ Length: 47.5mm+ StartOffset: 0.75mm+ }+}diff --git a/scripts/render-threaded-hexbolt-x1.py b/scripts/render-threaded-hexbolt-x1.pynew file mode 100644index 00000000..50b880d4--- /dev/null+++ b/scripts/render-threaded-hexbolt-x1.py@@ -0,0 +1,49 @@+"""Render the opt-in Firmament threaded HexBolt OBJ as a shaded catalogue preview."""+from pathlib import Path+import sys++import numpy as np+from PIL import Image, ImageDraw+++root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("artifacts/local/thread-x1")+vertices = []+faces = []+with (root / "threaded-hexbolt.obj").open() as stream:+ for line in stream:+ if line.startswith("v "):+ vertices.append([float(value) for value in line.split()[1:]])+ elif line.startswith("f "):+ faces.append([int(value) - 1 for value in line.split()[1:]])++points = np.asarray(vertices)+triangles = np.asarray(faces)+center = np.array([22.35, 0.0, 0.0])+view = np.array([-0.55, -1.1, 0.85])+view /= np.linalg.norm(view)+right = np.cross(view, [1.0, 0.0, 0.0])+right /= np.linalg.norm(right)+up = np.cross(view, right)+projected = np.column_stack(((points - center) @ right, (points - center) @ up, (points - center) @ view))+width, height = 1400, 1600+scale = min((width - 180) / np.ptp(projected[:, 0]), (height - 160) / np.ptp(projected[:, 1]))+xy = np.column_stack((width / 2 + projected[:, 0] * scale, height / 2 - projected[:, 1] * scale))+verts = points[triangles]+normals = np.cross(verts[:, 1] - verts[:, 0], verts[:, 2] - verts[:, 0])+lengths = np.linalg.norm(normals, axis=1)+valid = lengths > 1e-13+normals[valid] /= lengths[valid, None]+light = np.array([0.35, -0.6, 0.72])+light /= np.linalg.norm(light)+brightness = np.clip(0.4 + 0.6 * (normals @ light), 0.18, 1.0)+depth = projected[triangles, 2].mean(axis=1)+visible = np.where(valid & ((normals @ view) > 0))[0]+order = visible[np.argsort(depth[visible])]+image = Image.new("RGB", (width, height), (245, 247, 251))+draw = ImageDraw.Draw(image)+for index in order:+ shade = float(brightness[index])+ color = (int(58 + 118 * shade), int(83 + 130 * shade), int(121 + 124 * shade))+ draw.polygon([tuple(xy[vertex]) for vertex in triangles[index]], fill=color)+image.save(root / "threaded-hexbolt.png")+print(len(order), "visible triangles")