Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add semantic profile support for concept path features

Yuechen Li82adcf5cbad1
diff --git a/Aetheris.Kernel.Firmament.Tests/SemanticProfileM1Tests.cs b/Aetheris.Kernel.Firmament.Tests/SemanticProfileM1Tests.cs
new file mode 100644
index 00000000..5813780f
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/SemanticProfileM1Tests.cs
@@ -0,0 +1,181 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Semantics;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class SemanticProfileM1Tests
+{
+ [Fact]
+ public void Mir_LowersNamedMembersOneToManyWithStableProvenanceAndHash()
+ {
+ var ir = new SemanticProfileIr("Edge", "profile:Edge", "XY", new(0, 0), 0,
+ [
+ new SemanticProfileSpanIr("Lead", "profile:Edge.Lead", 10, null, null, null, "source:1"),
+ new SemanticProfileChamferIr("EndChamfer", "profile:Edge.EndChamfer", 3, 2, 1, "source:2"),
+ new SemanticProfileStepIr("LowerStep", "profile:Edge.LowerStep", 5, 2, -1, "source:3"),
+ new SemanticProfileNotchIr("CableNotch", "profile:Edge.CableNotch", 4, 1.5, 1, "source:4"),
+ new SemanticProfileCutbackIr("AttachmentCutback", "profile:Edge.AttachmentCutback", 3, 1, -1, "source:5"),
+ new SemanticProfileTabIr("MountTab", "profile:Edge.MountTab", 8, 3, -1, "source:6"),
+ new SemanticProfileArcTransitionIr("ReturnArc", "profile:Edge.ReturnArc", 2, 90, "source:7")
+ ], [], [new("DatumA", "profile:Edge.DatumA", new(0, 0), "authored")], "test");
+
+ var first = SemanticProfileMirResolver.Resolve(ir);
+ var second = SemanticProfileMirResolver.Resolve(ir);
+
+ Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics));
+ Assert.Equal(first.Profile!.DeterministicHash, second.Profile!.DeterministicHash);
+ Assert.Equal(3, first.Profile.Members.Single(member => member.Name == "MountTab").CurveDescendants.Count);
+ Assert.Equal(2, first.Profile.Members.Single(member => member.Name == "LowerStep").CurveDescendants.Count);
+ Assert.Equal(3, first.Profile.Members.Single(member => member.Name == "CableNotch").CurveDescendants.Count);
+ Assert.All(first.Profile.Members.SelectMany(member => member.CurveDescendants), curve => Assert.StartsWith("lowered-from:profile:Edge.", curve.Provenance, StringComparison.Ordinal));
+ Assert.Equal(first.Profile.Members.Sum(member => member.CurveDescendants.Count), first.Profile.ExactCurveChain.Count);
+ }
+
+ [Fact]
+ public void Mir_ConstraintDiagnosticsNameSemanticMembers()
+ {
+ var ir = new SemanticProfileIr("MirroredTabs", "profile:MirroredTabs", "XY", new(0, 0), 0,
+ [
+ new SemanticProfileTabIr("LeftTab", "profile:MirroredTabs.LeftTab", 10, 4, 1, "source:left"),
+ new SemanticProfileTabIr("RightTab", "profile:MirroredTabs.RightTab", 11.2, 4, -1, "source:right")
+ ], [new("TabMirror", "profile:MirroredTabs.TabMirror", "Mirror", ["LeftTab", "RightTab"], "authored")], [], "test");
+
+ var result = SemanticProfileMirResolver.Resolve(ir);
+
+ Assert.False(result.IsSuccess);
+ Assert.Contains("semantic-profile-mirror-mismatch:profile:MirroredTabs.TabMirror:LeftTab,RightTab", result.Diagnostics);
+ }
+
+ [Fact]
+ public void Mir_ExplicitlyLowersToPlanarContourAuthority()
+ {
+ var ir = new SemanticProfileIr("Rectangle", "profile:Rectangle", "XY", new(0, 0), 0,
+ [
+ new SemanticProfileSpanIr("Bottom", "profile:Rectangle.Bottom", 20, null, null, null, "source:1"),
+ new SemanticProfileSpanIr("Right", "profile:Rectangle.Right", 10, 90, null, null, "source:2"),
+ new SemanticProfileSpanIr("Top", "profile:Rectangle.Top", 20, 90, null, null, "source:3"),
+ new SemanticProfileCloseIr("Left", "profile:Rectangle.Left", "source:4")
+ ], [], [], "test");
+ var resolved = SemanticProfileMirResolver.Resolve(ir).Profile!;
+
+ var contour = resolved.LowerToPlanarContour2();
+
+ Assert.True(PlanarContourKernel.Validate(contour).IsValid);
+ Assert.Equal(["profile:Rectangle.Bottom", "profile:Rectangle.Right", "profile:Rectangle.Top", "profile:Rectangle.Left"],
+ contour.OuterLoop.Segments.Select(segment => segment.Provenance.ConceptStableId));
+ }
+
+ [Fact]
+ public void FirmamentSemanticMembers_LowerThroughNormalProfileExtrusionPath()
+ {
+ var parsed = ProfileAuthoringParser.Parse(MountingPlate);
+
+ var profile = Assert.IsType<ResolvedProfile2D>(parsed.Profile);
+ Assert.Empty(parsed.Diagnostics);
+ Assert.Equal(8, profile.Loops.Single().Segments.Count);
+ Assert.Equal(3, profile.Loops.Single().Segments.Count(segment => segment.Provenance.ConceptStableId == "concept-path:Outline.MountTab"));
+ Assert.All(profile.Loops.Single().Segments.Where(segment => segment.Provenance.ConceptStableId == "concept-path:Outline.MountTab"),
+ segment => Assert.Equal("SemanticProfileMIR:Tab", segment.Provenance.Derivation));
+ Assert.True(ResolvedProfile2DValidator.Validate(profile).IsValid);
+ Assert.Equal(LineArcProfileExtrudeStatus.Succeeded, ResolvedProfile2DValidator.Extrude(profile, parsed.Height).Status);
+ }
+
+ [Fact]
+ public void SemanticValue_PathAddressesProfileMemberAndExactDescendants()
+ {
+ var root = Assert.Single(FirmamentSemanticValues.FromProfilesAndConceptPaths(MountingPlate));
+ Assert.Equal("Plate", root.ExposedName);
+ Assert.Equal("SemanticProfile", root.Type.Name);
+ var reference = new SemanticReference(root, [], new("test", 0, 1));
+ Assert.True(SemanticValueValidator.TryResolveMember(reference, new("MountTab", new("test", 1, 8)), out var tab, out var tabDiagnostic), tabDiagnostic?.Message);
+ Assert.Equal("Tab", tab!.Value.Type.Name);
+ Assert.True(SemanticValueValidator.TryResolveMember(tab, new("Curve02", new("test", 9, 7)), out var curve, out var curveDiagnostic), curveDiagnostic?.Message);
+ Assert.Equal("ExactProfileCurve", curve!.Value.Type.Name);
+ Assert.True(SemanticValueValidator.TryResolveMember(tab, new("End", new("test", 16, 3)), out var end, out var endDiagnostic), endDiagnostic?.Message);
+ Assert.Equal("Point2", end!.Value.Type.Name);
+ }
+
+ [Fact]
+ public void UserDefinedGenericTemplate_ProducesAddressableSemanticProfile()
+ {
+ const string source = """
+ Model TemplateSemanticProfile {
+ Units: mm
+ Record PlateSpec { TabWidth: Length TabExtension: Length Thickness: Length }
+ Static Spec: PlateSpec = PlateSpec { TabWidth: 12mm TabExtension: 8mm Thickness: 3mm }
+ Template < P: PlateSpec >
+ Struct MountingPlateTemplate {
+ Concept Path Outline {
+ Start: Point2(0mm, 0mm)
+ Heading: 0deg
+ Span BottomLeft { Length: 44mm }
+ Tab MountTab { Width: P.TabWidth; Extension: P.TabExtension; Side: Right }
+ Span BottomRight { Length: 44mm }
+ Span Right { Turn: 90deg; Length: 60mm }
+ Span Top { Turn: 90deg; Length: 100mm }
+ Close Left
+ }
+ Profile Plate From Outline
+ Extrude Solid { Profile: Plate; From: 0mm; To: P.Thickness }
+ }
+ Struct Product = MountingPlateTemplate < P: Spec >
+ }
+ """;
+
+ var diagnostics = new List<string>();
+ var values = FirmamentSemanticValues.FromProfilesAndConceptPaths(source, reportedDiagnostics: diagnostics);
+
+ Assert.Empty(diagnostics);
+ var profile = Assert.Single(values);
+ Assert.Equal("Plate", profile.ExposedName);
+ Assert.Equal("Tab", profile.ExposedMembers["MountTab"].Type.Name);
+ Assert.Equal(3, profile.ExposedMembers["MountTab"].ExposedMembers.Count(member => member.Key.StartsWith("Curve", StringComparison.Ordinal)));
+ Assert.Contains(profile.Provenance, item => item.Stage == "template-specialization");
+ }
+
+ [Fact]
+ public void RectangleAndCircle_ExposeCanonicalSemanticMembers()
+ {
+ const string source = """
+ Point2 Origin { Position: Point2(0mm, 0mm) }
+ Rect2 PlateProfile { Center: [0mm, 0mm]; Size: [100mm, 60mm] }
+ Circle2 Vent { Center: Origin; Radius: 5mm }
+ """;
+ var values = FirmamentSemanticValues.FromProfilesAndConceptPaths(source);
+ var rectangle = values.Single(value => value.ExposedName == "PlateProfile");
+ var circle = values.Single(value => value.ExposedName == "Vent");
+
+ Assert.Equal("Span", rectangle.ExposedMembers["Right"].Type.Name);
+ Assert.Equal("Point2", rectangle.ExposedMembers["TopRight"].Type.Name);
+ Assert.Equal("Point2", circle.ExposedMembers["Center"].Type.Name);
+ Assert.Equal("Length", circle.ExposedMembers["Radius"].Type.Name);
+ }
+
+ [Theory]
+ [InlineData("Tab Bad { Width: 0mm; Extension: 2mm; Side: Right }", "semantic-profile-invalid-tab:concept-path:Outline.Bad")]
+ [InlineData("Step Bad { Run: 2mm; Rise: -1mm; Side: Left }", "semantic-profile-invalid-step:concept-path:Outline.Bad")]
+ [InlineData("Cutback Bad { Run: 2mm; Offset: 1mm }", "semantic-profile-invalid-cutback:concept-path:Outline.Bad")]
+ public void InvalidSemanticFeatures_NameTheSemanticPath(string feature, string expected)
+ {
+ var source = $"Concept Path Outline {{ Start: Point2(0mm, 0mm) Heading: 0deg {feature} }}\nProfile Plate From Outline\nExtrude Solid {{ Profile: Plate; From: 0mm; To: 1mm }}";
+ var result = ProfileAuthoringParser.Parse(source);
+ Assert.Null(result.Profile);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.StartsWith(expected, StringComparison.Ordinal));
+ }
+
+ private const string MountingPlate = """
+ Concept Path Outline {
+ Start: Point2(0mm, 0mm)
+ Heading: 0deg
+ Span BottomLeft { Length: 44mm }
+ Tab MountTab { Width: 12mm; Extension: 8mm; Side: Right }
+ Span BottomRight { Length: 44mm }
+ Span Right { Turn: 90deg; Length: 60mm }
+ Span Top { Turn: 90deg; Length: 100mm }
+ Close Left
+ }
+ Profile Plate From Outline
+ Extrude Solid { Profile: Plate; From: 0mm; To: 3mm }
+ """;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPathAst.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPathAst.cs
index c786949d..b48ad320 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPathAst.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPathAst.cs
@@ -24,6 +24,6 @@ public sealed record ConceptPathInspection(
IReadOnlyList<ConceptPathExposedMemberInspection>? ExposedMembers = null,
IReadOnlyList<ConceptPathConsumerInspection>? Consumers = null,
string? Provenance = null);
-public sealed record ConceptPathEntryInspection(string Name, string Kind, double StartX, double StartY, double EndX, double EndY, double HeadingDegrees, double? Radius, double? SweepDegrees, string GuideId, string EndpointId);
+public sealed record ConceptPathEntryInspection(string Name, string Kind, double StartX, double StartY, double EndX, double EndY, double HeadingDegrees, double? Radius, double? SweepDegrees, string GuideId, string EndpointId, int CurveCount = 1, string? SemanticKind = null);
public sealed record ConceptPathExposedMemberInspection(string Name, string Kind, string Capability, string StableId);
public sealed record ConceptPathConsumerInspection(string Kind, string Name, string RequiredCapability, string Provenance);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs
index e2046be6..8a81b03b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs
@@ -71,8 +71,12 @@ public static class FirmamentSemanticValues
var stepMatch = Regex.Match(expanded, $@"\b(?:Line|Arc|Close)\s+{Regex.Escape(entry.Name)}\b", RegexOptions.CultureInvariant);
var stepSpan = new SemanticSourceSpan(sourceIdentity, stepMatch.Success ? stepMatch.Index : span.Start, stepMatch.Success ? DeclarationLength(expanded, stepMatch.Index) : span.Length);
var memberAuthoredSpan = expansion is null ? stepSpan : authoredSpan;
- var end = new SemanticValue(entry.EndpointId, new("Point2"), provenance: [new("concept-path-segment", entry.Name, "validated endpoint", memberAuthoredSpan)], authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: "End");
- members.Add(new SemanticValue(entry.GuideId, new(entry.Kind + "2"), exposedMembers: [end], provenance: [new("concept-path-segment", entry.Name, "validated ordered planar guide", memberAuthoredSpan)], authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: entry.Name));
+ var end = new SemanticValue(entry.EndpointId, new("Point2"), provenance: [new("semantic-profile-member", entry.Name, "derived endpoint", memberAuthoredSpan)], authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: "End");
+ var descendants = Enumerable.Range(0, entry.CurveCount).Select(ordinal => new SemanticValue(
+ $"{entry.GuideId}.curve{ordinal:D2}", new("ExactProfileCurve"),
+ provenance: [new("semantic-profile-lowering", entry.Name, $"exact curve descendant {ordinal}", memberAuthoredSpan)],
+ authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: $"Curve{ordinal:D2}")).ToArray();
+ members.Add(new SemanticValue(entry.GuideId, new(entry.SemanticKind ?? entry.Kind), exposedMembers: [end, .. descendants], provenance: [new("semantic-profile-member", entry.Name, $"{entry.CurveCount} exact curve descendant(s)", memberAuthoredSpan)], authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: entry.Name));
}
var capabilities = new List<ISemanticCapability>();
var bindings = new List<SemanticBinding>();
@@ -84,8 +88,11 @@ public static class FirmamentSemanticValues
var provenance = new List<SemanticProvenance> { new("authored", inspection.Name, "Concept Path", authoredSpan) };
if (expansion is not null)
provenance.AddRange(expansion.Instantiations.Select(item => new SemanticProvenance("template-specialization", item.SpecializationIdentity, "expanded before semantic normalization", new(sourceIdentity, item.ApplicationSourceSpan.Start, item.ApplicationSourceSpan.Length))));
- values.Add(new SemanticValue(inspection.Provenance ?? "concept-path:" + inspection.Name, new("ConceptPath"), capabilities, bindings, members, provenance, authoredSpan, expansion is null ? null : span));
+ var exposedProfileNames = inspection.Consumers?.Where(consumer => consumer.Kind == "Profile").Select(consumer => consumer.Name).Distinct(StringComparer.Ordinal).ToArray() ?? [];
+ var exposedProfileName = exposedProfileNames.Length == 1 ? exposedProfileNames[0] : null;
+ values.Add(new SemanticValue(inspection.Provenance ?? "concept-path:" + inspection.Name, new(bindings.Count > 0 ? "SemanticProfile" : "ConceptPath"), capabilities, bindings, members, provenance, authoredSpan, expansion is null ? null : span, exposedName: exposedProfileName ?? inspection.Name));
}
+ values.AddRange(CanonicalPrimitiveSemanticValues(expanded, sourceIdentity));
return values;
}
@@ -166,4 +173,29 @@ public static class FirmamentSemanticValues
}
return 0;
}
+
+ private static IEnumerable<SemanticValue> CanonicalPrimitiveSemanticValues(string source, string sourceIdentity)
+ {
+ foreach (Match match in Regex.Matches(source, @"\bRect2\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var name = match.Groups["name"].Value;
+ var span = new SemanticSourceSpan(sourceIdentity, match.Index, DeclarationLength(source, match.Index));
+ SemanticValue Member(string member, string type) => new($"profile-primitive:{name}.{member}", new(type), provenance: [new("canonical-profile-semantics", name, member, span)], authoredSourceSpan: span, exposedName: member);
+ yield return new SemanticValue($"profile-primitive:{name}", new("RectangleProfile"), exposedMembers:
+ [
+ Member("Left", "Span"), Member("Right", "Span"), Member("Top", "Span"), Member("Bottom", "Span"), Member("Center", "Point2"),
+ Member("TopLeft", "Point2"), Member("TopRight", "Point2"), Member("BottomLeft", "Point2"), Member("BottomRight", "Point2")
+ ], provenance: [new("canonical-profile-semantics", name, "Rectangle members", span)], authoredSourceSpan: span, exposedName: name);
+ }
+ foreach (Match match in Regex.Matches(source, @"\bCircle2\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var name = match.Groups["name"].Value;
+ var span = new SemanticSourceSpan(sourceIdentity, match.Index, DeclarationLength(source, match.Index));
+ yield return new SemanticValue($"profile-primitive:{name}", new("CircleProfile"), exposedMembers:
+ [
+ new($"profile-primitive:{name}.Center", new("Point2"), provenance: [new("canonical-profile-semantics", name, "Center", span)], authoredSourceSpan: span, exposedName: "Center"),
+ new($"profile-primitive:{name}.Radius", new("Length"), provenance: [new("canonical-profile-semantics", name, "Radius", span)], authoredSourceSpan: span, exposedName: "Radius")
+ ], provenance: [new("canonical-profile-semantics", name, "Circle members", span)], authoredSourceSpan: span, exposedName: name);
+ }
+ }
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index a918e110..cc41c0b9 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -48,7 +48,7 @@ public static class ProfileAuthoringParser
};
exposed.AddRange(path.Steps.SelectMany(step => new[]
{
- new ConceptPathExposedMemberInspection(step.Name, step.Geometry is LineArcCircularArc2D ? "Arc2" : "Line2", "ProfileGuide", step.GuideName),
+ new ConceptPathExposedMemberInspection(step.Name, step.Kind, "ProfileGuide", step.GuideName),
new ConceptPathExposedMemberInspection(step.Name + ".End", "Point2", "ProfileEndpoint", step.EndpointName)
}));
var consumers = pathProfiles.Select(profile => new ConceptPathConsumerInspection("Profile", profile.Name, "ProfileSource", profile.SourceSpan))
@@ -56,8 +56,8 @@ public static class ProfileAuthoringParser
.ToArray();
return new ConceptPathInspection(
path.Name, path.Start.X, path.Start.Y, path.InitialHeading,
- path.Steps.Select(step => new ConceptPathEntryInspection(step.Name, step.Geometry is LineArcCircularArc2D ? "Arc" : "Line", step.Start.X, step.Start.Y, step.End.X, step.End.Y, step.Heading,
- step.Geometry is LineArcCircularArc2D arc ? arc.Radius : null, step.Geometry is LineArcCircularArc2D arc2 ? arc2.SweepAngleRadians * 180d / Math.PI : null, step.GuideName, step.EndpointName)).ToArray(),
+ path.Steps.Select(step => new ConceptPathEntryInspection(step.Name, step.Curves.Count == 1 && step.Curves[0] is LineArcCircularArc2D ? "Arc" : step.Curves.All(curve => curve is LineArcLineSegment2D) ? "LineChain" : "CurveChain", step.Start.X, step.Start.Y, step.End.X, step.End.Y, step.Heading,
+ step.Curves.Count == 1 && step.Curves[0] is LineArcCircularArc2D arc ? arc.Radius : null, step.Curves.Count == 1 && step.Curves[0] is LineArcCircularArc2D arc2 ? arc2.SweepAngleRadians * 180d / Math.PI : null, step.GuideName, step.EndpointName, step.Curves.Count, step.Kind)).ToArray(),
capabilities, exposed, consumers, $"concept-path:{path.Name}");
}).ToArray();
}
@@ -171,27 +171,28 @@ public static class ProfileAuthoringParser
var guideName = $"{name}.{step.Name}";
var endpointName = $"{guideName}.End";
if (guides.ContainsKey(guideName) || points.ContainsKey(endpointName)) { diagnostics.Add($"concept-path-name-collision:{guideName}"); continue; }
- if (!TryBindStep(name, step, current, ref heading, path.Start, points, out var geometry, out var endpoint, out var diagnostic)) { diagnostics.Add(diagnostic!); continue; }
- guides[guideName] = geometry!; points[endpointName] = endpoint; path.Steps.Add(new BoundPathStep(step.Name, guideName, endpointName, geometry!, current, endpoint, heading)); current = endpoint;
+ if (!TryBindStep(name, step, current, ref heading, path.Start, points, out var curves, out var endpoint, out var diagnostic)) { diagnostics.Add(diagnostic!); continue; }
+ if (curves!.Count == 1) guides[guideName] = curves[0];
+ points[endpointName] = endpoint; path.Steps.Add(new BoundPathStep(step.Name, step.Kind == "Line" ? "Span" : step.Kind == "Arc" ? "ArcTransition" : step.Kind, guideName, endpointName, curves, current, endpoint, heading)); current = endpoint;
}
result[name] = path;
}
return result;
}
- private static bool TryBindStep(string path, PathStep step, (double X, double Y) current, ref double headingDegrees, (double X, double Y) start, IReadOnlyDictionary<string, (double X, double Y)> points, out LineArcProfileCurve2D? geometry, out (double X, double Y) endpoint, out string? diagnostic)
+ private static bool TryBindStep(string path, PathStep step, (double X, double Y) current, ref double headingDegrees, (double X, double Y) start, IReadOnlyDictionary<string, (double X, double Y)> points, out IReadOnlyList<LineArcProfileCurve2D>? curves, out (double X, double Y) endpoint, out string? diagnostic)
{
- geometry = null; endpoint = default; diagnostic = null;
+ curves = null; endpoint = default; diagnostic = null;
var prefix = $"concept-path-{step.Kind.ToLowerInvariant()}-invalid:{path}:{step.Name}";
if (step.Kind == "Close")
{
endpoint = start;
if (Distance(current, endpoint) <= Tolerance) { diagnostic = $"concept-path-zero-length:{path}:{step.Name}"; return false; }
- geometry = new LineArcLineSegment2D(current, endpoint); headingDegrees = Heading(current, endpoint); return true;
+ curves = [new LineArcLineSegment2D(current, endpoint)]; headingDegrees = Heading(current, endpoint); return true;
}
var body = step.Body;
var turn = Property(body, "Turn"); var absolute = Property(body, "Heading"); var length = Property(body, "Length"); var to = Property(body, "To");
- if (step.Kind == "Line")
+ if (step.Kind is "Line" or "Span")
{
if (turn is not null && absolute is not null) { diagnostic = $"concept-path-turn-and-heading:{path}:{step.Name}"; return false; }
if (to is not null && (length is not null || turn is not null || absolute is not null)) { diagnostic = $"concept-path-to-mixed-direction-or-length:{path}:{step.Name}"; return false; }
@@ -200,12 +201,17 @@ public static class ProfileAuthoringParser
var targetName = string.Equals(to, "Start", StringComparison.Ordinal) ? $"{path}.Start" : to;
if (!points.TryGetValue(targetName, out endpoint)) { diagnostic = $"concept-path-unknown-target:{path}:{step.Name}:{to}"; return false; }
if (Distance(current, endpoint) <= Tolerance) { diagnostic = $"concept-path-zero-length:{path}:{step.Name}"; return false; }
- geometry = new LineArcLineSegment2D(current, endpoint); headingDegrees = Heading(current, endpoint); return true;
+ curves = [new LineArcLineSegment2D(current, endpoint)]; headingDegrees = Heading(current, endpoint); return true;
}
if (length is null || !TryMeasure(length, "mm", out var distance) || distance <= 0) { diagnostic = $"concept-path-length-invalid:{path}:{step.Name}"; return false; }
if (turn is not null) { if (!TryMeasure(turn, "deg", out var degrees) || !double.IsFinite(degrees)) { diagnostic = prefix; return false; } headingDegrees += degrees; }
else if (absolute is not null) { if (!TryMeasure(absolute, "deg", out var degrees) || !double.IsFinite(degrees)) { diagnostic = prefix; return false; } headingDegrees = degrees; }
- endpoint = Advance(current, headingDegrees, distance); geometry = new LineArcLineSegment2D(current, endpoint); return true;
+ endpoint = Advance(current, headingDegrees, distance); curves = [new LineArcLineSegment2D(current, endpoint)]; return true;
+ }
+ if (step.Kind is "Chamfer" or "Cutback" or "Step" or "Notch" or "Tab")
+ {
+ if (!TrySemanticFeature(path, step, current, headingDegrees, out curves, out endpoint, out diagnostic)) return false;
+ return true;
}
var radiusText = Property(body, "Radius");
if (step.Kind != "Arc" || radiusText is null || turn is null || absolute is not null || length is not null || to is not null || !TryMeasure(radiusText, "mm", out var radius) || radius <= 0 || !TryMeasure(turn, "deg", out var sweepDegrees) || !double.IsFinite(sweepDegrees) || Math.Abs(sweepDegrees) <= Tolerance || Math.Abs(sweepDegrees) >= 360d - Tolerance)
@@ -213,12 +219,71 @@ public static class ProfileAuthoringParser
var headingRadians = DegreesToRadians(headingDegrees); var sweepRadians = DegreesToRadians(sweepDegrees); var sign = Math.Sign(sweepRadians);
(double X, double Y) center = (current.X - sign * radius * Math.Sin(headingRadians), current.Y + sign * radius * Math.Cos(headingRadians));
var startAngle = Math.Atan2(current.Y - center.Y, current.X - center.X);
- geometry = new LineArcCircularArc2D(center, radius, startAngle, sweepRadians);
+ curves = [new LineArcCircularArc2D(center, radius, startAngle, sweepRadians)];
endpoint = (center.Item1 + radius * Math.Cos(startAngle + sweepRadians), center.Item2 + radius * Math.Sin(startAngle + sweepRadians));
headingDegrees += sweepDegrees;
return true;
}
+ private static bool TrySemanticFeature(string path, PathStep step, (double X, double Y) current, double headingDegrees, out IReadOnlyList<LineArcProfileCurve2D>? curves, out (double X, double Y) endpoint, out string? diagnostic)
+ {
+ curves = null; endpoint = default; diagnostic = null;
+ var stableId = $"concept-path:{path}.{step.Name}";
+ var sideText = Property(step.Body, "Side");
+ var side = string.Equals(sideText, "Left", StringComparison.OrdinalIgnoreCase) ? 1
+ : string.Equals(sideText, "Right", StringComparison.OrdinalIgnoreCase) ? -1 : 0;
+ bool Measure(string name, out double value)
+ {
+ value = default;
+ var text = Property(step.Body, name);
+ return text is not null && TryMeasure(text, "mm", out value);
+ }
+
+ SemanticProfileMemberIr? member = null;
+ if (step.Kind is "Chamfer" or "Cutback")
+ {
+ if (!Measure("Run", out var run) || !Measure("Offset", out var offset))
+ { diagnostic = $"semantic-profile-invalid-{step.Kind.ToLowerInvariant()}:{stableId}:Run and Offset are required"; return false; }
+ member = step.Kind == "Chamfer"
+ ? new SemanticProfileChamferIr(step.Name, stableId, run, offset, side, $"offset:{step.Index}")
+ : new SemanticProfileCutbackIr(step.Name, stableId, run, offset, side, $"offset:{step.Index}");
+ }
+ else if (step.Kind == "Step")
+ {
+ if (!Measure("Run", out var run) || !Measure("Rise", out var rise))
+ { diagnostic = $"semantic-profile-invalid-step:{stableId}:Run and Rise are required"; return false; }
+ member = new SemanticProfileStepIr(step.Name, stableId, run, rise, side, $"offset:{step.Index}");
+ }
+ else if (step.Kind == "Notch")
+ {
+ if (!Measure("Width", out var width) || !Measure("Depth", out var depth))
+ { diagnostic = $"semantic-profile-invalid-notch:{stableId}:Width and Depth are required"; return false; }
+ member = new SemanticProfileNotchIr(step.Name, stableId, width, depth, side, $"offset:{step.Index}");
+ }
+ else if (step.Kind == "Tab")
+ {
+ if (!Measure("Width", out var width) || !Measure("Extension", out var extension))
+ { diagnostic = $"semantic-profile-invalid-tab:{stableId}:Width and Extension are required"; return false; }
+ member = new SemanticProfileTabIr(step.Name, stableId, width, extension, side, $"offset:{step.Index}");
+ }
+
+ var ir = new SemanticProfileIr(path, "concept-path:" + path, "XY", new(current.X, current.Y), headingDegrees,
+ [member!], [], [], "Firmament Concept Path semantic member");
+ var resolution = SemanticProfileMirResolver.Resolve(ir);
+ if (!resolution.IsSuccess)
+ {
+ diagnostic = resolution.Diagnostics.FirstOrDefault() ?? $"semantic-profile-member-unresolved:{stableId}";
+ return false;
+ }
+ var resolved = AssertSingle(resolution.Profile!.Members);
+ curves = resolved.CurveDescendants.Select(descendant => descendant.Geometry).ToArray();
+ endpoint = (resolved.End.X, resolved.End.Y);
+ return true;
+
+ static ResolvedSemanticProfileMemberIr AssertSingle(IReadOnlyList<ResolvedSemanticProfileMemberIr> members) =>
+ members.Count == 1 ? members[0] : throw new InvalidOperationException("A bounded semantic feature must resolve to exactly one semantic member.");
+ }
+
private static IReadOnlyList<ResolvedProfileLoop2D> BindProfileLoops(ProfileBlock profile, IReadOnlyDictionary<string, BoundPath> paths, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
{
var loops = new List<ResolvedProfileLoop2D>();
@@ -262,7 +327,10 @@ public static class ProfileAuthoringParser
private static void AddPathLoop(string loopName, bool outer, string pathName, ProfileBlock profile, IReadOnlyDictionary<string, BoundPath> paths, List<ResolvedProfileLoop2D> loops, List<string> diagnostics)
{
if (!paths.TryGetValue(pathName, out var path)) { diagnostics.Add($"profile-path-missing:{profile.Name}:{pathName}"); return; }
- loops.Add(new ResolvedProfileLoop2D(loopName, outer, path.Steps.Select(step => SegmentResult(profile, loopName, outer ? step.Name : $"{loopName}.{step.Name}", step.Geometry, $"concept-path:{pathName}.{step.Name}", "ConceptPath")).ToArray()));
+ loops.Add(new ResolvedProfileLoop2D(loopName, outer, path.Steps.SelectMany(step => step.Curves.Select((curve, ordinal) => SegmentResult(
+ profile, loopName,
+ outer ? (step.Curves.Count == 1 ? step.Name : $"{step.Name}.curve{ordinal:D2}") : $"{loopName}.{step.Name}.curve{ordinal:D2}",
+ curve, $"concept-path:{pathName}.{step.Name}", $"SemanticProfileMIR:{step.Kind}"))).ToArray()));
}
private static ResolvedProfileSegment2D SegmentResult(ProfileBlock profile, string loop, string name, LineArcProfileCurve2D geometry, string conceptId, string derivation) => new(name, geometry, new($"profile:{profile.Name}.{loop}.{name}", conceptId, profile.SourceSpan, derivation, profile.Frame ?? "XY"));
@@ -316,7 +384,7 @@ public static class ProfileAuthoringParser
private static IEnumerable<PathStep> FindPathSteps(string body)
{
var entries = new List<PathStep>();
- foreach (var block in FindBlocks(body, @"\b(?<kind>Line|Arc)\s+(?<name>[A-Za-z_]\w*)\s*\{")) entries.Add(new(block.Match.Groups["kind"].Value, block.Match.Groups["name"].Value, block.Body, block.Match.Index));
+ foreach (var block in FindBlocks(body, @"\b(?<kind>Line|Span|Arc|Chamfer|Step|Notch|Cutback|Tab)\s+(?<name>[A-Za-z_]\w*)\s*\{")) entries.Add(new(block.Match.Groups["kind"].Value, block.Match.Groups["name"].Value, block.Body, block.Match.Index));
foreach (Match match in Regex.Matches(body, @"\bClose\s+(?<name>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant)) entries.Add(new("Close", match.Groups["name"].Value, string.Empty, match.Index));
return entries.OrderBy(x => x.Index);
}
@@ -334,6 +402,6 @@ public static class ProfileAuthoringParser
private sealed record Block(Match Match, string Body);
private sealed record ProfileBlock(string Name, string? Frame, string? FromPath, string? Body, string SourceSpan);
private sealed record PathStep(string Kind, string Name, string Body, int Index);
- private sealed record BoundPathStep(string Name, string GuideName, string EndpointName, LineArcProfileCurve2D Geometry, (double X, double Y) Start, (double X, double Y) End, double Heading);
+ private sealed record BoundPathStep(string Name, string Kind, string GuideName, string EndpointName, IReadOnlyList<LineArcProfileCurve2D> Curves, (double X, double Y) Start, (double X, double Y) End, double Heading);
private sealed record BoundPath(string Name, (double X, double Y) Start, double InitialHeading, List<BoundPathStep> Steps);
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticProfileIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticProfileIr.cs
new file mode 100644
index 00000000..d74c8363
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticProfileIr.cs
@@ -0,0 +1,252 @@
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// Semantic profile authority above exact curve segmentation. Members are stable engineering
+/// identities; their generated curve descendants are deliberately allowed to be one-to-many.
+/// This is a bounded resolver, not a general geometric constraint solver.
+/// </summary>
+public sealed record SemanticProfileIr(
+ string Name,
+ string StableId,
+ string LocalFrame,
+ SemanticProfilePoint Start,
+ double InitialHeadingDegrees,
+ IReadOnlyList<SemanticProfileMemberIr> Members,
+ IReadOnlyList<SemanticProfileConstraintIr> Constraints,
+ IReadOnlyList<SemanticProfileDatumIr> Datums,
+ string Provenance);
+
+public readonly record struct SemanticProfilePoint(double X, double Y);
+public sealed record SemanticProfileDatumIr(string Name, string StableId, SemanticProfilePoint Point, string Provenance);
+public sealed record SemanticProfileConstraintIr(string Name, string StableId, string Kind, IReadOnlyList<string> Members, string Provenance);
+
+public abstract record SemanticProfileMemberIr(string Name, string StableId, string Kind, string SourceSpan);
+public sealed record SemanticProfileSpanIr(string Name, string StableId, double Length, double? TurnDegrees, double? HeadingDegrees, SemanticProfilePoint? Target, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Span", SourceSpan);
+public sealed record SemanticProfileArcTransitionIr(string Name, string StableId, double Radius, double TurnDegrees, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "ArcTransition", SourceSpan);
+public sealed record SemanticProfileChamferIr(string Name, string StableId, double Run, double Offset, int Side, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Chamfer", SourceSpan);
+public sealed record SemanticProfileStepIr(string Name, string StableId, double Run, double Rise, int Side, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Step", SourceSpan);
+public sealed record SemanticProfileNotchIr(string Name, string StableId, double Width, double Depth, int Side, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Notch", SourceSpan);
+public sealed record SemanticProfileCutbackIr(string Name, string StableId, double Run, double Offset, int Side, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Cutback", SourceSpan);
+public sealed record SemanticProfileTabIr(string Name, string StableId, double Width, double Extension, int Side, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Tab", SourceSpan);
+public sealed record SemanticProfileCloseIr(string Name, string StableId, string SourceSpan)
+ : SemanticProfileMemberIr(Name, StableId, "Close", SourceSpan);
+
+public sealed record ResolvedSemanticProfileCurveIr(string StableId, int Ordinal, LineArcProfileCurve2D Geometry, string Provenance);
+public sealed record ResolvedSemanticProfileMemberIr(
+ string Name,
+ string StableId,
+ string Kind,
+ SemanticProfilePoint Start,
+ SemanticProfilePoint End,
+ IReadOnlyList<ResolvedSemanticProfileCurveIr> CurveDescendants,
+ string SourceSpan);
+public sealed record ResolvedSemanticProfileIr(
+ SemanticProfileIr Source,
+ IReadOnlyList<ResolvedSemanticProfileMemberIr> Members,
+ IReadOnlyDictionary<string, SemanticProfilePoint> Landmarks,
+ string DeterministicHash,
+ TimeSpan ResolutionTime)
+{
+ public IReadOnlyList<LineArcProfileCurve2D> ExactCurveChain => Members.SelectMany(member => member.CurveDescendants).Select(curve => curve.Geometry).ToArray();
+
+ /// <summary>The explicit semantic-to-exact boundary. PlanarContour2 remains topology authority after this call.</summary>
+ public ResolvedProfile2D LowerToResolvedProfile(ConstructionPlane? constructionPlane = null, double? localStartDepth = null, double? localEndDepth = null)
+ {
+ var segments = Members.SelectMany(member => member.CurveDescendants.Select(curve => new ResolvedProfileSegment2D(
+ curve.StableId, curve.Geometry, new(curve.StableId, member.StableId, member.SourceSpan, curve.Provenance, Source.LocalFrame)))).ToArray();
+ return new(Source.Name, Source.LocalFrame, [new("Outer", true, segments)], constructionPlane, localStartDepth, localEndDepth);
+ }
+
+ public PlanarContour2 LowerToPlanarContour2(string? provenance = null) =>
+ PlanarContourKernel.FromResolvedProfile(LowerToResolvedProfile(), provenance ?? $"SemanticProfileMIR:{Source.StableId}:{DeterministicHash}");
+}
+
+public sealed record SemanticProfileResolution(ResolvedSemanticProfileIr? Profile, IReadOnlyList<string> Diagnostics)
+{
+ public bool IsSuccess => Profile is not null && Diagnostics.Count == 0;
+}
+
+public static class SemanticProfileMirResolver
+{
+ private const double Tolerance = 1e-9;
+
+ public static SemanticProfileResolution Resolve(SemanticProfileIr profile)
+ {
+ ArgumentNullException.ThrowIfNull(profile);
+ var clock = Stopwatch.StartNew();
+ var diagnostics = new List<string>();
+ var resolved = new List<ResolvedSemanticProfileMemberIr>();
+ var landmarks = new Dictionary<string, SemanticProfilePoint>(StringComparer.Ordinal)
+ {
+ [profile.Name + ".Start"] = profile.Start,
+ [profile.StableId + ".Start"] = profile.Start
+ };
+ var identities = new HashSet<string>(StringComparer.Ordinal);
+ var current = profile.Start;
+ var heading = profile.InitialHeadingDegrees;
+
+ foreach (var member in profile.Members)
+ {
+ if (!identities.Add(member.StableId))
+ {
+ diagnostics.Add($"semantic-profile-duplicate-member:{member.StableId}");
+ continue;
+ }
+
+ var start = current;
+ var curves = new List<LineArcProfileCurve2D>();
+ void AddLine(SemanticProfilePoint end) { curves.Add(new LineArcLineSegment2D(ToTuple(current), ToTuple(end))); current = end; }
+ void AddBoxExcursion(double width, double depth, int side)
+ {
+ AddLine(AdvanceLocal(current, heading, 0d, side * depth));
+ AddLine(Advance(current, heading, width));
+ AddLine(AdvanceLocal(current, heading, 0d, -side * depth));
+ }
+ switch (member)
+ {
+ case SemanticProfileSpanIr span:
+ if (span.TurnDegrees is not null && span.HeadingDegrees is not null)
+ { diagnostics.Add($"semantic-profile-span-direction-conflict:{member.StableId}"); continue; }
+ if (span.Target is { } target)
+ {
+ if (Distance(current, target) <= Tolerance) { diagnostics.Add($"semantic-profile-zero-length:{member.StableId}"); continue; }
+ curves.Add(new LineArcLineSegment2D(ToTuple(current), ToTuple(target)));
+ current = target;
+ heading = Heading(start, current);
+ }
+ else
+ {
+ if (!Positive(span.Length)) { diagnostics.Add($"semantic-profile-invalid-span:{member.StableId}:Length must be positive"); continue; }
+ heading = span.HeadingDegrees ?? (heading + (span.TurnDegrees ?? 0d));
+ current = Advance(current, heading, span.Length);
+ curves.Add(new LineArcLineSegment2D(ToTuple(start), ToTuple(current)));
+ }
+ break;
+ case SemanticProfileArcTransitionIr arc:
+ if (!Positive(arc.Radius) || !FiniteNonZero(arc.TurnDegrees) || Math.Abs(arc.TurnDegrees) >= 360d - Tolerance)
+ { diagnostics.Add($"semantic-profile-invalid-arc-transition:{member.StableId}"); continue; }
+ var sweep = Degrees(arc.TurnDegrees); var tangent = Degrees(heading); var sign = Math.Sign(sweep);
+ var center = new SemanticProfilePoint(current.X - sign * arc.Radius * Math.Sin(tangent), current.Y + sign * arc.Radius * Math.Cos(tangent));
+ var startAngle = Math.Atan2(current.Y - center.Y, current.X - center.X);
+ curves.Add(new LineArcCircularArc2D(ToTuple(center), arc.Radius, startAngle, sweep));
+ current = new(center.X + arc.Radius * Math.Cos(startAngle + sweep), center.Y + arc.Radius * Math.Sin(startAngle + sweep));
+ heading += arc.TurnDegrees;
+ break;
+ case SemanticProfileChamferIr chamfer:
+ if (!Positive(chamfer.Run) || !Positive(chamfer.Offset) || !ValidSide(chamfer.Side)) { Invalid(member, "Run and Offset must be positive and Side must be Left or Right"); continue; }
+ current = AdvanceLocal(current, heading, chamfer.Run, chamfer.Side * chamfer.Offset);
+ curves.Add(new LineArcLineSegment2D(ToTuple(start), ToTuple(current)));
+ break;
+ case SemanticProfileCutbackIr cutback:
+ if (!Positive(cutback.Run) || !Positive(cutback.Offset) || !ValidSide(cutback.Side)) { Invalid(member, "Run and Offset must be positive and Side must be Left or Right"); continue; }
+ current = AdvanceLocal(current, heading, cutback.Run, cutback.Side * cutback.Offset);
+ curves.Add(new LineArcLineSegment2D(ToTuple(start), ToTuple(current)));
+ break;
+ case SemanticProfileStepIr step:
+ if (!Positive(step.Run) || !Positive(step.Rise) || !ValidSide(step.Side)) { Invalid(member, "Run and Rise must be positive and Side must be Left or Right"); continue; }
+ AddLine(Advance(current, heading, step.Run));
+ AddLine(AdvanceLocal(current, heading, 0d, step.Side * step.Rise));
+ break;
+ case SemanticProfileNotchIr notch:
+ if (!Positive(notch.Width) || !Positive(notch.Depth) || !ValidSide(notch.Side)) { Invalid(member, "Width and Depth must be positive and Side must be Left or Right"); continue; }
+ AddBoxExcursion(notch.Width, notch.Depth, notch.Side);
+ break;
+ case SemanticProfileTabIr tab:
+ if (!Positive(tab.Width) || !Positive(tab.Extension) || !ValidSide(tab.Side)) { Invalid(member, "Width and Extension must be positive and Side must be Left or Right"); continue; }
+ AddBoxExcursion(tab.Width, tab.Extension, tab.Side);
+ break;
+ case SemanticProfileCloseIr:
+ if (Distance(current, profile.Start) <= Tolerance) { diagnostics.Add($"semantic-profile-zero-length:{member.StableId}"); continue; }
+ current = profile.Start;
+ curves.Add(new LineArcLineSegment2D(ToTuple(start), ToTuple(current)));
+ break;
+ default:
+ diagnostics.Add($"semantic-profile-unsupported-member:{member.StableId}:{member.Kind}");
+ continue;
+ }
+
+ var descendants = curves.Select((geometry, ordinal) => new ResolvedSemanticProfileCurveIr(
+ $"{member.StableId}.curve{ordinal:D2}", ordinal, geometry, $"lowered-from:{member.StableId}")).ToArray();
+ resolved.Add(new(member.Name, member.StableId, member.Kind, start, current, descendants, member.SourceSpan));
+ landmarks[$"{profile.Name}.{member.Name}.Start"] = start;
+ landmarks[$"{profile.Name}.{member.Name}.End"] = current;
+ }
+
+ foreach (var constraint in profile.Constraints)
+ {
+ var selected = constraint.Members.Select(id => profile.Members.FirstOrDefault(member => member.StableId == id || member.Name == id || member.StableId == profile.StableId + "." + id)).ToArray();
+ var missing = constraint.Members.Where((_, index) => selected[index] is null).ToArray();
+ if (missing.Length > 0) diagnostics.Add($"semantic-profile-constraint-missing-member:{constraint.StableId}:{string.Join(',', missing)}");
+ else if (constraint.Kind.Equals("RequiredMembers", StringComparison.OrdinalIgnoreCase)) { }
+ else if (constraint.Kind.Equals("EqualSize", StringComparison.OrdinalIgnoreCase))
+ {
+ var signatures = selected.Select(member => SizeSignature(member!)).Distinct(StringComparer.Ordinal).ToArray();
+ if (signatures.Length != 1) diagnostics.Add($"semantic-profile-equal-size-mismatch:{constraint.StableId}:{string.Join(',', constraint.Members)}");
+ }
+ else if (constraint.Kind.Equals("Mirror", StringComparison.OrdinalIgnoreCase))
+ {
+ if (selected.Length != 2 || SizeSignature(selected[0]!) != SizeSignature(selected[1]!) || Side(selected[0]!) != -Side(selected[1]!))
+ diagnostics.Add($"semantic-profile-mirror-mismatch:{constraint.StableId}:{string.Join(',', constraint.Members)}");
+ }
+ else diagnostics.Add($"semantic-profile-constraint-unsupported:{constraint.StableId}:{constraint.Kind}");
+ }
+
+ clock.Stop();
+ if (diagnostics.Count > 0) return new(null, diagnostics);
+ var hashText = string.Join("|", resolved.SelectMany(member => member.CurveDescendants).Select(curve => $"{curve.StableId}:{curve.Geometry}"));
+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(hashText))).ToLowerInvariant();
+ return new(new(profile, resolved, landmarks, hash, clock.Elapsed), diagnostics);
+
+ void Invalid(SemanticProfileMemberIr member, string reason) => diagnostics.Add($"semantic-profile-invalid-{member.Kind.ToLowerInvariant()}:{member.StableId}:{reason}");
+ }
+
+ private static bool Positive(double value) => double.IsFinite(value) && value > Tolerance;
+ private static bool FiniteNonZero(double value) => double.IsFinite(value) && Math.Abs(value) > Tolerance;
+ private static bool ValidSide(int value) => value is -1 or 1;
+ private static int Side(SemanticProfileMemberIr member) => member switch
+ {
+ SemanticProfileChamferIr value => value.Side,
+ SemanticProfileStepIr value => value.Side,
+ SemanticProfileNotchIr value => value.Side,
+ SemanticProfileCutbackIr value => value.Side,
+ SemanticProfileTabIr value => value.Side,
+ _ => 0
+ };
+ private static string SizeSignature(SemanticProfileMemberIr member) => member switch
+ {
+ SemanticProfileChamferIr value => $"Chamfer:{value.Run:R}:{value.Offset:R}",
+ SemanticProfileStepIr value => $"Step:{value.Run:R}:{value.Rise:R}",
+ SemanticProfileNotchIr value => $"Notch:{value.Width:R}:{value.Depth:R}",
+ SemanticProfileCutbackIr value => $"Cutback:{value.Run:R}:{value.Offset:R}",
+ SemanticProfileTabIr value => $"Tab:{value.Width:R}:{value.Extension:R}",
+ SemanticProfileSpanIr value => $"Span:{value.Length:R}",
+ SemanticProfileArcTransitionIr value => $"ArcTransition:{value.Radius:R}:{Math.Abs(value.TurnDegrees):R}",
+ _ => member.Kind
+ };
+ private static double Degrees(double value) => value * Math.PI / 180d;
+ private static (double X, double Y) ToTuple(SemanticProfilePoint point) => (point.X, point.Y);
+ private static double Distance(SemanticProfilePoint a, SemanticProfilePoint b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
+ private static double Heading(SemanticProfilePoint a, SemanticProfilePoint b) => Math.Atan2(b.Y - a.Y, b.X - a.X) * 180d / Math.PI;
+ private static SemanticProfilePoint Advance(SemanticProfilePoint point, double headingDegrees, double length)
+ {
+ var radians = Degrees(headingDegrees);
+ return new(point.X + length * Math.Cos(radians), point.Y + length * Math.Sin(radians));
+ }
+ private static SemanticProfilePoint AdvanceLocal(SemanticProfilePoint point, double headingDegrees, double run, double normal)
+ {
+ var radians = Degrees(headingDegrees);
+ return new(point.X + run * Math.Cos(radians) - normal * Math.Sin(radians), point.Y + run * Math.Sin(radians) + normal * Math.Cos(radians));
+ }
+}
diff --git a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
index bfda2051..905f5ccb 100644
--- a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
+++ b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
@@ -8,6 +8,8 @@ using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
using Aetheris.Surfacing;
namespace Aetheris.SheetMetal;
@@ -294,10 +296,19 @@ internal static class AuthoredSheetMetalLowering
var right=tab.Center+tab.Width/2d;var left=tab.Center-tab.Width/2d;
if(left< -1e-8||right>cursor+1e-8)return Failure($"Tab '{tab.Path}' does not fit '{flange.Name}.Outer'.","sheetmetal-tab-outside-edge");
if(right<cursor-1e-8)points.Add(frame.OuterA+axis*right);
- points.Add(frame.OuterA+axis*right+direction*tab.Extension);points.Add(frame.OuterA+axis*left+direction*tab.Extension);
- if(left>1e-8)points.Add(frame.OuterA+axis*left);cursor=left;
+ var tabMir=new SemanticProfileIr(tab.Path,tab.Path,"SheetRegionLocal",new(right,0d),180d,
+ [new SemanticProfileTabIr(tab.Path.Split('.').Last(),tab.Path,tab.Width,tab.Extension,-1,"SheetMetalSemanticLayout")],[],[],"Sheet Metal semantic Tab");
+ var resolvedTab=SemanticProfileMirResolver.Resolve(tabMir);
+ if(!resolvedTab.IsSuccess)return Failure($"Tab '{tab.Path}' failed semantic Profile MIR resolution: {string.Join("; ",resolvedTab.Diagnostics)}","sheetmetal-tab-profile-mir-invalid");
+ foreach(var descendant in resolvedTab.Profile!.Members[0].CurveDescendants)
+ {
+ if(descendant.Geometry is not LineArcLineSegment2D line)return Failure($"Tab '{tab.Path}' generated a non-line descendant.","sheetmetal-tab-profile-mir-invalid");
+ var mapped=frame.OuterA+axis*line.End.X+direction*line.End.Y;
+ if((mapped-points[^1]).Length>1e-8)points.Add(mapped);
+ }
+ cursor=left;
}
- points.Add(frame.OuterA);boundary=points;
+ if((frame.OuterA-points[^1]).Length>1e-8)points.Add(frame.OuterA);boundary=points;
}
var plane = new SheetPlaneReference(tangentA, normal, axis, direction, true);
var flangeId=stableRegions[flange.Name];
diff --git a/docs/language/semantic-profiles.md b/docs/language/semantic-profiles.md
new file mode 100644
index 00000000..053e1498
--- /dev/null
+++ b/docs/language/semantic-profiles.md
@@ -0,0 +1,57 @@
+# Semantic Profiles and exact planar contours
+
+Firmament has two deliberately separate profile representations:
+
+- **Semantic Profile MIR** records what an engineering profile means: stable named members, local frame, datums, bounded relationships, and provenance.
+- **`PlanarContour2`** records the exact ordered curve topology that downstream geometry consumes.
+
+Primitive curves are lowering details, not the default authoring identity. One semantic member may generate several exact curves. For example:
+
+```firmament
+Concept Path Outline {
+ Start: Point2(0mm, 0mm)
+ Heading: 0deg
+ Span BottomLeft { Length: 44mm }
+ Tab MountTab { Width: 12mm; Extension: 8mm; Side: Right }
+ Span BottomRight { Length: 44mm }
+ Span Right { Turn: 90deg; Length: 60mm }
+ Span Top { Turn: 90deg; Length: 100mm }
+ Close Left
+}
+Profile Plate From Outline
+```
+
+`Plate.MountTab` is the stable semantic identity. It lowers deterministically to three lines named as curve descendants, but callers address the tab rather than relying on curve ordinal. `Plate.MountTab.End` is a derived landmark. Inspection can show `Curve00`–`Curve02` for debugging without promoting those descendants to authoring identity.
+
+## Bounded members
+
+The M1 resolver supports:
+
+| Member | Authored values | Exact lowering |
+|---|---|---|
+| `Span` | length and optional turn/heading | one line |
+| `Arc` | radius and turn | one tangent circular arc |
+| `Chamfer` | run, offset, side | one diagonal line |
+| `Step` | run, rise, side | two connected lines |
+| `Notch` | width, depth, side | three connected lines |
+| `Cutback` | run, offset, side | one diagonal line |
+| `Tab` | width, extension, side | three connected lines |
+| `Close` | profile start | one closing line |
+
+All measurements must be finite and positive. `Side` is `Left` or `Right` relative to the current local heading. Unsupported or contradictory input is rejected before exact contour construction, with the semantic member path in the diagnostic.
+
+## Lowering and identity
+
+```text
+Firmament Concept Path / Profile
+ -> SemanticProfileIr
+ -> bounded constraint resolution and derived landmarks
+ -> ResolvedSemanticProfileIr members and curve descendants
+ -> ResolvedProfile2D
+ -> PlanarContour2
+ -> extrusion, composition, sheet metal, drawing projection
+```
+
+Each exact descendant carries its semantic member stable ID as provenance. Splitting or offsetting a `PlanarContour2` preserves that ancestry. Stable IDs and contour hashes depend only on normalized semantic input and resolved exact geometry, not BRep edge numbering.
+
+This is intentionally not a general-purpose sketch solver. Relationships are admitted only when their resolution is direct and bounded. M1 includes required-member, equal-size, and paired mirror validation in the MIR API.
diff --git a/docs/modules/sheet-metal.md b/docs/modules/sheet-metal.md
index 9434302d..4312038a 100644
--- a/docs/modules/sheet-metal.md
+++ b/docs/modules/sheet-metal.md
@@ -22,7 +22,7 @@ The bounded kernel publishes line/line, line/arc, and arc/arc intersection; norm
## Authoring and Concept Paths
-M8 permits a `Concept Struct` to declare named `Datum`, regular `Pattern`, and bounded outer-edge `Tab` intent before the `SheetMetal` body. The compiler resolves those declarations into a `SheetMetalSemanticLayout`, validates required/equal-size/equal-pitch/mirror claims, generates stable feature members, and only then lowers exact formed and flat profiles. This is intentionally not a general sketch solver. `Span` and `SpanOffset` on a flange provide reusable partial-edge attachment.
+M8 permits a `Concept Struct` to declare named `Datum`, regular `Pattern`, and bounded outer-edge `Tab` intent before the `SheetMetal` body. The compiler resolves those declarations into a `SheetMetalSemanticLayout`, validates required/equal-size/equal-pitch/mirror claims, generates stable feature members, and only then lowers exact formed and flat profiles. Profile M1 routes the outer-edge `Tab` through the shared Semantic Profile MIR, so its stable path owns three generated contour descendants in both formed and flat states rather than relying on anonymous polygon indices. This is intentionally not a general sketch solver. `Span` and `SpanOffset` on a flange provide reusable partial-edge attachment. See [Semantic Profiles](../language/semantic-profiles.md).
The resolved layout is visible in `aetheris sheetmetal inspect --json`; semantic paths are visible through `aetheris sheetmetal paths`.
diff --git a/fixtures/FirmamentV2/Canonical/valid/semantic-profile-mounting-plate.firmament b/fixtures/FirmamentV2/Canonical/valid/semantic-profile-mounting-plate.firmament
new file mode 100644
index 00000000..bc3f5761
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/semantic-profile-mounting-plate.firmament
@@ -0,0 +1,17 @@
+Model SemanticMountingPlate {
+ Units: mm
+ Concept Path Outline {
+ Start: Point2(0mm, 0mm)
+ Heading: 0deg
+ Span BottomLeft { Length: 44mm }
+ Tab MountTab { Width: 12mm; Extension: 8mm; Side: Right }
+ Span BottomRight { Length: 44mm }
+ Span Right { Turn: 90deg; Length: 60mm }
+ Span Top { Turn: 90deg; Length: 100mm }
+ Close Left
+ }
+ Profile Plate From Outline
+ Struct PlateBody {
+ Extrude Solid { Profile: Plate; From: 0mm; To: 3mm }
+ }
+}