Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

PMI showcase phase 2: complete part specification and 3D layout

Clauded52bf65a424e
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
index 20f4efd2..f50f929f 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
@@ -93,8 +93,10 @@ public sealed class Step242ExporterTests
Assert.Equal(first.Value, second.Value);
Assert.Equal(2, CountOccurrences(first.Value, "SHAPE_ASPECT"));
Assert.Equal(2, CountOccurrences(first.Value, "PROPERTY_DEFINITION_REPRESENTATION"));
- Assert.Equal(2, CountOccurrences(first.Value, "SHAPE_DIMENSION_REPRESENTATION"));
- Assert.Equal(2, CountOccurrences(first.Value, "MEASURE_REPRESENTATION_ITEM"));
+ // Native and standard AP242 size forms are both written (2 holes x 2).
+ Assert.Equal(4, CountOccurrences(first.Value, "SHAPE_DIMENSION_REPRESENTATION"));
+ Assert.Equal(4, CountOccurrences(first.Value, "MEASURE_REPRESENTATION_ITEM"));
+ Assert.Equal(2, CountOccurrences(first.Value, "DIMENSIONAL_SIZE("));
Assert.Contains("firmament-feature:hole_a", first.Value, StringComparison.Ordinal);
Assert.Contains("firmament-feature:hole_b", first.Value, StringComparison.Ordinal);
Assert.Contains("MEASURE_REPRESENTATION_ITEM('diameter',8,#", first.Value, StringComparison.Ordinal);
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
index bb2fe619..6750b870 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
@@ -157,6 +157,15 @@ internal static class TrimmedSurfaceTessellator
return KernelResult<DisplayFaceMeshPatch>.Success(conformingPatch, qualityWarnings);
}
+ // A trim that is exactly the UV rectangle (a hole-wall strip between two section levels, say)
+ // needs no trim fidelity from the grid: size it by the surface's turning, not by the chord
+ // tolerance read as a parameter step, which made a straight ruling hundreds of cells long.
+ if (splineSupport is null && simplifiedLoops.Count == 1 && IsDisplayRectangle(simplifiedLoops[0]))
+ {
+ // Only a straight direction is coarsened; the curved one keeps the samples its edges were cut with.
+ if (curvedU <= 1) uSegments = 1;
+ if (curvedV <= 1) vSegments = 1;
+ }
var positions = new List<Point3D>((uSegments + 1) * (vSegments + 1));
var normals = new List<Vector3D>((uSegments + 1) * (vSegments + 1));
var uvGrid = new List<(double U, double V)>((uSegments + 1) * (vSegments + 1));
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 91a4f11c..0b2e407c 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -31,6 +31,10 @@ public static class Step242Exporter
if (control.GeometricFaceIds.Count == 0 || control.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
return Failure($"pmi-geometric-target-unresolved: '{control.Name}' requires proved face associations.", "Step242.Pmi");
}
+ // A projected dimension must stay attached to the geometry it measures.
+ foreach (var dimension in (semanticPmi ?? []).OfType<Step242SemanticPmiDimension>().Where(d => d.StandardKind is not null || d.FeatureId.StartsWith("compose:", StringComparison.Ordinal)))
+ if (dimension.GeometricFaceIds.Count == 0 || dimension.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
+ return Failure($"pmi-dimension-target-unresolved: '{dimension.Name}' does not resolve to faces of the exported body.", "Step242.Pmi");
// A datum feature without its face is a label with nothing to contact; never export one unattached.
foreach (var datum in (semanticPmi ?? []).OfType<Step242SemanticPmiDatum>().Where(d => d.RequiresFaceAssociation))
if (datum.GeometricFaceIds.Count == 0 || datum.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
@@ -541,6 +545,18 @@ public static class Step242Exporter
boundAspect = EmitHoleSemanticPmi(writer, shapeId, repContextId, lengthUnitId, hole);
break;
case Step242SemanticPmiDimension dimension:
+ if (dimension.LocationFaces is { } ends)
+ {
+ // Each end of a location is its own shape aspect bound to its faces.
+ string End(IReadOnlyList<int> faces, string role)
+ {
+ var end = writer.AddEntity("SHAPE_ASPECT", Step242TextWriter.String($"firmament-location-{role}:{dimension.Name}"),
+ Step242TextWriter.String($"location {role} {dimension.Name}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(true));
+ EmitGeometricItemAssociations(writer, shapeId, shapeRepresentationId, advancedFaceIds, dimension with { GeometricFaceIds = faces }, end);
+ return end;
+ }
+ dimension = dimension with { Location = (End(ends.From, "origin"), End(ends.To, "target")) };
+ }
boundAspect = EmitDimensionSemanticPmi(writer, shapeId, repContextId, lengthUnitId, dimension);
break;
case Step242SemanticPmiNote note:
@@ -617,6 +633,7 @@ public static class Step242Exporter
Step242TextWriter.Ref(repContextId));
writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyDefinitionId), Step242TextWriter.Ref(representationId));
EmitBilateralToleranceRepresentation(writer, featureShapeAspectId, repContextId, lengthUnitId, $"diameter_tolerance:{hole.FeatureId}", hole.TolerancePlus, hole.ToleranceMinus);
+ EmitStandardSize(writer, featureShapeAspectId, repContextId, lengthUnitId, "diameter", hole.Diameter, hole.TolerancePlus, hole.ToleranceMinus);
EmitQuantitySemanticPmi(writer, featureShapeAspectId, hole.FeatureId, hole.Quantity);
if (hole.Depth.HasValue)
@@ -672,10 +689,36 @@ public static class Step242Exporter
var representationId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String($"dimension:{dimension.Name}"), Step242TextWriter.List(valueId), Step242TextWriter.Ref(repContextId));
writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyId), Step242TextWriter.Ref(representationId));
EmitBilateralToleranceRepresentation(writer, aspectId, repContextId, lengthUnitId, $"dimension_tolerance:{dimension.Name}", dimension.TolerancePlus, dimension.ToleranceMinus);
+ if (dimension.StandardKind is { } standard && standard != "unresolved")
+ EmitStandardSize(writer, aspectId, repContextId, lengthUnitId, standard, dimension.Value, dimension.TolerancePlus, dimension.ToleranceMinus, dimension.Location);
EmitQuantitySemanticPmi(writer, aspectId, dimension.FeatureId, dimension.Quantity);
return aspectId;
}
+ /// <summary>
+ /// The same size in the standard AP242 form other CAD and inspection software reads
+ /// (CAx-IF semantic PMI): DIMENSIONAL_SIZE on the feature's shape aspect, its nominal
+ /// value, and a PLUS_MINUS_TOLERANCE with signed limits. Written alongside the
+ /// established Aetheris property records, which existing consumers read.
+ /// </summary>
+ private static void EmitStandardSize(Step242TextWriter writer, string aspectId, string repContextId, string lengthUnitId,
+ string kind, double nominal, double? tolerancePlus, double? toleranceMinus, (string From, string To)? location = null)
+ {
+ string Measure(double value, string role) => writer.AddRawEntity(
+ $"(LENGTH_MEASURE_WITH_UNIT()MEASURE_REPRESENTATION_ITEM()MEASURE_WITH_UNIT(LENGTH_MEASURE({Step242TextWriter.PmiNumber(value)}),{lengthUnitId})REPRESENTATION_ITEM({Step242TextWriter.String(role)}))");
+ var dimension = location is { } ends
+ ? writer.AddEntity("DIMENSIONAL_LOCATION", Step242TextWriter.String(kind), Step242TextWriter.String($"firmament-native:{aspectId}"), ends.From, ends.To)
+ : writer.AddEntity("DIMENSIONAL_SIZE", aspectId, Step242TextWriter.String(kind));
+ var value = Measure(nominal, "nominal value");
+ var representation = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String(""), Step242TextWriter.List(value), repContextId);
+ writer.AddEntity("DIMENSIONAL_CHARACTERISTIC_REPRESENTATION", dimension, representation);
+ if (!tolerancePlus.HasValue && !toleranceMinus.HasValue) return;
+ var plus = tolerancePlus ?? toleranceMinus!.Value;
+ var minus = toleranceMinus ?? tolerancePlus!.Value;
+ var limits = writer.AddEntity("TOLERANCE_VALUE", Measure(-minus, "lower limit"), Measure(plus, "upper limit"));
+ writer.AddEntity("PLUS_MINUS_TOLERANCE", limits, dimension);
+ }
+
private static void EmitBilateralToleranceRepresentation(
Step242TextWriter writer,
string aspectId,
diff --git a/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs b/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs
index 22c37ac1..64a267cf 100644
--- a/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs
@@ -46,6 +46,15 @@ internal sealed class Step242ForeignPmiReader
}
}
}
+ /// <summary>Shape aspects carrying an Aetheris native size or dimension record.</summary>
+ private HashSet<int> NativeAspects => nativeAspects ??= entities.Values
+ .Where(e => e.Name == "PROPERTY_DEFINITION" && Str(e.Arguments.FirstOrDefault()) is { } name
+ && (name.StartsWith("diameter:", StringComparison.Ordinal) || name.StartsWith("dimension:", StringComparison.Ordinal)))
+ .Select(e => Ref(e.Arguments.ElementAtOrDefault(2))).OfType<int>().ToHashSet();
+ private HashSet<int>? nativeAspects;
+ /// <summary>Standard size and location entities that restate a native record (read once, through it).</summary>
+ internal HashSet<int> Mirrors { get; } = [];
+
internal IReadOnlyList<Step242SemanticPmiInspectionItem> Read(IReadOnlyList<Step242SemanticPmiInspectionItem> existing)
{
var result = new List<Step242SemanticPmiInspectionItem>(); var skip = existing.Select(i => i.EntityId).ToHashSet();
@@ -81,6 +90,10 @@ internal sealed class Step242ForeignPmiReader
var location = entity.Name is "DIMENSIONAL_LOCATION" or "ANGULAR_LOCATION" or "DIRECTED_DIMENSIONAL_LOCATION";
var definition = Step242SubsetDecoder.TryGetConstructor(entity.Instance, location ? "DIMENSIONAL_LOCATION" : "DIMENSIONAL_SIZE") ?? entity.Instance.PrimaryConstructor;
var target = Ref(definition.Arguments.FirstOrDefault());
+ // Aetheris writes each native size record in the standard form too; read it once.
+ if (!location && target is { } sized && NativeAspects.Contains(sized)
+ || location && Str(definition.Arguments.ElementAtOrDefault(1))?.StartsWith("firmament-native:", StringComparison.Ordinal) == true)
+ { Mirrors.Add(entity.Id); continue; }
var targets = location ? definition.Arguments.Skip(2).OfType<Step242EntityReference>().Select(r => r.TargetId).Take(2).ToArray() : target is { } id ? [id] : [];
var representation = dimensionRepresentations.GetValueOrDefault(entity.Id);
var measureIds = entities.TryGetValue(representation, out var rep) ? Refs(rep.Arguments.ElementAtOrDefault(1)).ToArray() : [];
diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
index ccab38f5..9ea7c831 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
@@ -25,7 +25,16 @@ public sealed record Step242SemanticPmiDimension(
double Value,
double? TolerancePlus,
double? ToleranceMinus,
- int? Quantity = null) : Step242SemanticPmi(FeatureId);
+ int? Quantity = null) : Step242SemanticPmi(FeatureId)
+{
+ /// <summary>AP242 size or location name ("diameter", "length", "radius", "depth", "linear distance");
+ /// when set, the standard DIMENSIONAL_SIZE/LOCATION form is written alongside the native record.</summary>
+ public string? StandardKind { get; init; }
+ /// <summary>For a location, the two shape-aspect references it runs between (exporter-owned).</summary>
+ public (string From, string To)? Location { get; init; }
+ /// <summary>For a location, the faces at each end; <see cref="Step242SemanticPmi.GeometricFaceIds"/> holds both.</summary>
+ public (IReadOnlyList<int> From, IReadOnlyList<int> To)? LocationFaces { get; init; }
+}
public sealed record Step242SemanticPmiDatum(
string FeatureId,
diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs
index f0828061..290f191c 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs
@@ -40,6 +40,8 @@ public sealed record Step242SemanticPmiInspectionResult(
public int DimensionCount => Items.Count(item => item.Kind is "Diameter" or "Dimension");
public int GeometricToleranceCount => Items.Count(item => Step242GeometricToleranceKinds.Find(item.Kind) is not null || item.Kind == "GeometricTolerance");
public int AnnotationCount => Items.Count(item => item.Kind == "Annotation");
+ /// <summary>Standard AP242 size/location entities that restate a native record already in <see cref="Items"/>.</summary>
+ public IReadOnlyList<int> StandardMirrors { get; init; } = [];
}
/// <summary>
@@ -139,7 +141,8 @@ public static class Step242SemanticPmiInspector
PresentationSupported = detailed.PresentationSupported,
GeometricItemEntityIds = detailed.GeometricItemEntityIds,
GeometricFaceEntityIds = detailed.GeometricFaceEntityIds.Count > 0 ? detailed.GeometricFaceEntityIds : item.GeometricFaceEntityIds } : item);
- return new(true, combined.Concat(foreign.Where(item => native.All(n => n.EntityId != item.EntityId))).OrderBy(item => item.EntityId).ToArray(), []);
+ return new(true, combined.Concat(foreign.Where(item => native.All(n => n.EntityId != item.EntityId))).OrderBy(item => item.EntityId).ToArray(), [])
+ { StandardMirrors = schemaReader.Mirrors.Order().ToArray() };
}
private static Dictionary<string, IReadOnlyList<double>> BuildRepresentations(
diff --git a/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs b/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs
index a9c0c3f3..20fa6fb9 100644
--- a/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs
@@ -112,13 +112,97 @@ public sealed class PmiShowcaseTests
var result = FirmamentBuildAndExport.CompileSource(Showcase());
Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(d => d.Message)));
var inspection = Step242SemanticPmiInspector.Inspect(result.Value.StepText);
- Assert.Equal(3, inspection.DatumCount); Assert.Equal(2, inspection.DimensionCount);
+ Assert.Equal(3, inspection.DatumCount); Assert.Equal(17, inspection.DimensionCount);
Assert.Equal(5, inspection.GeometricToleranceCount); Assert.Equal(3, inspection.AnnotationCount);
Assert.All(inspection.Items.Where(i => i.Kind != "Annotation"), i => Assert.NotEmpty(i.GeometricFaceEntityIds));
var display = PmiDisplayProjection.FromStep(result.Value.StepText);
Assert.Equal(inspection.Items.Count, display.Count);
- Assert.All(display.Where(a => a.Kind != "Note"), a => Assert.NotNull(a.TextFill));
+ Assert.All(display, a => Assert.NotEmpty(a.Lines));
Assert.Contains(display, a => a.Text.StartsWith("4X Ø6.6 ±0.1", StringComparison.Ordinal));
Assert.Contains(display, a => a.Text == "Position Ø0.25 (M) | A | B | C");
+ Assert.Contains(display, a => a.Text == "2X 16 × 40");
+ Assert.Contains(display, a => a.Text == "1 × 45°");
+ }
+
+ [Fact]
+ public void ProjectedDimensions_ComeFromTheBuiltGeometry()
+ {
+ var step = Build("""
+ Datum A { target: face(-Z) }
+ Dimension T { target: stock.Height }
+ Dimension L { target: stock.Length }
+ Dimension W { target: stock.Width }
+ Dimension D { target: hub.Diameter }
+ Dimension H { target: hub.Height }
+ Location FromB { origin: face(-X) to: hub }
+ Location HoleFromC { origin: face(-Y) to: a basic: true }
+ """).StepText;
+ var items = Step242SemanticPmiInspector.Inspect(step).Items.Where(i => i.Kind == "Dimension").ToDictionary(i => i.Name);
+ Assert.Equal(8, items["T"].Value); Assert.Equal("thickness", items["T"].DimensionKind);
+ Assert.Equal(60, items["L"].Value); Assert.Equal(40, items["W"].Value);
+ Assert.Equal(20, items["D"].Value); Assert.Equal(6, items["H"].Value);
+ Assert.Equal(30, items["FromB"].Value); Assert.Equal("location -X", items["FromB"].DimensionKind);
+ Assert.Equal(8, items["HoleFromC"].Value); Assert.Equal("location -Y basic", items["HoleFromC"].DimensionKind);
+ Assert.All(items.Values, i => Assert.NotEmpty(i.GeometricFaceEntityIds));
+ }
+
+ [Fact]
+ public void Sizes_AreAlsoWrittenInStandardAp242Form_AndReadOnce()
+ {
+ var step = Build("HoleDiameter S { target: h dimension: d } Dimension D { target: hub.Diameter } Dimension T { target: stock.Height }").StepText;
+ Assert.Contains("DIMENSIONAL_SIZE(", step); Assert.Contains("PLUS_MINUS_TOLERANCE(", step); Assert.Contains("DIMENSIONAL_LOCATION(", step);
+ Assert.Equal(3, Step242SemanticPmiInspector.Inspect(step).DimensionCount);
+ // A reader that only knows the standard entities finds the same sizes and limits.
+ var standardOnly = step.Replace("PROPERTY_DEFINITION('diameter:", "PROPERTY_DEFINITION('x:").Replace("PROPERTY_DEFINITION('dimension:", "PROPERTY_DEFINITION('x:")
+ .Replace("'firmament-native:", "'x:");
+ var dims = Step242SemanticPmiInspector.Inspect(standardOnly).Items.Where(i => i.Kind == "Dimension").ToArray();
+ var hole = Assert.Single(dims, i => i.Value == 8 && i.DimensionKind == "diameter");
+ Assert.Equal(.1, hole.TolerancePlus); Assert.Equal(.05, hole.ToleranceMinus);
+ Assert.Single(dims, i => i.Value == 20 && i.DimensionKind == "diameter");
+ Assert.Single(dims, i => i.Value == 8 && i.DimensionKind == "linear distance");
+ }
+
+ [Fact]
+ public void HoleCallout_ProjectsItsCounterbore()
+ {
+ var source = Plate.Replace("Hole<Shaft> a { on: +Z; center: [-22mm, -12mm]; diameter: 5mm; end: ThroughAll }",
+ "Hole<Counterbore> a { on: +Z; center: [-22mm, -12mm]; diameter: 5mm; counterboreDiameter: 9mm; counterboreDepth: 3mm; end: ThroughAll }")
+ .Replace("PMI_BODY", "HoleCallout C { target: a value: 5mm tolerance: PlusMinus(0.1mm) }");
+ var result = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(d => d.Message)));
+ var items = Step242SemanticPmiInspector.Inspect(result.Value.StepText).Items;
+ Assert.Single(items, i => i.Kind == "Diameter" && i.Value == 5);
+ Assert.Single(items, i => i.Name == "C.CounterboreDiameter" && i.Value == 9);
+ Assert.Single(items, i => i.Name == "C.CounterboreDepth" && i.Value == 3);
+ Assert.Contains(PmiDisplayProjection.FromStep(result.Value.StepText), a => a.Text.Contains("Ø5 ±0.1", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Dimension D { target: stock.Volume }")]
+ [InlineData("Dimension D { target: [hub.Diameter, stock.Height] }")]
+ [InlineData("Location L { origin: face(+Z) to: hub }")]
+ [InlineData("Location L { origin: face(-X) to: nothing }")]
+ [InlineData("Location L { origin: face(-X) to: hub basic: true tolerance: PlusMinus(0.1mm) }")]
+ public void InvalidProjections_Reject(string pmi)
+ {
+ var result = FirmamentBuildAndExport.CompileSource(Plate.Replace("PMI_BODY", pmi));
+ Assert.False(result.IsSuccess);
+ }
+
+ [Fact]
+ public void HoleWall_OnAComposeHole_TargetsItsShaft()
+ {
+ var step = Build("Datum A { target: face(-Z) } Position P { target: face(h.Wall) tolerance: 0.1mm datumRefs: [A] }").StepText;
+ Assert.NotEmpty(Assert.Single(Step242SemanticPmiInspector.Inspect(step).Items, i => i.Kind == "Position").GeometricFaceEntityIds);
+ }
+
+ [Fact]
+ public void PmiRecordErrors_AreLocatedAndExplained()
+ {
+ var source = Plate.Replace("PMI_BODY", "HoleDiameter S { target: h dimension: nothere }");
+ var report = FirmamentV2.FirmamentV2ValidationReportBuilder.Build(FirmamentV2.FirmamentV2Parser.Parse(source), "plate.firmament", sourceText: source);
+ var error = Assert.Single(report.Diagnostics, d => d.Code.StartsWith("firmament-v2-pmi-dimension-type-mismatch:", StringComparison.Ordinal));
+ Assert.Contains("toleranced Length Static", error.Message);
+ Assert.NotNull(error.Line); Assert.NotEqual(1, error.Line);
}
}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
index a7d7b946..2ef69e42 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
@@ -173,10 +173,15 @@ public static class AssemblyGlbExporter
var pmiJsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
foreach (var annotation in display.Annotations)
{
- var positions = annotation.Lines.SelectMany(line => line.Zip(line.Skip(1), (a, b) => new[] { a, b })
+ // Filled text needs no glyph outline in a GLB; line-only consumers keep them in Lines.
+ var drawn = annotation.TextFill is not null && annotation.DraftingLines is { } drafting ? drafting : annotation.Lines;
+ var positions = drawn.SelectMany(line => line.Zip(line.Skip(1), (a, b) => new[] { a, b })
+ .SelectMany(pair => pair).SelectMany(point => point)).ToArray();
+ if (positions.Length == 0) positions = annotation.Lines.SelectMany(line => line.Zip(line.Skip(1), (a, b) => new[] { a, b })
.SelectMany(pair => pair).SelectMany(point => point)).ToArray();
if (positions.Length == 0) throw new InvalidOperationException("glb-pmi-presentation-empty:" + annotation.Name);
- materials.Add(new { name = "PMI " + annotation.Name, pbrMetallicRoughness = new { baseColorFactor = new[] { .05, .1, .18, 1 }, metallicFactor = 0, roughnessFactor = 1 }, emissiveFactor = new[] { .05, .1, .18 } });
+ var ink = annotation.LeaderColor ?? [.05, .1, .18];
+ materials.Add(new { name = "PMI " + annotation.Name, pbrMetallicRoughness = new { baseColorFactor = new[] { ink[0], ink[1], ink[2], 1 }, metallicFactor = 0, roughnessFactor = 1 }, emissiveFactor = ink });
var primitives = new List<object> { new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(positions, 3, true) }, mode = 1, material = materials.Count - 1 } };
if (annotation.TextFill is { Indices.Length: > 0 } fill)
{
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
index c40f22fe..4de5f355 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
@@ -90,7 +90,7 @@ public static partial class FirmamentDrawingCompiler
|| Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DIMENSIONAL_LOCATION") is not null
|| Step242SubsetDecoder.TryGetConstructor(entity.Instance, "GEOMETRIC_TOLERANCE") is not null
|| Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DATUM_FEATURE") is not null)
- && !inspected.Items.Any(item => item.EntityId == entity.Id)).Select(entity => $"#{entity.Id}:{entity.Name}").ToArray();
+ && !inspected.Items.Any(item => item.EntityId == entity.Id) && !inspected.StandardMirrors.Contains(entity.Id)).Select(entity => $"#{entity.Id}:{entity.Name}").ToArray();
if (unsupportedPmi.Length > 0) return Failure($"drawing-pmi-family-unsupported: These AP242 semantic entities require a qualified readback adapter: {string.Join(", ", unsupportedPmi)}. They were not omitted from a successful drawing.");
if (inspected.Items.Count > 0 && Math.Abs(parsed.Value.SourceMillimetresPerUnit - 1) > 1e-12)
return Failure("drawing-pmi-units-unsupported: Semantic PMI generation currently requires millimetre AP242 measures. Geometry-only reference views can use normalized imported units.");
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs
index f81281d7..7e8fb43b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs
@@ -58,9 +58,158 @@ public static partial class FirmamentBuildAndExport
.Select(other => other.Id.Value);
}
- /// <summary>The cap selector spellings a Compose body admits in <c>Pmi</c>.</summary>
+ /// <summary>The cap selectors, dimensionable parameters (<c>param:</c>) and locatable features
+ /// (<c>op:</c>) a Compose body admits in <c>Pmi</c>.</summary>
internal static IEnumerable<string> ComposeOperationCapTargets(PrismaticProfileCompositionFeature feature) =>
- feature.Operations.Where(o => o.Intent == PrismaticProfileIntent.Base).SelectMany(o => new[] { $"face({o.Name}.Top)", $"face({o.Name}.Bottom)" })
- .Concat((feature.Bosses ?? []).Select(b => $"face({b.Name}.Top)"))
- .Concat((feature.Pockets ?? []).Select(p => $"face({p.Name}.Floor)"));
+ feature.Operations.Where(o => o.Intent == PrismaticProfileIntent.Base).SelectMany(o => new[] { $"face({o.Name}.Top)", $"face({o.Name}.Bottom)",
+ $"param:{o.Name}.Height", $"param:{o.Name}.Length", $"param:{o.Name}.Width" })
+ .Concat((feature.Bosses ?? []).SelectMany(b => new[] { $"face({b.Name}.Top)", $"op:{b.Name}",
+ $"param:{b.Name}.Height", $"param:{b.Name}.Diameter", $"param:{b.Name}.Length", $"param:{b.Name}.Width", $"param:{b.Name}.Radius" }))
+ .Concat((feature.Pockets ?? []).SelectMany(p => new[] { $"face({p.Name}.Floor)", $"op:{p.Name}",
+ $"param:{p.Name}.Depth", $"param:{p.Name}.Diameter", $"param:{p.Name}.Length", $"param:{p.Name}.Width", $"param:{p.Name}.Radius" }));
+}
+
+/// <summary>A construction parameter projected into PMI: its value and the faces it measures.</summary>
+internal sealed record ComposeProjection(string Kind, double Value, int[] Faces, (int[] From, int[] To)? Ends = null, int Count = 1);
+
+public static partial class FirmamentBuildAndExport
+{
+ /// <summary>
+ /// Resolve <c>op.Param</c> on a composed body. Values come from the built geometry (walls,
+ /// caps, arcs), so a projected dimension cannot disagree with what was made.
+ /// Unknown or unmeasurable parameters return null and the PMI record rejects.
+ /// </summary>
+ internal static ComposeProjection? ProjectComposeParameter(PrismaticProfileCompositionFeature feature, BrepBody body,
+ SemanticTopologyCorrespondence? correspondence, string target)
+ {
+ var dot = target.LastIndexOf('.');
+ if (dot <= 0) return null;
+ var owner = target[..dot]; var parameter = target[(dot + 1)..];
+ var baseOp = feature.Operations.FirstOrDefault(o => o.Intent == PrismaticProfileIntent.Base && o.Name == owner);
+ var boss = (feature.Bosses ?? []).FirstOrDefault(b => b.Name == owner);
+ var pocket = (feature.Pockets ?? []).FirstOrDefault(p => p.Name == owner);
+ if (baseOp is null && boss is null && pocket is null) return ProjectEdgeFinish(body, parameter);
+ var profile = baseOp?.ProfileReference ?? boss?.ProfileReference ?? pocket!.ProfileReference;
+ var (from, to) = baseOp is not null ? (baseOp.From, baseOp.To) : boss is not null ? (boss.From, boss.To) : (pocket!.From, pocket.To);
+ var walls = Walls(body, correspondence, profile);
+ int[] Caps(double level, bool up, bool adjacent) => body.Topology.Faces.Where(f => body.TryGetFaceSurfaceGeometry(f.Id, out var s)
+ && s?.Plane is { } plane && Math.Abs(plane.Normal.ToVector().Z - (up ? 1 : -1)) < 1e-8 && Math.Abs(plane.Origin.Z - level) < 1e-7
+ && (!adjacent || Neighbours(body, f.Id).Any(walls.Contains)))
+ .Select(f => f.Id.Value).ToArray();
+ switch (parameter)
+ {
+ case "Height" when baseOp is not null:
+ {
+ var bottom = Caps(from, false, false); var top = Caps(to, true, false);
+ return bottom.Length == 0 || top.Length == 0 ? null : new("thickness", to - from, [.. bottom, .. top], (bottom, top));
+ }
+ case "Height" when boss is not null:
+ {
+ var support = Caps(from, true, true); var top = Caps(to, true, true);
+ return support.Length == 0 || top.Length == 0 ? null : new("height", to - from, [.. support, .. top], (support, top));
+ }
+ case "Depth" when pocket is not null:
+ {
+ var rim = Caps(to, true, true); var floor = Caps(from, true, true);
+ return rim.Length == 0 || floor.Length == 0 ? null : new("depth", to - from, [.. rim, .. floor], (rim, floor));
+ }
+ case "Length" or "Width":
+ {
+ // Length runs along X and Width along Y, between the profile's opposite straight walls.
+ var axis = parameter == "Length" ? new Aetheris.Kernel.Core.Math.Vector3D(1, 0, 0) : new Aetheris.Kernel.Core.Math.Vector3D(0, 1, 0);
+ var planar = walls.Select(id => (Id: id, Plane: body.GetFaceSurface(new FaceId(id)).Plane))
+ .Where(w => w.Plane is { } p && Math.Abs(Math.Abs(p.Normal.ToVector().Dot(axis)) - 1) < 1e-8)
+ .Select(w => (w.Id, Offset: (w.Plane!.Value.Origin - Aetheris.Kernel.Core.Math.Point3D.Origin).Dot(axis))).ToArray();
+ if (planar.Length < 2) return null;
+ var min = planar.Min(p => p.Offset); var max = planar.Max(p => p.Offset);
+ var low = planar.Where(p => Math.Abs(p.Offset - min) < 1e-7).Select(p => p.Id).ToArray();
+ var high = planar.Where(p => Math.Abs(p.Offset - max) < 1e-7).Select(p => p.Id).ToArray();
+ return max - min < 1e-9 ? null : new(parameter.ToLowerInvariant(), max - min, [.. low, .. high], (low, high));
+ }
+ case "Radius" or "Diameter":
+ {
+ var arcs = walls.Select(id => (Id: id, Cylinder: body.GetFaceSurface(new FaceId(id)).Cylinder)).Where(w => w.Cylinder is not null).ToArray();
+ if (arcs.Length == 0) return null;
+ var radii = arcs.Select(a => Math.Round(a.Cylinder!.Value.Radius, 9)).Distinct().ToArray();
+ if (radii.Length != 1) return null;
+ var axes = arcs.Select(a => (Math.Round(a.Cylinder!.Value.Origin.X, 6), Math.Round(a.Cylinder!.Value.Origin.Y, 6))).Distinct().Count();
+ // A diameter needs one full round wall; a radius is the corner arcs, counted per corner.
+ if (parameter == "Diameter" && (axes != 1 || arcs.Any(a => body.GetFaceSurface(new FaceId(a.Id)).Cylinder is null))
+ || parameter == "Diameter" && arcs.Length != walls.Count) return null;
+ return parameter == "Diameter" ? new("diameter", 2 * radii[0], arcs.Select(a => a.Id).ToArray())
+ : new("radius", radii[0], arcs.Select(a => a.Id).ToArray(), Count: axes);
+ }
+ }
+ return null;
+ }
+
+ /// <summary>An equal-distance chamfer: its distance from the inclined face's vertical extent and angle.</summary>
+ private static ComposeProjection? ProjectEdgeFinish(BrepBody body, string parameter)
+ {
+ if (parameter != "Distance") return null;
+ var faces = body.Topology.Faces.Select(f => (f.Id, Plane: body.TryGetFaceSurfaceGeometry(f.Id, out var s) ? s?.Plane : null))
+ .Where(f => f.Plane is { } p && Math.Abs(p.Normal.ToVector().Z) is > .05 and < .95).ToArray();
+ if (faces.Length == 0) return null;
+ var normal = faces[0].Plane!.Value.Normal.ToVector();
+ if (Math.Abs(Math.Abs(normal.Z) - Math.Sqrt(.5)) > 1e-6) return null; // only 45° chamfers are measured here
+ var points = body.Topology.GetFace(faces[0].Id).LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
+ .Select(id => body.Topology.GetEdge(body.Topology.GetCoedge(id).EdgeId))
+ .SelectMany(e => new[] { e.StartVertexId, e.EndVertexId }).Distinct()
+ .Select(v => body.TryGetVertexPoint(v, out var p) ? p.Z : double.NaN).Where(double.IsFinite).ToArray();
+ return points.Length < 2 ? null : new("chamfer", points.Max() - points.Min(), faces.Select(f => f.Id.Value).ToArray());
+ }
+
+ private static HashSet<int> Walls(BrepBody body, SemanticTopologyCorrespondence? correspondence, string profile) =>
+ (correspondence?.Descendants ?? [])
+ .Where(d => d.Face.HasValue && d.Role == SemanticTopologyRole.ExtrusionSideFace
+ && (d.SourceStableId.Contains("_" + profile + "_", StringComparison.Ordinal) || d.SourceStableId.StartsWith("profile:" + profile + ".", StringComparison.Ordinal)))
+ .Select(d => d.Face!.Value.Value).ToHashSet();
+
+ /// <summary>
+ /// A location from an axis face (its extreme support plane) to a hole axis or to the
+ /// mid-plane of a boss or pocket between its walls facing that direction.
+ /// </summary>
+ internal static ComposeProjection? ProjectComposeLocation(PrismaticProfileCompositionFeature feature, BrepBody body,
+ SemanticTopologyCorrespondence? correspondence, IReadOnlyDictionary<string, string> holeFeatures, string solid, string from, string to, bool basic)
+ {
+ var port = from switch { "face(+X)" => "plus_x_face", "face(-X)" => "minus_x_face", "face(+Y)" => "plus_y_face", "face(-Y)" => "minus_y_face", _ => null };
+ if (port is null) return null;
+ var datum = Execution.FirmamentSelectorResolver.ResolveSupportPlaneFaces(body, $"{solid}.{port}").Select(f => f.Value).ToArray();
+ if (datum.Length == 0) return null;
+ var plane = body.GetFaceSurface(new FaceId(datum[0])).Plane!.Value;
+ var n = plane.Normal.ToVector();
+ var origin = (plane.Origin - Aetheris.Kernel.Core.Math.Point3D.Origin).Dot(n);
+ int[] targetFaces; double coordinate;
+ if (holeFeatures.TryGetValue(to, out var featureId))
+ {
+ targetFaces = (correspondence?.Descendants ?? []).Where(d => d.Face.HasValue && (d.SourceStableId == featureId || d.ParentStableId == featureId)
+ && d.Role is not (SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCountersinkWallFace))
+ .Select(d => d.Face!.Value.Value).Distinct().ToArray();
+ var cylinder = targetFaces.Select(id => body.GetFaceSurface(new FaceId(id)).Cylinder).FirstOrDefault(c => c is not null);
+ if (cylinder is null || Math.Abs(cylinder.Value.Axis.ToVector().Dot(n)) > 1e-8) return null;
+ coordinate = (cylinder.Value.Origin - Aetheris.Kernel.Core.Math.Point3D.Origin).Dot(n);
+ }
+ else
+ {
+ var profile = (feature.Bosses ?? []).FirstOrDefault(b => b.Name == to)?.ProfileReference ?? (feature.Pockets ?? []).FirstOrDefault(p => p.Name == to)?.ProfileReference;
+ if (profile is null) return null;
+ var walls = Walls(body, correspondence, profile);
+ var facing = walls.Select(id => (Id: id, Plane: body.GetFaceSurface(new FaceId(id)).Plane))
+ .Where(w => w.Plane is { } p && Math.Abs(Math.Abs(p.Normal.ToVector().Dot(n)) - 1) < 1e-8).ToArray();
+ if (facing.Length < 2)
+ {
+ // A round boss or pocket is located by its axis.
+ var round = walls.Select(id => body.GetFaceSurface(new FaceId(id)).Cylinder).Where(c => c is not null).Select(c => c!.Value).ToArray();
+ if (round.Length == 0 || round.Select(c => Math.Round((c.Origin - Aetheris.Kernel.Core.Math.Point3D.Origin).Dot(n), 7)).Distinct().Count() != 1) return null;
+ var axisName0 = from[5..^1];
+ return new($"location {axisName0}{(basic ? " basic" : "")}", Math.Abs((round[0].Origin - Aetheris.Kernel.Core.Math.Point3D.Origin).Dot(n) - origin),
+ [.. datum, .. walls], (datum, walls.ToArray()));
+ }
+ var offsets = facing.Select(w => (w.Plane!.Value.Origin - Aetheris.Kernel.Core.Math.Point3D.Origin).Dot(n)).ToArray();
+ coordinate = (offsets.Min() + offsets.Max()) / 2; // to the feature's centre plane
+ targetFaces = facing.Select(w => w.Id).ToArray();
+ }
+ var axisName = from[5..^1];
+ return new($"location {axisName}{(basic ? " basic" : "")}", Math.Abs(coordinate - origin), [.. datum, .. targetFaces], (datum, targetFaces));
+ }
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
index 60014f97..ff63dc35 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
@@ -40,7 +40,7 @@ public static partial class FirmamentBuildAndExport
foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
pmi = BuildV2SemanticPmi(document, [], stack.Feature.Name, features, planned.Correspondence, planned.Body,
- ComposeOperationCapFaces(stack.Feature, planned.Body, planned.Correspondence)).ToArray();
+ ComposeOperationCapFaces(stack.Feature, planned.Body, planned.Correspondence), stack.Feature).ToArray();
}
var step = Step242Exporter.ExportBody(planned.Body, pmi, new Step242ExportOptions {
ProductName = stack.Feature.Name, ApplicationName = "Aetheris.ProfileRimFinish", BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 16ed1fca..c297f151 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -247,7 +247,12 @@ public static partial class FirmamentBuildAndExport
if (!support.IsSuccess) return support;
var expectedDatums = pmi.Count(record => record.Kind == FirmamentV2PmiKind.DatumPlane) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiDatum>().Count();
- var expectedDiameters = pmi.Count(record => record.Kind == FirmamentV2PmiKind.HoleDiameter) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiHole>().Count();
+ // Projected sizes and locations are dimensions too; a hole callout on counterbores adds its
+ // counterbore diameter and depth.
+ var counterbores = Regex.Matches(source, @"\bHole<Counterbore>\s+(?<name>[A-Za-z_]\w*)").Select(m => m.Groups["name"].Value).ToHashSet(StringComparer.Ordinal);
+ var calloutExtras = 2 * (document.BoundPmi?.Dimensions ?? []).Count(b => b.Callout && b.Targets.Any(counterbores.Contains));
+ var expectedDiameters = pmi.Count(record => record.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Dimension or FirmamentV2PmiKind.Location)
+ + calloutExtras + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiHole>().Count();
var expectedControls = pmi.Count(record => Step242GeometricToleranceKinds.Find(record.Kind.ToString()) is not null)
+ export.GeneratedSemanticPmi.OfType<Step242SemanticPmiGeometricTolerance>().Count();
foreach (var imported in document.Solids.Select(s => s.InlineStep).OfType<FirmamentV2InlineStepRecord>().Where(s => !s.GeometryOnly))
@@ -527,7 +532,7 @@ public static partial class FirmamentBuildAndExport
foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence, completedBody,
- ComposeOperationCapFaces(stack.Feature, completedBody, emitted.Correspondence)).ToArray();
+ ComposeOperationCapFaces(stack.Feature, completedBody, emitted.Correspondence), stack.Feature).ToArray();
}
var step = Step242Exporter.ExportBody(completedBody, semanticPmi);
if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
@@ -1197,7 +1202,7 @@ public static partial class FirmamentBuildAndExport
foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence, plannedEmission.Body,
- ComposeOperationCapFaces(stack.Feature, plannedEmission.Body, plannedEmission.Correspondence)).ToArray();
+ ComposeOperationCapFaces(stack.Feature, plannedEmission.Body, plannedEmission.Correspondence), stack.Feature).ToArray();
}
var plannedStep = Step242Exporter.ExportBody(plannedEmission.Body, semanticPmi, new Step242ExportOptions { ProductName = target.StableId, ApplicationName = "Aetheris.Firmament.ComposedProfileBoundaryChamfer.M3", BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
if (!plannedStep.IsSuccess || plannedStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(plannedStep.Diagnostics);
@@ -2868,7 +2873,8 @@ public static partial class FirmamentBuildAndExport
// owner. A supported record kind does not imply every requested field exports.
internal static KernelDiagnostic? V2PmiExportRejection(FirmamentV2PmiKind kind, string name, FirmamentV2BoundPmiRecord? bound)
{
- var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Note) && Step242GeometricToleranceKinds.Find(kind.ToString()) is null
+ var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Note or FirmamentV2PmiKind.Dimension or FirmamentV2PmiKind.Location)
+ && kind != FirmamentV2PmiKind.Location && Step242GeometricToleranceKinds.Find(kind.ToString()) is null
? $"firmament-v2-pmi-export-deferred: AP242 export for PMI record '{name}' ({kind.ToString().ToLowerInvariant()}) is deferred; use Datum, HoleDiameter or an admitted geometric control."
: kind == FirmamentV2PmiKind.HoleDiameter && bound?.DatumRefs.Count > 0
? $"firmament-v2-pmi-datum-reference-export-unsupported: HoleDiameter '{name}' requests datum references that native size export cannot preserve. Export Datum separately; datum-referenced geometric controls require a qualified PMI capability."
@@ -2883,7 +2889,8 @@ public static partial class FirmamentBuildAndExport
IReadOnlyDictionary<string, string>? explicitFeatureIds = null,
SemanticTopologyCorrespondence? correspondence = null,
BrepBody? body = null,
- IReadOnlyDictionary<string, int[]>? namedFaces = null)
+ IReadOnlyDictionary<string, int[]>? namedFaces = null,
+ PrismaticProfileCompositionFeature? composeFeature = null)
{
if (document.Pmi is null || document.Pmi.Count == 0)
{
@@ -2925,12 +2932,45 @@ public static partial class FirmamentBuildAndExport
else if (explicitFeatureIds is not null && explicitFeatureIds.TryGetValue(pmi.Target, out var featureId))
{
result.Add(new Step242SemanticPmiHole(featureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });
+ if (boundPmi?.Callout == true) result.AddRange(CounterboreCallout(pmi.Name, boundPmi.Targets, composeFeature, correspondence));
}
else if (TryResolveV2RecognizedRegionTarget(document, targetBinding, pmi.Target, out var importedTarget) || TryResolveV2ImportedFaceTarget(targetBinding, pmi.Target, out importedTarget))
{
result.Add(new Step242SemanticPmiHole($"{targetSolid}.{pmi.Name}", pmi.Value.Value, null, $"imported_canonical_face:{importedTarget}", tolerancePlus, toleranceMinus) { Name = pmi.Name });
}
}
+ else if (pmi.Kind == FirmamentV2PmiKind.Dimension && boundPmiByName.TryGetValue(pmi.Name, out var projectedRecord))
+ {
+ // Values are measured from the built body; every listed feature must agree.
+ var projections = composeFeature is null || body is null ? []
+ : projectedRecord.Targets.Select(t => ProjectComposeParameter(composeFeature, body, correspondence, t)).ToArray();
+ var resolved = projections.Length == projectedRecord.Targets.Count && projections.All(p => p is not null)
+ && projections.Select(p => (p!.Kind, Math.Round(p.Value, 9))).Distinct().Count() == 1;
+ var first = resolved ? projections[0]! : null;
+ var tolerance = projectedRecord.DimensionTolerance;
+ // One aspect per record: the feature, then the record name (features carry several dimensions).
+ result.Add(new Step242SemanticPmiDimension("compose:" + string.Join("+", projectedRecord.Targets.Select(t => t[..t.LastIndexOf('.')])) + "#" + pmi.Name,
+ pmi.Name, first?.Kind ?? "unresolved", first?.Value ?? 0, tolerance?.Plus, tolerance?.Minus,
+ resolved && projections.Sum(p => p!.Count) > 1 ? projections.Sum(p => p!.Count) : null)
+ {
+ StandardKind = first?.Kind switch { "diameter" => "diameter", "radius" => "radius", null => "unresolved",
+ _ => projections.Length == 1 && first.Ends is not null ? "linear distance" : null },
+ GeometricFaceIds = resolved ? projections.SelectMany(p => p!.Faces).Distinct().Order().ToArray() : [-1],
+ LocationFaces = resolved && projections.Length == 1 && first!.Ends is { } ends ? ends : null
+ });
+ }
+ else if (pmi.Kind == FirmamentV2PmiKind.Location && boundPmiByName.TryGetValue(pmi.Name, out var locationRecord) && locationRecord.From is { } fromFace)
+ {
+ var location = composeFeature is null || body is null ? null
+ : ProjectComposeLocation(composeFeature, body, correspondence, explicitFeatureIds ?? new Dictionary<string, string>(), targetSolid, fromFace, locationRecord.Targets[0], locationRecord.Basic);
+ var tolerance = locationRecord.DimensionTolerance;
+ result.Add(new Step242SemanticPmiDimension("compose:" + locationRecord.Targets[0] + "#" + pmi.Name, pmi.Name, location?.Kind ?? "unresolved", location?.Value ?? 0, tolerance?.Plus, tolerance?.Minus)
+ {
+ StandardKind = "linear distance",
+ GeometricFaceIds = location?.Faces ?? [-1],
+ LocationFaces = location?.Ends
+ });
+ }
else if (pmi.Kind == FirmamentV2PmiKind.Note && boundPmiByName.TryGetValue(pmi.Name, out var note) && note.Text is { } text)
{
result.Add(new Step242SemanticPmiNote(pmi.Name, targetSolid, text));
@@ -2997,6 +3037,27 @@ public static partial class FirmamentBuildAndExport
}).ToArray();
}
+ /// <summary>A hole callout's counterbore, projected from construction: diameter and depth on the counterbore walls.</summary>
+ private static IEnumerable<Step242SemanticPmi> CounterboreCallout(string name, IReadOnlyList<string> holes,
+ PrismaticProfileCompositionFeature? feature, SemanticTopologyCorrespondence? correspondence)
+ {
+ var counterbores = holes.Select(h => (feature?.CounterboreHoles ?? []).FirstOrDefault(c => c.Name == h)).ToArray();
+ if (counterbores.All(c => c is null)) yield break; // a plain shaft callout has nothing more to say
+ var alike = counterbores.All(c => c is not null)
+ && counterbores.Select(c => (Math.Round(c!.CounterboreDiameter, 9), Math.Round(c.CounterboreDepth, 9))).Distinct().Count() == 1;
+ var faces = alike ? (correspondence?.Descendants ?? []).Where(d => d.Face.HasValue && d.Role == SemanticTopologyRole.HoleCounterboreWallFace
+ && counterbores.Any(c => d.SourceStableId == c!.StableId || d.ParentStableId == c!.StableId))
+ .Select(d => d.Face!.Value.Value).Distinct().Order().ToArray() : [];
+ int[] attached = faces.Length > 0 ? faces : [-1];
+ var quantity = holes.Count > 1 ? holes.Count : (int?)null;
+ var first = counterbores[0];
+ var target = "compose:" + string.Join("+", holes) + "#" + name;
+ yield return new Step242SemanticPmiDimension(target + ".CounterboreDiameter", name + ".CounterboreDiameter", "counterbore diameter", first?.CounterboreDiameter ?? 0, null, null, quantity)
+ { StandardKind = "diameter", GeometricFaceIds = attached };
+ yield return new Step242SemanticPmiDimension(target + ".CounterboreDepth", name + ".CounterboreDepth", "counterbore depth", first?.CounterboreDepth ?? 0, null, null, quantity)
+ { StandardKind = null, GeometricFaceIds = attached };
+ }
+
private static KernelResult<bool> ValidateImportedPmiTargets(IReadOnlyList<Step242SemanticPmi> items, BrepBody body)
{
foreach (var item in items)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index f44ce769..d54e5821 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -295,7 +295,7 @@ public sealed record FirmamentV2SemanticHoleDecl(
FirmamentV2SemanticHoleTermination? Termination = null,
IReadOnlyList<FirmamentV2AuthoredField>? AuthoredFields = null);
public enum FirmamentV2PmiKind { HoleDiameter, DatumPlane, Distance, Flatness, Parallel, Perpendicular, Coplanar,
- Straightness, Roundness, Cylindricity, Parallelism, Perpendicularity, Angularity, Position, LineProfile, SurfaceProfile, CircularRunout, TotalRunout, Note }
+ Straightness, Roundness, Cylindricity, Parallelism, Perpendicularity, Angularity, Position, LineProfile, SurfaceProfile, CircularRunout, TotalRunout, Note, Dimension, Location }
public sealed record FirmamentV2PmiDecl(string Name, FirmamentV2PmiKind Kind, string Target, double? Value = null);
public sealed record FirmamentV2PmiBlock(IReadOnlyList<FirmamentV2PmiRecord> Records, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2PmiRecord(FirmamentV2PmiKind Kind, string Name, IReadOnlyDictionary<string, FirmamentV2PmiField> Fields, FirmamentV2SourceSpan SourceSpan, FirmamentV2BoundPmiRecord? Bound = null, FirmamentV2PmiProjection? Projection = null);
@@ -308,6 +308,11 @@ public sealed record FirmamentV2BoundPmiRecord(FirmamentV2PmiKind Kind, string N
public string? ZoneForm { get; init; }
/// <summary>Text of a part-level <c>Note</c>, such as material or general tolerances.</summary>
public string? Text { get; init; }
+ /// <summary>A <c>HoleCallout</c>: the hole size plus its counterbore or countersink, projected from construction.</summary>
+ public bool Callout { get; init; }
+ /// <summary>A <c>Location</c> written <c>origin: face(..) to: feature</c>; <c>basic: true</c> makes it theoretically exact.</summary>
+ public string? From { get; init; }
+ public bool Basic { get; init; }
}
/// <summary>Reusable, validated dimensional intent. Only equality of a semantic feature property
/// to a length expectation is admitted in Preview 1.</summary>
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 5063d1db..8eb0a867 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1302,7 +1302,8 @@ public static partial class FirmamentV2Parser
};
var (compositionPmi, compositionPmiBlock, compositionBoundPmi) = ParsePmi(
source, compositionSolids, [], [], statics, [], diagnostics, (feature.ShaftHoles ?? []).Select(hole => hole.Name).Concat((feature.CounterboreHoles ?? []).Select(hole => hole.Name)).Concat((feature.CountersinkHoles ?? []).Select(hole => hole.Name)),
- FirmamentBuildAndExport.ComposeOperationCapTargets(feature));
+ FirmamentBuildAndExport.ComposeOperationCapTargets(feature).Concat(Regex.Matches(body, @"\bEdgeFinish(?:<\w+>)?\s+(?<name>[A-Za-z_]\w*)\s*\{")
+ .SelectMany(m => new[] { $"param:{m.Groups["name"].Value}.Distance", $"param:{m.Groups["name"].Value}.Radius" })));
// Geometry capability belongs to the source-bound edge-finish planner;
// a curved Profile is not a syntax error. Normal validation builds it.
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
@@ -2418,7 +2419,13 @@ public static partial class FirmamentV2Parser
ValidatePmiFieldSet(kindRaw, name, fields, diagnostics);
var record = new FirmamentV2PmiRecord(kind, name, fields, new FirmamentV2SourceSpan(open + 1 + em.Index, entryClose - em.Index + 1));
records.Add(record);
- if (!TryBindPmiRecord(record, solids, modifyBlocks, regionByTarget, aliases, holeNames, letMap, recordMap, knownDatums, diagnostics, out var b)) continue;
+ var before = diagnostics.Count;
+ var admitted = TryBindPmiRecord(record, solids, modifyBlocks, regionByTarget, aliases, holeNames, letMap, recordMap, knownDatums, diagnostics, out var b);
+ // Bare record codes become located, readable diagnostics at this record; the bare code stays for callers that test it.
+ foreach (var code in diagnostics.Skip(before).Where(c => !c.Contains(": ", StringComparison.Ordinal)).Distinct().ToArray())
+ if (PmiRecordMessage(code, kindRaw) is { } message) diagnostics.Add($"{code.Split(':')[0]}:{name}: {message}");
+ if (!admitted) continue;
+ if (em.Groups["kind"].Value == "HoleCallout") b = b with { Callout = true };
bound.Add(b);
if (kind == FirmamentV2PmiKind.DatumPlane) knownDatums.Add(name);
if (b.Targets.Count > 0)
@@ -2426,7 +2433,7 @@ public static partial class FirmamentV2Parser
}
var block = new FirmamentV2PmiBlock(records, new FirmamentV2SourceSpan(match.Index, close - match.Index + 1));
- var boundBlock = new FirmamentV2BoundPmiBlock(bound.Where(r => r.Kind == FirmamentV2PmiKind.DatumPlane).ToArray(), bound.Where(r => r.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance).ToArray(), bound.Where(r => r.Kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance)).ToArray(), diagnostics.Where(d => d.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray());
+ var boundBlock = new FirmamentV2BoundPmiBlock(bound.Where(r => r.Kind == FirmamentV2PmiKind.DatumPlane).ToArray(), bound.Where(r => r.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance or FirmamentV2PmiKind.Dimension or FirmamentV2PmiKind.Location).ToArray(), bound.Where(r => r.Kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance or FirmamentV2PmiKind.Dimension or FirmamentV2PmiKind.Location)).ToArray(), diagnostics.Where(d => d.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray());
return (legacy, block, boundBlock);
}
@@ -2448,10 +2455,37 @@ public static partial class FirmamentV2Parser
return fields;
}
+ /// <summary>What a bare PMI record diagnostic means, in words, for the record that raised it.</summary>
+ private static string? PmiRecordMessage(string code, string kind) => code.Split(':')[0] switch
+ {
+ PmiTargetUnresolved or PmiInvalidTarget => code.Contains(':')
+ ? $"'{code[(code.IndexOf(':') + 1)..]}' is not a target this record can use"
+ : "the target does not name a face, hole or Compose feature of this part. Use face(-Z), face(hub.Top), a hole name or a list of holes",
+ PmiTargetMissing => "the record needs a target",
+ PmiDiameterInvalid => "the diameter must be a positive length (value: 8mm, or dimension: a toleranced Static)",
+ PmiDimensionTypeMismatch => "dimension must name a toleranced Length Static, such as Static bore: Length = 22mm tol +0.021mm -0mm",
+ PmiDimensionMissingTolerance => "a size needs a tolerance: tolerance: PlusMinus(..) or dimension: a toleranced Static",
+ PmiToleranceTypeMismatch => "the tolerance must be a length such as 0.02mm",
+ PmiUnknownDatum => "a datum it references is not declared above it",
+ PmiMissingRequiredField => $"a required field is missing for {kind}",
+ PmiUnknownField => $"a field is not one {kind} accepts",
+ PmiDuplicateField => "a field is written twice",
+ "firmament-v2-pmi-datum-precedence-invalid" => "datumRefs lists up to three distinct datums, primary first",
+ "firmament-v2-pmi-datum-not-applicable" => "form controls take no datums; orientation, location and runout controls need them",
+ "firmament-v2-pmi-zone-form-invalid" => "zone is Cylindrical, Spherical or BetweenSurfaces",
+ "firmament-v2-pmi-modifier-invalid" => "modifiers are distinct and from MaximumMaterial, LeastMaterial, FreeState, CommonZone, Statistical",
+ HoleWallUnknownHole => "face(H.Wall) names a hole that is not in a Modify block; on a Compose body target the hole by name (target: bore)",
+ HoleWallNotHole => "face(H.Wall) names something that is not a hole",
+ HoleWallAmbiguous => "the hole name is declared in more than one Modify block",
+ HoleWallConsumerInvalid => "only sizes and geometric controls can target a hole wall",
+ _ => null
+ };
+
private static string NormalizePmiKind(string raw) => raw switch
{
"Datum" => "datum",
"HoleDiameter" => "diameter",
+ "HoleCallout" => "diameter",
"Distance" => "distance",
"Flatness" => "flatness",
"Parallel" => "parallel",
@@ -2462,6 +2496,9 @@ public static partial class FirmamentV2Parser
private static string NormalizePmiField(string raw) => raw switch
{
+ "Origin" => "origin",
+ "To" => "to",
+ "Basic" => "basic",
"Text" => "text",
"Target" => "target",
"TargetA" => "targetA",
@@ -2484,6 +2521,18 @@ public static partial class FirmamentV2Parser
private static void ValidatePmiFieldSet(string kind, string name, IReadOnlyDictionary<string,FirmamentV2PmiField> fields, List<string> diagnostics)
{
+ if (kind == "Dimension")
+ {
+ if (!fields.ContainsKey("target")) diagnostics.Add($"{PmiMissingRequiredField}:{name}: Dimension requires target, a construction parameter such as pocket.Depth");
+ foreach (var f in fields.Keys.Where(f => f is not ("target" or "dimension" or "tolerance"))) diagnostics.Add($"{PmiUnknownField}:{name}.{f}");
+ return;
+ }
+ if (kind == "Location")
+ {
+ foreach (var f in new[] { "origin", "to" }.Where(f => !fields.ContainsKey(f))) diagnostics.Add($"{PmiMissingRequiredField}:{name}: Location requires {f}");
+ foreach (var f in fields.Keys.Where(f => f is not ("origin" or "to" or "basic" or "dimension" or "tolerance"))) diagnostics.Add($"{PmiUnknownField}:{name}.{f}");
+ return;
+ }
if (kind == "Note")
{
if (!fields.ContainsKey("text")) diagnostics.Add($"{PmiMissingRequiredField}:{name}: Note requires text");
@@ -2502,6 +2551,45 @@ public static partial class FirmamentV2Parser
private static bool TryBindPmiRecord(FirmamentV2PmiRecord r, Dictionary<string,FirmamentV2SolidBinding> solids, IReadOnlyList<FirmamentV2ModifyBlock> modifyBlocks, IReadOnlyDictionary<string,FirmamentV2RecognizedRegion> regions, HashSet<string> aliases, HashSet<string> holeNames, IReadOnlyDictionary<string,FirmamentV2BoundLet> lets, IReadOnlyDictionary<string,FirmamentV2BoundLetRecord> records, HashSet<string> datums, List<string> diagnostics, out FirmamentV2BoundPmiRecord bound)
{
bound=null!;
+ FirmamentV2Tolerance? ProjectedTolerance()
+ {
+ if (Field(r, "dimension") is string d)
+ {
+ var b = ResolveBoundLet(d, lets, records);
+ if (b is null || b.Type != FirmamentV2PrimitiveType.Length || b.Tolerance is null)
+ { diagnostics.Add($"{PmiDimensionTypeMismatch}:{r.Name}: dimension must name a toleranced Length Static"); return null; }
+ return b.Tolerance;
+ }
+ return Field(r, "tolerance") is string t && TryParseToleranceLiteral(NormalizePmiLengthLiteral(t), diagnostics, out var tol) ? tol : null;
+ }
+ if (r.Kind == FirmamentV2PmiKind.Dimension)
+ {
+ // A projected dimension names construction parameters; the compiler supplies the value.
+ var raw = Field(r, "target") ?? "";
+ var listed = raw.TrimStart().StartsWith('[') ? PmiNames(raw.Replace(".", "__DOT__"), diagnostics).Select(n => n.Replace("__DOT__", ".")).ToArray() : [raw.Trim()];
+ foreach (var t in listed.Where(t => !aliases.Contains("param:" + t)))
+ diagnostics.Add($"{PmiTargetUnresolved}:{r.Name}: '{t}' is not a dimensionable parameter of this part (for example pocket.Depth, hub.Diameter or stock.Height)");
+ if (listed.Length == 0 || listed.Distinct(StringComparer.Ordinal).Count() != listed.Length
+ || listed.Select(t => t[(t.LastIndexOf('.') + 1)..]).Distinct().Count() != 1)
+ diagnostics.Add($"{PmiInvalidTarget}:{r.Name}: a parameter list names the same parameter of distinct features");
+ var projected = ProjectedTolerance();
+ if (diagnostics.Any(d => d.Contains($":{r.Name}:", StringComparison.Ordinal))) return false;
+ bound = new(r.Kind, r.Name, listed, null, projected, null, [], r.SourceSpan) { DimensionOrigins = [] };
+ return true;
+ }
+ if (r.Kind == FirmamentV2PmiKind.Location && Field(r, "origin") is { } from)
+ {
+ var to = (Field(r, "to") ?? "").Trim();
+ if (!FaceSelectorRegex.IsMatch(from.Trim())) diagnostics.Add($"{PmiInvalidTarget}:{r.Name}: origin must be an axis face such as face(-X)");
+ if (!holeNames.Contains(to) && !aliases.Contains("op:" + to)) diagnostics.Add($"{PmiTargetUnresolved}:{r.Name}: '{to}' is not a hole, boss or pocket of this part");
+ var basic = Field(r, "basic") is { } flag ? flag.Trim() switch { "true" => true, "false" => false, _ => (bool?)null } : false;
+ if (basic is null) diagnostics.Add($"{PmiInvalidTarget}:{r.Name}: basic is true or false");
+ var projected = ProjectedTolerance();
+ if (basic == true && projected is not null) diagnostics.Add($"{PmiInvalidTarget}:{r.Name}: a basic dimension has no tolerance");
+ if (diagnostics.Any(d => d.Contains($":{r.Name}:", StringComparison.Ordinal))) return false;
+ bound = new(r.Kind, r.Name, [to], null, projected, null, [], r.SourceSpan) { From = from.Trim(), Basic = basic == true };
+ return true;
+ }
if (r.Kind == FirmamentV2PmiKind.Note)
{
// A part-level note: JSON string escapes, no control characters, never empty.
@@ -2529,6 +2617,7 @@ public static partial class FirmamentV2Parser
diagnostics.Add($"{PmiTargetUnresolved}:{r.Name}: '{name}' is not a hole of this part");
targets = listed.ToArray();
}
+ var composeWalls = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var t in holeSet ? [] : targets)
{
if (!FirmamentV2HoleWallSelector.TryParse(t, out var holeName))
@@ -2538,10 +2627,13 @@ public static partial class FirmamentV2Parser
}
if (r.Kind != FirmamentV2PmiKind.HoleDiameter && Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(r.Kind.ToString()) is null) { diagnostics.Add($"{HoleWallConsumerInvalid}:{r.Name}"); continue; }
var owners = modifyBlocks.Where(block => block.SemanticHoles.Any(hole => hole.Name == holeName)).Select(block => block.TargetSolid).Distinct(StringComparer.Ordinal).ToArray();
+ // A Compose hole's wall is the hole itself as a target: its shaft walls.
+ if (owners.Length == 0 && holeNames.Contains(holeName)) { composeWalls[t] = holeName; continue; }
if (owners.Length > 1) diagnostics.Add($"{HoleWallAmbiguous}:{holeName}");
else if (owners.Length == 0) diagnostics.Add($"{(solids.ContainsKey(holeName) ? HoleWallNotHole : HoleWallUnknownHole)}:{holeName}");
else wallTarget = new(holeName, owners[0]);
}
+ if (composeWalls.Count > 0) { targets = targets.Select(t => composeWalls.GetValueOrDefault(t, t)).ToArray(); if (target is not null) target = composeWalls.GetValueOrDefault(target, target); }
FirmamentV2LiteralValue? dim=null; FirmamentV2Tolerance? dimTol=null; FirmamentV2LiteralValue? ctlTol=null; var datumRefs=new List<string>();
if (r.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance)
{
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs
index 0ce13612..3fabbb0e 100644
--- a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs
@@ -12,6 +12,8 @@ namespace Aetheris.Kernel.Firmament.Visualization;
internal sealed class PmiCanvas
{
public List<(double X, double Y)[]> Lines { get; } = [];
+ /// <summary>Glyph outlines, kept apart from drafting lines: filled text needs no outline in a GLB.</summary>
+ public List<(double X, double Y)[]> GlyphLines { get; } = [];
public List<(double X, double Y)> Fill { get; } = [];
public List<int> FillIndices { get; } = [];
public List<(double X, double Y)> Panel { get; } = [];
@@ -45,7 +47,7 @@ internal sealed class PmiCanvas
FillNonZero(glyph.Select(c => c.Points.Select(p => (x + p.X, y + p.Y)).ToArray()).ToArray());
// Outlines too: line-only consumers (and very small zoom levels) still read the text.
foreach (var contour in contours)
- Lines.Add(contour.Points.Append(contour.Points[0]).Select(p => (x + p.X, y + p.Y)).ToArray());
+ GlyphLines.Add(contour.Points.Append(contour.Points[0]).Select(p => (x + p.X, y + p.Y)).ToArray());
return width;
}
@@ -96,6 +98,7 @@ internal sealed class PmiCanvas
public void Append(PmiCanvas other, double dx, double dy)
{
Lines.AddRange(other.Lines.Select(l => l.Select(p => (p.X + dx, p.Y + dy)).ToArray()));
+ GlyphLines.AddRange(other.GlyphLines.Select(l => l.Select(p => (p.X + dx, p.Y + dy)).ToArray()));
var o = Fill.Count; Fill.AddRange(other.Fill.Select(p => (p.X + dx, p.Y + dy))); FillIndices.AddRange(other.FillIndices.Select(i => i + o));
o = Panel.Count; Panel.AddRange(other.Panel.Select(p => (p.X + dx, p.Y + dy))); PanelIndices.AddRange(other.PanelIndices.Select(i => i + o));
}
@@ -143,6 +146,38 @@ internal static class PmiDrafting
return new(c, width, height);
}
+ /// <summary>
+ /// A callout line mixing text with drafting symbols drawn as vectors: <c>{CB}</c> counterbore,
+ /// <c>{DEPTH}</c> depth. For example <c>"{CB}Ø11 {DEPTH}6.5"</c>.
+ /// </summary>
+ public static PmiBlock CalloutLine(string text, double h)
+ {
+ var c = new PmiCanvas();
+ var pad = .35 * h; var height = 1.7 * h; var baseline = .45 * h;
+ var x = pad;
+ foreach (var part in System.Text.RegularExpressions.Regex.Split(text, "({CB}|{DEPTH})"))
+ {
+ if (part.Length == 0) continue;
+ if (part == "{CB}")
+ {
+ // Counterbore: an open-topped square bracket.
+ var w = .8 * h; c.Line((x, baseline + .85 * h), (x, baseline), (x + w, baseline), (x + w, baseline + .85 * h)); x += w + .3 * h;
+ }
+ else if (part == "{DEPTH}")
+ {
+ // Depth: a downward arrow standing on a bar.
+ var w = .7 * h; var mid = x + w / 2;
+ c.Line((mid, baseline + .9 * h), (mid, baseline + .05 * h)); c.Line((x, baseline), (x + w, baseline));
+ c.Triangle((mid, baseline + .05 * h), (mid - .22 * h, baseline + .45 * h), (mid + .22 * h, baseline + .45 * h));
+ x += w + .3 * h;
+ }
+ else x += c.Text(part, x, baseline, h);
+ }
+ var width = x + pad;
+ c.PanelRect(0, 0, width, height);
+ return new(c, width, height);
+ }
+
public static PmiBlock DatumBox(string label, double h)
{
var c = new PmiCanvas();
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
index 58a28f95..16dc5c79 100644
--- a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
@@ -20,6 +20,10 @@ public sealed record PmiDisplayAnnotation(string Id, string Kind, string Name, s
[System.Text.Json.Serialization.JsonIgnore] public PmiDisplayMesh? TextFill { get; init; }
/// <summary>Opaque backing panels behind text so callouts stay legible over a translucent part.</summary>
[System.Text.Json.Serialization.JsonIgnore] public PmiDisplayMesh? Panel { get; init; }
+ /// <summary>Drafting lines without glyph outlines (leaders, frames, dimension lines) for renderers that fill text.</summary>
+ [System.Text.Json.Serialization.JsonIgnore] public IReadOnlyList<double[][]>? DraftingLines { get; init; }
+ /// <summary>Leader colour (linear RGB) tying a callout to its feature; null draws the default ink.</summary>
+ [System.Text.Json.Serialization.JsonIgnore] public double[]? LeaderColor { get; init; }
}
/// <summary>Triangles in Z-up millimetres; three coordinates per position.</summary>
@@ -62,10 +66,13 @@ public static class PmiDisplayProjection
// 1. Resolve every semantic record to its exact supports.
var specs = new List<Spec>();
var notes = new List<Step242SemanticPmiInspectionItem>();
+ var projected = new List<Step242SemanticPmiInspectionItem>();
foreach (var item in inspection.Items)
{
// Part notes read back as AP242 annotations (material, general tolerances, finish).
if (item.Kind == "Annotation") { notes.Add(item); continue; }
+ // Sizes and locations projected from construction are drawn on their features below.
+ if (item.Kind == "Dimension" && item.Target.StartsWith("compose:", StringComparison.Ordinal)) { projected.Add(item); continue; }
if (!item.PresentationSupported)
throw new InvalidOperationException($"pmi-display-parameters-unsupported: '{item.Name}' retains advanced semantic parameters that this 3D label path cannot yet display completely.");
if (item.Kind is not ("Datum" or "Diameter" or "Dimension") && Step242GeometricToleranceKinds.Find(item.Kind) is null)
@@ -113,27 +120,67 @@ public static class PmiDisplayProjection
// model). They share one horizontal plane at the top of the vertical datum faces.
layout.DimensionLevel = datumFaces.Values.Where(d => d.Feature is PlanarFeature { } f && Math.Abs(f.Normal.Z) < 1e-7)
.SelectMany(d => d.Targets.SelectMany(t => t.Positions)).Select(p => p.Z).DefaultIfEmpty(maxZ).Max();
- var basics = BasicDimensions(specs, datumFaces, layout);
+ DisplayFaceMeshPatch[] Patches(Step242SemanticPmiInspectionItem item)
+ {
+ var found = item.GeometricFaceEntityIds.Where(id => sourceFaces.TryGetValue(id, out var face) && patches.ContainsKey(face))
+ .Select(id => patches[sourceFaces[id]]).ToArray();
+ if (found.Length == 0 || found.Length != item.GeometricFaceEntityIds.Count)
+ throw new InvalidOperationException($"pmi-display-target-unresolved: '{item.Name}' has no complete geometric face association.");
+ return found;
+ }
+ static string FeatureKey(Step242SemanticPmiInspectionItem item) { var t = item.Target["compose:".Length..]; var hash = t.IndexOf('#'); return hash < 0 ? t : t[..hash]; }
+ var locations = new List<(int Owner, Vector3D Normal, double DatumOffset, Point3D Point, bool Boxed)>();
+ foreach (var item in projected.Where(i => i.DimensionKind?.StartsWith("location ", StringComparison.Ordinal) == true))
+ {
+ var words = item.DimensionKind!.Split(' ');
+ var n = words[1] switch { "-X" => new Vector3D(-1, 0, 0), "+X" => new Vector3D(1, 0, 0), "-Y" => new Vector3D(0, -1, 0), "+Y" => new Vector3D(0, 1, 0),
+ _ => throw new InvalidOperationException($"pmi-display-location-unsupported: '{item.Name}' runs from {words[1]}.") };
+ var faces = Patches(item);
+ var offsets = faces.Select(f => (Face: f, Plane: body.GetFaceSurface(f.FaceId).Plane)).ToArray();
+ // The origin is the extreme plane in that direction; the rest is the located feature.
+ var datumOffset = offsets.Where(f => f.Plane is { } p && p.Normal.ToVector().Dot(n) > 1 - 1e-8).Max(f => (f.Plane!.Value.Origin - Point3D.Origin).Dot(n));
+ var feature = offsets.Where(f => !(f.Plane is { } p && p.Normal.ToVector().Dot(n) > 1 - 1e-8 && Math.Abs((p.Origin - Point3D.Origin).Dot(n) - datumOffset) < 1e-7))
+ .SelectMany(f => f.Face.Positions).ToArray();
+ var point = new Point3D((feature.Min(p => p.X) + feature.Max(p => p.X)) / 2, (feature.Min(p => p.Y) + feature.Max(p => p.Y)) / 2, feature.Max(p => p.Z));
+ locations.Add((item.EntityId, n, datumOffset, point, words.Contains("basic")));
+ }
+ var basics = BasicDimensions(specs, datumFaces, locations, layout);
var dimensionPlane = new PmiPlane(new Point3D(0, 0, layout.DimensionLevel), new Vector3D(1, 0, 0), new Vector3D(0, 1, 0));
- // Notes occupy the lower right of the front plane; reserve it before placing datum callouts there.
var notesBlock = notes.Count > 0 ? PmiDrafting.Notes(notes.Select(n => n.Text ?? "").ToArray(), .8 * height) : null;
- if (notesBlock is not null)
- layout.Reserve(new PmiPlane(new Point3D(0, minY, 0), new Vector3D(1, 0, 0), new Vector3D(0, 0, 1)),
- (maxX - notesBlock.Width, minZ - 3 * height - layout.DimensionDepth - notesBlock.Height, maxX, minZ - 3 * height - layout.DimensionDepth));
+
+ var attachedTo = new Dictionary<int, int>(); // records drawn as part of another record's line
+ // Each feature's leaders and dimensions share a colour, so a callout reads with its feature in 3D.
+ double[][] palette = [[.1, .36, .78], [.86, .5, .04], [.12, .56, .3], [.55, .24, .7], [.05, .55, .6], [.75, .2, .3]];
+ var nextColor = 0;
+ var featureColors = new Dictionary<string, double[]>(StringComparer.Ordinal);
// Holes first, so planar datum symbols find free space outside dimensions and hole callouts.
foreach (var group in groups.OrderBy(g => g[0].Feature is HoleFeature ? 0 : 1).ThenByDescending(g => g[0].Feature is HoleFeature hole ? hole.Cylinders.Length : 0))
{
var ordered = group.OrderBy(s => s.Item.Kind switch { "Diameter" or "Dimension" => 0, "Datum" => 3, "Position" => 2, _ => 1 }).ToArray();
- var blocks = ordered.Select(s => (Spec: s, Block: s.Item.Kind switch
+ var blockList = ordered.Select(s => (Spec: s, Block: s.Item.Kind switch
{
"Diameter" or "Dimension" => PmiDrafting.TextBlock(PmiDrafting.Size(s.Item), height),
"Datum" => PmiDrafting.DatumBox(s.Item.Name, height),
_ => PmiDrafting.ControlFrame(s.Item.Kind, PmiDrafting.ZonePrefix(s.Item.ZoneForms), s.Item.Value!.Value,
s.Item.Modifiers, s.Item.DatumReferenceFrames.Count > 0
? s.Item.DatumReferenceFrames.Select(f => string.Join("-", f.Labels)).ToArray() : s.Item.DatumReferences, height)
- })).ToArray();
+ })).ToList();
+ // A hole callout's counterbore line sits under its size: ⌴Ø11 ↧6.5.
+ var sizeName = ordered.FirstOrDefault(s => s.Item.Kind == "Diameter")?.Item.AuthoredName;
+ var extras = sizeName is null ? [] : projected.Where(p => p.Name.StartsWith(sizeName + ".Counterbore", StringComparison.Ordinal)).ToArray();
+ if (extras.Length > 0)
+ {
+ var cbDiameter = extras.FirstOrDefault(e => e.Name.EndsWith(".CounterboreDiameter", StringComparison.Ordinal));
+ var cbDepth = extras.FirstOrDefault(e => e.Name.EndsWith(".CounterboreDepth", StringComparison.Ordinal));
+ var text = (cbDiameter is null ? "" : "{CB}Ø" + PmiDrafting.Number(cbDiameter.Value!.Value)) + (cbDepth is null ? "" : " {DEPTH}" + PmiDrafting.Number(cbDepth.Value!.Value));
+ var owner = cbDiameter ?? cbDepth!;
+ blockList.Insert(1, (new Spec(owner, ordered[0].Targets, ordered[0].Feature), PmiDrafting.CalloutLine(text.Trim(), height)));
+ foreach (var other in extras.Where(e => e != owner)) attachedTo[other.EntityId] = owner.EntityId;
+ foreach (var e in extras) projected.Remove(e);
+ }
+ var blocks = blockList.ToArray();
var gap = .35 * height;
var stackHeight = blocks.Sum(b => b.Block.Height) + gap * (blocks.Length - 1);
var stackWidth = blocks.Max(b => b.Block.Width);
@@ -143,6 +190,7 @@ public static class PmiDisplayProjection
PlanarFeature planar => layout.PlacePlanarCallout(planar, ordered[0], stackWidth, stackHeight, ordered.Any(s => s.Item.Kind == "Datum")),
_ => throw new InvalidOperationException()
};
+ var groupColor = group[0].Feature is HoleFeature ? palette[nextColor++ % palette.Length] : null;
var y = placed.Y + stackHeight;
for (var i = 0; i < blocks.Length; i++)
{
@@ -153,19 +201,105 @@ public static class PmiDisplayProjection
if (i == 0) canvas.Append(placed.Leader, 0, 0);
y -= gap;
var emitted = Emit(spec, canvas, placed.Plane, placed.Anchor, height, layout.Lift,
- basics.GetValueOrDefault(spec.Item.EntityId), dimensionPlane);
+ basics.GetValueOrDefault(spec.Item.EntityId), dimensionPlane, groupColor);
if (i == 0 && placed.Drop > 1e-6)
- emitted = emitted with { Lines = [[P(placed.Anchor), P(placed.Anchor + new Vector3D(0, 0, placed.Drop))], .. emitted.Lines] };
+ {
+ double[][] drop = [P(placed.Anchor), P(placed.Anchor + new Vector3D(0, 0, placed.Drop))];
+ emitted = emitted with { Lines = [drop, .. emitted.Lines], DraftingLines = [drop, .. emitted.DraftingLines!] };
+ }
output[spec.Item.EntityId] = i > 0 ? emitted with { Target = null } : emitted;
}
}
- // 3. General notes: one block in the front plane below the part, clear of the datum callouts.
+ // 3. Sizes projected from construction, drawn on their features.
+ foreach (var feature in projected.Where(p => p.DimensionKind?.StartsWith("location ", StringComparison.Ordinal) != true)
+ .GroupBy(FeatureKey).OrderBy(g => g.Key, StringComparer.Ordinal))
+ {
+ var items = feature.ToArray();
+ var faces = items.SelectMany(Patches).ToArray();
+ if (items.All(i => i.DimensionKind is "thickness" or "length" or "width"))
+ {
+ foreach (var item in items) output[item.EntityId] = OverallDimension(item, Patches(item), layout, height);
+ continue;
+ }
+ // A callout on the feature: one line per characteristic, size first.
+ string Prefix(Step242SemanticPmiInspectionItem i) => i.Quantity is > 1 ? $"{i.Quantity}X " : "";
+ var length = items.FirstOrDefault(i => i.DimensionKind == "length"); var width = items.FirstOrDefault(i => i.DimensionKind == "width");
+ var lines = new List<(Step242SemanticPmiInspectionItem Item, string Text)>();
+ if (length is not null && width is not null)
+ { lines.Add((length, $"{Prefix(length)}{PmiDrafting.Number(length.Value!.Value)} × {PmiDrafting.Number(width.Value!.Value)}")); attachedTo[width.EntityId] = length.EntityId; }
+ foreach (var item in items.Where(i => i != length && i != width || length is null || width is null).OrderBy(i => i.DimensionKind switch
+ { "diameter" => 0, "length" or "width" => 1, "depth" => 2, "height" => 3, "radius" => 4, _ => 5 }))
+ {
+ if (attachedTo.ContainsKey(item.EntityId) || lines.Any(l => l.Item == item)) continue;
+ var value = PmiDrafting.Number(item.Value!.Value);
+ lines.Add((item, item.DimensionKind switch
+ {
+ "diameter" => $"{Prefix(item)}Ø{value}",
+ "radius" => $"{Prefix(item)}R{value}",
+ "depth" => $"{{DEPTH}}{value}",
+ "height" => $"{value} HIGH",
+ "chamfer" => $"{Prefix(item)}{value} × 45°",
+ "length" => $"{Prefix(item)}{value} LONG",
+ "width" => $"{Prefix(item)}{value} WIDE",
+ var other => throw new InvalidOperationException($"pmi-display-kind-unsupported: projected {other} '{item.Name}' has no callout yet.")
+ }));
+ }
+ var blocks = lines.Select(l => (l.Item, Block: PmiDrafting.CalloutLine(l.Text, height))).ToArray();
+ var gap = .2 * height;
+ var stackHeight = blocks.Sum(b => b.Block.Height) + gap * (blocks.Length - 1);
+ var stackWidth = blocks.Max(b => b.Block.Width);
+ var diameterFaces = items.Where(i => i.DimensionKind == "diameter").SelectMany(Patches).ToArray();
+ var round = diameterFaces.Select(f => body.GetFaceSurface(f.FaceId).Cylinder).FirstOrDefault(c => c is not null);
+ var placed = layout.PlaceFeatureCallout(faces, items, center, stackWidth, stackHeight, points, round);
+ var featureColor = featureColors[feature.Key] = palette[nextColor++ % palette.Length];
+ var y = placed.Y + stackHeight;
+ for (var k = 0; k < blocks.Length; k++)
+ {
+ y -= blocks[k].Block.Height;
+ var canvas = new PmiCanvas();
+ canvas.Append(blocks[k].Block.Canvas, placed.X, y);
+ if (k == 0) canvas.Append(placed.Leader, 0, 0);
+ y -= gap;
+ var item = blocks[k].Item;
+ var lines3 = Lines3D(canvas, placed.Plane, 0).ToList();
+ var drafting = Draft3D(canvas, placed.Plane).ToList();
+ if (k == 0 && placed.Drop > 1e-6)
+ {
+ double[][] drop = [P(placed.Anchor), P(placed.Anchor + new Vector3D(0, 0, placed.Drop))];
+ lines3.Insert(0, drop); drafting.Insert(0, drop);
+ }
+ output[item.EntityId] = new PmiDisplayAnnotation("pmi:" + item.EntityId, "Dimension", item.Name, blocks[k].Block is var _ ? lines[k].Text.Replace("{DEPTH}", "↧").Replace("{CB}", "⌴") : "",
+ item.Value, item.TolerancePlus, item.ToleranceMinus, item.GeometricFaceEntityIds, P(placed.Anchor), P(placed.Plane.At(placed.X, y)), height, lines3)
+ { TextFill = Fill3D(canvas.Fill, canvas.FillIndices, placed.Plane, layout.Lift * 2), Panel = Fill3D(canvas.Panel, canvas.PanelIndices, placed.Plane, -layout.Lift),
+ DraftingLines = drafting, LeaderColor = featureColor };
+ }
+ }
+ foreach (var item in projected.Where(p => p.DimensionKind?.StartsWith("location ", StringComparison.Ordinal) == true))
+ {
+ var canvas = basics.GetValueOrDefault(item.EntityId) ?? throw new InvalidOperationException($"pmi-display-location-unsupported: '{item.Name}'.");
+ output[item.EntityId] = new PmiDisplayAnnotation("pmi:" + item.EntityId, "Dimension", item.Name, PmiDrafting.Number(item.Value!.Value),
+ item.Value, item.TolerancePlus, item.ToleranceMinus, item.GeometricFaceEntityIds, P(dimensionPlane.At(0, 0)), P(dimensionPlane.At(0, 0)), height,
+ Lines3D(canvas, dimensionPlane, 0))
+ { TextFill = Fill3D(canvas.Fill, canvas.FillIndices, dimensionPlane, layout.Lift * 2), Panel = Fill3D(canvas.Panel, canvas.PanelIndices, dimensionPlane, -layout.Lift),
+ DraftingLines = Draft3D(canvas, dimensionPlane),
+ LeaderColor = featureColors.FirstOrDefault(c => c.Key.Split('+').Contains(FeatureKey(item))).Value };
+ }
+ // Records drawn on another record's line keep their own entry, pointing at the same place.
+ foreach (var (attached, owner) in attachedTo)
+ {
+ var host = output[owner]; var item = inspection.Items.Single(i => i.EntityId == attached);
+ output[attached] = host with { Id = "pmi:" + attached, Kind = "Dimension", Name = item.Name, Value = item.Value, TolerancePlus = item.TolerancePlus,
+ ToleranceMinus = item.ToleranceMinus, StepFaceEntities = item.GeometricFaceEntityIds, Lines = [[host.Anchor, host.LabelPosition]], DraftingLines = [], TextFill = null, Panel = null, Target = null };
+ }
+
+ // 4. General notes: one block in the front plane below the part, clear of the datum callouts.
if (notes.Count > 0)
{
var plane = new PmiPlane(new Point3D(0, minY, 0), new Vector3D(1, 0, 0), new Vector3D(0, 0, 1));
var block = notesBlock!;
- var x = maxX - block.Width; var top = minZ - 3 * height - layout.DimensionDepth;
+ // Notes go last, below the part on the right, clear of every callout in the default view.
+ var (x, top) = layout.PlaceNotes(plane, block.Width, block.Height);
var canvas = new PmiCanvas();
canvas.Append(block.Canvas, x, top - block.Height);
var at = P(plane.At(x, top));
@@ -173,6 +307,7 @@ public static class PmiDisplayProjection
output[note.EntityId] = new PmiDisplayAnnotation("pmi:" + note.EntityId, "Note", note.Name, note.Text ?? "",
null, null, null, [], at, at, height, index == 0 ? Lines3D(canvas, plane, 0) : [[at, at]])
{
+ DraftingLines = index == 0 ? Draft3D(canvas, plane) : null,
TextFill = index == 0 ? Fill3D(canvas.Fill, canvas.FillIndices, plane, layout.Lift * 2) : null,
Panel = index == 0 ? Fill3D(canvas.Panel, canvas.PanelIndices, plane, -layout.Lift) : null
};
@@ -207,6 +342,18 @@ public static class PmiDisplayProjection
.Select(e => (e.IsClosed ? e.Points.Append(e.Points[0]) : e.Points).Select(P).ToArray()).ToArray();
}
+ private static PmiDisplayAnnotation OverallDimension(Step242SemanticPmiInspectionItem item, DisplayFaceMeshPatch[] faces, Layout layout, double height)
+ {
+ var text = (item.Quantity is > 1 ? $"{item.Quantity}X " : "") + PmiDrafting.Number(item.Value!.Value)
+ + (item.TolerancePlus is { } plus && item.ToleranceMinus is { } minus ? (Math.Abs(plus - minus) < 1e-12 ? $" ±{PmiDrafting.Number(plus)}" : $" +{PmiDrafting.Number(plus)}/-{PmiDrafting.Number(minus)}") : "");
+ var (canvas, plane) = layout.Overall(item.DimensionKind!, faces.SelectMany(f => f.Positions).ToArray(), text);
+ var anchor = canvas.Lines[0][0];
+ return new PmiDisplayAnnotation("pmi:" + item.EntityId, "Dimension", item.Name, text, item.Value, item.TolerancePlus, item.ToleranceMinus,
+ item.GeometricFaceEntityIds, P(plane.At(anchor.X, anchor.Y)), P(plane.At(anchor.X, anchor.Y)), height, Lines3D(canvas, plane, 0))
+ { TextFill = Fill3D(canvas.Fill, canvas.FillIndices, plane, layout.Lift * 2), Panel = Fill3D(canvas.Panel, canvas.PanelIndices, plane, -layout.Lift),
+ DraftingLines = Draft3D(canvas, plane) };
+ }
+
private abstract record Feature;
private sealed record PlanarFeature(Vector3D Normal, DisplayFaceMeshPatch[] Patches) : Feature;
private sealed record HoleFeature(CylinderSurface[] Cylinders, DisplayFaceMeshPatch[][] Walls) : Feature;
@@ -225,7 +372,7 @@ public static class PmiDisplayProjection
}
private static PmiDisplayAnnotation Emit(Spec spec, PmiCanvas canvas, PmiPlane plane, Point3D anchor, double height, double lift,
- PmiCanvas? dimensions, PmiPlane dimensionPlane)
+ PmiCanvas? dimensions, PmiPlane dimensionPlane, double[]? color = null)
{
var item = spec.Item;
var text = item.Kind switch
@@ -246,16 +393,20 @@ public static class PmiDisplayProjection
fill = Merge(fill, Fill3D(dimensions.Fill, dimensions.FillIndices, dimensionPlane, lift * 2));
panel = Merge(panel, Fill3D(dimensions.Panel, dimensions.PanelIndices, dimensionPlane, -lift));
}
+ var drafting = Draft3D(canvas, plane).Concat(dimensions is null ? [] : Draft3D(dimensions, dimensionPlane)).ToArray();
return new("pmi:" + item.EntityId, item.Kind, item.AuthoredName ?? item.Name, text, item.Value, item.TolerancePlus, item.ToleranceMinus,
item.GeometricFaceEntityIds, P(anchor), P(plane.At(label.X, label.Y)), height, lines)
- { Target = Highlight(spec, height), TextFill = fill, Panel = panel };
+ { Target = Highlight(spec, height), TextFill = fill, Panel = panel, DraftingLines = drafting, LeaderColor = color };
}
private static PmiDisplayMesh? Merge(PmiDisplayMesh? a, PmiDisplayMesh? b) => a is null ? b : b is null ? a
: new(a.Positions.Concat(b.Positions).ToArray(), a.Indices.Concat(b.Indices.Select(i => i + a.Positions.Length / 3)).ToArray());
private static IReadOnlyList<double[][]> Lines3D(PmiCanvas canvas, PmiPlane plane, double lift) =>
- canvas.Lines.Select(line => line.Select(p => P(plane.At(p.X, p.Y, lift))).ToArray()).ToArray();
+ canvas.Lines.Concat(canvas.GlyphLines).Select(line => line.Select(p => P(plane.At(p.X, p.Y, lift))).ToArray()).ToArray();
+
+ private static IReadOnlyList<double[][]> Draft3D(PmiCanvas canvas, PmiPlane plane) =>
+ canvas.Lines.Select(line => line.Select(p => P(plane.At(p.X, p.Y))).ToArray()).ToArray();
private static PmiDisplayMesh? Fill3D(List<(double X, double Y)> points, List<int> indices, PmiPlane plane, double lift) =>
indices.Count == 0 ? null : new(points.SelectMany(p => P(plane.At(p.X, p.Y, lift))).ToArray(), indices.ToArray());
@@ -278,13 +429,15 @@ public static class PmiDisplayProjection
}
/// <summary>
- /// Boxed basic dimensions from each planar datum referenced by a Position control to every
- /// controlled hole axis, drawn in the datum face's top plane as baseline dimensions.
+ /// Baseline dimensions in one horizontal plane: boxed basic dimensions from each planar datum a
+ /// Position control references to every controlled hole axis, and authored locations from an
+ /// axis face to a feature's centre. Equal values share a tier only when both are basic or both not.
/// </summary>
- private static Dictionary<int, PmiCanvas> BasicDimensions(IReadOnlyList<Spec> specs, IReadOnlyDictionary<string, Spec> datums, Layout layout)
+ private static Dictionary<int, PmiCanvas> BasicDimensions(IReadOnlyList<Spec> specs, IReadOnlyDictionary<string, Spec> datums,
+ IReadOnlyList<(int Owner, Vector3D Normal, double DatumOffset, Point3D Point, bool Boxed)> locations, Layout layout)
{
var result = new Dictionary<int, PmiCanvas>();
- var requests = new List<(Spec Owner, Vector3D Normal, double DatumOffset, Point3D Axis, string Datum)>();
+ var requests = new List<(int Owner, Vector3D Normal, double DatumOffset, Point3D Point, bool Boxed)>(locations);
foreach (var position in specs.Where(s => s.Item.Kind == "Position" && s.Feature is HoleFeature))
foreach (var label in position.Item.DatumReferences)
if (datums.TryGetValue(label, out var datum) && datum.Feature is PlanarFeature { } face && Math.Abs(face.Normal.Z) < 1e-7)
@@ -292,20 +445,21 @@ public static class PmiDisplayProjection
var origin = datum.Targets[0].Positions[0];
foreach (var cylinder in ((HoleFeature)position.Feature).Cylinders)
if (Math.Abs(cylinder.Axis.ToVector().Z) > 1 - 1e-7)
- requests.Add((position, face.Normal, (origin - Point3D.Origin).Dot(face.Normal), cylinder.Origin, label));
+ requests.Add((position.Item.EntityId, face.Normal, (origin - Point3D.Origin).Dot(face.Normal), cylinder.Origin, true));
}
int tiersX = 0, tiersY = 0;
foreach (var direction in requests.GroupBy(r => (Math.Round(r.Normal.X), Math.Round(r.Normal.Y))))
{
- var values = direction.Select(r => (r, Value: Math.Abs((r.Axis - Point3D.Origin).Dot(r.Normal) - r.DatumOffset)))
- .GroupBy(v => Math.Round(v.Value, 6)).Select(g => g.First()).OrderBy(v => v.Value).ToArray();
- for (var tier = 0; tier < values.Length; tier++)
+ var values = direction.Select(r => (r, Value: Math.Abs((r.Point - Point3D.Origin).Dot(r.Normal) - r.DatumOffset)))
+ .GroupBy(v => (Math.Round(v.Value, 6), v.r.Boxed, v.r.Owner)).Select(g => g.First()).OrderBy(v => v.Value).ToArray();
+ var tiers = values.Select(v => (Math.Round(v.Value, 6), v.r.Boxed)).Distinct().ToList();
+ foreach (var (request, value) in values)
{
- var (request, value) = values[tier];
- var canvas = result.TryGetValue(request.Owner.Item.EntityId, out var existing) ? existing : result[request.Owner.Item.EntityId] = new PmiCanvas();
- layout.BasicDimension(canvas, request.Normal, request.DatumOffset, request.Axis, value, tier);
+ var tier = tiers.IndexOf((Math.Round(value, 6), request.Boxed));
+ var canvas = result.TryGetValue(request.Owner, out var existing) ? existing : result[request.Owner] = new PmiCanvas();
+ layout.BasicDimension(canvas, request.Normal, request.DatumOffset, request.Point, value, tier, request.Boxed);
}
- if (Math.Abs(direction.Key.Item1) > .5) tiersX = Math.Max(tiersX, values.Length); else tiersY = Math.Max(tiersY, values.Length);
+ if (Math.Abs(direction.Key.Item1) > .5) tiersX = Math.Max(tiersX, tiers.Count); else tiersY = Math.Max(tiersY, tiers.Count);
}
layout.ReserveDimensionBands(tiersX, tiersY);
return result;
@@ -325,8 +479,25 @@ public static class PmiDisplayProjection
private static string Key(PmiPlane plane) => string.Create(CultureInfo.InvariantCulture,
$"{plane.N.X:0.###},{plane.N.Y:0.###},{plane.N.Z:0.###}");
- private bool Free(PmiPlane plane, (double X0, double Y0, double X1, double Y1) r, bool outsideBody)
+ // Labels in different planes can still overlap on screen. The default view looks from the front
+ // left, above; label rectangles are also kept apart in that view's projection.
+ private static readonly Vector3D ViewRight = Direction3D.Create(new Vector3D(0, 0, 1).Cross(new Vector3D(-1, -1.27, 1.1))).ToVector();
+ private static readonly Vector3D ViewUp = Direction3D.Create(new Vector3D(-1, -1.27, 1.1).Cross(ViewRight)).ToVector();
+ private readonly List<(double X0, double Y0, double X1, double Y1)> screen = [];
+ private static (double X0, double Y0, double X1, double Y1) Screen(PmiPlane plane, (double X0, double Y0, double X1, double Y1) r)
{
+ var corners = new[] { plane.At(r.X0, r.Y0), plane.At(r.X1, r.Y0), plane.At(r.X1, r.Y1), plane.At(r.X0, r.Y1) }
+ .Select(p => (X: (p - Point3D.Origin).Dot(ViewRight), Y: (p - Point3D.Origin).Dot(ViewUp))).ToArray();
+ return (corners.Min(c => c.X), corners.Min(c => c.Y), corners.Max(c => c.X), corners.Max(c => c.Y));
+ }
+
+ private bool Free(PmiPlane plane, (double X0, double Y0, double X1, double Y1) r, bool outsideBody, bool label = true)
+ {
+ if (label)
+ {
+ var v = Screen(plane, r); var gap = .6 * h;
+ if (screen.Any(o => !(v.X1 + gap <= o.X0 || v.X0 - gap >= o.X1 || v.Y1 + gap <= o.Y0 || v.Y0 - gap >= o.Y1))) return false;
+ }
if (outsideBody)
{
var (bx0, by0) = plane.Local(new Point3D(minX, minY, minZ)); var (bx1, by1) = plane.Local(new Point3D(maxX, maxY, maxZ));
@@ -338,8 +509,9 @@ public static class PmiDisplayProjection
return list.All(o => r.X1 + m <= o.X0 || r.X0 - m >= o.X1 || r.Y1 + m <= o.Y0 || r.Y0 - m >= o.Y1);
}
- private void Occupy(PmiPlane plane, (double X0, double Y0, double X1, double Y1) r)
+ private void Occupy(PmiPlane plane, (double X0, double Y0, double X1, double Y1) r, bool label = true)
{
+ if (label) screen.Add(Screen(plane, r));
if (!occupied.TryGetValue(Key(plane), out var list)) occupied[Key(plane)] = list = [];
list.Add(r);
}
@@ -347,13 +519,53 @@ public static class PmiDisplayProjection
/// <summary>Leader from the hole's visible rim, out and away from the part, with a horizontal shoulder.</summary>
public Placement PlaceHoleCallout(HoleFeature hole, Point3D center, double width, double height, Point3D[] bodyPoints)
{
- // The callout points at the hole nearest the default front-left view, and leaves the part
- // along whichever diagonal reaches free space soonest (outward from the part first).
+ // The callout points at the hole nearest the default front-left view.
var cylinder = hole.Cylinders.OrderBy(c => c.Origin.X + c.Origin.Y).First();
var r = cylinder.Radius;
var level = bodyPoints.Where(p => Math.Pow(p.X - cylinder.Origin.X, 2) + Math.Pow(p.Y - cylinder.Origin.Y, 2) <= Math.Pow(2.2 * r + h, 2)).Max(p => p.Z);
+ // The callout belongs to the controlled wall: when it starts below the entry
+ // (inside a counterbore), the leader drops to the wall's rim.
+ var wallTop = hole.Walls.SelectMany(w => w).SelectMany(p => p.Positions).Max(p => p.Z);
+ return PlaceRadial((cylinder.Origin.X, cylinder.Origin.Y), r, level, Math.Min(level, wallTop), center, width, height);
+ }
+
+ /// <summary>A callout on a composed feature: a pocket at its floor, a boss at its top rim, a chamfer on its face.</summary>
+ public Placement PlaceFeatureCallout(DisplayFaceMeshPatch[] faces, IReadOnlyList<Step242SemanticPmiInspectionItem> items, Point3D center,
+ double width, double height, Point3D[] bodyPoints, CylinderSurface? cylinder)
+ {
+ var points = faces.SelectMany(f => f.Positions).ToArray();
+ var top = points.Max(p => p.Z);
+ if (items.Any(i => i.DimensionKind == "depth"))
+ {
+ // Point at the floor centre of the pocket nearest the default view, from the rim level.
+ var floorZ = points.Min(p => p.Z);
+ var floor = faces.Where(f => f.Positions.All(p => Math.Abs(p.Z - floorZ) < 1e-6))
+ .OrderBy(f => f.Positions.Average(p => p.X + p.Y)).First().Positions;
+ return PlaceRadial(((floor.Min(p => p.X) + floor.Max(p => p.X)) / 2, (floor.Min(p => p.Y) + floor.Max(p => p.Y)) / 2), 0, top, floorZ, center, width, height);
+ }
+ if (cylinder is { } round)
+ {
+ // A boss: point at its top rim.
+ var rim = faces.Where(f => f.Positions.Any()).SelectMany(f => f.Positions)
+ .Where(p => Math.Abs(Math.Sqrt(Math.Pow(p.X - round.Origin.X, 2) + Math.Pow(p.Y - round.Origin.Y, 2)) - round.Radius) < 1e-6).ToArray();
+ var rimTop = rim.Length > 0 ? rim.Max(p => p.Z) : top;
+ return PlaceRadial((round.Origin.X, round.Origin.Y), round.Radius, rimTop, rimTop, center, width, height);
+ }
+ if (items.Any(i => i.DimensionKind == "chamfer"))
+ {
+ // The chamfer nearest the default view, at its middle.
+ var front = faces.OrderBy(f => f.Positions.Average(p => p.Y)).First().Positions;
+ var mid = (X: (front.Min(p => p.X) + front.Max(p => p.X)) / 2, Y: (front.Min(p => p.Y) + front.Max(p => p.Y)) / 2);
+ return PlaceRadial(mid, 0, front.Max(p => p.Z), (front.Min(p => p.Z) + front.Max(p => p.Z)) / 2, center, width, height);
+ }
+ var axis = ((points.Min(p => p.X) + points.Max(p => p.X)) / 2, (points.Min(p => p.Y) + points.Max(p => p.Y)) / 2);
+ var radius = Math.Min(points.Max(p => p.X) - points.Min(p => p.X), points.Max(p => p.Y) - points.Min(p => p.Y)) / 2;
+ return PlaceRadial(axis, radius, top, top, center, width, height);
+ }
+
+ private Placement PlaceRadial((double X, double Y) axis, double r, double level, double anchorZ, Point3D center, double width, double height)
+ {
var plane = new PmiPlane(new Point3D(0, 0, level), new Vector3D(1, 0, 0), new Vector3D(0, 1, 0));
- var axis = (X: cylinder.Origin.X, Y: cylinder.Origin.Y);
var sx = Math.Sign(axis.X - center.X); var sy = Math.Sign(axis.Y - center.Y);
var preferred = (X: sx == 0 ? -1 : sx, Y: sy == 0 ? -1 : sy);
var directions = new[] { preferred, (X: -1, Y: -1), (X: 1, Y: -1), (X: -1, Y: 1), (X: 1, Y: 1) }.Distinct().ToArray();
@@ -374,13 +586,50 @@ public static class PmiDisplayProjection
var leader = new PmiCanvas();
leader.Line(tip, elbow, (outward.X >= 0 ? x : x + width, elbow.Y));
Arrow(leader, tip, (-outward.X, -outward.Y));
- // The callout belongs to the controlled wall: when it starts below the entry
- // (inside a counterbore), the leader drops to the wall's rim.
- var wallTop = hole.Walls.SelectMany(w => w).SelectMany(p => p.Positions).Max(p => p.Z);
- var anchor = new Point3D(tip.X, tip.Y, Math.Min(level, wallTop));
- return new(plane, x, elbow.Y - height / 2, leader, anchor) { Drop = level - anchor.Z };
+ var anchor = new Point3D(tip.X, tip.Y, anchorZ);
+ return new(plane, x, elbow.Y - height / 2, leader, anchor) { Drop = level - anchorZ };
}
- throw new InvalidOperationException("pmi-display-layout-no-space: a hole callout has no free position.");
+ throw new InvalidOperationException("pmi-display-layout-no-space: a callout has no free position.");
+ }
+
+ /// <summary>
+ /// An overall size outside the part: length behind it, width to its right (both in the plane of
+ /// the walls' top edges), thickness up its front right corner.
+ /// </summary>
+ public (PmiCanvas Canvas, PmiPlane Plane) Overall(string kind, Point3D[] points, string text)
+ {
+ var canvas = new PmiCanvas();
+ PmiPlane plane; (double X, double Y) a, b, offset;
+ if (kind == "thickness")
+ {
+ plane = new PmiPlane(new Point3D(0, minY, 0), new Vector3D(1, 0, 0), new Vector3D(0, 0, 1));
+ a = (maxX, points.Min(p => p.Z)); b = (maxX, points.Max(p => p.Z)); offset = (1, 0);
+ }
+ else
+ {
+ plane = new PmiPlane(new Point3D(0, 0, points.Max(p => p.Z)), new Vector3D(1, 0, 0), new Vector3D(0, 1, 0));
+ (a, b, offset) = kind == "length"
+ ? ((points.Min(p => p.X), maxY), (points.Max(p => p.X), maxY), (0d, 1d))
+ : ((maxX, points.Min(p => p.Y)), (maxX, points.Max(p => p.Y)), (1d, 0d));
+ }
+ var label = PmiDrafting.TextBlock(text, h);
+ for (var distance = 3 * h; distance < 60 * h; distance += h)
+ {
+ var la = (X: a.X + offset.X * distance, Y: a.Y + offset.Y * distance); var lb = (X: b.X + offset.X * distance, Y: b.Y + offset.Y * distance);
+ var mid = ((la.X + lb.X) / 2, (la.Y + lb.Y) / 2);
+ var rect = (mid.Item1 - label.Width / 2, mid.Item2 - label.Height / 2, mid.Item1 + label.Width / 2, mid.Item2 + label.Height / 2);
+ if (!Free(plane, rect, false)) continue;
+ Occupy(plane, (Math.Min(la.X, lb.X) - .5 * h, Math.Min(la.Y, lb.Y) - .5 * h, Math.Max(la.X, lb.X) + .5 * h, Math.Max(la.Y, lb.Y) + .5 * h), label: false);
+ Occupy(plane, rect);
+ canvas.Line((a.X + offset.X * .4 * h, a.Y + offset.Y * .4 * h), (la.X + offset.X * .6 * h, la.Y + offset.Y * .6 * h));
+ canvas.Line((b.X + offset.X * .4 * h, b.Y + offset.Y * .4 * h), (lb.X + offset.X * .6 * h, lb.Y + offset.Y * .6 * h));
+ canvas.Line(la, lb);
+ var along = (X: lb.X - la.X, Y: lb.Y - la.Y);
+ Arrow(canvas, la, (-along.X, -along.Y)); Arrow(canvas, lb, along);
+ canvas.Append(label.Canvas, rect.Item1, rect.Item2);
+ return (canvas, plane);
+ }
+ throw new InvalidOperationException("pmi-display-layout-no-space: an overall dimension has no free position.");
}
/// <summary>Reserve the band a set of baseline dimensions occupies, extension lines included.</summary>
@@ -389,8 +638,20 @@ public static class PmiDisplayProjection
var plane = new PmiPlane(new Point3D(0, 0, DimensionLevel), new Vector3D(1, 0, 0), new Vector3D(0, 1, 0));
var spacing = 2.6 * h; var first = 3.2 * h;
DimensionDepth = first + (Math.Max(tiersAlongX, 1) - 1) * spacing + 1.2 * h;
- if (tiersAlongX > 0) Occupy(plane, (minX - h, minY - first - (tiersAlongX - 1) * spacing - 1.2 * h, maxX + h, minY));
- if (tiersAlongY > 0) Occupy(plane, (minX - first - (tiersAlongY - 1) * spacing - 1.6 * h, minY - h, minX, maxY + h));
+ if (tiersAlongX > 0) Occupy(plane, (minX - h, minY - first - (tiersAlongX - 1) * spacing - 1.2 * h, maxX + h, minY), label: false);
+ if (tiersAlongY > 0) Occupy(plane, (minX - first - (tiersAlongY - 1) * spacing - 1.6 * h, minY - h, minX, maxY + h), label: false);
+ }
+
+ public (double X, double Top) PlaceNotes(PmiPlane plane, double width, double height)
+ {
+ for (var top = minZ - 3 * h; top > minZ - 200 * h; top -= h)
+ {
+ var rect = (maxX - width, top - height, maxX, top);
+ if (!Free(plane, rect, false)) continue;
+ Occupy(plane, rect);
+ return (maxX - width, top);
+ }
+ throw new InvalidOperationException("pmi-display-layout-no-space: the notes have no free position.");
}
/// <summary>Reserve a rectangle in a plane (for blocks placed by the caller).</summary>
@@ -473,7 +734,7 @@ public static class PmiDisplayProjection
}
/// <summary>One baseline basic dimension: extension lines, a dimension line with arrows and a boxed value.</summary>
- public void BasicDimension(PmiCanvas canvas, Vector3D datumNormal, double datumOffset, Point3D axis, double value, int tier)
+ public void BasicDimension(PmiCanvas canvas, Vector3D datumNormal, double datumOffset, Point3D axis, double value, int tier, bool boxed = true)
{
// Dimensions along X sit in front of the part; dimensions along Y sit to its left.
var alongX = Math.Abs(datumNormal.X) > .5;
@@ -481,7 +742,7 @@ public static class PmiDisplayProjection
var spacing = 2.6 * h; var first = 3.2 * h;
var datumCoordinate = datumOffset * (alongX ? datumNormal.X : datumNormal.Y);
var featureCoordinate = alongX ? axis.X : axis.Y;
- var label = PmiDrafting.TextBlock(PmiDrafting.Number(value), h, boxed: true);
+ var label = PmiDrafting.TextBlock(PmiDrafting.Number(value), h, boxed);
if (alongX)
{
var y = minY - first - tier * spacing;
@@ -496,7 +757,8 @@ public static class PmiDisplayProjection
: (datumCoordinate + featureCoordinate) / 2 - label.Width / 2;
canvas.Append(label.Canvas, cx, y - label.Height / 2);
dimensionLabels.Add((cx, y - label.Height / 2, cx + label.Width, y + label.Height / 2));
- Occupy(plane, (Math.Min(datumCoordinate, featureCoordinate), y - label.Height / 2, Math.Max(datumCoordinate, featureCoordinate), y + label.Height / 2));
+ Occupy(plane, (Math.Min(datumCoordinate, featureCoordinate), y - label.Height / 2, Math.Max(datumCoordinate, featureCoordinate), y + label.Height / 2), label: false);
+ Occupy(plane, (cx, y - label.Height / 2, cx + label.Width, y + label.Height / 2));
}
else
{
@@ -511,7 +773,8 @@ public static class PmiDisplayProjection
: (datumCoordinate + featureCoordinate) / 2 - label.Height / 2;
canvas.Append(label.Canvas, x - label.Width / 2, cy);
dimensionLabels.Add((x - label.Width / 2, cy, x + label.Width / 2, cy + label.Height));
- Occupy(plane, (x - label.Width / 2, Math.Min(datumCoordinate, featureCoordinate), x + label.Width / 2, Math.Max(datumCoordinate, featureCoordinate)));
+ Occupy(plane, (x - label.Width / 2, Math.Min(datumCoordinate, featureCoordinate), x + label.Width / 2, Math.Max(datumCoordinate, featureCoordinate)), label: false);
+ Occupy(plane, (x - label.Width / 2, cy, x + label.Width / 2, cy + label.Height));
}
// Mark the controlled axis.
canvas.Line((axis.X - .8 * h, axis.Y), (axis.X + .8 * h, axis.Y));
diff --git a/demos/Aetheris.PmiShowcase/Program.cs b/demos/Aetheris.PmiShowcase/Program.cs
index 27004797..1210bf72 100644
--- a/demos/Aetheris.PmiShowcase/Program.cs
+++ b/demos/Aetheris.PmiShowcase/Program.cs
@@ -23,8 +23,8 @@ try
var step = compilation.Value.StepText;
var imported = Step242Importer.ImportBody(step);
if (!imported.IsSuccess) throw new InvalidOperationException("STEP reimport failed.");
- // Presentation density: coarse enough for a phone or tablet, fine enough for true silhouettes.
- var options = DisplayTessellationOptions.Default with { AngularToleranceRadians = Math.PI / 24, MinimumSegments = 4, MaximumSegments = 12 };
+ // Presentation density: smooth silhouettes, still light enough for a phone or tablet.
+ var options = DisplayTessellationOptions.Default with { AngularToleranceRadians = Math.PI / 24 };
var tessellation = BrepDisplayTessellator.Tessellate(imported.Value, options);
if (!tessellation.IsSuccess) throw new InvalidOperationException("Display tessellation failed.");
var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
diff --git a/demos/Aetheris.PmiShowcase/README.md b/demos/Aetheris.PmiShowcase/README.md
new file mode 100644
index 00000000..b57de48b
--- /dev/null
+++ b/demos/Aetheris.PmiShowcase/README.md
@@ -0,0 +1,13 @@
+# PMI showcase
+
+Builds a Firmament part with manufacturing PMI into AP242 STEP and an annotated GLB
+that any glTF viewer opens. Every callout in the GLB is read back from the exported
+STEP, not from the source.
+
+```powershell
+dotnet run --project demos/Aetheris.PmiShowcase -- fixtures/Canonical/PMI/showcase-bearing-mount.firmament
+```
+
+Output goes to `artifacts/local/demos/pmi-showcase/`: `<part>.step`, `<part>.glb` and
+`<part>.pmi.json` (the semantic records read back from the STEP). The language is
+described in [Semantic PMI and AP242](../../docs/public/firmament/pmi.md).
diff --git a/docs/development/reports/2026-10/pmi-showcase-dogfood.md b/docs/development/reports/2026-10/pmi-showcase-dogfood.md
new file mode 100644
index 00000000..f5ba8cf2
--- /dev/null
+++ b/docs/development/reports/2026-10/pmi-showcase-dogfood.md
@@ -0,0 +1,64 @@
+# PMI showcase: dogfooding PMI on a real machined part
+
+**Goal.** Specify a composed machined part (boss, pockets, bore, counterbored holes,
+chamfer) completely enough to make it without a drawing, and present it as an
+annotated GLB. Use the attempt to find out whether the PMI system is usable, not just
+technically present.
+
+**Part.** `fixtures/Canonical/PMI/showcase-bearing-mount.firmament`, built by
+`demos/Aetheris.PmiShowcase` into STEP AP242 and GLB. 28 semantic records: 3 datums,
+17 sizes and locations, 5 geometric controls, 3 notes.
+
+## What blocked a complete specification, and what changed
+
+| Found | Change |
+|---|---|
+| `dimension:` never bound on Compose bodies (Statics were not passed to the Compose PMI binder) | Bound Statics flow to every mechanical construction route |
+| No way to target a boss top or pocket floor; `face(+Z)` is ambiguous on a stepped part | `face(op.Top)`, `face(op.Bottom)`, `face(pocket.Floor)` |
+| Datums on faces split by construction exported **unattached**, silently | Axis faces resolve to the extreme support plane (all coplanar pieces); an authored datum with no face rejects |
+| No quantity: one hole annotated, or four separate callouts | Hole lists: one requirement with its quantity, on every shaft wall |
+| Position on a counterbored hole also associated the counterbore wall | Hole sizes and controls apply to the shaft only |
+| No part notes (material, general tolerance) | `Note` |
+| Sizes written only in an Aetheris-private AP242 form | Also written as standard `DIMENSIONAL_SIZE`/`DIMENSIONAL_LOCATION` + `PLUS_MINUS_TOLERANCE`; readers count once |
+| No way to state block, boss, pocket, counterbore or chamfer sizes, or feature locations | `Dimension` (construction parameters, values from the built body), `Location`, `HoleCallout` |
+| `face(h.Wall)` rejected on Compose holes with a bare code | Accepted (the shaft); PMI record errors are located at the record and explained |
+| Hole-wall strips tessellated as 32×256 grids (chord tolerance read as a parameter step) | Straight direction of a rectangular trim is one cell; the curved direction keeps its edge samples. GLB 95 MB → 2.6 MB |
+
+Presentation was rewritten: callouts grouped per feature and placed in annotation
+planes with collision avoidance (including in the default view's projection),
+Y14.5-shaped frames and datum symbols drawn as vectors, filled text on panels, B-rep
+edges over a translucent body, per-feature leader colours, sizes on their features,
+overall dimensions outside the part, baseline locations.
+
+## Evidence
+
+- Showcase readback: every record associated with faces; display draws all 28.
+- Standard form checked independently: with the native records renamed away, the
+ foreign-PMI reader recovers each diameter, tolerance and location from the
+ standard entities alone (`PmiShowcaseTests.Sizes_AreAlsoWrittenInStandardAp242Form_AndReadOnce`).
+- Full lane passes. Drawing generation accepts the standard entities that restate a
+ native record (`StandardMirrors` on the inspection); it still rejects foreign ones.
+
+## Verdict
+
+Meaningful progression toward success: the part is fully specified by its model and
+the GLB reads as an engineering presentation.
+
+## Stopped or deferred, with reasons
+
+- **Rounded stock corners + boss + chamfer.** The composed chamfer planner transports
+ straight outer segments only (`ComposedProfileBoundaryChamferStackPlanner` casts to
+ line segments); a chamfer around an arc is a conical face the variable-outer
+ emitter does not produce. That is emitter work, not a bug fix; the showcase uses a
+ sharp-cornered outline.
+- **Standard form for quantity lists.** `2X` pocket lengths, depths and the chamfer
+ are written in the native form only; single-feature sizes and all locations are
+ written in both. A list needs one standard dimension per feature.
+- **Basic flag in AP242.** `basic: true` is native and presentation-only; the standard
+ qualifier for basic dimensions is not written yet.
+- **Not projected yet:** fillet radius, countersink callouts, locations between two
+ features (only from an axis face).
+- **Helios** draws PMI from `Lines`; glyph outlines remain there, so it keeps showing
+ text, but it does not yet use the filled text, panels or leader colours.
+- **NIST STEP File Analyzer** was not run (Windows-only); confirm the standard
+ entities with it before claiming conformance.
diff --git a/docs/public/firmament/pmi.md b/docs/public/firmament/pmi.md
index 68e58fe1..e4909c52 100644
--- a/docs/public/firmament/pmi.md
+++ b/docs/public/firmament/pmi.md
@@ -6,11 +6,86 @@ geometry, solving constraints, or proving that a manufacturing process can meet
the tolerance. Camera and label placement are presentation state. Checked
compile-time requirements can separately be projected into dimensional PMI.
-Native Model export supports planar `Datum`, `HoleDiameter`, and the explicit
-geometric controls below. The diameter record targets a named shaft hole; on a
-counterbore it means the shaft `diameter`, not `counterboreDiameter`. Parsed kinds
-outside the admitted set, including `Distance` and `Coplanar`, remain rejected by
-normal export rather than silently omitted.
+Native Model export supports planar `Datum`, `HoleDiameter`, `HoleCallout`, the
+explicit geometric controls below, sizes and locations projected from construction
+(`Dimension`, `Location`) and part `Note`s. The diameter record targets a named shaft
+hole; on a counterbore it means the shaft `diameter`, not `counterboreDiameter`.
+Parsed kinds outside the admitted set, including the older `Distance` and
+`Coplanar` forms, remain rejected by normal export rather than silently omitted.
+
+Every size is written twice in the AP242 file: in the Aetheris records that
+`aetheris analyze` reports, and in the standard semantic form other CAD and
+inspection software reads (`DIMENSIONAL_SIZE` or `DIMENSIONAL_LOCATION` with a
+`PLUS_MINUS_TOLERANCE`, associated with the measured faces). Readers count each
+size once.
+
+## A part specified by its model
+
+The complete example is
+[`showcase-bearing-mount.firmament`](../../../fixtures/Canonical/PMI/showcase-bearing-mount.firmament):
+a composed block with a boss, two pockets, a bearing bore, four counterbored
+mounting holes and a chamfered edge, with datums, sizes, geometric controls,
+locations and notes complete enough to make the part without a drawing.
+
+```firmament
+Pmi {
+ Datum A { target: face(-Z) }
+ Datum B { target: face(-X) }
+ Datum C { target: face(-Y) }
+ HoleCallout MountSize { target: [mountA, mountB, mountC, mountD] dimension: mountDiameter }
+ Position MountLocation { target: [mountA, mountB, mountC, mountD] tolerance: 0.25mm zone: Cylindrical datumRefs: [A, B, C] modifiers: [MaximumMaterial] }
+ Parallelism HubFace { target: face(hub.Top) tolerance: 0.03mm datumRefs: [A] }
+ Dimension PocketDepth { target: [left.Depth, right.Depth] }
+ Location LeftPocketFromB { origin: face(-X) to: left }
+ Dimension EdgeBreak { target: perimeterBreak.Distance }
+ Note Material { text: "MATERIAL: 6061-T6 ALUMINUM" }
+}
+```
+
+**Targets.**
+
+- `face(-X)` and the other axis faces mean the faces lying in the part's extreme
+ plane in that direction, the surface a datum simulator touches. A face split by
+ construction is associated in all its pieces. If the extreme in that direction is
+ not planar, the target does not resolve and the record rejects.
+- On a `Compose` body, `face(op.Top)` names a Base or Boss top, `face(op.Bottom)` a
+ Base bottom and `face(pocket.Floor)` a Pocket floor. A cap that is not exactly one
+ face rejects.
+- A hole is named directly (`target: bore`); `face(bore.Wall)` means the same on a
+ Compose body. A list of holes (`target: [a, b, c, d]`) is one requirement on every
+ listed hole, written with its quantity ("4X"). It applies to the shaft walls,
+ never to a counterbore or countersink wall.
+- An authored datum that resolves to no face rejects.
+
+**`HoleCallout`** takes the same fields as `HoleDiameter` and adds the hole's
+counterbore diameter and depth, projected from its construction:
+`4X Ø6.6 ±0.1 ⌴Ø11 ↧6.5`. The counterbore of every listed hole must be alike.
+
+**`Dimension`** names a construction parameter; the compiler supplies the value from
+the built geometry, so it cannot disagree with the part:
+
+| Target | Value |
+|---|---|
+| `base.Height`, `base.Length`, `base.Width` | Base thickness; X and Y extent between its walls |
+| `boss.Height`, `boss.Diameter`, `boss.Length`, `boss.Width`, `boss.Radius` | Boss height above its support; round or rectangular size; corner radius |
+| `pocket.Depth`, `pocket.Diameter`, `pocket.Length`, `pocket.Width`, `pocket.Radius` | Pocket depth to its floor; size; corner radius |
+| `finish.Distance` | An equal-distance 45° chamfer (`EdgeFinish<Chamfer>`) |
+
+`Length` runs along X and `Width` along Y, as `Rect2` writes `size: [x, y]`. A list
+of the same parameter on several features (`[left.Depth, right.Depth]`) is one
+requirement with a quantity; the values must agree. A value with no stated
+tolerance falls under the part's general-tolerance note; `dimension:` a toleranced
+`Static` or `tolerance: PlusMinus(..)` attaches one.
+
+**`Location`** runs from an axis face (`origin: face(-X)`) to a hole axis or to the
+centre of a boss or pocket (`to: left`). `basic: true` makes it theoretically exact
+(drawn boxed) and admits no tolerance.
+
+**`Note`** records part-level text such as material, general tolerances and finish.
+They read back as annotations.
+
+Fillet radii, countersink callouts and locations between two features are not yet
+projected. A `Dimension` or `Location` that does not resolve to faces rejects.
## Explicit GD&T
@@ -160,7 +235,10 @@ geometric requirement. The shipped size examples request independent datums and
size dimensions; they no longer request a relationship that was never emitted.
This is semantic product-definition PMI, recovered by `aetheris analyze`;
-graphical dimension-label placement is separate. Explicit `value:` and
+graphical dimension-label placement is separate. An annotated GLB draws it in 3D:
+callouts sit on their features, feature control frames and datum symbols follow
+ASME Y14.5 shapes, basic dimensions locate position-toleranced holes, and each
+feature's leaders share a colour. Explicit `value:` and
`tolerance: PlusMinus(upper, lower)` remain supported compatibility forms.
Existing `Require`-based `from:` / `as:` projections continue to mean a checked
semantic constraint, rather than an implicit export of all Static values.
diff --git a/fixtures/Canonical/PMI/showcase-bearing-mount.firmament b/fixtures/Canonical/PMI/showcase-bearing-mount.firmament
index 7ded7f81..d96d8ada 100644
--- a/fixtures/Canonical/PMI/showcase-bearing-mount.firmament
+++ b/fixtures/Canonical/PMI/showcase-bearing-mount.firmament
@@ -34,9 +34,25 @@ Model BearingMount {
HoleDiameter BoreSize { target: bore dimension: boreDiameter }
Perpendicularity BoreSquare { target: bore tolerance: 0.01mm zone: Cylindrical datumRefs: [A] }
Position BoreLocation { target: bore tolerance: 0.02mm zone: Cylindrical datumRefs: [A, B, C] }
- HoleDiameter MountSize { target: [mountA, mountB, mountC, mountD] dimension: mountDiameter }
+ HoleCallout MountSize { target: [mountA, mountB, mountC, mountD] dimension: mountDiameter }
Position MountLocation { target: [mountA, mountB, mountC, mountD] tolerance: 0.25mm zone: Cylindrical datumRefs: [A, B, C] modifiers: [MaximumMaterial] }
Parallelism HubFace { target: face(hub.Top) tolerance: 0.03mm datumRefs: [A] }
+
+ // Sizes and locations, projected from the construction above: the compiler supplies every value.
+ Dimension BlockLength { target: stock.Length }
+ Dimension BlockWidth { target: stock.Width }
+ Dimension BlockThickness { target: stock.Height }
+ Dimension HubDiameter { target: hub.Diameter }
+ Dimension HubHeight { target: hub.Height }
+ Dimension PocketLength { target: [left.Length, right.Length] }
+ Dimension PocketWidth { target: [left.Width, right.Width] }
+ Dimension PocketCorner { target: [left.Radius, right.Radius] }
+ Dimension PocketDepth { target: [left.Depth, right.Depth] }
+ Location LeftPocketFromB { origin: face(-X) to: left }
+ Location RightPocketFromB { origin: face(-X) to: right }
+ Location PocketsFromC { origin: face(-Y) to: left }
+ Dimension EdgeBreak { target: perimeterBreak.Distance }
+
Note Material { text: "MATERIAL: 6061-T6 ALUMINUM" }
Note GeneralTolerance { text: "UNTOLERANCED DIMENSIONS PER ISO 2768-mK. NOMINAL GEOMETRY FROM MODEL." }
Note Finish { text: "BREAK SHARP EDGES 0.2-0.5. BORE Ra 0.8, OTHER MACHINED SURFACES Ra 3.2." }