Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add bounded semantic mirror and radial pattern authoring
Yuechen Li73ef60eafdef
diff --git a/Aetheris.CLI.Tests/SemanticSymmetryCliTests.cs b/Aetheris.CLI.Tests/SemanticSymmetryCliTests.csnew file mode 100644index 00000000..cafc3574--- /dev/null+++ b/Aetheris.CLI.Tests/SemanticSymmetryCliTests.cs@@ -0,0 +1,63 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class SemanticSymmetryCliTests+{+ [Fact]+ public void Inspect_reports_mirror_and_radial_provenance()+ {+ var mirrorOut = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["inspect", Fixture("Canonical", "Symmetry", "mirrored-hole.firmament"), "--json"], mirrorOut, new StringWriter()));+ using var mirrorJson = JsonDocument.Parse(mirrorOut.ToString());+ var mirror = Assert.Single(mirrorJson.RootElement.GetProperty("mirrors").EnumerateArray());+ Assert.Equal("LeftMount", mirror.GetProperty("source").GetString());+ Assert.Equal("RightMount", mirror.GetProperty("destination").GetString());+ Assert.Equal("CanonicalRightHanded", mirror.GetProperty("handednessCorrection").GetString());++ var radialOut = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["inspect", Fixture("Canonical", "Symmetry", "radial-bolt-circle.firmament"), "--json"], radialOut, new StringWriter()));+ using var radialJson = JsonDocument.Parse(radialOut.ToString());+ var radial = Assert.Single(radialJson.RootElement.GetProperty("radialPatterns").EnumerateArray());+ Assert.Equal(6, radial.GetProperty("count").GetInt32());+ Assert.Equal("FullOpenEndpoint", radial.GetProperty("distribution").GetString());+ Assert.Equal(Enumerable.Range(0, 6).Select(index => $"BoltCircle.Instance{index}"),+ radial.GetProperty("instanceTransforms").EnumerateArray().Select(instance => instance.GetProperty("identity").GetString()));+ }++ [Fact]+ public void Inspect_resolves_semantic_boundary_then_mirrored_profile_for_revolve()+ {+ var stdout = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["inspect", Fixture("Canonical", "Symmetry", "mirrored-revolve.firmament"), "--json"], stdout, new StringWriter()));+ using var json = JsonDocument.Parse(stdout.ToString());+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());+ Assert.Equal("Revolve", json.RootElement.GetProperty("domain").GetString());+ var revolve = json.RootElement.GetProperty("revolve");+ Assert.Equal("UpperSection", revolve.GetProperty("profile").GetString());+ Assert.Equal(180d, revolve.GetProperty("sweepDegrees").GetDouble(), 10);+ }++ [Theory]+ [InlineData("count-zero.firmament", "firmament-symmetry-radial-count-invalid")]+ [InlineData("invalid-axis.firmament", "firmament-symmetry-radial-axis-invalid")]+ [InlineData("invalid-angle.firmament", "firmament-symmetry-radial-angle-invalid")]+ [InlineData("invalid-plane.firmament", "firmament-symmetry-plane-invalid")]+ [InlineData("identity-collision.firmament", "firmament-symmetry-identity-collision")]+ [InlineData("unsupported-mirror-type.firmament", "firmament-symmetry-type-unsupported")]+ [InlineData("unsupported-selector.firmament", "firmament-symmetry-feature-center-unsupported")]+ public void Invalid_symmetry_fixtures_are_fatal(string name, string code)+ {+ var stdout = new StringWriter();+ Assert.Equal(1, CliRunner.Run(["validate", Fixture("Invalid", "Symmetry", name), "--json"], stdout, new StringWriter()));+ using var json = JsonDocument.Parse(stdout.ToString());+ var report = json.RootElement.GetProperty("firmamentV2Validation");+ Assert.Equal("invalid", report.GetProperty("status").GetString());+ Assert.Contains(report.GetProperty("diagnostics").EnumerateArray(), diagnostic =>+ diagnostic.GetProperty("code").GetString()!.StartsWith(code, StringComparison.Ordinal)+ && diagnostic.GetProperty("severity").GetString() == "fatal");+ }++ private static string Fixture(params string[] parts) =>+ Path.GetFullPath(Path.Combine([AppContext.BaseDirectory, "../../../../fixtures", .. parts]));+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 95f4d741..dd2f3c36 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -1590,6 +1590,26 @@ Model CanonicalPanel {distribution = "AuthoredSourceOrder",status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan"}).ToArray() ?? [],+ mirrors = document?.StaticAuthoring?.Mirrors?.Select(mirror => new+ {+ kind = "Mirrored",+ mirror.Destination,+ mirror.Source,+ acrossPlane = mirror.AcrossPlane,+ mirror.HandednessCorrection,+ mirror.Provenance,+ members = mirror.Members+ }).ToArray() ?? [],+ radialPatterns = document?.StaticAuthoring?.RadialPatterns?.Select(pattern => new+ {+ pattern.Name,+ pattern.Source,+ pattern.Axis,+ pattern.Count,+ pattern.AngleRadians,+ pattern.Distribution,+ instanceTransforms = pattern.Instances+ }).ToArray() ?? [],templateInstances = (document?.TemplateInstantiations ?? document?.ConceptIr?.TemplateInstantiations)?.Select(instance => new{instance.Template,diff --git a/Aetheris.Kernel.Firmament.Tests/SemanticSymmetryX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/SemanticSymmetryX1Tests.csnew file mode 100644index 00000000..7c0962aa--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/SemanticSymmetryX1Tests.cs@@ -0,0 +1,225 @@+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Xunit;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class SemanticSymmetryX1Tests+{+ [Fact]+ public void Point_vector_axis_plane_and_frame_reflect_analytically()+ {+ var mirror = new SemanticSymmetryTransform.Plane(new(0, 0, 0), Direction3D.Create(new(1, 0, 0)));+ Assert.Equal(new Point3D(-3, 4, 5), SemanticSymmetryTransform.Reflect(new Point3D(3, 4, 5), mirror));+ Assert.Equal(new Vector3D(-3, 4, 5), SemanticSymmetryTransform.Reflect(new Vector3D(3, 4, 5), mirror));++ var axis = SemanticSymmetryTransform.Reflect(new SemanticSymmetryTransform.Axis(new(2, 1, 0), Direction3D.Create(new(1, 1, 0))), mirror);+ Assert.Equal(-2, axis.Origin.X, 12);+ Assert.Equal(-1 / Math.Sqrt(2), axis.Direction.X, 12);+ var plane = SemanticSymmetryTransform.Reflect(new SemanticSymmetryTransform.Plane(new(2, 0, 0), Direction3D.Create(new(1, 1, 0))), mirror);+ Assert.Equal(-2, plane.Origin.X, 12);+ Assert.Equal(-1 / Math.Sqrt(2), plane.Normal.X, 12);++ var frame = new SemanticSymmetryTransform.Frame(new(2, 0, 0), Direction3D.Create(new(1, 0, 0)), Direction3D.Create(new(0, 1, 0)), Direction3D.Create(new(0, 0, 1)));+ var naive = SemanticSymmetryTransform.Reflect(frame.X.ToVector(), mirror).Cross(SemanticSymmetryTransform.Reflect(frame.Y.ToVector(), mirror)).Dot(SemanticSymmetryTransform.Reflect(frame.Z.ToVector(), mirror));+ Assert.Equal(-1, naive, 12);+ var reflected = SemanticSymmetryTransform.Reflect(frame, mirror);+ Assert.Equal(1, reflected.Determinant, 12);+ var restored = SemanticSymmetryTransform.Reflect(reflected, mirror);+ Assert.Equal(frame.Origin, restored.Origin);+ Assert.Equal(1, restored.Determinant, 12);+ }++ [Fact]+ public void Mirrored_profile_reverses_reflected_traversal_and_retains_member_provenance()+ {+ var diagnostics = new List<string>();+ var expansion = Assert.IsType<SemanticSymmetryAuthoring.Result>(SemanticSymmetryAuthoring.Expand(ProfileSource, diagnostics));+ Assert.Empty(diagnostics);+ var profile = ProfileAuthoringParser.ResolveNamedProfile(expansion.Source, "RightCutout", out var profileDiagnostics);+ Assert.NotNull(profile);+ Assert.DoesNotContain(profileDiagnostics, item => item.Contains("invalid", StringComparison.OrdinalIgnoreCase));+ var points = profile!.Loops.Single().Segments.Select(segment => segment.Geometry).OfType<Aetheris.Kernel.Firmament.Materializer.LineArcLineSegment2D>().SelectMany(line => new[] { line.Start, line.End }).ToArray();+ Assert.Equal(-8, points.Min(point => point.X), 10);+ Assert.Equal(-2, points.Max(point => point.X), 10);+ Assert.Single(expansion.Mirrors);+ Assert.All(expansion.Mirrors[0].Members, member => Assert.StartsWith("LeftCutout.", member.SourceIdentity));+ }++ [Fact]+ public void Mirror_twice_recovers_profile_geometry()+ {+ var source = ProfileSource.Replace("Mirrored Profile RightCutout From LeftCutout { Across: CenterPlane }",+ "Mirrored Profile RightCutout From LeftCutout { Across: CenterPlane }\nMirrored Profile Restored From RightCutout { Across: CenterPlane }");+ var diagnostics = new List<string>();+ var first = SemanticSymmetryAuthoring.Expand(source, diagnostics);+ Assert.NotNull(first);+ Assert.Empty(diagnostics);+ var original = ProfileAuthoringParser.ResolveNamedProfile(first!.Source, "LeftCutout", out _)!;+ var restored = ProfileAuthoringParser.ResolveNamedProfile(first.Source, "Restored", out _)!;+ var originalPoints = original.Loops.Single().Segments.Select(segment => segment.Geometry).OfType<Aetheris.Kernel.Firmament.Materializer.LineArcLineSegment2D>().Select(line => line.Start).ToArray();+ var restoredPoints = restored.Loops.Single().Segments.Select(segment => segment.Geometry).OfType<Aetheris.Kernel.Firmament.Materializer.LineArcLineSegment2D>().Select(line => line.Start).ToArray();+ Assert.Equal(originalPoints.OrderBy(point => point.X).ThenBy(point => point.Y), restoredPoints.OrderBy(point => point.X).ThenBy(point => point.Y));+ }++ [Fact]+ public void Mirrored_arc_preserves_locus_and_canonical_loop_traversal()+ {+ var diagnostics = new List<string>();+ var expansion = SemanticSymmetryAuthoring.Expand(ArcProfileSource, diagnostics);+ Assert.NotNull(expansion);+ Assert.Empty(diagnostics);+ var mirrored = ProfileAuthoringParser.ResolveNamedProfile(expansion!.Source, "RightD", out var profileDiagnostics);+ Assert.NotNull(mirrored);+ Assert.Empty(profileDiagnostics);+ var arc = Assert.Single(mirrored!.Loops.Single().Segments.Select(segment => segment.Geometry).OfType<Aetheris.Kernel.Firmament.Materializer.LineArcCircularArc2D>());+ Assert.Equal(-5, arc.Center.X, 10);+ Assert.Equal(5, arc.Radius, 10);+ Assert.Equal(Math.PI, Math.Abs(arc.SweepAngleRadians), 10);+ }++ [Fact]+ public void Full_and_partial_radial_distributions_are_deterministic()+ {+ var fullDiagnostics = new List<string>();+ var full = Assert.IsType<SemanticSymmetryAuthoring.Result>(SemanticSymmetryAuthoring.Expand(RadialSource("6", "full"), fullDiagnostics));+ Assert.Empty(fullDiagnostics);+ var pattern = Assert.Single(full.RadialPatterns);+ Assert.Equal(Enumerable.Range(0, 6).Select(i => i * Math.PI / 3), pattern.Instances.Select(instance => instance.RotationAngleRadians), new DoubleComparer());+ Assert.Equal(6, RegexCount(full.Source, @"Hole\s*<\s*Shaft\s*>\s+BoltCircle_Instance"));++ var partialDiagnostics = new List<string>();+ var partial = Assert.IsType<SemanticSymmetryAuthoring.Result>(SemanticSymmetryAuthoring.Expand(RadialSource("5", "half"), partialDiagnostics));+ Assert.Empty(partialDiagnostics);+ Assert.Equal(new[] { 0d, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI }, partial.RadialPatterns.Single().Instances.Select(instance => instance.RotationAngleRadians), new DoubleComparer());++ var singleDiagnostics = new List<string>();+ var single = SemanticSymmetryAuthoring.Expand(RadialSource("1", "full"), singleDiagnostics);+ Assert.NotNull(single);+ Assert.Empty(singleDiagnostics);+ Assert.Equal(0, Assert.Single(single!.RadialPatterns.Single().Instances).RotationAngleRadians);+ }++ [Fact]+ public void Mirror_then_rotate_is_not_reordered()+ {+ var mirror = new SemanticSymmetryTransform.Plane(new(0, 0, 0), Direction3D.Create(new(1, 0, 0)));+ var axis = new SemanticSymmetryTransform.Axis(new(0, 0, 0), Direction3D.Create(new(0, 0, 1)));+ var point = new Point3D(3, 4, 0);+ var mirrorThenRotate = SemanticSymmetryTransform.Rotate(SemanticSymmetryTransform.Reflect(point, mirror), axis, Math.PI / 2);+ var rotateThenMirror = SemanticSymmetryTransform.Reflect(SemanticSymmetryTransform.Rotate(point, axis, Math.PI / 2), mirror);+ Assert.NotEqual(mirrorThenRotate, rotateThenMirror);+ }++ [Fact]+ public void Coincident_feature_mirror_is_rejected_before_materialization()+ {+ var source = ArcProfileSource.Replace("Mirrored Profile RightD From LeftD { Across: CenterPlane }",+ "Hole<Shaft> Centered { On: +Z; Center: Point2(0mm,0mm); Diameter: 4mm; End: ThroughAll }\nMirrored Feature Duplicate From Centered { Across: CenterPlane }");+ var diagnostics = new List<string>();+ Assert.Null(SemanticSymmetryAuthoring.Expand(source, diagnostics));+ Assert.Contains("firmament-symmetry-redundant-feature-mirror:Duplicate", diagnostics);+ }++ [Theory]+ [InlineData("0", "full", "firmament-symmetry-radial-count-invalid")]+ [InlineData("6", "nonsense", "firmament-symmetry-radial-angle-invalid")]+ public void Invalid_radial_inputs_fail_semantically(string count, string angle, string expected)+ {+ var diagnostics = new List<string>();+ Assert.Null(SemanticSymmetryAuthoring.Expand(RadialSource(count, angle), diagnostics));+ Assert.Contains(diagnostics, item => item.StartsWith(expected, StringComparison.Ordinal));+ }++ [Fact]+ public void Unsupported_mirror_type_fails_typed()+ {+ var diagnostics = new List<string>();+ Assert.Null(SemanticSymmetryAuthoring.Expand("Mirrored Material Right From Left { Across: CenterPlane }", diagnostics));+ Assert.Contains("firmament-symmetry-type-unsupported:Material", diagnostics);+ }++ [Theory]+ [InlineData("fixtures/Canonical/Symmetry/mirrored-hole.firmament")]+ [InlineData("fixtures/Canonical/Symmetry/mirrored-profile.firmament")]+ [InlineData("fixtures/Canonical/Symmetry/radial-bolt-circle.firmament")]+ [InlineData("fixtures/Canonical/Symmetry/mirrored-feature-with-override.firmament")]+ public void Canonical_feature_witnesses_parse_through_production_route(string path)+ {+ var source = File.ReadAllText(Path.Combine(RepositoryRoot(), path));+ var expanded = FirmamentV2Parser.TryExpandCanonicalStaticAuthoring(source, out var normalized, out var expansionDiagnostics);+ Assert.True(expanded, string.Join(Environment.NewLine, expansionDiagnostics) + Environment.NewLine + normalized);+ var parsed = FirmamentV2Parser.Parse(source[source.IndexOf("Model ", StringComparison.Ordinal)..]);+ Assert.True(parsed.IsSuccess, string.Join(Environment.NewLine, parsed.Diagnostics) + Environment.NewLine + normalized);+ }++ [Fact]+ public void Profile_and_revolve_witnesses_use_the_strongest_closed_boundary_semantics()+ {+ var profile = File.ReadAllText(Path.Combine(RepositoryRoot(), "fixtures/Canonical/Symmetry/mirrored-profile.firmament"));+ Assert.Contains("Triangle2<Explicit> LeftBoundary", profile, StringComparison.Ordinal);+ Assert.Contains("LeftBoundary |> TraceLoop", profile, StringComparison.Ordinal);+ Assert.DoesNotContain("Line2 AB", profile, StringComparison.Ordinal);++ var revolve = File.ReadAllText(Path.Combine(RepositoryRoot(), "fixtures/Canonical/Symmetry/mirrored-revolve.firmament"));+ Assert.Contains("Rect2 LowerBoundary", revolve, StringComparison.Ordinal);+ Assert.Contains("LowerBoundary |> TraceLoop", revolve, StringComparison.Ordinal);+ Assert.DoesNotContain("Line2 AB", revolve, StringComparison.Ordinal);+ }++ private const string ProfileSource = """+ Model MirrorProfile {+ Units: mm+ Concept Struct Supports { Center: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] } }+ Construction Plane CenterPlane { Trace: Supports.Center }+ Point2 A { Position: [2mm, 0mm] }+ Point2 B { Position: [8mm, 0mm] }+ Point2 C { Position: [5mm, 6mm] }+ Line2 AB { From: A; To: B }+ Line2 BC { From: B; To: C }+ Line2 CA { From: C; To: A }+ Profile LeftCutout {+ Loop Outer {+ Segment Bottom { Trace: AB; From: A; To: B }+ Segment Diagonal { Trace: BC; From: B; To: C }+ Segment Return { Trace: CA; From: C; To: A }+ }+ }+ Mirrored Profile RightCutout From LeftCutout { Across: CenterPlane }+ }+ """;++ private const string ArcProfileSource = """+ Model ArcMirror {+ Units: mm+ Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ Point2 East { Position: [10mm, 0mm] }+ Point2 West { Position: [0mm, 0mm] }+ Point2 Center { Position: [5mm, 0mm] }+ Circle2 Rim { Center: Center; Radius: 5mm }+ Line2 Diameter { From: West; To: East }+ Profile LeftD { Loop Outer {+ Segment RimArc { Trace: Rim; From: East; To: West; Sweep: CounterClockwise }+ Segment Closure { Trace: Diameter; From: West; To: East }+ } }+ Mirrored Profile RightD From LeftD { Across: CenterPlane }+ }+ """;++ private static string RadialSource(string count, string angle) => $$"""+ Model Radial {+ Units: mm+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }+ Hole<Shaft> Seed { On: +Z Center: Point2(20mm, 0mm) Diameter: 4mm End: ThroughAll }+ Radial Pattern BoltCircle { Source: Seed About: MainAxis Count: {{count}} Angle: {{angle}} }+ }+ """;++ private static int RegexCount(string source, string pattern) => System.Text.RegularExpressions.Regex.Matches(source, pattern).Count;+ private static string RepositoryRoot() => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", ".."));+ private sealed class DoubleComparer : IEqualityComparer<double>+ {+ public bool Equals(double x, double y) => Math.Abs(x - y) < 1e-12;+ public int GetHashCode(double obj) => 0;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 46167e5d..f3d8c422 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -14,8 +14,12 @@ internal static class CanonicalStaticAuthoringpublic static Result? Expand(string source, List<string> diagnostics){+ var symmetry = SemanticSymmetryAuthoring.Expand(source, diagnostics);+ if (symmetry is null) return null;+ source = symmetry.Source;var canonicalRoot = Regex.IsMatch(source, @"^\s*Model\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);- var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s*(?:<|[A-Za-z_]\w*\s*\()|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant);+ var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s*(?:<|[A-Za-z_]\w*\s*\()|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant)+ || symmetry.Mirrors.Count > 0 || symmetry.RadialPatterns.Count > 0;if (!staticDeclaration && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) return new(source, null);var changes = new List<(int Start, int Length, string Text)>();var names = new HashSet<string>(StringComparer.Ordinal);@@ -269,7 +273,7 @@ internal static class CanonicalStaticAuthoring.Where(change => !erasures.Any(erase => erase.Start < change.Start && change.Start < erase.Start + erase.Length)).OrderByDescending(change => change.Start))source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);- return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets));+ return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets, symmetry.Mirrors, symmetry.RadialPatterns));}private static IReadOnlyList<FirmamentV2StaticSetEntry> ParseSetEntries(string source, int start, int end, string setName, string elementType,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex a8f26b6d..9b7578cd 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -270,7 +270,7 @@ public sealed record FirmamentV2BossDecl(string Name, string Host, string On, stpublic sealed record FirmamentV2PocketDecl(string Name, string Host, string On, string Profile, double Depth, double HostThickness, double RemainingFloor, double MinimumFloorThickness, string MinimumFloorPolicySource, string StableId, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan);/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>-public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null);+public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null, IReadOnlyList<FirmamentV2MirrorDerivation>? Mirrors = null, IReadOnlyList<FirmamentV2RadialPatternDecl>? RadialPatterns = null);public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2StaticArrayDecl(string Name, string ElementType, IReadOnlyList<IReadOnlyDictionary<string, string>> Elements, FirmamentV2SourceSpan SourceSpan);/// <summary>A finite immutable source-ordered collection whose entry names are semantic identity.</summary>@@ -282,6 +282,10 @@ public sealed record FirmamentV2StaticTableDecl(string Name, string RowType, strpublic sealed record FirmamentV2CanonicalTemplateDecl(string Name, string ParameterType, string ParameterName, string Body, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2CanonicalPatternDecl(string Name, string Source, string Template, int GeneratedCount, IReadOnlyList<string> GeneratedIds, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<FirmamentV2PatternAssociation>? Associations = null);public sealed record FirmamentV2PatternAssociation(string GeneratedId, string SourceSet, string SourceEntry, string SourceValue, int ExpansionOrdinal, FirmamentV2SourceSpan Provenance);+public sealed record FirmamentV2MirrorDerivation(string Destination, string Kind, string Source, string AcrossPlane, string HandednessCorrection, IReadOnlyList<FirmamentV2MirrorMemberProvenance> Members, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<string> Provenance);+public sealed record FirmamentV2MirrorMemberProvenance(string DerivedIdentity, string SourceIdentity, string Transform, string SourceSpan);+public sealed record FirmamentV2RadialPatternDecl(string Name, string Source, string Axis, int Count, double AngleRadians, string Distribution, IReadOnlyList<FirmamentV2RadialInstance> Instances, FirmamentV2SourceSpan SourceSpan);+public sealed record FirmamentV2RadialInstance(string Identity, int InstanceIndex, double RotationAngleRadians, double CenterX, double CenterY, IReadOnlyList<string> Provenance);public sealed record FirmamentV2RequireDecl(string Name, string Expression, bool Value, FirmamentV2SourceSpan SourceSpan, string? Provenance = null, string? Subject = null, string? Expected = null, string? ToleranceSource = null);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>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.csindex 013c76ca..e406f72a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs@@ -307,7 +307,8 @@ public static class FirmamentV2ValidationReportBuildernew(code, IsFatal(code) ? "fatal" : "warning", Message(code));private static bool IsFatal(string code) =>- code.StartsWith("firmament-span-", StringComparison.Ordinal)+ code.StartsWith(SemanticSymmetryAuthoring.Prefix, StringComparison.Ordinal)+ || code.StartsWith("firmament-span-", StringComparison.Ordinal)|| code.StartsWith("firmament-feature-footprint-outside-span:", StringComparison.Ordinal)|| FirmamentV2Parser.IsFatalDiagnosticCode(code);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 5db70ce5..0c31a410 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -157,7 +157,9 @@ public static class ProfileAuthoringParser{var diagnostics = new List<string>();source = ExpandBuiltInPolygons(source, diagnostics);- var profile = FindProfiles(source).FirstOrDefault();+ var authoredProfiles = FindProfiles(source).ToArray();+ var extrudeProfile = Extrude.Match(source).Groups["p"].Value;+ var profile = authoredProfiles.FirstOrDefault(candidate => candidate.Name == extrudeProfile) ?? authoredProfiles.FirstOrDefault();if (profile is null)return (null, 0, ["profile-source-missing-profile"]);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.csindex d77405ce..425c5fee 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.cs@@ -28,6 +28,13 @@ public static class RevolveAuthoringParser{ArgumentNullException.ThrowIfNull(source);var diagnostics = new List<string>();+ var normalized = NormalizeSemanticSource(source, diagnostics);+ if (normalized is null)+ {+ reportedDiagnostics = diagnostics.Distinct(StringComparer.Ordinal).ToArray();+ return null;+ }+ source = normalized;var feature = Revolve.Match(source);if (!feature.Success) { reportedDiagnostics = [Prefix + "missing"]; return null; }var name = feature.Groups["name"].Value;@@ -94,6 +101,23 @@ public static class RevolveAuthoringParser: null;}+ private static string? NormalizeSemanticSource(string source, List<string> diagnostics)+ {+ // Revolve is inspected and validated through a dedicated CLI lane. Keep that lane+ // aligned with the production build ordering so semantic boundaries and Mirror are+ // resolved before the profile binder, just as they are for actual materialization.+ var boundaries = ClosedBoundary2Authoring.Expand(source, diagnostics);+ if (boundaries is null) return null;+ var features = FirmamentV2FeatureExpansion.Expand(boundaries.Source, diagnostics);+ if (features is null) return null;+ var templates = FirmamentV2TemplateExpansion.Expand(features.Source, diagnostics);+ if (templates is null) return null;+ var specializedBoundaries = ClosedBoundary2Authoring.Expand(templates.Source, diagnostics);+ if (specializedBoundaries is null) return null;+ var staticAuthoring = CanonicalStaticAuthoring.Expand(specializedBoundaries.Source, diagnostics);+ return staticAuthoring?.Source;+ }+private static string? Field(string body, string name){var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^;\r\n}}]+)", RegexOptions.CultureInvariant);@@ -108,7 +132,7 @@ public static class RevolveAuthoringParserreturn true;}- private static bool TryAngle(string text, out double radians, out string? alias)+ internal static bool TryAngle(string text, out double radians, out string? alias){radians = 0d; alias = null;var normalized = text.Trim().ToLowerInvariant();diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.csnew file mode 100644index 00000000..a9f766fb--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.cs@@ -0,0 +1,378 @@+using System.Globalization;+using System.Text;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>+/// Bounded authoring-time Mirror and radial Pattern expansion. Every admitted declaration+/// becomes ordinary Profile/Feature source before AIR and BRep materialization.+/// </summary>+internal static class SemanticSymmetryAuthoring+{+ internal const string Prefix = "firmament-symmetry-";+ private const double Tolerance = 1e-8;+ private const int MaxInstances = 1024;+ private static readonly Regex MirrorHeader = new(@"\bMirrored\s+(?<kind>Profile|Feature)\s+(?<destination>[A-Za-z_]\w*)\s+From\s+(?<source>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex UnsupportedMirrorHeader = new(@"\bMirrored\s+(?<kind>[A-Za-z_]\w*(?:\s*<[^>]+>)?)\s+(?<destination>[A-Za-z_]\w*)\s+From\s+(?<source>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex RadialHeader = new(@"\bRadial\s+Pattern\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex FeatureHeader = new(@"\b(?<kind>Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Boss|Pocket)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex AxisHeader = new(@"\bAxis\s+(?<name>[A-Za-z_]\w*)\s*\{\s*Origin\s*:\s*\[\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*,\s*(?<z>[-+.\deE]+)mm\s*\]\s*;?\s*Direction\s*:\s*\[\s*(?<dx>[-+.\deE]+)\s*,\s*(?<dy>[-+.\deE]+)\s*,\s*(?<dz>[-+.\deE]+)\s*\]", RegexOptions.CultureInvariant);+ private static readonly Regex PlaneHeader = new(@"\bPlane\s+(?<name>[A-Za-z_]\w*)\s*\{\s*Origin\s*:\s*\[\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*,\s*(?<z>[-+.\deE]+)mm\s*\]\s*;?\s*Normal\s*:\s*\[\s*(?<nx>[-+.\deE]+)\s*,\s*(?<ny>[-+.\deE]+)\s*,\s*(?<nz>[-+.\deE]+)\s*\](?:\s*;?\s*Up\s*:\s*\[[^]]+\])?", RegexOptions.CultureInvariant);++ internal sealed record Result(string Source, IReadOnlyList<FirmamentV2MirrorDerivation> Mirrors, IReadOnlyList<FirmamentV2RadialPatternDecl> RadialPatterns);++ public static Result? Expand(string source, List<string> diagnostics)+ {+ if (!Regex.IsMatch(source, @"\b(?:Mirrored\s+|Radial\s+Pattern\s+)", RegexOptions.CultureInvariant))+ return new(source, [], []);++ var mirrors = new List<FirmamentV2MirrorDerivation>();+ var radialPatterns = new List<FirmamentV2RadialPatternDecl>();++ foreach (Match unsupported in UnsupportedMirrorHeader.Matches(source))+ if (!MirrorHeader.Matches(source).Cast<Match>().Any(valid => valid.Index == unsupported.Index))+ diagnostics.Add(Prefix + "type-unsupported:" + unsupported.Groups["kind"].Value.Replace(" ", string.Empty, StringComparison.Ordinal));+ if (HasErrors(diagnostics)) return null;++ // Profiles are resolved from semantic guides and emitted again as semantic guides.+ // Removing all derivation declarations avoids recursive expansion in ResolveNamedProfile.+ var resolutionSource = RemoveDeclarations(source, MirrorHeader).Source;+ var mirrorChanges = new List<Change>();+ var mirrorPlaneRemovals = new Dictionary<int, Change>();+ foreach (Match declaration in MirrorHeader.Matches(source))+ {+ var open = source.IndexOf('{', declaration.Index);+ var close = Matching(source, open, '{', '}');+ if (close < 0) { diagnostics.Add(Prefix + "mirror-malformed:" + declaration.Groups["destination"].Value); continue; }+ var destination = declaration.Groups["destination"].Value;+ var sourceName = declaration.Groups["source"].Value;+ var kind = Regex.Replace(declaration.Groups["kind"].Value, @"\s+", string.Empty);+ if ((kind == "Profile" && Regex.IsMatch(resolutionSource, $@"\bProfile\s+{Regex.Escape(destination)}\b", RegexOptions.CultureInvariant))+ || (kind != "Profile" && FindFeature(resolutionSource, destination) is not null))+ { diagnostics.Add(Prefix + "identity-collision:" + destination); continue; }+ var acrossName = Field(source[(open + 1)..close], "Across");+ string? planeDiagnostic = null;+ SemanticSymmetryTransform.Plane? across = null;+ if (acrossName is null || !TryResolvePlane(resolutionSource, acrossName, out across, out planeDiagnostic))+ { diagnostics.Add(planeDiagnostic ?? Prefix + "plane-unresolved:" + destination); continue; }++ string? lowered;+ IReadOnlyList<FirmamentV2MirrorMemberProvenance> members;+ if (kind == "Profile")+ lowered = MirrorProfile(resolutionSource, destination, sourceName, across!, diagnostics, out members);+ else+ lowered = MirrorFeature(resolutionSource, destination, sourceName, across!, diagnostics, out members);+ if (lowered is null) continue;+ mirrorChanges.Add(new(declaration.Index, close - declaration.Index + 1, lowered));+ var directPlane = PlaneHeader.Matches(source).Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == acrossName);+ if (directPlane is not null)+ {+ var planeOpen = source.IndexOf('{', directPlane.Index); var planeClose = Matching(source, planeOpen, '{', '}');+ if (planeClose >= 0) mirrorPlaneRemovals[directPlane.Index] = new(directPlane.Index, planeClose - directPlane.Index + 1, string.Empty);+ }+ resolutionSource += Environment.NewLine + lowered;+ mirrors.Add(new(destination, kind, sourceName, acrossName, "CanonicalRightHanded", members,+ new(declaration.Index, close - declaration.Index + 1), [sourceName, $"Mirror({acrossName})", destination]));+ }+ if (HasErrors(diagnostics)) return null;+ source = Apply(source, mirrorChanges.Concat(mirrorPlaneRemovals.Values));++ // Immutable divergence is ordinary source cloning plus explicit field replacement.+ source = ExpandFeatureWith(source, mirrors, diagnostics);+ if (HasErrors(diagnostics)) return null;++ var radialChanges = new List<Change>();+ var radialSourceRemovals = new Dictionary<int, Change>();+ var radialAxisRemovals = new Dictionary<int, Change>();+ foreach (Match declaration in RadialHeader.Matches(source))+ {+ var open = source.IndexOf('{', declaration.Index); var close = Matching(source, open, '{', '}');+ var name = declaration.Groups["name"].Value;+ if (close < 0) { diagnostics.Add(Prefix + "radial-malformed:" + name); continue; }+ var body = source[(open + 1)..close];+ var sourceName = Field(body, "Source"); var axisName = Field(body, "About"); var countText = Field(body, "Count"); var angleText = Field(body, "Angle");+ if (sourceName is null || axisName is null || countText is null || angleText is null)+ { diagnostics.Add(Prefix + "radial-field-missing:" + name); continue; }+ if (!int.TryParse(countText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var count) || count < 1 || count > MaxInstances)+ { diagnostics.Add(Prefix + "radial-count-invalid:" + name + ":" + countText); continue; }+ if (!RevolveAuthoringParser.TryAngle(angleText, out var angle, out _))+ { diagnostics.Add(Prefix + "radial-angle-invalid:" + name + ":" + angleText); continue; }+ if (!TryResolveAxis(source, axisName, out var axis))+ { diagnostics.Add(Prefix + "radial-axis-invalid:" + name + ":" + axisName); continue; }+ var feature = FindFeature(source, sourceName);+ if (feature is null) { diagnostics.Add(Prefix + "radial-source-unsupported:" + name + ":" + sourceName); continue; }+ if (!TryPoint2(feature.Body, out var center)) { diagnostics.Add(Prefix + "feature-center-unsupported:" + sourceName); continue; }+ if (Math.Abs(Math.Abs(axis!.Direction.Z) - 1d) > Tolerance)+ { diagnostics.Add(Prefix + "radial-axis-not-profile-normal:" + name); continue; }+ if (Enumerable.Range(0, count).Any(index => FindFeature(source, name + "_Instance" + index.ToString(CultureInfo.InvariantCulture)) is not null))+ { diagnostics.Add(Prefix + "identity-collision:" + name); continue; }++ var denominator = NearlyFull(angle) ? count : Math.Max(1, count - 1);+ var instances = new List<FirmamentV2RadialInstance>(); var emitted = new List<string>();+ for (var index = 0; index < count; index++)+ {+ var theta = count == 1 ? 0d : angle * index / denominator;+ var rotated = SemanticSymmetryTransform.Rotate(new Point3D(center.X, center.Y, 0), axis, theta);+ var semanticId = name + ".Instance" + index.ToString(CultureInfo.InvariantCulture);+ var materialId = name + "_Instance" + index.ToString(CultureInfo.InvariantCulture);+ emitted.Add(CloneFeature(feature, materialId, (rotated.X, rotated.Y), semanticId));+ instances.Add(new(semanticId, index, theta, rotated.X, rotated.Y, [sourceName, $"Rotate({axisName},{theta:R})", semanticId]));+ }+ radialChanges.Add(new(declaration.Index, close - declaration.Index + 1, string.Join(Environment.NewLine, emitted)));+ radialSourceRemovals[feature.Start] = new(feature.Start, feature.Length, string.Empty);+ var axisDeclaration = AxisHeader.Matches(source).Cast<Match>().First(item => item.Groups["name"].Value == axisName);+ var axisOpen = source.IndexOf('{', axisDeclaration.Index); var axisClose = Matching(source, axisOpen, '{', '}');+ if (axisClose >= 0) radialAxisRemovals[axisDeclaration.Index] = new(axisDeclaration.Index, axisClose - axisDeclaration.Index + 1, string.Empty);+ radialPatterns.Add(new(name, sourceName, axisName, count, angle, NearlyFull(angle) ? "FullOpenEndpoint" : "PartialInclusiveEndpoints", instances,+ new(declaration.Index, close - declaration.Index + 1)));+ }+ if (HasErrors(diagnostics)) return null;+ source = Apply(source, radialChanges.Concat(radialSourceRemovals.Values).Concat(radialAxisRemovals.Values));+ return new(source, mirrors, radialPatterns);+ }++ private static string? MirrorProfile(string source, string destination, string sourceName, SemanticSymmetryTransform.Plane across,+ List<string> diagnostics, out IReadOnlyList<FirmamentV2MirrorMemberProvenance> memberEvidence)+ {+ memberEvidence = [];+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, sourceName, out var profileDiagnostics);+ if (profile is null)+ { diagnostics.AddRange(profileDiagnostics); diagnostics.Add(Prefix + "profile-source-invalid:" + sourceName); return null; }+ var frame = profile.EffectiveConstructionPlane;+ if (Math.Abs(across.Normal.ToVector().Dot(frame.AxisZ.ToVector())) > Tolerance)+ { diagnostics.Add(Prefix + "plane-not-profile-reflection-line:" + destination); return null; }+ var members = new List<FirmamentV2MirrorMemberProvenance>();+ var declarations = new StringBuilder(); var loopTexts = new List<string>();+ foreach (var loop in profile.Loops)+ {+ var transformed = loop.Segments.Select(segment => (segment, geometry: ReflectCurve(segment.Geometry, frame, across, diagnostics, destination))).ToArray();+ if (transformed.Any(item => item.geometry is null)) return null;+ // Reflection reverses winding. Reverse order and traversal to restore the source's+ // outer/inner canonical orientation while retaining each authored segment name.+ var canonical = transformed.Reverse().Select(item => (item.segment, geometry: Reverse(item.geometry!))).ToArray();+ var segmentTexts = new List<string>();+ foreach (var item in canonical)+ {+ var stem = destination + "_" + Safe(loop.Name) + "_" + Safe(item.segment.Name);+ if (item.geometry is LineArcFullCircle2D circle)+ {+ var centerName = stem + "_Center"; var guideName = stem + "_Guide";+ declarations.AppendLine($"Point2 {centerName} {{ Position: [{F(circle.Center.X)}mm, {F(circle.Center.Y)}mm] }}");+ declarations.AppendLine($"Circle2 {guideName} {{ Center: {centerName}; Radius: {F(circle.Radius)}mm }}");+ segmentTexts.Add(guideName + " |> TraceLoop");+ }+ else if (item.geometry is LineArcFullEllipse2D ellipse)+ {+ var centerName = stem + "_Center"; var guideName = stem + "_Guide";+ declarations.AppendLine($"Point2 {centerName} {{ Position: [{F(ellipse.Center.X)}mm, {F(ellipse.Center.Y)}mm] }}");+ declarations.AppendLine($"Ellipse2Guide {guideName} {{ Center: {centerName}; SemiAxes: [{F(ellipse.MajorRadius)}mm, {F(ellipse.MinorRadius)}mm]; Rotation: {F(ellipse.RotationRadians * 180d / Math.PI)}deg }}");+ segmentTexts.Add(guideName + " |> TraceLoop");+ }+ else+ {+ Endpoints(item.geometry, out var start, out var end);+ var from = stem + "_From"; var to = stem + "_To"; var guide = stem + "_Guide";+ declarations.AppendLine($"Point2 {from} {{ Position: [{F(start.X)}mm, {F(start.Y)}mm] }}");+ declarations.AppendLine($"Point2 {to} {{ Position: [{F(end.X)}mm, {F(end.Y)}mm] }}");+ if (item.geometry is LineArcLineSegment2D)+ declarations.AppendLine($"Line2 {guide} {{ From: {from}; To: {to} }}");+ else if (item.geometry is LineArcCircularArc2D arc)+ {+ var centerName = stem + "_Center";+ declarations.AppendLine($"Point2 {centerName} {{ Position: [{F(arc.Center.X)}mm, {F(arc.Center.Y)}mm] }}");+ declarations.AppendLine($"Circle2 {guide} {{ Center: {centerName}; Radius: {F(arc.Radius)}mm }}");+ }+ var sweep = item.geometry is LineArcCircularArc2D a ? (a.SweepAngleRadians > 0 ? "; Sweep: CounterClockwise" : "; Sweep: Clockwise") : string.Empty;+ segmentTexts.Add($"Segment {Safe(item.segment.Name)} {{ Trace: {guide}; From: {from}; To: {to}{sweep} }}");+ }+ members.Add(new(destination + "." + item.segment.Name, sourceName + "." + item.segment.Name, "Mirror", item.segment.Provenance.SourceSpan));+ }+ loopTexts.Add($"Loop {Safe(loop.Name)} {{ {string.Join(Environment.NewLine, segmentTexts)} }}");+ }+ memberEvidence = members;+ return declarations + $"Profile {destination}" + (profile.PlaneFrame == "XY" ? string.Empty : " Using " + profile.PlaneFrame) + " {\n" + string.Join(Environment.NewLine, loopTexts) + "\n}";+ }++ private static string? MirrorFeature(string source, string destination, string sourceName, SemanticSymmetryTransform.Plane across,+ List<string> diagnostics, out IReadOnlyList<FirmamentV2MirrorMemberProvenance> members)+ {+ members = [];+ var feature = FindFeature(source, sourceName);+ if (feature is null) { diagnostics.Add(Prefix + "feature-source-invalid:" + sourceName); return null; }+ if (!TryPoint2(feature.Body, out var center)) { diagnostics.Add(Prefix + "feature-center-unsupported:" + sourceName); return null; }+ var reflected = SemanticSymmetryTransform.Reflect(new Point3D(center.X, center.Y, 0), across);+ if (Math.Abs(reflected.Z) > Tolerance) { diagnostics.Add(Prefix + "feature-plane-mismatch:" + destination); return null; }+ if (Math.Abs(reflected.X - center.X) <= Tolerance && Math.Abs(reflected.Y - center.Y) <= Tolerance)+ { diagnostics.Add(Prefix + "redundant-feature-mirror:" + destination); return null; }+ members = [new(destination + ".Center", sourceName + ".Center", "Mirror", $"offset:{feature.Start}")];+ return CloneFeature(feature, destination, (reflected.X, reflected.Y), destination);+ }++ private static string ExpandFeatureWith(string source, List<FirmamentV2MirrorDerivation> mirrors, List<string> diagnostics)+ {+ var changes = new List<Change>();+ foreach (Match declaration in Regex.Matches(source, @"\bFeature\s+(?<destination>[A-Za-z_]\w*)\s*=\s*(?<source>[A-Za-z_]\w*)\s+with\s*\{", RegexOptions.CultureInvariant))+ {+ var open = source.IndexOf('{', declaration.Index); var close = Matching(source, open, '{', '}');+ if (close < 0) { diagnostics.Add(Prefix + "with-malformed:" + declaration.Groups["destination"].Value); continue; }+ var feature = FindFeature(source, declaration.Groups["source"].Value);+ if (feature is null) { diagnostics.Add(Prefix + "with-source-invalid:" + declaration.Groups["source"].Value); continue; }+ var body = feature.Body;+ foreach (Match field in Regex.Matches(source[(open + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>[^;\r\n}]+)", RegexOptions.CultureInvariant))+ {+ var replacement = new Regex($@"\b{Regex.Escape(field.Groups["name"].Value)}\s*:\s*[^;\r\n}}]+", RegexOptions.CultureInvariant);+ if (!replacement.IsMatch(body)) { diagnostics.Add(Prefix + "with-field-unknown:" + declaration.Groups["destination"].Value + ":" + field.Groups["name"].Value); continue; }+ body = replacement.Replace(body, field.Groups["name"].Value + ": " + field.Groups["value"].Value.Trim(), 1);+ }+ var destination = declaration.Groups["destination"].Value;+ var lowered = feature.Kind + " " + destination + " {" + body + "}";+ changes.Add(new(declaration.Index, close - declaration.Index + 1, lowered));+ changes.Add(new(feature.Start, feature.Length, string.Empty));+ var origin = mirrors.FirstOrDefault(item => item.Destination == declaration.Groups["source"].Value);+ if (origin is not null) mirrors.Add(origin with { Destination = destination, Kind = "FeatureWith", Provenance = origin.Provenance.Concat([$"with({destination})"]).ToArray() });+ }+ return Apply(source, changes);+ }++ private static LineArcProfileCurve2D? ReflectCurve(LineArcProfileCurve2D curve, ConstructionPlane frame, SemanticSymmetryTransform.Plane across, List<string> diagnostics, string destination)+ {+ (double X, double Y) P((double X, double Y) point)+ {+ var local = frame.ToLocal(SemanticSymmetryTransform.Reflect(frame.ToWorld(point), across));+ if (Math.Abs(local.Z) > Tolerance) diagnostics.Add(Prefix + "profile-plane-mismatch:" + destination);+ return (local.X, local.Y);+ }+ return curve switch+ {+ LineArcLineSegment2D line => new LineArcLineSegment2D(P(line.Start), P(line.End)),+ LineArcCircularArc2D arc => ReflectArc(arc, P),+ LineArcFullCircle2D circle => new LineArcFullCircle2D(P(circle.Center), circle.Radius),+ LineArcFullEllipse2D ellipse => ReflectEllipse(ellipse, P),+ _ => Unsupported()+ };+ LineArcProfileCurve2D? Unsupported() { diagnostics.Add(Prefix + "profile-curve-unsupported:" + destination + ":" + curve.GetType().Name); return null; }+ }++ private static LineArcCircularArc2D ReflectArc(LineArcCircularArc2D arc, Func<(double X, double Y), (double X, double Y)> reflect)+ {+ var center = reflect(arc.Center); var start = reflect((arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)));+ return new(center, arc.Radius, Math.Atan2(start.Y - center.Y, start.X - center.X), -arc.SweepAngleRadians);+ }++ private static LineArcFullEllipse2D ReflectEllipse(LineArcFullEllipse2D ellipse, Func<(double X, double Y), (double X, double Y)> reflect)+ {+ var center = reflect(ellipse.Center);+ var major = reflect((ellipse.Center.X + Math.Cos(ellipse.RotationRadians), ellipse.Center.Y + Math.Sin(ellipse.RotationRadians)));+ return new(center, ellipse.MajorRadius, ellipse.MinorRadius, Math.Atan2(major.Y - center.Y, major.X - center.X));+ }++ private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start),+ LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians, -arc.SweepAngleRadians),+ _ => curve+ };++ private static bool TryResolvePlane(string source, string reference, out SemanticSymmetryTransform.Plane? plane, out string? diagnostic)+ {+ plane = null; diagnostic = null; var conceptReference = reference;+ var direct = PlaneHeader.Matches(source).Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == reference);+ if (direct is not null && Numbers(direct, ["x", "y", "z", "nx", "ny", "nz"], out var values)+ && Direction3D.TryCreate(new(values[3], values[4], values[5]), out var directNormal))+ {+ plane = new(new(values[0], values[1], values[2]), directNormal);+ return true;+ }+ var construction = Regex.Matches(source, @"\bConstruction\s+Plane\s+(?<name>[A-Za-z_]\w*)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)", RegexOptions.CultureInvariant)+ .Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == reference);+ if (construction is not null) conceptReference = construction.Groups["trace"].Value;+ if (!ConceptIrResolver.TryResolvePlane(source, conceptReference, out var resolved, out diagnostic) || resolved is null)+ { diagnostic = Prefix + "plane-invalid:" + reference + ":" + (diagnostic ?? "unresolved"); return false; }+ if (!Direction3D.TryCreate(new(resolved.Normal.X, resolved.Normal.Y, resolved.Normal.Z), out var normal))+ { diagnostic = Prefix + "plane-invalid:" + reference + ":normal"; return false; }+ plane = new(new(resolved.Origin.X, resolved.Origin.Y, resolved.Origin.Z), normal); return true;+ }++ private static bool TryResolveAxis(string source, string name, out SemanticSymmetryTransform.Axis? axis)+ {+ axis = null;+ var match = AxisHeader.Matches(source).Cast<Match>().FirstOrDefault(item => item.Groups["name"].Value == name);+ if (match is null || !Numbers(match, ["x", "y", "z", "dx", "dy", "dz"], out var v) || !Direction3D.TryCreate(new(v[3], v[4], v[5]), out var direction)) return false;+ axis = new(new(v[0], v[1], v[2]), direction); return true;+ }++ private static FeatureBlock? FindFeature(string source, string name)+ {+ foreach (Match header in FeatureHeader.Matches(source))+ {+ if (header.Groups["name"].Value != name) continue;+ var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');+ if (close >= 0) return new(header.Groups["kind"].Value, name, source[(open + 1)..close], header.Index, close - header.Index + 1);+ }+ return null;+ }++ private static string CloneFeature(FeatureBlock feature, string name, (double X, double Y) center, string semanticId)+ {+ var body = Regex.Replace(feature.Body, @"\bCenter\s*:\s*Point2\(\s*[-+0-9.eE]+mm\s*,\s*[-+0-9.eE]+mm\s*\)", $"Center: Point2({F(center.X)}mm, {F(center.Y)}mm)", RegexOptions.CultureInvariant);+ return feature.Kind + " " + name + " {" + body + Environment.NewLine + "}";+ }++ private static bool TryPoint2(string body, out (double X, double Y) center)+ {+ center = default; var match = Regex.Match(body, @"\bCenter\s*:\s*Point2\(\s*(?<x>[-+0-9.eE]+)mm\s*,\s*(?<y>[-+0-9.eE]+)mm\s*\)", RegexOptions.CultureInvariant);+ return match.Success && double.TryParse(match.Groups["x"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out center.X) && double.TryParse(match.Groups["y"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out center.Y);+ }++ private static bool Numbers(Match match, string[] groups, out double[] values)+ {+ values = new double[groups.Length];+ for (var i = 0; i < groups.Length; i++) if (!double.TryParse(match.Groups[groups[i]].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]) || !double.IsFinite(values[i])) return false;+ return true;+ }++ private static string? Field(string body, string name)+ {+ var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^;\s}}]+)", RegexOptions.CultureInvariant);+ return match.Success ? match.Groups["value"].Value.Trim() : null;+ }++ private static (string Source, IReadOnlyList<Change> Changes) RemoveDeclarations(string source, Regex header)+ {+ var changes = new List<Change>();+ foreach (Match match in header.Matches(source)) { var open = source.IndexOf('{', match.Index); var close = Matching(source, open, '{', '}'); if (close >= 0) changes.Add(new(match.Index, close - match.Index + 1, string.Empty)); }+ return (Apply(source, changes), changes);+ }++ private static string Apply(string source, IEnumerable<Change> changes)+ {+ foreach (var change in changes.GroupBy(item => (item.Start, item.Length)).Select(group => group.Last()).OrderByDescending(item => item.Start))+ source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);+ return source;+ }++ private static int Matching(string source, int open, char opening, char closing)+ {+ if (open < 0) return -1; var depth = 0;+ for (var i = open; i < source.Length; i++) { if (source[i] == opening) depth++; else if (source[i] == closing && --depth == 0) return i; }+ return -1;+ }++ private static void Endpoints(LineArcProfileCurve2D curve, out (double X, double Y) start, out (double X, double Y) end)+ {+ if (curve is LineArcLineSegment2D line) { start = line.Start; end = line.End; return; }+ var arc = (LineArcCircularArc2D)curve;+ start = (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians));+ end = (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians));+ }++ private static bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(item => item.StartsWith(Prefix, StringComparison.Ordinal));+ private static bool NearlyFull(double angle) => Math.Abs(Math.Abs(angle) - 2d * Math.PI) <= Tolerance;+ private static string Safe(string value) => Regex.Replace(value, @"[^A-Za-z0-9_]", "_");+ private static string F(double value) => (Math.Abs(value) < 1e-12 ? 0d : value).ToString("R", CultureInfo.InvariantCulture);+ private sealed record Change(int Start, int Length, string Text);+ private sealed record FeatureBlock(string Kind, string Name, string Body, int Start, int Length);+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryTransform.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryTransform.csnew file mode 100644index 00000000..b90c4584--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryTransform.cs@@ -0,0 +1,68 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>+/// Exact semantic rigid transforms used before AIR/BRep materialization. Reflection is+/// deliberately absent from BodyState and BRep APIs: safe CAD transforms authoring values.+/// </summary>+public static class SemanticSymmetryTransform+{+ public sealed record Plane(Point3D Origin, Direction3D Normal);+ public sealed record Axis(Point3D Origin, Direction3D Direction);+ public sealed record Frame(Point3D Origin, Direction3D X, Direction3D Y, Direction3D Z)+ {+ public double Determinant => X.ToVector().Cross(Y.ToVector()).Dot(Z.ToVector());+ }++ public static Point3D Reflect(Point3D point, Plane across)+ {+ var n = across.Normal.ToVector();+ return point - n * (2d * (point - across.Origin).Dot(n));+ }++ public static Vector3D Reflect(Vector3D vector, Plane across)+ {+ var n = across.Normal.ToVector();+ return vector - n * (2d * vector.Dot(n));+ }++ public static Axis Reflect(Axis axis, Plane across) =>+ new(Reflect(axis.Origin, across), Direction3D.Create(Reflect(axis.Direction.ToVector(), across)));++ public static Plane Reflect(Plane plane, Plane across) =>+ new(Reflect(plane.Origin, across), Direction3D.Create(Reflect(plane.Normal.ToVector(), across)));++ public static Frame Reflect(Frame frame, Plane across)+ {+ // Reflecting all three basis vectors has determinant -1. Preserve reflected X/Z+ // semantics, then reconstruct Y through the existing right-handed cross-product law.+ var x = Direction3D.Create(Reflect(frame.X.ToVector(), across));+ var z = Direction3D.Create(Reflect(frame.Z.ToVector(), across));+ var y = Direction3D.Create(z.ToVector().Cross(x.ToVector()));+ x = Direction3D.Create(y.ToVector().Cross(z.ToVector()));+ return new(Reflect(frame.Origin, across), x, y, z);+ }++ public static Point3D Rotate(Point3D point, Axis about, double radians) =>+ about.Origin + Rotate(point - about.Origin, about.Direction, radians);++ public static Vector3D Rotate(Vector3D vector, Axis about, double radians) =>+ Rotate(vector, about.Direction, radians);++ public static Frame Rotate(Frame frame, Axis about, double radians)+ {+ var x = Direction3D.Create(Rotate(frame.X.ToVector(), about.Direction, radians));+ var z = Direction3D.Create(Rotate(frame.Z.ToVector(), about.Direction, radians));+ var y = Direction3D.Create(z.ToVector().Cross(x.ToVector()));+ return new(Rotate(frame.Origin, about, radians), x, y, z);+ }++ private static Vector3D Rotate(Vector3D vector, Direction3D direction, double radians)+ {+ var axis = direction.ToVector();+ var c = Math.Cos(radians);+ var s = Math.Sin(radians);+ return vector * c + axis.Cross(vector) * s + axis * (axis.Dot(vector) * (1d - c));+ }+}diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 1d8df618..d2885e1d 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -131,6 +131,43 @@ Inside a Set, `Name => Value` is a named association. Inside Pattern, `value =>Choose among the closed data forms by meaning: a `Record` is one structured value; an `Enum` is one-of-N alternatives; `T[]` is anonymous ordered data; `Set<T>` is a dataset in which all N named entries exist simultaneously. Pattern performs finite construction mapping, Feature supplies a reusable semantic transformation, and `|>` composes finite compatible geometry. Match is unchanged.+## Mirror and radial symmetry++Mirror and radial Pattern are resolved before geometry materialization. They transform semantic construction intent, not finished BRep topology.++An explicitly named destination derives from an existing Profile or concrete feature and an existing Plane:++```firmament+Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+Hole<Shaft> LeftMount { On: +Z; Center: Point2(24mm,0mm); Diameter: 6mm; End: ThroughAll }+Mirrored Feature RightMount From LeftMount { Across: CenterPlane }+```++Profiles may use either that direct Plane spelling or a `Construction Plane` traced from a `Concept Struct` Plane. Reflection analytically transforms points and curves, reverses arc traversal, then restores the Profile's canonical outer/inner winding. Frames use reflected origin/X/Z followed by canonical right-handed Y reconstruction; negative-determinant frames never reach a consumer. Mirroring an already-materialized STEP/BRep is not safe authoring and is not provided by this syntax.++Keep the source Profile semantic too. For example, an arbitrary triangular source should be authored as `Triangle2<Explicit> LeftBoundary { A: [...] B: [...] C: [...] }` and consumed with `LeftBoundary |> TraceLoop`; an axis-aligned four-sided section should use `Rect2`. Use `Polygon2<Explicit>` only when the linear boundary is genuinely an otherwise-unconstrained polygon. Closed boundaries lower to ordinary named Profile guides before Mirror resolves them.++A radial feature Pattern uses an existing Axis and includes the source construction as instance zero:++```firmament+Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }+Hole<Shaft> BoltSeed { On: +Z; Center: Point2(26mm,0mm); Diameter: 6mm; End: ThroughAll }+Radial Pattern BoltCircle { Source: BoltSeed About: MainAxis Count: 6 Angle: full }+```++`Count` is in `1..1024`; one is a valid trivial Pattern. `full` uses `theta[i] = i * 2*pi/Count` and omits the full-angle duplicate endpoint. Partial angles use inclusive endpoints, `theta[i] = i * Angle/(Count-1)`. Angles reuse Revolve spellings (`radians`, `deg`, `quarter`, `half`, `full`). Current radial feature lowering is deliberately bounded to planar Point2-centered Hole semantics about the support-normal Axis. Profile radial Pattern, whole Model/Struct derivation, arbitrary selector rebinding, Boss/Pocket radial derivation, and assembly occurrence symmetry remain explicit future qualifications.++Intentional asymmetry uses immutable `with`, not a mirror-exception mini-language:++```firmament+Mirrored Feature RightMount From LeftMount { Across: CenterPlane }+Feature RightMountCustom = RightMount with { Diameter: 8mm }+```++The derived feature retains the source/mirror/override provenance chain in `inspect --json`. Material, scalar magnitudes, and enum tags are invariant values; meaningless declarations such as `Mirrored Material` fail typed.++A Profile exactly on its reflection line may be retained as an equivalent named semantic derivation because it has not yet created material. A concrete feature whose center is unchanged is rejected as `firmament-symmetry-redundant-feature-mirror` so a Compose/Modify cannot silently create coincident duplicate material.+### Built-in closed polygons`Polygon2<Rhombus>` is the first bounded closed-polygon authoring form. A rhombus is specified by its center and full horizontal/vertical diagonal lengths:diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 9d922269..8db8010b 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -50,6 +50,7 @@| Language Concept constraint | Supported | explicit `type T satisfies Concept`; distinct from an ordinary value parameter || `Require` | Supported | finite specialization-time boolean admissibility; no runtime scripting || Static arrays, Tables, Pattern | Bounded | finite checked data and admitted feature expansion; no query language |+| Semantic Mirror and radial Pattern | Bounded | authoring-time Profile and planar feature reflection; full/partial radial Hole/feature replication; right-handed frame correction and retained provenance; no post-BRep reflection, generic affine transform, whole-Model, or assembly occurrence symmetry || Materials | Bounded by consuming domain | semantic identity can flow through existing Firmament/Forge paths; no SQLite or catalog queries in Templates || Sheet Metal product families | Supported | five embedded public families and Forge Protocol v1 exposure || Nested Templates | Bounded | acyclic concrete specialization only; Templates are not values |diff --git a/docs/release/GEOM-SYMMETRY-X1.md b/docs/release/GEOM-SYMMETRY-X1.mdnew file mode 100644index 00000000..4ea52f36--- /dev/null+++ b/docs/release/GEOM-SYMMETRY-X1.md@@ -0,0 +1,53 @@+# GEOM-SYMMETRY-X1 — semantic Mirror and radial Pattern++## Executive verdict++**Accepted for the bounded Profile and planar feature lanes documented below.** Firmament can express reflection and rotational symmetry as authoring-time derivations, retain explicit destination and instance identity, restore right-handed frames, and lower the results through ordinary Profile, Hole, Revolve, BRep, and STEP authorities. No finished BRep is reflected or semantically reconstructed.++## Audit and authority++The existing finite Pattern authority is `CanonicalStaticAuthoring`: it expands typed Static arrays or named Sets in source order, retains Pattern/instance associations, enforces a 1,024-instance bound, and erases the collection before material AIR. Profile/Path source resolves to `ResolvedProfile2D`; `ConstructionPlane.TryTrace` already reconstructs orthonormal right-handed frames. Feature functions expand before Template/static specialization. Assembly occurrences already own rigid positive-determinant placements but do not admit reflected occurrence transforms.++Existing kernel `CirMirror` names are analysis mirrors, not geometry reflection. `BodyState` rebuilds semantic construction plus typed operations and has no safe reflection authority. No unsafe post-BRep reflection was found or added. X1 therefore adds one bounded semantic expander at the existing static boundary: source Profile/feature plus Plane/Axis becomes ordinary semantic declarations, then the unchanged material pipeline runs.++## Transform matrix++| Semantic type | Mirror | Radial rotation | Notes |+| --- | --- | --- | --- |+| Point | Yes | Yes | analytic point transform, including translation term |+| Vector | Yes | Yes | direction only; no point translation |+| Axis | Yes | Yes | origin/direction normalized by `Direction3D` |+| Plane | Yes | Yes | origin/normal transformed analytically |+| DatumFrame | Yes | Yes | typed transform API; reflection reconstructs right-handed basis |+| Profile | Yes | Deferred | line, circular arc, circle, and ellipse carriers; canonical winding restored |+| Span | Deferred | Deferred | no copied helper curve or ambiguous selector rebinding admitted |+| Feature | Bounded | Bounded | concrete Point2-centered Hole qualified end-to-end; Boss/Pocket deferred |+| Model / Struct | Deferred | Deferred | no arbitrary record walk or second authoring IR |+| Assembly occurrence | Deferred | Deferred | current occurrence matrices require proper rigid transforms; no negative determinant placement |++## Handedness++For a source frame `(X,Y,Z)`, naively reflecting all axes produces `det(RX,RY,RZ) = -1`. X1 preserves reflected X and Z, reconstructs `Y' = Z' x X'`, then recomputes X through the same orthonormal law. Tests prove the result determinant is `+1`, unit and orthogonal axes are retained, and reflecting twice across the same Plane recovers the original frame. Profile reflection similarly reverses each curve and loop order after geometric reflection so outer/inner material orientation remains canonical. Circular arcs retain the mirrored locus, endpoints, radius, and corrected traversal.++## Identity, provenance, and `with`++Authors name mirror destinations; no English left/right renaming exists. CLI inspection reports `kind`, source, Plane, destination, handedness correction, member source identities, and the derivation chain. `Feature RightCustom = Right with { ... }` performs checked immutable field replacement after Mirror; inspection retains source → Mirror → local override provenance. There is no `MirrorExcept`, `SymmetryBreak`, or override sublanguage.++Radial Pattern generates `Pattern.Instance0` through `Pattern.InstanceN-1` in stable ordinal order. Instance zero is the zero-angle source construction. Full distribution uses `[0,2*pi)`; partial distribution includes both endpoints. The six-hole flagship reports angles `0, 60, 120, 180, 240, 300` degrees and one radius. Count one is valid; count zero is rejected.++## Qualified evidence++- `mirrored-profile.firmament`: a `Triangle2<Explicit>` source boundary lowers to the reflected asymmetric Profile, which extrudes to an enclosed five-face manifold with bounds X `[-16,-4]`, Y `[-6,8]`, Z `[0,8]` after STEP reimport.+- `mirrored-hole.firmament`: two independent semantic Hole features materialize at X `+24/-24`; STEP reimport reports two cylindrical faces and an enclosed manifold.+- `mirrored-feature-with-override.firmament`: left diameter 6 mm and mirror-derived overridden right diameter 8 mm materialize without special exception syntax.+- `radial-bolt-circle.firmament`: six independent Hole features at radius 26 mm; STEP reimport reports six cylinders, 12 faces, and an enclosed manifold.+- `partial-radial-pattern.firmament`: five holes over `half` use inclusive 45-degree spacing and reimport as five cylinders.+- `mirrored-revolve.firmament`: an axis-aligned `Rect2` source boundary lowers to the mirrored Profile, feeds the ordinary Revolve plan, and reimports as an enclosed six-face analytic manifold.++Repeated radial builds are byte-identical (`E499406CD574F360412A0C5C095838116BDB73CF350F9EDD6FFD7A730B6C7F32`). A fresh self-contained packaged CLI produced the same radial hash and the same mirrored-profile hash as the repository CLI (`9F9D2E2244AFE7ADB66E853D97137BCB89DFAD4597FB589F2E5C861DEA2DF5D8`). `inspect --json` exposes the retained mirror and radial transformation records; build output exposes the independent ordinary materialized features.++Release validation passed with a zero-warning Release solution build, 1,448 Firmament tests, 435 CLI tests, all six Symmetry canonical fixture actions, all seven invalid-fixture CLI checks, STEP export/reimport, deterministic repeat, packaged parity, documentation/link/layout tests included in the CLI suite, and `git diff --check`. The repository-wide canonical script still exits nonzero after every fixture action passes because its pre-existing content-policy guard rejects `Assembly/annular-pair.firmament` for legacy explicit assembly placement; this milestone does not alter that unrelated fixture.++## Explicit boundaries++X1 does not add Scale, affine matrices, user transform expressions, post-topology duplication, broad PMI transformation, FEA-result transformation, Thread/helix handedness rules, Sculpt reflection, whole-Model traversal, or assembly occurrence patterns. Profile radial repetition and Span/selector structural rebinding are deferred rather than implemented with copied geometry or nearest-face lookup. ENGINE-X0 could later simplify paired head/seat and bank feature authoring, but its working assembly demo is not rewritten in this milestone.diff --git a/fixtures/Canonical/Symmetry/mirrored-feature-with-override.firmament b/fixtures/Canonical/Symmetry/mirrored-feature-with-override.firmamentnew file mode 100644index 00000000..2107cbcd--- /dev/null+++ b/fixtures/Canonical/Symmetry/mirrored-feature-with-override.firmament@@ -0,0 +1,11 @@+schema Mechanical+Model MirroredFeatureWithOverride {+ Units: mm+ Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ Box Plate { Size: [90mm, 44mm, 8mm] }+ Modify Plate {+ Hole<Shaft> LeftMount { On: +Z; Center: Point2(26mm, 0mm); Diameter: 6mm; End: ThroughAll }+ Mirrored Feature RightMount From LeftMount { Across: CenterPlane }+ Feature RightMountCustom = RightMount with { Diameter: 8mm }+ }+}diff --git a/fixtures/Canonical/Symmetry/mirrored-hole.firmament b/fixtures/Canonical/Symmetry/mirrored-hole.firmamentnew file mode 100644index 00000000..31672a81--- /dev/null+++ b/fixtures/Canonical/Symmetry/mirrored-hole.firmament@@ -0,0 +1,10 @@+schema Mechanical+Model MirroredMountingHoles {+ Units: mm+ Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ Box Plate { Size: [80mm, 40mm, 8mm] }+ Modify Plate {+ Hole<Shaft> LeftMount { On: +Z Center: Point2(24mm, 0mm) Diameter: 6mm End: ThroughAll }+ Mirrored Feature RightMount From LeftMount { Across: CenterPlane }+ }+}diff --git a/fixtures/Canonical/Symmetry/mirrored-profile.firmament b/fixtures/Canonical/Symmetry/mirrored-profile.firmamentnew file mode 100644index 00000000..5ed6fcae--- /dev/null+++ b/fixtures/Canonical/Symmetry/mirrored-profile.firmament@@ -0,0 +1,19 @@+schema Mechanical+Model MirroredProfileExtrusion {+ Units: mm+ Concept Struct Supports {+ Center: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ }+ Construction Plane CenterPlane { Trace: Supports.Center }++ Triangle2<Explicit> LeftBoundary {+ A: [4mm, -6mm]+ B: [16mm, -6mm]+ C: [12mm, 8mm]+ }+ Profile LeftProfile {+ Loop Outer { LeftBoundary |> TraceLoop }+ }+ Mirrored Profile RightProfile From LeftProfile { Across: CenterPlane }+ Struct Body { Extrude RightPrism { Profile: RightProfile; From: 0mm; To: 8mm } }+}diff --git a/fixtures/Canonical/Symmetry/mirrored-revolve.firmament b/fixtures/Canonical/Symmetry/mirrored-revolve.firmamentnew file mode 100644index 00000000..be14a68f--- /dev/null+++ b/fixtures/Canonical/Symmetry/mirrored-revolve.firmament@@ -0,0 +1,10 @@+schema Mechanical+Model MirroredRevolve {+ Units: mm+ Plane MidPlane { Origin: [0mm,0mm,0mm]; Normal: [0,1,0]; Up: [0,0,1] }+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,1,0] }+ Rect2 LowerBoundary { Center: [9mm, -14mm] Size: [6mm, 12mm] }+ Profile LowerSection { Loop Outer { LowerBoundary |> TraceLoop } }+ Mirrored Profile UpperSection From LowerSection { Across: MidPlane }+ Revolve UpperRing { Profile: UpperSection; About: MainAxis; Angle: half }+}diff --git a/fixtures/Canonical/Symmetry/partial-radial-pattern.firmament b/fixtures/Canonical/Symmetry/partial-radial-pattern.firmamentnew file mode 100644index 00000000..bb36f29a--- /dev/null+++ b/fixtures/Canonical/Symmetry/partial-radial-pattern.firmament@@ -0,0 +1,10 @@+schema Mechanical+Model PartialRadialPattern {+ Units: mm+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }+ Box Plate { Size: [80mm, 80mm, 8mm] }+ Modify Plate {+ Hole<Shaft> HoleSeed { On: +Z Center: Point2(24mm, 0mm) Diameter: 4mm End: ThroughAll }+ Radial Pattern HalfArc { Source: HoleSeed About: MainAxis Count: 5 Angle: half }+ }+}diff --git a/fixtures/Canonical/Symmetry/radial-bolt-circle.firmament b/fixtures/Canonical/Symmetry/radial-bolt-circle.firmamentnew file mode 100644index 00000000..5c279683--- /dev/null+++ b/fixtures/Canonical/Symmetry/radial-bolt-circle.firmament@@ -0,0 +1,10 @@+schema Mechanical+Model RadialBoltCircle {+ Units: mm+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }+ Box Flange { Size: [80mm, 80mm, 8mm] }+ Modify Flange {+ Hole<Shaft> BoltSeed { On: +Z Center: Point2(26mm, 0mm) Diameter: 6mm End: ThroughAll }+ Radial Pattern BoltCircle { Source: BoltSeed About: MainAxis Count: 6 Angle: full }+ }+}diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex 374869f5..e42b1bf4 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -33,6 +33,7 @@{ "path": "Span", "operation": "build-step" },{ "path": "Boundary2", "operation": "build-step" },{ "path": "Revolve", "operation": "build-step" },+ { "path": "Symmetry", "operation": "build-step" },{ "path": "PMI", "operation": "build-step" },{ "path": "Templates", "operation": "build-step" },{ "path": "Integration", "operation": "build-step" }diff --git a/fixtures/Invalid/Symmetry/count-zero.firmament b/fixtures/Invalid/Symmetry/count-zero.firmamentnew file mode 100644index 00000000..66b8224f--- /dev/null+++ b/fixtures/Invalid/Symmetry/count-zero.firmament@@ -0,0 +1,6 @@+Model InvalidRadialCount {+ Units: mm+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }+ Hole<Shaft> Seed { On: +Z Center: Point2(10mm, 0mm) Diameter: 4mm End: ThroughAll }+ Radial Pattern Invalid { Source: Seed About: MainAxis Count: 0 Angle: full }+}diff --git a/fixtures/Invalid/Symmetry/identity-collision.firmament b/fixtures/Invalid/Symmetry/identity-collision.firmamentnew file mode 100644index 00000000..d0cf03ba--- /dev/null+++ b/fixtures/Invalid/Symmetry/identity-collision.firmament@@ -0,0 +1,7 @@+Model InvalidMirrorIdentity {+ Units: mm+ Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ Hole<Shaft> Left { On: +Z; Center: Point2(10mm,0mm); Diameter: 4mm; End: ThroughAll }+ Hole<Shaft> Right { On: +Z; Center: Point2(-10mm,0mm); Diameter: 4mm; End: ThroughAll }+ Mirrored Feature Right From Left { Across: CenterPlane }+}diff --git a/fixtures/Invalid/Symmetry/invalid-angle.firmament b/fixtures/Invalid/Symmetry/invalid-angle.firmamentnew file mode 100644index 00000000..69052766--- /dev/null+++ b/fixtures/Invalid/Symmetry/invalid-angle.firmament@@ -0,0 +1,6 @@+Model InvalidRadialAngle {+ Units: mm+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }+ Hole<Shaft> Seed { On: +Z; Center: Point2(10mm,0mm); Diameter: 4mm; End: ThroughAll }+ Radial Pattern Invalid { Source: Seed About: MainAxis Count: 4 Angle: around }+}diff --git a/fixtures/Invalid/Symmetry/invalid-axis.firmament b/fixtures/Invalid/Symmetry/invalid-axis.firmamentnew file mode 100644index 00000000..5ee69dba--- /dev/null+++ b/fixtures/Invalid/Symmetry/invalid-axis.firmament@@ -0,0 +1,6 @@+Model InvalidRadialAxis {+ Units: mm+ Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,0] }+ Hole<Shaft> Seed { On: +Z; Center: Point2(10mm,0mm); Diameter: 4mm; End: ThroughAll }+ Radial Pattern Invalid { Source: Seed About: MainAxis Count: 4 Angle: full }+}diff --git a/fixtures/Invalid/Symmetry/invalid-plane.firmament b/fixtures/Invalid/Symmetry/invalid-plane.firmamentnew file mode 100644index 00000000..93cee73f--- /dev/null+++ b/fixtures/Invalid/Symmetry/invalid-plane.firmament@@ -0,0 +1,6 @@+Model InvalidMirrorPlane {+ Units: mm+ Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [0,0,0]; Up: [0,0,1] }+ Hole<Shaft> Left { On: +Z; Center: Point2(10mm,0mm); Diameter: 4mm; End: ThroughAll }+ Mirrored Feature Right From Left { Across: CenterPlane }+}diff --git a/fixtures/Invalid/Symmetry/unsupported-mirror-type.firmament b/fixtures/Invalid/Symmetry/unsupported-mirror-type.firmamentnew file mode 100644index 00000000..a0e5964d--- /dev/null+++ b/fixtures/Invalid/Symmetry/unsupported-mirror-type.firmament@@ -0,0 +1,4 @@+Model InvalidMirrorType {+ Units: mm+ Mirrored Material RightMaterial From LeftMaterial { Across: CenterPlane }+}diff --git a/fixtures/Invalid/Symmetry/unsupported-selector.firmament b/fixtures/Invalid/Symmetry/unsupported-selector.firmamentnew file mode 100644index 00000000..6e374efb--- /dev/null+++ b/fixtures/Invalid/Symmetry/unsupported-selector.firmament@@ -0,0 +1,6 @@+Model InvalidMirrorSelector {+ Units: mm+ Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ Hole<Shaft> Left { On: +Z; Center: Mounts.Left; Diameter: 4mm; End: ThroughAll }+ Mirrored Feature Right From Left { Across: CenterPlane }+}