Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add Difference Engine showcase and repair assembly transforms
Yuechen Li1f717a133b81
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 57a2d636..b9ca7cd2 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -5229,7 +5229,7 @@ Model CanonicalPanel {private static void WriteAsmHelp(TextWriter stdout){- stdout.WriteLine("Inspect Firmament V2 assemblies. .firmasm is the supported Assembly document profile; only its historical JSON-shaped syntax is legacy.");+ stdout.WriteLine("Inspect Firmament V2 assemblies authored in .firmament or the .firmasm Assembly document profile. Historical JSON-shaped .firmasm syntax is legacy.");stdout.WriteLine();stdout.WriteLine(AsmExecUsage);stdout.WriteLine($" or: {AsmExportUsage[7..]}");diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.csindex 27da0cf9..ade86574 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs@@ -10,6 +10,28 @@ namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;public sealed class SurfaceMeshIrTests{+ [Theory]+ [InlineData(0d, 0d, 0d)]+ [InlineData(96d, 14d, -36d)]+ public void ExtrudedRectangle_RespectsExistingTrimSense_InDisplayAndExport(double x, double y, double z)+ {+ var frame = new ExtrudeFrame3D(new Point3D(x, y, z),+ Direction3D.Create(new Vector3D(0, 0, 1)), Direction3D.Create(new Vector3D(1, 0, 0)));+ var body = BrepExtrude.Create(PolylineProfile2D.Rectangle(484, 188), frame, 16).Value;+ Assert.True(SurfaceMeshIrTessellator.TryBuild(body, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out var document));+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out _, out var report));+ Assert.Equal(484d * 188d * 16d, report.SignedVolume, 6);+ var display = BrepDisplayTessellator.TessellateSurfaceMeshIr(body);+ Assert.True(display.IsSuccess);+ foreach (var face in display.Value.FacePatches)+ for (var i = 0; i < face.TriangleIndices.Count; i += 3)+ {+ var a = face.TriangleIndices[i]; var b = face.TriangleIndices[i + 1]; var c = face.TriangleIndices[i + 2];+ var cross = (face.Positions[b] - face.Positions[a]).Cross(face.Positions[c] - face.Positions[a]);+ Assert.True(cross.Dot(face.Normals[a]) > 0);+ }+ }+[Fact]public void Box_UsesSharedLinePlans_AndMostlyQuadPatchCells(){diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex 06a4fd7c..9d3dc283 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -698,7 +698,9 @@ public static class SurfaceMeshIrTessellatorvar coedges = body.GetCoedgeIds(outer.LoopId).Select(body.Topology.GetCoedge).ToArray();if (coedges.Length == 4 && coedges.All(c => plans[c.EdgeId].CurveKind == CurveGeometryKind.Line3) && outer.VertexIds.Count == 4)return new SurfacePatch(faceId, new SurfaceMeshSupport(SurfaceMeshSupportKind.Plane, Plane: plane), loops,- [new QuadCell(Orient(outer.VertexIds, sameSense))], sameSense, TrimLoopData: annotatedLoops, PlanarPlannerPath: "PlanarDomain.RectangleQuad");+ // Trim loops may already run against the support normal (e.g. an extrusion bottom).+ // Keep their order only when its measured sense matches the face sense.+ [new QuadCell(Orient(outer.VertexIds, (outer.SignedArea > 0d) == sameSense))], sameSense, TrimLoopData: annotatedLoops, PlanarPlannerPath: "PlanarDomain.RectangleQuad");}PlanarFeatureDecompositionPlan? failedFeaturePlan = null;if (inners.Length > 0)diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/NestedOccurrenceFrameTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/NestedOccurrenceFrameTests.csnew file mode 100644index 00000000..af1540c1--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/NestedOccurrenceFrameTests.cs@@ -0,0 +1,23 @@+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class NestedOccurrenceFrameTests+{+ [Fact]+ public void TranslatedNestedMembersComposeOnceUnderARotatedParent()+ {+ var source=FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/nested-occurrence-frames.firmament");+ var compiled=new AssemblyM1Pipeline().CompileFile(source);+ Assert.True(compiled.IsSuccess,string.Join("\n",compiled.Diagnostics.Select(d=>d.Message)));+ var tip=compiled.Ir!.Instances.Single(i=>i.Path.ToString()=="NestedFrames.Rotated.Offset.Tip");+ // Rz(90) * ([30,0,40] + [5,7,11]) + [100,200,300].+ Assert.Equal(93,tip.ResolvedTransform!.Matrix[12],9);+ Assert.Equal(235,tip.ResolvedTransform.Matrix[13],9);+ Assert.Equal(351,tip.ResolvedTransform.Matrix[14],9);+ var mesh=AssemblyDisplayMeshExporter.Export(compiled);+ Assert.Equal(tip.ResolvedTransform.Matrix,mesh.Occurrences.Single(i=>i.Id==tip.StableId).Transform);+ Assert.Equal(2,mesh.Definitions.Count);+ Assert.True(AssemblyIrAp242Exporter.Export(compiled).IsSuccess);+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex 6dd22d3b..9e3d0a8d 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -407,7 +407,18 @@ public sealed class AssemblyM0ParserAssemblyMemberSource ApplyLocal(AssemblyMemberSource item, AssemblyPath path){var localInstance = local.Ir.Instances.Single(instance => instance.Path.ToString() == path.ToString());- return item with { Children = item.Children.Select(child => ApplyLocal(child, path.Append(child.Name))).ToArray(), ExplicitTransform = item == specializedRoot ? null : localInstance.ResolvedTransform };+ // The solved definition stores world frames within its local root.+ // A reusable member tree must store parent-relative frames, otherwise+ // each nested occurrence applies its ancestors' transforms again.+ AssemblyTransform? relative = null;+ if (item != specializedRoot)+ {+ var world = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(localInstance.ResolvedTransform!.Matrix);+ var parent = local.Ir.Instances.Single(instance => instance.StableId == localInstance.ParentStableId);+ var parentWorld = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(parent.ResolvedTransform!.Matrix);+ relative = new((world * parentWorld.Inverse()).ToRowMajor());+ }+ return item with { Children = item.Children.Select(child => ApplyLocal(child, path.Append(child.Name))).ToArray(), ExplicitTransform = relative };}specializedRoot = ApplyLocal(specializedRoot, new([specializedRoot.Name]));var publicSemantics = specializedRoot.ExposedSemantics.Select(value => BindPublicSemantic(value, local.Ir, sourceIdentity)).ToArray();diff --git a/Aetheris.slnx b/Aetheris.slnxindex 08052c00..4e8c59ff 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -65,6 +65,7 @@</Project><Project Path="Aetheris.CLI/Aetheris.CLI.csproj" /><Folder Name="/demos/">+ <Project Path="demos/Aetheris.DifferenceEngine.Showcase/Aetheris.DifferenceEngine.Showcase.csproj" /><Project Path="demos/Aetheris.DifferenceEngine/Aetheris.DifferenceEngine.csproj" /><Project Path="demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj" /><Project Path="demos/Aetheris.EditableV8/Aetheris.EditableV8.csproj" />diff --git a/demos/Aetheris.DifferenceEngine.Showcase/Aetheris.DifferenceEngine.Showcase.csproj b/demos/Aetheris.DifferenceEngine.Showcase/Aetheris.DifferenceEngine.Showcase.csprojnew file mode 100644index 00000000..55d485ad--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/Aetheris.DifferenceEngine.Showcase.csproj@@ -0,0 +1,4 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><IsPackable>false</IsPackable></PropertyGroup>+ <ItemGroup><ProjectReference Include="../../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj" /></ItemGroup>+</Project>diff --git a/demos/Aetheris.DifferenceEngine.Showcase/Prepare-Viewer.ps1 b/demos/Aetheris.DifferenceEngine.Showcase/Prepare-Viewer.ps1new file mode 100644index 00000000..8cff1b49--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/Prepare-Viewer.ps1@@ -0,0 +1,16 @@+[CmdletBinding()]+param([string]$Output='artifacts/local/demos/difference-engine-showcase')+$ErrorActionPreference='Stop'+$repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))+$Output=[IO.Path]::GetFullPath($Output)+$dist=Join-Path $Output 'dist'+$three=Join-Path $repo 'aetheris.client/node_modules/three'+if(!(Test-Path -LiteralPath "$three/build/three.module.js")){throw 'Restore aetheris.client dependencies to provide the existing Three.js renderer.'}+New-Item -ItemType Directory -Force -Path "$dist/vendor"|Out-Null+Copy-Item -LiteralPath "$three/build/three.module.js","$three/build/three.core.js","$three/examples/jsm/controls/OrbitControls.js" -Destination "$dist/vendor"+Copy-Item -LiteralPath "$three/LICENSE" -Destination "$dist/vendor/three.LICENSE"+Copy-Item -LiteralPath "$three/examples/jsm/environments/RoomEnvironment.js" -Destination "$dist/vendor"+Copy-Item -Path "$PSScriptRoot/web/*" -Destination $dist+Copy-Item -LiteralPath "$Output/machine.mesh.json","$Output/difference-engine.step","$Output/design.json","$Output/motion.json","$Output/receipts.json" -Destination $dist+if(Test-Path -LiteralPath "$Output/review/assembly-hero.png") { Copy-Item -LiteralPath "$Output/review/assembly-hero.png" -Destination "$dist/preview.png" }+Write-Host "Production assets prepared: $dist"diff --git a/demos/Aetheris.DifferenceEngine.Showcase/PresentationManifest.cs b/demos/Aetheris.DifferenceEngine.Showcase/PresentationManifest.csnew file mode 100644index 00000000..e2555473--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/PresentationManifest.cs@@ -0,0 +1,119 @@+using System.Security.Cryptography;+using System.Text.Json;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.DifferenceEngine.Showcase;++public sealed record PresentationBinding(string OccurrenceId,string Kind,double[] Pivot,double Ratio,int Register,int Digit,string Role);+public sealed record PresentationGearLink(string A,string B,double Ratio,int TeethA,int TeethB,double CenterDistanceMm,string Interface);+public sealed record ExplosionBinding(string OccurrenceId,double[] Offset);+public sealed record DemonstrationState(int Result,int FirstDifference,int SecondDifference);+public sealed record DemonstrationProgram(string Id,string Name,IReadOnlyList<DemonstrationState> States);++public static class PresentationManifest+{+ private static readonly JsonSerializerOptions Json = new(){PropertyNamingPolicy=JsonNamingPolicy.CamelCase,WriteIndented=true};+ public static void Write(string output,ShowcaseDesign design,AssemblyM1CompilationResult compiled,AssemblyDisplayMeshDocument mesh)+ {+ var ir=compiled.Ir!;var byPath=mesh.Occurrences.ToDictionary(o=>o.Path,StringComparer.Ordinal);+ var byId=mesh.Occurrences.ToDictionary(o=>o.Id,StringComparer.Ordinal);+ var definitions=mesh.Definitions.ToDictionary(d=>d.Id,StringComparer.Ordinal);+ var gearAir=GearAuthoring.ParseDefinitions(File.ReadAllText(Path.Combine(output,"source/parts/Showcase.firmament"))).Gears.ToDictionary(g=>g.Name,StringComparer.Ordinal);+ var links=new List<PresentationGearLink>();+ void Add(MateIr mate,string? localRoot=null,string? occurrencePath=null) {+ if(mate.GearResult is not {Ratio:{} ratio} g)return;+ string Resolve(string id)=>localRoot is null?id:"assembly-instance:"+occurrencePath+id[("assembly-instance:"+localRoot).Length..];+ var a=Resolve(g.A.OccurrenceIdentity);var b=Resolve(g.B.OccurrenceIdentity);+ if(!byId.ContainsKey(a)||!byId.ContainsKey(b))throw new InvalidOperationException("presentation-gear-endpoint-missing");+ links.Add(new(a,b,ratio*g.RotationSign,g.A.Teeth!.Value,g.B.Teeth!.Value,g.ActualCenterDistanceMm,mate.Name));+ }+ foreach(var mate in ir.Mates)Add(mate);+ foreach(var definition in ir.AssemblyDefinitions!)foreach(var occurrence in ir.Instances.Where(i=>i.DefinitionIdentity==definition.DefinitionIdentity))+ foreach(var mate in definition.LocalMates)Add(mate,definition.TemplateName,occurrence.Path.ToString());+ links=links.DistinctBy(l=>l.A+"|"+l.B).OrderBy(l=>l.A,StringComparer.Ordinal).ThenBy(l=>l.B,StringComparer.Ordinal).ToList();+ var ratios=new Dictionary<string,double>(StringComparer.Ordinal);+ var seeds=new[]{"assembly-instance:DifferenceEngine.MainCrank.DriveGear"}+ .Concat(Enumerable.Range(0,4).Select(d=>$"assembly-instance:DifferenceEngine.ResultRegister.Digit{d}.DriveGear"));+ foreach(var seed in seeds) {+ if(ratios.ContainsKey(seed))continue;+ ratios[seed]=1;var queue=new Queue<string>();queue.Enqueue(seed);+ while(queue.TryDequeue(out var current))foreach(var edge in links.Where(l=>l.A==current||l.B==current)) {+ var next=edge.A==current?edge.B:edge.A;var ratio=ratios[current]*(edge.A==current?edge.Ratio:1/edge.Ratio);+ if(ratios.TryGetValue(next,out var existing)){if(double.Abs(existing-ratio)>1e-9)throw new InvalidOperationException("presentation-gear-cycle-conflict");}+ else {ratios[next]=ratio;queue.Enqueue(next);}+ }+ }+ var bindings=new List<PresentationBinding>();+ var explosions=new List<ExplosionBinding>();+ foreach(var occurrence in mesh.Occurrences){+ var path=occurrence.Path;var name=path.Split('.').Last();+ var register=path.Contains(".ResultRegister",StringComparison.Ordinal)?0:path.Contains(".FirstDifferenceRegister",StringComparison.Ordinal)?1:path.Contains(".SecondDifferenceRegister",StringComparison.Ordinal)?2:-1;+ var match=Regex.Match(path,@"\.Digit([0-3])(?:\.|$)");var digit=match.Success?int.Parse(match.Groups[1].Value):-1;+ if(occurrence.DefinitionId is null){+ var offset=name switch {+ "Frame"=>new[]{0d,110,0}, "MainCrank"=>new[]{-100d,0,0},+ "ResultRegister"=>new[]{-90d,0,0},"SecondDifferenceRegister"=>new[]{90d,0,0},+ "Transfer0" or "Transfer1"=>new[]{0d,-100,0}, "Carry"=>new[]{42d,20,0}, "Wheel"=>new[]{0d,0,18},+ _ when name.StartsWith("Digit",StringComparison.Ordinal)&&digit>=0=>new[]{0d,0,(digit-1.5)*32}, _=>new[]{0d,0,0}};+ explosions.Add(new(occurrence.Id,offset));continue;+ }+ var pivot=new[]{occurrence.Transform[12],occurrence.Transform[13],occurrence.Transform[14]};+ var kind="Static";var ratio=0d;var role=path.Contains(".Frame.",StringComparison.Ordinal)?"Frame":"Structure";+ if(gearAir.TryGetValue(definitions[occurrence.DefinitionId].Identity,out var gear))role=gear.Family.ToString();+ if(ratios.TryGetValue(occurrence.Id,out ratio))kind="GearRatio";+ else if(path.Contains(".Wheel.",StringComparison.Ordinal)){+ kind="IndexedWheel";var owner=byPath[path[..path.IndexOf(".Wheel.",StringComparison.Ordinal)]];+ pivot=[owner.Transform[12],owner.Transform[13],owner.Transform[14]];+ }+ else if(register>=0&&name=="Shaft"){kind="GearRatio";ratio=ratios[$"assembly-instance:DifferenceEngine.{path.Split('.')[1]}.Digit0.DriveGear"];}+ else if(path.Contains(".MainCrank.",StringComparison.Ordinal)&&name is "Shaft" or "Arm" or "Handle") {kind="GearRatio";ratio=1;pivot=[-88,0,0];}+ else if(path.Contains(".Carry.",StringComparison.Ordinal)&&name is "Pawl" or "Lever") {+ kind="CarryLever";var pin=byPath[path[..path.LastIndexOf('.')]+".Pivot"];+ pivot=[pin.Transform[12],pin.Transform[13],pin.Transform[14]+36];+ }+ else if(path.Contains(".Carry.",StringComparison.Ordinal)&&name is "ResetLink" or "LinkPin")kind="CarryLift";+ bindings.Add(new(occurrence.Id,kind,pivot,ratio,register,digit,role));+ }+ if(bindings.Count!=compiled.Geometry!.InstanceBodies.Count)throw new InvalidOperationException("presentation-missing-occurrence");+ var gantryClearances=Enumerable.Range(0,3).Select(r=>{+ var registerName=new[]{"ResultRegister","FirstDifferenceRegister","SecondDifferenceRegister"}[r];+ var crown=compiled.Geometry.Artifact.Instances.Single(i=>i.InstanceStableId==$"assembly-instance:DifferenceEngine.{registerName}.Crown");+ var bridge=compiled.Geometry.Artifact.Instances.Single(i=>i.InstanceStableId==$"assembly-instance:DifferenceEngine.Frame.CrownBridge{r*128}");+ var shaft=compiled.Geometry.Artifact.Instances.Single(i=>i.InstanceStableId==$"assembly-instance:DifferenceEngine.{registerName}.Shaft");+ var clearance=bridge.Metrics.Minimum[2]-crown.Metrics.Maximum[2];+ if(clearance<9.999999||shaft.Metrics.Maximum[2]<bridge.Metrics.Maximum[2]+3.999999)+ throw new InvalidOperationException($"showcase-gantry-clearance:{registerName}:{clearance}");+ return new{register=registerName,crownOccurrenceId=crown.InstanceStableId,bridgeOccurrenceId=bridge.InstanceStableId,clearanceMm=clearance,shaftProjectionMm=shaft.Metrics.Maximum[2]-bridge.Metrics.Maximum[2],placement="Interface<Fixed> GantryMount"+r};+ }).ToArray();+ foreach(var r in Enumerable.Range(0,3))foreach(var d in Enumerable.Range(0,4)) {+ var path=$"DifferenceEngine.{new[]{"ResultRegister","FirstDifferenceRegister","SecondDifferenceRegister"}[r]}.Digit{d}.Wheel.Drum";+ var drum=byPath[path];+ if(double.Abs(drum.Transform[12]-r*design.RegisterPitch)>1e-8||double.Abs(drum.Transform[14]-(design.FirstLevel+d*design.DigitPitch))>1e-8)+ throw new InvalidOperationException($"showcase-nested-placement:{path}");+ }+ var programs=new[]{+ new DemonstrationProgram("squares","Squares",Enumerable.Range(0,101).Select(n=>new DemonstrationState(n*n%10000,2*n+1,2)).ToArray()),+ new DemonstrationProgram("triangular","Triangular numbers",Enumerable.Range(0,101).Select(n=>new DemonstrationState(n*(n+1)/2,n+1,1)).ToArray()),+ new DemonstrationProgram("carry","Carry · 0099 → 0100",new[]{new DemonstrationState(99,1,0),new DemonstrationState(100,1,0)})};+ var manifest=new{schema="aetheris/difference-engine-presentation/1",authority="Prescribed choreography and demonstration sequences; not physical mechanism simulation",cycleSeconds=6,+ design,bindings,gearLinks=links,explosions,programs,+ drums=bindings.Where(b=>byId[b.OccurrenceId].Path.EndsWith(".Drum",StringComparison.Ordinal)).Select(b=>new{b.OccurrenceId,b.Register,b.Digit,radiusMm=34.25,labelZMm=22}),+ provenance=ir.SourceDependencies!.Select(d=>new{path=Path.GetRelativePath(output,d.Path).Replace('\\','/'),d.Sha256}).OrderBy(d=>d.path,StringComparer.Ordinal)};+ File.WriteAllText(Path.Combine(output,"motion.json"),JsonSerializer.Serialize(manifest,Json));+ var inventory=new{schema="aetheris/difference-engine-receipts/1",uniqueDefinitions=mesh.Definitions.Count,physicalOccurrences=bindings.Count,+ registers=3,digitModules=12,gears=bindings.Count(b=>b.Role=="SpurGear"),ratchets=bindings.Count(b=>b.Role=="RatchetGear"),pawls=bindings.Count(b=>b.Role=="Pawl"),+ shafts=bindings.Count(b=>Regex.IsMatch(byId[b.OccurrenceId].Path,@"\.(Shaft|.*Axle)$")),structuralMembers=bindings.Count(b=>b.Role is "Frame" or "Structure"&&b.Kind=="Static"),+ hierarchyDepth=ir.Instances.Max(i=>i.Path.Segments.Count),sourceFiles=ir.SourceDependencies!.Count,uniqueTriangles=mesh.Definitions.Sum(d=>d.Indices.Length/3),+ renderedTriangles=mesh.Occurrences.Where(o=>o.DefinitionId!=null).Sum(o=>definitions[o.DefinitionId!].Indices.Length/3),+ gearInterfaces=links.Count,gantryClearances,stepBytes=new FileInfo(Path.Combine(output,"difference-engine.step")).Length,+ aetherisVersion=typeof(AssemblyM1Pipeline).Assembly.GetName().Version!.ToString(),+ sharedModules=ir.AssemblyDefinitions!.Select(d=>new{definition=d.DefinitionIdentity,occurrences=ir.Instances.Count(i=>i.DefinitionIdentity==d.DefinitionIdentity)}),+ definitions=compiled.Geometry.Artifact.Definitions.Select(d=>new{d.StableId,d.DefinitionIdentity,d.StepSha256,d.Metrics}),+ receipts=new[]{"difference-engine.step","machine.mesh.json","motion.json"}.Select(f=>new{file=f,sha256=Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(output,f))))})};+ File.WriteAllText(Path.Combine(output,"receipts.json"),JsonSerializer.Serialize(inventory,Json));+ var files=Directory.GetFiles(Path.Combine(output,"source"),"*.firmament",SearchOption.AllDirectories).Concat(new[]{"difference-engine.step","machine.mesh.json","motion.json","design.json","receipts.json"}.Select(f=>Path.Combine(output,f))).Order(StringComparer.Ordinal);+ File.WriteAllText(Path.Combine(output,"hashes.json"),JsonSerializer.Serialize(files.ToDictionary(f=>Path.GetRelativePath(output,f).Replace('\\','/'),f=>Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(f)))),Json));+ }+}diff --git a/demos/Aetheris.DifferenceEngine.Showcase/Program.cs b/demos/Aetheris.DifferenceEngine.Showcase/Program.csnew file mode 100644index 00000000..b4bb486a--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/Program.cs@@ -0,0 +1,32 @@+using System.Security.Cryptography;+using System.Text.Json;+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.DifferenceEngine.Showcase;+public static class Program+{+ public static int Main(string[] args)+ {+ try {+ var output=Path.GetFullPath(args.Length>0?args[0]:"artifacts/local/demos/difference-engine-showcase");+ var design=args.Length>1?JsonSerializer.Deserialize<ShowcaseDesign>(File.ReadAllText(args[1]))!:new();+ var fixtures=Path.GetFullPath(args.Length>2?args[2]:"fixtures/DifferenceEngine");+ var source=Path.Combine(output,"source"); design.WriteSources(source,fixtures);+ Console.WriteLine("Compiling full showcase assembly…");+ var compiled=new AssemblyM1Pipeline().CompileFile(Path.Combine(source,"DifferenceEngine.firmament"));+ File.WriteAllText(Path.Combine(output,"build-diagnostics.json"),JsonSerializer.Serialize(new{compiled.Diagnostics,compiled.Ir},new JsonSerializerOptions{WriteIndented=true}));+ if(compiled.Geometry is {} geometry) File.WriteAllText(Path.Combine(output,"body-bounds.json"),JsonSerializer.Serialize(geometry.DefinitionBodies.Select(p=>new{p.Key,points=p.Value.Topology.Vertices.Select(v=>{p.Value.TryGetVertexPoint(v.Id,out var point);return point;}).ToArray()})));+ if(!compiled.IsSuccess)throw new InvalidOperationException(string.Join("\n",compiled.Diagnostics.Select(d=>d.Code+": "+d.Message)));+ var step=AssemblyIrAp242Exporter.Export(compiled); if(!step.IsSuccess)throw new InvalidOperationException(string.Join("\n",step.Diagnostics.Select(d=>d.Message)));+ File.WriteAllText(Path.Combine(output,"difference-engine.step"),step.Value);+ Console.WriteLine($"CAD: {compiled.Geometry!.DefinitionBodies.Count} shared bodies; {compiled.Geometry.InstanceBodies.Count} occurrences. Meshing…");+ var mesh=AssemblyDisplayMeshExporter.Export(compiled);+ File.WriteAllText(Path.Combine(output,"machine.mesh.json"),AssemblyDisplayMeshExporter.Serialize(mesh));+ File.WriteAllText(Path.Combine(output,"design.json"),JsonSerializer.Serialize(design,new JsonSerializerOptions{WriteIndented=true}));+ File.WriteAllText(Path.Combine(output,"assembly-inspection.json"),JsonSerializer.Serialize(compiled.Ir,new JsonSerializerOptions{WriteIndented=true}));+ PresentationManifest.Write(output,design,compiled,mesh);+ Console.WriteLine($"Mesh: {mesh.Definitions.Sum(d=>d.Indices.Length/3)} unique triangles. Complete assembly exported.");+ return 0;+ } catch(Exception e){Console.Error.WriteLine(e);return 1;}+ }+}diff --git a/demos/Aetheris.DifferenceEngine.Showcase/README.md b/demos/Aetheris.DifferenceEngine.Showcase/README.mdnew file mode 100644index 00000000..c321462f--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/README.md@@ -0,0 +1,52 @@+# Difference Engine showcase++A Babbage-inspired, three-register, four-digit assembly. Aetheris owns every mechanical surface, stable occurrence identity, shared mesh definition and AP242 assembly. The browser illustrates authored demonstration programs with prescribed motion.++## Run locally++From the repository root, with .NET 10, Node.js and Python on PATH:++```powershell+./demos/Aetheris.DifferenceEngine.Showcase/Run.ps1+```++This generates CAD, checks presentation, prepares the production assets and runs a foreground localhost server on port 8776. Open http://127.0.0.1:8776/. Stop the server with Ctrl+C. `-NoServe` only generates/checks the bundle. Three.js is reused from `aetheris.client/node_modules/three`; restore the client dependencies if absent. Nothing is deployed.++## Admitted configuration++The bounded configuration is `DigitPitch`, in millimetres, from 80 through 100 inclusive. Three registers and four digits remain fixed. Increasing pitch separates repeated digit modules, extends shafts and raises the frame, crown gantry and crank together. Gear module, tooth counts and register center distances stay compatible.++Save a JSON file such as `{ "DigitPitch": 90 }` under ignored `artifacts/local/`, then run:++```powershell+./demos/Aetheris.DifferenceEngine.Showcase/Run.ps1 -Spec artifacts/local/showcase-spec.json -Output artifacts/local/demos/showcase-variant -NoServe+```++For an already built executable (no rebuild required):++```powershell+dotnet demos/Aetheris.DifferenceEngine.Showcase/bin/Release/net10.0/Aetheris.DifferenceEngine.Showcase.dll artifacts/local/demos/showcase-variant artifacts/local/showcase-spec.json fixtures/DifferenceEngine+node demos/Aetheris.DifferenceEngine.Showcase/verify.mjs artifacts/local/demos/showcase-variant+./demos/Aetheris.DifferenceEngine.Showcase/Prepare-Viewer.ps1 -Output artifacts/local/demos/showcase-variant+```++The generator rejects values outside the admitted envelope. Do not edit generated Firmament: change the typed author in `ShowcaseDesign.cs` or the admitted JSON configuration. Source geometry templates are under `fixtures/DifferenceEngine/parts/`. Browser code only consumes exported meshes and occurrence IDs; its planes are text labels and the floor.++## Artifacts and authority++Outputs default to ignored `artifacts/local/demos/difference-engine-showcase/`:++- `source/`: ordinary Include/Subassembly/Expose Firmament hierarchy; all gear teeth come from the Gear Standard Library.+- `difference-engine.step`: complete AP242 rest assembly, without animation.+- `machine.mesh.json`: shared display meshes and stable occurrence hierarchy.+- `motion.json`: prescribed programs, actual gear-interface ratios, occurrence bindings and hierarchical explosion offsets.+- `receipts.json`: measured geometry counts, body metrics, gantry clearances and artifact fingerprints.+- `hashes.json`: deterministic source and artifact fingerprints.+- `assembly-inspection.json`: private full compiler inspection, including local paths; excluded from the site.+- `dist/`: self-contained static browser bundle, including STEP, local Three.js and its license.++The crown bars use three `Interface<Fixed>` mates to frame datum seats. Their bottom faces stay 10 mm above the register crowns; the supported shafts project 4 mm above the bars. This is checked against compiled instance body metrics on every generation. Meshed gears use `Interface<Gear>`; digit drive journals use `Interface<Revolute>`.++The browser evaluator is a pure function of program, step and phase. It does not add a state-machine stack. Reset/seek reconstruct transforms from CAD rest matrices, and explosion sums offsets along actual exported parent IDs. Ratchet and pawl animation illustrates carries; it does not qualify contact, clutch torque, transfer or manufacturing.++Read the [public guide](../../docs/public/demos/difference-engine-showcase.md), [gear documentation](../../docs/public/firmament/gears.md), and [assembly documentation](../../docs/public/firmament/assemblies.md). The earlier storage research remains in `demos/Aetheris.DifferenceEngine` and its historical release record.diff --git a/demos/Aetheris.DifferenceEngine.Showcase/Run.ps1 b/demos/Aetheris.DifferenceEngine.Showcase/Run.ps1new file mode 100644index 00000000..c504f79a--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/Run.ps1@@ -0,0 +1,15 @@+[CmdletBinding()]+param([string]$Output='artifacts/local/demos/difference-engine-showcase',[string]$Spec,[switch]$NoServe,[int]$Port=8776)+$ErrorActionPreference='Stop'+$repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))+Push-Location $repo+try {+ $argsList=@($Output)+ if($Spec){$argsList+=@($Spec,'fixtures/DifferenceEngine')}+ dotnet run --project "$PSScriptRoot/Aetheris.DifferenceEngine.Showcase.csproj" -c Release -- @argsList+ if($LASTEXITCODE -ne 0){throw 'CAD generation failed'}+ node "$PSScriptRoot/verify.mjs" $Output+ if($LASTEXITCODE -ne 0){throw 'Presentation qualification failed'}+ & "$PSScriptRoot/Prepare-Viewer.ps1" -Output $Output+ if(!$NoServe){python "$PSScriptRoot/serve.py" "$Output/dist" $Port}+} finally {Pop-Location}diff --git a/demos/Aetheris.DifferenceEngine.Showcase/ShowcaseDesign.cs b/demos/Aetheris.DifferenceEngine.Showcase/ShowcaseDesign.csnew file mode 100644index 00000000..aed54cf8--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/ShowcaseDesign.cs@@ -0,0 +1,136 @@+using System.Globalization;+using System.Text;++namespace Aetheris.DifferenceEngine.Showcase;++/// <summary>Bounded CAD author; presentation consumes its exported occurrence tree.</summary>+public sealed record ShowcaseDesign(double DigitPitch = 80)+{+ public int Digits => 4;+ public int Registers => 3;+ public double RegisterPitch => 128;+ public double FirstLevel => 42;+ public double Top => FirstLevel + 3 * DigitPitch + 64;+ public double GantryBottom => Top + 10;+ public double GantryThickness => 8;+ public double ShaftTop => GantryBottom + GantryThickness + 4;+ public void Validate() { if (!double.IsFinite(DigitPitch) || DigitPitch is < 80 or > 100) throw new ArgumentException("DigitPitch must be 80–100 mm."); }+ private static string N(double x) => x.ToString("G17", CultureInfo.InvariantCulture);+ private static string L(double x) => N(x) + "mm";+ private static string Ring(double ro, double ri, double z0, double z1) => $"Annulus<Rout: {L(ro)}, Rin: {L(ri)}, Zlow: {L(z0)}, Zhigh: {L(z1)}>";+ private static string Rod(double r, double z0, double z1) => $"RoundBar<R: {L(r)}, Zlow: {L(z0)}, Zhigh: {L(z1)}>";+ private static string Box(double w, double d, double h) => $"RectangularStock<W: {L(w)}, D: {L(d)}, H: {L(h)}>";+ private static string StockAt(double x,double y,double z,double w,double d,double h) => $"PositionedStock<X: {L(x)}, Y: {L(y)}, Zlow: {L(z)}, Zhigh: {L(z+h)}, W: {L(w)}, D: {L(d)}>";+ private const string Joint = "Semantic Joint { Axis Axis = [0,0,0] -> [0,0,1]; Plane Seat = [0,0,0] normal [0,0,1]; DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }";+ private static string Placement(double x, double y, double z, double angle = 0) {+ var c = N(double.Cos(angle)); var s = N(double.Sin(angle)); var ns = N(-double.Sin(angle));+ return $"Placement ImportedOccurrence = [{c},{s},0,0, {ns},{c},0,0, 0,0,1,0, {N(x)},{N(y)},{N(z)},1];";+ }+ private static string Part(string name, string type, double x=0, double y=0, double z=0, double angle=0,string semantics="",bool placed=true)+ {+ // A module's mounting datum is its origin, expressed in this part's+ // local frame. Its actual journal datum remains the separate Joint.+ var c=double.Cos(angle);var s=double.Sin(angle);+ var mount=$"Semantic Mount {{ DatumFrame Frame = [{N(-c*x-s*y)},{N(s*x-c*y)},{N(-z)}] x [{N(c)},{N(-s)},0] y [{N(s)},{N(c)},0] z [0,0,1]; }}";+ return $"<Part {name} = {type}> {Joint} {mount} {semantics} {(placed?Placement(x,y,z,angle):"")} </Part>\n";+ }+ private static string Child(string name, string type, double x=0, double y=0, double z=0)+ => $"<Assembly {name} = {type}> {Placement(x,y,z)} </Assembly>\n";+ private static string Module(string name, string members, string anchor, string relationships, string exposed)+ => $"Subassembly {name} {{\n<Assembly {name}>\n{members}</Assembly>\nAnchor: {name}.{anchor.Replace(".Joint", ".Mount", StringComparison.Ordinal)};\n{relationships}\nExpose {{ {exposed.Replace(".Joint;", ".Mount;", StringComparison.Ordinal)} }}\n}}\n";++ public void WriteSources(string destination, string fixtures)+ {+ Validate();+ Directory.CreateDirectory(Path.Combine(destination,"parts")); Directory.CreateDirectory(Path.Combine(destination,"modules"));+ foreach (var file in new[]{"Storage.firmament","Showcase.firmament"}) File.Copy(Path.Combine(fixtures,"parts",file),Path.Combine(destination,"parts",file),true);+ void Write(string file,string text) => File.WriteAllText(Path.Combine(destination,"modules",file),text);+ var stock = "Include \"../parts/Storage.firmament\";\nInclude \"../parts/Showcase.firmament\";\n";++ var wheel = Part("Drum",Ring(34,4.4,14,30)) + Part("LowerRim",Ring(35,4.4,12,14))+ + Part("UpperRim",Ring(35,4.4,30,32)) + Part("Hub",Ring(9,4.4,7,12))+ + Part("IndexRatchet","DecimalRatchet",z:36) + Part("UpperHub",Ring(8,4.4,32,36));+ Write("DigitWheel.firmament",stock+Module("DigitWheel",wheel,"Drum.Joint","","Semantic Mount = Drum.Joint; Gear Ratchet = IndexRatchet;"));++ var pivotX=34-8*.24*double.Cos(double.Pi/12);var pivotY=-8*.24*double.Sin(double.Pi/12);+ var carry = Part("Pawl","CarryPawl",x:34,z:36,angle:double.Pi)+ + Part("Pivot",Rod(2,33,44),pivotX,pivotY) + Part("PivotCollar",Ring(4,2.2,40,42),pivotX,pivotY)+ + Part("Pedestal",StockAt(46,0,8,8,10,25))+ + Part("Tongue",Box(22,10,3),39,0,33)+ + Part("Lever",Box(7,50,4),pivotX,20,42) + Part("LinkPin",Rod(2,44,59),pivotX,40)+ + Part("ResetLink",Box(7,7,17),pivotX,40,59);+ Write("CarryVisualModule.firmament",stock+Module("CarryVisualModule",carry,"Pedestal.Joint","","Semantic Mount = Pedestal.Joint;"));++ var digit = Part("Bearing",Ring(10,4.2,-12,-5)) + Part("DriveGear","RegisterDrive")+ + Part("LowerBridge","BearingBridge<W: 18mm, D: 116mm, H: 6mm, BoreD: 8.4mm>",z:-18)+ + Part("UpperBridge","BearingBridge<W: 18mm, D: 116mm, H: 6mm, BoreD: 8.4mm>",z:54)+ + Part("UpperBearing",Ring(10,4.2,48,54))+ + Child("Wheel","DigitWheel") + Child("Carry","CarryVisualModule");+ foreach(var y in new[]{-52d,52d}) {+ var name=y<0?"Front":"Rear";+ digit += Part(name+"Tie",Rod(2.5,-20,62),0,y)+Part(name+"Cap",Ring(4.5,2.5,60,63),0,y);+ }+ var revolute="Interface<Revolute> DriveJournal { A: DigitModule.DriveGear.Joint; B: DigitModule.Bearing.Joint; }";+ Write("DigitModule.firmament","Include \"DigitWheel.firmament\";\nInclude \"CarryVisualModule.firmament\";\n"+ +Module("DigitModule",digit,"Bearing.Joint",revolute,"Semantic Mount = Bearing.Joint; Gear Drive = DriveGear;"));++ var register = Part("Shaft",Rod(4,-20,ShaftTop-FirstLevel));+ var expose="Semantic Mount = Shaft.Joint;\n";+ for(var i=0;i<Digits;i++) {register+=Child("Digit"+i,"DigitModule",z:i*DigitPitch); expose+=$"Gear Drive{i} = Digit{i}.Drive;\n";}+ register+=Part("Crown",Ring(14,4,Top-FirstLevel-8,Top-FirstLevel))+Part("Foot",Ring(14,4,-20,-12))+ +Part("TopRetainer",Ring(8,4,GantryBottom+GantryThickness-FirstLevel,ShaftTop-FirstLevel));+ Write("Register.firmament","Include \"DigitModule.firmament\";\n"+Module("Register",register,"Shaft.Joint","",expose));++ var transfer="";+ foreach(var (name,x) in new[]{("Input",44d),("Output",84d)}) {+ transfer+=Part(name+"Gear","TransferIdler",x)+Part(name+"Axle",Rod(3,-18,12),x)+ +Part(name+"Bearing",Ring(7,3.2,-12,-5),x)+Part(name+"Collar",Ring(6,3.2,8,11),x);+ }+ transfer+=Part("Bridge","DoubleBearingBridge<W: 56mm>")+Part("RearSupport",Box(12,60,6),64,30,-24);+ Write("TransferModule.firmament",stock+Module("TransferModule",transfer,"Bridge.Joint",+ "Interface<Gear> IdlerMesh { A: TransferModule.InputGear; B: TransferModule.OutputGear; }",+ "Semantic Mount = Bridge.Joint; Gear Input = InputGear; Gear Output = OutputGear;"));+ var bank="";var ports="";+ for(var i=0;i<Digits;i++){bank+=Child("Level"+i,"TransferModule",z:i*DigitPitch);ports+=$"Gear Input{i} = Level{i}.Input; Gear Output{i} = Level{i}.Output;\n";}+ Write("TransferBank.firmament","Include \"TransferModule.firmament\";\n"+Module("TransferBank",bank,"Level0.Mount","",ports));++ var gantrySeats=string.Join("\n",Enumerable.Range(0,3).Select(r=>$"Semantic GantrySeat{r} {{ DatumFrame Frame = [{N(r*RegisterPitch)},0,{N(GantryBottom)}] x [1,0,0] y [0,1,0] z [0,0,1]; }}"));+ var frame=Part("Plinth",StockAt(96,14,-36,484,188,16),semantics:gantrySeats)+Part("BaseDeck",Box(464,168,8),96,14,-20);+ foreach(var (side,x) in new[]{("Left",-128d),("Right",320d)}) foreach(var (depth,y) in new[]{("Front",-60d),("Rear",88d)}) {+ frame+=Part(side+depth+"Post",Rod(7,-12,Top+12),x,y)+ +Part(side+depth+"Foot",Ring(13,7,-14,-6),x,y)+Part(side+depth+"Capital",Ring(13,7,Top,Top+12),x,y)+ +Part(side+depth+"Finial",Rod(9,Top+12,Top+20),x,y);+ }+ frame+=Part("TopFrontRail",Box(462,14,10),96,-60,Top)+Part("TopRearRail",Box(462,14,10),96,88,Top);+ for(var i=0;i<Digits;i++) frame+=Part("RearRail"+i,Box(450,12,8),96,62,FirstLevel+i*DigitPitch-18);+ foreach(var x in new[]{0d,128d,256d}) frame+=Part("RegisterSeat"+N(x),Ring(18,4.2,-12,FirstLevel-20),x,0)+ +Part("CrownBridge"+N(x),$"BearingBridge<W: 20mm, D: 176mm, H: {L(GantryThickness)}, BoreD: 8.4mm>",placed:false);+ frame+=Part("Plaque",Box(144,4,28),96,-82,-8);+ var gantryMates=string.Join("\n",Enumerable.Range(0,3).Select(r=>$"Interface<Fixed> GantryMount{r} {{ A: FrameBay.CrownBridge{N(r*RegisterPitch)}.Joint; B: FrameBay.Plinth.GantrySeat{r}; }}"));+ Write("Frame.firmament",stock+Module("FrameBay",frame,"Plinth.Joint",gantryMates,"Semantic Mount = Plinth.Joint;"));++ var crank=Part("Shaft",Rod(4,-12,GantryBottom+25),-88)+Part("DriveGear","RegisterDrive",-88,0,FirstLevel)+ +Part("Idler","TransferIdler",-44,0,FirstLevel)+Part("IdlerAxle",Rod(3,FirstLevel-18,FirstLevel+12),-44)+ +Part("Bearing","PositionedRing<X: -88mm, Y: 0mm, R: 12mm, BoreR: 4.2mm, Zlow: -12mm, Zhigh: 0mm>")+ +Part("BearingSeat","PositionedRing<X: -88mm, Y: 0mm, R: 16mm, BoreR: 12mm, Zlow: -12mm, Zhigh: 0mm>")+ +Part("UpperBearing",Ring(12,4.2,GantryBottom,GantryBottom+8),-88)+ +Part("Arm",Box(62,12,7),-113,0,GantryBottom+18)+Part("Handle",Rod(7,GantryBottom+25,GantryBottom+56),-138)+ +Part("CrankBridge","BearingBridge<W: 32mm, D: 176mm, H: 8mm, BoreD: 24.2mm>",-88,0,GantryBottom);+ Write("CrankDrive.firmament",stock+Module("CrankDrive",crank,"Bearing.Joint",+ "Interface<Gear> CrankMesh { A: CrankDrive.DriveGear; B: CrankDrive.Idler; }\nInterface<Fixed> BearingHousing { A: CrankDrive.Bearing.Joint; B: CrankDrive.BearingSeat.Joint; }",+ "Gear Output = Idler; Semantic Mount = Bearing.Joint;"));++ var root=new StringBuilder("Units: mm\nInclude \"modules/Register.firmament\";\nInclude \"modules/TransferBank.firmament\";\nInclude \"modules/Frame.firmament\";\nInclude \"modules/CrankDrive.firmament\";\nAssembly DifferenceEngine {\n<Assembly DifferenceEngine>\n");+ root.Append(Child("Frame","FrameBay")); root.Append(Child("MainCrank","CrankDrive"));+ var names=new[]{"ResultRegister","FirstDifferenceRegister","SecondDifferenceRegister"};+ for(var r=0;r<Registers;r++)root.Append(Child(names[r],"Register",r*RegisterPitch,0,FirstLevel));+ for(var b=0;b<2;b++)root.Append(Child("Transfer"+b,"TransferBank",b*RegisterPitch,0,FirstLevel));+ root.AppendLine("</Assembly>\nAnchor: DifferenceEngine.Frame.Mount;");+ root.AppendLine("Interface<Gear> CrankInput { A: DifferenceEngine.MainCrank.Output; B: DifferenceEngine.ResultRegister.Drive0; }");+ for(var b=0;b<2;b++)for(var d=0;d<Digits;d++){+ root.AppendLine($"Interface<Gear> Transfer{b}Input{d} {{ A: DifferenceEngine.{names[b]}.Drive{d}; B: DifferenceEngine.Transfer{b}.Input{d}; }}");+ root.AppendLine($"Interface<Gear> Transfer{b}Output{d} {{ A: DifferenceEngine.Transfer{b}.Output{d}; B: DifferenceEngine.{names[b+1]}.Drive{d}; }}");+ }+ root.AppendLine("}"); File.WriteAllText(Path.Combine(destination,"DifferenceEngine.firmament"),root.ToString());+ }+}diff --git a/demos/Aetheris.DifferenceEngine.Showcase/Verify-Packaged.ps1 b/demos/Aetheris.DifferenceEngine.Showcase/Verify-Packaged.ps1new file mode 100644index 00000000..59e81279--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/Verify-Packaged.ps1@@ -0,0 +1,23 @@+[CmdletBinding()]+param([string]$Output='artifacts/local/demos/difference-engine-showcase')+$ErrorActionPreference='Stop'+$repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))+$Output=[IO.Path]::GetFullPath($Output)+function Checked([scriptblock]$Command){& $Command;if($LASTEXITCODE){throw "Command failed ($LASTEXITCODE)"}}+$outside=Join-Path ([IO.Path]::GetTempPath()) ('aetheris-showcase-'+[guid]::NewGuid().ToString('N'))+New-Item -ItemType Directory -Force -Path $outside | Out-Null+Copy-Item -LiteralPath "$Output/source" -Destination "$outside/source" -Recurse+$version='2.0.0-showcase.'+[DateTime]::UtcNow.ToString('yyyyMMddHHmmss')+Checked {dotnet pack "$repo/Aetheris.CLI" -c Release -p:Version=$version -o "$Output/packages" --nologo -v q}+Checked {dotnet tool install Aetheris.CLI --version $version --add-source "$Output/packages" --tool-path "$outside/tool" --no-cache}+Push-Location $outside+try {+ Checked {& "$outside/tool/aetheris.exe" asm inspect source/DifferenceEngine.firmament --json > "$Output/cli-inspection.json"}+ Checked {& "$outside/tool/aetheris.exe" asm export-ap242 source/DifferenceEngine.firmament --out "$Output/packaged.step" --json > "$Output/packaged-export.json"}+ Checked {& "$outside/tool/aetheris.exe" mesh source/DifferenceEngine.firmament --format assembly-json --output "$Output/packaged.mesh.json" --json > "$Output/packaged-mesh.json"}+ Checked {& "$outside/tool/aetheris.exe" asm import-step "$Output/packaged.step" --out "$Output/packaged-reimport" --json > "$Output/packaged-reimport.json"}+} finally {Pop-Location}+if((Get-FileHash "$Output/difference-engine.step").Hash -ne (Get-FileHash "$Output/packaged.step").Hash){throw 'Packaged STEP mismatch'}+if((Get-FileHash "$Output/machine.mesh.json").Hash -ne (Get-FileHash "$Output/packaged.mesh.json").Hash){throw 'Packaged mesh mismatch'}+@{passed=$true;version=$version;outsideDirectory=$outside;stepSha256=(Get-FileHash "$Output/packaged.step").Hash;meshSha256=(Get-FileHash "$Output/packaged.mesh.json").Hash}|ConvertTo-Json|Set-Content "$Output/packaged-proof.json"+Write-Host 'Fresh packaged CLI outside checkout: STEP and shared meshes match exactly; AP242 import passed.'diff --git a/demos/Aetheris.DifferenceEngine.Showcase/serve.py b/demos/Aetheris.DifferenceEngine.Showcase/serve.pynew file mode 100644index 00000000..ea1f19bf--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/serve.py@@ -0,0 +1,15 @@+"""Foreground static production preview, intentionally without a backend."""+from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler+from functools import partial+import pathlib+import sys++root = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else 'artifacts/local/demos/difference-engine-showcase/dist').resolve()+port = int(sys.argv[2]) if len(sys.argv) > 2 else 8776+class Handler(SimpleHTTPRequestHandler):+ extensions_map = {**SimpleHTTPRequestHandler.extensions_map, '.mjs': 'text/javascript', '.js': 'text/javascript'}+ def end_headers(self):+ self.send_header('Cache-Control', 'no-store')+ super().end_headers()+print(f'http://127.0.0.1:{port}/', flush=True)+ThreadingHTTPServer(('127.0.0.1', port), partial(Handler, directory=str(root))).serve_forever()diff --git a/demos/Aetheris.DifferenceEngine.Showcase/verify.mjs b/demos/Aetheris.DifferenceEngine.Showcase/verify.mjsnew file mode 100644index 00000000..328f62de--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/verify.mjs@@ -0,0 +1,43 @@+import {readFileSync} from 'node:fs';+import assert from 'node:assert/strict';+import {evaluate,hierarchyOffsets} from './web/presentation.mjs';+const root=process.argv[2]??'artifacts/local/demos/difference-engine-showcase';+const read=f=>JSON.parse(readFileSync(`${root}/${f}`,'utf8'));+const manifest=read('motion.json'),mesh=read('machine.mesh.json'),receipts=read('receipts.json');+let transitions=0;+for(const program of manifest.programs)for(let step=0;step<program.states.length-1;step++){+ const start=evaluate(program,step,0),end=evaluate(program,step,1),next=program.states[step+1];+ assert.deepEqual(start.values,Object.values(program.states[step]));+ assert.deepEqual(end.values,Object.values(next));+ for(const phase of [0,.13,.28,.45,.6,.79,.93,1]){+ const p=evaluate(program,step,phase);assert.deepEqual(p,evaluate(program,step,phase));+ assert.ok(p.digits.every(d=>Number.isFinite(d.angle)&&d.carry>=0&&d.carry<=1));+ }+ transitions++;+}+const carry=manifest.programs.find(p=>p.id==='carry');+const pulses=[0,1].map(d=>Array.from({length:1001},(_,i)=>({t:i/1000,p:evaluate(carry,0,i/1000).digits[d].carry})).find(s=>s.p>.1).t);+assert.ok(pulses[0]<pulses[1],'Units carry must precede tens carry');+assert.deepEqual(evaluate(carry,0,1).values,[100,1,0]);+const bindings=new Map(manifest.bindings.map(b=>[b.occurrenceId,b]));+for(const link of manifest.gearLinks){+ assert.ok(Math.abs(link.ratio+link.teethA/link.teethB)<1e-10);+ assert.ok(Math.abs(bindings.get(link.b).ratio-bindings.get(link.a).ratio*link.ratio)<1e-10);+}+const offsets=hierarchyOffsets(mesh.occurrences,manifest.explosions);+assert.deepEqual(offsets.get('assembly-instance:DifferenceEngine.ResultRegister.Digit0.Wheel.Drum'),[-90,0,-30]);+assert.equal(new Set(manifest.bindings.map(b=>b.occurrenceId)).size,mesh.occurrences.filter(o=>o.definitionId).length);+assert.equal(manifest.drums.length,12);+for(const c of receipts.gantryClearances){assert.equal(c.clearanceMm,10);assert.equal(c.shaftProjectionMm,4);}+for(const definition of mesh.definitions){+ const p=definition.positions,n=definition.normals,ix=definition.indices;+ assert.ok(p.every(Number.isFinite));assert.ok(n.every(Number.isFinite));assert.ok(ix.every(i=>i>=0&&i<p.length/3));+ for(let axis=0;axis<3;axis++){const coordinates=p.filter((_,i)=>i%3===axis);assert.ok(Math.max(...coordinates)>Math.min(...coordinates),'Positive display extent');}+ for(let i=0;i<n.length;i+=3)assert.ok(Math.abs(Math.hypot(n[i],n[i+1],n[i+2])-1)<1e-9,'Unit surface normal');+ let volume=0;+ for(let i=0;i<ix.length;i+=3){const a=ix[i]*3,b=ix[i+1]*3,c=ix[i+2]*3;+ volume+=(p[a]*(p[b+1]*p[c+2]-p[b+2]*p[c+1])+p[a+1]*(p[b+2]*p[c]-p[b]*p[c+2])+p[a+2]*(p[b]*p[c+1]-p[b+1]*p[c]))/6;+ }+ assert.ok(volume>0,'Positive oriented display volume: '+definition.identity);+}+console.log(JSON.stringify({passed:true,transitions,gearLinks:manifest.gearLinks.length,carryPulseTimes:pulses,occurrences:bindings.size,gantryClearances:receipts.gantryClearances.map(c=>c.clearanceMm)}));diff --git a/demos/Aetheris.DifferenceEngine.Showcase/web/index.html b/demos/Aetheris.DifferenceEngine.Showcase/web/index.htmlnew file mode 100644index 00000000..e4da6a81--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/web/index.html@@ -0,0 +1,15 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>Difference Engine · Aetheris</title><meta name="description" content="A Babbage-inspired mechanical computer designed by GPT-6 Astra through Aetheris. Explore real CAD with prescribed explanatory animation.">+<meta property="og:title" content="The Difference Engine · Aetheris"><meta property="og:description" content="Real CAD. Mechanical arithmetic, made visible."><meta property="og:image" content="preview.png">+<link rel="stylesheet" href="style.css"><script type="importmap">{"imports":{"three":"./vendor/three.module.js","three/addons/":"./vendor/"}}</script>+</head><body>+<main id="machine" aria-label="Interactive Aetheris Difference Engine assembly"></main>+<header><span>AETHERIS <i>/</i> THE DIFFERENCE ENGINE</span><nav><button data-dialog="story">The story</button><button data-dialog="receipts">Inside the build</button><a href="difference-engine.step" download>STEP ↗</a></nav></header>+<section class="intro"><p class="eyebrow">A BABBAGE-INSPIRED STUDY</p><h1>Before software,<br><em>the machine.</em></h1><p>A mechanical computer designed by<br>GPT-6 Astra through Aetheris.</p></section>+<section class="readout" aria-label="Decimal registers"><div><span>RESULT</span><output id="result">0000</output></div><div><span>FIRST DIFFERENCE</span><output id="first">0001</output></div><div><span>SECOND DIFFERENCE</span><output id="second">0002</output></div><p id="equation">0 + 1 → 1</p><p id="stage" aria-live="off">Repeated addition, one turn at a time.</p></section>+<section class="transport" aria-label="Demonstration controls"><div class="playback"><button id="play" class="primary">Pause</button><button id="step">Turn once</button><button id="reset">Reset</button><label>Speed <select id="speed"><option value="0.5">½×</option><option value="1" selected>1×</option><option value="2">2×</option></select></label></div><div class="program"><label>DEMONSTRATION <select id="program"><option value="squares">Squares</option><option value="triangular">Triangular numbers</option><option value="carry">Carry · 0099 → 0100</option></select></label><span id="step-count">TURN 0 / 100</span></div></section>+<aside class="inspector"><button id="inspect" aria-expanded="false" aria-controls="inspection">Explore the assembly <span>+</span></button><div id="inspection" hidden><label>Camera <select id="camera"><option value="hero">Hero</option><option value="front">Front</option><option value="side">Side</option><option value="register">Register</option><option value="digit">Digit</option><option value="carry">Carry close-up</option><option value="exploded">Exploded</option><option value="full">Full machine</option></select></label><label>Show <select id="filter"><option value="full">Full assembly</option><option value="transparent">Transparent frame</option><option value="register">One register</option><option value="digit">One digit</option><option value="gears">Gears only</option><option value="carry">Carry mechanism</option></select></label><button id="explode" aria-pressed="false">Explode subassemblies</button><p>Drag to orbit · Scroll to inspect</p></div></aside>+<footer><span>REAL CAD. PRESCRIBED ANIMATION.</span><span id="receipt">Loading assembly…</span></footer>+<dialog id="story"><button class="close" aria-label="Close story">×</button><p class="eyebrow">THE IDEA BEHIND THE MACHINE</p><h2>Arithmetic by addition.</h2><p>A Difference Engine generates polynomial sequences through repeated addition. Here, each turn adds the first difference to the result, then the second difference to the first.</p><p>For squares: <strong>0, 1, 4, 9, 16…</strong> The first differences are <strong>1, 3, 5, 7…</strong> The second difference stays at <strong>2</strong>.</p><p>Charles Babbage conceived the Difference Engine. Ada Lovelace’s 1843 notes explored his later Analytical Engine and its wider possibilities.</p><p>This is a Babbage-inspired design, not a historical replica. The CAD is real; the animation illustrates the arithmetic.</p><a href="https://www.computerhistory.org/babbage/engines/" target="_blank" rel="noreferrer">Computer History Museum ↗</a> <a href="https://blog.sciencemuseum.org.uk/ada-lovelace-visionary-of-the-computer-age/" target="_blank" rel="noreferrer">Science Museum ↗</a></dialog>+<dialog id="receipts"><button class="close" aria-label="Close build details">×</button><p class="eyebrow">AETHERIS · GEOMETRIC RECEIPTS</p><h2>One machine.<br>Reusable parts.</h2><div id="inventory"></div><p>Every mechanical surface comes from Aetheris. Shared meshes retain the CAD occurrence hierarchy. Wheel numbers and motion are presentation layers.</p><p>Prescribed motion is not a claim of physical computation, contact simulation, or manufacturing qualification.</p><a href="difference-engine.step" download>Download complete AP242 assembly ↗</a><details><summary>Artifact fingerprint</summary><code id="fingerprint"></code></details></dialog>+<div id="loading" role="status">Loading the Aetheris assembly…</div><script type="module" src="viewer.mjs"></script></body></html>diff --git a/demos/Aetheris.DifferenceEngine.Showcase/web/presentation.mjs b/demos/Aetheris.DifferenceEngine.Showcase/web/presentation.mjsnew file mode 100644index 00000000..b12998de--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/web/presentation.mjs@@ -0,0 +1,41 @@+// A pure projection of authored demonstration states. No mechanism simulation.+const clamp=x=>Math.max(0,Math.min(1,x));+const ease=x=>{x=clamp(x);return x*x*(3-2*x);};+const keys=['result','firstDifference','secondDifference'];+export function evaluate(program,step,phase){+ step=Math.max(0,Math.min(program.states.length-1,Math.floor(step)));+ phase=clamp(phase);+ const before=program.states[step],after=program.states[Math.min(step+1,program.states.length-1)];+ const digits=[],values=[];+ for(let r=0;r<3;r++){+ const increment=(after[keys[r]]-before[keys[r]]+10000)%10000;+ let incoming=0,value=0;+ for(let d=0;d<4;d++){+ const place=10**d,startDigit=Math.floor(before[keys[r]]/place)%10;+ const delta=Math.floor(increment/place)%10+incoming;+ incoming=Math.floor((startDigit+delta)/10);+ const start=r===0?.10+d*.13:.67+d*.045,duration=r===0?.25:.15;+ const progress=ease((phase-start)/duration),position=startDigit+delta*progress;+ const crossing=delta>0?(10-startDigit)/delta:2;+ // The lever follows a rollover, then returns before the next cycle.+ const carry=incoming&&progress>=crossing?Math.sin(Math.PI*clamp((progress-crossing)/Math.max(.001,1-crossing))):0;+ const pulse=incoming?Math.max(carry,Math.sin(Math.PI*clamp((phase-start-duration*.8)/.16))):0;+ digits.push({register:r,digit:d,angle:-position*Math.PI/5,carry:pulse,rollover:incoming>0});+ value+=((Math.round(position)%10+10)%10)*place;+ }+ values.push(value);+ }+ return {step,phase,values,digits,turn:step+phase,complete:step===program.states.length-1};+}+export function hierarchyOffsets(occurrences,explosions){+ const byId=new Map(occurrences.map(o=>[o.id,o])),offsets=new Map(explosions.map(e=>[e.occurrenceId,e.offset]));+ return new Map(occurrences.map(o=>{+ const sum=[0,0,0],seen=new Set();let current=o;+ while(current){if(seen.has(current.id))throw Error('Cyclic occurrence hierarchy');seen.add(current.id);+ const delta=offsets.get(current.id);if(delta)delta.forEach((v,i)=>sum[i]+=v);+ if(current.parentId&&!byId.has(current.parentId))throw Error('Missing occurrence parent');+ current=byId.get(current.parentId);+ }+ return [o.id,sum];+ }));+}diff --git a/demos/Aetheris.DifferenceEngine.Showcase/web/style.css b/demos/Aetheris.DifferenceEngine.Showcase/web/style.cssnew file mode 100644index 00000000..306f9cfc--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/web/style.css@@ -0,0 +1,3 @@+:root{font-family:Arial,Helvetica,sans-serif;color:#e7dcc5;background:#111918;font-synthesis:none;color-scheme:dark}*{box-sizing:border-box}body{margin:0;overflow:hidden}#machine{position:fixed;inset:0}canvas{display:block;touch-action:none}header,footer{position:fixed;left:32px;right:32px;display:flex;justify-content:space-between;align-items:center;font-size:10px;letter-spacing:.15em}header{top:24px}header nav{display:flex;align-items:center;gap:18px}header button{background:none;border:0;padding:8px 0;font-size:12px}footer{bottom:20px;color:#aaa99a;font-size:9px;pointer-events:none}a{color:inherit;text-decoration:none;border-bottom:1px solid #78694d;padding-bottom:5px}i{font-style:normal;color:#cda35b;margin:0 12px}.intro{position:fixed;left:36px;top:90px;pointer-events:none}.eyebrow{font-size:10px;letter-spacing:.18em;color:#c0a069}h1{font-family:Georgia,serif;font-size:clamp(36px,4vw,62px);line-height:1.06;letter-spacing:-.04em;font-weight:400;margin:18px 0}h1 em{color:#d8b56e;font-weight:400}.intro>p:last-child{font-size:14px;color:#b1b8ae;line-height:1.65}button,select{font:13px Arial;color:#e6ddc9;background:#182521;border:1px solid #53635a;border-radius:3px;padding:10px;cursor:pointer}button:hover,button[aria-pressed=true],button.primary{background:#c5a366;color:#14231c;border-color:#c5a366}button:focus-visible,select:focus-visible,a:focus-visible{outline:2px solid #f5c978;outline-offset:4px}select{padding:8px;max-width:100%}label{font-size:11px;color:#b5bcaf}h2{font:36px/1.1 Georgia;font-weight:400;margin:20px 0}.readout{position:fixed;left:36px;top:370px;width:245px;pointer-events:none}.readout>div{display:flex;align-items:center;justify-content:space-between;border-top:1px solid #a5ab902b;padding:12px 0}.readout span{font-size:9px;letter-spacing:.12em;color:#a6b0a4}.readout output{font:25px Georgia;letter-spacing:.13em;font-variant-numeric:tabular-nums;color:#e3c385}#equation{font:22px Georgia;margin:16px 0 8px}#stage{color:#a9b0a6;font-size:12px;line-height:1.5;min-height:36px}.transport{position:fixed;bottom:72px;left:36px;width:350px}.playback{display:flex;gap:7px;align-items:center}.playback label{display:flex;gap:5px;align-items:center}.program{margin-top:16px;display:flex;justify-content:space-between;align-items:center;gap:10px}.program label{font-size:9px;letter-spacing:.07em}.program select{display:block;margin-top:7px;width:202px}#step-count{font-size:9px;letter-spacing:.1em;color:#a0ad9f}.inspector{position:fixed;right:32px;bottom:72px;width:230px}#inspect{width:100%;text-align:left;background:#15201dea}#inspect span{float:right}#inspection{padding:14px;background:#15201df0;border:1px solid #53635a;border-top:0}#inspection label{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}#inspection select{width:150px}#inspection button{width:100%}#inspection p{font-size:10px;color:#a5ad9e;margin-bottom:0}dialog{background:#172520;color:#e7dcc5;border:1px solid #6c755f;padding:34px;max-width:540px;width:calc(100% - 28px);max-height:85vh;border-radius:4px;box-shadow:0 25px 90px #0008}dialog::backdrop{background:#08120fc9;backdrop-filter:blur(5px)}dialog p{color:#bfc5b7;font-size:14px;line-height:1.75}dialog a{font-size:12px;display:inline-block;margin:10px 12px 10px 0}.close{position:absolute;right:14px;top:12px;font-size:22px;border:0;background:none}#inventory{display:grid;grid-template-columns:1fr 1fr;gap:18px;border-block:1px solid #79806b44;padding:20px 0}#inventory div{font:25px Georgia}#inventory small{display:block;font:10px Arial;letter-spacing:.06em;color:#aeb6a4;margin-top:6px}details{margin-top:20px;font-size:12px}code{display:block;font-size:10px;overflow-wrap:anywhere;line-height:1.7;padding-top:10px}#loading{position:fixed;inset:0;background:#111918;display:grid;place-items:center;font:20px Georgia}#loading:empty{display:none}[hidden]{display:none!important}@media(max-height:850px) and (min-width:701px){.intro{top:75px}h1{font-size:44px}.readout{top:300px}.readout>div{padding:8px 0}.transport{bottom:64px}.readout output{font-size:22px}}@media(max-width:700px){header,footer{left:18px;right:18px;font-size:8px}header{top:16px;align-items:flex-start}header>span{max-width:120px;line-height:1.7}header i{margin:0 3px}header nav{gap:12px}header button{font-size:10px}.intro{left:20px;top:65px}h1{font-size:35px;margin:12px 0}.eyebrow{font-size:8px}.intro>p:last-child{font-size:11px;line-height:1.5}.readout{left:20px;right:20px;top:auto;bottom:197px;width:auto;display:flex;justify-content:space-between;gap:12px}.readout>div{display:flex;flex-direction:column;gap:8px;align-items:flex-start;flex:1}.readout output{font-size:22px}.readout span{font-size:7px;letter-spacing:.02em}#equation,#stage{display:none}.transport{left:20px;right:20px;bottom:75px;width:auto}.playback button{padding:10px;font-size:12px}.playback{justify-content:space-between}.program{margin-top:8px}.program select{padding:6px;margin-top:4px}.inspector{right:20px;bottom:260px;width:205px}#inspect{font-size:11px;padding:9px}#inspection{padding:10px}.inspector:has(#inspection:not([hidden])){z-index:2}footer{bottom:17px;display:block;font-size:8px;line-height:1.8}footer span{display:block}dialog{padding:26px}dialog p{font-size:13px}}+body[data-inspecting=true] .intro{display:none}+@media(min-width:701px){body[data-inspecting=true] .readout{top:110px}}diff --git a/demos/Aetheris.DifferenceEngine.Showcase/web/viewer.mjs b/demos/Aetheris.DifferenceEngine.Showcase/web/viewer.mjsnew file mode 100644index 00000000..29dc33dd--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/web/viewer.mjs@@ -0,0 +1,96 @@+import * as THREE from 'three';+import {OrbitControls} from 'three/addons/OrbitControls.js';+import {RoomEnvironment} from 'three/addons/RoomEnvironment.js';+import {evaluate,hierarchyOffsets} from './presentation.mjs';+const $=id=>document.getElementById(id);+const renderer=new THREE.WebGLRenderer({antialias:true,alpha:false,preserveDrawingBuffer:true});+renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setClearColor(0x111918);renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;$('machine').appendChild(renderer.domElement);+const scene=new THREE.Scene();scene.fog=new THREE.Fog(0x111918,1500,3000);+const pmrem=new THREE.PMREMGenerator(renderer),room=new RoomEnvironment();scene.environment=pmrem.fromScene(room,.04).texture;room.dispose();pmrem.dispose();scene.environmentIntensity=.65;+const camera=new THREE.PerspectiveCamera(33,1,.2,5000);camera.up.set(0,0,1);+const controls=new OrbitControls(camera,renderer.domElement);controls.enableDamping=true;controls.dampingFactor=.075;+scene.add(new THREE.HemisphereLight(0xdbe9e0,0x233932,1.3));+for(const [color,power,x,y,z] of [[0xffe3ad,3.8,-300,-400,800],[0xd9eaff,2.4,400,200,600],[0xffd28a,1.8,100,400,250]]){const light=new THREE.DirectionalLight(color,power);light.position.set(x,y,z);scene.add(light);}+const ground=new THREE.Mesh(new THREE.PlaneGeometry(20000,20000),new THREE.MeshStandardMaterial({color:0x070d09,roughness:1}));ground.position.z=-37;scene.add(ground);+const nodes=new Map(),definitions=new Map(),labels=new Map();let doc,manifest,receipts,offsets;+try{+ [doc,manifest,receipts]=await Promise.all(['machine.mesh.json','motion.json','receipts.json'].map(async f=>{const r=await fetch(f);if(!r.ok)throw Error(`${f}: HTTP ${r.status}`);return r.json();}));+ offsets=hierarchyOffsets(doc.occurrences,manifest.explosions);+ const bindings=new Map(manifest.bindings.map(b=>[b.occurrenceId,b]));+ for(const d of doc.definitions){const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(d.positions,3));g.setAttribute('normal',new THREE.Float32BufferAttribute(d.normals,3));g.setIndex(d.indices);g.computeBoundingSphere();definitions.set(d.id,g);}+ for(const occurrence of doc.occurrences){if(!occurrence.definitionId)continue;+ const path=occurrence.path,name=path.split('.').at(-1);let color=0xbca16a,metalness=.82,roughness=.27;+ if(path.includes('.Frame.')){color=name==='Plaque'?0xc49b52:0x233b32;metalness=.62;roughness=.37;}+ if(/Shaft|Axle|Pivot|Tie|Pin|Link|Collar|Bearing/.test(name)){color=0x9aa6a4;metalness=.9;roughness=.28;}+ if(name==='Drum'){color=0xe8d7ad;metalness=.45;roughness=.37;}+ const material=new THREE.MeshStandardMaterial({color,metalness,roughness});+ const mesh=new THREE.Mesh(definitions.get(occurrence.definitionId),material);mesh.name=occurrence.id;mesh.matrix.fromArray(occurrence.transform);mesh.matrixAutoUpdate=false;mesh.userData={occurrence,rest:mesh.matrix.clone(),binding:bindings.get(occurrence.id)};scene.add(mesh);nodes.set(occurrence.id,mesh);+ }+ // Text is a presentation overlay. All mechanical geometry above is exported CAD.+ const digitMaterials=Array.from({length:10},(_,n)=>{const canvas=document.createElement('canvas');canvas.width=128;canvas.height=128;const c=canvas.getContext('2d');c.fillStyle='#2f291b';c.font='92px Georgia';c.textAlign='center';c.textBaseline='middle';c.fillText(String(n),64,67);const texture=new THREE.CanvasTexture(canvas);texture.colorSpace=THREE.SRGBColorSpace;return new THREE.MeshBasicMaterial({map:texture,transparent:true,alphaTest:.15,depthWrite:false});});+ const labelPlane=new THREE.PlaneGeometry(14,14);+ for(const drum of manifest.drums){const group=new THREE.Group();group.matrixAutoUpdate=false;+ for(let n=0;n<10;n++){const theta=-Math.PI/2+n*Math.PI/5,label=new THREE.Mesh(labelPlane,digitMaterials[n]);label.position.set(drum.radiusMm*Math.cos(theta),drum.radiusMm*Math.sin(theta),drum.labelZMm);label.quaternion.setFromRotationMatrix(new THREE.Matrix4().makeBasis(new THREE.Vector3(-Math.sin(theta),Math.cos(theta),0),new THREE.Vector3(0,0,1),new THREE.Vector3(Math.cos(theta),Math.sin(theta),0)));group.add(label);}+ scene.add(group);labels.set(drum.occurrenceId,group);+ }+ $('receipt').textContent=`${receipts.physicalOccurrences} parts · ${receipts.uniqueDefinitions} shared bodies · Aetheris CAD`;+ const fields=[[receipts.physicalOccurrences,'PHYSICAL PARTS'],[receipts.uniqueDefinitions,'SHARED DEFINITIONS'],[receipts.gears,'SPUR GEARS'],[receipts.ratchets,'RATCHETS'],[receipts.pawls,'PAWLS'],[receipts.sharedModules.reduce((n,m)=>n+m.occurrences,0),'SUBASSEMBLY OCCURRENCES'],[(receipts.stepBytes/1e6).toFixed(2)+' MB','AP242 STEP'],[receipts.aetherisVersion,'AETHERIS VERSION']];+ for(const [value,label] of fields){const el=document.createElement('div');el.textContent=value;const small=document.createElement('small');small.textContent=label;el.append(small);$('inventory').append(el);}+ $('fingerprint').textContent='STEP SHA-256: '+receipts.receipts.find(r=>r.file==='difference-engine.step').sha256;+ $('loading').textContent='';+}catch(error){$('loading').textContent=`Assembly could not load: ${error.message}`;throw error;}+let program=manifest.programs[0],step=0,phase=0,playing=!matchMedia('(prefers-reduced-motion: reduce)').matches,singleTurn=false,speed=1,exploded=false,explosion=0,filter='full',destination=null,currentView='hero';+function playLabel(){$('play').textContent=playing?'Pause':'Play';}+function reset(){step=0;phase=0;singleTurn=false;}+$('play').onclick=()=>{if(!playing&&step>=program.states.length-1)reset();playing=!playing;singleTurn=false;playLabel();};+$('step').onclick=()=>{if(step>=program.states.length-1)reset();playing=true;singleTurn=true;playLabel();};+$('reset').onclick=()=>{reset();playing=false;playLabel();};+$('speed').onchange=e=>speed=Number(e.target.value);+$('program').onchange=e=>{program=manifest.programs.find(p=>p.id===e.target.value);reset();if(program.id==='carry'){view('carry');speed=.5;$('speed').value='.5';$('speed').value='0.5';}playing=true;playLabel();};+$('inspect').onclick=()=>{const open=$('inspection').hidden;$('inspection').hidden=!open;$('inspect').setAttribute('aria-expanded',String(open));};+function visibility(){for(const mesh of nodes.values()){const b=mesh.userData.binding;+ mesh.visible=filter==='register'?b.register===0:filter==='digit'?b.register===0&&b.digit===1:filter==='gears'?['SpurGear','RatchetGear','Pawl'].includes(b.role):filter==='carry'?b.register===0&&(b.digit===0||b.digit===1||b.digit===2):true;+ const transparent=filter==='transparent'&&b.role==='Frame';+ if(mesh.material.transparent!==transparent){mesh.material.transparent=transparent;mesh.material.needsUpdate=true;}+ mesh.material.opacity=transparent ? .13 : 1;mesh.material.depthWrite=!transparent;+ }for(const [id,label] of labels)label.visible=nodes.get(id).visible;}+$('filter').onchange=e=>{filter=e.target.value;visibility();};+function setExplosion(value){exploded=value;$('explode').setAttribute('aria-pressed',String(value));$('explode').textContent=value?'Reassemble':'Explode subassemblies';}+$('explode').onclick=()=>{setExplosion(!exploded);if(exploded)view('exploded');};+$('camera').onchange=e=>view(e.target.value);+function view(name,instant=false){currentView=name;document.body.dataset.inspecting=String(!['hero','full'].includes(name));const z=manifest.design.firstLevel,pitch=manifest.design.digitPitch,top=manifest.design.top;+ filter=name==='register'?'register':name==='digit'?'digit':name==='carry'?'carry':'full';$('filter').value=filter;visibility();setExplosion(name==='exploded');$('camera').value=name;+ const views={hero:[[850,-1350,760],[75,0,top*.48]],full:[[850,-1350,760],[75,0,top*.48]],front:[[115,-1260,220],[115,0,top*.48]],side:[[1150,20,240],[110,0,top*.48]],register:[[210,-500,370],[0,0,top*.55]],digit:[[160,-255,z+pitch+155],[0,0,z+pitch+25]],carry:[[210,-340,z+pitch+165],[20,5,z+pitch+20]],exploded:[[1060,-1640,950],[80,0,top*.51]]};+ const [position,target]=views[name]??views.hero;destination={position:new THREE.Vector3(...position),target:new THREE.Vector3(...target)};+ if(name==='register'||name==='carry')destination.position.sub(destination.target).multiplyScalar(1.35).add(destination.target);+ if(innerWidth<=700){const scale=['digit','carry','register'].includes(name)?1.35:1.8;destination.position.sub(destination.target).multiplyScalar(scale).add(destination.target);destination.target.z+=55;camera.clearViewOffset();}+ else {const scale=innerWidth/innerHeight>1.4?(['hero','full'].includes(name)?.78:name==='exploded'?.88:1):1;destination.position.sub(destination.target).multiplyScalar(scale).add(destination.target);camera.setViewOffset(innerWidth,innerHeight,-innerWidth*.11,0,innerWidth,innerHeight);}+ document.body.dataset.cameraSettled='false';+ if(instant){camera.position.copy(destination.position);controls.target.copy(destination.target);destination=null;document.body.dataset.cameraSettled='true';}+}+controls.addEventListener('start',()=>{destination=null;document.body.dataset.cameraSettled='true';});+for(const button of document.querySelectorAll('[data-dialog]'))button.onclick=()=>{$(button.dataset.dialog).showModal();};+for(const dialog of document.querySelectorAll('dialog')){dialog.querySelector('.close').onclick=()=>dialog.close();dialog.addEventListener('click',e=>{if(e.target===dialog){const r=dialog.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)dialog.close();}});}+function resize(){renderer.setSize(innerWidth,innerHeight);camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();scene.fog.near=innerWidth<=700?3500:1500;scene.fog.far=innerWidth<=700?7000:3000;view(currentView,true);}window.addEventListener('resize',resize);resize();playLabel();+const rotation=new THREE.Matrix4();+function apply(p){for(const mesh of nodes.values()){const b=mesh.userData.binding,d=b.register>=0&&b.digit>=0?p.digits[b.register*4+b.digit]:null;+ let angle=b.kind==='GearRatio'?p.turn*Math.PI*2*b.ratio:b.kind==='IndexedWheel'?d.angle:b.kind==='CarryLever'?d.carry*.23:0;+ mesh.matrix.copy(mesh.userData.rest);+ if(angle!==0){const [x,y,z]=b.pivot;rotation.makeRotationZ(angle);rotation.setPosition(x-Math.cos(angle)*x+Math.sin(angle)*y,y-Math.sin(angle)*x-Math.cos(angle)*y,0);mesh.matrix.premultiply(rotation);}+ if(b.kind==='CarryLift')mesh.matrix.elements[14]+=d.carry*5;+ const offset=offsets.get(b.occurrenceId);for(let i=0;i<3;i++)mesh.matrix.elements[12+i]+=offset[i]*explosion;+ mesh.matrixWorldNeedsUpdate=true;+ if(b.kind==='CarryLever'){mesh.material.emissive.setHex(0xb66e1d);mesh.material.emissiveIntensity=d.carry*.55;}+ }for(const [id,label] of labels){label.matrix.copy(nodes.get(id).matrix);label.matrixWorldNeedsUpdate=true;}}+let previous=performance.now(),lastUi='';+function frame(now){requestAnimationFrame(frame);const dt=Math.min((now-previous)/1000,.08);previous=now;+ if(playing&&!document.hidden&&!document.querySelector('dialog[open]')){phase+=dt*speed/manifest.cycleSeconds;if(phase>=1){phase=0;step++;if(step>=program.states.length-1){playing=false;phase=0;}if(singleTurn){playing=false;singleTurn=false;}playLabel();}}+ const p=evaluate(program,step,phase);explosion+=(Number(exploded)-explosion)*.08;if(Math.abs(explosion-Number(exploded))<.0001)explosion=Number(exploded);apply(p);+ const key=p.values.join(',')+step+Math.floor(phase*10);if(key!==lastUi){['result','first','second'].forEach((id,i)=>$(id).textContent=String(p.values[i]).padStart(4,'0'));$('step-count').textContent=`TURN ${step} / ${program.states.length-1}`;+ const before=program.states[step],after=program.states[Math.min(step+1,program.states.length-1)];$('equation').textContent=p.complete?`Result ${String(before.result).padStart(4,'0')}`:`${before.result} + ${before.firstDifference} → ${after.result}`;+ $('stage').textContent=p.complete?'Program complete. Reset to play again.':p.digits.some(d=>d.carry>.15)?'Carry: a rollover advances the next digit.':phase>.67?'Advance the first difference.':'Add the first difference to the result.';lastUi=key;}+ if(destination){camera.position.lerp(destination.position,.075);controls.target.lerp(destination.target,.075);if(camera.position.distanceTo(destination.position)<.05){camera.position.copy(destination.position);controls.target.copy(destination.target);destination=null;document.body.dataset.cameraSettled='true';}}+ controls.update();renderer.render(scene,camera);+ if(!document.body.dataset.readyMs)document.body.dataset.readyMs=String(Math.round(performance.now()));+}requestAnimationFrame(frame);+diff --git a/demos/Aetheris.DifferenceEngine.Showcase/wrangler.jsonc b/demos/Aetheris.DifferenceEngine.Showcase/wrangler.jsoncnew file mode 100644index 00000000..a10a6dab--- /dev/null+++ b/demos/Aetheris.DifferenceEngine.Showcase/wrangler.jsonc@@ -0,0 +1,5 @@+{+ "name": "aetheris-difference-engine-showcase",+ "compatibility_date": "2026-09-13",+ "assets": { "directory": "../../artifacts/local/demos/difference-engine-showcase/dist" }+}diff --git a/docs/public/README.md b/docs/public/README.mdindex 90f731b9..6bfa447c 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -9,6 +9,7 @@ Start with [Getting Started](getting-started.md), then use these guides:- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)- Interoperability: [Forge Host Protocol v1](forge/interop.md)- Mechanisms: [Editable V8, prescribed motion and assembly mesh export](firmament/editable-mechanisms.md)+- Showcase: [Difference Engine, real hierarchical CAD and prescribed browser animation](demos/difference-engine-showcase.md)- Inspection: [Cadmata](cadmata/overview.md) and [Cadmata PMI](cadmata/pmi.md)- Reference: [CLI](reference/cli.md), [wireframe SVG previews](reference/wireframe.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)diff --git a/docs/public/demos/difference-engine-showcase.md b/docs/public/demos/difference-engine-showcase.mdnew file mode 100644index 00000000..44abc84a--- /dev/null+++ b/docs/public/demos/difference-engine-showcase.md@@ -0,0 +1,23 @@+# Difference Engine showcase++The [showcase README](../../../demos/Aetheris.DifferenceEngine.Showcase/README.md) is the runnable entry point, including regeneration and the admitted 80–100 mm digit pitch configuration.++Aetheris supplies the exact hierarchical machine: reusable digit wheels, digit modules, carry modules, registers, transfer banks, frame and crank. The Gear Standard Library owns tooth geometry. Include, Subassembly, Expose and typed Gear/Revolute/Fixed interfaces establish the real assembly. Shared display meshes preserve the same occurrence IDs as the compiler and AP242 rest assembly.++The Three.js site supplies numbered wheel overlays, lighting, cameras, deterministic prescribed motion, carry highlighting, transparency and hierarchy-aware explosion. Demonstration programs include squares, triangular numbers and the chained carry 0099 → 0100. Public copy is provisional. The design is inspired by Babbage; it is not a historical reconstruction.++## Visualization and analysis++**Browser visualizations communicate. Headless analysis validates.**++Presentation arithmetic is deliberately prescribed. Future contact, clutch, torque, interference and mechanism qualification belongs in dedicated headless engineering tools, not the public browser scene. The earlier indexed-storage qualification and rejected physical transfer candidate remain independent research; this showcase does not change their verdict.++## Production assets++`Run.ps1 -NoServe` creates an ignored `dist/` with relative URLs, local Three.js dependencies and its license, complete STEP, shared meshes and presentation manifest. Serve that directory with `serve.py` for the local production test. The checked-in `wrangler.jsonc` names the static asset directory for a future Cloudflare Workers deployment; deployment requires a separate explicit request. No worker backend, account registration or deployment is performed.++The hero preview is captured from the real browser into `dist/preview.png` during visual review. On later regeneration `Prepare-Viewer.ps1` reuses `review/assembly-hero.png` if present; regenerate that capture when the design changes. Do not substitute synthetic machine geometry or an AI image.++## Authoring findings++Nested reusable assemblies must retain parent-relative local transforms. Reapplying definition-root transforms at each nested level doubles offsets; the canonical nested-occurrence witness covers a translated and rotated hierarchy and checks mesh/STEP realization. Anchor-owner parts should be authored at the module origin; a semantic datum alone does not relocate the solver's anchor owner. Positioned stock templates keep offset geometry explicit while the anchor occurrence remains at zero. Extrusion bounds use explicit `Zlow`/`Zhigh` parameters in this bounded author.diff --git a/docs/release/DIFF-ENGINE-X0.md b/docs/release/DIFF-ENGINE-X0.mdindex 87a84704..f77a2981 100644--- a/docs/release/DIFF-ENGINE-X0.md+++ b/docs/release/DIFF-ENGINE-X0.md@@ -1,3 +1,71 @@+# DIFF-ENGINE-SHOWCASE-X0 — the Difference Engine showcase++## Current verdict++**Success for the prescribed-animation showcase. Human visual design accepted.** The complete three-register, four-digit machine is real hierarchical Aetheris CAD. The local static site supplies numbered wheels, squares, triangular numbers, a chained-carry lesson, play/pause, speed, single turns, reset, smooth cameras, hierarchy-aware explosion/reassembly, transparency, register/digit isolation, gear-only and carry views, short history and an AP242 download. Production assets are prepared locally for Cloudflare and have not been deployed. Public copy remains provisional.++The user identified the gantry/crown overlap during visual review. Three `Interface<Fixed>` mounts now place the bridge bottom at Z=356 mm, 10 mm above each brass crown. Extended supported shafts project 4 mm above the 8 mm bridges. Compiled instance end-face Z values enforce these clearances at every generation, including the 96 mm digit-pitch variant. This is an Aetheris mate/geometry repair. The user subsequently answered: “Accept the updated visual design.”++The original indexed-storage research, rejected permanent-mesh transfer and unqualified physical adder remain intact below and in the original demo. Prescribed browser arithmetic does not qualify contact, clutch operation, torque, friction or manufacturing.++## Assembly inventory++| Measured item | Baseline |+|---|---:|+| Physical occurrences / shared body definitions | 409 / 49 |+| Registers / digit modules | 3 / 12 |+| Spur gears / ratchets / pawls | 30 / 12 / 12 |+| Shaft and axle occurrences | 21 |+| Stationary frame/support members under the manifest role rule | 253 |+| Reusable subassembly definitions / occurrences | 8 / 51 |+| Complete occurrence tree including root / depth | 461 / 5 |+| Included Firmament files / Gear interfaces | 11 / 26 |+| Unique / instanced mechanical triangles | 63,672 / 843,944 |+| Complete AP242 STEP | 1,106,062 bytes |++DigitWheel, DigitModule and CarryVisualModule each have 12 occurrences; Register has 3, TransferModule 8, TransferBank 2, FrameBay 1 and CrankDrive 1. Gear Standard Library definitions own spur, ratchet and pawl geometry. Include/Subassembly/Expose carry hierarchical Gear ports; Revolute journals and Fixed bearing/gantry interfaces retain ordinary compiler authority.++Example identity: `assembly-instance:DifferenceEngine.ResultRegister.Digit2.DriveGear` survives Firmament, compiled assembly, shared mesh occurrence, motion binding and Three.js object name. BufferGeometry is created directly from exported positions, normals and indices. Browser primitives are restricted to labels, floor and lighting helpers.++Visual gear ratios combine compiled `GearResult.Ratio` and `RotationSign`. Authored demonstration states project through a pure `(program, step, phase)` function. No second HFSM or workflow stack was added. Explosion sums offsets through actual exported `parentId` ancestry; reassembly starts from the original CAD rest matrices.++## Artifact-driven repairs++- Nested reusable members previously retained definition-root transforms at every tree level, applying ancestor offsets repeatedly. The compiler now stores parent-relative frames. A rotated, translated canonical witness checks world point `[93,235,351]`, shared definitions, mesh parity and STEP export.+- SurfaceMeshIR's rectangle fast path assumed every trim loop followed the support normal before applying face sense. Extrusion bottoms can already run oppositely. Comparing measured loop signed area with face sense fixes reversed underside triangles in both polygon export and display lowering. Origin and translated plinth witnesses verify outward triangles and exact oriented volume `484 × 188 × 16 mm³`.+- Forty-seven definitions use the existing OBJ SurfaceMeshIR planar/cylindrical route, including disks, rings and bores. Two involute gear definitions retain the admitted spline tessellator. Failed admitted meshing does not silently fall back.+- Browser QA repaired a flattened vendor import, mobile fog obscuring the machine, clipped inspection cameras and material recompilation on transparency changes. These changes do not relocate CAD parts.+- Fresh-agent feedback corrected CLI help to name canonical `.firmament` alongside the `.firmasm` assembly profile.++Raw assembly metrics expose topology-vertex extents; these are not complete radial bounds for periodic surfaces. Gantry checks use their exact planar end Z values. Display extents are checked from all mesh vertices. No general interference or mass-property qualification is claimed.++## Validation and human review++- Release build and full serial non-SlowCorpus .NET lane pass; final counts are recorded in the local validation summary. All 17 focused SurfaceMeshIR/OBJ cases pass, including the new extrusion orientation witnesses.+- Headless presentation checks cover 201 transitions, deterministic evaluation, all 26 signed gear relationships, units-before-tens carry pulses, occurrence coverage, hierarchy offsets, positive mesh extents/oriented volume and unit normals across all 49 definitions.+- Repeat generation matches all source, STEP, mesh, design, motion and receipt hashes.+- A fresh explicitly versioned CLI installed outside the checkout inspects, exports and reimports copied source. STEP and mesh bytes match; reimport preserves 49 definitions and 460 non-root occurrences.+- A fresh agent independently chose DigitPitch=96 mm using public docs and the README. Regeneration, hierarchy IDs, STEP reimport and headless verification pass without source changes, tooth reconstruction, hierarchy flattening or browser geometry. It reran after the underside repair and verified all 16 hashes.+- Actual production browser tested at 1440×900, the app's ordinary viewport and 375×812. One turn produces `0001 / 0003 / 0002`; carry reaches `0100`. Playback, speed, reset, orbit, camera/isolation modes, explosion/reassembly, story, receipts and the actual STEP download event were exercised. Reduced-motion preference starts paused; otherwise playback starts automatically.+- Seven review views, active carry, transparency and mobile screenshots are retained under `review/`. Human visual design accepted. The final underside correction preserves that CAD design.+- Warm localhost first-frame observation: 343 ms. This is not a cold-network or device benchmark. Bundle approximately 8.2 MB uncompressed including STEP and preview; exact sizes and hashes are in `bundle-manifest.json`. STEP and social preview are not fetched during ordinary machine startup.+- Canonical qualification remains non-clean: the existing annular-pair LegacyExplicit policy violation is the first error; three existing include-only AssemblyInterfaces catalogs independently report `assembly-parse-missing-root`. The new nested occurrence fixture passes. These are not reported as a clean lane.+- Repository layout guard and diff whitespace checks pass. No remote CI or deployment was run.++## Reproduction and deliverables++`./demos/Aetheris.DifferenceEngine.Showcase/Run.ps1` generates CAD, runs presentation checks, prepares the static bundle and starts a foreground localhost preview. `-NoServe` generates only. `Verify-Packaged.ps1` performs a fresh outside-checkout package/parity test. Read the [demo README](../../demos/Aetheris.DifferenceEngine.Showcase/README.md) and [public guide](../public/demos/difference-engine-showcase.md) for prerequisites and the admitted 80–100 mm configuration.++Ignored output under `artifacts/local/demos/difference-engine-showcase/` contains STEP, meshes, motion, receipts, hashes, private compiler inspection, logs, screenshots and `dist/`. The site includes local Three.js and its license, relative URLs, social metadata and a real browser hero preview. `wrangler.jsonc` prepares a future static deployment only.++**Browser visualizations communicate. Headless analysis validates.** Future physical mechanism research remains separate.++---++# Historical physical-storage checkpoint — preserved++The earlier report below concerns the original physically computing mechanism, not the completed prescribed-animation showcase above. Its research findings are retained unchanged.+# DIFF-ENGINE-X0 — storage gate and assembly repairs## Executive verdictdiff --git a/fixtures/Canonical/AssemblyInterfaces/nested-occurrence-frames.firmament b/fixtures/Canonical/AssemblyInterfaces/nested-occurrence-frames.firmamentnew file mode 100644index 00000000..6c509058--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/nested-occurrence-frames.firmament@@ -0,0 +1,33 @@+Units: mm+Template < H: Length > Struct Pin {+ Circle2 Circle { Center: [0mm,0mm] Radius: 1mm }+ Profile Section { Loop Outer { Circle |> TraceLoop } }+ Extrude Body { Profile: Section From: 0mm To: H }+}+Subassembly Inner {+ <Assembly Inner>+ <Part Origin = Pin<H: 1mm>></Part>+ <Part Tip = Pin<H: 4mm>>+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 5,7,11,1];+ </Part>+ </Assembly>+ Anchor: Inner.Origin;+}+Subassembly Middle {+ <Assembly Middle>+ <Part Origin = Pin<H: 1mm>></Part>+ <Assembly Offset = Inner>+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 30,0,40,1];+ </Assembly>+ </Assembly>+ Anchor: Middle.Origin;+}+Assembly NestedFrames {+ <Assembly NestedFrames>+ <Part Origin = Pin<H: 1mm>></Part>+ <Assembly Rotated = Middle>+ Placement ImportedOccurrence = [0,1,0,0, -1,0,0,0, 0,0,1,0, 100,200,300,1];+ </Assembly>+ </Assembly>+ Anchor: NestedFrames.Origin;+}diff --git a/fixtures/DifferenceEngine/parts/Showcase.firmament b/fixtures/DifferenceEngine/parts/Showcase.firmamentnew file mode 100644index 00000000..d9f5412c--- /dev/null+++ b/fixtures/DifferenceEngine/parts/Showcase.firmament@@ -0,0 +1,38 @@+// Ordinary reusable mechanical stock. No viewer-generated product geometry.+Template < W: Length, D: Length, H: Length > Struct RectangularStock {+ Rect2 Outline { Center: [0mm,0mm] Size: [W,D] }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { Profile: Section From: 0mm To: H }+}+Template < W: Length, D: Length, H: Length, BoreD: Length > Struct BearingBridge {+ Rect2 Outline { Center: [0mm,0mm] Size: [W,D] }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+ Compose Body {+ Base Stock { Profile: Section From: 0mm To: H Role: Stock }+ Hole<Shaft> Bore { On: +Z Center: Point2(0mm,0mm) Diameter: BoreD End: ThroughAll }+ }+}+Template < X: Length, Y: Length, Zlow: Length, Zhigh: Length, W: Length, D: Length > Struct PositionedStock {+ Rect2 Outline { Center: [X,Y] Size: [W,D] }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { Profile: Section From: Zlow To: Zhigh }+}+Template < X: Length, Y: Length, R: Length, BoreR: Length, Zlow: Length, Zhigh: Length > Struct PositionedRing {+ Circle2 Outside { Center: [X,Y] Radius: R }+ Circle2 Inside { Center: [X,Y] Radius: BoreR }+ Profile Section { Loop Outer { Outside |> TraceLoop } Loop Inner { Inside |> TraceLoop } }+ Extrude Body { Profile: Section From: Zlow To: Zhigh }+}+Template < W: Length > Struct DoubleBearingBridge {+ Rect2 Outline { Center: [64mm,0mm] Size: [W,18mm] }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+ Compose Body {+ Base Stock { Profile: Section From: -18mm To: -12mm Role: Stock }+ Hole<Shaft> Left { On: +Z Center: Point2(44mm,0mm) Diameter: 6.4mm End: ThroughAll }+ Hole<Shaft> Right { On: +Z Center: Point2(84mm,0mm) Diameter: 6.4mm End: ThroughAll }+ }+}+SpurGear RegisterDrive { Module: 2mm Teeth: 24 PressureAngle: 20deg FaceWidth: 7mm BoreDiameter: 8.8mm Backlash: 0.15mm Phase: 0deg }+SpurGear TransferIdler { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 7mm BoreDiameter: 6.6mm Backlash: 0.15mm Phase: 9deg }+RatchetGear DecimalRatchet { Teeth: 20 OutsideDiameter: 52mm FaceWidth: 5mm BoreDiameter: 8.8mm DriveFaceAngle: 0deg Phase: 0deg }+Pawl CarryPawl { Width: 8mm Length: 22mm Thickness: 4mm PivotDiameter: 4.4mm NoseLength: 4mm EngagementAngle: 15deg }