Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

WIP: PMI showcase part and drafting-standard 3D callouts

Claudef2c788e42ad1
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index ba0a7f39..91a4f11c 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 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)))
+ return Failure($"pmi-datum-target-unresolved: Datum '{datum.Label}' does not resolve to a face of the exported body. Use a face that bounds the part in that direction, or name the face of a Compose operation such as face(stock.Top).", "Step242.Pmi");
IReadOnlyList<KernelDiagnostic> normalizationDiagnostics = [];
if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute)
{
diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
index c75a6824..ccab38f5 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
@@ -31,7 +31,11 @@ public sealed record Step242SemanticPmiDatum(
string FeatureId,
string DatumKind,
string Label,
- string Target) : Step242SemanticPmi(FeatureId);
+ string Target) : Step242SemanticPmi(FeatureId)
+{
+ /// <summary>An authored datum feature must resolve to its face; export rejects it unattached.</summary>
+ public bool RequiresFaceAssociation { get; init; }
+}
public sealed record Step242SemanticPmiNote(
string FeatureId,
diff --git a/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs b/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
index 07ea4846..5d948eac 100644
--- a/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
@@ -107,21 +107,25 @@ public sealed class ImportedPartPmiTests
Assert.Equal(.1, diameter.GetProperty("tolerancePlus").GetDouble());
Assert.Equal(.05, diameter.GetProperty("toleranceMinus").GetDouble());
Assert.Equal(1, diameter.GetProperty("stepFaceEntities").GetArrayLength());
- var target = diameter.GetProperty("target");
- var targetPoints = target.GetProperty("positions").EnumerateArray().Select(p => p.GetDouble()).ToArray();
- var targetNormals = target.GetProperty("normals").EnumerateArray().Select(p => p.GetDouble()).ToArray();
- var offset = target.GetProperty("surfaceOffset").GetDouble();
+ // GLB metadata keeps semantics; the highlighted support is geometry in the buffers.
+ var projected = PmiDisplayProjection.FromStep(built.Value.StepText, options).Single(a => a.Kind == "Diameter").Target!;
+ var targetPoints = projected.Positions; var targetNormals = projected.Normals; var offset = projected.SurfaceOffset;
+ Assert.NotEmpty(targetPoints);
for (var i = 0; i < targetPoints.Length; i += 3)
{
var point = new Point3D(targetPoints[i]-offset*targetNormals[i], targetPoints[i+1]-offset*targetNormals[i+1], targetPoints[i+2]-offset*targetNormals[i+2]);
Assert.Contains(tess.FacePatches.SelectMany(p => p.Positions), p => (p-point).Length < 1e-8);
}
- Assert.Equal(3, root.GetProperty("meshes").GetArrayLength());
- Assert.All(root.GetProperty("meshes").EnumerateArray().Skip(1), mesh => Assert.Equal(1, mesh.GetProperty("primitives")[0].GetProperty("mode").GetInt32()));
- Assert.All(root.GetProperty("meshes").EnumerateArray().Skip(1), mesh =>
- Assert.Contains(mesh.GetProperty("primitives").EnumerateArray(), p => p.GetProperty("mode").GetInt32() == 4));
+ // Body, two annotations and the model edges drawn over the translucent part.
+ Assert.Equal(4, root.GetProperty("meshes").GetArrayLength());
+ var annotationMeshes = root.GetProperty("meshes").EnumerateArray().Where(m => m.TryGetProperty("extras", out var extras)
+ && extras.TryGetProperty("role", out var role) && role.GetString() == "PMI presentation").ToArray();
+ Assert.Equal(2, annotationMeshes.Length);
+ Assert.All(annotationMeshes, mesh => Assert.Equal(1, mesh.GetProperty("primitives")[0].GetProperty("mode").GetInt32()));
+ Assert.All(annotationMeshes, mesh => Assert.Contains(mesh.GetProperty("primitives").EnumerateArray(), p => p.GetProperty("mode").GetInt32() == 4));
+ Assert.Single(root.GetProperty("meshes").EnumerateArray(), m => m.GetProperty("name").GetString() == "edges");
Assert.Equal("BLEND", root.GetProperty("materials")[0].GetProperty("alphaMode").GetString());
- Assert.Equal(.78, root.GetProperty("materials")[0].GetProperty("pbrMetallicRoughness").GetProperty("baseColorFactor")[3].GetDouble());
+ Assert.Equal(.55, root.GetProperty("materials")[0].GetProperty("pbrMetallicRoughness").GetProperty("baseColorFactor")[3].GetDouble());
// Body data is a byte-identical prefix; annotation curves are appended after it.
var beforeOffset = 28 + BitConverter.ToInt32(baseline, 12);
var afterOffset = 28 + BitConverter.ToInt32(file.Bytes, 12);
@@ -148,10 +152,9 @@ public sealed class ImportedPartPmiTests
var target = Assert.IsType<PmiDisplayTarget>(annotation.Target);
var normal = new Vector3D(target.Normal[0], target.Normal[1], target.Normal[2]);
Assert.Equal(1, normal.Length, 9);
- Assert.True((anchor - Point(annotation.Lines[0][1])).Cross(normal).Length < 1e-8);
- Assert.True((Point(annotation.Lines[0][1]) - anchor).Dot(normal) > 0);
+ // The leader starts on the support itself.
+ var leader = Assert.Single(annotation.Lines, line => (Point(line[0]) - anchor).Length < 1e-9);
var patch = tess.FacePatches.Single(p => p.FaceId == binding.FaceId);
- Assert.DoesNotContain(patch.Positions, p => (p-anchor).Length < 1e-6);
Assert.InRange(target.SurfaceOffset, 0, annotation.TextHeight*.002);
// Presentation is lifted very slightly to avoid coincident-surface GLB striping.
// Remove the disclosed offset when proving its relationship to exact geometry.
@@ -161,11 +164,15 @@ public sealed class ImportedPartPmiTests
if (surface!.Plane is { } plane)
{
Assert.Equal("PlanePatch", target.Kind);
+ // A planar feature is shown edge-on: the stem leaves along the face normal.
+ Assert.True((Point(leader[1]) - anchor).Cross(normal).Length < 1e-8);
+ Assert.True((Point(leader[1]) - anchor).Dot(normal) > 0);
Assert.All(marker.Append(anchor), p => Assert.True(Math.Abs((p-plane.Origin).Dot(plane.Normal.ToVector())) < 1e-8));
- // Every marker corner is in material on this actual trimmed face, including
+ // Every highlighted point is in material on this actual trimmed face, including
// its hole exclusion, not merely in the plane or the global box.
var seat = new Aetheris.Kernel.Core.Brep.Queries.BrepPlanarSeatQuery(body);
- Assert.All(marker.Append(anchor), p => Assert.Contains(binding.FaceId, seat.FindFaces(p, normal)));
+ Assert.All(marker, p => Assert.Contains(binding.FaceId, seat.FindFaces(p, normal)));
+ Assert.DoesNotContain(patch.Positions, p => (p-anchor).Length < 1e-6);
}
else
{
@@ -173,17 +180,11 @@ public sealed class ImportedPartPmiTests
Assert.Equal("CylinderWall", target.Kind);
Assert.All(marker.Append(anchor), p => {
var delta = p-cylinder.Origin; var axial = delta.Dot(cylinder.Axis.ToVector());
- Assert.Equal(cylinder.Radius, (delta-cylinder.Axis.ToVector()*axial).Length, 8);
+ Assert.Equal(cylinder.Radius, (delta-cylinder.Axis.ToVector()*axial).Length, 6);
});
+ // The anchor is on the wall's actual axial extent (its visible rim), never a chord.
var values = patch.Positions.Select(p => (p-cylinder.Origin).Dot(cylinder.Axis.ToVector())).ToArray();
- var v = (anchor-cylinder.Origin).Dot(cylinder.Axis.ToVector());
- Assert.InRange(v, values.Min() + (values.Max()-values.Min())*.2, values.Max() - (values.Max()-values.Min())*.2);
- Assert.True(target.StemLength < cylinder.Radius);
- Assert.NotEmpty(target.Lines);
- Assert.All(target.Lines, line => {
- var axial = line.Select(p => (Point(p)-cylinder.Origin).Dot(cylinder.Axis.ToVector())).ToArray();
- Assert.True(axial.Max()-axial.Min() < 1e-8, "Only physical rims, never the axial parameter seam, should be highlighted.");
- });
+ Assert.InRange((anchor-cylinder.Origin).Dot(cylinder.Axis.ToVector()), values.Min() - 1e-8, values.Max() + 1e-8);
}
}
static Point3D Point(double[] p) => new(p[0], p[1], p[2]);
diff --git a/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs b/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs
new file mode 100644
index 00000000..a9c0c3f3
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/PmiShowcaseTests.cs
@@ -0,0 +1,124 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Visualization;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+/// <summary>PMI on a composed machined part, as an engineer would specify it for manufacture.</summary>
+public sealed class PmiShowcaseTests
+{
+ private static string Fixture(string relative)
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return Path.Combine(directory!.FullName, relative);
+ }
+
+ private static string Showcase() => File.ReadAllText(Fixture("fixtures/Canonical/PMI/showcase-bearing-mount.firmament"));
+
+ private const string Plate = """
+ Model P {
+ units: mm
+ Static d: Length = 8mm tol +0.1mm -0.05mm
+ Profile s = Rect2 { center: [0mm, 0mm]; size: [60mm, 40mm] }
+ Profile pad = Circle2 { center: [0mm, 0mm]; radius: 10mm }
+ Compose body {
+ Base stock { profile: s; from: 0mm; to: 8mm; role: Stock }
+ Boss hub { on: Top; profile: pad; height: 6mm }
+ Hole<Shaft> h { on: +Z; center: [0mm, 0mm]; diameter: d; end: ThroughAll }
+ Hole<Shaft> a { on: +Z; center: [-22mm, -12mm]; diameter: 5mm; end: ThroughAll }
+ Hole<Shaft> b { on: +Z; center: [22mm, -12mm]; diameter: 5mm; end: ThroughAll }
+ }
+ Pmi {
+ PMI_BODY
+ }
+ }
+ """;
+
+ private static FirmamentStepExportResult Build(string pmi)
+ {
+ var result = FirmamentBuildAndExport.CompileSource(Plate.Replace("PMI_BODY", pmi));
+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(d => d.Message)));
+ return result.Value;
+ }
+
+ [Fact]
+ public void TypedToleranceDimension_BindsOnAComposedBody()
+ {
+ var step = Build("HoleDiameter S { target: h dimension: d }").StepText;
+ var size = Assert.Single(Step242SemanticPmiInspector.Inspect(step).Items, i => i.Kind == "Diameter");
+ Assert.Equal(8, size.Value); Assert.Equal(.1, size.TolerancePlus); Assert.Equal(.05, size.ToleranceMinus);
+ }
+
+ [Fact]
+ public void ComposeOperationCap_IsANamedPmiTarget()
+ {
+ var step = Build("Datum A { target: face(-Z) } Parallelism Top { target: face(hub.Top) tolerance: 0.02mm datumRefs: [A] }").StepText;
+ var control = Assert.Single(Step242SemanticPmiInspector.Inspect(step).Items, i => i.Kind == "Parallelism");
+ Assert.Single(control.GeometricFaceEntityIds);
+ // The ambiguous axis spelling is not silently resolved to some +Z face of a stepped body.
+ var body = Core.Step242.Step242Importer.ImportBody(step).Value;
+ var face = body.Bindings.FaceBindings.Single(b => b.SourceStepEntityId == control.GeometricFaceEntityIds[0]);
+ Assert.Equal(14, body.GetFaceSurface(face.FaceId).Plane!.Value.Origin.Z, 9);
+ }
+
+ [Fact]
+ public void AxisDatum_OnASplitFace_AttachesToEveryCoplanarPatch()
+ {
+ var step = Build("Datum A { target: face(-Z) } Datum B { target: face(-X) } Datum C { target: face(-Y) }").StepText;
+ var datums = Step242SemanticPmiInspector.Inspect(step).Items.Where(i => i.Kind == "Datum").ToArray();
+ Assert.Equal(3, datums.Length);
+ Assert.All(datums, d => Assert.NotEmpty(d.GeometricFaceEntityIds));
+ }
+
+ [Fact]
+ public void HoleList_IsOneRequirementWithItsQuantity_OnShaftWallsOnly()
+ {
+ var step = Build("Datum A { target: face(-Z) } Datum B { target: face(-X) } Datum C { target: face(-Y) }\n"
+ + "HoleDiameter S { target: [a, b] value: 5mm tolerance: PlusMinus(0.1mm) }\n"
+ + "Position L { target: [a, b] tolerance: 0.2mm zone: Cylindrical datumRefs: [A, B, C] modifiers: [MaximumMaterial] }").StepText;
+ var items = Step242SemanticPmiInspector.Inspect(step).Items;
+ var size = Assert.Single(items, i => i.Kind == "Diameter");
+ var position = Assert.Single(items, i => i.Kind == "Position");
+ Assert.Equal(2, size.Quantity); Assert.Equal(2, position.Quantity);
+ Assert.Equal(size.GeometricFaceEntityIds.Order(), position.GeometricFaceEntityIds.Order());
+ var display = PmiDisplayProjection.FromStep(step);
+ Assert.StartsWith("2X Ø5 ±0.1", Assert.Single(display, a => a.Kind == "Diameter").Text);
+ }
+
+ [Theory]
+ [InlineData("HoleDiameter S { target: [a] value: 5mm tolerance: PlusMinus(0.1mm) }")]
+ [InlineData("HoleDiameter S { target: [a, missing] value: 5mm tolerance: PlusMinus(0.1mm) }")]
+ [InlineData("Datum A { target: [a, b] }")]
+ public void InvalidHoleLists_Reject(string pmi)
+ {
+ var result = FirmamentBuildAndExport.CompileSource(Plate.Replace("PMI_BODY", pmi));
+ Assert.False(result.IsSuccess);
+ }
+
+ [Fact]
+ public void PartNotes_ExportAndReadBack()
+ {
+ var step = Build("Note Material { text: \"MATERIAL: 6061-T6\" }").StepText;
+ var note = Assert.Single(Step242SemanticPmiInspector.Inspect(step).Items, i => i.Kind == "Annotation");
+ Assert.Equal("Material", note.Name); Assert.Equal("MATERIAL: 6061-T6", note.Text);
+ var result = FirmamentBuildAndExport.CompileSource(Plate.Replace("PMI_BODY", "Note Empty { text: \"\" }"));
+ Assert.False(result.IsSuccess);
+ }
+
+ [Fact]
+ public void Showcase_SpecifiesThePartCompletely_AndEveryRecordIsDrawn()
+ {
+ 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(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.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");
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index 5fa9f9f6..ecff10c9 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -35,6 +35,8 @@ public sealed record AssemblyDisplayMeshDocument(string Schema, string Name, str
[System.Text.Json.Serialization.JsonIgnore]
public DisplayTessellationOptions? TessellationOptions { get; init; }
public IReadOnlyList<Visualization.PmiDisplayAnnotation> Annotations { get; init; } = [];
+ /// <summary>Optional B-rep edge polylines in Z-up millimetres, drawn over a translucent PMI presentation.</summary>
+ public IReadOnlyList<double[][]> EdgeLines { get; init; } = [];
public IReadOnlyList<DisplayCamera> Cameras { get; init; } = [];
public double[]? MinimumMm { get; init; }
public double[]? MaximumMm { get; init; }
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
index 3ed8c462..a7d7b946 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
@@ -88,6 +88,11 @@ public static class AssemblyGlbExporter
}
accessors.Add(accessor); return accessors.Count - 1;
}
+ int Indices(int[] values)
+ {
+ var view = AddView(() => { foreach (var v in values) writer.Write((uint)v); }, 34963);
+ accessors.Add(new { bufferView = view, componentType = 5125, count = values.Length, type = "SCALAR" }); return accessors.Count - 1;
+ }
foreach (var d in definitions)
{
var count = d.Positions.Length / 3;
@@ -101,7 +106,7 @@ public static class AssemblyGlbExporter
var appearance = appearances?.GetValueOrDefault(d.Identity) ?? new();
var m = appearance.Material ?? new();
// PMI inspection look only; engineering geometry and authored looks are retained.
- if (display.Annotations.Count > 0 && appearance.Material is null) m = m with { Opacity = .78 };
+ if (display.Annotations.Count > 0 && appearance.Material is null) m = m with { Red = .74, Green = .79, Blue = .86, Metallic = .1, Roughness = .55, Opacity = .55 };
if (new[] { m.Red, m.Green, m.Blue, m.Metallic, m.Roughness, m.Opacity, m.EmissiveRed, m.EmissiveGreen, m.EmissiveBlue }.Any(v => !double.IsFinite(v) || v < 0 || v > 1))
throw new InvalidOperationException("assembly-glb-invalid-material");
var pbr = new Dictionary<string, object> { ["baseColorFactor"] = new[] { m.Red, m.Green, m.Blue, m.Opacity }, ["metallicFactor"] = m.Metallic, ["roughnessFactor"] = m.Roughness };
@@ -173,21 +178,50 @@ public static class AssemblyGlbExporter
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 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)
+ {
+ materials.Add(new { name = "PMI text " + annotation.Name, doubleSided = true,
+ pbrMetallicRoughness = new { baseColorFactor = new[] { .04, .07, .13, 1 }, metallicFactor = 0, roughnessFactor = 1 },
+ emissiveFactor = new[] { .04, .07, .13 } });
+ primitives.Add(new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(fill.Positions, 3, true) },
+ indices = Indices(fill.Indices), mode = 4, material = materials.Count - 1 });
+ }
+ if (annotation.Panel is { Indices.Length: > 0 } panel)
+ {
+ // Backing panels stay readable over a translucent part; emissive keeps them white under any lighting.
+ materials.Add(new { name = "PMI panel " + annotation.Name, doubleSided = true,
+ pbrMetallicRoughness = new { baseColorFactor = new[] { 1d, 1d, 1d, .92 }, metallicFactor = 0, roughnessFactor = 1 },
+ emissiveFactor = new[] { .85, .87, .9 }, alphaMode = "BLEND" });
+ primitives.Add(new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(panel.Positions, 3, true) },
+ indices = Indices(panel.Indices), mode = 4, material = materials.Count - 1 });
+ }
if (annotation.Target is { } target)
{
- materials.Add(new { name = "PMI target " + target.Kind, doubleSided = true,
- pbrMetallicRoughness = new { baseColorFactor = new[] { 1d, .68, .12, 1 }, metallicFactor = 0, roughnessFactor = 1 },
- emissiveFactor = new[] { .3, .18, .02 } });
+ materials.Add(new { name = "PMI target " + target.Kind, doubleSided = true, alphaMode = "BLEND",
+ pbrMetallicRoughness = new { baseColorFactor = new[] { 1d, .7, .2, .38 }, metallicFactor = 0, roughnessFactor = 1 },
+ emissiveFactor = new[] { .25, .15, .02 } });
primitives.Add(new { attributes = new Dictionary<string, object> {
- ["POSITION"] = Floats(target.Indices.SelectMany(i => target.Positions.Skip(i*3).Take(3)).ToArray(), 3, true),
- ["NORMAL"] = Floats(target.Indices.SelectMany(i => target.Normals.Skip(i*3).Take(3)).ToArray(), 3) }, mode = 4, material = materials.Count - 1 });
+ ["POSITION"] = Floats(target.Indices.SelectMany(i => new[] { target.Positions[i*3], target.Positions[i*3+1], target.Positions[i*3+2] }).ToArray(), 3, true),
+ ["NORMAL"] = Floats(target.Indices.SelectMany(i => new[] { target.Normals[i*3], target.Normals[i*3+1], target.Normals[i*3+2] }).ToArray(), 3) }, mode = 4, material = materials.Count - 1 });
var outline = target.Lines.SelectMany(line => line.Zip(line.Skip(1), (a,b) => a.Concat(b)).SelectMany(p => p)).ToArray();
- primitives.Add(new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(outline, 3, true) }, mode = 1, material = materials.Count - 1 });
+ if (outline.Length > 0)
+ primitives.Add(new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(outline, 3, true) }, mode = 1, material = materials.Count - 1 });
}
meshes.Add(new { name = annotation.Id, primitives,
extras = new { role = "PMI presentation", annotationId = annotation.Id } });
roots.Add(nodes.Count);
- nodes.Add(new { name = annotation.Text, mesh = meshes.Count - 1, extras = new { pmi = JsonSerializer.SerializeToElement(annotation, pmiJsonOptions) } });
+ nodes.Add(new { name = annotation.Text, mesh = meshes.Count - 1, extras = new { pmi = JsonSerializer.SerializeToElement(Metadata(annotation), pmiJsonOptions) } });
+ }
+ if (display.EdgeLines.Count > 0)
+ {
+ // Model edges keep a translucent part readable: every B-rep edge as a dark line.
+ var edgePositions = display.EdgeLines.SelectMany(line => line.Zip(line.Skip(1), (a, b) => a.Concat(b)).SelectMany(p => p)).ToArray();
+ materials.Add(new { name = "Model edges", pbrMetallicRoughness = new { baseColorFactor = new[] { .16, .2, .26, 1 }, metallicFactor = 0, roughnessFactor = 1 },
+ emissiveFactor = new[] { .16, .2, .26 } });
+ meshes.Add(new { name = "edges", primitives = new[] { new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(edgePositions, 3, true) }, mode = 1, material = materials.Count - 1 } },
+ extras = new { role = "B-rep edges" } });
+ roots.Add(nodes.Count);
+ nodes.Add(new { name = "Edges", mesh = meshes.Count - 1 });
}
foreach (var (camera,index) in (cameras ?? []).Select((c,i) => (c,i)))
{
@@ -200,7 +234,7 @@ public static class AssemblyGlbExporter
nodes.Add(new { name = "Aetheris mm Z-up to glTF m Y-up", matrix = new double[] {.001,0,0,0, 0,0,-.001,0, 0,.001,0,0, 0,0,0,1}, children = roots });
var document = new Dictionary<string, object>
{
- ["asset"] = new { version = "2.0", generator = "Aetheris PRESENTATION-3D-X0", extras = new { modelName = display.Name, authority = "BRep/STEP; GLB is a presentation asset", sourceProject = "Aetheris", pmiSchema = "aetheris/pmi-display/1", pmiUnits = "mm", pmi = JsonSerializer.SerializeToElement(display.Annotations, pmiJsonOptions) } },
+ ["asset"] = new { version = "2.0", generator = "Aetheris PRESENTATION-3D-X0", extras = new { modelName = display.Name, authority = "BRep/STEP; GLB is a presentation asset", sourceProject = "Aetheris", pmiSchema = "aetheris/pmi-display/1", pmiUnits = "mm", pmi = JsonSerializer.SerializeToElement(display.Annotations.Select(Metadata), pmiJsonOptions) } },
["scene"] = 0, ["scenes"] = new[] { new { name = display.Name, nodes = new[] { nodes.Count - 1 } } },
["nodes"] = nodes, ["meshes"] = meshes, ["materials"] = materials,
["accessors"] = accessors, ["bufferViews"] = views, ["buffers"] = new[] { new { byteLength = checked((int)binary.Length) } }
@@ -218,6 +252,10 @@ public static class AssemblyGlbExporter
return result.ToArray();
}
+ /// <summary>GLB metadata carries the semantic record and its anchors; geometry stays in the buffers.</summary>
+ private static Visualization.PmiDisplayAnnotation Metadata(Visualization.PmiDisplayAnnotation annotation) =>
+ annotation with { Lines = [], Target = annotation.Target is { } target ? target with { Positions = [], Normals = [], Indices = [], Lines = [] } : null };
+
private static void ValidateTransform(double[] m)
{
var t = Transform3D.FromRowMajor(m);
diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs
index c68f9123..20cee9f1 100644
--- a/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs
+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs
@@ -10,6 +10,32 @@ namespace Aetheris.Kernel.Firmament.Execution;
internal static class FirmamentSelectorResolver
{
+ /// <summary>
+ /// PMI meaning of an axis face such as <c>face(-X)</c>: every planar face lying in the body's
+ /// extreme support plane in that direction, the surface a datum simulator would contact.
+ /// Construction may split one physical face into several coplanar patches; they are returned
+ /// together. Empty when the extreme in that direction is not planar.
+ /// </summary>
+ internal static IReadOnlyList<FaceId> ResolveSupportPlaneFaces(BrepBody body, string selector)
+ {
+ var port = selector[(selector.LastIndexOf('.') + 1)..];
+ Vector3D? axis = port switch { "top_face" => new(0, 0, 1), "bottom_face" => new(0, 0, -1),
+ "plus_x_face" => new(1, 0, 0), "minus_x_face" => new(-1, 0, 0), "plus_y_face" => new(0, 1, 0), "minus_y_face" => new(0, -1, 0), _ => null };
+ if (axis is not { } a) return [];
+ var planes = body.Topology.Faces.Select(face => (face.Id, Plane: body.TryGetFaceSurfaceGeometry(face.Id, out var surface) ? surface?.Plane : null))
+ .Where(f => f.Plane is { } plane && plane.Normal.ToVector().Dot(a) > 1 - 1e-8)
+ .Select(f => (f.Id, Offset: (f.Plane!.Value.Origin - Point3D.Origin).Dot(a))).ToArray();
+ if (planes.Length == 0) return [];
+ var extreme = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? (p - Point3D.Origin).Dot(a) : double.NegativeInfinity)
+ .Concat(body.Topology.Edges.Select(e => body.TryGetEdgeCurveGeometry(e.Id, out var curve) && curve?.Circle3 is { } circle
+ ? (circle.Center - Point3D.Origin).Dot(a) + circle.Radius * Math.Sqrt(Math.Max(0, 1 - Math.Pow(circle.Normal.ToVector().Dot(a), 2)))
+ : double.NegativeInfinity))
+ .DefaultIfEmpty(double.NegativeInfinity).Max();
+ var support = planes.Max(p => p.Offset);
+ if (support < extreme - 1e-7) return [];
+ return planes.Where(p => Math.Abs(p.Offset - support) < 1e-7).Select(p => p.Id).ToArray();
+ }
+
/// <summary>Resolve an existing axis-face port only when it denotes exactly one planar face.
/// A stepped body with multiple same-facing planes remains ambiguous.</summary>
internal static IReadOnlyList<FaceId> ResolveUniquePlanarFace(BrepBody body, string selector)
diff --git a/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs b/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
index 03938074..21c97ba5 100644
--- a/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
+++ b/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
@@ -72,6 +72,8 @@ public static class ProductArtifactExporter
case "glb":
var annotatedDisplay = source.StepText is not null && source.Assembly is null && source.Scene is null
? source.Display with { Annotations = Visualization.PmiDisplayProjection.FromStep(source.StepText, source.Display.TessellationOptions) } : source.Display;
+ if (annotatedDisplay.Annotations.Count > 0)
+ annotatedDisplay = annotatedDisplay with { EdgeLines = Visualization.PmiDisplayProjection.EdgeLines(source.StepText!, source.Display.TessellationOptions) };
bytes = source.Scene is { } scene ? SceneExport.Glb(scene) : AssemblyGlbExporter.Serialize(annotatedDisplay,
occurrenceLooks: source.Assembly?.Instances.Where(i => i.Appearance is not null)
.ToDictionary(i => i.StableId, i => i.Appearance!, StringComparer.Ordinal));
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs
new file mode 100644
index 00000000..f81281d7
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ComposeFaces.cs
@@ -0,0 +1,66 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Topology;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament;
+
+public static partial class FirmamentBuildAndExport
+{
+ /// <summary>
+ /// PMI targets that name a Compose operation's planar cap: <c>face(op.Top)</c> for Base and
+ /// Boss, <c>face(op.Bottom)</c> for Base and <c>face(op.Floor)</c> for Pocket. A cap is the
+ /// planar face at the operation's level whose normal points out of the material. When more
+ /// than one face sits at that level, only faces bounded by the operation's own profile walls
+ /// are kept. A target that does not resolve to exactly one face maps to no faces, so the
+ /// exporter's existing unresolved-target diagnostics reject it rather than guess.
+ /// </summary>
+ internal static IReadOnlyDictionary<string, int[]> ComposeOperationCapFaces(
+ PrismaticProfileCompositionFeature feature, BrepBody body, SemanticTopologyCorrespondence? correspondence)
+ {
+ var caps = new List<(string Target, string Profile, double Level, bool Up)>();
+ foreach (var operation in feature.Operations.Where(o => o.Intent == PrismaticProfileIntent.Base))
+ {
+ caps.Add(($"face({operation.Name}.Top)", operation.ProfileReference, operation.To, true));
+ caps.Add(($"face({operation.Name}.Bottom)", operation.ProfileReference, operation.From, false));
+ }
+ foreach (var boss in feature.Bosses ?? []) caps.Add(($"face({boss.Name}.Top)", boss.ProfileReference, boss.To, true));
+ foreach (var pocket in feature.Pockets ?? []) caps.Add(($"face({pocket.Name}.Floor)", pocket.ProfileReference, pocket.From, true));
+
+ var result = new Dictionary<string, int[]>(StringComparer.Ordinal);
+ foreach (var (target, profile, level, up) in caps)
+ {
+ var candidates = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var surface)
+ && surface?.Plane is { } plane
+ && Math.Abs(plane.Normal.ToVector().Z - (up ? 1 : -1)) < 1e-8
+ && Math.Abs(plane.Origin.Z - level) < 1e-7)
+ .Select(face => face.Id).ToArray();
+ if (candidates.Length > 1 && correspondence is not null)
+ {
+ // Profile walls carry their source profile; a cap belongs to the operation whose walls bound it.
+ var wallFaces = correspondence.Descendants
+ .Where(d => d.Face.HasValue && d.Role == SemanticTopologyRole.ExtrusionSideFace
+ && d.SourceStableId.Contains("_" + profile + "_", StringComparison.Ordinal))
+ .Select(d => d.Face!.Value.Value).ToHashSet();
+ candidates = candidates.Where(face => Neighbours(body, face).Any(wallFaces.Contains)).ToArray();
+ }
+ result[target] = candidates.Length == 1 ? [candidates[0].Value] : [];
+ }
+ return result;
+ }
+
+ private static IEnumerable<int> Neighbours(BrepBody body, FaceId face)
+ {
+ var edges = body.Topology.GetFace(face).LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
+ .Select(id => body.Topology.GetCoedge(id).EdgeId).ToHashSet();
+ return body.Topology.Faces.Where(other => other.Id != face && other.LoopIds
+ .SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
+ .Any(id => edges.Contains(body.Topology.GetCoedge(id).EdgeId)))
+ .Select(other => other.Id.Value);
+ }
+
+ /// <summary>The cap selector spellings 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)"));
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
index 1ba3ea00..60014f97 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
@@ -39,7 +39,8 @@ public static partial class FirmamentBuildAndExport
var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(h => h.Name, h => h.StableId, StringComparer.Ordinal);
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).ToArray();
+ pmi = BuildV2SemanticPmi(document, [], stack.Feature.Name, features, planned.Correspondence, planned.Body,
+ ComposeOperationCapFaces(stack.Feature, planned.Body, planned.Correspondence)).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 3b2bb252..16ed1fca 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -526,7 +526,8 @@ public static partial class FirmamentBuildAndExport
var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);
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).ToArray();
+ semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence, completedBody,
+ ComposeOperationCapFaces(stack.Feature, completedBody, emitted.Correspondence)).ToArray();
}
var step = Step242Exporter.ExportBody(completedBody, semanticPmi);
if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
@@ -1195,7 +1196,8 @@ public static partial class FirmamentBuildAndExport
var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);
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).ToArray();
+ semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence, plannedEmission.Body,
+ ComposeOperationCapFaces(stack.Feature, plannedEmission.Body, plannedEmission.Correspondence)).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);
@@ -2866,7 +2868,7 @@ 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) && Step242GeometricToleranceKinds.Find(kind.ToString()) is null
+ var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Note) && 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."
@@ -2880,7 +2882,8 @@ public static partial class FirmamentBuildAndExport
string targetSolid,
IReadOnlyDictionary<string, string>? explicitFeatureIds = null,
SemanticTopologyCorrespondence? correspondence = null,
- BrepBody? body = null)
+ BrepBody? body = null,
+ IReadOnlyDictionary<string, int[]>? namedFaces = null)
{
if (document.Pmi is null || document.Pmi.Count == 0)
{
@@ -2928,24 +2931,47 @@ public static partial class FirmamentBuildAndExport
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.Note && boundPmiByName.TryGetValue(pmi.Name, out var note) && note.Text is { } text)
+ {
+ result.Add(new Step242SemanticPmiNote(pmi.Name, targetSolid, text));
+ }
else if (pmi.Kind == FirmamentV2PmiKind.DatumPlane)
{
var selector = TryResolveV2RecognizedRegionTarget(document, targetBinding, pmi.Target, out var recognizedDatumTarget) ? recognizedDatumTarget : ResolveV2DatumTarget(targetBinding, pmi.Target);
- result.Add(new Step242SemanticPmiDatum(targetSolid, "plane", pmi.Name, selector));
+ result.Add(new Step242SemanticPmiDatum(targetSolid, "plane", pmi.Name, selector)
+ { GeometricFaceIds = namedFaces?.GetValueOrDefault(pmi.Target) ?? [], RequiresFaceAssociation = true });
}
else if (Step242GeometricToleranceKinds.Find(pmi.Kind.ToString()) is { } control && boundPmiByName.TryGetValue(pmi.Name, out var boundControl))
{
var feature = holeByName.TryGetValue(pmi.Target, out var hole) ? hole.FeatureId
: boundControl.HoleWallTarget is { } wall && holeByName.TryGetValue(wall.HoleName, out var wallFeature) ? wallFeature.FeatureId
: explicitFeatureIds?.GetValueOrDefault(pmi.Target) ?? $"{targetSolid}.{pmi.Name}";
- var faces = body is not null && FirmamentSelectorResolver.ResolveUniquePlanarFace(body, ResolveV2DatumTarget(targetBinding, pmi.Target)) is { Count: > 0 } planarFaces
+ var faces = namedFaces?.GetValueOrDefault(pmi.Target) is { } named ? named
+ : body is not null && FirmamentSelectorResolver.ResolveSupportPlaneFaces(body, ResolveV2DatumTarget(targetBinding, pmi.Target)) is { Count: > 0 } planarFaces
? planarFaces.Select(id => id.Value).ToArray() : Array.Empty<int>();
result.Add(new Step242SemanticPmiGeometricTolerance(feature, pmi.Name, control.Name, boundControl.ControlTolerance!.NumericValue!.Value, boundControl.DatumRefs)
{ Modifiers = boundControl.Modifiers, ZoneForm = boundControl.ZoneForm, GeometricFaceIds = faces });
}
}
- return result.Select(item => item with
+ // A hole-list target associates one requirement with the shaft walls of every listed hole.
+ int[] ShaftFaces(string featureId) => (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).ToArray();
+ var holeSets = boundPmiByName.Values.Where(b => b.Targets.Count > 1 && b.Kind != FirmamentV2PmiKind.Distance)
+ .ToDictionary(b => b.Name, b =>
+ {
+ var ids = b.Targets.Select(t => holeByName.TryGetValue(t, out var h) ? h.FeatureId : explicitFeatureIds?.GetValueOrDefault(t)).ToArray();
+ return ids.Any(id => id is null) ? [-1] : ids.SelectMany(id => ShaftFaces(id!)).Distinct().Order().ToArray();
+ }, StringComparer.Ordinal);
+ return result.Select(item => holeSets.TryGetValue(item switch { Step242SemanticPmiHole h => h.Name ?? "", Step242SemanticPmiGeometricTolerance g => g.Name, _ => "" }, out var setFaces)
+ ? item switch
+ {
+ Step242SemanticPmiHole h => h with { GeometricFaceIds = setFaces, Quantity = boundPmiByName[h.Name!].Targets.Count },
+ Step242SemanticPmiGeometricTolerance g => g with { GeometricFaceIds = setFaces, Quantity = boundPmiByName[g.Name].Targets.Count },
+ _ => item
+ } : item).Select(item => item with
{
// Imported entity numbers are provenance, not emitted entity numbers or face ordinals.
// The importer owns the source-entity -> BRep mapping; the exporter owns the inverse
@@ -2953,7 +2979,7 @@ public static partial class FirmamentBuildAndExport
GeometricFaceIds = importedFaces.TryGetValue(item switch
{ Step242SemanticPmiDatum d => d.Label, Step242SemanticPmiHole h => h.Name ?? "", Step242SemanticPmiGeometricTolerance g => g.Name, _ => "" }, out var faces)
? faces : item.GeometricFaceIds.Count > 0 ? item.GeometricFaceIds : item is Step242SemanticPmiDatum datum && body is not null
- ? FirmamentSelectorResolver.ResolveUniquePlanarFace(body, datum.Target).Select(id => id.Value).ToArray()
+ ? FirmamentSelectorResolver.ResolveSupportPlaneFaces(body, datum.Target).Select(id => id.Value).ToArray()
: (correspondence?.Descendants ?? [])
.Where(descendant => descendant.Face.HasValue
&& (string.Equals(descendant.SourceStableId, item.FeatureId, StringComparison.Ordinal)
@@ -2961,8 +2987,9 @@ public static partial class FirmamentBuildAndExport
// Shaft dimensions follow semantic wall ownership, not the
// asserted PMI number: contradictory PMI must keep its target
// so downstream geometry/requirement checks can diagnose it.
- .Where(descendant => item is not Step242SemanticPmiHole
- || descendant.Role is not (SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCountersinkWallFace))
+ // A hole's size and geometric controls apply to its shaft; counterbore
+ // and countersink walls are separate features with their own sizes.
+ .Where(descendant => descendant.Role is not (SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCountersinkWallFace))
.Select(descendant => descendant.Face!.Value.Value)
.Distinct()
.Order()
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index f1d6bf38..f44ce769 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 }
+ Straightness, Roundness, Cylindricity, Parallelism, Perpendicularity, Angularity, Position, LineProfile, SurfaceProfile, CircularRunout, TotalRunout, Note }
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);
@@ -306,6 +306,8 @@ public sealed record FirmamentV2BoundPmiRecord(FirmamentV2PmiKind Kind, string N
public IReadOnlyList<FirmamentV2ValueOrigin> DimensionOrigins { get; init; } = [];
public IReadOnlyList<string> Modifiers { get; init; } = [];
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>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/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
index 8941f088..03fb5ad2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -89,7 +89,7 @@ public static partial class FirmamentV2Parser
{ SourceSpan = wholeStockFinish.Span, Stage = "Capability" }] };
}
if (constructions.Length > 1 && constructions.All(d => d.Type.Name.Text == "Extrude") && primitives.Length == 0)
- return BindMechanicalExtrusionStack(model, constructions, source, diagnostics);
+ return BindMechanicalExtrusionStack(model, constructions, source, diagnostics, staticValues.Values);
if (constructions.Length > 1 || materialConstruction && primitives.Length > 0)
return CanonicalFailure(diagnostics, "firmament-v2-mechanical-material-owners-unsupported: Use one material body per mechanical document; use Assembly for separate parts.");
if (constructionConsumer)
@@ -98,7 +98,7 @@ public static partial class FirmamentV2Parser
// unused Static is data, never a reason to reject a material owner.
var construction = constructions.Length == 1 && IsCoaxialComposition(constructions[0])
? BindCoaxialComposition(model, constructions[0], source, diagnostics, staticValues.Values)
- : BindMechanicalConstruction(source, model, diagnostics, templateInstantiations, compileTime);
+ : BindMechanicalConstruction(source, model, diagnostics, templateInstantiations, compileTime, staticValues.Values);
return construction.Document is null ? construction : construction with
{
Document = construction.Document with { Lets = staticValues.Declarations, BoundLets = staticValues.Values },
@@ -250,7 +250,7 @@ public static partial class FirmamentV2Parser
// Multiple explicit extrusions are material requests, not alternative parser
// hints. Bind every one into the existing section-stack engineering IR.
private static FirmamentV2ParseResult BindMechanicalExtrusionStack(DeclarationSyntax model, IReadOnlyList<DeclarationSyntax> extrusions,
- string source, List<string> diagnostics)
+ string source, List<string> diagnostics, IReadOnlyList<FirmamentV2BoundLet> statics)
{
var units = model.Body!.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();
if (units.Length == 0 && model.Type.Name.Text != "Struct" || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm")) return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);
@@ -289,7 +289,7 @@ public static partial class FirmamentV2Parser
{ [name] = new(name, "Compose", new FirmamentV2AdvancedMaterialRecord("Compose")) };
var selections = ParseCanonicalSelections(source, 0, diagnostics);
ValidateCanonicalSelectionSources(source, selections, profiles.Keys, diagnostics);
- var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, [], [], [], [], diagnostics);
+ var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, [], [], statics, [], diagnostics);
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var document = new FirmamentV2Document(name, "mm", solids.Values.ToArray(),
Pmi: pmi, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections,
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index a778645a..5063d1db 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1243,8 +1243,11 @@ public static partial class FirmamentV2Parser
return adapterSource[..start] + text + adapterSource[(start + extrude.Span.Length)..];
}
- private static FirmamentV2ParseResult BindMechanicalConstruction(string source, DeclarationSyntax model, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null)
+ private static FirmamentV2ParseResult BindMechanicalConstruction(string source, DeclarationSyntax model, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null, IReadOnlyList<FirmamentV2BoundLet>? statics = null)
{
+ // Typed Static values are bound once by the mechanical model binder. PMI `dimension:`
+ // references them here exactly as it does on primitive stock.
+ statics ??= [];
source = MechanicalConstructionSource(source, model, diagnostics);
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
// Re-index the existing AST after local source transport; semantic binding
@@ -1298,7 +1301,8 @@ public static partial class FirmamentV2Parser
[feature.Name] = new FirmamentV2SolidBinding(feature.Name, "Compose", new FirmamentV2AdvancedMaterialRecord("Compose"))
};
var (compositionPmi, compositionPmiBlock, compositionBoundPmi) = ParsePmi(
- source, compositionSolids, [], [], [], [], diagnostics, (feature.ShaftHoles ?? []).Select(hole => hole.Name).Concat((feature.CounterboreHoles ?? []).Select(hole => hole.Name)).Concat((feature.CountersinkHoles ?? []).Select(hole => hole.Name)));
+ 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));
// 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);
@@ -1344,7 +1348,7 @@ public static partial class FirmamentV2Parser
{
[resolved.Name] = new FirmamentV2SolidBinding(resolved.Name, "Profile", new FirmamentV2AdvancedMaterialRecord("Profile"))
};
- var (profilePmi, profilePmiBlock, profileBoundPmi) = ParsePmi(source, profileSolids, [], [], [], [], diagnostics);
+ var (profilePmi, profilePmiBlock, profileBoundPmi) = ParsePmi(source, profileSolids, [], [], statics, [], diagnostics);
// 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);
@@ -2365,7 +2369,8 @@ public static partial class FirmamentV2Parser
IReadOnlyList<FirmamentV2BoundLet> boundLets,
IReadOnlyList<FirmamentV2BoundLetRecord> boundLetRecords,
List<string> diagnostics,
- IEnumerable<string>? additionalHoleNames = null)
+ IEnumerable<string>? additionalHoleNames = null,
+ IEnumerable<string>? namedFaceTargets = null)
{
var matches = PmiHeaderRegex.Matches(source);
if (matches.Count == 0) return ([], null, null);
@@ -2395,7 +2400,7 @@ public static partial class FirmamentV2Parser
var recordMap = boundLetRecords.ToDictionary(r => r.Name, StringComparer.Ordinal);
var holeNames = modifyBlocks.SelectMany(m => m.SemanticHoles).Select(h => h.Name).Concat(additionalHoleNames ?? []).ToHashSet(StringComparer.Ordinal);
var regionByTarget = recognizedRegions.ToDictionary(r => r.TargetSource, r => r, StringComparer.Ordinal);
- var aliases = solids.Values.SelectMany(s => s.Box?.Exposures ?? []).Select(e => e.Alias).ToHashSet(StringComparer.Ordinal);
+ var aliases = solids.Values.SelectMany(s => s.Box?.Exposures ?? []).Select(e => e.Alias).Concat(namedFaceTargets ?? []).ToHashSet(StringComparer.Ordinal);
foreach (Match em in PmiEntryHeaderRegex.Matches(body))
{
@@ -2457,6 +2462,7 @@ public static partial class FirmamentV2Parser
private static string NormalizePmiField(string raw) => raw switch
{
+ "Text" => "text",
"Target" => "target",
"TargetA" => "targetA",
"TargetB" => "targetB",
@@ -2478,6 +2484,12 @@ public static partial class FirmamentV2Parser
private static void ValidatePmiFieldSet(string kind, string name, IReadOnlyDictionary<string,FirmamentV2PmiField> fields, List<string> diagnostics)
{
+ if (kind == "Note")
+ {
+ if (!fields.ContainsKey("text")) diagnostics.Add($"{PmiMissingRequiredField}:{name}: Note requires text");
+ foreach (var f in fields.Keys.Where(f => f != "text")) diagnostics.Add($"{PmiUnknownField}:{name}.{f}");
+ return;
+ }
string[] required = kind switch { "datum"=>["target"], "diameter"=> fields.ContainsKey("dimension") ? ["target","dimension"] : fields.ContainsKey("diameter") ? ["target","diameter"] : ["target","value"], "distance"=>["targetA","targetB","dimension"], "flatness"=>["target","tolerance"], "parallel" or "perpendicular" or "coplanar"=>["target","datum","tolerance"], _=>[] };
if (TryPmiKind(kind, out var parsedKind) && Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(parsedKind.ToString()) is { } control)
required = control.RequiresDatum ? ["target", "datum", "tolerance"] : ["target", "tolerance"];
@@ -2490,10 +2502,34 @@ 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!;
+ if (r.Kind == FirmamentV2PmiKind.Note)
+ {
+ // A part-level note: JSON string escapes, no control characters, never empty.
+ string? text = null;
+ try { text = Field(r, "text") is { } raw && raw.StartsWith('"') ? System.Text.Json.JsonSerializer.Deserialize<string>(raw) : null; }
+ catch (System.Text.Json.JsonException) { }
+ if (string.IsNullOrWhiteSpace(text) || text.Any(char.IsControl))
+ { diagnostics.Add($"firmament-v2-pmi-note-text-invalid:{r.Name}: Note text is a non-empty quoted string without control characters"); return false; }
+ bound = new(r.Kind, r.Name, ["part"], null, null, null, [], r.SourceSpan) { Text = text };
+ return true;
+ }
string? target = Field(r,"target"); string? targetA=Field(r,"targetA"); string? targetB=Field(r,"targetB");
var targets = new[]{target,targetA,targetB}.Where(t=>t is not null).Cast<string>().ToArray();
FirmamentV2HoleWallSelector? wallTarget = null;
- foreach (var t in targets)
+ // A list of holes is one requirement on every listed hole (a "4X" callout).
+ var holeSet = target is not null && target.TrimStart().StartsWith('[');
+ if (holeSet)
+ {
+ var listed = PmiNames(target, diagnostics);
+ if (r.Kind != FirmamentV2PmiKind.HoleDiameter && Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(r.Kind.ToString()) is null)
+ diagnostics.Add($"{PmiInvalidTarget}:{r.Name}: only HoleDiameter and geometric controls accept a list of holes");
+ else if (listed.Count < 2 || listed.Distinct(StringComparer.Ordinal).Count() != listed.Count)
+ diagnostics.Add($"{PmiInvalidTarget}:{r.Name}: a hole list names two or more distinct holes");
+ foreach (var name in listed.Where(name => !holeNames.Contains(name)))
+ diagnostics.Add($"{PmiTargetUnresolved}:{r.Name}: '{name}' is not a hole of this part");
+ targets = listed.ToArray();
+ }
+ foreach (var t in holeSet ? [] : targets)
{
if (!FirmamentV2HoleWallSelector.TryParse(t, out var holeName))
{
diff --git a/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs b/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs
index 40ade5ba..6b9c3a9f 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs
@@ -24,6 +24,52 @@ public static class PlanarTextProfiles
{
private static readonly Lazy<Typeface> DefaultTypeface = new(LoadInter);
+ /// <summary>Presentation text as flattened closed polygons, one per glyph contour, with the
+ /// line's advance width. Counters (holes) are separate polygons; fill with even-odd.</summary>
+ internal static (IReadOnlyList<(int Glyph, (double X, double Y)[] Points)> Contours, double Width) PresentationPolygons(string content, double height)
+ {
+ if (string.IsNullOrEmpty(content) || content.IndexOfAny(['\r', '\n']) >= 0 || !double.IsFinite(height) || height <= 0)
+ throw new InvalidOperationException("pmi-display-text-invalid");
+ var typeface = DefaultTypeface.Value;
+ var scale = height / typeface.UnitsPerEm;
+ var cursor = 0d;
+ var polygons = new List<(int Glyph, (double X, double Y)[] Points)>();
+ var glyphNumber = 0;
+ foreach (var rune in content.EnumerateRunes())
+ {
+ glyphNumber++;
+ var index = typeface.GetGlyphIndex(rune.Value);
+ if (index == 0) throw new InvalidOperationException($"pmi-display-text-unsupported: Missing glyph U+{rune.Value:X4}.");
+ var glyph = typeface.GetGlyph(index);
+ if (glyph.IsCffGlyph) throw new InvalidOperationException("pmi-display-text-unsupported: CFF glyph.");
+ var translator = new OutlineTranslator();
+ IGlyphReaderExtensions.Read(translator, glyph.GlyphPoints, glyph.EndPoints);
+ foreach (var contour in translator.Contours.Select(c => c.Transform(cursor, scale)))
+ {
+ var points = new List<(double X, double Y)>();
+ foreach (var curve in contour.Curves)
+ switch (curve)
+ {
+ case LineArcLineSegment2D line: points.Add(line.Start); break;
+ case LineArcCubicBezier2D cubic:
+ for (var i = 0; i < 4; i++)
+ {
+ var t = i / 4d; var s = 1 - t;
+ points.Add((s*s*s*cubic.Start.X + 3*s*s*t*cubic.Control1.X + 3*s*t*t*cubic.Control2.X + t*t*t*cubic.End.X,
+ s*s*s*cubic.Start.Y + 3*s*s*t*cubic.Control1.Y + 3*s*t*t*cubic.Control2.Y + t*t*t*cubic.End.Y));
+ }
+ break;
+ default: throw new InvalidOperationException("pmi-display-font-curve-unsupported");
+ }
+ var distinct = points.Where((p, i) => i == 0 || Math.Abs(p.X - points[i - 1].X) + Math.Abs(p.Y - points[i - 1].Y) > 1e-9).ToList();
+ if (distinct.Count > 2 && Math.Abs(distinct[0].X - distinct[^1].X) + Math.Abs(distinct[0].Y - distinct[^1].Y) < 1e-9) distinct.RemoveAt(distinct.Count - 1);
+ if (distinct.Count >= 3) polygons.Add((glyphNumber, distinct.ToArray()));
+ }
+ cursor += typeface.GetAdvanceWidthFromGlyphIndex(index) * scale;
+ }
+ return (polygons, cursor);
+ }
+
/// <summary>Presentation contours only. Drawing an outline does not require the
/// material-island arrangement/Boolean normalization used for engineering text.</summary>
internal static IReadOnlyList<LineArcProfileCurve2D> PresentationContours(string content, double height)
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs
new file mode 100644
index 00000000..0ce13612
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayLayout.cs
@@ -0,0 +1,284 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Visualization;
+
+/// <summary>
+/// 2D drafting canvas for one annotation block: polylines, filled glyphs and symbols, and a
+/// background panel. Units are millimetres; x runs along the text, y up.
+/// </summary>
+internal sealed class PmiCanvas
+{
+ public List<(double X, double Y)[]> Lines { get; } = [];
+ public List<(double X, double Y)> Fill { get; } = [];
+ public List<int> FillIndices { get; } = [];
+ public List<(double X, double Y)> Panel { get; } = [];
+ public List<int> PanelIndices { get; } = [];
+
+ public void Line(params (double X, double Y)[] points) => Lines.Add(points);
+
+ public void Rect(double x, double y, double w, double h) => Line((x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y));
+
+ public void Circle(double cx, double cy, double r, int segments = 32) =>
+ Line(Enumerable.Range(0, segments + 1).Select(i => (cx + r * Math.Cos(2 * Math.PI * i / segments), cy + r * Math.Sin(2 * Math.PI * i / segments))).ToArray());
+
+ public void Triangle((double X, double Y) a, (double X, double Y) b, (double X, double Y) c)
+ {
+ var o = Fill.Count; Fill.Add(a); Fill.Add(b); Fill.Add(c); FillIndices.AddRange([o, o + 1, o + 2]);
+ }
+
+ public void PanelRect(double x, double y, double w, double h)
+ {
+ var o = Panel.Count;
+ Panel.AddRange([(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
+ PanelIndices.AddRange([o, o + 1, o + 2, o, o + 2, o + 3]);
+ }
+
+ /// <summary>Filled text with its baseline at <paramref name="y"/>; returns the advance width.</summary>
+ public double Text(string text, double x, double y, double height)
+ {
+ var (contours, width) = PlanarTextProfiles.PresentationPolygons(text, height);
+ // Fill glyph by glyph: bands stay local, so the triangle count follows the glyph outlines.
+ foreach (var glyph in contours.GroupBy(c => c.Glyph))
+ 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());
+ return width;
+ }
+
+ /// <summary>
+ /// Nonzero-winding fill by horizontal trapezoids. Font outlines may overlap (variable-font
+ /// masters keep overlapping contours), so bands also break at every edge crossing.
+ /// </summary>
+ private void FillNonZero(IReadOnlyList<(double X, double Y)[]> contours)
+ {
+ var edges = contours.SelectMany(c => c.Select((p, i) => (A: p, B: c[(i + 1) % c.Length])))
+ .Where(e => Math.Abs(e.A.Y - e.B.Y) > 1e-12).ToArray();
+ var levels = edges.SelectMany(e => new[] { e.A.Y, e.B.Y }).ToList();
+ for (var i = 0; i < edges.Length; i++)
+ for (var j = i + 1; j < edges.Length; j++)
+ if (Crossing(edges[i], edges[j]) is { } yc) levels.Add(yc);
+ var ys = levels.Order().Aggregate(new List<double>(), (list, v) => { if (list.Count == 0 || v - list[^1] > 1e-9) list.Add(v); return list; });
+ static double XAt(((double X, double Y) A, (double X, double Y) B) e, double yy) => e.A.X + (e.B.X - e.A.X) * (yy - e.A.Y) / (e.B.Y - e.A.Y);
+ for (var k = 0; k + 1 < ys.Count; k++)
+ {
+ var y0 = ys[k]; var y1 = ys[k + 1]; var mid = (y0 + y1) / 2;
+ var active = edges.Where(e => Math.Min(e.A.Y, e.B.Y) <= mid && Math.Max(e.A.Y, e.B.Y) >= mid)
+ .Select(e => (X0: XAt(e, y0), X1: XAt(e, y1), XM: XAt(e, mid), W: e.B.Y > e.A.Y ? 1 : -1)).OrderBy(e => e.XM).ToArray();
+ var winding = 0;
+ for (var a = 0; a + 1 < active.Length; a++)
+ {
+ winding += active[a].W;
+ if (winding == 0) continue;
+ var l = active[a]; var r = active[a + 1];
+ var o = Fill.Count;
+ Fill.AddRange([(l.X0, y0), (r.X0, y0), (r.X1, y1), (l.X1, y1)]);
+ FillIndices.AddRange([o, o + 1, o + 2, o, o + 2, o + 3]);
+ }
+ }
+ }
+
+ private static double? Crossing(((double X, double Y) A, (double X, double Y) B) p, ((double X, double Y) A, (double X, double Y) B) q)
+ {
+ var r = (X: p.B.X - p.A.X, Y: p.B.Y - p.A.Y); var s = (X: q.B.X - q.A.X, Y: q.B.Y - q.A.Y);
+ var denominator = r.X * s.Y - r.Y * s.X;
+ if (Math.Abs(denominator) < 1e-15) return null;
+ var t = ((q.A.X - p.A.X) * s.Y - (q.A.Y - p.A.Y) * s.X) / denominator;
+ var u = ((q.A.X - p.A.X) * r.Y - (q.A.Y - p.A.Y) * r.X) / denominator;
+ return t > 1e-9 && t < 1 - 1e-9 && u > 1e-9 && u < 1 - 1e-9 ? p.A.Y + t * r.Y : null;
+ }
+
+ public static double TextWidth(string text, double height) => PlanarTextProfiles.PresentationPolygons(text, height).Width;
+
+ 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()));
+ 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));
+ }
+}
+
+/// <summary>A laid-out drafting block: its canvas spans [0, Width] x [0, Height].</summary>
+internal sealed record PmiBlock(PmiCanvas Canvas, double Width, double Height);
+
+/// <summary>
+/// Drafting conventions for 3D callouts (ASME Y14.5 / Y14.41 shapes): feature control frames,
+/// datum feature symbols, size callouts with quantity, basic dimensions and notes.
+/// </summary>
+internal static class PmiDrafting
+{
+ /// <summary>Tolerance-zone prefix: Ø cylindrical, SØ spherical, none between two surfaces (the default form).</summary>
+ public static string ZonePrefix(IReadOnlyList<string> zoneForms) => string.Concat(zoneForms.Select(form => form switch
+ {
+ "cylindrical or circular" => "Ø", "spherical" => "SØ", "between two equidistant surfaces" => "",
+ _ => throw new InvalidOperationException($"pmi-display-zone-unsupported: unsupported zone form '{form}'.")
+ }));
+
+ public static string Number(double value) => Math.Round(value, 4).ToString("0.####", CultureInfo.InvariantCulture);
+
+ public static string Size(Aetheris.Kernel.Core.Step242.Step242SemanticPmiInspectionItem item)
+ {
+ var diameter = item.Kind == "Diameter" || item.DimensionKind?.Equals("diameter", StringComparison.OrdinalIgnoreCase) == true;
+ var quantity = item.Quantity is > 1 ? $"{item.Quantity}X " : "";
+ var nominal = (diameter ? "Ø" : "") + Number(item.Value!.Value);
+ var plus = item.TolerancePlus; var minus = item.ToleranceMinus;
+ if (plus is null || minus is null) return quantity + nominal;
+ if (Math.Abs(plus.Value - minus.Value) < 1e-12) return $"{quantity}{nominal} ±{Number(plus.Value)}";
+ string Signed(double v, bool upper) => v == 0 ? "0" : (upper ? "+" : "-") + Number(v);
+ return $"{quantity}{nominal} {Signed(plus.Value, true)}/{Signed(minus.Value, false)}";
+ }
+
+ /// <summary>One-line text block, optionally boxed (a basic dimension).</summary>
+ public static PmiBlock TextBlock(string text, double h, bool boxed = false)
+ {
+ var c = new PmiCanvas();
+ var pad = .35 * h; var height = 1.7 * h;
+ var width = PmiCanvas.TextWidth(text, h) + 2 * pad;
+ c.PanelRect(0, 0, width, height);
+ c.Text(text, pad, .45 * h, h);
+ if (boxed) c.Rect(0, 0, width, height);
+ return new(c, width, height);
+ }
+
+ public static PmiBlock DatumBox(string label, double h)
+ {
+ var c = new PmiCanvas();
+ var size = 1.9 * h;
+ var width = Math.Max(size, PmiCanvas.TextWidth(label, h) + .8 * h);
+ c.PanelRect(0, 0, width, size);
+ c.Rect(0, 0, width, size);
+ c.Text(label, (width - PmiCanvas.TextWidth(label, h)) / 2, .55 * h, h);
+ return new(c, width, size);
+ }
+
+ /// <summary>A feature control frame: characteristic | zone/tolerance/modifiers | datums.</summary>
+ public static PmiBlock ControlFrame(string kind, string zonePrefix, double tolerance, IReadOnlyList<string> modifiers,
+ IReadOnlyList<string> datums, double h)
+ {
+ var c = new PmiCanvas();
+ var H = 1.9 * h; var pad = .4 * h;
+ var x = 0d;
+ // Characteristic cell.
+ Symbol(c, kind, x + H / 2, H / 2, .62 * h);
+ x += H; c.Line((x, 0), (x, H));
+ // Tolerance cell: zone, value, material modifiers drawn as circled letters.
+ x += pad;
+ if (zonePrefix.Length > 0) x += c.Text(zonePrefix, x, .5 * h, h);
+ x += c.Text(Number(tolerance), x, .5 * h, h);
+ foreach (var modifier in modifiers)
+ {
+ var letter = modifier switch
+ {
+ "MAXIMUM_MATERIAL_REQUIREMENT" => "M", "LEAST_MATERIAL_REQUIREMENT" => "L", "FREE_STATE" => "F",
+ "STATISTICAL_TOLERANCE" => "ST", "COMMON_ZONE" => "CZ", _ => throw new InvalidOperationException($"pmi-display-modifier-unsupported: {modifier}")
+ };
+ x += .25 * h;
+ if (letter.Length == 1)
+ {
+ var r = .62 * h; var w = PmiCanvas.TextWidth(letter, .78 * h);
+ c.Circle(x + r, H / 2, r);
+ c.Text(letter, x + r - w / 2, H / 2 - .29 * h, .78 * h);
+ x += 2 * r;
+ }
+ else x += c.Text(letter, x, .5 * h, h);
+ }
+ x += pad;
+ c.Line((x, 0), (x, H));
+ foreach (var datum in datums)
+ {
+ var w = Math.Max(H, PmiCanvas.TextWidth(datum, h) + 2 * pad);
+ c.Text(datum, x + (w - PmiCanvas.TextWidth(datum, h)) / 2, .5 * h, h);
+ x += w; c.Line((x, 0), (x, H));
+ }
+ c.Rect(0, 0, x, H);
+ c.PanelRect(0, 0, x, H);
+ return new(c, x, H);
+ }
+
+ /// <summary>Geometric characteristic symbols drawn as vectors (fonts rarely carry them).</summary>
+ private static void Symbol(PmiCanvas c, string kind, double cx, double cy, double s)
+ {
+ switch (kind)
+ {
+ case "Position":
+ c.Circle(cx, cy, .62 * s); c.Line((cx - s, cy), (cx + s, cy)); c.Line((cx, cy - s), (cx, cy + s)); break;
+ case "Flatness":
+ c.Line((cx - s, cy - .45 * s), (cx + .55 * s, cy - .45 * s), (cx + s, cy + .45 * s), (cx - .55 * s, cy + .45 * s), (cx - s, cy - .45 * s)); break;
+ case "Perpendicularity":
+ c.Line((cx - s, cy - .8 * s), (cx + s, cy - .8 * s)); c.Line((cx, cy - .8 * s), (cx, cy + .9 * s)); break;
+ case "Parallelism":
+ c.Line((cx - .9 * s, cy - .8 * s), (cx - .1 * s, cy + .8 * s)); c.Line((cx + .1 * s, cy - .8 * s), (cx + .9 * s, cy + .8 * s)); break;
+ case "Straightness":
+ c.Line((cx - s, cy), (cx + s, cy)); break;
+ case "Roundness":
+ c.Circle(cx, cy, .75 * s); break;
+ case "Cylindricity":
+ c.Circle(cx, cy, .6 * s); c.Line((cx - .95 * s, cy - .85 * s), (cx - .25 * s, cy + .85 * s)); c.Line((cx + .25 * s, cy - .85 * s), (cx + .95 * s, cy + .85 * s)); break;
+ case "Angularity":
+ c.Line((cx + s, cy - .75 * s), (cx - s, cy - .75 * s), (cx + .6 * s, cy + .8 * s)); break;
+ case "LineProfile":
+ c.Line(Enumerable.Range(0, 17).Select(i => (cx + .9 * s * Math.Cos(Math.PI * i / 16), cy - .5 * s + .9 * s * Math.Sin(Math.PI * i / 16))).ToArray()); break;
+ case "SurfaceProfile":
+ c.Line(Enumerable.Range(0, 17).Select(i => (cx + .9 * s * Math.Cos(Math.PI * i / 16), cy - .5 * s + .9 * s * Math.Sin(Math.PI * i / 16))).ToArray());
+ c.Line((cx - .9 * s, cy - .5 * s), (cx + .9 * s, cy - .5 * s)); break;
+ case "CircularRunout":
+ c.Line((cx - .6 * s, cy - .8 * s), (cx + .5 * s, cy + .8 * s));
+ c.Triangle((cx + .5 * s, cy + .8 * s), (cx + .05 * s, cy + .55 * s), (cx + .5 * s, cy + .2 * s)); break;
+ case "TotalRunout":
+ c.Line((cx - .9 * s, cy - .8 * s), (cx + .1 * s, cy + .8 * s)); c.Line((cx - .2 * s, cy - .8 * s), (cx + .8 * s, cy + .8 * s));
+ c.Line((cx - .9 * s, cy - .8 * s), (cx - .2 * s, cy - .8 * s)); break;
+ default: throw new InvalidOperationException($"pmi-display-kind-unsupported: {kind} has no drafting symbol.");
+ }
+ }
+
+ /// <summary>Stack blocks top to bottom, left aligned.</summary>
+ public static PmiBlock Stack(IReadOnlyList<PmiBlock> blocks, double gap)
+ {
+ var canvas = new PmiCanvas();
+ var height = blocks.Sum(b => b.Height) + gap * Math.Max(0, blocks.Count - 1);
+ var y = height;
+ foreach (var block in blocks)
+ {
+ y -= block.Height;
+ canvas.Append(block.Canvas, 0, y);
+ y -= gap;
+ }
+ return new(canvas, blocks.Count == 0 ? 0 : blocks.Max(b => b.Width), height);
+ }
+
+ public static PmiBlock Notes(IReadOnlyList<string> notes, double h)
+ {
+ var lines = new List<string> { "NOTES" };
+ for (var i = 0; i < notes.Count; i++)
+ {
+ var words = notes[i].Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ var current = $"{i + 1}.";
+ foreach (var word in words)
+ {
+ if (current.Length + word.Length + 1 > 52) { lines.Add(current); current = " "; }
+ current += " " + word;
+ }
+ lines.Add(current);
+ }
+ var c = new PmiCanvas();
+ var lineHeight = 1.55 * h; var pad = .6 * h;
+ var width = lines.Max(l => PmiCanvas.TextWidth(l.Trim().Length == 0 ? "." : l, h)) + 2 * pad;
+ var height = lines.Count * lineHeight + pad;
+ c.PanelRect(0, 0, width, height);
+ c.Rect(0, 0, width, height);
+ for (var i = 0; i < lines.Count; i++)
+ if (lines[i].Trim().Length > 0) c.Text(lines[i], pad, height - pad - (i + 1) * lineHeight + .45 * h, h);
+ return new(c, width, height);
+ }
+}
+
+/// <summary>An annotation plane in model space: text runs along U, up is V, the reader looks along -N.</summary>
+internal readonly record struct PmiPlane(Point3D Origin, Vector3D U, Vector3D V)
+{
+ public Vector3D N => U.Cross(V);
+ public Point3D At(double x, double y, double lift = 0) => Origin + U * x + V * y + N * lift;
+ public (double X, double Y) Local(Point3D p) { var d = p - Origin; return (d.Dot(U), d.Dot(V)); }
+}
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
index 426f7984..58a28f95 100644
--- a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
@@ -15,8 +15,16 @@ public sealed record PmiDisplayAnnotation(string Id, string Kind, string Name, s
double[] Anchor, double[] LabelPosition, double TextHeight, IReadOnlyList<double[][]> Lines)
{
public PmiDisplayTarget? Target { get; init; }
+ /// <summary>Filled glyphs, arrowheads and datum triangles (dark), in model millimetres.
+ /// Geometry only: GLB metadata keeps the semantic fields, not these triangles.</summary>
+ [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>Triangles in Z-up millimetres; three coordinates per position.</summary>
+public sealed record PmiDisplayMesh(double[] Positions, int[] Indices);
+
/// <summary>A presentation witness on the associated support, not new engineering geometry.
/// Plane patches stay inside a trimmed display triangle. Cylinders highlight their associated
/// trimmed wall and physical rim wires; the leader evaluates the analytic support.</summary>
@@ -48,162 +56,480 @@ public static class PmiDisplayProjection
var minX = points.Min(p => p.X); var maxX = points.Max(p => p.X);
var minY = points.Min(p => p.Y); var maxY = points.Max(p => p.Y);
var minZ = points.Min(p => p.Z); var maxZ = points.Max(p => p.Z);
- var height = Math.Clamp(Math.Max(Math.Max(maxX - minX, maxY - minY), maxZ - minZ) / 25, .5, 8);
- var result = new List<PmiDisplayAnnotation>();
+ var height = Math.Clamp(Math.Max(Math.Max(maxX - minX, maxY - minY), maxZ - minZ) / 34, .5, 8);
+ var center = new Point3D((minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2);
+
+ // 1. Resolve every semantic record to its exact supports.
+ var specs = new List<Spec>();
+ var notes = 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; }
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)
throw new InvalidOperationException($"pmi-display-kind-unsupported: {item.Kind} '{item.Name}' has no qualified 3D callout yet.");
+ if (item.Kind != "Datum" && item.Value is null) throw new InvalidOperationException($"pmi-display-value-unresolved: '{item.Name}' has no semantic magnitude.");
var targets = item.GeometricFaceEntityIds.Where(id => sourceFaces.TryGetValue(id, out var face)
&& patches.TryGetValue(face, out var patch) && patch.Positions.Count > 0 && patch.TriangleIndices.Count >= 3)
.Select(id => patches[sourceFaces[id]]).ToArray();
if (targets.Length == 0 || targets.Length != item.GeometricFaceEntityIds.Count)
throw new InvalidOperationException($"pmi-display-target-unresolved: '{item.Name}' has no complete geometric face association.");
- double[] label = [maxX + height * 3, maxY - result.Count * height * 2.5, maxZ + height];
- // A section planner can partition one physical cylindrical wall.
- // Admit only a connected set on the same analytic cylinder, and
- // retain every associated patch in the highlight and leaders.
- if (targets.Length != 1 && (item.Kind is "Datum" or "Diameter") && (item.Kind != "Diameter" || !OneCylindricalWall(body, targets)))
- throw new InvalidOperationException($"pmi-display-target-multiple-unsupported: '{item.Name}' requires a multi-face presentation.");
- var internalEdges = targets.SelectMany(p => body.Topology.GetFace(p.FaceId).LoopIds
- .SelectMany(id => body.Topology.GetLoop(id).CoedgeIds).Select(id => body.Topology.GetCoedge(id).EdgeId).Distinct())
- .GroupBy(id => id).Where(g => g.Count() > 1).Select(g => g.Key).ToHashSet();
- var witnesses = targets.Select(p => Target(body, tessellation.Value, p, item.Kind, height, label, internalEdges)).ToArray();
- var (anchorPoint, normal, target) = witnesses[0];
- if (witnesses.Length > 1)
+ var surfaces = targets.Select(t => body.GetFaceSurface(t.FaceId)).ToArray();
+ Feature feature;
+ if (surfaces.All(s => s.Plane is not null))
{
- var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
- foreach (var witness in witnesses)
- {
- var offset = positions.Count / 3;
- positions.AddRange(witness.Marker.Positions); normals.AddRange(witness.Marker.Normals);
- indices.AddRange(witness.Marker.Indices.Select(i => i + offset));
- }
- target = target with { Positions = positions.ToArray(), Normals = normals.ToArray(), Indices = indices.ToArray(), Lines = witnesses.SelectMany(w => w.Marker.Lines).ToArray() };
+ // Construction may split one physical face; it must remain one plane.
+ var plane = surfaces[0].Plane!.Value; var n = plane.Normal.ToVector();
+ if (surfaces.Any(s => s.Plane!.Value.Normal.ToVector().Cross(n).Length > 1e-7 || Math.Abs((s.Plane!.Value.Origin - plane.Origin).Dot(n)) > 1e-7))
+ throw new InvalidOperationException($"pmi-display-target-multiple-unsupported: '{item.Name}' spans more than one plane.");
+ feature = new PlanarFeature(n, targets);
}
- double[] anchor = P(anchorPoint);
- var stem = anchorPoint + normal * target.StemLength;
- string N(double value) => value.ToString("G9", CultureInfo.InvariantCulture);
- string Modifier(string value) => value switch { "MAXIMUM_MATERIAL_REQUIREMENT" => "(M)", "LEAST_MATERIAL_REQUIREMENT" => "(L)", "FREE_STATE" => "(F)", "COMMON_ZONE" => "CZ", "STATISTICAL_TOLERANCE" => "ST", _ => value };
- var datumLabels = item.DatumReferenceFrames.Count > 0 ? item.DatumReferenceFrames.Select(frame => string.Join("-", frame.Labels) + string.Concat(frame.Modifiers.Select(Modifier))) : item.DatumReferences;
- var zoneLabels = string.Join(" ", item.ZoneForms.Select(form => form switch
+ else if (surfaces.All(s => s.Cylinder is not null))
{
- "cylindrical or circular" => "Ø", "spherical" => "SØ",
- "between two equidistant surfaces" => "BetweenSurfaces ",
- _ => throw new InvalidOperationException($"pmi-display-zone-unsupported: '{item.Name}' has unsupported zone form '{form}'.")
- }));
- if (item.Kind != "Datum" && item.Value is null) throw new InvalidOperationException($"pmi-display-value-unresolved: '{item.Name}' has no semantic magnitude.");
- var text = item.Kind == "Datum" ? $"[{item.Name}]" : Step242GeometricToleranceKinds.Find(item.Kind) is not null
- ? $"{item.Kind} | " + zoneLabels + $"{N(item.Value!.Value)} mm" + string.Concat(item.Modifiers.Select(Modifier))
- + (item.DatumReferences.Count > 0 ? " | " + string.Join(" | ", datumLabels) : "")
- : (item.Kind == "Diameter" || item.DimensionKind?.Equals("diameter", StringComparison.OrdinalIgnoreCase) == true ? "Ø" : (item.DimensionKind ?? "Length") + " ") + N(item.Value!.Value)
- + (item.TolerancePlus.HasValue && item.ToleranceMinus.HasValue ? $" +{N(item.TolerancePlus.Value)}/-{N(item.ToleranceMinus.Value)}" : "") + " " + item.ValueUnit;
- var outlines = PlanarTextProfiles.PresentationContours(text, height);
- var lines = new List<double[][]> { new[] { anchor, P(stem), new[] { label[0] - height, label[1], label[2] }, label } };
- foreach (var witness in witnesses.Skip(1))
- lines.Add([P(witness.Anchor), P(witness.Anchor + witness.Normal * witness.Marker.StemLength), [label[0] - height, label[1], label[2]], label]);
- // A small open arrow terminates at the actual support, along its face normal.
- var side = Direction3D.Create(normal.Cross(Math.Abs(normal.Z) < .9 ? new(0,0,1) : new Vector3D(0,1,0))).ToVector();
- lines.Add([P(anchorPoint + normal * target.StemLength * .35 + side * target.StemLength * .15), anchor,
- P(anchorPoint + normal * target.StemLength * .35 - side * target.StemLength * .15)]);
- foreach (var curve in outlines)
+ // One or more holes (a quantity callout); each hole is one connected wall on one cylinder.
+ var walls = targets.GroupBy(t => CylinderKey(body.GetFaceSurface(t.FaceId).Cylinder!.Value)).Select(g => g.ToArray()).ToArray();
+ if (walls.Any(w => !OneCylindricalWall(body, w)))
+ throw new InvalidOperationException($"pmi-display-target-multiple-unsupported: '{item.Name}' requires connected cylindrical walls.");
+ // Several holes are one callout only when the record states that quantity and the holes are alike.
+ if (walls.Length > 1 && (item.Quantity != walls.Length
+ || walls.Select(w => Math.Round(body.GetFaceSurface(w[0].FaceId).Cylinder!.Value.Radius, 9)).Distinct().Count() != 1))
+ throw new InvalidOperationException($"pmi-display-target-multiple-unsupported: '{item.Name}' spans {walls.Length} cylinders without a matching quantity of identical holes.");
+ feature = new HoleFeature(walls.Select(w => body.GetFaceSurface(w[0].FaceId).Cylinder!.Value).ToArray(), walls);
+ }
+ else throw new InvalidOperationException($"pmi-display-target-kind-unsupported: '{item.Name}' requires plane or cylinder supports.");
+ specs.Add(new(item, targets, feature));
+ }
+
+ // 2. Group records that describe the same feature into one callout (size above its frames).
+ var layout = new Layout(height, minX, maxX, minY, maxY, minZ, maxZ);
+ var output = new Dictionary<int, PmiDisplayAnnotation>();
+ var groups = specs.GroupBy(s => string.Join(",", s.Item.GeometricFaceEntityIds.Order())).Select(g => g.ToArray()).ToArray();
+ var datumFaces = specs.Where(s => s.Item.Kind == "Datum" && s.Feature is PlanarFeature)
+ .ToDictionary(s => s.Item.Name, s => s, StringComparer.Ordinal);
+
+ // Basic dimensions locate position-toleranced holes from their planar datums (theoretically exact, from the
+ // 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);
+ 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));
+
+ // 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
{
- double[] P((double X, double Y) p) => [label[0] + p.X, label[1] + p.Y, label[2]];
- lines.Add(curve 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();
+ var gap = .35 * height;
+ var stackHeight = blocks.Sum(b => b.Block.Height) + gap * (blocks.Length - 1);
+ var stackWidth = blocks.Max(b => b.Block.Width);
+ var placed = group[0].Feature switch
+ {
+ HoleFeature hole => layout.PlaceHoleCallout(hole, center, stackWidth, stackHeight, points),
+ PlanarFeature planar => layout.PlacePlanarCallout(planar, ordered[0], stackWidth, stackHeight, ordered.Any(s => s.Item.Kind == "Datum")),
+ _ => throw new InvalidOperationException()
+ };
+ var y = placed.Y + stackHeight;
+ for (var i = 0; i < blocks.Length; i++)
+ {
+ var (spec, block) = blocks[i];
+ y -= block.Height;
+ var canvas = new PmiCanvas();
+ canvas.Append(block.Canvas, placed.X, y);
+ 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);
+ 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] };
+ 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.
+ 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;
+ var canvas = new PmiCanvas();
+ canvas.Append(block.Canvas, x, top - block.Height);
+ var at = P(plane.At(x, top));
+ foreach (var (note, index) in notes.Select((n, k) => (n, k)))
+ 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]])
{
- LineArcLineSegment2D line => [P(line.Start), P(line.End)],
- LineArcCubicBezier2D cubic => Enumerable.Range(0, 13).Select(i =>
- {
- var t = i / 12d; var s = 1 - t;
- return P((s*s*s*cubic.Start.X + 3*s*s*t*cubic.Control1.X + 3*s*t*t*cubic.Control2.X + t*t*t*cubic.End.X,
- s*s*s*cubic.Start.Y + 3*s*s*t*cubic.Control1.Y + 3*s*t*t*cubic.Control2.Y + t*t*t*cubic.End.Y));
- }).ToArray(),
- _ => throw new InvalidOperationException("pmi-display-font-curve-unsupported")
- });
+ 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
+ };
+ }
+ return inspection.Items.Where(i => output.ContainsKey(i.EntityId)).Select(i => output[i.EntityId]).ToArray();
+ }
+
+ /// <summary>Model edges for presentation, excluding parameter seams and section splits inside one smooth face.</summary>
+ public static IReadOnlyList<double[][]> EdgeLines(string step, DisplayTessellationOptions? options = null)
+ {
+ var imported = Step242Importer.ImportBody(step);
+ if (!imported.IsSuccess) throw new InvalidOperationException("pmi-display-body-unavailable");
+ var body = imported.Value;
+ var tessellation = BrepDisplayTessellator.Tessellate(body, options ?? DisplayTessellationOptions.Default);
+ if (!tessellation.IsSuccess) throw new InvalidOperationException("pmi-display-target-unavailable");
+ var faces = body.Topology.Faces.ToDictionary(f => f.Id, f => f.LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
+ .Select(id => body.Topology.GetCoedge(id).EdgeId).ToArray());
+ var owners = faces.SelectMany(f => f.Value.Select(e => (Edge: e, Face: f.Key))).GroupBy(x => x.Edge).ToDictionary(g => g.Key, g => g.Select(x => x.Face).ToArray());
+ bool Smooth(Aetheris.Kernel.Core.Topology.EdgeId edge)
+ {
+ if (!owners.TryGetValue(edge, out var adjacent)) return false;
+ if (adjacent.Length == 2 && adjacent[0] == adjacent[1]) return true; // periodic seam
+ if (adjacent.Length != 2) return false;
+ var a = body.GetFaceSurface(adjacent[0]); var b = body.GetFaceSurface(adjacent[1]);
+ if (a.Plane is { } pa && b.Plane is { } pb)
+ return pa.Normal.ToVector().Cross(pb.Normal.ToVector()).Length < 1e-7 && Math.Abs((pb.Origin - pa.Origin).Dot(pa.Normal.ToVector())) < 1e-7;
+ if (a.Cylinder is { } ca && b.Cylinder is { } cb)
+ return CylinderKey(ca) == CylinderKey(cb);
+ return false;
+ }
+ return tessellation.Value.EdgePolylines.Where(e => !Smooth(e.EdgeId))
+ .Select(e => (e.IsClosed ? e.Points.Append(e.Points[0]) : e.Points).Select(P).ToArray()).ToArray();
+ }
+
+ private abstract record Feature;
+ private sealed record PlanarFeature(Vector3D Normal, DisplayFaceMeshPatch[] Patches) : Feature;
+ private sealed record HoleFeature(CylinderSurface[] Cylinders, DisplayFaceMeshPatch[][] Walls) : Feature;
+ private sealed record Spec(Step242SemanticPmiInspectionItem Item, DisplayFaceMeshPatch[] Targets, Feature Feature);
+ private sealed record Placement(PmiPlane Plane, double X, double Y, PmiCanvas Leader, Point3D Anchor)
+ {
+ /// <summary>Vertical distance from the annotation plane down to the anchor on the support.</summary>
+ public double Drop { get; init; }
+ }
+
+ private static string CylinderKey(CylinderSurface c)
+ {
+ var axis = c.Axis.ToVector(); if (axis.Z < 0 || axis.Z == 0 && (axis.Y < 0 || axis.Y == 0 && axis.X < 0)) axis = -axis;
+ var o = c.Origin - Point3D.Origin; var foot = o - axis * o.Dot(axis);
+ return string.Create(CultureInfo.InvariantCulture, $"{Math.Round(c.Radius, 6)}|{Math.Round(axis.X, 6)},{Math.Round(axis.Y, 6)},{Math.Round(axis.Z, 6)}|{Math.Round(foot.X, 5)},{Math.Round(foot.Y, 5)},{Math.Round(foot.Z, 5)}");
+ }
+
+ private static PmiDisplayAnnotation Emit(Spec spec, PmiCanvas canvas, PmiPlane plane, Point3D anchor, double height, double lift,
+ PmiCanvas? dimensions, PmiPlane dimensionPlane)
+ {
+ var item = spec.Item;
+ var text = item.Kind switch
+ {
+ "Datum" => $"Datum {item.Name}",
+ "Diameter" or "Dimension" => PmiDrafting.Size(item),
+ _ => $"{item.Kind} {(item.ZoneForms.Contains("between two equidistant surfaces") ? "BetweenSurfaces " : PmiDrafting.ZonePrefix(item.ZoneForms))}{PmiDrafting.Number(item.Value!.Value)}"
+ + string.Concat(item.Modifiers.Select(m => m switch { "MAXIMUM_MATERIAL_REQUIREMENT" => " (M)", "LEAST_MATERIAL_REQUIREMENT" => " (L)", _ => " " + m }))
+ + (item.DatumReferences.Count > 0 ? " | " + string.Join(" | ", item.DatumReferences) : "")
+ };
+ var lines = Lines3D(canvas, plane, 0).ToList();
+ (double X, double Y) label = canvas.Lines.Count > 0 ? canvas.Lines[0][0] : (0d, 0d);
+ var fill = Fill3D(canvas.Fill, canvas.FillIndices, plane, lift * 2);
+ var panel = Fill3D(canvas.Panel, canvas.PanelIndices, plane, -lift);
+ if (dimensions is not null)
+ {
+ lines.AddRange(Lines3D(dimensions, dimensionPlane, 0));
+ fill = Merge(fill, Fill3D(dimensions.Fill, dimensions.FillIndices, dimensionPlane, lift * 2));
+ panel = Merge(panel, Fill3D(dimensions.Panel, dimensions.PanelIndices, dimensionPlane, -lift));
+ }
+ 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 };
+ }
+
+ 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();
+
+ 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());
+
+ /// <summary>The highlighted support: every associated patch, lifted off the surface.</summary>
+ private static PmiDisplayTarget Highlight(Spec spec, double height)
+ {
+ var offset0 = height * .002;
+ var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
+ foreach (var patch in spec.Targets)
+ {
+ var offset = positions.Count / 3;
+ positions.AddRange(patch.Positions.Zip(patch.Normals, (p, n) => new[] { p.X + n.X * offset0, p.Y + n.Y * offset0, p.Z + n.Z * offset0 }).SelectMany(v => v));
+ normals.AddRange(patch.Normals.SelectMany(n => new[] { n.X, n.Y, n.Z }));
+ indices.AddRange(patch.TriangleIndices.Select(i => i + offset));
+ }
+ var normal = spec.Feature is PlanarFeature planar ? V(planar.Normal) : [0d, 0d, 1d];
+ return new(spec.Feature is PlanarFeature ? "PlanePatch" : "CylinderWall", normal, 0, positions.ToArray(), normals.ToArray(), indices.ToArray(), [])
+ { SurfaceOffset = offset0 };
+ }
+
+ /// <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.
+ /// </summary>
+ private static Dictionary<int, PmiCanvas> BasicDimensions(IReadOnlyList<Spec> specs, IReadOnlyDictionary<string, Spec> datums, Layout layout)
+ {
+ var result = new Dictionary<int, PmiCanvas>();
+ var requests = new List<(Spec Owner, Vector3D Normal, double DatumOffset, Point3D Axis, string Datum)>();
+ 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)
+ {
+ 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));
+ }
+ 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 (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);
}
- result.Add(new("pmi:" + item.EntityId, item.Kind, item.AuthoredName ?? item.Name, text,
- item.Value, item.TolerancePlus, item.ToleranceMinus, item.GeometricFaceEntityIds, anchor, label, height, lines) { Target = target });
+ if (Math.Abs(direction.Key.Item1) > .5) tiersX = Math.Max(tiersX, values.Length); else tiersY = Math.Max(tiersY, values.Length);
}
+ layout.ReserveDimensionBands(tiersX, tiersY);
return result;
}
- private static double[] P(Point3D p) => [p.X, p.Y, p.Z];
- private static double[] V(Vector3D v) => [v.X, v.Y, v.Z];
-
- private static (Point3D Anchor, Vector3D Normal, PmiDisplayTarget Marker) Target(
- BrepBody body, DisplayTessellationResult tessellation, DisplayFaceMeshPatch patch, string kind, double height, double[] label, IReadOnlySet<Aetheris.Kernel.Core.Topology.EdgeId> internalEdges)
+ /// <summary>Annotation-plane placement with simple collision avoidance in each plane.</summary>
+ private sealed class Layout(double h, double minX, double maxX, double minY, double maxY, double minZ, double maxZ)
{
- body.TryGetFaceSurfaceGeometry(patch.FaceId, out var surface);
- if (surface?.Plane is PlaneSurface plane)
- {
- // The largest triangle incircle is a bounded, deterministic interior witness.
- // A vertex average of the whole face can land in a hole or outside a concavity.
- var triangle = Triangles(patch).Select(t => Incenter(t.A, t.B, t.C)).MaxBy(t => t.Radius);
- if (triangle.Radius <= 1e-9) throw new InvalidOperationException("pmi-display-target-degenerate");
- var center = triangle.Center;
- var normal = plane.Normal.ToVector();
- if (normal.Dot(patch.Normals[0]) < 0) normal = -normal;
- var u = plane.UAxis.ToVector(); var v = plane.VAxis.ToVector();
- var size = Math.Min(height * .8, triangle.Radius * .6); // corners inside incircle
- var offset = Math.Min(height * .002, size * .01);
- var lifted = center + normal * offset;
- Point3D[] corners = [lifted - u * size - v * size, lifted + u * size - v * size,
- lifted + u * size + v * size, lifted - u * size + v * size];
- return (center, normal, new("PlanePatch", V(normal), height, corners.SelectMany(P).ToArray(),
- corners.SelectMany(_ => V(normal)).ToArray(), [0,1,2,0,2,3], [corners.Append(corners[0]).Select(P).ToArray(),
- [P(lifted - u * size), P(lifted + u * size)], [P(lifted - v * size), P(lifted + v * size)]]) { SurfaceOffset = offset });
+ private readonly Dictionary<string, List<(double X0, double Y0, double X1, double Y1)>> occupied = [];
+ private readonly List<(double X0, double Y0, double X1, double Y1)> dimensionLabels = [];
+ public double DimensionDepth { get; private set; }
+ public double Lift => .02;
+ /// <summary>Basic dimensions all live in one horizontal plane, at the top of the datum faces.</summary>
+ public double DimensionLevel { get; set; } = double.NaN;
+
+ // Parallel planes overlap in the view that reads them, so they share one occupancy map.
+ 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)
+ {
+ if (outsideBody)
+ {
+ var (bx0, by0) = plane.Local(new Point3D(minX, minY, minZ)); var (bx1, by1) = plane.Local(new Point3D(maxX, maxY, maxZ));
+ var pad = .6 * h;
+ if (r.X1 > Math.Min(bx0, bx1) - pad && r.X0 < Math.Max(bx0, bx1) + pad && r.Y1 > Math.Min(by0, by1) - pad && r.Y0 < Math.Max(by0, by1) + pad) return false;
+ }
+ var list = occupied.GetValueOrDefault(Key(plane)) ?? [];
+ var m = .5 * h;
+ return list.All(o => r.X1 + m <= o.X0 || r.X0 - m >= o.X1 || r.Y1 + m <= o.Y0 || r.Y0 - m >= o.Y1);
}
- if (surface?.Cylinder is CylinderSurface cylinder)
+
+ private void Occupy(PmiPlane plane, (double X0, double Y0, double X1, double Y1) r)
{
- // Unwrap each admitted display triangle locally, including the periodic seam.
- // Select a substantial triangle away from the end rims; use the label-facing
- // side only as a deterministic tie breaker, never as topology authority.
- Point3D Uv(Point3D point)
+ if (!occupied.TryGetValue(Key(plane), out var list)) occupied[Key(plane)] = list = [];
+ list.Add(r);
+ }
+
+ /// <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).
+ 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);
+ 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();
+ // The front faces the default view: try the front diagonals first within a modest reach.
+ var passes = new[] { (Directions: directions.Where(d => d.Y < 0).ToArray(), Limit: 32 * h), (Directions: directions, Limit: 90 * h) };
+ foreach (var (candidates, limit) in passes)
+ for (var reach = 3.5 * h; reach < limit; reach += .5 * h)
+ foreach (var d in candidates)
+ {
+ var outward = (X: d.X * Math.Sqrt(.5), Y: d.Y * Math.Sqrt(.5));
+ var tip = (X: axis.X + outward.X * r, Y: axis.Y + outward.Y * r);
+ var elbow = (X: tip.X + outward.X * reach, Y: tip.Y + outward.Y * reach);
+ var shoulder = 1.2 * h;
+ var x = outward.X >= 0 ? elbow.X + shoulder : elbow.X - shoulder - width;
+ var rect = (x, elbow.Y - height / 2, x + width, elbow.Y + height / 2);
+ if (!Free(plane, rect, true)) continue;
+ Occupy(plane, rect);
+ 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 };
+ }
+ throw new InvalidOperationException("pmi-display-layout-no-space: a hole callout has no free position.");
+ }
+
+ /// <summary>Reserve the band a set of baseline dimensions occupies, extension lines included.</summary>
+ public void ReserveDimensionBands(int tiersAlongX, int tiersAlongY)
+ {
+ 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));
+ }
+
+ /// <summary>Reserve a rectangle in a plane (for blocks placed by the caller).</summary>
+ public void Reserve(PmiPlane plane, (double X0, double Y0, double X1, double Y1) rect) => Occupy(plane, rect);
+
+ /// <summary>A planar feature is shown edge-on: datum triangle or arrow on the face line, stem along the normal.</summary>
+ public Placement PlacePlanarCallout(PlanarFeature face, Spec first, double width, double height, bool datum)
+ {
+ var n = face.Normal;
+ var facePoints = face.Patches.SelectMany(p => p.Positions).ToArray();
+ PmiPlane plane; (double X, double Y) anchor; (double X, double Y) dir; bool constrain;
+ if (Math.Abs(n.Z) > .9)
+ {
+ // Horizontal face: drawn in the front plane through its nearest edge.
+ var y0 = facePoints.Min(p => p.Y);
+ plane = new PmiPlane(new Point3D(0, y0, 0), new Vector3D(1, 0, 0), new Vector3D(0, 0, 1));
+ var z = facePoints[0].Z;
+ var xs = facePoints.Where(p => Math.Abs(p.Y - y0) < 1e-6).Select(p => p.X).DefaultIfEmpty(facePoints.Average(p => p.X)).ToArray();
+ var x0 = xs.Min(); var x1 = xs.Max();
+ anchor = (x0 + (x1 - x0) * (datum ? .3 : .7), z);
+ dir = (0, n.Z > 0 ? 1 : -1);
+ constrain = y0 > minY + 1e-6;
+ }
+ else
{
- var d = point - cylinder.Origin;
- return new(Math.Atan2(d.Dot(cylinder.YAxis.ToVector()), d.Dot(cylinder.XAxis.ToVector())) * cylinder.Radius,
- d.Dot(cylinder.Axis.ToVector()), 0);
+ // Vertical face: drawn in the horizontal plane through its top edge.
+ var z = facePoints.Max(p => p.Z);
+ plane = new PmiPlane(new Point3D(0, 0, z), new Vector3D(1, 0, 0), new Vector3D(0, 1, 0));
+ var top = facePoints.Where(p => Math.Abs(p.Z - z) < 1e-6).ToArray();
+ var tangent = new Vector3D(-n.Y, n.X, 0);
+ var ts = top.Select(p => (p - Point3D.Origin).Dot(tangent)).ToArray();
+ dir = (n.X, n.Y);
+ // Slide along the face until the stem clears every dimension value.
+ (double X, double Y) Along(double fraction)
+ {
+ var t = ts.Min() + (ts.Max() - ts.Min()) * fraction;
+ var basePoint = top[0] + tangent * (t - (top[0] - Point3D.Origin).Dot(tangent));
+ return (basePoint.X, basePoint.Y);
+ }
+ var direction = dir;
+ bool Clear((double X, double Y) a) => dimensionLabels.All(r =>
+ {
+ var far = (X: a.X + direction.X * 1000, Y: a.Y + direction.Y * 1000);
+ var x0 = Math.Min(a.X, far.X) - .6 * h; var x1 = Math.Max(a.X, far.X) + .6 * h;
+ var y0 = Math.Min(a.Y, far.Y) - .6 * h; var y1 = Math.Max(a.Y, far.Y) + .6 * h;
+ return r.X1 < x0 || r.X0 > x1 || r.Y1 < y0 || r.Y0 > y1;
+ });
+ anchor = new[] { .72, .5, .85, .3, .62, .4, .15, .92 }.Select(Along).FirstOrDefault(Clear, Along(.72));
+ constrain = z < maxZ - 1e-6;
}
- Point3D Unwrap(Point3D p, double reference) => p with { X = reference + Math.IEEERemainder(p.X - reference, 2 * Math.PI * cylinder.Radius) };
- Point3D Evaluate(Point3D uv) => cylinder.Evaluate(uv.X / cylinder.Radius, uv.Y);
- var midV = (patch.Positions.Min(p => Uv(p).Y) + patch.Positions.Max(p => Uv(p).Y)) / 2;
- var candidates = Triangles(patch).Select(t =>
+ for (var reach = 1.6 * h; reach < 80 * h; reach += .5 * h)
{
- var a = Uv(t.A); var b = Unwrap(Uv(t.B), a.X); var c = Unwrap(Uv(t.C), a.X);
- var center = new Point3D((a.X+b.X+c.X)/3, (a.Y+b.Y+c.Y)/3, 0);
- var area = (b-a).Cross(c-a).Length;
- var radial = cylinder.Normal(center.X/cylinder.Radius).ToVector();
- var facing = radial.Dot(new Point3D(label[0],label[1],label[2])-Evaluate(center));
- return (center,area,facing);
- }).Where(t => t.area > 1e-12).ToArray();
- if (candidates.Length == 0) throw new InvalidOperationException("pmi-display-target-degenerate");
- var largest = candidates.Max(t => t.area);
- var chosen = candidates.Where(t => t.area >= largest * .5)
- .OrderBy(t => Math.Round(Math.Abs(t.center.Y - midV)/height, 8)).ThenByDescending(t => t.facing).First();
- var anchor = Evaluate(chosen.center);
- var normal = cylinder.Normal(chosen.center.X/cylinder.Radius).ToVector();
- // Compare at the same angular location to retain the imported face orientation.
- var first = patch.Positions[patch.TriangleIndices[0]];
- var sense = cylinder.Normal(Uv(first).X/cylinder.Radius).ToVector().Dot(patch.Normals[patch.TriangleIndices[0]]) < 0 ? -1 : 1;
- normal *= sense;
- // Highlight the associated trimmed wall, not a nearly invisible tessellation strip.
- // Kernel edge wires identify its rims. An edge used twice by this face is a
- // parameter seam, not a manufactured edge, so it receives no rim highlight.
- var rims = body.Topology.GetFace(patch.FaceId).LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
- .Select(id => body.Topology.GetCoedge(id).EdgeId).GroupBy(id => id).Where(g => g.Count() == 1 && !internalEdges.Contains(g.Key)).Select(g => g.Key).ToHashSet();
- var stemLength = Math.Min(height, cylinder.Radius*.45);
- var offset = Math.Min(height * .002, stemLength * .01);
- double[] Lift(Point3D point) => P(point + cylinder.Normal(Uv(point).X/cylinder.Radius).ToVector() * sense * offset);
- var outlines = tessellation.EdgePolylines.Where(edge => rims.Contains(edge.EdgeId)).Select(edge =>
- (edge.IsClosed ? edge.Points.Append(edge.Points[0]) : edge.Points).Select(Lift).ToArray()).ToArray();
- return (anchor, normal, new("CylinderWall", V(normal), stemLength, patch.Positions.SelectMany(Lift).ToArray(),
- patch.Normals.SelectMany(V).ToArray(), patch.TriangleIndices.ToArray(), outlines) { SurfaceOffset = offset });
+ var end = (X: anchor.X + dir.X * reach, Y: anchor.Y + dir.Y * reach);
+ // The block attaches by the middle of its near edge.
+ var x = dir.X > .5 ? end.X : dir.X < -.5 ? end.X - width : end.X - (datum ? 0 : width / 2) - (datum ? width / 2 : 0);
+ var y = dir.Y > .5 ? end.Y : dir.Y < -.5 ? end.Y - height : end.Y - height / 2;
+ if (Math.Abs(dir.Y) > .5) x = end.X - width / 2;
+ var rect = (x, y, x + width, y + height);
+ if (!Free(plane, rect, constrain)) continue;
+ Occupy(plane, rect);
+ var leader = new PmiCanvas();
+ if (datum)
+ {
+ // Filled datum triangle with its base on the feature.
+ var side = (X: -dir.Y, Y: dir.X);
+ var b = .55 * h; var a = .95 * h;
+ leader.Line(anchor, end);
+ leader.Triangle((anchor.X + side.X * b, anchor.Y + side.Y * b), (anchor.X - side.X * b, anchor.Y - side.Y * b),
+ (anchor.X + dir.X * a, anchor.Y + dir.Y * a));
+ leader.Line((anchor.X + side.X * b, anchor.Y + side.Y * b), (anchor.X - side.X * b, anchor.Y - side.Y * b));
+ }
+ else
+ {
+ leader.Line(anchor, end);
+ Arrow(leader, anchor, (-dir.X, -dir.Y));
+ }
+ return new(plane, x, y, leader, plane.At(anchor.X, anchor.Y));
+ }
+ throw new InvalidOperationException($"pmi-display-layout-no-space: '{first.Item.Name}' has no free position.");
+ }
+
+ /// <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)
+ {
+ // Dimensions along X sit in front of the part; dimensions along Y sit to its left.
+ var alongX = Math.Abs(datumNormal.X) > .5;
+ 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;
+ 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);
+ if (alongX)
+ {
+ var y = minY - first - tier * spacing;
+ canvas.Line((datumCoordinate, minY - .4 * h), (datumCoordinate, y - .6 * h));
+ canvas.Line((featureCoordinate, axis.Y), (featureCoordinate, y - .6 * h));
+ canvas.Line((datumCoordinate, y), (featureCoordinate, y));
+ var s = Math.Sign(featureCoordinate - datumCoordinate);
+ Arrow(canvas, (datumCoordinate, y), (-s, 0)); Arrow(canvas, (featureCoordinate, y), (s, 0));
+ var span = Math.Abs(featureCoordinate - datumCoordinate);
+ // A short dimension keeps its value beyond the feature end rather than over the arrows.
+ var cx = span < label.Width + 2.4 * h ? featureCoordinate + s * (1.2 * h) - (s < 0 ? label.Width : 0)
+ : (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));
+ }
+ else
+ {
+ var x = minX - first - tier * spacing;
+ canvas.Line((minX - .4 * h, datumCoordinate), (x - .6 * h, datumCoordinate));
+ canvas.Line((axis.X, featureCoordinate), (x - .6 * h, featureCoordinate));
+ canvas.Line((x, datumCoordinate), (x, featureCoordinate));
+ var s = Math.Sign(featureCoordinate - datumCoordinate);
+ Arrow(canvas, (x, datumCoordinate), (0, -s)); Arrow(canvas, (x, featureCoordinate), (0, s));
+ var span = Math.Abs(featureCoordinate - datumCoordinate);
+ var cy = span < label.Height + 2.4 * h ? featureCoordinate + s * (1.2 * h) - (s < 0 ? label.Height : 0)
+ : (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)));
+ }
+ // Mark the controlled axis.
+ canvas.Line((axis.X - .8 * h, axis.Y), (axis.X + .8 * h, axis.Y));
+ canvas.Line((axis.X, axis.Y - .8 * h), (axis.X, axis.Y + .8 * h));
+ }
+
+ private void Arrow(PmiCanvas canvas, (double X, double Y) tip, (double X, double Y) pointing)
+ {
+ var length = Math.Sqrt(pointing.X * pointing.X + pointing.Y * pointing.Y);
+ var d = (X: pointing.X / length, Y: pointing.Y / length); var side = (X: -d.Y, Y: d.X);
+ var l = .9 * h; var w = .22 * h;
+ canvas.Triangle(tip, (tip.X - d.X * l + side.X * w, tip.Y - d.Y * l + side.Y * w), (tip.X - d.X * l - side.X * w, tip.Y - d.Y * l - side.Y * w));
}
- throw new InvalidOperationException($"pmi-display-target-kind-unsupported: {kind} requires its qualified plane or cylinder support.");
}
+ private static double[] P(Point3D p) => [p.X, p.Y, p.Z];
+ private static double[] V(Vector3D v) => [v.X, v.Y, v.Z];
+
private static bool OneCylindricalWall(BrepBody body, IReadOnlyList<DisplayFaceMeshPatch> patches)
{
var surfaces = patches.Select(p => body.GetFaceSurface(p.FaceId)).ToArray();
diff --git a/Aetheris.slnx b/Aetheris.slnx
index a98f2d91..7f7987c1 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -83,6 +83,7 @@
<Project Path="demos/Aetheris.DifferenceEngine/Aetheris.DifferenceEngine.csproj" />
<Project Path="demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj" />
<Project Path="demos/Aetheris.EditableV8/Aetheris.EditableV8.csproj" />
+ <Project Path="demos/Aetheris.PmiShowcase/Aetheris.PmiShowcase.csproj" />
</Folder>
<Project Path="Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj" />
<Project Path="Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj" />
diff --git a/demos/Aetheris.PmiShowcase/Aetheris.PmiShowcase.csproj b/demos/Aetheris.PmiShowcase/Aetheris.PmiShowcase.csproj
new file mode 100644
index 00000000..7ac0c5ec
--- /dev/null
+++ b/demos/Aetheris.PmiShowcase/Aetheris.PmiShowcase.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="../../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/demos/Aetheris.PmiShowcase/Program.cs b/demos/Aetheris.PmiShowcase/Program.cs
new file mode 100644
index 00000000..27004797
--- /dev/null
+++ b/demos/Aetheris.PmiShowcase/Program.cs
@@ -0,0 +1,55 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Export;
+
+// Compiles a Firmament part with PMI and writes its AP242 STEP and annotated GLB presentation.
+// Every callout in the GLB is read back from the exported STEP, never from the source.
+if (args.Length is < 1 or > 2 || args.Any(a => a.StartsWith('-')))
+{
+ Console.Error.WriteLine("Usage: Aetheris.PmiShowcase <part.firmament> [output-directory]");
+ return 1;
+}
+try
+{
+ var sourcePath = Path.GetFullPath(args[0]);
+ var output = Path.GetFullPath(args.ElementAtOrDefault(1) ?? "artifacts/local/demos/pmi-showcase");
+ Directory.CreateDirectory(output);
+ var compilation = FirmamentBuildAndExport.CompileSource(File.ReadAllText(sourcePath));
+ if (!compilation.IsSuccess) throw new InvalidOperationException(string.Join("\n", compilation.Diagnostics.Select(d => d.Message)));
+ 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 };
+ 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>();
+ foreach (var face in tessellation.Value.FacePatches)
+ {
+ var offset = positions.Count / 3;
+ positions.AddRange(face.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ normals.AddRange(face.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ indices.AddRange(face.TriangleIndices.Select(i => i + offset));
+ }
+ var name = Path.GetFileNameWithoutExtension(sourcePath);
+ var display = new AssemblyDisplayMeshDocument("aetheris/display-mesh/1", name, "mm",
+ [new("part-definition", name, positions.ToArray(), normals.ToArray(), indices.ToArray())],
+ [new("part", name, null, "part-definition", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])]) { TessellationOptions = options };
+ foreach (var artifact in ProductArtifactExporter.Export(new(name, step, display), ["step", "glb"], output))
+ File.WriteAllBytes(Path.Combine(output, artifact.FileName), artifact.Bytes);
+ var pmi = Step242SemanticPmiInspector.Inspect(step);
+ File.WriteAllText(Path.Combine(output, name + ".pmi.json"), JsonSerializer.Serialize(pmi.Items, new JsonSerializerOptions { WriteIndented = true }));
+ foreach (var file in Directory.GetFiles(output, name + ".*"))
+ Console.WriteLine($"{Path.GetFileName(file),-40} {new FileInfo(file).Length,10:N0} bytes {Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file)))[..12]}");
+ Console.WriteLine($"PMI records: {pmi.Items.Count} ({pmi.DatumCount} datums, {pmi.DimensionCount} sizes, {pmi.GeometricToleranceCount} controls, {pmi.AnnotationCount} notes)");
+ return 0;
+}
+catch (Exception exception) when (exception is InvalidOperationException or IOException)
+{
+ Console.Error.WriteLine(exception.Message);
+ return 1;
+}
diff --git a/fixtures/Canonical/PMI/showcase-bearing-mount.firmament b/fixtures/Canonical/PMI/showcase-bearing-mount.firmament
new file mode 100644
index 00000000..7ded7f81
--- /dev/null
+++ b/fixtures/Canonical/PMI/showcase-bearing-mount.firmament
@@ -0,0 +1,44 @@
+// A bearing mount block specified for manufacture by its model alone.
+Model BearingMount {
+ units: mm
+
+ Static boreDiameter: Length = 22mm tol +0.021mm -0mm
+ Static mountDiameter: Length = 6.6mm tol 0.1mm
+
+ Profile stockOutline = Rect2 { center: [0mm, 0mm]; size: [130mm, 90mm] }
+ Profile hubOutline = Circle2 { center: [0mm, 0mm]; radius: 22mm }
+ Profile leftRecess = RoundedRect2 { center: [-35mm, 0mm]; size: [16mm, 40mm]; radius: 4mm }
+ Profile rightRecess = RoundedRect2 { center: [35mm, 0mm]; size: [16mm, 40mm]; radius: 4mm }
+
+ Compose body {
+ Base stock { profile: stockOutline; from: 0mm; to: 14mm; role: Stock }
+ Boss hub { on: Top; profile: hubOutline; height: 14mm }
+ Pocket left { on: stock.Top; profile: leftRecess; depth: 6mm; minimumFloorThickness: 6mm }
+ Pocket right { on: stock.Top; profile: rightRecess; depth: 6mm; minimumFloorThickness: 6mm }
+ Hole<Shaft> bore { on: +Z; center: [0mm, 0mm]; diameter: boreDiameter; end: ThroughAll }
+ Hole<Counterbore> mountA { on: +Z; center: [-53mm, -33mm]; diameter: mountDiameter; counterboreDiameter: 11mm; counterboreDepth: 6.5mm; end: ThroughAll }
+ Hole<Counterbore> mountB { on: +Z; center: [53mm, -33mm]; diameter: mountDiameter; counterboreDiameter: 11mm; counterboreDepth: 6.5mm; end: ThroughAll }
+ Hole<Counterbore> mountC { on: +Z; center: [53mm, 33mm]; diameter: mountDiameter; counterboreDiameter: 11mm; counterboreDepth: 6.5mm; end: ThroughAll }
+ Hole<Counterbore> mountD { on: +Z; center: [-53mm, 33mm]; diameter: mountDiameter; counterboreDiameter: 11mm; counterboreDepth: 6.5mm; end: ThroughAll }
+ }
+
+ Modify body {
+ EdgeFinish<Chamfer> perimeterBreak { target: stockOutline.Outer; on: Top; distance: 1mm }
+ }
+
+ Pmi {
+ Datum A { target: face(-Z) }
+ Datum B { target: face(-X) }
+ Datum C { target: face(-Y) }
+ Flatness MountingFace { target: face(-Z) tolerance: 0.02mm }
+ 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 }
+ 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] }
+ 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." }
+ }
+}