Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Preserve inline STEP resources and export PMI annotations

Yuechen Li81454e55d754
diff --git a/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs b/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
index 4ebd64ea..b87d6c47 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
@@ -25,7 +25,12 @@ public sealed class StepLegacyQualificationTests
public void DisplayRefinementWarning_DoesNotDegradeAuthoritativeGeometry()
{
var body = Box.Value;
- var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body) with {
+ // This tests classification of a refinement warning, not the wall-clock budget.
+ // A timed-out partial box would exercise a different (correctly Partial) result.
+ var complete = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(complete.IsSuccess);
+ Assert.Equal(body.Topology.Faces.Count(), complete.Value.FacePatches.Count);
+ var mesh = complete.Value with {
FaceDiagnostics = [new(null, "BSplineSurfaceWithKnots", "FaceTessellation", "Viewer.Tessellation.RefinementIncomplete", "Display budget reached.")]
};
var report = BrepImportQualification.WithDisplay(body, mesh);
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs
index 6e5b5553..8292609c 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs
@@ -8,6 +8,41 @@ public sealed class FirmamentV2InlineStepTests
private const string FixturePath = "fixtures/Regression/InlineStep/valid/inline-step-v2-canonical-box-reexport-step-verified.valid.firmfixture";
private const string InputStepPath = "testdata/firmament/inline-step/canonical-box-10x8x6.step";
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void ImportedPmi_PreservesFaceAssociationsAndGeometry(bool regions)
+ {
+ var repo = FindRepoRoot();
+ var source = File.ReadAllText(Path.Combine(repo, "fixtures/Regression/InlineStep/valid/inline-step-v2-record-pmi-datum-diameter-step-verified.valid.firmfixture"))
+ .Replace("../../../../testdata/", "testdata/").Replace("6.0mm tol 0.05mm", "2.0mm tol 0.1mm");
+ if (!regions) source = source.Replace("part.region(\"baseFace\")", "part.face(\"#51\")")
+ .Replace("part.region(\"mountHoleA\")", "part.face(\"#191\")");
+ var baseline = FirmamentBuildAndExport.CompileSource(source[..source.IndexOf(" pmi {", StringComparison.Ordinal)] + "}", repo);
+ var annotated = FirmamentBuildAndExport.CompileSource(source, repo);
+ Assert.True(baseline.IsSuccess, string.Join("; ", baseline.Diagnostics));
+ Assert.True(annotated.IsSuccess, string.Join("; ", annotated.Diagnostics));
+ var inspection = Step242SemanticPmiInspector.Inspect(annotated.Value.StepText);
+ Assert.True(inspection.Success);
+ var datum = Assert.Single(inspection.Items, i => i.Kind == "Datum");
+ var diameter = Assert.Single(inspection.Items, i => i.Kind == "Diameter");
+ Assert.Single(datum.GeometricFaceEntityIds);
+ Assert.Single(diameter.GeometricFaceEntityIds);
+ Assert.NotEqual(datum.GeometricFaceEntityIds[0], diameter.GeometricFaceEntityIds[0]);
+ Assert.Equal(2, diameter.Value);
+ Assert.Equal(.1, diameter.TolerancePlus);
+ Assert.Equal(.1, diameter.ToleranceMinus);
+ var reimport = Step242Importer.ImportBody(annotated.Value.StepText).Value;
+ Assert.Equal(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Plane, reimport.Geometry.GetSurface(
+ reimport.Bindings.FaceBindings.Single(b => b.SourceStepEntityId == datum.GeometricFaceEntityIds[0]).SurfaceGeometryId).Kind);
+ Assert.Equal(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Cylinder, reimport.Geometry.GetSurface(
+ reimport.Bindings.FaceBindings.Single(b => b.SourceStepEntityId == diameter.GeometricFaceEntityIds[0]).SurfaceGeometryId).Kind);
+ // All pre-existing entity records, including topology and geometry, survive verbatim.
+ var before = System.Text.RegularExpressions.Regex.Matches(baseline.Value.StepText, @"(?m)^#\d+=[^\r\n]+;").Select(m => m.Value).ToArray();
+ Assert.NotEmpty(before);
+ Assert.All(before, record => Assert.Contains(record, annotated.Value.StepText, StringComparison.Ordinal));
+ }
+
[Theory]
[InlineData("modify")]
[InlineData("Modify")]
diff --git a/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs b/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
new file mode 100644
index 00000000..a553033e
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
@@ -0,0 +1,112 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Export;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Visualization;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ImportedPartPmiTests
+{
+ private static string Repo()
+ {
+ var d = new DirectoryInfo(AppContext.BaseDirectory);
+ while (d is not null && !File.Exists(Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent;
+ return d!.FullName;
+ }
+ private static string Source() => File.ReadAllText(Path.Combine(Repo(), "fixtures/Regression/ImportedPartPmi/annotated-part.firmament"));
+ private static string Step() => File.ReadAllText(Path.Combine(Repo(), "testdata/firmament/inline-step/canonical-through-hole.step"));
+ [Fact]
+ public void SnapshotAssets_AreExplicitAndRemainImmutableAfterAdmission()
+ {
+ var source = Source().Replace("../../../testdata/firmament/inline-step/canonical-through-hole.step", "assets/body.step");
+ var assets = new Dictionary<string, string> { ["assets/body.step"] = Step() };
+ var project = new FirmamentProjectSnapshot("part.firmament", assets.Append(new KeyValuePair<string, string>("part.firmament", source)));
+ Assert.Single(project.SourceDocuments);
+ Assert.Empty(FirmamentLanguageAnalysisService.Analyze(project, "part.firmament", "1").Diagnostics.Where(d => d.Severity == "error"));
+ var compiled = FirmamentBuildAndExport.CompileSource(source, resources: project.Documents);
+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics));
+ var admitted = Assert.IsType<FirmamentV2InlineStepRecord>(compiled.Value.RuntimeAdmissionDocument!.Solids.Single().Primitive);
+ Assert.Equal(Step(), admitted.SourceText);
+ assets["assets/body.step"] = "corrupt";
+ Assert.Equal(Step(), admitted.SourceText);
+ var missing = FirmamentBuildAndExport.CompileSource(Source(), Repo(), new Dictionary<string, string>());
+ Assert.False(missing.IsSuccess); // Even an existing disk resource cannot escape an explicit snapshot.
+ Assert.Contains(missing.Diagnostics, d => d.Message.Contains(FirmamentV2Parser.InlineStepPathInvalid) || d.Message.Contains(FirmamentV2Parser.InlineStepFileMissing));
+ }
+ [Theory]
+ [InlineData("#51", "#191")]
+ [InlineData("#191", "#51")]
+ public void IncompatibleImportedPmiSurface_IsRejected(string from, string to)
+ {
+ var built = FirmamentBuildAndExport.CompileSource(Source().Replace($"face(\"{from}\")", $"face(\"{to}\")"),
+ Path.Combine(Repo(), "fixtures/Regression/ImportedPartPmi"));
+ Assert.False(built.IsSuccess);
+ Assert.Contains(built.Diagnostics, d => d.Message.Contains("imported-pmi-target-kind"));
+ }
+ [Fact]
+ public void ExistingImportedAnnotations_AreRejectedInsteadOfSilentlyStripped()
+ {
+ var built = FirmamentBuildAndExport.CompileSource(Source(), Path.Combine(Repo(), "fixtures/Regression/ImportedPartPmi"));
+ Assert.True(built.IsSuccess);
+ var source = Source().Replace("../../../testdata/firmament/inline-step/canonical-through-hole.step", "annotated.step");
+ source = source[..source.IndexOf(" Pmi {", StringComparison.Ordinal)] + "}";
+ var imported = FirmamentBuildAndExport.CompileSource(source, resources: new Dictionary<string, string> { ["annotated.step"] = built.Value.StepText });
+ Assert.False(imported.IsSuccess);
+ Assert.Contains(imported.Diagnostics, d => d.Message.Contains("existing-pmi-unsupported"));
+ }
+ [Fact]
+ public void ImportedTopology_UsesProvenanceRatherThanEntityLineOrder()
+ {
+ var step = Step();
+ var records = System.Text.RegularExpressions.Regex.Matches(step, @"(?m)^#\d+=ADVANCED_FACE[^\r\n]+").Select(m => m.Value).ToArray();
+ var shuffled = step.Replace(records[0], "__FIRST_FACE__").Replace(records[^1], records[0]).Replace("__FIRST_FACE__", records[^1]);
+ var source = Source().Replace("../../../testdata/firmament/inline-step/canonical-through-hole.step", "body.step");
+ var result = FirmamentBuildAndExport.CompileSource(source, resources: new Dictionary<string, string> { ["body.step"] = shuffled });
+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics));
+ var map = result.Value.RuntimeAdmissionDocument!.Solids.Single().InlineStep!.TopologyMap;
+ var body = result.Value.RuntimeBody!;
+ foreach (var binding in body.Bindings.FaceBindings)
+ Assert.Equal($"face-{binding.FaceId.Value}", map.FaceEntityToFaceId["#" + binding.SourceStepEntityId]);
+ }
+ [Fact]
+ public void AnnotatedGlb_RetainsBodyBuffersAndCarriesSemanticValuesAndSeparatePresentation()
+ {
+ var built = FirmamentBuildAndExport.CompileSource(Source(), Path.Combine(Repo(), "fixtures/Regression/ImportedPartPmi"));
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics));
+ var body = built.Value.RuntimeBody!;
+ var tess = BrepDisplayTessellator.Tessellate(body, DisplayTessellationOptions.Default).Value;
+ var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
+ foreach (var patch in tess.FacePatches)
+ {
+ var start = positions.Count / 3;
+ positions.AddRange(patch.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ normals.AddRange(patch.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ indices.AddRange(patch.TriangleIndices.Select(i => i + start));
+ }
+ var display = new AssemblyDisplayMeshDocument("aetheris/display-mesh/1", "Imported", "mm",
+ [new("part", "part", positions.ToArray(), normals.ToArray(), indices.ToArray())],
+ [new("part:occurrence", "part", null, "part", [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])]);
+ var baseline = AssemblyGlbExporter.Serialize(display);
+ var file = Assert.Single(ProductArtifactExporter.Export(new("Imported", built.Value.StepText, display), ["glb"], Path.GetTempPath()));
+ using var json = JsonDocument.Parse(file.Bytes.AsMemory(20, BitConverter.ToInt32(file.Bytes, 12)));
+ var root = json.RootElement;
+ var records = root.GetProperty("asset").GetProperty("extras").GetProperty("pmi");
+ Assert.Equal(2, records.GetArrayLength());
+ var diameter = records.EnumerateArray().Single(r => r.GetProperty("kind").GetString() == "Diameter");
+ Assert.Equal(2, diameter.GetProperty("value").GetDouble());
+ Assert.Equal(.1, diameter.GetProperty("tolerancePlus").GetDouble());
+ Assert.Equal(.05, diameter.GetProperty("toleranceMinus").GetDouble());
+ Assert.Equal(1, diameter.GetProperty("stepFaceEntities").GetArrayLength());
+ 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()));
+ // 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);
+ var bodyLength = BitConverter.ToInt32(baseline, beforeOffset - 8);
+ Assert.Equal(baseline.AsSpan(beforeOffset, bodyLength).ToArray(), file.Bytes.AsSpan(afterOffset, bodyLength).ToArray());
+ Assert.All(PmiDisplayProjection.FromStep(built.Value.StepText), annotation => Assert.NotEmpty(annotation.Lines));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs b/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs
index c45eb05e..4bf84cf5 100644
--- a/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs
@@ -41,7 +41,9 @@ public sealed class ProductArtifactExportTests
Assert.True(Step242Importer.ImportBody(Encoding.UTF8.GetString(Bytes("step"))).IsSuccess);
var glb = Bytes("glb"); Assert.Equal("glTF", Encoding.ASCII.GetString(glb, 0, 4));
using var json = JsonDocument.Parse(glb.AsMemory(20, BitConverter.ToInt32(glb, 12)));
- Assert.Single(json.RootElement.GetProperty("meshes").EnumerateArray());
+ Assert.Single(json.RootElement.GetProperty("meshes").EnumerateArray().Where(mesh => mesh.GetProperty("extras").TryGetProperty("definitionIdentity", out _)));
+ Assert.Equal(expectedPmi.Count, json.RootElement.GetProperty("asset").GetProperty("extras").GetProperty("pmi").GetArrayLength());
+ Assert.All(json.RootElement.GetProperty("meshes").EnumerateArray(), mesh => Assert.True(mesh.GetProperty("primitives")[0].GetProperty("attributes").TryGetProperty("POSITION", out _)));
Assert.Contains("metersPerUnit = 0.001", Encoding.UTF8.GetString(Bytes("usda")));
Assert.Contains("f ", Encoding.UTF8.GetString(Bytes("obj")));
var stl = Bytes("stl"); Assert.Equal(84L + BitConverter.ToUInt32(stl, 80) * 50L, stl.Length);
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index 0156d12d..86e2ec2d 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -30,6 +30,7 @@ public sealed record ResolvedDisplayMaterial(double[] BaseColor, double Roughnes
public sealed record AssemblyDisplayMeshDocument(string Schema, string Name, string Units,
IReadOnlyList<AssemblyDisplayMeshDefinition> Definitions, IReadOnlyList<AssemblyDisplayMeshOccurrence> Occurrences)
{
+ public IReadOnlyList<Visualization.PmiDisplayAnnotation> Annotations { 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 ec6452ef..bf217d33 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
@@ -163,6 +163,18 @@ public static class AssemblyGlbExporter
// One explicit boundary converts Z-up millimetres to right-handed Y-up metres:
// (x,y,z) -> .001 * (x,z,-y). All original local frames remain inspectable.
var roots = occurrences.Where(o => o.ParentId is null).Select(o => occurrenceIds[o.Id]).ToList();
+ var pmiJsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+ foreach (var annotation in display.Annotations)
+ {
+ var positions = annotation.Lines.SelectMany(line => line.Zip(line.Skip(1), (a, b) => new[] { a, b })
+ .SelectMany(pair => pair).SelectMany(point => point)).ToArray();
+ if (positions.Length == 0) throw new InvalidOperationException("glb-pmi-presentation-empty:" + annotation.Name);
+ materials.Add(new { name = "PMI " + annotation.Name, pbrMetallicRoughness = new { baseColorFactor = new[] { .05, .1, .18, 1 }, metallicFactor = 0, roughnessFactor = 1 } });
+ meshes.Add(new { name = annotation.Id, primitives = new[] { new { attributes = new Dictionary<string, object> { ["POSITION"] = Floats(positions, 3, true) }, mode = 1, material = materials.Count - 1 } },
+ 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) } });
+ }
foreach (var (camera,index) in (cameras ?? []).Select((c,i) => (c,i)))
{
ValidateTransform(camera.Transform);
@@ -174,7 +186,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" } },
+ ["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) } },
["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) } }
diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
index 8f24a476..5cf1f8c2 100644
--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
@@ -2,7 +2,7 @@ using System.Collections.Frozen;
namespace Aetheris.Kernel.Firmament.Assembly;
-/// <summary>An immutable, project-relative source set for a Firmament Part, Assembly or Scene build.</summary>
+/// <summary>An immutable, project-relative source set and STEP text assets for a Firmament build.</summary>
public sealed class FirmamentProjectSnapshot
{
private readonly IReadOnlyDictionary<string, string> documents;
@@ -21,7 +21,8 @@ public sealed class FirmamentProjectSnapshot
{
var key = NormalizePath(path);
if (!key.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase) &&
- !key.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase))
+ !key.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase) &&
+ !IsStepAsset(key))
throw new ArgumentException($"Unsupported project document kind: '{key}'.", nameof(documents));
if (!normalized.TryAdd(key, source ?? throw new ArgumentException($"Null source for '{key}'.", nameof(documents))))
throw new ArgumentException($"Duplicate normalized project path: '{key}'.", nameof(documents));
@@ -50,4 +51,7 @@ public sealed class FirmamentProjectSnapshot
}
public bool TryResolve(string path, out string source) => documents.TryGetValue(NormalizePath(path), out source!);
+
+ public static bool IsStepAsset(string path) => path.EndsWith(".step", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".stp", StringComparison.OrdinalIgnoreCase);
+ public IEnumerable<KeyValuePair<string, string>> SourceDocuments => documents.Where(d => !IsStepAsset(d.Key));
}
diff --git a/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs b/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
index 9ba50549..6e2fcda8 100644
--- a/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
+++ b/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
@@ -70,7 +70,9 @@ public static class ProductArtifactExporter
{
case "step": bytes = Encoding.UTF8.GetBytes(source.StepText!); mediaType = "model/step"; break;
case "glb":
- bytes = source.Scene is { } scene ? SceneExport.Glb(scene) : AssemblyGlbExporter.Serialize(source.Display,
+ 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;
+ 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));
mediaType = "model/gltf-binary"; break;
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 7de6d6d1..7384204e 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -122,14 +122,15 @@ public static partial class FirmamentBuildAndExport
/// </summary>
public static KernelResult<FirmamentStepExportResult> CompileSource(
string sourceText,
- string? sourceDirectory = null) => CompileSourceCore(sourceText, sourceDirectory, true);
+ string? sourceDirectory = null, IReadOnlyDictionary<string, string>? resources = null) => CompileSourceCore(sourceText, sourceDirectory, true, resources);
/// <summary>Explicit inspection boundary: admit and build geometry, but do not
/// claim that its declared assertions passed. Used to discover assertion inputs.</summary>
public static KernelResult<FirmamentStepExportResult> CompileForMeasurement(string sourceText, string? sourceDirectory = null)
=> CompileSourceCore(sourceText, sourceDirectory, false);
- private static KernelResult<FirmamentStepExportResult> CompileSourceCore(string sourceText, string? sourceDirectory, bool enforceAssertions)
+ private static KernelResult<FirmamentStepExportResult> CompileSourceCore(string sourceText, string? sourceDirectory, bool enforceAssertions,
+ IReadOnlyDictionary<string, string>? resources = null)
{
ArgumentNullException.ThrowIfNull(sourceText);
var normalized = sourceText;
@@ -158,10 +159,10 @@ public static partial class FirmamentBuildAndExport
// In-memory compilation is the canonical V2 boundary used by Forge,
// assemblies, and drawings. Historical V1 execution is intentionally
// available only to the explicitly versioned file compatibility route.
- var export = ExportSource(normalized, sourceDirectory, allowV1Compatibility: false, frontend.Schema);
+ var export = ExportSource(normalized, sourceDirectory, allowV1Compatibility: false, frontend.Schema, resources);
if (!export.IsSuccess) return export;
- var enrichedExport = AttachAuthoredFeatureReports(normalized, sourceDirectory, export.Value);
- var pmiParity = VerifyV2PmiExportParity(normalized, sourceDirectory, enrichedExport);
+ var enrichedExport = AttachAuthoredFeatureReports(normalized, sourceDirectory, export.Value, resources);
+ var pmiParity = VerifyV2PmiExportParity(normalized, sourceDirectory, enrichedExport, resources);
if (!pmiParity.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(pmiParity.Diagnostics);
if (!enforceAssertions) return KernelResult<FirmamentStepExportResult>.Success(enrichedExport, export.Diagnostics);
var assertions = EvaluateAssertions(normalized, sourceDirectory, enrichedExport);
@@ -173,9 +174,9 @@ public static partial class FirmamentBuildAndExport
private static FirmamentStepExportResult AttachAuthoredFeatureReports(
string source,
string? sourceDirectory,
- FirmamentStepExportResult export)
+ FirmamentStepExportResult export, IReadOnlyDictionary<string, string>? resources = null)
{
- var parsed = ParseSemanticSource(source, sourceDirectory);
+ var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
if (!parsed.IsSuccess || parsed.Document is null) return export;
export = export with { DocumentName = parsed.Document.ModelName, RuntimeAdmissionDocument = parsed.Document,
ConceptDisplayValues = parsed.Document.ConceptIr?.Structs
@@ -221,9 +222,10 @@ public static partial class FirmamentBuildAndExport
};
}
- private static KernelResult<bool> VerifyV2PmiExportParity(string source, string? sourceDirectory, FirmamentStepExportResult export)
+ private static KernelResult<bool> VerifyV2PmiExportParity(string source, string? sourceDirectory, FirmamentStepExportResult export,
+ IReadOnlyDictionary<string, string>? resources = null)
{
- var parsed = ParseSemanticSource(source, sourceDirectory);
+ var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
if (!parsed.IsSuccess || parsed.Document is null || parsed.Document.Pmi is not { Count: > 0 } pmi)
return KernelResult<bool>.Success(true);
@@ -251,14 +253,14 @@ public static partial class FirmamentBuildAndExport
string sourceText,
string? sourceDirectory = null,
bool allowV1Compatibility = false,
- FirmamentFrontendSchema? explicitSchema = null)
+ FirmamentFrontendSchema? explicitSchema = null, IReadOnlyDictionary<string, string>? resources = null)
{
// Production mechanical execution consumes the result of AST admission.
// Its expansion pipeline runs once in the frontend. Unmigrated domain owners
// retain their existing expansion boundary until their own cutover.
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();
- var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema);
+ var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema, resources);
canonicalParseWatch.Stop();
var templateBindWatch = new System.Diagnostics.Stopwatch();
string materializerSource;
@@ -2203,7 +2205,7 @@ public static partial class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, FirmamentV2Parser.ReplacementVerificationFailed, "FirmamentV2.InlineStepReplacement")]);
}
- var stepText = File.ReadAllText(solid.InlineStep.NormalizedPath, Encoding.UTF8);
+ var stepText = solid.InlineStep.SourceText ?? File.ReadAllText(solid.InlineStep.NormalizedPath, Encoding.UTF8);
var import = Step242Importer.ImportBody(stepText);
if (!import.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(import.Diagnostics);
@@ -2263,7 +2265,10 @@ public static partial class FirmamentBuildAndExport
return null;
}
- var stepText = File.ReadAllText(inlineStep.NormalizedPath, Encoding.UTF8);
+ var stepText = inlineStep.SourceText ?? File.ReadAllText(inlineStep.NormalizedPath, Encoding.UTF8);
+ if (Step242SemanticPmiInspector.Inspect(stepText).Items.Count > 0)
+ return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,
+ KernelDiagnosticSeverity.Error, "firmament-v2-inline-step-existing-pmi-unsupported: This STEP already contains semantic PMI. Importing that annotation layer is not yet qualified and must not silently discard it. Reopen the original Firmament/Helios workspace instead.", "FirmamentV2.InlineStep")]);
var import = Step242Importer.ImportBody(stepText);
if (!import.IsSuccess)
{
@@ -2277,6 +2282,14 @@ public static partial class FirmamentBuildAndExport
}
var semanticPmi = BuildV2SemanticPmi(document, [], solid.Name, body: import.Value);
+ foreach (var item in semanticPmi)
+ {
+ var required = item is Step242SemanticPmiDatum ? SurfaceGeometryKind.Plane : SurfaceGeometryKind.Cylinder;
+ if (item.GeometricFaceIds.Count == 0 || item.GeometricFaceIds.Any(id =>
+ !import.Value.TryGetFaceSurface(new Core.Topology.FaceId(id), out var surface) || surface?.Kind != required))
+ return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,
+ KernelDiagnosticSeverity.Error, $"firmament-v2-imported-pmi-target-kind: '{item.FeatureId}' requires a resolved {required} face. The imported geometry is immutable; choose a compatible face.", "FirmamentV2.Pmi")]);
+ }
var export = Step242Exporter.ExportBody(import.Value, semanticPmi, new Step242ExportOptions
{
ProductName = solid.Name,
@@ -2297,7 +2310,8 @@ public static partial class FirmamentBuildAndExport
DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],
InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: "canonical-reexport", residualSurgery: false),
- InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document)));
+ InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document))
+ { RuntimeBody = import.Value, RuntimeBodySourceName = solid.Name, RuntimeAdmissionDocument = document });
}
private static KernelResult<FirmamentStepExportResult>? TryExportV2ControlledSideHoleBody(FirmamentV2Document document)
@@ -2766,8 +2780,17 @@ public static partial class FirmamentBuildAndExport
var boundPmiByName = (document.BoundPmi?.Datums ?? []).Concat(document.BoundPmi?.Dimensions ?? []).Concat(document.BoundPmi?.Controls ?? []).ToDictionary(p => p.Name, StringComparer.Ordinal);
var targetBinding = document.Solids.Single(s => string.Equals(s.Name, targetSolid, StringComparison.Ordinal));
var result = new List<Step242SemanticPmi>();
+ var importedFaces = new Dictionary<string, IReadOnlyList<int>>(StringComparer.Ordinal);
foreach (var pmi in document.Pmi)
{
+ if (targetBinding.InlineStep is not null && body is not null)
+ {
+ var references = ImportedPmiFaceReferences(document, targetBinding, pmi.Target);
+ if (references.Count > 0)
+ importedFaces[pmi.Name] = body.Bindings.FaceBindings
+ .Where(binding => binding.SourceStepEntityId is { } entity && references.Contains("#" + entity))
+ .Select(binding => binding.FaceId.Value).Distinct().Order().ToArray();
+ }
if (pmi.Kind == FirmamentV2PmiKind.HoleDiameter && pmi.Value.HasValue)
{
boundPmiByName.TryGetValue(pmi.Name, out var boundPmi);
@@ -2799,7 +2822,12 @@ public static partial class FirmamentBuildAndExport
return result.Select(item => item with
{
- GeometricFaceIds = item is Step242SemanticPmiDatum datum && body is not null
+ // 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
+ // BRep -> emitted-entity mapping. Preserve both boundaries.
+ GeometricFaceIds = importedFaces.TryGetValue(item switch
+ { Step242SemanticPmiDatum d => d.Label, Step242SemanticPmiHole h => h.Name ?? "", _ => "" }, out var faces)
+ ? faces : item is Step242SemanticPmiDatum datum && body is not null
? FirmamentSelectorResolver.ResolveUniquePlanarFace(body, datum.Target).Select(id => id.Value).ToArray()
: (correspondence?.Descendants ?? [])
.Where(descendant => descendant.Face.HasValue
@@ -2812,6 +2840,17 @@ public static partial class FirmamentBuildAndExport
}).ToArray();
}
+ private static IReadOnlyList<string> ImportedPmiFaceReferences(FirmamentV2Document document, FirmamentV2SolidBinding solid, string target)
+ {
+ var prefix = solid.Name + ".face(\"";
+ if (target.StartsWith(prefix, StringComparison.Ordinal) && target.EndsWith("\")", StringComparison.Ordinal))
+ return [target[prefix.Length..^2]];
+ prefix = solid.Name + ".region(\"";
+ if (!target.StartsWith(prefix, StringComparison.Ordinal) || !target.EndsWith("\")", StringComparison.Ordinal)) return [];
+ var name = target[prefix.Length..^2];
+ return document.RecognizedRegions?.SingleOrDefault(r => r.BodyName == solid.Name && r.RegionName == name)?.FaceRefs ?? [];
+ }
+
private static bool TryResolveV2RecognizedRegionTarget(FirmamentV2Document document, FirmamentV2SolidBinding solid, string target, out string resolved)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index c596f505..a564639b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -26,7 +26,8 @@ public static class FirmamentLanguageAnalysisService
private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.All
.SelectMany(construct => construct.Fields).SelectMany(field => field.Choices).ToHashSet(StringComparer.Ordinal);
- public static FirmamentLanguageAnalysis Analyze(string source, string document, string revision)
+ public static FirmamentLanguageAnalysis Analyze(string source, string document, string revision,
+ string? sourceDirectory = null, IReadOnlyDictionary<string, string>? resources = null)
{
ArgumentNullException.ThrowIfNull(source);
var lexemes = Lex(FirmamentSourceSpelling.Normalize(source));
@@ -86,7 +87,7 @@ public static class FirmamentLanguageAnalysisService
}
if (!hasConcreteRoot && lexemes.Any(t => t.Shape == "identifier" && t.Text is "Template" or "Subassembly" or "Appearance" or "Material"))
return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Declaration modules are validated in their consuming project.", 0, 0)]);
- var parse = FirmamentV2Parser.Parse(source);
+ var parse = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
var failures = parse.Diagnostics.Where(item => FirmamentV2Parser.IsFatalDiagnosticCode(item) || parse.SyntaxDiagnostics.Any(d => d.Code == item && d.Severity == "warning") ||
item == "firmament-v2-parse-failed").Distinct(StringComparer.Ordinal).ToArray();
if (failures.Length > 1) failures = failures.Where(item => item != "firmament-v2-parse-failed").ToArray();
@@ -130,7 +131,7 @@ public static class FirmamentLanguageAnalysisService
var tokens = Lex(FirmamentSourceSpelling.Normalize(source));
var selected = tokens.FirstOrDefault(t => t.Shape == "identifier" && t.Start <= offset && offset < t.Start + t.Length);
if (selected is null) return null;
- var matches = project.Documents.SelectMany(d => Declarations(Lex(d.Value), selected.Text, ReferenceKind(tokens, selected))
+ var matches = project.SourceDocuments.SelectMany(d => Declarations(Lex(d.Value), selected.Text, ReferenceKind(tokens, selected))
.Select(t => new FirmamentLanguageLocation(d.Key, t.Start, t.Length))).ToArray();
return matches.Length == 1 ? matches[0] : null;
}
@@ -138,6 +139,9 @@ public static class FirmamentLanguageAnalysisService
public static FirmamentLanguageAnalysis Analyze(FirmamentProjectSnapshot project, string document, string revision)
{
if (!project.TryResolve(document, out var source)) throw new ArgumentException("Document is absent from the snapshot.", nameof(document));
+ if (!project.TryResolve(project.RootDocument, out var rootSource)
+ || !HasAssemblyRoot(rootSource, project.RootDocument, project))
+ return Analyze(source, document, revision, Path.GetDirectoryName(document), project.Documents);
if (SceneAuthoring.HasRoot(source) || Garment.GarmentAuthoring.HasRoot(source)) return Analyze(source,document,revision);
var tokens = Lex(FirmamentSourceSpelling.Normalize(source));
var parsed = new AssemblyM0Parser().ParseProject(project);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs
index 3c2b22ab..a8789ec1 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs
@@ -115,7 +115,7 @@ public static class FirmamentLanguageOutlineService
var local = Outline(source, document, revision);
if (local.Externals.Count == 0) return local;
var self = Assembly.FirmamentProjectSnapshot.NormalizePath(document);
- var others = project.Documents.Where(d => !string.Equals(d.Key, self, StringComparison.Ordinal))
+ var others = project.SourceDocuments.Where(d => !string.Equals(d.Key, self, StringComparison.Ordinal))
.Select(d => Outline(d.Value, d.Key, revision)).ToArray();
var topLevel = others.SelectMany(o => o.Nodes.Where(n => n.ParentId is null && n.Name is not null && !NameIsUseKind(n))
.Select(n => (Document: o.Document, Node: n, Outline: o))).ToLookup(x => x.Node.Name!, StringComparer.Ordinal);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 7e72bf50..3b50f7ed 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -95,7 +95,12 @@ public sealed record FirmamentV2StandardPartRecord(
/// <summary>A bounded exact analytic construction recipe assembled from reusable
/// regular-prism, coaxial cone, torus-blend, cylinder, and cone-frustum operations.</summary>
public sealed record FirmamentV2ExactCoaxialPartRecord(IReadOnlyDictionary<string, string> Parameters) : FirmamentV2PrimitiveRecord;
-public sealed record FirmamentV2InlineStepRecord(string SourcePath, string NormalizedPath, string ContentHash, bool CanonicalInput, string CanonicalEvidence, ImportedStepTopologyMap TopologyMap) : FirmamentV2PrimitiveRecord;
+public sealed record FirmamentV2InlineStepRecord(string SourcePath, string NormalizedPath, string ContentHash, bool CanonicalInput, string CanonicalEvidence, ImportedStepTopologyMap TopologyMap) : FirmamentV2PrimitiveRecord
+{
+ /// <summary>The admitted immutable input. Lowering must not reopen a changed file.</summary>
+ [System.Text.Json.Serialization.JsonIgnore]
+ public string? SourceText { get; init; }
+}
public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string> FaceEntityToFaceId, IReadOnlyDictionary<string, string> FaceIdToFaceEntity)
{
public bool TryResolveFaceEntity(string entityRef, out string faceId) => FaceEntityToFaceId.TryGetValue(entityRef, out faceId!);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.cs
index 1a2117d2..8cd30dca 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.cs
@@ -118,7 +118,8 @@ public static partial class FirmamentV2Parser
// Historical solid declarations are an AST spelling adapter, not another
// primitive grammar. Units remain implicit only within this admitted syntax.
private static Dictionary<string, FirmamentV2SolidBinding> BindCompatibilitySolids(
- SyntaxParseResult syntax, DeclarationSyntax? model, string source, string? directory, List<string> diagnostics)
+ SyntaxParseResult syntax, DeclarationSyntax? model, string source, string? directory, List<string> diagnostics,
+ IReadOnlyDictionary<string, string>? resources = null)
{
var solids = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);
if (model?.Body is null) return solids;
@@ -161,7 +162,7 @@ public static partial class FirmamentV2Parser
// The import owner retains canonical AP242 admission and topology
// evidence; syntax and unknown-field admission are AST-owned.
var span = body.ContentSpan;
- binding = ParseInlineStep(declaration.Name.Text, source.Substring(span.Start, span.Length), diagnostics, directory);
+ binding = ParseInlineStep(declaration.Name.Text, source.Substring(span.Start, span.Length), diagnostics, directory, resources);
}
else if (type is "Box" or "Cylinder" or "Cone" or "Sphere" or "Torus")
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
index 388b2f09..d68c9011 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -37,7 +37,8 @@ public static partial class FirmamentV2Parser
/// follows declared material bodies; unused construction data cannot select a grammar.</summary>
private static FirmamentV2ParseResult BindMechanicalModel(DocumentSyntax syntax, DeclarationSyntax model,
string source, List<string> diagnostics, string? sourceDirectory,
- IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null)
+ IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null,
+ IReadOnlyDictionary<string, string>? resources = null)
{
if (model.Body is null || model.Name is null) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
if (model.Clauses.Count > 0 || model.Type.Arguments.Count > 0)
@@ -151,7 +152,7 @@ public static partial class FirmamentV2Parser
{
var body = declaration.Body;
if (body is null || declaration.Name is null) { diagnostics.Add(CanonicalPrimitiveMalformed); continue; }
- var imported = ParseInlineStep(declaration.Name.Text, source.Substring(body.Span.Start + 1, body.Span.Length - 2), diagnostics, sourceDirectory);
+ var imported = ParseInlineStep(declaration.Name.Text, source.Substring(body.Span.Start + 1, body.Span.Length - 2), diagnostics, sourceDirectory, resources);
if (imported is not null && !solids.TryAdd(imported.Name, imported)) diagnostics.Add(DuplicateName);
}
if (solids.Count == 0) diagnostics.Add(MissingSolid);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 4ee1b0a2..b7a33110 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -291,7 +291,8 @@ public static partial class FirmamentV2Parser
/// <summary>Carries a selected schema through library/specialization processing;
/// it cannot override a conflicting authored schema.</summary>
public static FirmamentV2ParseResult Parse(string sourceText, string? sourceDirectory,
- FirmamentV2ForgeConceptCatalog? conceptCatalog, FirmamentFrontendSchema? expectedSchema)
+ FirmamentV2ForgeConceptCatalog? conceptCatalog, FirmamentFrontendSchema? expectedSchema,
+ IReadOnlyDictionary<string, string>? resources = null)
{
using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("firmament.v2-parse");
ArgumentNullException.ThrowIfNull(sourceText);
@@ -299,8 +300,8 @@ public static partial class FirmamentV2Parser
// four times). The parser is a pure function of its text and directory, and its result is
// immutable records, except InlineStep, which reads a STEP file; those, and parses with a
// concept catalog, always run.
- if (conceptCatalog is not null || sourceText.Contains("InlineStep", StringComparison.OrdinalIgnoreCase))
- return ParseWithDirectives(sourceText, sourceDirectory, conceptCatalog, expectedSchema);
+ if (resources is not null || conceptCatalog is not null || sourceText.Contains("InlineStep", StringComparison.OrdinalIgnoreCase))
+ return ParseWithDirectives(sourceText, sourceDirectory, conceptCatalog, expectedSchema, resources);
var key = expectedSchema + "\0" + (sourceDirectory ?? string.Empty) + "\0" + sourceText;
lock (RecentParses)
{
@@ -326,7 +327,7 @@ public static partial class FirmamentV2Parser
private static readonly List<(string Key, FirmamentV2ParseResult Result)> RecentParses = [];
private static FirmamentV2ParseResult ParseWithDirectives(string source, string? directory, FirmamentV2ForgeConceptCatalog? catalog,
- FirmamentFrontendSchema? expectedSchema)
+ FirmamentFrontendSchema? expectedSchema, IReadOnlyDictionary<string, string>? resources = null)
{
var frontend = FirmamentFrontendSchemas.Select(source);
if (!frontend.IsSuccess) return frontend.Failure(source);
@@ -345,7 +346,7 @@ public static partial class FirmamentV2Parser
return FirmamentV2ParseResult.Failure(reported.Select(d => d.Code).ToArray()) with
{ OriginalSource = source, SyntaxDiagnostics = reported, ParserRoute = "UnifiedDirectives", OwnsUnifiedAdmission = true };
}
- var parsed = ParseUncached(frontend.Source, directory, catalog);
+ var parsed = ParseUncached(frontend.Source, directory, catalog, resources);
if (parsed.IsSuccess && (frontend.Schema ?? expectedSchema) is { } schema
&& FirmamentFrontendSchemas.DomainMismatch(schema, parsed.BoundSource ?? frontend.Source, admittedSchema: parsed.BoundSchema) is { } mismatch)
return (frontend with { Diagnostics = [mismatch.Code], LocatedDiagnostics =
@@ -394,7 +395,7 @@ public static partial class FirmamentV2Parser
private static FirmamentV2ParseResult ParseUncached(
string sourceText,
string? sourceDirectory,
- FirmamentV2ForgeConceptCatalog? conceptCatalog)
+ FirmamentV2ForgeConceptCatalog? conceptCatalog, IReadOnlyDictionary<string, string>? resources = null)
{
// Serialization roots belong to the historical reader, which still must
// prove explicit version 1 before execution. Their data values may be V2
@@ -586,7 +587,7 @@ public static partial class FirmamentV2Parser
if (!syntax.IsSuccess)
return FirmamentV2ParseResult.Failure(diagnostics.Concat(syntax.Diagnostics.Select(d => d.Code)).ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid)
with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };
- var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations, compileTime))
+ var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations, compileTime, resources))
with { DiagnosticSource = source };
if (parsed.Document is null) return parsed with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true };
if (domainDeclarations.Any(d => d.Type.Name.Text == "Plateau"))
@@ -622,7 +623,7 @@ public static partial class FirmamentV2Parser
var compatibilityCore = BindCompatibilityScope(syntax.Document, compatibilityModel, diagnostics);
if (compatibilityCore) diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code));
- var byName = BindCompatibilitySolids(syntax, compatibilityModel, source, sourceDirectory, diagnostics);
+ var byName = BindCompatibilitySolids(syntax, compatibilityModel, source, sourceDirectory, diagnostics, resources);
// A referenced record prototype is compile-time data, not another output
// body. Preserve legitimate `with` derivation while rejecting unrelated
// material that the last-body exporter would otherwise discard.
@@ -1077,7 +1078,8 @@ public static partial class FirmamentV2Parser
}
}
- private static FirmamentV2SolidBinding? ParseInlineStep(string name, string body, List<string> diagnostics, string? sourceDirectory)
+ private static FirmamentV2SolidBinding? ParseInlineStep(string name, string body, List<string> diagnostics, string? sourceDirectory,
+ IReadOnlyDictionary<string, string>? resources = null)
{
var match = Regex.Match(body, "\\b(?:path|Path)\\s*:\\s*\\\"(?<path>[^\\\"]+)\\\"", RegexOptions.CultureInvariant);
if (!match.Success) { diagnostics.Add(InlineStepPathMissing); return null; }
@@ -1089,15 +1091,22 @@ public static partial class FirmamentV2Parser
return null;
}
- var baseDirectory = string.IsNullOrWhiteSpace(sourceDirectory) ? Directory.GetCurrentDirectory() : sourceDirectory;
- var normalizedPath = Path.GetFullPath(Path.Combine(baseDirectory!, sourcePath));
- if (!File.Exists(normalizedPath))
+ string normalizedPath;
+ string stepText;
+ if (resources is not null)
{
- diagnostics.Add(InlineStepFileMissing);
- return null;
+ // Explicit browser/project snapshots never fall through to the host filesystem.
+ try { normalizedPath = Assembly.FirmamentProjectSnapshot.NormalizePath((sourceDirectory is { Length: > 0 } ? sourceDirectory + "/" : "") + sourcePath); }
+ catch (ArgumentException) { diagnostics.Add(InlineStepPathInvalid); return null; }
+ if (!resources.TryGetValue(normalizedPath, out stepText!)) { diagnostics.Add(InlineStepFileMissing); return null; }
+ }
+ else
+ {
+ var baseDirectory = string.IsNullOrWhiteSpace(sourceDirectory) ? Directory.GetCurrentDirectory() : sourceDirectory;
+ normalizedPath = Path.GetFullPath(Path.Combine(baseDirectory!, sourcePath));
+ if (!File.Exists(normalizedPath)) { diagnostics.Add(InlineStepFileMissing); return null; }
+ stepText = File.ReadAllText(normalizedPath, Encoding.UTF8);
}
-
- var stepText = File.ReadAllText(normalizedPath, Encoding.UTF8);
if (!IsAetherisCanonicalStep(stepText, out var evidence))
{
diagnostics.Add(InlineStepRequiresCanonical);
@@ -1105,19 +1114,19 @@ public static partial class FirmamentV2Parser
}
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(stepText))).ToLowerInvariant();
- return new FirmamentV2SolidBinding(name, "InlineStep", new FirmamentV2InlineStepRecord(sourcePath, normalizedPath, hash, true, evidence, BuildImportedStepTopologyMap(stepText)));
+ return new FirmamentV2SolidBinding(name, "InlineStep", new FirmamentV2InlineStepRecord(sourcePath, normalizedPath, hash, true, evidence, BuildImportedStepTopologyMap(stepText)) { SourceText = stepText });
}
private static ImportedStepTopologyMap BuildImportedStepTopologyMap(string stepText)
{
var faceEntityToFaceId = new Dictionary<string, string>(StringComparer.Ordinal);
var faceIdToFaceEntity = new Dictionary<string, string>(StringComparer.Ordinal);
- var ordinal = 0;
- foreach (Match match in Regex.Matches(stepText, @"(?m)^\s*(#[0-9]+)\s*=\s*ADVANCED_FACE\s*\(", RegexOptions.CultureInvariant))
+ var imported = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(stepText);
+ foreach (var binding in imported.IsSuccess ? imported.Value.Bindings.FaceBindings : [])
{
- ordinal++;
- var entity = match.Groups[1].Value;
- var faceId = $"face-{ordinal}";
+ if (binding.SourceStepEntityId is not { } sourceEntity) continue;
+ var entity = "#" + sourceEntity;
+ var faceId = $"face-{binding.FaceId.Value}";
faceEntityToFaceId[entity] = faceId;
faceIdToFaceEntity[faceId] = entity;
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs b/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs
index ee2bf6a2..40ade5ba 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PlanarTextProfiles.cs
@@ -24,6 +24,30 @@ public static class PlanarTextProfiles
{
private static readonly Lazy<Typeface> DefaultTypeface = new(LoadInter);
+ /// <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)
+ {
+ 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 curves = new List<LineArcProfileCurve2D>();
+ foreach (var rune in content.EnumerateRunes())
+ {
+ 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);
+ curves.AddRange(translator.Contours.SelectMany(contour => contour.Transform(cursor, scale).Curves));
+ cursor += typeface.GetAdvanceWidthFromGlyphIndex(index) * scale;
+ }
+ return curves;
+ }
+
public static PlanarTextProfileResult Build(string content, double height,
PlanarTextAlignment alignment = PlanarTextAlignment.Left,
ConstructionPlane? supportFrame = null, string featureId = "Text")
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
new file mode 100644
index 00000000..9ea78d3c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
@@ -0,0 +1,72 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Visualization;
+
+/// <summary>Presentation only. Values and topology associations come from AP242 readback,
+/// never from rounded display coordinates. Points are in Z-up millimetres.</summary>
+public sealed record PmiDisplayAnnotation(string Id, string Kind, string Name, string Text,
+ double? Value, double? TolerancePlus, double? ToleranceMinus, IReadOnlyList<int> StepFaceEntities,
+ double[] Anchor, double[] LabelPosition, double TextHeight, IReadOnlyList<double[][]> Lines);
+
+public static class PmiDisplayProjection
+{
+ public static IReadOnlyList<PmiDisplayAnnotation> FromStep(string step)
+ {
+ var inspection = Step242SemanticPmiInspector.Inspect(step);
+ if (!inspection.Success) throw new InvalidOperationException("pmi-display-inspection-failed: " + string.Join("; ", inspection.Diagnostics));
+ if (inspection.Items.Count == 0) return [];
+ var imported = Step242Importer.ImportBody(step);
+ if (!imported.IsSuccess) throw new InvalidOperationException("pmi-display-body-unavailable");
+ var body = imported.Value;
+ var tessellation = BrepDisplayTessellator.Tessellate(body, DisplayTessellationOptions.Default);
+ if (!tessellation.IsSuccess) throw new InvalidOperationException("pmi-display-target-unavailable");
+ var patches = tessellation.Value.FacePatches.ToDictionary(p => p.FaceId.Value);
+ var sourceFaces = body.Bindings.FaceBindings.Where(b => b.SourceStepEntityId.HasValue)
+ .ToDictionary(b => b.SourceStepEntityId!.Value, b => b.FaceId.Value);
+ var points = patches.Values.SelectMany(p => p.Positions).ToArray();
+ if (points.Length == 0) throw new InvalidOperationException("pmi-display-target-unavailable: No displayable faces are available for callouts.");
+ 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 maxZ = points.Max(p => p.Z);
+ var height = Math.Clamp(Math.Max(maxX - minX, maxY - minY) / 25, .5, 8);
+ var result = new List<PmiDisplayAnnotation>();
+ foreach (var item in inspection.Items)
+ {
+ if (item.Kind is not ("Datum" or "Diameter"))
+ throw new InvalidOperationException($"pmi-display-kind-unsupported: {item.Kind} '{item.Name}' has no qualified 3D callout yet.");
+ var targets = item.GeometricFaceEntityIds.Where(id => sourceFaces.TryGetValue(id, out var face)
+ && patches.TryGetValue(face, out var patch) && patch.Positions.Count > 0)
+ .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.");
+ var anchorPoint = targets[0].Positions[0];
+ double[] anchor = [anchorPoint.X, anchorPoint.Y, anchorPoint.Z];
+ double[] label = [maxX + height * 3, maxY - result.Count * height * 2.5, maxZ + height];
+ string N(double value) => value.ToString("G9", CultureInfo.InvariantCulture);
+ var text = item.Kind == "Datum" ? $"[{item.Name}]" : $"Ø{N(item.Value!.Value)}"
+ + (item.TolerancePlus.HasValue && item.ToleranceMinus.HasValue ? $" +{N(item.TolerancePlus.Value)}/-{N(item.ToleranceMinus.Value)}" : "") + " mm";
+ var outlines = PlanarTextProfiles.PresentationContours(text, height);
+ var lines = new List<double[][]> { new[] { anchor, new[] { label[0] - height, label[1], label[2] }, label } };
+ foreach (var curve in outlines)
+ {
+ double[] P((double X, double Y) p) => [label[0] + p.X, label[1] + p.Y, label[2]];
+ lines.Add(curve switch
+ {
+ 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")
+ });
+ }
+ 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));
+ }
+ return result;
+ }
+}
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index 8c9dfc93..b6f09a62 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -106,7 +106,7 @@ public static partial class Program
{
compile = true, solidModeling = true, assembly = true, displayMesh = true,
propertyInspection = true, parameterRebuild = true, stepExport = true, artifactExport = true,
- sheetMetal = false, fea = false, externalStepImport = false, forgeSubprocess = false,
+ sheetMetal = false, fea = false, externalStepImport = true, forgeSubprocess = false,
cancellation = false, worker = false
}
};
@@ -141,9 +141,8 @@ public static partial class Program
: null;
var root = request.ProjectRoot ?? name;
var project = documents is null ? null : new FirmamentProjectSnapshot(root, documents);
- var analysis = documents is not null && documents.TryGetValue(root, out var rootSource) &&
- FirmamentLanguageAnalysisService.HasAssemblyRoot(rootSource, root, project)
- ? FirmamentLanguageAnalysisService.Analyze(project!, name, request.SourceRevision)
+ var analysis = project is not null
+ ? FirmamentLanguageAnalysisService.Analyze(project, name, request.SourceRevision)
: FirmamentLanguageAnalysisService.Analyze(request.Source, name, request.SourceRevision);
return new { document = name, revision = request.SourceRevision, analysis.Tokens,
diagnostics = analysis.Diagnostics.Select(item => new WebDiagnostic(item.Severity, item.Code, item.Message,
@@ -345,7 +344,7 @@ public static partial class Program
{
RequireExportRevision(request.BuildRevision);
var formats = request.Formats ?? [];
- var needsStep = formats.Any(f => f is not ("glb" or "usda"));
+ var needsStep = formats.Any(f => f is not ("glb" or "usda")) || formats.Contains("glb") && _expectedPmi.Count > 0;
try
{
var files = ProductArtifactExporter.Export(new(Name, needsStep ? StepText : null, _exportDisplay!, _assembly, _scene, _expectedPmi, _sourceName),
@@ -536,7 +535,8 @@ public static partial class Program
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var compilePhase = BuildPerfTrace.Phase("web.compile-and-export");
- var build = FirmamentBuildAndExport.CompileSource(effective);
+ var project = _projectDocuments is { Count: > 0 } ? new FirmamentProjectSnapshot(_sourceName, _projectDocuments) : null;
+ var build = FirmamentBuildAndExport.CompileSource(effective, Path.GetDirectoryName(_sourceName), project?.Documents);
compilePhase.Dispose();
var compileMs = watch.Elapsed.TotalMilliseconds;
if (!build.IsSuccess || build.Value is null)
@@ -566,7 +566,7 @@ public static partial class Program
? SourceRefAt(_sourceName, effective, span.Start, span.Length) : null;
var boxSource = CompilerSource(entityId);
// Preserve the exported body category in Kind; report the authored construct separately.
- var parsed = FirmamentV2Parser.Parse(effective);
+ var parsed = FirmamentV2Parser.Parse(effective, Path.GetDirectoryName(_sourceName), null, null, project?.Documents);
var semanticConstruct = boxSource is null ? null : parsed.Document?.Solids
.FirstOrDefault(solid => string.Equals(solid.Name, entityId, StringComparison.Ordinal))?.RecordType;
IReadOnlyList<FirmamentConstructProjection> projections = _overrides.Count == 0 && parsed.Document is { } document
@@ -589,8 +589,20 @@ public static partial class Program
? SourceRefAt(_sourceName, effective, span.Start, span.Length) : CompilerSource(feature.FeatureId), StringComparer.Ordinal);
mappingPhase.Dispose();
var meshPhase = BuildPerfTrace.Phase("web.mesh-build");
+ IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.PmiDisplayAnnotation> annotations;
+ IReadOnlyList<WebDiagnostic> presentationDiagnostics = [];
+ try { annotations = Aetheris.Kernel.Firmament.Visualization.PmiDisplayProjection.FromStep(step); }
+ catch (InvalidOperationException error) when (error.Message.StartsWith("pmi-display-", StringComparison.Ordinal))
+ {
+ // A missing presentation adapter cannot invalidate admitted engineering geometry.
+ // STEP keeps its requirements; annotated GLB export still requires complete projection.
+ annotations = [];
+ presentationDiagnostics = [new("warning", "pmi-preview-unavailable", error.Message + " STEP remains authoritative. Annotated GLB export requires a supported callout projection.")];
+ }
var mesh = WebMeshBuilder.Build(Name, definitionId, entityId, displayBody, out var exportDisplay,
- build.Value.RuntimeCorrespondence, boxSource, Revision + 1, featureSources, build.Value.Cir, Aetheris.Kernel.Firmament.Visualization.ConceptDisplayProjection.Project(build.Value));
+ build.Value.RuntimeCorrespondence, boxSource, Revision + 1, featureSources, build.Value.Cir, Aetheris.Kernel.Firmament.Visualization.ConceptDisplayProjection.Project(build.Value),
+ build.Value.ExportedBodyCategory == "inline-step" ? entityId : null, annotations,
+ parsed.Document?.Solids.SingleOrDefault()?.InlineStep);
meshPhase.Dispose();
var meshMs = watch.Elapsed.TotalMilliseconds;
var featureNodes = (build.Value.EngineeringFeatures ?? []).Select(feature => new WebTreeNode(feature.FeatureId, feature.Kind, feature.Name, entityId, [], true,
@@ -605,7 +617,7 @@ public static partial class Program
var tree = new { rootId = root.Id, nodes = new[] { root, body }.Concat(featureNodes).ToArray() };
var expectedPmi = Aetheris.Kernel.Firmament.Drawing.FirmamentDrawingCompiler.AuthoredPmiNames(build.Value);
return WebBuildResult.Passed(step, tree, mesh, [Id, entityId, .. featureNodes.Select(item => item.Id)], compileMs, meshMs)
- with { Projections = projections, ExportDisplay = exportDisplay, ExpectedPmi = expectedPmi };
+ with { Projections = projections, ExportDisplay = exportDisplay, ExpectedPmi = expectedPmi, Diagnostics = presentationDiagnostics };
}
private WebBuildResult CompileAssembly(string effective, List<WebProperty> properties)
@@ -797,7 +809,9 @@ internal static class WebMeshBuilder
public static object Build(string name, string definitionId, string entityId, BrepBody body, out AssemblyDisplayMeshDocument exportDisplay,
Aetheris.Kernel.Firmament.Materializer.SemanticTopologyCorrespondence? correspondence = null,
WebSourceRef? source = null, int buildRevision = 0, IReadOnlyDictionary<string, WebSourceRef?>? featureSources = null,
- FirmamentCirRetention? cir = null, IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.ConceptDisplayWire>? concepts = null)
+ FirmamentCirRetention? cir = null, IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.ConceptDisplayWire>? concepts = null,
+ string? importedBodyName = null, IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.PmiDisplayAnnotation>? annotations = null,
+ FirmamentV2InlineStepRecord? importedAsset = null)
{
// Browser WASM has no blocking monitor wait. Use the existing synchronous
// tessellator authority; the Worker transport supplies UI responsiveness.
@@ -822,11 +836,14 @@ internal static class WebMeshBuilder
if (sourceMap is not null && sourceMap.TryGetByBrepFace(face.FaceId, out var mappedFace)) semanticFace = mappedFace;
var owner = semanticFace?.ParentStableId is { } parent && featureSources?.ContainsKey(parent) == true ? parent : entityId;
var faceSource = owner == entityId ? source : featureSources![owner];
+ var imported = importedBodyName is not null && body.Bindings.TryGetFaceBinding(face.FaceId, out var binding) ? binding.SourceStepEntityId : null;
+ body.TryGetFaceSurface(face.FaceId, out var surface);
ranges.Add(new { startTriangle = triangleStart, triangleCount = face.TriangleIndices.Count / 3, faceId = $"face:{face.FaceId.Value}", semanticEntityId = owner,
- semanticTopologyId = semanticFace?.StableId, topologyKind = "Face", outputRole = semanticFace?.Role.ToString(), originFeature = semanticFace?.SourceStableId,
- sourceAddressability = semanticFace?.Addressability.ToString() ?? "RuntimeOnly",
- selector = semanticFace?.FirmamentSelector,
- selectorReason = semanticFace is null ? "No compiler-owned source topology mapping is available for this display face."
+ semanticTopologyId = semanticFace?.StableId ?? (imported is { } importedEntity ? importedBodyName + ":#" + importedEntity : null), topologyKind = "Face", outputRole = semanticFace?.Role.ToString(), originFeature = semanticFace?.SourceStableId,
+ sourceAddressability = imported is not null ? "ImportedStable" : semanticFace?.Addressability.ToString() ?? "RuntimeOnly",
+ selector = imported is not null ? $"{importedBodyName}.face(\"#{imported}\")" : semanticFace?.FirmamentSelector,
+ surfaceKind = surface?.Kind.ToString(), diameterMm = surface?.Cylinder is { } cylinder ? (double?)(2 * cylinder.Radius) : null,
+ selectorReason = imported is not null ? null : semanticFace is null ? "No compiler-owned source topology mapping is available for this display face."
: semanticFace.FirmamentSelector is null ? "Construction identity is known, but Firmament has no qualified source selector for this topology." : null,
source = semanticFace is null ? null : faceSource, buildRevision });
}
@@ -836,12 +853,15 @@ internal static class WebMeshBuilder
var transform = new double[] { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
exportDisplay = new("aetheris/display-mesh/1", name, "mm",
[new(definitionId, entityId, positionArray, normalArray, indexArray)],
- [new(entityId + ":occurrence", name, null, definitionId, transform, entityId)]);
+ [new(entityId + ":occurrence", name, null, definitionId, transform, entityId)]) { Annotations = annotations ?? [] };
return new
{
schema = "aetheris/display-mesh/1",
name,
units = "mm",
+ annotations = annotations ?? [],
+ importedAsset = importedAsset is null ? null : new { path = importedAsset.SourcePath, sha256 = importedAsset.ContentHash,
+ evidence = importedAsset.CanonicalEvidence, qualification = body.ImportQualification },
definitions = new[] { new { id = definitionId, identity = entityId, positions = positionArray, normals = normalArray, indices = indexArray, ranges,
cir, shader, geometryRevision = definitionId, displayPath = shader.Artifact is not null ? "cir" : "mesh", fallbackReason = shader.Reason,
concepts = concepts ?? [],
diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.md
index 39469400..0f9fa7e5 100644
--- a/Aetheris.Web.Runtime/sdk/README.md
+++ b/Aetheris.Web.Runtime/sdk/README.md
@@ -45,6 +45,24 @@ transforms and resolved materials; Scene output also carries millimetre bounds,
environment boundaries and named cameras with poses/look-at/FOV. Scene is display
composition and does not provide a synthetic engineering STEP export.
+Standalone `InlineStep` parts also accept `.step`/`.stp` text in `projectDocuments`.
+Resolve `path` relative to `sourceName` inside that snapshot. The existing
+canonical-input checks apply; arbitrary vendor/assembly import and existing
+imported semantic-PMI layers are not admitted by this slice. The immutable
+admitted text, content hash and importer face provenance are retained. Imported
+face selections expose `ImportedStable`, `part.face("#entity")`, `surfaceKind`
+and `diameterMm` for cylinders. Source addressability is distinct from imported
+topology addressability: there is no synthetic native feature history.
+
+`model.mesh.importedAsset` exposes asset path, SHA-256 and import qualification.
+`model.mesh.annotations` projects AP242 datum/diameter requirements with exact
+values, allowances and separate font-outline/leader curves in Z-up millimetres.
+Shared Telos WebGPU/WebGL adapters render those curves. Part GLB export retains
+the body buffers and appends separate annotation nodes plus structured metadata
+under `asset.extras.pmi` (`aetheris/pmi-display/1`, `pmiUnits: mm`). An unsupported
+callout projection warns in the viewport and rejects annotated GLB export;
+STEP remains the engineering authority. USDA/STL/OBJ do not project PMI.
+
`cad.language.analyze(source, { sourceName, sourceRevision, projectRoot,
projectDocuments })` uses the existing snapshot-aware Assembly analysis when
the root is an Assembly. This resolves included ports without touching disk.
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index e6c0cb62..48ead4f4 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -18,7 +18,18 @@ export interface ConceptDisplayWire { readonly id: string; readonly owner: strin
export interface DisplayMeshDefinition { readonly concepts?: readonly ConceptDisplayWire[]; readonly id: string; readonly identity: string; readonly positions: Float64Array; readonly normals: Float64Array; readonly indices: Uint32Array; readonly ranges: readonly MeshRange[]; readonly edges?: readonly DisplayEdgePolyline[]; readonly cir?: CirRetention | null; readonly displayPath?: 'mesh' | 'cir'; readonly fallbackReason?: string | null; readonly shader?: { readonly artifact: DisplayShaderArtifact | null; readonly status: string; readonly reason: string | null; readonly cacheHit: boolean; readonly generationMilliseconds: number }; readonly geometryRevision?: string | null; readonly diagnostics?: readonly { readonly code: string; readonly message: string; readonly faceId?: string | null }[] }
export interface DisplayMeshOccurrence { readonly concepts?: readonly ConceptDisplayWire[]; readonly id: string; readonly path: string; readonly parentId?: string; readonly definitionId?: string; readonly semanticEntityId: string; readonly transform: readonly number[]; readonly material?: ResolvedDisplayMaterial | null; readonly kind?: string }
export interface DisplayBoundary { readonly path: string; readonly room: string; readonly kind: string; readonly frame: readonly number[]; readonly widthMm: number; readonly heightMm: number; readonly openings: readonly string[] }
-export interface DisplayMesh { readonly schema: 'aetheris/display-mesh/1' | 'aetheris/assembly-display-mesh/1' | 'aetheris/scene-display-mesh/1'; readonly name: string; readonly units: 'mm'; readonly definitions: readonly DisplayMeshDefinition[]; readonly occurrences: readonly DisplayMeshOccurrence[]; readonly cameras?: readonly DisplayCamera[]; readonly minimumMm?: readonly number[]; readonly maximumMm?: readonly number[]; readonly boundaries?: readonly DisplayBoundary[] }
+export interface DisplayMesh { readonly schema: 'aetheris/display-mesh/1' | 'aetheris/assembly-display-mesh/1' | 'aetheris/scene-display-mesh/1'; readonly name: string; readonly units: 'mm'; readonly definitions: readonly DisplayMeshDefinition[]; readonly occurrences: readonly DisplayMeshOccurrence[]; readonly cameras?: readonly DisplayCamera[]; readonly minimumMm?: readonly number[]; readonly maximumMm?: readonly number[]; readonly boundaries?: readonly DisplayBoundary[]; readonly annotations?: readonly PmiDisplayAnnotation[] }
+/** AP242-authoritative requirements and separate presentation curves, Z-up millimetres. */
+export interface PmiDisplayAnnotation {
+ readonly id: string; readonly kind: string; readonly name: string; readonly text: string;
+ readonly value: number | null; readonly tolerancePlus: number | null; readonly toleranceMinus: number | null;
+ readonly stepFaceEntities: readonly number[]; readonly anchor: readonly number[];
+ readonly labelPosition: readonly number[]; readonly textHeight: number;
+ readonly lines: readonly (readonly (readonly number[])[])[];
+}
+export interface MeshRange { readonly surfaceKind?: string | null; readonly diameterMm?: number | null }
+export interface SelectionDescription { readonly surfaceKind?: string | null; readonly diameterMm?: number | null }
+export interface DisplayMesh { readonly importedAsset?: { readonly path: string; readonly sha256: string; readonly evidence: string; readonly qualification: { readonly status: string; readonly geometryStatus: string } | null } | null }
export interface ChangeSet { readonly changedEntityIds: readonly string[]; readonly addedEntityIds: readonly string[]; readonly removedEntityIds: readonly string[]; readonly meshChanged: boolean; readonly diagnosticsChanged: boolean }
export interface RebuildResult { readonly success: boolean; readonly revision: number; readonly diagnostics: readonly Diagnostic[]; readonly retainedPreviousGeometry: boolean; readonly changes?: ChangeSet }
export interface RuntimeCapabilities { readonly compile: boolean; readonly solidModeling: boolean; readonly assembly: boolean; readonly displayMesh: boolean; readonly propertyInspection: boolean; readonly parameterRebuild: boolean; readonly stepExport: boolean; readonly artifactExport?: boolean; readonly sheetMetal: boolean; readonly fea: boolean; readonly externalStepImport: boolean; readonly forgeSubprocess: boolean; readonly cancellation: boolean; readonly worker: boolean }
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
index 25bea1d1..e93da3c5 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.js
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -209,6 +209,7 @@ export class ModelSession {
return range && occurrence ? { semanticEntityId: range.semanticEntityId ?? occurrence.semanticEntityId, faceId: range.faceId, occurrenceId: occurrence.id, definitionId,
semanticTopologyId: range.semanticTopologyId ?? null, topologyKind: range.topologyKind ?? 'Face', outputRole: range.outputRole ?? null, originFeature: range.originFeature ?? null,
selector: range.selector ?? null, sourceAddressability: range.sourceAddressability ?? 'RuntimeOnly',
+ surfaceKind: range.surfaceKind ?? null, diameterMm: range.diameterMm ?? null,
selectorReason: range.selectorReason ?? null, source: range.source ?? null, buildRevision: range.buildRevision ?? this.revision } : null;
}
describeSelection(definitionId, triangleIndex, occurrenceId) {
diff --git a/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs b/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs
index be30f82f..c80d55dc 100644
--- a/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs
+++ b/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs
@@ -2,6 +2,20 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { ModelSession } from '../src/index.js';
+test('imported provenance supplies face selectors and measured size without fabricating a native source span', () => {
+ const model = new ModelSession({}, { revision: 1, mesh: {
+ definitions: [{ id: 'part', ranges: [{ startTriangle: 0, triangleCount: 2, faceId: 'face:7',
+ semanticEntityId: 'part', sourceAddressability: 'ImportedStable', selector: 'part.face("#191")', surfaceKind: 'Cylinder', diameterMm: 2 }] }],
+ occurrences: [{ id: 'part:occurrence', definitionId: 'part', semanticEntityId: 'part' }],
+ } });
+ const picked = model.describeSelection('part', 0, 'part:occurrence');
+ assert.equal(picked.selector, 'part.face("#191")');
+ assert.equal(picked.diameterMm, 2);
+ assert.equal(picked.surfaceKind, 'Cylinder');
+ assert.equal(picked.sourceAddressable, false);
+ assert.equal(picked.source, null);
+});
+
test('display-only face identity never becomes a Firmament selector', () => {
const session = new ModelSession({}, {
mesh: {
diff --git a/Aetheris.Web.Runtime/telos/src/contracts.ts b/Aetheris.Web.Runtime/telos/src/contracts.ts
index 29684c49..4e4109f0 100644
--- a/Aetheris.Web.Runtime/telos/src/contracts.ts
+++ b/Aetheris.Web.Runtime/telos/src/contracts.ts
@@ -46,6 +46,8 @@ export interface TelosMesh {
triangleRange?: { startTriangle: number; triangleCount: number };
}
export interface TelosLine {
+ /** Finite annotations participate in whole-model framing; reference grids do not. */
+ includeInFit?: boolean;
/** Presentation-only guides must not intercept engineering picks. */
pickable?: boolean;
/** Fade finite reference-grid endpoints without changing engineering edge coverage. */
diff --git a/Aetheris.Web.Runtime/telos/src/host.ts b/Aetheris.Web.Runtime/telos/src/host.ts
index 9aaedf40..b5b897d9 100644
--- a/Aetheris.Web.Runtime/telos/src/host.ts
+++ b/Aetheris.Web.Runtime/telos/src/host.ts
@@ -658,6 +658,10 @@ export class TelosHost {
new Vector3(...field.bounds.maximum),
).applyMatrix4(matrix(field.transform)),
);
+ if (!occurrenceIds)
+ for (const line of this.scene.lines.filter(line => line.includeInFit && line.visible !== false))
+ for (let i = 0; i < line.points.length; i += 3)
+ bounds.expandByPoint(new Vector3(line.points[i], line.points[i + 1], line.points[i + 2]).applyMatrix4(matrix(line.transform)));
if (!bounds.isEmpty())
this.camera.fit(bounds.min.toArray(), bounds.max.toArray());
this.invalidate();
diff --git a/Aetheris.Web.Runtime/telos/src/index.ts b/Aetheris.Web.Runtime/telos/src/index.ts
index 045730da..a46f6706 100644
--- a/Aetheris.Web.Runtime/telos/src/index.ts
+++ b/Aetheris.Web.Runtime/telos/src/index.ts
@@ -12,3 +12,4 @@ export * from "./temporal.js";
export * from "./concepts.js";
export * from "./measurement.js";
export * from "./sketch.js";
+export { pmiLines, pmiGroup } from './pmi.js';
diff --git a/Aetheris.Web.Runtime/telos/src/pmi.ts b/Aetheris.Web.Runtime/telos/src/pmi.ts
new file mode 100644
index 00000000..fbb81567
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/pmi.ts
@@ -0,0 +1,21 @@
+import { BufferGeometry, Float32BufferAttribute, Group, LineBasicMaterial, LineSegments } from 'three';
+import type { TelosLine } from './contracts.js';
+
+/** Shared projection of compiler-supplied PMI. Neither adapter invents values or changes body meshes. */
+export interface PmiCurves { readonly id: string; readonly lines: readonly (readonly (readonly number[])[])[] }
+export function pmiLines(annotations: readonly PmiCurves[] = []): TelosLine[] {
+ return annotations.flatMap(annotation => annotation.lines.map((points, index) => ({
+ id: `${annotation.id}:${index}`, points: points.flatMap(p => [...p]), identity: { occurrenceId: annotation.id, overlayId: annotation.id },
+ color: [.04, .12, .24, 1], widthPixels: 1.5, overlay: true, depthMode: 'always-on-top' as const, pickable: false, includeInFit: true,
+ })));
+}
+export function pmiGroup(annotations: readonly PmiCurves[] = []): Group {
+ const group = new Group(); group.name = 'PMI presentation';
+ for (const annotation of annotations) {
+ const positions = annotation.lines.flatMap(line => line.slice(1).flatMap((point, i) => [...line[i], ...point]));
+ const geometry = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(positions, 3));
+ const object = new LineSegments(geometry, new LineBasicMaterial({ color: 0x153356, depthTest: false }));
+ object.name = annotation.id; object.renderOrder = 10; object.raycast = () => undefined; group.add(object);
+ }
+ return group;
+}
diff --git a/Aetheris.Web.Runtime/telos/tests/pmi.test.ts b/Aetheris.Web.Runtime/telos/tests/pmi.test.ts
new file mode 100644
index 00000000..6dd74963
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tests/pmi.test.ts
@@ -0,0 +1,20 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { pmiGroup, pmiLines } from '../dist/pmi.js';
+import { disposeConceptWireframe } from '../dist/concepts.js';
+
+test('both display adapters retain compiler coordinates and keep PMI outside engineering picks', () => {
+ const annotations = [{ id: 'pmi:1', lines: [[[1,2,3], [4,5,6], [7,8,9]]] }];
+ const lines = pmiLines(annotations);
+ assert.deepEqual(lines[0].points, [1,2,3,4,5,6,7,8,9]);
+ assert.equal(lines[0].pickable, false);
+ assert.equal(lines[0].includeInFit, true);
+ assert.equal(lines[0].depthMode, 'always-on-top');
+ const group = pmiGroup(annotations);
+ const geometry = (group.children[0] as import('three').LineSegments).geometry;
+ assert.deepEqual([...geometry.getAttribute('position').array], [1,2,3,4,5,6,4,5,6,7,8,9]);
+ assert.equal((group.children[0] as import('three').LineSegments).material instanceof Object, true);
+ disposeConceptWireframe(group);
+ assert.equal(group.children.length, 0);
+ assert.deepEqual(annotations[0].lines[0][0], [1,2,3]);
+});
diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.md
index de5b208d..1e509f3a 100644
--- a/docs/public/firmament/step-import.md
+++ b/docs/public/firmament/step-import.md
@@ -2,6 +2,53 @@
Use [surface and trim inspection](surface-inspection.md) in Cadmata or Helios to compare filled geometry, BRep wire, translucent overlays and isolated source faces without changing the camera.
+Direct STEP inspection is available through the native CLI/Cadmata workflows.
+Helios also provides **Import STEP** for the bounded canonical `InlineStep` part
+workflow described below. It retains the input as an immutable text asset and
+creates a Firmament annotation layer. This is not arbitrary vendor STEP or
+assembly import: the existing canonical-input and importer checks still apply.
+
+In Helios, select an imported planar face to **Add datum**, or a cylindrical face
+to **Add diameter**. Diameter authoring shows the measured value separately from
+the requirement and requires explicit upper/lower allowances in millimetres.
+Compilation checks the actual surface type and exports real AP242 geometric face
+associations. Recognition labels are optional; direct `part.face("#191")` targets
+use importer provenance, not STEP line order. Annotation changes do not edit the
+imported geometry.
+
+**Save workspace** downloads a `.helios.zip` containing the original STEP text
+and Firmament source; **Open file** reopens it. Local checkpoints retain both too.
+Cloud single-document saves cannot store these workspaces and refuse rather than
+omit the asset. Reopening an already annotated STEP as a new `InlineStep` is
+currently rejected explicitly: import of its existing semantic annotation layer
+is not qualified. Reopen the saved workspace to continue editing annotations.
+
+The browser SDK accepts `.step`/`.stp` text assets in `projectDocuments`:
+
+```js
+const source = 'Model Imported { units: mm InlineStep part { path: "body.step" } }';
+const result = await cad.compile(source, {
+ sourceName: 'part.firmament',
+ projectDocuments: { 'body.step': stepText },
+});
+```
+
+Paths resolve relative to the source document inside the explicit snapshot;
+missing assets never fall through to native disk. The admitted source text,
+SHA-256 and topology map remain bound to that compilation. Imported face picks
+report `ImportedStable`, the source selector, surface kind and measured cylinder
+diameter; these do not imply a native editable feature history.
+
+GLB part export projects supported datum/diameter PMI into separate font-outline
+and leader line primitives plus structured `asset.extras.pmi` records
+(`aetheris/pmi-display/1`, millimetres). Body vertex/index buffers are preserved.
+Callouts are static XY-plane outlines; the viewport legend remains readable when
+the geometry text is edge-on. These are presentation assets, not AP242 semantics
+or manufacturing approval.
+Unsupported callout kinds/associations fail annotated GLB export explicitly;
+an unavailable viewport callout is reported as a warning while STEP remains
+authoritative. USDA, STL and OBJ do not carry this annotation layer.
+
Use `aetheris analyze part.step --json` to inspect STEP topology, analytic surface families, bounds, manifold assessment, and semantic PMI. When a part is easiest to understand by its manufacturing section, inspect it first with `aetheris analyze section part.step --xy|--xz|--yz --offset value --json`; use `--origin x,y,z --normal x,y,z` for an arbitrary construction plane and `--out section.svg` for deterministic visual evidence. This section-first path preserves analytic line/arc trims and reports closed-loop nesting instead of asking a tessellated view to carry design intent. Use `aetheris sheetmetal recognize` for bounded Sheet Metal recognition rather than treating generic topology analysis as manufacturing intent.
`analyze --json` also reports `splineRecovery`: counts of analytic, exact spline, recovered spline, and unsupported edge/face geometry; the worst measured recovery deviation; and the requested engineering tolerance. The default `ImportPolicy.RecoveryToleranceMillimetres` is 0.1 mm after STEP unit normalization. Rational curves and surfaces are recognized as analytic geometry where qualified; otherwise the importer attempts bounded generic spline recovery and records provenance on recovered geometry. The maximum deviation is sampled evidence.
diff --git a/docs/release/IMPORTED-PART-PMI-2026-10-20.md b/docs/release/IMPORTED-PART-PMI-2026-10-20.md
new file mode 100644
index 00000000..2b64379b
--- /dev/null
+++ b/docs/release/IMPORTED-PART-PMI-2026-10-20.md
@@ -0,0 +1,149 @@
+# Imported Part + PMI — implementation and qualification
+
+**Success for the bounded canonical single-part workflow.** Full qualification
+passed; unsupported import/annotation families remain explicit stops below.
+
+## Scope
+
+Implements the bounded follow-up to the Helios STEP/PMI human-workflow audit.
+The original observations remain in the companion Helios repository's
+`docs/release/HUMAN-WORKFLOW-STEP-PMI-2026-10-20.md`.
+
+This is canonical single-part `InlineStep` annotation, not general vendor STEP,
+assembly import, geometry healing, arbitrary GD&T authoring or manufacturing
+approval. Imported BRep and its original text asset remain separate from the
+editable Firmament annotation layer.
+
+## Repairs and ownership
+
+- Imported PMI now carries source STEP entity -> imported BRep face -> exported
+ STEP entity associations. It no longer stores a resolved target only in prose.
+ The existing importer owns provenance; the existing exporter owns emitted IDs.
+- Imported topology maps use `FaceGeometryBinding.SourceStepEntityId`, including
+ when entity records occur in a different textual order. Face ordinals are not
+ guessed from a regular expression over file lines.
+- The existing parser/compiler accepts explicit project text resources.
+ `.step`/`.stp` assets resolve relative to the source document, never falling
+ through to disk when a snapshot was supplied. The admitted text and its UTF-8
+ SHA-256 are retained in the `InlineStep` record; lowering does not reopen it.
+ The retained text is excluded from diagnostic JSON serialization.
+- Language analysis receives the same snapshot. Assembly dependency documents
+ retain analysis through their project root, so a part cannot lose access to
+ included Templates while an imported standalone part gains asset resolution.
+- Imported face picks expose `ImportedStable`, source entity selector, surface
+ family and measured cylinder diameter. Datum/diameter export checks the actual
+ plane/cylinder support. A requirement is distinct from a measured nominal.
+- Helios adds Import STEP, face-driven Add datum/Add diameter, explicit asymmetric
+ allowance inputs, linked source nodes, read-only asset/hash/qualification
+ inspection, and portable `.helios.zip` save/reopen. Existing checkpoints retain
+ text assets in the same project snapshot; no second history store was added.
+- Shared AP242 readback projects supported PMI into separate annotation curves.
+ WebGPU and WebGL use shared Telos adapters; GLB appends separate line primitives
+ and `asset.extras.pmi` metadata with `aetheris/pmi-display/1`, millimetres and
+ target STEP entity references. The engineering body's buffers are unchanged.
+- Callouts use the existing font reader's raw contours. Reusing engineering text's
+ glyph-region Boolean normalization initially stalled a browser diameter edit;
+ presentation no longer performs that unnecessary construction. CAD text keeps
+ its existing material normalization path.
+- Finite annotation lines participate in whole-model framing. Reference grids
+ do not. Toolbar wrapping prevents narrow viewports from overlaying controls.
+ The graph counts authoring steps rather than calling PMI a physical part.
+- Worker failure is independent of pending work, preserving recovery controls.
+ Input classification rejects unsupported root files before creating a project.
+ Local archive paths and import sizes are bounded.
+
+## Real human-facing witnesses
+
+Used the real rebuilt browser SDK and current Helios, ordinary native file picker,
+viewport face picking, compiler edit transactions, actual downloads and reopen.
+The browser extension's upload API required file-URL permission; no permissions
+were changed. Native picker use is harness fallback, not a product capability.
+
+### Through-hole control
+
+Input: `testdata/firmament/inline-step/canonical-through-hole.step`.
+Picked planar face #102 for datum A and cylindrical face #191 for Bore.
+Authored Ø2 mm with explicit +0.1/-0.05 mm allowances, as projection-test values.
+These allowances are not inferred process capability or production approval.
+
+Saved a portable workspace, reloaded the app and reopened that downloaded file.
+Both requirements and the original asset survived. Final reopen built in about
+1.12 s; STEP + GLB export took about 0.70 s in the observed development runtime.
+These are smoke timings, not a controlled benchmark.
+
+Independent CLI inspection of the actual downloaded STEP finds datum and diameter
+face associations, nominal 2 mm and both exact allowances. All **154** baseline
+entity records remain identical. Analyzer summary, face, edge and vertex records
+are identical. The retained asset SHA-256 equals the original fixture's hash.
+
+Opened the actual downloaded GLB in a separate viewer using Three's GLTFLoader,
+without Firmament compilation. It decodes three meshes (one body, two callouts),
+two structured PMI records and readable datum/diameter text with leader geometry.
+The automated export regression additionally compares the body's binary payload
+before/after annotation and requires a byte-identical prefix.
+
+### Original L-bracket motivating input
+
+Input: `fixtures/Compatibility/Firmasm/LegacyAssembly/examples/occt-l-bracket/_part_003_l_bracket.step`.
+The real UI imported the bracket, picked planar #311 and cylindrical #569,
+created datum A and MountingBore Ø10 +0.1/-0.05 mm, then saved and exported.
+Observed import about 2.64 s; the final annotation build about 3.01 s and export
+about 0.92 s. All **550** baseline STEP entity records remain identical in the
+downloaded annotated STEP. Both annotations have real face associations.
+
+Both historical inputs currently carry the importer's **Degraded** geometry
+qualification, visibly retained in the inspector. Successful annotation and
+unchanged geometry do not upgrade that assessment. This pass performs no healing.
+
+## Qualification
+
+- Focused imported topology/PMI/resource/export, text-profile and cross-file
+ composition analysis: **85 passed**.
+- Core fast lane: **1,087 passed**.
+- Browser SDK transport/selection tests: **18 passed**.
+- Shared Telos tests: **16 passed**.
+- Helios tests: **126 passed**; development bundle/typecheck passed.
+- Full solution: **5,736 passed across 20 projects; zero failed or skipped**.
+ Final serial run: `artifacts/local/imported-pmi-final-full-tests.log`.
+
+Commands use Release, `-m:1 -nr:false -p:UseSharedCompilation=false` for builds,
+and `RunConfiguration.MaxCpuCount=1` for the full solution tests. Earlier runs
+found and repaired a stale one-mesh export assertion, an Assembly analysis
+regression and a wall-clock-sensitive synthetic refinement-warning test.
+The latter now starts from deterministic complete tessellation before injecting
+its warning, instead of accidentally testing a five-second partial-display stop.
+
+Raw ignored evidence: `artifacts/local/imported-pmi-implementation/`, including
+actual workspace/export archives, source/assets, CLI analyses, parity summaries,
+`independent-glb-view.jpg` and `bracket-workspace.jpg`. The primary bracket's
+workspace and exported STEP have the same basename, so they are inspected in
+separate `bracket/workspace/` and `bracket/export/` directories.
+
+## Boundaries and next work
+
+- Existing semantic PMI in a newly imported STEP is explicitly rejected rather
+ than stripped. Reopen its original workspace to continue. A later imported
+ annotation-layer adapter must preserve existing requirements and associations.
+- Arbitrary vendor/assembly import remains behind the existing canonical input
+ boundary. This work does not certify kernel interoperability beyond that scope.
+- The first purpose-facing authoring form covers planar datum and cylindrical
+ diameter. Existing graph/source transactions edit created records; complete
+ GD&T, distance, angular and coordinate-dimension authoring are future slices.
+- GLB callouts are static XY-plane outline/leader geometry, not camera-facing
+ billboards or a production drawing layout. The viewport legend remains readable
+ when a static label is edge-on. AP242 remains semantic engineering authority.
+ This metadata is not a standardized glTF semantic PMI extension.
+- An unsupported preview projection warns without rejecting admitted geometry;
+ annotated GLB export fails explicitly. USDA/STL/OBJ do not carry PMI.
+- Local portable workspaces and checkpoints retain assets. Cloud's single-source
+ save contract explicitly refuses multi-file workspaces.
+
+## Code-quality review
+
+Reused parser, binder, imported topology provenance, AP242 writer/inspector,
+language edits, project snapshots, checkpoints and Telos. No parallel importer,
+frontend validator, new parser route, rewrite pass, global asset state or second
+field schema was introduced. The obsolete regex face-order inference was removed.
+Geometry tests require source/association/geometry evidence, not message strings
+alone. Public import/export documentation and SDK guidance describe the admitted
+scope and remaining stops.
diff --git a/fixtures/Regression/ImportedPartPmi/annotated-part.firmament b/fixtures/Regression/ImportedPartPmi/annotated-part.firmament
new file mode 100644
index 00000000..1fa35b5f
--- /dev/null
+++ b/fixtures/Regression/ImportedPartPmi/annotated-part.firmament
@@ -0,0 +1,12 @@
+Model ImportedPart {
+ units: mm
+ InlineStep part { path: "../../../testdata/firmament/inline-step/canonical-through-hole.step" }
+ Pmi {
+ Datum A { target: part.face("#51") }
+ HoleDiameter Bore {
+ target: part.face("#191")
+ value: 2mm
+ tolerance: PlusMinus(0.1mm, 0.05mm)
+ }
+ }
+}