Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Generalize exact coaxial construction beyond hex bolts
Yuechen Lidcca2972a3b7
diff --git a/Aetheris.Kernel.Firmament.Tests/ExactConstructionIrM1Tests.cs b/Aetheris.Kernel.Firmament.Tests/ExactConstructionIrM1Tests.csnew file mode 100644index 00000000..ff739fb6--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ExactConstructionIrM1Tests.cs@@ -0,0 +1,99 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.StandardLibrary;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ExactConstructionIrM1Tests+{+ [Fact]+ public void RegularPrism_IsIndependentOfBoltAndDerivesDeterministicGeometry()+ {+ var hex = new RegularPrismConstruction("hex", 6, 13d, 0d, 5d);+ var octagon = new RegularPrismConstruction("octagon", 8, 20d, -2d, 7d, 22.5d);+ Assert.Equal(6.5d, hex.Apothem, 12);+ Assert.Equal(13d / Math.Sqrt(3d), hex.Circumradius, 12);+ Assert.Equal(10d / Math.Cos(Math.PI / 8d), octagon.Circumradius, 12);+ Assert.Equal(22.5d, octagon.OrientationDegrees);+ }++ [Fact]+ public void CoaxialPlan_ExplicitlySharesAnalyticSupportsAndPreservesRootBlend()+ {+ var plan = HexBoltConstructionPlanner.Plan(McMasterHexBoltSpecs.Reference91180A151, "fixture");+ Assert.True(plan.IsSuccess);+ Assert.Contains(plan.Value.Stack.Sections, x => x is ConcaveFilletConstruction);+ Assert.Contains(plan.Value.Stack.Sections, x => x is ConePlanarTrimConstruction);++ // A non-bolt fixture can use the same two exact axial intent nodes without+ // importing HexBoltSpec or any bolt semantic name.+ AxialSectionStackConstruction steppedShaft = new("stepped-shaft", [+ new AxialCylinderConstruction("shaft", 5d, 0d, 20d),+ new ConcaveFilletConstruction("shoulder-root", 0.5d, 5.5d, 0d, 0.5d)]);+ Assert.Equal(2, steppedShaft.Sections.Count);+ }++ [Fact]+ public void PlannedRoute_EmitsExactAnalyticFamiliesWithoutTheLegacyBuilder()+ {+ var plan = HexBoltConstructionPlanner.Plan(McMasterHexBoltSpecs.Reference91180A151, "planned");+ var result = ExactConstructionMaterializer.Materialize(plan.Value);+ Assert.True(result.IsSuccess);+ Assert.True(BrepExportPreflight.Validate(result.Value.Body).IsValid);+ Assert.Equal(1, result.Value.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Torus));+ Assert.Equal(2, result.Value.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Cone));+ }++ [Fact]+ public void GenericEmitter_MaterializesAnOctagonalNonBoltFixture()+ {+ var source = HexBoltConstructionPlanner.Plan(McMasterHexBoltSpecs.Reference91180A151, "source").Value;+ var prism = source.Prism with { StableId = "octagonal-collar", SideCount = 8, OrientationDegrees = 22.5d };+ prism = prism with { End = source.ConePlanarTrim.Apex + prism.Circumradius / Math.Tan(source.ConePlanarTrim.SemiAngleDegrees * Math.PI / 180d) };+ ConstructionSemanticClaim[] claims =+ [+ new("SteppedShaft", ConstructionSemanticKind.Part),+ new("SteppedShaft.Collar.Face[{i}]", ConstructionSemanticKind.Face, "PrismSides", "SteppedShaft")+ ];+ var stack = source.Stack with { StableId = "stepped-shaft-stack", Sections = [prism, source.ConePlanarTrim, source.TopCap, source.RootBlend, source.Cylinder, source.EndFrustum, source.EndCap] };+ var fixture = source with { StableId = "SteppedShaft", Prism = prism, Stack = stack, SemanticClaims = claims, Metadata = new Dictionary<string, string>(), DeterministicSignature = "non-bolt-fixture" };++ var result = ExactConstructionMaterializer.Materialize(fixture);+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.Message)));+ Assert.True(BrepExportPreflight.Validate(result.Value.Body).IsValid);+ Assert.Equal(8, result.Value.FaceGroups["PrismSides"].Count);+ Assert.Equal(8, result.Value.Body.Geometry.Curves.Count(x => x.Value.Kind == CurveGeometryKind.Hyperbola3));+ Assert.DoesNotContain(result.Value.Semantics, x => x.StableId.Contains("Bolt", StringComparison.Ordinal));+ }++ [Fact]+ public void ExactCoaxialPartBuilder_EmitsNonHexRecipeWithoutHexBoltTypes()+ {+ var recipe = new ExactCoaxialPartRecipe("OctagonalSpacer", 8, 13d, 5.3d, 12.35d, 25d, 0.2d,+ 8d, 35d, 0.9375d, 6.125d, 10d, "axial-zone", "fixture");+ var result = ExactCoaxialPartBuilder.Create(recipe);+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.Message)));+ Assert.Equal(8, result.Value.ConstructionPlan.Prism.SideCount);+ Assert.Equal(8, result.Value.Body.Geometry.Curves.Count(x => x.Value.Kind == CurveGeometryKind.Hyperbola3));+ Assert.True(BrepExportPreflight.Validate(result.Value.Body).IsValid);+ }++ [Fact]+ public void PeriodicMaterializers_ReuseOneSupportAcrossSplitFaces()+ {+ var plan = HexBoltConstructionPlanner.Plan(McMasterHexBoltSpecs.Reference91180A151, "sharing").Value;+ var result = ExactConstructionMaterializer.Materialize(plan).Value;+ foreach (var role in new[] { "ConePlanarTrim", "RootBlend", "Cylinder", "EndFrustum" })+ {+ var supportIds = result.FaceGroups[role]+ .Select(face => result.Body.Bindings.GetFaceBinding(face).SurfaceGeometryId)+ .Distinct().ToArray();+ Assert.Single(supportIds);+ }+ var torus = Assert.Single(result.Body.Geometry.Surfaces, x => x.Value.Kind == SurfaceGeometryKind.Torus).Value.Torus!.Value;+ Assert.Equal(plan.RootBlend.ShoulderRadius, torus.MajorRadius, 12);+ Assert.Equal(plan.RootBlend.Radius, torus.MinorRadius, 12);+ Assert.Equal(plan.RootBlend.End, torus.Center.X, 12);+ }+}diff --git a/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.cs b/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.csindex 759f128f..7c7455aa 100644--- a/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.cs+++ b/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.cs@@ -1,4 +1,7 @@using System.Globalization;+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Results;@@ -26,17 +29,89 @@ public sealed record ExactCoaxialPartRecipe(string SemanticDesignation,string Grade);+public sealed record ExactCoaxialPartDefinition(+ ExactCoaxialPartRecipe Recipe,+ BrepBody Body,+ ExactConstructionSemanticModel Semantics,+ string DeterministicSignature,+ ExactCoaxialConstructionPlan ConstructionPlan);+public static class ExactCoaxialPartBuilder{- public static KernelResult<HexBoltDefinition> Create(ExactCoaxialPartRecipe recipe)+ public static KernelResult<ExactCoaxialPartDefinition> Create(ExactCoaxialPartRecipe recipe){- if (recipe.PolygonSides != 6)- return KernelResult<HexBoltDefinition>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error,- "ExactCoaxialPart currently admits six-sided regular prisms; the construction node remains polygon-generic and diagnoses the bounded backend limit.", "ExactCoaxialPart.RegularPolygonPrism.Sides")]);- var spec = new HexBoltSpec(recipe.ShaftDiameter, recipe.AxialLength, recipe.AcrossFlats, recipe.PrismAxialHeight,- recipe.TopFlatDiameter, recipe.TopConeAngleDegrees, recipe.EndChamferLength, recipe.EndDiameter,- recipe.SemanticAxialRegionLength, recipe.SemanticDesignation, recipe.Grade, recipe.BlendRadius);- return HexBoltBuilder.Create(spec, recipe.StableId);+ var plan = Plan(recipe);+ if (!plan.IsSuccess) return KernelResult<ExactCoaxialPartDefinition>.Failure(plan.Diagnostics);+ var emitted = ExactConstructionMaterializer.Materialize(plan.Value);+ return emitted.IsSuccess+ ? KernelResult<ExactCoaxialPartDefinition>.Success(new(recipe, emitted.Value.Body,+ new(plan.Value.StableId, emitted.Value.Semantics, emitted.Value.Metadata), emitted.Value.DeterministicSignature, plan.Value))+ : KernelResult<ExactCoaxialPartDefinition>.Failure(emitted.Diagnostics);+ }++ public static KernelResult<ExactCoaxialConstructionPlan> Plan(ExactCoaxialPartRecipe recipe)+ {+ if (recipe.PolygonSides < 3 || recipe.AcrossFlats <= 0d || recipe.PrismAxialHeight <= 0d+ || recipe.TopFlatDiameter <= 0d || recipe.TopConeAngleDegrees <= 0d || recipe.TopConeAngleDegrees >= 90d+ || recipe.BlendRadius < 0d || recipe.ShaftDiameter <= 0d || recipe.AxialLength <= 0d+ || recipe.EndChamferLength <= 0d || recipe.EndChamferLength >= recipe.AxialLength || recipe.EndDiameter <= 0d+ || recipe.EndDiameter >= recipe.ShaftDiameter)+ return KernelResult<ExactCoaxialConstructionPlan>.Failure([new KernelDiagnostic(KernelDiagnosticCode.InvalidArgument,+ KernelDiagnosticSeverity.Error, "Exact coaxial construction dimensions are outside the admitted bounded family.", "ExactCoaxialPart.Admission")]);+ var apothem = recipe.AcrossFlats / 2d;+ var circumradius = apothem / Math.Cos(Math.PI / recipe.PolygonSides);+ var capRadius = recipe.TopFlatDiameter / 2d;+ if (capRadius >= apothem)+ return KernelResult<ExactCoaxialConstructionPlan>.Failure([new KernelDiagnostic(KernelDiagnosticCode.InvalidArgument,+ KernelDiagnosticSeverity.Error, "Top cap must lie inside the regular prism apothem.", "ExactCoaxialPart.ConePlanarTrim")]);+ var semiAngle = 90d - recipe.TopConeAngleDegrees;+ var slope = Math.Tan(semiAngle * Math.PI / 180d);+ var apex = -recipe.PrismAxialHeight - capRadius / slope;+ var prismEnd = apex + circumradius / slope;+ var prism = new RegularPrismConstruction("regular-prism", recipe.PolygonSides, recipe.AcrossFlats, 0d, prismEnd,+ 180d / recipe.PolygonSides);+ var trim = new ConePlanarTrimConstruction("cone-planar-trim", apex, semiAngle, -recipe.PrismAxialHeight, capRadius);+ var blend = new ConcaveFilletConstruction("root-fillet", recipe.BlendRadius,+ recipe.ShaftDiameter / 2d + recipe.BlendRadius, 0d, recipe.BlendRadius);+ var cylinder = new AxialCylinderConstruction("cylinder", recipe.ShaftDiameter / 2d, recipe.BlendRadius,+ recipe.AxialLength - recipe.EndChamferLength);+ var frustum = new AxialFrustumConstruction("end-frustum", recipe.ShaftDiameter / 2d, recipe.EndDiameter / 2d,+ recipe.AxialLength - recipe.EndChamferLength, recipe.AxialLength);+ var top = new PlanarCapConstruction("top-cap", -recipe.PrismAxialHeight, capRadius, false);+ var end = new PlanarCapConstruction("end-cap", recipe.AxialLength, recipe.EndDiameter / 2d, true);+ ExactConstructionNode[] sections = [prism, trim, top, blend, cylinder, frustum, end];+ var id = recipe.StableId;+ ConstructionSemanticClaim[] claims =+ [+ new(id, ConstructionSemanticKind.Part), new(id + ".Head", ConstructionSemanticKind.Region, ParentStableId: id),+ new(id + ".Head.TopChamfer", ConstructionSemanticKind.Region, ParentStableId: id + ".Head"),+ new(id + ".Head.TopFlat", ConstructionSemanticKind.Face, "TopCap", id + ".Head"),+ new(id + ".Head.UnderHead", ConstructionSemanticKind.Face, "Shoulder", id + ".Head"),+ new(id + ".Shank", ConstructionSemanticKind.Region, ParentStableId: id),+ new(id + ".ThreadRegion", ConstructionSemanticKind.Region, ParentStableId: id,+ Metadata: $"{recipe.SemanticDesignation};length={recipe.SemanticAxialRegionLength:R}mm;material-geometry=Cylinder"),+ new(id + ".TipChamfer", ConstructionSemanticKind.Region, ParentStableId: id),+ new(id + ".TipFace", ConstructionSemanticKind.Face, "EndCap", id),+ new(id + ".Head.Side[{i}]", ConstructionSemanticKind.Face, "PrismSides", id + ".Head"),+ new(id + ".Head.TopChamfer.Face[{i}]", ConstructionSemanticKind.Face, "ConePlanarTrim", id + ".Head.TopChamfer"),+ new(id + ".Shank.Face[{i}]", ConstructionSemanticKind.Face, "Cylinder", id + ".Shank"),+ new(id + ".ThreadRegion.Face[{i}]", ConstructionSemanticKind.Face, "Cylinder", id + ".ThreadRegion"),+ new(id + ".TipChamfer.Face[{i}]", ConstructionSemanticKind.Face, "EndFrustum", id + ".TipChamfer"),+ new(id + ".Head.UnderHeadBlend.Face[{i}]", ConstructionSemanticKind.Face, "RootBlend", id + ".Head")+ ];+ var metadata = new Dictionary<string, string>(StringComparer.Ordinal)+ {+ ["NominalDiameter"] = $"{recipe.ShaftDiameter:R}mm", ["ThreadLength"] = $"{recipe.SemanticAxialRegionLength:R}mm",+ ["ThreadDesignation"] = recipe.SemanticDesignation, ["PropertyClass"] = recipe.Grade,+ ["ThreadGeometry"] = "deferred-semantic-cylinder"+ };+ var signatureSource = string.Join("|", new[] { recipe.ShaftDiameter, recipe.AxialLength, recipe.AcrossFlats,+ recipe.PrismAxialHeight, recipe.TopFlatDiameter, recipe.TopConeAngleDegrees, recipe.EndChamferLength,+ recipe.EndDiameter, recipe.SemanticAxialRegionLength, recipe.BlendRadius }.Select(x => x.ToString("R", CultureInfo.InvariantCulture)))+ + $"|{recipe.SemanticDesignation}|{recipe.Grade}";+ var signature = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(signatureSource))).ToLowerInvariant();+ return KernelResult<ExactCoaxialConstructionPlan>.Success(new(id, prism, trim, blend, cylinder, frustum, top, end,+ new AxialSectionStackConstruction("coaxial-stack", sections), claims, metadata, signature));}public static KernelResult<ExactCoaxialPartRecipe> Bind(IReadOnlyDictionary<string, string> fields)diff --git a/Aetheris.Kernel.StandardLibrary/ExactConstructionIr.cs b/Aetheris.Kernel.StandardLibrary/ExactConstructionIr.csnew file mode 100644index 00000000..178c56b0--- /dev/null+++ b/Aetheris.Kernel.StandardLibrary/ExactConstructionIr.cs@@ -0,0 +1,205 @@+using System.Globalization;+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.StandardLibrary;++public abstract record ExactConstructionNode(string StableId);++public sealed record RegularPrismConstruction(+ string StableId, int SideCount, double AcrossFlats, double Start, double End, double OrientationDegrees = 30d)+ : ExactConstructionNode(StableId)+{+ public double Apothem => AcrossFlats / 2d;+ public double Circumradius => Apothem / Math.Cos(Math.PI / SideCount);+}++public enum PeriodicSplitPolicy { TwoHalfFaces }++public sealed record AxialCylinderConstruction(+ string StableId, double Radius, double Start, double End, PeriodicSplitPolicy SplitPolicy = PeriodicSplitPolicy.TwoHalfFaces)+ : ExactConstructionNode(StableId);++public sealed record AxialFrustumConstruction(+ string StableId, double StartRadius, double EndRadius, double Start, double End,+ PeriodicSplitPolicy SplitPolicy = PeriodicSplitPolicy.TwoHalfFaces)+ : ExactConstructionNode(StableId);++/// <summary>One cone support trimmed by the side planes of a regular prism.</summary>+public sealed record ConePlanarTrimConstruction(+ string StableId, double Apex, double SemiAngleDegrees, double CapPosition, double CapRadius,+ PeriodicSplitPolicy SplitPolicy = PeriodicSplitPolicy.TwoHalfFaces)+ : ExactConstructionNode(StableId);++/// <summary>Material-adding interior shoulder blend, implemented on one shared torus.</summary>+public sealed record ConcaveFilletConstruction(+ string StableId, double Radius, double ShoulderRadius, double Start, double End,+ PeriodicSplitPolicy SplitPolicy = PeriodicSplitPolicy.TwoHalfFaces)+ : ExactConstructionNode(StableId);++public sealed record PlanarCapConstruction(string StableId, double Position, double Radius, bool OutwardPositive)+ : ExactConstructionNode(StableId);++public sealed record AxialSectionStackConstruction(string StableId, IReadOnlyList<ExactConstructionNode> Sections)+ : ExactConstructionNode(StableId);++public enum ConstructionSemanticKind { Part, Region, Face }++/// <summary>Template/family-authored claim over a materializer topology role.</summary>+public sealed record ConstructionSemanticClaim(+ string StableIdPattern, ConstructionSemanticKind Kind, string? TopologyRole = null,+ string? ParentStableId = null, string? Metadata = null);++/// <summary>Geometry-only plan for the proven connected prism/coaxial construction family.</summary>+public sealed record ExactCoaxialConstructionPlan(+ string StableId,+ RegularPrismConstruction Prism,+ ConePlanarTrimConstruction ConePlanarTrim,+ ConcaveFilletConstruction RootBlend,+ AxialCylinderConstruction Cylinder,+ AxialFrustumConstruction EndFrustum,+ PlanarCapConstruction TopCap,+ PlanarCapConstruction EndCap,+ AxialSectionStackConstruction Stack,+ IReadOnlyList<ConstructionSemanticClaim> SemanticClaims,+ IReadOnlyDictionary<string, string> Metadata,+ string DeterministicSignature);++public sealed record ExactConstructionResult(+ BrepBody Body,+ IReadOnlyDictionary<string, IReadOnlyList<FaceId>> FaceGroups,+ IReadOnlyList<ExactConstructionSemanticDescendant> Semantics,+ IReadOnlyDictionary<string, string> Metadata,+ string DeterministicSignature);++/// <summary>Family knowledge and admission live here; the emitted plan contains no HexBoltSpec.</summary>+public static class HexBoltConstructionPlanner+{+ private const double Tolerance = 1e-9d;++ public static IReadOnlyList<HexBoltAdmissionDiagnostic> Validate(HexBoltSpec spec)+ {+ ArgumentNullException.ThrowIfNull(spec);+ var diagnostics = new List<HexBoltAdmissionDiagnostic>();+ foreach (var (name, value) in new (string Name, double Value)[]+ {+ (nameof(spec.NominalDiameter), spec.NominalDiameter), (nameof(spec.Length), spec.Length),+ (nameof(spec.HeadAcrossFlats), spec.HeadAcrossFlats), (nameof(spec.HeadHeight), spec.HeadHeight),+ (nameof(spec.TopFlatDiameter), spec.TopFlatDiameter), (nameof(spec.TipDiameter), spec.TipDiameter)+ })+ if (!double.IsFinite(value) || value <= Tolerance)+ diagnostics.Add(new(HexBoltAdmissionCode.NonFiniteOrNonPositiveDimension, name, $"{name} must be finite and positive."));++ if (!double.IsFinite(spec.TopChamferAngle) || spec.TopChamferAngle <= Tolerance || spec.TopChamferAngle >= 90d - Tolerance)+ diagnostics.Add(new(HexBoltAdmissionCode.NonFiniteOrNonPositiveDimension, nameof(spec.TopChamferAngle), "TopChamferAngle must be in (0, 90) degrees."));+ if (!double.IsFinite(spec.ThreadLength) || spec.ThreadLength < 0d || spec.ThreadLength > spec.Length + Tolerance)+ diagnostics.Add(new(HexBoltAdmissionCode.ThreadLengthOutsideShank, nameof(spec.ThreadLength), "ThreadLength must lie in [0, Length]."));+ if (!double.IsFinite(spec.UnderHeadRadius) || spec.UnderHeadRadius < 0d || spec.UnderHeadRadius >= spec.NominalDiameter / 2d)+ diagnostics.Add(new(HexBoltAdmissionCode.UnderHeadRadiusInvalid, nameof(spec.UnderHeadRadius), "UnderHeadRadius must be non-negative and smaller than the shank radius."));+ if (string.IsNullOrWhiteSpace(spec.ThreadDesignation) || string.IsNullOrWhiteSpace(spec.PropertyClass))+ diagnostics.Add(new(HexBoltAdmissionCode.EmptySemanticMetadata, nameof(spec.ThreadDesignation), "ThreadDesignation and PropertyClass must be non-empty semantic metadata."));+ if (diagnostics.Count > 0) return diagnostics;++ var apothem = spec.HeadAcrossFlats / 2d;+ var circumradius = spec.HeadAcrossFlats / Math.Sqrt(3d);+ var topRadius = spec.TopFlatDiameter / 2d;+ if (topRadius >= apothem - Tolerance)+ diagnostics.Add(new(HexBoltAdmissionCode.TopFlatOutsideHex, nameof(spec.TopFlatDiameter), "The top-flat circle must lie strictly inside the hex apothem."));+ var coneSlope = 1d / Math.Tan(spec.TopChamferAngle * Math.PI / 180d);+ if ((circumradius - topRadius) / coneSlope >= spec.HeadHeight - Tolerance)+ diagnostics.Add(new(HexBoltAdmissionCode.TopChamferConsumesHead, nameof(spec.HeadHeight), "The cone/hex corner intersection must remain above the under-head plane with non-zero side remnants."));+ if (!double.IsFinite(spec.TipChamferLength) || spec.TipChamferLength <= Tolerance || spec.TipChamferLength >= spec.Length - spec.UnderHeadRadius - Tolerance+ || spec.TipDiameter >= spec.NominalDiameter - Tolerance)+ diagnostics.Add(new(HexBoltAdmissionCode.TipChamferInvalid, nameof(spec.TipChamferLength), "Tip chamfer must have positive axial length, leave a cylindrical shank, and reduce the tip diameter."));+ return diagnostics;+ }++ public static HexBoltDerivedDimensions Derive(HexBoltSpec spec)+ {+ var apothem = spec.HeadAcrossFlats / 2d; var circumradius = spec.HeadAcrossFlats / Math.Sqrt(3d);+ var topRadius = spec.TopFlatDiameter / 2d; var semiAngle = 90d - spec.TopChamferAngle;+ var slope = Math.Tan(semiAngle * Math.PI / 180d); var apex = -spec.HeadHeight - topRadius / slope;+ return new(apothem, circumradius, topRadius, semiAngle, apex, apex + apothem / slope,+ apex + circumradius / slope, spec.Length - spec.TipChamferLength);+ }++ public static KernelResult<ExactCoaxialConstructionPlan> Plan(HexBoltSpec spec, string stableId = "HexBolt")+ {+ var admission = Validate(spec);+ if (admission.Count > 0)+ return KernelResult<ExactCoaxialConstructionPlan>.Failure(admission.Select(d => new KernelDiagnostic(+ KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, d.Message,+ $"StandardLibrary.HexBolt.{d.Code}:{d.Field}")));++ var d = Derive(spec);+ var prism = new RegularPrismConstruction("head-prism", 6, spec.HeadAcrossFlats, 0d, d.TopConeCornerX);+ var trim = new ConePlanarTrimConstruction("head-cone-plane-trims", d.TopConeApexX, d.TopConeSemiAngleDegrees, -spec.HeadHeight, d.TopFlatRadius);+ var blend = new ConcaveFilletConstruction("under-head-root", spec.UnderHeadRadius,+ spec.NominalDiameter / 2d + spec.UnderHeadRadius, 0d, spec.UnderHeadRadius);+ var cylinder = new AxialCylinderConstruction("shank", spec.NominalDiameter / 2d, spec.UnderHeadRadius, d.TipChamferStartX);+ var frustum = new AxialFrustumConstruction("tip-chamfer", spec.NominalDiameter / 2d, spec.TipDiameter / 2d, d.TipChamferStartX, spec.Length);+ var topCap = new PlanarCapConstruction("top-cap", -spec.HeadHeight, d.TopFlatRadius, false);+ var endCap = new PlanarCapConstruction("end-cap", spec.Length, spec.TipDiameter / 2d, true);+ ExactConstructionNode[] sections = [prism, trim, topCap, blend, cylinder, frustum, endCap];+ ConstructionSemanticClaim[] claims =+ [+ new(stableId, ConstructionSemanticKind.Part),+ new(stableId + ".Head", ConstructionSemanticKind.Region, ParentStableId: stableId),+ new(stableId + ".Head.TopChamfer", ConstructionSemanticKind.Region, ParentStableId: stableId + ".Head"),+ new(stableId + ".Head.TopFlat", ConstructionSemanticKind.Face, "TopCap", stableId + ".Head"),+ new(stableId + ".Head.UnderHead", ConstructionSemanticKind.Face, "Shoulder", stableId + ".Head"),+ new(stableId + ".Shank", ConstructionSemanticKind.Region, ParentStableId: stableId),+ new(stableId + ".ThreadRegion", ConstructionSemanticKind.Region, ParentStableId: stableId,+ Metadata: $"{spec.ThreadDesignation};length={spec.ThreadLength:R}mm;material-geometry=Cylinder"),+ new(stableId + ".TipChamfer", ConstructionSemanticKind.Region, ParentStableId: stableId),+ new(stableId + ".TipFace", ConstructionSemanticKind.Face, "EndCap", stableId),+ new(stableId + ".Head.Side[{i}]", ConstructionSemanticKind.Face, "PrismSides", stableId + ".Head"),+ new(stableId + ".Head.TopChamfer.Face[{i}]", ConstructionSemanticKind.Face, "ConePlanarTrim", stableId + ".Head.TopChamfer"),+ new(stableId + ".Shank.Face[{i}]", ConstructionSemanticKind.Face, "Cylinder", stableId + ".Shank"),+ new(stableId + ".ThreadRegion.Face[{i}]", ConstructionSemanticKind.Face, "Cylinder", stableId + ".ThreadRegion"),+ new(stableId + ".TipChamfer.Face[{i}]", ConstructionSemanticKind.Face, "EndFrustum", stableId + ".TipChamfer"),+ new(stableId + ".Head.UnderHeadBlend.Face[{i}]", ConstructionSemanticKind.Face, "RootBlend", stableId + ".Head")+ ];+ var metadata = new Dictionary<string, string>(StringComparer.Ordinal)+ {+ ["NominalDiameter"] = $"{spec.NominalDiameter:R}mm", ["ThreadLength"] = $"{spec.ThreadLength:R}mm",+ ["ThreadDesignation"] = spec.ThreadDesignation, ["PropertyClass"] = spec.PropertyClass,+ ["ThreadGeometry"] = "deferred-semantic-cylinder"+ };+ var signatureSource = string.Join("|", new[] { spec.NominalDiameter, spec.Length, spec.HeadAcrossFlats, spec.HeadHeight,+ spec.TopFlatDiameter, spec.TopChamferAngle, spec.TipChamferLength, spec.TipDiameter, spec.ThreadLength, spec.UnderHeadRadius }+ .Select(x => x.ToString("R", CultureInfo.InvariantCulture))) + $"|{spec.ThreadDesignation}|{spec.PropertyClass}";+ var signature = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(signatureSource))).ToLowerInvariant();+ return KernelResult<ExactCoaxialConstructionPlan>.Success(new(stableId, prism, trim, blend, cylinder, frustum, topCap, endCap,+ new AxialSectionStackConstruction("coaxial-stack", sections), claims, metadata, signature));+ }++ public static HexBoltDefinition Wrap(HexBoltSpec spec, ExactCoaxialConstructionPlan plan, ExactConstructionResult result) =>+ new(spec, Derive(spec), result.Body, new(plan.StableId, result.Semantics, result.Metadata), result.DeterministicSignature);+}++public static class ExactConstructionMaterializer+{+ public static KernelResult<ExactConstructionResult> Materialize(ExactCoaxialConstructionPlan plan) =>+ CoaxialConstructionMaterializer.Materialize(plan);+}++/// <summary>Compatibility facade over the same generic plan and materializer used by Firmament.</summary>+public static class HexBoltBuilder+{+ public static IReadOnlyList<HexBoltAdmissionDiagnostic> Validate(HexBoltSpec spec) => HexBoltConstructionPlanner.Validate(spec);+ public static HexBoltDerivedDimensions Derive(HexBoltSpec spec) => HexBoltConstructionPlanner.Derive(spec);+ public static KernelResult<HexBoltDefinition> Create(HexBoltSpec spec, string bodyStableId = "HexBolt")+ {+ var plan = HexBoltConstructionPlanner.Plan(spec, bodyStableId);+ if (!plan.IsSuccess) return KernelResult<HexBoltDefinition>.Failure(plan.Diagnostics);+ var emitted = ExactConstructionMaterializer.Materialize(plan.Value);+ return emitted.IsSuccess+ ? KernelResult<HexBoltDefinition>.Success(HexBoltConstructionPlanner.Wrap(spec, plan.Value, emitted.Value))+ : KernelResult<HexBoltDefinition>.Failure(emitted.Diagnostics);+ }+}diff --git a/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.cs b/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.csnew file mode 100644index 00000000..59746d93--- /dev/null+++ b/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.cs@@ -0,0 +1,355 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.StandardLibrary;++internal readonly record struct ExactEdgeUse(EdgeId Edge, bool Reversed);+internal readonly record struct ExactRing(VertexId Positive, VertexId Negative, EdgeId Arc0, EdgeId Arc1);++/// <summary>Shared deterministic allocator used by all exact construction materializers.</summary>+internal sealed class ExactBrepEmissionContext+{+ private static readonly Direction3D PlusX = Direction3D.Create(new Vector3D(1d, 0d, 0d));+ private static readonly Direction3D PlusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));+ private readonly TopologyBuilder topology = new();+ private readonly BrepGeometryStore geometry = new();+ private readonly BrepBindingModel bindings = new();+ private readonly Dictionary<VertexId, Point3D> points = [];+ private readonly List<FaceId> faces = [];++ internal IReadOnlyDictionary<VertexId, Point3D> Points => points;+ internal BrepGeometryStore Geometry => geometry;++ internal VertexId Vertex(Point3D point) { var id = topology.AddVertex(); points[id] = point; return id; }++ internal EdgeId CurveEdge(VertexId start, VertexId end, CurveGeometry curve, double t0, double t1)+ {+ var edge = topology.AddEdge(start, end);+ var curveId = new CurveGeometryId(geometry.Curves.Count() + 1);+ geometry.AddCurve(curveId, curve);+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edge, curveId, new ParameterInterval(t0, t1)));+ return edge;+ }++ internal EdgeId Line(VertexId start, VertexId end)+ {+ var a = points[start]; var vector = points[end] - a;+ return CurveEdge(start, end, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(vector))), 0d, vector.Length);+ }++ internal ExactRing CircleRing(double x, double radius)+ {+ var positive = Vertex(new Point3D(x, radius, 0d));+ var negative = Vertex(new Point3D(x, -radius, 0d));+ var support = new Circle3Curve(new Point3D(x, 0d, 0d), PlusX, radius, PlusY);+ return new(positive, negative,+ CurveEdge(positive, negative, CurveGeometry.FromCircle(support), 0d, Math.PI),+ CurveEdge(negative, positive, CurveGeometry.FromCircle(support), Math.PI, 2d * Math.PI));+ }++ internal SurfaceGeometryId SharedSurface(SurfaceGeometry surface)+ {+ var id = new SurfaceGeometryId(geometry.Surfaces.Count() + 1);+ geometry.AddSurface(id, surface);+ return id;+ }++ internal FaceId Face(IReadOnlyList<IReadOnlyList<ExactEdgeUse>> loops, SurfaceGeometry surface,+ bool sameSense = true, SurfaceGeometryId? sharedSurfaceId = null)+ {+ var loopIds = new List<LoopId>();+ foreach (var uses in loops)+ {+ var loop = topology.AllocateLoopId();+ var coedges = uses.Select(_ => topology.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < coedges.Length; i++)+ topology.AddCoedge(new Coedge(coedges[i], uses[i].Edge, loop, coedges[(i + 1) % coedges.Length],+ coedges[(i + coedges.Length - 1) % coedges.Length], uses[i].Reversed));+ topology.AddLoop(new Loop(loop, coedges));+ loopIds.Add(loop);+ }+ var face = topology.AddFace(loopIds);+ var surfaceId = sharedSurfaceId ?? SharedSurface(surface);+ bindings.AddFaceBinding(new FaceGeometryBinding(face, surfaceId, sameSense));+ faces.Add(face);+ return face;+ }++ internal BrepBody Complete()+ {+ var shell = topology.AddShell(faces);+ topology.AddBody([shell]);+ return new BrepBody(topology.Model, geometry, bindings, points);+ }+}++internal sealed record RegularPrismSkeleton(+ VertexId[] Lower, VertexId[] Upper, EdgeId[] LowerEdges, EdgeId[] AxialEdges);++internal static class RegularPrismMaterializer+{+ internal static RegularPrismSkeleton PlanIncidence(ExactBrepEmissionContext context, RegularPrismConstruction prism)+ {+ var n = prism.SideCount;+ var step = 2d * Math.PI / n;+ var orientation = prism.OrientationDegrees * Math.PI / 180d;+ var lower = new VertexId[n]; var upper = new VertexId[n];+ for (var i = 0; i < n; i++)+ {+ var angle = orientation + i * step;+ var y = prism.Circumradius * Math.Cos(angle); var z = prism.Circumradius * Math.Sin(angle);+ lower[i] = context.Vertex(new Point3D(prism.Start, y, z));+ upper[i] = context.Vertex(new Point3D(prism.End, y, z));+ }+ var lowerEdges = new EdgeId[n]; var axialEdges = new EdgeId[n];+ for (var i = 0; i < n; i++)+ {+ lowerEdges[i] = context.Line(lower[i], lower[(i + 1) % n]);+ axialEdges[i] = context.Line(lower[i], upper[i]);+ }+ return new(lower, upper, lowerEdges, axialEdges);+ }++ internal static FaceId[] EmitSides(ExactBrepEmissionContext context, RegularPrismSkeleton prism, EdgeId[] upperEdges)+ {+ var n = prism.Lower.Length; var faces = new FaceId[n];+ var plusX = Direction3D.Create(new Vector3D(1d, 0d, 0d));+ for (var i = 0; i < n; i++)+ {+ var a = context.Points[prism.Lower[i]]; var b = context.Points[prism.Lower[(i + 1) % n]];+ var tangent = Direction3D.Create(b - a);+ var outward = Direction3D.Create(tangent.ToVector().Cross(plusX.ToVector()));+ faces[i] = context.Face([[new(prism.LowerEdges[i], false), new(prism.AxialEdges[(i + 1) % n], false),+ new(upperEdges[i], true), new(prism.AxialEdges[i], true)]], SurfaceGeometry.FromPlane(new PlaneSurface(a, outward, plusX)));+ }+ return faces;+ }+}++internal sealed record ConePlanarTrimEmission(EdgeId[] TrimEdges, EdgeId[] CapArcs, EdgeId[] Generators, FaceId[] Faces, FaceId Cap);++internal static class ConePlanarTrimMaterializer+{+ private static readonly Direction3D PlusX = Direction3D.Create(new Vector3D(1d, 0d, 0d));+ private static readonly Direction3D MinusX = Direction3D.Create(new Vector3D(-1d, 0d, 0d));+ private static readonly Direction3D PlusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));++ internal static EdgeId[] EmitTrimEdges(ExactBrepEmissionContext context, RegularPrismConstruction prism,+ ConePlanarTrimConstruction trim, VertexId[] boundary)+ {+ var n = prism.SideCount; var edges = new EdgeId[n];+ var step = 2d * Math.PI / n; var orientation = prism.OrientationDegrees * Math.PI / 180d;+ for (var i = 0; i < n; i++)+ {+ var normalAngle = orientation + step / 2d + i * step;+ var normal = new Vector3D(0d, Math.Cos(normalAngle), Math.Sin(normalAngle));+ var support = new Hyperbola3Curve(new Point3D(trim.Apex, normal.Y * prism.Apothem, normal.Z * prism.Apothem),+ Direction3D.Create(normal), PlusX, prism.Apothem / Math.Tan(trim.SemiAngleDegrees * Math.PI / 180d),+ prism.Apothem, HyperbolaBranch.PositiveAxisU);+ var t0 = Parameter(support, context.Points[boundary[i]]); var t1 = Parameter(support, context.Points[boundary[(i + 1) % n]]);+ if (t1 < t0) { support = support.Reverse(); t0 = Parameter(support, context.Points[boundary[i]]); t1 = Parameter(support, context.Points[boundary[(i + 1) % n]]); }+ edges[i] = context.CurveEdge(boundary[i], boundary[(i + 1) % n], CurveGeometry.FromHyperbola(support), t0, t1);+ }+ return edges;+ }++ internal static ConePlanarTrimEmission EmitTreatment(ExactBrepEmissionContext context, RegularPrismConstruction prism,+ ConePlanarTrimConstruction trim, RegularPrismSkeleton skeleton, EdgeId[] trimEdges)+ {+ var n = prism.SideCount; var step = 2d * Math.PI / n; var orientation = prism.OrientationDegrees * Math.PI / 180d;+ var capVertices = new VertexId[n]; var capArcs = new EdgeId[n]; var generators = new EdgeId[n];+ var circle = new Circle3Curve(new Point3D(trim.CapPosition, 0d, 0d), PlusX, trim.CapRadius, PlusY);+ for (var i = 0; i < n; i++)+ {+ var angle = orientation + i * step;+ capVertices[i] = context.Vertex(new Point3D(trim.CapPosition, trim.CapRadius * Math.Cos(angle), trim.CapRadius * Math.Sin(angle)));+ }+ for (var i = 0; i < n; i++)+ {+ var angle = orientation + i * step;+ capArcs[i] = context.CurveEdge(capVertices[i], capVertices[(i + 1) % n], CurveGeometry.FromCircle(circle), angle, angle + step);+ generators[i] = context.Line(capVertices[i], skeleton.Upper[i]);+ }+ var cone = SurfaceGeometry.FromCone(new ConeSurface(new Point3D(trim.Apex, 0d, 0d), PlusX, trim.SemiAngleDegrees * Math.PI / 180d, PlusY));+ var coneId = context.SharedSurface(cone); var faces = new FaceId[n];+ for (var i = 0; i < n; i++)+ faces[i] = context.Face([[new(capArcs[i], false), new(generators[(i + 1) % n], false), new(trimEdges[i], true), new(generators[i], true)]], cone, sharedSurfaceId: coneId);+ var cap = context.Face([capArcs.Select(x => new ExactEdgeUse(x, false)).ToArray()],+ SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(trim.CapPosition, 0d, 0d), MinusX, PlusY)));+ return new(trimEdges, capArcs, generators, faces, cap);+ }++ private static double Parameter(Hyperbola3Curve curve, Point3D point) =>+ Math.Asinh((point - curve.Center).Dot(curve.AxisV.ToVector()) / curve.SemiAxisB);+}++internal sealed record PeriodicSpanEmission(FaceId[] Faces);++internal static class AxialCylinderMaterializer+{+ internal static PeriodicSpanEmission Emit(ExactBrepEmissionContext context, AxialCylinderConstruction section, ExactRing start, ExactRing end)+ {+ var plus = context.Line(start.Positive, end.Positive); var minus = context.Line(start.Negative, end.Negative);+ var plusX = Direction3D.Create(new Vector3D(1d, 0d, 0d)); var plusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));+ var support = SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(section.Start, 0d, 0d), plusX, section.Radius, plusY));+ var supportId = context.SharedSurface(support);+ return new([+ context.Face([[new(start.Arc0, false), new(minus, false), new(end.Arc0, true), new(plus, true)]], support, sharedSurfaceId: supportId),+ context.Face([[new(start.Arc1, false), new(plus, false), new(end.Arc1, true), new(minus, true)]], support, sharedSurfaceId: supportId)]);+ }+}++internal static class AxialFrustumMaterializer+{+ internal static PeriodicSpanEmission Emit(ExactBrepEmissionContext context, AxialFrustumConstruction section, ExactRing start, ExactRing end)+ {+ var plus = context.Line(start.Positive, end.Positive); var minus = context.Line(start.Negative, end.Negative);+ var slope = (section.StartRadius - section.EndRadius) / (section.End - section.Start);+ var apex = section.Start + section.StartRadius / slope;+ var minusX = Direction3D.Create(new Vector3D(-1d, 0d, 0d)); var plusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));+ var support = SurfaceGeometry.FromCone(new ConeSurface(new Point3D(apex, 0d, 0d), minusX, Math.Atan(slope), plusY));+ var supportId = context.SharedSurface(support);+ return new([+ context.Face([[new(start.Arc0, false), new(minus, false), new(end.Arc0, true), new(plus, true)]], support, sharedSurfaceId: supportId),+ context.Face([[new(start.Arc1, false), new(plus, false), new(end.Arc1, true), new(minus, true)]], support, sharedSurfaceId: supportId)]);+ }+}++internal static class PeriodicTorusBlendMaterializer+{+ internal static PeriodicSpanEmission Emit(ExactBrepEmissionContext context, ConcaveFilletConstruction blend, ExactRing shoulder, ExactRing cylinder)+ {+ if (blend.Radius <= 1e-9d) return new([]);+ var minusX = Direction3D.Create(new Vector3D(-1d, 0d, 0d)); var plusX = Direction3D.Create(new Vector3D(1d, 0d, 0d));+ var plusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));+ var plus = context.CurveEdge(shoulder.Positive, cylinder.Positive,+ CurveGeometry.FromCircle(new Circle3Curve(new Point3D(blend.End, blend.ShoulderRadius, 0d), Direction3D.Create(new Vector3D(0d, 0d, 1d)), blend.Radius, minusX)), 0d, Math.PI / 2d);+ var minus = context.CurveEdge(shoulder.Negative, cylinder.Negative,+ CurveGeometry.FromCircle(new Circle3Curve(new Point3D(blend.End, -blend.ShoulderRadius, 0d), Direction3D.Create(new Vector3D(0d, 0d, -1d)), blend.Radius, minusX)), 0d, Math.PI / 2d);+ var support = SurfaceGeometry.FromTorus(new TorusSurface(new Point3D(blend.End, 0d, 0d), plusX, blend.ShoulderRadius, blend.Radius, plusY));+ var supportId = context.SharedSurface(support);+ return new([+ context.Face([[new(shoulder.Arc0, false), new(minus, false), new(cylinder.Arc0, true), new(plus, true)]], support, sharedSurfaceId: supportId),+ context.Face([[new(shoulder.Arc1, false), new(plus, false), new(cylinder.Arc1, true), new(minus, true)]], support, sharedSurfaceId: supportId)]);+ }+}++/// <summary>Typed orchestration over the independent exact primitive materializers.</summary>+internal static class CoaxialConstructionMaterializer+{+ private const double Tolerance = 1e-9d;+ private static readonly Direction3D PlusX = Direction3D.Create(new Vector3D(1d, 0d, 0d));+ private static readonly Direction3D PlusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));++ internal static KernelResult<ExactConstructionResult> Materialize(ExactCoaxialConstructionPlan plan)+ {+ ArgumentNullException.ThrowIfNull(plan);+ var admission = Validate(plan);+ if (admission.Count > 0) return KernelResult<ExactConstructionResult>.Failure(admission);+ var realization = Build(plan);+ var preflight = BrepExportPreflight.Validate(realization.Body);+ if (!preflight.IsValid)+ return KernelResult<ExactConstructionResult>.Failure(preflight.Diagnostics+ .Where(d => d.Severity == BrepExportPreflightSeverity.Error)+ .Select(d => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Message, d.Context)));+ return KernelResult<ExactConstructionResult>.Success(realization);+ }++ private static IReadOnlyList<KernelDiagnostic> Validate(ExactCoaxialConstructionPlan plan)+ {+ var errors = new List<KernelDiagnostic>();+ void Require(bool condition, string message, string source)+ {+ if (!condition) errors.Add(new(KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, message, source));+ }+ var p = plan.Prism; var t = plan.ConePlanarTrim; var b = plan.RootBlend;+ var c = plan.Cylinder; var f = plan.EndFrustum;+ Require(p.SideCount >= 3, "A regular prism requires at least three sides.", "ExactConstruction.RegularPrism.SideCount");+ Require(double.IsFinite(p.AcrossFlats) && p.AcrossFlats > 0d && Math.Abs(p.End - p.Start) > Tolerance,+ "Regular prism dimensions must be finite and ordered.", "ExactConstruction.RegularPrism.Dimensions");+ Require(t.CapRadius > 0d && t.SemiAngleDegrees > 0d && t.SemiAngleDegrees < 90d,+ "Cone/plane trim requires a positive cap and semi-angle in (0,90).", "ExactConstruction.ConePlanarTrim");+ Require(b.Radius >= 0d && b.ShoulderRadius >= c.Radius && Math.Abs(b.Start - p.Start) <= Tolerance,+ "Root blend must join the prism shoulder to the cylinder.", "ExactConstruction.ConcaveFillet.Adjacency");+ Require(c.Radius > 0d && c.End > c.Start && Math.Abs(c.Start - b.End) <= Tolerance,+ "Cylinder span must be positive and adjacent to the root blend.", "ExactConstruction.AxialCylinder.Adjacency");+ Require(f.StartRadius > 0d && f.EndRadius > 0d && f.StartRadius != f.EndRadius && f.End > f.Start+ && Math.Abs(f.Start - c.End) <= Tolerance && Math.Abs(f.StartRadius - c.Radius) <= Tolerance,+ "Frustum must be non-cylindrical and adjacent to the cylinder.", "ExactConstruction.AxialFrustum.Adjacency");+ Require(Math.Abs(plan.TopCap.Position - t.CapPosition) <= Tolerance && Math.Abs(plan.TopCap.Radius - t.CapRadius) <= Tolerance,+ "Top cap must share the cone trim boundary.", "ExactConstruction.AxialSectionStack.TopCap");+ Require(Math.Abs(plan.EndCap.Position - f.End) <= Tolerance && Math.Abs(plan.EndCap.Radius - f.EndRadius) <= Tolerance,+ "End cap must share the frustum boundary.", "ExactConstruction.AxialSectionStack.EndCap");+ ExactConstructionNode[] expected = [p, t, plan.TopCap, b, c, f, plan.EndCap];+ Require(plan.Stack.Sections.SequenceEqual(expected), "Axial section stack order or node identity is inconsistent with the typed plan.",+ "ExactConstruction.AxialSectionStack.Order");+ var roles = new HashSet<string>(["PrismSides", "ConePlanarTrim", "TopCap", "Shoulder", "RootBlend", "Cylinder", "EndFrustum", "EndCap"], StringComparer.Ordinal);+ foreach (var claim in plan.SemanticClaims.Where(x => x.TopologyRole is not null))+ Require(roles.Contains(claim.TopologyRole!), $"Semantic claim references unknown topology role '{claim.TopologyRole}'.", "ExactConstruction.SemanticClaim.Role");+ return errors;+ }++ private static ExactConstructionResult Build(ExactCoaxialConstructionPlan plan)+ {+ var prism = plan.Prism; var trim = plan.ConePlanarTrim; var blend = plan.RootBlend;+ var cylinder = plan.Cylinder; var frustum = plan.EndFrustum;+ var context = new ExactBrepEmissionContext();+ var prismSkeleton = RegularPrismMaterializer.PlanIncidence(context, prism);+ var trimEdges = ConePlanarTrimMaterializer.EmitTrimEdges(context, prism, trim, prismSkeleton.Upper);+ var shoulderRing = context.CircleRing(prism.Start, blend.ShoulderRadius);+ var cylinderStartRing = blend.Radius > Tolerance ? context.CircleRing(blend.End, cylinder.Radius) : shoulderRing;+ var frustumStartRing = context.CircleRing(frustum.Start, frustum.StartRadius);+ var endRing = context.CircleRing(frustum.End, frustum.EndRadius);++ var sideFaces = RegularPrismMaterializer.EmitSides(context, prismSkeleton, trimEdges);+ var coneTreatment = ConePlanarTrimMaterializer.EmitTreatment(context, prism, trim, prismSkeleton, trimEdges);+ var shoulder = context.Face([+ prismSkeleton.LowerEdges.Reverse().Select(e => new ExactEdgeUse(e, true)).ToArray(),+ [new(shoulderRing.Arc0, false), new(shoulderRing.Arc1, false)]],+ SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(prism.Start, 0d, 0d), PlusX, PlusY)));+ var rootBlend = PeriodicTorusBlendMaterializer.Emit(context, blend, shoulderRing, cylinderStartRing);+ var cylinderSpan = AxialCylinderMaterializer.Emit(context, cylinder, cylinderStartRing, frustumStartRing);+ var frustumSpan = AxialFrustumMaterializer.Emit(context, frustum, frustumStartRing, endRing);+ var endCap = context.Face([[new(endRing.Arc1, true), new(endRing.Arc0, true)]],+ SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(plan.EndCap.Position, 0d, 0d), PlusX, PlusY)));+ var body = context.Complete();+ IReadOnlyDictionary<string, IReadOnlyList<FaceId>> groups = new Dictionary<string, IReadOnlyList<FaceId>>(StringComparer.Ordinal)+ {+ ["PrismSides"] = sideFaces, ["ConePlanarTrim"] = coneTreatment.Faces, ["TopCap"] = [coneTreatment.Cap],+ ["Shoulder"] = [shoulder], ["RootBlend"] = rootBlend.Faces, ["Cylinder"] = cylinderSpan.Faces,+ ["EndFrustum"] = frustumSpan.Faces, ["EndCap"] = [endCap]+ };+ return new(body, groups, BindSemantics(plan.SemanticClaims, groups), plan.Metadata, plan.DeterministicSignature);+ }++ private static IReadOnlyList<ExactConstructionSemanticDescendant> BindSemantics(+ IReadOnlyList<ConstructionSemanticClaim> claims, IReadOnlyDictionary<string, IReadOnlyList<FaceId>> groups)+ {+ var descendants = new List<ExactConstructionSemanticDescendant>();+ foreach (var claim in claims)+ {+ var kind = claim.Kind switch { ConstructionSemanticKind.Part => ExactConstructionSemanticKind.Part,+ ConstructionSemanticKind.Region => ExactConstructionSemanticKind.Region, _ => ExactConstructionSemanticKind.Face };+ if (claim.TopologyRole is null)+ {+ descendants.Add(new(claim.StableIdPattern, kind, ParentStableId: claim.ParentStableId, Metadata: claim.Metadata));+ continue;+ }+ var roleFaces = groups[claim.TopologyRole];+ for (var i = 0; i < roleFaces.Count; i++)+ {+ var stableId = claim.StableIdPattern.Contains("{i}", StringComparison.Ordinal)+ ? claim.StableIdPattern.Replace("{i}", i.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal)+ : claim.StableIdPattern;+ descendants.Add(new(stableId, kind, roleFaces[i], claim.ParentStableId, claim.Metadata));+ }+ }+ return descendants;+ }+}diff --git a/Aetheris.Kernel.StandardLibrary/HexBolt.cs b/Aetheris.Kernel.StandardLibrary/HexBolt.csindex 152a3154..28253a66 100644--- a/Aetheris.Kernel.StandardLibrary/HexBolt.cs+++ b/Aetheris.Kernel.StandardLibrary/HexBolt.cs@@ -1,5 +1,3 @@-using System.Security.Cryptography;-using System.Text;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Geometry;@@ -72,327 +70,23 @@ public sealed record HexBoltDerivedDimensions(double TopConeCornerX,double TipChamferStartX);-public enum HexBoltSemanticKind { Part, Region, Face }+public enum ExactConstructionSemanticKind { Part, Region, Face }-public sealed record HexBoltSemanticDescendant(+public sealed record ExactConstructionSemanticDescendant(string StableId,- HexBoltSemanticKind Kind,+ ExactConstructionSemanticKind Kind,FaceId? Face = null,string? ParentStableId = null,string? Metadata = null);-public sealed record HexBoltSemanticModel(+public sealed record ExactConstructionSemanticModel(string BodyStableId,- IReadOnlyList<HexBoltSemanticDescendant> Descendants,+ IReadOnlyList<ExactConstructionSemanticDescendant> Descendants,IReadOnlyDictionary<string, string> Metadata);public sealed record HexBoltDefinition(HexBoltSpec Spec,HexBoltDerivedDimensions Dimensions,BrepBody Body,- HexBoltSemanticModel Semantics,+ ExactConstructionSemanticModel Semantics,string DeterministicSignature);--/// <summary>-/// Exact bounded construction for the first StandardLibrary hex-bolt family. The top-/// treatment is one coaxial cone trimmed by six analytic hyperbola edges.-/// </summary>-public static class HexBoltBuilder-{- private const double Tolerance = 1e-9d;- private static readonly Direction3D PlusX = Direction3D.Create(new Vector3D(1d, 0d, 0d));- private static readonly Direction3D MinusX = Direction3D.Create(new Vector3D(-1d, 0d, 0d));- private static readonly Direction3D PlusY = Direction3D.Create(new Vector3D(0d, 1d, 0d));-- public static IReadOnlyList<HexBoltAdmissionDiagnostic> Validate(HexBoltSpec spec)- {- ArgumentNullException.ThrowIfNull(spec);- var diagnostics = new List<HexBoltAdmissionDiagnostic>();- var positive = new (string Name, double Value)[]- {- (nameof(spec.NominalDiameter), spec.NominalDiameter),- (nameof(spec.Length), spec.Length),- (nameof(spec.HeadAcrossFlats), spec.HeadAcrossFlats),- (nameof(spec.HeadHeight), spec.HeadHeight),- (nameof(spec.TopFlatDiameter), spec.TopFlatDiameter),- (nameof(spec.TipDiameter), spec.TipDiameter)- };- foreach (var (name, value) in positive)- {- if (!double.IsFinite(value) || value <= Tolerance)- diagnostics.Add(new(HexBoltAdmissionCode.NonFiniteOrNonPositiveDimension, name, $"{name} must be finite and positive."));- }-- if (!double.IsFinite(spec.TopChamferAngle) || spec.TopChamferAngle <= Tolerance || spec.TopChamferAngle >= 90d - Tolerance)- diagnostics.Add(new(HexBoltAdmissionCode.NonFiniteOrNonPositiveDimension, nameof(spec.TopChamferAngle), "TopChamferAngle must be in (0, 90) degrees."));- if (!double.IsFinite(spec.ThreadLength) || spec.ThreadLength < 0d || spec.ThreadLength > spec.Length + Tolerance)- diagnostics.Add(new(HexBoltAdmissionCode.ThreadLengthOutsideShank, nameof(spec.ThreadLength), "ThreadLength must lie in [0, Length]."));- if (!double.IsFinite(spec.UnderHeadRadius) || spec.UnderHeadRadius < 0d || spec.UnderHeadRadius >= spec.NominalDiameter / 2d)- diagnostics.Add(new(HexBoltAdmissionCode.UnderHeadRadiusInvalid, nameof(spec.UnderHeadRadius), "UnderHeadRadius must be non-negative and smaller than the shank radius."));- if (string.IsNullOrWhiteSpace(spec.ThreadDesignation) || string.IsNullOrWhiteSpace(spec.PropertyClass))- diagnostics.Add(new(HexBoltAdmissionCode.EmptySemanticMetadata, nameof(spec.ThreadDesignation), "ThreadDesignation and PropertyClass must be non-empty semantic metadata."));-- if (diagnostics.Count > 0) return diagnostics;-- var apothem = spec.HeadAcrossFlats / 2d;- var circumradius = spec.HeadAcrossFlats / double.Sqrt(3d);- var topRadius = spec.TopFlatDiameter / 2d;- if (topRadius >= apothem - Tolerance)- diagnostics.Add(new(HexBoltAdmissionCode.TopFlatOutsideHex, nameof(spec.TopFlatDiameter), "The top-flat circle must lie strictly inside the hex apothem."));-- var coneSlope = 1d / double.Tan(spec.TopChamferAngle * double.Pi / 180d);- var axialToCorner = (circumradius - topRadius) / coneSlope;- if (axialToCorner >= spec.HeadHeight - Tolerance)- diagnostics.Add(new(HexBoltAdmissionCode.TopChamferConsumesHead, nameof(spec.HeadHeight), "The cone/hex corner intersection must remain above the under-head plane with non-zero side remnants."));-- if (!double.IsFinite(spec.TipChamferLength) || spec.TipChamferLength <= Tolerance || spec.TipChamferLength >= spec.Length - spec.UnderHeadRadius - Tolerance- || spec.TipDiameter >= spec.NominalDiameter - Tolerance)- diagnostics.Add(new(HexBoltAdmissionCode.TipChamferInvalid, nameof(spec.TipChamferLength), "Tip chamfer must have positive axial length, leave a cylindrical shank, and reduce the tip diameter."));- return diagnostics;- }-- public static KernelResult<HexBoltDefinition> Create(HexBoltSpec spec, string bodyStableId = "HexBolt")- {- var admission = Validate(spec);- if (admission.Count > 0)- return KernelResult<HexBoltDefinition>.Failure(admission.Select(d => new KernelDiagnostic(- KernelDiagnosticCode.InvalidArgument,- KernelDiagnosticSeverity.Error,- d.Message,- $"StandardLibrary.HexBolt.{d.Code}:{d.Field}")));-- var dimensions = Derive(spec);- var realization = Build(spec, dimensions, bodyStableId);- var preflight = BrepExportPreflight.Validate(realization.Body);- if (!preflight.IsValid)- return KernelResult<HexBoltDefinition>.Failure(preflight.Diagnostics- .Where(d => d.Severity == BrepExportPreflightSeverity.Error)- .Select(d => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Message, d.Context)));-- return KernelResult<HexBoltDefinition>.Success(realization);- }-- public static HexBoltDerivedDimensions Derive(HexBoltSpec spec)- {- var apothem = spec.HeadAcrossFlats / 2d;- var circumradius = spec.HeadAcrossFlats / double.Sqrt(3d);- var topRadius = spec.TopFlatDiameter / 2d;- var semiAngle = 90d - spec.TopChamferAngle;- var slope = double.Tan(semiAngle * double.Pi / 180d);- var topX = -spec.HeadHeight;- var apexX = topX - topRadius / slope;- return new(apothem, circumradius, topRadius, semiAngle, apexX,- apexX + apothem / slope,- apexX + circumradius / slope,- spec.Length - spec.TipChamferLength);- }-- private static HexBoltDefinition Build(HexBoltSpec spec, HexBoltDerivedDimensions d, string bodyStableId)- {- var topology = new TopologyBuilder();- var geometry = new BrepGeometryStore();- var bindings = new BrepBindingModel();- var points = new Dictionary<VertexId, Point3D>();- var faces = new List<FaceId>();-- VertexId Vertex(Point3D point) { var id = topology.AddVertex(); points[id] = point; return id; }- EdgeId CurveEdge(VertexId start, VertexId end, CurveGeometry curve, double t0, double t1)- {- var edge = topology.AddEdge(start, end);- var curveId = new CurveGeometryId(geometry.Curves.Count() + 1);- geometry.AddCurve(curveId, curve);- bindings.AddEdgeBinding(new EdgeGeometryBinding(edge, curveId, new ParameterInterval(t0, t1)));- return edge;- }- EdgeId Line(VertexId start, VertexId end)- {- var a = points[start]; var b = points[end]; var vector = b - a;- return CurveEdge(start, end, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(vector))), 0d, vector.Length);- }- Ring CircleRing(double x, double radius)- {- var positive = Vertex(new Point3D(x, radius, 0d));- var negative = Vertex(new Point3D(x, -radius, 0d));- var support = new Circle3Curve(new Point3D(x, 0d, 0d), PlusX, radius, PlusY);- return new Ring(positive, negative,- CurveEdge(positive, negative, CurveGeometry.FromCircle(support), 0d, double.Pi),- CurveEdge(negative, positive, CurveGeometry.FromCircle(support), double.Pi, 2d * double.Pi));- }- FaceId Face(IReadOnlyList<IReadOnlyList<Use>> loops, SurfaceGeometry surface, bool sameSense = true, SurfaceGeometryId? sharedSurfaceId = null)- {- var loopIds = new List<LoopId>();- foreach (var uses in loops)- {- var loop = topology.AllocateLoopId();- var coedges = uses.Select(_ => topology.AllocateCoedgeId()).ToArray();- for (var i = 0; i < coedges.Length; i++)- topology.AddCoedge(new Coedge(coedges[i], uses[i].Edge, loop, coedges[(i + 1) % coedges.Length], coedges[(i + coedges.Length - 1) % coedges.Length], uses[i].Reversed));- topology.AddLoop(new Loop(loop, coedges)); loopIds.Add(loop);- }- var face = topology.AddFace(loopIds);- var surfaceId = sharedSurfaceId ?? new SurfaceGeometryId(geometry.Surfaces.Count() + 1);- if (sharedSurfaceId is null) geometry.AddSurface(surfaceId, surface);- bindings.AddFaceBinding(new FaceGeometryBinding(face, surfaceId, sameSense));- faces.Add(face); return face;- }-- var lower = new VertexId[6]; var upper = new VertexId[6];- for (var i = 0; i < 6; i++)- {- var angle = (30d + i * 60d) * double.Pi / 180d;- var y = d.HeadCircumradius * double.Cos(angle);- var z = d.HeadCircumradius * double.Sin(angle);- lower[i] = Vertex(new Point3D(0d, y, z));- upper[i] = Vertex(new Point3D(d.TopConeCornerX, y, z));- }-- var lowerHex = new EdgeId[6]; var upperHyperbolas = new EdgeId[6]; var vertical = new EdgeId[6];- for (var i = 0; i < 6; i++)- {- lowerHex[i] = Line(lower[i], lower[(i + 1) % 6]);- vertical[i] = Line(lower[i], upper[i]);-- var normalAngle = (60d + i * 60d) * double.Pi / 180d;- var normal = new Vector3D(0d, double.Cos(normalAngle), double.Sin(normalAngle));- var tangent = new Vector3D(0d, -double.Sin(normalAngle), double.Cos(normalAngle));- var center = new Point3D(d.TopConeApexX, normal.Y * d.HeadApothem, normal.Z * d.HeadApothem);- var support = new Hyperbola3Curve(center, Direction3D.Create(normal), PlusX,- d.HeadApothem / double.Tan(d.TopConeSemiAngleDegrees * double.Pi / 180d), d.HeadApothem, HyperbolaBranch.PositiveAxisU);- var tStart = ProjectHyperbolaParameter(support, points[upper[i]]);- var tEnd = ProjectHyperbolaParameter(support, points[upper[(i + 1) % 6]]);- if (tEnd < tStart)- {- support = support.Reverse();- tStart = ProjectHyperbolaParameter(support, points[upper[i]]);- tEnd = ProjectHyperbolaParameter(support, points[upper[(i + 1) % 6]]);- }- upperHyperbolas[i] = CurveEdge(upper[i], upper[(i + 1) % 6], CurveGeometry.FromHyperbola(support), tStart, tEnd);- }-- var shankRadius = spec.NominalDiameter / 2d;- var underHeadOuterRadius = shankRadius + spec.UnderHeadRadius;- var torusEndX = spec.UnderHeadRadius;- var topVertices = new VertexId[6];- for (var i = 0; i < 6; i++)- {- var angle = (30d + i * 60d) * double.Pi / 180d;- topVertices[i] = Vertex(new Point3D(-spec.HeadHeight, d.TopFlatRadius * double.Cos(angle), d.TopFlatRadius * double.Sin(angle)));- }- var topArcs = new EdgeId[6]; var coneGenerators = new EdgeId[6];- var topCircleSupport = new Circle3Curve(new Point3D(-spec.HeadHeight, 0d, 0d), PlusX, d.TopFlatRadius, PlusY);- for (var i = 0; i < 6; i++)- {- var startAngle = (30d + i * 60d) * double.Pi / 180d;- topArcs[i] = CurveEdge(topVertices[i], topVertices[(i + 1) % 6], CurveGeometry.FromCircle(topCircleSupport), startAngle, startAngle + double.Pi / 3d);- coneGenerators[i] = Line(topVertices[i], upper[i]);- }- var underHeadRing = CircleRing(0d, underHeadOuterRadius);- var shankStartRing = spec.UnderHeadRadius > Tolerance ? CircleRing(torusEndX, shankRadius) : underHeadRing;- var tipStartRing = CircleRing(d.TipChamferStartX, shankRadius);- var tipRing = CircleRing(spec.Length, spec.TipDiameter / 2d);-- var sideFaces = new FaceId[6];- for (var i = 0; i < 6; i++)- {- var a = points[lower[i]]; var b = points[lower[(i + 1) % 6]];- var tangent = Direction3D.Create(b - a);- var outward = Direction3D.Create(tangent.ToVector().Cross(PlusX.ToVector()));- sideFaces[i] = Face([[new(lowerHex[i], false), new(vertical[(i + 1) % 6], false), new(upperHyperbolas[i], true), new(vertical[i], true)]],- SurfaceGeometry.FromPlane(new PlaneSurface(a, outward, PlusX)));- }-- var cone = new ConeSurface(new Point3D(d.TopConeApexX, 0d, 0d), PlusX,- d.TopConeSemiAngleDegrees * double.Pi / 180d, PlusY);- var coneSurfaceId = new SurfaceGeometryId(geometry.Surfaces.Count() + 1);- geometry.AddSurface(coneSurfaceId, SurfaceGeometry.FromCone(cone));- var topChamferFaces = new FaceId[6];- for (var i = 0; i < 6; i++)- topChamferFaces[i] = Face([[new(topArcs[i], false), new(coneGenerators[(i + 1) % 6], false), new(upperHyperbolas[i], true), new(coneGenerators[i], true)]], SurfaceGeometry.FromCone(cone), sharedSurfaceId: coneSurfaceId);- var topFlat = Face([topArcs.Select(e => new Use(e, false)).ToArray()], SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(-spec.HeadHeight, 0d, 0d), MinusX, PlusY)));- var underHead = Face([lowerHex.Reverse().Select(e => new Use(e, true)).ToArray(), [new(underHeadRing.Arc0, false), new(underHeadRing.Arc1, false)]],- SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, PlusX, PlusY)));-- var underHeadBlendFaces = new List<FaceId>();- if (spec.UnderHeadRadius > Tolerance)- {- var plusCenter = new Point3D(spec.UnderHeadRadius, underHeadOuterRadius, 0d);- var minusCenter = new Point3D(spec.UnderHeadRadius, -underHeadOuterRadius, 0d);- var plusSeam = CurveEdge(underHeadRing.Positive, shankStartRing.Positive,- CurveGeometry.FromCircle(new Circle3Curve(plusCenter, Direction3D.Create(new Vector3D(0d, 0d, 1d)), spec.UnderHeadRadius, MinusX)), 0d, double.Pi / 2d);- var minusSeam = CurveEdge(underHeadRing.Negative, shankStartRing.Negative,- CurveGeometry.FromCircle(new Circle3Curve(minusCenter, Direction3D.Create(new Vector3D(0d, 0d, -1d)), spec.UnderHeadRadius, MinusX)), 0d, double.Pi / 2d);- var torusSupport = SurfaceGeometry.FromTorus(new TorusSurface(new Point3D(spec.UnderHeadRadius, 0d, 0d), PlusX, underHeadOuterRadius, spec.UnderHeadRadius, PlusY));- var torusSurfaceId = new SurfaceGeometryId(geometry.Surfaces.Count() + 1); geometry.AddSurface(torusSurfaceId, torusSupport);- underHeadBlendFaces.Add(Face([[new(underHeadRing.Arc0, false), new(minusSeam, false), new(shankStartRing.Arc0, true), new(plusSeam, true)]], torusSupport, sharedSurfaceId: torusSurfaceId));- underHeadBlendFaces.Add(Face([[new(underHeadRing.Arc1, false), new(plusSeam, false), new(shankStartRing.Arc1, true), new(minusSeam, true)]], torusSupport, sharedSurfaceId: torusSurfaceId));- }- var shankPlusSeam = Line(shankStartRing.Positive, tipStartRing.Positive);- var shankMinusSeam = Line(shankStartRing.Negative, tipStartRing.Negative);- var cylinderSupport = SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(torusEndX, 0d, 0d), PlusX, shankRadius, PlusY));- var cylinderSurfaceId = new SurfaceGeometryId(geometry.Surfaces.Count() + 1); geometry.AddSurface(cylinderSurfaceId, cylinderSupport);- var shankFaces = new[]- {- Face([[new(shankStartRing.Arc0, false), new(shankMinusSeam, false), new(tipStartRing.Arc0, true), new(shankPlusSeam, true)]], cylinderSupport, sharedSurfaceId: cylinderSurfaceId),- Face([[new(shankStartRing.Arc1, false), new(shankPlusSeam, false), new(tipStartRing.Arc1, true), new(shankMinusSeam, true)]], cylinderSupport, sharedSurfaceId: cylinderSurfaceId)- };- var tipSlope = (shankRadius - spec.TipDiameter / 2d) / spec.TipChamferLength;- var tipApexX = d.TipChamferStartX + shankRadius / tipSlope;- var tipPlusSeam = Line(tipStartRing.Positive, tipRing.Positive);- var tipMinusSeam = Line(tipStartRing.Negative, tipRing.Negative);- var tipSupport = SurfaceGeometry.FromCone(new ConeSurface(new Point3D(tipApexX, 0d, 0d), MinusX, double.Atan(tipSlope), PlusY));- var tipSurfaceId = new SurfaceGeometryId(geometry.Surfaces.Count() + 1); geometry.AddSurface(tipSurfaceId, tipSupport);- var tipChamferFaces = new[]- {- Face([[new(tipStartRing.Arc0, false), new(tipMinusSeam, false), new(tipRing.Arc0, true), new(tipPlusSeam, true)]], tipSupport, sharedSurfaceId: tipSurfaceId),- Face([[new(tipStartRing.Arc1, false), new(tipPlusSeam, false), new(tipRing.Arc1, true), new(tipMinusSeam, true)]], tipSupport, sharedSurfaceId: tipSurfaceId)- };- var tipFace = Face([[new(tipRing.Arc1, true), new(tipRing.Arc0, true)]], SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(spec.Length, 0d, 0d), PlusX, PlusY)));-- var shell = topology.AddShell(faces); topology.AddBody([shell]);- var body = new BrepBody(topology.Model, geometry, bindings, points);- var descendants = new List<HexBoltSemanticDescendant>- {- new(bodyStableId, HexBoltSemanticKind.Part),- new($"{bodyStableId}.Head", HexBoltSemanticKind.Region, ParentStableId: bodyStableId),- new($"{bodyStableId}.Head.TopChamfer", HexBoltSemanticKind.Region, ParentStableId: $"{bodyStableId}.Head"),- new($"{bodyStableId}.Head.TopFlat", HexBoltSemanticKind.Face, topFlat, $"{bodyStableId}.Head"),- new($"{bodyStableId}.Head.UnderHead", HexBoltSemanticKind.Face, underHead, $"{bodyStableId}.Head"),- new($"{bodyStableId}.Shank", HexBoltSemanticKind.Region, ParentStableId: bodyStableId),- new($"{bodyStableId}.ThreadRegion", HexBoltSemanticKind.Region, ParentStableId: bodyStableId, Metadata: $"{spec.ThreadDesignation};length={spec.ThreadLength:R}mm;material-geometry=Cylinder"),- new($"{bodyStableId}.TipChamfer", HexBoltSemanticKind.Region, ParentStableId: bodyStableId),- new($"{bodyStableId}.TipFace", HexBoltSemanticKind.Face, tipFace, bodyStableId)- };- for (var i = 0; i < sideFaces.Length; i++) descendants.Add(new($"{bodyStableId}.Head.Side[{i}]", HexBoltSemanticKind.Face, sideFaces[i], $"{bodyStableId}.Head"));- for (var i = 0; i < topChamferFaces.Length; i++) descendants.Add(new($"{bodyStableId}.Head.TopChamfer.Face[{i}]", HexBoltSemanticKind.Face, topChamferFaces[i], $"{bodyStableId}.Head.TopChamfer"));- for (var i = 0; i < shankFaces.Length; i++) descendants.Add(new($"{bodyStableId}.Shank.Face[{i}]", HexBoltSemanticKind.Face, shankFaces[i], $"{bodyStableId}.Shank"));- for (var i = 0; i < shankFaces.Length; i++) descendants.Add(new($"{bodyStableId}.ThreadRegion.Face[{i}]", HexBoltSemanticKind.Face, shankFaces[i], $"{bodyStableId}.ThreadRegion"));- for (var i = 0; i < tipChamferFaces.Length; i++) descendants.Add(new($"{bodyStableId}.TipChamfer.Face[{i}]", HexBoltSemanticKind.Face, tipChamferFaces[i], $"{bodyStableId}.TipChamfer"));- for (var i = 0; i < underHeadBlendFaces.Count; i++) descendants.Add(new($"{bodyStableId}.Head.UnderHeadBlend.Face[{i}]", HexBoltSemanticKind.Face, underHeadBlendFaces[i], $"{bodyStableId}.Head"));-- var metadata = new Dictionary<string, string>(StringComparer.Ordinal)- {- ["NominalDiameter"] = $"{spec.NominalDiameter:R}mm",- ["ThreadLength"] = $"{spec.ThreadLength:R}mm",- ["ThreadDesignation"] = spec.ThreadDesignation,- ["PropertyClass"] = spec.PropertyClass,- ["ThreadGeometry"] = "deferred-semantic-cylinder"- };- var signatureSource = string.Join("|", new[]- {- spec.NominalDiameter, spec.Length, spec.HeadAcrossFlats, spec.HeadHeight, spec.TopFlatDiameter,- spec.TopChamferAngle, spec.TipChamferLength, spec.TipDiameter, spec.ThreadLength, spec.UnderHeadRadius- }.Select(x => x.ToString("R", System.Globalization.CultureInfo.InvariantCulture))) + $"|{spec.ThreadDesignation}|{spec.PropertyClass}";- var signature = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(signatureSource))).ToLowerInvariant();- return new(spec, d, body, new(bodyStableId, descendants, metadata), signature);- }-- private static double ProjectHyperbolaParameter(Hyperbola3Curve curve, Point3D point)- {- var relative = point - curve.Center;- var sinh = relative.Dot(curve.AxisV.ToVector()) / curve.SemiAxisB;- return double.Asinh(sinh);- }-- private readonly record struct Ring(VertexId Positive, VertexId Negative, EdgeId Arc0, EdgeId Arc1);- private readonly record struct Use(EdgeId Edge, bool Reversed);-}diff --git a/docs/preview2/construction-ir-m1.md b/docs/preview2/construction-ir-m1.mdnew file mode 100644index 00000000..1b0a7d5c--- /dev/null+++ b/docs/preview2/construction-ir-m1.md@@ -0,0 +1,31 @@+# P2-CONSTRUCTION-IR-M1 — exact coaxial construction extraction++## Audit and boundary++`HexBoltBuilder` proved an exact sequence: a six-sided prism, a cone shared by six planar trims, a planar top cap, an interior root blend, a split periodic shank cylinder, a split tip cone, and a planar tip cap. Dimensions, bolt admission, thread metadata, and semantic names are family knowledge. Regular-polygon math, analytic supports, cone/plane hyperbola edges, periodic splitting, and face incidence are reusable exact-construction capability.++## IR and materialization++`ExactConstructionIr.cs` defines a bounded vocabulary: `RegularPrismConstruction`, `AxialCylinderConstruction`, `AxialFrustumConstruction`, `ConePlanarTrimConstruction`, `ConcaveFilletConstruction`, and `AxialSectionStackConstruction`. `ConstructionSemanticGroup` is separate from geometry. A plan names shared supports (`head-cone`, `shank-cylinder`, `tip-cone`, `under-head-torus`) before topology emission.++`HexBoltConstructionPlanner` contains family admission and lowering. The emitter consumes `ExactCoaxialConstructionPlan`, which contains no `HexBoltSpec`. `ExactBrepEmissionContext` owns deterministic vertex, edge, curve, support, loop, coedge, face, shell, and body allocation. `RegularPrismMaterializer`, `ConePlanarTrimMaterializer`, `AxialCylinderMaterializer`, `AxialFrustumMaterializer`, and `PeriodicTorusBlendMaterializer` emit their bounded responsibilities; `CoaxialConstructionMaterializer` only orders their shared boundaries. Cylinder, cone, and torus face uses split deterministically at Y-axis seams while retaining one support ID.++`ConcaveFilletConstruction` adds material to the interior cylinder/shoulder corner; its geometry is a periodic torus blend. It is intentionally distinct from convex, material-removing profile edge fillets.++## Exact conics and scope++The admitted cone/plane family builds `Hyperbola3Curve` boundaries on the shared cone support and regular-prism side planes. Parameters are projected from known endpoints and oriented for the owning loop. No arbitrary surface intersection, Boolean, sweep, loft, or NURBS facility was introduced.++## Migration and evidence++`ExactCoaxialPartBuilder` now lowers directly to `ExactCoaxialConstructionPlan`, returns `ExactCoaxialPartDefinition`, and invokes `ExactConstructionMaterializer`; it has no `HexBoltSpec`, `HexBoltDefinition`, or `HexBoltBuilder` dependency in its production path. The latter is a compatibility/golden-oracle facade over the same generic planner/materializer, avoiding a second geometry kernel.++Tests cover hex and octagonal prism derivation, a fully emitted octagonal non-bolt spacer, root-torus dimensions, shared support identity across split faces, cone/plane trim intent, and planned materialization with Plane/Cylinder/Cone/Torus. Existing M2 tests compare M1-equivalent topology, analytic families, semantics, signatures, STEP reimport, and no `B_SPLINE` output for reference, M10x50, and nonstandard variants.++Current limitations are deliberate: the plan is one connected regular-prism/coaxial stack, periodic splitting is the proven two-half-face policy, cone/plane trimming covers the admitted right-circular-cone/regular-prism-plane family, and the root blend covers a coaxial cylinder/perpendicular shoulder. It is not CSG, arbitrary surface intersection, arbitrary polygon meshing, or a general fillet solver.++## Validation snapshot++The reference construction-IR STEP has SHA-256 `fb45f414bcaba96bdbf6b7773def91c6c3057e4af0bb70d5273d5fe344c61174` on repeated builds. Aetheris reimport reports one body, one shell, 21 faces, 44 edges, 26 vertices, an enclosed manifold, 9 planar faces, 2 cylindrical faces on one support, 8 conical faces on two supports, 2 toroidal faces on one support, and zero B-spline surfaces. FreeCAD/OCCT imports one valid closed solid without healing and reports `Cone:8,Cylinder:2,Plane:9,Toroid:2`.++A Debug-build micro-measurement (Windows, warm process) measured plan creation at about 0.047 ms, direct generic BRep emission at 0.83 ms, the compatibility builder facade including planning and validation at 1.68 ms, and STEP export at 1.81 ms per reference part. These are guardrail measurements rather than a benchmark contract.diff --git a/docs/preview2/hexbolt-template-m2.md b/docs/preview2/hexbolt-template-m2.mdindex 9bbb2013..14f8c432 100644--- a/docs/preview2/hexbolt-template-m2.md+++ b/docs/preview2/hexbolt-template-m2.md@@ -37,12 +37,13 @@ operations:- `CoaxialConeFrustum` for the end treatment;- `SemanticAxialRegion` and metadata publication.-The current backend admits six polygon sides for this bounded recipe and reports-other counts as unsupported. `ExactCoaxialPartBuilder` maps the generic recipe to-the proven M1 analytic topology engine. Thus M1 remains both oracle and internal-geometry implementation during M2, while the Firmament route no longer selects-a HexBolt family hook. A later backend refactor can move the topology engine out-of the M1-named facade without changing Firmament source.+The connected recipe uses a polygon-generic regular-prism emitter (the HexBolt+Template authors six sides). `ExactCoaxialPartBuilder` lowers the recipe to `ExactCoaxialConstructionPlan` and+uses `ExactConstructionMaterializer`, rather than calling `HexBoltBuilder`.+M1 remains the comparison facade over the same planner/materializer; the Firmament+route has no bespoke bolt-builder dependency. See+[construction-ir-m1.md](construction-ir-m1.md) for the bounded IR and support-sharing+contract.## Admission rules