Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

step assembly import fix.

Yuechen Lib8d72639c817
diff --git a/Aetheris.CLI.Tests/AssemblyM0CliTests.cs b/Aetheris.CLI.Tests/AssemblyM0CliTests.cs
index 5ea1ea75..071f8be2 100644
--- a/Aetheris.CLI.Tests/AssemblyM0CliTests.cs
+++ b/Aetheris.CLI.Tests/AssemblyM0CliTests.cs
@@ -4,6 +4,24 @@ namespace Aetheris.CLI.Tests;
public sealed class AssemblyM0CliTests
{
+ [Fact]
+ public void AnalyzeAssembly_ReportsSourceHierarchyWithoutWritingPackage()
+ {
+ var source = Path.Combine(FindRepoRoot(), "testdata", "step242", "OCCT", "as1.step");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+
+ var exit = Aetheris.CLI.CliRunner.Run(["analyze", "assembly", source, "--json"], stdout, stderr);
+
+ Assert.Equal(0, exit);
+ using var json = JsonDocument.Parse(stdout.ToString());
+ Assert.Equal("SourceAssembly", json.RootElement.GetProperty("provenance").GetString());
+ Assert.Equal(5, json.RootElement.GetProperty("definitionCount").GetInt32());
+ Assert.Equal(27, json.RootElement.GetProperty("occurrenceCount").GetInt32());
+ Assert.NotEqual(JsonValueKind.Null, json.RootElement.GetProperty("assemblyBoundingBox").ValueKind);
+ Assert.Equal(27, json.RootElement.GetProperty("occurrences").GetArrayLength());
+ Assert.Empty(stderr.ToString());
+ }
+
[Fact]
public void AsmInspect_EmitsMachineReadableAssemblyIr()
{
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 4f4be9b4..c2dd10a5 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -147,6 +147,7 @@ public static class CliRunner
private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--approximate --resolution <N>] [--json]";
private const string AnalyzeCompareUsage = "Usage: aetheris analyze compare <reference.step> <candidate.step> [--approximate-volume --resolution <N>] [--json]";
private const string AnalyzeCompoundUsage = "Usage: aetheris analyze compound <file.step> [--json]";
+ private const string AnalyzeAssemblyUsage = "Usage: aetheris analyze assembly <file.step> [--json]";
private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";
private const string VerifyUsage = "Usage: aetheris verify <file.firmament|file.step> [--expected-volume <value>] [--cad-assistant] [--cad-assistant-path <path>] [--timeout <seconds>] [--evidence-dir <path>] [--require-external] [--json]";
private const string InspectUsage = "Usage: aetheris inspect <file.firmament|file.step> [--json]";
@@ -2872,6 +2873,7 @@ Model CanonicalPanel {
stderr.WriteLine($" or: {AnalyzeVolumeUsage[7..]}");
stderr.WriteLine($" or: {AnalyzeCompareUsage[7..]}");
stderr.WriteLine($" or: {AnalyzeCompoundUsage[7..]}");
+ stderr.WriteLine($" or: {AnalyzeAssemblyUsage[7..]}");
stderr.WriteLine("Run 'aetheris analyze --help' for examples.");
return 1;
}
@@ -2900,6 +2902,10 @@ Model CanonicalPanel {
{
return RunAnalyzeCompound(args.Skip(1).ToArray(), stdout, stderr);
}
+ if (string.Equals(args[0], "assembly", StringComparison.Ordinal))
+ {
+ return RunAnalyzeAssembly(args.Skip(1).ToArray(), stdout, stderr);
+ }
if (string.Equals(args[0], "compare", StringComparison.Ordinal))
{
return RunAnalyzeCompare(args.Skip(1).ToArray(), stdout, stderr);
@@ -4724,6 +4730,69 @@ Model CanonicalPanel {
return 1;
}
+ private static int RunAnalyzeAssembly(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || IsHelpFlag(args[0])) { (args.Length == 0 ? stderr : stdout).WriteLine(AnalyzeAssemblyUsage); return args.Length == 0 ? 1 : 0; }
+ if (args.Length > 2 || args.Length == 2 && args[1] != "--json" || !File.Exists(args[0]))
+ {
+ stderr.WriteLine(AnalyzeAssemblyUsage);
+ return 1;
+ }
+ var imported = Step242AssemblyImporter.Import(File.ReadAllText(args[0]));
+ if (!imported.IsSuccess)
+ {
+ foreach (var diagnostic in imported.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}");
+ return 1;
+ }
+ var structure = imported.Value;
+ var definitions = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
+ var occurrences = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
+ var world = new Dictionary<string, Transform3D>(StringComparer.Ordinal);
+ var depths = new Dictionary<string, int>(StringComparer.Ordinal);
+ Transform3D World(Step242ImportedProductOccurrence occurrence)
+ {
+ if (world.TryGetValue(occurrence.StableId, out var cached)) return cached;
+ var local = Transform3D.FromRowMajor(occurrence.LocalTransform);
+ return world[occurrence.StableId] = occurrence.ParentStableId is null ? local : local * World(occurrences[occurrence.ParentStableId]);
+ }
+ int Depth(Step242ImportedProductOccurrence occurrence)
+ {
+ if (depths.TryGetValue(occurrence.StableId, out var cached)) return cached;
+ return depths[occurrence.StableId] = occurrence.ParentStableId is null ? 1 : 1 + Depth(occurrences[occurrence.ParentStableId]);
+ }
+ var points = new List<Point3D>();
+ foreach (var occurrence in structure.Occurrences)
+ {
+ var body = definitions[occurrence.DefinitionStableId].Geometry;
+ if (body is null) continue;
+ var placement = World(occurrence);
+ foreach (var vertex in body.Topology.Vertices)
+ if (body.TryGetVertexPoint(vertex.Id, out var point)) points.Add(placement.Apply(point));
+ }
+ var assemblyName = definitions.GetValueOrDefault(structure.RootDefinitionStableId)?.Name ?? "RecoveredMultiBodyAssembly";
+ var report = new {
+ command = "analyze assembly", success = true, assemblyName, provenance = structure.Provenance,
+ definitionCount = structure.Definitions.Count(item => item.Geometry is not null),
+ occurrenceCount = structure.Occurrences.Count,
+ subassemblyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is null),
+ bodyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is not null),
+ repeatedInstanceCount = structure.Occurrences.Where(item => definitions[item.DefinitionStableId].Geometry is not null)
+ .GroupBy(item => item.DefinitionStableId).Sum(group => Math.Max(0, group.Count() - 1)),
+ maxHierarchyDepth = structure.Occurrences.Count == 0 ? 0 : structure.Occurrences.Max(Depth),
+ assemblyBoundingBox = points.Count == 0 ? null : new {
+ minimum = new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) },
+ maximum = new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) }
+ },
+ performance = structure.Performance,
+ definitions = structure.Definitions.Select(item => new { item.StableId, item.Name, hasGeometry = item.Geometry is not null, item.ProductDefinitionEntityId }).ToArray(),
+ occurrences = structure.Occurrences.Select(item => new { item.StableId, item.Name, item.ParentStableId, item.DefinitionStableId,
+ item.LocalTransform, worldTransform = World(item).ToRowMajor(), item.StepEntityId }).ToArray()
+ };
+ stdout.WriteLine(args.Length == 2 ? JsonSerializer.Serialize(report, JsonOptions)
+ : $"Assembly '{assemblyName}': {report.definitionCount} definitions, {report.occurrenceCount} occurrences, {report.subassemblyCount} subassemblies, {report.repeatedInstanceCount} repeated instances; bbox {string.Join(",", report.assemblyBoundingBox?.minimum ?? [])} to {string.Join(",", report.assemblyBoundingBox?.maximum ?? [])}.");
+ return 0;
+ }
+
private static int RunAsmImportStep(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length == 0 || IsHelpFlag(args[0])) { (args.Length == 0 ? stderr : stdout).WriteLine(AsmImportStepUsage); return args.Length == 0 ? 1 : 0; }
@@ -4732,8 +4801,53 @@ Model CanonicalPanel {
if (output is null || !File.Exists(args[0])) { stderr.WriteLine(AsmImportStepUsage); return 1; }
var result = Step242FirmasmPackageImporter.Import(args[0], output);
if (!result.IsSuccess) { foreach (var diagnostic in result.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}"); return 1; }
- var report = new { success = true, result.Value.FirmasmPath, result.Value.ManifestPath, definitionCount = result.Value.Components.Count, occurrenceCount = result.Value.ProductStructure.Occurrences.Count, result.Value.FirmasmSha256 };
- stdout.WriteLine(json ? JsonSerializer.Serialize(report, JsonOptions) : $"Imported AP242 assembly to {result.Value.FirmasmPath} ({result.Value.Components.Count} definitions, {result.Value.ProductStructure.Occurrences.Count} occurrences).");
+ var structure = result.Value.ProductStructure;
+ var definitions = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
+ var occurrences = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
+ var world = new Dictionary<string, Transform3D>(StringComparer.Ordinal);
+ var depths = new Dictionary<string, int>(StringComparer.Ordinal);
+ Transform3D World(Step242ImportedProductOccurrence occurrence)
+ {
+ if (world.TryGetValue(occurrence.StableId, out var cached)) return cached;
+ var local = Transform3D.FromRowMajor(occurrence.LocalTransform);
+ return world[occurrence.StableId] = occurrence.ParentStableId is null ? local : local * World(occurrences[occurrence.ParentStableId]);
+ }
+ int Depth(Step242ImportedProductOccurrence occurrence)
+ {
+ if (depths.TryGetValue(occurrence.StableId, out var cached)) return cached;
+ return depths[occurrence.StableId] = occurrence.ParentStableId is null ? 1 : 1 + Depth(occurrences[occurrence.ParentStableId]);
+ }
+ var points = new List<Point3D>();
+ foreach (var occurrence in structure.Occurrences)
+ {
+ var body = definitions[occurrence.DefinitionStableId].Geometry;
+ if (body is null) continue;
+ var placement = World(occurrence);
+ foreach (var vertex in body.Topology.Vertices)
+ if (body.TryGetVertexPoint(vertex.Id, out var point)) points.Add(placement.Apply(point));
+ }
+ var assemblyName = definitions.GetValueOrDefault(structure.RootDefinitionStableId)?.Name ?? "ImportedAssembly";
+ var report = new {
+ success = true, result.Value.FirmasmPath, result.Value.ManifestPath, assemblyName,
+ provenance = structure.Provenance,
+ definitionCount = structure.Definitions.Count(item => item.Geometry is not null),
+ occurrenceCount = structure.Occurrences.Count,
+ subassemblyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is null),
+ bodyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is not null),
+ repeatedInstanceCount = structure.Occurrences.Where(item => definitions[item.DefinitionStableId].Geometry is not null)
+ .GroupBy(item => item.DefinitionStableId).Sum(group => Math.Max(0, group.Count() - 1)),
+ maxHierarchyDepth = structure.Occurrences.Count == 0 ? 0 : structure.Occurrences.Max(Depth),
+ assemblyBoundingBox = points.Count == 0 ? null : new {
+ minimum = new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) },
+ maximum = new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) }
+ },
+ performance = structure.Performance,
+ definitions = structure.Definitions.Select(item => new { item.StableId, item.Name, hasGeometry = item.Geometry is not null, item.ProductDefinitionEntityId }).ToArray(),
+ occurrences = structure.Occurrences.Select(item => new { item.StableId, item.Name, item.ParentStableId, item.DefinitionStableId,
+ item.LocalTransform, worldTransform = World(item).ToRowMajor(), item.StepEntityId }).ToArray(),
+ result.Value.FirmasmSha256
+ };
+ stdout.WriteLine(json ? JsonSerializer.Serialize(report, JsonOptions) : $"Imported AP242 assembly '{assemblyName}' to {result.Value.FirmasmPath} ({report.definitionCount} definitions, {report.occurrenceCount} occurrences, {report.subassemblyCount} subassemblies; bbox {string.Join(",", report.assemblyBoundingBox?.minimum ?? [])} to {string.Join(",", report.assemblyBoundingBox?.maximum ?? [])}).");
return 0;
}
@@ -5013,7 +5127,8 @@ Model CanonicalPanel {
stdout.WriteLine(" - Use 'aetheris analyze map --help' for orthographic map options.");
stdout.WriteLine(" - Use 'aetheris analyze section --help' for section options.");
stdout.WriteLine(" - Use 'aetheris analyze volume --help' for volume options.");
- stdout.WriteLine(" - Summary mode remains single-part; use 'analyze compound' to inspect every multi-root solid without assigning product semantics.");
+ stdout.WriteLine(" - Summary mode remains single-part; use 'analyze assembly' for product structure, transforms, and world bounds.");
+ stdout.WriteLine(" - Use 'analyze compound' to inspect multi-root solids without assigning product semantics.");
stdout.WriteLine();
stdout.WriteLine("Examples:");
stdout.WriteLine(" aetheris analyze part.step");
@@ -5023,6 +5138,7 @@ Model CanonicalPanel {
stdout.WriteLine(" aetheris analyze map part.step --right --rows 20 --cols 30 --json");
stdout.WriteLine(" aetheris analyze section part.step --yz --offset 1.25 --json");
stdout.WriteLine(" aetheris analyze compound multi-solid.step --json");
+ stdout.WriteLine(" aetheris analyze assembly machine.step --json");
}
private static void WriteAnalyzeMapHelp(TextWriter stdout)
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs
index ca91159e..cb629666 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs
@@ -1,10 +1,83 @@
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Step242;
+using System.Text.RegularExpressions;
namespace Aetheris.Kernel.Core.Tests.Step242;
public sealed class Step242AssemblyProductStructureTests
{
+ [Fact]
+ public void ProductWithTwoRigidRoots_PromotesBodiesUnderEachRepeatedOccurrence()
+ {
+ var body = BrepPrimitives.CreateBox(2, 3, 4).Value;
+ double[] identity = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
+ double[] moved = [1,0,0,0, 0,1,0,0, 0,0,1,0, 20,0,0,1];
+ var exported = Step242AssemblyExporter.Export(new("Root", "root", [new("multi", "Multi", body)], [
+ new("root", "Root", null, null, identity),
+ new("first", "First", "root", "multi", identity),
+ new("second", "Second", "root", "multi", moved)
+ ])).Value;
+ var rigidRoot = Regex.Match(exported, @"#(?<id>\d+)=MANIFOLD_SOLID_BREP\('[^']*',#(?<shell>\d+)\);");
+ Assert.True(rigidRoot.Success);
+ var maxId = Regex.Matches(exported, @"#(?<id>\d+)=").Select(match => int.Parse(match.Groups["id"].Value)).Max();
+ var representation = Regex.Match(exported, $@"#\d+=SHAPE_REPRESENTATION\([^\r\n]*\(#{rigidRoot.Groups["id"].Value}\)[^\r\n]*;");
+ Assert.True(representation.Success);
+ exported = exported.Replace(representation.Value,
+ representation.Value.Replace($"(#{rigidRoot.Groups["id"].Value})", $"(#{rigidRoot.Groups["id"].Value},#{maxId + 1})", StringComparison.Ordinal), StringComparison.Ordinal);
+ exported = exported.Insert(exported.LastIndexOf("ENDSEC;", StringComparison.Ordinal),
+ $"#{maxId + 1}=MANIFOLD_SOLID_BREP('Additional',#{rigidRoot.Groups["shell"].Value});\r\n");
+
+ var imported = Step242AssemblyImporter.Import(exported);
+
+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics.Select(item => item.Message)));
+ Assert.Equal(2, imported.Value.Definitions.Count(item => item.Geometry is not null));
+ Assert.Equal(4, imported.Value.Occurrences.Count(item => item.DefinitionStableId.StartsWith("multi/body:", StringComparison.Ordinal)));
+ Assert.Equal(2, imported.Value.Occurrences.Count(item => item.DefinitionStableId == "multi"));
+ Assert.All(imported.Value.Occurrences.Where(item => item.DefinitionStableId.StartsWith("multi/body:", StringComparison.Ordinal)),
+ occurrence => Assert.Contains(imported.Value.Occurrences, parent => parent.StableId == occurrence.ParentStableId));
+ Assert.Equal(2, imported.Value.Occurrences.Where(item => item.DefinitionStableId.StartsWith("multi/body:", StringComparison.Ordinal))
+ .Select(item => item.DefinitionStableId).Distinct().Count());
+ }
+
+ [Fact]
+ public void FlatMultipleRigidRoots_RecoversSyntheticAssemblyWithoutUnion()
+ {
+ var step = Step242Exporter.ExportBody(BrepPrimitives.CreateBox(2, 3, 4).Value).Value;
+ var root = Regex.Match(step, @"MANIFOLD_SOLID_BREP\('[^']*',#(?<shell>\d+)\)");
+ Assert.True(root.Success);
+ var maxId = Regex.Matches(step, @"#(?<id>\d+)=").Select(match => int.Parse(match.Groups["id"].Value)).Max();
+ var second = $"#{maxId + 1}=MANIFOLD_SOLID_BREP('Second',#{root.Groups["shell"].Value});\r\n";
+ step = step.Insert(step.LastIndexOf("ENDSEC;", StringComparison.Ordinal), second);
+
+ var imported = Step242AssemblyImporter.Import(step);
+
+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics.Select(item => item.Message)));
+ Assert.Equal("RecoveredMultiBodyAssembly", imported.Value.Provenance);
+ Assert.Equal(2, imported.Value.Definitions.Count);
+ Assert.Equal(2, imported.Value.Occurrences.Count);
+ Assert.Contains(imported.Value.Definitions, definition => definition.Name == "Second");
+ Assert.All(imported.Value.Definitions, definition => Assert.NotNull(definition.Geometry));
+ Assert.All(imported.Value.Definitions, definition => Assert.Single(definition.Geometry!.Topology.Bodies));
+ Assert.False(Step242Importer.ImportBody(step).IsSuccess);
+ }
+
+ [Fact]
+ public void MissingOccurrenceTransform_FailsWithIdentifiedOccurrence()
+ {
+ var body = BrepPrimitives.CreateBox(1, 1, 1).Value;
+ double[] identity = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
+ var exported = Step242AssemblyExporter.Export(new("Root", "root", [new("part", "Part", body)], [
+ new("root", "Root", null, null, identity), new("child", "Child", "root", "part", identity)
+ ])).Value;
+ var broken = exported.Replace("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(", "UNSUPPORTED_CONTEXT_SHAPE(", StringComparison.Ordinal);
+
+ var imported = Step242AssemblyImporter.Import(broken);
+
+ Assert.False(imported.IsSuccess);
+ Assert.Contains(imported.Diagnostics, diagnostic => diagnostic.Source == "Importer.Assembly.MissingOccurrenceTransform"
+ && diagnostic.Message.Contains("child", StringComparison.Ordinal));
+ }
+
[Fact]
public void RepeatedDefinition_RoundTripsOccurrencesTransformsAndExactGeometry()
{
diff --git a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs
index e689b30e..e2bb9272 100644
--- a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs
@@ -1,10 +1,12 @@
using System.Globalization;
+using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Import;
using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
namespace Aetheris.Kernel.Core.Step242;
@@ -44,7 +46,9 @@ public sealed record Step242ImportedProductOccurrence(
public sealed record Step242ProductStructure(
string RootDefinitionStableId,
IReadOnlyList<Step242ImportedProductDefinition> Definitions,
- IReadOnlyList<Step242ImportedProductOccurrence> Occurrences);
+ IReadOnlyList<Step242ImportedProductOccurrence> Occurrences,
+ string Provenance = "SourceAssembly",
+ IReadOnlyDictionary<string, double>? Performance = null);
/// <summary>Bounded AP242 product-structure lowering: product definitions, NAUO occurrences, rigid transforms, and shared shape representations.</summary>
public static class Step242AssemblyExporter
@@ -192,8 +196,10 @@ public static class Step242AssemblyImporter
{
public static KernelResult<Step242ProductStructure> Import(string stepText, ImportPolicy? policy = null)
{
+ var started = Stopwatch.GetTimestamp();
var parsed = Step242SubsetParser.Parse(stepText);
if (!parsed.IsSuccess) return KernelResult<Step242ProductStructure>.Failure(parsed.Diagnostics);
+ var parsedAt = Stopwatch.GetTimestamp();
var document = parsed.Value;
if (policy is not null)
{
@@ -204,6 +210,31 @@ public static class Step242AssemblyImporter
policy.RecoveryToleranceMillimetres);
document.AllowBoundedNearCoincidentInnerLoop = policy.AllowBoundedNearCoincidentInnerLoop;
}
+ if (!document.Entities.Any(entity => entity.Name == "NEXT_ASSEMBLY_USAGE_OCCURRENCE")
+ && document.Entities.Count(entity => entity.Name == "PRODUCT_DEFINITION") <= 1)
+ {
+ var roots = Step242RigidRootClassifier.Classify(document).RigidRoots.OrderBy(entity => entity.Id).ToArray();
+ if (roots.Length > 1)
+ {
+ var flatDefinitions = new List<Step242ImportedProductDefinition>();
+ var flatOccurrences = new List<Step242ImportedProductOccurrence>();
+ foreach (var (root, index) in roots.Select((root, index) => (root, index)))
+ {
+ var imported = Step242Importer.ImportExactBrepCore(document, root.Id);
+ if (!imported.IsSuccess)
+ return KernelResult<Step242ProductStructure>.Failure(imported.Diagnostics.Prepend(new(KernelDiagnosticCode.ValidationFailed,
+ KernelDiagnosticSeverity.Error, $"Multibody component at STEP #{root.Id} could not import.", "Importer.Assembly.MultiBodyComponent")).ToArray());
+ var stableId = $"step-rigid-root:{root.Id}";
+ var sourceName = Text(root, 0);
+ var name = string.IsNullOrWhiteSpace(sourceName) ? $"Body {index + 1}" : sourceName;
+ flatDefinitions.Add(new(stableId, name, root.Id, null, root.Id, imported.Value, null));
+ flatOccurrences.Add(new($"step-occurrence:{root.Id}", name, null, stableId, Identity(), root.Id));
+ }
+ var importedAt = Stopwatch.GetTimestamp();
+ return KernelResult<Step242ProductStructure>.Success(new("aetheris:recovered-multibody-assembly", flatDefinitions,
+ flatOccurrences, "RecoveredMultiBodyAssembly", Timing(started, parsedAt, importedAt, importedAt)));
+ }
+ }
var products = document.Entities.Where(entity => entity.Name == "PRODUCT").ToDictionary(entity => entity.Id);
var formations = document.Entities.Where(entity => entity.Name == "PRODUCT_DEFINITION_FORMATION").ToDictionary(entity => entity.Id);
var definitionsByEntity = document.Entities.Where(entity => entity.Name == "PRODUCT_DEFINITION").ToDictionary(entity => entity.Id);
@@ -217,6 +248,7 @@ public static class Step242AssemblyImporter
var importedDefinitions = new List<Step242ImportedProductDefinition>();
var stableByPd = new Dictionary<int, string>();
+ var splitDefinitionsByPd = new Dictionary<int, Step242ImportedProductDefinition[]>();
foreach (var definition in definitionsByEntity.Values.OrderBy(entity => entity.Id))
{
var formationId = Ref(definition, 2); if (formationId is null || !formations.TryGetValue(formationId.Value, out var formation)) continue;
@@ -228,9 +260,29 @@ public static class Step242AssemblyImporter
? repIds.FirstOrDefault(repId => document.TryGetEntity(repId).Value.Arguments.ElementAtOrDefault(1) is Step242ListValue items
&& items.Items.OfType<Step242EntityReference>().Any(item => document.TryGetEntity(item.TargetId).Value.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS")) is var selected && selected != 0 ? selected : repIds.FirstOrDefault()
: null;
- int? rigidRoot = null;
+ int[] rigidRoots = [];
if (representationId is not null && document.TryGetEntity(representationId.Value).Value is { } representation && representation.Arguments.ElementAtOrDefault(1) is Step242ListValue items)
- rigidRoot = items.Items.OfType<Step242EntityReference>().Select(item => item.TargetId).FirstOrDefault(id => document.TryGetEntity(id).Value.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS") is var candidate && candidate != 0 ? candidate : null;
+ rigidRoots = items.Items.OfType<Step242EntityReference>().Select(item => item.TargetId)
+ .Where(id => document.TryGetEntity(id).Value.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS").Distinct().ToArray();
+ if (rigidRoots.Length > 1)
+ {
+ var components = new List<Step242ImportedProductDefinition>();
+ foreach (var (rootId, index) in rigidRoots.Select((rootId, index) => (rootId, index)))
+ {
+ var geometry = Step242Importer.ImportExactBrepCore(document, rootId);
+ if (!geometry.IsSuccess)
+ return KernelResult<Step242ProductStructure>.Failure(geometry.Diagnostics.Prepend(new(KernelDiagnosticCode.ValidationFailed,
+ KernelDiagnosticSeverity.Error, $"Product '{name}' component #{rootId} could not import.", "Importer.Assembly.MultiBodyComponent")).ToArray());
+ var componentName = Text(document.TryGetEntity(rootId).Value, 0);
+ components.Add(new($"{stableId}/body:{rootId}", string.IsNullOrWhiteSpace(componentName) ? $"{name} Body {index + 1}" : componentName,
+ definition.Id, representationId, rootId, geometry.Value, null));
+ }
+ splitDefinitionsByPd[definition.Id] = components.ToArray();
+ importedDefinitions.Add(new(stableId, name, definition.Id, representationId, null, null, null));
+ importedDefinitions.AddRange(components);
+ continue;
+ }
+ int? rigidRoot = rigidRoots.Length == 1 ? rigidRoots[0] : null;
BrepBody? body = null; string? hash = null;
if (rigidRoot is not null)
{
@@ -241,6 +293,7 @@ public static class Step242AssemblyImporter
}
importedDefinitions.Add(new(stableId, name, definition.Id, representationId, rigidRoot, body, hash));
}
+ var geometryAt = Stopwatch.GetTimestamp();
var usages = document.Entities.Where(entity => entity.Name == "NEXT_ASSEMBLY_USAGE_OCCURRENCE").OrderBy(entity => entity.Id).ToArray();
if (usages.Length == 0)
@@ -250,7 +303,8 @@ public static class Step242AssemblyImporter
return KernelResult<Step242ProductStructure>.Failure([new(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, "STEP contains neither an admitted AP242 occurrence hierarchy nor ambiguous multipart multiplicity; retain the ordinary single-part import path.", "Importer.Assembly.ProductStructure")]);
var flat = geometricDefinitions.Select((definition, index) => new Step242ImportedProductOccurrence(
$"normalized-occurrence:{index + 1:D4}", definition.Name, null, definition.StableId, Identity(), definition.RigidRootEntityId ?? definition.ProductDefinitionEntityId)).ToArray();
- return KernelResult<Step242ProductStructure>.Success(new("aetheris:normalized-multipart-assembly", importedDefinitions, flat), [
+ return KernelResult<Step242ProductStructure>.Success(new("aetheris:normalized-multipart-assembly", importedDefinitions, flat,
+ "RecoveredMultiBodyAssembly", Timing(started, parsedAt, geometryAt, Stopwatch.GetTimestamp())), [
new(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Info,
"Incoming STEP provides multiple independent rigid products without trustworthy hierarchy; Aetheris normalized multiplicity to a flat Assembly.", "Importer.Assembly.MultiplicityNormalization")]);
}
@@ -270,12 +324,40 @@ public static class Step242AssemblyImporter
var transform = document.TryGetEntity(transformId.Value).Value;
var placementId = Ref(transform, 3); if (placementId is not null) transformByUsage[usageId] = Placement(document, placementId.Value);
}
+ foreach (var usage in usages)
+ if (!transformByUsage.ContainsKey(usage.Id))
+ return KernelResult<Step242ProductStructure>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ $"Occurrence '{occurrenceStableByUsage[usage.Id]}' (STEP #{usage.Id}) has no supported rigid placement relationship.", "Importer.Assembly.MissingOccurrenceTransform")]);
+ foreach (var (usageId, matrix) in transformByUsage)
+ {
+ try { Transform3D.FromRowMajor(matrix); }
+ catch (ArgumentException exception)
+ {
+ return KernelResult<Step242ProductStructure>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ $"STEP occurrence #{usageId} has unsupported non-rigid placement: {exception.Message}", "Importer.Assembly.NonRigidTransform")]);
+ }
+ }
var childPds = usages.Select(usage => Ref(usage, 4)!.Value).ToHashSet();
var rootPd = usages.Select(usage => Ref(usage, 3)!.Value).First(id => !childPds.Contains(id));
var usagesByParentDefinition = usages.GroupBy(usage => Ref(usage, 3)!.Value).ToDictionary(group => group.Key, group => group.OrderBy(item => item.Id).ToArray());
var occurrences = new List<Step242ImportedProductOccurrence>();
var usedOccurrenceStableIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var usage in usagesByParentDefinition.GetValueOrDefault(rootPd, [])) Expand(usage, null, 0);
+ if (splitDefinitionsByPd.TryGetValue(rootPd, out var rootComponents))
+ foreach (var component in rootComponents)
+ occurrences.Add(new($"root-solid:{component.RigidRootEntityId}", component.Name, null, component.StableId,
+ Identity(), component.RigidRootEntityId!.Value));
+ if (usages.Any(usage => occurrences.All(occurrence => occurrence.StepEntityId != usage.Id)))
+ return KernelResult<Step242ProductStructure>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ "One or more STEP occurrence relationships were not reachable from the root product.", "Importer.Assembly.DisconnectedOccurrences")]);
+ foreach (var occurrence in occurrences)
+ {
+ var definition = importedDefinitions.Single(item => item.StableId == occurrence.DefinitionStableId);
+ if (definition.Geometry is null && occurrences.All(item => item.ParentStableId != occurrence.StableId))
+ return KernelResult<Step242ProductStructure>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ $"STEP occurrence '{occurrence.Name}' (#{occurrence.StepEntityId}) has no imported body and no child occurrences; product definition #{definition.ProductDefinitionEntityId} cannot be represented without dropping a component.",
+ "Importer.Assembly.MissingComponentGeometry")]);
+ }
void Expand(Step242ParsedEntity usage, string? parentStableId, int depth)
{
if (depth > usages.Length) throw new InvalidOperationException("AP242 assembly definition hierarchy is cyclic.");
@@ -285,11 +367,24 @@ public static class Step242AssemblyImporter
var childPd = Ref(usage, 4)!.Value;
occurrences.Add(new(stableId, Text(usage, 1) ?? baseStableId, parentStableId, stableByPd[childPd],
transformByUsage.TryGetValue(usage.Id, out var matrix) ? matrix : Identity(), usage.Id));
+ if (splitDefinitionsByPd.TryGetValue(childPd, out var components))
+ foreach (var component in components)
+ occurrences.Add(new($"{stableId}/solid:{component.RigidRootEntityId}", component.Name, stableId,
+ component.StableId, Identity(), component.RigidRootEntityId!.Value));
foreach (var childUsage in usagesByParentDefinition.GetValueOrDefault(childPd, [])) Expand(childUsage, stableId, depth + 1);
}
- return KernelResult<Step242ProductStructure>.Success(new(stableByPd[rootPd], importedDefinitions, occurrences));
+ return KernelResult<Step242ProductStructure>.Success(new(stableByPd[rootPd], importedDefinitions, occurrences,
+ "SourceAssembly", Timing(started, parsedAt, geometryAt, Stopwatch.GetTimestamp())));
}
+ private static IReadOnlyDictionary<string, double> Timing(long started, long parsedAt, long geometryAt, long completed) =>
+ new Dictionary<string, double>
+ {
+ ["stepParseMilliseconds"] = Stopwatch.GetElapsedTime(started, parsedAt).TotalMilliseconds,
+ ["uniqueDefinitionImportMilliseconds"] = Stopwatch.GetElapsedTime(parsedAt, geometryAt).TotalMilliseconds,
+ ["assemblyGraphMilliseconds"] = Stopwatch.GetElapsedTime(geometryAt, completed).TotalMilliseconds
+ };
+
private static int? Ref(Step242ParsedEntity entity, int index) => entity.Arguments.ElementAtOrDefault(index) is Step242EntityReference reference ? reference.TargetId : null;
private static string? Text(Step242ParsedEntity entity, int index) => entity.Arguments.ElementAtOrDefault(index) is Step242StringValue text ? text.Value : null;
private static bool Has(Step242ParsedEntity entity, string constructor) => Step242SubsetDecoder.TryGetConstructor(entity.Instance, constructor) is not null;
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs
index ca9c1e74..e4fea5b2 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs
@@ -54,7 +54,7 @@ public static class Step242FirmasmPackageImporter
var definitions = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
var occurrences = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
var children = structure.Occurrences.GroupBy(item => item.ParentStableId).ToDictionary(group => group.Key ?? string.Empty, group => group.OrderBy(item => item.StableId, StringComparer.Ordinal).ToArray(), StringComparer.Ordinal);
- var rootName = "ImportedAssembly";
+ var rootName = Identifier(definitions.GetValueOrDefault(structure.RootDefinitionStableId)?.Name ?? "ImportedAssembly");
var builder = new StringBuilder();
builder.AppendLine($"// Imported from {provenance}; occurrence transforms are interchange evidence, not semantic Mates.");
builder.AppendLine("// Multiplicity without trustworthy foreign hierarchy is intentionally normalized to a flat Assembly.");
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index e2bc828f..2558c0bd 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -3,12 +3,43 @@ using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Aetheris.Server.Contracts;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Aetheris.Server.Tests;
public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
+ [Fact]
+ public async Task StepImport_ExportedAssembly_ReturnsCadmataInstanceScene()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+ double[] identity = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
+ double[] moved = [1,0,0,0, 0,1,0,0, 0,0,1,0, 25,0,0,1];
+ var model = new Step242AssemblyExportModel("Two instances", "root", [
+ new("shared", "Shared box", BrepPrimitives.CreateBox(2, 3, 4).Value)
+ ], [
+ new("root", "Two instances", null, null, identity),
+ new("one", "First", "root", "shared", identity),
+ new("two", "Second", "root", "shared", moved)
+ ]);
+ var exported = Step242AssemblyExporter.Export(model);
+ Assert.True(exported.IsSuccess);
+
+ var response = await _client.PostAsJsonAsync($"/api/v1/documents/{document.Data!.DocumentId}/import/step",
+ new StepImportRequestDto(exported.Value, "two.step"));
+ response.EnsureSuccessStatusCode();
+ var imported = await response.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();
+ Assert.True(imported!.Success);
+ var scene = Assert.IsType<AssemblyDisplayPacketDto>(imported.Data!.AssemblyPresentation);
+ Assert.Single(scene.Definitions);
+ Assert.Equal(3, scene.Occurrences.Count);
+ Assert.Equal("shared", scene.Occurrences.Single(item => item.StableId == "two").DefinitionStableId);
+ Assert.Equal(25, scene.Occurrences.Single(item => item.StableId == "two").WorldTransform[12]);
+ Assert.NotEmpty(scene.Definitions[0].FacePatches);
+ }
+
private readonly HttpClient _client;
public KernelApiIntegrationTests(WebApplicationFactory<Program> factory)
diff --git a/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs b/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs
new file mode 100644
index 00000000..44fa9403
--- /dev/null
+++ b/Aetheris.Server.Tests/StepAssemblyDisplayTests.cs
@@ -0,0 +1,41 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Server.Api;
+
+namespace Aetheris.Server.Tests;
+
+public sealed class StepAssemblyDisplayTests
+{
+ [Fact]
+ public void ExportedNestedRepeatedAssembly_BuildsSharedCadmataSceneWithWorldPlacement()
+ {
+ var body = BrepPrimitives.CreateBox(2, 4, 6).Value;
+ double[] identity = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
+ double[] parent = [0,1,0,0, -1,0,0,0, 0,0,1,0, 10,0,0,1];
+ double[] first = [1,0,0,0, 0,1,0,0, 0,0,1,0, 3,0,0,1];
+ double[] second = [1,0,0,0, 0,1,0,0, 0,0,1,0, 8,0,0,1];
+ var source = new Step242AssemblyExportModel("Fixture", "root", [new("part-def", "Shared Part", body)], [
+ new("root", "Fixture", null, null, identity),
+ new("sub", "Rotated subassembly", "root", null, parent),
+ new("first", "First", "sub", "part-def", first),
+ new("second", "Second", "sub", "part-def", second)
+ ]);
+ var step = Step242AssemblyExporter.Export(source);
+ Assert.True(step.IsSuccess);
+ var imported = Step242AssemblyImporter.Import(step.Value);
+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics.Select(item => item.Message)));
+
+ var built = AssemblyDisplayService.TryBuildStep(imported.Value, out var packet, out var error);
+
+ Assert.True(built, error);
+ Assert.NotNull(packet);
+ Assert.Single(packet.Definitions);
+ Assert.Equal(4, packet.Occurrences.Count);
+ Assert.Equal("sub", packet.Occurrences.Single(item => item.StableId == "first").ParentStableId);
+ Assert.Equal("part-def", packet.Occurrences.Single(item => item.StableId == "second").DefinitionStableId);
+ Assert.Equal(10, packet.Occurrences.Single(item => item.StableId == "first").WorldTransform[12], 8);
+ Assert.Equal(3, packet.Occurrences.Single(item => item.StableId == "first").WorldTransform[13], 8);
+ Assert.Equal(8, packet.Occurrences.Single(item => item.StableId == "second").WorldTransform[13], 8);
+ Assert.True(packet.Bounds.Maximum[1] > packet.Bounds.Minimum[1]);
+ }
+}
diff --git a/Aetheris.Server/Api/AssemblyDisplayService.cs b/Aetheris.Server/Api/AssemblyDisplayService.cs
index df06f1b9..cfa63891 100644
--- a/Aetheris.Server/Api/AssemblyDisplayService.cs
+++ b/Aetheris.Server/Api/AssemblyDisplayService.cs
@@ -1,5 +1,7 @@
using System.Diagnostics;
using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Server.Contracts;
@@ -7,6 +9,67 @@ namespace Aetheris.Server.Api;
public static class AssemblyDisplayService
{
+ public static bool TryBuildStep(Step242ProductStructure structure, out AssemblyDisplayPacketDto? packet, out string error)
+ {
+ packet = null; error = string.Empty;
+ var watch = Stopwatch.StartNew();
+ var definitions = new List<AssemblyDisplayDefinitionDto>();
+ foreach (var definition in structure.Definitions.Where(item => item.Geometry is not null).OrderBy(item => item.StableId, StringComparer.Ordinal))
+ {
+ var mesh = BrepDisplayTessellator.TessellateBounded(definition.Geometry!);
+ if (!mesh.IsSuccess)
+ {
+ error = $"STEP definition '{definition.Name}' (#{definition.ProductDefinitionEntityId}) could not be prepared for display: "
+ + string.Join("; ", mesh.Diagnostics.Select(item => item.Message));
+ return false;
+ }
+ definitions.Add(new(definition.StableId, definition.Name, ApiMappings.ToTessellationResponse(mesh.Value).FacePatches));
+ }
+ var byDefinition = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
+ var byOccurrence = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
+ var rootId = "step-root:" + structure.RootDefinitionStableId;
+ var world = new Dictionary<string, Transform3D>(StringComparer.Ordinal);
+ Transform3D World(Step242ImportedProductOccurrence occurrence)
+ {
+ if (world.TryGetValue(occurrence.StableId, out var cached)) return cached;
+ var local = Transform3D.FromRowMajor(occurrence.LocalTransform);
+ return world[occurrence.StableId] = occurrence.ParentStableId is null ? local : local * World(byOccurrence[occurrence.ParentStableId]);
+ }
+ var occurrences = new List<AssemblyDisplayOccurrenceDto>
+ {
+ new(rootId, byDefinition.GetValueOrDefault(structure.RootDefinitionStableId)?.Name ?? "ImportedAssembly", rootId,
+ null, null, "Assembly", Transform3D.Identity.ToRowMajor(), "ImportedOccurrence")
+ };
+ var points = new List<Point3D>();
+ foreach (var occurrence in structure.Occurrences)
+ {
+ if (!byDefinition.TryGetValue(occurrence.DefinitionStableId, out var definition))
+ {
+ error = $"STEP occurrence '{occurrence.Name}' refers to missing definition '{occurrence.DefinitionStableId}'.";
+ return false;
+ }
+ var transform = World(occurrence);
+ occurrences.Add(new(occurrence.StableId, occurrence.Name, occurrence.StableId,
+ occurrence.ParentStableId ?? rootId, occurrence.DefinitionStableId,
+ definition.Geometry is null ? "Assembly" : "Part", transform.ToRowMajor(), "ImportedOccurrence"));
+ if (definition.Geometry is null) continue;
+ foreach (var vertex in definition.Geometry.Topology.Vertices)
+ if (definition.Geometry.TryGetVertexPoint(vertex.Id, out var point)) points.Add(transform.Apply(point));
+ }
+ var minimum = points.Count == 0 ? new[] { 0d, 0d, 0d } : new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) };
+ var maximum = points.Count == 0 ? new[] { 0d, 0d, 0d } : new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) };
+ watch.Stop();
+ var performance = new Dictionary<string, double>(structure.Performance ?? new Dictionary<string, double>(), StringComparer.Ordinal)
+ {
+ ["displayPreparationMilliseconds"] = watch.Elapsed.TotalMilliseconds,
+ ["definitionCount"] = definitions.Count,
+ ["occurrenceCount"] = occurrences.Count - 1
+ };
+ packet = new("aetheris/cadmata-assembly-display/m3", occurrences[0].Name, rootId, definitions, occurrences,
+ [], [], new(minimum, maximum), [], performance);
+ return true;
+ }
+
public static bool TryBuild(string path, out AssemblyDisplayPacketDto? packet, out string error)
{
packet = null; error = string.Empty;
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index 39fb2c0e..6082afb6 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -260,6 +260,17 @@ public static class KernelEndpoints
return ApiMappings.BadRequestFromMessage("StepText must be provided.", "documents.import.step");
}
+ var assemblyResult = Step242AssemblyImporter.Import(request.StepText);
+ if (assemblyResult.IsSuccess)
+ {
+ if (!AssemblyDisplayService.TryBuildStep(assemblyResult.Value, out var assemblyPacket, out var displayError))
+ return ApiMappings.BadRequestFromMessage(displayError, "documents.import.step.assembly.display");
+ return ApiMappings.Ok(new StepImportResponseDto(documentId, Guid.Empty, Guid.Empty,
+ assemblyPacket!.Name, [], AssemblyPresentation: assemblyPacket));
+ }
+ if (assemblyResult.Diagnostics.All(diagnostic => diagnostic.Source != "Importer.Assembly.ProductStructure"))
+ return ApiMappings.KernelFailure(assemblyResult.Diagnostics);
+
var importResult = Step242Importer.ImportBody(request.StepText);
if (!importResult.IsSuccess)
{
diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.cs
index b9d36371..99461f1a 100644
--- a/Aetheris.Server/Contracts/ApiContracts.cs
+++ b/Aetheris.Server/Contracts/ApiContracts.cs
@@ -50,7 +50,8 @@ public sealed record StepImportResponseDto(
Guid OccurrenceId,
string? Name,
IReadOnlyList<DiagnosticDto> Diagnostics,
- CadmataVisualizationArtifactDto? SemanticPresentation = null);
+ CadmataVisualizationArtifactDto? SemanticPresentation = null,
+ AssemblyDisplayPacketDto? AssemblyPresentation = null);
public sealed record ExtrudeRequestDto(
IReadOnlyList<ProfilePoint2Dto> Profile,
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 8c5a02ff..5e349b9a 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -19,7 +19,6 @@ import {
exportDefinitionStep,
getDocumentSummary,
importStep,
- loadCadmataFixture,
maximizePaperclips,
pickBody,
prepareBodyDisplay,
@@ -553,6 +552,23 @@ function App() {
}
const imported = await importStep(documentId, stepText, fileName);
+ if (imported.assemblyPresentation) {
+ setAssemblyPacket(imported.assemblyPresentation);
+ setSelectedAssemblyOccurrenceId(imported.assemblyPresentation.rootOccurrenceStableId);
+ setDisplayPreparation(null);
+ setBodyIds([]);
+ setOccurrences([]);
+ setActiveBodyId(null);
+ setCadmataArtifact(null);
+ setStepCanonicalHash(null);
+ setStatus("success");
+ setStatusMessage(`Assembly loaded: ${imported.assemblyPresentation.name}`);
+ setImportStatus("success");
+ setImportStatusMessage(`Assembly ready: ${imported.assemblyPresentation.occurrences.length - 1} occurrences, ${imported.assemblyPresentation.definitions.length} definitions.`);
+ dispatchDocumentEvent({ type: "LoadSucceeded", documentId });
+ return;
+ }
+ setAssemblyPacket(null);
const semanticPresentation = imported.semanticPresentation
? parseCadmataVisualizationArtifact(imported.semanticPresentation)
: null;
@@ -834,23 +850,6 @@ function App() {
[activeBodyId, cadmataArtifact, documentId],
);
- const handleLoadCadmataFixture = useCallback(
- async (fixtureId: string) => {
- if (!documentId) return;
- await runAction(`Load Cadmata ${fixtureId}`, async () => {
- const loaded = await loadCadmataFixture(documentId, fixtureId);
- const artifact = parseCadmataVisualizationArtifact(loaded.visualization);
- setCadmataArtifact(artifact);
- setSelectedCadmataId(artifact.entities[0]?.stableId ?? null);
- await refreshSummaryAndActiveTessellation(loaded.bodyId);
- setStatusMessage(
- `Cadmata fixture '${fixtureId}' loaded with compiler-published correspondence.`,
- );
- });
- },
- [documentId, refreshSummaryAndActiveTessellation, runAction],
- );
-
const displayScene = useMemo(
() => buildDisplaySceneData(displayPreparation),
[displayPreparation],
@@ -1278,29 +1277,6 @@ function App() {
) : null}
</>
) : null}
- <div className="stack-row">
- {[
- "direct-profile",
- "split-compose-chamfer",
- "semantic-shaft-hole",
- "construction-plane-blind-drillpoint",
- "ctc-01-x3",
- "ctc-01-x4",
- "profile-compose-l-bracket-counterbore-pmi",
- "pmi-projected-hole-diameter",
- "hexbolt-m1",
- ].map((fixtureId) => (
- <Button
- key={fixtureId}
- type="button"
- variant="outline"
- onClick={() => void handleLoadCadmataFixture(fixtureId)}
- disabled={!documentId || status === "loading"}
- >
- {fixtureId}
- </Button>
- ))}
- </div>
{cadmataArtifact ? (
<>
<SemanticInspector
@@ -1360,13 +1336,13 @@ function App() {
})()
: null}
</>
- ) : (
+ ) : !assemblyPacket ? (
<SemanticInspector
artifact={cadmataArtifact}
selectedId={selectedCadmataId}
onSelect={setSelectedCadmataId}
/>
- )}
+ ) : null}
</section>
<section className="tool-section tool-section--import">
<h2 className="section-title">Step Import</h2>
diff --git a/aetheris.client/src/__tests__/App.test.tsx b/aetheris.client/src/__tests__/App.test.tsx
index 266ee2af..bb483516 100644
--- a/aetheris.client/src/__tests__/App.test.tsx
+++ b/aetheris.client/src/__tests__/App.test.tsx
@@ -106,6 +106,8 @@ describe("App STEP file upload flow", () => {
expect(screen.getByRole("button", { name: "GRID" }).getAttribute("aria-pressed")).toBe("true");
expect(screen.getByRole("button", { name: "COORD" }).getAttribute("aria-pressed")).toBe("true");
expect(screen.queryByText("Create Box")).toBeNull();
+ expect(screen.queryByRole("button", { name: "direct-profile" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "hexbolt-m1" })).toBeNull();
fireEvent.click(screen.getByRole("tab", { name: /Modeling Demo/i }));
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index 2d7603c9..c9509706 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -64,6 +64,7 @@ export interface StepImportResponseDto {
name: string | null;
diagnostics: DiagnosticDto[];
semanticPresentation?: unknown | null;
+ assemblyPresentation?: AssemblyDisplayPacketDto | null;
}
export interface PaperclipDemoRequestDto {
diff --git a/docs/public/cadmata/overview.md b/docs/public/cadmata/overview.md
index 81643e0f..b9e12dd6 100644
--- a/docs/public/cadmata/overview.md
+++ b/docs/public/cadmata/overview.md
@@ -4,4 +4,6 @@ Cadmata is Aetheris's interactive 3D engineering presentation and inspection sur
Use `aetheris view model.firmament` or `aetheris view part.step` from the qualified Windows bundle. The standalone .NET tool package does not contain Cadmata. Cadmata is not primarily a traditional drawing system: static drawing and shop-floor projection are downstream presentations of the semantic model.
+Cadmata opens AP242 STEP assemblies as a product tree with shared part definitions and placed occurrences. The STEP viewer's import control is the normal entry point; internal fixture endpoints are reserved for automated qualification and are not part of the viewer controls.
+
Preview 3 qualification is Windows x64. See [PMI presentation](pmi.md) and the [support matrix](../reference/supported-features.md).
diff --git a/docs/release/STEP-ASSEMBLY-X0.md b/docs/release/STEP-ASSEMBLY-X0.md
new file mode 100644
index 00000000..e3da7870
--- /dev/null
+++ b/docs/release/STEP-ASSEMBLY-X0.md
@@ -0,0 +1,47 @@
+# STEP-ASSEMBLY-X0 — AP242 product structure import
+
+## Contract
+
+`Step242AssemblyImporter.Import` reads AP242 product structure into shared product definitions and distinct occurrences. `Step242Importer.ImportBody` retains its strict single-body contract. An assembly is never silently reduced to its first body. The Cadmata STEP import endpoint returns an assembly display packet when the product-structure route succeeds; ordinary single-body files keep their existing response.
+
+The admitted source hierarchy uses `PRODUCT`, `PRODUCT_DEFINITION_FORMATION`, `PRODUCT_DEFINITION`, `PRODUCT_DEFINITION_SHAPE`, `SHAPE_DEFINITION_REPRESENTATION`, `SHAPE_REPRESENTATION`, `NEXT_ASSEMBLY_USAGE_OCCURRENCE`, `CONTEXT_DEPENDENT_SHAPE_REPRESENTATION`, `REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION`, `ITEM_DEFINED_TRANSFORMATION`, and `AXIS2_PLACEMENT_3D`. Definition geometry uses the existing exact BRep importer, once per definition. Instances share that geometry and carry local rigid 4×4 transforms. World transforms compose child local placement with parent world placement in Aetheris row-vector order. A missing occurrence transform fails with the occurrence name and STEP entity number; non-rigid placements fail explicitly.
+
+`Step242ProductStructure.Provenance` is `SourceAssembly` for explicit AP242 hierarchy and `RecoveredMultiBodyAssembly` for multiple rigid roots without useful hierarchy. The latter makes one synthetic definition and occurrence per rigid root. This inference does not claim source-authored hierarchy and never unions the bodies.
+
+`aetheris analyze assembly <file.step> --json` reads this graph without writing a package. `aetheris asm import-step <file.step> --out <directory> --json` writes the reusable `.firmasm` package. Both report hierarchy, definitions, occurrences, shared instances, transforms, world bounds, and import timings.
+
+When one authored product representation contains several independent rigid roots, import retains that product as a geometryless parent and creates one body definition per root. Each occurrence of the authored product receives child body occurrences, so repeated products still share their component geometry. A focused witness verifies two body definitions beneath each of two repeated product occurrences.
+
+## Canonical self witness
+
+Source: `fixtures/Regression/Assembly/bearing-module-family-with-legacy-placement.firmament`. The real CLI exported it with `asm export-ap242`, imported it with `asm import-step`, exported the resulting `.firmasm` again, and imported the second STEP. Generated evidence is under ignored `artifacts/local/step-assembly-x0/`.
+
+| Measure | Source | First STEP import | Second STEP import |
+| --- | ---: | ---: | ---: |
+| Body definitions | 3 | 3 | 3 |
+| Body occurrences | 9 | 9 | 9 |
+| Subassembly occurrences | 2 | 2 | 2 |
+| Non-root occurrences | 11 | 11 | 11 |
+| Repeated body instances beyond first use | 6 | 6 | 6 |
+| World bbox minimum (mm) | `[-40,-10,0]` | `[-40,-10,0]` | `[-40,-10,0]` |
+| World bbox maximum (mm) | `[40,53,20]` | `[40,53,20]` | `[40,53,20]` |
+
+The source has 12 IR instances including the root. The STEP importer represents the root through `RootDefinitionStableId` and lists its 11 descendants. Both `LeftModule` and `RightModule` retain their named children. The imported JSON report lists each definition, occurrence, parent, local transform, world transform, and bounding box. The source and imported world bounds agree exactly for this witness.
+
+Comparing each descendant by its hierarchy name path found all 11 imported paths and a maximum world-matrix element delta of `0`. All three component definitions remained enclosed manifolds after reexport/reimport, with equal face, edge, and vertex counts and equal local bounding boxes. Each has 10 faces, 20 edges, and 12 vertices in this fixture.
+
+One local run measured STEP parse `7.37 ms`, unique geometry definition import `136.86 ms`, assembly graph construction `4.07 ms`, and Cadmata display preparation `7.35 ms`. These are diagnostic wall times from one run, not performance guarantees. Geometry import ran for three unique definitions, not nine part occurrences.
+
+## Cadmata and external witness
+
+The Cadmata import endpoint was exercised through its HTTP API using an Aetheris-exported repeated-instance STEP. It returned one tessellated definition and two placed occurrences. A live browser launch with the canonical STEP showed the `Machine` product tree, both module instances and all nine visible part occurrences at their placed positions; the status read `Assembly ready: 11 occurrences, 3 definitions.` No assembly-import error appeared. Cadmata's existing assembly renderer consumes shared definition meshes and occurrence world transforms.
+
+The viewer's leftover prototype fixture buttons were removed from the semantic inspector. The existing fixture API remains available to automated tests; ordinary users open their own STEP files through the import control.
+
+The existing `testdata/step242/OCCT/as1.step` witness imports as 27 occurrences and 5 geometry definitions, of which 18 occurrences are parts. This is a bounded secondary compatibility witness, not a claim of universal STEP dialect support.
+
+## Limits
+
+- The Cadmata STEP assembly response is an inspectable scene packet. It is not yet persisted in `DocumentSession` for assembly editing, body-level picking, or document-level reexport. The `.firmasm` CLI package is the supported import/reexport route.
+- Synthetic multibody identity uses rigid-root STEP entity identifiers because those files have no stronger occurrence identity. Explicit product and usage IDs take precedence when available.
+- Other historical assembly encodings and unsupported non-rigid transforms require explicit diagnostics and further witnesses. No kinematics, mates, constraints, or USD lowering are part of X0.