Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add structural weldment authoring and cut-list export
Yuechen Licd28ac66dd08
diff --git a/Aetheris.CLI.Tests/StructuralCliTests.cs b/Aetheris.CLI.Tests/StructuralCliTests.csnew file mode 100644index 00000000..e5b50a3c--- /dev/null+++ b/Aetheris.CLI.Tests/StructuralCliTests.cs@@ -0,0 +1,18 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class StructuralCliTests+{+ [Fact]+ public void BuildAndInspect_ExposeStructuralArtifactAndCutList()+ {+ var root = FindRoot(); var source = Path.Combine(root,"fixtures","Canonical","Structural","welded-workbench.firmament");+ using var temp = new Temp(); var step=Path.Combine(temp.Path,"workbench.step");var output=new StringWriter();var error=new StringWriter();+ Assert.Equal(0,CliRunner.Run(["build",source,"--output",step,"--json"],output,error));Assert.Empty(error.ToString());Assert.True(File.Exists(step));Assert.True(File.Exists(Path.ChangeExtension(step,".cutlist.json")));+ using(var json=JsonDocument.Parse(output.ToString())){var structural=json.RootElement.GetProperty("structural");Assert.Equal(10,structural.GetProperty("bodyCount").GetInt32());Assert.Equal(4,structural.GetProperty("cutList").GetArrayLength());Assert.True(structural.GetProperty("membersEnclosed").GetBoolean());}+ output.GetStringBuilder().Clear();Assert.Equal(0,CliRunner.Run(["inspect",source,"--json"],output,error));using var inspection=JsonDocument.Parse(output.ToString());Assert.Equal("Structural",inspection.RootElement.GetProperty("domain").GetString());+ }+ private static string FindRoot(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return d?.FullName??throw new DirectoryNotFoundException();}+ private sealed class Temp:IDisposable{public Temp(){Path=System.IO.Path.Combine(System.IO.Path.GetTempPath(),"aetheris-x2-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(Path);}public string Path{get;}public void Dispose(){if(Directory.Exists(Path))Directory.Delete(Path,true);}}+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 6beb77b5..b0cf06db 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -24,6 +24,7 @@ using Aetheris.Piping;using Aetheris.Surfacing;using Aetheris.Geometry;using Aetheris.SheetMetal;+using Aetheris.Kernel.Firmament.Structural;namespace Aetheris.CLI;@@ -459,6 +460,7 @@ public static class CliRunnerfeatures = build.Value.Export.Features,engineeringFeatures = build.Value.Export.EngineeringFeatures,patterns = build.Value.Export.Patterns,+ structural = build.Value.Export.Structural,featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0),inlineStepMigration = build.Value.Export.InlineStepMigration,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,@@ -479,6 +481,8 @@ public static class CliRunnerstdout.WriteLine($"Standard part: {standardPart.Family} via {standardPart.Template ?? "direct record"} ({standardPart.SemanticDescendants.Count} semantic descendants)");if (build.Value.Export.Sweep is { } sweep)stdout.WriteLine($"Sweep: {sweep.SegmentCount} analytic path segments, {sweep.Diameter:G6} mm diameter, {sweep.CenterlineLength:G6} mm centerline ({sweep.Cylinders} cylinders, {sweep.Tori} tori)");+ if (build.Value.Export.Structural is { } structure)+ stdout.WriteLine($"Structure: {structure.Members.Count} members, {structure.Joints.Count} joints, {structure.CutList.Count} cut-list groups; cut list: {structure.CutListArtifactPath}");foreach (var diagnostic in build.Diagnostics.Where(diagnostic => diagnostic.Severity == KernelDiagnosticSeverity.Warning))stderr.WriteLine($"- [Warning] {diagnostic.Source}: {diagnostic.Message}");}@@ -987,6 +991,14 @@ Model CanonicalPanel {}var source = File.ReadAllText(fullPath);+ if (StructuralAuthoring.IsStructuralSource(source))+ {+ var structural = StructuralAuthoring.Compile(source, fullPath);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = structural.IsSuccess, input = fullPath, domain = "Structural", structural = structural.Report, diagnostics = structural.Diagnostics }, JsonOptions));+ else if (structural.IsSuccess && structural.Report is { } structuralReport) stdout.WriteLine($"Structure {structuralReport.Structure}: {structuralReport.Members.Count} members, {structuralReport.Joints.Count} joints, {structuralReport.Welds.Count} welds, {structuralReport.CutList.Count} cut-list groups");+ else foreach (var diagnostic in structural.Diagnostics) stderr.WriteLine($"error: {diagnostic}");+ return structural.IsSuccess ? 0 : 1;+ }var library = FirmamentStandardLibraryResolver.Resolve(source, out var libraryDiagnostics);var inspectionSource = library?.Source ?? source;var sweepSource = ExpandSweepInspectionSource(source, out var sweepExpansionDiagnostics);@@ -1623,6 +1635,14 @@ Model CanonicalPanel {}var validationSource=File.ReadAllText(sourcePath);+ if (StructuralAuthoring.IsStructuralSource(validationSource))+ {+ var structural = StructuralAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));+ var payload = new { source = sourcePath, status = structural.IsSuccess ? "valid" : "invalid", domain = "Structural", summary = new { fatalDiagnosticCount = structural.Diagnostics.Count, warningDiagnosticCount = 0, members = structural.Report?.Members.Count ?? 0, joints = structural.Report?.Joints.Count ?? 0 }, diagnostics = structural.Diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));+ else stdout.WriteLine($"Firmament V2 Structural validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");+ return structural.IsSuccess ? 0 : 1;+ }if (CircularSweepAuthoring.IsSweepSource(validationSource)){var sweepSource = ExpandSweepInspectionSource(validationSource, out var sweepExpansionDiagnostics);diff --git a/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.cs b/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.csindex 28121473..88ecfbdb 100644--- a/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.cs+++ b/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.cs@@ -6,7 +6,7 @@ namespace Aetheris.Forge.Host.Tests;public sealed class StandardProductLibraryTests{[Fact]- public void CatalogExposesEightCoherentStandardProductFamilies()+ public void CatalogExposesEightProductFamiliesAlongsideOtherTemplateDomains(){var products = new ForgeProtocolHost().ListTemplates().Templates.Where(item => item.Id.StartsWith("Standard.Products.", StringComparison.Ordinal)).ToArray();diff --git a/Aetheris.Forge.Host.Tests/StructuralForgeProtocolTests.cs b/Aetheris.Forge.Host.Tests/StructuralForgeProtocolTests.csnew file mode 100644index 00000000..bdd383be--- /dev/null+++ b/Aetheris.Forge.Host.Tests/StructuralForgeProtocolTests.cs@@ -0,0 +1,19 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Forge.Host.Tests;++public sealed class StructuralForgeProtocolTests+{+ [Fact]+ public void Workbench_ListDescribeInvoke_UsesProtocolV1AndReturnsAssemblyAndCutList()+ {+ var host=new ForgeProtocolHost();const string id="Standard.Structural.WeldedWorkbench";+ Assert.Contains(host.ListTemplates().Templates,x=>x.Id==id);var description=Assert.IsType<ForgeTemplateDescription>(host.DescribeTemplate(id));Assert.Equal(6,description.Parameters.Single().Fields!.Count);Assert.Contains(ForgeArtifactKind.CutListJson,description.Artifacts);+ using var output=new Temp();var args=new Dictionary<string,JsonElement>{{"width",JsonSerializer.SerializeToElement("1000 mm")},{"depth",JsonSerializer.SerializeToElement("600 mm")},{"height",JsonSerializer.SerializeToElement("800 mm")},{"tubeSize",JsonSerializer.SerializeToElement("40 mm")},{"wallThickness",JsonSerializer.SerializeToElement("3 mm")},{"material",JsonSerializer.SerializeToElement("Standard.Materials.Steel.ASTM_A36")}};+ var result=host.InvokeTemplate(id,new(1,args,[ForgeArtifactKind.StepAp242,ForgeArtifactKind.CutListJson]),output.Path);Assert.True(result.Success,string.Join(Environment.NewLine,result.Diagnostics.Select(x=>x.Code+": "+x.Message)));Assert.Equal(2,result.Artifacts.Count);+ var step=File.ReadAllText(Path.Combine(output.Path,result.Artifacts.Single(x=>x.Kind==ForgeArtifactKind.StepAp242).Path));var imported=Step242AssemblyImporter.Import(step);Assert.True(imported.IsSuccess);Assert.Equal(10,imported.Value.Occurrences.Count);+ using var cut=JsonDocument.Parse(File.ReadAllText(Path.Combine(output.Path,result.Artifacts.Single(x=>x.Kind==ForgeArtifactKind.CutListJson).Path)));Assert.Equal(4,cut.RootElement.GetProperty("entries").GetArrayLength());+ }+ private sealed class Temp:IDisposable{public Temp(){Path=System.IO.Path.Combine(System.IO.Path.GetTempPath(),"forge-x2-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(Path);}public string Path{get;}public void Dispose(){if(Directory.Exists(Path))Directory.Delete(Path,true);}}+}diff --git a/Aetheris.Forge.Host/ForgeProtocolContracts.cs b/Aetheris.Forge.Host/ForgeProtocolContracts.csindex 39828ecf..e96285ad 100644--- a/Aetheris.Forge.Host/ForgeProtocolContracts.cs+++ b/Aetheris.Forge.Host/ForgeProtocolContracts.cs@@ -10,7 +10,7 @@ public static class ForgeHostProtocol}public enum ForgeProtocolDiagnosticSeverity { Info, Warning, Error }-public enum ForgeArtifactKind { StepAp242, FlatStep, Svg }+public enum ForgeArtifactKind { StepAp242, FlatStep, Svg, CutListJson }public sealed record ForgeHostInfo(int ProtocolVersion,diff --git a/Aetheris.Forge.Host/ForgeProtocolHost.cs b/Aetheris.Forge.Host/ForgeProtocolHost.csindex de0e05dc..5b6b63b3 100644--- a/Aetheris.Forge.Host/ForgeProtocolHost.cs+++ b/Aetheris.Forge.Host/ForgeProtocolHost.cs@@ -197,6 +197,7 @@ public sealed class ForgeProtocolHost["FlangedAdapterTemplate"] = ("Standard.Products.Mechanical.FlangedAdapter", "Flanged Adapter", "Six-hole circular flanged adapter with a central bore, bolt-circle constraints, and bore PMI."),["RackPanelTemplate"] = ("Standard.Products.Electronics.RackPanel", "Rack Panel", "Metric planar equipment panel with symmetric mounting holes and configurable edge inset."),["StandoffTemplate"] = ("Standard.Products.Mechanical.Standoff", "Standoff", "Compact cylindrical spacer with a concentric fastener-clearance bore."),+ ["WeldedWorkbenchTemplate"] = ("Standard.Structural.WeldedWorkbench", "Welded Workbench", "Semantic square-tube workbench frame with miter/butt joints, A36 defaults, AP242 member assembly, and deterministic Cut List."),};var records = products.Records.ToDictionary(record => record.Name, StringComparer.Ordinal);var enums = products.Enums.ToDictionary(value => value.Name, StringComparer.Ordinal);@@ -206,8 +207,9 @@ public sealed class ForgeProtocolHostvar definition = definitions[item.Name];var recordName = item.Parameters.Single().TypeName;var isolatedSource = StandardProductTemplateLibrary.GetTemplateSource(item.Name, recordName);+ var artifacts = item.Name == "WeldedWorkbenchTemplate" ? new[] { ForgeArtifactKind.StepAp242, ForgeArtifactKind.CutListJson } : [ForgeArtifactKind.StepAp242];return new RegisteredTemplate(definition.Id, definition.Name, productVersion, definition.Documentation,- isolatedSource, item, records, enums, staticRecords, [ForgeArtifactKind.StepAp242], true);+ isolatedSource, item, records, enums, staticRecords, artifacts, true);});return sheetMetal.Concat(productTemplates).ToArray();}@@ -386,8 +388,10 @@ public sealed class ForgeProtocolHostprivate static (string Name, string ContentType, string Content) GenerateNativeArtifact(ForgeArtifactKind kind, FirmamentStepExportResult result, string templateId) =>kind == ForgeArtifactKind.StepAp242- ? (templateId == PaperclipTemplateLibrary.TemplateId ? "paperclip.step" : "part.step", "model/step", result.StepText)- : throw new InvalidOperationException($"Native Firmament artifact kind '{kind}' has no generator.");+ ? (templateId == PaperclipTemplateLibrary.TemplateId ? "paperclip.step" : templateId == "Standard.Structural.WeldedWorkbench" ? "welded-workbench.step" : "part.step", "model/step", result.StepText)+ : kind == ForgeArtifactKind.CutListJson && result.Structural is not null+ ? ("welded-workbench.cutlist.json", "application/json", Aetheris.Kernel.Firmament.Structural.StructuralAuthoring.CutListJson(result.Structural))+ : throw new InvalidOperationException($"Native Firmament artifact kind '{kind}' has no generator.");private static ForgeProtocolDiagnostic FromFirmamentDiagnostic(string value){diff --git a/Aetheris.Kernel.Firmament.Tests/StructuralX2Tests.cs b/Aetheris.Kernel.Firmament.Tests/StructuralX2Tests.csnew file mode 100644index 00000000..6504887e--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/StructuralX2Tests.cs@@ -0,0 +1,189 @@+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Firmament.Structural;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class StructuralX2Tests+{+ private static readonly string Root = FindRoot();++ [Fact]+ public void WeldedWorkbench_LowersSemanticMembersBeforeGeometry_AndRoundTripsAsAssembly()+ {+ var path = Path.Combine(Root, "fixtures", "Canonical", "Structural", "welded-workbench.firmament");+ var result = StructuralAuthoring.Compile(File.ReadAllText(path), path);++ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics));+ var report = Assert.IsType<StructuralReport>(result.Report);+ Assert.Equal(10, report.Members.Count);+ Assert.Equal(10, report.Assembly.MemberDefinitions.Count);+ Assert.Equal(10, report.Assembly.MemberOccurrences.Count);+ Assert.Equal(12, report.Assembly.JointInterfaces.Count);+ Assert.Equal(12, report.Joints.Count);+ Assert.Equal(12, report.Interfaces.Count);+ Assert.Equal(4, report.Interfaces.Count(x => x.Relation == "SharedCutSurface"));+ Assert.All(report.Interfaces, x =>+ {+ Assert.True(x.RetainedHalfSpacesOpposed);+ Assert.Equal(0d, x.VolumetricOverlapMm3);+ });+ Assert.All(report.Interfaces.Where(x => x.Relation == "SharedCutSurface"), x =>+ {+ Assert.True(x.MatingSurfacesCoincident);+ Assert.Equal("SeparatingAngleBisector", x.SelectedStrategy);+ Assert.Contains(x.RejectedCandidates, candidate => candidate.StartsWith("ReflexAngleBisector:", StringComparison.Ordinal));+ });+ Assert.Equal(12, report.Welds.Count);+ Assert.Equal(4, report.CutList.Count);+ Assert.Contains(report.CutList, x => x.Quantity == 4 && x.FinishedLengthMm == 780 && x.StartTreatment == "Square" && x.EndTreatment == "TrimmedTo");+ Assert.Contains(report.CutList, x => x.Quantity == 2 && x.FinishedLengthMm == 1000 && x.StartTreatment == "Miter 45deg");+ Assert.Contains(report.CutList, x => x.Quantity == 2 && x.FinishedLengthMm == 560 && x.StartTreatment == "TrimmedTo" && x.EndTreatment == "TrimmedTo");+ Assert.True(report.MembersEnclosed);+ Assert.Equal(10, report.BodyCount);+ Assert.Equal(100, report.PlaneCount);+ Assert.Equal([-20d,-20d,0d,1020d,620d,820d], report.Bounds);++ var imported = Step242AssemblyImporter.Import(result.StepText!);+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(x => x.Message)));+ Assert.Equal(10, imported.Value.Occurrences.Count);+ Assert.Equal(10, imported.Value.Definitions.Count(x => x.Geometry is not null));+ }++ [Fact]+ public void WeldedWorkbench_IsDeterministic()+ {+ var path = Path.Combine(Root, "fixtures", "Canonical", "Structural", "welded-workbench.firmament");+ var source = File.ReadAllText(path);+ var first = StructuralAuthoring.Compile(source, path);+ var second = StructuralAuthoring.Compile(source, path);+ Assert.True(first.IsSuccess && second.IsSuccess);+ Assert.Equal(first.StepText, second.StepText);+ Assert.Equal(first.Report!.StepSha256, second.Report!.StepSha256);+ Assert.Equal(StructuralAuthoring.CutListJson(first.Report), StructuralAuthoring.CutListJson(second.Report));+ }++ [Fact]+ public void MiterPathingPolicy_RejectsReflexOverlapCandidate()+ {+ var result = StructuralJointPathingPolicy.SelectMiter(new(new(-1,0,0), new(0,1,0)));+ Assert.True(result.IsSuccess);+ Assert.Equal("SeparatingAngleBisector", result.SelectedStrategy);+ Assert.True(result.RetainedHalfSpacesOpposed);+ Assert.Equal(new Vector3D(-1,-1,0), result.PlaneNormal);+ Assert.Contains(result.RejectedCandidates, candidate => candidate.StartsWith("ReflexAngleBisector:", StringComparison.Ordinal));+ }++ [Fact]+ public void PictureFrameRail_ReimportedTopProfile_IsIsoscelesTrapezoidNotParallelogram()+ {+ var path = Path.Combine(Root, "fixtures", "Canonical", "Structural", "welded-workbench.firmament");+ var compiled = StructuralAuthoring.Compile(File.ReadAllText(path), path);+ Assert.True(compiled.IsSuccess, string.Join(Environment.NewLine, compiled.Diagnostics));+ var frontRail = Assert.Single(Assert.IsAssignableFrom<IReadOnlyList<StructuralMemberIr>>(compiled.RealizedMembers),+ member => member.StableId == "member:FrontRail");+ Assert.True(Math.Abs(frontRail.StartPlane.CenterDepth) < 1e-7,+ $"Unexpected FrontRail start plane: {frontRail.StartPlane}");+ Assert.Equal(1d, frontRail.StartPlane.XCoefficient, 7);+ Assert.Equal(-1d, frontRail.EndPlane.XCoefficient, 7);+ var directBody = frontRail.Body;+ AssertTopProfile(directBody, "direct member BRep");+ var imported = Step242AssemblyImporter.Import(compiled.StepText!);+ Assert.True(imported.IsSuccess);+ var body = Assert.IsType<BrepBody>(imported.Value.Definitions.Single(x => x.Name == "member:FrontRail").Geometry);+ AssertTopProfile(body, "reimported AP242 member definition");++ static void AssertTopProfile(BrepBody body, string stage)+ {+ var top = body.Topology.Faces.Single(face =>+ {+ var surface = body.GetFaceSurface(face.Id);+ return surface.Kind == SurfaceGeometryKind.Plane && surface.Plane!.Value.Normal.Z > .999+ && Math.Abs(surface.Plane.Value.Origin.Z - 820d) < 1e-7;+ });+ var points = top.LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)+ .Select(id => body.Topology.GetCoedge(id)).Select(coedge => (Coedge: coedge, Edge: body.Topology.GetEdge(coedge.EdgeId)))+ .Select(use => { Assert.True(body.TryGetVertexPoint(use.Coedge.IsReversed ? use.Edge.EndVertexId : use.Edge.StartVertexId, out var point)); return point; })+ .Distinct().ToArray();+ Assert.True(points.Length == 4, $"{stage}: expected four trapezoid vertices, got {points.Length}: {string.Join("; ", points.Select(p => $"({p.X:G17},{p.Y:G17},{p.Z:G17})"))}");+ var lowerY = points.Where(point => Math.Abs(point.Y + 20d) < 1e-7).OrderBy(point => point.X).ToArray();+ var upperY = points.Where(point => Math.Abs(point.Y - 20d) < 1e-7).OrderBy(point => point.X).ToArray();+ Assert.Equal([-20d, 1020d], lowerY.Select(point => point.X).ToArray());+ Assert.True(upperY.Select(point => point.X).SequenceEqual([20d, 980d]),+ $"{stage}: unexpected upper edge; face={string.Join("; ", points.Select(p => $"({p.X:G17},{p.Y:G17},{p.Z:G17})"))}; all-top={string.Join("; ", body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : default).Where(p => Math.Abs(p.Z-820d)<1e-7).Select(p => $"({p.X:G17},{p.Y:G17},{p.Z:G17})"))}");+ Assert.Equal(1040d, lowerY[1].X - lowerY[0].X);+ Assert.Equal(960d, upperY[1].X - upperY[0].X);+ }+ }++ [Fact]+ public void MiterCapSupportPlaneMismatch_ReportsActionableStepAndPictureFrameDiagnostic()+ {+ var path = Path.Combine(Root, "fixtures", "Canonical", "Structural", "welded-workbench.firmament");+ var compiled = StructuralAuthoring.Compile(File.ReadAllText(path), path);+ Assert.True(compiled.IsSuccess, string.Join(Environment.NewLine, compiled.Diagnostics));+ var member = Assert.Single(compiled.RealizedMembers!, item => item.StableId == "member:FrontRail");+ var body = member.Body;+ var startFace = body.Topology.Faces.OrderBy(face => face.Id.Value).First();+ var startBinding = body.Bindings.GetFaceBinding(startFace.Id);+ var geometry = new BrepGeometryStore();+ foreach (var entry in body.Geometry.Curves)+ geometry.AddCurve(entry.Key, entry.Value);+ foreach (var entry in body.Geometry.Surfaces)+ {+ var replacement = entry.Key == startBinding.SurfaceGeometryId+ ? SurfaceGeometry.FromPlane(new PlaneSurface(+ entry.Value.Plane!.Value.Origin,+ Direction3D.Create(new Vector3D(-1, -1, 0)),+ Direction3D.Create(new Vector3D(0, 0, 1))))+ : entry.Value;+ geometry.AddSurface(entry.Key, replacement);+ }+ var points = body.Topology.Vertices.ToDictionary(+ vertex => vertex.Id,+ vertex => { Assert.True(body.TryGetVertexPoint(vertex.Id, out var point)); return point; });+ var malformed = new BrepBody(body.Topology, geometry, body.Bindings, points);++ var diagnostic = Assert.Single(StructuralMemberBrepEmitter.ValidateCapSupportPlanes("FrontRail", malformed));+ Assert.StartsWith("structural-member-cap-support-plane-mismatch:FrontRail:Start:", diagnostic, StringComparison.Ordinal);+ Assert.Contains("STEP resolves vertices from incident support planes", diagnostic, StringComparison.Ordinal);+ Assert.Contains("picture-frame miters into a parallelogram", diagnostic, StringComparison.Ordinal);+ Assert.Contains("normal = -Z + X*Start.XCoefficient + Y*Start.YCoefficient", diagnostic, StringComparison.Ordinal);+ }++ [Theory]+ [InlineData("zero-length-member.firmament", "structural-zero-length-member-path")]+ [InlineData("invalid-section-dimensions.firmament", "structural-section-invalid-dimensions")]+ [InlineData("wall-thickness-too-large.firmament", "structural-section-wall-too-large")]+ [InlineData("missing-section-orientation.firmament", "structural-member-orientation-required")]+ [InlineData("disconnected-joint.firmament", "structural-disconnected-joint")]+ [InlineData("miter-geometry-unsupported.firmament", "structural-miter-round-section-unsupported")]+ [InlineData("joint-unknown-member.firmament", "structural-joint-unknown-member")]+ public void InvalidStructuralFixtures_IsolateExpectedDiagnostic(string file, string expected)+ {+ var path = Path.Combine(Root, "fixtures", "Invalid", "Structural", file);+ var result = StructuralAuthoring.Compile(File.ReadAllText(path), path);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, x => x.Contains(expected, StringComparison.Ordinal));+ }++ [Theory]+ [InlineData("square-tube-member.firmament")]+ [InlineData("rectangular-tube-member.firmament")]+ [InlineData("oriented-angle-member.firmament")]+ [InlineData("butt-joint.firmament")]+ [InlineData("miter-joint.firmament")]+ [InlineData("simple-structural-frame.firmament")]+ public void CanonicalStructuralFixtures_CompileAndReimport(string file)+ {+ var path = Path.Combine(Root, "fixtures", "Canonical", "Structural", file);+ var result = StructuralAuthoring.Compile(File.ReadAllText(path), path);+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics));+ Assert.True(Step242AssemblyImporter.Import(result.StepText!).IsSuccess);+ }++ private static string FindRoot() { var d = new DirectoryInfo(AppContext.BaseDirectory); while (d is not null && !File.Exists(Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent; return d?.FullName ?? throw new DirectoryNotFoundException(); }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 892dcdb9..d984fd05 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -18,6 +18,7 @@ using Aetheris.Kernel.Firmament.Execution;using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Firmament.Materializer;using Aetheris.Kernel.StandardLibrary;+using Aetheris.Kernel.Firmament.Structural;namespace Aetheris.Kernel.Firmament;@@ -37,6 +38,21 @@ public static class FirmamentBuildAndExportvar fullSourcePath = Path.GetFullPath(sourcePath);var sourceText = NormalizeLf(File.ReadAllText(fullSourcePath, Encoding.UTF8));+ if (StructuralAuthoring.IsStructuralSource(sourceText))+ {+ var structural = StructuralAuthoring.Compile(sourceText, fullSourcePath);+ if (!structural.IsSuccess || structural.StepText is null || structural.Report is null)+ return KernelResult<FirmamentBuildAndExportResult>.Failure(structural.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Structural.X2")).ToArray());+ var structuralOutputPath = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath(fullSourcePath) : Path.GetFullPath(outputPath);+ Directory.CreateDirectory(Path.GetDirectoryName(structuralOutputPath)!);+ File.WriteAllText(structuralOutputPath, structural.StepText, new UTF8Encoding(false));+ var cutListPath = Path.Combine(Path.GetDirectoryName(structuralOutputPath)!, Path.GetFileNameWithoutExtension(structuralOutputPath) + ".cutlist.json");+ File.WriteAllText(cutListPath, StructuralAuthoring.CutListJson(structural.Report), new UTF8Encoding(false));+ var report = structural.Report with { CutListArtifactPath = cutListPath };+ var structuralExport = new FirmamentStepExportResult(structural.StepText, "structure:" + report.Structure, -1, "Assembly", "Structure", Structural: report);+ return KernelResult<FirmamentBuildAndExportResult>.Success(new(fullSourcePath, structuralOutputPath, structuralExport));+ }var library = FirmamentStandardLibraryResolver.Resolve(sourceText, out var libraryDiagnostics);if (library is null)return KernelResult<FirmamentBuildAndExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));@@ -85,6 +101,14 @@ public static class FirmamentBuildAndExport{ArgumentNullException.ThrowIfNull(sourceText);var normalized = NormalizeLf(sourceText);+ if (StructuralAuthoring.IsStructuralSource(normalized))+ {+ var structural = StructuralAuthoring.Compile(normalized, sourceDirectory ?? "memory");+ return structural.IsSuccess && structural.StepText is not null && structural.Report is not null+ ? KernelResult<FirmamentStepExportResult>.Success(new(structural.StepText, "structure:" + structural.Report.Structure, -1, "Assembly", "Structure", Structural: structural.Report))+ : KernelResult<FirmamentStepExportResult>.Failure(structural.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Structural.X2")).ToArray());+ }var library = FirmamentStandardLibraryResolver.Resolve(normalized, out var libraryDiagnostics);if (library is null)return KernelResult<FirmamentStepExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 9fe19c9c..9813aeff 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -23,7 +23,8 @@ public sealed record FirmamentStepExportResult(FirmamentStandardPartReport? StandardPart = null,IReadOnlyList<FirmamentEngineeringFeatureReport>? EngineeringFeatures = null,FirmamentSweepReport? Sweep = null,- IReadOnlyList<FirmamentSemanticPatternReport>? Patterns = null);+ IReadOnlyList<FirmamentSemanticPatternReport>? Patterns = null,+ Aetheris.Kernel.Firmament.Structural.StructuralReport? Structural = null);public sealed record FirmamentSemanticPatternReport(string Name,diff --git a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmamentindex fea4d182..73854a5f 100644--- a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament+++ b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament@@ -224,4 +224,46 @@ Model StandardProducts {} }Compose Body { Base Standoff { Profile: StandoffProfile; From: 0mm; To: P.Length; Role: Stock } Hole<Shaft> Bore { On: +Z; Center: [0mm, 0mm]; Diameter: P.BoreDiameter; End: ThroughAll; Role: FastenerClearance } }}++ Record WeldedWorkbenchPolicy { Width: Length Depth: Length Height: Length TubeSize: Length WallThickness: Length Material: String }+ Static StandardWeldedWorkbench: WeldedWorkbenchPolicy = WeldedWorkbenchPolicy { Width: 1000mm Depth: 600mm Height: 800mm TubeSize: 40mm WallThickness: 3mm Material: "Standard.Materials.Steel.ASTM_A36" }+ Template<P: WeldedWorkbenchPolicy = StandardWeldedWorkbench>+ Struct WeldedWorkbenchTemplate {+ Require PositiveEnvelope => P.Width > 0mm && P.Depth > 0mm && P.Height > 0mm+ Require PositiveSection => P.TubeSize > 0mm && P.WallThickness > 0mm+ Structure WorkbenchFrame {+ Node FLL = [0mm,0mm,0mm]; Node FRL = [P.Width,0mm,0mm]; Node BRL = [P.Width,P.Depth,0mm]; Node BLL = [0mm,P.Depth,0mm];+ Node FLT = [0mm,0mm,P.Height]; Node FRT = [P.Width,0mm,P.Height]; Node BRT = [P.Width,P.Depth,P.Height]; Node BLT = [0mm,P.Depth,P.Height];+ Node CAF = [P.Width / 3,0mm,P.Height]; Node CAB = [P.Width / 3,P.Depth,P.Height]; Node CBF = [P.Width * 2 / 3,0mm,P.Height]; Node CBB = [P.Width * 2 / 3,P.Depth,P.Height];+ Path FrontRail: FLT -> FRT; Path RightRail: FRT -> BRT; Path BackRail: BRT -> BLT; Path LeftRail: BLT -> FLT;+ Path FrontLeftLeg: FLL -> FLT; Path FrontRightLeg: FRL -> FRT; Path BackRightLeg: BRL -> BRT; Path BackLeftLeg: BLL -> BLT;+ Path CrossmemberA: CAF -> CAB; Path CrossmemberB: CBF -> CBB;+ }+ Section Tube { Kind: Standard.Structural.SquareTube; Width: P.TubeSize; Thickness: P.WallThickness; }+ StructuralDefaults Defaults { Material: P.Material; }+ Record StructuralMemberRow { Name: String Path: String Section: String Orientation: String }+ Static Table Members: StructuralMemberRow Key: Name {+ Name: ["FrontRail","RightRail","BackRail","LeftRail","FrontLeftLeg","FrontRightLeg","BackRightLeg","BackLeftLeg","CrossmemberA","CrossmemberB"]+ Path: ["FrontRail","RightRail","BackRail","LeftRail","FrontLeftLeg","FrontRightLeg","BackRightLeg","BackLeftLeg","CrossmemberA","CrossmemberB"]+ Section: ["Tube","Tube","Tube","Tube","Tube","Tube","Tube","Tube","Tube","Tube"]+ Orientation: ["UpZ","UpZ","UpZ","UpZ","UpX","UpX","UpX","UpX","UpZ","UpZ"]+ }+ Record StructuralJointRow { Name: String Type: String FirstMember: String FirstEnd: String SecondMember: String SecondEnd: String Primary: String }+ Static Table Joints: StructuralJointRow Key: Name {+ Name: ["J1","J2","J3","J4","J5","J6","J7","J8","J9","J10","J11","J12"]+ Type: ["Miter","Miter","Miter","Miter","Butt","Butt","Butt","Butt","Butt","Butt","Butt","Butt"]+ FirstMember: ["FrontRail","RightRail","BackRail","LeftRail","FrontRail","FrontRail","BackRail","BackRail","FrontRail","BackRail","FrontRail","BackRail"]+ FirstEnd: ["End","End","End","End","Start","End","Start","End","Start","Start","Start","Start"]+ SecondMember: ["RightRail","BackRail","LeftRail","FrontRail","FrontLeftLeg","FrontRightLeg","BackRightLeg","BackLeftLeg","CrossmemberA","CrossmemberA","CrossmemberB","CrossmemberB"]+ SecondEnd: ["Start","Start","Start","Start","End","End","End","End","Start","End","Start","End"]+ Primary: ["FrontRail","RightRail","BackRail","LeftRail","FrontRail","FrontRail","BackRail","BackRail","FrontRail","BackRail","FrontRail","BackRail"]+ }+ Record StructuralWeldRow { Name: String Joint: String Type: String Size: Length }+ Static Table Welds: StructuralWeldRow Key: Name {+ Name: ["W1","W2","W3","W4","W5","W6","W7","W8","W9","W10","W11","W12"]+ Joint: ["J1","J2","J3","J4","J5","J6","J7","J8","J9","J10","J11","J12"]+ Type: ["Fillet","Fillet","Fillet","Fillet","Fillet","Fillet","Fillet","Fillet","Fillet","Fillet","Fillet","Fillet"]+ Size: [4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm]+ }+ }}diff --git a/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs b/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.csnew file mode 100644index 00000000..5961fc5d--- /dev/null+++ b/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs@@ -0,0 +1,531 @@+using System.Globalization;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Numerics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.StandardLibrary.Materials;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Structural;++public enum StructuralSectionKind { SquareTube, RectangularTube, RoundTube, Angle, FlatBar, RoundBar }+public enum StructuralJointKind { Butt, Miter }+public enum StructuralEnd { Start, End }++public sealed record StructuralNodeAir(string StableId, string Name, Point3D Point, string SourceProvenance);+public sealed record StructuralPathAir(string StableId, string Name, string StartNode, string EndNode, Vector3D Direction, double Length, string SourceProvenance);+public sealed record StructuralSectionAir(string StableId, string Name, StructuralSectionKind Kind, double Width, double Height, double Thickness, double Radius, double Area);+public sealed record StructuralMemberAir(string StableId, string Name, string Path, string Section, string Material, Vector3D Orientation, string StartInterface, string EndInterface);+public sealed record StructuralJointAir(string StableId, string Name, StructuralJointKind Kind, string FirstMember, StructuralEnd FirstEnd, string SecondMember, StructuralEnd SecondEnd, string PrimaryMember);+public sealed record StructuralWeldAir(string StableId, string Name, string Joint, string Type, double Size, IReadOnlyList<string> Members);+public sealed record StructuralJointInterfaceIr(+ string StableId, string Joint, string Relation,+ string FirstMember, string FirstMemberInterface, string SecondMember, string SecondMemberInterface,+ IReadOnlyList<double>? SharedPlaneOrigin, IReadOnlyList<double>? SharedPlaneNormal, bool? MatingSurfacesCoincident,+ string? SelectedStrategy, double? UtilityScore, bool? RetainedHalfSpacesOpposed,+ double? VolumetricOverlapMm3, IReadOnlyList<string> RejectedCandidates);+public sealed record StructuralAssemblyIr(+ string StableId, string Name, IReadOnlyList<string> MemberDefinitions,+ IReadOnlyList<string> MemberOccurrences, IReadOnlyList<string> JointInterfaces);+public sealed record StructuralEndTreatmentIr(string Kind, double? AngleDegrees = null, string? RelatedMember = null);+public sealed record StructuralMemberIr(string StableId, string PathStableId, string SectionStableId, string Material, double RawLength, double FinishedLength, StructuralEndTreatmentIr StartTreatment, StructuralEndTreatmentIr EndTreatment, double VolumeMm3, double MassKilograms, BrepBody Body, StructuralEndPlane StartPlane, StructuralEndPlane EndPlane);+public sealed record StructuralCutListEntry(string GroupId, string Section, string SectionKind, string Material, int Quantity, double RawLengthMm, double FinishedLengthMm, string StartTreatment, string EndTreatment, double MassKilograms, IReadOnlyList<string> Members);+public sealed record StructuralTimingReport(double ParseBindMilliseconds, double JointResolutionMilliseconds, double MemberGeometryMilliseconds, double AssemblyAndStepMilliseconds, double CutListMilliseconds);+public sealed record StructuralReport(+ string Schema, string Structure, StructuralAssemblyIr Assembly, IReadOnlyList<StructuralNodeAir> Nodes, IReadOnlyList<StructuralPathAir> Paths,+ IReadOnlyList<StructuralSectionAir> Sections, IReadOnlyList<StructuralMemberSummary> Members,+ IReadOnlyList<StructuralJointAir> Joints, IReadOnlyList<StructuralJointInterfaceIr> Interfaces,+ IReadOnlyList<StructuralWeldAir> Welds, IReadOnlyList<StructuralCutListEntry> CutList,+ string MaterializationRoute, string StepSha256, int BodyCount, int FaceCount, int PlaneCount, int CylinderCount,+ IReadOnlyList<double> Bounds, double AssemblyMassKilograms, bool StepReimportSucceeded, bool MembersEnclosed,+ string? CutListArtifactPath, StructuralTimingReport Timings);+public sealed record StructuralMemberSummary(string StableId, string Path, string Section, string Material, double RawLengthMm, double FinishedLengthMm, string StartTreatment, string EndTreatment, double MassKilograms);++public sealed record StructuralCompilationResult(bool IsSuccess, string? StepText, StructuralReport? Report, IReadOnlyList<string> Diagnostics,+ IReadOnlyList<StructuralMemberIr>? RealizedMembers = null);+public readonly record struct StructuralEndPlane(double CenterDepth, double XCoefficient, double YCoefficient, StructuralEndTreatmentIr Treatment);++/// <summary>+/// Bounded X2 structural authoring front end. It deliberately recognizes only explicit Nodes,+/// straight Paths, constant Sections, Members, two-member Butt/Miter Joints, and Fillet Weld requirements.+/// The resulting immutable records are fabrication AIR; no joint is inferred from finished solids.+/// </summary>+public static class StructuralAuthoring+{+ private const double Tol = 1e-7;+ public static bool IsStructuralSource(string source) => Regex.IsMatch(source, @"\bStructure\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);++ public static StructuralCompilationResult Compile(string source, string sourceIdentity = "memory")+ {+ var total = System.Diagnostics.Stopwatch.StartNew();+ var diagnostics = new List<string>();+ var parseClock = System.Diagnostics.Stopwatch.StartNew();+ var parsed = Parse(source, sourceIdentity, diagnostics);+ parseClock.Stop();+ if (parsed is null) return new(false, null, null, diagnostics);++ var jointClock = System.Diagnostics.Stopwatch.StartNew();+ var resolved = ResolveJoints(parsed, diagnostics);+ jointClock.Stop();+ if (diagnostics.Count > 0) return new(false, null, null, diagnostics);++ var geometryClock = System.Diagnostics.Stopwatch.StartNew();+ var realized = new List<StructuralMemberIr>();+ foreach (var member in parsed.Members.OrderBy(x => x.StableId, StringComparer.Ordinal))+ {+ var path = parsed.Paths.Single(x => x.Name == member.Path);+ var section = parsed.Sections.Single(x => x.Name == member.Section);+ var start = parsed.Nodes.Single(x => x.Name == path.StartNode).Point;+ var direction = Direction3D.Create(path.Direction);+ var frame = MemberFrame(direction, member.Orientation, diagnostics, member.Name);+ if (frame is null) continue;+ var endPlan = resolved[member.Name];+ var body = StructuralMemberBrepEmitter.Emit(member.Name, section, start, frame.Value.X, frame.Value.Y, direction, endPlan.Start, endPlan.End);+ if (!body.IsSuccess || body.Value is null)+ {+ diagnostics.AddRange(body.Diagnostics.Select(x => $"structural-member-geometry:{member.Name}: {x.Message}"));+ continue;+ }+ var finished = endPlan.End.CenterDepth - endPlan.Start.CenterDepth;+ var volume = section.Area * finished;+ var material = parsed.Materials[member.Material];+ realized.Add(new(member.StableId, path.StableId, section.StableId, material.Identity.FirmamentPath, path.Length, finished,+ endPlan.Start.Treatment, endPlan.End.Treatment, volume, volume * 1e-9 * material.Structural!.Density.SiValue, body.Value, endPlan.Start, endPlan.End));+ }+ geometryClock.Stop();+ if (diagnostics.Count > 0) return new(false, null, null, diagnostics);++ var interfaces = BuildInterfaces(parsed, realized, diagnostics);+ if (diagnostics.Count > 0) return new(false, null, null, diagnostics);++ var assemblyClock = System.Diagnostics.Stopwatch.StartNew();+ var definitions = realized.Select(x => new Step242AssemblyDefinition("def:" + x.StableId, x.StableId, x.Body)).ToArray();+ var identity = new double[] { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };+ var occurrences = new[] { new Step242AssemblyOccurrence("structure:" + parsed.Name, parsed.Name, null, null, identity) }+ .Concat(realized.Select(x => new Step242AssemblyOccurrence("occ:" + x.StableId, x.StableId, "structure:" + parsed.Name, "def:" + x.StableId, identity))).ToArray();+ var assembly = new StructuralAssemblyIr("structure:" + parsed.Name, parsed.Name,+ definitions.Select(x => x.StableId).Order(StringComparer.Ordinal).ToArray(),+ occurrences.Where(x => x.DefinitionStableId is not null).Select(x => x.StableId).Order(StringComparer.Ordinal).ToArray(),+ interfaces.Select(x => x.StableId).Order(StringComparer.Ordinal).ToArray());+ var step = Step242AssemblyExporter.Export(new(parsed.Name, "structure:" + parsed.Name, definitions, occurrences));+ if (!step.IsSuccess || step.Value is null)+ {+ diagnostics.AddRange(step.Diagnostics.Select(x => "structural-step-export: " + x.Message));+ return new(false, null, null, diagnostics);+ }+ var imported = Step242AssemblyImporter.Import(step.Value);+ assemblyClock.Stop();+ if (!imported.IsSuccess)+ {+ diagnostics.AddRange(imported.Diagnostics.Select(x => "structural-step-reimport: " + x.Message));+ return new(false, null, null, diagnostics);+ }++ var cutClock = System.Diagnostics.Stopwatch.StartNew();+ var cutList = BuildCutList(parsed, realized);+ cutClock.Stop();+ var allPoints = realized.SelectMany(x => x.Body.Topology.Vertices.Select(v => x.Body.TryGetVertexPoint(v.Id, out var p) ? p : default)).ToArray();+ var surfaces = realized.SelectMany(x => x.Body.Topology.Faces.Select(f => x.Body.GetFaceSurface(f.Id).Kind)).ToArray();+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();+ total.Stop();+ var summaries = realized.Select(x => new StructuralMemberSummary(x.StableId, x.PathStableId, x.SectionStableId, x.Material, x.RawLength, x.FinishedLength,+ Treatment(x.StartTreatment), Treatment(x.EndTreatment), x.MassKilograms)).ToArray();+ var report = new StructuralReport("aetheris:structural:x2", parsed.Name, assembly, parsed.Nodes, parsed.Paths, parsed.Sections, summaries, parsed.Joints, interfaces, parsed.Welds, cutList,+ "Structure->MemberAIR->JointResolution->AssemblyInterfaces->MemberFinalization->AP242Assembly+CutList", hash, realized.Count,+ realized.Sum(x => x.Body.Topology.Faces.Count()), surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x == SurfaceGeometryKind.Cylinder),+ [allPoints.Min(x => x.X), allPoints.Min(x => x.Y), allPoints.Min(x => x.Z), allPoints.Max(x => x.X), allPoints.Max(x => x.Y), allPoints.Max(x => x.Z)],+ realized.Sum(x => x.MassKilograms), true, realized.All(IsEnclosed), null,+ new(parseClock.Elapsed.TotalMilliseconds, jointClock.Elapsed.TotalMilliseconds, geometryClock.Elapsed.TotalMilliseconds, assemblyClock.Elapsed.TotalMilliseconds, cutClock.Elapsed.TotalMilliseconds));+ return new(true, step.Value, report, [], realized);+ }++ public static string CutListJson(StructuralReport report) => JsonSerializer.Serialize(new+ {+ schema = "aetheris:structural-cut-list:x2", structure = report.Structure, units = new { length = "mm", mass = "kg" }, entries = report.CutList+ }, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase });++ private sealed record Parsed(string Name, IReadOnlyList<StructuralNodeAir> Nodes, IReadOnlyList<StructuralPathAir> Paths, IReadOnlyList<StructuralSectionAir> Sections, IReadOnlyList<StructuralMemberAir> Members, IReadOnlyList<StructuralJointAir> Joints, IReadOnlyList<StructuralWeldAir> Welds, IReadOnlyDictionary<string, ResolvedMaterial> Materials);+ private sealed record MemberEnds(StructuralEndPlane Start, StructuralEndPlane End);++ private static Parsed? Parse(string source, string sourceIdentity, List<string> d)+ {+ var structure = Blocks(source, "Structure").SingleOrDefault();+ if (structure == default) { d.Add("structural-missing-structure: exactly one Structure block is required"); return null; }+ if (Blocks(source, "Structure").Count != 1) { d.Add("structural-multiple-structures-unsupported: X2 admits one Structure per model"); return null; }+ var nodes = Regex.Matches(structure.Body, @"\bNode\s+(?<n>[A-Za-z_]\w*)\s*=\s*\[(?<v>[^\]]+)\]\s*;", RegexOptions.CultureInvariant)+ .Select(m => new StructuralNodeAir($"structure:{structure.Name}:node:{m.Groups["n"].Value}", m.Groups["n"].Value, Point(Vector(m.Groups["v"].Value, d, "node:" + m.Groups["n"].Value)), sourceIdentity)).ToArray();+ var paths = Regex.Matches(structure.Body, @"\bPath\s+(?<n>[A-Za-z_]\w*)\s*:\s*(?<a>[A-Za-z_]\w*)\s*->\s*(?<b>[A-Za-z_]\w*)\s*;", RegexOptions.CultureInvariant)+ .Select(m => (Name:m.Groups["n"].Value, A:m.Groups["a"].Value, B:m.Groups["b"].Value)).ToArray();+ Duplicates(nodes.Select(x => x.Name), "node", d); Duplicates(paths.Select(x => x.Name), "path", d);+ var nodeByName = nodes.ToDictionary(x => x.Name, StringComparer.Ordinal);+ var pathAir = new List<StructuralPathAir>();+ foreach (var p in paths)+ {+ if (!nodeByName.TryGetValue(p.A, out var a) || !nodeByName.TryGetValue(p.B, out var b)) { d.Add($"structural-path-unknown-node:{p.Name}: '{p.A}' -> '{p.B}'"); continue; }+ var delta = b.Point - a.Point; if (delta.Length <= Tol) { d.Add($"structural-zero-length-member-path:{p.Name}"); continue; }+ pathAir.Add(new($"structure:{structure.Name}:path:{p.Name}", p.Name, p.A, p.B, delta / delta.Length, delta.Length, sourceIdentity));+ }++ var sections = new List<StructuralSectionAir>();+ foreach (var block in Blocks(source, "Section"))+ {+ var kindText = Field(block.Body, "Kind");+ if (kindText.StartsWith("Standard.Structural.", StringComparison.Ordinal)) kindText = kindText["Standard.Structural.".Length..];+ if (!Enum.TryParse<StructuralSectionKind>(kindText, out var kind)) { d.Add($"structural-section-kind-unsupported:{block.Name}: '{kindText}'"); continue; }+ var width = LengthField(block.Body, kind == StructuralSectionKind.RoundTube || kind == StructuralSectionKind.RoundBar ? "Diameter" : "Width", d, block.Name);+ var height = kind is StructuralSectionKind.SquareTube ? width : kind is StructuralSectionKind.RoundTube or StructuralSectionKind.RoundBar ? width : LengthField(block.Body, "Height", d, block.Name);+ var thickness = kind is StructuralSectionKind.FlatBar or StructuralSectionKind.RoundBar ? 0 : LengthField(block.Body, "Thickness", d, block.Name);+ if (width <= 0 || height <= 0) d.Add($"structural-section-invalid-dimensions:{block.Name}: dimensions must be positive");+ if (kind is StructuralSectionKind.SquareTube or StructuralSectionKind.RectangularTube or StructuralSectionKind.RoundTube && (thickness <= 0 || thickness * 2 >= Math.Min(width, height))) d.Add($"structural-section-wall-too-large:{block.Name}");+ var area = kind switch { StructuralSectionKind.SquareTube or StructuralSectionKind.RectangularTube => width*height-(width-2*thickness)*(height-2*thickness), StructuralSectionKind.RoundTube => Math.PI/4*(width*width-(width-2*thickness)*(width-2*thickness)), StructuralSectionKind.Angle => thickness*(width+height-thickness), StructuralSectionKind.FlatBar => width*height, StructuralSectionKind.RoundBar => Math.PI/4*width*width, _ => 0 };+ sections.Add(new($"standard:structural:{kind}:{Q(width)}:{Q(height)}:{Q(thickness)}", block.Name, kind, width, height, thickness, width/2, area));+ }+ Duplicates(sections.Select(x => x.Name), "section", d);++ var resolver = new MaterialResolver(); var materials = new Dictionary<string, ResolvedMaterial>(StringComparer.Ordinal);+ var members = new List<StructuralMemberAir>();+ foreach (var block in Blocks(source, "Member"))+ {+ AddMember(block.Name, Field(block.Body, "Path"), Field(block.Body, "Section"), Field(block.Body, "Material"), Field(block.Body, "Orientation", required:false));+ }+ var defaultMaterial = Blocks(source,"StructuralDefaults").Select(x=>Field(x.Body,"Material",required:false)).FirstOrDefault(x=>!string.IsNullOrWhiteSpace(x)) ?? "";+ foreach (var row in TableRows(source, "StructuralMemberRow", d))+ AddMember(Cell(row,"Name"),Cell(row,"Path"),Cell(row,"Section"),Cell(row,"Material",false) is var tableMaterial && tableMaterial.Length>0?tableMaterial:defaultMaterial,Cell(row,"Orientation",false));+ void AddMember(string name,string path,string section,string materialValue,string orientationText)+ {+ var materialRef=materialValue.Trim().Trim('"');+ if (!pathAir.Any(x => x.Name == path)) d.Add($"structural-member-unknown-path:{name}: '{path}'");+ if (!sections.Any(x => x.Name == section)) d.Add($"structural-member-unknown-section:{name}: '{section}'");+ var asymmetric = sections.FirstOrDefault(x => x.Name == section)?.Kind is StructuralSectionKind.Angle;+ if (asymmetric && string.IsNullOrWhiteSpace(orientationText)) d.Add($"structural-member-orientation-required:{name}: asymmetric section '{section}' requires Orientation");+ var orientation = Orientation(orientationText,d,name);+ if (!materials.ContainsKey(materialRef)) { var resolvedMaterial = resolver.Resolve(materialRef); if (!resolvedMaterial.IsSuccess) d.Add($"structural-material-unresolved:{name}: {resolvedMaterial.Message}"); else materials[materialRef] = resolvedMaterial.Material!; }+ members.Add(new($"member:{name}", name, path, section, materialRef, orientation, "interface:"+name+":start", "interface:"+name+":end"));+ }+ Duplicates(members.Select(x => x.Name), "member", d);+ if (pathAir.Select(x => x.Name).Except(members.Select(x => x.Path), StringComparer.Ordinal).Any()) d.Add("structural-unassigned-path: every structural Path must have one Member assignment");+ if (members.GroupBy(x => x.Path).Any(g => g.Count() != 1)) d.Add("structural-path-member-cardinality: each Path must have exactly one Member");++ var joints = new List<StructuralJointAir>();+ foreach (var block in Blocks(source, "Joint"))+ {+ var endpoints = Field(block.Body, "Members").Trim('[',']').Split(',', StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);+ if (endpoints.Length != 2 || !TryEndpoint(endpoints[0], out var a, out var ae) || !TryEndpoint(endpoints[1], out var b, out var be)) { d.Add($"structural-joint-endpoints-invalid:{block.Name}: exactly two Member.Start/End references are required"); continue; }+ AddJoint(block.Name,Field(block.Body,"Type"),a,ae,b,be,Field(block.Body,"Primary",required:false));+ }+ foreach(var row in TableRows(source,"StructuralJointRow",d))+ {+ if(!Enum.TryParse<StructuralEnd>(Cell(row,"FirstEnd"),out var ae)||!Enum.TryParse<StructuralEnd>(Cell(row,"SecondEnd"),out var be)){d.Add($"structural-joint-endpoints-invalid:{Cell(row,"Name")}");continue;}+ AddJoint(Cell(row,"Name"),Cell(row,"Type"),Cell(row,"FirstMember"),ae,Cell(row,"SecondMember"),be,Cell(row,"Primary",false));+ }+ void AddJoint(string name,string type,string a,StructuralEnd ae,string b,StructuralEnd be,string primary)+ {+ if (!Enum.TryParse<StructuralJointKind>(type, out var kind)) { d.Add($"structural-joint-kind-unsupported:{name}: '{type}'"); return; }+ if (!members.Any(x => x.Name == a) || !members.Any(x => x.Name == b)) { d.Add($"structural-joint-unknown-member:{name}"); return; }+ if (string.IsNullOrEmpty(primary)) primary = a;+ if (kind == StructuralJointKind.Butt && primary != a && primary != b) d.Add($"structural-butt-primary-invalid:{name}: Primary must name a participant");+ joints.Add(new($"joint:{name}", name, kind, a, ae, b, be, primary));+ }+ Duplicates(joints.Select(x => x.Name), "joint", d);+ // A through member can host several terminating butt joints without changing its own end.+ // Only geometry-owning endpoints (both miter participants and the butt secondary) are exclusive.+ var occupied = joints.SelectMany(x => x.Kind == StructuralJointKind.Miter+ ? new[] { x.FirstMember+"."+x.FirstEnd, x.SecondMember+"."+x.SecondEnd }+ : new[] { (x.PrimaryMember == x.FirstMember ? x.SecondMember+"."+x.SecondEnd : x.FirstMember+"."+x.FirstEnd) })+ .GroupBy(x => x).Where(g => g.Count()>1).Select(g=>g.Key).ToArray();+ if (occupied.Length > 0) d.Add("structural-multiple-joints-at-end-unsupported: " + string.Join(", ", occupied));++ var welds = new List<StructuralWeldAir>();+ foreach (var block in Blocks(source, "Weld"))+ {+ AddWeld(block.Name,Field(block.Body,"Joint"),Field(block.Body,"Type"),Field(block.Body,"Size"));+ }+ foreach(var row in TableRows(source,"StructuralWeldRow",d))AddWeld(Cell(row,"Name"),Cell(row,"Joint"),Cell(row,"Type"),Cell(row,"Size"));+ void AddWeld(string name,string joint,string type,string sizeText)+ {+ var size=ParseLength(sizeText,d,name+".Size");var j=joints.FirstOrDefault(x=>x.Name==joint);if(j is null)d.Add($"structural-weld-unknown-joint:{name}: '{joint}'");if(type!="Fillet")d.Add($"structural-weld-type-unsupported:{name}: X2 admits Fillet");welds.Add(new($"weld:{name}",name,"joint:"+joint,type,size,j is null?[]:[j.FirstMember,j.SecondMember]));+ }+ return d.Count == 0 ? new(structure.Name, nodes, pathAir, sections, members, joints, welds, materials) : null;+ }++ private static Dictionary<string, MemberEnds> ResolveJoints(Parsed p, List<string> d)+ {+ var result = p.Members.ToDictionary(x => x.Name, x => new MemberEnds(new(0,0,0,new("Square")), new(p.Paths.Single(y=>y.Name==x.Path).Length,0,0,new("Square"))), StringComparer.Ordinal);+ foreach (var joint in p.Joints.OrderBy(x => x.StableId, StringComparer.Ordinal))+ {+ var first = p.Members.Single(x=>x.Name==joint.FirstMember); var second=p.Members.Single(x=>x.Name==joint.SecondMember);+ var fp=p.Paths.Single(x=>x.Name==first.Path); var sp=p.Paths.Single(x=>x.Name==second.Path);+ var nodeA = joint.FirstEnd==StructuralEnd.Start ? fp.StartNode : fp.EndNode; var nodeB=joint.SecondEnd==StructuralEnd.Start ? sp.StartNode : sp.EndNode;+ if (joint.Kind == StructuralJointKind.Miter && nodeA != nodeB) { d.Add($"structural-disconnected-joint:{joint.Name}: endpoints resolve to '{nodeA}' and '{nodeB}'"); continue; }+ var dot=Math.Abs(fp.Direction.Dot(sp.Direction)); if(dot>1-1e-6){d.Add($"structural-joint-collinear-unsupported:{joint.Name}");continue;}+ if(joint.Kind==StructuralJointKind.Miter)+ {+ var awayF=joint.FirstEnd==StructuralEnd.Start?fp.Direction:-fp.Direction; var awayS=joint.SecondEnd==StructuralEnd.Start?sp.Direction:-sp.Direction;+ // The two angle bisectors are not interchangeable. The difference bisector+ // separates the two rays leaving the node, so both member caps occupy one+ // coincident weld surface. The sum bisector puts both rays on the same side+ // and creates the characteristic crossed spikes/gaps at an outside corner.+ var selection=StructuralJointPathingPolicy.SelectMiter(new(awayF,awayS));+ if(!selection.IsSuccess||selection.SelectedStrategy is null){d.Add($"structural-miter-geometry-unsupported:{joint.Name}: {string.Join(" | ",selection.RejectedCandidates)}");continue;}+ var normal=selection.PlaneNormal;+ SetPlane(first,fp,joint.FirstEnd,normal,new("Miter", Math.Acos(Math.Clamp(awayF.Dot(awayS),-1,1))*90/Math.PI, second.StableId));+ SetPlane(second,sp,joint.SecondEnd,normal,new("Miter", Math.Acos(Math.Clamp(awayF.Dot(awayS),-1,1))*90/Math.PI, first.StableId));+ }+ else+ {+ var primary = joint.PrimaryMember==first.Name?first:second; var secondary=primary==first?second:first; var primaryPath=primary==first?fp:sp; var secondaryPath=secondary==first?fp:sp; var secondaryEnd=secondary==first?joint.FirstEnd:joint.SecondEnd;+ var secondaryNode=secondaryEnd==StructuralEnd.Start?secondaryPath.StartNode:secondaryPath.EndNode;+ var secondaryPoint=p.Nodes.Single(x=>x.Name==secondaryNode).Point;var primaryStart=p.Nodes.Single(x=>x.Name==primaryPath.StartNode).Point;var along=(secondaryPoint-primaryStart).Dot(primaryPath.Direction);+ var residual=(secondaryPoint-(primaryStart+primaryPath.Direction*along)).Length;+ if(residual>Tol||along < -Tol||along > primaryPath.Length+Tol){d.Add($"structural-disconnected-joint:{joint.Name}: terminating endpoint does not lie on through member '{primary.Name}'");continue;}+ var primarySection=p.Sections.Single(x=>x.Name==primary.Section); var clearance=ProjectedHalfExtent(primarySection, primaryPath.Direction, secondaryPath.Direction);+ var center=secondaryEnd==StructuralEnd.End?secondaryPath.Length-clearance:clearance;+ Update(secondary.Name,secondaryEnd,new(center,0,0,new("TrimmedTo",null,primary.StableId)));+ }+ void SetPlane(StructuralMemberAir member, StructuralPathAir path, StructuralEnd end, Vector3D worldNormal, StructuralEndTreatmentIr treatment)+ {+ var dir=Direction3D.Create(path.Direction); var frame=MemberFrame(dir,member.Orientation,d,member.Name); if(frame is null)return;+ var denominator=worldNormal.Dot(dir.ToVector()); if(Math.Abs(denominator)<Tol){d.Add($"structural-miter-geometry-unsupported:{joint.Name}: cut plane parallel to '{member.Name}'");return;}+ var center=end==StructuralEnd.Start?0:path.Length;+ Update(member.Name,end,new(center,-worldNormal.Dot(frame.Value.X.ToVector())/denominator,-worldNormal.Dot(frame.Value.Y.ToVector())/denominator,treatment));+ }+ void Update(string member,StructuralEnd end,StructuralEndPlane plane){var current=result[member];result[member]=end==StructuralEnd.Start?current with{Start=plane}:current with{End=plane};}+ }+ foreach(var pair in result) if(pair.Value.End.CenterDepth-pair.Value.Start.CenterDepth<=Tol)d.Add($"structural-member-finished-length-invalid:{pair.Key}");+ return result;+ }++ private static IReadOnlyList<StructuralJointInterfaceIr> BuildInterfaces(Parsed p, IReadOnlyList<StructuralMemberIr> realized, List<string> d)+ {+ var bodies = realized.ToDictionary(x => x.StableId, x => x.Body, StringComparer.Ordinal);+ var result = new List<StructuralJointInterfaceIr>();+ foreach (var joint in p.Joints.OrderBy(x => x.StableId, StringComparer.Ordinal))+ {+ var first = p.Members.Single(x => x.Name == joint.FirstMember);+ var second = p.Members.Single(x => x.Name == joint.SecondMember);+ var firstInterface = joint.FirstEnd == StructuralEnd.Start ? first.StartInterface : first.EndInterface;+ var secondInterface = joint.SecondEnd == StructuralEnd.Start ? second.StartInterface : second.EndInterface;+ if (joint.Kind == StructuralJointKind.Butt)+ {+ var primary = joint.PrimaryMember == first.Name ? first : second;+ var secondary = primary == first ? second : first;+ var primaryPath = p.Paths.Single(x => x.Name == primary.Path);+ var secondaryPath = p.Paths.Single(x => x.Name == secondary.Path);+ var secondaryEnd = secondary == first ? joint.FirstEnd : joint.SecondEnd;+ var secondaryNodeName = secondaryEnd == StructuralEnd.Start ? secondaryPath.StartNode : secondaryPath.EndNode;+ var node = p.Nodes.Single(x => x.Name == secondaryNodeName).Point;+ var away = secondaryEnd == StructuralEnd.Start ? secondaryPath.Direction : -secondaryPath.Direction;+ var primarySection = p.Sections.Single(x => x.Name == primary.Section);+ var contact = node + away * ProjectedHalfExtent(primarySection, primaryPath.Direction, secondaryPath.Direction);+ var primaryContained = AllVerticesInRetainedHalfSpace(bodies[primary.StableId], contact, away, -1);+ var secondaryContained = AllVerticesInRetainedHalfSpace(bodies[secondary.StableId], contact, away, 1);+ var buttOpposed = primaryContained && secondaryContained;+ if (!buttOpposed)+ d.Add($"structural-butt-interface-overlap:{joint.Name}: terminating and through members are not bounded to opposite contact half-spaces");+ result.Add(new("interface:" + joint.Name, joint.StableId, "EndToMemberEnvelope", first.StableId, firstInterface,+ second.StableId, secondInterface, [contact.X, contact.Y, contact.Z], [away.X, away.Y, away.Z], null,+ "AuthoredPrimaryButt", 100d, buttOpposed, buttOpposed ? 0d : null, []));+ continue;+ }++ var firstPath = p.Paths.Single(x => x.Name == first.Path);+ var secondPath = p.Paths.Single(x => x.Name == second.Path);+ var nodeName = joint.FirstEnd == StructuralEnd.Start ? firstPath.StartNode : firstPath.EndNode;+ var origin = p.Nodes.Single(x => x.Name == nodeName).Point;+ var awayFirst = joint.FirstEnd == StructuralEnd.Start ? firstPath.Direction : -firstPath.Direction;+ var awaySecond = joint.SecondEnd == StructuralEnd.Start ? secondPath.Direction : -secondPath.Direction;+ var selection = StructuralJointPathingPolicy.SelectMiter(new(awayFirst, awaySecond));+ if (!selection.IsSuccess || selection.SelectedStrategy is null)+ {+ d.Add($"structural-miter-interface-pathing-rejected:{joint.Name}: {string.Join(" | ", selection.RejectedCandidates)}");+ continue;+ }+ var normal = Direction3D.Create(selection.PlaneNormal).ToVector();+ var firstPoints = EndFacePoints(bodies[first.StableId], joint.FirstEnd);+ var secondPoints = EndFacePoints(bodies[second.StableId], joint.SecondEnd);+ var coincident = SamePointSet(firstPoints, secondPoints);+ if (!coincident)+ d.Add($"structural-miter-interface-noncoincident:{joint.Name}: member end loops do not share one weld surface");+ var onDeclaredPlane = firstPoints.Concat(secondPoints).All(point => Math.Abs(normal.Dot(point - origin)) <= Tol);+ if (!onDeclaredPlane)+ d.Add($"structural-miter-interface-off-plane:{joint.Name}: materialized end loops do not lie on the declared shared interface plane");+ var firstSign = Math.Sign(normal.Dot(awayFirst));+ var secondSign = Math.Sign(normal.Dot(awaySecond));+ var firstContained = AllVerticesInRetainedHalfSpace(bodies[first.StableId], origin, normal, firstSign);+ var secondContained = AllVerticesInRetainedHalfSpace(bodies[second.StableId], origin, normal, secondSign);+ var opposed = selection.RetainedHalfSpacesOpposed && firstSign == -secondSign && firstContained && secondContained;+ if (!opposed)+ d.Add($"structural-miter-interface-overlap:{joint.Name}: material is not bounded to opposite retained half-spaces");+ result.Add(new("interface:" + joint.Name, joint.StableId, "SharedCutSurface", first.StableId, firstInterface,+ second.StableId, secondInterface, [origin.X, origin.Y, origin.Z], [normal.X, normal.Y, normal.Z], coincident,+ selection.SelectedStrategy, selection.UtilityScore, opposed, opposed ? 0d : null, selection.RejectedCandidates));+ }+ return result;++ static IReadOnlyList<Point3D> EndFacePoints(BrepBody body, StructuralEnd end)+ {+ var caps = body.Topology.Faces.OrderBy(x => x.Id.Value).Take(2).ToArray();+ var face = caps[end == StructuralEnd.Start ? 0 : 1];+ return face.LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)+ .Select(id => body.Topology.GetCoedge(id))+ .Select(coedge => body.Topology.GetEdge(coedge.EdgeId))+ .Select(edge => body.TryGetVertexPoint(edge.StartVertexId, out var point) ? point : default)+ .ToArray();+ }+ static bool SamePointSet(IReadOnlyList<Point3D> a, IReadOnlyList<Point3D> b) =>+ a.Count == b.Count && a.All(point => b.Any(other => (point - other).Length <= Tol));+ static bool AllVerticesInRetainedHalfSpace(BrepBody body, Point3D origin, Vector3D normal, int retainedSign) =>+ retainedSign != 0 && body.Topology.Vertices.All(vertex =>+ body.TryGetVertexPoint(vertex.Id, out var point) && retainedSign * normal.Dot(point - origin) >= -Tol);+ }++ private static double ProjectedHalfExtent(StructuralSectionAir section, Vector3D primaryDirection, Vector3D targetDirection)+ {+ // X2 butt qualification is intentionally orthogonal and conservative: the through member's+ // circumscribed half-size is the deterministic terminating offset.+ return Math.Abs(primaryDirection.Dot(targetDirection)) > 1e-6 ? 0 : Math.Max(section.Width, section.Height)/2;+ }++ private static IReadOnlyList<StructuralCutListEntry> BuildCutList(Parsed p, IReadOnlyList<StructuralMemberIr> members)+ {+ return members.GroupBy(x => $"{x.SectionStableId}|{x.Material}|{Q(x.RawLength)}|{Q(x.FinishedLength)}|{TreatmentKey(x.StartTreatment)}|{TreatmentKey(x.EndTreatment)}", StringComparer.Ordinal)+ .OrderBy(g=>g.Key,StringComparer.Ordinal).Select((g,i)=>new StructuralCutListEntry($"cut-group:{i+1:D3}",g.First().SectionStableId,p.Sections.Single(x=>x.StableId==g.First().SectionStableId).Kind.ToString(),g.First().Material,g.Count(),g.First().RawLength,g.First().FinishedLength,TreatmentKey(g.First().StartTreatment),TreatmentKey(g.First().EndTreatment),g.Sum(x=>x.MassKilograms),g.Select(x=>x.StableId).Order(StringComparer.Ordinal).ToArray())).ToArray();+ }+ private static string TreatmentKey(StructuralEndTreatmentIr x)=>x.Kind=="Miter"?$"Miter {x.AngleDegrees:G6}deg":x.Kind;+ private static string Treatment(StructuralEndTreatmentIr x)=>x.Kind=="Miter"?$"Miter {x.AngleDegrees:G6}deg":x.Kind=="TrimmedTo"?$"TrimmedTo {x.RelatedMember}":x.Kind;+ private static bool IsEnclosed(StructuralMemberIr x)=>x.Body.Topology.Edges.All(e=>x.Body.Topology.Coedges.Count(c=>c.EdgeId==e.Id)==2);+ private static (Direction3D X,Direction3D Y)? MemberFrame(Direction3D z,Vector3D authored,List<string>d,string member)+ {+ var hint=authored.Length>Tol?authored:new[]{new Vector3D(0,0,1),new Vector3D(0,1,0),new Vector3D(1,0,0)}.OrderBy(x=>Math.Abs(x.Dot(z.ToVector()))).First();+ var projected=hint-z.ToVector()*hint.Dot(z.ToVector()); if(!Direction3D.TryCreate(projected,out var y)){d.Add($"structural-member-orientation-parallel:{member}");return null;} var x=Direction3D.Create(y.ToVector().Cross(z.ToVector())); y=Direction3D.Create(z.ToVector().Cross(x.ToVector()));return(x,y);+ }+ private static bool TryEndpoint(string text,out string member,out StructuralEnd end){var parts=text.Split('.',StringSplitOptions.TrimEntries);member=parts.ElementAtOrDefault(0)??"";end=default;return parts.Length==2&&Enum.TryParse(parts[1],out end);}+ private static string Field(string body,string name,bool required=true){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[^;\r\n]+)\s*;",RegexOptions.CultureInvariant);return m.Success?m.Groups["v"].Value.Trim():required?"":"";}+ private static double LengthField(string body,string name,List<string>d,string owner)=>ParseLength(Field(body,name),d,owner+"."+name);+ private static double ParseLength(string value,List<string>d,string owner){var m=Regex.Match(value,@"^(?<n>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*mm$",RegexOptions.CultureInvariant);if(!m.Success||!double.TryParse(m.Groups["n"].Value,NumberStyles.Float,CultureInfo.InvariantCulture,out var n)){d.Add($"structural-length-invalid:{owner}: '{value}'");return 0;}return n;}+ private static Vector3D Orientation(string value,List<string>d,string owner)=>value.Trim().Trim('"') switch{"" or "Auto"=>Vector3D.Zero,"UpX"=>new(1,0,0),"UpY"=>new(0,1,0),"UpZ"=>new(0,0,1),var raw=>Vector(raw.Trim('[',']'),d,"orientation:"+owner)};+ private static Vector3D Vector(string value,List<string>d,string owner){var parts=value.Split(',',StringSplitOptions.TrimEntries);if(parts.Length!=3||parts.Any(x=>!TryScalar(x,out _))){d.Add($"structural-vector-invalid:{owner}: '{value}'");return Vector3D.Zero;}return new(Scalar(parts[0]),Scalar(parts[1]),Scalar(parts[2]));}+ private static bool TryScalar(string expression,out double value)+ {+ value=0;var normalized=expression.Replace("mm",string.Empty,StringComparison.Ordinal).Trim();var tokens=Regex.Split(normalized,@"\s*([*/])\s*",RegexOptions.CultureInvariant).Where(x=>x.Length>0).ToArray();if(tokens.Length==0||!double.TryParse(tokens[0],NumberStyles.Float,CultureInfo.InvariantCulture,out value))return false;for(var i=1;i+1<tokens.Length;i+=2){if(!double.TryParse(tokens[i+1],NumberStyles.Float,CultureInfo.InvariantCulture,out var operand))return false;if(tokens[i]=="*")value*=operand;else if(tokens[i]=="/"&&Math.Abs(operand)>Tol)value/=operand;else return false;}return tokens.Length%2==1&&double.IsFinite(value);+ }+ private static double Scalar(string expression){TryScalar(expression,out var value);return value;}+ private static Point3D Point(Vector3D v)=>new(v.X,v.Y,v.Z);+ private static void Duplicates(IEnumerable<string> values,string kind,List<string>d){foreach(var g in values.GroupBy(x=>x,StringComparer.Ordinal).Where(x=>x.Count()>1))d.Add($"structural-duplicate-{kind}:{g.Key}");}+ private static long Q(double x)=>(long)Math.Round(x*1_000_000,MidpointRounding.AwayFromZero);+ private readonly record struct Block(string Name,string Body);+ private static string Cell(IReadOnlyDictionary<string,string> row,string name,bool required=true)=>row.TryGetValue(name,out var value)?value.Trim().Trim('"'):required?"":"";+ private static IReadOnlyList<IReadOnlyDictionary<string,string>> TableRows(string source,string rowType,List<string>d)+ {+ var rows=new List<IReadOnlyDictionary<string,string>>();var pattern=$@"\bStatic\s+Table\s+(?<name>[A-Za-z_]\w*)\s*:\s*{Regex.Escape(rowType)}(?:\s+Key\s*:\s*[A-Za-z_]\w*)?\s*\{{";+ foreach(Match match in Regex.Matches(source,pattern,RegexOptions.CultureInvariant)){var open=match.Index+match.Length-1;var close=Matching(source,open,'{','}');if(close<0){d.Add($"structural-table-malformed:{match.Groups["name"].Value}");continue;}var body=source[(open+1)..close];var columns=new Dictionary<string,string[]>(StringComparer.Ordinal);foreach(Match column in Regex.Matches(body,@"\b(?<name>[A-Za-z_]\w*)\s*:\s*\[",RegexOptions.CultureInvariant)){var arrayOpen=column.Index+column.Length-1;var arrayClose=Matching(body,arrayOpen,'[',']');if(arrayClose<0)continue;var values=body[(arrayOpen+1)..arrayClose].Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);columns[column.Groups["name"].Value]=values;}var lengths=columns.Values.Select(x=>x.Length).Distinct().ToArray();if(lengths.Length!=1){d.Add($"structural-table-unequal-column-length:{match.Groups["name"].Value}");continue;}for(var i=0;i<lengths[0];i++)rows.Add(columns.ToDictionary(x=>x.Key,x=>x.Value[i],StringComparer.Ordinal));}+ return rows;+ }+ private static int Matching(string source,int open,char opening,char closing){var depth=0;for(var i=open;i<source.Length;i++){if(source[i]==opening)depth++;else if(source[i]==closing&&--depth==0)return i;}return-1;}+ private static IReadOnlyList<Block> Blocks(string source,string keyword)+ {+ var result=new List<Block>();foreach(Match m in Regex.Matches(source,$@"\b{keyword}\s+(?<n>[A-Za-z_]\w*)\s*\{{",RegexOptions.CultureInvariant)){var open=m.Index+m.Length-1;var depth=0;var close=-1;for(var i=open;i<source.Length;i++){if(source[i]=='{')depth++;else if(source[i]=='}'&&--depth==0){close=i;break;}}if(close>open)result.Add(new(m.Groups["n"].Value,source[(open+1)..close]));}return result;+ }+}++internal static class StructuralMemberBrepEmitter+{+ public static KernelResult<BrepBody> Emit(string memberName, StructuralSectionAir section, Point3D origin, Direction3D x, Direction3D y, Direction3D z, StructuralEndPlane start, StructuralEndPlane end)+ {+ if(section.Kind is StructuralSectionKind.RoundTube or StructuralSectionKind.RoundBar)+ {+ if(Math.Abs(start.XCoefficient)>1e-12||Math.Abs(start.YCoefficient)>1e-12||Math.Abs(end.XCoefficient)>1e-12||Math.Abs(end.YCoefficient)>1e-12)+ return Fail("structural-miter-round-section-unsupported: X2 admits miter geometry for polygonal sections only");+ var profileLoops = new List<LineArcProfileLoop2D> { new([new LineArcFullCircle2D((0,0), section.Width/2)], false) };+ if (section.Kind == StructuralSectionKind.RoundTube) profileLoops.Add(new([new LineArcFullCircle2D((0,0), section.Width/2-section.Thickness)], true));+ var frame = new ConstructionPlane("structural-frame", "member-orientation", origin, x, y, z, "structural-air", "explicit-member-frame");+ var plan = ProfileExtrusionBRepPlanner.TryPlan(new(profileLoops, end.CenterDepth-start.CenterDepth, frame, start.CenterDepth, end.CenterDepth));+ if (!plan.Succeeded || plan.Plan is null) return Fail("structural-round-section-plan-failed: " + string.Join("; ", plan.Diagnostics));+ var materialized = ProfileExtrusionBRepMaterializer.TryMaterialize(plan.Plan);+ return materialized.Succeeded && materialized.Body is not null ? KernelResult<BrepBody>.Success(materialized.Body) : Fail("structural-round-section-materialization-failed: " + string.Join("; ", materialized.Diagnostics));+ }+ var loops=Loops(section); var b=new TopologyBuilder();var geometry=new BrepGeometryStore();var bindings=new BrepBindingModel();var points=new Dictionary<VertexId,Point3D>();+ var rings=new List<(VertexId[] S,VertexId[] E,EdgeId[] SE,EdgeId[] EE,EdgeId[] Span,bool Hole)>();+ foreach(var loop in loops)+ {+ var sv=new VertexId[loop.Points.Count];var ev=new VertexId[loop.Points.Count];var se=new EdgeId[loop.Points.Count];var ee=new EdgeId[loop.Points.Count];var span=new EdgeId[loop.Points.Count];+ for(var i=0;i<loop.Points.Count;i++){sv[i]=b.AddVertex();ev[i]=b.AddVertex();var p=loop.Points[i];points[sv[i]]=World(p,start.CenterDepth+start.XCoefficient*p.X+start.YCoefficient*p.Y);points[ev[i]]=World(p,end.CenterDepth+end.XCoefficient*p.X+end.YCoefficient*p.Y);}+ for(var i=0;i<loop.Points.Count;i++){var n=(i+1)%loop.Points.Count;se[i]=b.AddEdge(sv[i],sv[n]);ee[i]=b.AddEdge(ev[i],ev[n]);span[i]=b.AddEdge(sv[i],ev[i]);}+ rings.Add((sv,ev,se,ee,span,loop.Hole));+ }+ var faces=new List<FaceId>();+ var startLoops=rings.Select(r=>AddLoop(b,r.SE.Select(Use.F).ToArray())).ToArray();var endLoops=rings.Select(r=>AddLoop(b,r.EE.Select(Use.R).ToArray())).ToArray();+ faces.Add(b.AddFace(startLoops));faces.Add(b.AddFace(endLoops));+ foreach(var ring in rings)for(var i=0;i<ring.SE.Length;i++){var n=(i+1)%ring.SE.Length;faces.Add(AddFace(b,[Use.F(ring.SE[i]),Use.F(ring.Span[n]),Use.R(ring.EE[i]),Use.R(ring.Span[i])]));}+ var shell=b.AddShell(faces);b.AddBody([shell]);+ var curve=1;foreach(var edge in b.Model.Edges.OrderBy(e=>e.Id.Value)){var a=points[edge.StartVertexId];var e=points[edge.EndVertexId];var cid=new CurveGeometryId(curve++);geometry.AddCurve(cid,CurveGeometry.FromLine(new Line3Curve(a,Direction3D.Create(e-a))));bindings.AddEdgeBinding(new(edge.Id,cid,new ParameterInterval(0,(e-a).Length)));}+ var surface=1;BindPlane(faces[0],points[rings[0].S[0]],-z.ToVector()+x.ToVector()*start.XCoefficient+y.ToVector()*start.YCoefficient,x.ToVector());BindPlane(faces[1],points[rings[0].E[0]],z.ToVector()-x.ToVector()*end.XCoefficient-y.ToVector()*end.YCoefficient,x.ToVector());+ var fi=2;foreach(var ring in rings)for(var i=0;i<ring.SE.Length;i++){var n=(i+1)%ring.SE.Length;var a=points[ring.S[i]];var edge=points[ring.S[n]]-a;var longitudinal=points[ring.E[i]]-a;var normal=edge.Cross(longitudinal);if(ring.Hole)normal=-normal;BindPlane(faces[fi++],a,normal,edge);}+ var body=new BrepBody(b.Model,geometry,bindings,points);+ var capDiagnostics=ValidateCapSupportPlanes(memberName,body);+ if(capDiagnostics.Count>0)return KernelResult<BrepBody>.Failure(capDiagnostics.Select(message=>new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,message,"StructuralMemberBrepEmitter")).ToArray());+ var validation=BrepBindingValidator.Validate(body,true);return validation.IsSuccess?KernelResult<BrepBody>.Success(body):KernelResult<BrepBody>.Failure(validation.Diagnostics);+ Point3D World((double X,double Y)p,double depth)=>origin+x.ToVector()*p.X+y.ToVector()*p.Y+z.ToVector()*depth;+ void BindPlane(FaceId face,Point3D o,Vector3D normal,Vector3D u){var sid=new SurfaceGeometryId(surface++);geometry.AddSurface(sid,SurfaceGeometry.FromPlane(new PlaneSurface(o,Direction3D.Create(normal),Direction3D.Create(u))));bindings.AddFaceBinding(new(face,sid));}+ }++ internal static IReadOnlyList<string> ValidateCapSupportPlanes(string memberName, BrepBody body)+ {+ var diagnostics = new List<string>();+ var caps = body.Topology.Faces.OrderBy(face => face.Id.Value).Take(2).ToArray();+ for (var index = 0; index < caps.Length; index++)+ {+ var cap = caps[index];+ if (!body.TryGetFaceSurfaceGeometry(cap.Id, out var surface) || surface?.Plane is not PlaneSurface plane)+ continue;++ var maximumDeviation = cap.LoopIds+ .SelectMany(loopId => body.Topology.GetLoop(loopId).CoedgeIds)+ .Select(coedgeId => body.Topology.GetCoedge(coedgeId))+ .Select(coedge => body.Topology.GetEdge(coedge.EdgeId))+ .SelectMany(edge => new[] { edge.StartVertexId, edge.EndVertexId })+ .Distinct()+ .Select(vertexId => body.TryGetVertexPoint(vertexId, out var point)+ ? Math.Abs((point - plane.Origin).Dot(plane.Normal.ToVector()))+ : double.PositiveInfinity)+ .DefaultIfEmpty(double.PositiveInfinity)+ .Max();+ if (maximumDeviation <= 1e-7)+ continue;++ var end = index == 0 ? "Start" : "End";+ var bindingFormula = index == 0+ ? "normal = -Z + X*Start.XCoefficient + Y*Start.YCoefficient"+ : "normal = +Z - X*End.XCoefficient - Y*End.YCoefficient";+ var deviation = maximumDeviation.ToString("G9", CultureInfo.InvariantCulture);+ diagnostics.Add(+ $"structural-member-cap-support-plane-mismatch:{memberName}:{end}: cap loop is {deviation} mm off its bound PlaneSurface. " ++ "STEP resolves vertices from incident support planes; exporting this body can turn mirror-opposed picture-frame miters into a parallelogram. " ++ $"Bind the cap with `{bindingFormula}` and keep every cap-loop vertex on that plane.");+ }+ return diagnostics;+ }+ private static IReadOnlyList<(IReadOnlyList<(double X,double Y)> Points,bool Hole)> Loops(StructuralSectionAir s)+ {+ static (double,double)[] Rect(double w,double h)=>[(-w/2,-h/2),(w/2,-h/2),(w/2,h/2),(-w/2,h/2)];+ if(s.Kind is StructuralSectionKind.SquareTube or StructuralSectionKind.RectangularTube)return[(Rect(s.Width,s.Height),false),(Rect(s.Width-2*s.Thickness,s.Height-2*s.Thickness).Reverse().ToArray(),true)];+ if(s.Kind==StructuralSectionKind.Angle)return[([( -s.Width/2,-s.Height/2),(s.Width/2,-s.Height/2),(s.Width/2,-s.Height/2+s.Thickness),(-s.Width/2+s.Thickness,-s.Height/2+s.Thickness),(-s.Width/2+s.Thickness,s.Height/2),(-s.Width/2,s.Height/2)],false)];+ if(s.Kind==StructuralSectionKind.FlatBar)return[(Rect(s.Width,s.Height),false)];+ var n=32;var outer=Enumerable.Range(0,n).Select(i=>(s.Width/2*Math.Cos(2*Math.PI*i/n),s.Width/2*Math.Sin(2*Math.PI*i/n))).ToArray();if(s.Kind==StructuralSectionKind.RoundBar)return[(outer,false)];var inner=Enumerable.Range(0,n).Reverse().Select(i=>((s.Width/2-s.Thickness)*Math.Cos(2*Math.PI*i/n),(s.Width/2-s.Thickness)*Math.Sin(2*Math.PI*i/n))).ToArray();return[(outer,false),(inner,true)];+ }+ private static LoopId AddLoop(TopologyBuilder b,IReadOnlyList<Use> uses){var loop=b.AllocateLoopId();var ids=uses.Select(_=>b.AllocateCoedgeId()).ToArray();for(var i=0;i<ids.Length;i++)b.AddCoedge(new(ids[i],uses[i].Edge,loop,ids[(i+1)%ids.Length],ids[(i+ids.Length-1)%ids.Length],uses[i].Reverse));b.AddLoop(new Loop(loop,ids));return loop;}+ private static FaceId AddFace(TopologyBuilder b,IReadOnlyList<Use> uses)=>b.AddFace([AddLoop(b,uses)]);+ private readonly record struct Use(EdgeId Edge,bool Reverse){public static Use F(EdgeId e)=>new(e,false);public static Use R(EdgeId e)=>new(e,true);}+ private static KernelResult<BrepBody> Fail(string message)=>KernelResult<BrepBody>.Failure([new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,message,"StructuralMemberBrepEmitter")]);+}diff --git a/Aetheris.Kernel.Firmament/Structural/StructuralJointPathingPolicy.cs b/Aetheris.Kernel.Firmament/Structural/StructuralJointPathingPolicy.csnew file mode 100644index 00000000..05c06ac5--- /dev/null+++ b/Aetheris.Kernel.Firmament/Structural/StructuralJointPathingPolicy.cs@@ -0,0 +1,75 @@+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Firmament.Structural;++public sealed record StructuralMiterPathingContext(Vector3D FirstAway, Vector3D SecondAway);++public sealed record StructuralMiterPathingPolicyResult(+ bool IsSuccess, string? SelectedStrategy, Vector3D PlaneNormal, double UtilityScore,+ bool RetainedHalfSpacesOpposed, IReadOnlyList<string> RejectedCandidates);++/// <summary>+/// Bounded strategy chooser for a two-member miter. Candidate selection is+/// explicit because the two angle bisectors have different material-side+/// semantics even though both pass through the same centerline node.+/// </summary>+public static class StructuralJointPathingPolicy+{+ private const double Tolerance = 1e-9;+ private const string Separating = "SeparatingAngleBisector";+ private const string Reflex = "ReflexAngleBisector";++ public static StructuralMiterPathingPolicyResult SelectMiter(StructuralMiterPathingContext context)+ {+ var candidates = Candidates();+ var judgment = new JudgmentEngine<StructuralMiterPathingContext>().Evaluate(context, candidates);+ var rejected = candidates.Where(candidate => !candidate.IsAdmissible(context))+ .Select(candidate => $"{candidate.Name}:{candidate.RejectionReason?.Invoke(context) ?? "candidate predicates were not satisfied"}")+ .ToArray();+ if (!judgment.IsSuccess || !judgment.Selection.HasValue)+ return new(false, null, default, double.NegativeInfinity, false, rejected);++ var selection = judgment.Selection.Value;+ var normal = selection.Candidate.Name switch+ {+ Separating => context.FirstAway - context.SecondAway,+ Reflex => context.FirstAway + context.SecondAway,+ _ => default+ };+ return new(true, selection.Candidate.Name, normal, selection.Score, OpposesMaterial(context, normal), rejected);+ }++ private static IReadOnlyList<JudgmentCandidate<StructuralMiterPathingContext>> Candidates() =>+ [+ new(Separating,+ IsAdmissible: context => IsFiniteNondegenerate(context.FirstAway - context.SecondAway)+ && OpposesMaterial(context, context.FirstAway - context.SecondAway),+ Score: context => 200d + BalanceScore(context, context.FirstAway - context.SecondAway),+ RejectionReason: _ => "requires a finite bisector that places the two retained member rays in opposite open half-spaces",+ TieBreakerPriority: 0),+ new(Reflex,+ IsAdmissible: context => IsFiniteNondegenerate(context.FirstAway + context.SecondAway)+ && OpposesMaterial(context, context.FirstAway + context.SecondAway),+ Score: context => 100d + BalanceScore(context, context.FirstAway + context.SecondAway),+ RejectionReason: _ => "reflex bisector leaves both retained member rays on the same side and would admit volumetric overlap",+ TieBreakerPriority: 1)+ ];++ private static bool OpposesMaterial(StructuralMiterPathingContext context, Vector3D normal)+ {+ if (!IsFiniteNondegenerate(normal)) return false;+ var first = normal.Dot(context.FirstAway);+ var second = normal.Dot(context.SecondAway);+ return first * second < -Tolerance;+ }++ private static double BalanceScore(StructuralMiterPathingContext context, Vector3D normal)+ {+ var unit = normal / normal.Length;+ return 1d - Math.Abs(Math.Abs(unit.Dot(context.FirstAway)) - Math.Abs(unit.Dot(context.SecondAway)));+ }++ private static bool IsFiniteNondegenerate(Vector3D value) =>+ double.IsFinite(value.X) && double.IsFinite(value.Y) && double.IsFinite(value.Z) && value.Length > Tolerance;+}diff --git a/docs/public/README.md b/docs/public/README.mdindex 2d74e343..b8fee422 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -4,7 +4,7 @@ This directory is the only authoritative in-repository guide to behavior shippedStart with [Getting Started](getting-started.md), then use these guides:-- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [Circular Sweep](firmament/sweep.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)+- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [Circular Sweep](firmament/sweep.md), [Structural members and weldments](firmament/structural.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)- Interoperability: [Forge Host Protocol v1](forge/interop.md)- Inspection: [Cadmata](cadmata/overview.md) and [Cadmata PMI](cadmata/pmi.md)diff --git a/docs/public/firmament/overview.md b/docs/public/firmament/overview.mdindex a687ce42..65378a26 100644--- a/docs/public/firmament/overview.md+++ b/docs/public/firmament/overview.md@@ -8,4 +8,4 @@ Units are part of values and types. Lengths such as `8mm`, forces such as `500N`Named semantic features survive beyond geometry construction. Supported PMI is emitted as AP242 product-definition semantics; feature and topology correspondence is available to inspection consumers such as Cadmata. Presentation orientation is not authoritative engineering state.-Canonical authoring is Firmament V2. V1 and JSON-shaped `.firmasm` exist only as explicitly identified compatibility inputs. See [syntax](syntax.md), [targets](../reference/targets.md), and the [support matrix](../reference/supported-features.md).+Canonical authoring is Firmament V2. V1 and JSON-shaped `.firmasm` exist only as explicitly identified compatibility inputs. See [syntax](syntax.md), [structural members and weldments](structural.md), [targets](../reference/targets.md), and the [support matrix](../reference/supported-features.md).diff --git a/docs/public/firmament/structural.md b/docs/public/firmament/structural.mdnew file mode 100644index 00000000..bcd11b89--- /dev/null+++ b/docs/public/firmament/structural.md@@ -0,0 +1,128 @@+# Structural members and weldments++Aetheris X2 authors a weldment as a semantic structure, not as a Boolean union of intersecting solids:++```text+Structure → Member AIR → Joint resolution → Assembly Interfaces → finished members → AP242 Assembly + Cut List+```++The bounded X2 workflow supports explicit 3D nodes, straight paths, constant structural sections, member orientation, catalog material resolution, two-member butt and polygonal miter joints, fillet-weld requirements, and deterministic JSON cut lists. Curved members, tube coping, three-member miters, connection design, weld sizing, and structural FEA are future work.++## 1. Author the structure graph++Nodes are structurally meaningful locations. Paths retain stable identity, endpoints, direction, length, and source provenance.++```firmament+Structure Corner {+ Node A = [0mm, 0mm, 0mm];+ Node B = [600mm, 0mm, 0mm];+ Node C = [600mm, 400mm, 0mm];+ Path Horizontal: A -> B;+ Path Vertical: B -> C;+}+```++X2 paths are straight segments and every path has exactly one Member assignment.++## 2. Define sections and members++Section geometry and material identity are separate. X2 admits `Standard.Structural.SquareTube`, `RectangularTube`, `RoundTube`, `Angle`, `FlatBar`, and `RoundBar`.++Tube sections are genuinely hollow. Square/rectangular tube fields are `Width`, optional `Height`, and `Thickness`; round sections use `Diameter`; angles use `Width`, `Height`, and `Thickness`.++```firmament+Section RHS {+ Kind: Standard.Structural.SquareTube;+ Width: 40mm;+ Thickness: 3mm;+}++Member Horizontal {+ Path: Horizontal;+ Section: RHS;+ Material: Standard.Materials.Steel.ASTM_A36;+ Orientation: [0,0,1];+}+```++`Orientation` is a reference vector projected perpendicular to the member axis. It is mandatory for asymmetric `Angle` sections. `Auto` is deterministic for symmetric sections.++### Columnar graph tables++For frames with many edges, use the existing first-class `Record` + `Static Table` mechanism instead of repeating blocks. Structural table rows normalize to exactly the same Member AIR:++```firmament+Record StructuralMemberRow { Name: String Path: String Section: String Material: String Orientation: String }+Static Table Members: StructuralMemberRow Key: Name {+ Name: ["Top", "Bottom", "Left", "Right"]+ Path: ["TopPath", "BottomPath", "LeftPath", "RightPath"]+ Section: ["RHS", "RHS", "RHS", "RHS"]+ Material: ["Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36"]+ Orientation: ["UpZ", "UpZ", "UpZ", "UpZ"]+}+```++`StructuralJointRow` columns are `Name`, `Type`, `FirstMember`, `FirstEnd`, `SecondMember`, `SecondEnd`, and `Primary`. End values are `Start` or `End`; `Type` is `Butt` or `Miter`. `Primary` names the through member for a butt joint. The column is still required for a miter row because Static Tables have one fixed schema, but its value is ignored. `StructuralWeldRow` columns are `Name`, `Joint`, `Type`, and `Size`; X2 weld type is `Fillet`.++```firmament+Record StructuralJointRow { Name: String Type: String FirstMember: String FirstEnd: String SecondMember: String SecondEnd: String Primary: String }+Static Table Joints: StructuralJointRow Key: Name {+ Name: ["TopLeft"]+ Type: ["Butt"]+ FirstMember: ["Top"]+ FirstEnd: ["Start"]+ SecondMember: ["Left"]+ SecondEnd: ["End"]+ Primary: ["Top"]+}++Record StructuralWeldRow { Name: String Joint: String Type: String Size: Length }+Static Table Welds: StructuralWeldRow Key: Name {+ Name: ["TopLeftWeld"]+ Joint: ["TopLeft"]+ Type: ["Fillet"]+ Size: [4mm]+}+```++Column cardinality is checked and source order does not control identity, joint ownership, grouping, or output ordering. Explicit `Member`/`Joint`/`Weld` blocks remain useful for small examples and may coexist with table rows when identities do not collide. Prefer identity names that describe location rather than treatment (`TopLeft`, not `TopLeftButt`) so a later joint-type change does not make the identity misleading.++Path dimensions describe member centerlines. Section material extends around those centerlines, so a 1000 mm by 600 mm rectangular path loop made from 40 mm tube has 1040 mm by 640 mm outside bounds. The cut list preserves both raw path length and finished length: a nominal 800 mm leg trimmed beneath a 40 mm top rail has a 780 mm finished cut.++## 3. Resolve joints, then weld requirements++A Joint changes member end geometry and lowers an explicit interface between two member occurrences. A Weld records a fabrication requirement against that interface; it does not create a bead solid.++```firmament+Joint CornerMiter { Members: [Horizontal.End, Vertical.Start]; Type: Miter; }+Weld CornerWeld { Joint: CornerMiter; Type: Fillet; Size: 4mm; }+```++`Miter` supports two non-collinear polygonal members. Joint pathing is selected through `JudgmentEngine`: the separating and reflex angle-bisector candidates publish admissibility, utility score, deterministic tie-breaking, and rejection reasons. The reflex candidate is rejected when both retained member rays would occupy the same half-space. Both independently materialized member end loops must coincide on the selected interface or compilation fails. A `Butt` joint identifies the through member explicitly:++For a closed rectangular picture frame, the two cuts on each rail have opposite handedness. Its top/plan outline is therefore an isosceles trapezoid, not a parallelogram. Export qualification checks that the cap loops lie on both the declared joint-interface planes and their bound B-rep `PlaneSurface` supports, then checks that this trapezoidal profile survives AP242 reimport. A support mismatch fails before export with `structural-member-cap-support-plane-mismatch:<member>:<end>`; the diagnostic names the corrective binding formula because STEP reconstructs vertices from incident support planes and can otherwise turn correct topology points into a parallelogram.++```firmament+Joint TeeButt {+ Members: [Through.Start, Terminating.End];+ Type: Butt;+ Primary: Through;+}+```++The terminating member is trimmed to the primary envelope. Unsupported round-section miters, collinear joints, disconnected references, and repeated geometry-owning end treatments fail explicitly.++## 4. Inspect fabrication output++```powershell+aetheris inspect fixtures/Canonical/Structural/welded-workbench.firmament --json+aetheris build fixtures/Canonical/Structural/welded-workbench.firmament --output artifacts/local/x2/x2-welded-workbench.step --json+```++Build emits an AP242 occurrence assembly and sibling `*.cutlist.json`. Members remain independent definitions and occurrences; the structural report exposes the assembly plus every joint interface. Miter interfaces include their shared plane, selected Judgment strategy and utility, rejected candidates, and a checked `matingSurfacesCoincident` result. Every admitted butt or miter contact also verifies that the complete member vertex sets occupy opposite retained half-spaces; `volumetricOverlapMm3` is reported as zero only when that proof succeeds. The report also contains nodes, paths, sections, materials, members, joints, welds, cut-list groups, mass, bounds, analytic surface families, reimport status, and stage timings. Grouping compares section, material, raw/finished length, and fabrication treatment—not length alone.++Copy [the welded workbench fixture](../../../fixtures/Canonical/Structural/welded-workbench.firmament) for a complete example. Smaller examples live beside it in `fixtures/Canonical/Structural/`.++### Template-generated graph tables++For policy-level authoring, invoke `Standard.Structural.WeldedWorkbench` through Forge Protocol v1. Its typed `WeldedWorkbenchPolicy` exposes width, depth, height, tube size, wall thickness, and material. The Template generates the skeleton plus columnar Member/Joint/Weld tables; downstream AIR and fabrication behavior are identical to explicit tables. Forge `list`, `describe`, and `invoke` require no structural-specific RPC and can return both `StepAp242` and `CutListJson`.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 28c4ccca..316e92e5 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -7,6 +7,7 @@| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition || Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring || Circular Sweep | Bounded (X0) | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep |+| Structural / weldment | Bounded (X2) | Explicit 3D nodes and straight paths; identifiable members; square/rectangular/round tube, angle, flat/round bar; orientation; catalog material; two-member butt and polygonal miter joints; semantic fillet welds; AP242 member assembly and deterministic JSON Cut List. No coping, curved routing, multi-member miter, connection design, weld analysis, or structural FEA. See [guide](../firmament/structural.md). || Boss | Bounded | First-class connected finite `On: Top` profile addition on an admitted Compose host; positive height; lowers through existing `Add`; no arbitrary solid union || Pocket | Bounded | First-class enclosed finite-depth `On: Top` profile removal; positive depth, non-through termination, and minimum remaining floor enforced; lowers through existing `Remove` || Lower-level profile composition | Bounded | Existing prismatic `Compose` `Add`/`Remove` remains compatible for bounded blockout authoring |diff --git a/docs/public/standard-library/README.md b/docs/public/standard-library/README.mdindex 11693ed2..6d096604 100644--- a/docs/public/standard-library/README.md+++ b/docs/public/standard-library/README.md@@ -12,9 +12,10 @@ The Standard Library is a shipped, curated catalog of typed Firmament product fa| Flanged Adapter | `Standard.Products.Mechanical.FlangedAdapter` | circular flange, 4/6/8-hole semantic Pattern, bore PMI || Rack Panel | `Standard.Products.Electronics.RackPanel` | planar stock, symmetric mounting holes || Standoff | `Standard.Products.Mechanical.Standoff` | circular spacer, clearance bore |+| Welded Workbench | `Standard.Structural.WeldedWorkbench` | structure graph, generated Member/Joint/Weld tables, AP242 assembly, Cut List JSON || Electronics Enclosure | `Standard.SheetMetal.ElectronicsEnclosure` | Sheet Metal, DFM, formed STEP, flat STEP, SVG |-The namespace taxonomy is intentionally shallow: `Standard.Products.Mechanical`, `.Electronics`, and `.Office` identify ordinary products; the existing `Standard.SheetMetal` namespace remains stable for manufacturing Templates.+The namespace taxonomy is intentionally shallow: `Standard.Products.Mechanical`, `.Electronics`, and `.Office` identify ordinary products; `Standard.Structural` owns structure-first weldments; the existing `Standard.SheetMetal` namespace remains stable for manufacturing Templates.## Invoke a familydiff --git a/docs/release/X2-STRUCTURAL-WELDMENT.md b/docs/release/X2-STRUCTURAL-WELDMENT.mdnew file mode 100644index 00000000..e45d952f--- /dev/null+++ b/docs/release/X2-STRUCTURAL-WELDMENT.md@@ -0,0 +1,56 @@+# X2 — Structural / weldment foundation++## Executive verdict++**Accepted.** Aetheris represents the bounded X2 structural/weldment foundation semantically from skeleton through fabrication output. The flagship workbench completes the real parser → AIR → joint → BRep → AP242 assembly → reimport/Cut List path. Forge Protocol template invocation and independent fresh-agent A/B/C authoring both pass through their packaged, public paths.++## Semantic architecture++```text+Structure nodes/paths+→ StructuralMemberAir (path + section + material + orientation + end interfaces)+→ deterministic Butt/Miter joint resolution+→ explicit assembly joint interfaces+→ per-member end planes and treatments+→ exact enclosed member BReps+→ AP242 product definitions and occurrences+→ Cut List IR and JSON+```++Profile geometry is materialized only after joint resolution. Assembly semantics were audited and reused for AP242 product identity; the general mate solver was not stretched into a fabrication cut solver.++## Sections and joints++X2 admits SquareTube, RectangularTube, RoundTube, Angle, FlatBar, and RoundBar. Material is resolved independently through the existing catalog. Tubes retain true inner walls; round square-cut tubes use analytic cylinders. Polygonal two-member miter joints route through a bounded JudgmentEngine policy. The separating and reflex bisectors have explicit admissibility, utility, tie-breaking, and rejection evidence; the same-side reflex candidate is rejected as overlap-producing. The compiler compares independently materialized end-loop point sets and proves the complete participant vertex sets remain in opposite retained half-spaces. Butt contacts receive the same post-materialization half-space proof. Butt joints identify a through/Primary member and trim the terminating member to its envelope. Round-section miters, collinear joints, multi-member miters, coping, and arbitrary profile intersections reject explicitly.++## Fabrication outputs++The canonical build emits an AP242 assembly of independent member definitions plus deterministic Cut List JSON. Weld requirements retain weld, joint, type, size, and member identity without pretending to supply bead geometry or AWS compliance. CLI `inspect`, `validate`, and `build --json` expose structural records directly. Member/Joint/Weld graphs can be authored as checked columnar `Static Table` data, and the Standard Structural workbench Template generates those tables from six policy fields before the same AIR lowering.++## Workbench evidence++Final source: `fixtures/Canonical/Structural/welded-workbench.firmament`.++- 10 members, 12 joints, 12 semantic fillet welds+- four cut-list groups: two 1000 mm miter rails, two 600 mm miter rails, two 560 mm crossmembers trimmed both ends, four 780 mm legs+- 40 × 40 × 3 mm square tube, `Standard.Materials.Steel.ASTM_A36`+- overall BRep bounds: `[-20,-20,0]` to `[1020,620,820]` mm+- 10 enclosed member bodies, 100 analytic planar faces+- AP242 assembly reimport: 10 geometric definitions and 10 occurrences+- nominal assembly mass: approximately 25.93 kg++The final manual artifact is `artifacts/local/x2/final/x2-welded-workbench.step`, SHA-256 `d401a4bf453835d79140bbc19116de5942313343ab886c4c7532b851d228ed88`. It contains 10 independent definitions and occurrences plus 12 reported joint interfaces; all four miter interfaces have coincident shared cut surfaces. Picture-frame rails retain mirror-opposed cuts and reimport as isosceles trapezoids rather than parallelograms. Its sibling Cut List is `artifacts/local/x2/final/x2-welded-workbench.cutlist.json`. Independent repeat builds produced byte-identical STEP output.++## Qualification and locality++Canonical member, orientation, butt, miter, frame, and workbench fixtures are present. Seven invalid fixtures isolate zero length, invalid dimensions, excessive wall, missing asymmetric orientation, disconnected joint, unsupported round miter, and unknown-member diagnostics. Determinism tests compare STEP text, hash, and cut-list JSON. A deliberately malformed cap binding is rejected before export with `structural-member-cap-support-plane-mismatch:<member>:<end>`; the message reports plane deviation, explains the STEP/parallelogram consequence, and supplies the correct start/end normal formula. Changing Butt/Miter treatment is localized to joint resolution and member end planes; graph, section, and material records remain unchanged.++Forge Protocol v1 lists, describes, and invokes `Standard.Structural.WeldedWorkbench`, returning AP242 and Cut List JSON without a structural-specific RPC. A published Forge Host invocation produced both artifacts successfully. A fresh agent, restricted to public docs and canonical fixtures, authored a rectangular butt-welded frame, four-legged Cut List-ready workbench, and miter variant; all three validated, built, and reimported on the literal first attempt with zero diagnostics. Its report is under `artifacts/local/x2/fresh-agent/qualification-report.md`. No piping, surfacing, weld analysis, connection design, or structural FEA scope was introduced.++## Friction and deferred work++- **MustFixX2:** none.+- **DocsFix:** resolved fresh-agent findings by documenting fixed table schemas, centerline dimensions, raw versus finished length, ignored miter `Primary`, and treatment-neutral identity naming.+- **DeferredX2a:** end caps, channel, weld PMI symbols, exploded view, generalized member-interior interface syntax.+- **FuturePiping:** routed/curved tube and fishmouth coping.+- **FutureSurfacing:** freeform multi-member intersection solving.diff --git a/fixtures/Canonical/Structural/butt-joint.firmament b/fixtures/Canonical/Structural/butt-joint.firmamentnew file mode 100644index 00000000..79fc35db--- /dev/null+++ b/fixtures/Canonical/Structural/butt-joint.firmament@@ -0,0 +1,9 @@+Model ButtJoint {+ Units: mm+ Structure Tee { Node A = [0mm,0mm,0mm]; Node B = [800mm,0mm,0mm]; Node C = [400mm,-400mm,0mm]; Node D = [400mm,0mm,0mm]; Path ThroughAxis: A -> B; Path TerminatingAxis: C -> D; }+ Section RHS { Kind: SquareTube; Width: 40mm; Thickness: 3mm; }+ Member Through { Path: ThroughAxis; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Member Terminating { Path: TerminatingAxis; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Joint TeeButt { Members: [Through.Start, Terminating.End]; Type: Butt; Primary: Through; }+ Weld TeeWeld { Joint: TeeButt; Type: Fillet; Size: 4mm; }+}diff --git a/fixtures/Canonical/Structural/miter-joint.firmament b/fixtures/Canonical/Structural/miter-joint.firmamentnew file mode 100644index 00000000..06d9bd3a--- /dev/null+++ b/fixtures/Canonical/Structural/miter-joint.firmament@@ -0,0 +1,9 @@+Model MiterJoint {+ Units: mm+ Structure Corner { Node A = [0mm,0mm,0mm]; Node B = [600mm,0mm,0mm]; Node C = [600mm,400mm,0mm]; Path Horizontal: A -> B; Path Vertical: B -> C; }+ Section RHS { Kind: SquareTube; Width: 40mm; Thickness: 3mm; }+ Member Horizontal { Path: Horizontal; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Member Vertical { Path: Vertical; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Joint CornerMiter { Members: [Horizontal.End, Vertical.Start]; Type: Miter; }+ Weld CornerWeld { Joint: CornerMiter; Type: Fillet; Size: 4mm; }+}diff --git a/fixtures/Canonical/Structural/oriented-angle-member.firmament b/fixtures/Canonical/Structural/oriented-angle-member.firmamentnew file mode 100644index 00000000..72b6aeda--- /dev/null+++ b/fixtures/Canonical/Structural/oriented-angle-member.firmament@@ -0,0 +1,6 @@+Model OrientedAngleMember {+ Units: mm+ Structure Brace { Node A = [0mm,0mm,0mm]; Node B = [0mm,0mm,500mm]; Path Axis: A -> B; }+ Section L40 { Kind: Angle; Width: 40mm; Height: 40mm; Thickness: 4mm; }+ Member Brace { Path: Axis; Section: L40; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [1,0,0]; }+}diff --git a/fixtures/Canonical/Structural/rectangular-tube-member.firmament b/fixtures/Canonical/Structural/rectangular-tube-member.firmamentnew file mode 100644index 00000000..4ff8c79e--- /dev/null+++ b/fixtures/Canonical/Structural/rectangular-tube-member.firmament@@ -0,0 +1,6 @@+Model RectangularTubeMember {+ Units: mm+ Structure Beam { Node A = [0mm,0mm,0mm]; Node B = [0mm,900mm,0mm]; Path Axis: A -> B; }+ Section RHS { Kind: RectangularTube; Width: 60mm; Height: 40mm; Thickness: 3mm; }+ Member Beam { Path: Axis; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+}diff --git a/fixtures/Canonical/Structural/simple-structural-frame.firmament b/fixtures/Canonical/Structural/simple-structural-frame.firmamentnew file mode 100644index 00000000..95bf4a71--- /dev/null+++ b/fixtures/Canonical/Structural/simple-structural-frame.firmament@@ -0,0 +1,13 @@+Model SimpleStructuralFrame {+ Units: mm+ Structure Frame { Node A = [0mm,0mm,0mm]; Node B = [1000mm,0mm,0mm]; Node C = [1000mm,600mm,0mm]; Node D = [0mm,600mm,0mm]; Path AB: A -> B; Path BC: B -> C; Path CD: C -> D; Path DA: D -> A; }+ Section RHS { Kind: SquareTube; Width: 40mm; Thickness: 3mm; }+ Member AB { Path: AB; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Member BC { Path: BC; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Member CD { Path: CD; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Member DA { Path: DA; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+ Joint J1 { Members: [AB.End, BC.Start]; Type: Miter; }+ Joint J2 { Members: [BC.End, CD.Start]; Type: Miter; }+ Joint J3 { Members: [CD.End, DA.Start]; Type: Miter; }+ Joint J4 { Members: [DA.End, AB.Start]; Type: Miter; }+}diff --git a/fixtures/Canonical/Structural/square-tube-member.firmament b/fixtures/Canonical/Structural/square-tube-member.firmamentnew file mode 100644index 00000000..e6de7092--- /dev/null+++ b/fixtures/Canonical/Structural/square-tube-member.firmament@@ -0,0 +1,6 @@+Model SquareTubeMember {+ Units: mm+ Structure Beam { Node A = [0mm,0mm,0mm]; Node B = [750mm,0mm,0mm]; Path Axis: A -> B; }+ Section RHS { Kind: SquareTube; Width: 40mm; Thickness: 3mm; }+ Member Beam { Path: Axis; Section: RHS; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; }+}diff --git a/fixtures/Canonical/Structural/welded-workbench.firmament b/fixtures/Canonical/Structural/welded-workbench.firmamentnew file mode 100644index 00000000..dd71c5fc--- /dev/null+++ b/fixtures/Canonical/Structural/welded-workbench.firmament@@ -0,0 +1,63 @@+Model WeldedWorkbench {+ Units: mm++ Structure WorkbenchFrame {+ Node FLL = [0mm, 0mm, 0mm];+ Node FRL = [1000mm, 0mm, 0mm];+ Node BRL = [1000mm, 600mm, 0mm];+ Node BLL = [0mm, 600mm, 0mm];+ Node FLT = [0mm, 0mm, 800mm];+ Node FRT = [1000mm, 0mm, 800mm];+ Node BRT = [1000mm, 600mm, 800mm];+ Node BLT = [0mm, 600mm, 800mm];+ Node CrossAFront = [333.333333mm, 0mm, 800mm];+ Node CrossABack = [333.333333mm, 600mm, 800mm];+ Node CrossBFront = [666.666667mm, 0mm, 800mm];+ Node CrossBBack = [666.666667mm, 600mm, 800mm];++ Path FrontRail: FLT -> FRT;+ Path RightRail: FRT -> BRT;+ Path BackRail: BRT -> BLT;+ Path LeftRail: BLT -> FLT;+ Path FrontLeftLeg: FLL -> FLT;+ Path FrontRightLeg: FRL -> FRT;+ Path BackRightLeg: BRL -> BRT;+ Path BackLeftLeg: BLL -> BLT;+ Path CrossmemberA: CrossAFront -> CrossABack;+ Path CrossmemberB: CrossBFront -> CrossBBack;+ }++ Section Tube40x40x3 {+ Kind: Standard.Structural.SquareTube;+ Width: 40mm;+ Thickness: 3mm;+ }++ Record StructuralMemberRow { Name: String Path: String Section: String Material: String Orientation: String }+ Static Table Members: StructuralMemberRow Key: Name {+ Name: ["FrontRail", "RightRail", "BackRail", "LeftRail", "FrontLeftLeg", "FrontRightLeg", "BackRightLeg", "BackLeftLeg", "CrossmemberA", "CrossmemberB"]+ Path: ["FrontRail", "RightRail", "BackRail", "LeftRail", "FrontLeftLeg", "FrontRightLeg", "BackRightLeg", "BackLeftLeg", "CrossmemberA", "CrossmemberB"]+ Section: ["Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3", "Tube40x40x3"]+ Material: ["Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36", "Standard.Materials.Steel.ASTM_A36"]+ Orientation: ["UpZ", "UpZ", "UpZ", "UpZ", "UpX", "UpX", "UpX", "UpX", "UpZ", "UpZ"]+ }++ Record StructuralJointRow { Name: String Type: String FirstMember: String FirstEnd: String SecondMember: String SecondEnd: String Primary: String }+ Static Table Joints: StructuralJointRow Key: Name {+ Name: ["FrontRightMiter", "BackRightMiter", "BackLeftMiter", "FrontLeftMiter", "FrontLeftButt", "FrontRightButt", "BackRightButt", "BackLeftButt", "CrossAFrontButt", "CrossABackButt", "CrossBFrontButt", "CrossBBackButt"]+ Type: ["Miter", "Miter", "Miter", "Miter", "Butt", "Butt", "Butt", "Butt", "Butt", "Butt", "Butt", "Butt"]+ FirstMember: ["FrontRail", "RightRail", "BackRail", "LeftRail", "FrontRail", "FrontRail", "BackRail", "BackRail", "FrontRail", "BackRail", "FrontRail", "BackRail"]+ FirstEnd: ["End", "End", "End", "End", "Start", "End", "Start", "End", "Start", "Start", "Start", "Start"]+ SecondMember: ["RightRail", "BackRail", "LeftRail", "FrontRail", "FrontLeftLeg", "FrontRightLeg", "BackRightLeg", "BackLeftLeg", "CrossmemberA", "CrossmemberA", "CrossmemberB", "CrossmemberB"]+ SecondEnd: ["Start", "Start", "Start", "Start", "End", "End", "End", "End", "Start", "End", "Start", "End"]+ Primary: ["FrontRail", "RightRail", "BackRail", "LeftRail", "FrontRail", "FrontRail", "BackRail", "BackRail", "FrontRail", "BackRail", "FrontRail", "BackRail"]+ }++ Record StructuralWeldRow { Name: String Joint: String Type: String Size: Length }+ Static Table Welds: StructuralWeldRow Key: Name {+ Name: ["W01", "W02", "W03", "W04", "W05", "W06", "W07", "W08", "W09", "W10", "W11", "W12"]+ Joint: ["FrontRightMiter", "BackRightMiter", "BackLeftMiter", "FrontLeftMiter", "FrontLeftButt", "FrontRightButt", "BackRightButt", "BackLeftButt", "CrossAFrontButt", "CrossABackButt", "CrossBFrontButt", "CrossBBackButt"]+ Type: ["Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet", "Fillet"]+ Size: [4mm, 4mm, 4mm, 4mm, 4mm, 4mm, 4mm, 4mm, 4mm, 4mm, 4mm, 4mm]+ }+}diff --git a/fixtures/Canonical/Structural/welded-workbench.forge.json b/fixtures/Canonical/Structural/welded-workbench.forge.jsonnew file mode 100644index 00000000..8e5a7abd--- /dev/null+++ b/fixtures/Canonical/Structural/welded-workbench.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"width":"1000 mm","depth":"600 mm","height":"800 mm","tubeSize":"40 mm","wallThickness":"3 mm","material":"Standard.Materials.Steel.ASTM_A36"},"artifacts":["StepAp242","CutListJson"]}diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex 1e5efd5b..f3035326 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -6,6 +6,7 @@{ "path": "FEA", "operation": "fea-solve" },{ "path": "Materials", "operation": "fea-solve" },{ "path": "SheetMetal", "operation": "sheet-metal-flatten" },+ { "path": "Structural", "operation": "build-step" },{ "path": "Basics", "operation": "build-step" },{ "path": "Primitives", "operation": "build-step" },{ "path": "Profiles", "operation": "build-step" },diff --git a/fixtures/Invalid/Structural/disconnected-joint.firmament b/fixtures/Invalid/Structural/disconnected-joint.firmamentnew file mode 100644index 00000000..a64d5c67--- /dev/null+++ b/fixtures/Invalid/Structural/disconnected-joint.firmament@@ -0,0 +1 @@+Model InvalidDisconnected { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [100mm,0mm,0mm]; Node C = [200mm,0mm,0mm]; Node D = [200mm,100mm,0mm]; Path P: A -> B; Path Q: C -> D; } Section T { Kind: SquareTube; Width: 40mm; Thickness: 3mm; } Member M1 { Path: P; Section: T; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; } Member M2 { Path: Q; Section: T; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; } Joint J { Members: [M1.End, M2.Start]; Type: Miter; } }diff --git a/fixtures/Invalid/Structural/invalid-section-dimensions.firmament b/fixtures/Invalid/Structural/invalid-section-dimensions.firmamentnew file mode 100644index 00000000..3d96448d--- /dev/null+++ b/fixtures/Invalid/Structural/invalid-section-dimensions.firmament@@ -0,0 +1 @@+Model InvalidSection { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [100mm,0mm,0mm]; Path P: A -> B; } Section Q { Kind: RectangularTube; Width: 0mm; Height: 40mm; Thickness: 3mm; } Member M { Path: P; Section: Q; Material: Standard.Materials.Steel.ASTM_A36; Orientation: Auto; } }diff --git a/fixtures/Invalid/Structural/joint-unknown-member.firmament b/fixtures/Invalid/Structural/joint-unknown-member.firmamentnew file mode 100644index 00000000..13cfce34--- /dev/null+++ b/fixtures/Invalid/Structural/joint-unknown-member.firmament@@ -0,0 +1 @@+Model InvalidUnknownMember { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [100mm,0mm,0mm]; Path P: A -> B; } Section T { Kind: SquareTube; Width: 40mm; Thickness: 3mm; } Member M1 { Path: P; Section: T; Material: Standard.Materials.Steel.ASTM_A36; Orientation: Auto; } Joint J { Members: [M1.End, Missing.Start]; Type: Butt; Primary: M1; } }diff --git a/fixtures/Invalid/Structural/missing-section-orientation.firmament b/fixtures/Invalid/Structural/missing-section-orientation.firmamentnew file mode 100644index 00000000..3b3b7d3a--- /dev/null+++ b/fixtures/Invalid/Structural/missing-section-orientation.firmament@@ -0,0 +1 @@+Model InvalidOrientation { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [100mm,0mm,0mm]; Path P: A -> B; } Section Q { Kind: Angle; Width: 40mm; Height: 40mm; Thickness: 4mm; } Member M { Path: P; Section: Q; Material: Standard.Materials.Steel.ASTM_A36; } }diff --git a/fixtures/Invalid/Structural/miter-geometry-unsupported.firmament b/fixtures/Invalid/Structural/miter-geometry-unsupported.firmamentnew file mode 100644index 00000000..1c35ce61--- /dev/null+++ b/fixtures/Invalid/Structural/miter-geometry-unsupported.firmament@@ -0,0 +1 @@+Model InvalidRoundMiter { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [100mm,0mm,0mm]; Node C = [100mm,100mm,0mm]; Path P: A -> B; Path Q: B -> C; } Section T { Kind: RoundTube; Diameter: 40mm; Thickness: 3mm; } Member M1 { Path: P; Section: T; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; } Member M2 { Path: Q; Section: T; Material: Standard.Materials.Steel.ASTM_A36; Orientation: [0,0,1]; } Joint J { Members: [M1.End, M2.Start]; Type: Miter; } }diff --git a/fixtures/Invalid/Structural/wall-thickness-too-large.firmament b/fixtures/Invalid/Structural/wall-thickness-too-large.firmamentnew file mode 100644index 00000000..b5e48837--- /dev/null+++ b/fixtures/Invalid/Structural/wall-thickness-too-large.firmament@@ -0,0 +1 @@+Model InvalidWall { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [100mm,0mm,0mm]; Path P: A -> B; } Section Q { Kind: SquareTube; Width: 40mm; Thickness: 21mm; } Member M { Path: P; Section: Q; Material: Standard.Materials.Steel.ASTM_A36; Orientation: Auto; } }diff --git a/fixtures/Invalid/Structural/zero-length-member.firmament b/fixtures/Invalid/Structural/zero-length-member.firmamentnew file mode 100644index 00000000..3042d733--- /dev/null+++ b/fixtures/Invalid/Structural/zero-length-member.firmament@@ -0,0 +1 @@+Model InvalidZeroLength { Units: mm Structure S { Node A = [0mm,0mm,0mm]; Node B = [0mm,0mm,0mm]; Path P: A -> B; } Section Q { Kind: SquareTube; Width: 40mm; Thickness: 3mm; } Member M { Path: P; Section: Q; Material: Standard.Materials.Steel.ASTM_A36; Orientation: Auto; } }diff --git a/tools/vscode-firmament/manifest.tsx b/tools/vscode-firmament/manifest.tsxindex b1dbdc07..8a766965 100644--- a/tools/vscode-firmament/manifest.tsx+++ b/tools/vscode-firmament/manifest.tsx@@ -88,7 +88,13 @@ export default define({name: "package",runtime: "node",- command: ["vsce", "package", "--no-dependencies", "--out", "dist/aetheris-firmament-0.3.0-preview.3.vsix"],+ command: [+ "vsce",+ "package",+ "--no-dependencies",+ "--out",+ "../../artifacts/local/vscode-firmament/aetheris-firmament-0.3.0-preview.3.vsix",+ ],},]}/>diff --git a/tools/vscode-firmament/package.json b/tools/vscode-firmament/package.jsonindex 8785694c..87442cf5 100644--- a/tools/vscode-firmament/package.json+++ b/tools/vscode-firmament/package.json@@ -25,7 +25,7 @@"onCommand:aetheris.verify"],"files": [- "dist/**",+ "dist/extension.cjs","syntaxes/**","snippets/**","language-configuration.json",