Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support ruled-surface tessellation and reliable assembly meshing

Yuechen Li5822d6ac2329
diff --git a/Aetheris.Kernel.Core.Tests/Mechanisms/IndexedRotaryStorageTests.cs b/Aetheris.Kernel.Core.Tests/Mechanisms/IndexedRotaryStorageTests.cs
new file mode 100644
index 00000000..87f97678
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Mechanisms/IndexedRotaryStorageTests.cs
@@ -0,0 +1,75 @@
+using Aetheris.Kernel.Core.Mechanisms;
+
+namespace Aetheris.Kernel.Core.Tests.Mechanisms;
+
+public sealed class IndexedRotaryStorageTests
+{
+ [Theory]
+ [InlineData(2)]
+ [InlineData(10)]
+ [InlineData(12)]
+ public void IndependentOccurrencesReadOnlyReachedIndicesAndRetainAllCrossings(int positions)
+ {
+ var definition = new RotaryIndexDefinition(positions, 4.5, 5);
+ for (var preload = 0; preload < positions; preload++)
+ {
+ var a = new IndexedRotaryStorage("source", definition, preload);
+ var b = new IndexedRotaryStorage("destination", definition);
+ var original = a.Capture();
+ Assert.Throws<InvalidOperationException>(() => b.Advance(.1));
+ b.SetPinLift(5);
+ b.Advance(definition.IndexAngleRadians / 2);
+ Assert.Null(b.ReadIndex);
+ Assert.Throws<InvalidOperationException>(() => b.SetPinLift(0));
+ var events = b.Advance(2 * double.Pi - definition.IndexAngleRadians / 2);
+ Assert.Equal(positions, events.Count);
+ Assert.Single(events, e => e.Rollover);
+ Assert.Equal(0, b.ReadIndex);
+ b.SetPinLift(0);
+ Assert.Equal(original, a.Capture());
+ }
+ }
+
+ [Fact]
+ public void LargeIrregularAndResumedAdvancesHaveIdenticalEventOrder()
+ {
+ var definition = new RotaryIndexDefinition(10, 4.5, 5);
+ var direct = new IndexedRotaryStorage("wheel", definition, 9);
+ var stepped = new IndexedRotaryStorage("wheel", definition, 9);
+ direct.SetPinLift(5); stepped.SetPinLift(5);
+ var expected = direct.Advance(8 * double.Pi);
+ var events = new List<RotaryIndexCrossing>();
+ double accumulated = 0;
+ for (var i = 0; i < 100; i++)
+ {
+ var step = (i % 7 + 1) * .019;
+ events.AddRange(stepped.Advance(step));
+ accumulated += step;
+ if (i == 50)
+ {
+ var json = System.Text.Json.JsonSerializer.Serialize(stepped.Capture());
+ stepped = new IndexedRotaryStorage("wheel", definition);
+ stepped.Restore(System.Text.Json.JsonSerializer.Deserialize<RotaryStorageSnapshot>(json)!);
+ }
+ }
+ events.AddRange(stepped.Advance(8 * double.Pi - accumulated));
+ Assert.Equal(expected, events);
+ Assert.Equal(direct.UnwrappedRadians, stepped.UnwrappedRadians, 9);
+ Assert.Equal(direct.ReadIndex, stepped.ReadIndex);
+ }
+
+ [Fact]
+ public void InvalidSnapshotsAndDriveAreAtomicFailures()
+ {
+ var joint = new IndexedRotaryStorage("a", new(10, 4.5, 5));
+ var before = joint.Capture();
+ Assert.Throws<ArgumentException>(() => joint.Restore(before with { OccurrenceId = "b" }));
+ Assert.Throws<ArgumentException>(() => joint.Restore(before with { UnwrappedRadians = .1 }));
+ Assert.Throws<ArgumentException>(() => joint.Restore(before with { Definition = new(12, 4.5, 5) }));
+ Assert.Throws<ArgumentException>(() => joint.Restore(before with { Version = 2 }));
+ Assert.Throws<ArgumentOutOfRangeException>(() => joint.Advance(double.NaN));
+ Assert.Throws<ArgumentOutOfRangeException>(() => joint.Advance(-.1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => joint.SetPinLift(6));
+ Assert.Equal(before, joint.Capture());
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index 22a51a0b..87101f7e 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -263,6 +263,12 @@ public static class BrepDisplayTessellator
SurfaceGeometryKind.Sphere => TessellateSphereFace(body, faceId, surface.Sphere!.Value, options),
SurfaceGeometryKind.Torus => TessellateTorusFace(body, faceId, surface.Torus!.Value, options, executionBudget),
SurfaceGeometryKind.BSplineSurfaceWithKnots => TessellateBSplineSurfaceFace(body, faceId, surface.BSplineSurfaceWithKnots!, options, executionBudget),
+ SurfaceGeometryKind.LinearExtrusion when surface.LinearExtrusion!.Value.Directrix.BSpline3 is { } curve
+ => TessellateBSplineSurfaceFace(body, faceId, new BSplineSurfaceWithKnots(
+ curve.Degree, 1,
+ curve.ControlPoints.Select(p => (IReadOnlyList<Point3D>)new[] { p, p + surface.LinearExtrusion.Value.ExtrusionVector }).ToArray(),
+ "RULED_SURF", curve.ClosedCurve, false, curve.SelfIntersect,
+ curve.KnotMultiplicities, [2, 2], curve.KnotValues, [0d, 1d], curve.KnotSpec), options, executionBudget),
_ => KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} has unsupported surface kind '{surface.Kind}'.")]),
};
}
@@ -1572,6 +1578,18 @@ public static class BrepDisplayTessellator
var tangentU = surface.Evaluate(uPlus, v) - surface.Evaluate(uMinus, v);
var tangentV = surface.Evaluate(u, vPlus) - surface.Evaluate(u, vMinus);
+ // Finite-difference lengths depend on parameter scale. Rescale before
+ // the cross product so a regular, small ruled face is not mistaken for
+ // a singularity (notably near an involute's zero-speed base endpoint).
+ static Vector3D Rescale(Vector3D t)
+ {
+ var scale = System.Math.Max(System.Math.Abs(t.X), System.Math.Max(System.Math.Abs(t.Y), System.Math.Abs(t.Z)));
+ // Component division is intentional: Vector3D's geometric division
+ // guard treats small physical lengths as zero; this scale is relative.
+ return scale > 0 && double.IsFinite(scale) ? new(t.X / scale, t.Y / scale, t.Z / scale) : t;
+ }
+ tangentU = Rescale(tangentU);
+ tangentV = Rescale(tangentV);
var normal = tangentU.Cross(tangentV);
if (!normal.TryNormalize(out var normalized))
{
diff --git a/Aetheris.Kernel.Core/Mechanisms/IndexedRotaryStorage.cs b/Aetheris.Kernel.Core/Mechanisms/IndexedRotaryStorage.cs
new file mode 100644
index 00000000..5969f420
--- /dev/null
+++ b/Aetheris.Kernel.Core/Mechanisms/IndexedRotaryStorage.cs
@@ -0,0 +1,93 @@
+namespace Aetheris.Kernel.Core.Mechanisms;
+
+/// <summary>An ideal rotary joint with an axially withdrawn indexing pin.
+/// This is a mechanical primitive, not a sequencer, adder or state-machine host.</summary>
+public sealed record RotaryIndexDefinition(int Positions, double RequiredPinLiftMm, double MaximumPinLiftMm)
+{
+ public double IndexAngleRadians => 2 * double.Pi / Positions;
+ public void Validate()
+ {
+ if (Positions is < 2 or > 100 || !double.IsFinite(RequiredPinLiftMm) || RequiredPinLiftMm <= 0
+ || !double.IsFinite(MaximumPinLiftMm) || MaximumPinLiftMm < RequiredPinLiftMm)
+ throw new ArgumentException("mechanism-index-definition-invalid");
+ }
+}
+
+public sealed record RotaryStorageSnapshot(string OccurrenceId, double UnwrappedRadians, double PinLiftMm, RotaryIndexDefinition Definition, int Version = 1);
+public sealed record RotaryIndexCrossing(string OccurrenceId, long Crossing, int Index, bool Rollover);
+
+public sealed class IndexedRotaryStorage
+{
+ private const double AngularTolerance = 1e-10;
+ public RotaryIndexDefinition Definition { get; }
+ public string OccurrenceId { get; }
+ public double UnwrappedRadians { get; private set; }
+ public double PinLiftMm { get; private set; }
+ public double PositionRadians => UnwrappedRadians % (2 * double.Pi);
+ public bool Locked => PinLiftMm < Definition.RequiredPinLiftMm;
+ public int? ReadIndex
+ {
+ get
+ {
+ var coordinate = UnwrappedRadians / Definition.IndexAngleRadians;
+ var nearest = double.Round(coordinate);
+ return double.Abs(coordinate - nearest) <= AngularTolerance
+ ? (int)((long)nearest % Definition.Positions) : null;
+ }
+ }
+
+ public IndexedRotaryStorage(string occurrenceId, RotaryIndexDefinition definition, int preloadIndex = 0)
+ {
+ definition.Validate();
+ if (string.IsNullOrWhiteSpace(occurrenceId)) throw new ArgumentException("mechanism-occurrence-missing");
+ if (preloadIndex < 0 || preloadIndex >= definition.Positions) throw new ArgumentOutOfRangeException(nameof(preloadIndex));
+ Definition = definition;
+ OccurrenceId = occurrenceId;
+ // Explicit setup only. Drive never accepts a target digit or register value.
+ UnwrappedRadians = preloadIndex * definition.IndexAngleRadians;
+ }
+
+ public void SetPinLift(double liftMm)
+ {
+ if (!double.IsFinite(liftMm) || liftMm < 0 || liftMm > Definition.MaximumPinLiftMm) throw new ArgumentOutOfRangeException(nameof(liftMm));
+ if (liftMm < Definition.RequiredPinLiftMm && ReadIndex is null)
+ throw new InvalidOperationException("mechanism-index-pin-misaligned");
+ PinLiftMm = liftMm;
+ }
+
+ public IReadOnlyList<RotaryIndexCrossing> Advance(double radians)
+ {
+ if (!double.IsFinite(radians) || radians < 0 || radians > 200 * double.Pi
+ || UnwrappedRadians + radians > 2_000_000 * double.Pi)
+ throw new ArgumentOutOfRangeException(nameof(radians), "mechanism-index-drive-outside-envelope");
+ if (radians == 0) return [];
+ if (Locked) throw new InvalidOperationException("mechanism-lock-drive-conflict");
+ var start = UnwrappedRadians / Definition.IndexAngleRadians;
+ var finish = (UnwrappedRadians + radians) / Definition.IndexAngleRadians;
+ if (double.Abs(finish - double.Round(finish)) <= AngularTolerance) finish = double.Round(finish);
+ var events = new List<RotaryIndexCrossing>();
+ for (var crossing = (long)double.Floor(start + AngularTolerance) + 1; crossing <= (long)double.Floor(finish); crossing++)
+ {
+ var index = (int)(crossing % Definition.Positions);
+ events.Add(new(OccurrenceId, crossing, index, index == 0));
+ }
+ UnwrappedRadians = finish * Definition.IndexAngleRadians;
+ return events;
+ }
+
+ public RotaryStorageSnapshot Capture() => new(OccurrenceId, UnwrappedRadians, PinLiftMm, Definition);
+
+ public void Restore(RotaryStorageSnapshot snapshot)
+ {
+ if (snapshot.Version != 1 || snapshot.Definition != Definition || snapshot.OccurrenceId != OccurrenceId || !double.IsFinite(snapshot.UnwrappedRadians)
+ || snapshot.UnwrappedRadians < 0 || snapshot.UnwrappedRadians > 2_000_000 * double.Pi
+ || !double.IsFinite(snapshot.PinLiftMm) || snapshot.PinLiftMm < 0 || snapshot.PinLiftMm > Definition.MaximumPinLiftMm)
+ throw new ArgumentException("mechanism-index-snapshot-invalid");
+ var coordinate = snapshot.UnwrappedRadians / Definition.IndexAngleRadians;
+ if (snapshot.PinLiftMm < Definition.RequiredPinLiftMm
+ && double.Abs(coordinate - double.Round(coordinate)) > AngularTolerance)
+ throw new ArgumentException("mechanism-index-snapshot-lock-conflict");
+ UnwrappedRadians = snapshot.UnwrappedRadians;
+ PinLiftMm = snapshot.PinLiftMm;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.cs
new file mode 100644
index 00000000..ff43a788
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.cs
@@ -0,0 +1,123 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+[CollectionDefinition("StorageGateMeshing", DisableParallelization = true)]
+public sealed class StorageGateMeshingCollection;
+
+// Keep wall-clock-bounded production meshing outside competing xUnit collections.
+// The exporter retains its ordinary five-second budget.
+[Collection("StorageGateMeshing")]
+public sealed class DifferenceEngineStorageGateTests
+{
+ [Fact]
+ public void MixedCatalogBuildsTheRequestedShaftAndReusesItsDefinition()
+ {
+ var result = Compile("gear-with-ordinary-part");
+ Assert.Equal(2, result.Geometry!.DefinitionBodies.Count);
+ var shaft = result.Geometry.DefinitionBodies.Single(x => x.Key.StartsWith("Shaft<", StringComparison.Ordinal)).Value;
+ Assert.Equal(3, shaft.Topology.Faces.Count());
+ var cylinder = Assert.Single(shaft.Geometry.Surfaces.Select(p => p.Value), x => x.Kind == SurfaceGeometryKind.Cylinder).Cylinder!.Value;
+ Assert.Equal(4, cylinder.Radius, 9);
+ Assert.DoesNotContain(shaft.Geometry.Surfaces.Select(p => p.Value), x => x.Kind == SurfaceGeometryKind.LinearExtrusion);
+ var z = shaft.Topology.Vertices.Select(v => { Assert.True(shaft.TryGetVertexPoint(v.Id, out var p)); return p.Z; }).ToArray();
+ Assert.Equal(0, z.Min(), 9); Assert.Equal(40, z.Max(), 9);
+ var output = AssemblyIrAp242Exporter.Export(result);
+ Assert.True(output.IsSuccess);
+ var imported = Step242AssemblyImporter.Import(output.Value);
+ Assert.True(imported.IsSuccess);
+ Assert.Equal(6, imported.Value.Occurrences.Count);
+ Assert.Equal(4, imported.Value.Definitions.Count);
+ Assert.Equal(output.Value, AssemblyIrAp242Exporter.Export(Compile("gear-with-ordinary-part")).Value);
+ }
+
+ [Fact]
+ public void FullCircleCompositionProducesTenRealCylindricalIndexHoles()
+ {
+ var result = Compile("index-plate-with-gear");
+ var plate = result.Geometry!.DefinitionBodies.Single(x => x.Key.StartsWith("DecimalIndexPlate<", StringComparison.Ordinal)).Value;
+ var holes = plate.Geometry.Surfaces.Select(p => p.Value).Where(s => s.Cylinder is { Radius: > 2.19 and < 2.21 })
+ .Select(s => s.Cylinder!.Value).ToArray();
+ var centers = holes.Select(c => (X: double.Round(c.Origin.X, 7), Y: double.Round(c.Origin.Y, 7))).Distinct().ToArray();
+ Assert.Equal(10, centers.Length);
+ foreach (var center in centers) Assert.Equal(26, double.Sqrt(center.X * center.X + center.Y * center.Y), 6);
+ var mesh = AssemblyDisplayMeshExporter.Export(result);
+ var definition = mesh.Definitions.Single(d => d.Identity.StartsWith("DecimalIndexPlate<", StringComparison.Ordinal));
+ Assert.Equal(DisplayMeshPipeline.SurfaceMeshIr.ToString(), definition.MeshPipeline);
+ Assert.True(SurfaceMeshIrTessellator.TryBuild(plate,
+ SurfaceMeshPolicy.FromDisplayOptions(new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64)), out var document));
+ Assert.True(SurfaceMeshIrValidator.TryValidate(document, out _));
+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var sharedMesh, out var topology));
+ Assert.True(topology.IsWatertight);
+ Assert.True(topology.IsConnected);
+ Assert.True(topology.IsOutwardOriented);
+ Assert.Equal(0, topology.CrackCount);
+ Assert.Equal(0, topology.NonManifoldEdgeCount);
+ Assert.Equal(0, topology.DuplicateTriangleCount);
+ Assert.Equal(0, topology.ZeroAreaTriangleCount);
+ Assert.Equal(sharedMesh.TriangleIndices.Count, definition.Indices.Length);
+ // The assembly adapter must not apply face sense twice to the already
+ // oriented IR patches. Both caps and inward-facing bores stay consistent.
+ for (var i = 0; i < definition.Indices.Length; i += 3)
+ {
+ var a = definition.Indices[i]; var b = definition.Indices[i + 1]; var c = definition.Indices[i + 2];
+ var normal = new Vector3D(definition.Normals[a * 3], definition.Normals[a * 3 + 1], definition.Normals[a * 3 + 2]);
+ Assert.True((At(definition, b) - At(definition, a)).Cross(At(definition, c) - At(definition, a)).Dot(normal) > 0);
+ }
+ var expected = double.Pi * (32 * 32 - 6.15 * 6.15 - 10 * 2.2 * 2.2) * 6;
+ Assert.InRange(Volume(definition) / expected, .98, 1.02);
+ Assert.Equal(AssemblyDisplayMeshExporter.Serialize(mesh), AssemblyDisplayMeshExporter.Serialize(AssemblyDisplayMeshExporter.Export(Compile("index-plate-with-gear"))));
+ }
+
+ [Fact]
+ public void GearMeshIncludesEveryFlankWithOutwardNormalsAndClosedVolume()
+ {
+ var result = Compile("gear-with-ordinary-part");
+ var gear = result.Geometry!.DefinitionBodies["Drive"];
+ Assert.Contains(gear.Geometry.Surfaces.Select(p => p.Value), s => s.Kind == SurfaceGeometryKind.LinearExtrusion);
+ var tessellation = BrepDisplayTessellator.Tessellate(gear);
+ Assert.True(tessellation.IsSuccess, string.Join("\n", tessellation.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(gear.Topology.Faces.Count(), tessellation.Value.FacePatches.Count);
+ foreach (var patch in tessellation.Value.FacePatches)
+ {
+ Assert.NotEmpty(patch.TriangleIndices);
+ Assert.All(patch.Normals, n => Assert.InRange(n.LengthSquared, .9999, 1.0001));
+ Assert.True(gear.TryGetFaceSurfaceGeometry(patch.FaceId, out var surface));
+ if (surface!.Kind == SurfaceGeometryKind.LinearExtrusion)
+ Assert.All(patch.Normals, n => Assert.InRange(double.Abs(n.Z), 0, 1e-7));
+ }
+ var mesh = AssemblyDisplayMeshExporter.Export(result).Definitions.Single(d => d.Identity == "Drive");
+ var volume = Volume(mesh);
+ Assert.InRange(volume, double.Pi * (17.5 * 17.5 - 4.2 * 4.2) * 8, double.Pi * (22 * 22 - 4.2 * 4.2) * 8);
+ // For a prism, the oriented surface integral must agree with cap area * height.
+ // This detects a "successful" mesh with inward/missing/degenerate side normals.
+ double capArea = 0;
+ for (var i = 0; i < mesh.Indices.Length; i += 3)
+ {
+ var a = At(mesh, mesh.Indices[i]); var b = At(mesh, mesh.Indices[i + 1]); var c = At(mesh, mesh.Indices[i + 2]);
+ if (double.Abs(a.Z - 8) < 1e-9 && double.Abs(b.Z - 8) < 1e-9 && double.Abs(c.Z - 8) < 1e-9)
+ capArea += (b - a).Cross(c - a).Z / 2;
+ }
+ Assert.InRange(volume / (capArea * 8), .995, 1.005);
+ }
+
+ private static AssemblyM1CompilationResult Compile(string name)
+ {
+ var result = new AssemblyM1Pipeline().CompileFile(FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Canonical/AssemblyInterfaces/{name}.firmament"));
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Code + ": " + d.Message)));
+ return result;
+ }
+ private static Vector3D At(AssemblyDisplayMeshDefinition m, int i) => new(m.Positions[i * 3], m.Positions[i * 3 + 1], m.Positions[i * 3 + 2]);
+ private static double Volume(AssemblyDisplayMeshDefinition m)
+ {
+ double volume = 0;
+ for (var i = 0; i < m.Indices.Length; i += 3)
+ volume += At(m, m.Indices[i]).Dot(At(m, m.Indices[i + 1]).Cross(At(m, m.Indices[i + 2]))) / 6;
+ return volume;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index 77b7d143..2279afa5 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -1,9 +1,11 @@
using System.Text.Json;
using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
namespace Aetheris.Kernel.Firmament.Assembly;
-public sealed record AssemblyDisplayMeshDefinition(string Id, string Identity, double[] Positions, double[] Normals, int[] Indices);
+public sealed record AssemblyDisplayMeshDefinition(string Id, string Identity, double[] Positions, double[] Normals, int[] Indices,
+ string MeshPipeline = "LegacyTessellator");
public sealed record AssemblyDisplayMeshOccurrence(string Id, string Path, string? ParentId, string? DefinitionId, double[] Transform);
public sealed record AssemblyDisplayMeshDocument(string Schema, string Name, string Units,
IReadOnlyList<AssemblyDisplayMeshDefinition> Definitions, IReadOnlyList<AssemblyDisplayMeshOccurrence> Occurrences);
@@ -20,13 +22,24 @@ public static class AssemblyDisplayMeshExporter
var definitions = new List<AssemblyDisplayMeshDefinition>();
foreach (var (identity, body) in geometry.DefinitionBodies.OrderBy(p => p.Key, StringComparer.Ordinal))
{
- var tessellation = BrepDisplayTessellator.TessellateBounded(body, options ?? new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64));
+ var effectiveOptions = options ?? new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64);
+ // Reuse the OBJ export's shared-boundary mesher for planar/cylindrical
+ // parts. A failure on this admitted family must remain visible; do not
+ // silently replace a failed cap or bore with the legacy mesh.
+ var useSurfaceMeshIr = body.Topology.Faces.All(face =>
+ body.TryGetFaceSurfaceGeometry(face.Id, out var surface)
+ && surface?.Kind is SurfaceGeometryKind.Plane or SurfaceGeometryKind.Cylinder);
+ var tessellation = useSurfaceMeshIr
+ ? BrepDisplayTessellator.TessellateSurfaceMeshIr(body, effectiveOptions)
+ : BrepDisplayTessellator.TessellateBounded(body, effectiveOptions);
if (!tessellation.IsSuccess || tessellation.Value.FacePatches.Count != body.Topology.Faces.Count())
throw new InvalidOperationException($"assembly-mesh-definition-failed:{identity}:" + string.Join(";", tessellation.Diagnostics.Select(d => d.Message)));
var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
foreach (var rawFace in tessellation.Value.FacePatches.OrderBy(p => p.FaceId.Value))
{
- var face = DisplayMeshOrientation.Orient(body, rawFace);
+ // SurfaceMeshIR already applies the B-rep face sense to both
+ // normals and winding; the legacy patch contains support normals.
+ var face = useSurfaceMeshIr ? rawFace : DisplayMeshOrientation.Orient(body, rawFace);
if (face.Positions.Count == 0 || face.Normals.Count != face.Positions.Count || face.TriangleIndices.Count == 0
|| face.TriangleIndices.Count % 3 != 0 || face.TriangleIndices.Any(i => i < 0 || i >= face.Positions.Count))
throw new InvalidOperationException($"assembly-mesh-face-invalid:{identity}:{face.FaceId}:positions={face.Positions.Count};normals={face.Normals.Count};indices={face.TriangleIndices.Count};" + string.Join(";", tessellation.Diagnostics.Select(d => d.Message)));
@@ -37,7 +50,8 @@ public static class AssemblyDisplayMeshExporter
}
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()));
+ definitions.Add(new(ids[identity], identity, positions.ToArray(), normals.ToArray(), indices.ToArray(),
+ tessellation.Value.MeshPipeline.ToString()));
}
var occurrences = compilation.Ir.Instances.OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
{
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
index dfdbdc31..d30375a4 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
@@ -81,6 +81,18 @@ internal static class AssemblyDefinitionMaterializer
return new(definitionIdentity, "gear:" + definitionIdentity, materialization.Body, [],
new(gearStableId, definitionIdentity, "gear:" + definitionIdentity, gearHash, Metrics(materialization.Body), gearProvenance));
}
+ // An ordinary template specialization must not see sibling Gear roots:
+ // the standalone build route would otherwise select the Gear profile and
+ // successfully return that gear for every shaft, support and wheel.
+ // Use producer-owned declaration spans; retain offsets for diagnostics.
+ if (gearDocument.Gears.Count > 0)
+ {
+ var ordinaryDeclarations = definitionSource.ToCharArray();
+ foreach (var sibling in gearDocument.Gears)
+ for (var i = sibling.SourceSpan.Start; i < sibling.SourceSpan.Start + sibling.SourceSpan.Length; i++)
+ if (ordinaryDeclarations[i] is not ('\r' or '\n')) ordinaryDeclarations[i] = ' ';
+ definitionSource = new string(ordinaryDeclarations);
+ }
}
var externalStep = System.Text.RegularExpressions.Regex.Match(definitionIdentity, "^ExternalStep<\\\"(?<path>[^\\\"]+)\\\">$", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
if (externalStep.Success)
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
index 54e9288e..e3dabbd4 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
@@ -225,6 +225,14 @@ public static class ProfileArrangementBuilder
private static ProfileArrangementResult Build(string frame, IReadOnlyList<ArrangementSourceCurve2D> sources, Func<(double X, double Y), bool> material, string context, bool rejectAmbiguousTangencies, bool allowMultipleRegions)
{
+ // Full circles are exact profile boundaries. Adapt them into finite arcs
+ // before the existing line/arc intersection and graph machinery runs.
+ sources = sources.SelectMany(source => source.Geometry is LineArcFullCircle2D circle
+ ? Enumerable.Range(0, 4).Select(i => source with
+ {
+ StableId = source.StableId + $".quarter{i}",
+ Geometry = new LineArcCircularArc2D(circle.Center, circle.Radius, i * Math.PI / 2d, Math.PI / 2d)
+ }) : new[] { source }).ToArray();
var diagnostics = new List<string>();
var intersectionClock = Stopwatch.StartNew();
var parameters = sources.ToDictionary(x => x.StableId, _ => new List<double> { 0d, 1d }, StringComparer.Ordinal);
@@ -551,6 +559,12 @@ public static class ProfileArrangementBuilder
private static double Length(LineArcProfileCurve2D curve) => curve switch { LineArcLineSegment2D line => Distance(line.Start, line.End), LineArcCircularArc2D arc => Math.Abs(arc.Radius * arc.SweepAngleRadians), _ => 0d };
private static ArrangementPointLocation PointInLoop(IReadOnlyList<LineArcProfileCurve2D> curves, (double X, double Y) point)
{
+ if (curves.Count == 1 && curves[0] is LineArcFullCircle2D circle)
+ {
+ var radialDistance = Distance(circle.Center, point) - circle.Radius;
+ return Math.Abs(radialDistance) <= Tol ? ArrangementPointLocation.OnBoundary
+ : radialDistance < 0 ? ArrangementPointLocation.Inside : ArrangementPointLocation.Outside;
+ }
if (curves.Any(curve => OnCurve(curve, point, out _))) return ArrangementPointLocation.OnBoundary;
// A horizontal ray to +X; half-open endpoint ownership avoids ray-through-vertex double counting.
var crossings = 0;
diff --git a/Aetheris.slnx b/Aetheris.slnx
index 02b497ea..08052c00 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/Aetheris.DifferenceEngine.csproj" />
<Project Path="demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj" />
<Project Path="demos/Aetheris.EditableV8/Aetheris.EditableV8.csproj" />
</Folder>
diff --git a/demos/Aetheris.DifferenceEngine/Aetheris.DifferenceEngine.csproj b/demos/Aetheris.DifferenceEngine/Aetheris.DifferenceEngine.csproj
new file mode 100644
index 00000000..2c6073c7
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/Aetheris.DifferenceEngine.csproj
@@ -0,0 +1,10 @@
+<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/BuildInspection.ps1 b/demos/Aetheris.DifferenceEngine/BuildInspection.ps1
new file mode 100644
index 00000000..a1609a1d
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/BuildInspection.ps1
@@ -0,0 +1,11 @@
+[CmdletBinding()]
+param([string]$Output='')
+$ErrorActionPreference='Stop'
+$repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
+if(!$Output){$Output=Join-Path $repo 'artifacts/local/demos/difference-engine'}
+$three=Join-Path $repo 'aetheris.client/node_modules/three/build/three.cjs'
+if(!(Test-Path -LiteralPath $three)){throw 'Restore aetheris.client dependencies to supply its existing Three.js renderer.'}
+$template=Get-Content -LiteralPath "$PSScriptRoot/inspection.html" -Raw
+$html=$template.Replace('/*THREE_RUNTIME*/',(Get-Content -LiteralPath $three -Raw)).Replace('/*ASSEMBLY_DOCUMENT*/',(Get-Content -LiteralPath "$Output/storage-gate.mesh.json" -Raw))
+Set-Content -LiteralPath "$Output/storage-inspection.html" -Value $html -Encoding utf8
+Write-Host "Open $Output/storage-inspection.html in a browser. No server is required."
diff --git a/demos/Aetheris.DifferenceEngine/Program.cs b/demos/Aetheris.DifferenceEngine/Program.cs
new file mode 100644
index 00000000..31ee9147
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/Program.cs
@@ -0,0 +1,53 @@
+using System.Text.Json;
+using System.Security.Cryptography;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.DifferenceEngine;
+
+public static class Program
+{
+ public static int Main(string[] args)
+ {
+ try
+ {
+ var destination = Path.GetFullPath(args.Length>0 ? args[0] : "artifacts/local/demos/difference-engine");
+ var output = Path.Combine(destination,".generation");
+ var fixtures = Path.GetFullPath(args.Length>1 ? args[1] : "fixtures/DifferenceEngine");
+ var design = new StorageDesign();
+ var source = Path.Combine(output,"source");
+ design.WriteSources(source,fixtures);
+ var compiled = new AssemblyM1Pipeline().CompileFile(Path.Combine(source,"StorageGate.firmament"));
+ 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,"storage-gate.step"),step.Value);
+ File.WriteAllText(Path.Combine(output,"storage-gate.mesh.json"),AssemblyDisplayMeshExporter.Serialize(AssemblyDisplayMeshExporter.Export(compiled)));
+ File.WriteAllText(Path.Combine(output,"storage-design.json"),JsonSerializer.Serialize(design,new JsonSerializerOptions{WriteIndented=true}));
+ var qualification=StorageQualification.Run(design,compiled,Path.GetFullPath(Path.Combine(fixtures,"../..")));
+ File.WriteAllText(Path.Combine(output,"storage-qualification.json"),JsonSerializer.Serialize(qualification,new JsonSerializerOptions{WriteIndented=true}));
+ var metadata=new {
+ schema="aetheris/difference-engine-storage-gate/1",
+ assembly=compiled.Ir!.Name,
+ uniqueParts=compiled.Geometry!.DefinitionBodies.Count,
+ physicalOccurrences=compiled.Geometry.InstanceBodies.Count,
+ assemblyDepth=compiled.Ir.Instances.Max(i=>i.Path.Segments.Count),
+ modules=compiled.Ir.AssemblyDefinitions!.Select(d=>d.DefinitionIdentity).Order(StringComparer.Ordinal),
+ dependencies=compiled.Ir.SourceDependencies!.Select(d=>new {path=Path.GetRelativePath(output,d.Path).Replace('\\','/'),d.Sha256}),
+ occurrenceTree=compiled.Ir.Instances.Select(i=>new {i.StableId,path=i.Path.ToString(),i.ParentStableId,i.DefinitionIdentity})
+ };
+ File.WriteAllText(Path.Combine(output,"storage-manifest.json"),JsonSerializer.Serialize(metadata,new JsonSerializerOptions{WriteIndented=true}));
+ var files=Directory.GetFiles(output,"*",SearchOption.AllDirectories).Where(f=>Path.GetFileName(f)!="hashes.json").Order(StringComparer.Ordinal).ToArray();
+ var hashes=files.ToDictionary(f=>Path.GetRelativePath(output,f).Replace('\\','/'),f=>Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(f))));
+ File.WriteAllText(Path.Combine(output,"hashes.json"),JsonSerializer.Serialize(hashes,new JsonSerializerOptions{WriteIndented=true}));
+ foreach(var file in files.Append(Path.Combine(output,"hashes.json"))) {
+ var target=Path.Combine(destination,Path.GetRelativePath(output,file));
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ File.Copy(file,target,true);
+ }
+ Console.WriteLine($"Storage gate: {compiled.Geometry!.DefinitionBodies.Count} unique parts; {compiled.Geometry.InstanceBodies.Count} physical occurrences.");
+ Console.WriteLine("Gate B NOT ADMITTED: a permanent output gear mesh back-drives storage during reader return. No adder or complete machine is claimed.");
+ return 0;
+ }
+ catch (Exception e) { Console.Error.WriteLine(e); return 1; }
+ }
+}
diff --git a/demos/Aetheris.DifferenceEngine/README.md b/demos/Aetheris.DifferenceEngine/README.md
new file mode 100644
index 00000000..893964af
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/README.md
@@ -0,0 +1,5 @@
+# DIFF-ENGINE-X0
+
+The current delivery is the storage gate, not a complete Difference Engine.
+
+See the [public guide](../../docs/public/firmament/difference-engine.md) for reproduction and the [release record](../../docs/release/DIFF-ENGINE-X0.md) for qualification and the next blocked gate.
diff --git a/demos/Aetheris.DifferenceEngine/Run.ps1 b/demos/Aetheris.DifferenceEngine/Run.ps1
new file mode 100644
index 00000000..9327442e
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/Run.ps1
@@ -0,0 +1,55 @@
+[CmdletBinding()]
+param([string]$Output='', [switch]$Packaged)
+$ErrorActionPreference='Stop'
+$repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
+if(!$Output){$Output=Join-Path $repo 'artifacts/local/demos/difference-engine'}
+$Output=[IO.Path]::GetFullPath($Output)
+function Checked([scriptblock]$Command){ & $Command; if($LASTEXITCODE){throw "Command failed ($LASTEXITCODE): $Command"} }
+Checked { dotnet run --project "$PSScriptRoot/Aetheris.DifferenceEngine.csproj" -c Release -- $Output "$repo/fixtures/DifferenceEngine" }
+Checked { dotnet test "$repo/Aetheris.Kernel.Core.Tests" -c Release --filter 'FullyQualifiedName~IndexedRotaryStorageTests' --nologo -v q }
+Checked { dotnet test "$repo/Aetheris.Kernel.Firmament.Tests" -c Release --filter 'FullyQualifiedName~DifferenceEngineStorageGateTests' --nologo -v q }
+Checked { dotnet build "$repo/Aetheris.CLI" -c Release --nologo -v q }
+$cli="$repo/Aetheris.CLI/bin/Release/net10.0/aetheris.dll"
+Checked { dotnet $cli asm inspect "$Output/source/StorageGate.firmament" --json > "$Output/cli-inspection.json" }
+Checked { dotnet $cli asm export-ap242 "$Output/source/StorageGate.firmament" --out "$Output/cli-storage.step" --json > "$Output/cli-export.json" }
+Checked { dotnet $cli asm import-step "$Output/cli-storage.step" --out "$Output/reimport" --json > "$Output/cli-reimport.json" }
+if((Get-FileHash "$Output/storage-gate.step").Hash -ne (Get-FileHash "$Output/cli-storage.step").Hash){throw 'CLI/demo STEP parity failed'}
+Checked { dotnet $cli mesh "$Output/source/StorageGate.firmament" --format assembly-json --output "$Output/cli-storage.mesh.json" --json > "$Output/cli-mesh.json" }
+if((Get-FileHash "$Output/storage-gate.mesh.json").Hash -ne (Get-FileHash "$Output/cli-storage.mesh.json").Hash){throw 'CLI/demo mesh parity failed'}
+# Use this import's manifest, never a wildcard that can select stale component files.
+# Component STEP is inspected here; it is never fed back into assembly construction.
+$meshDocument=Get-Content "$Output/storage-gate.mesh.json" -Raw|ConvertFrom-Json
+$plate=@($meshDocument.definitions|Where-Object {$_.identity.StartsWith('DecimalIndexPlate<')})
+if($plate.Count -ne 1){throw 'Expected one indexing plate definition'}
+$componentPackage=Get-Content "$Output/reimport/component-package.json" -Raw|ConvertFrom-Json
+$plateComponent=@($componentPackage.components|Where-Object {$_.DefinitionStableId -eq $plate[0].id})
+if($plateComponent.Count -ne 1){throw 'Indexing plate missing from current STEP import manifest'}
+$plateStep=Join-Path "$Output/reimport" $plateComponent[0].RelativePath
+if((Get-FileHash $plateStep).Hash -ne $plateComponent[0].Sha256){throw 'Indexing plate component hash mismatch'}
+Checked { dotnet $cli mesh $plateStep --format obj --output "$Output/index-plate.obj" --debug-ir "$Output/index-plate.surface-mesh.json" --json > "$Output/index-plate.obj-report.json" }
+$objReport=Get-Content "$Output/index-plate.obj-report.json" -Raw|ConvertFrom-Json
+if(!$objReport.watertight -or !$objReport.connected -or !$objReport.outwardOriented -or $objReport.crackCount -or $objReport.nonManifoldEdgeCount -or $objReport.duplicateTriangleCount -or $objReport.zeroAreaTriangleCount){throw 'OBJ plate topology qualification failed'}
+if($Packaged){
+ # A fresh tool installation and source copy, explicitly requested for qualification.
+ # It is deliberately retained for inspection; this script deletes no temp/user files.
+ $outside=Join-Path ([IO.Path]::GetTempPath()) ('aetheris-diff-engine-x0-'+[guid]::NewGuid().ToString('N'))
+ [IO.Directory]::CreateDirectory($outside) | Out-Null
+ Copy-Item -LiteralPath "$Output/source" -Destination "$outside/source" -Recurse
+ Copy-Item -LiteralPath "$repo/fixtures/Canonical/AssemblyInterfaces/gear-with-ordinary-part.firmament" -Destination "$outside/mixed.firmament"
+ $version='2.0.0-diffengine-x0.'+[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 export-ap242 source/StorageGate.firmament --out "$Output/packaged-storage.step" --json > "$Output/packaged-export.json" }
+ Checked { & "$outside/tool/aetheris.exe" asm export-ap242 mixed.firmament --out "$Output/packaged-mixed.step" --json > "$Output/packaged-mixed-export.json" }
+ Checked { & "$outside/tool/aetheris.exe" asm import-step "$Output/packaged-storage.step" --out "$Output/packaged-reimport" --json > "$Output/packaged-reimport.json" }
+ Checked { & "$outside/tool/aetheris.exe" mesh source/StorageGate.firmament --format assembly-json --output "$Output/packaged-storage.mesh.json" --json > "$Output/packaged-mesh.json" }
+ Checked { & "$outside/tool/aetheris.exe" mesh $plateStep --format obj --output "$outside/index-plate.obj" --json > "$Output/packaged-obj-report.json" }
+ } finally { Pop-Location }
+ if((Get-FileHash "$Output/storage-gate.step").Hash -ne (Get-FileHash "$Output/packaged-storage.step").Hash){throw 'Packaged STEP parity failed'}
+ if((Get-FileHash "$Output/storage-gate.mesh.json").Hash -ne (Get-FileHash "$Output/packaged-storage.mesh.json").Hash){throw 'Packaged mesh parity failed'}
+ if((Get-FileHash "$Output/index-plate.obj").Hash -ne (Get-FileHash "$outside/index-plate.obj").Hash){throw 'Packaged OBJ parity failed'}
+ @{version=$version;outsideDirectory=$outside;storageStepSha256=(Get-FileHash "$Output/packaged-storage.step").Hash}|ConvertTo-Json|Set-Content "$Output/packaged-run.json"
+}
+Write-Host 'Storage gate artifacts and focused qualification complete. The adder, carry chain and full Difference Engine are not yet qualified.'
diff --git a/demos/Aetheris.DifferenceEngine/StorageDesign.cs b/demos/Aetheris.DifferenceEngine/StorageDesign.cs
new file mode 100644
index 00000000..7eccbc4b
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/StorageDesign.cs
@@ -0,0 +1,99 @@
+using System.Globalization;
+using System.Text;
+
+namespace Aetheris.DifferenceEngine;
+
+/// <summary>Millimetres; vertical stationary shafts and gravity-biased index pins.
+/// Gear teeth and decimal positions are deliberately independent.</summary>
+public sealed record StorageDesign
+{
+ public int Positions => 10;
+ public int GearTeeth => 20;
+ public double GearModule => 2;
+ public double WheelRadius => 32;
+ public double IndexRadius => 26;
+ public double IndexHoleDiameter => 4.4;
+ public double PinDiameter => 4;
+ public double ShaftDiameter => 8;
+ public double SleeveInsideDiameter => 8.4;
+ public double SleeveOutsideDiameter => 12;
+ public double BondedBoreDiameter => 12.3;
+ public double IndexBottom => 14;
+ public double IndexTop => 20;
+ public double PinTipReady => 16;
+ public double PinLift => 5;
+ public double GearBottom => 2;
+ public double GearWidth => 8;
+ public double SupportTop => 32;
+ public double StagePitch => 100;
+ private static string N(double x) => x.ToString("G17", CultureInfo.InvariantCulture);
+ private static string L(double x) => N(x) + "mm";
+ private static string Frame(double x=0, double y=0, double z=0)
+ => $"DatumFrame Frame = [{N(x)},{N(y)},{N(z)}] x [1,0,0] y [0,1,0] z [0,0,1];";
+
+ public void WriteSources(string output, string fixtureDirectory)
+ {
+ Directory.CreateDirectory(Path.Combine(output, "parts"));
+ Directory.CreateDirectory(Path.Combine(output, "modules"));
+ File.Copy(Path.Combine(fixtureDirectory, "parts", "Storage.firmament"), Path.Combine(output, "parts", "Storage.firmament"), true);
+ File.WriteAllText(Path.Combine(output, "parts", "Gear.firmament"), $$"""
+ SpurGear TransmissionGear {
+ Module: {{L(GearModule)}} Teeth: {{GearTeeth}} PressureAngle: 20deg
+ FaceWidth: {{L(GearWidth)}} BoreDiameter: {{L(BondedBoreDiameter)}} Backlash: 0.15mm Phase: 0deg
+ }
+ """);
+ var members = new List<(string Name, string Type, double X, double Y, double Z, bool Rotates)>
+ {
+ ("Shaft", $"RoundBar<R: {L(ShaftDiameter/2)}, Zlow: -12mm, Zhigh: 44mm>",0,0,0,false),
+ ("Sleeve", $"Annulus<Rout: {L(SleeveOutsideDiameter/2)}, Rin: {L(SleeveInsideDiameter/2)}, Zlow: 0mm, Zhigh: 22mm>",0,0,0,true),
+ ("Gear", "TransmissionGear",0,0,GearBottom,true),
+ ("Display", $"Annulus<Rout: {L(WheelRadius)}, Rin: {L(BondedBoreDiameter/2)}, Zlow: 10mm, Zhigh: 14mm>",0,0,0,true),
+ ("IndexPlate", $"DecimalIndexPlate<Rout: {L(WheelRadius)}, Rin: {L(BondedBoreDiameter/2)}, PitchR: {L(IndexRadius)}, HoleD: {L(IndexHoleDiameter)}, Zlow: {L(IndexBottom)}, Zhigh: {L(IndexTop)}>",0,0,0,true),
+ ("Bond", $"Annulus<Rout: {L(BondedBoreDiameter/2)}, Rin: {L(SleeveOutsideDiameter/2)}, Zlow: 2mm, Zhigh: 20mm>",0,0,0,true),
+ ("LowerRetainer", $"Annulus<Rout: 7mm, Rin: {L(ShaftDiameter/2)}, Zlow: -3mm, Zhigh: -0.5mm>",0,0,0,false),
+ ("UpperRetainer", $"Annulus<Rout: 7mm, Rin: {L(ShaftDiameter/2)}, Zlow: 22.5mm, Zhigh: 25mm>",0,0,0,false),
+ ("LowerSupport", "StorageSupport<W: 88mm, D: 80mm, H: 6mm, ShaftD: 8mm, PinX: 26mm, PinD: 4.4mm, MountX: 34mm, MountY: -30mm>",0,0,-10,false),
+ ("UpperSupport", "StorageSupport<W: 88mm, D: 80mm, H: 6mm, ShaftD: 8mm, PinX: 26mm, PinD: 4.4mm, MountX: 34mm, MountY: -30mm>",0,0,SupportTop,false),
+ ("IndexPin", $"RoundBar<R: {L(PinDiameter/2)}, Zlow: {L(PinTipReady)}, Zhigh: {L(SupportTop+6)}>",IndexRadius,0,0,false),
+ ("PinHead", $"RoundBar<R: 5mm, Zlow: {L(SupportTop+6)}, Zhigh: {L(SupportTop+10)}>",IndexRadius,0,0,false)
+ };
+ foreach (var (side,x) in new[] { ("Left",-34d),("Right",34d) })
+ {
+ members.Add((side+"Spacer","Annulus<Rout: 6mm, Rin: 2.25mm, Zlow: -4mm, Zhigh: 32mm>",x,-30,0,false));
+ members.Add((side+"TieBolt","RoundBar<R: 2mm, Zlow: -10mm, Zhigh: 42mm>",x,-30,0,false));
+ members.Add((side+"BoltHead","RoundBar<R: 4mm, Zlow: -14mm, Zhigh: -10mm>",x,-30,0,false));
+ members.Add((side+"NutEnvelope","Annulus<Rout: 4mm, Rin: 2mm, Zlow: 38mm, Zhigh: 42mm>",x,-30,0,false));
+ }
+ var source = new StringBuilder("Include \"../parts/Storage.firmament\";\nInclude \"../parts/Gear.firmament\";\nInterface<Fixed> StorageRestSeat { }\nSubassembly DecimalDigit {\n<Assembly DecimalDigit>\n");
+ foreach (var p in members)
+ {
+ source.AppendLine($"<Part {p.Name} = {p.Type}>");
+ source.AppendLine($"Semantic Mount {{ {Frame()} }}");
+ if (p.Name == "Shaft")
+ foreach (var c in members.Where(c=>c.Name != "Shaft")) source.AppendLine($"Semantic Seat{c.Name} {{ {Frame(c.X,c.Y,c.Z)} }}");
+ source.AppendLine("</Part>");
+ }
+ source.AppendLine("</Assembly>\nAnchor: DecimalDigit.Shaft.Mount;");
+ foreach (var p in members.Where(p=>p.Name!="Shaft"))
+ source.AppendLine($"Mate Place{p.Name}: StorageRestSeat {{ A: DecimalDigit.{p.Name}.Mount; B: DecimalDigit.Shaft.Seat{p.Name}; }}");
+ source.AppendLine("Expose {\nSemantic Mount = Shaft.Mount;\nGear Drive = Gear;");
+ // The module owns which leaves move together; consumers resolve only exposed ports.
+ foreach (var p in members.Where(p=>p.Rotates || p.Name is "IndexPin" or "PinHead"))
+ source.AppendLine($"Semantic {p.Name}Position = {p.Name}.Mount;");
+ source.AppendLine("}\n}");
+ File.WriteAllText(Path.Combine(output,"modules","DecimalDigit.firmament"),source.ToString());
+ File.WriteAllText(Path.Combine(output,"StorageGate.firmament"),$$"""
+ Units: mm
+ Include "modules/DecimalDigit.firmament";
+ Assembly StorageGate {
+ <Assembly StorageGate>
+ <Assembly Source = DecimalDigit></Assembly>
+ <Assembly Destination = DecimalDigit>
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, {{N(StagePitch)}},0,0,1];
+ </Assembly>
+ </Assembly>
+ Anchor: StorageGate.Source.Mount;
+ }
+ """);
+ }
+}
diff --git a/demos/Aetheris.DifferenceEngine/StorageQualification.cs b/demos/Aetheris.DifferenceEngine/StorageQualification.cs
new file mode 100644
index 00000000..35348591
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/StorageQualification.cs
@@ -0,0 +1,79 @@
+using Aetheris.Kernel.Core.Mechanisms;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Semantics;
+
+namespace Aetheris.DifferenceEngine;
+
+public static class StorageQualification
+{
+ public static object Run(StorageDesign design, AssemblyM1CompilationResult assembly, string repository)
+ {
+ var plate = assembly.Geometry!.DefinitionBodies.Single(p => p.Key.StartsWith("DecimalIndexPlate<", StringComparison.Ordinal)).Value;
+ var holeCenters = plate.Geometry.Surfaces.Where(p => p.Value.Cylinder is { } c && double.Abs(2*c.Radius-design.IndexHoleDiameter)<1e-8)
+ .Select(p => p.Value.Cylinder!.Value.Origin)
+ .DistinctBy(p => (double.Round(p.X,7),double.Round(p.Y,7))).ToArray();
+ Check(holeCenters.Length == design.Positions, "index-hole-count");
+ var definition = new RotaryIndexDefinition(holeCenters.Length, design.IndexTop-design.PinTipReady+.5, design.PinLift);
+ var bindings = new List<object>();
+ var joints = new List<IndexedRotaryStorage>();
+ foreach (var module in assembly.Ir!.Instances.Where(i => i.DefinitionIdentity == "DecimalDigit"))
+ {
+ Check(module.SemanticRoot.ExposedMembers["Drive"].TryBinding<TypedSemanticAuthorityBinding<GearAir>>(out var gear), "gear-authority-binding");
+ var leafPath = module.Path + "." + string.Join('.',gear!.RelativeOccurrencePath!);
+ var leaf = assembly.Ir.Instances.Single(i=>i.Path.ToString()==leafPath);
+ Check(gear.Authority.Teeth == design.GearTeeth, "gear-authority-teeth");
+ bindings.Add(new { module = module.StableId, publicPort = module.Path+".Drive", storageOccurrence = leaf.StableId,
+ definition, rest = leaf.ResolvedTransform!.Matrix });
+ joints.Add(new(leaf.StableId,definition));
+ }
+ var source = joints[0]; var destination = joints[1]; var sourceBefore = source.Capture();
+ var cases = new List<object>();
+ for (var i=0;i<definition.Positions;i++)
+ {
+ var angle=i*definition.IndexAngleRadians;
+ var alignment=holeCenters.Min(p=>double.Sqrt(double.Pow(p.X*double.Cos(angle)-p.Y*double.Sin(angle)-design.IndexRadius,2)
+ +double.Pow(p.X*double.Sin(angle)+p.Y*double.Cos(angle),2)));
+ var radialClearance=(design.IndexHoleDiameter-design.PinDiameter)/2-alignment;
+ Check(radialClearance>.19,"pin-hole-running-clearance");
+ destination.SetPinLift(design.PinLift);
+ var events=destination.Advance(definition.IndexAngleRadians);
+ Check(events.Count==1,"exact-index-crossing");
+ destination.SetPinLift(0);
+ Check(destination.ReadIndex==(i+1)%definition.Positions,"index-readout");
+ Check(sourceBefore==source.Capture(),"independent-storage");
+ cases.Add(new { setupIndex=i, alignmentErrorMm=alignment, radialClearanceMm=radialClearance, snapshot=destination.Capture(), events });
+ }
+ var pinClearance=design.PinTipReady+design.PinLift-design.IndexTop;
+ Check(pinClearance>=.5,"withdrawn-pin-clearance");
+
+ // A concrete rejected transfer candidate: using only an input clutch does
+ // not release a permanent output mesh on reader return. Consume the real
+ // compiled Gear law; do not invent a favorable browser disconnection.
+ var pair=new AssemblyM0Pipeline().CompileFile(Path.Combine(repository,"fixtures/Canonical/AssemblyInterfaces/gear-with-ordinary-part.firmament"));
+ Check(pair.IsSuccess,"reset-witness-compilation");
+ var mesh=pair.Ir!.Mates.Single(m=>m.GearResult is not null).GearResult!;
+ var ratio=mesh.RotationSign*mesh.Ratio!.Value;
+ var forwardInput=-definition.IndexAngleRadians;
+ var destinationAdvance=PrescribedMotion.AngularRatio(forwardInput,ratio);
+ var resetBackdrive=PrescribedMotion.AngularRatio(-forwardInput,ratio);
+ Check(destinationAdvance>0 && resetBackdrive<0 && double.Abs(destinationAdvance+resetBackdrive)<1e-12,"reset-counterexample");
+ return new {
+ verdict="Meaningful progression", gate="A: storage geometry and ideal indexing primitive",
+ arithmeticVerified=false, completeDifferenceEngine=false, physicalPrototypeTested=false,
+ status="Gate B not admitted: output release/freewheel and source-triggered clutch trip remain unqualified",
+ bindings, selectedGeometry=new { indexPositions=holeCenters.Length, pinClearanceMm=pinClearance,
+ sleeveDiameterClearanceMm=design.SleeveInsideDiameter-design.ShaftDiameter,
+ source= "Actual cylinder locations in the compiled indexing plate; analytic rotation at each of ten indices", toleranceMm=1e-7 }, cases,
+ rejectedTransferCandidate=new { meshA=mesh.A,meshB=mesh.B,ratio,forwardInputRadians=forwardInput,
+ destinationAdvanceRadians=destinationAdvance,resetBackdriveRadians=resetBackdrive,
+ diagnostic="permanent-output-mesh-backdrives-storage-on-reader-return",
+ required="CAD-bound output disengagement or one-way coupling, separately from the drive-input clutch; source-stop trip, zero case and return must qualify before an adder can run" }
+ };
+ }
+
+ private static void Check(bool passed,string code)
+ {
+ if(!passed) throw new InvalidOperationException("storage-gate-"+code);
+ }
+}
diff --git a/demos/Aetheris.DifferenceEngine/inspection.html b/demos/Aetheris.DifferenceEngine/inspection.html
new file mode 100644
index 00000000..03dbc76c
--- /dev/null
+++ b/demos/Aetheris.DifferenceEngine/inspection.html
@@ -0,0 +1,48 @@
+<!doctype html>
+<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Difference Engine · storage geometry inspection</title>
+<style>
+body{margin:0;background:#eff2f5;color:#213641;font:16px system-ui}header,footer{padding:24px 36px}h1{margin:4px 0 10px;font-size:30px}p{margin:8px 0}button{padding:8px 16px;border:1px solid #9badb8;border-radius:5px;background:white;cursor:pointer;margin-right:6px}main{display:flex}section{width:50%;text-align:center}canvas{display:block;width:100%;height:60vh}footer{font-size:14px;color:#87502e}#status{font-size:13px}
+</style>
+<header><h1>DIFF-ENGINE-X0 · storage geometry</h1><p>Two independent indexed disks, authored and meshed in Aetheris.</p>
+<button id="iso">Isometric</button><button id="top">Top</button><button id="bottom">Underside</button><button id="wire">Toggle mesh edges</button><p id="status">Loading exported geometry…</p></header>
+<main><section><h3>Two storage occurrences</h3><canvas id="assembly"></canvas></section><section><h3>Ten-hole indexing plate · isolated</h3><canvas id="plate"></canvas></section></main>
+<footer>Static geometry inspection. Transfer, carry, cycle control and a complete Difference Engine remain unqualified.</footer>
+<script>const THREE=(()=>{const exports={};/*THREE_RUNTIME*/;return exports;})();</script>
+<script>
+const documentMesh=/*ASSEMBLY_DOCUMENT*/;
+const definitions=new Map(documentMesh.definitions.map(d=>[d.id,d]));
+const panels=[];
+for(const id of ['assembly','plate']){
+ const canvas=document.getElementById(id),renderer=new THREE.WebGLRenderer({canvas,antialias:true});
+ renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setClearColor(0xeff2f5);
+ const scene=new THREE.Scene(),group=new THREE.Group();scene.add(group);
+ scene.add(new THREE.HemisphereLight(0xffffff,0x61717b,2));
+ const light=new THREE.DirectionalLight(0xffffff,3);light.position.set(30,-60,120);scene.add(light);
+ const materials=[],geometries=new Map();
+ for(const occurrence of documentMesh.occurrences){
+ if(!occurrence.definitionId)continue;
+ const name=occurrence.path.split('.').pop();
+ if(id==='plate'&&(!occurrence.path.includes('.Source.')||name!=='IndexPlate'))continue;
+ const d=definitions.get(occurrence.definitionId);
+ let geometry=geometries.get(d.id);
+ if(!geometry){geometry=new THREE.BufferGeometry();geometry.setAttribute('position',new THREE.Float32BufferAttribute(d.positions,3));geometry.setAttribute('normal',new THREE.Float32BufferAttribute(d.normals,3));geometry.setIndex(d.indices);geometries.set(d.id,geometry);}
+ const color=name==='Gear'?0xc29b3b:['IndexPlate','Display'].includes(name)?0x327f9f:['IndexPin','PinHead'].includes(name)?0xe27448:0xa6b1b9;
+ const glass=name.includes('Support');
+ const material=new THREE.MeshStandardMaterial({color,metalness:.15,roughness:.65,transparent:glass,opacity:glass?.2:1,depthWrite:!glass});materials.push(material);
+ const mesh=new THREE.Mesh(geometry,material);mesh.matrix.fromArray(occurrence.transform);mesh.matrixAutoUpdate=false;group.add(mesh);
+ }
+ const box=new THREE.Box3().setFromObject(group),center=box.getCenter(new THREE.Vector3()),size=box.getSize(new THREE.Vector3()),radius=size.length()*.62;
+ const camera=new THREE.PerspectiveCamera(35,1,.1,2000);camera.up.set(0,0,1);
+ const panel={renderer,scene,camera,center,radius,materials,canvas};panels.push(panel);
+}
+function render(){for(const p of panels){const w=p.canvas.clientWidth,h=p.canvas.clientHeight;p.renderer.setSize(w,h,false);p.camera.aspect=w/h;p.camera.updateProjectionMatrix();p.renderer.render(p.scene,p.camera);}}
+function view(x,y,z){for(const p of panels){p.camera.up.set(0,z===1||z===-1?1:0,z===1||z===-1?0:1);p.camera.position.copy(p.center).addScaledVector(new THREE.Vector3(x,y,z).normalize(),p.radius*2.2);p.camera.lookAt(p.center);}render();}
+document.getElementById('iso').onclick=()=>view(1,-1,.85);
+document.getElementById('top').onclick=()=>view(0,0,1);
+document.getElementById('bottom').onclick=()=>view(0,0,-1);
+document.getElementById('wire').onclick=()=>{for(const p of panels)for(const m of p.materials)m.wireframe=!m.wireframe;render();};
+window.onresize=render;view(1,-1,.85);
+const count=documentMesh.definitions.filter(d=>d.meshPipeline==='SurfaceMeshIr').length;
+document.getElementById('status').textContent=`${documentMesh.definitions.length} shared definitions · ${documentMesh.occurrences.filter(o=>o.definitionId).length} physical occurrences · ${count} definitions use the OBJ SurfaceMeshIR path`;
+</script></html>
diff --git a/docs/public/firmament/difference-engine.md b/docs/public/firmament/difference-engine.md
new file mode 100644
index 00000000..20879a86
--- /dev/null
+++ b/docs/public/firmament/difference-engine.md
@@ -0,0 +1,60 @@
+# Difference Engine storage gate
+
+DIFF-ENGINE-X0 is **incomplete**. The current executable builds and qualifies a decimal storage candidate, not an operating three-register Difference Engine. Its next gate is non-destructive digit transfer, including source-triggered clutch release and an output coupling that does not back-drive storage during reader return.
+
+From the repository root, run the headless qualification:
+
+```powershell
+./demos/Aetheris.DifferenceEngine/Run.ps1 -Packaged
+```
+
+Omit `-Packaged` to skip the fresh CLI installation. `-Output <directory>` selects an output directory; the default is ignored `artifacts/local/demos/difference-engine/`. A successful command means the **storage gate checks** passed. It does not mean the full milestone passed. There is no complete-cycle viewer to launch yet.
+
+The command generates ordinary multi-file Firmament, builds the storage assembly, exports shared meshes and AP242, exercises indexing, inspects and reimports the assembly through Aetheris.CLI, and runs the focused tests. The packaged option installs a fresh CLI in a temporary directory outside the checkout and builds a copied storage assembly and a mixed gear/shaft fixture there. It preserves that directory for inspection.
+
+## Source and authority
+
+[`StorageDesign.cs`](../../../demos/Aetheris.DifferenceEngine/StorageDesign.cs) owns the fixed print-oriented dimensions. It supplies ordinary template arguments to the reusable [part definitions](../../../fixtures/DifferenceEngine/parts/Storage.firmament), writes the `DecimalDigit` Subassembly, and composes two independent occurrences. Generated source remains under the output's `source/` directory; its author and templates are versioned. No child STEP is used as linkage.
+
+Each module exposes a typed Gear drive port and semantic position ports. The storage qualification resolves the drive's `GearAir` and relative occurrence path through that public port, checks real cylindrical index-hole locations in the compiled plate, and creates separate rotary state for each occurrence. Definition geometry is shared; state is not.
+
+[`IndexedRotaryStorage`](../../../Aetheris.Kernel.Core/Mechanisms/IndexedRotaryStorage.cs) is a low-level ideal joint under the existing Mechanisms namespace. It accepts forward angular displacement and pin lift, reports crossed index locations and rollover events, rejects a locked drive or misaligned pin insertion, and captures versioned occurrence-specific snapshots. The readout is absent between indexed positions. Setup accepts an initial index explicitly; drive does not accept a target digit or register sum. This primitive neither latches nor transmits carry and does not supply cycle sequencing.
+
+The model assumes vertical stationary shafts and gravity-biased pins. The gear, display, indexing plate and sleeve rotate together through a modeled adhesive annulus. Retainer collars limit axial sleeve travel; their attachment, adhesive strength and purchased hardware fits are unqualified. The pin head rests on the upper guide at the indexed position. A 5 mm lift gives 1 mm clearance above the indexing plate. The runtime admits a maximum 5 mm lift and requires at least 4.5 mm before rotation.
+
+## Inspect the evidence
+
+The output contains:
+
+| Artifact | Meaning |
+|---|---|
+| `storage-gate.step` | Whole storage assembly; 15 unique part definitions, 40 physical occurrences |
+| `storage-gate.mesh.json` | Shared Aetheris meshes, stable occurrence IDs and solved rest transforms |
+| `storage-manifest.json` | Hierarchy, source dependency hashes and inventory |
+| `storage-qualification.json` | Actual index-hole alignment, independent states, events, and rejected reset candidate |
+| `storage-design.json` | Typed nominal design dimensions |
+| `hashes.json` | Deterministic source and artifact digests |
+| `cli-reimport.json` | Product-structure reimport result |
+| `packaged-run.json` | Optional package version, external working directory and STEP digest |
+
+For a self-contained WebGL geometry inspection, use the checkout's existing Three.js dependency (restore `aetheris.client` dependencies first if absent):
+
+```powershell
+./demos/Aetheris.DifferenceEngine/BuildInspection.ps1
+```
+
+Open the generated `storage-inspection.html` directly in a browser; no server is needed. Top, underside and mesh-edge controls inspect the exported triangles and normals without generating replacement geometry. The second view isolates the indexing plate. This is a geometry inspector, not an operating mechanical simulation. Browser automation could not verify this local page because its URL policy rejected local-file navigation.
+
+Planar/cylindrical assembly definitions now use the same shared-boundary `SurfaceMeshIR` construction as OBJ export. Other surface families retain the existing bounded display tessellator; each definition records `meshPipeline`. An IR failure on a planar/cylindrical definition fails export instead of silently falling back. `Run.ps1` exports the actual reimported indexing plate through `aetheris mesh --format obj`, checks watertightness and topology defects, and compares assembly meshes and OBJ bytes against the packaged CLI. The component is selected by the current import manifest and verified hash, so stale files from earlier runs cannot be mistaken for current geometry.
+
+The earlier Matplotlib image showed suspicious depth-order artifacts and is superseded by this inspector; it is not accepted visual evidence. OBJ topology passes independently, although the plate's planar audit reports a bounded fallback with skinny cells, so no high-quality quad-layout claim is made.
+
+## The next gate
+
+The compiled equal-gear witness has ratio `-1`. A reader stroke of `-36°` advances its output `+36°`; returning that reader by `+36°` imposes `-36°` on the same permanent output mesh. Locking the destination would instead create a lock/drive conflict. Releasing an upstream drive clutch alone does not disconnect this output relationship.
+
+The next implementation must provide and qualify a physical output disengagement or one-way coupling as well as the source-stop trip, input clutch, and reset actuation. The witness is a rejection of that simple candidate, **not** evidence that all possible rotor adders fail. No two-digit carry or complete engine is admitted on the strength of these storage tests.
+
+The frozen future operating order is `Result <- FirstDifference`, Result carries, `FirstDifference <- SecondDifference`, FirstDifference carries, controlled return. Squares start at `0000 / 0001 / 0002`. Arithmetic verification, carry latches, overflow, sequence presets and the diagnostic machine viewer remain unimplemented. There is no arithmetic oracle in the storage primitive.
+
+See the [release record](../../release/DIFF-ENGINE-X0.md) for scope, qualification and remaining limitations. Rotor/clutch and modular-adder inspiration is attributed to Andrew Carol's [A Difference Engine Built With LEGO Pieces](https://www.cs.princeton.edu/~chazelle/courses/BIB/babbage.pdf); the storage geometry here is independently authored.
diff --git a/docs/public/firmament/gears.md b/docs/public/firmament/gears.md
index f4fb5876..a13f226a 100644
--- a/docs/public/firmament/gears.md
+++ b/docs/public/firmament/gears.md
@@ -49,7 +49,7 @@ Interface<Gear> Indexing {
}
```
-This relationship is ideal geometry and kinematics. It is not a contact, dynamics, torque, wear, or stress solver.
+This relationship is ideal geometry and kinematics. It is not a contact, dynamics, torque, wear, or stress solver. It also does not acquire a clutch state automatically: a permanent mesh still transmits reader return motion. See the [Difference Engine storage gate](difference-engine.md) for the corresponding reset counterexample.
## Gear ports in subassemblies
diff --git a/docs/release/DIFF-ENGINE-X0.md b/docs/release/DIFF-ENGINE-X0.md
new file mode 100644
index 00000000..87a84704
--- /dev/null
+++ b/docs/release/DIFF-ENGINE-X0.md
@@ -0,0 +1,124 @@
+# DIFF-ENGINE-X0 — storage gate and assembly repairs
+
+## Executive verdict
+
+**Meaningful progression. The requested Difference Engine is not complete.** The real mixed gear/ordinary-part assembly path, ten-hole indexing-plate construction and gear display-mesh path were repaired. A reusable decimal storage candidate now builds as exact hierarchical CAD and has an ideal indexing primitive with occurrence-specific state and replay checks.
+
+Gate B is not admitted. A concrete counterexample confirms that a reader connected to storage through a permanent output mesh cancels its transfer when it returns. Disconnecting only the input drive does not solve this. A physical output disengagement or one-way coupling, source-stop trip, clutch actuation and return linkage still need implementation and qualification. This is a specific missing mechanism, not a claim that a rotor adder is impossible.
+
+No full machine, arithmetic adder, carry latch/chain, master cam schedule, overflow mechanism, quadratic presets, independent arithmetic oracle, browser evaluator, or interactive machine viewer is delivered. Gate A's **selected geometry and ideal joint checks** must not be read as acceptance of every physical provision or the entire milestone. The later gates were not replaced with numerical arithmetic or a precomputed animation.
+
+## Brief capability audit
+
+| Existing authority | Reused / finding |
+|---|---|
+| GEAR-LIB-X0 | Qualified m2, 20-tooth spur geometry and GearAir; transmission tooth count remains independent of the ten index positions. Ratchet/pawl compatibility is not a validated freewheel. |
+| ASM-INTERFACE-X1 | Include, reusable Subassembly, Expose, local rest mates and shared definition execution. |
+| ASM-GEAR-BRIDGE-X1 | Typed exposed Gear binding, relative occurrence path and actual ratio/center-distance validation. A mixed ordinary-part catalog bug was uncovered below that semantic boundary. |
+| ENGINE-X0 / V8 | AssemblyDisplayMeshExporter, prescribed-ratio utility and artifact discipline. Rest placement and prescribed motion do not supply stateful clutch/carry operation. |
+| Profile / Pattern | Circle2, exact ring profiles, ordinary extrusion, circular holes and ten-position Radial Pattern. Full-circle composition required the bounded adaptation described below. |
+| Revolve / material offsets | Existing bounded geometry routes; not needed for this prismatic storage candidate and not extended. |
+| WireForm | Existing spring and winding-datum support remains available. This candidate explicitly uses vertical, gravity-biased index pins; no spring-force claim is made. |
+| Copeland / MachinaLayout.JS / TSPack | Read the current Copeland Ariadne/Dominatus consumer and persistence usage, MachinaLayout package surface and TSPack Flow workflow contract after the user's reuse guidance. These remain candidates for presentation/sequencing. No second HFSM, layout engine or workflow stack was added, and no other repository was modified. |
+
+Andrew Carol's [A Difference Engine Built With LEGO Pieces](https://www.cs.princeton.edu/~chazelle/courses/BIB/babbage.pdf) provides modular rotor/clutch precedent. This work independently authors its storage geometry and does not copy LEGO proportions. The requested arithmetic convention remains authoritative: initialize squares as `0000 / 0001 / 0002`, transfer FirstDifference into Result and finish its carries, then transfer SecondDifference into FirstDifference and finish its carries, then return. This convention is documented only; the sequence evaluator is not implemented.
+
+## Architecture and inventory
+
+`StorageDesign` supplies typed millimetre dimensions to ordinary multi-file Firmament templates. The root composes two occurrences of `DecimalDigit`. The assembly compiler owns physical geometry, rest placement, public ports and occurrence identity. `StorageQualification` resolves the public Gear ports and their original GearAir rather than copying tooth parameters into a parallel gear definition. Actual index-hole cylinder centers establish the admitted index count and geometric alignment checks.
+
+The primitive `IndexedRotaryStorage` lives under the existing Core Mechanisms namespace alongside `SliderCrank` and `PrescribedMotion`. It accepts angular drive displacement and axial pin lift. It stores unwrapped angle separately from the index readout, reports each crossed index and rollover, rejects lock/drive and pin-insertion conflicts, and saves versioned snapshots carrying occurrence and definition identity. It is not a scheduler, latch, carry service or adder. Its indexed setup constructor is explicit; ongoing drive cannot accept a digit or register answer. The two occurrences have independent state despite sharing geometry.
+
+| Quantity | Storage witness |
+|---|---:|
+| Unique physical definitions | 15 |
+| Physical occurrences | 40 |
+| DecimalDigit occurrences / reusable module definitions | 2 / 1 |
+| Gears / stationary shafts / indexing pins | 2 / 2 / 2 |
+| Clutches / carry latches | 0 / 0 |
+| Assembly depth, including root and leaf | 3 |
+| Generated Firmament dependency files | 4 |
+| Reimported AP242 occurrences, including two module occurrences | 42 |
+
+The 20 physical members per digit are gear, sleeve, display, indexing plate, adhesive annulus, shaft, two retainer collars, two supports, index pin and head, two spacers, two tie-bolt shanks, two bolt-head envelopes and two nut envelopes. Fastener heads/shanks are separate simplified geometric definitions, not a claim of complete purchased fastener CAD.
+
+## Qualification and evidence
+
+| Check | Result / boundary |
+|---|---|
+| Mixed catalog geometry | Shaft remains a radius-4 mm, 40 mm cylinder alongside the spur gear; it no longer silently becomes another gear. Hierarchical reuse, deterministic STEP and reimport checked. |
+| Indexing plate | Ten actual cylindrical holes on radius 26 mm, 4.4 mm diameter; radial pin clearance approximately 0.2 mm at each index. |
+| Axial withdrawal | Pin ready tip Z=16 mm, plate top Z=20 mm, maximum lift 5 mm: 1 mm nominal withdrawn clearance. Runtime requires at least 4.5 mm lift. |
+| Shaft/sleeve | Nominal 8 mm stationary shaft, 8.4 mm sleeve bore; 0.4 mm diameter clearance. Retainer gaps are 0.5 mm at each sleeve end. |
+| Independent indexed storage | All ten nominal positions, source occurrence unchanged while the other advances; in-between readout absent. Generic 2-, 10- and 12-position definitions tested. This is not a three-/four-digit structural variant. |
+| Drive and replay | Multiple index crossings, rollover events, irregular vs large increments, pause/serialized restore, invalid snapshot/definition/version, finite bounds and lock conflicts checked. |
+| Gear meshes | Every flank has nonempty triangles and finite unit normals; straight extrusion flanks have no erroneous axial normals. Signed volume is between root- and addendum-cylinder bounds and agrees with cap area × thickness within 0.5%. |
+| Plate mesh | The existing OBJ SurfaceMeshIR path succeeds: 50 analytic patches, watertight, connected, outward-oriented, zero cracks/nonmanifold edges/duplicate or zero-area triangles. Assembly export now reuses that path, with matching triangle count, winding/normal agreement and signed volume within 2% of the independently calculated plate less eleven bores. |
+| Reset counterexample | Compiled equal-gear ratio -1: -36° reader stroke gives +36° destination motion; +36° reader return imposes -36° destination motion. Locking instead would conflict. No favorable clutch disconnection is invented. |
+| Physical readiness | Selected nominal clearances only. Adhesive strength, retention forces, gravity-pin reliability, manufacturing tolerance, wear and full moving-contact coverage are unqualified. |
+| Later acceptance tests | All 100/200 digit arithmetic combinations, carry cascades, register additions, presets through overflow, ablations of an operating machine, browser parity and fresh-agent complete-machine reuse are **not reached**. |
+
+Geometric index checks use analytic rotations at ten exact indices and a `1e-7 mm` comparison tolerance. Assembly meshing uses angular tolerance π/16, chord tolerance 0.3 mm and 6–64 segments. Planar/cylindrical definitions use SurfaceMeshIR directly; other families retain the legacy tessellator's unchanged five-second budget. CLI OBJ uses its existing default policy (not the coarser assembly policy). These checks do not certify tooth contact. The OBJ planar audit explicitly reports two fallback caps with skinny cells; a high-quality quad layout is not claimed.
+
+The original Matplotlib image showed suspicious apparent recesses despite geometric coverage checks; it is not accepted visual evidence. It is superseded by a self-contained Three.js inspection page using the exported triangles and normals, with top/underside/mesh-edge controls. Browser automation rejected local-file navigation under its URL policy, so the WebGL page's visual result remains unverified. No alternate browser route was used to bypass that restriction.
+
+## Friction and reusable repairs
+
+1. **Observation:** an annulus definition failed meshing with an involute LinearExtrusion face. **Incorrect initial hypothesis:** an ordinary annulus needed a new surface route. **Root cause:** the mixed declaration catalog was passed to the standalone build path, whose Gear profile selected the sibling gear for an ordinary template. **Repair:** remove sibling Gear declarations using the existing producer-owned source spans before ordinary template materialization. **Rejected workaround:** hand-building ordinary parts or dropping GearAir. **Limit:** this does not introduce Gear templates or a new definition compiler.
+2. **Observation:** the now-real circular plate threw from ProfileArrangementBuilder.Trim when combined with drilled holes. **Repair:** adapt full circles to four exact circular arcs before existing arrangement operations and classify a full-circle loop analytically. **Rejected workaround:** manually polygonizing every authored circle. **Limit:** no general spline arrangement/intersection engine was added.
+3. **Observation:** actual spur meshes rejected LinearExtrusion side surfaces. **Repair:** represent a non-rational B-spline extrusion exactly as a degree-1 ruled B-spline surface for the existing trimmed tessellator. **Rejected workaround:** omit flanks or generate browser gears. **Limit:** this adds the B-spline-directrix case; arbitrary other LinearExtrusion directrices remain subject to existing admission rules.
+4. **Observation:** the initial mesh volume was below the solid gear-root lower bound; base-endpoint normals sometimes defaulted to +Z. **Repair:** rescale finite-difference tangents before their cross product so physical absolute-length tolerance does not turn a regular small tangent into a singular normal. **Evidence:** horizontal flank normals and closed-prism volume checks now pass. No tolerance budget was weakened.
+5. **Observation:** a full-suite run contended with the new bounded mesh test. **Repair:** isolate the new meshing test collection from other xUnit collections while retaining the production five-second limit. The initial suite also found a release-document link before this report existed; the link is now populated. These were this run's failures, not pre-existing failures.
+6. **Observation:** the user identified the existing cylindrical OBJ path after the disk image looked wrong. **Finding:** OBJ already uses shared-boundary SurfaceMeshIR; assembly JSON used the older display path. **Repair:** planar/cylindrical assembly definitions reuse SurfaceMeshIR, record the pipeline, fail visibly on rejected IR geometry, and preserve already-oriented IR normals without applying face sense twice. **Evidence:** annulus, indexing plate, gear and placement tests pass; actual plate OBJ is watertight. **Limit:** gear B-spline extrusions retain the explicit legacy route and cap layout quality remains limited by the existing bounded planar fallback.
+
+## Preliminary make/buy plan
+
+Quantities are for the **two-digit storage witness**, not an invented full-machine BOM.
+
+| Family | Quantity | Proposal | Critical interface / unresolved issue |
+|---|---:|---|---|
+| Spur gear, display, index plate | 2 each | Make, candidate PA or PETG print | Bonded bore and 36° registration; shrinkage, tooth finish and wear unqualified |
+| Rotating sleeve | 2 | Make or machine polymer/metal | 8.4 mm bore on 8 mm shaft; running fit and friction unqualified |
+| Adhesive annulus | 2 | Bonding-process allowance | 0.15 mm radial gap; adhesive choice and torque capacity unqualified |
+| Stationary shafts | 2 | Buy/cut metal stock | Alignment and support/retainer attachment unqualified |
+| Retainer collars | 4 | Buy or make | Axial retention; no set-screw/thread detail or force validation |
+| Support plates / spacers | 4 / 4 | Make, candidate printed polymer | Shaft/guide alignment and mounting stiffness unqualified |
+| Index pins and heads | 2 each | Buy/machine metal candidate | Gravity bias, straightness, release actuation and wear unqualified |
+| Tie bolts and nuts | 4 each | Buy, nominal M4 candidate | Thread geometry is an envelope only; access and tightening process unqualified |
+
+No supplier availability, price, fabrication time or printer-independent fit is claimed. After the release/reset mechanism qualifies, the first fabrication experiment should be one adder/carry module. Ordering or fabricating the full engine is premature.
+
+## Reproduction and handoff boundary
+
+Base checkout: `e7134210f0f18ccd51fc7c1f8fb992e879b810b2`; this report describes the working-tree changes, not a newly created commit. Public instructions are in the [storage guide](../public/firmament/difference-engine.md).
+
+```powershell
+./demos/Aetheris.DifferenceEngine/Run.ps1 -Packaged
+dotnet build Aetheris.slnx -c Release -m:1
+dotnet test Aetheris.slnx -c Release --no-build -m:1 --filter 'Category!=SlowCorpus'
+pwsh -NoProfile -File scripts/Test-CanonicalFixtures.ps1 -NoBuild
+pwsh -NoProfile -File scripts/Test-RepositoryLayout.ps1
+git diff --check
+```
+
+Default output: `artifacts/local/demos/difference-engine/`. Exact source, mesh, STEP, manifest, state/event evidence and hashes are included there; timings, package version, temporary paths and logs are separate. `index-plate.obj-report.json` records the real CLI topology and planar audit. `BuildInspection.ps1` generates `storage-inspection.html` using the existing client Three.js package; no server is required. STEP supplies only product geometry and structure; the primitive's definition/snapshots do not make the STEP an executable calculator.
+
+Final local validation:
+
+- Release solution build: 0 warnings, 0 errors (`release-build-final.log`).
+- Serial solution tests, excluding `SlowCorpus`: **3,512 passed**, 0 failed across 18 test projects (`serial-regression-final.log`). The legacy-gated FrictionLab assembly contains no matching tests in this lane.
+- Focused storage tests: 5 Core and 3 Firmament cases passed; the additional existing annulus/placement comparisons passed (6 Firmament mesh tests together).
+- Fresh package `2.0.0-diffengine-x0.20260914023545` installed and executed outside the checkout. Repository/demo/package STEP and assembly meshes are byte-identical; repository/package plate OBJ is byte-identical. The imported assembly has 15 definitions and 42 occurrences including two modules.
+- OBJ plate: 7,400 final triangles, 3,879 polygons including 3,374 quads, maximum reported boundary chord deviation 0.0438548879 mm. The assembly policy independently yields 8,680 plate triangles; its different tolerance policy is explicit.
+- Repository layout guard and `git diff --check` passed. The guard reports 4,192 tracked files; new files were separately checked against the declared fixture/demo/public-doc/release-report locations.
+- Inspection-page scripts pass `node --check`; browser rendering remains unverified due to the local-file URL rejection above.
+- Separate-output deterministic regeneration: all 9 source/core artifact SHA-256 entries match (`determinism-report.json`).
+- Canonical lane: **210 operations passed out of 213 source files**, including both new fixtures; the overall command exits 1. The first reported failure is the existing `Assembly/annular-pair.firmament` `LegacyExplicit` source-policy violation. Three existing include catalogs (`AssemblyInterfaces/digit-module.firmament`, `executable-cell.firmament`, `register.firmament`) are incorrectly dispatched as standalone roots by the qualification manifest and independently return `assembly-parse-missing-root`. All four source conditions are present at the base commit. The runner's stop-on-error report prints only the first accumulated error; the three direct CLI diagnostics are retained in `canonical-*.json`. This is not a clean canonical lane.
+
+| Artifact | SHA-256 |
+|---|---|
+| `storage-gate.step` | `AE9131821FBF838873CBC514A44C9FE2C09785D0A85D9D4FEB584BB8879CCAD1` |
+| `storage-gate.mesh.json` | `C620878E06D34EA5E9EAB02FE6BC798CB3F7D4B4467CB7177EDC6E49BEC85619` |
+| `index-plate.obj` | `C5B70C26E412B3DB8B8BC1959D9D1E27F9572354BA3F0338403ACE9A05655D7A` |
+
+No remote CI, deployment, account change, procurement, full-machine fresh-agent test or modification to another repository was performed.
diff --git a/fixtures/Canonical/AssemblyInterfaces/gear-with-ordinary-part.firmament b/fixtures/Canonical/AssemblyInterfaces/gear-with-ordinary-part.firmament
new file mode 100644
index 00000000..8049a98f
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/gear-with-ordinary-part.firmament
@@ -0,0 +1,28 @@
+Units: mm
+SpurGear Drive { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 8mm BoreDiameter: 8.4mm }
+Template < R: Length, H: Length > Struct Shaft {
+ Circle2 Outside { Center: [0mm,0mm] Radius: R }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Extrude Body { Profile: Section From: 0mm To: H }
+}
+Subassembly GearAndShaft {
+ <Assembly GearAndShaft>
+ <Part Wheel = Drive></Part>
+ <Part Axle = Shaft<R: 4mm, H: 40mm>>
+ Semantic Mount { Axis Axis = [0,0,0] -> [0,0,1]; }
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,-16,1];
+ </Part>
+ </Assembly>
+ Anchor: GearAndShaft.Wheel;
+ Expose { Gear Drive = Wheel; Semantic Mount = Axle.Mount; }
+}
+Assembly MixedMechanism {
+ <Assembly MixedMechanism>
+ <Assembly First = GearAndShaft></Assembly>
+ <Assembly Second = GearAndShaft>
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 40,0,0,1];
+ </Assembly>
+ </Assembly>
+ Anchor: MixedMechanism.First.Mount;
+ Interface<Gear> Mesh { A: MixedMechanism.First.Drive; B: MixedMechanism.Second.Drive; }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/index-plate-with-gear.firmament b/fixtures/Canonical/AssemblyInterfaces/index-plate-with-gear.firmament
new file mode 100644
index 00000000..54b077c3
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/index-plate-with-gear.firmament
@@ -0,0 +1,12 @@
+Units: mm
+Include "../../DifferenceEngine/parts/Storage.firmament";
+SpurGear Drive { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 8mm BoreDiameter: 8.4mm }
+Assembly IndexedGear {
+ <Assembly IndexedGear>
+ <Part Wheel = Drive></Part>
+ <Part Plate = DecimalIndexPlate<Rout: 32mm, Rin: 6.15mm, PitchR: 26mm, HoleD: 4.4mm, Zlow: 0mm, Zhigh: 6mm>>
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,10,1];
+ </Part>
+ </Assembly>
+ Anchor: IndexedGear.Wheel;
+}
diff --git a/fixtures/DifferenceEngine/README.md b/fixtures/DifferenceEngine/README.md
new file mode 100644
index 00000000..60990a93
--- /dev/null
+++ b/fixtures/DifferenceEngine/README.md
@@ -0,0 +1,5 @@
+# Difference Engine reusable source
+
+`parts/Storage.firmament` contains ordinary parameterized part definitions used by the typed storage author and canonical regression fixtures. It is an include catalog, not a standalone build root.
+
+See the [public guide](../../docs/public/firmament/difference-engine.md). Generated Subassembly roots, STEP and meshes belong under ignored `artifacts/local/`.
diff --git a/fixtures/DifferenceEngine/parts/Storage.firmament b/fixtures/DifferenceEngine/parts/Storage.firmament
new file mode 100644
index 00000000..aac66f7d
--- /dev/null
+++ b/fixtures/DifferenceEngine/parts/Storage.firmament
@@ -0,0 +1,42 @@
+// Dimensional arguments are supplied by the typed design author.
+// These ordinary templates are also usable without the demo executable.
+Template < Rout: Length, Rin: Length, Zlow: Length, Zhigh: Length >
+Struct Annulus {
+ Circle2 Outside { Center: [0mm,0mm] Radius: Rout }
+ Circle2 Inside { Center: [0mm,0mm] Radius: Rin }
+ Profile Section { Loop Outer { Outside |> TraceLoop } Loop Inner { Inside |> TraceLoop } }
+ Extrude Body { Profile: Section From: Zlow To: Zhigh }
+}
+
+Template < R: Length, Zlow: Length, Zhigh: Length >
+Struct RoundBar {
+ Circle2 Outside { Center: [0mm,0mm] Radius: R }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Extrude Body { Profile: Section From: Zlow To: Zhigh }
+}
+
+Template < Rout: Length, Rin: Length, PitchR: Length, HoleD: Length, Zlow: Length, Zhigh: Length >
+Struct DecimalIndexPlate {
+ Circle2 Outside { Center: [0mm,0mm] Radius: Rout }
+ Circle2 Inside { Center: [0mm,0mm] Radius: Rin }
+ Profile Section { Loop Outer { Outside |> TraceLoop } Loop Inner { Inside |> TraceLoop } }
+ Axis IndexAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }
+ Compose Body {
+ Base Stock { Profile: Section From: Zlow To: Zhigh Role: Stock }
+ Hole<Shaft> IndexZero { On: +Z Center: Point2(PitchR,0mm) Diameter: HoleD End: ThroughAll }
+ Radial Pattern IndexPositions { Source: IndexZero About: IndexAxis Count: 10 Angle: full }
+ }
+}
+
+Template < W: Length, D: Length, H: Length, ShaftD: Length, PinX: Length, PinD: Length, MountX: Length, MountY: Length >
+Struct StorageSupport {
+ Rect2 Outside { Center: [0mm,0mm] Size: [W,D] }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Compose Body {
+ Base Stock { Profile: Section From: 0mm To: H Role: Stock }
+ Hole<Shaft> ShaftBore { On: +Z Center: Point2(0mm,0mm) Diameter: ShaftD End: ThroughAll }
+ Hole<Shaft> PlungerGuide { On: +Z Center: Point2(PinX,0mm) Diameter: PinD End: ThroughAll }
+ Hole<Shaft> MountLeft { On: +Z Center: Point2(-MountX,MountY) Diameter: 4.5mm End: ThroughAll }
+ Hole<Shaft> MountRight { On: +Z Center: Point2(MountX,MountY) Diameter: 4.5mm End: ThroughAll }
+ }
+}