Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add standalone cubic lattice STEP export and verification

Yuechen Lic26e3bd3ab9d
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index a311c95a..a7096330 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -379,6 +379,7 @@ public static class CliRunner
air = build.Value.Export.Air,
roundedBox = build.Value.Export.RoundedBox,
hollow = build.Value.Export.Hollow,
+ lattice = build.Value.Export.Lattice,
features = build.Value.Export.Features,
inlineStepMigration = build.Value.Export.InlineStepMigration,
inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,
diff --git a/Aetheris.Kernel.Core.Tests/CubicLatticeBRepPlanTests.cs b/Aetheris.Kernel.Core.Tests/CubicLatticeBRepPlanTests.cs
new file mode 100644
index 00000000..5e30c834
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/CubicLatticeBRepPlanTests.cs
@@ -0,0 +1,56 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests;
+
+public sealed class CubicLatticeBRepPlanTests
+{
+ [Fact]
+ public void CanonicalGraph_IsDeterministicAndSharesNodesAndMembers()
+ {
+ var graph = CubicLatticeBRepPlanner.BuildGraph(3, 3, 3, 8d);
+
+ Assert.Equal(27, graph.Cells.Count);
+ Assert.Equal(64, graph.Nodes.Count);
+ Assert.Equal(144, graph.Members.Count);
+ Assert.Equal(8, graph.Nodes.Count(node => node.Valence == 3));
+ Assert.Equal(24, graph.Nodes.Count(node => node.Valence == 4));
+ Assert.Equal(24, graph.Nodes.Count(node => node.Valence == 5));
+ Assert.Equal(8, graph.Nodes.Count(node => node.Valence == 6));
+ Assert.Equal(graph.Signature, CubicLatticeBRepPlanner.BuildGraph(3, 3, 3, 8d).Signature);
+ }
+
+ [Fact]
+ public void CanonicalPrimitive_UsesOneAuthoritativeAnalyticPlanAndRoundTripsStep()
+ {
+ var result = CubicLatticeBRepPlanner.Create(3, 3, 3, 8d, .8d, 1.2d);
+
+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var realization = result.Value;
+ Assert.True(realization.Plan.IsAuthoritative);
+ Assert.Equal(288, realization.Plan.SeamCount);
+ Assert.Equal(64 + 144, realization.Body.Topology.Faces.Count());
+ Assert.Equal(64, realization.Body.Geometry.Surfaces.Count(pair => pair.Value.Kind == SurfaceGeometryKind.Sphere));
+ Assert.Equal(144, realization.Body.Geometry.Surfaces.Count(pair => pair.Value.Kind == SurfaceGeometryKind.Cylinder));
+ var step = Step242Exporter.ExportBody(realization.Body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });
+ Assert.True(step.IsSuccess, string.Join(", ", step.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var imported = Step242Importer.ImportBody(step.Value);
+ Assert.True(imported.IsSuccess, string.Join(", ", imported.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var mass = BrepMassProperties.Evaluate(realization.Body);
+ Assert.True(mass.Status != BrepMassPropertiesStatus.Unavailable, string.Join(", ", mass.Diagnostics));
+ Assert.True(mass.AbsoluteVolume > 0d, string.Join(", ", mass.Diagnostics));
+ }
+
+ [Theory]
+ [InlineData(.8d, 1.1d, CubicLatticeBRepPlanner.NodeRadiusTooSmallForStruts)]
+ [InlineData(.8d, 1.2d, "")]
+ public void GeometryAdmissions_AreExplicit(double strutRadius, double nodeRadius, string expectedFailure)
+ {
+ var result = CubicLatticeBRepPlanner.Create(1, 1, 1, 2d, strutRadius, nodeRadius);
+
+ Assert.Equal(string.IsNullOrEmpty(expectedFailure), result.IsSuccess);
+ if (!result.IsSuccess) Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message == expectedFailure);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Air/LatticeFillFeature.cs b/Aetheris.Kernel.Core/Air/LatticeFillFeature.cs
index b6ca99d0..a3adcc9c 100644
--- a/Aetheris.Kernel.Core/Air/LatticeFillFeature.cs
+++ b/Aetheris.Kernel.Core/Air/LatticeFillFeature.cs
@@ -40,6 +40,27 @@ public sealed record LatticeFillFeature(
AdditiveManufacturingContext AdditiveContext,
LatticeFillProvenance Provenance);
+/// <summary>M9R's standalone intent. Host replacement remains a separate, deferred M9 route.</summary>
+public enum CubicLatticePlacementPolicy { MaterialBounds }
+public sealed record CubicLatticeAdditiveContext(string Template, string Process, double MinimumStrutDiameter, double MinimumNodeDiameter, double MinimumFeatureSpacing, string Provenance);
+public sealed record CubicLatticeFeature(
+ string FeatureId,
+ LatticeFillRegion Domain,
+ int CellsX,
+ int CellsY,
+ int CellsZ,
+ double CellSize,
+ double StrutRadius,
+ double NodeRadius,
+ CubicLatticePlacementPolicy PlacementPolicy,
+ CubicLatticeAdditiveContext AdditiveContext,
+ LatticeFillProvenance Provenance)
+{
+ public string Pattern => "CubicTruss";
+ public string Materialization => "StandaloneBody";
+ public string? HostId => null;
+}
+
public sealed record LatticeNodeInstance(string Id, Point3D Position, string Role);
public sealed record LatticeMemberInstance(string Id, string StartNodeId, string EndNodeId, Point3D Start, Point3D End, string Role);
public sealed record LatticeBoundaryIncident(string MemberId, string NodeId, string BoundaryPlane, Point3D Point);
diff --git a/Aetheris.Kernel.Core/Brep/CubicLatticeBRepPlan.cs b/Aetheris.Kernel.Core/Brep/CubicLatticeBRepPlan.cs
new file mode 100644
index 00000000..58f5de35
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/CubicLatticeBRepPlan.cs
@@ -0,0 +1,104 @@
+using System.Security.Cryptography;
+using System.Text;
+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.Results;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep;
+
+public sealed record CubicLatticeNode(string Id, int I, int J, int K, Point3D Position, int Valence);
+public sealed record CubicLatticeMember(string Id, string StartNodeId, string EndNodeId, string Axis, Point3D Start, Point3D End);
+public sealed record CubicLatticeConstruction(IReadOnlyList<(int X,int Y,int Z)> Cells, IReadOnlyList<CubicLatticeNode> Nodes, IReadOnlyList<CubicLatticeMember> Members, string Signature);
+public sealed record LatticeNodeBRepPlan(string NodeId, IReadOnlyList<string> MemberIds, int Valence);
+public sealed record LatticeMemberBRepPlan(string MemberId, string StartNodeId, string EndNodeId, string Axis, double ExposedLength);
+public sealed record LatticeBodyBRepPlan(CubicLatticeConstruction Construction, IReadOnlyList<LatticeNodeBRepPlan> Nodes, IReadOnlyList<LatticeMemberBRepPlan> Members, int SeamCount, string Signature)
+{ public bool IsAuthoritative => true; }
+public sealed record CubicLatticeRealization(LatticeBodyBRepPlan Plan, BrepBody Body, double AnalyticVolume);
+
+/// <summary>Bounded exact analytic M9R lattice plan. It directly creates shared sphere/cylinder seams; no Boolean operation is used.</summary>
+public static class CubicLatticeBRepPlanner
+{
+ public const string NodeRadiusTooSmallForStruts = "NodeRadiusTooSmallForStruts";
+ public const string MemberConsumedByNodes = "MemberConsumedByNodes";
+
+ public static KernelResult<CubicLatticeRealization> Create(int nx, int ny, int nz, double cellSize, double strutRadius, double nodeRadius, Point3D? center = null)
+ {
+ if (nx <= 0 || ny <= 0 || nz <= 0 || !double.IsFinite(cellSize) || !double.IsFinite(strutRadius) || !double.IsFinite(nodeRadius) || cellSize <= 0 || strutRadius <= 0 || nodeRadius <= 0)
+ return Failure("InvalidCubicLatticeParameters");
+ if (nodeRadius <= double.Sqrt(2d) * strutRadius) return Failure(NodeRadiusTooSmallForStruts);
+ var seamOffset = double.Sqrt(nodeRadius * nodeRadius - strutRadius * strutRadius);
+ if (cellSize - 2d * seamOffset <= 1e-9) return Failure(MemberConsumedByNodes);
+
+ var construction = BuildGraph(nx, ny, nz, cellSize, center ?? new Point3D(0d, 0d, 0d));
+ var nodePlans = construction.Nodes.Select(n => new LatticeNodeBRepPlan(n.Id, construction.Members.Where(m => m.StartNodeId == n.Id || m.EndNodeId == n.Id).Select(m => m.Id).Order().ToArray(), n.Valence)).ToArray();
+ var memberPlans = construction.Members.Select(m => new LatticeMemberBRepPlan(m.Id, m.StartNodeId, m.EndNodeId, m.Axis, cellSize - 2d * seamOffset)).ToArray();
+ var planText = construction.Signature + "|" + string.Join("|", memberPlans.Select(m => m.MemberId));
+ var plan = new LatticeBodyBRepPlan(construction, nodePlans, memberPlans, construction.Members.Count * 2, Hash(planText));
+ var body = BuildBody(construction, strutRadius, nodeRadius, seamOffset);
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid) return KernelResult<CubicLatticeRealization>.Failure(preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => new Diagnostics.KernelDiagnostic(Diagnostics.KernelDiagnosticCode.ValidationFailed, Diagnostics.KernelDiagnosticSeverity.Error, d.Code, d.Context)).ToArray());
+ var capHeight = nodeRadius - seamOffset;
+ var capVolume = double.Pi * capHeight * capHeight * (nodeRadius - capHeight / 3d);
+ var analytic = construction.Nodes.Count * (4d / 3d * double.Pi * nodeRadius * nodeRadius * nodeRadius)
+ - construction.Members.Count * 2d * capVolume
+ + construction.Members.Count * double.Pi * strutRadius * strutRadius * (cellSize - 2d * seamOffset);
+ return KernelResult<CubicLatticeRealization>.Success(new(plan, body, analytic));
+ }
+
+ public static CubicLatticeConstruction BuildGraph(int nx, int ny, int nz, double cellSize, Point3D? center = null)
+ {
+ var nodes = new List<CubicLatticeNode>();
+ var members = new List<CubicLatticeMember>();
+ var domainCenter = center ?? new Point3D(0d, 0d, 0d);
+ var origin = new Vector3D(domainCenter.X - cellSize * nx / 2d, domainCenter.Y - cellSize * ny / 2d, domainCenter.Z - cellSize * nz / 2d);
+ for (var i=0;i<=nx;i++) for (var j=0;j<=ny;j++) for (var k=0;k<=nz;k++)
+ {
+ // Boundary dimensions remove one incident direction each.
+ var v = 6 - ((i==0?1:0)+(i==nx?1:0)+(j==0?1:0)+(j==ny?1:0)+(k==0?1:0)+(k==nz?1:0));
+ nodes.Add(new($"cubic:node:{i}:{j}:{k}",i,j,k,new Point3D(origin.X+i*cellSize,origin.Y+j*cellSize,origin.Z+k*cellSize),v));
+ }
+ var byId=nodes.ToDictionary(n=>n.Id,StringComparer.Ordinal);
+ foreach(var n in nodes)
+ {
+ Add(n, n.I<nx ? (n.I+1,n.J,n.K) : (-1,-1,-1), "X");
+ Add(n, n.J<ny ? (n.I,n.J+1,n.K) : (-1,-1,-1), "Y");
+ Add(n, n.K<nz ? (n.I,n.J,n.K+1) : (-1,-1,-1), "Z");
+ }
+ var cells=(from i in Enumerable.Range(0,nx) from j in Enumerable.Range(0,ny) from k in Enumerable.Range(0,nz) select (i,j,k)).ToArray();
+ var text=string.Join("|",nodes.Select(n=>n.Id))+";"+string.Join("|",members.Select(m=>m.Id));
+ return new(cells,nodes,members,Hash(text));
+ void Add(CubicLatticeNode a,(int I,int J,int K) q,string axis) { if(q.I<0)return; var b=byId[$"cubic:node:{q.I}:{q.J}:{q.K}"]; members.Add(new($"cubic:member:{axis}:{a.Id}:{b.Id}",a.Id,b.Id,axis,a.Position,b.Position)); }
+ }
+
+ private static BrepBody BuildBody(CubicLatticeConstruction c, double rs, double rn, double d)
+ {
+ var b=new TopologyBuilder(); var g=new BrepGeometryStore(); var bind=new BrepBindingModel(); var points=new Dictionary<VertexId,Point3D>();
+ var nodeMembers=c.Nodes.ToDictionary(n=>n.Id,_=>new List<(CubicLatticeMember M,bool Start)>(),StringComparer.Ordinal);
+ foreach(var m in c.Members){nodeMembers[m.StartNodeId].Add((m,true));nodeMembers[m.EndNodeId].Add((m,false));}
+ var seam=new Dictionary<(string,string),EdgeId>();
+ foreach(var n in c.Nodes.OrderBy(n=>n.Id,StringComparer.Ordinal))
+ {
+ var loops=new List<IReadOnlyList<Use>>();
+ foreach(var x in nodeMembers[n.Id].OrderBy(x=>x.M.Id,StringComparer.Ordinal))
+ { var e=AddSeam(n,x.M,x.Start); seam[(x.M.Id,n.Id)]=e; loops.Add([new Use(e,false)]); }
+ var f=AddFace(b,loops); AddSurface(f,SurfaceGeometry.FromSphere(new SphereSurface(n.Position,Z(),rn,X())),g,bind);
+ }
+ foreach(var m in c.Members.OrderBy(m=>m.Id,StringComparer.Ordinal))
+ {
+ var axis=Direction3D.Create(m.End-m.Start); var f=AddFace(b,[[new Use(seam[(m.Id,m.StartNodeId)],false)],[new Use(seam[(m.Id,m.EndNodeId)],true)]]);
+ AddSurface(f,SurfaceGeometry.FromCylinder(new CylinderSurface(m.Start,axis,rs,Reference(axis))),g,bind);
+ }
+ var shell=b.AddShell(b.Model.Faces.Select(f=>f.Id).ToArray());b.AddBody([shell]);return new BrepBody(b.Model,g,bind,points);
+ EdgeId AddSeam(CubicLatticeNode n,CubicLatticeMember m,bool start){var axis=Direction3D.Create(m.End-m.Start);var dir=start?axis.ToVector():-axis.ToVector();var center=n.Position+dir*d;var refAxis=Reference(axis);var v=b.AddVertex();points[v]=center+refAxis.ToVector()*rs;var e=b.AddEdge(v,v);var cid=new CurveGeometryId(g.Curves.Count()+1);g.AddCurve(cid,CurveGeometry.FromCircle(new Circle3Curve(center,axis,rs,refAxis)));bind.AddEdgeBinding(new EdgeGeometryBinding(e,cid,new ParameterInterval(0,2d*double.Pi)));return e;}
+ }
+ private static Direction3D X()=>Direction3D.Create(new Vector3D(1,0,0)); private static Direction3D Z()=>Direction3D.Create(new Vector3D(0,0,1));
+ private static Direction3D Reference(Direction3D a)=>System.Math.Abs(a.ToVector().Z)<.9?Z():X();
+ private static void AddSurface(FaceId f,SurfaceGeometry s,BrepGeometryStore g,BrepBindingModel b){var id=new SurfaceGeometryId(g.Surfaces.Count()+1);g.AddSurface(id,s);b.AddFaceBinding(new FaceGeometryBinding(f,id));}
+ private static FaceId AddFace(TopologyBuilder b,IReadOnlyList<IReadOnlyList<Use>> loops){var ids=new List<LoopId>();foreach(var uses in loops){var l=b.AllocateLoopId();var cs=uses.Select(_=>b.AllocateCoedgeId()).ToArray();for(var i=0;i<cs.Length;i++)b.AddCoedge(new Coedge(cs[i],uses[i].Edge,l,cs[(i+1)%cs.Length],cs[(i+cs.Length-1)%cs.Length],uses[i].Reverse));b.AddLoop(new Loop(l,cs));ids.Add(l);}return b.AddFace(ids);}
+ private static string Hash(string s)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(s))).ToLowerInvariant();
+ private static KernelResult<CubicLatticeRealization> Failure(string code)=>KernelResult<CubicLatticeRealization>.Failure([new Diagnostics.KernelDiagnostic(Diagnostics.KernelDiagnosticCode.ValidationFailed,Diagnostics.KernelDiagnosticSeverity.Error,code,"CubicLattice")]);
+ private readonly record struct Use(EdgeId Edge,bool Reverse);
+}
diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
index c40916e3..b48e6d2d 100644
--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
@@ -1,5 +1,6 @@
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Topology;
@@ -77,6 +78,17 @@ public static class BrepMassProperties
return Unavailable(effective, topology, "Mass properties require a closed, orientable material boundary.");
}
+ // A lattice node is an exact spherical surface with several disjoint
+ // circular openings. Its trim arrangement is deliberately richer than
+ // the display tessellator's one-loop sphere path, but its material
+ // measure is available directly from the emitted B-rep supports and
+ // seam circles. This route consumes topology/bindings only; it never
+ // consults the lattice construction plan.
+ if (TryEvaluateExactSphereCylinderSeamBody(body, effective, topology, out var exact))
+ {
+ return exact;
+ }
+
var coarse = EvaluateAtResolution(body, effective, refinement: 1);
if (coarse.Error is not null)
{
@@ -136,6 +148,174 @@ public static class BrepMassProperties
private static BrepMassPropertiesResult Unavailable(BrepMassPropertiesOptions options, BrepMassPropertiesTopologyDiagnostics topology, string reason)
=> new(BrepMassPropertiesStatus.Unavailable, 0d, 0d, 0d, null, topology.IsEnclosed, topology.IsOrientationConsistent, [], "DeterministicTrimmedFaceTriangulationBoundaryIntegral", null, options, topology, topology.Messages.Append(reason).ToArray());
+ private static bool TryEvaluateExactSphereCylinderSeamBody(
+ BrepBody body,
+ BrepMassPropertiesOptions options,
+ BrepMassPropertiesTopologyDiagnostics topology,
+ out BrepMassPropertiesResult result)
+ {
+ result = default!;
+ var faces = body.Topology.Faces.OrderBy(face => face.Id.Value).ToArray();
+ if (faces.Length == 0)
+ {
+ return false;
+ }
+
+ var sphereFaces = new List<(FaceId Id, Geometry.Surfaces.SphereSurface Surface)>();
+ var cylinderFaces = new List<(FaceId Id, Geometry.Surfaces.CylinderSurface Surface)>();
+ foreach (var face in faces)
+ {
+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var surface) || surface is null)
+ {
+ return false;
+ }
+
+ if (surface.Kind == SurfaceGeometryKind.Sphere && surface.Sphere is { } sphere)
+ {
+ sphereFaces.Add((face.Id, sphere));
+ }
+ else if (surface.Kind == SurfaceGeometryKind.Cylinder && surface.Cylinder is { } cylinder)
+ {
+ cylinderFaces.Add((face.Id, cylinder));
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ if (sphereFaces.Count == 0 || cylinderFaces.Count == 0)
+ {
+ return false;
+ }
+
+ var volume = 0d;
+ var area = 0d;
+ var moment = new Vector3D(0d, 0d, 0d);
+ var contributions = new List<BrepMassPropertiesFaceContribution>(faces.Length);
+
+ foreach (var (faceId, sphere) in sphereFaces)
+ {
+ var capVolume = 0d;
+ var capArea = 0d;
+ var capMoment = new Vector3D(0d, 0d, 0d);
+ var loops = body.GetLoopIds(faceId);
+ if (loops.Count == 0)
+ {
+ return false;
+ }
+
+ foreach (var loopId in loops)
+ {
+ if (!TryGetSingleFullCircle(body, loopId, out var circle))
+ {
+ return false;
+ }
+
+ var offset = circle.Center - sphere.Center;
+ var distance = offset.Length;
+ if (distance <= 1e-9d || distance >= sphere.Radius || double.Abs(circle.Radius * circle.Radius + distance * distance - sphere.Radius * sphere.Radius) > sphere.Radius * sphere.Radius * 1e-6d)
+ {
+ return false;
+ }
+
+ var height = sphere.Radius - distance;
+ var removedVolume = double.Pi * height * height * (sphere.Radius - height / 3d);
+ var removedArea = 2d * double.Pi * sphere.Radius * height;
+ var axialCentroid = (double.Pi / 4d) * double.Pow(sphere.Radius * sphere.Radius - distance * distance, 2d) / removedVolume;
+ var normal = offset / distance;
+ var capCentroid = sphere.Center + normal * axialCentroid;
+ capVolume += removedVolume;
+ capArea += removedArea;
+ capMoment += ToVector(capCentroid) * removedVolume;
+ }
+
+ var fullVolume = 4d * double.Pi * double.Pow(sphere.Radius, 3d) / 3d;
+ var faceVolume = fullVolume - capVolume;
+ if (faceVolume <= 1e-12d)
+ {
+ return false;
+ }
+
+ var faceArea = 4d * double.Pi * sphere.Radius * sphere.Radius - capArea;
+ volume += faceVolume;
+ area += faceArea;
+ moment += ToVector(sphere.Center) * fullVolume - capMoment;
+ contributions.Add(new(faceId, SurfaceGeometryKind.Sphere, faceVolume, faceArea, 0, true, true, true));
+ }
+
+ foreach (var (faceId, cylinder) in cylinderFaces)
+ {
+ var loops = body.GetLoopIds(faceId);
+ if (loops.Count != 2 || !TryGetSingleFullCircle(body, loops[0], out var first) || !TryGetSingleFullCircle(body, loops[1], out var second))
+ {
+ return false;
+ }
+
+ var length = (second.Center - first.Center).Length;
+ if (length <= 1e-9d || double.Abs(first.Radius - cylinder.Radius) > cylinder.Radius * 1e-6d || double.Abs(second.Radius - cylinder.Radius) > cylinder.Radius * 1e-6d)
+ {
+ return false;
+ }
+
+ var faceVolume = double.Pi * cylinder.Radius * cylinder.Radius * length;
+ var faceArea = 2d * double.Pi * cylinder.Radius * length;
+ var centroid = new Point3D((first.Center.X + second.Center.X) / 2d, (first.Center.Y + second.Center.Y) / 2d, (first.Center.Z + second.Center.Z) / 2d);
+ volume += faceVolume;
+ area += faceArea;
+ moment += ToVector(centroid) * faceVolume;
+ contributions.Add(new(faceId, SurfaceGeometryKind.Cylinder, faceVolume, faceArea, 0, true, true, true));
+ }
+
+ if (volume <= 1e-12d)
+ {
+ return false;
+ }
+
+ var centroidResult = new Point3D(moment.X / volume, moment.Y / volume, moment.Z / volume);
+ result = new BrepMassPropertiesResult(
+ BrepMassPropertiesStatus.NumericalConverged,
+ volume,
+ volume,
+ area,
+ centroidResult,
+ topology.IsEnclosed,
+ topology.IsOrientationConsistent,
+ contributions,
+ "ExactAnalyticSphereCylinderSeamBoundaryIntegral",
+ 0d,
+ options,
+ topology,
+ topology.Messages.Append("Exact sphere-cylinder seam integration used emitted B-rep supports and trim circles; no construction-plan data was consumed.").ToArray());
+ return true;
+ }
+
+ private static bool TryGetSingleFullCircle(BrepBody body, LoopId loopId, out Circle3Curve circle)
+ {
+ circle = default;
+ var coedges = body.GetCoedgeIds(loopId);
+ if (coedges.Count != 1)
+ {
+ return false;
+ }
+
+ var coedge = body.Topology.GetCoedge(coedges[0]);
+ if (!body.TryGetEdgeCurveGeometry(coedge.EdgeId, out var curve)
+ || curve?.Kind != CurveGeometryKind.Circle3
+ || curve.Circle3 is not { } circleValue
+ || !body.Bindings.TryGetEdgeBinding(coedge.EdgeId, out var binding)
+ || binding.TrimInterval is not { } interval
+ || double.Abs((interval.End - interval.Start) - 2d * double.Pi) > 1e-6d)
+ {
+ return false;
+ }
+
+ circle = circleValue;
+ return true;
+ }
+
+ private static Vector3D ToVector(Point3D point) => new(point.X, point.Y, point.Z);
+
private static Evaluation EvaluateAtResolution(BrepBody body, BrepMassPropertiesOptions options, int refinement)
{
// Reserve the upper half of the declared deterministic segment budget for
diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
index 83b4fb17..fdcf3569 100644
--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
@@ -38,6 +38,9 @@ public sealed class Step242ExportOptions
/// <summary>Records why this route selected its preflight mode.</summary>
public BrepExportPreflightPolicy BrepExportPreflightPolicy { get; init; } = BrepExportPreflightPolicy.LegacyRoute;
+ /// <summary>Preserve a full circular edge's declared parameter interval as TRIMMED_CURVE.</summary>
+ public bool EmitFullCircleTrimmedCurves { get; init; }
+
public static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata)
{
static string Coalesce(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value!;
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 49830596..6f751d07 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -65,7 +65,7 @@ public static class Step242Exporter
var bsplineIds = new Dictionary<EdgeId, string>();
var ellipseIds = new Dictionary<EdgeId, string>();
- var outerClosedShellId = BuildClosedShell(writer, body, model, shellRepresentation.OuterShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds);
+ var outerClosedShellId = BuildClosedShell(writer, body, model, shellRepresentation.OuterShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, options.EmitFullCircleTrimmedCurves);
EmitAuxiliaryVertexPointForVertexlessAnalyticBody(writer, body, model);
if (outerClosedShellId is null)
{
@@ -82,7 +82,7 @@ public static class Step242Exporter
var orientedVoidShellIds = new List<string>();
foreach (var innerShellId in shellRepresentation.InnerShellIds.OrderBy(id => id.Value))
{
- var innerClosedShellId = BuildClosedShell(writer, body, model, innerShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds);
+ var innerClosedShellId = BuildClosedShell(writer, body, model, innerShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, options.EmitFullCircleTrimmedCurves);
if (innerClosedShellId is null)
{
return Failure($"Shell {innerShellId.Value} could not be exported.", $"Shell:{innerShellId.Value}");
@@ -158,7 +158,8 @@ public static class Step242Exporter
Dictionary<EdgeId, string> lineIds,
Dictionary<EdgeId, string> circleIds,
Dictionary<EdgeId, string> bsplineIds,
- Dictionary<EdgeId, string> ellipseIds)
+ Dictionary<EdgeId, string> ellipseIds,
+ bool emitFullCircleTrimmedCurves)
{
if (!model.TryGetShell(shellId, out var shell) || shell is null)
{
@@ -203,7 +204,7 @@ public static class Step242Exporter
if (!edgeCurveIds.TryGetValue(coedge.EdgeId, out var edgeCurveId))
{
- var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, vertexPoints, cartesianPointIds, vertexPointIds, lineIds, circleIds, bsplineIds, ellipseIds);
+ var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, vertexPoints, cartesianPointIds, vertexPointIds, lineIds, circleIds, bsplineIds, ellipseIds, emitFullCircleTrimmedCurves);
if (!edgeResult.IsSuccess)
{
return null;
@@ -614,7 +615,8 @@ public static class Step242Exporter
IDictionary<EdgeId, string> lineIds,
IDictionary<EdgeId, string> circleIds,
IDictionary<EdgeId, string> bsplineIds,
- IDictionary<EdgeId, string> ellipseIds)
+ IDictionary<EdgeId, string> ellipseIds,
+ bool emitFullCircleTrimmedCurves)
{
var edge = model.GetEdge(edgeId);
@@ -704,7 +706,7 @@ public static class Step242Exporter
// analytic edge, rather than relying on a viewer to infer it from a wire.
var trim = edgeBinding.TrimInterval.Value;
var isFullCircle = double.Abs((trim.End - trim.Start) - (2d * double.Pi)) <= 1e-12d;
- geometryCurveId = isFullCircle
+ geometryCurveId = isFullCircle && !emitFullCircleTrimmedCurves
? circleId
: writer.AddEntity("TRIMMED_CURVE", "$", Step242TextWriter.Ref(circleId),
Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(trim.Start)})"),
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index ebae54f6..2a40b55a 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -1636,9 +1636,14 @@ public static class Step242Importer
SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),
SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),
SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),
- SurfaceGeometryKind.Sphere => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
- "Multi-loop hole classification is unsupported for surface type 'Sphere'.",
- "Importer.LoopRole.UnsupportedSurfaceForHoles.Sphere"),
+ // A sphere has no privileged planar-style outer loop. In particular,
+ // a constructive lattice node carries one disjoint circular trim for
+ // every incident member. The STEP face preserves each loop's exact
+ // orientation already, so deterministic loop-id order is sufficient
+ // and avoids inventing a containment relationship on a periodic
+ // spherical parameter domain.
+ SurfaceGeometryKind.Sphere => KernelResult<IReadOnlyList<LoopBuildData>>.Success(
+ loops.OrderBy(loop => loop.LoopId.Value).ToArray()),
_ => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
$"Multi-loop hole classification is unsupported for surface type '{surface.Kind}'.",
$"Importer.LoopRole.UnsupportedSurfaceForHoles.{surface.Kind}")
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2StandaloneCubicLatticeTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2StandaloneCubicLatticeTests.cs
new file mode 100644
index 00000000..37fd187f
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2StandaloneCubicLatticeTests.cs
@@ -0,0 +1,101 @@
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2StandaloneCubicLatticeTests
+{
+ [Fact]
+ public void Parser_AdmitsStandaloneMaterialBoundsCubicTrussWithoutHost()
+ {
+ var parsed = FirmamentV2Parser.Parse(Source());
+
+ Assert.True(parsed.IsSuccess, string.Join(", ", parsed.Diagnostics));
+ var fill = Assert.Single(parsed.Document!.StandaloneLatticeFills!);
+ Assert.Equal("Domain", fill.Name);
+ Assert.Equal("CubicTruss", fill.Pattern);
+ Assert.Equal([3, 3, 3], [fill.CellsX, fill.CellsY, fill.CellsZ]);
+ Assert.Equal(26.4d, fill.Region.Size[0], 8);
+ Assert.Empty(parsed.Document.Solids);
+ }
+
+ [Fact]
+ public void Build_EmitsOneVerifiedAnalyticCubicLatticeBody()
+ {
+ var sourcePath = Path.Combine(Path.GetTempPath(), $"aetheris-m9r-{Guid.NewGuid():N}.firmament");
+ var stepPath = Path.ChangeExtension(sourcePath, ".step");
+ try
+ {
+ File.WriteAllText(sourcePath, Source());
+ var build = FirmamentBuildAndExport.Run(sourcePath, stepPath);
+
+ Assert.True(build.IsSuccess, string.Join(", ", build.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var lattice = Assert.IsType<FirmamentStandaloneLatticeReport>(build.Value.Export.Lattice);
+ Assert.Equal(64, lattice.Nodes);
+ Assert.Equal(144, lattice.Members);
+ Assert.Equal(288, lattice.Seams);
+ Assert.Equal(208, lattice.Faces);
+ Assert.Equal(64, lattice.SphericalFaces);
+ Assert.Equal(144, lattice.CylindricalFaces);
+ Assert.True(lattice.AuthoritativePlan);
+ Assert.Equal(lattice.AnalyticVolume, lattice.BrepVolume, 8);
+ Assert.Contains("SPHERICAL_SURFACE", build.Value.Export.StepText, StringComparison.Ordinal);
+ Assert.Contains("CYLINDRICAL_SURFACE", build.Value.Export.StepText, StringComparison.Ordinal);
+ Assert.Contains("TRIMMED_CURVE", build.Value.Export.StepText, StringComparison.Ordinal);
+ Assert.True(Step242Importer.ImportBody(build.Value.Export.StepText).IsSuccess);
+ }
+ finally
+ {
+ if (File.Exists(sourcePath)) File.Delete(sourcePath);
+ if (File.Exists(stepPath)) File.Delete(stepPath);
+ }
+ }
+
+ [Theory]
+ [InlineData("nodeRadius: 1.1mm", "node-radius-too-small-for-struts")]
+ [InlineData("strutRadius: 0.4mm", "minimum-strut-diameter-violation")]
+ public void Build_RejectsInvalidStandaloneDfmBeforeEmission(string replacement, string expectedDiagnostic)
+ {
+ var sourcePath = Path.Combine(Path.GetTempPath(), $"aetheris-m9r-invalid-{Guid.NewGuid():N}.firmament");
+ var stepPath = Path.ChangeExtension(sourcePath, ".step");
+ try
+ {
+ var source = replacement.StartsWith("nodeRadius", StringComparison.Ordinal)
+ ? Source().Replace("nodeRadius: 1.2mm", replacement, StringComparison.Ordinal)
+ : Source().Replace("strutRadius: 0.8mm", replacement, StringComparison.Ordinal);
+ File.WriteAllText(sourcePath, source);
+ var build = FirmamentBuildAndExport.Run(sourcePath, stepPath);
+
+ Assert.False(build.IsSuccess);
+ Assert.Contains(build.Diagnostics, diagnostic => diagnostic.Message.Contains(expectedDiagnostic, StringComparison.Ordinal));
+ Assert.False(File.Exists(stepPath));
+ }
+ finally
+ {
+ if (File.Exists(sourcePath)) File.Delete(sourcePath);
+ if (File.Exists(stepPath)) File.Delete(stepPath);
+ }
+ }
+
+ private static string Source() => """
+ model CubicLatticeSample {
+ units mm
+ template<Additive> PolymerLattice {
+ concept MinimumStrutDiameter: 1.0mm
+ concept MinimumNodeDiameter: 2.0mm
+ concept MinimumFeatureSpacing: 0.5mm
+ }
+ region Domain { box { size: [26.4mm, 26.4mm, 26.4mm] } }
+ fill Domain {
+ pattern: CubicTruss {
+ cells: [3, 3, 3]
+ cellSize: 8mm
+ strutRadius: 0.8mm
+ nodeRadius: 1.2mm
+ }
+ placement: MaterialBounds
+ }
+ }
+ """;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 29233f51..b97867da 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -4,6 +4,7 @@ using Aetheris.Kernel.Core.Air;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Verification;
using Aetheris.Kernel.Core.Brep.Boolean;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Curves;
@@ -57,6 +58,11 @@ public static class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Failure(dfm.Diagnostics);
}
+ if (TryExportV2StandaloneCubicLattice(v2Parse.Document) is { } latticeExport)
+ {
+ return latticeExport;
+ }
+
if (TryExportV2HollowBody(v2Parse.Document) is { } hollowExport)
{
return hollowExport;
@@ -178,6 +184,64 @@ public static class FirmamentBuildAndExport
return FirmamentStepExporter.Export(new FirmamentCompileRequest(new FirmamentSourceDocument(sourceText)));
}
+ private static KernelResult<FirmamentStepExportResult>? TryExportV2StandaloneCubicLattice(FirmamentV2Document document)
+ {
+ var fills = document.StandaloneLatticeFills ?? [];
+ if (fills.Count == 0) return null;
+ if (fills.Count != 1)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "standalone-fill-multiple-unsupported", "FirmamentV2.CubicLattice")]);
+ }
+
+ var fill = fills[0];
+ var center = new Point3D(fill.Region.Center[0], fill.Region.Center[1], fill.Region.Center[2]);
+ var realization = CubicLatticeBRepPlanner.Create(fill.CellsX, fill.CellsY, fill.CellsZ, fill.CellSize, fill.StrutRadius, fill.NodeRadius, center);
+ if (!realization.IsSuccess || realization.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(realization.Diagnostics);
+ var body = realization.Value.Body;
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid || !FirmamentManifoldChecker.IsManifold(body))
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "lattice-topology-verification-failed", "FirmamentV2.CubicLattice")]);
+ }
+
+ var mass = BrepMassProperties.Evaluate(body);
+ if (mass.Status == BrepMassPropertiesStatus.Unavailable || mass.AbsoluteVolume <= 0d || mass.Centroid is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "lattice-topology-verification-failed: BRep mass properties unavailable", "FirmamentV2.CubicLattice")]);
+ }
+
+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
+ {
+ ProductName = fill.Name,
+ ApplicationName = "Aetheris.Firmament.CubicTruss.M9R",
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ EmitFullCircleTrimmedCurves = true,
+ });
+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var reimport = Step242Importer.ImportBody(step.Value);
+ if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(reimport.IsSuccess
+ ? [new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "lattice-topology-verification-failed: STEP reimport is not manifold", "FirmamentV2.CubicLattice")]
+ : reimport.Diagnostics);
+ }
+
+ var template = (document.Templates ?? []).Single(template => string.Equals(template.Process, "Additive", StringComparison.OrdinalIgnoreCase));
+ var graph = realization.Value.Plan.Construction;
+ var centroid = mass.Centroid.Value;
+ var report = new FirmamentStandaloneLatticeReport(
+ template.Name, fill.Pattern, [fill.CellsX, fill.CellsY, fill.CellsZ], fill.CellSize, fill.StrutRadius, fill.NodeRadius, fill.Region.Size, fill.Placement,
+ graph.Nodes.Count, graph.Members.Count, realization.Value.Plan.SeamCount,
+ graph.Nodes.Count(node => node.Valence == 3), graph.Nodes.Count(node => node.Valence == 4), graph.Nodes.Count(node => node.Valence == 5), graph.Nodes.Count(node => node.Valence == 6),
+ realization.Value.Plan.IsAuthoritative, realization.Value.Plan.Signature,
+ body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(),
+ body.Geometry.Surfaces.Count(pair => pair.Value.Kind == SurfaceGeometryKind.Sphere), body.Geometry.Surfaces.Count(pair => pair.Value.Kind == SurfaceGeometryKind.Cylinder),
+ realization.Value.AnalyticVolume, mass.AbsoluteVolume, double.Abs(realization.Value.AnalyticVolume - mass.AbsoluteVolume), mass.SurfaceArea,
+ [centroid.X, centroid.Y, centroid.Z], Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant(), true, true);
+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, fill.Name, 0, "standalone-lattice", "cubic-truss", Lattice: report));
+ }
+
private static KernelResult<FirmamentStepExportResult>? TryExportV2AirChamferBody(FirmamentV2Document document)
{
var finishes = (document.ModifyBlocks ?? []).SelectMany(m => (m.EdgeFinishes ?? []).Select(f => (Modify: m, Finish: f))).ToArray();
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index 5ea9cb18..c51919b0 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -16,7 +16,41 @@ public sealed record FirmamentStepExportResult(
Aetheris.Kernel.Firmament.FirmamentV2.ConceptIrDocument? ConceptIr = null,
IReadOnlyList<FirmamentHoleFeatureReport>? Features = null,
FirmamentRoundedBoxReport? RoundedBox = null,
- FirmamentHollowBodyReport? Hollow = null);
+ FirmamentHollowBodyReport? Hollow = null,
+ FirmamentStandaloneLatticeReport? Lattice = null);
+
+public sealed record FirmamentStandaloneLatticeReport(
+ string Template,
+ string Pattern,
+ IReadOnlyList<int> Cells,
+ double CellSize,
+ double StrutRadius,
+ double NodeRadius,
+ IReadOnlyList<double> DomainSize,
+ string Placement,
+ int Nodes,
+ int Members,
+ int Seams,
+ int Valence3,
+ int Valence4,
+ int Valence5,
+ int Valence6,
+ bool AuthoritativePlan,
+ string Signature,
+ int Vertices,
+ int Edges,
+ int Faces,
+ int SphericalFaces,
+ int CylindricalFaces,
+ double AnalyticVolume,
+ double BrepVolume,
+ double VolumeDelta,
+ double SurfaceArea,
+ IReadOnlyList<double> Centroid,
+ string StepSha256,
+ bool ReimportSucceeded,
+ bool ReimportedManifold,
+ bool LegacyFallback = false);
/// <summary>Export evidence for the generic Primitive&lt;Hollow&gt; path.</summary>
public sealed record FirmamentHollowBodyReport(
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 4ca8a100..3bca6e4f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -1,6 +1,6 @@
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null)
+public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null)
{
public FirmamentV2SolidBinding Solid => Solids[^1];
public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>
@@ -179,6 +179,8 @@ public sealed record FirmamentV2ConceptDecl(string Name, string RawValue, double
public sealed record FirmamentV2TemplateDecl(string Process, string Name, IReadOnlyList<FirmamentV2ConceptDecl> Concepts);
public sealed record FirmamentV2FillRegionDecl(string Name, IReadOnlyList<double> Size, IReadOnlyList<double> Center, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2LatticeFillDecl(string Name, string Host, FirmamentV2FillRegionDecl Region, string Pattern, double CellSize, double StrutRadius, string BoundaryPolicy, FirmamentV2SourceSpan SourceSpan);
+/// <summary>M9R's admitted standalone material body. It is intentionally distinct from the deferred host-replacement Fill.</summary>
+public sealed record FirmamentV2StandaloneLatticeFillDecl(string Name, FirmamentV2FillRegionDecl Region, string Pattern, int CellsX, int CellsY, int CellsZ, double CellSize, double StrutRadius, double NodeRadius, string Placement, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2ParseResult(bool IsSuccess, FirmamentV2Document? Document, IReadOnlyList<string> Diagnostics)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs
index 8667064b..9e190750 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs
@@ -83,6 +83,44 @@ internal static class FirmamentV2DfmEnforcement
}
}
+ foreach (var fill in document.StandaloneLatticeFills ?? [])
+ {
+ var template = (document.Templates ?? []).SingleOrDefault(t => string.Equals(t.Process, "Additive", StringComparison.OrdinalIgnoreCase));
+ if (template is null)
+ {
+ diagnostics.Add(Error("additive-template-required: standalone CubicTruss requires one Template<Additive> context."));
+ continue;
+ }
+
+ double Concept(string name)
+ {
+ var concept = template.Concepts.SingleOrDefault(c => string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase));
+ if (concept is null || !string.Equals(concept.Unit, document.Units, StringComparison.OrdinalIgnoreCase))
+ {
+ diagnostics.Add(Error($"additive-concept-required: template '{template.Name}' requires typed length concept '{name}' in '{document.Units}'."));
+ return double.NaN;
+ }
+ return concept.NumericValue;
+ }
+
+ var minStrut = Concept("MinimumStrutDiameter");
+ var minNode = Concept("MinimumNodeDiameter");
+ var minSpacing = Concept("MinimumFeatureSpacing");
+ if (!double.IsFinite(minStrut) || !double.IsFinite(minNode) || !double.IsFinite(minSpacing)) continue;
+ var strutDiameter = 2d * fill.StrutRadius;
+ var nodeDiameter = 2d * fill.NodeRadius;
+ var spacing = fill.CellSize - 2d * fill.NodeRadius;
+ if (strutDiameter + 1e-9d < minStrut) diagnostics.Add(Error($"minimum-strut-diameter-violation: template '{template.Name}', feature '{fill.Name}', actual {strutDiameter:R}{document.Units}, required {minStrut:R}{document.Units}."));
+ if (nodeDiameter + 1e-9d < minNode) diagnostics.Add(Error($"minimum-node-diameter-violation: template '{template.Name}', feature '{fill.Name}', actual {nodeDiameter:R}{document.Units}, required {minNode:R}{document.Units}."));
+ if (spacing + 1e-9d < minSpacing) diagnostics.Add(Error($"minimum-feature-spacing-violation: template '{template.Name}', feature '{fill.Name}', actual {spacing:R}{document.Units}, required {minSpacing:R}{document.Units}."));
+ if (fill.NodeRadius <= double.Sqrt(2d) * fill.StrutRadius) diagnostics.Add(Error($"node-radius-too-small-for-struts: feature '{fill.Name}', nodeRadius {fill.NodeRadius:R}{document.Units}, strutRadius {fill.StrutRadius:R}{document.Units}."));
+ var seam = double.IsFinite(fill.NodeRadius) && double.IsFinite(fill.StrutRadius) && fill.NodeRadius > fill.StrutRadius
+ ? double.Sqrt(fill.NodeRadius * fill.NodeRadius - fill.StrutRadius * fill.StrutRadius) : double.PositiveInfinity;
+ if (fill.CellSize - 2d * seam <= 1e-9d) diagnostics.Add(Error($"member-consumed-by-nodes: feature '{fill.Name}', exposedLength {fill.CellSize - 2d * seam:R}{document.Units}."));
+ var expected = new[] { fill.CellsX * fill.CellSize + 2d * fill.NodeRadius, fill.CellsY * fill.CellSize + 2d * fill.NodeRadius, fill.CellsZ * fill.CellSize + 2d * fill.NodeRadius };
+ if (fill.Region.Size.Count != 3 || expected.Where((value, index) => double.Abs(value - fill.Region.Size[index]) > 1e-9d).Any()) diagnostics.Add(Error($"material-bounds-mismatch: feature '{fill.Name}' requires domain [{expected[0]:R}, {expected[1]:R}, {expected[2]:R}]{document.Units} for exact MaterialBounds placement."));
+ }
+
return diagnostics.Count == 0
? KernelResult<object>.Success(new object())
: KernelResult<object>.Failure(diagnostics);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 5c2757f9..be7992d6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -47,6 +47,14 @@ public static class FirmamentV2Parser
public const string FillInvalidStrutRadius = "firmament-v2-fill-invalid-strut-radius";
public const string FillUnsupportedBoundaryPolicy = "firmament-v2-fill-unsupported-boundary-policy";
public const string FillMultipleUnsupported = "firmament-v2-fill-multiple-unsupported";
+ public const string StandaloneFillRegionRequired = "standalone-fill-region-required";
+ public const string UnsupportedStandaloneFillPattern = "unsupported-standalone-fill-pattern";
+ public const string InvalidCellCount = "invalid-cell-count";
+ public const string CellSizeMustBePositive = "cell-size-must-be-positive";
+ public const string StrutRadiusMustBePositive = "strut-radius-must-be-positive";
+ public const string NodeRadiusMustBePositive = "node-radius-must-be-positive";
+ public const string MaterialBoundsMismatch = "material-bounds-mismatch";
+ public const string StandaloneFillMultipleUnsupported = "standalone-fill-multiple-unsupported";
public const string UnknownConstructionPolicy = "firmament-v2-unknown-construction-policy";
public const string PrimitiveDoesNotSatisfyHollowConstructible = "firmament-v2-primitive-does-not-satisfy-hollow-constructible";
public const string WallThicknessRequired = "firmament-v2-wall-thickness-required";
@@ -275,7 +283,8 @@ public static class FirmamentV2Parser
var solidMatches = FindSolids(source).ToArray();
if (solidMatches.Length == 0 && LegacyEqualsSolidRegex.IsMatch(source)) diagnostics.Add(UnsupportedConstruct);
- if (solidMatches.Length == 0) diagnostics.Add(MissingSolid);
+ var appearsStandaloneLattice = Regex.IsMatch(source, @"\bfill\s+[A-Za-z_][A-Za-z0-9_]*\s*\{[\s\S]*?\bpattern\s*:\s*CubicTruss\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (solidMatches.Length == 0 && !appearsStandaloneLattice) diagnostics.Add(MissingSolid);
var solids = new List<FirmamentV2SolidBinding>();
var byName = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);
@@ -308,14 +317,15 @@ public static class FirmamentV2Parser
var modifyBlocks = ParseModifyBlocks(source, byName, diagnostics);
var templates = ParseTemplates(source, diagnostics);
var latticeFills = ParseLatticeFills(source, byName, diagnostics);
+ var standaloneLatticeFills = ParseStandaloneLatticeFills(source, diagnostics);
var recognizedRegions = ParseRecognizedRegions(source, byName, diagnostics);
var replacements = ParseReplacements(source, byName, recognizedRegions, diagnostics);
var (pmi, pmiBlock, boundPmi) = ParsePmi(source, byName, modifyBlocks, recognizedRegions, boundLets, boundLetRecords, diagnostics);
var (manufacturingConcepts, featureConcepts) = ParseConceptApplications(source, boundLets, boundLetRecords, conceptCatalog, diagnostics);
FirmamentV2Document? document = null;
- if (modelMatch.Success && unitsMatch.Success && solids.Count > 0 && !diagnostics.Any(d => d.StartsWith("firmament-v2-fill-", StringComparison.Ordinal)))
- document = new FirmamentV2Document(modelMatch.Groups["name"].Value, unitsMatch.Groups["units"].Value, solids, modifyBlocks, templates, pmi, recognizedRegions, replacements, lets, boundLets, letRecords, boundLetRecords, manufacturingConcepts, featureConcepts, pmiBlock, boundPmi, null, latticeFills);
+ if (modelMatch.Success && unitsMatch.Success && (solids.Count > 0 || standaloneLatticeFills.Count > 0) && !diagnostics.Any(d => d.StartsWith("firmament-v2-fill-", StringComparison.Ordinal)))
+ document = new FirmamentV2Document(modelMatch.Groups["name"].Value, unitsMatch.Groups["units"].Value, solids, modifyBlocks, templates, pmi, recognizedRegions, replacements, lets, boundLets, letRecords, boundLetRecords, manufacturingConcepts, featureConcepts, pmiBlock, boundPmi, null, latticeFills, standaloneLatticeFills);
var hasFatalDiagnostics = diagnostics.Any(IsFatalDiagnosticCode);
diagnostics.Add(document is null || hasFatalDiagnostics ? "firmament-v2-parse-failed" : "firmament-v2-parse-succeeded");
@@ -986,7 +996,7 @@ public static class FirmamentV2Parser
|| code.StartsWith(ConceptIrResolver.PointProjectionUnsupported, StringComparison.Ordinal)
|| code.StartsWith("firmament-static-", StringComparison.Ordinal);
- public static bool IsFatalDiagnosticCode(string code) => IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch;
+ public static bool IsFatalDiagnosticCode(string code) => IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;
private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics)
{
@@ -1425,7 +1435,8 @@ public static class FirmamentV2Parser
var boxBody = body[(boxOpen + 1)..boxClose];
var size = Regex.Match(boxBody, @"\bsize\s*:\s*\[(?<v>[^\]]+)\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
var center = Regex.Match(boxBody, @"\bcenter\s*:\s*\[(?<v>[^\]]+)\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- if (!size.Success || !center.Success || !TryParseLatticeTriple(size.Groups["v"].Value, positive: true, out var sizeValues) || !TryParseLatticeTriple(center.Groups["v"].Value, positive: false, out var centerValues)) { diagnostics.Add(FillRegionInvalid); continue; }
+ IReadOnlyList<double> centerValues = [0d, 0d, 0d];
+ if (!size.Success || !TryParseLatticeTriple(size.Groups["v"].Value, positive: true, out var sizeValues) || (center.Success && !TryParseLatticeTriple(center.Groups["v"].Value, positive: false, out centerValues))) { diagnostics.Add(FillRegionInvalid); continue; }
if (!regions.TryAdd(match.Groups["name"].Value, new(match.Groups["name"].Value, sizeValues, centerValues, new(match.Index, close - match.Index + 1)))) diagnostics.Add(FillRegionInvalid);
}
@@ -1437,9 +1448,10 @@ public static class FirmamentV2Parser
if (close < 0) { diagnostics.Add(FillRegionInvalid); continue; }
var body = source[(open + 1)..close];
if (!regions.TryGetValue(match.Groups["name"].Value, out var region)) { diagnostics.Add(FillUnknownRegion); continue; }
+ var pattern = Regex.Match(body, @"\bpattern\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
var host = Regex.Match(body, @"\bhost\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (!host.Success && pattern.Success && string.Equals(pattern.Groups["v"].Value, "CubicTruss", StringComparison.OrdinalIgnoreCase)) continue;
if (!host.Success || !solids.ContainsKey(host.Groups["v"].Value)) { diagnostics.Add(FillUnknownHost); continue; }
- var pattern = Regex.Match(body, @"\bpattern\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (!pattern.Success || !string.Equals(pattern.Groups["v"].Value, "OctetTruss", StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(FillUnsupportedPattern); continue; }
var patternOpen = body.IndexOf('{', pattern.Index);
var patternClose = FindMatchingBrace(body, patternOpen);
@@ -1454,6 +1466,64 @@ public static class FirmamentV2Parser
return fills;
}
+ private static IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl> ParseStandaloneLatticeFills(string source, List<string> diagnostics)
+ {
+ var regions = new Dictionary<string, FirmamentV2FillRegionDecl>(StringComparer.Ordinal);
+ foreach (Match match in FillRegionHeaderRegex.Matches(source))
+ {
+ var open = source.IndexOf('{', match.Index); var close = FindMatchingBrace(source, open);
+ if (close < 0) continue;
+ var body = source[(open + 1)..close]; var box = Regex.Match(body, @"\bbox\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (!box.Success) continue;
+ var boxOpen = body.IndexOf('{', box.Index); var boxClose = FindMatchingBrace(body, boxOpen);
+ if (boxClose < 0) { diagnostics.Add(StandaloneFillRegionRequired); continue; }
+ var boxBody = body[(boxOpen + 1)..boxClose];
+ var size = Regex.Match(boxBody, @"\bsize\s*:\s*\[(?<v>[^\]]+)\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ var center = Regex.Match(boxBody, @"\bcenter\s*:\s*\[(?<v>[^\]]+)\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ IReadOnlyList<double> location = [0d, 0d, 0d];
+ if (!size.Success || !TryParseLatticeTriple(size.Groups["v"].Value, positive: true, out var dimensions) || (center.Success && !TryParseLatticeTriple(center.Groups["v"].Value, positive: false, out location))) { diagnostics.Add(StandaloneFillRegionRequired); continue; }
+ regions[match.Groups["name"].Value] = new FirmamentV2FillRegionDecl(match.Groups["name"].Value, dimensions, location, new FirmamentV2SourceSpan(match.Index, close - match.Index + 1));
+ }
+
+ var fills = new List<FirmamentV2StandaloneLatticeFillDecl>();
+ foreach (Match match in FillHeaderRegex.Matches(source))
+ {
+ var open = source.IndexOf('{', match.Index); var close = FindMatchingBrace(source, open);
+ if (close < 0) continue;
+ var body = source[(open + 1)..close];
+ var pattern = Regex.Match(body, @"\bpattern\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (!pattern.Success || !string.Equals(pattern.Groups["v"].Value, "CubicTruss", StringComparison.OrdinalIgnoreCase)) continue;
+ if (Regex.IsMatch(body, @"\bhost\s*:", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)) { diagnostics.Add(UnsupportedStandaloneFillPattern); continue; }
+ if (!regions.TryGetValue(match.Groups["name"].Value, out var region)) { diagnostics.Add(StandaloneFillRegionRequired); continue; }
+ var patternOpen = body.IndexOf('{', pattern.Index); var patternClose = FindMatchingBrace(body, patternOpen);
+ if (patternClose < 0) { diagnostics.Add(UnsupportedStandaloneFillPattern); continue; }
+ var p = body[(patternOpen + 1)..patternClose];
+ var cells = Regex.Match(p, @"\bcells\s*:\s*\[(?<v>[^\]]+)\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (!cells.Success || !TryParseLatticeCellTriple(cells.Groups["v"].Value, out var counts)) { diagnostics.Add(InvalidCellCount); continue; }
+ if (!TryReadLatticePositive(p, "cellSize", out var cellSize)) { diagnostics.Add(CellSizeMustBePositive); continue; }
+ if (!TryReadLatticePositive(p, "strutRadius", out var strutRadius)) { diagnostics.Add(StrutRadiusMustBePositive); continue; }
+ if (!TryReadLatticePositive(p, "nodeRadius", out var nodeRadius)) { diagnostics.Add(NodeRadiusMustBePositive); continue; }
+ var placement = Regex.Match(body, @"\bplacement\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (!placement.Success || !string.Equals(placement.Groups["v"].Value, "MaterialBounds", StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(MaterialBoundsMismatch); continue; }
+ fills.Add(new(match.Groups["name"].Value, region, "CubicTruss", counts[0], counts[1], counts[2], cellSize, strutRadius, nodeRadius, "MaterialBounds", new FirmamentV2SourceSpan(match.Index, close - match.Index + 1)));
+ }
+ if (fills.Count > 1) diagnostics.Add(StandaloneFillMultipleUnsupported);
+ return fills;
+ }
+
+ private static bool TryParseLatticeCellTriple(string text, out IReadOnlyList<int> values)
+ {
+ var parts = text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
+ var parsed = new List<int>(3);
+ foreach (var part in parts)
+ {
+ if (!int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) || value <= 0) { values = []; return false; }
+ parsed.Add(value);
+ }
+ values = parsed;
+ return parsed.Count == 3;
+ }
+
private static bool TryReadLatticePositive(string body, string name, out double value)
{
value = 0d;
diff --git a/docs/air/air-lattice-fill-m9.md b/docs/air/air-lattice-fill-m9.md
index 2741aace..d9540c72 100644
--- a/docs/air/air-lattice-fill-m9.md
+++ b/docs/air/air-lattice-fill-m9.md
@@ -1,5 +1,7 @@
# AIR-LATTICE-FILL-M9 — explicit-region lattice-fill foundation
+> Status after M9R: this is a deferred host-replacement design, not a materialized STEP route. The completed lattice capability is the standalone CubicTruss proof documented in [AIR-LATTICE-PRIMITIVE-M9R](air-lattice-primitive-m9r.md).
+
> Aetheris does not guess which material is expendable.
>
> The FillRegion is an explicit engineering authority boundary.
diff --git a/docs/air/air-lattice-primitive-m9r.md b/docs/air/air-lattice-primitive-m9r.md
new file mode 100644
index 00000000..1f64ff18
--- /dev/null
+++ b/docs/air/air-lattice-primitive-m9r.md
@@ -0,0 +1,60 @@
+# AIR-LATTICE-PRIMITIVE-M9R — standalone exact CubicTruss
+
+M9R is Aetheris's bounded pre-release additive proof. It compiles one standalone lattice body; it does not lightweight an existing part.
+
+## Admitted Firmament
+
+```firmament
+model CubicLatticeSample {
+ units mm
+ template<Additive> PolymerLattice {
+ concept MinimumStrutDiameter: 1.0mm
+ concept MinimumNodeDiameter: 2.0mm
+ concept MinimumFeatureSpacing: 0.5mm
+ }
+ region Domain { box { size: [26.4mm, 26.4mm, 26.4mm] } }
+ fill Domain {
+ pattern: CubicTruss {
+ cells: [3, 3, 3]
+ cellSize: 8mm
+ strutRadius: 0.8mm
+ nodeRadius: 1.2mm
+ }
+ placement: MaterialBounds
+ }
+}
+```
+
+`Region` is the actual material-bounds declaration. `Fill` has no `Host`; it produces `StandaloneBody` materialization. The parser accepts one axis-aligned box domain, one `CubicTruss`, positive integral cell counts, and exact `MaterialBounds` only. The declared size must equal `N * CellSize + 2 * NodeRadius` on each axis—there is no rescaling or clipping.
+
+## AIR, graph, and plan
+
+`CubicLatticeFeature` preserves the host-null intent, box domain, cells, uniform radii, `MaterialBounds`, additive context, and source provenance. `CubicLatticeConstruction` is the hierarchical construction AIR used by `LatticeBodyBRepPlan`: cell domain → deterministic node graph → member graph → junction valence → seam instances.
+
+For `Nx, Ny, Nz`, nodes are `(i,j,k)` for `0..Nx`, `0..Ny`, and `0..Nz`; their centres are spaced by `CellSize`. Members are only positive-X, positive-Y, and positive-Z nearest-neighbour pairs. IDs are `cubic:node:i:j:k` and `cubic:member:axis:canonical-start:canonical-end`, so construction does not depend on traversal order.
+
+The canonical 3×3×3 result has 27 cells, 64 nodes, 144 members, and 288 endpoint seams. Its node classes are 8 valence-3 corners, 24 valence-4 edge nodes, 24 valence-5 face nodes, and 8 valence-6 interior nodes.
+
+`LatticeBodyBRepPlan` is authoritative and immutable. It owns one exact spherical face per node, one exact cylindrical lateral face per member, every circular seam/edge/loop/coedge, and a deterministic SHA-256 signature. It does not Boolean-union separate solids, emit cylinder caps, or emit a planar domain skin.
+
+## Exact junction geometry
+
+For strut radius `Rs` and node radius `Rn`, each sphere-cylinder seam lies `d = sqrt(Rn² - Rs²)` from the node centre. A cylinder has exposed length `CellSize - 2d`; it is admitted only when positive. The spherical cap opening has `alpha = asin(Rs/Rn)`. M9R requires `Rn > sqrt(2) * Rs`, so openings on orthogonal cubic directions cannot overlap.
+
+The canonical parameters give `d = sqrt(0.8) mm` and positive exposed members. Every seam is a full exact `CIRCLE`, used exactly once by its sphere and once by its cylinder. The resulting BRep is one connected, closed, manifold body.
+
+## DFM and verification
+
+`Template<Additive>` is a typed, inspectable manufacturing context. Before BRep/STEP emission M9R enforces minimum strut diameter, node diameter, non-incident spacing, cap-overlap admission, positive exposed length, and exact material-bounds fit. Examples include `minimum-strut-diameter-violation`, `minimum-node-diameter-violation`, `minimum-feature-spacing-violation`, `node-radius-too-small-for-struts`, `member-consumed-by-nodes`, and `material-bounds-mismatch`.
+
+The M8 verifier operates on emitted BRep topology and bindings. For this multi-loop spherical topology it has an exact sphere-cylinder-seam integration path: retained sphere volume after each spherical cap removal plus exposed cylinder volume. It consumes the materialized BRep supports and circles, not the construction plan. STEP reimport preserves the one body, 208 faces, 288 edges, 288 vertices, 64 `SPHERICAL_SURFACE`s, and 144 `CYLINDRICAL_SURFACE`s.
+
+The canonical artifact verified on 2026-08-04 has analytic and BRep volume `2168.779690804 mm³`, surface area `4990.344609935 mm²`, and centroid approximately `(0,0,0)`. Its 229,831-byte STEP has SHA-256 `e06fe7f345ce9e694c40a816e6061b2c019a9cf3d81a54e284509f530b30aeac` and contains 64 `SPHERICAL_SURFACE`, 144 `CYLINDRICAL_SURFACE`, 288 `CIRCLE`, and 288 `TRIMMED_CURVE` entities. External CAD inspection is `ExternalInspectionPending`—no CAD Assistant visual claim is made.
+
+## Scope and post-release roadmap
+
+M9R does **not** support host replacement, skins, cavities, through-hole coexistence, bonding, OctetTruss materialization, imported STEP hosts, curved regions, graded lattices, TPMS/SDF extraction, FEA, or toolpaths. The earlier M9 host-fill semantics remain in the codebase with their `lattice-fill-brep-plan-not-materialized` safety gate.
+
+## Post-Release Lattice Roadmap
+
+Fitting a lattice into an explicit region, OctetTruss, retained-host replacement, imported STEP lightweighting, boundary bonding, graded fields, FEA-driven distribution, implicit/TPMS backends, and additive toolpath lowering are all **deferred until after the initial Aetheris release**. They are not current support and are not required for M9R admission. Pre-release work returns to CNC and general mechanical CAD after M9R.
diff --git a/fixtures/FirmamentV2/Lattice/cubic-truss-1x1x1.debug.firmament b/fixtures/FirmamentV2/Lattice/cubic-truss-1x1x1.debug.firmament
new file mode 100644
index 00000000..21b84d74
--- /dev/null
+++ b/fixtures/FirmamentV2/Lattice/cubic-truss-1x1x1.debug.firmament
@@ -0,0 +1,6 @@
+model CubicLatticeDebug {
+ units mm
+ template<Additive> PolymerLattice { concept MinimumStrutDiameter: 1.0mm concept MinimumNodeDiameter: 2.0mm concept MinimumFeatureSpacing: 0.5mm }
+ region Domain { box { size: [10.4mm, 10.4mm, 10.4mm] } }
+ fill Domain { pattern: CubicTruss { cells: [1, 1, 1] cellSize: 8mm strutRadius: 0.8mm nodeRadius: 1.2mm } placement: MaterialBounds }
+}
diff --git a/fixtures/FirmamentV2/Lattice/cubic-truss-2x1x1.debug.firmament b/fixtures/FirmamentV2/Lattice/cubic-truss-2x1x1.debug.firmament
new file mode 100644
index 00000000..26496227
--- /dev/null
+++ b/fixtures/FirmamentV2/Lattice/cubic-truss-2x1x1.debug.firmament
@@ -0,0 +1,6 @@
+model CubicLatticeDebug {
+ units mm
+ template<Additive> PolymerLattice { concept MinimumStrutDiameter: 1.0mm concept MinimumNodeDiameter: 2.0mm concept MinimumFeatureSpacing: 0.5mm }
+ region Domain { box { size: [18.4mm, 10.4mm, 10.4mm] } }
+ fill Domain { pattern: CubicTruss { cells: [2, 1, 1] cellSize: 8mm strutRadius: 0.8mm nodeRadius: 1.2mm } placement: MaterialBounds }
+}
diff --git a/fixtures/FirmamentV2/Lattice/cubic-truss-2x2x2.debug.firmament b/fixtures/FirmamentV2/Lattice/cubic-truss-2x2x2.debug.firmament
new file mode 100644
index 00000000..068bfa42
--- /dev/null
+++ b/fixtures/FirmamentV2/Lattice/cubic-truss-2x2x2.debug.firmament
@@ -0,0 +1,6 @@
+model CubicLatticeDebug {
+ units mm
+ template<Additive> PolymerLattice { concept MinimumStrutDiameter: 1.0mm concept MinimumNodeDiameter: 2.0mm concept MinimumFeatureSpacing: 0.5mm }
+ region Domain { box { size: [18.4mm, 18.4mm, 18.4mm] } }
+ fill Domain { pattern: CubicTruss { cells: [2, 2, 2] cellSize: 8mm strutRadius: 0.8mm nodeRadius: 1.2mm } placement: MaterialBounds }
+}
diff --git a/fixtures/FirmamentV2/Lattice/cubic-truss-3x3x3.valid.firmament b/fixtures/FirmamentV2/Lattice/cubic-truss-3x3x3.valid.firmament
new file mode 100644
index 00000000..f9ac9b4a
--- /dev/null
+++ b/fixtures/FirmamentV2/Lattice/cubic-truss-3x3x3.valid.firmament
@@ -0,0 +1,26 @@
+model CubicLatticeSample {
+ units mm
+
+ template<Additive> PolymerLattice {
+ concept MinimumStrutDiameter: 1.0mm
+ concept MinimumNodeDiameter: 2.0mm
+ concept MinimumFeatureSpacing: 0.5mm
+ }
+
+ region Domain {
+ box {
+ size: [26.4mm, 26.4mm, 26.4mm]
+ }
+ }
+
+ fill Domain {
+ pattern: CubicTruss {
+ cells: [3, 3, 3]
+ cellSize: 8mm
+ strutRadius: 0.8mm
+ nodeRadius: 1.2mm
+ }
+
+ placement: MaterialBounds
+ }
+}