Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add GLB export and 3D presentation commands

Yuechen Li15f3dd13b293
diff --git a/Aetheris.CLI.Tests/AssemblyGlbCommandTests.cs b/Aetheris.CLI.Tests/AssemblyGlbCommandTests.cs
new file mode 100644
index 00000000..2f3925b9
--- /dev/null
+++ b/Aetheris.CLI.Tests/AssemblyGlbCommandTests.cs
@@ -0,0 +1,27 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class AssemblyGlbCommandTests
+{
+ [Fact]
+ public void RealCliExportsAndRejectsBadOptionsWithoutOverwritingOutput()
+ {
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ Assert.NotNull(root);
+ var fixture = Path.Combine(root!.FullName, "fixtures/Canonical/AssemblyInterfaces/two-link-arm-usd.firmament");
+ var output = Path.Combine(root.FullName, "artifacts/local/tests/glb", Guid.NewGuid().ToString("N") + ".glb");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var result = CliRunner.Run(["asm", "export-glb", fixture, output, "--state", "Shoulder=35", "--json"], stdout, stderr);
+ Assert.True(result == 0, stderr.ToString());
+ var valid = File.ReadAllBytes(output);
+ using var report = JsonDocument.Parse(stdout.ToString());
+ Assert.Equal(valid.Length, report.RootElement.GetProperty("bytes").GetInt32());
+ foreach (var extra in new[] { new[] { "--state", "Typo=1" }, new[] { "--state", "Shoulder=NaN" }, new[] { "--sample", "0:Shoulder=2" } })
+ {
+ result = CliRunner.Run(["asm", "export-glb", fixture, output, .. extra], stdout, stderr);
+ Assert.NotEqual(0, result); Assert.Equal(valid, File.ReadAllBytes(output));
+ }
+ }
+}
diff --git a/Aetheris.CLI/AssemblyGlbCommand.cs b/Aetheris.CLI/AssemblyGlbCommand.cs
new file mode 100644
index 00000000..89a79968
--- /dev/null
+++ b/Aetheris.CLI/AssemblyGlbCommand.cs
@@ -0,0 +1,86 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Text.Json;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.SheetMetal;
+
+namespace Aetheris.CLI;
+
+internal static class AssemblyGlbCommand
+{
+ internal const string Usage = "aetheris asm export-glb <assembly.firmament|assembly.firmasm> [out.glb] [--state Joint=value] [--materials appearance.json] [--json]";
+
+ internal sealed record AppearanceInput(double Red = .48, double Green = .55, double Blue = .63,
+ double Metallic = .8, double Roughness = .28, string? BaseColorTexture = null, double[]? TextureCoordinates = null);
+
+ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || args[0] is "--help" or "-h")
+ { (args.Length == 0 ? stderr : stdout).WriteLine(Usage); return args.Length == 0 ? 1 : 0; }
+ try
+ {
+ var source = Path.GetFullPath(args[0]);
+ var output = Path.GetFullPath(Path.Combine("artifacts", "local", "glb", Path.GetFileNameWithoutExtension(source) + ".glb"));
+ string? materialsPath = null; var json = false;
+ var state = new Dictionary<string, double>(StringComparer.Ordinal);
+ for (var i = 1; i < args.Length; i++)
+ {
+ if (i == 1 && !args[i].StartsWith('-')) output = Path.GetFullPath(args[i]);
+ else if (args[i] == "--json") json = true;
+ else if (args[i] == "--materials" && i + 1 < args.Length) materialsPath = Path.GetFullPath(args[++i]);
+ else if (args[i] == "--state" && i + 1 < args.Length)
+ {
+ var pair = args[++i].Split('=');
+ if (pair.Length != 2 || string.IsNullOrWhiteSpace(pair[0])
+ || !double.TryParse(pair[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
+ || !double.IsFinite(value) || !state.TryAdd(pair[0], value))
+ throw new ArgumentException("GLB state requires unique Joint=finite-value (degrees or mm).");
+ }
+ else throw new ArgumentException("Unknown or incomplete GLB option: " + args[i]);
+ }
+ if (!Path.GetExtension(output).Equals(".glb", StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("Static presentation export writes .glb.");
+ if (output.Equals(source, StringComparison.OrdinalIgnoreCase) || output.Equals(materialsPath, StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("GLB output must differ from source inputs.");
+ Dictionary<string, AssemblyGlbAppearance>? appearances = null;
+ if (materialsPath is not null)
+ {
+ var input = JsonSerializer.Deserialize<Dictionary<string, AppearanceInput>>(File.ReadAllText(materialsPath), new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
+ ?? throw new ArgumentException("GLB materials must be a definition-keyed object.");
+ appearances = new(StringComparer.Ordinal);
+ foreach (var (identity, m) in input)
+ {
+ if (m is null) throw new ArgumentException("GLB material must be an object.");
+ byte[]? bytes = null; string? mime = null;
+ if (m.BaseColorTexture is not null)
+ {
+ var texturePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(materialsPath)!, m.BaseColorTexture));
+ if (output.Equals(texturePath, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("GLB output must differ from texture input.");
+ mime = Path.GetExtension(texturePath).ToLowerInvariant() switch { ".png" => "image/png", ".jpg" or ".jpeg" => "image/jpeg", _ => throw new ArgumentException("GLB textures require PNG or JPEG.") };
+ bytes = File.ReadAllBytes(texturePath);
+ }
+ appearances.Add(identity, new(new(m.Red, m.Green, m.Blue, m.Metallic, m.Roughness), m.TextureCoordinates, bytes, mime));
+ }
+ }
+ var watch = Stopwatch.StartNew();
+ var compilation = Path.GetExtension(source).Equals(".firmasm", StringComparison.OrdinalIgnoreCase)
+ ? new FirmamentAssemblyDocumentCompiler().CompileFile(source).Compilation
+ : new AssemblyM1Pipeline().CompileFile(source, File.ReadAllText(source).Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal) ? EnclosureProductFamilies.MaterializeAssemblyPart : null);
+ if (!compilation.IsSuccess) throw new InvalidOperationException(string.Join("\n", compilation.Diagnostics.Select(d => d.Code + ": " + d.Message)));
+ var compilationMilliseconds = watch.Elapsed.TotalMilliseconds; watch.Restart();
+ var pose = AssemblyKinematics.Evaluate(compilation.Ir!, state);
+ var display = AssemblyDisplayMeshExporter.Export(compilation, pose: pose);
+ var meshMilliseconds = watch.Elapsed.TotalMilliseconds; watch.Restart();
+ var bytesGlb = AssemblyGlbExporter.Serialize(display, appearances);
+ var serializationMilliseconds = watch.Elapsed.TotalMilliseconds;
+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);
+ File.WriteAllBytes(output, bytesGlb);
+ var report = new { status = "exported", format = "glb", output, definitions = display.Definitions.Count,
+ occurrences = display.Occurrences.Count, bytes = bytesGlb.Length, compilationMilliseconds, meshMilliseconds, serializationMilliseconds };
+ stdout.WriteLine(json ? JsonSerializer.Serialize(report, CliRunner.JsonOptions) : $"GLB exported: {output}; {display.Definitions.Count} shared definitions, {display.Occurrences.Count} occurrences.");
+ return 0;
+ }
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or IOException or JsonException or FormatException or OverflowException)
+ { stderr.WriteLine("assembly-glb-export-failed: " + ex.Message); return 1; }
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 9310a0de..771e0d21 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -229,6 +229,7 @@ public static class CliRunner
"analyze" => RunAnalyze(args.Skip(1).ToArray(), stdout, stderr),
"fea" => RunFea(args.Skip(1).ToArray(), stdout, stderr),
"drawing" => RunDrawing(args.Skip(1).ToArray(), stdout, stderr),
+ "presentation" => Presentation3DCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
"verify" => RunVerify(args.Skip(1).ToArray(), stdout, stderr),
"view" => RunView(args.Skip(1).ToArray(), stdout, stderr, cadmataLauncher, cliBaseDirectory),
"match" => RunMatch(args.Skip(1).ToArray(), stdout, stderr),
@@ -3733,6 +3734,8 @@ Model CanonicalPanel {
return RunAsmExportAp242(args.Skip(1).ToArray(), stdout, stderr);
if (string.Equals(args[0], "export-usd", StringComparison.Ordinal))
return AssemblyUsdCommand.Run(args.Skip(1).ToArray(), stdout, stderr);
+ if (string.Equals(args[0], "export-glb", StringComparison.Ordinal))
+ return AssemblyGlbCommand.Run(args.Skip(1).ToArray(), stdout, stderr);
stderr.WriteLine($"Unknown asm subcommand '{args[0]}'.");
stderr.WriteLine(AsmExecUsage);
@@ -5406,6 +5409,8 @@ Model CanonicalPanel {
stdout.WriteLine($" or: {AsmImportStepUsage[7..]}");
stdout.WriteLine($" or: {AsmExportAp242Usage[7..]}");
stdout.WriteLine($" or: {AssemblyUsdCommand.Usage}");
+ stdout.WriteLine($" or: {AssemblyGlbCommand.Usage}");
+ stdout.WriteLine($" or: {Presentation3DCommand.Usage}");
stdout.WriteLine();
stdout.WriteLine("Options:");
stdout.WriteLine(" --out <path> Required for 'asm export'; output directory for package artifacts.");
diff --git a/Aetheris.CLI/Presentation3DCommand.cs b/Aetheris.CLI/Presentation3DCommand.cs
new file mode 100644
index 00000000..f6e19d1d
--- /dev/null
+++ b/Aetheris.CLI/Presentation3DCommand.cs
@@ -0,0 +1,46 @@
+using System.Diagnostics;
+using System.Text.Json;
+using Aetheris.Kernel.Firmament.Drawing;
+
+namespace Aetheris.CLI;
+
+internal static class Presentation3DCommand
+{
+ internal const string Usage = "aetheris presentation compile <deck.json> [out.pptx] [--json]";
+ private sealed record Deck(string Title, IReadOnlyList<Model3DSlide> Slides,
+ double WidthMm = 338.6667, double HeightMm = 190.5);
+
+ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || args[0] is "--help" or "-h") { stdout.WriteLine(Usage); return args.Length == 0 ? 1 : 0; }
+ try
+ {
+ if (args[0] != "compile" || args.Length < 2) throw new ArgumentException(Usage);
+ var input = Path.GetFullPath(args[1]);
+ var output = Path.GetFullPath(Path.Combine("artifacts", "local", "presentations", Path.GetFileNameWithoutExtension(input) + ".pptx"));
+ var json = false;
+ for (var i = 2; i < args.Length; i++)
+ {
+ if (i == 2 && !args[i].StartsWith('-')) output = Path.GetFullPath(args[i]);
+ else if (args[i] == "--json") json = true;
+ else throw new ArgumentException("Unknown presentation option: " + args[i]);
+ }
+ if (!Path.GetExtension(output).Equals(".pptx", StringComparison.OrdinalIgnoreCase) || output.Equals(input, StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("Presentation output must be a separate .pptx file.");
+ var deck = JsonSerializer.Deserialize<Deck>(File.ReadAllText(input), new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
+ ?? throw new ArgumentException("A presentation deck object is required.");
+ if (deck.Slides is null || deck.Slides.Any(s => s is null || s.Models is null || s.Models.Any(m => m is null)))
+ throw new ArgumentException("Every slide requires an explicit Models list.");
+ var directory = Path.GetDirectoryName(input)!;
+ var slides = deck.Slides.Select(s => s with { Models = s.Models.Select(m => m with
+ { Source = Path.GetFullPath(Path.Combine(directory, m.Source)), Preview = Path.GetFullPath(Path.Combine(directory, m.Preview)) }).ToArray() }).ToArray();
+ var timer = Stopwatch.StartNew();
+ DrawingPptxWriter.WriteModel3DDeck(slides, output, deck.Title, deck.WidthMm, deck.HeightMm);
+ var report = new { status = "compiled", output, slides = slides.Length, embeddedModels = slides.Sum(s => s.Models.Count), bytes = new FileInfo(output).Length, compilationMilliseconds = timer.Elapsed.TotalMilliseconds };
+ stdout.WriteLine(json ? JsonSerializer.Serialize(report, CliRunner.JsonOptions) : $"Presentation compiled: {output}; {report.embeddedModels} embedded 3D models.");
+ return 0;
+ }
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or IOException or JsonException or OverflowException)
+ { stderr.WriteLine("presentation-3d-compile-failed: " + ex.Message); return 1; }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyGlbExportTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyGlbExportTests.cs
new file mode 100644
index 00000000..7562380e
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyGlbExportTests.cs
@@ -0,0 +1,114 @@
+using System.Buffers.Binary;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+public sealed class AssemblyGlbExportTests
+{
+ [Fact]
+ public void SharedMeshesHierarchySharpNormalsAndWorldFramesSurviveBinaryLowering()
+ {
+ var compilation = Compile("two-link-arm-usd.firmament");
+ var pose = AssemblyKinematics.Evaluate(compilation.Ir!, new Dictionary<string, double> { ["Shoulder"] = 35, ["Elbow"] = 65 });
+ var mesh = AssemblyDisplayMeshExporter.Export(compilation, pose: pose);
+ var bytes = AssemblyGlbExporter.Serialize(mesh);
+ Assert.Equal(bytes, AssemblyGlbExporter.Serialize(mesh));
+ var (json, binary) = Read(bytes); using var document = json;
+ var root = json.RootElement;
+ Assert.Equal(mesh.Definitions.Count, root.GetProperty("meshes").GetArrayLength());
+ Assert.Equal(mesh.Occurrences.Count + 1, root.GetProperty("nodes").GetArrayLength());
+ var nodes = root.GetProperty("nodes").EnumerateArray().ToArray();
+ var byName = nodes.Select((n, i) => (n, i)).ToDictionary(p => p.n.GetProperty("name").GetString()!, p => p.i);
+ double[] World(int index)
+ {
+ var local = nodes[index].GetProperty("matrix").EnumerateArray().Select(v => v.GetDouble()).ToArray();
+ var parent = Enumerable.Range(0, nodes.Length).Where(i => nodes[i].TryGetProperty("children", out var c) && c.EnumerateArray().Any(v => v.GetInt32() == index)).ToArray();
+ return parent.Length == 0 ? local : Multiply(local, World(Assert.Single(parent)));
+ }
+ foreach (var o in mesh.Occurrences)
+ {
+ var world = World(byName[o.Path]);
+ var source = Transform3D.FromRowMajor(o.Transform).Apply(new Point3D(11, 22, 33));
+ var p = new[] { 11d, 22, 33, 1 };
+ var actual = Enumerable.Range(0, 3).Select(c => Enumerable.Range(0, 4).Sum(r => p[r] * world[r * 4 + c])).ToArray();
+ Assert.Equal(source.X * .001, actual[0], 10); Assert.Equal(source.Z * .001, actual[1], 10); Assert.Equal(-source.Y * .001, actual[2], 10);
+ }
+ foreach (var (d, index) in mesh.Definitions.OrderBy(d => d.Id, StringComparer.Ordinal).Select((d, i) => (d, i)))
+ {
+ var attributes = root.GetProperty("meshes")[index].GetProperty("primitives")[0].GetProperty("attributes");
+ foreach (var (name, source) in new[] { ("POSITION", d.Positions), ("NORMAL", d.Normals) })
+ {
+ var accessor = root.GetProperty("accessors")[attributes.GetProperty(name).GetInt32()];
+ var view = root.GetProperty("bufferViews")[accessor.GetProperty("bufferView").GetInt32()];
+ var offset = view.GetProperty("byteOffset").GetInt32();
+ Assert.Equal(source.Length / 3, accessor.GetProperty("count").GetInt32());
+ for (var i = 0; i < source.Length; i++) Assert.Equal((float)source[i], BitConverter.ToSingle(binary, offset + i * 4));
+ }
+ }
+ }
+
+ [Fact]
+ public void PbrAndTextureBytesAreEmbeddedWithExplicitUvs()
+ {
+ var mesh = Triangle();
+ var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a3ioAAAAASUVORK5CYII=");
+ var appearance = new AssemblyGlbAppearance(new(.2,.3,.4,.6,.7), [0,0,1,0,0,1], png, "image/png");
+ var (json, binary) = Read(AssemblyGlbExporter.Serialize(mesh, new Dictionary<string, AssemblyGlbAppearance> { ["triangle"] = appearance }));
+ using var document = json; var root = json.RootElement;
+ var image = root.GetProperty("images")[0]; Assert.False(image.TryGetProperty("uri", out _));
+ var view = root.GetProperty("bufferViews")[image.GetProperty("bufferView").GetInt32()];
+ Assert.Equal(png, binary.Skip(view.GetProperty("byteOffset").GetInt32()).Take(view.GetProperty("byteLength").GetInt32()));
+ var pbr = root.GetProperty("materials")[0].GetProperty("pbrMetallicRoughness");
+ Assert.Equal(.6, pbr.GetProperty("metallicFactor").GetDouble()); Assert.Equal(.7, pbr.GetProperty("roughnessFactor").GetDouble());
+ Assert.Equal(.2, pbr.GetProperty("baseColorFactor")[0].GetDouble());
+ Assert.False(root.GetProperty("buffers")[0].TryGetProperty("uri", out _));
+ }
+
+ [Fact]
+ public void InvalidHierarchyUnitsNormalsIndicesAndAppearanceFailExplicitly()
+ {
+ var mesh = Triangle(); var d = mesh.Definitions[0]; var o = mesh.Occurrences[0];
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh with { Units = "m" }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh with { Occurrences = [o with { ParentId = o.Id }] }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh with { Occurrences = [o with { ParentId = "missing" }] }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh with { Definitions = [d with { Indices = [0,1,3] }] }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh with { Definitions = [d with { Normals = new double[9] }] }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh, new Dictionary<string, AssemblyGlbAppearance> { ["missing"] = new() }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh, new Dictionary<string, AssemblyGlbAppearance> { ["triangle"] = new(new(Roughness: double.NaN)) }));
+ Assert.Throws<InvalidOperationException>(() => AssemblyGlbExporter.Serialize(mesh, new Dictionary<string, AssemblyGlbAppearance> { ["triangle"] = new(BaseColorTexture: [1,2,3], TextureMimeType: "image/png") }));
+ }
+
+ [Theory]
+ [InlineData("IndustrialAtlas/atlas-industrial.firmament")]
+ [InlineData("GuitarX0/guitar.firmasm")]
+ public void PresentationWitnessUsesRealDisplayPath(string path)
+ {
+ var fullPath = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/" + path);
+ var compilation = path.EndsWith(".firmasm", StringComparison.Ordinal)
+ ? new FirmamentAssemblyDocumentCompiler().CompileFile(fullPath).Compilation : new AssemblyM1Pipeline().CompileFile(fullPath);
+ Assert.True(compilation.IsSuccess, string.Join("\n", compilation.Diagnostics));
+ var display = AssemblyDisplayMeshExporter.Export(compilation);
+ var (json, _) = Read(AssemblyGlbExporter.Serialize(display)); using var document = json;
+ Assert.Equal(display.Definitions.Count, json.RootElement.GetProperty("meshes").GetArrayLength());
+ Assert.Equal(display.Occurrences.Count + 1, json.RootElement.GetProperty("nodes").GetArrayLength());
+ Assert.True(display.Definitions.Count > 20); Assert.True(display.Occurrences.Count > 50);
+ }
+
+ private static AssemblyM1CompilationResult Compile(string path) => new AssemblyM1Pipeline().CompileFile(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/" + path));
+ private static AssemblyDisplayMeshDocument Triangle() => new("aetheris/assembly-display-mesh/1", "Triangle", "mm",
+ [new("d", "triangle", [0,0,0,10,0,0,0,10,0], [0,0,1,0,0,1,0,0,1], [0,1,2])],
+ [new("o", "Triangle", null, "d", Transform3D.Identity.ToRowMajor())]);
+ private static (JsonDocument, byte[]) Read(byte[] bytes)
+ {
+ Assert.Equal(0x46546C67u, BinaryPrimitives.ReadUInt32LittleEndian(bytes));
+ Assert.Equal(2u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(4)));
+ Assert.Equal((uint)bytes.Length, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(8)));
+ var length = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(12));
+ Assert.Equal(0, length % 4); Assert.Equal(0x4E4F534Au, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(16)));
+ Assert.Equal(0x004E4942u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(24 + length)));
+ return (JsonDocument.Parse(bytes.AsMemory(20, length)), bytes[(28 + length)..]);
+ }
+ private static double[] Multiply(double[] a, double[] b) => Enumerable.Range(0, 16).Select(i => Enumerable.Range(0, 4).Sum(k => a[i / 4 * 4 + k] * b[k * 4 + i % 4])).ToArray();
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/DrawingPptxModel3DTests.cs b/Aetheris.Kernel.Firmament.Tests/DrawingPptxModel3DTests.cs
new file mode 100644
index 00000000..dac9c524
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/DrawingPptxModel3DTests.cs
@@ -0,0 +1,62 @@
+using System.IO.Compression;
+using System.Xml.Linq;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Drawing;
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Validation;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class DrawingPptxModel3DTests
+{
+ [Fact]
+ public void CompilerEmbedsExactAssetsWithOffice2019SchemaAndOracleStructure()
+ {
+ using var temporary = new TemporaryDirectory();
+ var source = Path.Combine(temporary.Path, "triangle.glb"); var preview = Path.Combine(temporary.Path, "preview.png");
+ var display = new AssemblyDisplayMeshDocument("aetheris/assembly-display-mesh/1", "Triangle", "mm",
+ [new("d", "Triangle", [0,0,0,10,0,0,0,10,0], [0,0,1,0,0,1,0,0,1], [0,1,2])],
+ [new("o", "Triangle", null, "d", Transform3D.Identity.ToRowMajor())]);
+ var glb = AssemblyGlbExporter.Serialize(display); File.WriteAllBytes(source, glb);
+ var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a3ioAAAAASUVORK5CYII="); File.WriteAllBytes(preview, png);
+ var model = new Model3D(source, preview, 100,60,110,110, new(0,0,0,100,20,30,0), "Triangle <3D>");
+ var slides = new[] { new Model3DSlide("Editable title", "Positioning", [model, model with { X=12, Width=70 }]) };
+ var path = Path.Combine(temporary.Path,"test.pptx"); var second = Path.Combine(temporary.Path,"second.pptx");
+ DrawingPptxWriter.WriteModel3DDeck(slides, path); DrawingPptxWriter.WriteModel3DDeck(slides, second);
+ Assert.Equal(File.ReadAllBytes(path), File.ReadAllBytes(second));
+ using (var document = PresentationDocument.Open(path, false))
+ {
+ var errors = new OpenXmlValidator(FileFormatVersions.Office2019).Validate(document).ToArray();
+ Assert.True(errors.Length == 0, string.Join("\n", errors.Select(e => $"{e.Part?.Uri}: {e.Path?.XPath}: {e.Description}")));
+ }
+ using var zip = ZipFile.OpenRead(path);
+ byte[] ReadBytes(string name) { using var stream=zip.GetEntry(name)!.Open(); using var buffer=new MemoryStream(); stream.CopyTo(buffer); return buffer.ToArray(); }
+ Assert.Equal(glb, ReadBytes("ppt/media/model3d-1-1.glb")); Assert.Equal(png, ReadBytes("ppt/media/model3d-1-1.png"));
+ var slide = XDocument.Parse(System.Text.Encoding.UTF8.GetString(ReadBytes("ppt/slides/slide1.xml")));
+ var rels = XDocument.Parse(System.Text.Encoding.UTF8.GetString(ReadBytes("ppt/slides/_rels/slide1.xml.rels")));
+ Assert.DoesNotContain(rels.Descendants(), e => (string?)e.Attribute("TargetMode") == "External");
+ Assert.Equal(2, rels.Descendants().Count(e => ((string?)e.Attribute("Type"))?.EndsWith("/model3d", StringComparison.Ordinal) == true));
+ XNamespace am3d="http://schemas.microsoft.com/office/drawing/2017/model3d";
+ var oracle = XDocument.Load(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Presentation3D/office-model3d-oracle.xml"));
+ var expected = oracle.Descendants(am3d+"model3d").Single().DescendantsAndSelf().Select(e=>e.Name).ToArray();
+ Assert.Equal(expected, slide.Descendants(am3d+"model3d").First().DescendantsAndSelf().Select(e=>e.Name));
+ XNamespace mc="http://schemas.openxmlformats.org/markup-compatibility/2006";
+ Assert.Equal(2, slide.Descendants(mc+"Fallback").Count());
+ Assert.DoesNotContain(temporary.Path, slide.ToString(), StringComparison.Ordinal);
+ var valid = File.ReadAllBytes(path);
+ Assert.Throws<ArgumentException>(() => DrawingPptxWriter.WriteModel3DDeck([new("Bad", "", [model with { Width = double.NaN }])], path));
+ Assert.Equal(valid, File.ReadAllBytes(path));
+ File.WriteAllText(source, "invalid glb");
+ Assert.Throws<ArgumentException>(() => DrawingPptxWriter.WriteModel3DDeck(slides,path));
+ Assert.Equal(valid, File.ReadAllBytes(path));
+ }
+
+ private sealed class TemporaryDirectory : IDisposable
+ {
+ public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aetheris-model3d-"+Guid.NewGuid().ToString("N"));
+ public TemporaryDirectory() => Directory.CreateDirectory(Path);
+ public void Dispose() => Directory.Delete(Path, true);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
new file mode 100644
index 00000000..a8554205
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
@@ -0,0 +1,159 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Kernel.Firmament.Assembly;
+
+/// <summary>Explicit presentation appearance. UVs follow the display definition's vertices;
+/// texture bytes are embedded, never linked. Color factors are linear RGB.</summary>
+public sealed record AssemblyGlbAppearance(AssemblyUsdMaterial? Material = null,
+ double[]? TextureCoordinates = null, byte[]? BaseColorTexture = null, string? TextureMimeType = null);
+
+/// <summary>Static glTF 2.0 binary lowering of qualified display geometry.
+/// BRep/STEP remains engineering authority. No tessellation, shading graph, or animation here.</summary>
+public static class AssemblyGlbExporter
+{
+ public static byte[] Export(AssemblyM1CompilationResult compilation,
+ IReadOnlyDictionary<string, double>? state = null,
+ IReadOnlyDictionary<string, AssemblyGlbAppearance>? appearances = null)
+ {
+ if (!compilation.IsSuccess || compilation.Ir is null)
+ throw new InvalidOperationException("assembly-glb-invalid-compilation");
+ var pose = AssemblyKinematics.Evaluate(compilation.Ir, state ?? new Dictionary<string, double>());
+ return Serialize(AssemblyDisplayMeshExporter.Export(compilation, pose: pose), appearances);
+ }
+
+ public static byte[] Serialize(AssemblyDisplayMeshDocument display,
+ IReadOnlyDictionary<string, AssemblyGlbAppearance>? appearances = null)
+ {
+ if (display.Units != "mm" || display.Definitions.Count == 0 || display.Occurrences.Count == 0)
+ throw new InvalidOperationException("assembly-glb-invalid-document");
+ var definitions = display.Definitions.OrderBy(d => d.Id, StringComparer.Ordinal).ToArray();
+ var occurrences = display.Occurrences.OrderBy(o => o.Path, StringComparer.Ordinal).ToArray();
+ var definitionIds = definitions.Select((d, i) => (d.Id, i)).ToDictionary(p => p.Id, p => p.i, StringComparer.Ordinal);
+ var occurrenceIds = occurrences.Select((o, i) => (o.Id, i)).ToDictionary(p => p.Id, p => p.i, StringComparer.Ordinal);
+ if (appearances?.Keys.Any(key => !definitions.Any(d => d.Identity == key)) == true)
+ throw new InvalidOperationException("assembly-glb-material-definition-unknown");
+ // Validate the entire forest before allocating binary payloads; cycles and missing parents
+ // must never silently drop geometry or create invalid glTF trees.
+ foreach (var o in occurrences)
+ {
+ ValidateTransform(o.Transform);
+ if (o.DefinitionId is not null && !definitionIds.ContainsKey(o.DefinitionId))
+ throw new InvalidOperationException("assembly-glb-missing-definition");
+ var visited = new HashSet<string>(StringComparer.Ordinal) { o.Id };
+ var parent = o.ParentId;
+ while (parent is not null)
+ {
+ if (!visited.Add(parent) || !occurrenceIds.TryGetValue(parent, out var p))
+ throw new InvalidOperationException("assembly-glb-invalid-hierarchy");
+ parent = occurrences[p].ParentId;
+ }
+ }
+ using var binary = new MemoryStream();
+ using var writer = new BinaryWriter(binary);
+ var views = new List<object>(); var accessors = new List<object>();
+ var meshes = new List<object>(); var materials = new List<object>();
+ var images = new List<object>(); var textures = new List<object>();
+ int AddView(Action write, int? target = null)
+ {
+ while (binary.Position % 4 != 0) writer.Write((byte)0);
+ var start = checked((int)binary.Position); write();
+ var view = new Dictionary<string, object> { ["buffer"] = 0, ["byteOffset"] = start, ["byteLength"] = checked((int)binary.Position - start) };
+ if (target is not null) view["target"] = target.Value;
+ views.Add(view); return views.Count - 1;
+ }
+ int Floats(double[] values, int components, bool bounds = false)
+ {
+ var floats = values.Select(v => (float)v).ToArray();
+ if (floats.Any(v => !float.IsFinite(v))) throw new InvalidOperationException("assembly-glb-float-overflow");
+ var view = AddView(() => { foreach (var v in floats) writer.Write(v); }, 34962);
+ var accessor = new Dictionary<string, object> { ["bufferView"] = view, ["componentType"] = 5126, ["count"] = values.Length / components, ["type"] = "VEC" + components };
+ if (bounds)
+ {
+ accessor["min"] = Enumerable.Range(0, components).Select(c => floats.Where((_, i) => i % components == c).Min()).ToArray();
+ accessor["max"] = Enumerable.Range(0, components).Select(c => floats.Where((_, i) => i % components == c).Max()).ToArray();
+ }
+ accessors.Add(accessor); return accessors.Count - 1;
+ }
+ foreach (var d in definitions)
+ {
+ var count = d.Positions.Length / 3;
+ if (count == 0 || d.Positions.Length % 3 != 0 || d.Normals.Length != d.Positions.Length
+ || d.Indices.Length == 0 || d.Indices.Length % 3 != 0 || d.Indices.Any(i => i < 0 || i >= count)
+ || d.Positions.Concat(d.Normals).Any(v => !double.IsFinite(v)))
+ throw new InvalidOperationException("assembly-glb-invalid-mesh:" + d.Identity);
+ for (var i = 0; i < d.Normals.Length; i += 3)
+ if (Math.Abs(Math.Sqrt(d.Normals[i]*d.Normals[i] + d.Normals[i+1]*d.Normals[i+1] + d.Normals[i+2]*d.Normals[i+2]) - 1) > 1e-4)
+ throw new InvalidOperationException("assembly-glb-invalid-normal:" + d.Identity);
+ var appearance = appearances?.GetValueOrDefault(d.Identity) ?? new();
+ var m = appearance.Material ?? new();
+ if (new[] { m.Red, m.Green, m.Blue, m.Metallic, m.Roughness }.Any(v => !double.IsFinite(v) || v < 0 || v > 1))
+ throw new InvalidOperationException("assembly-glb-invalid-material");
+ var pbr = new Dictionary<string, object> { ["baseColorFactor"] = new[] { m.Red, m.Green, m.Blue, 1 }, ["metallicFactor"] = m.Metallic, ["roughnessFactor"] = m.Roughness };
+ var attributes = new Dictionary<string, object> { ["POSITION"] = Floats(d.Positions, 3, true), ["NORMAL"] = Floats(d.Normals, 3) };
+ if (appearance.BaseColorTexture is not null)
+ {
+ var bytes = appearance.BaseColorTexture;
+ var png = bytes.Length >= 8 && bytes.AsSpan(0, 8).SequenceEqual(new byte[] {137,80,78,71,13,10,26,10});
+ var jpeg = bytes.Length >= 3 && bytes[0] == 255 && bytes[1] == 216 && bytes[2] == 255;
+ if (!(png && appearance.TextureMimeType == "image/png" || jpeg && appearance.TextureMimeType == "image/jpeg")
+ || appearance.TextureCoordinates is null || appearance.TextureCoordinates.Length != count * 2
+ || appearance.TextureCoordinates.Any(v => !double.IsFinite(v)))
+ throw new InvalidOperationException("assembly-glb-invalid-texture");
+ attributes["TEXCOORD_0"] = Floats(appearance.TextureCoordinates, 2);
+ images.Add(new { bufferView = AddView(() => writer.Write(bytes)), mimeType = appearance.TextureMimeType });
+ textures.Add(new { source = images.Count - 1 });
+ pbr["baseColorTexture"] = new { index = textures.Count - 1 };
+ }
+ else if (appearance.TextureCoordinates is not null || appearance.TextureMimeType is not null)
+ throw new InvalidOperationException("assembly-glb-texture-missing");
+ materials.Add(new { name = d.Identity, pbrMetallicRoughness = pbr });
+ var indexView = AddView(() => { foreach (var index in d.Indices) writer.Write((uint)index); }, 34963);
+ var indexAccessor = accessors.Count;
+ accessors.Add(new { bufferView = indexView, componentType = 5125, count = d.Indices.Length, type = "SCALAR" });
+ meshes.Add(new { name = d.Identity, primitives = new[] { new { attributes, indices = indexAccessor, material = materials.Count - 1 } }, extras = new { definitionIdentity = d.Identity, meshPipeline = d.MeshPipeline } });
+ }
+ var nodes = new List<object>();
+ foreach (var o in occurrences)
+ {
+ // Historical row-vector matrix storage is already the column-major array
+ // of its transpose, exactly what glTF consumes. Do not transpose it again.
+ var local = Transform3D.FromRowMajor(o.Transform);
+ if (o.ParentId is not null) local *= Transform3D.FromRowMajor(occurrences[occurrenceIds[o.ParentId]].Transform).Inverse();
+ var node = new Dictionary<string, object> { ["name"] = o.Path, ["matrix"] = local.ToRowMajor(), ["extras"] = new { occurrenceIdentity = o.Id } };
+ if (o.DefinitionId is not null) node["mesh"] = definitionIds[o.DefinitionId];
+ var children = occurrences.Where(c => c.ParentId == o.Id).Select(c => occurrenceIds[c.Id]).ToArray();
+ if (children.Length > 0) node["children"] = children;
+ nodes.Add(node);
+ }
+ // One explicit boundary converts Z-up millimetres to right-handed Y-up metres:
+ // (x,y,z) -> .001 * (x,z,-y). All original local frames remain inspectable.
+ var roots = occurrences.Where(o => o.ParentId is null).Select(o => occurrenceIds[o.Id]).ToArray();
+ nodes.Add(new { name = "Aetheris mm Z-up to glTF m Y-up", matrix = new double[] {.001,0,0,0, 0,0,-.001,0, 0,.001,0,0, 0,0,0,1}, children = roots });
+ var document = new Dictionary<string, object>
+ {
+ ["asset"] = new { version = "2.0", generator = "Aetheris PRESENTATION-3D-X0", extras = new { modelName = display.Name, authority = "BRep/STEP; GLB is a presentation asset", sourceProject = "Aetheris" } },
+ ["scene"] = 0, ["scenes"] = new[] { new { name = display.Name, nodes = new[] { nodes.Count - 1 } } },
+ ["nodes"] = nodes, ["meshes"] = meshes, ["materials"] = materials,
+ ["accessors"] = accessors, ["bufferViews"] = views, ["buffers"] = new[] { new { byteLength = checked((int)binary.Length) } }
+ };
+ if (images.Count > 0) { document["images"] = images; document["textures"] = textures; }
+ var json = JsonSerializer.SerializeToUtf8Bytes(document);
+ using var result = new MemoryStream(); using var output = new BinaryWriter(result);
+ var jsonLength = (json.Length + 3) & ~3; var binaryLength = checked(((int)binary.Length + 3) & ~3);
+ output.Write(0x46546C67u); output.Write(2u); output.Write(checked((uint)(28L + jsonLength + binaryLength)));
+ output.Write(jsonLength); output.Write(0x4E4F534Au); output.Write(json);
+ for (var i = json.Length; i < jsonLength; i++) output.Write((byte)32);
+ output.Write(binaryLength); output.Write(0x004E4942u); output.Write(binary.ToArray());
+ for (var i = binary.Length; i < binaryLength; i++) output.Write((byte)0);
+ return result.ToArray();
+ }
+
+ private static void ValidateTransform(double[] m)
+ {
+ var t = Transform3D.FromRowMajor(m);
+ if (Math.Abs(m[3]) > 1e-12 || Math.Abs(m[7]) > 1e-12 || Math.Abs(m[11]) > 1e-12 || Math.Abs(m[15] - 1) > 1e-12
+ || t.Apply(new Vector3D(1,0,0)).Cross(t.Apply(new Vector3D(0,1,0))).Dot(t.Apply(new Vector3D(0,0,1))) <= 0)
+ throw new InvalidOperationException("assembly-glb-invalid-transform");
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxModel3D.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxModel3D.cs
new file mode 100644
index 00000000..38caac09
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxModel3D.cs
@@ -0,0 +1,126 @@
+using System.Buffers.Binary;
+using System.Globalization;
+using System.IO.Compression;
+using System.Xml.Linq;
+
+namespace Aetheris.Kernel.Firmament.Drawing;
+
+/// <summary>Deliberate static Office view. Coordinates are glTF metres; presentation
+/// normalization affects camera framing only, never the embedded engineering-derived asset.</summary>
+public sealed record Model3DView(double CenterXMetres, double CenterYMetres, double CenterZMetres,
+ double PresentationScale, double RotationXDegrees, double RotationYDegrees, double RotationZDegrees,
+ double CameraDistanceMetres = 1.8, double FieldOfViewDegrees = 45);
+
+/// <summary>A real embedded interactive 3D object, with a required PNG preview.
+/// Slide placement is in millimetres, like the existing drawing compiler.</summary>
+public sealed record Model3D(string Source, string Preview, double X, double Y, double Width, double Height,
+ Model3DView Camera, string Name = "Aetheris 3D Model");
+public sealed record Model3DSlide(string Title, string Subtitle, IReadOnlyList<Model3D> Models, string? Caption = null);
+
+public static partial class DrawingPptxWriter
+{
+ private const string ModelNamespace = "http://schemas.microsoft.com/office/drawing/2017/model3d";
+ private const string ModelRelationship = "http://schemas.microsoft.com/office/2017/06/relationships/model3d";
+
+ /// <summary>Bounded presentation API over the existing slide builder and OPC writer.
+ /// Packaging follows the desktop-authored PRESENTATION-3D-X0 reference oracle.</summary>
+ public static void WriteModel3DDeck(IReadOnlyList<Model3DSlide> slides, string path,
+ string title = "Aetheris interactive 3D", double widthMm = 338.6667, double heightMm = 190.5)
+ {
+ if (slides.Count == 0 || !double.IsFinite(widthMm) || !double.IsFinite(heightMm) || widthMm <= 0 || heightMm <= 0)
+ throw new ArgumentException("A finite, nonempty deck is required.");
+ var media = new List<(int Slide, int Index, byte[] Model, byte[] Preview)>();
+ var xml = new List<string>();
+ for (var s = 0; s < slides.Count; s++)
+ {
+ var slide = slides[s]; var builder = new SlideBuilder(widthMm, heightMm);
+ builder.Text("Presentation.Title", slide.Title, 12, 10, widthMm - 24, 25, 11.3, bold: true);
+ builder.Text("Presentation.Positioning", slide.Subtitle, 12, 39, widthMm - 24, 18, 6);
+ for (var m = 0; m < slide.Models.Count; m++)
+ {
+ var model = slide.Models[m]; ValidateModelView(model, widthMm, heightMm);
+ var sourcePath = Path.GetFullPath(model.Source); var previewPath = Path.GetFullPath(model.Preview);
+ if (Path.GetFullPath(path).Equals(sourcePath, StringComparison.OrdinalIgnoreCase) || Path.GetFullPath(path).Equals(previewPath, StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("PPTX output must differ from its source assets.");
+ var modelBytes = File.ReadAllBytes(sourcePath); var previewBytes = File.ReadAllBytes(previewPath);
+ if (modelBytes.Length < 28 || BinaryPrimitives.ReadUInt32LittleEndian(modelBytes) != 0x46546C67u
+ || BinaryPrimitives.ReadUInt32LittleEndian(modelBytes.AsSpan(4)) != 2
+ || BinaryPrimitives.ReadUInt32LittleEndian(modelBytes.AsSpan(8)) != modelBytes.Length)
+ throw new ArgumentException("Model3D requires a glTF 2.0 GLB asset.");
+ if (previewBytes.Length < 24 || !previewBytes.AsSpan(0,8).SequenceEqual(new byte[] {137,80,78,71,13,10,26,10}))
+ throw new ArgumentException("Model3D requires a PNG fallback preview.");
+ media.Add((s, m, modelBytes, previewBytes));
+ builder.Model(model, $"rId{2 + m * 2}", $"rId{3 + m * 2}");
+ }
+ if (slide.Caption is not null) builder.Text("Presentation.Caption", slide.Caption, 12, heightMm - 17, widthMm - 24, 14, 3.2);
+ xml.Add(builder.Build());
+ }
+ // All assets and views are checked before the existing package writer touches output.
+ WritePackage(path, xml, widthMm, heightMm, title);
+ using var archive = ZipFile.Open(path, ZipArchiveMode.Update);
+ XNamespace ct = "http://schemas.openxmlformats.org/package/2006/content-types";
+ var types = XDocument.Parse(Read(archive.GetEntry("[Content_Types].xml")!));
+ types.Root!.Add(new XElement(ct + "Default", new XAttribute("Extension", "glb"), new XAttribute("ContentType", "model/gltf.binary")));
+ types.Root.Add(new XElement(ct + "Default", new XAttribute("Extension", "png"), new XAttribute("ContentType", "image/png")));
+ archive.GetEntry("[Content_Types].xml")!.Delete(); Add(archive, "[Content_Types].xml", types.ToString(SaveOptions.DisableFormatting));
+ for (var s = 0; s < slides.Count; s++)
+ {
+ XNamespace rel = "http://schemas.openxmlformats.org/package/2006/relationships";
+ var relationships = XDocument.Parse(SlideRelationships());
+ foreach (var item in media.Where(p => p.Slide == s))
+ {
+ var suffix = $"{s+1}-{item.Index+1}";
+ var modelName = "model3d-" + suffix + ".glb"; var imageName = "model3d-" + suffix + ".png";
+ AddBinary(archive, "ppt/media/" + modelName, item.Model); AddBinary(archive, "ppt/media/" + imageName, item.Preview);
+ relationships.Root!.Add(new XElement(rel + "Relationship", new XAttribute("Id", $"rId{2+item.Index*2}"), new XAttribute("Type", ModelRelationship), new XAttribute("Target", "../media/" + modelName)));
+ relationships.Root.Add(new XElement(rel + "Relationship", new XAttribute("Id", $"rId{3+item.Index*2}"), new XAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"), new XAttribute("Target", "../media/" + imageName)));
+ }
+ var name = $"ppt/slides/_rels/slide{s+1}.xml.rels";
+ archive.GetEntry(name)!.Delete(); Add(archive, name, relationships.ToString(SaveOptions.DisableFormatting));
+ }
+ }
+
+ private static void AddBinary(ZipArchive archive, string name, byte[] bytes)
+ { var entry = archive.CreateEntry(name, CompressionLevel.Optimal); entry.LastWriteTime = PackageTime; using var stream = entry.Open(); stream.Write(bytes); }
+
+ private static void ValidateModelView(Model3D m, double width, double height)
+ {
+ var v = m.Camera ?? throw new ArgumentException("Model3D requires a deliberate camera.");
+ if (new[] { m.X,m.Y,m.Width,m.Height,v.CenterXMetres,v.CenterYMetres,v.CenterZMetres,v.PresentationScale,v.RotationXDegrees,v.RotationYDegrees,v.RotationZDegrees,v.CameraDistanceMetres,v.FieldOfViewDegrees }.Any(n => !double.IsFinite(n))
+ || m.X < 0 || m.Y < 0 || m.Width <= 0 || m.Height <= 0 || m.X + m.Width > width || m.Y + m.Height > height
+ || v.PresentationScale <= 0 || v.CameraDistanceMetres <= 0 || v.FieldOfViewDegrees <= 0 || v.FieldOfViewDegrees >= 180)
+ throw new ArgumentException("Model3D placement or camera is invalid.");
+ }
+
+ private sealed partial class SlideBuilder
+ {
+ public void Model(Model3D m, string modelId, string imageId)
+ {
+ var shapeId = id++; var v = m.Camera;
+ static string Number(double value) => checked((long)Math.Round(value, MidpointRounding.AwayFromZero)).ToString(CultureInfo.InvariantCulture);
+ string Metres(double value) => Number(value * 36_000_000);
+ string Degrees(double value) => Number(value * 60_000);
+ var offset = $"<a:off x=\"{Mm(m.X)}\" y=\"{Mm(m.Y)}\"/>";
+ var extent = $"<a:ext cx=\"{Mm(m.Width)}\" cy=\"{Mm(m.Height)}\"/>";
+ var nonvisual = $"<p:cNvPr id=\"{shapeId}\" name=\"{X(m.Name)}\"/>";
+ // Namespace, child order, lighting preset, raster relationship and
+ // AlternateContent branch mirror the desktop-authored reference package.
+ shapes.Append($"""
+ <mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:am3d="{ModelNamespace}">
+ <mc:Choice Requires="am3d"><p:graphicFrame><p:nvGraphicFramePr>{nonvisual}<p:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>
+ <p:xfrm>{offset}{extent}</p:xfrm><a:graphic><a:graphicData uri="{ModelNamespace}"><am3d:model3d r:embed="{modelId}">
+ <am3d:spPr><a:xfrm><a:off x="0" y="0"/>{extent}</a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></am3d:spPr>
+ <am3d:camera><am3d:pos x="0" y="0" z="{Metres(v.CameraDistanceMetres)}"/><am3d:up dx="0" dy="36000000" dz="0"/><am3d:lookAt x="0" y="0" z="0"/><am3d:perspective fov="{Degrees(v.FieldOfViewDegrees)}"/></am3d:camera>
+ <am3d:trans><am3d:meterPerModelUnit n="{Number(v.PresentationScale*1_000_000)}" d="1000000"/><am3d:preTrans dx="{Metres(-v.CenterXMetres*v.PresentationScale)}" dy="{Metres(-v.CenterYMetres*v.PresentationScale)}" dz="{Metres(-v.CenterZMetres*v.PresentationScale)}"/><am3d:scale><am3d:sx n="1000000" d="1000000"/><am3d:sy n="1000000" d="1000000"/><am3d:sz n="1000000" d="1000000"/></am3d:scale><am3d:rot ax="{Degrees(v.RotationXDegrees)}" ay="{Degrees(v.RotationYDegrees)}" az="{Degrees(v.RotationZDegrees)}"/><am3d:postTrans dx="0" dy="0" dz="0"/></am3d:trans>
+ <am3d:raster rName="Aetheris.Blender" rVer="PRESENTATION-3D-X0"><am3d:blip r:embed="{imageId}"/></am3d:raster><am3d:objViewport viewportSz="{Mm(Math.Min(m.Width,m.Height))}"/>
+ <am3d:ambientLight><am3d:clr><a:scrgbClr r="50000" g="50000" b="50000"/></am3d:clr><am3d:illuminance n="500000" d="1000000"/></am3d:ambientLight>
+ <am3d:ptLight rad="0"><am3d:clr><a:scrgbClr r="100000" g="75000" b="50000"/></am3d:clr><am3d:intensity n="9765625" d="1000000"/><am3d:pos x="21959998" y="70920001" z="16344003"/></am3d:ptLight>
+ <am3d:ptLight rad="0"><am3d:clr><a:scrgbClr r="40000" g="60000" b="95000"/></am3d:clr><am3d:intensity n="12250000" d="1000000"/><am3d:pos x="-37964106" y="51130435" z="57631972"/></am3d:ptLight>
+ <am3d:ptLight rad="0"><am3d:clr><a:scrgbClr r="86837" g="72700" b="100000"/></am3d:clr><am3d:intensity n="3125000" d="1000000"/><am3d:pos x="-37739122" y="58056624" z="-34769649"/></am3d:ptLight>
+ </am3d:model3d></a:graphicData></a:graphic></p:graphicFrame></mc:Choice>
+ <mc:Fallback><p:pic><p:nvPicPr>{nonvisual}<p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="{imageId}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr><a:xfrm>{offset}{extent}</a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic></mc:Fallback>
+ </mc:AlternateContent>
+ """);
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs
index 20d786f9..fcdd5856 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs
@@ -8,7 +8,7 @@ using Aetheris.Collaboration;
namespace Aetheris.Kernel.Firmament.Drawing;
/// <summary>Deterministic, offline OPC/Open XML lowering from authoritative DrawingIR to native PowerPoint objects.</summary>
-public static class DrawingPptxWriter
+public static partial class DrawingPptxWriter
{
private const long EmuPerMillimetre = 36_000;
private static readonly DateTimeOffset PackageTime = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
@@ -197,7 +197,7 @@ public static class DrawingPptxWriter
private static string X(string value) => SecurityElement.Escape(value) ?? string.Empty;
private static string Safe(string value) => Regex.Replace(value, @"[^A-Za-z0-9_.-]", "_");
- private sealed class SlideBuilder
+ private sealed partial class SlideBuilder
{
private readonly double width, height; private readonly StringBuilder shapes = new(); private uint id = 2;
public SlideBuilder(double width, double height) { this.width = width; this.height = height; }
diff --git a/docs/public/firmament/glb.md b/docs/public/firmament/glb.md
new file mode 100644
index 00000000..02c81eea
--- /dev/null
+++ b/docs/public/firmament/glb.md
@@ -0,0 +1,58 @@
+# Static GLB presentation export
+
+Aetheris exports GLB from the same compiled assembly display meshes used by USD.
+BRep and STEP retain engineering authority. GLB carries downstream presentation
+geometry for web, DCC, game assets, and presentations.
+
+```powershell
+dotnet run --project Aetheris.CLI -c Release -- asm export-glb `
+ fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament `
+ artifacts/local/presentation-3d-x0/atlas-display.glb `
+ --materials fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/appearance.json `
+ --state Shoulder=-75 --state Elbow=-140 --state GripLeft=10 --state GripRight=10 --json
+```
+
+The output defaults to ignored `artifacts/local/glb/`. `.firmasm` assemblies are
+also supported. Definitions become shared indexed triangle meshes. Occurrences
+retain their hierarchy and rigid local transforms. Separate face normals retain
+sharp features. One root transform converts right-handed Z-up millimetres to
+right-handed Y-up metres: `(x,y,z) → .001 × (x,z,-y)`.
+
+Appearance JSON maps exact definition identities to `red`, `green`, `blue`,
+`metallic`, and `roughness` values in `[0,1]`. RGB factors are linear, as in the
+existing USD preview mapping. Optional `baseColorTexture` names a PNG/JPEG relative
+to the appearance file, and `textureCoordinates` supplies two values per display
+vertex in glTF UV convention. Images are physically embedded in GLB, so moving the
+asset requires no external files. UV seams must already be represented by separate
+display vertices. Invalid units, frames, normals, indices, hierarchy, materials,
+and texture bindings fail explicitly.
+
+The polished X0 witnesses use their existing Aetheris-generated USD/Blender
+presentation scenes. `scripts/export-presentation-scene.py` preserves product
+positions and polygons, embeds the ATLAS maker label, and bakes the guitar's
+existing procedural sunburst/wood base color. It does not translate general
+material graphs or alter guitar geometry. Procedural grain bump is omitted.
+
+ATLAS is an independent Aetheris demo robot. Aetheris is not affiliated with,
+endorsed by, or associated with Boston Dynamics. The shared name is coincidental.
+
+The existing C# slide writer supports `Model3D(Source, Preview, X, Y, Width,
+Height, Camera, Name)` through `DrawingPptxWriter.WriteModel3DDeck`. Placement is
+in millimetres; `Model3DView` specifies the glTF centre in metres, presentation
+scale, Euler rotation and camera distance/field of view. Each object requires a
+PNG preview. The compiler physically embeds both assets and emits the Office
+3D object with a static fallback.
+
+```powershell
+dotnet run --project Aetheris.CLI -c Release -- presentation compile `
+ fixtures/Canonical/Presentation3D/interactive-3d-demo.json `
+ artifacts/local/presentation-3d-x0/interactive-3d-demo.pptx --json
+```
+
+Paths in the JSON authoring input resolve relative to that input. After
+compilation, the PPTX needs no external model or image files. Desktop PowerPoint
+rotation and save/reopen qualification is separate from package/schema checks.
+
+See [PRESENTATION-3D-X0](../../release/PRESENTATION-3D-X0.md) for artifact and
+PowerPoint qualification status. No animation, glTF import, compression, or
+game-engine integration is included.
diff --git a/docs/public/firmament/openusd.md b/docs/public/firmament/openusd.md
index 5e3f1f52..74551fc4 100644
--- a/docs/public/firmament/openusd.md
+++ b/docs/public/firmament/openusd.md
@@ -58,6 +58,8 @@ pwsh -File scripts/qualify-usd-export-x0.ps1 -CaptureMotion
ATLAS uses exact Aetheris pedestal, perforated housings, shared collars, and a two-finger gripper. The separate studio USD layer adds lights, camera, stage, and a reflective sphere; those are presentation-only. See [the milestone evidence report](../../release/USD-EXPORT-X0.md) for the pinned tool, source provenance, screenshots, physical-scale checks, and limits.
+ATLAS is an independent Aetheris demo robot. Aetheris is not affiliated with, endorsed by, or associated with Boston Dynamics. The shared name is coincidental.
+
The refined industrial ATLAS witness is authored in `fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament`. Its tapered G1 housings use `SectionChainFile` definitions, alongside ordinary exact drums, rings, rounded panels and parallel jaws. Native shared instances retain the repeated fasteners. The assembly display exporter has a bounded structured tessellation lane for natural rectangular spline patches with simple planar caps: adjacent faces share sampled BRep edges, and sharp cap normals remain separate. Convex caps retain the centroid fan; concave single-loop caps use the existing simple-polygon triangulator over the same edge samples. General trimmed spline remeshing and caps with holes are outside that lane. The [single-cut guitar witness](../demos/guitar-surfacing-x0.md) exercises concave caps, carved G1 surfaces, formed strings, STEP, USD, and Cycles presentation.
After the solution build and installation above, reproduce its external validation and slide render with:
diff --git a/docs/release/PRESENTATION-3D-X0.md b/docs/release/PRESENTATION-3D-X0.md
new file mode 100644
index 00000000..83dd9ac1
--- /dev/null
+++ b/docs/release/PRESENTATION-3D-X0.md
@@ -0,0 +1,170 @@
+# PRESENTATION-3D-X0
+
+Status on 2026-10-02: **Meaningful progression; desktop qualification pending.**
+
+The C# GLB exporter and the existing C# slide writer now produce a two-slide PPTX
+containing physically embedded ATLAS and guitar GLBs. Independent glTF validation
+and Blender import succeed. Acceptance remains conditional on observing rotation,
+tilt, save, close, reopen, and further interaction in desktop PowerPoint without
+repair or missing-media warnings. Schema validation alone cannot prove this.
+
+## Architecture and authority
+
+`AssemblyGlbExporter` lowers `AssemblyDisplayMeshDocument`, the same qualified
+display representation used by USD. The assembly compiler and pose evaluator
+remain the owners of geometry and occurrence frames. Definitions become shared
+indexed triangle meshes with existing normals. Occurrences become named glTF
+nodes, using world-to-parent local transforms. Aetheris row-vector storage is the
+column-major array of its transpose, so GLB requires no extra array transpose.
+
+One root boundary maps `(x,y,z)` to `.001 × (x,z,-y)`, converting right-handed
+Z-up millimetres to right-handed Y-up metres. Sharp face boundaries remain split
+in the display mesh. No second tessellator, BRep serialization, glTF importer,
+animation, compression, or game-engine integration was introduced. STEP/BRep
+retains engineering authority.
+
+## Appearance
+
+The reusable .NET exporter maps existing USD preview RGB, metallic and roughness
+values into glTF PBR factors. Explicit definition UVs and PNG/JPEG texture bytes
+are supported and embedded in the binary buffer. Paths never enter GLB metadata.
+
+The final polished witnesses use their established Aetheris USD-derived Blender
+scenes. `export-presentation-scene.py` preserves product positions and polygons,
+exports the existing ATLAS label texture, and bakes five guitar sunburst/wood
+base-color surfaces. This is a bounded finishing step, not a general material
+graph translator. Procedural wood-grain bump is omitted; scalar PBR and supported
+coat survive. No guitar geometry work was reopened. Studio floors, lights and
+the chrome target are excluded from the exported assets.
+
+The direct .NET exports are retained as `atlas-display.glb` and
+`guitar-display.glb`; the polished deliverables are `atlas.glb` and `guitar.glb`.
+
+## C# slide compiler and OOXML oracle
+
+`DrawingPptxWriter.WriteModel3DDeck` extends the existing slide builder and OPC
+package writer. `Model3D` provides source, PNG preview, millimetre placement,
+semantic name and explicit view parameters. The JSON CLI is:
+
+```powershell
+dotnet run --project Aetheris.CLI -c Release -- presentation compile `
+ fixtures/Canonical/Presentation3D/interactive-3d-demo.json `
+ artifacts/local/presentation-3d-x0/interactive-3d-demo.pptx --json
+```
+
+The user authored `powerpoint-reference.pptx` in desktop PowerPoint
+**16.0.20430.20118**, inserting both local GLBs with Insert → 3D Models → This
+Device and saving the package. Its original 43-part package remains local. Slide
+2 contains both models. A compact first-object XML extract is retained under
+`fixtures/Canonical/Presentation3D/office-model3d-oracle.xml`.
+
+The generated package follows the inspected oracle:
+
+- Content type `model/gltf.binary` for GLB and `image/png` for fallback.
+- Internal model relationship
+ `http://schemas.microsoft.com/office/2017/06/relationships/model3d`.
+- `mc:AlternateContent`, with an `am3d` choice containing `p:graphicFrame` and
+ `a:graphicData` for `http://schemas.microsoft.com/office/drawing/2017/model3d`.
+- `am3d:model3d r:embed`, shape properties, deliberate camera, centering/scale/
+ rotation, raster image relationship, viewport, ambient and point lights.
+- A `p:pic` fallback referencing the same embedded PNG.
+
+The compiler embeds the exact input GLB bytes; it does not invoke Office to
+generate the deck. It adds no Open XML dependency to production: the writer
+already emits OOXML directly. Tests use the existing Open XML SDK 3.3.0 and
+Office 2019 validation. Current part locations are `ppt/media/model3d-1-1.glb`
+and `ppt/media/model3d-2-1.glb`. All relationships are internal. Package byte
+equality against the source assets and XML structure against the manual oracle
+are checked, without demanding byte identity with Office's rewritten package.
+
+## External validation and fallback
+
+Khronos glTF Validator **2.0.0-dev.3.10** reports zero errors and zero warnings on
+both direct display GLBs and both polished GLBs. ATLAS has one informational
+message for the existing 1024×192 label texture; direct display GLBs have
+informational default-matrix messages. Guitar has no validator issues.
+
+Blender **5.2.2 LTS** imports the polished assets independently. ATLAS has 61
+visible meshes using 25 mesh datablocks, including its printed label. Guitar has
+107 visible mesh objects and five embedded 1024×1024 images. Imported normals
+are unit length and transforms are positive-handed. Measured physical bounds in
+Blender's Z-up metres are approximately:
+
+| Model | X | Y | Z |
+|---|---:|---:|---:|
+| ATLAS | 0.295001 | 0.130000 | 0.340774 |
+| Guitar | 0.337550 | 1.039273 | 0.066480 |
+
+`atlas-fallback.png` and `guitar-fallback.png` render the independently imported
+GLBs. Visual inspection confirms the industrial robot, maker mark, polished
+metal parts, and guitar sunburst. View parameters in the deck are deliberate
+presentation normalization and Euler rotation; the embedded GLBs retain physical
+scale. Fallback images are useful static views, not a substitute for interaction.
+
+## Artifacts, timing and regression
+
+Generated files, raw validators, import reports, build/test logs and the manual
+oracle live under ignored `artifacts/local/presentation-3d-x0/`.
+
+| Artifact | Bytes |
+|---|---:|
+| ATLAS polished GLB | 546,680 |
+| Guitar polished GLB | 5,404,940 |
+| Two-slide PPTX before models | 6,526 |
+| Embedded two-slide PPTX | 4,779,099 |
+
+Direct .NET GLB lowering took about 60 ms for ATLAS and 96 ms for guitar after
+display preparation. Compilation and tessellation took about 4.29 s and 8.90 s
+respectively. Polished finishing took approximately 0.70 s and 2.09 s. C# slide
+compilation took approximately 116 ms. Desktop PowerPoint load time is unmeasured.
+The complete reproduction script ran successfully, including independent import,
+renders, all four validator reports and both deck variants.
+
+Focused GLB tests cover real display geometry, world placement, shared meshes,
+normal bytes, deterministic output, textures/PBR, malformed inputs and both
+witnesses. CLI tests cover valid export and preservation of output after invalid
+options. Three existing/new PPTX tests pass, including Office 2019 validation,
+exact embedding, multiple model relationships, fallback, deterministic packages,
+oracle structure and existing drawing functionality. Release build succeeds;
+the fast core lane passes 1,005 tests. The complete serial solution lane passes
+4,042 tests with zero failures (`full-tests-closeout.log`), including 1,138 core,
+1,736 Firmament and 455 CLI tests.
+
+The first full run is retained in `full-tests.log`: its documentation check ran
+before this report existed, and an existing USD export test exceeded the bounded
+five-second tessellation budget (5,916 ms). Both passed in a focused diagnostic
+run without changing production USD behavior. After generation completed, the
+full serial closeout run passed. The initial failures are retained rather than
+erased from the evidence.
+
+Reproduce the generated assets with:
+
+```powershell
+pwsh -File scripts/qualify-presentation-3d-x0.ps1
+```
+
+This requires the existing qualified `.blend` scenes. If absent, run the existing
+industrial ATLAS and guitar qualification scripts with `-Render` first. The
+qualifier builds both direct GLBs, finishes both polished scenes, imports/renders
+them independently, runs pinned Khronos validation, and calls the C# deck compiler.
+It does not claim desktop acceptance.
+
+## ATLAS disclaimer
+
+ATLAS is an independent Aetheris demo robot. Aetheris is not affiliated with,
+endorsed by, or associated with Boston Dynamics. The shared name is coincidental.
+
+The deck caption, asset metadata, fixture README and public documentation carry
+this disclaimer. Renaming is possible later, but changing source identities,
+labels and historical witness names would complicate provenance; X0 retains the
+existing name with explicit non-affiliation.
+
+## Remaining acceptance gate
+
+Open the generated PPTX in desktop PowerPoint. Select each 3D model and use its
+central 3D control to rotate and tilt. Save under another local folder, close and
+reopen, then rotate both again. Record model appearance, textures, warnings and
+repair behavior. These manual results are still required for Accepted. Desktop
+PowerPoint is installed and the manual oracle is available; the remaining gate
+is qualification of the compiler-generated deck, not installation or package
+schema discovery. No successful interaction result is claimed yet.
diff --git a/fixtures/Canonical/Presentation3D/README.md b/fixtures/Canonical/Presentation3D/README.md
new file mode 100644
index 00000000..3b1dd531
--- /dev/null
+++ b/fixtures/Canonical/Presentation3D/README.md
@@ -0,0 +1,16 @@
+# PRESENTATION-3D-X0 fixtures
+
+`interactive-3d-demo.json` is the bounded two-slide authoring input for the C#
+presentation compiler. It refers to generated local GLBs and fallback PNGs.
+
+`office-model3d-oracle.xml` is a compact regression extract from
+`powerpoint-reference.pptx`, authored by the user in desktop PowerPoint
+16.0.20430.20118 on 2026-10-02 using Insert → 3D Models → This Device.
+The local oracle contains ATLAS and guitar on slide 2. The extract retains the
+first model's AlternateContent, model/camera/transform/lighting/raster structure
+and fallback. Creation/modification identifiers were removed. Embedded binaries
+and the complete original package remain under ignored
+`artifacts/local/presentation-3d-x0/`.
+
+ATLAS is an independent Aetheris demo robot. Aetheris is not affiliated with,
+endorsed by, or associated with Boston Dynamics. The shared name is coincidental.
diff --git a/fixtures/Canonical/Presentation3D/interactive-3d-demo.json b/fixtures/Canonical/Presentation3D/interactive-3d-demo.json
new file mode 100644
index 00000000..708f1025
--- /dev/null
+++ b/fixtures/Canonical/Presentation3D/interactive-3d-demo.json
@@ -0,0 +1,34 @@
+{
+ "title": "Aetheris interactive 3D",
+ "slides": [
+ {
+ "title": "The Engineering Runtime for Physical AI",
+ "subtitle": "Exact engineering geometry → STEP for manufacturing → OpenUSD and GLB for simulation and presentation",
+ "caption": "ATLAS is an independent Aetheris demo robot. Aetheris is not affiliated with, endorsed by, or associated with Boston Dynamics. The shared name is coincidental.",
+ "models": [{
+ "name": "ATLAS independent Aetheris robot",
+ "source": "../../../artifacts/local/presentation-3d-x0/atlas.glb",
+ "preview": "../../../artifacts/local/presentation-3d-x0/atlas-fallback.png",
+ "x": 114, "y": 60, "width": 110, "height": 110,
+ "camera": {
+ "centerXMetres": -0.01646425575, "centerYMetres": 0.16238697665, "centerZMetres": 0,
+ "presentationScale": 2.934496, "rotationXDegrees": 23.25575, "rotationYDegrees": 41.32525, "rotationZDegrees": 15.84267
+ }
+ }]
+ },
+ {
+ "title": "Code-native 3D design beyond primitive CAD",
+ "subtitle": "Exact authored geometry. A polished sunburst finish. The actual model in the slide.",
+ "models": [{
+ "name": "GUITAR-SURFACING-X0",
+ "source": "../../../artifacts/local/presentation-3d-x0/guitar.glb",
+ "preview": "../../../artifacts/local/presentation-3d-x0/guitar-fallback.png",
+ "x": 114, "y": 60, "width": 110, "height": 110,
+ "camera": {
+ "centerXMetres": 0.00038237805, "centerYMetres": 0.03224023158, "centerZMetres": -0.29963669926,
+ "presentationScale": 0.962210, "rotationXDegrees": 65, "rotationYDegrees": 25, "rotationZDegrees": -25
+ }
+ }]
+ }
+ ]
+}
diff --git a/fixtures/Canonical/Presentation3D/office-model3d-oracle.xml b/fixtures/Canonical/Presentation3D/office-model3d-oracle.xml
new file mode 100644
index 00000000..a1ad2a63
--- /dev/null
+++ b/fixtures/Canonical/Presentation3D/office-model3d-oracle.xml
@@ -0,0 +1,108 @@
+<mc:AlternateContent xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
+ <mc:Choice Requires="am3d">
+ <p:graphicFrame>
+ <p:nvGraphicFramePr>
+ <p:cNvPr id="5" name="Content Placeholder 4" />
+ <p:cNvGraphicFramePr>
+ <a:graphicFrameLocks noGrp="1" noChangeAspect="1" />
+ </p:cNvGraphicFramePr>
+ <p:nvPr>
+ <p:ph idx="1" />
+ </p:nvPr>
+ </p:nvGraphicFramePr>
+ <p:xfrm>
+ <a:off x="1134746" y="1690688" />
+ <a:ext cx="3851645" cy="4907741" />
+ </p:xfrm>
+ <a:graphic>
+ <a:graphicData uri="http://schemas.microsoft.com/office/drawing/2017/model3d">
+ <am3d:model3d r:embed="rId2">
+ <am3d:spPr>
+ <a:xfrm>
+ <a:off x="0" y="0" />
+ <a:ext cx="3851645" cy="4907741" />
+ </a:xfrm>
+ <a:prstGeom prst="rect">
+ <a:avLst />
+ </a:prstGeom>
+ </am3d:spPr>
+ <am3d:camera>
+ <am3d:pos x="0" y="0" z="64748452" />
+ <am3d:up dx="0" dy="36000000" dz="0" />
+ <am3d:lookAt x="0" y="0" z="0" />
+ <am3d:perspective fov="2700000" />
+ </am3d:camera>
+ <am3d:trans>
+ <am3d:meterPerModelUnit n="2934496" d="1000000" />
+ <am3d:preTrans dx="1739315" dy="-17154862" dz="0" />
+ <am3d:scale>
+ <am3d:sx n="1000000" d="1000000" />
+ <am3d:sy n="1000000" d="1000000" />
+ <am3d:sz n="1000000" d="1000000" />
+ </am3d:scale>
+ <am3d:rot ax="1395345" ay="2479515" az="950560" />
+ <am3d:postTrans dx="0" dy="0" dz="0" />
+ </am3d:trans>
+ <am3d:raster rName="Office3DRenderer" rVer="16.0.8326">
+ <am3d:blip r:embed="rId3" />
+ </am3d:raster>
+ <am3d:objViewport viewportSz="6258321" />
+ <am3d:ambientLight>
+ <am3d:clr>
+ <a:scrgbClr r="50000" g="50000" b="50000" />
+ </am3d:clr>
+ <am3d:illuminance n="500000" d="1000000" />
+ </am3d:ambientLight>
+ <am3d:ptLight rad="0">
+ <am3d:clr>
+ <a:scrgbClr r="100000" g="75000" b="50000" />
+ </am3d:clr>
+ <am3d:intensity n="9765625" d="1000000" />
+ <am3d:pos x="21959998" y="70920001" z="16344003" />
+ </am3d:ptLight>
+ <am3d:ptLight rad="0">
+ <am3d:clr>
+ <a:scrgbClr r="40000" g="60000" b="95000" />
+ </am3d:clr>
+ <am3d:intensity n="12250000" d="1000000" />
+ <am3d:pos x="-37964106" y="51130435" z="57631972" />
+ </am3d:ptLight>
+ <am3d:ptLight rad="0">
+ <am3d:clr>
+ <a:scrgbClr r="86837" g="72700" b="100000" />
+ </am3d:clr>
+ <am3d:intensity n="3125000" d="1000000" />
+ <am3d:pos x="-37739122" y="58056624" z="-34769649" />
+ </am3d:ptLight>
+ </am3d:model3d>
+ </a:graphicData>
+ </a:graphic>
+ </p:graphicFrame>
+ </mc:Choice>
+ <mc:Fallback>
+ <p:pic>
+ <p:nvPicPr>
+ <p:cNvPr id="5" name="Content Placeholder 4" />
+ <p:cNvPicPr>
+ <a:picLocks noGrp="1" noRot="1" noChangeAspect="1" noMove="1" noResize="1" noEditPoints="1" noAdjustHandles="1" noChangeArrowheads="1" noChangeShapeType="1" noCrop="1" />
+ </p:cNvPicPr>
+ <p:nvPr />
+ </p:nvPicPr>
+ <p:blipFill>
+ <a:blip r:embed="rId3" />
+ <a:stretch>
+ <a:fillRect />
+ </a:stretch>
+ </p:blipFill>
+ <p:spPr>
+ <a:xfrm>
+ <a:off x="1134746" y="1690688" />
+ <a:ext cx="3851645" cy="4907741" />
+ </a:xfrm>
+ <a:prstGeom prst="rect">
+ <a:avLst />
+ </a:prstGeom>
+ </p:spPr>
+ </p:pic>
+ </mc:Fallback>
+</mc:AlternateContent>
diff --git a/scripts/export-presentation-scene.py b/scripts/export-presentation-scene.py
new file mode 100644
index 00000000..085b9a69
--- /dev/null
+++ b/scripts/export-presentation-scene.py
@@ -0,0 +1,116 @@
+"""Bounded finishing of the existing qualified ATLAS/guitar Blender scenes.
+
+No new product geometry. Bake only existing procedural base color; export static
+GLB with embedded images. The .NET exporter remains the reusable display lowering.
+blender --background --python scripts/export-presentation-scene.py --
+ guitar artifacts/local/guitar-x0/guitar-studio.blend artifacts/local/presentation-3d-x0/guitar.glb
+"""
+import bpy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+
+kind, source, destination = sys.argv[sys.argv.index('--') + 1:][:3]
+assert kind in ('atlas', 'guitar')
+source, destination = Path(source).resolve(), Path(destination).resolve()
+destination.parent.mkdir(parents=True, exist_ok=True)
+bpy.ops.wm.open_mainfile(filepath=str(source))
+scene = bpy.context.scene
+started = time.perf_counter()
+disclaimer = ('ATLAS is an independent Aetheris demo robot. Aetheris is not affiliated with, '
+ 'endorsed by, or associated with Boston Dynamics. The shared name is coincidental.')
+
+def signature():
+ digest = hashlib.sha256()
+ for mesh in sorted(bpy.data.meshes, key=lambda m: m.name):
+ digest.update(mesh.name.encode())
+ for v in mesh.vertices:
+ digest.update(str(tuple(v.co)).encode())
+ for p in mesh.polygons:
+ digest.update(str(tuple(p.vertices)).encode())
+ return digest.hexdigest()
+
+original = signature()
+products = [o for o in scene.objects if o.type == 'MESH' and not o.name.startswith('Presentation_')]
+def object_geometry(obj):
+ return (tuple(tuple(v.co) for v in obj.data.vertices),
+ tuple(tuple(p.vertices) for p in obj.data.polygons))
+product_geometry = {o.name: object_geometry(o) for o in products}
+if kind == 'guitar':
+ assert len(products) == 107, len(products)
+ scene.render.engine = 'CYCLES'
+ scene.cycles.samples = 1
+ scene.cycles.device = 'CPU'
+ # Baking color via emission preserves metallic base color too. Lighting,
+ # roughness, coat and normals are not baked into the base-color image.
+ baked = []
+ for obj in products:
+ material = obj.data.materials[0]
+ shader = material.node_tree.nodes.get('Principled BSDF')
+ if not shader.inputs['Base Color'].is_linked:
+ continue
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True); bpy.context.view_layer.objects.active = obj
+ obj.data = obj.data.copy()
+ material = material.copy(); obj.data.materials[0] = material
+ nodes, links = material.node_tree.nodes, material.node_tree.links
+ shader = nodes.get('Principled BSDF')
+ color = shader.inputs['Base Color'].links[0].from_socket
+ # A UV seam may split exported vertices, but positions/triangles never change.
+ bpy.ops.object.mode_set(mode='EDIT'); bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.uv.smart_project(island_margin=.02)
+ bpy.ops.object.mode_set(mode='OBJECT')
+ image = bpy.data.images.new('Aetheris baked ' + obj.name, width=1024, height=1024)
+ image.colorspace_settings.name = 'sRGB'
+ target = nodes.new('ShaderNodeTexImage'); target.image = image; nodes.active = target
+ emission = nodes.new('ShaderNodeEmission'); links.new(color, emission.inputs['Color'])
+ output = next(n for n in nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output)
+ links.new(emission.outputs[0], output.inputs['Surface'])
+ scene.render.bake.margin = 12
+ bpy.ops.object.bake(type='EMIT')
+ links.new(shader.outputs[0], output.inputs['Surface']); nodes.remove(emission)
+ links.new(target.outputs['Color'], shader.inputs['Base Color'])
+ image.pack()
+ # glTF cannot carry the procedural grain bump. Leave the real shader in
+ # the source scene and export base color + PBR factors explicitly.
+ for link in list(shader.inputs['Normal'].links): links.remove(link)
+ baked.append(obj.name)
+else:
+ baked = []
+
+# Export only the product assembly tree, including its existing printed label.
+# USD's root supplies the mm-to-metres conversion, retained by Blender/glTF.
+bpy.ops.object.select_all(action='DESELECT')
+def belongs_to_product(obj):
+ current = obj
+ while current:
+ if current.name == 'Assembly': return True
+ current = current.parent
+ return False
+selected = [o for o in scene.objects if belongs_to_product(o)]
+assert selected, 'Missing qualified USD Assembly root'
+for obj in selected:
+ obj.select_set(True)
+ obj['sourceProject'] = 'Aetheris'
+ obj['milestone'] = 'PRESENTATION-3D-X0'
+ obj['authority'] = 'BRep/STEP; GLB is a presentation asset'
+root = next(o for o in selected if o.name == 'Assembly')
+if kind == 'atlas': root['disclaimer'] = disclaimer
+root['creator'] = 'Aetheris with OpenAI Codex assistance'
+assert all(object_geometry(o) == product_geometry[o.name] for o in products), 'Baking changed product geometry'
+if kind == 'atlas': assert signature() == original, 'Presentation export changed topology'
+bpy.ops.export_scene.gltf(filepath=str(destination), export_format='GLB', use_selection=True,
+ export_animations=False, export_skins=False, export_morph=False,
+ export_extras=True, export_normals=True, export_materials='EXPORT',
+ export_yup=True, export_image_format='AUTO', export_attributes=False,
+ export_vertex_color='NONE')
+report = dict(model=kind, tool='Blender', version=bpy.app.version_string,
+ source=source.name, output=destination.name, bytes=destination.stat().st_size,
+ exportSeconds=time.perf_counter()-started, bakedObjects=baked,
+ selectedObjects=len(selected), originalGeometrySignature=original,
+ limitations=['Procedural grain bump omitted; base color baked and scalar PBR/coat retained.'] if kind == 'guitar' else [])
+if kind == 'atlas': report['disclaimer'] = disclaimer
+destination.with_suffix('.export.json').write_text(json.dumps(report, indent=2) + '\n')
+print(json.dumps(report), flush=True)
diff --git a/scripts/inspect-presentation-glb.py b/scripts/inspect-presentation-glb.py
new file mode 100644
index 00000000..cbd45601
--- /dev/null
+++ b/scripts/inspect-presentation-glb.py
@@ -0,0 +1,70 @@
+"""Independent Blender import and useful GLB fallback render, no geometry replacement.
+blender --background --python scripts/inspect-presentation-glb.py -- <model.glb> <evidence-dir>
+"""
+import bpy
+import json
+import math
+import sys
+import time
+from pathlib import Path
+from mathutils import Vector
+
+source, output = map(lambda p: Path(p).resolve(), sys.argv[sys.argv.index('--') + 1:][:2])
+output.mkdir(parents=True, exist_ok=True)
+bpy.ops.wm.read_factory_settings(use_empty=True)
+started = time.perf_counter()
+bpy.ops.import_scene.gltf(filepath=str(source))
+load_seconds = time.perf_counter() - started
+scene = bpy.context.scene
+products = [o for o in scene.objects if o.type == 'MESH']
+assert products
+points = [o.matrix_world @ Vector(corner) for o in products for corner in o.bound_box]
+lo = Vector(tuple(min(p[i] for p in points) for i in range(3)))
+hi = Vector(tuple(max(p[i] for p in points) for i in range(3)))
+size, center = hi-lo, (hi+lo)/2
+assert all(math.isfinite(v) for p in points for v in p)
+assert .05 < max(size) < 2, 'Expected mm engineering models converted to physical metres'
+for obj in products:
+ assert obj.data.polygons
+ assert all(abs(v.normal.length-1) < 1e-3 for v in obj.data.vertices)
+ assert obj.matrix_world.determinant() > 0
+images = [i for i in bpy.data.images if i.type == 'IMAGE']
+for image in images:
+ assert image.size[0] > 0 and image.size[1] > 0, 'Missing texture'
+materials = []
+for m in bpy.data.materials:
+ if not m.use_nodes: continue
+ p = next((n for n in m.node_tree.nodes if n.type == 'BSDF_PRINCIPLED'), None)
+ if p:
+ materials.append(dict(name=m.name, metallic=p.inputs['Metallic'].default_value,
+ roughness=p.inputs['Roughness'].default_value,
+ textured=p.inputs['Base Color'].is_linked))
+report = dict(tool='Blender', version=bpy.app.version_string, file=source.name,
+ loadSeconds=load_seconds, meshObjects=len(products), sharedMeshData=len({o.data.name for o in products}),
+ triangles=sum(len(o.data.loop_triangles) for o in products),
+ boundsMetres=dict(min=list(lo), max=list(hi), size=list(size)),
+ materials=materials, images=[dict(name=i.name, size=list(i.size)) for i in images],
+ hierarchy=[dict(name=o.name, parent=o.parent.name if o.parent else None) for o in scene.objects],
+ normalAndTransformChecks='passed')
+output.joinpath(source.stem+'.blender.json').write_text(json.dumps(report, indent=2)+'\n')
+camera_data = bpy.data.cameras.new('Aetheris Presentation Camera')
+camera = bpy.data.objects.new('Aetheris Presentation Camera', camera_data); scene.collection.objects.link(camera)
+camera.location = center + Vector((.85,-1.5,1.0) if source.stem.startswith('atlas') else (.9,-.8,1.3)) * max(size)
+camera.rotation_euler = (center-camera.location).to_track_quat('-Z','Y').to_euler()
+camera_data.type='ORTHO'; camera_data.ortho_scale=max(size)*1.45; scene.camera=camera
+scene.world=bpy.data.worlds.new('Studio'); scene.world.use_nodes=True
+scene.world.node_tree.nodes['Background'].inputs['Color'].default_value=(.28,.32,.4,1)
+scene.world.node_tree.nodes['Background'].inputs['Strength'].default_value=.5
+for name, direction, power in [('Key',(-1,-1,2),55),('Fill',(1,-.3,1),35),('Rim',(0,1,1),60)]:
+ light_data=bpy.data.lights.new(name,'AREA'); light_data.energy=power*max(size)**2; light_data.size=max(size)
+ light=bpy.data.objects.new(name,light_data); scene.collection.objects.link(light)
+ light.location=center+Vector(direction)*max(size)
+ light.rotation_euler=(center-light.location).to_track_quat('-Z','Y').to_euler()
+scene.render.engine='CYCLES'; scene.cycles.samples=24; scene.cycles.use_denoising=True
+scene.render.resolution_x=1200; scene.render.resolution_y=1200; scene.render.resolution_percentage=100
+scene.render.image_settings.file_format='PNG'; scene.render.film_transparent=True
+scene.render.filepath=str(output/(source.stem+'-fallback.png'))
+scene.view_settings.view_transform='AgX'
+bpy.ops.wm.save_as_mainfile(filepath=str(output/(source.stem+'-imported.blend')))
+bpy.ops.render.render(write_still=True)
+print(json.dumps({k:v for k,v in report.items() if k not in ('materials','hierarchy')}), flush=True)
diff --git a/scripts/qualify-presentation-3d-x0.ps1 b/scripts/qualify-presentation-3d-x0.ps1
new file mode 100644
index 00000000..d4ef5b79
--- /dev/null
+++ b/scripts/qualify-presentation-3d-x0.ps1
@@ -0,0 +1,46 @@
+[CmdletBinding()]
+param(
+ [string]$OutDir = 'artifacts/local/presentation-3d-x0',
+ [string]$Blender = 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe'
+)
+$ErrorActionPreference = 'Stop'
+$repoRoot = Split-Path -Parent $PSScriptRoot
+Push-Location $repoRoot
+try {
+ $out = [IO.Path]::GetFullPath($OutDir)
+ New-Item -ItemType Directory -Force $out | Out-Null
+ foreach ($scene in @('artifacts/local/usd-industrial/atlas-hero.blend','artifacts/local/guitar-x0/guitar-studio.blend')) {
+ if (!(Test-Path -LiteralPath $scene)) { throw "Missing qualified presentation scene: $scene. Run the existing qualify-industrial-atlas.ps1 -Render and qualify-guitar-x0.ps1 -Render first." }
+ }
+ function Invoke-Logged([string]$Program, [string[]]$Arguments, [string]$Log) {
+ & $Program @Arguments *> $Log
+ if ($LASTEXITCODE -ne 0) { throw "Command failed ($LASTEXITCODE): $Program. See $Log" }
+ }
+ Invoke-Logged 'dotnet' @('build','Aetheris.CLI','-c','Release','-m:1','--nologo','-v:q') "$out/cli-build.log"
+ $cli = 'Aetheris.CLI/bin/Release/net10.0/aetheris.dll'
+ Invoke-Logged 'dotnet' @($cli,'asm','export-glb','fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament',"$out/atlas-display.glb",'--materials','fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/appearance.json','--state','Shoulder=-75','--state','Elbow=-140','--state','GripLeft=10','--state','GripRight=10','--json') "$out/atlas-display-export.json"
+ Invoke-Logged 'dotnet' @($cli,'asm','export-glb','fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm',"$out/guitar-display.glb",'--materials','fixtures/Canonical/AssemblyInterfaces/GuitarX0/preview-materials.json','--json') "$out/guitar-display-export.json"
+ foreach ($kind in @('atlas','guitar')) {
+ $scene = if ($kind -eq 'atlas') { 'artifacts/local/usd-industrial/atlas-hero.blend' } else { 'artifacts/local/guitar-x0/guitar-studio.blend' }
+ Invoke-Logged $Blender @('--background','--python','scripts/export-presentation-scene.py','--',$kind,$scene,"$out/$kind.glb") "$out/$kind-polish.log"
+ Invoke-Logged $Blender @('--background','--python','scripts/inspect-presentation-glb.py','--',"$out/$kind.glb",$out) "$out/$kind-blender.log"
+ }
+ $toolsRoot = "$out/tools"
+ Invoke-Logged 'npm' @('install','--prefix',$toolsRoot,'[email protected]') "$out/validator-install.log"
+ Invoke-Logged 'node' @('scripts/validate-presentation-glb.cjs',"$toolsRoot/node_modules/gltf-validator","$out/atlas-display.glb","$out/guitar-display.glb","$out/atlas.glb","$out/guitar.glb") "$out/validator.log"
+ $deck = Get-Content -Raw fixtures/Canonical/Presentation3D/interactive-3d-demo.json | ConvertFrom-Json
+ for ($i=0; $i -lt 2; $i++) {
+ $kind = @('atlas','guitar')[$i]
+ $deck.slides[$i].models[0].source = "$out/$kind.glb"
+ $deck.slides[$i].models[0].preview = "$out/$kind-fallback.png"
+ }
+ $manifest = "$out/deck.json"
+ $deck | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $manifest -Encoding utf8
+ Invoke-Logged 'dotnet' @($cli,'presentation','compile',$manifest,"$out/interactive-3d-demo.pptx",'--json') "$out/deck-compile.json"
+ $empty = $deck | ConvertTo-Json -Depth 20 | ConvertFrom-Json
+ foreach ($slide in $empty.slides) { $slide.models = @() }
+ $empty | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath "$out/deck-without-models.json" -Encoding utf8
+ Invoke-Logged 'dotnet' @($cli,'presentation','compile',"$out/deck-without-models.json","$out/deck-without-models.pptx",'--json') "$out/deck-without-models-compile.json"
+ Write-Host "Generated and externally validated static GLBs and embedded PPTX: $out. Desktop rotation/save/reopen must be tested separately."
+}
+finally { Pop-Location }
diff --git a/scripts/validate-presentation-glb.cjs b/scripts/validate-presentation-glb.cjs
new file mode 100644
index 00000000..229e411a
--- /dev/null
+++ b/scripts/validate-presentation-glb.cjs
@@ -0,0 +1,17 @@
+// Offline Khronos validation. Install only in ignored local tools:
+// npm install --prefix artifacts/local/presentation-3d-x0/tools [email protected]
+// node scripts/validate-presentation-glb.cjs <tools/node_modules/gltf-validator> <file.glb> ...
+const fs = require('node:fs');
+const path = require('node:path');
+const validator = require(path.resolve(process.argv[2]));
+(async () => {
+ let failed = false;
+ for (const filename of process.argv.slice(3)) {
+ const bytes = fs.readFileSync(filename);
+ const report = await validator.validateBytes(new Uint8Array(bytes), { uri: path.basename(filename), maxIssues: 1000 });
+ fs.writeFileSync(filename.replace(/\.glb$/i, '.validator.json'), JSON.stringify(report, null, 2) + '\n');
+ console.log(JSON.stringify({ file: path.basename(filename), validatorVersion: validator.version(), ...report.issues }));
+ if (report.issues.numErrors) failed = true;
+ }
+ if (failed) process.exitCode = 1;
+})().catch(error => { console.error(error); process.exitCode = 1; });