Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add spatial scene inspection and USD/GLB export

Yuechen Li39b36aada756
diff --git a/Aetheris.CLI.Tests/SceneCommandTests.cs b/Aetheris.CLI.Tests/SceneCommandTests.cs
new file mode 100644
index 00000000..97b89f08
--- /dev/null
+++ b/Aetheris.CLI.Tests/SceneCommandTests.cs
@@ -0,0 +1,27 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class SceneCommandTests
+{
+ [Fact]
+ public void RealSceneInspectionExportsAndStepBoundaryAreExplicit()
+ {
+ 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 input=Path.Combine(root!.FullName,"fixtures/Canonical/Scene/room.firmament");
+ var output=Path.Combine(root.FullName,"artifacts/local/tests/scene",Guid.NewGuid().ToString("N")+".glb");
+ var stdout=new StringWriter(); var stderr=new StringWriter();
+ Assert.Equal(0,CliRunner.Run(["inspect",input,"--json"],stdout,stderr));
+ using(var report=JsonDocument.Parse(stdout.ToString())) Assert.Equal("mm",report.RootElement.GetProperty("internalUnits").GetString());
+ stdout.GetStringBuilder().Clear();
+ Assert.True(CliRunner.Run(["scene","export-glb",input,output,"--json"],stdout,stderr) == 0,stderr.ToString());
+ var bytes=File.ReadAllBytes(output);
+ Assert.NotEqual(0,CliRunner.Run(["scene","export-glb",input,output,"--repeat","0"],stdout,stderr));
+ Assert.Equal(bytes,File.ReadAllBytes(output));
+ Assert.NotEqual(0,CliRunner.Run(["build",input,"--json"],stdout,stderr));
+ Assert.Contains("scene-step-export-unsupported",stderr.ToString());
+ stdout.GetStringBuilder().Clear(); Assert.Equal(0,CliRunner.Run(["validate",input,"--json"],stdout,stderr));
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 483f15b4..a9654a5d 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -237,6 +237,7 @@ public static class CliRunner
"trace" => RunTrace(args.Skip(1).ToArray(), stdout, stderr),
"canon" => RunCanon(args.Skip(1).ToArray(), stdout, stderr),
"asm" => RunAsm(args.Skip(1).ToArray(), stdout, stderr),
+ "scene" => SceneCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
"experimental" => RunExperimental(args.Skip(1).ToArray(), stdout, stderr),
"modules" => RunModules(args.Skip(1).ToArray(), stdout, stderr),
"sheetmetal" => RunSheetMetal(args.Skip(1).ToArray(), stdout, stderr),
@@ -488,6 +489,8 @@ public static class CliRunner
if (File.Exists(sourcePath))
{
var source = File.ReadAllText(sourcePath);
+ if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source))
+ { stderr.WriteLine("scene-step-export-unsupported: Scene is a spatial product; use scene export-usd or scene export-glb."); return 1; }
if (Path.GetExtension(sourcePath).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source))
return RunAsmExportAp242([sourcePath, "--out", outPath ?? Path.GetFullPath(Path.Combine("artifacts", "local", "build", Path.GetFileNameWithoutExtension(sourcePath) + ".step")), .. (json ? new[] { "--json" } : [])], stdout, stderr);
if (SectionChainAuthoringParser.IsSectionChainSource(source))
@@ -1401,6 +1404,8 @@ Model CanonicalPanel {
}
var input = args[0];
+ if (File.Exists(input) && Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(File.ReadAllText(input)))
+ return SceneCommand.Run(["inspect", .. args], stdout, stderr);
if (File.Exists(input) && (Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(File.ReadAllText(input))))
return RunAsmInspect(args, stdout, stderr);
var json = args.Skip(1).SequenceEqual(["--json"]);
@@ -2318,6 +2323,14 @@ Model CanonicalPanel {
}
var validationSource=File.ReadAllText(sourcePath);
+ if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(validationSource))
+ {
+ var scene = Aetheris.Kernel.Firmament.Scene.SceneAuthoring.Parse(validationSource,Path.GetFullPath(sourcePath));
+ var payload = new { success=scene.IsSuccess, domain="Scene", diagnostics=scene.Diagnostics };
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(payload,JsonOptions));
+ else { stdout.WriteLine(scene.IsSuccess ? "Scene source valid; engineering definitions are checked by scene inspect/export." : "Scene source invalid."); foreach(var d in scene.Diagnostics) stderr.WriteLine(d.Code+": "+d.Message); }
+ return scene.IsSuccess ? 0 : 1;
+ }
var frontend = FirmamentFrontendSchemas.Select(validationSource);
if (!frontend.IsSuccess)
{
@@ -5024,6 +5037,7 @@ Model CanonicalPanel {
stdout.WriteLine(" fea Compile and solve a Firmament linear-elastic analysis and export Abaqus verification input.");
stdout.WriteLine(" drawing Compile production drawings or inspect/highlight PDFs with source-linked Drawing Notes.");
stdout.WriteLine(" asm Inspect, execute, import, and export Firmament V2 assemblies.");
+ stdout.WriteLine(" scene Inspect spatial scenes and export OpenUSD or GLB.");
stdout.WriteLine(" modules Inspect built-in engineering Modules and capabilities.");
stdout.WriteLine(" sheetmetal Inspect/recover sheet semantics and generate manufacturing flat-pattern SVG.");
stdout.WriteLine(" sculpture Build bounded non-manufacturing virtual sculpture artifacts.");
diff --git a/Aetheris.CLI/SceneCommand.cs b/Aetheris.CLI/SceneCommand.cs
new file mode 100644
index 00000000..1cacb86a
--- /dev/null
+++ b/Aetheris.CLI/SceneCommand.cs
@@ -0,0 +1,67 @@
+using System.Diagnostics;
+using System.Text;
+using System.Text.Json;
+using Aetheris.Kernel.Firmament.Scene;
+
+namespace Aetheris.CLI;
+
+internal static class SceneCommand
+{
+ internal const string Usage="aetheris scene <inspect|export-usd|export-glb> <scene.firmament> [out.usda|out.glb] [--repeat 1..16] [--json]";
+ 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.Length < 2 || args[0] is not ("inspect" or "export-usd" or "export-glb")) throw new ArgumentException(Usage);
+ var operation=args[0]; var path=Path.GetFullPath(args[1]); var json=false; var repeat=1; string? output=null;
+ for(var i=2;i<args.Length;i++)
+ {
+ if(args[i] == "--json") json=true;
+ else if(args[i] == "--repeat" && i+1<args.Length && int.TryParse(args[++i],out repeat) && repeat is >=1 and <=16) { }
+ else if(!args[i].StartsWith('-') && output is null && operation != "inspect") output=args[i];
+ else throw new ArgumentException("Unknown or incomplete Scene option: "+args[i]);
+ }
+ if(operation != "inspect")
+ {
+ var extension=operation == "export-usd" ? ".usda" : ".glb";
+ output=Path.GetFullPath(output ?? Path.Combine("artifacts","local","scene",Path.GetFileNameWithoutExtension(path)+extension));
+ if(!Path.GetExtension(output).Equals(extension,StringComparison.OrdinalIgnoreCase) || output.Equals(path,StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("Scene output requires "+extension+" and must differ from input.");
+ }
+ using var session=new FirmamentSceneSession(); SceneCompilationResult? result=null; var builds=new List<object>();
+ for(var i=0;i<repeat;i++)
+ {
+ var watch=Stopwatch.StartNew(); result=session.CompileFile(path);
+ builds.Add(new {index=i,elapsedMilliseconds=watch.Elapsed.TotalMilliseconds,performance=result.Scene?.Performance,reuse=result.Scene?.Reuse});
+ if(!result.IsSuccess) break;
+ }
+ if(!result!.IsSuccess)
+ {
+ if(json) stdout.WriteLine(JsonSerializer.Serialize(new {success=false,diagnostics=result.Diagnostics},CliRunner.JsonOptions));
+ else foreach(var d in result.Diagnostics) stderr.WriteLine(d.Code+": "+d.Message);
+ return 1;
+ }
+ var scene=result.Scene!; var export=Stopwatch.StartNew(); long bytes=0;
+ if(output is not null)
+ {
+ // Protect every engineering input, including AssemblyFile dependencies.
+ if(scene.Source.Occurrences.Any(o => o.Definition.Contains('"') && o.Definition.Contains(Path.GetFileName(output),StringComparison.Ordinal)))
+ throw new ArgumentException("Output must differ from engineering definition inputs.");
+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);
+ if(operation == "export-usd") File.WriteAllText(output,SceneExport.Usd(scene),new UTF8Encoding(false));
+ else File.WriteAllBytes(output,SceneExport.Glb(scene));
+ bytes=new FileInfo(output).Length;
+ }
+ var report=new {success=true,scene=scene.Source.Name,authoringUnits=scene.Source.Units,internalUnits="mm",rooms=scene.Source.Rooms.Count,
+ assemblies=scene.Source.Occurrences.Count(o => o.Kind == "Assembly"),parts=scene.Source.Occurrences.Count(o => o.Kind == "Part"),
+ definitions=scene.Display.Definitions.Count,occurrences=scene.Display.Occurrences.Count,cameras=scene.Source.Cameras.Count,
+ bounds=new {minimumMm=scene.MinimumMm,maximumMm=scene.MaximumMm},boundaries=scene.Boundaries,openings=scene.Source.Openings,
+ nodes=scene.Nodes,builds,output,bytes,exportMilliseconds=output is null ? 0 : export.Elapsed.TotalMilliseconds};
+ stdout.WriteLine(json ? JsonSerializer.Serialize(report,CliRunner.JsonOptions) : $"Scene {scene.Source.Name}: {scene.Source.Rooms.Count} rooms, {scene.Source.Occurrences.Count} authored placements, {scene.Display.Definitions.Count} shared display definitions"+(output is null ? "." : $"; exported {output}."));
+ return 0;
+ }
+ catch(Exception ex) when(ex is ArgumentException or IOException or InvalidOperationException or FormatException or OverflowException)
+ { stderr.WriteLine("scene-command-failed: "+ex.Message); return 1; }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs
index 642d9108..90e37a2a 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs
@@ -8,7 +8,7 @@ public sealed class FirmamentSemanticSchemaTests
public void GeneratedRegistry_IsStableOptInAndCoversFirstConstructs()
{
Assert.Equal("firmament-semantic-schema/1", FirmamentSemanticSchemas.Version);
- Assert.Equal(["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance", "Box", "Concept", "Points", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Loft", "Perforation", "Material", "Linear", "Series", "Section", "Thread", "Follow", "WireRoute"], FirmamentSemanticSchemas.All.Select(s => s.Name));
+ Assert.Equal(["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance", "Box", "Concept", "Points", "Door", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Loft", "Perforation", "Material", "Linear", "Series", "Room", "Scene", "Camera", "Section", "Thread", "Window", "Follow", "WireRoute"], FirmamentSemanticSchemas.All.Select(s => s.Name));
var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));
var diameter = Assert.Single(hole.Fields, f => f.Name == "Diameter");
Assert.Equal("Hole.Diameter", diameter.Id.Value);
diff --git a/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs
index e13d868b..ed56384c 100644
--- a/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs
@@ -68,7 +68,7 @@ public sealed class ProfileBoundaryAuthoringTests
Assert.Contains(errors, e => e.StartsWith("profile-edit-overlap:"));
const string disjoint = "Replace LeftGrip { On: Blank.Left; Through: [[-50mm,0mm]] }";
var a = ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace("From: Blank", "From: Blank\n" + disjoint), "Panel", out var ae);
- var b = ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace("Join: Tangent\n }", "Join: Tangent\n }\n" + disjoint), "Panel", out var be);
+ var b = ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace("\r\n", "\n", StringComparison.Ordinal).Replace("Join: Tangent\n }", "Join: Tangent\n }\n" + disjoint), "Panel", out var be);
Assert.Empty(ae); Assert.Empty(be);
Assert.Equal(a!.Loops[0].Segments.Select(s => s.Geometry), b!.Loops[0].Segments.Select(s => s.Geometry));
}
diff --git a/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.cs
new file mode 100644
index 00000000..7403c727
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.cs
@@ -0,0 +1,158 @@
+using System.Buffers.Binary;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Scene;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class SceneAuthoringTests
+{
+ private static string PathFor(string name) => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Scene/"+name+".firmament");
+ private static string Source(string name) => File.ReadAllText(PathFor(name));
+ private static CompiledScene Compile(string name)
+ { using var session=new FirmamentSceneSession(); var r=session.CompileFile(PathFor(name)); Assert.True(r.IsSuccess,string.Join("\n",r.Diagnostics)); return r.Scene!; }
+
+ [Fact]
+ public void RoomMetresNormalizeToMmAndPublishOwnedStableBoundaries()
+ {
+ var s=Compile("room"); var room=Assert.Single(s.Source.Rooms);
+ Assert.Equal(new[] {10000d,8000,4000},room.SizeMm);
+ Assert.Equal(6,s.Boundaries.Count); Assert.Contains(s.Boundaries,b => b.Path == "hall.floor");
+ var south=Assert.Single(s.Boundaries,b => b.Path == "hall.southWall");
+ Assert.Equal(new[] {1000d,2000,0},south.Frame.Skip(12).Take(3)); Assert.Equal("loading",Assert.Single(south.Openings));
+ Assert.Equal(new[] {900d,1900,-100},s.MinimumMm); Assert.Equal(new[] {11100d,10100,4100},s.MaximumMm);
+ }
+
+ [Fact]
+ public void ActualWallDisplayVolumeExcludesDoorAndWindowApertures()
+ {
+ var s=Compile("room"); var defs=s.Display.Definitions.ToDictionary(d => d.Id);
+ double Volume(string wall) => s.Display.Occurrences.Where(o => o.Path.StartsWith("RoomProof.hall."+wall+".panel",StringComparison.Ordinal)).Sum(o =>
+ {
+ var p=defs[o.DefinitionId!].Positions;
+ return Enumerable.Range(0,3).Select(a => Enumerable.Range(0,p.Length/3).Max(i => p[i*3+a])-Enumerable.Range(0,p.Length/3).Min(i => p[i*3+a])).Aggregate(1d,(a,b) => a*b);
+ });
+ Assert.Equal((10000d*4000-2000*3000)*100,Volume("southWall"));
+ Assert.Equal((8000d*4000-2000*1000)*100,Volume("eastWall"));
+ var opening=Assert.Single(s.Source.Openings,o => o.Kind == "Window"); Assert.Equal(1500,opening.SillMm);
+ Assert.Contains(s.Nodes,n => n.Path == "RoomProof.hall.eastWall.glazing" && n.Kind == "Window");
+ }
+
+ [Theory]
+ [InlineData("[10m, 8m, 4m]","[10000mm, 8000mm, 4000mm]")]
+ [InlineData("units: m","units: mm")]
+ public void MmCompatibilityAndExplicitSuffixesPreserveGeometry(string before,string after)
+ {
+ using var session=new FirmamentSceneSession(); var baseline=session.Compile(Source("room")); var changed=session.Compile(Source("room").Replace(before,after,StringComparison.Ordinal));
+ Assert.True(changed.IsSuccess); Assert.Equal(baseline.Scene!.MinimumMm,changed.Scene!.MinimumMm); Assert.Equal(baseline.Scene.MaximumMm,changed.Scene.MaximumMm);
+ }
+
+ [Theory]
+ [InlineData("[10m, 8m, 4m]","[10, 8m, 4m]","scene-length-unit-required")]
+ [InlineData("width: 2m; height: 3m","width: 11m; height: 3m","scene-opening-outside-wall")]
+ [InlineData("hall.southWall","hall.floor","scene-opening-boundary-invalid")]
+ [InlineData("thickness: 100mm","thickness: 0mm","scene-room-size-invalid")]
+ [InlineData("fov: 45deg","fov: 180deg","scene-camera-invalid")]
+ [InlineData("size: [10m, 8m, 4m]","size: [10m, 8m, 4m]; Size: [10m,8m,4m]","scene-duplicate-field")]
+ public void InvalidSceneIntentFailsWithSpecificDiagnostics(string before,string after,string code)
+ {
+ var r=SceneAuthoring.Parse(Source("room").Replace(before,after,StringComparison.Ordinal)); Assert.False(r.IsSuccess); Assert.Contains(r.Diagnostics,d => d.Code == code);
+ }
+
+ [Fact]
+ public void PatternKeysSourceSpansAndSharedGeometrySurviveCameraPlacementAndCountEdits()
+ {
+ using var session=new FirmamentSceneSession(); var source=Source("parts-and-pattern");
+ var first=session.Compile(source,PathFor("parts-and-pattern")); Assert.True(first.IsSuccess,string.Join("\n",first.Diagnostics));
+ Assert.Single(first.Scene!.Display.Definitions); Assert.Equal(2,first.Scene.Source.Occurrences.Count);
+ var bodies=first.Scene.Display.Occurrences.Where(o => o.DefinitionId is not null).ToArray(); Assert.Equal(bodies[0].DefinitionId,bodies[1].DefinitionId);
+ Assert.Equal(1000,bodies[0].Transform[12]); Assert.Equal(2000,bodies[1].Transform[12]);
+ foreach(var o in first.Scene.Source.Occurrences) { Assert.NotNull(o.PatternKey); Assert.StartsWith("Pattern packages",source.Substring(o.Span.Start,o.Span.Length)); }
+ var edited=source.Replace("[3m, -2m, 1m]","[4m, -2m, 1m]",StringComparison.Ordinal).Replace("x: 2m","x: 2.5m",StringComparison.Ordinal);
+ var second=session.Compile(edited,PathFor("parts-and-pattern")); Assert.True(second.IsSuccess);
+ Assert.Equal(0,second.Scene!.Performance.RebuiltEngineeringDefinitions); Assert.Equal(1,second.Scene.Performance.ReusedEngineeringDefinitions);
+ Assert.Equal(bodies.Select(o => o.Id),second.Scene.Display.Occurrences.Where(o => o.DefinitionId is not null).Select(o => o.Id));
+ var third=session.Compile(edited.Replace("second => Site", "third => Site { x: 3m; }\n second => Site",StringComparison.Ordinal),PathFor("parts-and-pattern"));
+ Assert.True(third.IsSuccess); Assert.Equal(3,third.Scene!.Source.Occurrences.Count); Assert.Equal(0,third.Scene.Performance.RebuiltEngineeringDefinitions);
+ }
+
+ [Fact]
+ public void SceneEditorProjectsSchemaHoverDiagnosticsAndCommentSafePreferredFormatting()
+ {
+ var source=Source("room"); var entries=FirmamentLanguageService.Complete("", "scene","r",0).Entries!;
+ foreach(var kind in new[] {"Scene","Room","Door","Window","Camera"}) Assert.Contains(entries,e => e.Name == kind);
+ var prefix="Scene Factory { units: m; Room hall { "; var completion=FirmamentLanguageService.Complete(prefix,"scene","r",prefix.Length);
+ Assert.Equal("Room",completion.Context); Assert.Contains(completion.Fields,f => f.Name == "Size");
+ var scenePrefix="Scene Factory { units: m;\n Ro";
+ Assert.Contains(FirmamentLanguageService.Complete(scenePrefix,"scene","r",scenePrefix.Length).Entries!,e => e.Name == "Room");
+ Assert.NotNull(FirmamentLanguageAnalysisService.Hover(source,"scene","r",source.IndexOf("Room hall",StringComparison.Ordinal)));
+ Assert.DoesNotContain(FirmamentLanguageAnalysisService.Analyze(source,"scene","r").Diagnostics,d => d.Severity == "error");
+ var pascal=source.Replace("units:","Units:",StringComparison.Ordinal).Replace("size:","Size:",StringComparison.Ordinal);
+ var formatted=FirmamentLanguageAnalysisService.Format(pascal,"scene","r").Text;
+ Assert.Equal(source,formatted); Assert.Equal(formatted,FirmamentLanguageAnalysisService.Format(formatted,"scene","r").Text);
+ Assert.Contains("// A semantic room",formatted); Assert.Equal("RoomProof",SceneAuthoring.Parse(formatted).Source!.Name);
+ }
+
+ [Theory]
+ [InlineData("Scene test { units: m; <Part unfinished = }")]
+ [InlineData("Scene test { units: m; <Part unfinished = ></Part> }")]
+ public void UnfinishedOccurrenceDefinitionsReturnSyntaxDiagnostics(string source)
+ {
+ var parsed=SceneAuthoring.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.Diagnostics,d => d.Code == "scene-syntax-invalid");
+ }
+
+ [Fact]
+ public void SceneUsdAndGlbPreserveHierarchyCamerasAndInstancing()
+ {
+ var s=Compile("parts-and-pattern"); var usd=SceneExport.Usd(s);
+ Assert.Contains("defaultPrim = \"Scene\"",usd); Assert.Contains("instanceable = true",usd); Assert.Contains("def Camera",usd);
+ Assert.DoesNotContain("PhysicsRigidBodyAPI",usd); Assert.DoesNotContain("PhysicsFixedJoint",usd);
+ var bytes=SceneExport.Glb(s); Assert.Equal(bytes,SceneExport.Glb(s));
+ var length=BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(12,4)); using var json=JsonDocument.Parse(bytes.AsMemory(20,length));
+ Assert.Single(json.RootElement.GetProperty("meshes").EnumerateArray()); Assert.Single(json.RootElement.GetProperty("cameras").EnumerateArray());
+ var bodyNodes=json.RootElement.GetProperty("nodes").EnumerateArray().Where(n => n.TryGetProperty("mesh",out _)).ToArray();
+ Assert.Equal(bodyNodes[0].GetProperty("mesh").GetInt32(),bodyNodes[1].GetProperty("mesh").GetInt32());
+ }
+
+ [Fact]
+ public void PascalCompatibilityAndPreferredFieldsHaveByteIdenticalPresentationArtifacts()
+ {
+ using var session=new FirmamentSceneSession(); var source=Source("room");
+ var preferred=session.Compile(source); var pascal=session.Compile(FirmamentSourceSpelling.Normalize(source));
+ Assert.True(preferred.IsSuccess); Assert.True(pascal.IsSuccess);
+ Assert.Equal(SceneExport.Usd(preferred.Scene!),SceneExport.Usd(pascal.Scene!));
+ Assert.Equal(SceneExport.Glb(preferred.Scene!),SceneExport.Glb(pascal.Scene!));
+ }
+
+ [Fact]
+ public void WarehousePlacesThreeExistingRobotsWithoutSolvingMechanicalRelationshipsAtSceneRoot()
+ {
+ var s=Compile("warehouse"); Assert.Equal(3,s.Source.Occurrences.Count(o => o.Kind == "Assembly")); Assert.Equal(5,s.Source.Occurrences.Count(o => o.Path.Contains(".packages.",StringComparison.Ordinal)));
+ var robot=s.Display.Occurrences.Single(o => o.Path == "WarehouseX0.robots.sorting.robot"); Assert.Equal(2500,robot.Transform[12]); Assert.Equal(2000,robot.Transform[13]);
+ Assert.Single(s.Source.Cameras); Assert.All(s.Nodes,n => Assert.Equal("SceneFrame",n.PlacementAuthority));
+ var shared=s.Display.Occurrences.Where(o => o.Path.EndsWith(".robot.Base",StringComparison.Ordinal)).Select(o => o.DefinitionId).Distinct().ToArray(); Assert.Single(shared);
+ }
+
+ [Fact]
+ public void WarehouseCameraAndPlacementEditsReuseEveryEngineeringDefinition()
+ {
+ using var session=new FirmamentSceneSession(); var path=PathFor("warehouse"); var source=Source("warehouse");
+ var first=session.Compile(source,path); Assert.True(first.IsSuccess,string.Join("\n",first.Diagnostics));
+ var changed=source.Replace("position: [5.6m","position: [5.4m",StringComparison.Ordinal)
+ .Replace("x: 2500mm","x: 2600mm",StringComparison.Ordinal);
+ var second=session.Compile(changed,path); Assert.True(second.IsSuccess,string.Join("\n",second.Diagnostics));
+ Assert.Equal(0,second.Scene!.Performance.RebuiltEngineeringDefinitions);
+ Assert.Equal(first.Scene!.Performance.UniqueEngineeringDefinitions,second.Scene.Performance.ReusedEngineeringDefinitions);
+ foreach(var d in first.Scene.Display.Definitions)
+ {
+ var reused=second.Scene.Display.Definitions.Single(v => v.Id == d.Id);
+ Assert.Equal(d.Positions,reused.Positions); Assert.Equal(d.Indices,reused.Indices);
+ }
+ Assert.Equal(2600,second.Scene.Display.Occurrences.Single(o => o.Path == "WarehouseX0.robots.sorting.robot").Transform[12]);
+ Assert.Equal(2500,first.Scene.Display.Occurrences.Single(o => o.Path == "WarehouseX0.robots.sorting.robot").Transform[12]);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index 50c58404..b7b51375 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -48,6 +48,21 @@ public static class AssemblyDisplayMeshExporter
var definitions = new List<AssemblyDisplayMeshDefinition>();
foreach (var (identity, body) in geometry.DefinitionBodies.OrderBy(p => p.Key, StringComparer.Ordinal))
{
+ definitions.Add(PrepareDefinition(ids[identity], identity, body, options));
+ }
+ var occurrences = (pose?.Instances ?? compilation.Ir.Instances).OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
+ {
+ var id = instance.Kind == AssemblyInstanceKind.Part
+ ? ids.GetValueOrDefault(instance.DefinitionIdentity) ?? throw new InvalidOperationException($"assembly-mesh-missing-definition:{instance.Path}") : null;
+ if (instance.ResolvedTransform is null || instance.ResolvedTransform.Matrix.Length != 16 || instance.ResolvedTransform.Matrix.Any(v => !double.IsFinite(v)))
+ throw new InvalidOperationException($"assembly-mesh-unresolved-transform:{instance.Path}");
+ return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray(), instance.StableId);
+ }).ToArray();
+ return new("aetheris/assembly-display-mesh/1", compilation.Ir.Name, "mm", definitions, occurrences);
+ }
+
+ internal static AssemblyDisplayMeshDefinition PrepareDefinition(string id, string identity, Aetheris.Kernel.Core.Brep.BrepBody body, DisplayTessellationOptions? options = null)
+ {
var effectiveOptions = options ?? new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64);
// Reuse the OBJ export's shared-boundary mesher for planar/cylindrical
// and formed-wire torus parts. A failure on this admitted family must remain visible; do not
@@ -79,22 +94,12 @@ public static class AssemblyDisplayMeshExporter
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));
- ranges.Add(new(startTriangle, face.TriangleIndices.Count / 3, $"face:{face.FaceId.Value}", ids[identity]));
+ ranges.Add(new(startTriangle, face.TriangleIndices.Count / 3, $"face:{face.FaceId.Value}", id));
}
if (positions.Concat(normals).Any(v => !double.IsFinite(v)))
throw new InvalidOperationException($"assembly-mesh-nonfinite:{identity}");
- definitions.Add(new(ids[identity], identity, positions.ToArray(), normals.ToArray(), indices.ToArray(),
- tessellation.Value.MeshPipeline.ToString(), ranges));
- }
- var occurrences = (pose?.Instances ?? compilation.Ir.Instances).OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
- {
- var id = instance.Kind == AssemblyInstanceKind.Part
- ? ids.GetValueOrDefault(instance.DefinitionIdentity) ?? throw new InvalidOperationException($"assembly-mesh-missing-definition:{instance.Path}") : null;
- if (instance.ResolvedTransform is null || instance.ResolvedTransform.Matrix.Length != 16 || instance.ResolvedTransform.Matrix.Any(v => !double.IsFinite(v)))
- throw new InvalidOperationException($"assembly-mesh-unresolved-transform:{instance.Path}");
- return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray(), instance.StableId);
- }).ToArray();
- return new("aetheris/assembly-display-mesh/1", compilation.Ir.Name, "mm", definitions, occurrences);
+ return new(id, identity, positions.ToArray(), normals.ToArray(), indices.ToArray(),
+ tessellation.Value.MeshPipeline.ToString(), ranges);
}
public static string Serialize(AssemblyDisplayMeshDocument document)
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
index a8554205..a1b9b550 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyGlbExporter.cs
@@ -23,7 +23,9 @@ public static class AssemblyGlbExporter
}
public static byte[] Serialize(AssemblyDisplayMeshDocument display,
- IReadOnlyDictionary<string, AssemblyGlbAppearance>? appearances = null)
+ IReadOnlyDictionary<string, AssemblyGlbAppearance>? appearances = null,
+ IReadOnlyDictionary<string, AssemblyAppearanceBinding>? occurrenceLooks = null,
+ IReadOnlyList<DisplayCamera>? cameras = null)
{
if (display.Units != "mm" || display.Definitions.Count == 0 || display.Occurrences.Count == 0)
throw new InvalidOperationException("assembly-glb-invalid-document");
@@ -53,6 +55,7 @@ public static class AssemblyGlbExporter
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 primitiveTemplates = new List<(Dictionary<string,object> Attributes,int Indices)>();
var images = new List<object>(); var textures = new List<object>();
int AddView(Action write, int? target = null)
{
@@ -112,7 +115,9 @@ public static class AssemblyGlbExporter
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 } });
+ primitiveTemplates.Add((attributes,indexAccessor));
}
+ var variants = new Dictionary<(string, AssemblyUsdMaterial), int>();
var nodes = new List<object>();
foreach (var o in occurrences)
{
@@ -121,14 +126,41 @@ public static class AssemblyGlbExporter
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];
+ if (o.DefinitionId is not null)
+ {
+ var meshIndex = definitionIds[o.DefinitionId];
+ if (occurrenceLooks?.GetValueOrDefault(o.Id) is { } look)
+ {
+ var m = look.Preview;
+ 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");
+ if (!variants.TryGetValue((o.DefinitionId,m),out var variant))
+ {
+ // Material variants share all accessors and buffer views.
+ var primitive = primitiveTemplates[meshIndex];
+ materials.Add(new {name=look.Appearance,pbrMetallicRoughness=new {baseColorFactor=new[] {m.Red,m.Green,m.Blue,1},metallicFactor=m.Metallic,roughnessFactor=m.Roughness}});
+ meshes.Add(new {name=definitions[meshIndex].Identity,primitives=new[] {new {attributes=primitive.Attributes,indices=primitive.Indices,material=materials.Count-1}}});
+ variants[(o.DefinitionId,m)]=variant=meshes.Count-1;
+ }
+ meshIndex=variant;
+ }
+ node["mesh"] = meshIndex;
+ }
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();
+ var roots = occurrences.Where(o => o.ParentId is null).Select(o => occurrenceIds[o.Id]).ToList();
+ foreach (var (camera,index) in (cameras ?? []).Select((c,i) => (c,i)))
+ {
+ ValidateTransform(camera.Transform);
+ if (!double.IsFinite(camera.FovDegrees) || camera.FovDegrees <= 0 || camera.FovDegrees >= 180)
+ throw new InvalidOperationException("display-glb-camera-invalid");
+ roots.Add(nodes.Count);
+ nodes.Add(new {name=camera.Name,matrix=camera.Transform,camera=index});
+ }
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>
{
@@ -137,6 +169,7 @@ public static class AssemblyGlbExporter
["nodes"] = nodes, ["meshes"] = meshes, ["materials"] = materials,
["accessors"] = accessors, ["bufferViews"] = views, ["buffers"] = new[] { new { byteLength = checked((int)binary.Length) } }
};
+ if (cameras?.Count > 0) document["cameras"] = cameras.Select(c => new {name=c.Name,type="perspective",perspective=new {yfov=c.FovDegrees*Math.PI/180,znear=1d}}).ToArray();
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);
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
index 995a748b..8c63c08b 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
@@ -81,7 +81,7 @@ public sealed class AssemblyM0Parser
return string.Join(Environment.NewLine, declarations);
}
- private static string FindAllowedSourceRoot(string path)
+ internal static string FindAllowedSourceRoot(string path)
{
var directory = new DirectoryInfo(Path.GetDirectoryName(path)!);
while (directory is not null)
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs
index ba8c3724..cf273f4a 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs
@@ -13,6 +13,12 @@ public sealed record AssemblyUsdOptions(IReadOnlyDictionary<string, double>? Sta
IReadOnlyList<AssemblyUsdSample>? Samples = null,
IReadOnlyDictionary<string, AssemblyUsdMaterial>? DefinitionMaterials = null);
+public sealed record DisplayCamera(string Name, double[] Transform, double FovDegrees);
+public sealed record SpatialUsdMetadata(IReadOnlyDictionary<string,string> DefinitionIdentities,
+ IReadOnlyDictionary<string,AssemblyAppearanceBinding> Appearances,
+ IReadOnlyDictionary<string,IReadOnlyDictionary<string,string>> Properties,
+ IReadOnlyList<DisplayCamera> Cameras);
+
/// <summary>Bounded USDA lowering of the accepted assembly and production display mesh.
/// STEP/BRep and the Interface compiler remain authoritative. No USD dependency or solver.</summary>
public static class AssemblyUsdExporter
@@ -34,17 +40,35 @@ public static class AssemblyUsdExporter
if (mesh.Units != "mm" || mesh.Occurrences.Count != ir.Instances.Count
|| !mesh.Occurrences.Select(o => o.Id).ToHashSet(StringComparer.Ordinal).SetEquals(ir.Instances.Select(i => i.StableId)))
throw new InvalidOperationException("assembly-usd-document-mismatch");
+ return SerializeCore(ir, mesh, options, evaluatedState, null);
+ }
+
+ /// <summary>Spatial display projection. No assembly IR, mechanical solving or inferred joints.</summary>
+ public static string SerializeSpatial(AssemblyDisplayMeshDocument mesh, SpatialUsdMetadata metadata,
+ AssemblyUsdOptions? options = null)
+ {
+ if (mesh.Units != "mm" || mesh.Occurrences.Count(o => o.ParentId is null) != 1
+ || mesh.Occurrences.Any(o => o.Transform.Length != 16 || o.Transform.Any(v => !double.IsFinite(v))))
+ throw new InvalidOperationException("spatial-usd-invalid-document");
+ return SerializeCore(null, mesh, options ?? new(), null, metadata);
+ }
+
+ private static string SerializeCore(AssemblyIr? ir, AssemblyDisplayMeshDocument mesh, AssemblyUsdOptions options,
+ IReadOnlyDictionary<string, double>? evaluatedState, SpatialUsdMetadata? spatial)
+ {
+ var rootId = ir?.RootInstanceStableId ?? mesh.Occurrences.Single(o => o.ParentId is null).Id;
+ var rootPrim = spatial is null ? "Assembly" : "Scene";
var occurrences = mesh.Occurrences.ToDictionary(o => o.Id, StringComparer.Ordinal);
var definitions = mesh.Definitions.OrderBy(d => d.Id, StringComparer.Ordinal).ToArray();
- var authoredLooks = ir.Instances.Where(i => i.Appearance is not null).Select(i => i.Appearance!)
+ var authoredLooks = (ir is null ? spatial!.Appearances.Values : ir.Instances.Where(i => i.Appearance is not null).Select(i => i.Appearance!))
.DistinctBy(a => a.Appearance).OrderBy(a => a.Appearance, StringComparer.Ordinal).ToArray();
var lookPaths = authoredLooks.Select((look, index) => (look.Appearance, Path: "/Looks/Authored_" + index))
.ToDictionary(p => p.Appearance, p => p.Path, StringComparer.Ordinal);
- var declaredPose = AssemblyKinematics.Evaluate(ir, evaluatedState ?? options.State ?? new Dictionary<string, double>());
- if (!declaredPose.IsSuccess || declaredPose.Instances.Any(instance => instance.ResolvedTransform is null
+ var declaredPose = ir is null ? null : AssemblyKinematics.Evaluate(ir, evaluatedState ?? options.State ?? new Dictionary<string, double>());
+ if (declaredPose is not null && (!declaredPose.IsSuccess || declaredPose.Instances.Any(instance => instance.ResolvedTransform is null
|| occurrences[instance.StableId].Transform.Length != 16
|| occurrences[instance.StableId].Transform.Any(value => !double.IsFinite(value))
- || occurrences[instance.StableId].Transform.Zip(instance.ResolvedTransform.Matrix, (a,b) => Math.Abs(a-b)).Any(delta => delta > 1e-9)))
+ || occurrences[instance.StableId].Transform.Zip(instance.ResolvedTransform.Matrix, (a,b) => Math.Abs(a-b)).Any(delta => delta > 1e-9))))
throw new InvalidOperationException("assembly-usd-mesh-state-mismatch");
if (options.DefinitionMaterials is not null && options.DefinitionMaterials.Keys.Any(identity => !definitions.Any(d => d.Identity == identity)))
throw new InvalidOperationException("assembly-usd-material-definition-unknown");
@@ -56,18 +80,18 @@ public static class AssemblyUsdExporter
var children = mesh.Occurrences.Where(o => o.ParentId == id).OrderBy(o => o.Path, StringComparer.Ordinal).ToArray();
for (var i = 0; i < children.Length; i++) Assign(children[i].Id, path + "/" + Identifier(children[i].Path.Split('.').Last()) + "_" + i);
}
- Assign(ir.RootInstanceStableId, "/Assembly");
+ Assign(rootId, "/" + rootPrim);
if (paths.Count != occurrences.Count) throw new InvalidOperationException("assembly-usd-invalid-hierarchy");
var definitionPaths = definitions.Select((d, i) => (d.Id, Path: "/Definitions/D_" + i)).ToDictionary(p => p.Id, p => p.Path);
var samples = (options.Samples ?? []).OrderBy(s => s.Time).ToArray();
if (samples.Any(s => !double.IsFinite(s.Time)) || samples.Select(s => s.Time).Distinct().Count() != samples.Length)
throw new InvalidOperationException("assembly-usd-invalid-sample-time");
- var poses = samples.Select(s => (s.Time, Pose: AssemblyKinematics.Evaluate(ir, s.State))).ToArray();
+ var poses = ir is null ? [] : samples.Select(s => (s.Time, Pose: AssemblyKinematics.Evaluate(ir, s.State))).ToArray();
if (poses.Any(p => !p.Pose.IsSuccess)) throw new InvalidOperationException("assembly-usd-invalid-sample-state");
var text = new StringBuilder();
void Line(string value = "") => text.Append(value).Append('\n');
Line("#usda 1.0");
- Line("("); Line(" defaultPrim = \"Assembly\""); Line(" metersPerUnit = 0.001"); Line(" upAxis = \"Z\"");
+ Line("("); Line($" defaultPrim = {Q(rootPrim)}"); Line(" metersPerUnit = 0.001"); Line(" upAxis = \"Z\"");
if (samples.Length > 0)
{ Line($" startTimeCode = {F(samples[0].Time)}"); Line($" endTimeCode = {F(samples[^1].Time)}"); Line(" timeCodesPerSecond = 24"); }
Line(")");
@@ -116,26 +140,28 @@ public static class AssemblyUsdExporter
Line(" token outputs:surface"); Line(" }"); Line(" }");
}
Line("}");
- var joints = ir.Joints ?? [];
+ var joints = ir?.Joints ?? [];
var bodies = joints.SelectMany(j => new[] { j.ParentOccurrenceId, j.ChildOccurrenceId }).ToHashSet();
void WriteOccurrence(string id, int depth)
{
var o = occurrences[id]; var indent = new string(' ', depth * 4);
var api = new List<string>();
- if (id == ir.RootInstanceStableId && joints.Count > 0) api.Add("PhysicsArticulationRootAPI");
+ if (id == rootId && joints.Count > 0) api.Add("PhysicsArticulationRootAPI");
if (bodies.Contains(id)) api.Add("PhysicsRigidBodyAPI");
Line($"{indent}def Xform {Q(paths[id].Split('/').Last())}" + (api.Count == 0 ? "" : $" (prepend apiSchemas = [{string.Join(", ", api.Select(Q))}])") + " {");
Line($"{indent} custom string aetheris:occurrenceIdentity = {Q(id)}");
Line($"{indent} custom string aetheris:sourcePath = {Q(o.Path)}");
- Line($"{indent} custom string aetheris:definitionIdentity = {Q(ir.Instances.Single(i => i.StableId == id).DefinitionIdentity)}");
+ Line($"{indent} custom string aetheris:definitionIdentity = {Q(ir?.Instances.Single(i => i.StableId == id).DefinitionIdentity ?? spatial!.DefinitionIdentities.GetValueOrDefault(id, ""))}");
+ foreach (var field in spatial?.Properties.GetValueOrDefault(id) ?? new Dictionary<string,string>())
+ Line($"{indent} custom string aetheris:{Identifier(field.Key)} = {Q(field.Value)}");
if (bodies.Contains(id)) { Line($"{indent} bool physics:rigidBodyEnabled = true"); Line($"{indent} bool physics:kinematicEnabled = true"); }
- if (id == ir.RootInstanceStableId)
+ if (id == rootId)
{
- Line($"{indent} custom string aetheris:sourceName = {Q(ir.Name)}");
- if (ir.Annotations?.Release is { } release)
+ Line($"{indent} custom string aetheris:sourceName = {Q(ir?.Name ?? mesh.Name)}");
+ if (ir?.Annotations?.Release is { } release)
foreach (var field in release.Fields.OrderBy(p => p.Key, StringComparer.Ordinal))
Line($"{indent} custom string aetheris:provenance:{field.Key} = {Q(field.Value)}");
- foreach (var note in ir.Annotations?.Notes ?? [])
+ foreach (var note in ir?.Annotations?.Notes ?? [])
{
Line($"{indent} custom string aetheris:pmi:{note.Name}:target = {Q(note.Target)}");
Line($"{indent} custom string aetheris:pmi:{note.Name}:text = {Q(note.Text)}");
@@ -165,7 +191,7 @@ public static class AssemblyUsdExporter
}
if (o.DefinitionId is not null)
{
- var look = ir.Instances.Single(i => i.StableId == id).Appearance;
+ var look = ir?.Instances.Single(i => i.StableId == id).Appearance ?? spatial?.Appearances.GetValueOrDefault(id);
Line($"{indent} def Xform \"Geometry\" (prepend references = <{definitionPaths[o.DefinitionId]}>; instanceable = true" +
(look is null ? "" : "; prepend apiSchemas = [\"MaterialBindingAPI\"]") + ") {");
if (look is not null)
@@ -181,9 +207,21 @@ public static class AssemblyUsdExporter
Line($"{indent} }}");
}
foreach (var child in mesh.Occurrences.Where(c => c.ParentId == id).OrderBy(c => c.Path, StringComparer.Ordinal)) WriteOccurrence(child.Id, depth + 1);
+ if (id == rootId)
+ foreach (var (camera, index) in (spatial?.Cameras ?? []).Select((c, i) => (c, i)))
+ {
+ Line($"{indent} def Camera {Q(Identifier(camera.Name) + "_" + index)} {{");
+ Line($"{indent} matrix4d xformOp:transform = {Matrix(camera.Transform)}");
+ Line($"{indent} uniform token[] xformOpOrder = [\"xformOp:transform\"]");
+ Line($"{indent} float verticalAperture = 20.955");
+ Line($"{indent} float horizontalAperture = 20.955");
+ Line($"{indent} float focalLength = {F(20.955 / (2 * Math.Tan(camera.FovDegrees * Math.PI / 360)))}");
+ Line($"{indent} float2 clippingRange = (1, 100000000)");
+ Line($"{indent} }}");
+ }
Line(indent + "}");
}
- WriteOccurrence(ir.RootInstanceStableId, 0);
+ WriteOccurrence(rootId, 0);
Line("def Scope \"Joints\" {");
foreach (var (j, i) in joints.OrderBy(j => j.Name, StringComparer.Ordinal).Select((j, i) => (j, i)))
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
index f46d0432..6d298519 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -13,7 +13,7 @@ internal static class CanonicalStaticAuthoring
private sealed record Template(string Name, string Type, string Parameter, string Body, FirmamentV2SourceSpan Span);
/// <summary>Assembly consumes the same checked Record/Set values, but yields product-tree declarations.</summary>
- internal static Result? ExpandAssemblyPatterns(string source, List<string> diagnostics)
+ internal static Result? ExpandAssemblyPatterns(string source, List<string> diagnostics, bool spatial = false)
{
var points = ConceptPointAuthoring.Expand(source, diagnostics);
if (points is null) return null;
@@ -35,7 +35,19 @@ internal static class CanonicalStaticAuthoring
if (close<0) { diagnostics.Add(Prefix+"assembly-pattern-catalog-malformed"); return null; }
source.CopyTo(header.Index,catalog,header.Index,close-header.Index+1);
}
- var data=Expand(new string(catalog),diagnostics);
+ var catalogSource = new string(catalog);
+ if (spatial)
+ {
+ // Scene-scale Set data normalizes to the existing typed mm catalog.
+ // Strings and authored identifiers are never unit-converted.
+ var tokens = FirmamentLanguageAnalysisService.Lex(catalogSource);
+ for (var i = tokens.Count - 2; i >= 0; i--)
+ if (tokens[i].Shape == "number" && tokens[i+1].Text == "m" && tokens[i].Start+tokens[i].Length == tokens[i+1].Start
+ && double.TryParse(tokens[i].Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var metres))
+ catalogSource = catalogSource.Remove(tokens[i].Start,tokens[i].Length+1)
+ .Insert(tokens[i].Start,(metres*1000).ToString("R",CultureInfo.InvariantCulture)+"mm");
+ }
+ var data=Expand(catalogSource,diagnostics);
if (data?.Document is null || diagnostics.Count>0) return null;
var sets=(data.Document.Sets ?? []).ToDictionary(s=>s.Name,StringComparer.Ordinal);
var changes=new List<(int Start,int Length,string Text)>();
@@ -58,10 +70,10 @@ internal static class CanonicalStaticAuthoring
var mapping=SubstituteSetMapping(arrow.Groups["mapping"].Value,arrow.Groups["binder"].Value,entry);
if (Regex.IsMatch(mapping,$@"\b{Regex.Escape(arrow.Groups["binder"].Value)}\."))
{ diagnostics.Add(Prefix+"assembly-pattern-member-unresolved:"+name+"."+entry.Name); continue; }
- output.Add($"<Assembly {entry.Name}> {identity}\n{mapping}\n</Assembly>");
+ output.Add(spatial ? $"<Group {entry.Name}>\n{mapping}\n</Group>" : $"<Assembly {entry.Name}> {identity}\n{mapping}\n</Assembly>");
associations.Add(new(name+"."+entry.Name,set.Name,entry.Name,entry.Value,entry.SourceOrder,entry.Provenance));
}
- changes.Add((header.Index,close-header.Index+1,$"<Assembly {name}> {identity}\n{string.Join(Environment.NewLine,output)}\n</Assembly>"));
+ changes.Add((header.Index,close-header.Index+1,spatial ? $"<Group {name}>\n{string.Join(Environment.NewLine,output)}\n</Group>" : $"<Assembly {name}> {identity}\n{string.Join(Environment.NewLine,output)}\n</Assembly>"));
patterns.Add(new(name,set.Name,"Assembly",set.Entries.Count,associations.Select(a=>a.GeneratedId).ToArray(),new(header.Index,close-header.Index+1),associations,
sites.Recipes.GetValueOrDefault(set.Name)));
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index 4955731e..9a363846 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -1,4 +1,5 @@
using System.Text;
+using Aetheris.Kernel.Firmament.Scene;
using Aetheris.Kernel.Firmament.Assembly;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
@@ -31,6 +32,12 @@ public static class FirmamentLanguageAnalysisService
var lexemes = Lex(FirmamentSourceSpelling.Normalize(source));
var tokens = lexemes.Select((lexeme, index) => new FirmamentLanguageToken(
lexeme.Start, lexeme.Length, Classify(lexemes, index))).ToArray();
+ if (SceneAuthoring.HasRoot(source))
+ {
+ var scene = SceneAuthoring.Parse(source, document);
+ return new(document, revision, tokens, scene.Diagnostics.Select(d => new FirmamentLanguageDiagnostic(
+ "error", d.Code, d.Message, 0, 0)).ToArray());
+ }
// Imported authoring modules need project context. Do not feed them into
// the unrelated concrete-part parser and manufacture syntax errors.
if (lexemes.Any(t => t.Text == "Include" && t.Shape == "identifier"))
@@ -102,6 +109,7 @@ public static class FirmamentLanguageAnalysisService
public static FirmamentLanguageAnalysis Analyze(FirmamentProjectSnapshot project, string document, string revision)
{
if (!project.TryResolve(document, out var source)) throw new ArgumentException("Document is absent from the snapshot.", nameof(document));
+ if (SceneAuthoring.HasRoot(source)) return Analyze(source,document,revision);
var tokens = Lex(FirmamentSourceSpelling.Normalize(source));
var parsed = new AssemblyM0Parser().ParseProject(project);
return new(document, revision, tokens.Select((t, i) => new FirmamentLanguageToken(t.Start, t.Length, Classify(tokens, i))).ToArray(),
@@ -148,6 +156,16 @@ public static class FirmamentLanguageAnalysisService
public static FirmamentLanguageFormat Format(string source, string document, string revision)
{
+ if (SceneAuthoring.HasRoot(source))
+ {
+ if (!SceneAuthoring.Parse(source,document).IsSuccess)
+ throw new InvalidOperationException("Format Document requires valid Scene source. Fix syntax errors first.");
+ // Preserve generic specialization text, authored ports and pattern keys.
+ var scene = FormatConventions(source,document,revision);
+ if (!SceneAuthoring.Parse(scene.Text,document).IsSuccess)
+ throw new InvalidOperationException("Scene formatting changed parser admission.");
+ return scene;
+ }
if (!FirmamentV2Parser.Parse(source).IsSuccess)
throw new InvalidOperationException("Format Document requires valid Firmament source. Fix syntax errors first.");
var preferred = FirmamentSourceSpelling.Prefer(source);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs
index 11277fd9..3707411f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs
@@ -30,6 +30,7 @@ public static class FirmamentLanguageService
var composition = ActiveCompositionConstruct(source, offset);
if (composition is not null)
{
+ beforePrefix = source[Math.Max(lineStart,composition.Value.Open+1)..prefixStart];
fields = FirmamentSchemaAuthoringFields.For(composition.Value.Name);
context = composition.Value.Name;
}
@@ -93,6 +94,13 @@ public static class FirmamentLanguageService
if (!present.Contains("Members")) missing.Add("Members");
}
if (context == "Helix" && !present.Contains("Pitch") && !present.Contains("Height")) missing.Add("Pitch or Height");
+ if (context == "Scene")
+ {
+ var entries = FirmamentSemanticSchemas.All.Where(item => item.Context == "Scene" && item.Entry is not null
+ && item.Name.StartsWith(prefix,StringComparison.OrdinalIgnoreCase))
+ .Select(item => new FirmamentLanguageEntry(item.Id.Value,item.Name,item.Context!,FirmamentSourceSpelling.Prefer(item.Entry!))).ToArray();
+ return new(document,revision,context,prefixStart,prefix.Length,candidates,missing,entries);
+ }
return new(document, revision, context, prefixStart, prefix.Length, candidates, missing);
}
@@ -131,7 +139,7 @@ public static class FirmamentLanguageService
{
// Ignore comments/strings and balance nested blocks in incomplete drafts.
var prefix = Regex.Replace(source[..offset], @"//[^\r\n]*|/\*[\s\S]*?\*/|""(?:\\.|[^""\\])*""", m => new string(' ', m.Length));
- var names = "WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform";
+ var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform";
var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<[^>]+>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");
foreach (Match header in matches.Cast<Match>().Reverse())
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
index 1b01fcba..86f9cddf 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
@@ -182,7 +182,8 @@ public static class FirmamentSourceSpelling
}
// Bounded owner vocabularies not yet projected through generated schema.
Add("Model", "Units Material");
- Add("Assembly Subassembly", "Anchor Provenance");
+ Add("Scene", "Units");
+ Add("Assembly Subassembly", "Anchor Provenance Appearance");
Add("Part Occurrence", "Material Appearance");
Add("Plane DatumPlane", "Origin Normal Up From Offset RotateLocal Clocking");
Add("DatumFrame", "On At X");
diff --git a/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs b/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs
new file mode 100644
index 00000000..803399bf
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs
@@ -0,0 +1,341 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Semantics;
+
+namespace Aetheris.Kernel.Firmament.Scene;
+
+[FirmamentConstruct("Scene", "Scene", Context = "Document", Entry = "Scene Factory { Units: m; }", Description = "Spatial composition above independently engineered Parts and Assemblies. Placements imply no mechanical relationship.")]
+[FirmamentField("Units", "Units", FirmamentSchemaValueKind.Choice, Required = true, Choices = ["m", "mm"])]
+public static class SceneDeclaration { }
+
+[FirmamentConstruct("Room", "Room", Context = "Scene", Entry = "Room warehouse { Size: [30m, 18m, 7m]; }", Description = "A rectangular spatial enclosure with stable named floor, ceiling and wall boundaries.")]
+[FirmamentField("Size", "Size", FirmamentSchemaValueKind.Vector, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("At", "At", FirmamentSchemaValueKind.Vector, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Thickness", "Thickness", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Default = "100mm")]
+[FirmamentField("Appearance", "Appearance", FirmamentSchemaValueKind.ConstructReference)]
+[FirmamentOutput("floor", "floor", "SceneBoundary", SourceAddressable = true)]
+[FirmamentOutput("ceiling", "ceiling", "SceneBoundary", SourceAddressable = true)]
+[FirmamentOutput("northWall", "northWall", "SceneBoundary", SourceAddressable = true)]
+[FirmamentOutput("southWall", "southWall", "SceneBoundary", SourceAddressable = true)]
+[FirmamentOutput("eastWall", "eastWall", "SceneBoundary", SourceAddressable = true)]
+[FirmamentOutput("westWall", "westWall", "SceneBoundary", SourceAddressable = true)]
+public static class RoomDeclaration { }
+
+[FirmamentConstruct("Door", "Door", Context = "Scene", Entry = "Door loadingBay { On: warehouse.southWall; Width: 4m; Height: 4.5m; Along: 6m; }", Description = "Room-owned rectangular aperture measured from the wall's minimum X or Y; bottom lies on the floor.")]
+[FirmamentField("On", "On", FirmamentSchemaValueKind.ConstructReference, Required = true)]
+[FirmamentField("Width", "Width", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Height", "Height", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Along", "Along", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+public static class DoorDeclaration { }
+
+[FirmamentConstruct("Window", "Window", Context = "Scene", Entry = "Window officeGlass { On: warehouse.eastWall; Width: 6m; Height: 2.5m; Sill: 1m; Along: 4m; }", Description = "Room-owned rectangular wall aperture; no glazing or curtain-wall system.")]
+[FirmamentField("On", "On", FirmamentSchemaValueKind.ConstructReference, Required = true)]
+[FirmamentField("Width", "Width", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Height", "Height", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Along", "Along", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Sill", "Sill", FirmamentSchemaValueKind.Length, Required = true, Unit = FirmamentUnitKind.Length)]
+public static class WindowDeclaration { }
+
+[FirmamentConstruct("SceneCamera", "Camera", Context = "Scene", Entry = "Camera hero { Position: [35m, -15m, 20m]; LookAt: [15m, 9m, 1m]; Fov: 45deg; }", Description = "Presentation state in a Z-up world; independent of engineering geometry.")]
+[FirmamentField("Position", "Position", FirmamentSchemaValueKind.Vector, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("LookAt", "LookAt", FirmamentSchemaValueKind.Vector, Required = true, Unit = FirmamentUnitKind.Length)]
+[FirmamentField("Fov", "Fov", FirmamentSchemaValueKind.Angle, Required = true, Unit = FirmamentUnitKind.Angle)]
+public static class SceneCameraDeclaration { }
+
+public sealed record SceneRoom(string Name, double[] SizeMm, double[] AtMm, double ThicknessMm, string? Appearance, SemanticSourceSpan Span);
+public sealed record SceneOpening(string Name, string Kind, string Boundary, double WidthMm, double HeightMm, double AlongMm, double SillMm, SemanticSourceSpan Span);
+public sealed record SceneCamera(string Name, double[] PositionMm, double[] LookAtMm, double FovDegrees, SemanticSourceSpan Span)
+{
+ public double[] WorldTransform()
+ {
+ var z = new Vector3D(PositionMm[0]-LookAtMm[0], PositionMm[1]-LookAtMm[1], PositionMm[2]-LookAtMm[2]);
+ if (!z.TryNormalize(out z)) throw new InvalidOperationException("scene-camera-degenerate");
+ var up = Math.Abs(z.Z) > .999 ? new Vector3D(0,1,0) : new Vector3D(0,0,1);
+ var x = up.Cross(z); x.TryNormalize(out x); var y = z.Cross(x);
+ return [x.X,x.Y,x.Z,0,y.X,y.Y,y.Z,0,z.X,z.Y,z.Z,0,PositionMm[0],PositionMm[1],PositionMm[2],1];
+ }
+}
+public sealed record SceneOccurrenceSource(string Path, string Kind, string Definition, AssemblyFrameTransformSource Placement,
+ string From, string? Appearance, SemanticSourceSpan Span, string? PatternKey = null);
+public sealed record SceneSource(string Name, string Units, string DefinitionSource, string SourceIdentity,
+ IReadOnlyList<SceneRoom> Rooms, IReadOnlyList<SceneOpening> Openings, IReadOnlyList<SceneCamera> Cameras,
+ IReadOnlyList<SceneOccurrenceSource> Occurrences, AssemblyAppearanceCatalog Looks,
+ IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns);
+public sealed record SceneParseResult(SceneSource? Source, IReadOnlyList<AssemblyDiagnostic> Diagnostics)
+{ public bool IsSuccess => Source is not null && Diagnostics.All(d => d.Severity != AssemblyDiagnosticSeverity.Error); }
+
+/// <summary>Scene owns spatial syntax. Engineering definitions and frame math stay with their existing producers.</summary>
+public static class SceneAuthoring
+{
+ public static bool HasRoot(string source)
+ {
+ var tokens=FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();
+ var depth=0;
+ for(var i=0;i+1<tokens.Length;i++)
+ {
+ if (depth == 0 && tokens[i].Shape == "identifier" && tokens[i].Text == "Scene" && tokens[i+1].Shape == "identifier") return true;
+ if (tokens[i].Text == "{") depth++; else if (tokens[i].Text == "}") depth--;
+ }
+ return false;
+ }
+
+ public static SceneParseResult Parse(string input, string sourceIdentity = "<memory>")
+ {
+ var diagnostics = new List<AssemblyDiagnostic>();
+ try { return ParseCore(input, sourceIdentity, diagnostics); }
+ catch (SceneSyntaxException ex) { diagnostics.Add(new(ex.Code, ex.Message)); return new(null, diagnostics); }
+ }
+
+ private static SceneParseResult ParseCore(string input, string identity, List<AssemblyDiagnostic> diagnostics)
+ {
+ var normalized = FirmamentSourceSpelling.Normalize(input);
+ // Comments are erased at their lexical spans, preserving strings and positions.
+ var chars = normalized.ToCharArray();
+ foreach (var t in FirmamentLanguageAnalysisService.Lex(normalized).Where(t => t.Shape == "comment"))
+ Array.Fill(chars, ' ', t.Start, t.Length);
+ var text = new string(chars);
+ var authoredText = text;
+ if (Regex.IsMatch(text,@"<\s*/?\s*Group\b")) Fail("scene-group-reserved","Pattern groups are generated by the shared expander; author Pattern over a keyed Set.");
+ var original = new Reader(text, identity);
+ var definitionEnd = 0;
+ var geometryDeclarations = new List<string>();
+ while (!original.End && original.Peek != "Scene")
+ {
+ var kind = original.Peek;
+ if (kind is not ("Template" or "Record" or "Static" or "Function" or "Appearance" or "Material"))
+ Fail("scene-declaration-unsupported", $"Unsupported Scene module declaration '{kind}'. Use AssemblyFile for independently compiled assemblies.");
+ var declarationStart = original.Position;
+ original.SkipDeclaration(); definitionEnd = original.Position;
+ var declaration = text[declarationStart..definitionEnd];
+ // Scene keyed Sets and preview looks are composition inputs, not geometry inputs.
+ if (kind is not ("Appearance" or "Material") && !Regex.IsMatch(declaration,@"^Static\s+\w+\s*:\s*Set\s*<"))
+ geometryDeclarations.Add(declaration);
+ }
+ if (original.End) Fail("scene-root-missing", "Expected one Scene root.");
+ original.Expect("Scene"); var name = original.Identifier();
+ original.Block(); original.Optional(";");
+ if (!original.End) Fail("scene-multiple-roots", "A Scene document requires exactly one Scene root and no trailing declarations.");
+ var definitionSource = string.Join("\n",geometryDeclarations);
+ var errors = new List<string>();
+ var expanded = CanonicalStaticAuthoring.ExpandAssemblyPatterns(text, errors, spatial: true);
+ foreach (var error in errors) diagnostics.Add(new("scene-pattern-invalid", error));
+ if (expanded is null || errors.Count != 0) return new(null, diagnostics);
+ text = expanded.Source;
+ var looks = AssemblyAppearanceAuthoring.Parse(ref text, diagnostics, out _);
+ var reader = new Reader(text, identity);
+ while (!reader.End && reader.Peek != "Scene") reader.SkipDeclaration();
+ reader.Expect("Scene"); reader.Identifier(); var sceneBody = reader.Block();
+ var body = new Reader(sceneBody.Text, identity, sceneBody.Start);
+ var units = ""; var rooms = new List<SceneRoom>(); var openings = new List<SceneOpening>();
+ var cameras = new List<SceneCamera>(); var occurrences = new List<SceneOccurrenceSource>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ var patterns = expanded.Document?.Patterns ?? [];
+ while (!body.End)
+ {
+ if (body.Optional(";")) continue;
+ if (body.Peek == "Units")
+ {
+ body.Take(); body.Expect(":"); var value = body.Take(); body.Optional(";");
+ if (units.Length != 0 || value is not ("m" or "mm")) Fail("scene-units-invalid", "Declare units: m or units: mm exactly once; coordinates still require suffixes.");
+ units = value; continue;
+ }
+ if (body.Peek == "<") { ReadOccurrence(body, name); continue; }
+ var start = body.Position; var kind = body.Take(); var id = body.Identifier(); var block = body.Block();
+ if (!names.Add(id)) Fail("scene-name-collision", $"Scene name '{id}' is duplicated.");
+ var span = AuthoredSpan(kind,id);
+ var f = Fields(block.Text, identity);
+ switch (kind)
+ {
+ case "Room":
+ Check(f, "Size At Thickness Appearance", "Size");
+ var size = Vector(f["Size"]); var at = Vector(f.GetValueOrDefault("At", "[0mm,0mm,0mm]"));
+ var thickness = Length(f.GetValueOrDefault("Thickness", "100mm"));
+ if (size.Any(v => v <= 0) || thickness <= 0) Fail("scene-room-size-invalid", "Room dimensions and thickness must be positive.");
+ rooms.Add(new(id,size,at,thickness,f.GetValueOrDefault("Appearance"),span)); break;
+ case "Door": case "Window":
+ Check(f, kind == "Door" ? "On Width Height Along" : "On Width Height Along Sill", kind == "Door" ? "On Width Height Along" : "On Width Height Along Sill");
+ openings.Add(new(id,kind,f["On"],Length(f["Width"]),Length(f["Height"]),Length(f["Along"]),kind == "Window" ? Length(f["Sill"]) : 0,span)); break;
+ case "Camera":
+ Check(f,"Position LookAt Fov","Position LookAt Fov");
+ var position = Vector(f["Position"]); var target = Vector(f["LookAt"]); var fov = Angle(f["Fov"]);
+ if (fov <= 0 || fov >= 180 || position.SequenceEqual(target)) Fail("scene-camera-invalid", "Camera requires distinct position/lookAt and 0 < fov < 180deg.");
+ cameras.Add(new(id,position,target,fov,span)); break;
+ default: Fail("scene-construct-unsupported", $"'{kind}' is not an X0 Scene construct; mechanical relationships belong to an Assembly."); break;
+ }
+ }
+ if (units.Length == 0) Fail("scene-units-required", "Scene requires units: m or units: mm.");
+ foreach (var opening in openings)
+ {
+ var path = opening.Boundary.Split('.');
+ var room = path.Length == 2 ? rooms.SingleOrDefault(r => r.Name == path[0]) : null;
+ if (room is null || path[1] is not ("northWall" or "southWall" or "eastWall" or "westWall"))
+ Fail("scene-opening-boundary-invalid", $"Opening '{opening.Name}' requires a declared Room wall, e.g. warehouse.southWall.");
+ var extent = path[1] is "northWall" or "southWall" ? room.SizeMm[0] : room.SizeMm[1];
+ if (opening.WidthMm <= 0 || opening.HeightMm <= 0 || opening.AlongMm < 0 || opening.SillMm < 0
+ || opening.AlongMm+opening.WidthMm > extent || opening.SillMm+opening.HeightMm > room.SizeMm[2])
+ Fail("scene-opening-outside-wall", $"Opening '{opening.Name}' must lie inside its wall bounds.");
+ foreach (var other in openings.Where(o => o != opening && o.Boundary == opening.Boundary))
+ if (opening.AlongMm < other.AlongMm+other.WidthMm && other.AlongMm < opening.AlongMm+opening.WidthMm
+ && opening.SillMm < other.SillMm+other.HeightMm && other.SillMm < opening.SillMm+opening.HeightMm)
+ Fail("scene-openings-overlap", $"Openings '{opening.Name}' and '{other.Name}' overlap.");
+ }
+ foreach (var look in rooms.Select(r => r.Appearance).Concat(occurrences.Select(o => o.Appearance)).OfType<string>())
+ if (!looks.Appearances.ContainsKey(look)) Fail("scene-appearance-unknown", $"Unknown Appearance '{look}'.");
+ return new(new(name,units,definitionSource,identity,rooms,openings,cameras,occurrences,looks,patterns),diagnostics);
+
+ void ReadOccurrence(Reader r, string parent)
+ {
+ var start = r.Position; r.Expect("<"); var kind = r.Take(); var id = r.Identifier();
+ if (kind == "Group")
+ {
+ r.Expect(">"); var group = parent+"."+id;
+ while (!(r.Peek == "<" && r.Next == "/")) ReadOccurrence(r,group);
+ r.Expect("<"); r.Expect("/"); r.Expect("Group"); r.Expect(">"); return;
+ }
+ if (kind is not ("Part" or "Assembly")) Fail("scene-occurrence-kind-invalid", "Scene occurrences are Part or Assembly.");
+ r.Expect("="); var definition = r.UntilTagEnd(); var content = r.UntilClosing(kind);
+ var prefix=$"<{kind} {id}>"; var suffix=$"</{kind}>";
+ var occurrenceBody=FirmamentSourceSpelling.Normalize(prefix+content.Text+suffix)[prefix.Length..^suffix.Length];
+ var placementReader = new Reader(occurrenceBody,identity,content.Start); string? appearance = null; string? placement = null;
+ while (!placementReader.End)
+ {
+ if (placementReader.Optional(";")) continue;
+ if (placementReader.Optional("Appearance"))
+ { if (appearance is not null) Fail("scene-duplicate-field","Repeated appearance."); placementReader.Expect(":"); appearance=placementReader.Identifier(); placementReader.Optional(";"); }
+ else if (placementReader.Optional("Placement"))
+ { if (placement is not null) Fail("scene-placement-duplicate","Repeated Placement."); placement=placementReader.Block().Text; }
+ else Fail("scene-occurrence-field-invalid", $"Occurrence '{id}' has unknown field '{placementReader.Peek}' at {placementReader.Position}. Expected Placement and optional appearance; mechanical semantics remain in its definition.");
+ }
+ if (placement is null) Fail("scene-placement-required", $"Occurrence '{id}' requires Placement.");
+ var fields = Fields(placement,identity); var from = fields.GetValueOrDefault("From", "Origin");
+ fields.Remove("From");
+ if (fields.TryGetValue("TranslateLocal",out var translation)) fields["TranslateLocal"]="["+string.Join(",",Vector(translation).Select(v => v.ToString("R",CultureInfo.InvariantCulture)+"mm"))+"]";
+ var target = AssemblyFrameAuthoring.Parse(id,string.Join(";",fields.Select(f => f.Key+":"+f.Value))+";","To",identity,diagnostics);
+ if (target is null) Fail("scene-placement-invalid", $"Invalid Placement for '{id}'.");
+ var path = parent+"."+id;
+ if (occurrences.Any(o => o.Path == path)) Fail("scene-occurrence-collision", $"Duplicate occurrence '{path}'.");
+ var pattern = patterns.FirstOrDefault(p => path.StartsWith(name+"."+p.Name+".",StringComparison.Ordinal));
+ var key = pattern is null ? null : path.Split('.')[2];
+ var span = pattern is null ? AuthoredSpan(kind,id,tag:true) : AuthoredSpan("Pattern",pattern.Name);
+ occurrences.Add(new(path,kind,definition,target,from,appearance,span,key));
+ }
+ SemanticSourceSpan AuthoredSpan(string kind,string id,bool tag=false)
+ {
+ var t=FirmamentLanguageAnalysisService.Lex(authoredText);
+ for(var i=0;i+1<t.Count;i++)
+ {
+ if(t[i].Text != kind || t[i+1].Text != id || t[i].Shape != "identifier") continue;
+ if(tag && (i == 0 || t[i-1].Text != "<")) continue;
+ var start=tag ? t[i-1].Start : t[i].Start;
+ if(tag)
+ {
+ for(var j=i+2;j+3<t.Count;j++)
+ if(t[j].Text == "<" && t[j+1].Text == "/" && t[j+2].Text == kind && t[j+3].Text == ">")
+ return new(identity,start,t[j+3].Start+t[j+3].Length-start);
+ }
+ else
+ {
+ var depth=0; var seen=false;
+ for(var j=i+2;j<t.Count;j++)
+ { if(t[j].Text == "{") { depth++; seen=true; } else if(t[j].Text == "}" && --depth == 0 && seen) return new(identity,start,t[j].Start+1-start); }
+ }
+ }
+ Fail("scene-source-span-unresolved",$"Cannot locate authored declaration '{kind} {id}'."); return default!;
+ }
+ }
+
+ internal static Dictionary<string,string> Fields(string source, string identity)
+ {
+ var r = new Reader(source,identity); var fields = new Dictionary<string,string>(StringComparer.Ordinal);
+ while (!r.End)
+ {
+ if (r.Optional(";")) continue;
+ var name = r.Identifier(); r.Expect(":"); var value = r.FieldValue();
+ if (!fields.TryAdd(name,value)) Fail("scene-duplicate-field", $"Repeated field '{name}'.");
+ }
+ return fields;
+ }
+ private static void Check(Dictionary<string,string> f,string allowed,string required)
+ {
+ if (f.Keys.Except(allowed.Split(' ')).Any() || required.Split(' ').Any(k => !f.ContainsKey(k)))
+ Fail("scene-fields-invalid", $"Required fields: {required}; allowed fields: {allowed}.");
+ }
+ internal static double Length(string value)
+ {
+ var m = Regex.Match(value.Trim(),@"^(?<n>[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)(?<u>mm|m)$");
+ double n = 0;
+ if (!m.Success || !double.TryParse(m.Groups["n"].Value,NumberStyles.Float,CultureInfo.InvariantCulture,out n)
+ || !double.IsFinite(n) || !double.IsFinite(n*(m.Groups["u"].Value == "m" ? 1000 : 1)))
+ Fail("scene-length-unit-required", $"Expected a finite length with m or mm suffix, got '{value}'.");
+ return n*(m.Groups["u"].Value == "m" ? 1000 : 1);
+ }
+ private static double Angle(string value)
+ {
+ double n = 0;
+ if (!value.EndsWith("deg",StringComparison.Ordinal) || !double.TryParse(value[..^3],NumberStyles.Float,CultureInfo.InvariantCulture,out n) || !double.IsFinite(n))
+ Fail("scene-angle-invalid","Scene camera fov requires a finite deg literal.");
+ return n;
+ }
+ internal static double[] Vector(string value)
+ {
+ if (!value.StartsWith('[') || !value.EndsWith(']')) Fail("scene-vector-invalid","Expected a three-length vector.");
+ var v = value[1..^1].Split(',',StringSplitOptions.TrimEntries);
+ if (v.Length != 3) Fail("scene-vector-invalid","Expected a three-length vector.");
+ return v.Select(Length).ToArray();
+ }
+ [System.Diagnostics.CodeAnalysis.DoesNotReturn]
+ internal static void Fail(string code,string message) => throw new SceneSyntaxException(code,message);
+ private sealed class SceneSyntaxException(string code,string message) : Exception(message) { internal string Code { get; } = code; }
+
+ private sealed class Reader
+ {
+ private readonly string source; private readonly string identity; private readonly int offset;
+ private readonly List<FirmamentLanguageAnalysisService.Lexeme> tokens; private int index;
+ internal Reader(string text,string identity,int offset=0) { source=text; this.identity=identity; this.offset=offset; tokens=FirmamentLanguageAnalysisService.Lex(text).Where(t => t.Shape != "comment").ToList(); }
+ internal bool End => index >= tokens.Count;
+ internal string Peek => End ? "" : tokens[index].Text;
+ internal string Next => index+1 >= tokens.Count ? "" : tokens[index+1].Text;
+ internal int Position => offset+(End ? source.Length : tokens[index].Start);
+ internal string Take() { if (End) Fail("scene-syntax-invalid",$"Unexpected end of {identity}."); return tokens[index++].Text; }
+ internal bool Optional(string s) { if (Peek != s) return false; index++; return true; }
+ internal void Expect(string s) { if (!Optional(s)) Fail("scene-syntax-invalid",$"Expected '{s}', got '{Peek}' at {Position}."); }
+ internal string Identifier() { if (End || tokens[index].Shape != "identifier") Fail("scene-syntax-invalid",$"Expected name at {Position}."); return Take(); }
+ internal (string Text,int Start) Block()
+ {
+ Expect("{"); var start=index == 0 ? 0 : tokens[index-1].Start+1; var depth=1;
+ while (!End) { var t=tokens[index++]; if (t.Text == "{") depth++; if (t.Text == "}") depth--;
+ if (t.Text == "}" && depth == 0) return (source[start..t.Start],offset+start); }
+ Fail("scene-syntax-invalid","Unclosed declaration."); return default;
+ }
+ internal void SkipDeclaration() { while (!End && Peek != "{") Take(); Block(); Optional(";"); }
+ internal string FieldValue()
+ {
+ var start=End ? source.Length : tokens[index].Start; var end=start; var depth=0;
+ while (!End)
+ {
+ if (depth == 0 && (Peek == ";" || (end > start && tokens[index].Shape == "identifier" && Next == ":"))) break;
+ var t=tokens[index++]; end=t.Start+t.Length;
+ if (t.Text is "[" or "{" or "(") depth++; else if (t.Text is "]" or "}" or ")") depth--;
+ if (depth < 0) Fail("scene-fields-invalid","Unbalanced field value.");
+ }
+ if (depth != 0 || start == end) Fail("scene-fields-invalid","Empty or unbalanced field value.");
+ Optional(";"); return source[start..end].Trim();
+ }
+ internal string UntilTagEnd()
+ {
+ if (End || Peek == ">") Fail("scene-syntax-invalid","Expected an occurrence definition before the closing tag.");
+ var start=tokens[index].Start; var depth=0;
+ while (!End) { var t=tokens[index++]; if (t.Text == "<") depth++; else if (t.Text == ">") { if (depth == 0) return source[start..t.Start].Trim(); depth--; } }
+ Fail("scene-syntax-invalid","Unclosed occurrence tag."); return "";
+ }
+ internal (string Text,int Start) UntilClosing(string kind)
+ {
+ var start=End ? source.Length : tokens[index].Start;
+ while (!End) { if (Peek == "<" && Next == "/") { var end=tokens[index].Start; Expect("<"); Expect("/"); Expect(kind); Expect(">"); return (source[start..end],offset+start); } Take(); }
+ Fail("scene-syntax-invalid","Unclosed occurrence."); return default;
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs b/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs
new file mode 100644
index 00000000..f81583bc
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs
@@ -0,0 +1,234 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Semantics;
+
+namespace Aetheris.Kernel.Firmament.Scene;
+
+public sealed record SceneBoundary(string Path, string Room, string Kind, double[] Frame, double WidthMm, double HeightMm,
+ IReadOnlyList<string> Openings);
+public sealed record SceneNode(string Path, string Kind, string DefinitionIdentity, string PlacementAuthority,
+ SemanticSourceSpan Span, string? PatternKey = null);
+public sealed record ScenePerformance(double BindMilliseconds, double DefinitionCompilationMilliseconds, double CompositionMilliseconds,
+ int UniqueEngineeringDefinitions, int ReusedEngineeringDefinitions, int RebuiltEngineeringDefinitions, double DisplayPreparationMilliseconds);
+public sealed record CompiledScene(SceneSource Source, AssemblyDisplayMeshDocument Display, IReadOnlyList<SceneBoundary> Boundaries,
+ IReadOnlyList<SceneNode> Nodes, IReadOnlyDictionary<string, AssemblyAppearanceBinding> Appearances,
+ IReadOnlyList<AssemblyDefinitionReuse> Reuse, ScenePerformance Performance, double[] MinimumMm, double[] MaximumMm);
+public sealed record SceneCompilationResult(CompiledScene? Scene, IReadOnlyList<AssemblyDiagnostic> Diagnostics)
+{ public bool IsSuccess => Scene is not null && Diagnostics.All(d => d.Severity != AssemblyDiagnosticSeverity.Error); }
+
+/// <summary>Retained scene composition reuses the existing immutable STEP definition cache.
+/// Each independently engineered assembly keeps its own ordinary compiler/session.
+/// Scene owns display/environment and occurrence state, never a BRep product.</summary>
+public sealed class FirmamentSceneSession : IDisposable
+{
+ private readonly object gate = new();
+ private readonly AssemblyDefinitionCache parts = new(256);
+ private readonly Dictionary<string,FirmamentCompilationSession> assemblies = new(StringComparer.OrdinalIgnoreCase);
+ private bool disposed;
+ public SceneCompilationResult CompileFile(string path) => Compile(File.ReadAllText(path),Path.GetFullPath(path));
+ public SceneCompilationResult Compile(string source, string sourceIdentity = "<memory>")
+ {
+ lock (gate)
+ {
+ ObjectDisposedException.ThrowIf(disposed,this);
+ var watch = Stopwatch.StartNew(); var parsed = SceneAuthoring.Parse(source,sourceIdentity);
+ if (!parsed.IsSuccess) return new(null,parsed.Diagnostics);
+ var bindMs=watch.Elapsed.TotalMilliseconds; watch.Restart(); parts.BeginBuild();
+ var s=parsed.Source!; var diagnostics=parsed.Diagnostics.ToList();
+ var definitions=new Dictionary<string,AssemblyDisplayMeshDefinition>(StringComparer.Ordinal);
+ var occurrences=new List<AssemblyDisplayMeshOccurrence>(); var nodes=new List<SceneNode>();
+ var looks=new Dictionary<string,AssemblyAppearanceBinding>(StringComparer.Ordinal);
+ var compiledAssemblies=new Dictionary<string,AssemblyM1CompilationResult>(StringComparer.OrdinalIgnoreCase);
+ var preparedAssemblies=new Dictionary<string,AssemblyDisplayMeshDocument>(StringComparer.OrdinalIgnoreCase);
+ double displayMs=0;
+ var materializedParts=new Dictionary<string,MaterializedAssemblyDefinition>(StringComparer.Ordinal);
+ foreach (var item in s.Occurrences)
+ {
+ if (item.Kind == "Assembly")
+ {
+ var match=Regex.Match(item.Definition,"^AssemblyFile<\\s*\"(?<path>[^\"]+)\"\\s*>$");
+ if (!match.Success) { Error("scene-assembly-definition-invalid","X0 assembly occurrences require AssemblyFile<\"relative.firmament\">; their document compiles independently."); continue; }
+ var path=Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(sourceIdentity))!,match.Groups["path"].Value));
+ var allowedRoot=AssemblyM0Parser.FindAllowedSourceRoot(Path.GetFullPath(sourceIdentity));
+ var allowedPrefix=Path.TrimEndingDirectorySeparator(allowedRoot)+Path.DirectorySeparatorChar;
+ if (!path.StartsWith(allowedPrefix,StringComparison.OrdinalIgnoreCase))
+ { Error("scene-assembly-file-outside-root","AssemblyFile must stay inside the existing allowed source root."); continue; }
+ if (!path.EndsWith(".firmament",StringComparison.OrdinalIgnoreCase)) { Error("scene-assembly-file-invalid","AssemblyFile requires a .firmament source document."); continue; }
+ if (!compiledAssemblies.ContainsKey(path))
+ {
+ if (!File.Exists(path)) { Error("scene-assembly-file-missing",path); continue; }
+ if (!assemblies.TryGetValue(path,out var session))
+ {
+ if (assemblies.Count >= 256) { Error("scene-definition-session-capacity-exceeded","The retained Scene session supports at most 256 independent Assembly sources; start a fresh session."); continue; }
+ assemblies[path]=session=new();
+ }
+ var assembly=session.CompileFile(path); compiledAssemblies.Add(path,assembly);
+ diagnostics.AddRange(assembly.Diagnostics);
+ }
+ }
+ else if (!materializedParts.ContainsKey(item.Definition))
+ {
+ var part=parts.Materialize(item.Definition,s.DefinitionSource,sourceIdentity,diagnostics,null,
+ () => AssemblyDefinitionMaterializer.TryMaterialize(item.Definition,s.DefinitionSource,sourceIdentity,diagnostics));
+ if (part is not null) materializedParts.Add(item.Definition,part);
+ }
+ }
+ var definitionMs=watch.Elapsed.TotalMilliseconds; watch.Restart();
+ if (diagnostics.Any(d => d.Severity == AssemblyDiagnosticSeverity.Error)) return new(null,diagnostics);
+ var boundaries=s.Rooms.SelectMany(RoomBoundaries).ToArray();
+ AddNode(s.Name,"Scene",s.Name,null,Transform3D.Identity.ToRowMajor(),null,new(sourceIdentity,0,source.Length));
+ foreach (var room in s.Rooms)
+ {
+ var roomPath=s.Name+"."+room.Name; var transform=Transform3D.CreateTranslation(new(room.AtMm[0],room.AtMm[1],room.AtMm[2]));
+ AddNode(roomPath,"Room",room.Name,s.Name,transform.ToRowMajor(),null,room.Span);
+ foreach (var boundary in boundaries.Where(b => b.Room == room.Name))
+ {
+ var wallPath=s.Name+"."+boundary.Path;
+ AddNode(wallPath,"SceneBoundary",boundary.Path,roomPath,transform.ToRowMajor(),null,room.Span);
+ foreach (var panel in Panels(room,boundary.Kind,s.Openings.Where(o => o.Boundary == boundary.Path).ToArray()))
+ {
+ var key="scene-box:"+string.Join(":",panel.Size.Select(F)); var id=Id(key);
+ if (!definitions.ContainsKey(id)) definitions.Add(id,Box(id,key,panel.Size));
+ var panelPath=wallPath+".panel"+panel.Index;
+ var world=Transform3D.CreateTranslation(new(panel.At[0],panel.At[1],panel.At[2]))*transform;
+ AddNode(panelPath,"EnvironmentPanel",key,wallPath,world.ToRowMajor(),id,room.Span);
+ ApplyLook(panelPath,room.Appearance);
+ }
+ foreach (var opening in s.Openings.Where(o => o.Boundary == boundary.Path))
+ {
+ var frame=Transform3D.FromRowMajor(boundary.Frame);
+ var aperture=Transform3D.CreateTranslation(new(opening.AlongMm,opening.SillMm,0))*frame;
+ AddNode(wallPath+"."+opening.Name,opening.Kind,opening.Name,wallPath,aperture.ToRowMajor(),null,opening.Span);
+ }
+ }
+ }
+ foreach (var item in s.Occurrences)
+ {
+ // Existing frame composition owns rotation/basis/translation; no Mate is synthesized.
+ Transform3D target;
+ if (item.Placement.From == "World") target=Transform3D.Identity;
+ else if (boundaries.SingleOrDefault(b => b.Path == item.Placement.From) is { } boundary) target=Transform3D.FromRowMajor(boundary.Frame);
+ else { Error("scene-frame-unresolved",$"Unknown Scene target frame '{item.Placement.From}'."); continue; }
+ var world=AssemblyFrameAuthoring.Compose(target,item.Placement,diagnostics);
+ var segments=item.Path.Split('.');
+ for (var n=2;n<segments.Length;n++)
+ {
+ var group=string.Join('.',segments.Take(n));
+ if (!occurrences.Any(o => o.Path == group)) AddNode(group,"PatternGroup",group,string.Join('.',segments.Take(n-1)),Transform3D.Identity.ToRowMajor(),null,item.Span,item.PatternKey);
+ }
+ var parent=string.Join('.',segments.SkipLast(1));
+ if (item.Kind == "Part")
+ {
+ if (item.From != "Origin") { Error("scene-part-source-frame-unsupported","X0 Part Scene placement starts at Origin; assembly published source frames are supported."); continue; }
+ var part=materializedParts[item.Definition]; var id=Id("part:"+item.Definition);
+ if (!definitions.ContainsKey(id))
+ { var preparation=Stopwatch.StartNew(); definitions.Add(id,AssemblyDisplayMeshExporter.PrepareDefinition(id,item.Definition,part.Body)); displayMs+=preparation.Elapsed.TotalMilliseconds; }
+ AddNode(item.Path,"Part",item.Definition,parent,world.ToRowMajor(),id,item.Span,item.PatternKey); ApplyLook(item.Path,item.Appearance);
+ }
+ else
+ {
+ var match=Regex.Match(item.Definition,"\"(?<path>[^\"]+)\"");
+ var path=Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(sourceIdentity))!,match.Groups["path"].Value));
+ var assembly=compiledAssemblies[path];
+ if (!preparedAssemblies.TryGetValue(path,out var mesh))
+ { var preparation=Stopwatch.StartNew(); preparedAssemblies[path]=mesh=AssemblyDisplayMeshExporter.Export(assembly); displayMs+=preparation.Elapsed.TotalMilliseconds; }
+ if (item.From != "Origin")
+ {
+ var root=assembly.Ir!.Instances.Single(i => i.ParentStableId is null);
+ var reference=AssemblyPath.Parse(root.Path+"."+item.From);
+ if (!AssemblyM0Compiler.TryResolve(reference,assembly.Ir.Instances,out var resolved) || !resolved!.Value.TryBinding<ExactDatumFrameBinding>(out var binding))
+ { Error("scene-source-frame-unresolved",$"Assembly does not publish source frame '{item.From}'."); continue; }
+ world=AssemblyFrameAuthoring.Matrix(binding).Inverse()*world;
+ }
+ var prefix=Id(path); var rootPath=mesh.Occurrences.Single(o => o.ParentId is null).Path;
+ foreach (var d in mesh.Definitions)
+ {
+ var id=prefix+":"+d.Id;
+ if (!definitions.ContainsKey(id)) definitions.Add(id,d with { Id=id, Identity=path+"::"+d.Identity });
+ }
+ foreach (var o in mesh.Occurrences)
+ {
+ var scenePath=item.Path+o.Path[rootPath.Length..];
+ var parentPath=o.ParentId is null ? parent : item.Path+mesh.Occurrences.Single(p => p.Id == o.ParentId).Path[rootPath.Length..];
+ var instance=assembly.Ir!.Instances.Single(i => i.StableId == o.Id);
+ AddNode(scenePath,instance.Kind.ToString(),instance.DefinitionIdentity,parentPath,(Transform3D.FromRowMajor(o.Transform)*world).ToRowMajor(),o.DefinitionId is null ? null : prefix+":"+o.DefinitionId,item.Span,item.PatternKey);
+ if (instance.Appearance is { } look) looks[Id(scenePath)]=look;
+ ApplyLook(scenePath,item.Appearance);
+ }
+ }
+ }
+ if (diagnostics.Any(d => d.Severity == AssemblyDiagnosticSeverity.Error)) return new(null,diagnostics);
+ var display=new AssemblyDisplayMeshDocument("aetheris/scene-display-mesh/1",s.Name,"mm",definitions.Values.ToArray(),occurrences);
+ var bounds=WorldBounds(display);
+ var reuse=parts.Evidence.Concat(compiledAssemblies.Values.SelectMany(a => a.Reuse?.Definitions ?? [])).ToArray();
+ var perf=new ScenePerformance(bindMs,definitionMs,watch.Elapsed.TotalMilliseconds-displayMs,reuse.Length,reuse.Count(r => r.Reused),reuse.Count(r => !r.Reused),displayMs);
+ return new(new(s,display,boundaries,nodes,looks,reuse,perf,bounds.Min,bounds.Max),diagnostics);
+
+ IEnumerable<SceneBoundary> RoomBoundaries(SceneRoom room)
+ {
+ var w=room.SizeMm[0]; var d=room.SizeMm[1]; var h=room.SizeMm[2];
+ foreach (var (kind,frame,width,height) in new (string,double[],double,double)[] {
+ ("floor",[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],w,d),
+ ("ceiling",[1,0,0,0,0,1,0,0,0,0,1,0,0,0,h,1],w,d),
+ ("southWall",[1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1],w,h),
+ ("northWall",[1,0,0,0,0,0,1,0,0,-1,0,0,0,d,0,1],w,h),
+ ("westWall",[0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,1],d,h),
+ ("eastWall",[0,1,0,0,0,0,1,0,1,0,0,0,w,0,0,1],d,h) })
+ {
+ var world=Transform3D.FromRowMajor(frame)*Transform3D.CreateTranslation(new(room.AtMm[0],room.AtMm[1],room.AtMm[2]));
+ var path=room.Name+"."+kind;
+ yield return new(path,room.Name,kind,world.ToRowMajor(),width,height,s.Openings.Where(o => o.Boundary == path).Select(o => o.Name).ToArray());
+ }
+ }
+ void Error(string code,string message) => diagnostics.Add(new(code,message));
+ void AddNode(string path,string kind,string definition,string? parent,double[] transform,string? def,SemanticSourceSpan span,string? key=null)
+ { occurrences.Add(new(Id(path),path,parent is null ? null : Id(parent),def,transform,path)); nodes.Add(new(path,kind,definition,"SceneFrame",span,key)); }
+ void ApplyLook(string path,string? look)
+ { if (look is not null) looks[Id(path)]=new("","",look,s.Looks.Appearances[look].Preview,"scene-appearance"); }
+ }
+ }
+ public void Dispose() { lock(gate) { foreach (var session in assemblies.Values) session.Dispose(); assemblies.Clear(); parts.Clear(); disposed=true; } }
+ private static string F(double value) => value.ToString("R",CultureInfo.InvariantCulture);
+ private static string Id(string value) => "scene:"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)))[..24];
+ private sealed record Panel(int Index,double[] At,double[] Size);
+ private static IEnumerable<Panel> Panels(SceneRoom r,string wall,IReadOnlyList<SceneOpening> openings)
+ {
+ var w=r.SizeMm[0]; var d=r.SizeMm[1]; var h=r.SizeMm[2]; var t=r.ThicknessMm;
+ if (wall is "floor" or "ceiling") { yield return new(0,[0,0,wall == "floor" ? -t : h],[w,d,t]); yield break; }
+ var horizontal=wall is "southWall" or "northWall"; var width=horizontal ? w : d;
+ var xs=new[] {0d,width}.Concat(openings.SelectMany(o => new[] {o.AlongMm,o.AlongMm+o.WidthMm})).Distinct().Order().ToArray();
+ var zs=new[] {0d,h}.Concat(openings.SelectMany(o => new[] {o.SillMm,o.SillMm+o.HeightMm})).Distinct().Order().ToArray();
+ var index=0;
+ for(var x=0;x+1<xs.Length;x++) for(var z=0;z+1<zs.Length;z++)
+ {
+ if (openings.Any(o => (xs[x]+xs[x+1])/2 > o.AlongMm && (xs[x]+xs[x+1])/2 < o.AlongMm+o.WidthMm && (zs[z]+zs[z+1])/2 > o.SillMm && (zs[z]+zs[z+1])/2 < o.SillMm+o.HeightMm)) continue;
+ yield return horizontal ? new(index++,[xs[x],wall == "southWall" ? -t : d,zs[z]],[xs[x+1]-xs[x],t,zs[z+1]-zs[z]])
+ : new(index++,[wall == "westWall" ? -t : w,xs[x],zs[z]],[t,xs[x+1]-xs[x],zs[z+1]-zs[z]]);
+ }
+ }
+ private static AssemblyDisplayMeshDefinition Box(string id,string identity,double[] s)
+ {
+ double[][] p=[[0,0,0],[s[0],0,0],[s[0],s[1],0],[0,s[1],0],[0,0,s[2]],[s[0],0,s[2]],[s[0],s[1],s[2]],[0,s[1],s[2]]];
+ int[][] faces=[[0,3,2,1],[4,5,6,7],[0,1,5,4],[3,7,6,2],[0,4,7,3],[1,2,6,5]];
+ double[][] normals=[[0,0,-1],[0,0,1],[0,-1,0],[0,1,0],[-1,0,0],[1,0,0]];
+ var positions=new List<double>(); var ns=new List<double>(); var indices=new List<int>();
+ for(var f=0;f<6;f++) { var start=positions.Count/3; foreach(var v in faces[f]) { positions.AddRange(p[v]); ns.AddRange(normals[f]); } indices.AddRange([start,start+1,start+2,start,start+2,start+3]); }
+ return new(id,identity,positions.ToArray(),ns.ToArray(),indices.ToArray(),"SceneRectangularBoundary");
+ }
+ private static (double[] Min,double[] Max) WorldBounds(AssemblyDisplayMeshDocument d)
+ {
+ var min=new[] {double.PositiveInfinity,double.PositiveInfinity,double.PositiveInfinity}; var max=new[] {double.NegativeInfinity,double.NegativeInfinity,double.NegativeInfinity};
+ var defs=d.Definitions.ToDictionary(v => v.Id);
+ foreach(var o in d.Occurrences.Where(o => o.DefinitionId is not null))
+ {
+ var p=defs[o.DefinitionId!].Positions; var t=Transform3D.FromRowMajor(o.Transform);
+ for(var i=0;i<p.Length;i+=3) { var point=t.Apply(new Point3D(p[i],p[i+1],p[i+2])); var xyz=new[] {point.X,point.Y,point.Z}; for(var a=0;a<3;a++) { min[a]=Math.Min(min[a],xyz[a]); max[a]=Math.Max(max[a],xyz[a]); } }
+ }
+ return double.IsFinite(min[0]) ? (min,max) : (new double[3],new double[3]);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Scene/SceneExport.cs b/Aetheris.Kernel.Firmament/Scene/SceneExport.cs
new file mode 100644
index 00000000..195255f5
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Scene/SceneExport.cs
@@ -0,0 +1,25 @@
+using System.Globalization;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.Kernel.Firmament.Scene;
+
+public static class SceneExport
+{
+ public static string Usd(CompiledScene scene)
+ {
+ var ids=scene.Display.Occurrences.ToDictionary(o => o.Path,o => o.Id,StringComparer.Ordinal);
+ var identities=scene.Nodes.ToDictionary(n => ids[n.Path],n => n.DefinitionIdentity,StringComparer.Ordinal);
+ var properties=scene.Nodes.ToDictionary(n => ids[n.Path],n => (IReadOnlyDictionary<string,string>)new Dictionary<string,string> {
+ ["kind"]=n.Kind,["sourceDocument"]=n.Span.Source,["sourceStart"]=n.Span.Start.ToString(CultureInfo.InvariantCulture),
+ ["sourceLength"]=n.Span.Length.ToString(CultureInfo.InvariantCulture),["patternKey"]=n.PatternKey ?? "",["placementAuthority"]=n.PlacementAuthority },StringComparer.Ordinal);
+ foreach (var o in scene.Source.Openings)
+ {
+ var id=ids[scene.Source.Name+"."+o.Boundary+"."+o.Name];
+ properties[id]=new Dictionary<string,string>(properties[id]) { ["widthMm"]=F(o.WidthMm),["heightMm"]=F(o.HeightMm),["alongMm"]=F(o.AlongMm),["sillMm"]=F(o.SillMm),["boundary"]=o.Boundary };
+ }
+ return AssemblyUsdExporter.SerializeSpatial(scene.Display,new(identities,scene.Appearances,properties,Cameras(scene)));
+ }
+ public static byte[] Glb(CompiledScene scene) => AssemblyGlbExporter.Serialize(scene.Display,occurrenceLooks:scene.Appearances,cameras:Cameras(scene));
+ private static DisplayCamera[] Cameras(CompiledScene scene) => scene.Source.Cameras.Select(c => new DisplayCamera(c.Name,c.WorldTransform(),c.FovDegrees)).ToArray();
+ private static string F(double v) => v.ToString("R",CultureInfo.InvariantCulture);
+}
diff --git a/docs/development/firmament-language-inconsistencies.md b/docs/development/firmament-language-inconsistencies.md
index 274531fc..1a291efc 100644
--- a/docs/development/firmament-language-inconsistencies.md
+++ b/docs/development/firmament-language-inconsistencies.md
@@ -4,7 +4,7 @@ This A5d register classifies the language seams first exposed by A5b and complet
| Area | Final classification | Decision and evidence |
|---|---|---|
-| Declaration and construct casing | ResolvedCanonical | Firmament-owned vocabulary is canonically PascalCase. Audited lowercase aliases remain only where unambiguous and select the same semantic route; no style warnings exist. |
+| Declaration and construct casing | ResolvedCanonical | Constructs and types use PascalCase; built-in properties, concrete occurrences and new ports prefer camelCase under the accepted language-style contract. Explicit legacy field aliases retain identical semantics; no global case folding or style warnings. Scene X0 dogfoods this convention. |
| Legacy V1 document shape | LegacyQuarantined | `fixtures/Compatibility/LegacyV1/` remains untouched and is compatibility evidence, not V2 authoring authority. |
| Legacy primitive/Boolean vocabulary | LegacyQuarantined | V1 operations remain on their versioned compiler path. Public V2 uses named declarations and semantic features. |
| Direct versus `solid` primitive declarations | RetainedCompatibility | Direct `Box`/`Cylinder`/`Cone`/`Sphere`/`Torus` declarations are canonical. `solid name: Type` remains a compatibility adapter to the same primitive AST/lowering. |
@@ -28,7 +28,7 @@ This A5d register classifies the language seams first exposed by A5b and complet
| `Modify` | ResolvedCanonical | Applies admitted semantic operations to an existing body after construction. |
| historical lowercase manufacturing `template<Process>` | ResolvedCompatibility | Persisted CNC/Additive syntax is adapted to the same DFM representation. CNC/FDM/SheetMetal examples are ported to canonical typed Record/Static/`with`/Template/Concept Struct families. Canonical policy wins when both forms occur; new source uses the modern form. |
| Boss / Pocket versus Add / Remove | RetainedCompatibility | Boss/Pocket preserve their first-class engineering contracts. Low-level Add/Remove remain bounded profile-composition compatibility, not coequal public feature design. |
-| Units and literals | ResolvedCanonical | V2 uses `Units: mm` and unit-bearing engineering literals. Lowercase V2 input, external JSON, and unitless V1 arrays are separately classified compatibility forms. |
+| Units and literals | ResolvedCanonical | Engineering geometry uses `units: mm`; Scene additionally admits `units: m` and explicit m/mm lengths normalized to mm. Unitless Scene coordinates are rejected. External JSON and unitless V1 arrays remain compatibility forms. |
| Speculative keyword families | SpeculativeQuarantined | Future/not-implemented `.firmfixture` bodies remain untouched and do not define parser or documentation requirements. |
| External identifiers and snake_case | IntentionalDomainDifference | Standards, material designations, part numbers, namespaces, and imported identities preserve source spelling. No global identifier-style enforcement exists. |
diff --git a/docs/development/firmament-v2-grammar-inventory.md b/docs/development/firmament-v2-grammar-inventory.md
index 360fa523..6a8a312b 100644
--- a/docs/development/firmament-v2-grammar-inventory.md
+++ b/docs/development/firmament-v2-grammar-inventory.md
@@ -1,6 +1,9 @@
# Firmament V2 active grammar inventory
-This A5c inventory records parser and lowering ownership. Canonical forms use PascalCase; compatibility aliases are deliberately bounded rather than produced by global case folding.
+This inventory records parser and lowering ownership. Constructs and types use
+PascalCase; field labels prefer camelCase under the accepted public language
+style. Explicit compatibility aliases remain bounded; there is no global case
+folding. Older rows retain their historical spelling examples.
| Construct / token | Owning parser/domain | Accepted forms | Canonical form | Compatibility policy | Lowering/runtime owner |
|---|---|---|---|---|---|
@@ -15,6 +18,7 @@ This A5c inventory records parser and lowering ownership. Canonical forms use Pa
| Analysis, Fixed, Force | `FirmamentAnalysisCompiler` | case-insensitive audited keywords/fields; ordinary Model Box or bounded inline STEP | PascalCase vocabulary over ordinary Model geometry | lowercase forms bind the same Analysis IR | Continuum region producer and linear-elastic solver |
| inlineSTEP / InlineStep | FEA expression reader / canonical import declaration | bounded `inlineSTEP("path")`; `InlineStep Name { Path: ... }` | declaration form in a Model; expression spelling retained in FEA | domain-specific compatibility | STEP importer and recognized-region bridge |
| Assembly | `FirmamentAssemblyDocumentProfile`, `AssemblyM0Parser` | V2 `Assembly Name { ... }`; deprecated JSON-shaped `.firmasm` | V2 Assembly source profile | JSON is legacy compatibility only | Assembly compiler/executor/AP242 interop |
+| Scene, Room, Door, Window, Camera | `SceneAuthoring` and compiler-owned schemas | PascalCase constructs, camelCase fields and bounded PascalCase field aliases; explicit m/mm coordinates | `Scene warehouse { units: m ... }` | no construct case folding; authored names and Room boundary paths are case-sensitive | `FirmamentSceneSession`; shared ordinary Part/Assembly compilation, spatial display/USD/GLB projection |
| Drawing | `FirmamentDrawingCompiler` | qualified Drawing declarations | PascalCase qualified fixture form | separate domain grammar | Drawing IR and SVG/PDF/PPTX writers |
## Semantic ownership matrix
@@ -22,6 +26,7 @@ This A5c inventory records parser and lowering ownership. Canonical forms use Pa
| Construct | Meaning and placement | Geometry effect | Owner |
|---|---|---|---|
| Template | typed compile-time specialization over values/Records | none directly; emits ordinary admitted source | Template expansion |
+| Scene / Room / Door / Window / Camera | spatial occurrence product, Room-owned boundary references/apertures and presentation state | derives environment display panels; composes existing engineering occurrences | Scene binder/session, shared placement and export infrastructure |
| Record / Static / Table / `with` | immutable finite engineering data and derivation | none; erased after binding | static authoring and Template expansion |
| Pattern / Over | finite repetition from static data | repeats an admitted feature | static authoring into the owning material grammar |
| Struct | named construction intent or concept materialization | contains the selected construction route | concept/profile frontend |
diff --git a/docs/public/firmament/language-style.md b/docs/public/firmament/language-style.md
index d7c568d9..94c88d42 100644
--- a/docs/public/firmament/language-style.md
+++ b/docs/public/firmament/language-style.md
@@ -6,13 +6,13 @@ The [design proposal](casing-and-layout-proposal.md) records the reasoning.
| Role | Convention | Examples |
| --- | --- | --- |
-| Artifact, declaration, construction form | PascalCase | `Model`, `Assembly`, `Concept Struct`, `Profile`, `Feature`, `Placement`, `Mate` |
+| Artifact, declaration, construction form | PascalCase | `Model`, `Assembly`, `Scene`, `Room`, `Door`, `Window`, `Camera`, `Concept Struct`, `Profile`, `Feature`, `Placement`, `Mate` |
| Type and reusable recipe | PascalCase | `Length`, `PickupSpec`, `Humbucker`, `ControlKnob` |
| Concrete value, local geometry, occurrence, parameter, port | camelCase | `layout`, `outline`, `neckPickup`, `bottomSeat`, `width` |
| Built-in property label | camelCase | `units`, `size`, `from`, `translateLocal`, `minimumBendRadius` |
| Linking and scope word | lowercase | `using`, `on`, `over`, `with`, `return`, `include`, `expose`, `bind` |
| Scalar function | camelCase | `fretDistance`, `halfWidth` |
-| Engineering symbol, enum, external identity | Preserve domain spelling | `XY`, `+Z`, `Fixed`, `Periodic`, `Stock`, `mm`, `304_Annealed` |
+| Engineering symbol, enum, external identity | Preserve domain spelling | `XY`, `+Z`, `Outer`, `World`, `Origin`, `Fixed`, `Periodic`, `Stock`, `mm`, `m`, `304_Annealed` |
The root product may keep its definition name: `Assembly GuitarX0` and
`<Assembly GuitarX0>`. Feature constructors such as `Coil` remain PascalCase.
diff --git a/docs/public/firmament/overview.md b/docs/public/firmament/overview.md
index 65378a26..859e3c10 100644
--- a/docs/public/firmament/overview.md
+++ b/docs/public/firmament/overview.md
@@ -9,3 +9,8 @@ Units are part of values and types. Lengths such as `8mm`, forces such as `500N`
Named semantic features survive beyond geometry construction. Supported PMI is emitted as AP242 product-definition semantics; feature and topology correspondence is available to inspection consumers such as Cadmata. Presentation orientation is not authoritative engineering state.
Canonical authoring is Firmament V2. V1 and JSON-shaped `.firmasm` exist only as explicitly identified compatibility inputs. See [syntax](syntax.md), [structural members and weldments](structural.md), [targets](../reference/targets.md), and the [support matrix](../reference/supported-features.md).
+
+[Scenes](scenes.md) compose metre-scale Rooms, wall openings, independently
+compiled Assemblies, shared Part occurrences and cameras. Scene owns spatial
+composition and presentation exports; engineered Parts and Assemblies retain
+their geometry and mechanical authority.
diff --git a/docs/public/firmament/scenes.md b/docs/public/firmament/scenes.md
new file mode 100644
index 00000000..b9b21782
--- /dev/null
+++ b/docs/public/firmament/scenes.md
@@ -0,0 +1,114 @@
+# Scenes
+
+`Model` / Part describes an engineered object. `Assembly` describes objects and
+their mechanical or semantic relationships. `Scene` describes independent
+objects coexisting in a spatial environment. Scene placement does not create a
+Mate or Interface. Engineering geometry still belongs to its part or assembly.
+
+```firmament
+Scene Factory {
+ units: m;
+ Room warehouse { size: [6m, 4m, 3m]; thickness: 100mm; }
+ Door loadingBay { on: warehouse.southWall; width: 1.5m; height: 2.4m; along: .4m; }
+ Window officeGlass { on: warehouse.eastWall; width: 1.5m; height: 1m; sill: 1.2m; along: 1m; }
+ <Assembly robot = AssemblyFile<"robot.firmament">>
+ Placement { from: Origin; to: World; translateLocal: [1m, 2m, 0mm]; }
+ </Assembly>
+ Camera hero { position: [5.6m, .25m, 2.65m]; lookAt: [2.5m, 2.1m, .8m]; fov: 65deg; }
+}
+```
+
+`AssemblyFile` references an independently compiled `.firmament` Assembly source;
+it requires file/project directory context. X0 does not merge its declarations
+into the Scene or import its mechanical constraints into the Scene root.
+Individual Part occurrences use ordinary typed Template specializations declared
+before the Scene, for example `<Part package = Package<R:100mm,H:200mm>>`.
+Those templates retain their existing **mm** geometry authoring contract.
+
+## Units and room coordinates
+
+`units: m` selects scene-scale authoring; `units: mm` also works. Every Scene
+length and coordinate still requires an explicit `m` or `mm` suffix. Binding
+normalizes `1m` to `1000mm`; changing `units` never rescales explicit literals.
+Kernel geometry and tolerances remain in mm. Scene Set lengths are converted
+at the existing typed pattern catalog boundary before occurrence expansion.
+
+A Room occupies `[0,width] × [0,depth] × [0,height]`, optionally translated by
+`at: [x,y,z]`. Its clear interior dimensions are `size`. Default enclosure
+thickness is `100mm`, placed outside the clear interior. X0 rooms are rectangular
+and axis-aligned; dimensions and thickness must be positive.
+
+Every Room publishes case-sensitive `floor`, `ceiling`, `northWall`, `southWall`,
+`eastWall`, and `westWall` references. Their exact boundary frames, dimensions and
+owned openings are available to inspection. These are Scene boundary references,
+independent of BRep face or triangle IDs. Wall coordinates use local X for
+`along`, local Y for vertical height. Along increases in world +X on north/south
+walls and world +Y on east/west walls, always measured from the minimum corner.
+These right-handed frames are coordinate charts for `along` and height; their
+third axis is not an inward/outward wall-normal classification.
+
+Door bottom is the floor. Window bottom is its `sill`. Openings must fit inside
+the selected wall and cannot overlap. They lower to actual missing wall volume
+by a deterministic rectangular partition. No authored subtraction is required.
+Windows are apertures in X0; glazing and door leaves are not synthesized.
+The semantic hierarchy is Room → boundary → opening, even when the boundary's
+display consists of multiple panels. Panel names are derived display structure;
+the named boundary and opening retain authority.
+
+## Placement, sharing and presentation
+
+Scene `Placement` reuses the existing `translateLocal`, `rotateLocal`, `normal`,
+`up`, and frame composition implementation. `to` may name `World` or a Room
+boundary. `from: Origin` is available on Parts and Assemblies; Assemblies may
+also name an exact published DatumFrame. Rotation retains the existing form
+`rotateLocal: { axis: Z; angle: 90deg; }`. There are no authored matrices.
+Named Scene `FrameTransform` declarations and Part source-port alignment are
+deferred; Scene rejects unsupported declarations with a diagnostic.
+
+The existing `Pattern name over keyedSet` frontend expands Parts and Assemblies;
+X0 adds no Scene loop language. Pattern containers are spatial groups, not
+engineered assemblies. Names, pattern keys, declaration spans, definition
+identities and placement authority survive inspection and USD metadata.
+
+Each unique AssemblyFile compiles once per build. Repeated occurrences share its
+part display definitions. Local Part specializations use the existing immutable
+STEP definition cache. `FirmamentSceneSession` keeps independent retained
+Assembly sessions. Camera, placement and Scene Set edits do not invalidate
+unchanged geometry declarations. Cache hits still reimport fresh exact bodies;
+they do not expose cached mutable topology.
+
+`Camera` is presentation state: a unit-bearing `position` and `lookAt`, plus a
+vertical `fov` in degrees. Export uses Z-up camera orientation. Cameras never
+modify engineering geometry. Scene `Appearance` definitions and occurrence
+`appearance` overrides reuse the existing finite preview material values.
+Physical material/density selection remains in engineering definitions.
+
+## CLI and exports
+
+```powershell
+aetheris validate fixtures/Canonical/Scene/warehouse.firmament --json
+aetheris inspect fixtures/Canonical/Scene/warehouse.firmament --repeat 2 --json
+aetheris scene export-usd fixtures/Canonical/Scene/warehouse.firmament --json
+aetheris scene export-glb fixtures/Canonical/Scene/warehouse.firmament --json
+```
+
+Default output is ignored `artifacts/local/scene/`. USD preserves spatial
+hierarchy, shared instances, transforms, named opening metadata, cameras and
+appearance overrides. GLB uses the existing display exporter and the established
+mm/Z-up to m/Y-up boundary; material variants share geometry buffers. GLB is a
+static presentation asset. Assembly kinematics and STEP authority remain with
+the source assembly; X0 Scene USD does not export a combined physics articulation.
+
+The existing PowerPoint 3D pipeline can embed the generated GLB and a rendered
+fallback PNG. Desktop rotation/save/reopen is a separate manual qualification.
+Whole-scene manufacturing STEP is deliberately unsupported.
+
+Completion, hover and source diagnostics use compiler-owned schemas. Scene
+formatting safely prefers camelCase field labels while preserving layout,
+comments, generic specialization spelling and authored identities. It is
+deterministic and idempotent; it does not rename public ports or pattern keys.
+Project-snapshot language analysis reads Scene syntax; compiling AssemblyFile
+resources from a virtual/browser project is deferred.
+
+Nested Scenes, BIM/IFC, general walls, zones, lights, logistics, collision
+avoidance, path planning, physics and robotics control are outside X0.
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index bdc910f2..7a79caaf 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -7,6 +7,7 @@
| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |
| Gear Standard Library | Supported / bounded by family | Supported external/internal standard involute spur gears; bounded straight bevel/miter and ratchet/pawl; typed `Interface<Gear>` compatibility and ideal ratios; deterministic manifold AP242. No contact, dynamics, ratings, helical/worm, spiral-bevel, or qualified hub/keyway geometry. See the [gear guide](../firmament/gears.md). |
| Assembly Interface bundles and Subassemblies | Supported / bounded | Compiler-owned `Fixed`, `Axial`, and `Revolute` expansion; explicit `Custom` atomic bundles; compile-time relative `Include`; reusable nested definitions; private-by-default internals; exposed semantic ports that preserve type, including Gear; stable hierarchical paths and dependency hashes. Include aliases are deferred. See [assemblies](../firmament/assemblies.md). |
+| Scene spatial composition | Supported / bounded | Metre/mm coordinates; rectangular Room boundaries; Door/Window apertures; independent AssemblyFile and typed Part occurrences; keyed patterns; retained definition reuse; cameras and appearances; USD/GLB. No Scene mechanical relationships, nested Scenes, whole-scene STEP or BIM. See [scenes](../firmament/scenes.md). |
| Bounded mathematical sculpting | Bounded (SURF-X3b subset) | Immutable single-predecessor `BodyState` reconstructed from versioned `BaseConstruction` plus typed replay operations; persistent `OffsetRegion`, `ReplaceRegion`, judged `BlendBoundary`, `HoleFeature`, east-attached `AddSectionChain`, and west/east through-duct `RemoveSectionChain`; atomic replay, semantic support invalidation, locality/preservation evidence, pcurves, AP242 associations, and rational-free STEP. General blend networks and arbitrary SectionChain supports remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |
| Molded plastic shell | Bounded (MOLD-X0a) | First-class `PlasticShell` IR; exact drafted coaxial-frustum shell; analytic annular standoffs with retained core holes; constant-shell-thickness planar B-rep rib walls with flat tops; one closed product boundary; face-associated AP242 notes; and explicit zero-release-draft warning for constant-section vertical features. The retired polar height field is available only through the non-manufacturing experimental art command. Freeform exterior offsets and general junctions remain unsupported. See the [PlasticShell guide](../firmament/plastic-shell.md). |
| Virtual Sculpture | Bounded (ART-X0) | The explicit `Mode: Virtual` Sol 1 flagship: deterministic golden-angle/Fibonacci 3D lattice, analytic toroidal frame and eye, exact closed-body AP242 assembly, evidence/preview output, and zero rational product surfaces. This is not manufacturing geometry and does not extend Firmament engineering domains. See [Virtual Sculpture](../virtual-sculpture.md). |
diff --git a/docs/release/SCENE-AUTHORING-X0.md b/docs/release/SCENE-AUTHORING-X0.md
new file mode 100644
index 00000000..a0e4f056
--- /dev/null
+++ b/docs/release/SCENE-AUTHORING-X0.md
@@ -0,0 +1,209 @@
+# SCENE-AUTHORING-X0
+
+Date: 2026-10-04. Executive verdict: **Accepted**.
+
+Firmament now authors a warehouse-scale spatial environment above ordinary
+assemblies with explicit metre coordinates, declarative Room apertures,
+shared engineering definitions and OpenUSD/GLB output. The warehouse also
+packages through the existing PowerPoint 3D pipeline. Scene remains a distinct
+spatial product, with the deliberate qualification limits recorded below.
+
+## Design decisions
+
+1. **Scene versus Assembly.** Scene owns a spatial occurrence product and an
+ environment display representation. It never constructs an AssemblySource or
+ AssemblyIr to stand in for the world. Each AssemblyFile compiles through the
+ unchanged ordinary assembly pipeline and keeps its local mechanical authority.
+ Scene placement composes transforms without introducing Interfaces or Mates.
+2. **Scene-only constructs.** Scene, Room, Door, Window and Camera are bounded
+ spatial/presentation authoring. Model/Part geometry and mechanical relations
+ retain their existing owners. Pattern is shared compile-time authoring.
+3. **Metres.** Every Scene coordinate has an m/mm suffix; the binder multiplies
+ metres by 1000. Scene Set lengths normalize at the existing typed catalog
+ boundary. Geometry templates and the kernel retain mm. Neither units nor
+ display scale selects a different tolerance policy.
+4. **Room boundary authority.** Each rectangular Room owns stable case-sensitive
+ floor/ceiling/four-wall paths, reference frames, clear extents and opening
+ names. Doors/windows own exact aperture dimensions under their wall path.
+ Derived rectangular panels cover wall volume outside the apertures. These
+ display/reference solids are independent of BRep/manufacturing authority.
+5. **Shared instances.** One ordinary assembly compilation per unique file and
+ one ordinary materialization per unique local Part specialization feed shared
+ display definitions. Pattern groups are spatial containers. Assembly display
+ preparation is shared within a build. Retained Scene sessions reuse the
+ existing immutable STEP definition cache and independent Assembly sessions;
+ cached topology is never handed back as mutable shared state.
+6. **Rules tested.** PascalCase constructs/types, camelCase field labels and
+ concrete occurrences/ports, lowercase linking words, preserved domain symbols
+ and exact authored/generic/public identities.
+7. **Canonical recommendation.** Keep the already accepted mixed convention.
+ Scene makes the hierarchy easy to scan: `Room warehouse`, `Door loadingBay`,
+ `on: warehouse.southWall`, `width: 1.5m`. Preserve engineering symbols and
+ established public contracts. Keep legacy field aliases explicitly scoped to
+ their schema owner and reject duplicate aliases.
+8. **Deliberate limits.** No nested Scenes, BIM/IFC, arbitrary building systems,
+ explicit Wall/Floor/Zone/Light authoring, glazing/door leaves, simulation,
+ pathfinding or robot control. Room is axis-aligned. Scene FrameTransform
+ declarations and Part source-port alignment are deferred. AssemblyFile is a
+ file-context seam; virtual/browser resource compilation is not qualified.
+ Whole-scene STEP and a combined USD physics articulation are unsupported.
+
+## Capitalization dogfood
+
+Reviewed [the accepted proposal](../public/firmament/casing-and-layout-proposal.md)
+and [current style contract](../public/firmament/language-style.md), alongside
+Concept, Interface, Assembly/Subassembly, Pattern, FrameTransform, Appearance,
+Template and Function owners. The proposal had already been accepted on
+2026-10-01; this milestone tests that decision rather than inventing another
+language dialect.
+
+The room witness compiles with both preferred field spelling and its explicit
+PascalCase compatibility spelling. Tests compare byte-identical USD/GLB output.
+Formatter tests verify comment preservation, idempotence and unchanged identity.
+Compiler-owned schema entries, hover, Scene-body construct discovery, Room fields
+and unit choices are consumed through the existing language-service API. No
+editor-owned grammar or Helios tables were added.
+
+CamelCase fields and occurrence names read more naturally because dimensions
+and descriptions stop competing with the constructs. Lowercasing constructs
+would flatten that visual hierarchy. Lowercasing domain roles is worse: the
+real profile dogfood requires `Loop Outer`, not `Loop outer`; `World`, `Origin`,
+axis choices and existing robot parameters/public members retain their spelling.
+The bounded formatter preserves layout and specialization argument spelling,
+avoiding accidental changes to definition keys or public identities.
+
+New Scene boundaries prefer `floor`, `southWall`, etc. Older authored robot ports
+and parameters are not renamed. Any future migration requires paired declaration
+and use-site edits. No broad naming migration is part of X0.
+
+Two development documents still described all-PascalCase as canonical. Their
+active summaries now point at the accepted mixed convention. The new public
+[Scene guide](../public/firmament/scenes.md) records actual qualified syntax.
+
+## Warehouse witness and artifacts
+
+Source: `fixtures/Canonical/Scene/warehouse.firmament`.
+
+One 6 × 4 × 3 m Room, one 1.5 × 2.4 m loading Door, one 1.5 × 1 m Window,
+a conveyor on shared supports, a storage structure, three occurrences of the
+existing independent Aetheris industrial ATLAS robot on shared pedestals,
+five shared package occurrences, finite preview looks and one Hero camera.
+The robot geometry/source assembly is unchanged. The ATLAS non-affiliation
+disclaimer is retained in source and in the presentation caption.
+
+Inspection reports 3 assembly placements, 14 part placements, 44 shared display
+definitions, 243 hierarchy nodes and 211 mesh occurrences. These are different
+counts: hierarchy containers/opening metadata have no mesh. The outer bounds
+are 6.2 × 4.2 × 3.2 m including the external 100 mm enclosure thickness.
+
+All generated output remains under ignored `artifacts/local/scene/`: readable
+USD, GLB, external validator reports, actual usdview captures, Blender import
+evidence/preview and an embedded PowerPoint deck.
+
+```powershell
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll scene inspect fixtures/Canonical/Scene/warehouse.firmament --repeat 2 --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll scene export-usd fixtures/Canonical/Scene/warehouse.firmament --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll scene export-glb fixtures/Canonical/Scene/warehouse.firmament --json
+```
+
+The existing `scripts/capture-usd-export-x0.py` opens the actual usdview/Hydra
+viewport with `/Scene/N_hero_0`. `scripts/render-scene-x0.py` independently
+imports GLB into Blender, checks dimensions and shared mesh data, and renders
+the authored camera with presentation-only lights. The existing
+`presentation compile` pipeline packages GLB and PNG without slide compiler
+changes. Desktop PowerPoint interior camera behavior, rotation/save/reopen
+remain a manual follow-up; packaging and fallback checks are separate claims.
+The reproducible deck input is `fixtures/Canonical/Scene/warehouse-presentation.json`:
+
+```powershell
+& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' --background --python-exit-code 1 --python scripts/render-scene-x0.py -- artifacts/local/scene/warehouse.glb artifacts/local/scene
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll presentation compile fixtures/Canonical/Scene/warehouse-presentation.json artifacts/local/scene/warehouse.pptx --json
+```
+
+## Performance
+
+Representative CLI process, Release build, one cold and one retained build:
+
+| Phase | Cold | Retained |
+|---|---:|---:|
+| Bind/expand | 60.0 ms | 7.0 ms |
+| Unique engineering definition compilation/reimport | 4810.2 ms | 455.6 ms |
+| Spatial composition | 14.7 ms | 2.1 ms |
+| Display preparation | 368.6 ms | 191.3 ms |
+| Total CLI compilation | 5258.9 ms | 656.2 ms |
+
+Final warehouse serialization: USD 53.0 ms / 2,587,292 bytes; GLB 81.3 ms /
+871,284 bytes. The existing presentation compiler packages one slide/model in
+57.2 ms. These export timings exclude engineering compilation; Blender rendering
+is separate downstream presentation work.
+
+30 unique engineering definitions: cold rebuilt 30; retained reused 30 and
+rebuilt zero. This cache reimports fresh exact bodies and still resolves local
+assemblies; reuse does not mean zero work. A warehouse regression changes both
+Hero camera and a robot station, verifies all definitions are reused, and checks
+that the earlier compiled scene's geometry/transforms are unchanged. The package
+witness also checks placement and keyed count edits without geometry rebuilds.
+Timing is machine/run-specific and not a performance guarantee.
+
+## Qualification
+
+- Focused Scene, existing USD/GLB and schema tests exercise the real producers.
+- OpenUSD 25.08 `usdchecker`: success; real usdview capture uses Storm/Hydra.
+- OpenUSD material resolution: 211 mesh occurrences resolve five bound preview
+ materials/colors, including instance-proxy geometry. The plain usdview capture
+ uses its default viewport lighting; the Blender image is the presentation fallback.
+- Khronos glTF Validator: zero errors and warnings on the warehouse GLB.
+- Blender 5.2.2: physical bounds, camera, 211 mesh occurrences sharing 44 mesh
+ data blocks, positive transforms and a real fallback image.
+- PowerPoint: existing pipeline embeds the actual GLB and PNG; desktop interaction
+ remains unqualified. Package inspection finds one Model3D and one fallback
+ picture; embedded media SHA-256 values match the final GLB/PNG exactly.
+ Desktop PowerPoint is not installed on this host.
+- Fast Core lane: 1005 passed. Final full build/test results follow below.
+
+The first full run overlapped Blender rendering and hit a Core 10-second
+tessellation budget (10372 ms). No tolerance, budget or kernel behavior was
+changed. It also exposed the expected schema registry golden update and an
+existing line-ending-sensitive profile test: LF-only replacement in a CRLF raw
+source string omitted the second disjoint edit. That failure reproduced in
+isolation. The test now normalizes fixture newlines before the replacement;
+the intended geometry comparison and overlap assertion remain intact.
+
+Final review also found that an unfinished occurrence definition could index
+past the token list in editor analysis. A local reader guard now returns
+`scene-syntax-invalid`; two malformed-source regressions exercise that path.
+
+Final serial gate: **passed**. Release solution build completed with zero errors
+and five existing WebAssembly SQLite varargs warnings. The required full serial
+solution lane passed **4,285 tests across 20 test projects**, zero failures and
+zero skipped tests; Core 1,138, Firmament 1,973 and CLI 461. The FrictionLab
+project reports no discoverable tests. The fast Core lane previously passed
+1,005 tests. Build/test logs are `artifacts/local/scene-final-build.log` and
+`artifacts/local/scene-final-tests.log`.
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 --no-restore
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+```
+
+The corpus file rewritten by the test lane was restored to its initial tracked
+content. `git diff --check` passes. No engineering tolerance, timing budget,
+robot source, assembly constraint or slide compiler was changed.
+
+## Acceptance evidence map
+
+| Criteria | Evidence |
+|---|---|
+| 1–2: distinct Scene above Assembly | `CompiledScene` owns spatial/display state; `AssemblyFile` invokes independent ordinary Assembly sessions; no world AssemblyIr is synthesized. |
+| 3–4: metres and unchanged kernel mm | Room/placement binder requires explicit suffixes; m/mm equivalence and dimension tests exercise normalized values. |
+| 5–8: Room/boundaries/Doors/Windows | `room.firmament` tests six owned references, bounds, aperture dimensions/sill and actual excluded wall volume. |
+| 9–12: placed engineering objects, sharing and Pattern | Warehouse tests three existing robot assemblies; keyed package/pedestal occurrences share definitions and retain authored declaration spans. |
+| 13–15: real warehouse, USD and compatibility | CLI witness inspection/exports, external usdchecker/usdview, and full serial solution lane. |
+| 16–17: language service and formatter | Schema registry, root/body/field completion, hover/diagnostics, comment preservation and formatter idempotence regressions. |
+| 18–19: casing dogfood and canonical recommendation | PascalCase compatibility and preferred fields produce byte-identical USD/GLB; recommendation and domain-symbol counterexample above. |
+| 20: bounded spatial foundation | Qualified public Scene guide records explicit deferred constructs and excludes BIM/simulation/combined mechanical world authority. |
+
+Additional GLB/PowerPoint evidence: Khronos validation, independent Blender import,
+inspected rendered fallback, existing deck compilation and embedded-media equality.
+These checks establish static asset/package behavior; they do not establish
+desktop PowerPoint rotation or save/reopen behavior.
diff --git a/fixtures/Canonical/Scene/parts-and-pattern.firmament b/fixtures/Canonical/Scene/parts-and-pattern.firmament
new file mode 100644
index 00000000..f6d2c216
--- /dev/null
+++ b/fixtures/Canonical/Scene/parts-and-pattern.firmament
@@ -0,0 +1,19 @@
+Template<R: Length, H: Length> Struct Package {
+ RoundedRect2 outline { center: [0mm, 0mm]; size: [R, R]; radius: 1mm; }
+ Profile section { Loop Outer { outline |> TraceLoop } }
+ Extrude body { profile: section; from: 0mm; to: H; }
+}
+Record Site { x: Length; }
+Static sites: Set<Site> {
+ first => Site { x: 1m; }
+ second => Site { x: 2m; }
+}
+Scene Packages {
+ units: m;
+ Pattern packages over sites {
+ site => <Part package = Package<R:100mm,H:200mm>>
+ Placement { from: Origin; to: World; translateLocal: [site.x, 0mm, 0mm]; }
+ </Part>
+ }
+ Camera hero { position: [3m, -2m, 1m]; lookAt: [1m, 0mm, 0mm]; fov: 45deg; }
+}
diff --git a/fixtures/Canonical/Scene/room.firmament b/fixtures/Canonical/Scene/room.firmament
new file mode 100644
index 00000000..be4d7594
--- /dev/null
+++ b/fixtures/Canonical/Scene/room.firmament
@@ -0,0 +1,8 @@
+// A semantic room, not six authored boxes.
+Scene RoomProof {
+ units: m;
+ Room hall { size: [10m, 8m, 4m]; at: [1m, 2m, 0mm]; thickness: 100mm; }
+ Door loading { on: hall.southWall; width: 2m; height: 3m; along: 1m; }
+ Window glazing { on: hall.eastWall; width: 2m; height: 1m; sill: 1.5m; along: 3m; }
+ Camera hero { position: [9m, 3m, 3m]; lookAt: [5m, 6m, 1m]; fov: 45deg; }
+}
diff --git a/fixtures/Canonical/Scene/warehouse-presentation.json b/fixtures/Canonical/Scene/warehouse-presentation.json
new file mode 100644
index 00000000..431a502d
--- /dev/null
+++ b/fixtures/Canonical/Scene/warehouse-presentation.json
@@ -0,0 +1,15 @@
+{
+ "title": "Aetheris scene authoring",
+ "slides": [{
+ "title": "Automated warehouse",
+ "subtitle": "A spatial environment authored in Firmament with shared engineered objects",
+ "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": "WarehouseX0",
+ "source": "../../../artifacts/local/scene/warehouse.glb",
+ "preview": "../../../artifacts/local/scene/warehouse-fallback.png",
+ "x": 76, "y": 60, "width": 176, "height": 110,
+ "camera": {"centerXMetres": 3, "centerYMetres": 1.5, "centerZMetres": -2, "presentationScale": 0.24, "rotationXDegrees": 25, "rotationYDegrees": 35, "rotationZDegrees": 0}
+ }]
+ }]
+}
diff --git a/fixtures/Canonical/Scene/warehouse.firmament b/fixtures/Canonical/Scene/warehouse.firmament
new file mode 100644
index 00000000..c2c627d3
--- /dev/null
+++ b/fixtures/Canonical/Scene/warehouse.firmament
@@ -0,0 +1,79 @@
+// Compact automated warehouse. Original Aetheris industrial robot design;
+// ATLAS is a demo name. No affiliation with any robot manufacturer is implied.
+Template<L: Length, W: Length, H: Length> Struct Cuboid {
+ RoundedRect2 outline { center: [L / 2, W / 2]; size: [L, W]; radius: 1mm; }
+ Profile section { Loop Outer { outline |> TraceLoop } }
+ Extrude body { profile: section; from: 0mm; to: H; }
+}
+Template<R: Length, H: Length> Struct Pedestal {
+ RoundedRect2 outline { center: [0mm, 0mm]; size: [R, R]; radius: 5mm; }
+ Profile section { Loop Outer { outline |> TraceLoop } }
+ Extrude body { profile: section; from: 0mm; to: H; }
+}
+Record Site { x: Length; y: Length; z: Length; }
+Static robotSites: Set<Site> {
+ loading => Site { x: 1000mm; y: 2000mm; z: 658mm; }
+ sorting => Site { x: 2500mm; y: 2000mm; z: 658mm; }
+ packing => Site { x: 4000mm; y: 2000mm; z: 658mm; }
+}
+Static packageSites: Set<Site> {
+ first => Site { x: 1.3m; y: 1.05m; z: .7m; }
+ second => Site { x: 1.9m; y: 1.05m; z: .7m; }
+ third => Site { x: 2.5m; y: 1.05m; z: .7m; }
+ fourth => Site { x: 3.1m; y: 1.05m; z: .7m; }
+ fifth => Site { x: 3.7m; y: 1.05m; z: .7m; }
+}
+Appearance concrete { color: [.48, .52, .56]; metallic: 0; roughness: .8; }
+Appearance safetyBlue { color: [.04, .18, .42]; metallic: .5; roughness: .35; }
+Appearance belt { color: [.035, .045, .05]; metallic: 0; roughness: .7; }
+Appearance cardboard { color: [.55, .32, .12]; metallic: 0; roughness: .9; }
+Appearance robotOrange { color: [.9, .19, .025]; metallic: .25; roughness: .35; }
+
+Scene WarehouseX0 {
+ units: m;
+ Room warehouse { size: [6m, 4m, 3m]; thickness: 100mm; appearance: concrete; }
+ Door loadingBay { on: warehouse.southWall; width: 1.5m; height: 2.4m; along: .4m; }
+ Window officeGlass { on: warehouse.eastWall; width: 1.5m; height: 1m; sill: 1.2m; along: 1m; }
+
+ <Part conveyor = Cuboid<L:3400mm,W:650mm,H:120mm>>
+ appearance: belt;
+ Placement { from: Origin; to: World; translateLocal: [1m, .9m, .58m]; }
+ </Part>
+ <Part conveyorStandA = Cuboid<L:150mm,W:500mm,H:580mm>>
+ appearance: safetyBlue;
+ Placement { from: Origin; to: World; translateLocal: [1.2m, 1m, 0mm]; }
+ </Part>
+ <Part conveyorStandB = Cuboid<L:150mm,W:500mm,H:580mm>>
+ appearance: safetyBlue;
+ Placement { from: Origin; to: World; translateLocal: [4m, 1m, 0mm]; }
+ </Part>
+ <Part rackBack = Cuboid<L:3000mm,W:100mm,H:2000mm>>
+ appearance: safetyBlue;
+ Placement { from: Origin; to: World; translateLocal: [1.5m, 3.7m, 0mm]; }
+ </Part>
+ <Part rackShelfLow = Cuboid<L:3000mm,W:600mm,H:60mm>>
+ appearance: safetyBlue;
+ Placement { from: Origin; to: World; translateLocal: [1.5m, 3.1m, .55m]; }
+ </Part>
+ <Part rackShelfHigh = Cuboid<L:3000mm,W:600mm,H:60mm>>
+ appearance: safetyBlue;
+ Placement { from: Origin; to: World; translateLocal: [1.5m, 3.1m, 1.25m]; }
+ </Part>
+ Pattern robots over robotSites {
+ site => <Assembly robot = AssemblyFile<"../AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament">>
+ appearance: robotOrange;
+ Placement { from: Origin; to: World; translateLocal: [site.x, site.y, site.z]; }
+ </Assembly>
+ <Part pedestal = Pedestal<R:300mm,H:650mm>>
+ appearance: safetyBlue;
+ Placement { from: Origin; to: World; translateLocal: [site.x, site.y, 0mm]; }
+ </Part>
+ }
+ Pattern packages over packageSites {
+ site => <Part package = Cuboid<L:250mm,W:300mm,H:250mm>>
+ appearance: cardboard;
+ Placement { from: Origin; to: World; translateLocal: [site.x, site.y, site.z]; }
+ </Part>
+ }
+ Camera hero { position: [5.6m, .25m, 2.65m]; lookAt: [2.5m, 2.1m, .8m]; fov: 65deg; }
+}
diff --git a/scripts/render-scene-x0.py b/scripts/render-scene-x0.py
new file mode 100644
index 00000000..a6003744
--- /dev/null
+++ b/scripts/render-scene-x0.py
@@ -0,0 +1,59 @@
+"""Independent Blender GLB import, physical-size/instancing checks and authored-camera preview.
+blender --background --python-exit-code 1 --python scripts/render-scene-x0.py -- warehouse.glb output-dir
+Only presentation lights are added; imported scene geometry is unchanged.
+"""
+import json
+import math
+import sys
+from pathlib import Path
+import bpy
+from mathutils import Vector
+
+source, output = [Path(p).resolve() for p in sys.argv[sys.argv.index('--') + 1:][:2]]
+output.mkdir(parents=True, exist_ok=True)
+bpy.ops.wm.read_factory_settings(use_empty=True)
+bpy.ops.import_scene.gltf(filepath=str(source))
+scene = bpy.context.scene
+products = [o for o in scene.objects if o.type == 'MESH']
+cameras = [o for o in scene.objects if o.type == 'CAMERA']
+assert products and len(cameras) == 1
+points = [o.matrix_world @ Vector(c) for o in products for c in o.bound_box]
+lo = [min(p[i] for p in points) for i in range(3)]
+hi = [max(p[i] for p in points) for i in range(3)]
+assert all(math.isfinite(v) for v in lo + hi)
+assert abs((hi[0]-lo[0])-6.2) < .001
+assert abs((hi[1]-lo[1])-4.2) < .001
+assert abs((hi[2]-lo[2])-3.2) < .001
+assert len({o.data.as_pointer() for o in products}) < len(products)
+for obj in products:
+ assert obj.matrix_world.determinant() > 0
+ assert obj.data.polygons
+report = dict(tool='Blender', version=bpy.app.version_string, meshes=len(products),
+ sharedMeshData=len({o.data.as_pointer() for o in products}),
+ boundsMetres=dict(min=lo, max=hi), camera=cameras[0].name)
+(output/'blender-validation.json').write_text(json.dumps(report, indent=2)+'\n')
+scene.camera = cameras[0]
+scene.camera.data.clip_start = .01
+scene.camera.data.clip_end = 100
+scene.world = bpy.data.worlds.new('Warehouse presentation world')
+scene.world.use_nodes = True
+scene.world.node_tree.nodes['Background'].inputs['Strength'].default_value = .2
+for i, point in enumerate([(1.5,1.5,2.8),(4,2.5,2.8)]):
+ data = bpy.data.lights.new('Presentation area '+str(i), 'AREA')
+ data.energy = 600
+ data.size = 2
+ light = bpy.data.objects.new(data.name, data)
+ scene.collection.objects.link(light)
+ light.location = point
+scene.render.engine = 'CYCLES'
+scene.cycles.samples = 24
+scene.cycles.use_denoising = True
+scene.render.resolution_x = 1440
+scene.render.resolution_y = 900
+scene.render.resolution_percentage = 100
+scene.render.image_settings.file_format = 'PNG'
+scene.render.filepath = str(output/'warehouse-fallback.png')
+scene.view_settings.view_transform = 'AgX'
+bpy.ops.wm.save_as_mainfile(filepath=str(output/'warehouse-imported.blend'))
+bpy.ops.render.render(write_still=True)
+print(json.dumps(report))