Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add semantic piping support to Firmament
Yuechen Lic12ec06f1655
diff --git a/.gitignore b/.gitignoreindex a7aa28ab..eb71a6df 100644--- a/.gitignore+++ b/.gitignore@@ -206,6 +206,7 @@ _TeamCity*# Coverlet is a free, cross platform Code Coverage Toolcoverage*.json+!fixtures/Canonical/coverage.jsoncoverage*.xmlcoverage*.infodiff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex b0cf06db..4c35239f 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -25,6 +25,7 @@ using Aetheris.Surfacing;using Aetheris.Geometry;using Aetheris.SheetMetal;using Aetheris.Kernel.Firmament.Structural;+using Aetheris.Kernel.Firmament.Piping;namespace Aetheris.CLI;@@ -461,6 +462,7 @@ public static class CliRunnerengineeringFeatures = build.Value.Export.EngineeringFeatures,patterns = build.Value.Export.Patterns,structural = build.Value.Export.Structural,+ piping = build.Value.Export.Piping,featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0),inlineStepMigration = build.Value.Export.InlineStepMigration,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,@@ -483,6 +485,8 @@ public static class CliRunnerstdout.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}");+ if (build.Value.Export.Piping is { } piping)+ stdout.WriteLine($"Piping system: {piping.Connections.Count} connections, {piping.Routes.Count} routes, {piping.PipeSegments.Count} pipe segments, {piping.Fittings.Count} fittings, {piping.Nozzles.Count} equipment nozzles, {piping.Mates.Count} endpoint mates; routing report: {piping.RoutingReportArtifactPath}");foreach (var diagnostic in build.Diagnostics.Where(diagnostic => diagnostic.Severity == KernelDiagnosticSeverity.Warning))stderr.WriteLine($"- [Warning] {diagnostic.Source}: {diagnostic.Message}");}@@ -991,6 +995,14 @@ Model CanonicalPanel {}var source = File.ReadAllText(fullPath);+ if (PipingAuthoring.IsPipingSource(source))+ {+ var piping = PipingAuthoring.Compile(source, fullPath);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = piping.IsSuccess, input = fullPath, domain = "Piping", piping = piping.Report, diagnostics = piping.Diagnostics }, JsonOptions));+ else if (piping.IsSuccess && piping.Report is { } pipingReport) stdout.WriteLine($"Piping system {pipingReport.PipingSystem}: {pipingReport.Connections.Count} connections, {pipingReport.Routes.Count} routes, {pipingReport.PipeSegments.Count} pipe segments, {pipingReport.Fittings.Count} fittings, {pipingReport.Nozzles.Count} equipment nozzles, {pipingReport.Mates.Count} endpoint mates");+ else foreach (var diagnostic in piping.Diagnostics) stderr.WriteLine($"error: {diagnostic}");+ return piping.IsSuccess ? 0 : 1;+ }if (StructuralAuthoring.IsStructuralSource(source)){var structural = StructuralAuthoring.Compile(source, fullPath);@@ -1635,6 +1647,14 @@ Model CanonicalPanel {}var validationSource=File.ReadAllText(sourcePath);+ if (PipingAuthoring.IsPipingSource(validationSource))+ {+ var piping = PipingAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));+ var payload = new { source = sourcePath, status = piping.IsSuccess ? "valid" : "invalid", domain = "Piping", summary = new { fatalDiagnosticCount = piping.Diagnostics.Count, warningDiagnosticCount = 0, connections = piping.Report?.Connections.Count ?? 0, routes = piping.Report?.Routes.Count ?? 0 }, diagnostics = piping.Diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));+ else stdout.WriteLine($"Firmament V2 Piping validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");+ return piping.IsSuccess ? 0 : 1;+ }if (StructuralAuthoring.IsStructuralSource(validationSource)){var structural = StructuralAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));diff --git a/Aetheris.Forge.Host.Tests/PipingForgeProtocolTests.cs b/Aetheris.Forge.Host.Tests/PipingForgeProtocolTests.csnew file mode 100644index 00000000..10fbbbea--- /dev/null+++ b/Aetheris.Forge.Host.Tests/PipingForgeProtocolTests.cs@@ -0,0 +1,25 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Forge.Host.Tests;++public sealed class PipingForgeProtocolTests+{+ [Fact]+ public void PumpSkid_ListDescribeInvoke_UsesProtocolV1AndReturnsRoutedAssembly()+ {+ const string id="Standard.Piping.PumpSkid";var host=new ForgeProtocolHost();+ Assert.Contains(host.ListTemplates().Templates,x=>x.Id==id);+ var description=Assert.IsType<ForgeTemplateDescription>(host.DescribeTemplate(id));+ Assert.Equal(4,description.Parameters.Single().Fields!.Count);Assert.Equal([ForgeArtifactKind.StepAp242],description.Artifacts);+ var args=new Dictionary<string,JsonElement>{{"outerDiameter",JsonSerializer.SerializeToElement("25 mm")},{"wallThickness",JsonSerializer.SerializeToElement("2 mm")},{"clearance",JsonSerializer.SerializeToElement("30 mm")},{"material",JsonSerializer.SerializeToElement("Standard.Materials.StainlessSteel.304_Annealed")}};+ using var output=new Temp();var result=host.InvokeTemplate(id,new(1,args,[ForgeArtifactKind.StepAp242]),output.Path);+ Assert.True(result.Success,string.Join(Environment.NewLine,result.Diagnostics.Select(x=>x.Code+": "+x.Message)));+ var artifact=Assert.Single(result.Artifacts);Assert.Equal("pump-skid.step",artifact.Path);+ var imported=Step242AssemblyImporter.Import(File.ReadAllText(Path.Combine(output.Path,artifact.Path)));+ Assert.True(imported.IsSuccess,string.Join(Environment.NewLine,imported.Diagnostics.Select(x=>x.Message)));+ Assert.True(imported.Value.Occurrences.Count>=5);+ Assert.Equal(2,imported.Value.Definitions.Count(x=>x.Name.StartsWith("nozzle:",StringComparison.Ordinal)));+ }+ private sealed class Temp:IDisposable{public Temp(){Path=System.IO.Path.Combine(System.IO.Path.GetTempPath(),"forge-x3-"+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/ForgeProtocolHost.cs b/Aetheris.Forge.Host/ForgeProtocolHost.csindex 5b6b63b3..bc1c934b 100644--- a/Aetheris.Forge.Host/ForgeProtocolHost.cs+++ b/Aetheris.Forge.Host/ForgeProtocolHost.cs@@ -198,6 +198,7 @@ public sealed class ForgeProtocolHost["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."),+ ["PumpSkidTemplate"] = ("Standard.Piping.PumpSkid", "Pump Cooling Skid", "Routable semantic piping skid with equipment-owned nozzle stubs, target-port-scoped KeepOut exemptions, endpoint mates, deterministic accepted routing, AP242 assembly, BOM, and pipe Cut List."),};var records = products.Records.ToDictionary(record => record.Name, StringComparer.Ordinal);var enums = products.Enums.ToDictionary(value => value.Name, StringComparer.Ordinal);@@ -388,7 +389,7 @@ 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" : templateId == "Standard.Structural.WeldedWorkbench" ? "welded-workbench.step" : "part.step", "model/step", result.StepText)+ ? (templateId == PaperclipTemplateLibrary.TemplateId ? "paperclip.step" : templateId == "Standard.Structural.WeldedWorkbench" ? "welded-workbench.step" : templateId == "Standard.Piping.PumpSkid" ? "pump-skid.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.");diff --git a/Aetheris.Kernel.Firmament.Tests/PipingX3Tests.cs b/Aetheris.Kernel.Firmament.Tests/PipingX3Tests.csnew file mode 100644index 00000000..383bd3d4--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/PipingX3Tests.cs@@ -0,0 +1,123 @@+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Piping;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class PipingX3Tests+{+ private static readonly string Root=FindRoot();++ [Theory]+ [InlineData("pipe-segment.firmament")]+ [InlineData("elbow90.firmament")]+ [InlineData("explicit-route.firmament")]+ [InlineData("route-around-keepout.firmament")]+ [InlineData("autorouted-connection.firmament")]+ [InlineData("local-reroute.firmament")]+ [InlineData("pump-skid.firmament")]+ public void CanonicalPipingFixtures_CompileAndReimportAsAssembly(string file)+ {+ var path=Path.Combine(Root,"fixtures","Canonical","Piping",file);+ var result=PipingAuthoring.Compile(File.ReadAllText(path),path);+ Assert.True(result.IsSuccess,string.Join(Environment.NewLine,result.Diagnostics));+ Assert.NotNull(result.Report);Assert.NotEmpty(result.Report.Routes);Assert.NotEmpty(result.Report.PipeSegments);+ Assert.True(result.Report.ComponentsEnclosed);Assert.True(result.Report.GeometryClearanceVerified);+ var imported=Step242AssemblyImporter.Import(result.StepText!);+ Assert.True(imported.IsSuccess,string.Join(Environment.NewLine,imported.Diagnostics.Select(x=>x.Message)));+ Assert.Equal(result.Report.BodyCount,imported.Value.Definitions.Count(x=>x.Geometry is not null));+ }++ [Fact]+ public void Autoroute_IsDeterministicInspectable_AndAcceptanceCreatesOrdinaryRouteAuthority()+ {+ var path=Path.Combine(Root,"fixtures","Canonical","Piping","autorouted-connection.firmament");var source=File.ReadAllText(path);+ var first=PipingAuthoring.Compile(source,path);var second=PipingAuthoring.Compile(source,path);+ Assert.True(first.IsSuccess&&second.IsSuccess,string.Join(Environment.NewLine,first.Diagnostics.Concat(second.Diagnostics)));+ Assert.Equal(first.StepText,second.StepText);Assert.Equal(PipingAuthoring.RoutingJson(first.Report!),PipingAuthoring.RoutingJson(second.Report!));+ var proposal=Assert.Single(first.Report!.RouteProposals);Assert.True(proposal.IsSuccess);Assert.True(proposal.MinimumClearanceMm>=30);+ var route=Assert.Single(first.Report.Routes);Assert.Equal(RouteProvenance.AutoGenerated,route.Provenance);+ Assert.StartsWith("accepted:proposal:",route.SourceProvenance,StringComparison.Ordinal);+ Assert.NotEmpty(route.Anchors);Assert.DoesNotContain("Request",route.StableId,StringComparison.Ordinal);+ }++ [Fact]+ public void MaterializedClearance_CatchesElbowEnvelopeThatSharpPolylineMisses()+ {+ var obstacle=new KeepOutIr("keepout:test","Frame",new(0,0,-10),new(100,100,10),"StructureMember");+ Point3D[] points=[new(-100,-42.5,0),new(142.5,-42.5,0),new(142.5,200,0)];+ var sharp=OrthogonalAutoRouter.MinimumClearance(points,[obstacle],12.5);+ var realized=OrthogonalAutoRouter.MinimumMaterializedClearance(points,[obstacle],12.5,50);+ Assert.Equal(30,sharp,6);+ Assert.True(realized<30,$"Expected the torus envelope to reduce clearance below 30 mm; measured {realized:G6} mm.");+ }++ [Fact]+ public void EquipmentNozzles_AreOwnedMatedContinuous_AndOnlyExemptTheirOwnKeepOut()+ {+ var path=Path.Combine(Root,"fixtures","Canonical","Piping","pump-skid.firmament");var result=PipingAuthoring.Compile(File.ReadAllText(path),path);+ Assert.True(result.IsSuccess,string.Join(Environment.NewLine,result.Diagnostics));var report=result.Report!;+ Assert.Equal("aetheris:piping:x3a",report.Schema);Assert.Equal(2,report.Equipment.Count);Assert.Equal(4,report.Nozzles.Count);Assert.Equal(4,report.Mates.Count);Assert.Equal(4,report.KeepOutExemptions.Count);+ Assert.All(report.Mates,m=>{Assert.True(m.Coincident);Assert.True(m.DirectionsOpposed);Assert.Equal(m.Position,report.Ports.Single(p=>p.Name==m.Port).Position);});+ Assert.All(report.KeepOutExemptions,e=>Assert.Equal("NozzleEnvelopeOnly",e.Scope));+ foreach(var nozzle in report.Nozzles)+ {+ var port=report.Ports.Single(x=>x.Name==nozzle.Port);var owner=report.KeepOuts.Single(x=>x.Name==nozzle.OwnerKeepOut);var policy=report.PipePolicies.Single(x=>x.StableId==nozzle.PipePolicy);+ Assert.Equal(port.Position,nozzle.TipPosition);Assert.Equal(port.NozzleLengthMm,(nozzle.TipPosition-nozzle.RootPosition).Length,6);+ Assert.Equal(0,OrthogonalAutoRouter.MinimumClearance([nozzle.RootPosition,nozzle.TipPosition],[owner],policy.RadiusMm),6);+ var foreign=report.KeepOuts.Where(x=>x.Name!=owner.Name).ToArray();Assert.True(OrthogonalAutoRouter.MinimumClearance([nozzle.RootPosition,nozzle.TipPosition],foreign,policy.RadiusMm)>=30);+ }+ Assert.True(report.GeometryClearanceVerified);Assert.True(report.MinimumVerifiedClearanceMm>=30);+ }++ [Fact]+ public void LocalReroute_PreservesSuffixAndLockOutsideAuthorizedInterval()+ {+ var path=Path.Combine(Root,"fixtures","Canonical","Piping","local-reroute.firmament");var result=PipingAuthoring.Compile(File.ReadAllText(path),path);+ Assert.True(result.IsSuccess,string.Join(Environment.NewLine,result.Diagnostics));var route=Assert.Single(result.Report!.Routes);+ Assert.Equal(RouteProvenance.LocallyRerouted,route.Provenance);+ Assert.Equal(new Point3D(500,300,300),route.Anchors[^2].Point);+ Assert.Equal(new Point3D(1000,300,300),route.Anchors[^1].Point);+ var locked=Assert.Single(route.Segments,x=>x.Locked);+ Assert.Equal(new Point3D(500,300,0),route.Anchors[locked.Ordinal].Point);+ Assert.Equal(new Point3D(500,300,300),route.Anchors[locked.Ordinal+1].Point);+ }++ [Theory]+ [InlineData("pipe-wall-too-thick.firmament","piping-pipe-wall-too-thick")]+ [InlineData("incompatible-port.firmament","piping-incompatible-port")]+ [InlineData("route-through-keepout.firmament","piping-route-through-keepout")]+ [InlineData("insufficient-clearance.firmament","piping-insufficient-clearance")]+ [InlineData("unreachable-hard-waypoint.firmament","piping-autoroute-hard-waypoint-unreachable")]+ [InlineData("autoroute-no-solution.firmament","piping-autoroute-endpoint-direction-impossible")]+ [InlineData("local-reroute-crosses-lock.firmament","piping-local-reroute-crosses-lock")]+ [InlineData("nozzle-root-off-owner-face.firmament","piping-nozzle-root-not-on-owner-face")]+ [InlineData("nozzle-crosses-foreign-keepout.firmament","piping-nozzle-foreign-keepout-clearance")]+ public void InvalidPipingFixtures_IsolateDiagnostic(string file,string code)+ {+ var path=Path.Combine(Root,"fixtures","Invalid","Piping",file);var result=PipingAuthoring.Compile(File.ReadAllText(path),path);+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,x=>x.Contains(code,StringComparison.Ordinal));+ }++ [Fact]+ public void StandardPipingLibrary_ResolvesGenericProducts()+ {+ const string source="""+ Use Standard.Piping+ Model LibraryWitness {+ Units: mm+ Let Pipe = Standard.Piping.Pipe+ Let Elbow = Standard.Piping.Elbow90+ Let Tee = Standard.Piping.Tee+ }+ """;+ var resolved=FirmamentStandardLibraryResolver.Resolve(source,out var diagnostics);+ Assert.NotNull(resolved);Assert.Empty(diagnostics);+ Assert.Contains("Struct PipeTemplate",resolved.Source,StringComparison.Ordinal);+ Assert.Contains("Struct Elbow90Template",resolved.Source,StringComparison.Ordinal);+ Assert.Contains("Struct TeeTemplate",resolved.Source,StringComparison.Ordinal);+ }++ 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 d984fd05..a3eb9c51 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -19,6 +19,7 @@ using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Firmament.Materializer;using Aetheris.Kernel.StandardLibrary;using Aetheris.Kernel.Firmament.Structural;+using Aetheris.Kernel.Firmament.Piping;namespace Aetheris.Kernel.Firmament;@@ -38,6 +39,24 @@ public static class FirmamentBuildAndExportvar fullSourcePath = Path.GetFullPath(sourcePath);var sourceText = NormalizeLf(File.ReadAllText(fullSourcePath, Encoding.UTF8));+ if (PipingAuthoring.IsPipingSource(sourceText))+ {+ var piping = PipingAuthoring.Compile(sourceText, fullSourcePath);+ if (!piping.IsSuccess || piping.StepText is null || piping.Report is null)+ return KernelResult<FirmamentBuildAndExportResult>.Failure(piping.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Piping.X3")).ToArray());+ var pipingOutputPath = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath(fullSourcePath) : Path.GetFullPath(outputPath);+ Directory.CreateDirectory(Path.GetDirectoryName(pipingOutputPath)!);+ File.WriteAllText(pipingOutputPath, piping.StepText, new UTF8Encoding(false));+ var stem = Path.Combine(Path.GetDirectoryName(pipingOutputPath)!, Path.GetFileNameWithoutExtension(pipingOutputPath));+ var routingPath = stem + ".routing.json"; var cutListPath = stem + ".cutlist.json"; var bomPath = stem + ".bom.json";+ File.WriteAllText(routingPath, PipingAuthoring.RoutingJson(piping.Report), new UTF8Encoding(false));+ File.WriteAllText(cutListPath, PipingAuthoring.CutListJson(piping.Report), new UTF8Encoding(false));+ File.WriteAllText(bomPath, PipingAuthoring.BomJson(piping.Report), new UTF8Encoding(false));+ var report = piping.Report with { RoutingReportArtifactPath = routingPath, CutListArtifactPath = cutListPath, BomArtifactPath = bomPath };+ return KernelResult<FirmamentBuildAndExportResult>.Success(new(fullSourcePath, pipingOutputPath,+ new(piping.StepText, "piping-system:" + report.PipingSystem, -1, "Assembly", "PipingSystem", Piping: report)));+ }if (StructuralAuthoring.IsStructuralSource(sourceText)){var structural = StructuralAuthoring.Compile(sourceText, fullSourcePath);@@ -101,6 +120,14 @@ public static class FirmamentBuildAndExport{ArgumentNullException.ThrowIfNull(sourceText);var normalized = NormalizeLf(sourceText);+ if (PipingAuthoring.IsPipingSource(normalized))+ {+ var piping = PipingAuthoring.Compile(normalized, sourceDirectory ?? "memory");+ return piping.IsSuccess && piping.StepText is not null && piping.Report is not null+ ? KernelResult<FirmamentStepExportResult>.Success(new(piping.StepText, "piping-system:" + piping.Report.PipingSystem, -1, "Assembly", "PipingSystem", Piping: piping.Report))+ : KernelResult<FirmamentStepExportResult>.Failure(piping.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Piping.X3")).ToArray());+ }if (StructuralAuthoring.IsStructuralSource(normalized)){var structural = StructuralAuthoring.Compile(normalized, sourceDirectory ?? "memory");diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 9813aeff..1718aec2 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -24,7 +24,8 @@ public sealed record FirmamentStepExportResult(IReadOnlyList<FirmamentEngineeringFeatureReport>? EngineeringFeatures = null,FirmamentSweepReport? Sweep = null,IReadOnlyList<FirmamentSemanticPatternReport>? Patterns = null,- Aetheris.Kernel.Firmament.Structural.StructuralReport? Structural = null);+ Aetheris.Kernel.Firmament.Structural.StructuralReport? Structural = null,+ Aetheris.Kernel.Firmament.Piping.PipingReport? Piping = null);public sealed record FirmamentSemanticPatternReport(string Name,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.csindex 4c49903f..c8a6692e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs@@ -36,6 +36,10 @@ public static class FirmamentStandardLibraryResolvernew("Standard.Products.Mechanical", "FlangedAdapter", "FlangedAdapterTemplate", "FlangedAdapterPolicy", "StandardFlangedAdapter"),new("Standard.Products.Mechanical", "Standoff", "StandoffTemplate", "StandoffPolicy", "StandardStandoff"),new("Standard.Products.Electronics", "RackPanel", "RackPanelTemplate", "RackPanelPolicy", "StandardRackPanel"),+ new("Standard.Piping", "Pipe", "PipeTemplate", "PipeProductPolicy", "StandardPipe"),+ new("Standard.Piping", "Elbow90", "Elbow90Template", "Elbow90Policy", "StandardElbow90"),+ new("Standard.Piping", "Tee", "TeeTemplate", "TeePolicy", "StandardTee"),+ new("Standard.Piping", "PumpSkid", "PumpSkidTemplate", "PumpSkidPolicy", "StandardPumpSkid"),];public static FirmamentLibraryResolution? Resolve(string source, out IReadOnlyList<string> diagnostics)@@ -56,7 +60,7 @@ public static class FirmamentStandardLibraryResolvererrors.Add($"{UnknownModule}:{module}: shipped Standard Library module could not be resolved");var references = Regex.Matches(source,- @"\bStandard\.Products\.(?:Office|Mechanical|Electronics)\.[A-Za-z_][A-Za-z0-9_]*\b",+ @"\b(?:Standard\.Products\.(?:Office|Mechanical|Electronics)|Standard\.Piping)\.[A-Za-z_][A-Za-z0-9_]*\b",RegexOptions.CultureInvariant).Cast<Match>().Select(match => match.Value).Distinct(StringComparer.Ordinal).ToArray();var selected = new HashSet<Export>();diff --git a/Aetheris.Kernel.Firmament/Piping/OrthogonalAutoRouter.cs b/Aetheris.Kernel.Firmament/Piping/OrthogonalAutoRouter.csnew file mode 100644index 00000000..87e98711--- /dev/null+++ b/Aetheris.Kernel.Firmament/Piping/OrthogonalAutoRouter.cs@@ -0,0 +1,321 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Firmament.Piping;++/// <summary>+/// Deterministic bounded 3D orthogonal router. Candidate coordinates come from endpoints,+/// hard waypoints, and clearance-inflated obstacle faces; A* explores only adjacent visible+/// coordinate-grid nodes. Cost is length + 1000 mm per turn so fittings dominate small savings.+/// </summary>+public static class OrthogonalAutoRouter+{+ private const double Tol = 1e-7;+ private const double ElbowPenaltyMm = 1000d;+ private static readonly AxisDirection[] DirectionOrder =+ [+ new(0, 0, 1, 0, 0), new(1, 0, -1, 0, 0), new(2, 1, 0, 1, 0),+ new(3, 1, 0, -1, 0), new(4, 2, 0, 0, 1), new(5, 2, 0, 0, -1)+ ];++ public static RouteProposalIr Propose(RouteRequestIr request)+ {+ ArgumentNullException.ThrowIfNull(request);+ var diagnostics = Validate(request);+ if (diagnostics.Count > 0)+ return Failed(request, RouteFailureKind.EndpointDirectionImpossible, diagnostics);++ var inflated = request.KeepOuts.Select(x => x.Inflate(request.PipePolicy.RadiusMm + request.ClearanceMm)).ToArray();+ // Use farther coordinate planes for candidate corners without falsely treating a+ // valid nozzle inside that extra planning margin as collision geometry.+ const int verificationArcIntervals = 128;+ var verificationMargin = request.BendRadiusMm * (1 - Math.Cos(Math.PI / (4 * verificationArcIntervals))) + Tol;+ var candidateBounds = request.KeepOuts.Select(x => x.Inflate(request.PipePolicy.RadiusMm + request.ClearanceMm + request.BendRadiusMm + verificationMargin)).ToArray();+ var required = new[] { request.From.Position }.Concat(request.HardWaypoints).Append(request.To.Position).ToArray();+ var all = new List<Point3D>();+ AxisDirection? incoming = null;+ for (var leg = 0; leg < required.Length - 1; leg++)+ {+ var startRequired = leg == 0 ? Axis(request.From.OutwardDirection) : incoming;+ var endRequired = leg == required.Length - 2 ? Axis(-request.To.OutwardDirection) : null;+ var search = Search(required[leg], required[leg + 1], startRequired, endRequired, candidateBounds, inflated, required, request.BendRadiusMm);+ if (!search.Success)+ {+ var kind = request.HardWaypoints.Count > 0 && leg < required.Length - 2+ ? RouteFailureKind.HardWaypointUnreachable : search.Failure;+ return Failed(request, kind, [$"piping-autoroute-{Code(kind)}:{request.Name}: {search.Diagnostic}"]);+ }+ if (all.Count > 0) all.RemoveAt(all.Count - 1);+ all.AddRange(search.Points);+ if (search.Points.Count >= 2) incoming = Axis(search.Points[^1] - search.Points[^2]);+ }++ var simplified = Simplify(all);+ var anchors = simplified.Select((point, i) => new RouteAnchorIr(+ $"proposal:{request.Name}:anchor:{i}", i, point,+ i == 0 || i == simplified.Count - 1 ? RouteAnchorKind.Endpoint+ : request.HardWaypoints.Any(w => Near(w, point)) ? RouteAnchorKind.HardWaypoint : RouteAnchorKind.AutoWaypoint)).ToArray();+ var length = Pairwise(simplified).Sum(x => Distance(x.A, x.B));+ var elbows = Math.Max(0, simplified.Count - 2);+ var minimum = MinimumMaterializedClearance(simplified, request.KeepOuts, request.PipePolicy.RadiusMm, request.BendRadiusMm);+ if (minimum + Tol < request.ClearanceMm)+ return Failed(request, RouteFailureKind.NoCollisionFreePath,+ [$"piping-autoroute-fitting-clearance:{request.Name}: realized elbow envelope has {minimum:G6}mm clearance, required {request.ClearanceMm:G6}mm"]);+ return new($"proposal:{request.Name}", request.Name, true, anchors, length, elbows, minimum,+ length + elbows * ElbowPenaltyMm, ["piping-autoroute-deterministic", "piping-route-simplified", "piping-endpoint-directions-respected"], null);+ }++ public static RouteIr Accept(RouteProposalIr proposal, RouteRequestIr request, string routeName)+ {+ if (!proposal.IsSuccess) throw new InvalidOperationException("Cannot accept an unsuccessful route proposal.");+ var anchors = proposal.Anchors.Select((x, i) => x with { StableId = $"route:{routeName}:anchor:{i}", Ordinal = i }).ToArray();+ return BuildRoute(routeName, request.Connection, request.From.StableId, request.To.StableId, anchors,+ request.BendRadiusMm, RouteProvenance.AutoGenerated, $"accepted:{proposal.StableId}", []);+ }++ public static (RouteIr? Route, IReadOnlyList<string> Diagnostics) Reroute(+ RouteIr original, RouteRequestIr environment, int fromAnchor, int toAnchor, IReadOnlyList<KeepOutIr>? additionalKeepOuts = null)+ {+ if (fromAnchor < 0 || toAnchor >= original.Anchors.Count || fromAnchor >= toAnchor)+ return (null, [$"piping-local-reroute-interval-invalid:{original.Name}:{fromAnchor}:{toAnchor}"]);+ if (original.LockedSegmentOrdinals.Any(i => i >= fromAnchor && i < toAnchor))+ return (null, [$"piping-local-reroute-crosses-lock:{original.Name}: locked segment prevents solution"]);++ var obstacles = environment.KeepOuts.Concat(additionalKeepOuts ?? []).DistinctBy(x => x.StableId).ToArray();+ var from = original.Anchors[fromAnchor].Point;+ var to = original.Anchors[toAnchor].Point;+ var startDirection = fromAnchor == 0 ? environment.From.OutwardDirection : original.Anchors[fromAnchor + 1].Point - from;+ var endOutward = toAnchor == original.Anchors.Count - 1 ? environment.To.OutwardDirection : -(to - original.Anchors[toAnchor - 1].Point);+ var request = environment with+ {+ StableId = environment.StableId + ":local",+ Name = environment.Name + "Local",+ From = environment.From with { Position = from, OutwardDirection = NormalizeAxis(startDirection) },+ To = environment.To with { Position = to, OutwardDirection = NormalizeAxis(endOutward) },+ KeepOuts = obstacles,+ HardWaypoints = []+ };+ var proposal = Propose(request);+ if (!proposal.IsSuccess)+ return (null, [$"piping-local-reroute-no-solution:{original.Name}:{string.Join("; ", proposal.Diagnostics)}"]);++ var replacement = proposal.Anchors.Select(x => x.Point).ToArray();+ var points = original.Anchors.Take(fromAnchor).Select(x => x.Point)+ .Concat(replacement)+ .Concat(original.Anchors.Skip(toAnchor + 1).Select(x => x.Point)).ToArray();+ var anchors = points.Select((p, i) => new RouteAnchorIr($"route:{original.Name}:anchor:{i}", i, p,+ i == 0 || i == points.Length - 1 ? RouteAnchorKind.Endpoint : RouteAnchorKind.AutoWaypoint)).ToArray();+ var shiftedLocks = original.LockedSegmentOrdinals.Where(i => i < fromAnchor)+ .Concat(original.LockedSegmentOrdinals.Where(i => i >= toAnchor).Select(i => i + replacement.Length - (toAnchor - fromAnchor + 1))).ToArray();+ return (BuildRoute(original.Name, original.Connection, original.StartInterface, original.EndInterface, anchors,+ environment.BendRadiusMm, RouteProvenance.LocallyRerouted, $"local-reroute:{fromAnchor}:{toAnchor}", shiftedLocks), []);+ }++ public static RouteIr BuildRoute(string name, string connection, string startInterface, string endInterface,+ IReadOnlyList<RouteAnchorIr> anchors, double bendRadius, RouteProvenance provenance, string source, IReadOnlyList<int> locks)+ {+ var segments = Pairwise(anchors).Select((pair, i) => new RouteSegmentIr($"route:{name}:segment:{i}", i,+ pair.A.StableId, pair.B.StableId, Distance(pair.A.Point, pair.B.Point), locks.Contains(i))).ToArray();+ var turns = Enumerable.Range(1, Math.Max(0, anchors.Count - 2)).Select(i =>+ new RouteTurnIr($"route:{name}:fitting:{i}", i, "Standard.Piping.Elbow90", bendRadius)).ToArray();+ return new($"route:{name}", name, connection, startInterface, endInterface, anchors, segments, turns, locks.Order().ToArray(), provenance, source);+ }++ public static IReadOnlyList<Point3D> Simplify(IReadOnlyList<Point3D> points)+ {+ var result = new List<Point3D>();+ foreach (var point in points)+ {+ if (result.Count > 0 && Near(result[^1], point)) continue;+ while (result.Count >= 2 && Collinear(result[^2], result[^1], point)) result.RemoveAt(result.Count - 1);+ result.Add(point);+ }+ return result;+ }++ public static double MinimumClearance(IReadOnlyList<Point3D> points, IReadOnlyList<KeepOutIr> obstacles, double pipeRadius)+ {+ if (obstacles.Count == 0) return 1_000_000_000_000d;+ var best = double.PositiveInfinity;+ foreach (var (a, b) in Pairwise(points))+ foreach (var obstacle in obstacles)+ best = Math.Min(best, SegmentBoxDistance(a, b, obstacle) - pipeRadius);+ return Math.Max(0, best);+ }++ /// <summary>+ /// Independently checks the realized straight cylinders and 90-degree torus envelopes.+ /// Arc sampling subtracts the maximum chord sagitta, making the reported distance a+ /// conservative lower bound rather than an optimistic sample estimate.+ /// </summary>+ public static double MinimumMaterializedClearance(IReadOnlyList<Point3D> points, IReadOnlyList<KeepOutIr> obstacles,+ double pipeRadius, double bendRadius)+ {+ if (obstacles.Count == 0) return 1_000_000_000_000d;+ var best = double.PositiveInfinity;+ for (var i = 0; i + 1 < points.Count; i++)+ {+ var direction = NormalizeAxis(points[i + 1] - points[i]);+ var start = i == 0 ? points[i] : points[i] + direction * bendRadius;+ var end = i == points.Count - 2 ? points[i + 1] : points[i + 1] - direction * bendRadius;+ foreach (var obstacle in obstacles)+ best = Math.Min(best, SegmentBoxDistance(start, end, obstacle) - pipeRadius);+ }++ const int arcIntervals = 128;+ var sagitta = bendRadius * (1 - Math.Cos(Math.PI / (4 * arcIntervals)));+ for (var i = 1; i + 1 < points.Count; i++)+ {+ var u = NormalizeAxis(points[i] - points[i - 1]);+ var v = NormalizeAxis(points[i + 1] - points[i]);+ var center = points[i] - u * bendRadius + v * bendRadius;+ foreach (var obstacle in obstacles)+ for (var sample = 0; sample <= arcIntervals; sample++)+ {+ var angle = Math.PI * sample / (2 * arcIntervals);+ var point = center - v * (bendRadius * Math.Cos(angle)) + u * (bendRadius * Math.Sin(angle));+ best = Math.Min(best, PointBoxDistance(point, obstacle) - pipeRadius - sagitta);+ }+ }+ return Math.Max(0, best);+ }++ private static SearchResult Search(Point3D start, Point3D end, AxisDirection? startRequired, AxisDirection? endRequired,+ IReadOnlyList<KeepOutIr> candidateBounds, IReadOnlyList<KeepOutIr> blockedBounds, IReadOnlyList<Point3D> required, double bendRadius)+ {+ var margin = Math.Max(100d, bendRadius * 2d);+ var requiredX=required.Select(x=>x.X).ToArray();var requiredY=required.Select(x=>x.Y).ToArray();var requiredZ=required.Select(x=>x.Z).ToArray();+ var xs = Coordinates(requiredX, CandidateFaces(candidateBounds.SelectMany(x => new[] { x.Minimum.X, x.Maximum.X }),requiredX,bendRadius), margin);+ var ys = Coordinates(requiredY, CandidateFaces(candidateBounds.SelectMany(x => new[] { x.Minimum.Y, x.Maximum.Y }),requiredY,bendRadius), margin);+ var zs = Coordinates(requiredZ, CandidateFaces(candidateBounds.SelectMany(x => new[] { x.Minimum.Z, x.Maximum.Z }),requiredZ,bendRadius), margin);+ var nodes = new List<Point3D>();+ var index = new Dictionary<GridKey, int>();+ foreach (var x in xs) foreach (var y in ys) foreach (var z in zs)+ {+ var p = new Point3D(x, y, z);+ if (InsideAny(p, blockedBounds) && !Near(p, start) && !Near(p, end)) continue;+ index[new(Q(x), Q(y), Q(z))] = nodes.Count; nodes.Add(p);+ }+ if (!index.TryGetValue(Key(start), out var startNode) || !index.TryGetValue(Key(end), out var endNode))+ return new(false, [], RouteFailureKind.ClearanceTooLarge, "clearance-inflated obstacle contains an endpoint");++ var states = new Dictionary<State, Score>();+ var previous = new Dictionary<State, State>();+ var queue = new PriorityQueue<State, Priority>();+ var initial = new State(startNode, -1);+ states[initial] = new(0, 0, 0);+ queue.Enqueue(initial, new(Manhattan(start, end), 0, 0, startNode, -1));+ State? goal = null;+ while (queue.TryDequeue(out var current, out _))+ {+ var currentScore = states[current];+ var point = nodes[current.Node];+ if (current.Node == endNode && (endRequired is null || current.Direction == endRequired.Value.Order)) { goal = current; break; }+ foreach (var direction in DirectionOrder)+ {+ if (current.Direction < 0 && startRequired is not null && direction.Order != startRequired.Value.Order) continue;+ var neighborKey = Neighbor(point, direction, xs, ys, zs);+ if (neighborKey is null || !index.TryGetValue(neighborKey.Value, out var neighbor)) continue;+ var nextPoint = nodes[neighbor];+ if (SegmentBlocked(point, nextPoint, blockedBounds)) continue;+ var turn = current.Direction >= 0 && current.Direction != direction.Order ? 1 : 0;+ var length = Distance(point, nextPoint);+ var score = new Score(currentScore.Cost + length + turn * ElbowPenaltyMm, currentScore.Length + length, currentScore.Turns + turn);+ var next = new State(neighbor, direction.Order);+ if (states.TryGetValue(next, out var known) && known.CompareTo(score) <= 0) continue;+ states[next] = score; previous[next] = current;+ queue.Enqueue(next, new(score.Cost + Manhattan(nextPoint, end), score.Turns, score.Length, neighbor, direction.Order));+ }+ }+ if (goal is null)+ return new(false, [], startRequired is not null || endRequired is not null ? RouteFailureKind.EndpointDirectionImpossible : RouteFailureKind.RoutingRegionDisconnected,+ "candidate routing graph has no path satisfying obstacle, clearance, and endpoint-direction constraints");+ var path = new List<Point3D>(); var cursor = goal.Value;+ while (true) { path.Add(nodes[cursor.Node]); if (cursor.Equals(initial)) break; cursor = previous[cursor]; }+ path.Reverse();+ return new(true, path, default, string.Empty);+ }++ private static IReadOnlyList<string> Validate(RouteRequestIr r)+ {+ var d = new List<string>();+ if (r.ClearanceMm < 0 || !double.IsFinite(r.ClearanceMm)) d.Add($"piping-clearance-invalid:{r.Name}");+ if (Axis(r.From.OutwardDirection) is null) d.Add($"piping-port-direction-nonorthogonal:{r.From.Name}");+ if (Axis(r.To.OutwardDirection) is null) d.Add($"piping-port-direction-nonorthogonal:{r.To.Name}");+ return d;+ }++ private static RouteProposalIr Failed(RouteRequestIr request, RouteFailureKind kind, IReadOnlyList<string> diagnostics) =>+ new($"proposal:{request.Name}", request.Name, false, [], 0, 0, 0, double.PositiveInfinity, diagnostics, kind);+ private static string Code(RouteFailureKind kind) => kind switch+ {+ RouteFailureKind.NoCollisionFreePath => "no-collision-free-path",+ RouteFailureKind.EndpointDirectionImpossible => "endpoint-direction-impossible",+ RouteFailureKind.ClearanceTooLarge => "clearance-too-large",+ RouteFailureKind.HardWaypointUnreachable => "hard-waypoint-unreachable",+ RouteFailureKind.RoutingRegionDisconnected => "routing-region-disconnected",+ RouteFailureKind.LockedIntervalPreventsSolution => "locked-interval-prevents-solution",+ _ => "failed"+ };+ private static IReadOnlyList<double> Coordinates(IEnumerable<double> required, IEnumerable<double> obstacleFaces, double margin)+ {+ var values = required.Concat(obstacleFaces).DistinctBy(Q).Order().ToList();+ if (values.Count == 0) return [0];+ values.Add(values[0] - margin); values.Add(values.Max() + margin);+ return values.DistinctBy(Q).Order().ToArray();+ }+ private static IEnumerable<double> CandidateFaces(IEnumerable<double> faces,IReadOnlyList<double> required,double bendRadius)=>+ faces.Where(face=>required.All(value=>Math.Abs(face-value)>2*bendRadius+Tol));+ private static GridKey? Neighbor(Point3D p, AxisDirection d, IReadOnlyList<double> xs, IReadOnlyList<double> ys, IReadOnlyList<double> zs)+ {+ var values = d.Axis == 0 ? xs : d.Axis == 1 ? ys : zs;+ var coordinate = d.Axis == 0 ? p.X : d.Axis == 1 ? p.Y : p.Z;+ var i = values.ToList().FindIndex(x => Math.Abs(x - coordinate) <= Tol);+ var n = i + (d.Sign > 0 ? 1 : -1); if (n < 0 || n >= values.Count) return null;+ return d.Axis switch { 0 => new(Q(values[n]), Q(p.Y), Q(p.Z)), 1 => new(Q(p.X), Q(values[n]), Q(p.Z)), _ => new(Q(p.X), Q(p.Y), Q(values[n])) };+ }+ private static bool SegmentBlocked(Point3D a, Point3D b, IReadOnlyList<KeepOutIr> boxes) => boxes.Any(box => SegmentIntersectsInterior(a, b, box));+ private static bool SegmentIntersectsInterior(Point3D a, Point3D b, KeepOutIr box)+ {+ if (Math.Abs(a.X - b.X) > Tol) return Between(a.Y, box.Minimum.Y, box.Maximum.Y) && Between(a.Z, box.Minimum.Z, box.Maximum.Z) && IntervalInterior(a.X, b.X, box.Minimum.X, box.Maximum.X);+ if (Math.Abs(a.Y - b.Y) > Tol) return Between(a.X, box.Minimum.X, box.Maximum.X) && Between(a.Z, box.Minimum.Z, box.Maximum.Z) && IntervalInterior(a.Y, b.Y, box.Minimum.Y, box.Maximum.Y);+ return Between(a.X, box.Minimum.X, box.Maximum.X) && Between(a.Y, box.Minimum.Y, box.Maximum.Y) && IntervalInterior(a.Z, b.Z, box.Minimum.Z, box.Maximum.Z);+ }+ private static bool InsideAny(Point3D p, IReadOnlyList<KeepOutIr> boxes) => boxes.Any(b => Between(p.X,b.Minimum.X,b.Maximum.X)&&Between(p.Y,b.Minimum.Y,b.Maximum.Y)&&Between(p.Z,b.Minimum.Z,b.Maximum.Z));+ private static bool Between(double v, double min, double max) => v > min + Tol && v < max - Tol;+ private static bool IntervalInterior(double a,double b,double min,double max)=>Math.Max(Math.Min(a,b),min)<Math.Min(Math.Max(a,b),max)-Tol;+ private static double SegmentBoxDistance(Point3D a, Point3D b, KeepOutIr box)+ {+ var dx=IntervalDistance(Math.Min(a.X,b.X),Math.Max(a.X,b.X),box.Minimum.X,box.Maximum.X);+ var dy=IntervalDistance(Math.Min(a.Y,b.Y),Math.Max(a.Y,b.Y),box.Minimum.Y,box.Maximum.Y);+ var dz=IntervalDistance(Math.Min(a.Z,b.Z),Math.Max(a.Z,b.Z),box.Minimum.Z,box.Maximum.Z);+ return Math.Sqrt(dx*dx+dy*dy+dz*dz);+ }+ private static double PointBoxDistance(Point3D p,KeepOutIr box)+ {+ var dx=IntervalDistance(p.X,p.X,box.Minimum.X,box.Maximum.X);+ var dy=IntervalDistance(p.Y,p.Y,box.Minimum.Y,box.Maximum.Y);+ var dz=IntervalDistance(p.Z,p.Z,box.Minimum.Z,box.Maximum.Z);+ return Math.Sqrt(dx*dx+dy*dy+dz*dz);+ }+ private static double IntervalDistance(double aMin,double aMax,double bMin,double bMax)=>Math.Max(0,Math.Max(aMin,bMin)-Math.Min(aMax,bMax));+ private static AxisDirection? Axis(Vector3D v)+ {+ var components = new[] { Math.Abs(v.X), Math.Abs(v.Y), Math.Abs(v.Z) }; var axis = Array.IndexOf(components, components.Max());+ if (components[axis] <= Tol || components.Where((_,i)=>i!=axis).Any(x=>x>Tol)) return null;+ var sign = (axis==0?v.X:axis==1?v.Y:v.Z)>0?1:-1; return DirectionOrder.Single(x=>x.Axis==axis&&x.Sign==sign);+ }+ private static Vector3D NormalizeAxis(Vector3D v) { var a=Axis(v)??throw new ArgumentException("Direction must be axis aligned."); return new(a.X,a.Y,a.Z); }+ private static bool Collinear(Point3D a,Point3D b,Point3D c)=>(b-a).Cross(c-b).Length<=Tol;+ private static bool Near(Point3D a,Point3D b)=>Distance(a,b)<=Tol;+ private static double Distance(Point3D a,Point3D b)=>(b-a).Length;+ private static double Manhattan(Point3D a,Point3D b)=>Math.Abs(a.X-b.X)+Math.Abs(a.Y-b.Y)+Math.Abs(a.Z-b.Z);+ private static IEnumerable<(T A,T B)> Pairwise<T>(IReadOnlyList<T> values){for(var i=0;i+1<values.Count;i++)yield return(values[i],values[i+1]);}+ private static long Q(double x)=>(long)Math.Round(x*1_000_000,MidpointRounding.AwayFromZero);+ private static GridKey Key(Point3D p)=>new(Q(p.X),Q(p.Y),Q(p.Z));+ private readonly record struct GridKey(long X,long Y,long Z);+ private readonly record struct AxisDirection(int Order,int Axis,int X,int Y,int Z){public int Sign=>Axis==0?X:Axis==1?Y:Z;}+ private readonly record struct State(int Node,int Direction);+ private readonly record struct Score(double Cost,double Length,int Turns):IComparable<Score>{public int CompareTo(Score o){var c=Cost.CompareTo(o.Cost);if(c!=0)return c;c=Turns.CompareTo(o.Turns);return c!=0?c:Length.CompareTo(o.Length);}}+ private readonly record struct Priority(double EstimatedCost,int Turns,double Length,int Node,int Direction):IComparable<Priority>{public int CompareTo(Priority o){var c=EstimatedCost.CompareTo(o.EstimatedCost);if(c!=0)return c;c=Turns.CompareTo(o.Turns);if(c!=0)return c;c=Length.CompareTo(o.Length);if(c!=0)return c;c=Node.CompareTo(o.Node);return c!=0?c:Direction.CompareTo(o.Direction);}}+ private sealed record SearchResult(bool Success,IReadOnlyList<Point3D> Points,RouteFailureKind Failure,string Diagnostic);+}diff --git a/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.cs b/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.csnew file mode 100644index 00000000..be1948ff--- /dev/null+++ b/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.cs@@ -0,0 +1,233 @@+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.Geometry;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.StandardLibrary.Materials;++namespace Aetheris.Kernel.Firmament.Piping;++/// <summary>Bounded X3 semantic piping front end for explicit and accepted orthogonal routes.</summary>+public static class PipingAuthoring+{+ private const double Tol=1e-7;+ public static bool IsPipingSource(string source)=>Regex.IsMatch(source,@"\bPipingSystem\s+[A-Za-z_]\w*\s*\{",RegexOptions.CultureInvariant);++ public static PipingCompilationResult Compile(string source,string sourceIdentity="memory")+ {+ var diagnostics=new List<string>();var parseClock=System.Diagnostics.Stopwatch.StartNew();+ var parsed=Parse(source,sourceIdentity,diagnostics);parseClock.Stop();+ if(parsed is null||diagnostics.Count>0)return new(false,null,null,diagnostics);+ ValidateNozzleContracts(parsed,diagnostics);+ if(diagnostics.Count>0)return new(false,null,null,diagnostics);+ var obstacleClock=System.Diagnostics.Stopwatch.StartNew();var obstacles=parsed.KeepOuts;obstacleClock.Stop();+ var routeClock=System.Diagnostics.Stopwatch.StartNew();+ var routes=new List<RouteIr>(parsed.Routes);var proposals=new List<RouteProposalIr>();+ foreach(var request in parsed.Requests)+ {+ var proposal=OrthogonalAutoRouter.Propose(request.Request);proposals.Add(proposal);+ if(!proposal.IsSuccess){diagnostics.AddRange(proposal.Diagnostics);continue;}+ if(request.AcceptAs.Length>0)routes.Add(OrthogonalAutoRouter.Accept(proposal,request.Request,request.AcceptAs));+ }+ foreach(var edit in parsed.Reroutes)+ {+ var index=routes.FindIndex(x=>x.Name==edit.Route);+ if(index<0){diagnostics.Add($"piping-local-reroute-unknown-route:{edit.Name}:{edit.Route}");continue;}+ var connection=parsed.Connections.Single(x=>x.Name==routes[index].Connection);+ var environment=RequestFor(connection,parsed,edit.Name,edit.Clearance);+ var extra=edit.Avoid.Select(name=>parsed.KeepOuts.SingleOrDefault(x=>x.Name==name)).Where(x=>x is not null).Cast<KeepOutIr>().ToArray();+ if(extra.Length!=edit.Avoid.Count){diagnostics.Add($"piping-local-reroute-unknown-keepout:{edit.Name}");continue;}+ var rerouted=OrthogonalAutoRouter.Reroute(routes[index],environment,edit.FromAnchor,edit.ToAnchor,extra);+ if(rerouted.Route is null)diagnostics.AddRange(rerouted.Diagnostics);else routes[index]=rerouted.Route;+ }+ routeClock.Stop();+ ValidateRoutes(routes,parsed,diagnostics);+ if(diagnostics.Count>0)return new(false,null,null,diagnostics);++ var simplifyClock=System.Diagnostics.Stopwatch.StartNew();+ routes=routes.Select(Canonicalize).ToList();simplifyClock.Stop();+ var fittingClock=System.Diagnostics.Stopwatch.StartNew();+ var segments=new List<PipeSegmentComponentIr>();var fittings=new List<PipingFittingComponentIr>();+ foreach(var route in routes.OrderBy(x=>x.StableId,StringComparer.Ordinal))+ {+ var connection=parsed.Connections.Single(x=>x.Name==route.Connection);var policy=parsed.Policies.Single(x=>x.Name==connection.PipePolicy);+ var bend=route.Turns.FirstOrDefault()?.BendRadiusMm??Math.Max(50,policy.OuterDiameterMm*2);+ for(var i=0;i<route.Segments.Count;i++)+ {+ var run=PipingGeometry.TrimmedRun(route.Anchors,i,bend);var body=PipingGeometry.Pipe(run.Start,run.End,policy);+ if(!body.IsSuccess||body.Value is null){diagnostics.AddRange(body.Diagnostics.Select(x=>$"piping-segment-geometry:{route.Name}:{i}:{x.Message}"));continue;}+ var length=(run.End-run.Start).Length;segments.Add(new($"pipe-segment:{route.Name}:{i}",route.Name,i,policy.StableId,policy.Material,+ i==0?$"interface:pipe-segment:{route.Name}:{i}:Start":$"fitting:{route.Name}:{i}:Outlet",i==route.Segments.Count-1?$"interface:pipe-segment:{route.Name}:{i}:End":$"fitting:{route.Name}:{i+1}:Inlet",length,length,body.Value));+ }+ for(var i=1;i<route.Anchors.Count-1;i++)+ {+ var incoming=route.Anchors[i].Point-route.Anchors[i-1].Point;var outgoing=route.Anchors[i+1].Point-route.Anchors[i].Point;+ var body=PipingGeometry.Elbow(route.Anchors[i].Point,incoming,outgoing,policy,bend);+ if(!body.IsSuccess||body.Value is null){diagnostics.AddRange(body.Diagnostics.Select(x=>$"piping-fitting-geometry:{route.Name}:{i}:{x.Message}"));continue;}+ var u=incoming/incoming.Length;var v=outgoing/outgoing.Length;+ fittings.Add(new($"fitting:{route.Name}:{i}",route.Name,i,"Standard.Piping.Elbow90",policy.StableId,+ [new($"fitting:{route.Name}:{i}:Inlet","Inlet",route.Anchors[i].Point-u*bend,-u),new($"fitting:{route.Name}:{i}:Outlet","Outlet",route.Anchors[i].Point+v*bend,v)],body.Value));+ }+ }+ var nozzles=new List<EquipmentNozzleComponentIr>();+ foreach(var port in parsed.Ports.Where(x=>x.Equipment is not null))+ {+ var policy=parsed.Policies.Single(x=>x.Name==port.PipePolicy);var u=port.OutwardDirection/port.OutwardDirection.Length;+ var nozzleRoot=port.Position-u*port.NozzleLengthMm;var body=PipingGeometry.Pipe(nozzleRoot,port.Position,policy);+ if(!body.IsSuccess||body.Value is null){diagnostics.AddRange(body.Diagnostics.Select(x=>$"piping-nozzle-geometry:{port.Name}:{x.Message}"));continue;}+ nozzles.Add(new($"nozzle:{port.Name}",port.Name,port.Equipment!,port.OwnerKeepOut!,policy.StableId,nozzleRoot,port.Position,+ new($"interface:nozzle:{port.Name}:EquipmentMate","EquipmentMate",nozzleRoot,-u),+ new(port.StableId,"PipeMate",port.Position,u),body.Value));+ }+ var mates=BuildEndpointMates(routes,parsed,segments,nozzles,diagnostics);+ var exemptions=nozzles.Select(x=>new PipingKeepOutExemptionIr($"keepout-exemption:{x.Port}",x.Port,x.StableId,x.OwnerKeepOut,"NozzleEnvelopeOnly")).ToArray();+ fittingClock.Stop();if(diagnostics.Count>0)return new(false,null,null,diagnostics);++ var brepClock=System.Diagnostics.Stopwatch.StartNew();+ var proxies=parsed.KeepOuts.Select(x=>(KeepOut:x,Body:PipingGeometry.Proxy(x))).ToArray();+ foreach(var p in proxies.Where(x=>!x.Body.IsSuccess))diagnostics.AddRange(p.Body.Diagnostics.Select(x=>$"piping-proxy-geometry:{p.KeepOut.Name}:{x.Message}"));+ if(diagnostics.Count>0)return new(false,null,null,diagnostics);+ var definitions=segments.Select(x=>new Step242AssemblyDefinition("def:"+x.StableId,x.StableId,x.Body))+ .Concat(fittings.Select(x=>new Step242AssemblyDefinition("def:"+x.StableId,x.StableId,x.Body)))+ .Concat(nozzles.Select(x=>new Step242AssemblyDefinition("def:"+x.StableId,x.StableId,x.Body)))+ .Concat(proxies.Select(x=>new Step242AssemblyDefinition("def:proxy:"+x.KeepOut.Name,"routing-proxy:"+x.KeepOut.Name,x.Body.Value))).ToArray();+ var identity=new double[]{1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};var root="piping-system:"+parsed.Name;+ var occurrences=new[]{new Step242AssemblyOccurrence(root,parsed.Name,null,null,identity)}.Concat(definitions.Select(x=>new Step242AssemblyOccurrence("occ:"+x.StableId,x.Name,root,x.StableId,identity))).ToArray();+ var step=Step242AssemblyExporter.Export(new(parsed.Name,root,definitions,occurrences));+ if(!step.IsSuccess||step.Value is null){diagnostics.AddRange(step.Diagnostics.Select(x=>"piping-step-export:"+x.Message));return new(false,null,null,diagnostics);}+ var imported=Step242AssemblyImporter.Import(step.Value);if(!imported.IsSuccess){diagnostics.AddRange(imported.Diagnostics.Select(x=>"piping-step-reimport:"+x.Message));return new(false,null,null,diagnostics);}+ brepClock.Stop();+ var bom=BuildBom(segments,fittings,nozzles);var cut=BuildCutList(parsed.Policies,segments);+ var bodies=segments.Select(x=>x.Body).Concat(fittings.Select(x=>x.Body)).Concat(nozzles.Select(x=>x.Body)).Concat(proxies.Select(x=>x.Body.Value)).ToArray();+ var points=bodies.SelectMany(BodyPoints).ToArray();var surfaces=bodies.SelectMany(x=>x.Geometry.Surfaces.Select(s=>s.Value.Kind)).ToArray();+ var maximumRadius=parsed.Policies.Max(x=>x.RadiusMm);var routePoints=routes.SelectMany(x=>x.Anchors.Select(a=>a.Point)).ToArray();+ var bounds=new[]{+ Math.Min(routePoints.Min(x=>x.X)-maximumRadius,parsed.KeepOuts.Select(x=>x.Minimum.X).DefaultIfEmpty(double.PositiveInfinity).Min()),+ Math.Min(routePoints.Min(x=>x.Y)-maximumRadius,parsed.KeepOuts.Select(x=>x.Minimum.Y).DefaultIfEmpty(double.PositiveInfinity).Min()),+ Math.Min(routePoints.Min(x=>x.Z)-maximumRadius,parsed.KeepOuts.Select(x=>x.Minimum.Z).DefaultIfEmpty(double.PositiveInfinity).Min()),+ Math.Max(routePoints.Max(x=>x.X)+maximumRadius,parsed.KeepOuts.Select(x=>x.Maximum.X).DefaultIfEmpty(double.NegativeInfinity).Max()),+ Math.Max(routePoints.Max(x=>x.Y)+maximumRadius,parsed.KeepOuts.Select(x=>x.Maximum.Y).DefaultIfEmpty(double.NegativeInfinity).Max()),+ Math.Max(routePoints.Max(x=>x.Z)+maximumRadius,parsed.KeepOuts.Select(x=>x.Maximum.Z).DefaultIfEmpty(double.NegativeInfinity).Max())};+ var routeClearance=routes.Select(r=>{var p=parsed.Policies.Single(x=>x.Name==parsed.Connections.Single(c=>c.Name==r.Connection).PipePolicy);var bend=r.Turns.FirstOrDefault()?.BendRadiusMm??Math.Max(50,p.OuterDiameterMm*2);return OrthogonalAutoRouter.MinimumMaterializedClearance(r.Anchors.Select(x=>x.Point).ToArray(),parsed.KeepOuts,p.RadiusMm,bend);}).DefaultIfEmpty(double.PositiveInfinity).Min();+ var nozzleClearance=nozzles.Select(n=>{var p=parsed.Policies.Single(x=>x.StableId==n.PipePolicy);var obstacles=parsed.KeepOuts.Where(x=>x.Name!=n.OwnerKeepOut).ToArray();return OrthogonalAutoRouter.MinimumClearance([n.RootPosition,n.TipPosition],obstacles,p.RadiusMm);}).DefaultIfEmpty(double.PositiveInfinity).Min();+ var clearance=Math.Min(routeClearance,nozzleClearance);+ var geometryClear=routes.All(r=>{var p=parsed.Policies.Single(x=>x.Name==parsed.Connections.Single(c=>c.Name==r.Connection).PipePolicy);var bend=r.Turns.FirstOrDefault()?.BendRadiusMm??Math.Max(50,p.OuterDiameterMm*2);var required=parsed.Requests.FirstOrDefault(x=>x.Request.Connection==r.Connection)?.Request.ClearanceMm??parsed.DefaultClearance;return OrthogonalAutoRouter.MinimumMaterializedClearance(r.Anchors.Select(x=>x.Point).ToArray(),parsed.KeepOuts,p.RadiusMm,bend)+Tol>=required;});+ foreach(var nozzle in nozzles)+ {+ var policy=parsed.Policies.Single(x=>x.StableId==nozzle.PipePolicy);var foreignObstacles=parsed.KeepOuts.Where(x=>x.Name!=nozzle.OwnerKeepOut).ToArray();+ var actual=OrthogonalAutoRouter.MinimumClearance([nozzle.RootPosition,nozzle.TipPosition],foreignObstacles,policy.RadiusMm);var required=RequiredClearanceForPort(parsed,nozzle.Port);+ if(actual+Tol<required){geometryClear=false;diagnostics.Add($"piping-nozzle-foreign-keepout-clearance:{nozzle.Port}: verified {actual:G6}mm, required {required:G6}mm");}+ }+ if(!geometryClear){diagnostics.Add("piping-final-geometry-clearance-failed: materialized pipe envelope violates KeepOut clearance");return new(false,null,null,diagnostics);}+ var hash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();+ var assemblyInterfaces=parsed.Ports.Select(x=>x.StableId).Concat(nozzles.Select(x=>x.EquipmentInterface.StableId)).Concat(segments.SelectMany(x=>new[]{x.StartInterface,x.EndInterface})).Concat(fittings.SelectMany(x=>x.Interfaces.Select(i=>i.StableId))).Distinct().ToArray();+ var assembly=new PipingAssemblyIr(root,parsed.Name,definitions.Select(x=>x.StableId).ToArray(),occurrences.Skip(1).Select(x=>x.StableId).ToArray(),assemblyInterfaces);+ var report=new PipingReport("aetheris:piping:x3a",parsed.Name,assembly,parsed.Policies,parsed.Equipment,parsed.Ports,parsed.Connections,parsed.KeepOuts,proposals,routes,segments,fittings,nozzles,mates,exemptions,bom,cut,+ clearance,geometryClear,bodies.All(IsEnclosed),bodies.Length,surfaces.Count(x=>x==SurfaceGeometryKind.Cylinder),surfaces.Count(x=>x==SurfaceGeometryKind.Torus),surfaces.Count(x=>x==SurfaceGeometryKind.Plane),+ bounds,hash,true,+ "PipingSystem->EquipmentPort/Nozzle->Connection->RouteRequest/ExplicitRoute->RouteProposal->AcceptedRoute->PipeSegments+Fittings->Mates->Assembly->BOM/CutList->AP242",null,null,null,+ new(parseClock.Elapsed.TotalMilliseconds,obstacleClock.Elapsed.TotalMilliseconds,routeClock.Elapsed.TotalMilliseconds,simplifyClock.Elapsed.TotalMilliseconds,fittingClock.Elapsed.TotalMilliseconds,brepClock.Elapsed.TotalMilliseconds));+ return new(true,step.Value,report,[],segments,fittings,nozzles);+ }++ public static string RoutingJson(PipingReport r)=>JsonSerializer.Serialize(new{schema="aetheris:piping-routing:x3a",pipingSystem=r.PipingSystem,equipment=r.Equipment,ports=r.Ports,nozzles=r.Nozzles,mates=r.Mates,keepOutExemptions=r.KeepOutExemptions,routes=r.Routes.Select(x=>new{x.StableId,x.Connection,provenance=x.Provenance.ToString(),anchors=x.Anchors.Select(a=>new{a.Ordinal,kind=a.Kind.ToString(),point=new[]{a.Point.X,a.Point.Y,a.Point.Z},a.Locked}),segments=x.Segments,turns=x.Turns}),r.MinimumVerifiedClearanceMm},JsonOptions);+ public static string CutListJson(PipingReport r)=>JsonSerializer.Serialize(new{schema="aetheris:pipe-cut-list:x3",units=new{length="mm"},pipingSystem=r.PipingSystem,entries=r.CutList},JsonOptions);+ public static string BomJson(PipingReport r)=>JsonSerializer.Serialize(new{schema="aetheris:piping-bom:x3a",pipingSystem=r.PipingSystem,entries=r.Bom},JsonOptions);+ private static readonly JsonSerializerOptions JsonOptions=new(){WriteIndented=true,PropertyNamingPolicy=JsonNamingPolicy.CamelCase};++ private sealed record Parsed(string Name,IReadOnlyList<PipePolicyIr> Policies,IReadOnlyList<PipingEquipmentIr> Equipment,IReadOnlyList<PipingPortInterfaceIr> Ports,IReadOnlyList<PipingConnectionIr> Connections,IReadOnlyList<KeepOutIr> KeepOuts,IReadOnlyList<RouteIr> Routes,IReadOnlyList<AcceptedRequest> Requests,IReadOnlyList<RerouteSpec> Reroutes,double DefaultClearance);+ private sealed record AcceptedRequest(RouteRequestIr Request,string AcceptAs);+ private sealed record RerouteSpec(string Name,string Route,int FromAnchor,int ToAnchor,IReadOnlyList<string>Avoid,double Clearance);+ private readonly record struct Block(string Name,string Body);++ private static Parsed? Parse(string source,string sourceIdentity,List<string>d)+ {+ var systems=Blocks(source,"PipingSystem");if(systems.Count!=1){d.Add("piping-system-cardinality: exactly one PipingSystem is required");return null;}var system=systems[0];+ var defaultClear=Blocks(source,"RouteSpace").Select(x=>Length(Field(x.Body,"Clearance",false),25,d,"route-space:"+x.Name)).FirstOrDefault();if(defaultClear==0)defaultClear=25;+ var policies=new List<PipePolicyIr>();foreach(var b in Blocks(source,"PipePolicy")){var od=Length(Field(b.Body,"OuterDiameter"),0,d,b.Name);var wall=Length(Field(b.Body,"WallThickness"),0,d,b.Name);var material=Field(b.Body,"Material").Trim('"');if(od<=0||wall<=0)d.Add($"piping-pipe-policy-positive:{b.Name}");if(2*wall>=od)d.Add($"piping-pipe-wall-too-thick:{b.Name}");var resolved=new MaterialResolver().Resolve(material);if(!resolved.IsSuccess)d.Add($"piping-material-unresolved:{b.Name}:{material}");policies.Add(new($"standard:piping:pipe:{Q(od)}:{Q(wall)}:{material}",b.Name,od,wall,material));}Duplicates(policies.Select(x=>x.Name),"pipe-policy",d);+ var keepouts=new List<KeepOutIr>();foreach(var b in Blocks(source,"KeepOut")){var min=Point(Field(b.Body,"Min"),d,"keepout:"+b.Name);var max=Point(Field(b.Body,"Max"),d,"keepout:"+b.Name);if(max.X<=min.X||max.Y<=min.Y||max.Z<=min.Z)d.Add($"piping-keepout-invalid-bounds:{b.Name}");keepouts.Add(new($"concept:keepout:{b.Name}",b.Name,min,max,Field(b.Body,"Concept",false) is var c&&c.Length>0?c:"KeepOut"));}Duplicates(keepouts.Select(x=>x.Name),"keepout",d);+ var equipment=new List<PipingEquipmentIr>();foreach(var b in Blocks(source,"Equipment")){var keepOut=Field(b.Body,"KeepOut");if(!keepouts.Any(x=>x.Name==keepOut))d.Add($"piping-equipment-unknown-keepout:{b.Name}:{keepOut}");equipment.Add(new($"equipment:{b.Name}",b.Name,keepOut));}Duplicates(equipment.Select(x=>x.Name),"equipment",d);+ var ports=new List<PipingPortInterfaceIr>();foreach(var b in Blocks(source,"Port")){var policy=Field(b.Body,"PipePolicy");if(!policies.Any(x=>x.Name==policy))d.Add($"piping-port-unknown-policy:{b.Name}:{policy}");var position=Point(Field(b.Body,"Position"),d,"port:"+b.Name);var direction=Vector(Field(b.Body,"Direction"),d,"port:"+b.Name);if(!Axis(direction))d.Add($"piping-port-direction-nonorthogonal:{b.Name}");if(!Enum.TryParse<PipingConnectionType>(Field(b.Body,"ConnectionType",false) is var ct&&ct.Length>0?ct:"Generic",out var type))d.Add($"piping-port-connection-type-unsupported:{b.Name}");var owner=Field(b.Body,"Equipment",false);var nozzleLength=Length(Field(b.Body,"NozzleLength",false),0,d,"port:"+b.Name);string? ownerKeepOut=null;if(owner.Length>0){var e=equipment.SingleOrDefault(x=>x.Name==owner);if(e is null)d.Add($"piping-port-unknown-equipment:{b.Name}:{owner}");else ownerKeepOut=e.KeepOut;if(nozzleLength<=0)d.Add($"piping-nozzle-length-invalid:{b.Name}");}else if(nozzleLength>0)d.Add($"piping-nozzle-owner-required:{b.Name}");ports.Add(new($"interface:port:{b.Name}",b.Name,position,direction,policy,type,$"datum-frame:port:{b.Name}",owner.Length>0?owner:null,ownerKeepOut,nozzleLength));}Duplicates(ports.Select(x=>x.Name),"port",d);+ var connections=new List<PipingConnectionIr>();foreach(var b in Blocks(source,"Connection")){var from=Field(b.Body,"From");var to=Field(b.Body,"To");var policy=Field(b.Body,"PipePolicy");var fp=ports.SingleOrDefault(x=>x.Name==from);var tp=ports.SingleOrDefault(x=>x.Name==to);if(fp is null||tp is null){d.Add($"piping-connection-unknown-port:{b.Name}");continue;}if(!policies.Any(x=>x.Name==policy)){d.Add($"piping-connection-unknown-policy:{b.Name}:{policy}");continue;}var reducer=fp.PipePolicy!=tp.PipePolicy;var adapter=fp.ConnectionType!=tp.ConnectionType;if(reducer&&!Bool(Field(b.Body,"Reducer",false)))d.Add($"piping-incompatible-port:{b.Name}: different pipe policies require Reducer: true");if(adapter&&!Bool(Field(b.Body,"Adapter",false)))d.Add($"piping-incompatible-port:{b.Name}: connection styles require Adapter: true");connections.Add(new($"connection:{b.Name}",b.Name,from,to,policy,Field(b.Body,"Service",false).Trim('"') is var s&&s.Length>0?s:null,reducer,adapter));}Duplicates(connections.Select(x=>x.Name),"connection",d);+ var routes=new List<RouteIr>();foreach(var b in Blocks(source,"Route")){var connection=connections.SingleOrDefault(x=>x.Name==Field(b.Body,"Connection"));if(connection is null){d.Add($"piping-route-unknown-connection:{b.Name}");continue;}var points=Points(Field(b.Body,"Through"),d,"route:"+b.Name);var from=ports.Single(x=>x.Name==connection.FromPort);var to=ports.Single(x=>x.Name==connection.ToPort);if(points.Count==0||!Near(points[0],from.Position)||!Near(points[^1],to.Position))d.Add($"piping-route-endpoints-mismatch:{b.Name}");var anchors=points.Select((p,i)=>new RouteAnchorIr($"route:{b.Name}:anchor:{i}",i,p,i==0||i==points.Count-1?RouteAnchorKind.Endpoint:RouteAnchorKind.HardWaypoint)).ToArray();var locks=Ints(Field(b.Body,"LockedSegments",false));var provenance=Enum.TryParse<RouteProvenance>(Field(b.Body,"Provenance",false),out var pv)?pv:RouteProvenance.Explicit;var bend=Length(Field(b.Body,"BendRadius",false),Math.Max(50,policies.Single(x=>x.Name==connection.PipePolicy).OuterDiameterMm*2),d,b.Name);routes.Add(OrthogonalAutoRouter.BuildRoute(b.Name,connection.Name,from.StableId,to.StableId,anchors,bend,provenance,sourceIdentity,locks));}+ var provisional=new Parsed(system.Name,policies,equipment,ports,connections,keepouts,routes,[],[],defaultClear);+ var requests=new List<AcceptedRequest>();foreach(var b in Blocks(source,"RouteRequest")){var connection=connections.SingleOrDefault(x=>x.Name==Field(b.Body,"Connection"));if(connection is null){d.Add($"piping-route-request-unknown-connection:{b.Name}");continue;}var clearance=Length(Field(b.Body,"Clearance",false),defaultClear,d,b.Name);var bend=Length(Field(b.Body,"BendRadius",false),Math.Max(50,policies.Single(x=>x.Name==connection.PipePolicy).OuterDiameterMm*2),d,b.Name);var req=RequestFor(connection,provisional,b.Name,clearance) with{HardWaypoints=Points(Field(b.Body,"HardWaypoints",false),d,"request:"+b.Name),BendRadiusMm=bend};requests.Add(new(req,Field(b.Body,"AcceptAs",false)));}+ var reroutes=new List<RerouteSpec>();foreach(var b in Blocks(source,"LocalReroute")){if(!int.TryParse(Field(b.Body,"FromAnchor"),out var from)||!int.TryParse(Field(b.Body,"ToAnchor"),out var to)){d.Add($"piping-local-reroute-anchor-invalid:{b.Name}");continue;}reroutes.Add(new(b.Name,Field(b.Body,"Route"),from,to,Names(Field(b.Body,"Avoid",false)),Length(Field(b.Body,"Clearance",false),defaultClear,d,b.Name)));}+ return provisional with{Requests=requests,Reroutes=reroutes};+ }++ private static RouteRequestIr RequestFor(PipingConnectionIr c,Parsed p,string name,double clearance)=>new($"route-request:{name}",name,c.Name,p.Ports.Single(x=>x.Name==c.FromPort),p.Ports.Single(x=>x.Name==c.ToPort),p.Policies.Single(x=>x.Name==c.PipePolicy),p.KeepOuts,clearance,[]);+ private static void ValidateNozzleContracts(Parsed p,List<string>d)+ {+ foreach(var port in p.Ports.Where(x=>x.Equipment is not null))+ {+ if(port.OwnerKeepOut is null)continue;+ var owner=p.KeepOuts.SingleOrDefault(x=>x.Name==port.OwnerKeepOut);if(owner is null)continue;+ var u=port.OutwardDirection/port.OutwardDirection.Length;var root=port.Position-u*port.NozzleLengthMm;+ if(!OnOutwardFace(root,u,owner))d.Add($"piping-nozzle-root-not-on-owner-face:{port.Name}:{owner.Name}");+ if(InsideOpen(port.Position,owner))d.Add($"piping-nozzle-tip-inside-owner:{port.Name}:{owner.Name}");+ }+ }+ private static IReadOnlyList<PipingMateIr> BuildEndpointMates(IReadOnlyList<RouteIr> routes,Parsed p,IReadOnlyList<PipeSegmentComponentIr> segments,IReadOnlyList<EquipmentNozzleComponentIr> nozzles,List<string>d)+ {+ var result=new List<PipingMateIr>();+ foreach(var route in routes)+ {+ var connection=p.Connections.Single(x=>x.Name==route.Connection);var first=segments.Single(x=>x.Route==route.Name&&x.Ordinal==0);var last=segments.Single(x=>x.Route==route.Name&&x.Ordinal==route.Segments.Count-1);+ Add(p.Ports.Single(x=>x.Name==connection.FromPort),first.StartInterface,route.Anchors[0].Point,-Unit(route.Anchors[1].Point-route.Anchors[0].Point),"From",route.Name);+ Add(p.Ports.Single(x=>x.Name==connection.ToPort),last.EndInterface,route.Anchors[^1].Point,Unit(route.Anchors[^1].Point-route.Anchors[^2].Point),"To",route.Name);+ }+ return result;+ void Add(PipingPortInterfaceIr port,string pipeInterface,Point3D pipePosition,Vector3D pipeOutward,string end,string routeName)+ {+ if(port.Equipment is null)return;var nozzle=nozzles.SingleOrDefault(x=>x.Port==port.Name);+ if(nozzle is null){d.Add($"piping-nozzle-missing:{port.Name}");return;}+ var coincident=Near(nozzle.PipeInterface.Position,pipePosition);var opposed=(nozzle.PipeInterface.OutwardDirection+pipeOutward).Length<=Tol;+ if(!coincident)d.Add($"piping-port-mate-not-coincident:{port.Name}:{end}");if(!opposed)d.Add($"piping-port-mate-direction-mismatch:{port.Name}:{end}");+ result.Add(new($"mate:{port.Name}:{routeName}",port.Name,nozzle.PipeInterface.StableId,pipeInterface,pipePosition,nozzle.PipeInterface.OutwardDirection,pipeOutward,coincident,opposed));+ }+ }+ private static double RequiredClearanceForPort(Parsed p,string port)+ {+ var connections=p.Connections.Where(x=>x.FromPort==port||x.ToPort==port).Select(x=>x.Name).ToHashSet(StringComparer.Ordinal);+ return p.Requests.Where(x=>connections.Contains(x.Request.Connection)).Select(x=>x.Request.ClearanceMm).Append(p.DefaultClearance).Max();+ }+ private static void ValidateRoutes(IReadOnlyList<RouteIr> routes,Parsed p,List<string>d)+ {+ Duplicates(routes.Select(x=>x.Name),"route",d);foreach(var r in routes){var c=p.Connections.Single(x=>x.Name==r.Connection);var policy=p.Policies.Single(x=>x.Name==c.PipePolicy);if(r.Anchors.Count<2){d.Add($"piping-route-too-short:{r.Name}");continue;}for(var i=0;i<r.Segments.Count;i++){var a=r.Anchors[i].Point;var b=r.Anchors[i+1].Point;if(!Axis(b-a))d.Add($"piping-route-nonorthogonal:{r.Name}:segment:{i}");}var first=r.Anchors[1].Point-r.Anchors[0].Point;var last=r.Anchors[^1].Point-r.Anchors[^2].Point;var from=p.Ports.Single(x=>x.Name==c.FromPort);var to=p.Ports.Single(x=>x.Name==c.ToPort);if(!Parallel(first,from.OutwardDirection)||Dot(first,from.OutwardDirection)<0)d.Add($"piping-endpoint-direction-impossible:{r.Name}:start");if(!Parallel(last,-to.OutwardDirection)||Dot(last,-to.OutwardDirection)<0)d.Add($"piping-endpoint-direction-impossible:{r.Name}:end");var bend=r.Turns.FirstOrDefault()?.BendRadiusMm??50;foreach(var segment in r.Segments)if(segment.LengthMm<=bend*((segment.Ordinal>0?1:0)+(segment.Ordinal<r.Segments.Count-1?1:0))+Tol)d.Add($"piping-route-bend-spacing-insufficient:{r.Name}:segment:{segment.Ordinal}");var required=p.Requests.FirstOrDefault(x=>x.Request.Connection==r.Connection)?.Request.ClearanceMm??p.DefaultClearance;var actual=OrthogonalAutoRouter.MinimumMaterializedClearance(r.Anchors.Select(x=>x.Point).ToArray(),p.KeepOuts,policy.RadiusMm,bend);if(actual+Tol<required)d.Add(actual<=Tol?$"piping-route-through-keepout:{r.Name}: verified {actual:G6}mm, required {required:G6}mm":$"piping-insufficient-clearance:{r.Name}: verified {actual:G6}mm, required {required:G6}mm");}}+ private static RouteIr Canonicalize(RouteIr r){var points=OrthogonalAutoRouter.Simplify(r.Anchors.Select(x=>x.Point).ToArray());if(points.Count==r.Anchors.Count)return r;var a=points.Select((p,i)=>new RouteAnchorIr($"route:{r.Name}:anchor:{i}",i,p,i==0||i==points.Count-1?RouteAnchorKind.Endpoint:RouteAnchorKind.AutoWaypoint)).ToArray();return OrthogonalAutoRouter.BuildRoute(r.Name,r.Connection,r.StartInterface,r.EndInterface,a,r.Turns.FirstOrDefault()?.BendRadiusMm??50,r.Provenance,r.SourceProvenance,[]);}+ private static IReadOnlyList<PipingBomEntry> BuildBom(IReadOnlyList<PipeSegmentComponentIr>s,IReadOnlyList<PipingFittingComponentIr>f,IReadOnlyList<EquipmentNozzleComponentIr>n)=>s.GroupBy(x=>new{x.PipePolicy,x.Material}).Select(g=>new PipingBomEntry("Standard.Piping.Pipe",g.Key.PipePolicy,g.Key.Material,g.Count(),g.Select(x=>x.StableId).Order().ToArray())).Concat(f.GroupBy(x=>new{x.ProductIdentity,x.PipePolicy}).Select(g=>new PipingBomEntry(g.Key.ProductIdentity,g.Key.PipePolicy,"AsSpecifiedByPipePolicy",g.Count(),g.Select(x=>x.StableId).Order().ToArray()))).Concat(n.GroupBy(x=>x.PipePolicy).Select(g=>new PipingBomEntry("Standard.Piping.NozzleStub",g.Key,"AsSpecifiedByPipePolicy",g.Count(),g.Select(x=>x.StableId).Order().ToArray()))).OrderBy(x=>x.ProductIdentity).ThenBy(x=>x.PipePolicy).ToArray();+ private static IReadOnlyList<PipeCutListEntry> BuildCutList(IReadOnlyList<PipePolicyIr>p,IReadOnlyList<PipeSegmentComponentIr>s)=>s.GroupBy(x=>new{x.PipePolicy,x.Material,Length=Q(x.CutLengthMm)}).Select((g,i)=>{var policy=p.Single(x=>x.StableId==g.Key.PipePolicy);return new PipeCutListEntry($"pipe-cut-group:{i+1}",g.Key.PipePolicy,policy.OuterDiameterMm,policy.WallThicknessMm,g.Key.Material,g.First().CutLengthMm,g.Count(),g.Select(x=>x.StableId).Order().ToArray());}).OrderBy(x=>x.PipePolicy).ThenBy(x=>x.CutLengthMm).ToArray();+ private static IEnumerable<Point3D> BodyPoints(BrepBody b)=>b.Topology.Vertices.Select(v=>b.TryGetVertexPoint(v.Id,out var p)?p:default);+ private static bool IsEnclosed(BrepBody b)=>b.ShellRepresentation is not null&&b.Topology.Edges.All(e=>{var uses=b.Topology.Coedges.Count(c=>c.EdgeId==e.Id);return uses>=2&&uses%2==0;});+ 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 close=Matching(source,open);if(close>open)result.Add(new(m.Groups["n"].Value,source[(open+1)..close]));}return result;}+ private static int Matching(string s,int open){var depth=0;for(var i=open;i<s.Length;i++){if(s[i]=='{')depth++;else if(s[i]=='}'&&--depth==0)return i;}return-1;}+ private static string Field(string body,string name,bool required=true){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[^;]+);",RegexOptions.CultureInvariant);return m.Success?m.Groups["v"].Value.Trim():required?"":"";}+ private static double Length(string value,double fallback,List<string>d,string owner){if(string.IsNullOrWhiteSpace(value))return fallback;var n=value.Replace("mm","",StringComparison.Ordinal).Trim();if(double.TryParse(n,NumberStyles.Float,CultureInfo.InvariantCulture,out var x)&&double.IsFinite(x))return x;d.Add($"piping-length-invalid:{owner}:{value}");return fallback;}+ private static Point3D Point(string value,List<string>d,string owner){var v=Vector(value,d,owner);return new(v.X,v.Y,v.Z);}+ private static Vector3D Vector(string value,List<string>d,string owner){var parts=value.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);if(parts.Length!=3){d.Add($"piping-vector-invalid:{owner}:{value}");return default;}var values=parts.Select(x=>Length(x,0,d,owner)).ToArray();return new(values[0],values[1],values[2]);}+ private static IReadOnlyList<Point3D> Points(string value,List<string>d,string owner)=>Regex.Matches(value??"",@"\[(?<p>[^\[\]]+)\]").Select(m=>Point(m.Groups["p"].Value,d,owner)).ToArray();+ private static IReadOnlyList<int> Ints(string v)=>v.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries).Select(x=>int.TryParse(x,out var n)?n:-1).Where(x=>x>=0).ToArray();+ private static IReadOnlyList<string> Names(string v)=>v.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Trim('"')).ToArray();+ private static bool Bool(string v)=>string.Equals(v,"true",StringComparison.OrdinalIgnoreCase);+ private static bool Axis(Vector3D v)=>new[]{Math.Abs(v.X)>Tol,Math.Abs(v.Y)>Tol,Math.Abs(v.Z)>Tol}.Count(x=>x)==1;+ private static bool Parallel(Vector3D a,Vector3D b)=>a.Cross(b).Length<=Tol;+ private static double Dot(Vector3D a,Vector3D b)=>a.Dot(b);+ private static bool Near(Point3D a,Point3D b)=>(b-a).Length<=Tol;+ private static Vector3D Unit(Vector3D v)=>v/v.Length;+ private static bool InsideOpen(Point3D p,KeepOutIr b)=>p.X>b.Minimum.X+Tol&&p.X<b.Maximum.X-Tol&&p.Y>b.Minimum.Y+Tol&&p.Y<b.Maximum.Y-Tol&&p.Z>b.Minimum.Z+Tol&&p.Z<b.Maximum.Z-Tol;+ private static bool OnOutwardFace(Point3D p,Vector3D u,KeepOutIr b)+ {+ bool Within(double value,double min,double max)=>value>=min-Tol&&value<=max+Tol;+ if(Math.Abs(u.X)>Tol)return Math.Abs(p.X-(u.X>0?b.Maximum.X:b.Minimum.X))<=Tol&&Within(p.Y,b.Minimum.Y,b.Maximum.Y)&&Within(p.Z,b.Minimum.Z,b.Maximum.Z);+ if(Math.Abs(u.Y)>Tol)return Math.Abs(p.Y-(u.Y>0?b.Maximum.Y:b.Minimum.Y))<=Tol&&Within(p.X,b.Minimum.X,b.Maximum.X)&&Within(p.Z,b.Minimum.Z,b.Maximum.Z);+ return Math.Abs(p.Z-(u.Z>0?b.Maximum.Z:b.Minimum.Z))<=Tol&&Within(p.X,b.Minimum.X,b.Maximum.X)&&Within(p.Y,b.Minimum.Y,b.Maximum.Y);+ }+ private static void Duplicates(IEnumerable<string>v,string k,List<string>d){foreach(var g in v.GroupBy(x=>x,StringComparer.Ordinal).Where(x=>x.Count()>1))d.Add($"piping-duplicate-{k}:{g.Key}");}+ private static long Q(double x)=>(long)Math.Round(x*1_000_000,MidpointRounding.AwayFromZero);+}diff --git a/Aetheris.Kernel.Firmament/Piping/PipingGeometry.cs b/Aetheris.Kernel.Firmament/Piping/PipingGeometry.csnew file mode 100644index 00000000..a991d9b1--- /dev/null+++ b/Aetheris.Kernel.Firmament/Piping/PipingGeometry.cs@@ -0,0 +1,97 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Numerics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Kernel.StandardLibrary.Materials;++namespace Aetheris.Kernel.Firmament.Piping;++internal static class PipingGeometry+{+ private static readonly ToleranceContext Tolerance = ToleranceContext.Default;++ public static KernelResult<BrepBody> Pipe(Point3D start, Point3D end, PipePolicyIr policy)+ {+ var delta = end - start;+ if (delta.Length <= Tolerance.Linear) return Fail("piping-pipe-segment-zero-length");+ var z = Direction3D.Create(delta);+ var reference = Math.Abs(z.ToVector().Z) < .9 ? new Vector3D(0,0,1) : new Vector3D(0,1,0);+ var x = Direction3D.Create(reference.Cross(z.ToVector()));+ var y = Direction3D.Create(z.ToVector().Cross(x.ToVector()));+ var outer = policy.OuterDiameterMm / 2d;+ var inner = policy.InnerDiameterMm / 2d;+ var loops = new List<LineArcProfileLoop2D> { new([new LineArcFullCircle2D((0,0), outer)], false) };+ if (inner > Tolerance.Linear) loops.Add(new([new LineArcFullCircle2D((0,0), inner)], true));+ var plane = new ConstructionPlane("piping-pipe-frame", "route-segment", start, x, y, z, "piping-route", "semantic-pipe-segment");+ var plan = ProfileExtrusionBRepPlanner.TryPlan(new(loops, delta.Length, plane, 0, delta.Length));+ if (!plan.Succeeded || plan.Plan is null) return Fail("piping-pipe-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("piping-pipe-materialization-failed: " + string.Join("; ", materialized.Diagnostics));+ }++ public static KernelResult<BrepBody> Elbow(Point3D corner, Vector3D incoming, Vector3D outgoing, PipePolicyIr policy, double bendRadius)+ {+ var u = Unit(incoming); var v = Unit(outgoing);+ if (Math.Abs(u.Dot(v)) > Tolerance.Angular) return Fail("piping-elbow-nonorthogonal");+ var built = CanonicalHollowElbow(policy, bendRadius);+ if (!built.IsSuccess || built.Value is null) return built;++ var worldX = -v; var worldY = u; var worldZ = worldX.Cross(worldY);+ var center = corner - u * bendRadius + v * bendRadius;+ var transform = Transform3D.FromRowMajor([+ worldX.X,worldX.Y,worldX.Z,0,+ worldY.X,worldY.Y,worldY.Z,0,+ worldZ.X,worldZ.Y,worldZ.Z,0,+ center.X,center.Y,center.Z,1]);+ return KernelResult<BrepBody>.Success(FirmasmAssemblyExecutor.TransformBody(built.Value, transform));+ }++ public static KernelResult<BrepBody> Proxy(KeepOutIr keepOut)+ {+ var size = keepOut.Maximum - keepOut.Minimum;+ var box = BrepPrimitives.CreateBox(size.X, size.Y, size.Z);+ if (!box.IsSuccess || box.Value is null) return box;+ var center = new Point3D((keepOut.Minimum.X+keepOut.Maximum.X)/2, (keepOut.Minimum.Y+keepOut.Maximum.Y)/2, (keepOut.Minimum.Z+keepOut.Maximum.Z)/2);+ return KernelResult<BrepBody>.Success(FirmasmAssemblyExecutor.TransformBody(box.Value, Transform3D.CreateTranslation(center - new Point3D(0,0,0))));+ }++ public static (Point3D Start, Point3D End) TrimmedRun(IReadOnlyList<RouteAnchorIr> anchors, int segment, double bendRadius)+ {+ var a=anchors[segment].Point;var b=anchors[segment+1].Point;var direction=Unit(b-a);+ var start=segment==0?a:a+direction*bendRadius;+ var end=segment==anchors.Count-2?b:b-direction*bendRadius;+ return(start,end);+ }++ private static Vector3D Unit(Vector3D v) => v / v.Length;+ private static KernelResult<BrepBody> CanonicalHollowElbow(PipePolicyIr policy,double bendRadius)+ {+ var ro=policy.RadiusMm;var ri=policy.InnerDiameterMm/2;+ if(ri<=Tolerance.Linear||bendRadius<=ro+Tolerance.Linear)return Fail("piping-elbow-policy-invalid");+ var b=new TopologyBuilder();var os=b.AddVertex();var oe=b.AddVertex();var ins=b.AddVertex();var ine=b.AddVertex();+ var osr=b.AddEdge(os,os);var oer=b.AddEdge(oe,oe);var isr=b.AddEdge(ins,ins);var ier=b.AddEdge(ine,ine);var oseam=b.AddEdge(os,oe);var iseam=b.AddEdge(ins,ine);+ var outer=AddFace(b,[[(oseam,false),(oer,false),(oseam,true),(osr,true)]]);+ var inner=AddFace(b,[[(iseam,true),(isr,false),(iseam,false),(ier,true)]]);+ var start=AddFace(b,[[(osr,false)],[(isr,true)]]);var end=AddFace(b,[[(oer,true)],[(ier,false)]]);+ var shell=b.AddShell([outer,inner,start,end]);b.AddBody([shell]);+ var points=new Dictionary<VertexId,Point3D>{{os,new(bendRadius,0,ro)},{oe,new(0,bendRadius,ro)},{ins,new(bendRadius,0,ri)},{ine,new(0,bendRadius,ri)}};+ var g=new BrepGeometryStore();var bindings=new BrepBindingModel();var cy=Direction3D.Create(new Vector3D(0,1,0));var nx=Direction3D.Create(new Vector3D(-1,0,0));var z=Direction3D.Create(new Vector3D(0,0,1));var x=Direction3D.Create(new Vector3D(1,0,0));+ AddCircle(osr,new(bendRadius,0,0),cy,ro,z,0,2*Math.PI,1);AddCircle(oer,new(0,bendRadius,0),nx,ro,z,0,2*Math.PI,2);AddCircle(isr,new(bendRadius,0,0),cy,ri,z,0,2*Math.PI,3);AddCircle(ier,new(0,bendRadius,0),nx,ri,z,0,2*Math.PI,4);AddCircle(oseam,new(0,0,ro),z,bendRadius,x,0,Math.PI/2,5);AddCircle(iseam,new(0,0,ri),z,bendRadius,x,0,Math.PI/2,6);+ AddSurface(outer,SurfaceGeometry.FromTorus(new TorusSurface(new(0,0,0),z,bendRadius,ro,x)),1);AddSurface(inner,SurfaceGeometry.FromTorus(new TorusSurface(new(0,0,0),z,bendRadius,ri,x)),2);AddSurface(start,SurfaceGeometry.FromPlane(new PlaneSurface(new(bendRadius,0,0),Direction3D.Create(new Vector3D(0,-1,0)),z)),3);AddSurface(end,SurfaceGeometry.FromPlane(new PlaneSurface(new(0,bendRadius,0),nx,z)),4);+ var body=new BrepBody(b.Model,g,bindings,points);var valid=BrepBindingValidator.Validate(body,true);return valid.IsSuccess?KernelResult<BrepBody>.Success(body):KernelResult<BrepBody>.Failure(valid.Diagnostics);+ void AddCircle(EdgeId edge,Point3D center,Direction3D normal,double radius,Direction3D axis,double from,double to,int id){var cid=new CurveGeometryId(id);g.AddCurve(cid,CurveGeometry.FromCircle(new Circle3Curve(center,normal,radius,axis)));bindings.AddEdgeBinding(new(edge,cid,new ParameterInterval(from,to)));}+ void AddSurface(FaceId face,SurfaceGeometry surface,int id){var sid=new SurfaceGeometryId(id);g.AddSurface(sid,surface);bindings.AddFaceBinding(new(face,sid));}+ }+ private static FaceId AddFace(TopologyBuilder b,IReadOnlyList<IReadOnlyList<(EdgeId Edge,bool Reverse)>> loops)=>b.AddFace(loops.Select(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;}).ToArray());+ private static KernelResult<BrepBody> Fail(string message) => KernelResult<BrepBody>.Failure([new(+ Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Piping.X3.Geometry")]);+}diff --git a/Aetheris.Kernel.Firmament/Piping/PipingModels.cs b/Aetheris.Kernel.Firmament/Piping/PipingModels.csnew file mode 100644index 00000000..f670e78a--- /dev/null+++ b/Aetheris.Kernel.Firmament/Piping/PipingModels.cs@@ -0,0 +1,118 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Math;+using System.Text.Json.Serialization;++namespace Aetheris.Kernel.Firmament.Piping;++public enum RouteAnchorKind { Endpoint, HardWaypoint, AutoWaypoint }+public enum RouteProvenance { Explicit, AutoGenerated, LocallyRerouted }+public enum PipingConnectionType { Generic, Flange, Weld, Threaded }++public sealed record PipePolicyIr(string StableId, string Name, double OuterDiameterMm, double WallThicknessMm, string Material)+{+ public double RadiusMm => OuterDiameterMm / 2d;+ public double InnerDiameterMm => OuterDiameterMm - 2d * WallThicknessMm;+}++/// <summary>A piping port is an Assembly Interface with a bounded circular compatibility contract.</summary>+public sealed record PipingPortInterfaceIr(+ string StableId, string Name, Point3D Position, Vector3D OutwardDirection,+ string PipePolicy, PipingConnectionType ConnectionType, string DatumFrame,+ string? Equipment = null, string? OwnerKeepOut = null, double NozzleLengthMm = 0);++public sealed record PipingEquipmentIr(string StableId, string Name, string KeepOut);++public sealed record PipingConnectionIr(+ string StableId, string Name, string FromPort, string ToPort, string PipePolicy,+ string? Service, bool ReducerRequired, bool AdapterRequired);++public sealed record KeepOutIr(string StableId, string Name, Point3D Minimum, Point3D Maximum, string SourceConcept)+{+ public KeepOutIr Inflate(double distance) => new(StableId, Name,+ new(Minimum.X - distance, Minimum.Y - distance, Minimum.Z - distance),+ new(Maximum.X + distance, Maximum.Y + distance, Maximum.Z + distance), SourceConcept);+}++public sealed record RouteAnchorIr(string StableId, int Ordinal, Point3D Point, RouteAnchorKind Kind, bool Locked = false);+public sealed record RouteSegmentIr(string StableId, int Ordinal, string StartAnchor, string EndAnchor, double LengthMm, bool Locked);+public sealed record RouteTurnIr(string StableId, int AnchorOrdinal, string Fitting, double BendRadiusMm, double AngleDegrees = 90d);++public sealed record RouteIr(+ string StableId, string Name, string Connection, string StartInterface, string EndInterface,+ IReadOnlyList<RouteAnchorIr> Anchors, IReadOnlyList<RouteSegmentIr> Segments,+ IReadOnlyList<RouteTurnIr> Turns, IReadOnlyList<int> LockedSegmentOrdinals,+ RouteProvenance Provenance, string SourceProvenance)+{+ public double CenterlineLengthMm => Segments.Sum(x => x.LengthMm);+}++public sealed record RouteRequestIr(+ string StableId, string Name, string Connection, PipingPortInterfaceIr From, PipingPortInterfaceIr To,+ PipePolicyIr PipePolicy, IReadOnlyList<KeepOutIr> KeepOuts, double ClearanceMm,+ IReadOnlyList<Point3D> HardWaypoints, double BendRadiusMm = 50d);++public enum RouteFailureKind+{+ NoCollisionFreePath,+ EndpointDirectionImpossible,+ ClearanceTooLarge,+ HardWaypointUnreachable,+ RoutingRegionDisconnected,+ LockedIntervalPreventsSolution+}++public sealed record RouteProposalIr(+ string StableId, string Request, bool IsSuccess, IReadOnlyList<RouteAnchorIr> Anchors,+ double LengthMm, int ElbowCount, double MinimumClearanceMm, double Cost,+ IReadOnlyList<string> Diagnostics, RouteFailureKind? FailureKind,+ string Algorithm = "adaptive-coordinate-grid-a-star");++public sealed record PipeSegmentComponentIr(+ string StableId, string Route, int Ordinal, string PipePolicy, string Material,+ string StartInterface, string EndInterface, double CenterlineLengthMm, double CutLengthMm, [property: JsonIgnore] BrepBody Body);++public sealed record FittingInterfaceIr(string StableId, string Name, Point3D Position, Vector3D OutwardDirection);+public sealed record PipingFittingComponentIr(+ string StableId, string Route, int AnchorOrdinal, string ProductIdentity, string PipePolicy,+ IReadOnlyList<FittingInterfaceIr> Interfaces, [property: JsonIgnore] BrepBody Body);++public sealed record EquipmentNozzleComponentIr(+ string StableId, string Port, string Equipment, string OwnerKeepOut, string PipePolicy,+ Point3D RootPosition, Point3D TipPosition,+ FittingInterfaceIr EquipmentInterface, FittingInterfaceIr PipeInterface,+ [property: JsonIgnore] BrepBody Body);++public sealed record PipingMateIr(+ string StableId, string Port, string NozzleInterface, string PipeInterface,+ Point3D Position, Vector3D NozzleOutwardDirection, Vector3D PipeOutwardDirection,+ bool Coincident, bool DirectionsOpposed);++public sealed record PipingKeepOutExemptionIr(+ string StableId, string Port, string Nozzle, string KeepOut, string Scope);++public sealed record PipingBomEntry(string ProductIdentity, string PipePolicy, string Material, int Quantity, IReadOnlyList<string> Components);+public sealed record PipeCutListEntry(string GroupId, string PipePolicy, double OuterDiameterMm, double WallThicknessMm, string Material, double CutLengthMm, int Quantity, IReadOnlyList<string> Segments);+public sealed record PipingAssemblyIr(string StableId, string Name, IReadOnlyList<string> Definitions, IReadOnlyList<string> Occurrences, IReadOnlyList<string> Interfaces);+public sealed record PipingTimingReport(double ParseBindMilliseconds, double ObstaclePreparationMilliseconds, double GraphCreationAndSearchMilliseconds, double SimplificationMilliseconds, double FittingRealizationMilliseconds, double BrepAndStepMilliseconds);++public sealed record PipingReport(+ string Schema, string PipingSystem, PipingAssemblyIr Assembly,+ IReadOnlyList<PipePolicyIr> PipePolicies, IReadOnlyList<PipingEquipmentIr> Equipment,+ IReadOnlyList<PipingPortInterfaceIr> Ports,+ IReadOnlyList<PipingConnectionIr> Connections, IReadOnlyList<KeepOutIr> KeepOuts,+ IReadOnlyList<RouteProposalIr> RouteProposals, IReadOnlyList<RouteIr> Routes,+ IReadOnlyList<PipeSegmentComponentIr> PipeSegments, IReadOnlyList<PipingFittingComponentIr> Fittings,+ IReadOnlyList<EquipmentNozzleComponentIr> Nozzles, IReadOnlyList<PipingMateIr> Mates,+ IReadOnlyList<PipingKeepOutExemptionIr> KeepOutExemptions,+ IReadOnlyList<PipingBomEntry> Bom, IReadOnlyList<PipeCutListEntry> CutList,+ double MinimumVerifiedClearanceMm, bool GeometryClearanceVerified, bool ComponentsEnclosed,+ int BodyCount, int CylinderCount, int TorusCount, int PlaneCount, IReadOnlyList<double> Bounds,+ string StepSha256, bool StepReimportSucceeded, string MaterializationRoute,+ string? RoutingReportArtifactPath, string? CutListArtifactPath, string? BomArtifactPath,+ PipingTimingReport Timings);++public sealed record PipingCompilationResult(+ bool IsSuccess, string? StepText, PipingReport? Report, IReadOnlyList<string> Diagnostics,+ IReadOnlyList<PipeSegmentComponentIr>? RealizedSegments = null,+ IReadOnlyList<PipingFittingComponentIr>? RealizedFittings = null,+ IReadOnlyList<EquipmentNozzleComponentIr>? RealizedNozzles = null);diff --git a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmamentindex 73854a5f..d52f2b6d 100644--- a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament+++ b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament@@ -266,4 +266,55 @@ Model StandardProducts {Size: [4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm,4mm]}}++ // X3 generic dimensional piping products. These are intentionally not ASME/DIN claims;+ // the PipingSystem lowering binds the policies and realizes named assembly components.+ Record PipeProductPolicy { OuterDiameter: Length WallThickness: Length Material: String }+ Static StandardPipe: PipeProductPolicy = PipeProductPolicy { OuterDiameter: 25mm WallThickness: 2mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: PipeProductPolicy = StandardPipe>+ Struct PipeTemplate {+ Require PositiveDiameter => P.OuterDiameter > 0mm+ Require PositiveWall => P.WallThickness > 0mm+ Require WallFitsDiameter => P.WallThickness * 2 < P.OuterDiameter+ }++ Record Elbow90Policy { OuterDiameter: Length WallThickness: Length BendRadius: Length Material: String }+ Static StandardElbow90: Elbow90Policy = Elbow90Policy { OuterDiameter: 25mm WallThickness: 2mm BendRadius: 50mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: Elbow90Policy = StandardElbow90>+ Struct Elbow90Template {+ Require PositiveDiameter => P.OuterDiameter > 0mm+ Require WallFitsDiameter => P.WallThickness > 0mm && P.WallThickness < P.OuterDiameter / 2+ Require BendClearsPipe => P.BendRadius > P.OuterDiameter / 2+ }++ Record TeePolicy { RunOuterDiameter: Length BranchOuterDiameter: Length WallThickness: Length Material: String }+ Static StandardTee: TeePolicy = TeePolicy { RunOuterDiameter: 25mm BranchOuterDiameter: 25mm WallThickness: 2mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: TeePolicy = StandardTee>+ Struct TeeTemplate {+ Require PositiveRun => P.RunOuterDiameter > 0mm+ Require PositiveBranch => P.BranchOuterDiameter > 0mm+ Require WallFitsRun => P.WallThickness > 0mm && P.WallThickness * 2 < P.RunOuterDiameter+ }++ Record PumpSkidPolicy { OuterDiameter: Length WallThickness: Length Clearance: Length Material: String }+ Static StandardPumpSkid: PumpSkidPolicy = PumpSkidPolicy { OuterDiameter: 25mm WallThickness: 2mm Clearance: 30mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: PumpSkidPolicy = StandardPumpSkid>+ Struct PumpSkidTemplate {+ Require PositiveDiameter => P.OuterDiameter > 0mm+ Require PositiveWall => P.WallThickness > 0mm+ Require NonnegativeClearance => P.Clearance >= 0mm+ PipingSystem PumpCoolingSkid {+ PipePolicy ProcessPipe { OuterDiameter: P.OuterDiameter; WallThickness: P.WallThickness; Material: P.Material; }+ Port PumpDischarge { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: ProcessPipe; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }+ Port CoolerInlet { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: ProcessPipe; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }+ Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: ProcessPipe; Service: "CoolingSupply"; }+ KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }+ KeepOut PumpBody { Min: [-100mm,-100mm,-100mm]; Max: [-50mm,100mm,100mm]; Concept: EquipmentProxy; }+ KeepOut CoolerBody { Min: [1050mm,-100mm,-100mm]; Max: [1100mm,100mm,100mm]; Concept: EquipmentProxy; }+ Equipment Pump { KeepOut: PumpBody; }+ Equipment Cooler { KeepOut: CoolerBody; }+ RouteSpace SkidRouting { Clearance: P.Clearance; }+ RouteRequest SupplyRequest { Connection: Supply; Clearance: P.Clearance; BendRadius: 50mm; HardWaypoints: []; AcceptAs: SupplyRoute; }+ }+ }}diff --git a/docs/public/README.md b/docs/public/README.mdindex b8fee422..22b75bd5 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), [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)+- 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), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)- 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/piping.md b/docs/public/firmament/piping.mdnew file mode 100644index 00000000..66197f03--- /dev/null+++ b/docs/public/firmament/piping.md@@ -0,0 +1,163 @@+# Semantic piping and local autorouting++Aetheris X3/X3a separates connection intent from route geometry and hardens the equipment endpoint seam:++```text+PipingSystem → equipment-owned Port + Nozzle → Connection+→ explicit Route or RouteRequest → RouteProposal → accepted Route+→ endpoint Mate + PipeSegments + fittings → Assembly → BOM/Cut List → AP242+```++The router is a design assistant. `RouteProposal` is inspectable; acceptance copies its ordered anchors into an ordinary `RouteIr`. The accepted route retains provenance but no solver ownership. Rebuilding an explicit or previously materialized route does not invoke pathfinding.++## Ports and logical connections++`Port` is the piping specialization of an Assembly Interface. It has stable identity, a position/DatumFrame, an outward axis direction, a `PipePolicy`, and a bounded connection style.++```firmament+PipePolicy Pipe25 {+ OuterDiameter: 25mm;+ WallThickness: 2mm;+ Material: "Standard.Materials.StainlessSteel.304_Annealed";+}+Port PumpDischarge {+ Position: [100mm,100mm,250mm];+ Direction: [1,0,0];+ PipePolicy: Pipe25;+ ConnectionType: Flange;+ Equipment: Pump;+ NozzleLength: 50mm;+}+Connection Supply {+ From: PumpDischarge;+ To: CoolerInlet;+ PipePolicy: Pipe25;+ Service: "CoolingSupply";+}+```++Connections exist before routes. Different port policies require `Reducer: true`; different connection styles require `Adapter: true`. X3 records those requirements but does not claim a standards database.++Direct `PipePolicy` declarations require all three fields: `OuterDiameter`, `WallThickness`, and `Material`; there are no implicit dimensional or material defaults. Both dimensions must be positive and twice the wall thickness must be less than the OD.++## Equipment-owned nozzles and endpoint mates++X3a associates a port with one equipment proxy and materializes the gap between the equipment face and route endpoint as a hollow semantic nozzle occurrence:++```firmament+KeepOut PumpBody {+ Min: [0mm,0mm,0mm];+ Max: [50mm,300mm,350mm];+ Concept: EquipmentProxy;+}+Equipment Pump { KeepOut: PumpBody; }+Port PumpDischarge {+ Position: [100mm,100mm,250mm];+ Direction: [1,0,0];+ PipePolicy: Pipe25;+ ConnectionType: Flange;+ Equipment: Pump;+ NozzleLength: 50mm;+}+```++`Position` is the pipe-side mating plane. The nozzle root is `Position - Direction × NozzleLength` and must lie exactly on the outward face of the equipment's KeepOut. The nozzle exposes `EquipmentMate` at its root and the stable port Interface as `PipeMate` at its tip. The first or last pipe segment exposes its own endpoint Interface at the same position with the opposite outward direction; `PipingMateIr` records that coincidence and opposition explicitly.++The only clearance exemption is an inspectable `PipingKeepOutExemptionIr` scoped as `NozzleEnvelopeOnly` for that port's nozzle against that port's owning equipment KeepOut. It does not apply to the route, another port, another nozzle, or any foreign KeepOut. Thus a nozzle may touch its own equipment face while route and nozzle clearance remain fully enforced everywhere else.++The generic shipped product identities are `Standard.Piping.Pipe`, `Standard.Piping.Elbow90`, and `Standard.Piping.Tee`. Their dimensional policies are available from `Use Standard.Piping`. They are generic products, not ASME, DIN, or ISO parts.++## Explicit routes++An explicit route is an ordered axis-aligned 3D path. The first run must follow the source port's outward direction and the final run must approach opposite the destination's outward direction.++```firmament+Route SupplyRoute {+ Connection: Supply;+ Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]];+ BendRadius: 50mm;+ LockedSegments: [1];+ Provenance: Explicit;+}+```++Interior anchors become semantic 90-degree turns. Straight intervals lower to hollow `PipeSegment` components using the declared OD and wall. Each turn lowers to a hollow analytic-torus `Standard.Piping.Elbow90` occurrence with named `Inlet` and `Outlet` Interfaces. Pipe segments stop at elbow tangent points; cut length is therefore distinct from corner-to-corner route length.++For the admitted 90-degree route, a segment's cut length is its corner-to-corner interval minus one `BendRadius` for each adjacent interior turn: one radius at an end interval and two on an interval between two elbows. Validation rejects routes whose anchor spacing cannot accommodate those tangent setbacks.++## KeepOut, clearance, and autorouting++`KeepOut` is semantic obstacle geometry; names have no routing meaning. X3 uses conservative axis-aligned bounds for structural members, equipment proxies, and explicit service volumes.+An existing structural body is not implicitly routable space: author or generate a `KeepOut` from its conservative bounds. This makes avoidance semantic and inspectable instead of depending on object names.++```firmament+KeepOut Frame {+ Min: [400mm,-100mm,-100mm];+ Max: [600mm,100mm,100mm];+ Concept: StructureMember;+}+RouteSpace SkidRouting { Clearance: 30mm; }+RouteRequest SupplyRequest {+ Connection: Supply;+ Clearance: 30mm;+ BendRadius: 50mm;+ HardWaypoints: [];+ AcceptAs: SupplyRoute;+}+```++Forbidden centerline space is the obstacle bound inflated by pipe radius plus required clearance. Candidate search conservatively adds one bend radius to that planning inflation so an elbow torus cannot cut inside an otherwise valid sharp corner; the reported final clearance is then recomputed against the actual trimmed straights and torus centerlines without that extra planning margin. The deterministic router builds coordinates from endpoints, hard waypoints, and inflated obstacle faces, then searches the adjacent 3D coordinate graph with A*. Cost is route length plus a 1000 mm penalty per elbow, so small length savings do not add fittings. Neighbor order and priority tie-breaking are stable. Collinear search points are removed before the proposal is exposed.++`RouteSpace.Clearance` is the system default. `RouteRequest.Clearance`, when present, is the request-local value used for proposal and final verification; current fixtures repeat it deliberately so generated state remains self-evident. `AcceptAs` performs the explicit acceptance step and names the materialized ordinary route. Omit `AcceptAs` to inspect a proposal without adding route geometry. Search neighbor order is `+X, -X, +Y, -Y, +Z, -Z`; exact anchors also depend on port positions/directions, policy radius, bend radius, hard waypoints, and obstacle bounds.++`aetheris inspect source.firmament --json` reports proposals separately from accepted routes. A successful proposal includes anchors, length, elbow count, minimum clearance, cost, and diagnostics. Failures distinguish endpoint direction, hard-waypoint reachability, excessive clearance, disconnection, and lock conflicts.++## Local rerouting++`LocalReroute` authorizes one anchor interval:++```firmament+LocalReroute AroundMotor {+ Route: SupplyRoute;+ FromAnchor: 0;+ ToAnchor: 2;+ Avoid: [Motor];+ Clearance: 25mm;+}+```++The prefix before `FromAnchor` and suffix after `ToAnchor` are copied unchanged. Locks outside the interval are shifted only by the number of replacement anchors; a lock inside the interval fails with `piping-local-reroute-crosses-lock`. The resulting ordinary route has `LocallyRerouted` provenance.++Anchor and segment ordinals are zero-based. The authorized interval includes both boundary anchors but only segments with ordinals `FromAnchor .. ToAnchor-1`; the `ToAnchor` and the segment leaving it begin the preserved suffix. `LocalReroute` updates the named route in place and retains its identity—there is no `AcceptAs` because the operation is already an explicit authored edit. `LocalReroute.Clearance` overrides the RouteSpace default for the replacement interval. All system KeepOuts remain active; `Avoid` adds/names edit-specific obstacles and never disables unlisted KeepOuts.++## Build and fabrication output++```powershell+aetheris inspect fixtures/Canonical/Piping/autorouted-connection.firmament --json+aetheris build fixtures/Canonical/Piping/pump-skid.firmament --output artifacts/local/x3a/x3a-pump-skid.step --json+```++Build emits an AP242 occurrence assembly plus sibling `.routing.json`, `.cutlist.json`, and `.bom.json`. The routing report contains the system, equipment, ports, nozzles, endpoint mates, scoped exemptions, connections, proposals, accepted routes and their anchors/segments/turns/provenance, KeepOuts, realized pipe segments/fittings, minimum clearance, and timing evidence. The Cut List contains deterministic fabrication groups keyed by policy/material/cut length; the BOM separately groups semantic pipe, fitting, and nozzle-stub products. Routing proxies are separate named assembly components; they are not equipment-detail models. Grouping uses semantic product/policy/material and cut length, never geometry hash alone. Final qualification independently checks exact axis-aligned cylinder/nozzle centerline intervals and each realized elbow's torus centerline against the applicable original KeepOut bounds, then subtracts the pipe radius. Elbow arcs use deterministic dense sampling with the maximum chord sagitta subtracted, so the reported clearance is a conservative lower bound rather than an optimistic sample.++## Bounded support++Supported:++- logical Connections independent of geometry;+- stable port Interfaces and endpoint directions;+- equipment-owned hollow nozzle stubs, scoped owner exemptions, and coincident endpoint mates;+- explicit orthogonal 3D routes and 90-degree elbows;+- deterministic local autorouting around axis-aligned KeepOut bounds;+- hard waypoints, locked segments, and bounded local rerouting;+- hollow analytic pipe and elbow bodies;+- AP242 assembly, BOM, pipe Cut List, and routing evidence.++Not supported:++- freeform or spline routing, arbitrary bends, or 45-degree elbows;+- tees in automatic branch realization (the generic Tee product policy is shipped for future branch lowering);+- reducers, flanges, and adapters as automatic geometry;+- penetrations, pipe supports, spools, pressure class, or standards lookup;+- stress, flow, gravity-slope, or plant-scale optimization.++Copy the [autorouted connection fixture](../../../fixtures/Canonical/Piping/autorouted-connection.firmament), [local reroute fixture](../../../fixtures/Canonical/Piping/local-reroute.firmament), or [pump skid fixture](../../../fixtures/Canonical/Piping/pump-skid.firmament) as current examples.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 316e92e5..dafb7b76 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -8,6 +8,7 @@| 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). |+| Semantic piping / routing | Bounded (X3a) | Logical connections; equipment-owned port Interfaces and hollow nozzle stubs; target-port-scoped owner KeepOut exemptions; coincident endpoint mates; explicit orthogonal 3D routes; deterministic A* proposals; editable accepted routes; 90-degree elbows; bounded local rerouting; AP242 assembly, BOM, and pipe Cut List. No freeform, stress-, flow-, slope-, or plant-scale routing. See [guide](../firmament/piping.md). || Boss | Bounded | First-class connected finite `On: Top` profile addition on an admitted Compose host; positive height; lowers through existing `Add`; no arbitrary solid union || 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 6d096604..694fab83 100644--- a/docs/public/standard-library/README.md+++ b/docs/public/standard-library/README.md@@ -13,6 +13,8 @@ The Standard Library is a shipped, curated catalog of typed Firmament product fa| 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 |+| Generic Pipe / Elbow90 / Tee | `Standard.Piping` | dimensional, non-standards-claim piping product policies |+| Pump Cooling Skid | `Standard.Piping.PumpSkid` | equipment-owned nozzle ports, scoped KeepOut exemptions, endpoint mates, deterministic accepted route, AP242 assembly || 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; `Standard.Structural` owns structure-first weldments; the existing `Standard.SheetMetal` namespace remains stable for manufacturing Templates.diff --git a/docs/release/X3-PIPING-LOCAL-AUTOROUTING.md b/docs/release/X3-PIPING-LOCAL-AUTOROUTING.mdnew file mode 100644index 00000000..b614d518--- /dev/null+++ b/docs/release/X3-PIPING-LOCAL-AUTOROUTING.md@@ -0,0 +1,115 @@+# X3 — Piping and local autorouting++> Follow-up: [X3a equipment port and nozzle connection hardening](X3A-EQUIPMENT-PORT-NOZZLE-CONNECTION-HARDENING.md) closes the flagship's proxy-to-pipe visual gaps with equipment-owned nozzle stubs and target-scoped KeepOut exemptions.++## Executive verdict++**Accepted.** Aetheris can represent logical piping connections independently of geometry, author or deterministically propose orthogonal routes, accept proposals into ordinary semantic route state, locally replace a bounded interval while preserving the remainder, realize hollow analytic pipe/fitting components, and emit deterministic fabrication reports plus an AP242 assembly.++This is bounded skid-scale routing, not industrial plant routing.++## Architecture++```text+PipingSystem+→ logical Connection between port Interfaces+→ explicit Route or RouteRequest+→ inspectable RouteProposal+→ accepted ordinary Route+→ Elbow90 fittings + hollow PipeSegments+→ AP242 occurrence Assembly+→ semantic BOM + pipe Cut List + routing JSON+```++X2's Interface and assembly doctrine is reused. A piping port is `PipingPortInterfaceIr`: stable identity, position/DatumFrame, outward direction, circular policy, and connection style. There is no second piping-only endpoint identity beneath it. The older `Aetheris.Piping` module remains the lower-level bounded analytic route capability; X3 adds the Firmament system graph, authoring, router, fabrication model, and assembly path without changing that module's public contracts.++Accepted state is `RouteIr`, regardless of whether its provenance is `Explicit`, `AutoGenerated`, or `LocallyRerouted`. The geometry path consumes only `RouteIr`. A proposal is copied into stable route anchors by `OrthogonalAutoRouter.Accept`; it is not stored as an opaque solver object and no router call is needed to rebuild a materialized explicit route.++## Router++The router uses a bounded adaptive coordinate grid, not uniform voxelization.++- Candidate coordinates: source/destination coordinates, hard-waypoint coordinates, bend-aware obstacle min/max faces, and one deterministic exterior margin plane on each axis. Corner planes include a bend-radius planning margin; planes too close to a required point to fit adjacent tangent setbacks are removed.+- Obstacles: axis-aligned semantic `KeepOutIr` bounds inflated by `pipe OD / 2 + requested clearance`.+- Graph: Cartesian coordinate intersections outside inflated interiors; edges connect adjacent visible coordinates along `±X`, `±Y`, or `±Z`.+- Search: A* over `(node, incoming direction)` state.+- Cost: `route length + 1000 mm × elbow count`. The elbow penalty deliberately dominates small length savings.+- Endpoint policy: the first edge equals the source outward direction; the final edge equals the negative destination outward direction.+- Determinism: fixed direction order (`+X,-X,+Y,-Y,+Z,-Z`) and priority tie-breaking by estimated cost, turns, traveled length, node ordinal, then direction.+- Simplification: duplicate and collinear nodes are removed before proposal materialization.++The current bounded AABB query is exact for the admitted KeepOut representation, so X3 did not force obstacles through CIR merely to rename the same calculation. CIR remains the intended query adapter when routing admits non-box implicit obstacles; final BRep authority remains AIR/construction-derived.++Failures distinguish endpoint-direction impossibility, excessive clearance, unreachable hard waypoints, disconnected routing space, no collision-free path, and locked-interval conflicts.++## Geometry and clearance++Every straight run is shortened to fitting tangent points and becomes an independent hollow analytic-cylinder `PipeSegment`. Every turn becomes an independent hollow `Standard.Piping.Elbow90` with outer and inner analytic torus surfaces plus annular planar ends. OD, wall thickness, bend radius, material, named fitting Interfaces, centerline length, and cut length remain semantic fields.++Planner visibility uses obstacles inflated by pipe radius plus requested clearance, while candidate corner planes add a bend-radius margin. After materialization, an independent pass computes exact axis-aligned straight-run distance to each original KeepOut and samples every realized torus centerline deterministically, subtracting both pipe radius and the maximum sampling-chord sagitta. The result is a conservative lower bound for the actual cylinder/elbow envelope, not a zero-radius polyline check. Routing clearance and the kernel tolerance context remain separate quantities.++KeepOut proxies are emitted as distinct named AP242 components to make the inspection artifact intelligible. They are routing proxies, not detailed pumps, heat exchangers, or structural designs.++## Local rerouting witness++The canonical local witness begins with:++```text+[0,0,0] → [500,0,0] → [500,300,0]+→ [500,300,300] → [1000,300,300]+```++Segment 2 (the vertical riser, using zero-based ordinals) is locked. `LocalReroute AroundMotor` authorizes anchors `0..2`; segment 2 begins at the exclusive interval boundary and is therefore preserved. The accepted result changes only that prefix interval and retains the suffix points exactly:++```text+[500,300,300] → [1000,300,300]+```++The lock is shifted to the corresponding final segment without changing its endpoints. Regression tests assert `LocallyRerouted` provenance, exact suffix points, preserved lock, stable port Interfaces, and rejection when an authorized interval crosses a lock.++## Flagship pump/cooling skid++Source: `fixtures/Canonical/Piping/pump-skid.firmament`++Generation command:++```powershell+dotnet run --project Aetheris.CLI -c Release -- build fixtures/Canonical/Piping/pump-skid.firmament --output artifacts/local/x3/x3-pump-skid.step --json+```++Fresh qualification evidence:++| Field | Result |+|---|---:|+| logical connections / accepted routes | 2 / 2 |+| pipe segments / Elbow90 fittings | 12 / 10 |+| AP242 bodies | 26 (22 routed components + 4 proxies) |+| analytic cylinders / tori / planes | 24 / 20 / 68 |+| verified minimum clearance | 37.499 mm conservative lower bound (30 mm required) |+| bounds | `[0,-112.5,0] → [1250,662.5,800]` mm |+| pipe Cut List groups | 9 |+| components enclosed | true |+| AP242 reimport | succeeded |+| STEP SHA-256 | `25e30e81fcad5e928eb9950bb98e0823c40fc15ef8ffc7fede56131e5b51160a` |++One route is explicitly authored and contains a locked vertical interval. The second is materialized ordinary route state with `AutoGenerated` provenance. A separate `ReturnProposalWitness` proves that the same model can produce an inspectable proposal without owning the materialized return route.++One observed development run spent approximately 255 ms parsing/binding, 39 ms preparing/searching the graph, under 1 ms simplifying, 53 ms realizing route components, and 113 ms exporting/reimporting AP242. These timings are diagnostic, not performance promises.++## Standard Library, CLI, Forge, and inspection++The embedded Standard source ships generic `Pipe`, `Elbow90`, `Tee`, and `PumpSkid` policies. `Use Standard.Piping` resolves them through normal X1a semantics. Forge Protocol v1 exposes `Standard.Piping.PumpSkid` through the existing `list`, `describe`, and `invoke` operations; no piping RPC was added.++`aetheris inspect --json`, `validate --json`, and `build --json` report the PipingSystem, policies, ports, Connections, KeepOuts, proposals, accepted Routes, PipeSegments, fittings, BOM, Cut List, clearance evidence, analytic surface counts, bounds, timings, and AP242 evidence. The ordinary assembly/product structure remains visible to existing STEP/Cadmata inspection.++## Limitations and follow-up++X3 intentionally does not implement 45-degree elbows, freeform/spline routing, arbitrary bend fabrication, automatic tee branch realization, automatic reducers/flanges/adapters, standards dimensions or pressure classes, penetrations, supports, anchors/guides, spools, slope, stress, flow, pump sizing, or plant-scale routing. The shipped Tee policy is an architectural product hook; automatic branch graph lowering is future work.++Preference regions and CIR-backed non-box distance queries are deferred until a real admitted obstacle family needs them. Equipment and frame bodies in the flagship are conservative proxies. Route search is bounded by the candidate-coordinate graph and is not complete over arbitrary continuous geometry.++## Qualification++`PipingX3Tests` covers canonical compilation/reimport, explicit routes, KeepOut avoidance, deterministic proposals and tie-breaking, proposal acceptance, hollow pipe/fitting realization, semantic BOM/Cut List grouping, local invariants, locks, port compatibility, isolated invalid fixtures, Standard Library resolution, and the flagship artifact. Repository-wide Release build/tests, CLI/Forge tests, layout and Markdown checks are recorded in the completion handoff.++The manual artifact is `artifacts/local/x3/x3-pump-skid.step`. Open it in a STEP viewer and inspect the four port connections, both paths around the proxy frame, elbow orientation, pipe-to-elbow tangency, unexpected collisions, and overall skid plausibility.diff --git a/docs/release/X3A-EQUIPMENT-PORT-NOZZLE-CONNECTION-HARDENING.md b/docs/release/X3A-EQUIPMENT-PORT-NOZZLE-CONNECTION-HARDENING.mdnew file mode 100644index 00000000..84c8736c--- /dev/null+++ b/docs/release/X3A-EQUIPMENT-PORT-NOZZLE-CONNECTION-HARDENING.md@@ -0,0 +1,78 @@+# X3a — Equipment port and nozzle connection hardening++## Executive verdict++**Accepted.** The X3 flagship no longer uses an unexplained air gap between route endpoints and equipment proxies. Each owned port now materializes a hollow nozzle stub from the equipment face to the route endpoint, and a first-class mate joins the nozzle's pipe-side Interface to the endpoint pipe Interface.++The change is deliberately bounded. It adds no flange catalog, equipment CAD library, penetration system, or generalized collision exception language.++## Semantic seam++```text+Equipment → owning KeepOut+→ owned Port (pipe-side mating position + outward direction)+→ hollow NozzleStub (equipment face → port)+→ coincident/opposed PipingMate+→ endpoint PipeSegment+```++`Equipment` names its conservative proxy `KeepOut`. An owned `Port` names that equipment and a positive `NozzleLength`. Its derived nozzle root must lie on the owner's outward AABB face. The port's existing stable Interface is the nozzle's `PipeMate`; the nozzle also exposes an `EquipmentMate` at its root. The endpoint pipe segment exposes a distinct Interface at the same point with the opposite outward direction.++## Scoped clearance exemption++The former 50 mm visual gap existed because every route component was checked against every equipment KeepOut. X3a does not weaken that rule globally.++For each owned port, the compiler records exactly one `PipingKeepOutExemptionIr`:++```text+Port: <target port>+Nozzle: <that port's nozzle only>+KeepOut: <that port's owning equipment only>+Scope: NozzleEnvelopeOnly+```++The accepted route continues to check every KeepOut, including its endpoint equipment. The nozzle checks every foreign KeepOut at full required clearance. Only nozzle-to-owning-equipment contact is exempt, allowing the stub root to touch the proxy face. Regression fixtures reject an off-face nozzle root and a nozzle that crosses a foreign bracket even though its route remains clear.++## Physical realization++Nozzles use the same qualified hollow analytic pipe construction as straight route segments. They remain distinct `Standard.Piping.NozzleStub` semantic/AP242 occurrences and BOM components. Their root annulus touches the equipment proxy face; their tip annulus is coincident with the endpoint pipe annulus. No BRep topology editing or fusing is used as semantic authority.++## Flagship evidence++Source: `fixtures/Canonical/Piping/pump-skid.firmament`++Generation command:++```powershell+dotnet run --project Aetheris.CLI -c Release -- build fixtures/Canonical/Piping/pump-skid.firmament --output artifacts/local/x3a/x3a-pump-skid.step --json+```++| Field | Result |+|---|---:|+| logical connections / routes | 2 / 2 |+| pipe segments / Elbow90 fittings | 12 / 10 |+| equipment / owned nozzles / endpoint mates | 2 / 4 / 4 |+| scoped KeepOut exemptions | 4, all `NozzleEnvelopeOnly` |+| AP242 bodies | 30 (22 route components + 4 nozzles + 4 proxies) |+| analytic cylinders / tori / planes | 32 / 20 / 76 |+| verified minimum non-exempt clearance | 37.499 mm conservative lower bound (30 mm required) |+| bounds | `[0,-112.5,0] → [1250,662.5,800]` mm |+| components enclosed | true |+| AP242 reimport | succeeded |+| STEP SHA-256 | `f515741168825ff90052a7ac76b4e21cd87f4246cd24b2aa9ec4dbdb76d52510` |++The routing JSON now reports equipment, owned ports, nozzle root/tip positions, endpoint mates, and scoped exemptions. The BOM separately groups four `Standard.Piping.NozzleStub` components; nozzle stubs are not added to the pipe Cut List.++## Qualification++Focused X3/X3a tests cover ownership, on-face roots, physical length, coincident/opposed mates, exemption scope, own-owner contact, full foreign clearance, invalid foreign collision, AP242 occurrence/reimport, and all prior routing/locality invariants. Qualification passed with 21 focused tests, all 87 canonical fixtures, a zero-warning Release build, all 3,068 discovered .NET tests, 82 client tests plus build/lint, 13 VS Code extension tests plus typecheck/build/package, a fresh packaged CLI, fresh win-x64 NativeAOT Forge `list`/`describe`/`invoke`, the repository layout guard, Markdown link scan, and `git diff --check`.++## Manual inspection++Open `artifacts/local/x3a/x3a-pump-skid.step` and inspect:++- both pump nozzle roots touching the pump proxy face;+- both cooler nozzle roots touching the cooler proxy face;+- no gap or overlap at each nozzle-to-pipe mate;+- unchanged frame clearance and route shapes;+- elbow orientation and general skid plausibility.diff --git a/fixtures/Canonical/Piping/autorouted-connection.firmament b/fixtures/Canonical/Piping/autorouted-connection.firmamentnew file mode 100644index 00000000..b19b05a2--- /dev/null+++ b/fixtures/Canonical/Piping/autorouted-connection.firmament@@ -0,0 +1,12 @@+Model AutoRouteWitness {+ Units: mm+ PipingSystem AutoWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port Cooler { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }+ KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }+ RouteSpace Skid { Clearance: 30mm; }+ RouteRequest SupplyRequest { Connection: Supply; Clearance: 30mm; BendRadius: 50mm; HardWaypoints: []; AcceptAs: SupplyRoute; }+ }+}diff --git a/fixtures/Canonical/Piping/elbow90.firmament b/fixtures/Canonical/Piping/elbow90.firmamentnew file mode 100644index 00000000..641399a9--- /dev/null+++ b/fixtures/Canonical/Piping/elbow90.firmament@@ -0,0 +1,10 @@+Model Elbow90Witness {+ Units: mm+ PipingSystem ElbowWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Port Outlet { Position: [300mm,500mm,0mm]; Direction: [0,-1,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; }+ Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Canonical/Piping/explicit-route.firmament b/fixtures/Canonical/Piping/explicit-route.firmamentnew file mode 100644index 00000000..431d0c9d--- /dev/null+++ b/fixtures/Canonical/Piping/explicit-route.firmament@@ -0,0 +1,10 @@+Model ExplicitRouteWitness {+ Units: mm+ PipingSystem ExplicitWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port PumpDischarge { Position: [0mm,0mm,100mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port CoolerInlet { Position: [700mm,350mm,100mm]; Direction: [0,-1,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: Pipe25; Service: "CoolingSupply"; }+ Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,100mm],[400mm,0mm,100mm],[400mm,200mm,100mm],[700mm,200mm,100mm],[700mm,350mm,100mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Canonical/Piping/local-reroute.firmament b/fixtures/Canonical/Piping/local-reroute.firmamentnew file mode 100644index 00000000..68a4afc0--- /dev/null+++ b/fixtures/Canonical/Piping/local-reroute.firmament@@ -0,0 +1,13 @@+Model LocalRerouteWitness {+ Units: mm+ PipingSystem LocalWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port Cooler { Position: [1000mm,300mm,300mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }+ KeepOut Motor { Min: [250mm,-50mm,-50mm]; Max: [450mm,150mm,150mm]; Concept: EquipmentProxy; }+ RouteSpace Skid { Clearance: 25mm; }+ Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm],[500mm,300mm,0mm],[500mm,300mm,300mm],[1000mm,300mm,300mm]]; BendRadius: 50mm; LockedSegments: [2]; Provenance: AutoGenerated; }+ LocalReroute AroundMotor { Route: SupplyRoute; FromAnchor: 0; ToAnchor: 2; Avoid: [Motor]; Clearance: 25mm; }+ }+}diff --git a/fixtures/Canonical/Piping/pipe-segment.firmament b/fixtures/Canonical/Piping/pipe-segment.firmamentnew file mode 100644index 00000000..d8068ddf--- /dev/null+++ b/fixtures/Canonical/Piping/pipe-segment.firmament@@ -0,0 +1,10 @@+Model PipeSegmentWitness {+ Units: mm+ PipingSystem SegmentWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Port Outlet { Position: [500mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; Service: "CoolingWater"; }+ Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Canonical/Piping/pump-skid.firmament b/fixtures/Canonical/Piping/pump-skid.firmamentnew file mode 100644index 00000000..b2ffb7ea--- /dev/null+++ b/fixtures/Canonical/Piping/pump-skid.firmament@@ -0,0 +1,22 @@+Model X3PumpCoolingSkid {+ Units: mm+ PipingSystem CoolingSkid {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port PumpDischarge { Position: [100mm,100mm,250mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }+ Port CoolerInlet { Position: [1100mm,500mm,650mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }+ Port CoolerOutlet { Position: [1100mm,400mm,550mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }+ Port PumpSuction { Position: [100mm,200mm,150mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }+ Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: Pipe25; Service: "CoolingSupply"; }+ Connection Return { From: CoolerOutlet; To: PumpSuction; PipePolicy: Pipe25; Service: "CoolingReturn"; }+ KeepOut FrontRail { Min: [350mm,0mm,0mm]; Max: [390mm,600mm,800mm]; Concept: StructureMember; }+ KeepOut BackRail { Min: [700mm,0mm,0mm]; Max: [740mm,600mm,800mm]; Concept: StructureMember; }+ KeepOut PumpBody { Min: [0mm,0mm,0mm]; Max: [50mm,300mm,350mm]; Concept: EquipmentProxy; }+ KeepOut CoolerBody { Min: [1150mm,300mm,300mm]; Max: [1250mm,600mm,800mm]; Concept: EquipmentProxy; }+ Equipment Pump { KeepOut: PumpBody; }+ Equipment Cooler { KeepOut: CoolerBody; }+ RouteSpace SkidRouting { Clearance: 30mm; }+ Route SupplyRoute { Connection: Supply; Through: [[100mm,100mm,250mm],[250mm,100mm,250mm],[250mm,650mm,250mm],[900mm,650mm,250mm],[900mm,650mm,650mm],[900mm,500mm,650mm],[1100mm,500mm,650mm]]; BendRadius: 50mm; LockedSegments: [3]; Provenance: Explicit; }+ Route ReturnRoute { Connection: Return; Through: [[1100mm,400mm,550mm],[900mm,400mm,550mm],[900mm,-100mm,550mm],[900mm,-100mm,150mm],[300mm,-100mm,150mm],[300mm,200mm,150mm],[100mm,200mm,150mm]]; BendRadius: 50mm; Provenance: AutoGenerated; }+ RouteRequest ReturnProposalWitness { Connection: Return; Clearance: 30mm; BendRadius: 50mm; HardWaypoints: [[900mm,-100mm,550mm]]; }+ }+}diff --git a/fixtures/Canonical/Piping/route-around-keepout.firmament b/fixtures/Canonical/Piping/route-around-keepout.firmamentnew file mode 100644index 00000000..a22be8b5--- /dev/null+++ b/fixtures/Canonical/Piping/route-around-keepout.firmament@@ -0,0 +1,12 @@+Model RouteAroundKeepOut {+ Units: mm+ PipingSystem KeepOutWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port Cooler { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }+ KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }+ RouteSpace Skid { Clearance: 30mm; }+ Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,200mm,0mm],[700mm,200mm,0mm],[700mm,0mm,0mm],[1000mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Canonical/Piping/tee.firmament b/fixtures/Canonical/Piping/tee.firmamentnew file mode 100644index 00000000..71eaafb9--- /dev/null+++ b/fixtures/Canonical/Piping/tee.firmament@@ -0,0 +1,13 @@+Use Standard.Piping+Model StandardTeeWitness {+ Units: mm+ Let TeeProduct = Standard.Piping.Tee+ Let TeePolicy = Standard.Piping.TeePolicy+ PipingSystem TeeLibraryWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Port Outlet { Position: [300mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; Service: "TeeLibraryWitness"; }+ Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Canonical/README.md b/fixtures/Canonical/README.mdindex db2f96c7..9bc47f82 100644--- a/fixtures/Canonical/README.md+++ b/fixtures/Canonical/README.md@@ -28,6 +28,7 @@ Everything in this directory is current authoring guidance. Examples progress fr| run FEA | `FEA/cantilever.firmament` | material, `Fixed`, `Force`, four result families || analyze imported STEP | `FEA/inline-step-cantilever.firmament` | repository-stable `inlineSTEP`, face selection, FEA || author an assembly | `Assembly/bearing-module.firmament` | Interface, Mate, nested identity, tolerance stack |+| route a piping system | `Piping/pump-skid.firmament` | logical Connection, equipment-owned nozzle Interfaces/mates, scoped owner exemption, explicit/accepted Routes, strict foreign KeepOut clearance, fittings, BOM/Cut List || combine machining operations | `Integration/machined-mounting-block.firmament` | Boss, Pocket, holes, counterbores, chamfer, PMI |`Pocket` never means through-all; use a supported `Hole` or `Slot` for through removal. General loft, helix, arbitrary Boolean authoring, and freeform surface features are not in Preview 3; see [`docs/public/reference/supported-features.md`](../../docs/public/reference/supported-features.md).@@ -41,6 +42,7 @@ Everything in this directory is current authoring guidance. Examples progress fr| Sheet Metal | `Aetheris.SheetMetal.Tests` || FEA and Materials | `Aetheris.FEA.Tests` || Assembly | `Aetheris.Kernel.Firmament.Tests` assembly suite |+| Piping | `PipingX3Tests` || Drawings | `Aetheris.CLI.Tests` drawing suite |The compact action map is `qualification.json`; `coverage.json` is the public-operation guard. Generated outputs go to `artifacts/local/`, never beside these sources.diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.jsonnew file mode 100644index 00000000..5391c31b--- /dev/null+++ b/fixtures/Canonical/coverage.json@@ -0,0 +1,36 @@+{+ "schemaVersion": 1,+ "features": {+ "Box": "Basics/box.firmament",+ "Cylinder": "Basics/cylinder.firmament",+ "Frustum": "Primitives/frustum.firmament",+ "RoundedBox": "Primitives/rounded-box.firmament",+ "Sphere": "Primitives/sphere.firmament",+ "Cone": "Primitives/cone.firmament",+ "PointedCone": "Primitives/pointed-cone.firmament",+ "Torus": "Primitives/torus.firmament",+ "Profile": "Profiles/concept-path-line-arc-profile.firmament",+ "ProfileDelta": "Profiles/profile-delta-recess-extrusion.firmament",+ "Sweep": "Features/Sweep/circular-planar-path-sweep.firmament",+ "Paperclip": "Templates/paperclip.firmament",+ "Boss": "Features/Boss/rectangular-boss.firmament",+ "Pocket": "Features/Pocket/rectangular-pocket.firmament",+ "Hole": "Features/Holes/through-hole.firmament",+ "BlindHole": "Features/Holes/blind-hole.firmament",+ "Counterbore": "Features/Holes/counterbore.firmament",+ "Countersink": "Features/Holes/countersink.firmament",+ "Slot": "Features/Slots/straight-slot.firmament",+ "Pattern": "Patterns/record-array-hole-pattern.firmament",+ "Chamfer": "Features/EdgeFinish/boundary-chamfer.firmament",+ "Fillet": "Features/EdgeFinish/single-edge-fillet.firmament",+ "RecordStaticTableWith": "Profiles/profile-delta-recess-extrusion.firmament",+ "Material": "Materials/material-catalog-coupon.firmament",+ "PMI": "PMI/multiple-hole-dimensions-with-chamfer.firmament",+ "Template": "Templates/generic-mounting-plate.firmament",+ "SheetMetal": "SheetMetal/l-bracket-with-hole.firmament",+ "FEA": "FEA/cantilever.firmament",+ "inlineSTEP": "FEA/inline-step-cantilever.firmament",+ "Assembly": "Assembly/bearing-module.firmament",+ "Piping": "Piping/pump-skid.firmament"+ }+}diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex f3035326..0afda076 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -7,6 +7,7 @@{ "path": "Materials", "operation": "fea-solve" },{ "path": "SheetMetal", "operation": "sheet-metal-flatten" },{ "path": "Structural", "operation": "build-step" },+ { "path": "Piping", "operation": "build-step" },{ "path": "Basics", "operation": "build-step" },{ "path": "Primitives", "operation": "build-step" },{ "path": "Profiles", "operation": "build-step" },diff --git a/fixtures/Invalid/Piping/autoroute-no-solution.firmament b/fixtures/Invalid/Piping/autoroute-no-solution.firmamentnew file mode 100644index 00000000..6ade8766--- /dev/null+++ b/fixtures/Invalid/Piping/autoroute-no-solution.firmament@@ -0,0 +1 @@+Model InvalidAutoRoute { PipingSystem Invalid { PipePolicy P { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } Port A { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: P; } Port B { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: P; } Connection C { From: A; To: B; PipePolicy: P; } KeepOut Wall { Min: [1mm,-10000mm,-10000mm]; Max: [999mm,10000mm,10000mm]; Concept: KeepOut; } RouteRequest R { Connection: C; Clearance: 25mm; HardWaypoints: []; AcceptAs: Impossible; } } }diff --git a/fixtures/Invalid/Piping/incompatible-port.firmament b/fixtures/Invalid/Piping/incompatible-port.firmamentnew file mode 100644index 00000000..5e3aa5b9--- /dev/null+++ b/fixtures/Invalid/Piping/incompatible-port.firmament@@ -0,0 +1 @@+Model InvalidPorts { PipingSystem Invalid { PipePolicy A { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } PipePolicy B { OuterDiameter: 32mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } Port P1 { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: A; ConnectionType: Flange; } Port P2 { Position: [500mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: B; ConnectionType: Weld; } Connection C { From: P1; To: P2; PipePolicy: A; } } }diff --git a/fixtures/Invalid/Piping/insufficient-clearance.firmament b/fixtures/Invalid/Piping/insufficient-clearance.firmamentnew file mode 100644index 00000000..d7f7f489--- /dev/null+++ b/fixtures/Invalid/Piping/insufficient-clearance.firmament@@ -0,0 +1 @@+Model InvalidClearance { PipingSystem Invalid { PipePolicy P { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } Port A { Position: [0mm,80mm,0mm]; Direction: [1,0,0]; PipePolicy: P; } Port B { Position: [500mm,80mm,0mm]; Direction: [-1,0,0]; PipePolicy: P; } Connection C { From: A; To: B; PipePolicy: P; } KeepOut K { Min: [200mm,0mm,-50mm]; Max: [300mm,50mm,50mm]; Concept: KeepOut; } RouteSpace S { Clearance: 25mm; } Route R { Connection: C; Through: [[0mm,80mm,0mm],[500mm,80mm,0mm]]; } } }diff --git a/fixtures/Invalid/Piping/local-reroute-crosses-lock.firmament b/fixtures/Invalid/Piping/local-reroute-crosses-lock.firmamentnew file mode 100644index 00000000..8498cf2c--- /dev/null+++ b/fixtures/Invalid/Piping/local-reroute-crosses-lock.firmament@@ -0,0 +1 @@+Model InvalidLock { PipingSystem Invalid { PipePolicy P { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } Port A { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: P; } Port B { Position: [500mm,300mm,0mm]; Direction: [0,-1,0]; PipePolicy: P; } Connection C { From: A; To: B; PipePolicy: P; } Route R { Connection: C; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,300mm,0mm],[500mm,300mm,0mm]]; LockedSegments: [1]; } LocalReroute Bad { Route: R; FromAnchor: 0; ToAnchor: 2; Avoid: []; Clearance: 25mm; } } }diff --git a/fixtures/Invalid/Piping/nozzle-crosses-foreign-keepout.firmament b/fixtures/Invalid/Piping/nozzle-crosses-foreign-keepout.firmamentnew file mode 100644index 00000000..b25c2b41--- /dev/null+++ b/fixtures/Invalid/Piping/nozzle-crosses-foreign-keepout.firmament@@ -0,0 +1,14 @@+Model NozzleCrossesForeignKeepOut {+ Units: mm+ PipingSystem InvalidNozzleClearance {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ KeepOut PumpBody { Min: [0mm,0mm,0mm]; Max: [50mm,200mm,200mm]; Concept: EquipmentProxy; }+ KeepOut ForeignBracket { Min: [55mm,90mm,90mm]; Max: [60mm,110mm,110mm]; Concept: StructureMember; }+ Equipment Pump { KeepOut: PumpBody; }+ Port PumpOut { Position: [100mm,100mm,100mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }+ Port Sink { Position: [500mm,100mm,100mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: PumpOut; To: Sink; PipePolicy: Pipe25; }+ RouteSpace Space { Clearance: 25mm; }+ Route SupplyRoute { Connection: Supply; Through: [[100mm,100mm,100mm],[500mm,100mm,100mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Invalid/Piping/nozzle-root-off-owner-face.firmament b/fixtures/Invalid/Piping/nozzle-root-off-owner-face.firmamentnew file mode 100644index 00000000..842449c3--- /dev/null+++ b/fixtures/Invalid/Piping/nozzle-root-off-owner-face.firmament@@ -0,0 +1,12 @@+Model NozzleRootOffOwnerFace {+ Units: mm+ PipingSystem InvalidNozzleRoot {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ KeepOut PumpBody { Min: [0mm,0mm,0mm]; Max: [50mm,200mm,200mm]; Concept: EquipmentProxy; }+ Equipment Pump { KeepOut: PumpBody; }+ Port PumpOut { Position: [100mm,100mm,100mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 40mm; }+ Port Sink { Position: [500mm,100mm,100mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: PumpOut; To: Sink; PipePolicy: Pipe25; }+ Route SupplyRoute { Connection: Supply; Through: [[100mm,100mm,100mm],[500mm,100mm,100mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Invalid/Piping/pipe-wall-too-thick.firmament b/fixtures/Invalid/Piping/pipe-wall-too-thick.firmamentnew file mode 100644index 00000000..fa06e043--- /dev/null+++ b/fixtures/Invalid/Piping/pipe-wall-too-thick.firmament@@ -0,0 +1 @@+Model InvalidWall { PipingSystem Invalid { PipePolicy P { OuterDiameter: 25mm; WallThickness: 13mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } } }diff --git a/fixtures/Invalid/Piping/route-through-keepout.firmament b/fixtures/Invalid/Piping/route-through-keepout.firmamentnew file mode 100644index 00000000..3aad93c4--- /dev/null+++ b/fixtures/Invalid/Piping/route-through-keepout.firmament@@ -0,0 +1 @@+Model InvalidCollision { PipingSystem Invalid { PipePolicy P { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } Port A { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: P; } Port B { Position: [500mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: P; } Connection C { From: A; To: B; PipePolicy: P; } KeepOut K { Min: [200mm,-50mm,-50mm]; Max: [300mm,50mm,50mm]; Concept: KeepOut; } Route R { Connection: C; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm]]; } } }diff --git a/fixtures/Invalid/Piping/unreachable-hard-waypoint.firmament b/fixtures/Invalid/Piping/unreachable-hard-waypoint.firmamentnew file mode 100644index 00000000..a77f3f97--- /dev/null+++ b/fixtures/Invalid/Piping/unreachable-hard-waypoint.firmament@@ -0,0 +1 @@+Model InvalidWaypoint { PipingSystem Invalid { PipePolicy P { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; } Port A { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: P; } Port B { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: P; } Connection C { From: A; To: B; PipePolicy: P; } KeepOut K { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: KeepOut; } RouteRequest R { Connection: C; Clearance: 25mm; HardWaypoints: [[500mm,0mm,0mm]]; AcceptAs: Impossible; } } }diff --git a/scripts/Test-CanonicalFixtures.ps1 b/scripts/Test-CanonicalFixtures.ps1index 69c4d003..65556f00 100644--- a/scripts/Test-CanonicalFixtures.ps1+++ b/scripts/Test-CanonicalFixtures.ps1@@ -28,7 +28,7 @@ $forbidden = @()$failures = [Collections.Generic.List[string]]::new()-$requiredFeatures = @('Box', 'Cylinder', 'Sphere', 'Cone', 'Torus', 'Profile', 'Sweep', 'Paperclip', 'Boss', 'Pocket', 'Hole', 'BlindHole', 'Counterbore', 'Countersink', 'Slot', 'Pattern', 'Chamfer', 'Fillet', 'Material', 'PMI', 'Template', 'SheetMetal', 'FEA', 'inlineSTEP', 'Assembly')+$requiredFeatures = @('Box', 'Cylinder', 'Sphere', 'Cone', 'Torus', 'Profile', 'Sweep', 'Paperclip', 'Boss', 'Pocket', 'Hole', 'BlindHole', 'Counterbore', 'Countersink', 'Slot', 'Pattern', 'Chamfer', 'Fillet', 'Material', 'PMI', 'Template', 'SheetMetal', 'FEA', 'inlineSTEP', 'Assembly', 'Piping')foreach ($feature in $requiredFeatures) {$entry = $coverage.features.$featureif ([string]::IsNullOrWhiteSpace($entry)) { $failures.Add("coverage: missing $feature"); continue }