Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add browser product artifact export

Yuechen Lic0d588b35980
diff --git a/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs b/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs
new file mode 100644
index 00000000..c45eb05e
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ProductArtifactExportTests.cs
@@ -0,0 +1,87 @@
+using System.IO.Compression;
+using System.Text;
+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;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ProductArtifactExportTests
+{
+ [Fact]
+ public void ExistingExportersProduceReadablePartArtifactsAndPreserveExactStep()
+ {
+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/DrawingGeneration/inspection-plate.firmament");
+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(fixture));
+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics.Select(d => d.Message)));
+ var step = compiled.Value.StepText;
+ var body = Step242Importer.ImportBody(step).Value;
+ var tessellation = BrepDisplayTessellator.Tessellate(body).Value;
+ var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
+ foreach (var face in tessellation.FacePatches)
+ {
+ var offset = positions.Count / 3;
+ positions.AddRange(face.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ normals.AddRange(face.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ indices.AddRange(face.TriangleIndices.Select(i => i + offset));
+ }
+ var display = new AssemblyDisplayMeshDocument("aetheris/display-mesh/1", "Plate", "mm",
+ [new("definition", "plate", positions.ToArray(), normals.ToArray(), indices.ToArray())],
+ [new("occurrence", "Plate", null, "definition", [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])]);
+ var scratch = Path.Combine(Path.GetDirectoryName(fixture)!, "../../../artifacts/local/tests/product-export");
+ var expectedPmi = Drawing.FirmamentDrawingCompiler.AuthoredPmiNames(compiled.Value);
+ Assert.Equal(11, expectedPmi.Count);
+ var files = ProductArtifactExporter.Export(new("Plate", step, display, ExpectedPmi: expectedPmi),
+ ["step", "glb", "usda", "stl", "obj", "pdf", "svg", "pptx"], scratch);
+ Assert.Equal(8, files.Count);
+ byte[] Bytes(string extension) => files.Single(f => f.FileName.EndsWith("." + extension, StringComparison.Ordinal)).Bytes;
+ Assert.Equal(step, Encoding.UTF8.GetString(Bytes("step")));
+ 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.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);
+ Assert.Equal("%PDF-", Encoding.ASCII.GetString(Bytes("pdf"), 0, 5));
+ Assert.Contains("<svg", Encoding.UTF8.GetString(Bytes("svg")));
+ using var pptx = new ZipArchive(new MemoryStream(Bytes("pptx")));
+ Assert.Contains(pptx.Entries, e => e.FullName == "ppt/slides/slide1.xml");
+ var package = ProductArtifactExporter.Package(files);
+ Assert.Equal("Plate-exports.zip", package.FileName);
+ using var zip = new ZipArchive(new MemoryStream(package.Bytes));
+ Assert.Equal(8, zip.Entries.Count);
+ foreach (var file in files)
+ {
+ using var stream = zip.GetEntry(file.FileName)!.Open(); using var copy = new MemoryStream(); stream.CopyTo(copy);
+ Assert.Equal(file.Bytes, copy.ToArray());
+ }
+ Assert.Equal(step, compiled.Value.StepText);
+ Assert.Empty(Directory.GetDirectories(scratch));
+ var rejected = Assert.Throws<InvalidOperationException>(() => ProductArtifactExporter.Export(
+ new("Plate", step, display, ExpectedPmi: ["MissingAuthoredRequirement"]), ["pdf"], scratch));
+ Assert.StartsWith("drawing-pmi-not-exported:", rejected.Message);
+ Assert.Empty(Directory.GetDirectories(scratch));
+ }
+
+ [Fact]
+ public void AssemblyAvailabilityIsExplicitAndUnknownOrUnavailableFormatsNeverSucceed()
+ {
+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Assembly/annular-pair.firmament");
+ var compilation = new AssemblyM1Pipeline().Compile(File.ReadAllText(fixture), fixture);
+ Assert.True(compilation.IsSuccess);
+ var display = AssemblyDisplayMeshExporter.Export(compilation);
+ var source = new ProductExportSource("Pair", null, display, compilation.Ir);
+ var scratch = Path.Combine(Path.GetDirectoryName(fixture)!, "../../../artifacts/local/tests/product-export");
+ Assert.Contains(ProductArtifactExporter.Options(true, false), o => o.Format == "pdf" && !o.Available && o.Reason is not null);
+ Assert.Throws<InvalidOperationException>(() => ProductArtifactExporter.Export(source, ["banana"], scratch));
+ Assert.Throws<InvalidOperationException>(() => ProductArtifactExporter.Export(source, ["stl"], scratch));
+ var files = ProductArtifactExporter.Export(source, ["glb", "usda"], scratch);
+ using var glb = JsonDocument.Parse(files[0].Bytes.AsMemory(20, BitConverter.ToInt32(files[0].Bytes, 12)));
+ Assert.Equal(display.Occurrences.Count + 1, glb.RootElement.GetProperty("nodes").GetArrayLength()); // unit/up-axis conversion root
+ Assert.Equal(60, display.Occurrences.Single(o => o.Path == "AnnularPair.Second").Transform[12]);
+ Assert.Equal("#usda 1.0", Encoding.UTF8.GetString(files[1].Bytes).Split('\n')[0]);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
index 2f84f388..c40f22fe 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
@@ -16,6 +16,21 @@ public static partial class FirmamentDrawingCompiler
public static DrawingCompileResult Generate(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff = null)
=> Generate(sourcePath, outputDirectory, signoff, new());
+ /// <summary>Project an already compiled product, retaining its authored PMI admission checks.
+ /// The browser has no source file to reopen; STEP bytes remain the geometry authority.</summary>
+ public static DrawingCompileResult GenerateFromStep(string step, string name, string sourceDocument,
+ IReadOnlyList<string> expectedPmi, string outputDirectory)
+ {
+ try { return GeneratePart(sourceDocument, step, name, "AP242", step, expectedPmi, outputDirectory, null, new()); }
+ catch (InvalidOperationException e) when (e.Message.StartsWith("drawing-", StringComparison.Ordinal)) { return Failure(e.Message); }
+ }
+
+ public static IReadOnlyList<string> AuthoredPmiNames(FirmamentStepExportResult product)
+ {
+ var bound = product.RuntimeAdmissionDocument?.BoundPmi;
+ return (bound?.Datums ?? []).Concat(bound?.Dimensions ?? []).Concat(bound?.Controls ?? []).Select(p => p.Name).ToArray();
+ }
+
public static DrawingCompileResult Generate(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff, DrawingGenerationOptions options)
{
if (DrawingTitleBlockLayout.ValidateSignoff(signoff) is { } error) return Failure(error);
@@ -47,8 +62,7 @@ public static partial class FirmamentDrawingCompiler
}
var compiled = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(path));
if (!compiled.IsSuccess) return new(false, null, compiled.Diagnostics.Select(d => $"{d.Source}: {d.Message}").ToArray());
- var bound = compiled.Value.RuntimeAdmissionDocument?.BoundPmi;
- expectedPmi = (bound?.Datums ?? []).Concat(bound?.Dimensions ?? []).Concat(bound?.Controls ?? []).Select(p => p.Name).ToArray();
+ expectedPmi = AuthoredPmiNames(compiled.Value);
step = compiled.Value.StepText;
name = compiled.Value.DocumentName ?? name;
sourceKind = "FirmamentPart";
@@ -56,6 +70,12 @@ public static partial class FirmamentDrawingCompiler
else if (Path.GetExtension(path).ToLowerInvariant() is not (".step" or ".stp"))
return Failure("drawing-input-unsupported: Generate expects a Firmament part or STEP BRep; use drawing compile for authored Assembly drawings.");
+ return GeneratePart(path, source, name, sourceKind, step, expectedPmi, outputDirectory, signoff, options);
+ }
+
+ private static DrawingCompileResult GeneratePart(string path, string source, string name, string sourceKind, string step,
+ IReadOnlyList<string> expectedPmi, string outputDirectory, DrawingSignoffIr? signoff, DrawingGenerationOptions options)
+ {
var imported = Step242Importer.ImportBody(step);
if (!imported.IsSuccess) return new(false, null, imported.Diagnostics.Select(d => $"{d.Source}: {d.Message}").ToArray());
var inspected = Step242SemanticPmiInspector.Inspect(step);
diff --git a/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs b/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
new file mode 100644
index 00000000..9ba50549
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Export/ProductArtifactExporter.cs
@@ -0,0 +1,119 @@
+using System.Text;
+using System.IO.Compression;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Drawing;
+using Aetheris.Kernel.Firmament.Scene;
+
+namespace Aetheris.Kernel.Firmament.Export;
+
+public sealed record ProductExportOption(string Format, string Label, string Description, bool Available, string? Reason = null);
+public sealed record ProductExportFile(string FileName, string MediaType, byte[] Bytes);
+public sealed record ProductExportSource(string Name, string? StepText, AssemblyDisplayMeshDocument Display,
+ AssemblyIr? Assembly = null, CompiledScene? Scene = null,
+ IReadOnlyList<string>? ExpectedPmi = null, string? SourceDocument = null);
+
+/// <summary>Download adapters over the existing engineering and presentation exporters.
+/// Scratch files belong to this invocation and are removed even when an exporter rejects a product.</summary>
+public static class ProductArtifactExporter
+{
+ public static ProductExportFile Package(IReadOnlyList<ProductExportFile> files)
+ {
+ if (files.Count == 1) return files[0];
+ using var memory = new MemoryStream();
+ using (var archive = new ZipArchive(memory, ZipArchiveMode.Create, leaveOpen: true))
+ foreach (var file in files)
+ {
+ var entry = archive.CreateEntry(file.FileName);
+ entry.LastWriteTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ using var stream = entry.Open(); stream.Write(file.Bytes);
+ }
+ return new(Path.GetFileNameWithoutExtension(files[0].FileName) + "-exports.zip", "application/zip", memory.ToArray());
+ }
+ public static IReadOnlyList<ProductExportOption> Options(bool hasStep, bool isPart) =>
+ [
+ new("step", "STEP AP242", "Exact geometry and supported semantic PMI", hasStep, hasStep ? null : "Scenes have no STEP product artifact."),
+ new("glb", "glTF / GLB", "Binary glTF 2.0 · static authored pose", true),
+ new("usda", "OpenUSD / USDA", "Scene hierarchy and static authored pose", true),
+ new("stl", "STL", "Validated closed triangle mesh · millimetres", isPart, isPart ? null : "STL export currently requires a single part."),
+ new("obj", "OBJ", "SurfaceMeshIR polygons · millimetres", isPart, isPart ? null : "OBJ export currently requires a single part."),
+ new("pdf", "PDF drawing", "Dimensioned drawing · supported part families", isPart, isPart ? null : "Automatic drawings currently require a single part."),
+ new("svg", "SVG drawing", "Vector drawing sheets", isPart, isPart ? null : "Automatic drawings currently require a single part."),
+ new("pptx", "PowerPoint drawing", "Drawing sheets in an editable slide deck", isPart, isPart ? null : "Automatic drawings currently require a single part.")
+ ];
+
+ public static IReadOnlyList<ProductExportFile> Export(ProductExportSource source, IReadOnlyList<string> formats, string scratchRoot)
+ {
+ if (formats.Count == 0) throw new InvalidOperationException("export-format-required: Select at least one format.");
+ var options = Options(source.StepText is not null, source.Assembly is null && source.Scene is null);
+ foreach (var format in formats)
+ {
+ var option = options.SingleOrDefault(o => o.Format == format)
+ ?? throw new InvalidOperationException($"export-format-unknown: Unknown export format '{format}'.");
+ if (!option.Available) throw new InvalidOperationException($"export-format-unavailable: {option.Label}: {option.Reason}");
+ }
+ // Never use a document name as a filesystem path, including browser project paths.
+ var stem = new string(source.Name.Select(c => char.IsLetterOrDigit(c) || c is '-' or '_' or '.' ? c : '_').ToArray());
+ if (string.IsNullOrWhiteSpace(stem) || stem is "." or "..") stem = "model";
+ var scratch = Path.Combine(Path.GetFullPath(scratchRoot), "export-" + Guid.NewGuid().ToString("N"));
+ var files = new List<ProductExportFile>();
+ DrawingCompileArtifacts? drawing = null;
+ SurfaceMeshDocument? surfaceMesh = null;
+ try
+ {
+ foreach (var format in formats.Distinct(StringComparer.Ordinal))
+ {
+ byte[] bytes;
+ var mediaType = "application/octet-stream";
+ switch (format)
+ {
+ 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,
+ 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;
+ case "usda":
+ var usd = source.Scene is { } spatial ? SceneExport.Usd(spatial)
+ : source.Assembly is { } assembly ? AssemblyUsdExporter.Serialize(assembly, source.Display)
+ : AssemblyUsdExporter.SerializeSpatial(source.Display, new(
+ source.Display.Occurrences.ToDictionary(o => o.Id, _ => source.Display.Definitions[0].Identity),
+ new Dictionary<string, AssemblyAppearanceBinding>(), new Dictionary<string, IReadOnlyDictionary<string, string>>(), []));
+ bytes = Encoding.UTF8.GetBytes(usd); mediaType = "text/plain"; break;
+ case "stl":
+ case "obj":
+ if (surfaceMesh is null)
+ {
+ var body = Step242Importer.ImportBody(source.StepText!);
+ if (!body.IsSuccess) throw new InvalidOperationException("mesh-import-failed: " + string.Join("; ", body.Diagnostics.Select(d => d.Message)));
+ if (!SurfaceMeshIrTessellator.TryBuild(body.Value, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out surfaceMesh, out var failure)
+ || !SurfaceMeshIrValidator.TryValidate(surfaceMesh, out failure))
+ throw new InvalidOperationException("mesh-export-unsupported: " + failure);
+ }
+ if (format == "obj") { bytes = Encoding.UTF8.GetBytes(SurfaceMeshObjExporter.Export(surfaceMesh, stem).Text); mediaType = "text/plain"; break; }
+ if (!SurfaceMeshIrTessellator.TryLowerToTriangleMesh(surfaceMesh, out var mesh, out var topology))
+ throw new InvalidOperationException($"stl-mesh-not-closed: cracks={topology.CrackCount}, nonmanifold={topology.NonManifoldEdgeCount}, outward={topology.IsOutwardOriented}.");
+ Directory.CreateDirectory(scratch);
+ var stl = Path.Combine(scratch, "model.stl"); BinaryStlExporter.Export(stl, mesh);
+ bytes = File.ReadAllBytes(stl); mediaType = "model/stl"; break;
+ default: // All drawing formats share the same admitted DrawingIR and generation pass.
+ if (drawing is null)
+ {
+ Directory.CreateDirectory(scratch);
+ var generated = FirmamentDrawingCompiler.GenerateFromStep(source.StepText!, stem,
+ source.SourceDocument ?? stem + ".step", source.ExpectedPmi ?? [], Path.Combine(scratch, "drawing"));
+ if (!generated.IsSuccess) throw new InvalidOperationException(string.Join("; ", generated.Diagnostics));
+ drawing = generated.Artifacts!;
+ }
+ bytes = File.ReadAllBytes(format == "pdf" ? drawing.PdfPath : format == "svg" ? drawing.SvgPath : drawing.PptxPath);
+ mediaType = format == "pdf" ? "application/pdf" : format == "svg" ? "image/svg+xml" : "application/vnd.openxmlformats-officedocument.presentationml.presentation";
+ break;
+ }
+ files.Add(new(stem + "." + format, mediaType, bytes));
+ }
+ return files;
+ }
+ finally { if (Directory.Exists(scratch)) Directory.Delete(scratch, recursive: true); }
+ }
+}
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index 9d6c61d0..7e5fa66c 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -13,6 +13,7 @@ using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.Materializer;
using Aetheris.Kernel.Firmament.Scene;
+using Aetheris.Kernel.Firmament.Export;
namespace Aetheris.Web.Runtime;
@@ -71,6 +72,7 @@ public static partial class Program
"setSource" => SetSource(request),
"rebuild" => Rebuild(request),
"exportStep" => ExportStep(request),
+ "exportArtifacts" => Session(request).ExportArtifacts(request),
"disposeSession" => DisposeSession(request),
"disposeRuntime" => DisposeRuntime(),
_ => throw new WebRuntimeException("unknown-operation", $"Unknown runtime operation '{request.Operation}'.")
@@ -100,7 +102,7 @@ public static partial class Program
capabilities = new
{
compile = true, solidModeling = true, assembly = true, displayMesh = true,
- propertyInspection = true, parameterRebuild = true, stepExport = true,
+ propertyInspection = true, parameterRebuild = true, stepExport = true, artifactExport = true,
sheetMetal = false, fea = false, externalStepImport = false, forgeSubprocess = false,
cancellation = false, worker = false
}
@@ -245,6 +247,7 @@ public static partial class Program
private static object ExportStep(WebRequest request)
{
var session = Session(request);
+ session.RequireExportRevision(request.BuildRevision);
var stepText = session.StepText;
if (stepText is null) throw new WebRuntimeException("step-export-unavailable", "The current document has no STEP product artifact.");
return new { mediaType = "model/step", fileName = session.Name + ".step", base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(stepText)), revision = session.Revision };
@@ -273,7 +276,8 @@ public static partial class Program
string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null,
bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null, string? ProjectRoot = null,
int? Bridge = null, IReadOnlyList<FirmamentLanguageEditOperation>? Operations = null,
- string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false);
+ string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false,
+ IReadOnlyList<string>? Formats = null);
/// <summary>
/// BUILD-PERF-M3 response bridge (request <c>bridge: 1</c>, sent by the SDK). Large numeric arrays
@@ -308,7 +312,35 @@ public static partial class Program
private AssemblyCompilationReuse? _lastReuse;
private AssemblyIr? _assembly;
private AssemblyIr? _pendingAssembly;
- public void Dispose() { _assembly = null; _pendingAssembly = null; _compilationSession.Dispose(); _sceneSession.Dispose(); }
+ private CompiledScene? _scene;
+ private CompiledScene? _pendingScene;
+ private AssemblyDisplayMeshDocument? _exportDisplay;
+ private bool _dirty = true;
+ private IReadOnlyList<string> _expectedPmi = [];
+ public void RequireExportRevision(int? revision)
+ {
+ if (_dirty || _exportDisplay is null || revision is { } expected && expected != Revision)
+ throw new WebRuntimeException("export-stale-revision", "Build the current source successfully before exporting.");
+ }
+ public object ExportArtifacts(WebRequest request)
+ {
+ RequireExportRevision(request.BuildRevision);
+ var formats = request.Formats ?? [];
+ var needsStep = formats.Any(f => f is not ("glb" or "usda"));
+ try
+ {
+ var files = ProductArtifactExporter.Export(new(Name, needsStep ? StepText : null, _exportDisplay!, _assembly, _scene, _expectedPmi, _sourceName),
+ formats, Path.GetTempPath());
+ var file = ProductArtifactExporter.Package(files);
+ return new { revision = Revision, files = new[] { new { file.FileName, file.MediaType, base64 = Convert.ToBase64String(file.Bytes) } } };
+ }
+ catch (InvalidOperationException error)
+ {
+ var separator = error.Message.IndexOf(':');
+ throw new WebRuntimeException(separator > 0 ? error.Message[..separator] : "export-failed", error.Message);
+ }
+ }
+ public void Dispose() { _assembly = null; _pendingAssembly = null; _scene = null; _pendingScene = null; _exportDisplay = null; _compilationSession.Dispose(); _sceneSession.Dispose(); }
internal object SampleMotion(WebRequest request)
{
if (_assembly is null || request.Motion is null || request.TimeSeconds is null)
@@ -352,6 +384,7 @@ public static partial class Program
{
if (documents is not null) _projectDocuments = documents;
_source = nextSource;
+ _dirty = true;
if (!string.IsNullOrWhiteSpace(nextSourceName)) _sourceName = nextSourceName;
_overrides.Clear();
_projections = [];
@@ -408,6 +441,7 @@ public static partial class Program
if (property.Type == "Length" && value.Value <= 0)
throw new WebRuntimeException("property-out-of-range", $"Property '{property.Name}' must be greater than zero.");
_overrides[propertyId] = value;
+ _dirty = true;
}
public WebBuildResult Rebuild()
@@ -420,6 +454,8 @@ public static partial class Program
var effective = ApplyOverrides(_source, sourceProperties, _overrides);
_lastReuse = null;
_pendingAssembly = null;
+ _pendingScene = null;
+ _dirty = true;
var nextProperties = sourceProperties;
foreach (var (propertyId, value) in _overrides)
{
@@ -437,6 +473,10 @@ public static partial class Program
Revision++;
_assembly = _pendingAssembly;
+ _scene = _pendingScene;
+ _exportDisplay = compiled.ExportDisplay ?? (AssemblyDisplayMeshDocument)compiled.Mesh!;
+ _dirty = false;
+ _expectedPmi = compiled.ExpectedPmi;
_properties = nextProperties;
_projections = compiled.Projections ?? [];
_stepText = compiled.StepText;
@@ -460,6 +500,7 @@ public static partial class Program
id = Id, name = Name, revision = Revision, source = _source, sourceName = _sourceName,
tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,
diagnostics = compiled.Diagnostics, changes, timings,
+ exportFormats = ProductArtifactExporter.Options(_stepText is not null || _stepWriter is not null, _assembly is null && _scene is null),
motions = (_assembly?.Motions ?? []).Select(m => new { m.Name, m.DurationSeconds, repeat = m.Repeat.ToString(),
tracks = m.Tracks.Select(t => new { t.Name, t.MateStableId, t.JointName, valueDimension = t.Curve.ValueDimension.ToString() }) }).ToArray()
};
@@ -525,7 +566,7 @@ 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");
- var mesh = WebMeshBuilder.Build(Name, definitionId, entityId, displayBody,
+ 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));
meshPhase.Dispose();
var meshMs = watch.Elapsed.TotalMilliseconds;
@@ -539,7 +580,9 @@ public static partial class Program
boxSource ?? projectedBodySource ?? SourceRef(_sourceName, 0, effective.Length), SemanticConstruct: semanticConstruct);
var root = new WebTreeNode(Id, "Model", Name, null, [body.Id], true, SourceRef(_sourceName, 0, effective.Length));
var tree = new { rootId = root.Id, nodes = new[] { root, body }.Concat(featureNodes).ToArray() };
- return WebBuildResult.Passed(step, tree, mesh, [Id, entityId, .. featureNodes.Select(item => item.Id)], compileMs, meshMs) with { Projections = projections };
+ 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 };
}
private WebBuildResult CompileAssembly(string effective, List<WebProperty> properties)
@@ -619,6 +662,7 @@ public static partial class Program
var nodes = mesh.Occurrences.Select(o => new WebTreeNode(o.Id, o.Kind ?? "SceneNode", o.Path.Split('.').Last(), o.ParentId,
mesh.Occurrences.Where(c => c.ParentId == o.Id).Select(c => c.Id).ToArray(), true, SceneSource(o.Path))).ToArray();
var tree = new { rootId = mesh.Occurrences.Single(o => o.ParentId is null).Id, nodes };
+ _pendingScene = compiledScene;
return WebBuildResult.Passed(null, tree, mesh, nodes.Select(n => n.Id).ToArray(), watch.Elapsed.TotalMilliseconds, compiledScene.Performance.DisplayPreparationMilliseconds);
}
}
@@ -722,7 +766,7 @@ internal static class ParameterInspector
internal static class WebMeshBuilder
{
- public static object Build(string name, string definitionId, string entityId, BrepBody body,
+ 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)
@@ -760,12 +804,17 @@ internal static class WebMeshBuilder
}
mapPhase.Dispose();
var shader = CirShaderArtifactProvider.Resolve(cir);
+ var positionArray = positions.ToArray(); var normalArray = normals.ToArray(); var indexArray = indices.ToArray();
+ 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)]);
return new
{
schema = "aetheris/display-mesh/1",
name,
units = "mm",
- definitions = new[] { new { id = definitionId, identity = entityId, positions = positions.ToArray(), normals = normals.ToArray(), indices = indices.ToArray(), ranges,
+ 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 ?? [],
edges = tessellation.Value.EdgePolylines.Select(edge =>
@@ -780,7 +829,7 @@ internal static class WebMeshBuilder
: semanticEdge.FirmamentSelector is null ? "Construction identity is known, but Firmament has no qualified source selector for this edge." : null,
source = semanticEdge is null ? null : owner == entityId ? source : featureSources![owner], buildRevision };
}).ToArray() } },
- occurrences = new[] { new { id = entityId + ":occurrence", path = name, parentId = (string?)null, definitionId, semanticEntityId = entityId, transform = new double[] { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 } } }
+ occurrences = new[] { new { id = entityId + ":occurrence", path = name, parentId = (string?)null, definitionId, semanticEntityId = entityId, transform } }
};
}
}
@@ -794,6 +843,8 @@ internal sealed record WebBuildResult(bool Success, int Revision, object? Model,
object? Tree = null, object? Mesh = null, IReadOnlyList<string>? EntityIds = null, object? Timings = null, object? Changes = null, string? StepText = null,
IReadOnlyList<FirmamentConstructProjection>? Projections = null, double CompileMilliseconds = 0, double MeshMilliseconds = 0)
{
+ [System.Text.Json.Serialization.JsonIgnore] public AssemblyDisplayMeshDocument? ExportDisplay { get; init; }
+ [System.Text.Json.Serialization.JsonIgnore] public IReadOnlyList<string> ExpectedPmi { get; init; } = [];
/// <summary>The session that produced this build; never serialized.</summary>
[System.Text.Json.Serialization.JsonIgnore] public object? Owner { get; init; }
/// <summary>Writes the STEP text on first request; never serialized.</summary>
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index 225787f2..3e098d67 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -21,7 +21,7 @@ export interface DisplayBoundary { readonly path: string; readonly room: 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 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 sheetMetal: boolean; readonly fea: boolean; readonly externalStepImport: boolean; readonly forgeSubprocess: boolean; readonly cancellation: boolean; readonly worker: boolean }
+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 }
export interface RuntimeInfo { readonly packageVersion: string; readonly runtimeVersion: string; readonly contractVersion: 'aetheris/web-editor-contract/1'; readonly language: 'Firmament'; readonly capabilities: RuntimeCapabilities }
export interface WorkerTiming { readonly operation: string; readonly executionMilliseconds: number; readonly transportMilliseconds: number; readonly payloadBytes: number; readonly initialization?: { readonly moduleImportMilliseconds: number; readonly runtimeCreateMilliseconds: number; readonly assemblyExportsMilliseconds: number } | null }
export interface OperationOptions { readonly signal?: AbortSignal; readonly sourceRevision?: string; readonly performance?: boolean }
@@ -87,6 +87,9 @@ export class Aetheris {
export interface MotionClip { readonly name: string; readonly durationSeconds: number; readonly repeat: 'Once' | 'Loop'; readonly tracks: readonly { readonly name: string; readonly mateStableId: string; readonly jointName: string; readonly valueDimension: 'Angle' | 'Length' }[] }
export interface MotionPose { readonly revision: number; readonly motion: string; readonly timeSeconds: number; readonly state: Readonly<Record<string, number>>; readonly transforms: readonly { readonly id: string; readonly matrix: readonly number[] | Float64Array }[] }
export class ModelSession {
+ readonly exportFormats: readonly ExportFormatOption[];
+ /** One format returns its file; multiple formats return one ZIP. Rejected exports produce no files. */
+ exportArtifacts(formats: readonly ExportFormat[], options?: OperationOptions): Promise<readonly ExportFile[]>;
readonly motions: readonly MotionClip[];
sampleMotion(motion: string, timeSeconds: number, options?: OperationOptions & { readonly preserveEndpoint?: boolean }): Promise<MotionPose>;
readonly id: string; readonly name: string; readonly revision: number; readonly source: string; readonly sourceName: string;
@@ -112,3 +115,6 @@ export class ModelSession {
exportSTEPBlob(options?: OperationOptions): Promise<Blob>;
dispose(): Promise<void>;
}
+export type ExportFormat = 'step' | 'glb' | 'usda' | 'stl' | 'obj' | 'pdf' | 'svg' | 'pptx';
+export interface ExportFormatOption { readonly format: ExportFormat; readonly label: string; readonly description: string; readonly available: boolean; readonly reason?: string | null }
+export interface ExportFile { readonly fileName: string; readonly mediaType: string; readonly bytes: Uint8Array }
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
index 1b8b2047..57acd743 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.js
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -245,12 +245,20 @@ export class ModelSession {
.sort((a, b) => a.selector < b.selector ? -1 : a.selector > b.selector ? 1 : 0);
}
async exportSTEP(options = {}) {
- throwIfAborted(options.signal);
- const result = await this.transport.request({ operation: 'exportStep', sessionId: this.id });
- if (result.bytes instanceof Uint8Array) return result.bytes;
- const binary = atob(result.base64); const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
- return bytes;
+ return (await this.exportArtifacts(['step'], options))[0].bytes;
+ }
+ async exportArtifacts(formats, options = {}) {
+ return this.serial(async () => {
+ throwIfAborted(options.signal);
+ const result = await this.transport.request({ operation: 'exportArtifacts', sessionId: this.id, buildRevision: this.revision, formats });
+ throwIfAborted(options.signal);
+ if (result.revision !== this.revision) throw new AetherisError('export-stale-revision', 'The export belongs to a different build revision.');
+ return result.files.map(file => {
+ const binary = atob(file.base64);
+ const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
+ return { fileName: file.fileName, mediaType: file.mediaType, bytes };
+ });
+ });
}
async exportSTEPBlob(options = {}) { return new Blob([await this.exportSTEP(options)], { type: 'model/step' }); }
async dispose() { await this.transport.request({ operation: 'disposeSession', sessionId: this.id }); }
diff --git a/docs/development/HELIOS-EXPORTS.md b/docs/development/HELIOS-EXPORTS.md
new file mode 100644
index 00000000..fcaf9289
--- /dev/null
+++ b/docs/development/HELIOS-EXPORTS.md
@@ -0,0 +1,131 @@
+# Helios export picker qualification
+
+Date: 2026-10-19
+
+## Behavior and ownership
+
+Helios replaces **Export STEP** with a checkbox picker for STEP AP242, GLB,
+USDA, STL, OBJ and PDF/SVG/PPTX drawings. The command palette opens the same picker.
+One format downloads directly; several formats download as one ZIP, avoiding
+browser multiple-download permission prompts. Failures return no partial archive.
+The file stem comes from the compiled project root, including while a component
+document is open.
+
+`ProductArtifactExporter` is a small adapter over the existing STEP bytes,
+Assembly/Scene GLB and USDA writers, SurfaceMeshIR STL/OBJ exporters and Drawing
+compiler. It owns format metadata and packages files; Helios supplies no format
+schema or geometry implementation. Existing `exportSTEP()` and `exportSTEPBlob()`
+remain available through the same SDK admission path. The older runtime
+`exportStep` operation remains for clients using that transport contract.
+
+The Web runtime retains the accepted display packet and scene/assembly context.
+Part export packets share the viewport's position/normal/index arrays. STEP is
+still written lazily for assemblies; GLB/USDA-only requests do not force STEP
+serialization. Source/property edits and failed rebuilds mark exports dirty.
+Requests carry the build revision; the UI rebuilds changed source and discards an
+export if another edit occurs while preparation runs. The last-valid viewport
+remains available without becoming an accidental export of the current draft.
+
+Drawing generation projects the retained compiled STEP through the existing
+dimension planner. `GenerateFromStep` shares the same implementation as native
+file generation, including unsupported-family, PMI-readback and complete nominal
+geometry checks. Authored PMI names come from the compiler-owned admission
+document through `AuthoredPmiNames`; the adapter cannot silently omit a requirement
+that lacks an AP242 projection. STL retains the native closed-mesh validation.
+Temporary drawing/STL files are invocation-owned and removed in `finally`.
+
+## Deliberate limits
+
+- Parts offer all eight formats, subject to the existing geometry/drawing admission
+ checks. Assemblies offer STEP/GLB/USDA. Scenes offer GLB/USDA. Disabled options
+ explain their product-kind boundary.
+- GLB is the glTF 2.0 download. No standalone JSON glTF or DXF implementation was
+ added. GLB/USDA use the authored static pose, supported appearances and Scene
+ cameras; they do not serialize a currently playing animation or viewport state.
+- Automatic drawings remain limited to rectangular stock and disjoint circular
+ Z-through holes. Missing tolerances, material and signoffs remain unspecified.
+ The picker does not infer manufacturing requirements, use reference-only fallback,
+ or claim engineering approval.
+- Qualification uses the local development WASM package and real Helios browser
+ application. It does not constitute a published package or new production AOT
+ release. No new CAD/kernel capability is claimed.
+
+## Reproduction
+
+Run the normal serial .NET build and both required lanes:
+
+```powershell
+$env:MSBUILDDISABLENODEREUSE='1'
+$env:DOTNET_PROCESSOR_COUNT='2'
+dotnet build Aetheris.slnx -c Release --no-restore -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet test Aetheris.Kernel.Firmament.Tests -c Release --no-build -m:1 --filter FullyQualifiedName~ProductArtifactExportTests
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 --filter 'Category!=SlowCorpus'
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+node --test Aetheris.Web.Runtime/sdk/tests/*.test.mjs
+```
+
+Install the current local SDK with Helios's existing
+`node scripts/install-local-sdk.mjs`, then run its TypeScript, Vitest and Vite
+builds. Start Helios's existing Vite server on port 4173. From the Aetheris root:
+
+```powershell
+node scripts/qualify-helios-exports.mts ../HeliosCAD/node_modules/playwright/index.mjs
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Regression/DrawingGeneration/inspection-plate.firmament --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll inspect artifacts/local/helios-exports/inspection-plate.step --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/DrawingGeneration/inspection-plate.firmament --out artifacts/local/helios-exports/native-plate.step --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll mesh artifacts/local/helios-exports/inspection-plate.step --format stl --output artifacts/local/helios-exports/native-plate.stl --json
+python scripts/qualify-helios-export-files.py
+```
+
+The file verifier needs `pypdf`; `pypdfium2` renders the PDF pages for visual
+inspection. Browser qualification uses isolated headless Edge and closes its
+browser. Shut down the temporary Vite server after qualification.
+
+## Evidence
+
+Raw logs, downloads, ZIP contents, PDF renders and screenshots are ignored under
+`artifacts/local/helios-exports/` and `artifacts/local/export-*.log`.
+
+- Real part download: all eight files, a single ZIP and a direct STEP file.
+- Assembly: STEP/GLB/USDA; Scene: GLB/USDA including three authored cameras.
+- Invalid changed source prevents exporting the retained last-good model.
+ An unsupported chamfered-part drawing rejects with
+ `drawing-definition-incomplete`, producing no download.
+- Unit coverage checks the format catalogue, archive contents, readable output
+ structure, source revision changes during export, stable diagnostic codes,
+ missing authored PMI rejection, and scratch cleanup.
+- The inspection plate reopens through the CLI as one body, 16 faces, 42 edges,
+ 48 vertices, with bounds `[-50,-35,0]` to `[50,35,8]` mm. STL has 1,684 triangles.
+ Downloaded STEP and STL are byte-identical to native CLI output.
+- STEP SHA256: `17eccf1954168db4b3764343e0db44bef707d51e29ecb6660a6b51c55d8c1119`.
+ STL SHA256: `a4942626a3c6ddd6cc87e2869f7d2daa1e006ae396500407936b7fc44a71009d`.
+- Downloaded PDF text, SVG XML, GLB JSON/binary headers, USDA unit/axis metadata
+ and PPTX package contents are independently reopened. The PDF visibly retains
+ X0/Y0 references, diameter PMI, controlling stock dimensions and incomplete
+ manufacturing-requirement notices.
+
+## Final gates and verdict
+
+| Gate | Result |
+| --- | --- |
+| Release solution build | Passed, zero errors; existing nullable/WASM native-import warnings remain |
+| Focused artifact tests | 2 passed |
+| Core fast lane | 1,087 passed |
+| Full solution, including corpus lane | 5,665 passed across 20 test assemblies; zero failures/skips |
+| Web SDK tests | 14 passed |
+| Helios tests | 101 passed across 21 files |
+| Helios TypeScript and Vite development build | Passed; existing bundle-size advisory remains |
+| Real Helios browser and SDK exports | Passed, no uncaught page errors |
+| Download reopening, native STEP/STL byte parity and PDF visual inspection | Passed |
+| Whitespace checks in both repositories | Passed |
+
+The SDK source, built distribution and Helios-installed JavaScript hashes agree.
+The direct browser SDK check also exercises the retained `exportSTEP()` API and
+rejects export after an unsuccessful `setSource` rebuild. The menu was visually
+checked after correcting its stacking over Monaco's scrollbar. The temporary Vite
+server and browser were closed; no .NET build/test/runtime hosts remained at
+closeout.
+
+**Success.** The requested exports work through the real browser/runtime paths,
+with explicit product-family limits and preserved engineering geometry. Public
+guides in both repositories describe the current download behavior and limits.
diff --git a/docs/public/drawings.md b/docs/public/drawings.md
index e9be7c69..e448538c 100644
--- a/docs/public/drawings.md
+++ b/docs/public/drawings.md
@@ -5,6 +5,12 @@ its picture. The compiler distinguishes nominal geometry coverage, specified
limits, material and actual process qualification. Searchable PDF text and a clean
layout are presentation checks, not manufacturing approval.
+Helios exposes PDF, SVG and PPTX in **Export** for supported parts, using this same
+dimension planner. Selecting several formats downloads a ZIP. The browser projects
+the current compiled STEP and checks that authored PMI has not disappeared; it does
+not invent material, tolerances or signoffs. Use the authoring workflow below to
+supply those requirements. Assembly/Scene automatic drawings are not exposed there.
+
## Generate a dimensioned plate
```powershell
diff --git a/docs/public/web-sdk/api-reference.md b/docs/public/web-sdk/api-reference.md
index 0f645398..5523677b 100644
--- a/docs/public/web-sdk/api-reference.md
+++ b/docs/public/web-sdk/api-reference.md
@@ -2,7 +2,7 @@
The stable preview contract is `aetheris/web-editor-contract/1`.
-- `Aetheris.create(options?)` initializes the runtime. Options: `worker` (only `false`/omitted in X1), `wasmUrl`, and a diagnostics callback.
+- `Aetheris.create(options?)` initializes the runtime. Options: `worker` (`true` uses a dedicated module Worker), `wasmUrl`, and a diagnostics callback.
- `cad.info()` and `cad.capabilities()` report package/runtime/contract versions and support flags.
- `cad.compile(source, { sourceName?, signal? })` returns `{ model, diagnostics }`; compiler failures are values, not thrown private exceptions.
- `cad.language.complete(source, offset, { sourceName?, sourceRevision })` returns bounded partial-source field help for Helix and Loft. The caller must provide a nonempty revision token. The JSON-safe result contains `document`, `revision`, `context`, `replaceStart`, `replaceLength`, `fields`, and `missingRequiredFields`. Each field has `name`, `type`, `required`, `meaning`, optional `default`, and optional `choices`. Unsupported contexts return no fields. This operation does not build geometry.
@@ -14,6 +14,8 @@ The stable preview contract is `aetheris/web-editor-contract/1`.
- `model.resolveSelection(...)` and `selectionForEntity(...)` translate selection in both directions.
- `model.selectorCandidates('Face' | 'Edge')` returns source-addressable selectors from the compiled geometry source map. Candidates carry the source reference, semantic key, output role, qualification, and build revision. Runtime-only, unstable, ambiguous, and selector-less topology is excluded. The candidates describe the last valid compiled snapshot, so an editor must not apply them to a different source revision.
- `model.exportSTEP()` returns `Uint8Array`; `exportSTEPBlob()` returns a browser `Blob`.
+- `model.exportFormats` lists format identifiers, labels, descriptions, availability and rejection reasons for the compiled product kind.
+- `model.exportArtifacts(['step', 'glb'])` returns download records with `fileName`, `mediaType` and `bytes: Uint8Array`. A single format returns its native file; multiple formats return one ZIP containing all selected artifacts. Preparation is atomic: an unsupported export throws with its diagnostic and returns no partial download. Supported identifiers are `step`, `glb`, `usda`, `stl`, `obj`, `pdf`, `svg`, `pptx`. Assemblies support STEP/GLB/USDA; Scenes support GLB/USDA; mesh and automatic drawing exports currently require a part. Automatic drawings retain [the drawing compiler's completeness and PMI checks](../drawings.md), and do not invent missing manufacturing requirements. Exports require a successful current build. Presentation exports use the static authored pose, not a sampled animation or the viewport camera.
- `model.dispose()` and `cad.dispose()` release managed sessions.
Unexpected failures throw `AetherisError` with stable `code`, safe `message`, and optional developer `details`. See the shipped `index.d.ts` for exact readonly record types.
diff --git a/docs/public/web-sdk/capability-matrix.md b/docs/public/web-sdk/capability-matrix.md
index 822aa2b0..0d309d95 100644
--- a/docs/public/web-sdk/capability-matrix.md
+++ b/docs/public/web-sdk/capability-matrix.md
@@ -1,21 +1,25 @@
-# Web SDK X1 capability matrix
+# Web SDK capability matrix
-| Capability | Native | Browser WASM X1 | Notes |
+| Capability | Native | Browser WASM | Notes |
|---|---:|---:|---|
| Firmament V2 compile from memory | Yes | Yes | Same compiler/materializer |
| Solid modeling | Yes | Yes | Qualified canonical box-with-hole fixture |
-| Assembly hierarchy and mesh | Yes | Yes | Same M1 assembly pipeline; external-file definitions excluded |
+| Assembly hierarchy and mesh | Yes | Yes | Same M1 assembly pipeline; referenced source files must be supplied in explicit project snapshots |
| Display mesh | Yes | Yes | Same B-rep tessellator, synchronous browser route |
| Face/semantic selection | Yes | Yes | Triangle ranges plus occurrence IDs |
| Property inspection/edit | Yes | Bounded | Scalar template arguments and canonical box/hole properties |
| Transactional rebuild | Yes | Yes | Last valid snapshot retained |
| AP242 STEP export in memory | Yes | Yes | UTF-8 bytes; no temporary file |
+| GLB / USDA download | Yes | Yes | Existing static Part/Assembly/Scene exporters; geometry, hierarchy, supported materials and cameras |
+| STL / OBJ download | Yes | Bounded | Part-only SurfaceMeshIR route; STL requires a validated closed triangle mesh |
+| PDF / SVG / PPTX drawing download | Yes | Bounded | Automatic dimensioned plate/box family; existing completeness and PMI checks; missing requirements remain explicit |
+| Multiple export formats | Yes | Yes | One ZIP download; no partial files on failure; transient drawing/STL scratch files are removed |
| Sheet metal | Yes | No | Not qualified in browser X1 |
| FEA | Yes | No | Deferred |
| SQLite materials | Yes | No | Native vararg calls are not browser-safe |
| External STEP file import | Yes | No | Browser filesystem/resource abstraction deferred |
| Forge process/subprocess operations | Yes | No | Browser host exposes editor operations only |
-| Web Worker | N/A | No | Transport initialization does not complete in Chromium; typed rejection |
+| Web Worker | N/A | Yes | Dedicated module Worker; used by Helios for builds and exports |
| Cancellation | Yes | Pre-start only | No mid-kernel cancellation |
The browser package is currently large because it carries untrimmed transitive assemblies. Package-size optimization is deferred; capability claims do not depend on removing those assemblies.
diff --git a/docs/public/web-sdk/getting-started.md b/docs/public/web-sdk/getting-started.md
index 04b918a4..01a3d4a2 100644
--- a/docs/public/web-sdk/getting-started.md
+++ b/docs/public/web-sdk/getting-started.md
@@ -32,6 +32,6 @@ const step = await model.exportSTEP();
const download = URL.createObjectURL(new Blob([step], { type: "model/step" }));
```
-Call `model.dispose()` and `cad.dispose()` when finished. X1 runs on the page thread. `worker: true` is rejected with `worker-unavailable` until that transport is qualified.
+Call `model.dispose()` and `cad.dispose()` when finished. Use `Aetheris.create({ worker: true })` for a dedicated module Worker, as Helios does. See [the API reference](api-reference.md) for the export format catalogue and multi-format ZIP downloads.
The package is AGPL-3.0-only in X1. Contact the Aetheris project about commercial licensing; obtain legal advice for your distribution model.
diff --git a/scripts/qualify-helios-export-files.py b/scripts/qualify-helios-export-files.py
new file mode 100644
index 00000000..9d4bb978
--- /dev/null
+++ b/scripts/qualify-helios-export-files.py
@@ -0,0 +1,74 @@
+"""Inspect real Helios downloads after qualify-helios-exports.mts and CLI parity exports.
+Requires pypdf; pypdfium2 additionally renders the downloaded PDF for visual review.
+"""
+from hashlib import sha256
+from pathlib import Path
+import json
+import math
+import struct
+import xml.etree.ElementTree as ET
+import zipfile
+from pypdf import PdfReader
+
+root = Path(__file__).resolve().parent.parent / "artifacts/local/helios-exports"
+families = {
+ "inspection-plate": {"step", "glb", "usda", "stl", "obj", "pdf", "svg", "pptx"},
+ "shared-block-assembly": {"step", "glb", "usda"},
+ "scene": {"glb", "usda"},
+}
+for name, extensions in families.items():
+ with zipfile.ZipFile(root / (name + "-exports.zip")) as archive:
+ assert archive.testzip() is None
+ assert set(archive.namelist()) == {name + "." + ext for ext in extensions}
+ destination = root / name
+ destination.mkdir(exist_ok=True)
+ for entry in archive.infolist():
+ assert "/" not in entry.filename and "\\" not in entry.filename
+ (destination / entry.filename).write_bytes(archive.read(entry))
+ glb = (destination / (name + ".glb")).read_bytes()
+ magic, version, length, json_length, json_type = struct.unpack_from("<5I", glb)
+ assert magic == 0x46546C67 and version == 2 and length == len(glb) and json_type == 0x4E4F534A
+ document = json.loads(glb[20:20 + json_length])
+ assert document["asset"]["version"] == "2.0" and document["meshes"] and document["nodes"]
+ assert any(node.get("name") == "Aetheris mm Z-up to glTF m Y-up" for node in document["nodes"])
+ if name == "scene":
+ assert len(document["cameras"]) == 3
+ usd = (destination / (name + ".usda")).read_text(encoding="utf-8")
+ assert usd.startswith("#usda 1.0") and "metersPerUnit = 0.001" in usd and 'upAxis = "Z"' in usd
+
+part = root / "inspection-plate"
+step = (part / "inspection-plate.step").read_bytes()
+assert step == (root / "inspection-plate.step").read_bytes() == (root / "native-plate.step").read_bytes()
+stl = (part / "inspection-plate.stl").read_bytes()
+assert stl == (root / "native-plate.stl").read_bytes()
+triangles, = struct.unpack_from("<I", stl, 80)
+assert triangles > 0 and len(stl) == 84 + 50 * triangles
+vertices = []
+for offset in range(84, len(stl), 50):
+ values = struct.unpack_from("<12fH", stl, offset)
+ assert all(math.isfinite(v) for v in values)
+ assert abs(sum(v*v for v in values[:3]) - 1) < 1e-5
+ vertices.extend((values[3:6], values[6:9], values[9:12]))
+assert [min(v[i] for v in vertices) for i in range(3)] == [-50, -35, 0]
+assert [max(v[i] for v in vertices) for i in range(3)] == [50, 35, 8]
+assert "f " in (part / "inspection-plate.obj").read_text(encoding="utf-8")
+assert ET.parse(part / "inspection-plate.svg").getroot().tag.endswith("svg")
+reader = PdfReader(part / "inspection-plate.pdf")
+text = "\n".join(page.extract_text() for page in reader.pages)
+for required in ("THRU", "X0", "Y0", "100", "70", "NOT FOR MANUFACTURE", "INCOMPLETE REQUIREMENTS"):
+ assert required in text, required
+(root / "pdf-text.txt").write_text(text, encoding="utf-8")
+with zipfile.ZipFile(part / "inspection-plate.pptx") as deck:
+ assert deck.testzip() is None and "ppt/slides/slide1.xml" in deck.namelist()
+try:
+ import pypdfium2 as pdfium
+ document = pdfium.PdfDocument(str(part / "inspection-plate.pdf"))
+ for i in range(len(document)):
+ document[i].render(scale=1.8).to_pil().save(root / f"drawing-page-{i+1}.png")
+except ImportError:
+ print("Install pypdfium2 or render with pdftoppm for visual review.")
+evidence = {"success": True, "partFormats": len(families["inspection-plate"]), "pdfPages": len(reader.pages),
+ "stlTriangles": triangles, "stepByteIdenticalToNativeCli": True, "stlByteIdenticalToNativeCli": True,
+ "stepSha256": sha256(step).hexdigest(), "stlSha256": sha256(stl).hexdigest()}
+(root / "files.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
+print(json.dumps(evidence, indent=2))
diff --git a/scripts/qualify-helios-exports.mts b/scripts/qualify-helios-exports.mts
new file mode 100644
index 00000000..04a76f6b
--- /dev/null
+++ b/scripts/qualify-helios-exports.mts
@@ -0,0 +1,89 @@
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+const output = resolve('artifacts/local/helios-exports'); await mkdir(output, { recursive: true });
+const browser = await chromium.launch({ executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });
+try {
+ const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, acceptDownloads: true });
+ page.setDefaultTimeout(180000);
+ const errors: string[] = []; page.on('pageerror', (error: Error) => errors.push(error.message));
+ await page.goto('http://127.0.0.1:4173/local'); await page.locator('.status-ready').waitFor();
+ console.log('Helios initialized');
+ const input = page.locator('input[type="file"]');
+ const trigger = page.getByRole('button', { name: 'Export ▾', exact: true });
+ const ready = async () => { await page.waitForFunction(() => !document.querySelector<HTMLButtonElement>('.export-picker > button')?.disabled); };
+ const download = async (name: string) => {
+ const pending = page.waitForEvent('download');
+ await page.getByRole('button', { name: /^Download/ }).click();
+ const file = await pending; const failure = await file.failure(); if (failure) throw new Error(failure);
+ if (file.suggestedFilename() !== name) throw new Error(`Unexpected filename ${file.suggestedFilename()} instead of ${name}`);
+ await file.saveAs(resolve(output, name));
+ };
+ await input.setInputFiles(resolve('fixtures/Regression/DrawingGeneration/inspection-plate.firmament')); await ready();
+ await trigger.click();
+ const options = page.getByRole('checkbox');
+ if (await options.count() !== 8) throw new Error('Expected eight supported export formats');
+ for (const option of await options.all()) await option.check();
+ await page.screenshot({ path: resolve(output, 'picker.png') });
+ await download('inspection-plate-exports.zip'); console.log('All eight part formats downloaded');
+ // A single format is a direct file, not a ZIP; reuse the current accepted model.
+ await trigger.click();
+ for (const option of await options.all()) await option.uncheck();
+ await page.getByRole('checkbox', { name: /STEP AP242/ }).check();
+ await download('inspection-plate.step'); console.log('Direct STEP download passed');
+ const validPart = await readFile(resolve('fixtures/Regression/DrawingGeneration/inspection-plate.firmament'), 'utf8');
+ await page.evaluate(async (source: string) => {
+ const { WebSdkCadRuntime } = await import('/src/sdk/CadRuntime.ts');
+ const runtime = new WebSdkCadRuntime();
+ try {
+ const built = await runtime.open(source, 'direct.firmament');
+ if (!built.model) throw new Error('Direct SDK model did not build');
+ const bytes = await runtime.exportSTEP();
+ if (!new TextDecoder().decode(bytes).startsWith('ISO-10303-21;')) throw new Error('Legacy STEP method lost its contract');
+ const failed = await runtime.setSource(source.replace('diameter: 4mm', 'diametr: 4mm'), 'direct.firmament');
+ if (failed.success) throw new Error('Invalid SDK revision was accepted');
+ try { await runtime.exportArtifacts(['step']); } catch (error) {
+ if ((error as { code?: string }).code === 'export-stale-revision') return;
+ throw error;
+ }
+ throw new Error('SDK exported retained geometry after a failed rebuild');
+ } finally { await runtime.dispose(); }
+ }, validPart);
+ console.log('SDK STEP compatibility and failed-rebuild export guard passed');
+
+ await input.setInputFiles(resolve('fixtures/Canonical/WebSdk/shared-block-assembly.firmament')); await ready();
+ await trigger.click();
+ if (await page.getByRole('checkbox', { name: /STL/ }).isEnabled()) throw new Error('Assembly STL must explain its single-part boundary');
+ await page.getByRole('checkbox', { name: /glTF/ }).check(); await page.getByRole('checkbox', { name: /OpenUSD/ }).check();
+ await download('shared-block-assembly-exports.zip'); console.log('Assembly STEP/GLB/USDA downloaded');
+
+ await input.setInputFiles(['scene.firmament', 'mixed.firmament'].map(name => resolve('fixtures/Canonical/DisplayProjection', name))); await ready();
+ await trigger.click();
+ if (await page.getByRole('checkbox', { name: /STEP AP242/ }).isEnabled()) throw new Error('Scene STEP must be unavailable');
+ await page.getByRole('checkbox', { name: /glTF/ }).check(); await page.getByRole('checkbox', { name: /OpenUSD/ }).check();
+ await download('scene-exports.zip'); console.log('Scene GLB/USDA downloaded');
+
+ await input.setInputFiles(resolve('fixtures/Regression/Visualization/concept-structs.firmament')); await ready();
+ await trigger.click(); for (const option of await options.all()) if (await option.isEnabled()) await option.uncheck();
+ await page.getByRole('checkbox', { name: /PDF drawing/ }).check();
+ let downloads = 0; page.on('download', () => downloads++);
+ await page.getByRole('button', { name: /^Download/ }).click();
+ await page.getByText(/drawing-definition-incomplete/).first().waitFor(); await ready();
+ if (downloads) throw new Error('Incomplete drawing unexpectedly downloaded');
+ await page.screenshot({ path: resolve(output, 'drawing-rejection.png') });
+ await page.keyboard.press('Escape');
+ const source = await readFile(resolve('fixtures/Regression/Visualization/concept-structs.firmament'), 'utf8');
+ await input.setInputFiles({ name: 'concept-structs.firmament', mimeType: 'text/plain', buffer: Buffer.from(source.replace('distance: 1.5mm', 'distnace: 1.5mm')) });
+ await page.waitForFunction(() => document.querySelector('.viewport-caption')?.textContent?.includes('Last good model'));
+ await ready(); await trigger.click(); for (const option of await options.all()) if (await option.isEnabled()) await option.uncheck();
+ await page.getByRole('checkbox', { name: /STEP AP242/ }).check();
+ await page.getByRole('button', { name: /^Download/ }).click(); await ready();
+ if (downloads) throw new Error('Invalid draft downloaded retained geometry');
+ if (errors.length) throw new Error(JSON.stringify(errors));
+ await writeFile(resolve(output, 'browser.json'), JSON.stringify({ success: true, partFormats: 8,
+ assemblyFormats: 3, sceneFormats: 2, unsupportedDrawingRejected: true, invalidDraftExportRejected: true, errors }, null, 2));
+ console.log('Real Helios export qualification passed');
+} catch (error) { console.error(error); throw error; }
+finally { await browser.close(); }