Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add assembly mesh export and preserve specialized boundary semantics

Yuechen Li4605ac2355b5
diff --git a/Aetheris.CLI.Tests/AssemblyMeshCommandTests.cs b/Aetheris.CLI.Tests/AssemblyMeshCommandTests.cs
new file mode 100644
index 00000000..5d7e23bb
--- /dev/null
+++ b/Aetheris.CLI.Tests/AssemblyMeshCommandTests.cs
@@ -0,0 +1,28 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class AssemblyMeshCommandTests
+{
+ [Fact]
+ public void AssemblyMeshPreservesSharedDefinitionsAndFailsClosed()
+ {
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root != null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ Assert.NotNull(root);
+ var output = Path.Combine(root!.FullName, "artifacts/local/tests/assembly-mesh", Guid.NewGuid().ToString("N") + ".json");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var fixture = Path.Combine(root.FullName, "fixtures/Canonical/Assembly/annular-pair.firmament");
+ var exit = CliRunner.Run(["mesh", fixture, "--format", "assembly-json", "--output", output, "--json"], stdout, stderr);
+ Assert.True(exit == 0, stderr.ToString() + stdout);
+ using var document = JsonDocument.Parse(File.ReadAllText(output));
+ Assert.Equal("aetheris/assembly-display-mesh/1", document.RootElement.GetProperty("schema").GetString());
+ Assert.Single(document.RootElement.GetProperty("definitions").EnumerateArray());
+ Assert.Equal(3, document.RootElement.GetProperty("occurrences").GetArrayLength());
+ var valid = File.ReadAllText(output);
+ stdout.GetStringBuilder().Clear(); stderr.GetStringBuilder().Clear();
+ exit = CliRunner.Run(["mesh", fixture + ".missing", "--format", "assembly-json", "--output", output, "--json"], stdout, stderr);
+ Assert.NotEqual(0, exit);
+ Assert.Equal(valid, File.ReadAllText(output));
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index e579648f..02f81680 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -134,7 +134,7 @@ public static class CliRunner
int? RigidRootCount = null);
private const string TopLevelUsage = "Usage: aetheris <command> [options]";
private const string BuildUsage = "Usage: aetheris build <file.firmament> [--output <path>] [--json]";
- private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.step> [--format stl|obj] [--output <path>] [--debug-ir <path>] [--json]";
+ private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|assembly-json] [--output <path>] [--debug-ir <path>] [--json]";
private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--json]";
private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";
private const string InspectSpansUsage = "Usage: aetheris inspect-spans <file.firmament> --json";
@@ -1202,9 +1202,29 @@ Model CanonicalPanel {
default: stderr.WriteLine($"Unknown mesh option '{args[i]}'."); stderr.WriteLine(MeshUsage); return 1;
}
}
+ if (string.Equals(format, "assembly-json", StringComparison.OrdinalIgnoreCase))
+ {
+ if (debugIr is not null) { stderr.WriteLine("assembly-json does not support --debug-ir."); return 1; }
+ var compilation = Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase)
+ ? new FirmamentAssemblyDocumentCompiler().CompileFile(input).Compilation
+ : new AssemblyM1Pipeline().CompileFile(input);
+ if (!compilation.IsSuccess)
+ return WriteMeshFailure(compilation.Diagnostics.Select(d => d.Code + ": " + d.Message), json, input, stdout, stderr);
+ try
+ {
+ var assemblyDocument = AssemblyDisplayMeshExporter.Export(compilation);
+ var destination = Path.GetFullPath(output ?? Path.Combine("artifacts", "local", "mesh", Path.GetFileNameWithoutExtension(input) + ".mesh.json"));
+ Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
+ File.WriteAllText(destination, AssemblyDisplayMeshExporter.Serialize(assemblyDocument));
+ stdout.WriteLine(JsonSerializer.Serialize(new { status = "success", output = destination, definitions = assemblyDocument.Definitions.Count,
+ occurrences = assemblyDocument.Occurrences.Count, triangles = assemblyDocument.Definitions.Sum(d => d.Indices.Length / 3) }));
+ return 0;
+ }
+ catch (InvalidOperationException error) { return WriteMeshFailure([error.Message], json, input, stdout, stderr); }
+ }
if (!string.Equals(format, "stl", StringComparison.OrdinalIgnoreCase) && !string.Equals(format, "obj", StringComparison.OrdinalIgnoreCase))
{
- stderr.WriteLine("Mesh supports binary STL and topology-preserving OBJ.");
+ stderr.WriteLine("Mesh supports binary STL, topology-preserving OBJ, and assembly-json definition/occurrence meshes.");
return 1;
}
var fullInput = Path.GetFullPath(input);
diff --git a/Aetheris.Kernel.Core.Tests/Mechanisms/SliderCrankTests.cs b/Aetheris.Kernel.Core.Tests/Mechanisms/SliderCrankTests.cs
new file mode 100644
index 00000000..4d2e16be
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Mechanisms/SliderCrankTests.cs
@@ -0,0 +1,44 @@
+using Aetheris.Kernel.Core.Mechanisms;
+
+namespace Aetheris.Kernel.Core.Tests.Mechanisms;
+
+public sealed class SliderCrankTests
+{
+ [Theory]
+ [InlineData(44, 145)]
+ [InlineData(48, 155)]
+ public void FullCycleClosesAtBothBanksAndFourCrankpinPhases(double r, double length)
+ {
+ var mechanism = new SliderCrank(r, length);
+ foreach (var bank in new[] { -45d, 45d })
+ foreach (var phase in new[] { 45d, 135d, 225d, 315d })
+ for (var degree = 0; degree <= 720; degree++)
+ {
+ var pose = mechanism.Evaluate(degree * double.Pi / 180, bank * double.Pi / 180, phase * double.Pi / 180);
+ Assert.InRange(double.Abs((pose.WristPin - pose.CrankPin).Length - length), 0, 1e-10);
+ Assert.InRange(pose.WristPin.Cross(pose.BoreAxis).Length, 0, 1e-10);
+ Assert.InRange(double.Abs(pose.CrankPin.Length - r), 0, 1e-10);
+ }
+ Assert.Equal(2 * r, mechanism.Evaluate(0).PistonPositionMm - mechanism.Evaluate(double.Pi).PistonPositionMm, 10);
+ Assert.NotEqual(length, mechanism.Evaluate(double.Pi / 2).PistonPositionMm);
+ }
+
+ [Fact]
+ public void RatioAndWrappedLiftAreBoundedAndPeriodic()
+ {
+ Assert.Equal(2 * double.Pi, PrescribedMotion.AngularRatio(4 * double.Pi, .5));
+ for (var degree = -720; degree <= 1440; degree++)
+ {
+ var lift = PrescribedMotion.ValveLift(degree, 700, 180, 10);
+ Assert.InRange(lift, 0, 10);
+ Assert.Equal(lift, PrescribedMotion.ValveLift(degree + 720, 700, 180, 10), 12);
+ }
+ Assert.Equal(10, PrescribedMotion.ValveLift(70, 700, 180, 10), 12);
+ Assert.Equal(0, PrescribedMotion.ValveLift(160, 700, 180, 10));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new SliderCrank(44, 44).Evaluate(0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new SliderCrank(44, 145).Evaluate(double.NaN));
+ Assert.Throws<ArgumentOutOfRangeException>(() => PrescribedMotion.ValveLift(0, 0, 720, 10));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new SliderCrank(44, double.MaxValue).Evaluate(0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => PrescribedMotion.ValveLift(double.MaxValue, -double.MaxValue, 180, 10));
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.cs
new file mode 100644
index 00000000..3b0736d5
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.cs
@@ -0,0 +1,24 @@
+namespace Aetheris.Kernel.Core.Brep.Tessellation;
+
+/// <summary>Projects the exact face sense into render normals and front-face triangle winding.</summary>
+public static class DisplayMeshOrientation
+{
+ public static DisplayFaceMeshPatch Orient(BrepBody body, DisplayFaceMeshPatch patch)
+ {
+ if (patch.Normals.Count != patch.Positions.Count || patch.TriangleIndices.Count % 3 != 0
+ || patch.TriangleIndices.Any(i => i < 0 || i >= patch.Positions.Count))
+ throw new InvalidOperationException($"display-mesh-invalid-patch:{patch.FaceId}");
+ if (!body.Bindings.TryGetFaceBinding(patch.FaceId, out var binding))
+ throw new InvalidOperationException($"display-mesh-missing-face-binding:{patch.FaceId}");
+ var normals = patch.Normals.Select(normal => binding.SameSense ? normal : -normal).ToArray();
+ var indices = patch.TriangleIndices.ToArray();
+ for (var i = 0; i < indices.Length; i += 3)
+ {
+ var a = indices[i]; var b = indices[i + 1]; var c = indices[i + 2];
+ var cross = (patch.Positions[b] - patch.Positions[a]).Cross(patch.Positions[c] - patch.Positions[a]);
+ if (cross.Dot(normals[a] + normals[b] + normals[c]) < 0)
+ (indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]);
+ }
+ return patch with { Normals = normals, TriangleIndices = indices };
+ }
+}
diff --git a/Aetheris.Kernel.Core/Mechanisms/SliderCrank.cs b/Aetheris.Kernel.Core/Mechanisms/SliderCrank.cs
new file mode 100644
index 00000000..65170369
--- /dev/null
+++ b/Aetheris.Kernel.Core/Mechanisms/SliderCrank.cs
@@ -0,0 +1,53 @@
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Kernel.Core.Mechanisms;
+
+/// <summary>Analytical, in-line slider-crank in the XY plane; shaft axis is +Z.
+/// Angles are radians measured from +Y toward +X. This prescribes motion, not forces.</summary>
+public sealed record SliderCrank(double CrankRadiusMm, double RodLengthMm)
+{
+ public SliderCrankPose Evaluate(double shaftAngleRadians, double bankAngleRadians = 0, double crankpinPhaseRadians = 0)
+ {
+ if (!double.IsFinite(CrankRadiusMm) || !double.IsFinite(RodLengthMm) || CrankRadiusMm <= 0 || RodLengthMm <= CrankRadiusMm)
+ throw new ArgumentOutOfRangeException(nameof(RodLengthMm), "mechanism-slider-crank-domain: require finite L > r > 0.");
+ if (!double.IsFinite(shaftAngleRadians) || !double.IsFinite(bankAngleRadians) || !double.IsFinite(crankpinPhaseRadians))
+ throw new ArgumentOutOfRangeException(nameof(shaftAngleRadians), "mechanism-angle-nonfinite");
+ var angle = shaftAngleRadians + crankpinPhaseRadians;
+ var pin = new Vector3D(CrankRadiusMm * double.Sin(angle), CrankRadiusMm * double.Cos(angle), 0);
+ var axis = new Vector3D(double.Sin(bankAngleRadians), double.Cos(bankAngleRadians), 0);
+ var along = pin.Dot(axis);
+ var perpendicular = pin - axis * along;
+ var position = along + double.Sqrt(RodLengthMm * RodLengthMm - perpendicular.LengthSquared);
+ if (!double.IsFinite(position))
+ throw new ArgumentOutOfRangeException(nameof(RodLengthMm), "mechanism-slider-crank-nonfinite-solution");
+ var wrist = axis * position;
+ var rod = wrist - pin;
+ return new(pin, wrist, axis, position, double.Atan2(rod.X, rod.Y));
+ }
+}
+
+public sealed record SliderCrankPose(Vector3D CrankPin, Vector3D WristPin, Vector3D BoreAxis,
+ double PistonPositionMm, double RodAngleRadians);
+
+public static class PrescribedMotion
+{
+ public static double AngularRatio(double inputRadians, double ratio)
+ {
+ if (!double.IsFinite(inputRadians) || !double.IsFinite(ratio) || !double.IsFinite(inputRadians * ratio))
+ throw new ArgumentOutOfRangeException(nameof(inputRadians), "mechanism-angular-ratio-nonfinite");
+ return inputRadians * ratio;
+ }
+
+ /// <summary>Periodic, idealized sin-squared lift. Opening/closing define a forward interval within one cycle.</summary>
+ public static double ValveLift(double phaseDegrees, double openingDegrees, double durationDegrees, double maximumLiftMm, double cycleDegrees = 720)
+ {
+ if (!double.IsFinite(phaseDegrees) || !double.IsFinite(openingDegrees) || !double.IsFinite(durationDegrees)
+ || !double.IsFinite(maximumLiftMm) || !double.IsFinite(cycleDegrees)
+ || cycleDegrees <= 0 || durationDegrees <= 0 || durationDegrees >= cycleDegrees || maximumLiftMm < 0)
+ throw new ArgumentOutOfRangeException(nameof(durationDegrees), "mechanism-lift-domain");
+ var relative = ((phaseDegrees - openingDegrees) % cycleDegrees + cycleDegrees) % cycleDegrees;
+ if (!double.IsFinite(relative))
+ throw new ArgumentOutOfRangeException(nameof(phaseDegrees), "mechanism-lift-nonfinite-phase");
+ return relative >= durationDegrees ? 0 : maximumLiftMm * double.Pow(double.Sin(double.Pi * relative / durationDegrees), 2);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Mechanisms/Web/prescribed-motion.mjs b/Aetheris.Kernel.Core/Mechanisms/Web/prescribed-motion.mjs
new file mode 100644
index 00000000..456f0128
--- /dev/null
+++ b/Aetheris.Kernel.Core/Mechanisms/Web/prescribed-motion.mjs
@@ -0,0 +1,20 @@
+// Browser projection of the public analytical mechanism contract. Inputs carry all dimensions.
+export function sliderCrank(radius, length, shaft, bank = 0, phase = 0) {
+ if (![radius, length, shaft, bank, phase].every(Number.isFinite) || radius <= 0 || length <= radius)
+ throw Error('mechanism-slider-crank-domain');
+ const pin = [radius * Math.sin(shaft + phase), radius * Math.cos(shaft + phase), 0];
+ const axis = [Math.sin(bank), Math.cos(bank), 0];
+ const along = pin[0] * axis[0] + pin[1] * axis[1];
+ const px = pin[0] - axis[0] * along, py = pin[1] - axis[1] * along;
+ const position = along + Math.sqrt(length * length - px * px - py * py);
+ if (!Number.isFinite(position)) throw Error('mechanism-slider-crank-nonfinite-solution');
+ const wrist = axis.map(v => v * position);
+ return { pin, wrist, position, rodAngle: Math.atan2(wrist[0] - pin[0], wrist[1] - pin[1]) };
+}
+export function valveLift(phase, opening, duration, maximum, cycle = 720) {
+ if (![phase, opening, duration, maximum, cycle].every(Number.isFinite) || cycle <= 0 || duration <= 0 || duration >= cycle || maximum < 0)
+ throw Error('mechanism-lift-domain');
+ const relative = ((phase - opening) % cycle + cycle) % cycle;
+ if (!Number.isFinite(relative)) throw Error('mechanism-lift-nonfinite-phase');
+ return relative >= duration ? 0 : maximum * Math.sin(Math.PI * relative / duration) ** 2;
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyDisplayMeshTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyDisplayMeshTests.cs
new file mode 100644
index 00000000..b9cad9a9
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyDisplayMeshTests.cs
@@ -0,0 +1,82 @@
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+public sealed class AssemblyDisplayMeshTests
+{
+ [Fact]
+ public void AnnularDefinitionsRetainSeamsCapsIdentityAndDeterministicMeshes()
+ {
+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Assembly/annular-pair.firmament");
+ var compilation = new AssemblyM1Pipeline().CompileFile(fixture);
+ Assert.True(compilation.IsSuccess, string.Join("\n", compilation.Diagnostics.Select(d => d.Message)));
+ var body = Assert.Single(compilation.Geometry!.DefinitionBodies).Value;
+ Assert.Equal(4, body.Topology.Vertices.Count());
+ var tessellation = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(tessellation.IsSuccess);
+ Assert.All(tessellation.Value.FacePatches, face => Assert.NotEmpty(face.TriangleIndices));
+ var document = AssemblyDisplayMeshExporter.Export(compilation);
+ var definition = Assert.Single(document.Definitions);
+ double volume = 0;
+ for (var i = 0; i < definition.Indices.Length; i += 3)
+ {
+ Aetheris.Kernel.Core.Math.Vector3D Position(int index) => new(definition.Positions[index * 3], definition.Positions[index * 3 + 1], definition.Positions[index * 3 + 2]);
+ var a = Position(definition.Indices[i]); var b = Position(definition.Indices[i + 1]); var c = Position(definition.Indices[i + 2]);
+ volume += a.Dot(b.Cross(c)) / 6;
+ }
+ var expectedVolume = double.Pi * (20 * 20 - 15 * 15) * 20;
+ Assert.InRange(volume / expectedVolume, .98, 1.02);
+ Assert.Equal(2, document.Occurrences.Count(o => o.DefinitionId == definition.Id));
+ Assert.Equal(60, document.Occurrences.Single(o => o.Path == "AnnularPair.Second").Transform[12]);
+ var second = AssemblyDisplayMeshExporter.Export(new AssemblyM1Pipeline().CompileFile(fixture));
+ Assert.Equal(AssemblyDisplayMeshExporter.Serialize(document), AssemblyDisplayMeshExporter.Serialize(second));
+ Assert.Throws<InvalidOperationException>(() => AssemblyDisplayMeshExporter.Export(compilation with { Geometry = null }));
+ }
+
+ [Fact]
+ public void ExplicitObliquePlacementKeepsDoublePrecision()
+ {
+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Assembly/annular-pair.firmament");
+ var source = File.ReadAllText(fixture).Replace("1,0,0,0,0,1,0,0,0,0,1,0,60,0,0,1", "0.7071067811865476,0.7071067811865475,0,0,-0.7071067811865475,0.7071067811865476,0,0,0,0,1,0,60,0,0,1", StringComparison.Ordinal);
+ var compilation = new AssemblyM1Pipeline().Compile(source, fixture);
+ Assert.True(compilation.IsSuccess, string.Join("\n", compilation.Diagnostics.Select(d => d.Message)));
+ var transform = compilation.Ir!.Instances.Single(i => i.Path.ToString() == "AnnularPair.Second").ResolvedTransform!.Matrix;
+ Assert.Equal(double.Cos(double.Pi / 4), transform[0], 14);
+ Assert.True(Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(transform).IsRigid());
+ }
+
+ [Fact]
+ public void ObliqueFrameMateRetainsPrecisionThroughMaterializedResiduals()
+ {
+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Assembly/annular-pair.firmament");
+ var source = File.ReadAllText(fixture);
+ source = source[..source.IndexOf("Assembly AnnularPair", StringComparison.Ordinal)] + """
+ Interface RegisteredSeat {
+ Role Moving requires DatumFrameCapable;
+ Role Fixed requires DatumFrameCapable;
+ Lower FrameCoincident Moving Fixed SameDirection;
+ }
+ Assembly Oblique {
+ <Assembly Oblique>
+ <Part First = Sleeve<R: 20mm>>
+ Semantic Origin { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }
+ Semantic Seat { DatumFrame Frame = [60,0,0] x [0.7648421872844885,-0.644217687237691,0] y [0.644217687237691,0.7648421872844885,0] z [0,0,1]; }
+ </Part>
+ <Part Second = Sleeve<R: 20mm>>
+ Semantic Mount { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }
+ </Part>
+ </Assembly>
+ Anchor: Oblique.First.Origin;
+ Mate Install: RegisteredSeat { Moving: Oblique.Second.Mount; Fixed: Oblique.First.Seat; }
+ }
+ """;
+ var compilation = new AssemblyM1Pipeline().Compile(source, fixture);
+ Assert.True(compilation.IsSuccess, string.Join("\n", compilation.Diagnostics.Select(d => d.Message)));
+ var residual = Assert.Single(compilation.Geometry!.Artifact.MateResiduals);
+ Assert.True(residual.Passed);
+ Assert.InRange(residual.AngularResidualRadians, 0, 1e-14);
+ var document = AssemblyDisplayMeshExporter.Export(compilation);
+ Assert.Equal(double.Cos(.7), document.Occurrences.Single(o => o.Path == "Oblique.Second").Transform[0], 14);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/WindingAxisMateTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/WindingAxisMateTests.cs
new file mode 100644
index 00000000..3f9b0f6e
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/WindingAxisMateTests.cs
@@ -0,0 +1,36 @@
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Semantics;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+public sealed class WindingAxisMateTests
+{
+ [Theory]
+ [InlineData(6)]
+ [InlineData(4.5)]
+ public void WindingDatumMatesActualPitchedCoilAxisToStem(double pitch)
+ {
+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Assembly/coil-on-stem.firmament");
+ var source = File.ReadAllText(fixture).Replace("P: 6mm", "P: " + pitch.ToString(System.Globalization.CultureInfo.InvariantCulture) + "mm", StringComparison.Ordinal);
+ var result = new AssemblyM1Pipeline().Compile(source, fixture);
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ var coil = result.Ir!.Instances.Single(i => i.Path.ToString() == "GuidedSpring.Coil");
+ var datum = coil.SemanticRoot.ExposedMembers["Winding"].ExposedMembers["Axis"];
+ Assert.True(datum.TryBinding<ExactAxisBinding>(out var local));
+ Assert.Equal(9, local.OriginY, 10);
+ Assert.InRange(local.DirectionX, .07, .12); // Wire tangent is not the helix axis.
+ var world = Assert.IsType<ExactAxisBinding>(AssemblyWorldQuery.Resolve(result.Ir, datum.StableIdentity));
+ Assert.InRange(double.Abs(world.OriginX) + double.Abs(world.OriginY), 0, 1e-12);
+ Assert.InRange(double.Abs(world.DirectionX) + double.Abs(world.DirectionY), 0, 1e-12);
+ Assert.Equal(1, world.DirectionZ, 12);
+ Assert.Equal(2, result.Geometry!.Artifact.MateResiduals.Count);
+ Assert.All(result.Geometry.Artifact.MateResiduals, r => Assert.True(r.Passed));
+ Assert.Single(result.Ir.FitResults);
+ // Fit classification uses the compiler-derived clear diameter, not the part origin.
+ var invalid = new AssemblyM1Pipeline().Compile(source.Replace("Diameter = 8mm", "Diameter = 17mm", StringComparison.Ordinal), fixture);
+ Assert.False(Assert.Single(invalid.Ir!.FitResults).Compatible);
+ var wrongAxis = new AssemblyM1Pipeline().Compile(source.Replace("-> [0,0,1]", "-> [1,0,0]", StringComparison.Ordinal), fixture);
+ Assert.False(wrongAxis.IsSuccess);
+ Assert.Contains(wrongAxis.Diagnostics, d => d.Code == "assembly-mate-geometry-residual");
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.cs b/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.cs
index 01d4ea62..23a47ae3 100644
--- a/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.cs
@@ -7,6 +7,21 @@ namespace Aetheris.Kernel.Firmament.Tests;
public sealed class ClosedBoundary2X1Tests
{
+ [Fact]
+ public void TemplateLocalBoundariesAreLoweredOnlyAfterSpecialization()
+ {
+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Templates/local-closed-boundaries.firmament"));
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var boundary = Assert.Single(parsed.Document!.Boundaries!);
+ Assert.Equal(20, boundary.Dimensions["Radius"]);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics.Select(d => d.Message)));
+ var revised = FirmamentBuildAndExport.CompileSource(source.Replace("Disc<R: 20mm>", "Disc<R: 24mm>", StringComparison.Ordinal));
+ Assert.True(revised.IsSuccess, string.Join("\n", revised.Diagnostics.Select(d => d.Message)));
+ Assert.NotEqual(build.Value.StepText, revised.Value.StepText);
+ }
+
public static TheoryData<string, string, int> LinearFamilies => new()
{
{ "Rect2 Shape { Center: [0mm,0mm] Size: [40mm,20mm] }", "Rect2", 4 },
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
new file mode 100644
index 00000000..77b7d143
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -0,0 +1,55 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+
+namespace Aetheris.Kernel.Firmament.Assembly;
+
+public sealed record AssemblyDisplayMeshDefinition(string Id, string Identity, double[] Positions, double[] Normals, int[] Indices);
+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);
+
+/// <summary>Deterministic local-definition meshes plus world occurrence frames. Never drops failed geometry.</summary>
+public static class AssemblyDisplayMeshExporter
+{
+ public static AssemblyDisplayMeshDocument Export(AssemblyM1CompilationResult compilation, DisplayTessellationOptions? options = null)
+ {
+ if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)
+ throw new InvalidOperationException("assembly-mesh-invalid-compilation");
+ var geometry = compilation.Geometry;
+ var ids = geometry.Artifact.Definitions.ToDictionary(d => d.DefinitionIdentity, d => d.StableId, StringComparer.Ordinal);
+ 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));
+ 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);
+ 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)));
+ var offset = positions.Count / 3;
+ positions.AddRange(face.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ normals.AddRange(face.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ indices.AddRange(face.TriangleIndices.Select(i => i + offset));
+ }
+ 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()));
+ }
+ var occurrences = compilation.Ir.Instances.OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
+ {
+ var id = instance.Kind == AssemblyInstanceKind.Part
+ ? ids.GetValueOrDefault(instance.DefinitionIdentity) ?? throw new InvalidOperationException($"assembly-mesh-missing-definition:{instance.Path}") : null;
+ if (instance.ResolvedTransform is null || instance.ResolvedTransform.Matrix.Length != 16 || instance.ResolvedTransform.Matrix.Any(v => !double.IsFinite(v)))
+ throw new InvalidOperationException($"assembly-mesh-unresolved-transform:{instance.Path}");
+ return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray());
+ }).ToArray();
+ return new("aetheris/assembly-display-mesh/1", compilation.Ir.Name, "mm", definitions, occurrences);
+ }
+
+ public static string Serialize(AssemblyDisplayMeshDocument document)
+ => JsonSerializer.Serialize(document, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs
index 8ef6e364..931ce18d 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs
@@ -246,9 +246,9 @@ public sealed class AssemblyM0Compiler
var parent = instance.ParentStableId is null ? null : instances.Single(candidate => candidate.StableId == instance.ParentStableId);
AssemblyTransform? parentWorld = null;
if (parent is not null && !known.TryGetValue(parent.StableId, out parentWorld)) continue;
- var local = ToMatrix(instance.LocalTransform!);
- var world = parent is null ? local : local * ToMatrix(parentWorld!);
- known[instance.StableId] = FromMatrix(world);
+ var local = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(instance.LocalTransform!.Matrix);
+ var world = parent is null ? local : local * Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(parentWorld!.Matrix);
+ known[instance.StableId] = new(world.ToRowMajor());
explicitPending.Remove(instance);
explicitProgress = true;
}
@@ -313,8 +313,9 @@ public sealed class AssemblyM0Compiler
var parent = instance.ParentStableId is null ? null : instances.Single(candidate => candidate.StableId == instance.ParentStableId);
AssemblyTransform? parentWorld = null;
if (parent is not null && !known.TryGetValue(parent.StableId, out parentWorld)) continue;
- var world = parent is null ? ToMatrix(instance.LocalTransform!) : ToMatrix(instance.LocalTransform!) * ToMatrix(parentWorld!);
- known[instance.StableId] = FromMatrix(world); explicitPending.Remove(instance); explicitProgress = true;
+ var local = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(instance.LocalTransform!.Matrix);
+ var world = parent is null ? local : local * Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(parentWorld!.Matrix);
+ known[instance.StableId] = new(world.ToRowMajor()); explicitPending.Remove(instance); explicitProgress = true;
}
}
@@ -373,10 +374,9 @@ public sealed class AssemblyM0Compiler
{
var source = FrameMatrix(sourceFrame, DatumOrientationRelation.SameDirection);
var targetFrameMatrix = FrameMatrix(targetFrame, frameConstraint.Orientation);
- if (!Matrix4x4.Invert(source, out var inverse)) return targetWorld ?? AssemblyTransform.Identity;
- var transform = inverse * targetFrameMatrix;
- if (targetWorld is not null) transform *= ToMatrix(targetWorld);
- return FromMatrix(transform);
+ var transform = source.Inverse() * targetFrameMatrix;
+ if (targetWorld is not null) transform *= Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(targetWorld.Matrix);
+ return new(transform.ToRowMajor());
}
var axis = constraints.FirstOrDefault(x => x.Kind == PlacementConstraintKind.AxisCoincident);
if (axis is null || !values[axis.FirstSemanticValueId].TryBinding<ExactAxisBinding>(out var a) || !values[axis.SecondSemanticValueId].TryBinding<ExactAxisBinding>(out var b))
@@ -405,14 +405,14 @@ public sealed class AssemblyM0Compiler
rotation.M31, rotation.M32, rotation.M33, rotation.M34, rotation.M41, rotation.M42, rotation.M43, rotation.M44]);
}
- private static Matrix4x4 FrameMatrix(ExactDatumFrameBinding frame, DatumOrientationRelation orientation)
+ private static Aetheris.Kernel.Core.Math.Transform3D FrameMatrix(ExactDatumFrameBinding frame, DatumOrientationRelation orientation)
{
- var x = Vector3.Normalize(new((float)frame.XAxisX, (float)frame.XAxisY, (float)frame.XAxisZ));
- var y = Vector3.Normalize(new((float)frame.YAxisX, (float)frame.YAxisY, (float)frame.YAxisZ));
- var z = Vector3.Normalize(new((float)frame.ZAxisX, (float)frame.ZAxisY, (float)frame.ZAxisZ));
+ new Aetheris.Kernel.Core.Math.Vector3D(frame.XAxisX, frame.XAxisY, frame.XAxisZ).TryNormalize(out var x);
+ new Aetheris.Kernel.Core.Math.Vector3D(frame.YAxisX, frame.YAxisY, frame.YAxisZ).TryNormalize(out var y);
+ new Aetheris.Kernel.Core.Math.Vector3D(frame.ZAxisX, frame.ZAxisY, frame.ZAxisZ).TryNormalize(out var z);
if (orientation == DatumOrientationRelation.OpposedDirection) { y = -y; z = -z; }
- return new(x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X, z.Y, z.Z, 0,
- (float)frame.OriginX, (float)frame.OriginY, (float)frame.OriginZ, 1);
+ return Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor([x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X, z.Y, z.Z, 0,
+ frame.OriginX, frame.OriginY, frame.OriginZ, 1]);
}
private static Matrix4x4 ToMatrix(AssemblyTransform transform) => new(
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
index d8aad0c7..6831bf75 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
@@ -116,13 +116,37 @@ internal static class AssemblyDefinitionMaterializer
if (build.Value.ConceptIr?.TemplateInstantiations?.LastOrDefault()?.RecordArguments is { Count: > 0 } records)
provenance.AddRange(records.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair =>
new SemanticProvenance("static-record", pair.Value.StaticValue, $"{pair.Key}:{pair.Value.RecordType};{pair.Value.Provenance}", SemanticSourceSpan.Generated(sourceIdentity))));
- var semantics = build.Value.ConceptIr is null ? Array.Empty<SemanticValue>() : SemanticValues(build.Value.ConceptIr, provenance, sourceIdentity);
+ var semantics = (build.Value.ConceptIr is null ? Array.Empty<SemanticValue>() : SemanticValues(build.Value.ConceptIr, provenance, sourceIdentity))
+ .Concat(WindingSemantics(build.Value.WireForm, provenance, sourceIdentity)).ToArray();
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(build.Value.StepText)));
var stableId = "assembly-definition:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(definitionIdentity)))[..16];
var artifact = new AssemblyDefinitionArtifactIr(stableId, definitionIdentity, specialization, hash, Metrics(import.Value), provenance);
return new(definitionIdentity, specialization, import.Value, semantics, artifact);
}
+ private static IEnumerable<SemanticValue> WindingSemantics(FirmamentWireFormReport? wire,
+ IReadOnlyList<SemanticProvenance> provenance, string sourceIdentity)
+ {
+ foreach (var operation in wire?.Operations ?? [])
+ {
+ if (operation.AxisDatum is not { } datum) continue;
+ var id = operation.StableId + ":winding-datum";
+ var o = datum.Origin; var x = datum.Radial; var z = datum.Direction;
+ var y = new Vector3D(z[0], z[1], z[2]).Cross(new(x[0], x[1], x[2]));
+ var span = SemanticSourceSpan.Generated(sourceIdentity);
+ SemanticValue[] members = [
+ new(id + ":axis", new("Axis"), [new AxisCapability()],
+ [new ExactAxisBinding(o[0], o[1], o[2], z[0], z[1], z[2], id + ":axis")], exposedName: "Axis"),
+ new(id + ":frame", new("DatumFrame"), [new DatumFrameCapability()],
+ [new ExactDatumFrameBinding(o[0], o[1], o[2], x[0], x[1], x[2], y.X, y.Y, y.Z, z[0], z[1], z[2], id + ":frame")], exposedName: "Frame"),
+ new(id + ":clear-diameter", new("Length"), [new DimensionalCapability()],
+ [new TolerancedDimensionBinding(datum.ClearDiameterMm, 0, 0, "mm", id + ":clear-diameter")], exposedName: "ClearDiameter")
+ ];
+ yield return new(id, new("Semantic"), [new AxisCapability(), new DatumFrameCapability(), new DimensionalCapability()],
+ exposedMembers: members, provenance: provenance, authoredSourceSpan: span, exposedName: operation.Name);
+ }
+ }
+
private static IReadOnlyList<SemanticValue> SemanticValues(ConceptIrDocument ir, IReadOnlyList<SemanticProvenance> provenance, string sourceIdentity)
{
var members = ir.MaterializedStruct.ExposedMembers
@@ -359,13 +383,13 @@ public static class AssemblyWorldQuery
var ad = Unit(new(a.DirectionX, a.DirectionY, a.DirectionZ)); var bd = Unit(new(b.DirectionX, b.DirectionY, b.DirectionZ));
var delta = new Vector3D(a.OriginX - b.OriginX, a.OriginY - b.OriginY, a.OriginZ - b.OriginZ);
var cross = Cross(delta, bd);
- return (cross.Length, double.Acos(Math.Clamp(Math.Abs(ad.Dot(bd)), -1, 1)));
+ return (cross.Length, UndirectedAngle(ad, bd));
}
if (first is ExactPlaneBinding p && second is ExactPlaneBinding q)
{
var pn = Unit(new(p.NormalX, p.NormalY, p.NormalZ)); var qn = Unit(new(q.NormalX, q.NormalY, q.NormalZ));
var delta = new Vector3D(p.OriginX - q.OriginX, p.OriginY - q.OriginY, p.OriginZ - q.OriginZ);
- return (Math.Abs(delta.Dot(qn) - offset), double.Acos(Math.Clamp(Math.Abs(pn.Dot(qn)), -1, 1)));
+ return (Math.Abs(delta.Dot(qn) - offset), UndirectedAngle(pn, qn));
}
if (first is ExactPointBinding x && second is ExactPointBinding y)
{
@@ -378,11 +402,15 @@ public static class AssemblyWorldQuery
var fx = Unit(new(f.XAxisX, f.XAxisY, f.XAxisZ)); var gx = Unit(new(g.XAxisX, g.XAxisY, g.XAxisZ));
var fz = Unit(new(f.ZAxisX, f.ZAxisY, f.ZAxisZ)); var gz = Unit(new(g.ZAxisX, g.ZAxisY, g.ZAxisZ));
var expectedZDot = orientation == DatumOrientationRelation.OpposedDirection ? -1d : 1d;
- return (delta.Length, Math.Max(Math.Acos(Math.Clamp(fx.Dot(gx), -1, 1)), Math.Acos(Math.Clamp(expectedZDot * fz.Dot(gz), -1, 1))));
+ return (delta.Length, Math.Max(DirectedAngle(fx, gx), DirectedAngle(fz, gz * expectedZDot)));
}
return (double.PositiveInfinity, double.PositiveInfinity);
}
+ // atan2 retains precision near aligned axes; acos(dot) turns rounding at 1 into
+ // a spurious ~1e-8 rad residual even for identical oblique datum frames.
+ private static double DirectedAngle(Vector3D a, Vector3D b) => double.Atan2(Cross(a, b).Length, a.Dot(b));
+ private static double UndirectedAngle(Vector3D a, Vector3D b) => double.Atan2(Cross(a, b).Length, double.Abs(a.Dot(b)));
private static Vector3D Unit(Vector3D value) => value / value.Length;
private static Vector3D Cross(Vector3D a, Vector3D b) => new(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
private static IEnumerable<SemanticValue> Flatten(SemanticValue root)
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index b3835443..5142823b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -301,7 +301,10 @@ public static class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.TemplateExpansion")).ToArray());
}
- var staticExpansion = CanonicalStaticAuthoring.Expand(templateExpansion.Source, staticDiagnostics);
+ var specializedBoundaries = ClosedBoundary2Authoring.Expand(templateExpansion.Source, staticDiagnostics);
+ if (specializedBoundaries is null)
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(SchemaDiagnostic).ToArray());
+ var staticExpansion = CanonicalStaticAuthoring.Expand(specializedBoundaries.Source, staticDiagnostics);
if (staticExpansion is null)
{
return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index 34951014..bbd502da 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -47,7 +47,12 @@ public sealed record FirmamentWireOperationReport(
double? TubeRadiusLimitMm = null, double? RawClosureRotationRadians = null,
double? AppliedDistributedCorrectionRadians = null, double? FinalClosureRotationErrorRadians = null,
double? KnotApproximationMaxErrorMm = null, double? KnotApproximationRmsErrorMm = null,
- double? ClosestParameter1 = null, double? ClosestParameter2 = null);
+ double? ClosestParameter1 = null, double? ClosestParameter2 = null,
+ FirmamentWireAxisDatum? AxisDatum = null);
+
+/// <summary>The actual winding axis, independent of the wire start tangent and part origin.</summary>
+public sealed record FirmamentWireAxisDatum(IReadOnlyList<double> Origin, IReadOnlyList<double> Direction,
+ IReadOnlyList<double> Radial, double ClearDiameterMm);
public sealed record FirmamentWireTerminalReport(
string Name, IReadOnlyList<double> Position, IReadOnlyList<double> Tangent, IReadOnlyList<double> Up, double DiameterMm);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
index 72308877..110cebd4 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
@@ -29,9 +29,14 @@ internal static class ClosedBoundary2Authoring
public static Result? Expand(string source, List<string> diagnostics)
{
+ // Template bodies have local names and unbound dimensions. Their selected
+ // specializations pass through this lowering after ordinary template binding.
+ var templates = FirmamentV2TemplateExpansion.DeclarationSpans(source, diagnostics);
+ bool InTemplate(int offset) => templates.Any(span => offset >= span.Start && offset < span.Start + span.Length);
var shapes = new List<Shape>(); var names = new HashSet<string>(StringComparer.Ordinal);
foreach (Match header in Header.Matches(source))
{
+ if (InTemplate(header.Index)) continue;
var open = source.IndexOf('{', header.Index); var close = Matching(source, open); var name = header.Groups["name"].Value;
if (close < 0) { diagnostics.Add(Prefix + "malformed:" + name); continue; }
if (!names.Add(name)) { diagnostics.Add(Prefix + "duplicate-name:" + name); continue; }
@@ -44,10 +49,10 @@ internal static class ClosedBoundary2Authoring
{
if (shape.LoweredSource is not null) changes.Add((shape.Start, shape.Length, shape.LoweredSource));
foreach (Match trace in Regex.Matches(source, $@"\b{Regex.Escape(shape.Declaration.Name)}\s*\|>\s*TraceLoop\b", RegexOptions.CultureInvariant))
- if (!Inside(trace.Index, shapes)) changes.Add((trace.Index, trace.Length, shape.TraceExpression));
+ if (!Inside(trace.Index, shapes) && !InTemplate(trace.Index)) changes.Add((trace.Index, trace.Length, shape.TraceExpression));
foreach (var member in shape.MemberMap)
foreach (Match reference in Regex.Matches(source, $@"\b{Regex.Escape(shape.Declaration.Name)}\s*\.\s*{Regex.Escape(member.Key)}\b", RegexOptions.CultureInvariant))
- if (!Inside(reference.Index, shapes)) changes.Add((reference.Index, reference.Length, member.Value));
+ if (!Inside(reference.Index, shapes) && !InTemplate(reference.Index)) changes.Add((reference.Index, reference.Length, member.Value));
}
foreach (var change in changes.OrderByDescending(x => x.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
return new(source, shapes.Select(x => x.Declaration).ToArray());
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 6b0d6e94..b364bd6c 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -352,6 +352,16 @@ public static class FirmamentV2Parser
}
source = templateExpansion.Source;
+ var specializedBoundaries = ClosedBoundary2Authoring.Expand(source, diagnostics);
+ if (specializedBoundaries is null)
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid);
+ }
+ source = specializedBoundaries.Source;
+ polygonExpansion = new(source, polygonExpansion.Boundaries.Concat(specializedBoundaries.Boundaries)
+ .DistinctBy(boundary => boundary.Name, StringComparer.Ordinal).ToArray());
+
var canonicalStaticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
if (canonicalStaticExpansion is null)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index d7c01994..54258156 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -347,6 +347,9 @@ internal static class FirmamentV2TemplateExpansion
return new(source, instantiations);
}
+ internal static IReadOnlyList<FirmamentV2SourceSpan> DeclarationSpans(string source, List<string> diagnostics)
+ => ParseDeclarations(source, diagnostics).Select(item => item.SourceSpan).ToArray();
+
private static ImmutableArray<TemplateDeclarationIr> ParseDeclarations(string source, List<string> diagnostics)
{
var result = ImmutableArray.CreateBuilder<TemplateDeclarationIr>(); var names = new HashSet<string>(StringComparer.Ordinal);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index 2374488f..a22651b3 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -701,7 +701,7 @@ public static class ProfileAuthoringParser
if (stages.Count == 2 && stages[1].Kind == PipelineStageKind.TraceLoop)
{
if (guides.TryGetValue(stages[0].Reference!, out var closedGuide) && closedGuide is LineArcFullCircle2D or LineArcFullEllipse2D)
- return [PipelineSegment(profile, loopName, "Boundary", closedGuide, $"concept:{profile.Frame ?? "XY"}.{stages[0].Reference}", stages[0].Reference!, false, 0, match.Index)];
+ return [PipelineSegment(profile, loopName, loopName == "Outer" ? "Boundary" : $"{loopName}.Boundary", closedGuide, $"concept:{profile.Frame ?? "XY"}.{stages[0].Reference}", stages[0].Reference!, false, 0, match.Index)];
if (!paths.TryGetValue(stages[0].Reference!, out var path))
{
diagnostics.Add($"firmament-profile-traceloop-not-loop:{stages[0].Reference}");
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs
index ed0a3b58..2900f914 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs
@@ -145,25 +145,27 @@ public static class ProfileExtrusionBRepPlanner
}
case LineArcFullCircle2D circle:
{
- sv0 = Vertex(circle.Center, false, segmentSource); sv1 = sv0; ev0 = Vertex(circle.Center, true, segmentSource); ev1 = ev0;
+ var seam = (circle.Center.X + circle.Radius, circle.Center.Y);
+ sv0 = Vertex(seam, false, segmentSource); sv1 = sv0; ev0 = Vertex(seam, true, segmentSource); ev1 = ev0;
var trim = new ParameterInterval(0, 2 * Math.PI);
- startEdge = Edge(prefix + ":edge:local-start", sv0, sv0, Curve(prefix + ":curve:local-start", CurveGeometry.FromCircle(new Circle3Curve(sv0.WorldPoint, frame.AxisZ, circle.Radius, frame.AxisX)), trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalStartBoundary);
- endEdge = Edge(prefix + ":edge:local-end", ev0, ev0, Curve(prefix + ":curve:local-end", CurveGeometry.FromCircle(new Circle3Curve(ev0.WorldPoint, frame.AxisZ, circle.Radius, frame.AxisX)), trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalEndBoundary);
- startLongitudinal = Vertical(circle.Center, sv0, ev0, segmentSource); endLongitudinal = startLongitudinal;
- sideSurface = SurfaceGeometry.FromCylinder(new CylinderSurface(sv0.WorldPoint, frame.AxisZ, circle.Radius, frame.AxisX));
+ startEdge = Edge(prefix + ":edge:local-start", sv0, sv0, Curve(prefix + ":curve:local-start", CurveGeometry.FromCircle(new Circle3Curve(frame.ToWorld(circle.Center, start), frame.AxisZ, circle.Radius, frame.AxisX)), trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalStartBoundary);
+ endEdge = Edge(prefix + ":edge:local-end", ev0, ev0, Curve(prefix + ":curve:local-end", CurveGeometry.FromCircle(new Circle3Curve(frame.ToWorld(circle.Center, end), frame.AxisZ, circle.Radius, frame.AxisX)), trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalEndBoundary);
+ startLongitudinal = Vertical(seam, sv0, ev0, segmentSource); endLongitudinal = startLongitudinal;
+ sideSurface = SurfaceGeometry.FromCylinder(new CylinderSurface(frame.ToWorld(circle.Center, start), frame.AxisZ, circle.Radius, frame.AxisX));
break;
}
case LineArcFullEllipse2D ellipse:
{
- sv0 = Vertex(ellipse.Center, false, segmentSource); sv1 = sv0; ev0 = Vertex(ellipse.Center, true, segmentSource); ev1 = ev0;
+ var seam = (ellipse.Center.X + ellipse.MajorRadius * Math.Cos(ellipse.RotationRadians), ellipse.Center.Y + ellipse.MajorRadius * Math.Sin(ellipse.RotationRadians));
+ sv0 = Vertex(seam, false, segmentSource); sv1 = sv0; ev0 = Vertex(seam, true, segmentSource); ev1 = ev0;
var trim = new ParameterInterval(0, 2 * Math.PI);
var localAxis = new Vector3D(Math.Cos(ellipse.RotationRadians), Math.Sin(ellipse.RotationRadians), 0);
var axis = Direction3D.Create(frame.ToWorldDirection(localAxis));
- var startEllipse = CurveGeometry.FromEllipse(new Ellipse3Curve(sv0.WorldPoint, frame.AxisZ, ellipse.MajorRadius, ellipse.MinorRadius, axis));
- var endEllipse = CurveGeometry.FromEllipse(new Ellipse3Curve(ev0.WorldPoint, frame.AxisZ, ellipse.MajorRadius, ellipse.MinorRadius, axis));
+ var startEllipse = CurveGeometry.FromEllipse(new Ellipse3Curve(frame.ToWorld(ellipse.Center, start), frame.AxisZ, ellipse.MajorRadius, ellipse.MinorRadius, axis));
+ var endEllipse = CurveGeometry.FromEllipse(new Ellipse3Curve(frame.ToWorld(ellipse.Center, end), frame.AxisZ, ellipse.MajorRadius, ellipse.MinorRadius, axis));
startEdge = Edge(prefix + ":edge:local-start", sv0, sv0, Curve(prefix + ":curve:local-start", startEllipse, trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalStartBoundary);
endEdge = Edge(prefix + ":edge:local-end", ev0, ev0, Curve(prefix + ":curve:local-end", endEllipse, trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalEndBoundary);
- startLongitudinal = Vertical(ellipse.Center, sv0, ev0, segmentSource); endLongitudinal = startLongitudinal;
+ startLongitudinal = Vertical(seam, sv0, ev0, segmentSource); endLongitudinal = startLongitudinal;
sideSurface = SurfaceGeometry.FromLinearExtrusion(new LinearExtrusionSurface(startEllipse, frame.AxisZ.ToVector() * (end - start)));
break;
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
index 7b31d21a..cc8d0a52 100644
--- a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
@@ -479,7 +479,12 @@ public static class WireFormReportFactory
operation is WireKnotPathAir knotError ? knotError.ApproximationError.MaxMm : null,
operation is WireKnotPathAir knotRms ? knotRms.ApproximationError.RmsMm : null,
operation is WireKnotPathAir knotT1 ? knotT1.Qualification.ClosestParameter1 : null,
- operation is WireKnotPathAir knotT2 ? knotT2.Qualification.ClosestParameter2 : null)).ToArray();
+ operation is WireKnotPathAir knotT2 ? knotT2.Qualification.ClosestParameter2 : null,
+ operation is WireAxisCoilAir datum ? new FirmamentWireAxisDatum(
+ [datum.AxisOrigin.X, datum.AxisOrigin.Y, datum.AxisOrigin.Z],
+ [datum.Axis.X, datum.Axis.Y, datum.Axis.Z],
+ [datum.StartRadial.X, datum.StartRadial.Y, datum.StartRadial.Z],
+ 2 * datum.RadiusMm - feature.DiameterMm) : null)).ToArray();
return new(feature.Name, feature.DiameterMm, feature.Material.Identity.FirmamentPath, feature.Operations.Count,
feature.Operations.Count(x => x is WireStraightAir), feature.Operations.Count(x => x is WireBendAir),
feature.TotalStraightLengthMm, feature.TotalBendLengthMm, feature.TotalWireLengthMm, built.VolumeMm3, built.MassKilograms,
diff --git a/Aetheris.slnx b/Aetheris.slnx
index 39e8d488..02b497ea 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -64,6 +64,10 @@
<Deploy />
</Project>
<Project Path="Aetheris.CLI/Aetheris.CLI.csproj" />
+ <Folder Name="/demos/">
+ <Project Path="demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj" />
+ <Project Path="demos/Aetheris.EditableV8/Aetheris.EditableV8.csproj" />
+ </Folder>
<Project Path="Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj" />
<Project Path="Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj" />
<Project Path="test-support/Aetheris.TestForgePack/Aetheris.TestForgePack.csproj" />
diff --git a/demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj b/demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj
new file mode 100644
index 00000000..6cd7f281
--- /dev/null
+++ b/demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj
@@ -0,0 +1,15 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <IsPackable>false</IsPackable>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
+ <PackageReference Include="xunit" Version="2.9.2" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
+ <Using Include="Xunit" />
+ <ProjectReference Include="../Aetheris.EditableV8/Aetheris.EditableV8.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/demos/Aetheris.EditableV8.Tests/EngineTests.cs b/demos/Aetheris.EditableV8.Tests/EngineTests.cs
new file mode 100644
index 00000000..de65db9c
--- /dev/null
+++ b/demos/Aetheris.EditableV8.Tests/EngineTests.cs
@@ -0,0 +1,66 @@
+using System.Text.Json;
+using Aetheris.EditableV8;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.EditableV8.Tests;
+
+public sealed class EngineTests
+{
+ [Fact]
+ public void RevisionRebuildsGeometryAndMotionWithoutChangingOccurrenceIdentity()
+ {
+ var baseline = new EngineAuthor(new()); var revised = new EngineAuthor(new(Stroke: 94));
+ var source = baseline.Engine(8); var revision = revised.Engine(8);
+ Assert.NotEqual(source, revision);
+ var a = baseline.Motion(); var b = revised.Motion();
+ Assert.Equal(a.Bindings.Select(x => x.Name), b.Bindings.Select(x => x.Name));
+ Assert.Equal(3, b.Spec.DeckHeight - a.Spec.DeckHeight);
+ Assert.Equal(3, b.Spec.CrankRadius - a.Spec.CrankRadius);
+ Assert.NotEqual(a.Spec.CrankcaseFloor, b.Spec.CrankcaseFloor);
+ var repeat = new EngineAuthor(new()); Assert.Equal(source, repeat.Engine(8));
+ Assert.Equal(JsonSerializer.Serialize(a), JsonSerializer.Serialize(repeat.Motion()));
+ EngineMotion.Validate(a); EngineMotion.Validate(b);
+ foreach (var motion in new[] { a, b }) foreach (var binding in motion.Bindings.Where(b => !b.Kind.EndsWith("Spring", StringComparison.Ordinal)))
+ {
+ var atZero = EngineMotion.Evaluate(motion, binding, 0);
+ var atCycle = EngineMotion.Evaluate(motion, binding, 720);
+ Assert.All(atZero.Zip(binding.Rest), p => Assert.InRange(double.Abs(p.First - p.Second), 0, 1e-10));
+ Assert.All(atZero.Zip(atCycle), p => Assert.InRange(double.Abs(p.First - p.Second), 0, 1e-10));
+ }
+ }
+
+ [Fact]
+ public void PhysicalEngineUsesInterfacePlacementAndDimensionalFits()
+ {
+ var engine = new EngineAuthor(new()); var source = engine.Engine(8);
+ var result = new AssemblyM1Pipeline().Compile(source, "editable-v8-test.firmament");
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ Assert.DoesNotContain("LegacyExplicit", source);
+ Assert.Equal(engine.Bindings.Count - 1, result.Ir!.Mates.Count);
+ Assert.Equal(32, result.Ir.FitResults.Count);
+ Assert.All(result.Geometry!.Artifact.MateResiduals, residual => Assert.True(residual.Passed));
+ var export = AssemblyDisplayMeshExporter.Export(result);
+ Assert.Equal(engine.Bindings.Count, export.Occurrences.Count(o => o.DefinitionId != null));
+ Assert.Equal(export.Occurrences.Count, export.Occurrences.Select(o => o.Id).Distinct().Count());
+ Assert.True(export.Definitions.Count < engine.Bindings.Count / 4);
+ var solved = EngineMotion.BindAssembly(engine.Motion(), result);
+ EngineMotion.ValidateSpringAlignment(solved);
+ foreach (var binding in solved.Bindings.Where(b => b.SpringAxis != null))
+ {
+ var atZero = EngineMotion.Evaluate(solved, binding, 0);
+ var atCycle = EngineMotion.Evaluate(solved, binding, 720);
+ Assert.All(atZero.Zip(atCycle), p => Assert.InRange(double.Abs(p.First - p.Second), 0, 1e-10));
+ }
+ }
+
+ [Fact]
+ public void InvalidDesignFailsBeforeArtifactGeneration()
+ {
+ Assert.Throws<ArgumentException>(() => new V8Spec(Stroke: double.NaN).Validate());
+ Assert.Throws<ArgumentException>(() => new V8Spec(BankAngle: 60).Validate());
+ var unsafeDesign = new EngineAuthor(new(Bore: 80, Stroke: 100, RodLength: 135));
+ unsafeDesign.Engine(8);
+ var failure = Assert.Throws<InvalidOperationException>(() => EngineMotion.Validate(unsafeDesign.Motion()));
+ Assert.Contains("engine-sweep-failed", failure.Message);
+ }
+}
diff --git a/demos/Aetheris.EditableV8/Aetheris.EditableV8.csproj b/demos/Aetheris.EditableV8/Aetheris.EditableV8.csproj
new file mode 100644
index 00000000..2c6073c7
--- /dev/null
+++ b/demos/Aetheris.EditableV8/Aetheris.EditableV8.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.EditableV8/EngineMotion.cs b/demos/Aetheris.EditableV8/EngineMotion.cs
new file mode 100644
index 00000000..8aec8ebd
--- /dev/null
+++ b/demos/Aetheris.EditableV8/EngineMotion.cs
@@ -0,0 +1,190 @@
+using Aetheris.Kernel.Core.Mechanisms;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Semantics;
+
+namespace Aetheris.EditableV8;
+
+public sealed record EngineCylinder(int Number, double BankRadians, double CrankpinRadians, double Z, double IgnitionDegrees);
+public sealed record EngineBinding(string Name, string Kind, int Cylinder, string Category, double[] Rest, string? OccurrenceId = null,
+ IReadOnlyList<int>? CylinderMembership = null, EngineSpringAxis? SpringAxis = null);
+public sealed record EngineSpringAxis(double[] LocalOrigin, double[] LocalDirection, string StemOccurrenceId);
+public sealed record EngineMotionManifest(string Schema, V8Spec Spec, int CycleDegrees, double CamRatio,
+ int[] FiringOrder, IReadOnlyList<EngineCylinder> Cylinders, IReadOnlyList<EngineBinding> Bindings);
+
+public static class EngineMotion
+{
+ public static EngineMotionManifest BindAssembly(EngineMotionManifest motion, AssemblyM1CompilationResult assembly)
+ {
+ if (!assembly.IsSuccess) throw new ArgumentException("engine-motion-unqualified-assembly");
+ if (assembly.Ir!.FitResults.Any(f => !f.Compatible)) throw new ArgumentException("engine-motion-incompatible-interface-fit");
+ var instances = assembly.Ir!.Instances.ToDictionary(i => i.Path.Segments.Last(), StringComparer.Ordinal);
+ var zShift = instances["MainJournal1"].ResolvedTransform!.Matrix[14] - motion.Bindings.Single(b => b.Name == "MainJournal1").Rest[14];
+ return motion with {
+ Cylinders = motion.Cylinders.Select(c => c with { Z = c.Z + zShift }).ToArray(),
+ Bindings = motion.Bindings.Select(b => {
+ var instance = instances[b.Name]; EngineSpringAxis? springAxis = null;
+ if (b.Kind.EndsWith("Spring", StringComparison.Ordinal))
+ {
+ if (!instance.SemanticRoot.ExposedMembers["Winding"].ExposedMembers["Axis"].TryBinding<ExactAxisBinding>(out var axis))
+ throw new InvalidOperationException("engine-spring-axis-missing:" + b.Name);
+ springAxis = new([axis.OriginX, axis.OriginY, axis.OriginZ], [axis.DirectionX, axis.DirectionY, axis.DirectionZ],
+ instances[b.Name.Replace("Spring", "Stem", StringComparison.Ordinal)].StableId);
+ }
+ return b with { OccurrenceId = instance.StableId, Rest = instance.ResolvedTransform!.Matrix.ToArray(), SpringAxis = springAxis };
+ }).ToArray()
+ };
+ }
+
+ public static double[] Evaluate(EngineMotionManifest manifest, EngineBinding binding, double degrees)
+ {
+ if (!double.IsFinite(degrees) || binding.Rest.Length != 16 || binding.Rest.Any(v => !double.IsFinite(v)))
+ throw new ArgumentException("engine-motion-invalid-transform-or-angle");
+ if (binding.Kind is not ("Crank" or "Cam" or "Fixed" or "Rod" or "Piston" or "Intake" or "Exhaust" or "IntakeSpring" or "ExhaustSpring"))
+ throw new ArgumentException("engine-motion-unknown-kind:" + binding.Kind);
+ var transform = binding.Rest.ToArray();
+ var angle = degrees * double.Pi / 180;
+ if (binding.Kind is "Crank" or "Cam")
+ {
+ var turn = binding.Kind == "Cam" ? PrescribedMotion.AngularRatio(angle, manifest.CamRatio) : angle;
+ var s = double.Sin(turn); var c = double.Cos(turn);
+ for (var i = 0; i < 12; i += 4)
+ {
+ transform[i] = c * binding.Rest[i] + s * binding.Rest[i + 1];
+ transform[i + 1] = -s * binding.Rest[i] + c * binding.Rest[i + 1];
+ }
+ if (binding.Kind == "Crank")
+ {
+ transform[12] = c * binding.Rest[12] + s * binding.Rest[13];
+ transform[13] = -s * binding.Rest[12] + c * binding.Rest[13];
+ }
+ return transform;
+ }
+ if (binding.Kind == "Fixed") return transform;
+ var cylinder = manifest.Cylinders.Single(c => c.Number == binding.Cylinder);
+ var mechanism = new SliderCrank(manifest.Spec.CrankRadius, manifest.Spec.RodLength);
+ var pose = mechanism.Evaluate(angle, cylinder.BankRadians, cylinder.CrankpinRadians);
+ if (binding.Kind == "Rod")
+ {
+ var s = double.Sin(pose.RodAngleRadians); var c = double.Cos(pose.RodAngleRadians);
+ return [c,-s,0,0, s,c,0,0, 0,0,1,0, pose.CrankPin.X,pose.CrankPin.Y,cylinder.Z,1];
+ }
+ double displacement;
+ if (binding.Kind == "Piston")
+ displacement = pose.PistonPositionMm - mechanism.Evaluate(0, cylinder.BankRadians, cylinder.CrankpinRadians).PistonPositionMm;
+ else
+ {
+ var intake = binding.Kind.StartsWith("Intake", StringComparison.Ordinal);
+ var opening = intake ? manifest.Spec.IntakeOpeningDegrees : manifest.Spec.ExhaustOpeningDegrees;
+ var lift = PrescribedMotion.ValveLift(degrees - cylinder.IgnitionDegrees, opening, manifest.Spec.ValveDurationDegrees, manifest.Spec.ValveLift, manifest.CycleDegrees);
+ var initial = PrescribedMotion.ValveLift(-cylinder.IgnitionDegrees, opening, manifest.Spec.ValveDurationDegrees, manifest.Spec.ValveLift, manifest.CycleDegrees);
+ displacement = -(lift - initial);
+ if (binding.Kind.EndsWith("Spring", StringComparison.Ordinal))
+ {
+ // Compress along the solved winding axis, about its actual seating origin.
+ // The coil's source-local Z axis need not coincide with its winding axis.
+ var datum = binding.SpringAxis ?? throw new InvalidOperationException("engine-spring-axis-missing:" + binding.Name);
+ var rest = Transform3D.FromRowMajor(binding.Rest);
+ var origin = rest.Apply(new Point3D(datum.LocalOrigin[0], datum.LocalOrigin[1], datum.LocalOrigin[2]));
+ var direction = rest.Apply(new Vector3D(datum.LocalDirection[0], datum.LocalDirection[1], datum.LocalDirection[2]));
+ direction /= direction.Length;
+ var scale = (manifest.Spec.SpringFreeHeight - lift) / (manifest.Spec.SpringFreeHeight - initial);
+ for (var i = 0; i < 16; i += 4)
+ {
+ var vector = new Vector3D(transform[i], transform[i + 1], transform[i + 2]);
+ var relative = i == 12 ? vector - new Vector3D(origin.X, origin.Y, origin.Z) : vector;
+ vector += direction * ((scale - 1) * relative.Dot(direction));
+ transform[i] = vector.X; transform[i + 1] = vector.Y; transform[i + 2] = vector.Z;
+ }
+ return transform;
+ }
+ }
+ transform[12] += double.Sin(cylinder.BankRadians) * displacement;
+ transform[13] += double.Cos(cylinder.BankRadians) * displacement;
+ return transform;
+ }
+
+ public static object ValidateSpringAlignment(EngineMotionManifest manifest)
+ {
+ double distance = 0, angle = 0, seatDrift = 0; var count = 0;
+ static Vector3D Apply(double[] m, double[] v, bool point) => new(
+ v[0]*m[0]+v[1]*m[4]+v[2]*m[8]+(point?m[12]:0),
+ v[0]*m[1]+v[1]*m[5]+v[2]*m[9]+(point?m[13]:0),
+ v[0]*m[2]+v[1]*m[6]+v[2]*m[10]+(point?m[14]:0));
+ foreach (var spring in manifest.Bindings.Where(b => b.SpringAxis != null))
+ {
+ var datum = spring.SpringAxis!;
+ var stem = manifest.Bindings.Single(b => b.OccurrenceId == datum.StemOccurrenceId);
+ var seat = Apply(spring.Rest, datum.LocalOrigin, true);
+ for (var degree = 0; degree <= 720; degree++)
+ {
+ var springMatrix = Evaluate(manifest, spring, degree); var stemMatrix = Evaluate(manifest, stem, degree);
+ var origin = Apply(springMatrix, datum.LocalOrigin, true);
+ var a = Apply(springMatrix, datum.LocalDirection, false); a /= a.Length;
+ var b = Apply(stemMatrix, [0,0,1], false); b /= b.Length;
+ var stemOrigin = Apply(stemMatrix, [0,0,0], true);
+ distance = double.Max(distance, (origin - stemOrigin).Cross(b).Length);
+ angle = double.Max(angle, double.Atan2(a.Cross(b).Length, a.Dot(b)));
+ seatDrift = double.Max(seatDrift, (origin - seat).Length); count++;
+ }
+ }
+ if (count != manifest.Cylinders.Count * 2 * 721 || distance > 1e-9 || angle > 1e-9 || seatDrift > 1e-9)
+ throw new InvalidOperationException($"engine-spring-axis-sweep-failed:distance={distance};angle={angle};seat={seatDrift};samples={count}");
+ return new { status = "pass", samples = count, maximumAxisDistanceMm = distance, maximumAxisAngleRadians = angle, maximumSeatDriftMm = seatDrift };
+ }
+
+ public static object Validate(EngineMotionManifest manifest)
+ {
+ double rod = 0, axis = 0, radius = 0, headClearance = double.PositiveInfinity, valveClearance = double.PositiveInfinity;
+ double rodSleeve = double.PositiveInfinity, rodFloor = double.PositiveInfinity;
+ var mechanism = new SliderCrank(manifest.Spec.CrankRadius, manifest.Spec.RodLength);
+ foreach (var cylinder in manifest.Cylinders)
+ for (var degree = 0; degree <= 720; degree++)
+ {
+ var pose = mechanism.Evaluate(degree * double.Pi / 180, cylinder.BankRadians, cylinder.CrankpinRadians);
+ rod = double.Max(rod, double.Abs((pose.WristPin - pose.CrankPin).Length - manifest.Spec.RodLength));
+ axis = double.Max(axis, pose.WristPin.Cross(pose.BoreAxis).Length);
+ radius = double.Max(radius, double.Abs(pose.CrankPin.Length - manifest.Spec.CrankRadius));
+ var pistonTop = pose.PistonPositionMm + manifest.Spec.PistonCompressionHeight;
+ headClearance = double.Min(headClearance, manifest.Spec.DeckHeight + 8 - pistonTop);
+ var lift = double.Max(PrescribedMotion.ValveLift(degree - cylinder.IgnitionDegrees, 360, 180, manifest.Spec.ValveLift),
+ PrescribedMotion.ValveLift(degree - cylinder.IgnitionDegrees, 180, 180, manifest.Spec.ValveLift));
+ valveClearance = double.Min(valveClearance, manifest.Spec.DeckHeight + 4 - lift - pistonTop);
+ var corners = new[] { (-26d, -24d), (26d, -24d), (26d, manifest.Spec.RodLength + 24), (-26d, manifest.Spec.RodLength + 24) }
+ .Select(p => (X: pose.CrankPin.X + double.Cos(pose.RodAngleRadians) * p.Item1 + double.Sin(pose.RodAngleRadians) * p.Item2,
+ Y: pose.CrankPin.Y - double.Sin(pose.RodAngleRadians) * p.Item1 + double.Cos(pose.RodAngleRadians) * p.Item2)).ToArray();
+ rodFloor = double.Min(rodFloor, corners.Min(p => p.Y) - manifest.Spec.CrankcaseFloor);
+ var projected = corners.Select(p => (Axial: p.X * pose.BoreAxis.X + p.Y * pose.BoreAxis.Y,
+ Lateral: p.X * pose.BoreAxis.Y - p.Y * pose.BoreAxis.X)).ToList();
+ var sleeveBottom = manifest.Spec.DeckHeight - manifest.Spec.Stroke - 29;
+ var clipped = new List<(double Axial, double Lateral)>();
+ for (var i = 0; i < projected.Count; i++)
+ {
+ var a = projected[i]; var b = projected[(i + 1) % projected.Count];
+ if (a.Axial >= sleeveBottom) clipped.Add(a);
+ if ((a.Axial >= sleeveBottom) != (b.Axial >= sleeveBottom))
+ {
+ var t = (sleeveBottom - a.Axial) / (b.Axial - a.Axial);
+ clipped.Add((sleeveBottom, a.Lateral + t * (b.Lateral - a.Lateral)));
+ }
+ }
+ if (clipped.Count > 0)
+ rodSleeve = double.Min(rodSleeve, manifest.Spec.Bore / 2 - double.Sqrt(clipped.Max(p => p.Lateral * p.Lateral) + 6 * 6));
+ }
+ if (rod > 1e-9 || axis > 1e-9 || radius > 1e-9 || headClearance < 1 || valveClearance < 1 || rodSleeve < 1 || rodFloor < 1)
+ throw new InvalidOperationException($"engine-sweep-failed:rod={rod};axis={axis};radius={radius};head={headClearance};valve={valveClearance};rod-sleeve={rodSleeve};rod-floor={rodFloor}");
+ foreach (var cylinder in manifest.Cylinders)
+ {
+ var ignition = mechanism.Evaluate(cylinder.IgnitionDegrees * double.Pi / 180, cylinder.BankRadians, cylinder.CrankpinRadians);
+ if (double.Abs(ignition.PistonPositionMm - manifest.Spec.CrankRadius - manifest.Spec.RodLength) > 1e-9)
+ throw new InvalidOperationException("engine-firing-not-at-tdc:" + cylinder.Number);
+ }
+ return new { status = "pass", samples = 721 * manifest.Cylinders.Count, rodClosureMm = rod, pistonAxisMm = axis, crankRadiusMm = radius,
+ headClearanceMm = headClearance, valvePistonClearanceMm = valveClearance, camAdvanceDegrees = 720 * manifest.CamRatio,
+ rodSleeveClearanceMm = rodSleeve, rodFloorClearanceMm = rodFloor,
+ crankWebFloorClearanceMm = -manifest.Spec.CrankWebEnvelope - manifest.Spec.CrankcaseFloor,
+ pairedRodAxialClearanceMm = 4, rodWebAxialClearanceMm = 2,
+ rodSupportAxialClearanceMm = manifest.Spec.CylinderSpacing / 2 - 8 - 14,
+ clearanceScope = "parallel crown/head/valve planes, clipped conservative rod box against own bore, rod floor, web swept disk vs floor, axial rod/rod/web/support slabs; other interference not certified" };
+ }
+}
diff --git a/demos/Aetheris.EditableV8/Prepare-Viewer.ps1 b/demos/Aetheris.EditableV8/Prepare-Viewer.ps1
new file mode 100644
index 00000000..f5401d1b
--- /dev/null
+++ b/demos/Aetheris.EditableV8/Prepare-Viewer.ps1
@@ -0,0 +1,13 @@
+[CmdletBinding()]
+param([string]$Output = 'artifacts/local/demos/editable-v8')
+$ErrorActionPreference = 'Stop'
+$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
+$destination = [IO.Path]::GetFullPath($Output)
+$three = Join-Path $repo 'aetheris.client/node_modules/three'
+if (-not (Test-Path -LiteralPath "$three/build/three.module.js")) { throw 'Run npm ci --prefix aetheris.client to install the lockfile-pinned Three.js dependency.' }
+New-Item -ItemType Directory -Force -Path "$destination/vendor" | Out-Null
+Copy-Item -LiteralPath "$three/build/three.module.js", "$three/build/three.core.js", "$three/examples/jsm/controls/OrbitControls.js" -Destination "$destination/vendor"
+Copy-Item -LiteralPath "$three/LICENSE" -Destination "$destination/vendor/three.LICENSE"
+Copy-Item -Path "$PSScriptRoot/web/*" -Destination $destination
+Copy-Item -LiteralPath "$repo/Aetheris.Kernel.Core/Mechanisms/Web/prescribed-motion.mjs" -Destination $destination
+Write-Host "Viewer prepared: $destination/index.html"
diff --git a/demos/Aetheris.EditableV8/Program.cs b/demos/Aetheris.EditableV8/Program.cs
new file mode 100644
index 00000000..1d0525a3
--- /dev/null
+++ b/demos/Aetheris.EditableV8/Program.cs
@@ -0,0 +1,403 @@
+using System.Globalization;
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Mechanisms;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.EditableV8;
+
+public sealed record V8Spec(double Bore = 90, double Stroke = 88, double RodLength = 145,
+ double BankAngle = 90, double CylinderSpacing = 110, double ValveLift = 9)
+{
+ public double CrankRadius => Stroke / 2;
+ public double PistonCompressionHeight => 40;
+ public double DeckHeight => RodLength + CrankRadius + PistonCompressionHeight + 3;
+ public double CrankWebEnvelope => double.Sqrt(30 * 30 + double.Pow(CrankRadius + 30, 2));
+ public double CrankcaseFloor => -CrankWebEnvelope - 6;
+ public double SpringFreeHeight => 36;
+ public double IntakeOpeningDegrees => 360;
+ public double ExhaustOpeningDegrees => 180;
+ public double ValveDurationDegrees => 180;
+ public void Validate()
+ {
+ if (new[] { Bore, Stroke, RodLength, BankAngle, CylinderSpacing, ValveLift }.Any(v => !double.IsFinite(v))
+ || Bore < 80 || Bore > 100 || Stroke < 70 || Stroke > 100 || RodLength < 135 || RodLength > 170
+ || BankAngle != 90 || CylinderSpacing < Bore + 16 || ValveLift < 1 || ValveLift > 10)
+ throw new ArgumentException("engine-spec-outside-admitted-envelope");
+ }
+}
+
+public static class Program
+{
+ public static int Main(string[] args)
+ {
+ try
+ {
+ var destination = Path.GetFullPath(args.Length > 0 ? args[0] : "artifacts/local/demos/editable-v8");
+ // Preserve the last successful artifact set when any generation stage fails.
+ var output = Path.Combine(destination, ".generation");
+ var performance = new List<object>();
+ var spec = args.Length > 1 ? JsonSerializer.Deserialize<V8Spec>(File.ReadAllText(args[1]))! : new V8Spec();
+ spec.Validate();
+ Directory.CreateDirectory(output);
+ var author = new EngineAuthor(spec);
+ var source = author.StageA();
+ var path = Path.Combine(output, "stage-a.firmament");
+ File.WriteAllText(path, source);
+ File.WriteAllText(Path.Combine(output, "spec.json"), JsonSerializer.Serialize(spec, new JsonSerializerOptions { WriteIndented = true }));
+ var result = new AssemblyM1Pipeline().CompileFile(path);
+ foreach (var diagnostic in result.Diagnostics) Console.WriteLine($"{diagnostic.Code}: {diagnostic.Message}");
+ if (!result.IsSuccess) return 1;
+ var step = AssemblyIrAp242Exporter.Export(result);
+ if (!step.IsSuccess) throw new InvalidOperationException(string.Join("\n", step.Diagnostics.Select(d => d.Message)));
+ File.WriteAllText(Path.Combine(output, "stage-a.step"), step.Value);
+ var mesh = AssemblyDisplayMeshExporter.Export(result);
+ File.WriteAllText(Path.Combine(output, "stage-a.mesh.json"), AssemblyDisplayMeshExporter.Serialize(mesh));
+ Console.WriteLine($"Stage A: {result.Geometry!.DefinitionBodies.Count} definitions, {result.Geometry.InstanceBodies.Count} occurrences.");
+ var stageBPath = Path.Combine(output, "stage-b.firmament");
+ File.WriteAllText(stageBPath, new EngineAuthor(spec).StageA(withValves: true));
+ var stageB = new AssemblyM1Pipeline().CompileFile(stageBPath);
+ if (!stageB.IsSuccess) throw new InvalidOperationException(string.Join("\n", stageB.Diagnostics.Select(d => d.Code + ": " + d.Message)));
+ File.WriteAllText(Path.Combine(output, "stage-b.mesh.json"), AssemblyDisplayMeshExporter.Serialize(AssemblyDisplayMeshExporter.Export(stageB)));
+ Console.WriteLine($"Stage B: {stageB.Geometry!.DefinitionBodies.Count} definitions, {stageB.Geometry.InstanceBodies.Count} occurrences.");
+ foreach (var (label, cylinders, design) in new[] { ("stage-c", 4, spec), ("baseline", 8, spec), ("revised", 8, spec with { Stroke = spec.Stroke + 6 }) })
+ {
+ design.Validate();
+ var engine = new EngineAuthor(design);
+ var file = Path.Combine(output, label + ".firmament");
+ File.WriteAllText(file, engine.Engine(cylinders));
+ var motion = engine.Motion();
+ var watch = Stopwatch.StartNew();
+ var validation = EngineMotion.Validate(motion);
+ var sweepMs = watch.Elapsed.TotalMilliseconds; watch.Restart();
+ var built = new AssemblyM1Pipeline().CompileFile(file);
+ if (!built.IsSuccess) throw new InvalidOperationException(string.Join("\n", built.Diagnostics.Select(d => d.Code + ": " + d.Message)));
+ var compileMs = watch.Elapsed.TotalMilliseconds; watch.Restart();
+ var display = AssemblyDisplayMeshExporter.Export(built);
+ var meshMs = watch.Elapsed.TotalMilliseconds;
+ motion = EngineMotion.BindAssembly(motion, built);
+ var springValidation = EngineMotion.ValidateSpringAlignment(motion);
+ File.WriteAllText(Path.Combine(output, label + ".spring-validation.json"), JsonSerializer.Serialize(springValidation));
+ File.WriteAllText(Path.Combine(output, label + ".assembly.json"), JsonSerializer.Serialize(new { instances = built.Ir!.Instances.Count, mates = built.Ir.Mates.Count,
+ fits = built.Ir.FitResults, residuals = built.Geometry!.Artifact.MateResiduals, authority = built.Ir.Instances.Select(i => new { i.StableId, i.PlacementAuthority }) }, new JsonSerializerOptions { WriteIndented = true }));
+ File.WriteAllText(Path.Combine(output, label + ".mesh.json"), AssemblyDisplayMeshExporter.Serialize(display));
+ watch.Restart();
+ var export = AssemblyIrAp242Exporter.Export(built);
+ var stepMs = watch.Elapsed.TotalMilliseconds;
+ if (!export.IsSuccess) throw new InvalidOperationException(string.Join("\n", export.Diagnostics.Select(d => d.Message)));
+ File.WriteAllText(Path.Combine(output, label + ".step"), export.Value);
+ var json = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true };
+ File.WriteAllText(Path.Combine(output, label + ".motion.json"), JsonSerializer.Serialize(motion, json));
+ File.WriteAllText(Path.Combine(output, label + ".validation.json"), JsonSerializer.Serialize(validation, json));
+ var samples = new[] { 0d, 45d, 90d, 180d, 270d, 360d, 450d, 540d, 630d, 720d }
+ .Select(degrees => new { degrees, transforms = motion.Bindings.Select(binding => new { id = binding.OccurrenceId, matrix = EngineMotion.Evaluate(motion, binding, degrees) }).ToArray() }).ToArray();
+ File.WriteAllText(Path.Combine(output, label + ".samples.json"), JsonSerializer.Serialize(samples, json));
+ performance.Add(new { label, compileMs, meshMs, stepMs, sweepMs, meshBytes = new FileInfo(Path.Combine(output, label + ".mesh.json")).Length,
+ definitions = display.Definitions.Count, occurrences = display.Occurrences.Count, triangles = display.Definitions.Sum(d => d.Indices.Length / 3) });
+ Console.WriteLine($"{label}: {display.Definitions.Count} definitions, {display.Occurrences.Count} occurrences, {display.Definitions.Sum(d => d.Indices.Length / 3)} triangles; {JsonSerializer.Serialize(validation)}");
+ }
+ File.WriteAllText(Path.Combine(output, "performance.json"), JsonSerializer.Serialize(performance, new JsonSerializerOptions { WriteIndented = true }));
+ var files = Directory.GetFiles(output).Where(f => Path.GetFileName(f) != "hashes.json").OrderBy(Path.GetFileName, StringComparer.Ordinal).ToArray();
+ var hashes = files.Where(f => Path.GetFileName(f) != "performance.json").ToDictionary(f => Path.GetFileName(f)!, 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"))) File.Copy(file, Path.Combine(destination, Path.GetFileName(file)), overwrite: true);
+ return 0;
+ }
+ catch (Exception error) { Console.Error.WriteLine(error); return 1; }
+ }
+}
+
+public sealed class EngineAuthor(V8Spec spec)
+{
+ private readonly StringBuilder definitions = new();
+ private readonly Dictionary<string, string> references = new(StringComparer.Ordinal);
+ private readonly Dictionary<string, string> partDefinitions = new(StringComparer.Ordinal);
+ public List<EngineBinding> Bindings { get; } = [];
+ public List<EngineCylinder> Cylinders { get; } = [];
+ private static string N(double value) => value.ToString("G17", CultureInfo.InvariantCulture);
+
+ private string Define(string name, string body, string parameters, string arguments)
+ {
+ definitions.AppendLine($"Template < {parameters} > Struct {name} {{ {body} }}");
+ var reference = name + "<" + arguments + ">";
+ references.Add(name, reference);
+ return reference;
+ }
+
+ private string Ring(string name, double outer, double inner, double height)
+ => Define(name, """
+ 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: Zmin To: Zmax }
+ """, "Rout: Length, Rin: Length, Zmin: Length, Zmax: Length", $"Rout: {N(outer)}mm, Rin: {N(inner)}mm, Zmin: {N(-height / 2)}mm, Zmax: {N(height / 2)}mm");
+
+ private string Disc(string name, double radius, double height)
+ => Define(name, """
+ Circle2 Outside { Center: [0mm,0mm] Radius: R }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Extrude Body { Profile: Section From: Zmin To: Zmax }
+ """, "R: Length, Zmin: Length, Zmax: Length", $"R: {N(radius)}mm, Zmin: {N(-height / 2)}mm, Zmax: {N(height / 2)}mm");
+
+ private string Plate(string name, double width, double height, double centerY, double depth, params (double Y, double Diameter)[] holes)
+ {
+ var cuts = string.Join("\n", holes.Select((hole, i) => $"Hole<Shaft> Pin{i} {{ On: +Z Center: Point2(0mm,HoleY{i}) Diameter: HoleD{i} End: ThroughAll }}"));
+ var parameters = "W: Length, H: Length, C: Length, Zmin: Length, Zmax: Length" + string.Concat(holes.Select((_,i) => $", HoleY{i}: Length, HoleD{i}: Length"));
+ var arguments = $"W: {N(width)}mm, H: {N(height)}mm, C: {N(centerY)}mm, Zmin: {N(-depth / 2)}mm, Zmax: {N(depth / 2)}mm" + string.Concat(holes.Select((hole,i) => $", HoleY{i}: {N(hole.Y)}mm, HoleD{i}: {N(hole.Diameter)}mm"));
+ return Define(name, $$"""
+ Rect2 Outside { Center: [0mm,C] Size: [W,H] }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Compose Body {
+ Base Stock { Profile: Section From: Zmin To: Zmax Role: Stock }
+ {{cuts}}
+ }
+ """, parameters, arguments);
+ }
+
+ private void Part(string name, string definition, double x, double y, double z, double angle = 0, bool axialY = false,
+ string motion = "Fixed", int cylinder = 0, string category = "Metal")
+ {
+ var s = double.Sin(angle); var c = double.Cos(angle);
+ double[] transform = axialY
+ ? [c,-s,0,0, 0,0,-1,0, s,c,0,0, x,y,z,1]
+ : [c,-s,0,0, s,c,0,0, 0,0,1,0, x,y,z,1];
+ Bindings.Add(new(name, motion, cylinder, category, transform));
+ partDefinitions.Add(name, definition);
+ }
+
+ public string StageA(bool withValves = false)
+ {
+ var pose = new SliderCrank(spec.CrankRadius, spec.RodLength).Evaluate(0);
+ var r = spec.CrankRadius;
+ var rod = Define("ConnectingRod", """
+ Polygon2<Trapezoid> Outside { Center: [0mm,C] BottomWidth: 52mm TopWidth: 28mm Height: H }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Compose Body {
+ Base Stock { Profile: Section From: -6mm To: 6mm Role: Stock }
+ Hole<Shaft> BigEnd { On: +Z Center: Point2(0mm,0mm) Diameter: 44.4mm End: ThroughAll }
+ Hole<Shaft> SmallEnd { On: +Z Center: Point2(0mm,L) Diameter: 16.4mm End: ThroughAll }
+ }
+ """, "L: Length, H: Length, C: Length", $"L: {N(spec.RodLength)}mm, H: {N(spec.RodLength + 48)}mm, C: {N(spec.RodLength / 2)}mm");
+ var crown = Disc("PistonCrown", spec.Bore / 2 - .3, 15);
+ var lug = Plate("PistonLug", 24, 37, 6.5, 6, (0, 16.4));
+ var pin = Disc("WristPin", 8, 44);
+ var sleeve = Ring("CylinderSleeve", spec.Bore / 2 + 6, spec.Bore / 2, spec.Stroke + 29);
+ var journal = Disc("Crankpin", 22, 26);
+ var web = Plate("CrankWeb", 60, r + 60, r / 2, 12);
+ var main = Disc("MainJournal", 25, 20);
+ Part("Rod1", rod, pose.CrankPin.X, pose.CrankPin.Y, 0, pose.RodAngleRadians);
+ Part("Piston1", crown, 0, pose.PistonPositionMm + 32.5, 0, axialY: true);
+ Part("PistonLug1A", lug, 0, pose.PistonPositionMm, -16);
+ Part("PistonLug1B", lug, 0, pose.PistonPositionMm, 16);
+ Part("WristPin1", pin, 0, pose.PistonPositionMm, 0);
+ Part("Cylinder1", sleeve, 0, spec.DeckHeight - (spec.Stroke + 29) / 2, 0, axialY: true);
+ Part("Crankpin1", journal, 0, r, 0);
+ Part("CrankWeb1A", web, 0, 0, -19);
+ Part("CrankWeb1B", web, 0, 0, 19);
+ Part("MainJournal1", main, 0, 0, -35);
+ Part("MainJournal2", main, 0, 0, 35);
+ if (withValves)
+ {
+ var head = Plate("CylinderHead", spec.Bore + 12, 70, 0, 10, (-20, 8.4), (20, 8.4));
+ Part("Head1", head, 0, spec.DeckHeight + 13, 0, axialY: true);
+ var intake = Disc("IntakeValve", 16, 4);
+ var exhaust = Disc("ExhaustValve", 14, 4);
+ var stem = Disc("ValveStem", 4, 60);
+ var retainer = Ring("SpringRetainer", 12, 4.2, 3);
+ var spring = Define("ValveSpring", """
+ WireForm Spring {
+ Diameter: 2mm
+ Material: Standard.Materials.StainlessSteel.304_Annealed
+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }
+ AxisCoil Winding { Radius: 9mm; Turns: 6; Pitch: P; Handedness: RightHanded; StartPhase: 0deg }
+ }
+ """, "P: Length", "P: 6mm");
+ foreach (var (name, offset, valve) in new[] { ("Intake", -20d, intake), ("Exhaust", 20d, exhaust) })
+ {
+ Part(name + "Valve1", valve, 0, spec.DeckHeight + 6, offset, axialY: true);
+ Part(name + "Stem1", stem, 0, spec.DeckHeight + 38, offset, axialY: true);
+ Part(name + "Retainer1", retainer, 0, spec.DeckHeight + 58.5, offset, axialY: true);
+ Part(name + "Spring1", spring, 0, spec.DeckHeight + 20, offset, axialY: true);
+ }
+ }
+ return MatedAssembly("SliderCrankStageA");
+ }
+
+ public string Engine(int cylinderCount)
+ {
+ if (cylinderCount is not (4 or 8)) throw new ArgumentOutOfRangeException(nameof(cylinderCount));
+ // Share exactly the same admitted part catalog as the independently built single-cylinder stage.
+ StageA(withValves: true);
+ Bindings.Clear(); partDefinitions.Clear();
+ var skirt = Ring("PistonSkirt", spec.Bore / 2 - .3, spec.Bore / 2 - 4.3, 25);
+ var compressedSpring = Define("CompressedValveSpring", $$"""
+ WireForm Spring {
+ Diameter: 2mm
+ Material: Standard.Materials.StainlessSteel.304_Annealed
+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }
+ AxisCoil Winding { Radius: 9mm; Turns: 6; Pitch: P; Handedness: RightHanded; StartPhase: 0deg }
+ }
+ """, "P: Length", $"P: {N((36 - spec.ValveLift) / 6)}mm");
+ var phases = new[] { 45d, 135d, 315d, 225d };
+ var firing = new[] { 1, 5, 7, 3, 6, 8, 4, 2 };
+ for (var station = 0; station < 4; station++)
+ foreach (var bank in cylinderCount == 8 ? new[] { 1, -1 } : new[] { 1 })
+ {
+ var number = 2 * station + (bank == 1 ? 1 : 2);
+ var b = bank * spec.BankAngle / 2 * double.Pi / 180;
+ var p = phases[station] * double.Pi / 180;
+ var z = station * spec.CylinderSpacing + bank * 8;
+ var ignition = Array.IndexOf(firing, number) * 90d;
+ Cylinders.Add(new(number, b, p, z, ignition));
+ var pose = new SliderCrank(spec.CrankRadius, spec.RodLength).Evaluate(0, b, p);
+ void OnAxis(string name, string definition, double distance, double offsetZ = 0, bool axial = true, string motion = "Fixed", string category = "Metal")
+ => Part(name + number, references[definition], double.Sin(b) * distance, double.Cos(b) * distance, z + offsetZ, b, axial, motion, number, category);
+ Part("Rod" + number, references["ConnectingRod"], pose.CrankPin.X, pose.CrankPin.Y, z, pose.RodAngleRadians, motion: "Rod", cylinder: number, category: "Rod");
+ OnAxis("Piston", "PistonCrown", pose.PistonPositionMm + 32.5, motion: "Piston", category: "Piston");
+ OnAxis("PistonSkirt", "PistonSkirt", pose.PistonPositionMm + 12.5, motion: "Piston", category: "Piston");
+ OnAxis("PistonLugA", "PistonLug", pose.PistonPositionMm, -16, false, "Piston");
+ OnAxis("PistonLugB", "PistonLug", pose.PistonPositionMm, 16, false, "Piston");
+ OnAxis("WristPin", "WristPin", pose.PistonPositionMm, axial: false, motion: "Piston");
+ OnAxis("Cylinder", "CylinderSleeve", spec.DeckHeight - (spec.Stroke + 29) / 2, category: "Block");
+ OnAxis("Head", "CylinderHead", spec.DeckHeight + 13, category: "Head");
+ foreach (var (name, offset) in new[] { ("Intake", -20d), ("Exhaust", 20d) })
+ {
+ var lift = PrescribedMotion.ValveLift(-ignition, name == "Intake" ? 360 : 180, 180, spec.ValveLift);
+ OnAxis(name + "Valve", name + "Valve", spec.DeckHeight + 6 - lift, offset, motion: name, category: name);
+ OnAxis(name + "Stem", "ValveStem", spec.DeckHeight + 38 - lift, offset, motion: name);
+ OnAxis(name + "Retainer", "SpringRetainer", spec.DeckHeight + 58.5 - lift, offset, motion: name);
+ OnAxis(name + "Spring", lift > 0 ? "CompressedValveSpring" : "ValveSpring", spec.DeckHeight + 20, offset, motion: name + "Spring", category: "Spring");
+ }
+ }
+ var crankpin = Disc("PairedCrankpin", 22, 32);
+ var main = Disc("LongMainJournal", 25, spec.CylinderSpacing - 56);
+ for (var station = 0; station < 4; station++)
+ {
+ var p = phases[station] * double.Pi / 180;
+ Part("Crankpin" + (station + 1), crankpin, double.Sin(p) * spec.CrankRadius, double.Cos(p) * spec.CrankRadius, station * spec.CylinderSpacing, motion: "Crank", category: "Crank");
+ foreach (var side in new[] { -1, 1 })
+ Part("CrankWeb" + (station + 1) + (side < 0 ? "A" : "B"), references["CrankWeb"], 0, 0, station * spec.CylinderSpacing + side * 22, p, motion: "Crank", category: "Crank");
+ }
+ var support = Plate("MainSupport", 72, 36 - spec.CrankcaseFloor, (36 + spec.CrankcaseFloor) / 2, 16, (0, 50.8));
+ for (var station = 0; station < 5; station++)
+ {
+ var z = (station - .5) * spec.CylinderSpacing;
+ Part("MainJournal" + (station + 1), main, 0, 0, z, motion: "Crank", category: "Crank");
+ Part("MainSupport" + (station + 1), support, 0, 0, z, category: "Block");
+ }
+ var length = 4 * spec.CylinderSpacing + 16;
+ var rail = Plate("CrankcaseRail", 20, 16, 0, length);
+ Part("CrankcaseRailA", rail, -26, spec.CrankcaseFloor - 8, spec.CylinderSpacing * 1.5, category: "Block");
+ Part("CrankcaseRailB", rail, 26, spec.CrankcaseFloor - 8, spec.CylinderSpacing * 1.5, category: "Block");
+ var flywheel = Disc("Flywheel", 75, 16);
+ Part("Flywheel", flywheel, 0, 0, -spec.CylinderSpacing + 20, motion: "Crank", category: "Crank");
+ var cam = Disc("Camshaft", 8, length);
+ var lobe = Ring("TimingLobe", 12, 8.2, 8);
+ foreach (var bank in cylinderCount == 8 ? new[] { 1, -1 } : new[] { 1 })
+ {
+ var b = bank * spec.BankAngle / 2 * double.Pi / 180;
+ var height = spec.DeckHeight + 80;
+ Part("Camshaft" + (bank > 0 ? "Right" : "Left"), cam, double.Sin(b) * height, double.Cos(b) * height, spec.CylinderSpacing * 1.5, motion: "Cam", category: "Cam");
+ foreach (var cylinder in Cylinders.Where(c => double.Sign(c.BankRadians) == bank))
+ foreach (var offset in new[] { -20, 20 })
+ Part("TimingLobe" + cylinder.Number + (offset < 0 ? "In" : "Ex"), lobe, double.Sin(b) * height, double.Cos(b) * height, cylinder.Z + offset, motion: "Cam", category: "Cam");
+ }
+ return MatedAssembly("EditableV8");
+ }
+
+ public EngineMotionManifest Motion() => new("aetheris/engine-motion/1", spec, 720, .5, [1,5,7,3,6,8,4,2], Cylinders,
+ Bindings.Select(b => b with { CylinderMembership = b.Cylinder > 0 ? [b.Cylinder]
+ : b.Kind == "Crank" ? Cylinders.Where(c => double.Abs(c.Z - b.Rest[14]) < spec.CylinderSpacing * .6).Select(c => c.Number).ToArray()
+ : b.Kind == "Cam" ? Cylinders.Where(c => double.Sign(c.BankRadians) == double.Sign(b.Rest[12])).Select(c => c.Number).ToArray() : [] }).ToArray());
+
+ private string MatedAssembly(string root)
+ {
+ const string anchor = "MainJournal1";
+ var byName = Bindings.ToDictionary(b => b.Name, StringComparer.Ordinal);
+ static bool IsSpring(EngineBinding b) => b.Name.StartsWith("IntakeSpring", StringComparison.Ordinal) || b.Name.StartsWith("ExhaustSpring", StringComparison.Ordinal);
+ string Parent(EngineBinding b)
+ {
+ if (IsSpring(b)) return b.Name.Replace("Spring", "Stem", StringComparison.Ordinal);
+ var n = b.Cylinder;
+ if (n > 0)
+ {
+ if (b.Name.StartsWith("Rod", StringComparison.Ordinal)) return "Crankpin" + ((n + 1) / 2);
+ if (b.Name.StartsWith("WristPin", StringComparison.Ordinal)) return "Rod" + n;
+ if (b.Name.StartsWith("Piston", StringComparison.Ordinal)) return "WristPin" + n;
+ if (b.Name.StartsWith("Cylinder", StringComparison.Ordinal)) return "MainSupport" + ((n + 1) / 2);
+ if (b.Name.StartsWith("Head", StringComparison.Ordinal)) return "Cylinder" + n;
+ if (b.Name.Contains("Valve", StringComparison.Ordinal) || b.Name.Contains("Retainer", StringComparison.Ordinal))
+ return (b.Name.StartsWith("Intake", StringComparison.Ordinal) ? "IntakeStem" : "ExhaustStem") + n;
+ return "Head" + n;
+ }
+ if (b.Name.StartsWith("Crankpin", StringComparison.Ordinal)) return "CrankWeb" + b.Name[8..] + "A";
+ return anchor;
+ }
+ var parent = Bindings.Where(b => b.Name != anchor).ToDictionary(b => b.Name, b => Parent(b), StringComparer.Ordinal);
+ // The stage-A witness has no block support. Its parts register to the shaft datum.
+ foreach (var key in parent.Keys.ToArray()) if (!byName.ContainsKey(parent[key])) parent[key] = anchor;
+ var identity = Aetheris.Kernel.Core.Math.Transform3D.Identity.ToRowMajor();
+ string Frame(double[] m) => $"DatumFrame Frame = [{N(m[12])},{N(m[13])},{N(m[14])}] x [{N(m[0])},{N(m[1])},{N(m[2])}] y [{N(m[4])},{N(m[5])},{N(m[6])}] z [{N(m[8])},{N(m[9])},{N(m[10])}];";
+ var text = new StringBuilder(definitions.ToString());
+ text.AppendLine("""
+ // Interfaces qualify the indexed rest assembly. The exported analytical mechanism
+ // drives its revolute/slider coordinates; these are not general dynamic mates.
+ Interface SpringOnStem {
+ Role Spring requires AxisCapable, DatumFrameCapable, DimensionalCapable;
+ Role Stem requires AxisCapable, DatumFrameCapable, DimensionalCapable;
+ Lower AxisCoincident Spring.Axis Stem.Axis;
+ Lower FrameCoincident Spring.Frame Stem.Frame SameDirection;
+ Fit Stem.Diameter inside Spring.ClearDiameter;
+ }
+ Interface RegisteredSeat {
+ Role Moving requires DatumFrameCapable;
+ Role Fixed requires DatumFrameCapable;
+ Lower FrameCoincident Moving Fixed SameDirection;
+ }
+ Interface JournalBoreSeat {
+ Role Moving requires DatumFrameCapable, DimensionalCapable;
+ Role Fixed requires DatumFrameCapable, DimensionalCapable;
+ Lower FrameCoincident Moving Fixed SameDirection;
+ Fit Fixed.Diameter inside Moving.Diameter;
+ }
+ Interface WristPinSeat {
+ Role Moving requires DatumFrameCapable, DimensionalCapable;
+ Role Fixed requires DatumFrameCapable, DimensionalCapable;
+ Lower FrameCoincident Moving Fixed SameDirection;
+ Fit Moving.Diameter inside Fixed.Diameter;
+ }
+ """);
+ text.AppendLine($"Assembly {root} {{\n<Assembly {root}>");
+ foreach (var b in Bindings)
+ {
+ text.AppendLine($"<Part {b.Name} = {partDefinitions[b.Name]}>");
+ var diameter = b.Kind == "Rod" ? " Dimension Diameter = 44.4mm;" : b.Name.StartsWith("WristPin", StringComparison.Ordinal) ? " Dimension Diameter = 16mm;" : "";
+ if (!IsSpring(b)) text.AppendLine($"Semantic Mount {{ {Frame(identity)}{diameter} }}");
+ var inverse = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(b.Rest).Inverse();
+ foreach (var child in Bindings.Where(child => parent.GetValueOrDefault(child.Name) == b.Name))
+ {
+ var local = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(child.Rest) * inverse;
+ var seatDiameter = child.Kind == "Rod" ? " Dimension Diameter = 44mm;" : child.Name.StartsWith("WristPin", StringComparison.Ordinal) && child.Cylinder > 0 ? " Dimension Diameter = 16.4mm;" : "";
+ var m = local.ToRowMajor();
+ var axis = IsSpring(child) ? $" Axis Axis = [{N(m[12])},{N(m[13])},{N(m[14])}] -> [{N(m[8])},{N(m[9])},{N(m[10])}]; Dimension Diameter = 8mm;" : "";
+ text.AppendLine($"Semantic Seat{child.Name} {{ {Frame(m)}{seatDiameter}{axis} }}");
+ }
+ text.AppendLine("</Part>");
+ }
+ text.AppendLine($"</Assembly>\nAnchor: {root}.{anchor}.Mount;");
+ foreach (var b in Bindings.Where(b => b.Name != anchor))
+ {
+ if (IsSpring(b))
+ {
+ text.AppendLine($"Mate Install{b.Name}: SpringOnStem {{ Spring: {root}.{b.Name}.Winding; Stem: {root}.{parent[b.Name]}.Seat{b.Name}; }}");
+ continue;
+ }
+ var contract = b.Kind == "Rod" ? "JournalBoreSeat" : b.Name.StartsWith("WristPin", StringComparison.Ordinal) && b.Cylinder > 0 ? "WristPinSeat" : "RegisteredSeat";
+ text.AppendLine($"Mate Install{b.Name}: {contract} {{ Moving: {root}.{b.Name}.Mount; Fixed: {root}.{parent[b.Name]}.Seat{b.Name}; }}");
+ }
+ text.AppendLine("}");
+ return text.ToString();
+ }
+}
diff --git a/demos/Aetheris.EditableV8/README.md b/demos/Aetheris.EditableV8/README.md
new file mode 100644
index 00000000..e872c6dc
--- /dev/null
+++ b/demos/Aetheris.EditableV8/README.md
@@ -0,0 +1,15 @@
+# The editable V8
+
+An Aetheris-authored, interface-mated four-stroke mechanism. The browser displays exported definition meshes and animates their stable occurrences using the exported mechanical specification.
+
+From a checkout with .NET 10, Node/npm, Python 3 and PowerShell:
+
+```powershell
+./demos/Aetheris.EditableV8/Run.ps1
+```
+
+Open `http://127.0.0.1:8765/`. The command builds the staged assemblies, exports AP242 and meshes, validates the mechanism, installs the existing lockfile-pinned viewer dependency if needed, checks the actual JavaScript evaluator against C#, and serves the result in the foreground. Ctrl+C stops the server. Add `-NoServe` for generation and validation only.
+
+The current authoring, export, variant and inspection contract is documented in [Editable mechanisms](../../docs/public/firmament/editable-mechanisms.md). See that guide before creating a variant. Outputs default to ignored `artifacts/local/demos/editable-v8/`; no generated meshes belong in source control.
+
+Use the baseline/revised buttons, orbit/zoom, camera presets, cylinder selector, bank/cylinder isolation, glass/cutaway/solid views, and crank-angle scrubber. The revised engine adds 6 mm of stroke. Cycle color is illustrative; there is no pressure, torque, combustion, contact-dynamics or FEA model.
diff --git a/demos/Aetheris.EditableV8/Run.ps1 b/demos/Aetheris.EditableV8/Run.ps1
new file mode 100644
index 00000000..7d4362dc
--- /dev/null
+++ b/demos/Aetheris.EditableV8/Run.ps1
@@ -0,0 +1,21 @@
+[CmdletBinding()]
+param([string]$Output = '', [string]$Spec = '', [switch]$NoServe)
+$ErrorActionPreference = 'Stop'
+$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
+if (!$Output) { $Output = Join-Path $repo 'artifacts/local/demos/editable-v8' }
+$Output = [IO.Path]::GetFullPath($Output)
+$arguments = @('run', '--project', "$PSScriptRoot/Aetheris.EditableV8.csproj", '-c', 'Release', '--', $Output)
+if ($Spec) { $arguments += [IO.Path]::GetFullPath($Spec) }
+& dotnet @arguments
+if ($LASTEXITCODE) { throw 'Engine generation failed.' }
+if (!(Test-Path -LiteralPath "$repo/aetheris.client/node_modules/three/build/three.module.js")) {
+ & npm ci --prefix "$repo/aetheris.client"
+ if ($LASTEXITCODE) { throw 'Viewer dependency installation failed.' }
+}
+& "$PSScriptRoot/Prepare-Viewer.ps1" -Output $Output
+& node "$PSScriptRoot/Verify-Browser.mjs" $Output
+if ($LASTEXITCODE) { throw 'Browser evaluator parity failed.' }
+if (!$NoServe) {
+ Write-Host 'Open http://127.0.0.1:8765/ in your browser. Ctrl+C stops this foreground preview.'
+ & python "$PSScriptRoot/serve.py" $Output
+}
diff --git a/demos/Aetheris.EditableV8/Verify-Browser.mjs b/demos/Aetheris.EditableV8/Verify-Browser.mjs
new file mode 100644
index 00000000..ac86e364
--- /dev/null
+++ b/demos/Aetheris.EditableV8/Verify-Browser.mjs
@@ -0,0 +1,27 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+const directory=path.resolve(process.argv[2]??'artifacts/local/demos/editable-v8');
+const {evaluate}=await import(pathToFileURL(path.join(directory,'engine-motion.mjs')));
+const reports=[];
+for(const label of ['baseline','revised']) {
+ const read=kind=>JSON.parse(fs.readFileSync(path.join(directory,`${label}.${kind}.json`),'utf8'));
+ const motion=read('motion'), mesh=read('mesh'), samples=read('samples');
+ const objects=new Map(mesh.occurrences.filter(o=>o.definitionId).map(o=>[o.id,o]));
+ const bindings=new Map(motion.bindings.map(b=>[b.occurrenceId,b]));
+ if(objects.size!==bindings.size||bindings.size!==motion.bindings.length)throw Error('mesh-binding-count-mismatch');
+ for(const b of bindings.values()) if(!objects.has(b.occurrenceId))throw Error(`missing-object:${b.name}`);
+ let maximum=0, compared=0;
+ for(const sample of samples)for(const expected of sample.transforms) {
+ const actual=evaluate(motion,bindings.get(expected.id),sample.degrees);
+ actual.forEach((value,i)=>{if(!Number.isFinite(value))throw Error('nonfinite-transform');maximum=Math.max(maximum,Math.abs(value-expected.matrix[i]));compared++;});
+ }
+ if(maximum>1e-9)throw Error(`browser-transform-parity:${maximum}`);
+ for(const name of ['Piston3','Crankpin1','IntakeValve3']) {
+ const b=motion.bindings.find(b=>b.name===name), occurrence=objects.get(b.occurrenceId);
+ if(!mesh.definitions.some(d=>d.id===occurrence.definitionId))throw Error(`missing-mesh:${name}`);
+ }
+ reports.push({label,compared,maximumError:maximum,tolerance:1e-9,objects:objects.size,status:'pass'});
+}
+fs.writeFileSync(path.join(directory,'browser-parity.json'),JSON.stringify(reports,null,2));
+console.log(JSON.stringify(reports,null,2));
diff --git a/demos/Aetheris.EditableV8/serve.py b/demos/Aetheris.EditableV8/serve.py
new file mode 100644
index 00000000..c5533fb8
--- /dev/null
+++ b/demos/Aetheris.EditableV8/serve.py
@@ -0,0 +1,30 @@
+"""Foreground, loopback-only static showcase server. Ctrl+C stops it."""
+import argparse
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+
+parser = argparse.ArgumentParser()
+parser.add_argument("directory")
+parser.add_argument("--port", type=int, default=8765)
+args = parser.parse_args()
+
+class Handler(SimpleHTTPRequestHandler):
+ # Windows registry MIME associations must not turn ES modules into text/plain.
+ extensions_map = {**SimpleHTTPRequestHandler.extensions_map, ".mjs": "text/javascript", ".js": "text/javascript"}
+ def do_GET(self):
+ if "If-Modified-Since" in self.headers:
+ del self.headers["If-Modified-Since"]
+ super().do_GET()
+
+ def end_headers(self):
+ self.send_header("Cache-Control", "no-store")
+ super().end_headers()
+
+server = ThreadingHTTPServer(("127.0.0.1", args.port), partial(Handler, directory=args.directory))
+print(f"Editable V8: http://127.0.0.1:{args.port}/ (Ctrl+C to stop)", flush=True)
+try:
+ server.serve_forever()
+except KeyboardInterrupt:
+ pass
+finally:
+ server.server_close()
diff --git a/demos/Aetheris.EditableV8/web/engine-motion.mjs b/demos/Aetheris.EditableV8/web/engine-motion.mjs
new file mode 100644
index 00000000..f3b4b043
--- /dev/null
+++ b/demos/Aetheris.EditableV8/web/engine-motion.mjs
@@ -0,0 +1,51 @@
+import { sliderCrank, valveLift } from './prescribed-motion.mjs';
+export { sliderCrank, valveLift };
+export function evaluate(manifest, binding, degrees) {
+ if (!Number.isFinite(degrees) || binding.rest.length!==16 || !binding.rest.every(Number.isFinite)) throw Error('engine-motion-invalid-transform-or-angle');
+ if (!['Crank','Cam','Fixed','Rod','Piston','Intake','Exhaust','IntakeSpring','ExhaustSpring'].includes(binding.kind)) throw Error('engine-motion-unknown-kind:'+binding.kind);
+ const rest = binding.rest, result = [...rest], angle = degrees * Math.PI / 180;
+ if (binding.kind === 'Crank' || binding.kind === 'Cam') {
+ const turn = binding.kind === 'Cam' ? angle * manifest.camRatio : angle;
+ const s = Math.sin(turn), c = Math.cos(turn);
+ for (let i = 0; i < 12; i += 4) {
+ result[i] = c * rest[i] + s * rest[i + 1];
+ result[i + 1] = -s * rest[i] + c * rest[i + 1];
+ }
+ if (binding.kind === 'Crank') {
+ result[12] = c * rest[12] + s * rest[13]; result[13] = -s * rest[12] + c * rest[13];
+ }
+ return result;
+ }
+ if (binding.kind === 'Fixed') return result;
+ const cylinder = manifest.cylinders.find(c => c.number === binding.cylinder), spec = manifest.spec;
+ const pose = sliderCrank(spec.crankRadius, spec.rodLength, angle, cylinder.bankRadians, cylinder.crankpinRadians);
+ if (binding.kind === 'Rod') {
+ const s = Math.sin(pose.rodAngle), c = Math.cos(pose.rodAngle);
+ return [c,-s,0,0,s,c,0,0,0,0,1,0,...pose.pin.slice(0,2),cylinder.z,1];
+ }
+ let displacement;
+ if (binding.kind === 'Piston')
+ displacement = pose.position - sliderCrank(spec.crankRadius, spec.rodLength, 0, cylinder.bankRadians, cylinder.crankpinRadians).position;
+ else {
+ const opening = binding.kind.startsWith('Intake') ? spec.intakeOpeningDegrees : spec.exhaustOpeningDegrees;
+ const lift = valveLift(degrees - cylinder.ignitionDegrees, opening, spec.valveDurationDegrees, spec.valveLift, manifest.cycleDegrees);
+ const initial = valveLift(-cylinder.ignitionDegrees, opening, spec.valveDurationDegrees, spec.valveLift, manifest.cycleDegrees);
+ if (binding.kind.endsWith('Spring')) {
+ const datum=binding.springAxis; if(!datum)throw Error('engine-spring-axis-missing:'+binding.name);
+ const apply=(v,point)=>[0,1,2].map(i=>v[0]*rest[i]+v[1]*rest[4+i]+v[2]*rest[8+i]+(point?rest[12+i]:0));
+ const origin=apply(datum.localOrigin,true), direction=apply(datum.localDirection,false);
+ const norm=Math.hypot(...direction); for(let i=0;i<3;i++)direction[i]/=norm;
+ const scale = (spec.springFreeHeight - lift) / (spec.springFreeHeight - initial);
+ for(let i=0;i<16;i+=4) {
+ const relative=[0,1,2].map(j=>rest[i+j]-(i===12?origin[j]:0));
+ const projection=relative.reduce((sum,v,j)=>sum+v*direction[j],0);
+ for(let j=0;j<3;j++)result[i+j]+=direction[j]*((scale-1)*projection);
+ }
+ return result;
+ }
+ displacement = -(lift - initial);
+ }
+ result[12] += Math.sin(cylinder.bankRadians) * displacement;
+ result[13] += Math.cos(cylinder.bankRadians) * displacement;
+ return result;
+}
diff --git a/demos/Aetheris.EditableV8/web/index.html b/demos/Aetheris.EditableV8/web/index.html
new file mode 100644
index 00000000..a1cf2108
--- /dev/null
+++ b/demos/Aetheris.EditableV8/web/index.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
+<title>The editable V8 · Aetheris</title><link rel="stylesheet" href="style.css">
+<script type="importmap">{"imports":{"three":"./vendor/three.module.js","three/addons/":"./vendor/"}}</script>
+</head><body>
+<main id="scene" aria-label="Interactive Aetheris V8 assembly"></main>
+<header><span class="brand">AETHERIS <i> / </i> ENGINEERING IN MOTION</span><span class="edition">ENGINE—X0 <i>·</i> 01 / MECHANISMS</span></header>
+<section class="intro"><div class="eyebrow">ONE DEFINITION. EVERY REVOLUTION.</div><h1>The editable<br><em>V8.</em></h1><p>A four-stroke mechanism, authored in CAD.<br>Geometry and motion share the same dimensions.</p><div class="rule"></div><span class="eyebrow">90° CROSS-PLANE · 8 CYLINDERS</span></section>
+<aside class="left"><section class="panel"><div class="eyebrow">ENGINEERING DEFINITION</div><h2 id="variant-title">V8—A <span>BASELINE</span></h2><dl id="dimensions"></dl><div class="switch"><button id="baseline" class="active">V8—A</button><button id="revised">V8—B <small>+6 mm stroke</small></button></div><p class="note">Switch the specification. See the crank, travel and case regenerate together.</p></section><section class="proof panel"><div class="eyebrow">KINEMATIC SWEEP</div><strong id="proof">Loading evidence…</strong><p id="proof-detail"></p><a id="source-link" href="baseline.firmament" target="_blank">Read the generated Firmament source ↗</a></section></aside>
+<aside class="right"><section class="panel cycle"><div class="eyebrow">TRACKING <select id="cylinder" aria-label="Selected cylinder"></select></div><h2 id="phase">Power</h2><div class="stroke-label">ILLUSTRATIVE CYCLE STATE</div><div class="phase-strip"><span>POWER</span><span>EXHAUST</span><span>INTAKE</span><span>COMPRESSION</span></div><dl><div><dt>Piston travel from TDC</dt><dd id="piston-value">—</dd></div><div><dt>Intake / exhaust lift</dt><dd id="lift-value">—</dd></div></dl><svg id="chart" viewBox="0 0 240 100" aria-label="Valve lift through the four-stroke cycle"></svg><div class="chart-key"><span>— INTAKE</span><span>— EXHAUST</span><span>0—720°</span></div></section><section class="panel views"><div class="eyebrow">INSPECT THE ASSEMBLY</div><div class="row" id="cameras"><button class="active" data-camera="hero">Hero</button><button data-camera="front">Front</button><button data-camera="side">Side</button></div><div class="row" id="visibility"><button data-mode="glass" class="active">Glass</button><button data-mode="cutaway">Cutaway</button><button data-mode="solid">Solid</button></div><div class="row"><button id="bank">One bank</button><button id="isolate">One cylinder</button></div><p class="note">Drag to orbit · Scroll to zoom<br>Click a cylinder number to track it.</p></section></aside>
+<section class="bottom"><div class="firing"><span class="eyebrow">FIRING ORDER</span><div id="firing-order"></div><span class="note">One power stroke every 90°</span></div><div class="timeline"><button id="play">Ⅱ Pause</button><button id="back" aria-label="Step back 15 degrees">−15°</button><input id="angle" aria-label="Crank angle" type="range" min="0" max="720" step="0.1" value="0"><button id="forward" aria-label="Step forward 15 degrees">+15°</button><strong id="angle-value">0.0°</strong><label>RPM <input id="rpm" aria-label="Engine RPM" type="number" min="60" max="8000" value="700"></label><label>PLAYBACK <select id="speed"><option value="0.025">1 / 40</option><option selected value="0.05">1 / 20</option><option value="0.1">1 / 10</option><option value="1">1×</option></select></label></div></section>
+<footer><span>EXACT CAD → SHARED MESH DEFINITIONS → OCCURRENCE MOTION</span><span>Prescribed kinematics · Idealized valve actuation · No combustion or performance model</span></footer>
+<div id="loading">Building the view from Aetheris artifacts…</div>
+<script type="module" src="viewer.mjs"></script></body></html>
diff --git a/demos/Aetheris.EditableV8/web/style.css b/demos/Aetheris.EditableV8/web/style.css
new file mode 100644
index 00000000..e20fe951
--- /dev/null
+++ b/demos/Aetheris.EditableV8/web/style.css
@@ -0,0 +1 @@
+:root{font-family:Arial,Helvetica,sans-serif;color:#252b2c;background:#e8e9e6;font-synthesis:none;--accent:#c5392b;--muted:#6b7374}*{box-sizing:border-box}body{margin:0;overflow:hidden}#scene{position:fixed;inset:0}canvas{display:block}header,footer{position:absolute;left:30px;right:30px;display:flex;justify-content:space-between;font-size:10px;letter-spacing:1.5px}header{top:25px;border-bottom:1px solid #bdc4c2;padding-bottom:16px}.brand{font-weight:800}.brand i,.edition i{color:var(--accent);font-style:normal;margin:0 12px}.edition{color:var(--muted)}.intro{position:absolute;left:32px;top:95px;width:310px;pointer-events:none}.eyebrow{font-size:9px;letter-spacing:1.6px;font-weight:700;color:var(--muted)}h1{font-size:49px;line-height:1.04;font-weight:500;letter-spacing:-2px;margin:16px 0}h1 em{color:var(--accent);font-style:normal;font-weight:800}p{font-size:12px;line-height:1.65;color:var(--muted)}.rule{width:32px;height:3px;background:var(--accent);margin:23px 0 17px}.left,.right{position:absolute;width:248px}.left{left:32px;top:390px}.right{right:32px;top:95px}.panel{background:#f7f8f5e8;padding:20px;margin-bottom:12px;border:1px solid #ffffffb0;backdrop-filter:blur(10px);box-shadow:0 5px 24px #30433b08}h2{font-size:24px;font-weight:500;margin:12px 0 19px}h2 span{font-size:9px;letter-spacing:1.5px;color:var(--muted);margin-left:12px}dl{font-size:11px;margin:10px 0 16px}dl div{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #dce1dd}dt{color:var(--muted)}dd{font-weight:600;font-variant-numeric:tabular-nums;margin:0}.switch,.row{display:flex;gap:5px}.switch button{flex:1;text-align:left}.switch small{display:block;font-size:8px;margin-top:4px;font-weight:400}button,select,input{font:inherit}button{cursor:pointer;border:1px solid #cbd0cd;background:#fafbf9;color:#444e4d;padding:9px 11px;font-size:10px;transition:background .15s}button:hover{background:#e5e9e4}button.active,#play{background:#283b38;border-color:#283b38;color:white}.note{font-size:10px;line-height:1.65;margin-bottom:0}.proof strong{font-size:17px;color:#446953;display:block;margin-top:13px}.proof p{font-size:10px;margin:7px 0 12px}a{font-size:10px;color:#526a62;text-decoration:none}a:hover{text-decoration:underline}.cycle h2{font-size:30px;margin-bottom:8px;color:var(--accent)}select{border:0;background:transparent;color:#2c3431;font-size:11px;padding:5px}.stroke-label{font-size:8px;letter-spacing:1px;color:#929994;margin-bottom:15px}.phase-strip{display:flex;gap:5px}.phase-strip span{font-size:6px;color:#89938d;border-top:3px solid #d8ded8;padding-top:6px;flex:1}.phase-strip span.active{border-color:var(--accent);color:var(--accent)}#chart{width:100%;margin-top:8px}.chart-key{display:flex;justify-content:space-between;font-size:7px;color:#879089}.chart-key span:first-child{color:#3b85ab}.chart-key span:nth-child(2){color:var(--accent)}.views .row{margin-top:10px}.row button{flex:1;padding:8px 4px}.bottom{position:absolute;bottom:58px;left:310px;right:310px}.firing{text-align:center;margin-bottom:24px}.firing>.eyebrow{display:block;margin-bottom:11px}#firing-order{display:flex;justify-content:center;gap:10px;margin-bottom:8px}#firing-order button{border-radius:50%;height:27px;width:27px;padding:0;background:#fafbf9cc;border-color:#b9c5bb}#firing-order button.firing-now{background:#e5b5ac;border-color:#bf5243}#firing-order button.selected{outline:1.5px solid #2c443b;outline-offset:3px}.timeline{display:flex;align-items:center;gap:9px;border-top:1px solid #b9c3bc;padding-top:13px}.timeline button{white-space:nowrap;padding:9px}#angle{flex:1;min-width:70px;accent-color:var(--accent);height:3px}#angle-value{font-size:15px;min-width:55px;font-variant-numeric:tabular-nums}.timeline label{font-size:8px;color:#6f7b73;letter-spacing:1px}.timeline label input{display:block;width:46px;border:0;background:transparent;font-size:11px;padding:5px 0}.timeline label select{display:block;padding:5px 0}footer{bottom:23px;font-size:7px;letter-spacing:1px;color:#6a786f}#loading{position:fixed;inset:0;display:grid;place-items:center;background:#e8e9e6;letter-spacing:1px;font-size:13px}#loading.error{color:var(--accent)}@media(max-height:850px){.intro{top:80px}h1{font-size:39px;margin:12px 0}.intro p{font-size:10px}.rule{margin:15px 0}.left{top:310px}.panel{padding:15px}.proof{padding-top:12px;padding-bottom:12px}.right{top:80px}.bottom{bottom:49px}.firing{margin-bottom:15px}}@media(max-width:1250px){.left,.right{width:218px}.intro{width:240px}.bottom{left:270px;right:270px}.timeline label{display:none}.edition{display:none}}
diff --git a/demos/Aetheris.EditableV8/web/viewer.mjs b/demos/Aetheris.EditableV8/web/viewer.mjs
new file mode 100644
index 00000000..c8a1b4c5
--- /dev/null
+++ b/demos/Aetheris.EditableV8/web/viewer.mjs
@@ -0,0 +1,122 @@
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/OrbitControls.js';
+import { evaluate, sliderCrank, valveLift } from './engine-motion.mjs';
+const $ = id => document.getElementById(id);
+const scene = new THREE.Scene(); scene.background = new THREE.Color('#e8e9e6');
+const camera = new THREE.PerspectiveCamera(35, innerWidth / innerHeight, 1, 5000);
+const renderer = new THREE.WebGLRenderer({ antialias:true, preserveDrawingBuffer:true });
+renderer.setSize(innerWidth, innerHeight); renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.25;
+$('scene').append(renderer.domElement);
+const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true;
+scene.add(new THREE.HemisphereLight('#f5faff', '#657568', 2.7));
+for (const [position, intensity] of [[[200,700,-300],4], [[-500,250,300],3], [[400,150,600],2]]) {
+ const light = new THREE.DirectionalLight('#ffffff', intensity); light.position.set(...position); scene.add(light);
+ if (intensity === 4) { light.castShadow = true; light.shadow.mapSize.set(2048,2048); Object.assign(light.shadow.camera,{left:-600,right:600,top:600,bottom:-600,near:1,far:1800}); light.shadow.bias = -.0002; }
+}
+const floor = new THREE.Mesh(new THREE.PlaneGeometry(5000,5000),new THREE.ShadowMaterial({opacity:.12}));
+floor.rotation.x = -Math.PI/2; floor.receiveShadow = true; scene.add(floor);
+const group = new THREE.Group(); scene.add(group);
+const palette = {Block:'#536961',Head:'#50675e',Piston:'#d4d7d3',Rod:'#c1c7c5',Crank:'#343e3a',Intake:'#5892ac',Exhaust:'#bb6955',Spring:'#9a9482',Cam:'#8f7a55',Metal:'#adb4b1'};
+let manifest, packet, validation, angle=0, playing=true, selected=1, mode='glass', bank=false, isolate=false, current='baseline', loadingToken=0;
+let objects=new Map();
+async function load(label) {
+ const token=++loadingToken;
+ const values = await Promise.all(['mesh','motion','validation'].map(async kind => {
+ const response = await fetch(`${label}.${kind}.json`); if(!response.ok) throw Error(`${kind}: ${response.status}`); return response.json();
+ }));
+ if(token!==loadingToken) return;
+ [packet,manifest,validation]=values; current=label;
+ if(packet.schema!=='aetheris/assembly-display-mesh/1'||packet.units!=='mm'||manifest.schema!=='aetheris/engine-motion/1'||validation.status!=='pass') throw Error('Unsupported or unqualified artifact set');
+ for(const object of group.children) { object.geometry.dispose(); object.material.dispose(); }
+ group.clear(); objects.clear();
+ const definitions = new Map(packet.definitions.map(def=> {
+ const geometry=new THREE.BufferGeometry();
+ geometry.setAttribute('position',new THREE.Float32BufferAttribute(def.positions,3));
+ geometry.setAttribute('normal',new THREE.Float32BufferAttribute(def.normals,3));
+ geometry.setIndex(def.indices); geometry.computeBoundingSphere(); return [def.id,geometry];
+ }));
+ const bindings=new Map(manifest.bindings.map(b=>[b.occurrenceId,b]));
+ if(bindings.size!==manifest.bindings.length||bindings.size!==packet.occurrences.filter(o=>o.definitionId).length) throw Error('Occurrence/binding count mismatch');
+ for(const occurrence of packet.occurrences.filter(o=>o.definitionId)) {
+ const binding=bindings.get(occurrence.id); if(!binding) throw Error(`Missing mechanism binding: ${occurrence.path}`);
+ if(!definitions.has(occurrence.definitionId)) throw Error(`Missing mesh definition: ${occurrence.path}`);
+ const material=new THREE.MeshStandardMaterial({color:palette[binding.category]??palette.Metal,metalness:binding.category==='Block'?.35:.65,roughness:binding.category==='Piston'?.27:.36});
+ const object=new THREE.Mesh(definitions.get(occurrence.definitionId),material); object.name=occurrence.id; object.matrixAutoUpdate=false;
+ object.castShadow=!['Block','Spring'].includes(binding.category); object.receiveShadow=true; object.userData={binding,occurrence};
+ objects.set(occurrence.id,object); group.add(object);
+ }
+ const s=manifest.spec;
+ $('dimensions').innerHTML=[['Bore',`${s.bore.toFixed(0)} mm`],['Stroke',`${s.stroke.toFixed(0)} mm`],['Connecting rod',`${s.rodLength.toFixed(0)} mm`],['Crank radius',`${s.crankRadius.toFixed(0)} mm`]].map(([a,b])=>`<div><dt>${a}</dt><dd>${b}</dd></div>`).join('');
+ $('variant-title').innerHTML=label==='baseline'?'V8—A <span>BASELINE</span>':'V8—B <span>REVISED</span>';
+ for(const name of ['baseline','revised']) $(name).classList.toggle('active',name===label);
+ $('source-link').href=`${label}.firmament`;
+ $('proof').textContent=`${validation.samples.toLocaleString()} samples · PASS`;
+ $('proof-detail').textContent=`Rod closure < ${validation.rodClosureMm.toExponential(1)} mm. ${packet.definitions.length} shared definitions. ${objects.size} part occurrences.`;
+ $('cylinder').innerHTML=manifest.cylinders.map(c=>`<option value="${c.number}" ${c.number===selected?'selected':''}>CYLINDER ${c.number}</option>`).join('');
+ $('firing-order').innerHTML=manifest.firingOrder.map(n=>`<button data-cylinder="${n}" aria-label="Track cylinder ${n}">${n}</button>`).join('');
+ floor.position.y=s.crankcaseFloor-16;
+ preset(isolate?'cylinder':'hero'); update(); $('loading').style.display='none';
+}
+function preset(name) {
+ if(!manifest) return;
+ const center=new THREE.Vector3(0,110,manifest.cylinders.reduce((sum,c)=>sum+c.z,0)/manifest.cylinders.length);
+ if(name==='cylinder') {
+ const c=manifest.cylinders.find(c=>c.number===selected);
+ center.set(Math.sin(c.bankRadians)*130,110,c.z); camera.position.copy(center).add(new THREE.Vector3(360,150,-260));
+ } else camera.position.copy(center).add(new THREE.Vector3(...({hero:[570,360,-670],front:[0,150,-920],side:[920,190,0]}[name]??[570,360,-670])));
+ const fit = Math.max(1.1, innerHeight / Math.max(400, innerWidth - 610) * 1.14);
+ camera.position.sub(center).multiplyScalar(fit).add(center);
+ controls.target.copy(center); controls.update();
+}
+function update() {
+ if(!manifest)return;
+ const cylinder=manifest.cylinders.find(c=>c.number===selected), spec=manifest.spec;
+ const cycle=((angle-cylinder.ignitionDegrees)%720+720)%720, phase=Math.floor(cycle/180);
+ $('phase').textContent=['Power','Exhaust','Intake','Compression'][phase];
+ [...document.querySelectorAll('.phase-strip span')].forEach((item,i)=>item.classList.toggle('active',i===phase));
+ const pose=sliderCrank(spec.crankRadius,spec.rodLength,angle*Math.PI/180,cylinder.bankRadians,cylinder.crankpinRadians);
+ $('piston-value').textContent=`${(spec.crankRadius+spec.rodLength-pose.position).toFixed(1)} mm`;
+ const intake=valveLift(cycle,spec.intakeOpeningDegrees,spec.valveDurationDegrees,spec.valveLift);
+ const exhaust=valveLift(cycle,spec.exhaustOpeningDegrees,spec.valveDurationDegrees,spec.valveLift);
+ $('lift-value').textContent=`${intake.toFixed(1)} / ${exhaust.toFixed(1)} mm`;
+ $('angle').value=angle; $('angle-value').textContent=`${angle.toFixed(1)}°`;
+ for(const button of $('firing-order').children) {
+ const n=Number(button.dataset.cylinder), c=manifest.cylinders.find(c=>c.number===n);
+ const p=((angle-c.ignitionDegrees)%720+720)%720;
+ button.classList.toggle('firing-now',p<90); button.classList.toggle('selected',n===selected);
+ }
+ for(const object of objects.values()) {
+ const b=object.userData.binding;
+ object.matrix.fromArray(evaluate(manifest,b,angle)); object.matrixWorldNeedsUpdate=true;
+ const bankMembers=manifest.cylinders.filter(c=>Math.sign(c.bankRadians)===Math.sign(cylinder.bankRadians)).map(c=>c.number);
+ const inBank=b.cylinderMembership.length===0||b.cylinderMembership.some(n=>bankMembers.includes(n));
+ object.visible=(!isolate || b.kind!=='Cam'&&b.cylinderMembership.includes(selected)) && (!bank || inBank);
+ const enclosure=['Block','Head'].includes(b.category);
+ if(mode==='cutaway'&&enclosure)object.visible=false;
+ object.material.transparent=mode==='glass'&&enclosure;
+ object.material.opacity=object.material.transparent?.12:1; object.material.depthWrite=!object.material.transparent;
+ if(b.category==='Piston') {
+ const c=manifest.cylinders.find(c=>c.number===b.cylinder), p=((angle-c.ignitionDegrees)%720+720)%720;
+ object.material.emissive.set(p<90?'#9b3824':'#000000'); object.material.emissiveIntensity=p<90?.12:0;
+ }
+ }
+ const path=opening=>Array.from({length:145},(_,i)=>`${i?'L':'M'}${i/144*240},${88-valveLift(i*5,opening,spec.valveDurationDegrees,spec.valveLift)/spec.valveLift*70}`).join(' ');
+ $('chart').innerHTML=`<path d="M0 88H240M0 18H240" stroke="#dce2db" fill="none"/><path d="${path(spec.intakeOpeningDegrees)}" fill="none" stroke="#3b85ab" stroke-width="2"/><path d="${path(spec.exhaustOpeningDegrees)}" fill="none" stroke="#bb6955" stroke-width="2"/><path d="M${cycle/720*240} 7V95" stroke="#344d40" stroke-width="1" stroke-dasharray="3 3"/>`;
+}
+$('play').onclick=()=>{playing=!playing;$('play').textContent=playing?'Ⅱ Pause':'▶ Play';};
+$('angle').oninput=()=>{playing=false;$('play').textContent='▶ Play';angle=Number($('angle').value);update();};
+for(const [id,delta] of [['back',-15],['forward',15]])$(id).onclick=()=>{playing=false;$('play').textContent='▶ Play';angle=(angle+delta+720)%720;update();};
+for(const name of ['baseline','revised'])$(name).onclick=()=>load(name).catch(fail);
+$('cylinder').onchange=()=>{selected=Number($('cylinder').value);if(isolate)preset('cylinder');update();};
+$('firing-order').onclick=e=>{if(e.target.dataset.cylinder){selected=Number(e.target.dataset.cylinder);$('cylinder').value=selected;if(isolate)preset('cylinder');update();}};
+$('cameras').onclick=e=>{if(e.target.dataset.camera){preset(e.target.dataset.camera);for(const b of $('cameras').children)b.classList.toggle('active',b===e.target);}};
+$('visibility').onclick=e=>{if(e.target.dataset.mode){mode=e.target.dataset.mode;for(const b of $('visibility').children)b.classList.toggle('active',b===e.target);update();}};
+$('bank').onclick=()=>{bank=!bank;$('bank').classList.toggle('active',bank);update();};
+$('isolate').onclick=()=>{isolate=!isolate;$('isolate').classList.toggle('active',isolate);preset(isolate?'cylinder':'hero');update();};
+addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight);});
+let previous=performance.now();
+function animate(now){requestAnimationFrame(animate);const dt=Math.min((now-previous)/1000,.1);previous=now;if(playing){const rpm=Math.min(8000,Math.max(60,Number($('rpm').value)||700));angle=(angle+dt*rpm*6*Number($('speed').value))%720;update();}controls.update();renderer.render(scene,camera);}
+function fail(error){$('loading').style.display='grid';$('loading').className='error';$('loading').textContent=`Artifact load failed: ${error.message}`;console.error(error);}
+load('baseline').then(()=>requestAnimationFrame(animate)).catch(fail);
diff --git a/docs/public/README.md b/docs/public/README.md
index 3617f7c7..65f59bdb 100644
--- a/docs/public/README.md
+++ b/docs/public/README.md
@@ -8,6 +8,7 @@ Start with [Getting Started](getting-started.md), then use these guides:
- Non-manufacturing work: [Virtual Sculpture and Sol 1](virtual-sculpture.md)
- 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)
- 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/firmament/editable-mechanisms.md b/docs/public/firmament/editable-mechanisms.md
new file mode 100644
index 00000000..9afcbe2a
--- /dev/null
+++ b/docs/public/firmament/editable-mechanisms.md
@@ -0,0 +1,59 @@
+# Editable mechanisms and assembly display meshes
+
+The editable V8 demo is a bounded consumer of ordinary Firmament templates, semantic datum frames, interfaces, the executable assembly pipeline, and an analytical slider-crank API. Geometry and mechanism dimensions originate in C# authoring and generated Firmament. The browser consumes the resulting artifacts.
+
+## Build and revise
+
+Run `demos/Aetheris.EditableV8/Run.ps1` from PowerShell. Prerequisites are .NET 10, Node/npm and Python 3. The script resolves the project from its own location and also works when invoked by absolute path from another working directory. `-NoServe` generates and validates without launching the foreground server. `-Output <directory>` selects an output directory.
+
+Create a UTF-8 JSON specification, for example:
+
+```json
+{
+ "Bore": 92,
+ "Stroke": 84,
+ "RodLength": 150,
+ "BankAngle": 90,
+ "CylinderSpacing": 110,
+ "ValveLift": 8
+}
+```
+
+Pass its path with `-Spec`. Property names are case sensitive. Omitted values use the defaults: bore 90 mm, stroke 88 mm, rod length 145 mm, bank angle 90°, cylinder spacing 110 mm, valve lift 9 mm. The script also generates a revised engine with stroke increased by 6 mm. Baseline stroke therefore cannot exceed 94 mm in this paired workflow.
+
+The admitted scalar envelope is bore 80–100 mm, stroke 70–100 mm, rod length 135–170 mm, exactly 90° bank angle, spacing at least bore + 16 mm, and lift 1–10 mm. Passing these scalar bounds does not guarantee geometric clearance: the subsequent sweep can reject combinations with `engine-sweep-failed`. Nonfinite or out-of-range dimensions fail with `engine-spec-outside-admitted-envelope`.
+
+The runner exports a single-cylinder stage A, a valve-equipped stage B, a four-cylinder bank stage C, and baseline/revised V8s. `<variant>.firmament` is an independently compilable dimensioned source artifact. Shared definitions include piston crowns/skirts, rods, sleeves, crank webs, journals, heads, valves and WireForm springs. `<variant>.assembly.json` records actual interface fits, placement authority and world-space residuals. `<variant>.motion.json` records the input and derived dimensions, cylinder bank/phase membership, stable occurrence bindings and solved rest matrices. `<variant>.validation.json` reports the 1° sweep. `<variant>.samples.json` and `browser-parity.json` qualify the same evaluator used by the viewer.
+
+## Interfaces and geometry
+
+Each physical occurrence exposes a datum frame. `RegisteredSeat` registers frames; `JournalBoreSeat` also checks a 44 mm journal inside a 44.4 mm rod bore; `WristPinSeat` checks a 16 mm pin inside a 16.4 mm bore. The crank main journal anchors the assembly. Rods register to crankpins, pins to rods, pistons to pins, sleeves to supports, and valve parts to their head/stem seats. Firmament solves the indexed rest assembly and validates the resulting materialized frames. The motion manifest uses these solved transforms, rather than exporting an unrelated placement list.
+
+`SpringOnStem` constrains the actual `AxisCoil` winding axis to the valve-stem axis, registers its seating frame, and checks the stem diameter against the coil's clear diameter. Firmament exposes `Winding.Axis`, `Winding.Frame` and `Winding.ClearDiameter` directly from the WireForm compiler; a wire's starting tangent is not its coil axis. `<variant>.spring-validation.json` sweeps all 16 springs for coaxiality and fixed-seat drift at 1° intervals. Spring display deformation follows this solved axis, even when it is tilted relative to the source-local Z axis.
+
+These interfaces qualify a rest configuration. They do not implement general dynamic mates or a constraint-based mechanism solver. The demo's typed author computes seat frames from mechanical dimensions, and the prescribed mechanism drives the subsequent motion.
+
+`AssemblyDisplayMeshExporter.Export(AssemblyM1CompilationResult, DisplayTessellationOptions?)` emits `aetheris/assembly-display-mesh/1`: millimetre local meshes with positions, outward normals and triangle indices, shared definition IDs, and individually identified occurrences with world transforms and parent IDs. Matrices use the existing row-vector convention, with translation at indices 12–14. Three.js can consume the array directly because its column-major representation expresses the equivalent column-vector transform. Failed definitions, missing faces, invalid indices and unresolved transforms fail instead of being omitted.
+
+The CLI exposes the same exporter:
+
+```powershell
+dotnet run --project Aetheris.CLI -c Release -- mesh artifacts/local/demos/editable-v8/baseline.firmament --format assembly-json --output artifacts/local/demos/editable-v8/cli.mesh.json --json
+dotnet run --project Aetheris.CLI -c Release -- asm inspect artifacts/local/demos/editable-v8/baseline.firmament --json
+```
+
+Use a packaged `aetheris` executable with the same arguments outside a checkout. `mesh --format assembly-json` accepts executable `.firmament` and `.firmasm` assemblies; it preserves definition sharing and assembly occurrence identity. STEP export remains on the existing `asm export-ap242` path; inspect its `--help` for options.
+
+## Prescribed motion
+
+`Aetheris.Kernel.Core.Mechanisms.SliderCrank(r, L).Evaluate(shaftRadians, bankRadians, crankpinPhaseRadians)` returns the crankpin, wrist pin, bore axis, piston position and rod angle. Shaft axis is +Z; the bore axis in XY is `(sin(bank), cos(bank), 0)`. The exact closure is the crankpin projection onto that axis plus `sqrt(L² - perpendicularDistance²)`, with `L > r > 0`. It is not a sinusoidal piston approximation.
+
+`PrescribedMotion.AngularRatio` supplies the cam's 1:2 ratio. `PrescribedMotion.ValveLift` takes phase, opening angle, duration (closing minus opening), lift and cycle duration; a periodic sin² pulse gives zero lift and slope at each endpoint. The reusable browser equivalent is `Aetheris.Kernel.Core/Mechanisms/Web/prescribed-motion.mjs`.
+
+The V8 uses cross-plane crankpin phases 45°, 135°, 315°, 225°, banks at ±45°, paired rods offset ±8 mm, and firing order 1–5–7–3–6–8–4–2. Ignition is checked against each actual TDC. Each cylinder follows power, exhaust, intake and compression over 720°. Exhaust opens at 180° and intake at 360° after ignition, each for 180°, without overlap. Springs use exported WireForm coils and bounded axial display deformation about their compiler-derived winding axes. Timing collars represent the cam system; their idealized valve actuation is prescribed, without cam-contact analysis.
+
+## Qualification boundary
+
+Every baseline and revised cylinder is swept through 0–720° inclusive at 1° increments. Checks cover rod closure, piston-axis alignment, crank radius, ignition at TDC, parallel piston/head/valve clearance planes, a conservative rod envelope clipped against its sleeve, rod/case floor, swept crank-web envelope/floor, and axial rod/rod/web/support slabs. The report explicitly names this scope. It does not certify all-part interference, physical cam contact, spring stress, gas flow, combustion, torque, pressure or FEA. RPM controls visual playback only.
+
+Browser geometry for engine parts is exclusively exported Aetheris geometry. The floor, lighting and UI are presentation elements. No browser hand placement or independent engine primitive reconstruction is required when changing the specification.
diff --git a/docs/public/firmament/wire-form.md b/docs/public/firmament/wire-form.md
index 2f1c3759..b7587e2b 100644
--- a/docs/public/firmament/wire-form.md
+++ b/docs/public/firmament/wire-form.md
@@ -64,3 +64,23 @@ X1 coils remain continuous, unbranched, open paths. WIRE-X2 adds a distinct clos
See the canonical [axis coil](../../../fixtures/Canonical/WireForm/axis-coil.firmament), [frustum SurfaceCoil](../../../fixtures/Canonical/WireForm/frustum-surface-coil.firmament), [sphere SurfaceCoil](../../../fixtures/Canonical/WireForm/sphere-surface-coil.firmament), [composed Straight/Coil/Straight](../../../fixtures/Canonical/WireForm/straight-coil-straight.firmament), [90-degree bend](../../../fixtures/Canonical/WireForm/single-bend-90.firmament), and [Paperclip](../../../fixtures/Canonical/WireForm/paperclip.firmament).
`aetheris inspect source.firmament --json` reports the semantic `wireForm` object, including `operations`, `totalStraightLength`, `totalBendLength`, and compiler-derived `totalWireLength`. A materializing `build --json` adds volume, mass, surface inventory, manifold/reimport status, rational/faceted counts, and the STEP hash.
+
+## Mating a coil to a rod
+
+An `AxisCoil` starts at the current wire point and preserves its tangent. Its winding axis is generally **offset from that point and tilted from StartFrame.Up**: pitch contributes an axial component to the tangent. Do not mate the part origin or assume local Z is the spring axis.
+
+Executable Assembly template occurrences now expose each `AxisCoil` operation by its authored name. For `AxisCoil Winding`, the public semantic members are `Winding.Axis`, `Winding.Frame` and `Winding.ClearDiameter`. They come from the same compiler-derived axis origin, direction, start radial and wire radius that build the coil. The frame's Z axis is the winding axis, X is its start radial, and its origin is the winding-axis base. Clear diameter is twice the coil centerline radius minus wire diameter. The build report retains these values as `wireForm.operations[].axisDatum`.
+
+A bounded spring-to-rod interface can combine axial alignment with a seating frame:
+
+```firmament
+Interface SpringOnRod {
+ Role Spring requires AxisCapable, DatumFrameCapable, DimensionalCapable;
+ Role Rod requires AxisCapable, DatumFrameCapable, DimensionalCapable;
+ Lower AxisCoincident Spring.Axis Rod.Axis;
+ Lower FrameCoincident Spring.Frame Rod.Frame SameDirection;
+ Fit Rod.Diameter inside Spring.ClearDiameter;
+}
+```
+
+The datum frame fixes axial seat position and roll; the explicit axis constraint independently validates coaxiality after materialization. Fit analysis classifies diameter compatibility. See the executable [coil-on-stem fixture](../../../fixtures/Canonical/Assembly/coil-on-stem.firmament). This automatic datum exposure currently covers `AxisCoil`; it does not infer an axis for knots or arbitrary SurfaceCoil supports.
diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.md
index 43af526d..5b4e91a4 100644
--- a/docs/public/reference/cli.md
+++ b/docs/public/reference/cli.md
@@ -17,3 +17,7 @@ Primary public commands:
| `asm ...` | Inspect/execute/import/export assemblies |
Run `aetheris <command> --help` for exact options. JSON is a public automation surface, but its root is command-specific: process exit status is authoritative, `validate` reports `firmamentV2Validation.status`, and materializing/analysis commands report `success` where documented. Diagnostics are structured; artifact paths are explicit; wireframe reports trim/pcurve coverage and a deterministic SVG hash; Sheet Metal reports regions, bends, and lowered features separately; FEA reports requested/result artifacts; sculpting builds report every `BodyState`, `GeometricDelta`, validation evidence, surface-family inventory, and the sibling `.delta.json` path; other builds report emitted features and PMI export evidence. Counts describe semantic items at the stated layer, not arbitrary STEP entity counts.
+
+## Assembly display meshes
+
+`aetheris mesh <assembly.firmament|assembly.firmasm> --format assembly-json --output <file.mesh.json> --json` exports shared local definition meshes and stable world-space occurrences. Failed geometry is not omitted. The default destination is `artifacts/local/mesh/<name>.mesh.json`. See [editable mechanisms](../firmament/editable-mechanisms.md) for the schema and a working consumer.
diff --git a/docs/release/ENGINE-X0.md b/docs/release/ENGINE-X0.md
new file mode 100644
index 00000000..71a7f290
--- /dev/null
+++ b/docs/release/ENGINE-X0.md
@@ -0,0 +1,64 @@
+# ENGINE-X0 — the editable V8
+
+The bounded CAD and prescribed-kinematics demonstration works through the real Firmament assembly, AP242, mesh-export and browser paths. It builds a single slider-crank, a valve-equipped cylinder, one bank, and baseline/revised V8s. The browser consumes exported geometry and solved occurrence frames. A stroke change regenerates the source, exact geometry, interfaces, mesh and motion together.
+
+## Reproduce
+
+```powershell
+./demos/Aetheris.EditableV8/Run.ps1
+```
+
+Open `http://127.0.0.1:8765/`; Ctrl+C stops the foreground server. Use `-NoServe` for headless generation and evaluator qualification. Variant input and CLI inspection are documented in the [demo README](../../demos/Aetheris.EditableV8/README.md) and [public mechanism guide](../public/firmament/editable-mechanisms.md).
+
+Generated evidence stays under `artifacts/local/demos/editable-v8/`. That includes source, STEP, definition meshes, motion and assembly manifests, numerical reports, timings, hashes and screenshots. No generated engine mesh is tracked.
+
+## Authority and reusable results
+
+- A typed C# specification authors ordinary dimensioned Firmament templates. Circle2, Rect2, Polygon2, TraceLoop, hole features and WireForm build the actual parts. Identical components share definitions.
+- Named datum interfaces solve the indexed assembly. The V8 has 171 physical occurrences, one assembly root, 170 mates, 32 diameter-fit results and 186 materialized constraint residuals. Rod/pin/head/sleeve relationships are explicit. Motion rest matrices come from the solved assembly.
+- `SliderCrank` supplies exact closure in an arbitrarily oriented XY bank; `PrescribedMotion` supplies the angular ratio and idealized valve-lift law. A browser projection is checked against the C# evaluator.
+- `AssemblyDisplayMeshExporter` and `mesh --format assembly-json` export shared local geometry, outward normals, triangle indices, stable occurrence IDs and world transforms. Engine geometry is not recreated in Three.js.
+- WireForm `AxisCoil` operations expose compiler-derived winding-axis and seating-frame semantics. `SpringOnStem` constrains the actual coil axis to the valve stem, fixes the seat/roll, and checks clear diameter. This corrected the visible spring misalignment identified during review. Compression now acts about the solved winding axis, not source-local Z.
+
+The spring defect was a useful authority test: `StartFrame.Up` and the part origin were not the helix axis. The compiler-derived axis was both offset and tilted to preserve the wire's starting tangent. The fix exposes the actual winding datum from the same AIR used for geometry. The canonical [coil-on-stem fixture](../../fixtures/Canonical/Assembly/coil-on-stem.firmament) proves free/compressed pitches and rejects contradictory axis constraints.
+
+Other bounded product fixes cover template-local closed boundaries, distinct inner-loop names, correct full-circle/ellipse seam vertices, consumer mesh winding, double-precision placement composition and stable near-zero angular residual calculation. Small regression fixtures exercise the generic capabilities independently of the V8.
+
+## Verified results
+
+| Check | Baseline | Revised |
+|---|---:|---:|
+| Bore / stroke / rod length, mm | 90 / 88 / 145 | 90 / 94 / 145 |
+| Crank radius, mm | 44 | 47 |
+| Shared definitions / physical occurrences | 21 / 171 | 21 / 171 |
+| Unique definition triangles | 178,716 | 178,716 |
+| Cylinder samples, 0–720° at 1° | 5,768 | 5,768 |
+| Maximum rod closure error, mm | 5.69e-14 | 8.53e-14 |
+| Conservative rod/sleeve clearance, mm | 4.701 | 2.527 |
+| Head / valve clearance, mm | 11 / 7 | 11 / 7 |
+| Spring-axis samples | 11,536 | 11,536 |
+| Maximum spring/stem axis separation, mm | 3.56e-14 | 5.60e-14 |
+| Maximum spring-axis angular error, rad | 9.26e-17 | 2.33e-16 |
+| Fixed spring-seat drift, mm | 0 | 0 |
+
+Cam rotation is 360° per 720° crank cycle. Firing order 1–5–7–3–6–8–4–2 is checked against the actual cylinder TDCs. Both browser variants compare 27,360 matrix entries against C# samples, with maximum error 2.85e-14 and tolerance 1e-9.
+
+Two complete generations produced identical hashes for all 30 deterministic source, STEP, mesh, assembly, motion, sample and validation artifacts. Per-run timings are kept separately. Source → assembly → AP242 occurrence → mesh definition → motion binding → browser object traces cover Piston3, Crankpin1, IntakeValve3 and IntakeSpring1 in both variants.
+
+Release solution build: zero warnings/errors. Serial solution tests: **3,404 passed, zero failed, zero skipped** across 18 populated suites. The legacy-gated FrictionLab test project exposes no tests by default. An earlier parallel run during competing generation/build work exceeded existing tessellation wall-clock budgets; the serial run passed without changing those budgets. Repository layout and whitespace checks passed. Remote CI was not run.
+
+A freshly packed/installed CLI was run from a temporary directory outside the checkout to inspect the generated Firmament assembly, export its mesh and AP242, and re-import the STEP. Definition and physical occurrence counts are preserved. A fresh agent, using only public instructions and reusable entry points, generated a 92 mm bore / 84 mm stroke / 150 mm rod / 8 mm lift variant and its +6 mm revision. Both mechanical sweeps, spring-axis sweeps and browser-evaluator parity passed without editing internals or repairing placements. The agent's report is under `artifacts/local/demos/engine-x0-fresh-agent/report.md`.
+
+Representative local baseline timings: assembly compilation 1.15 s, mesh export 1.77 s, STEP export 0.25 s, mechanical sweep 5.4 ms. Baseline mesh JSON is 10,632,049 bytes; revised is 10,632,671 bytes. These are observations, not a performance guarantee or optimization target.
+
+## Visual review
+
+Review artifacts: [full engine](../../artifacts/local/demos/editable-v8/baseline-hero.png), [front](../../artifacts/local/demos/editable-v8/baseline-front.png), [one-bank cutaway](../../artifacts/local/demos/editable-v8/baseline-bank-cutaway.png), [isolated cylinder at maximum intake lift](../../artifacts/local/demos/editable-v8/baseline-cylinder.png), [corrected spring axes](../../artifacts/local/demos/editable-v8/spring-axis-fixed.png), and [revised engine](../../artifacts/local/demos/editable-v8/revised-hero.png). Playback, scrubbing, selection, isolation, transparency and variant switching were exercised in the real browser.
+
+## Modeling and language boundaries
+
+The engine is a simplified engineering demonstration. Heads, crankcase supports and timing collars are simplified; valve actuation is an idealized law without physical cam contact. Coil compression is display deformation. The clearance report explicitly limits its scope to the checked planes, clipped rod envelope, floor envelope and axial slabs. It does not certify every pairwise interference. There is no pressure, torque, combustion, thermal, contact-dynamics, fatigue or FEA result.
+
+Closed boundaries and reusable templates materially reduced profile authoring. Finite bank/station tables in C# emit repeated assembly occurrences using the existing public assembly language; no general loop syntax, second CAD IR or general dynamic mate solver was added. Set/Pattern/Feature/Span were not extended to assembly occurrence generation in this milestone. Symmetry would primarily simplify paired bank seats, heads and crank webs; the present rigid placements preserve handedness without introducing generic reflection.
+
+Remaining language friction: scalar template substitution can collide with property labels such as `Radius`, so these templates use unambiguous parameter names; extrusion limits are supplied as explicit typed Zmin/Zmax values because that lane does not admit general arithmetic expressions. These boundaries are recorded rather than hidden behind browser geometry or placement repairs.
diff --git a/fixtures/Canonical/Assembly/annular-pair.firmament b/fixtures/Canonical/Assembly/annular-pair.firmament
new file mode 100644
index 00000000..be712e39
--- /dev/null
+++ b/fixtures/Canonical/Assembly/annular-pair.firmament
@@ -0,0 +1,17 @@
+Template < R: Length > Struct Sleeve {
+ Circle2 Outside { Center: [0mm,0mm] Radius: R }
+ Circle2 Inside { Center: [0mm,0mm] Radius: 15mm }
+ Profile Section { Loop Outer { Outside |> TraceLoop } Loop Inner { Inside |> TraceLoop } }
+ Extrude Body { Profile: Section From: -10mm To: 10mm }
+}
+Assembly AnnularPair {
+ <Assembly AnnularPair>
+ <Part First = Sleeve<R: 20mm>>
+ Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];
+ </Part>
+ <Part Second = Sleeve<R: 20mm>>
+ Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,60,0,0,1];
+ </Part>
+ </Assembly>
+ Anchor: AnnularPair;
+}
diff --git a/fixtures/Canonical/Assembly/coil-on-stem.firmament b/fixtures/Canonical/Assembly/coil-on-stem.firmament
new file mode 100644
index 00000000..c9355c73
--- /dev/null
+++ b/fixtures/Canonical/Assembly/coil-on-stem.firmament
@@ -0,0 +1,34 @@
+Template < R: Length > Struct Stem {
+ Circle2 Outside { Center: [0mm,0mm] Radius: R }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Extrude Body { Profile: Section From: -10mm To: 60mm }
+}
+Template < P: Length > Struct Spring {
+ WireForm SpringWire {
+ Diameter: 2mm
+ Material: Standard.Materials.StainlessSteel.304_Annealed
+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }
+ AxisCoil Winding { Radius: 9mm; Turns: 6; Pitch: P; Handedness: RightHanded; StartPhase: 0deg }
+ }
+}
+Interface SpringOnRod {
+ Role Spring requires AxisCapable, DatumFrameCapable, DimensionalCapable;
+ Role Rod requires AxisCapable, DatumFrameCapable, DimensionalCapable;
+ Lower AxisCoincident Spring.Axis Rod.Axis;
+ Lower FrameCoincident Spring.Frame Rod.Frame SameDirection;
+ Fit Rod.Diameter inside Spring.ClearDiameter;
+}
+Assembly GuidedSpring {
+ <Assembly GuidedSpring>
+ <Part Rod = Stem<R: 4mm>>
+ Semantic SpringSeat {
+ Axis Axis = [0,0,0] -> [0,0,1];
+ DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1];
+ Dimension Diameter = 8mm;
+ }
+ </Part>
+ <Part Coil = Spring<P: 6mm>> </Part>
+ </Assembly>
+ Anchor: GuidedSpring.Rod.SpringSeat;
+ Mate Install: SpringOnRod { Spring: GuidedSpring.Coil.Winding; Rod: GuidedSpring.Rod.SpringSeat; }
+}
diff --git a/fixtures/Canonical/Templates/local-closed-boundaries.firmament b/fixtures/Canonical/Templates/local-closed-boundaries.firmament
new file mode 100644
index 00000000..5d07c4ec
--- /dev/null
+++ b/fixtures/Canonical/Templates/local-closed-boundaries.firmament
@@ -0,0 +1,14 @@
+Model LocalClosedBoundaries {
+ Units: mm
+ Template < R: Length > Struct Disc {
+ Circle2 Outside { Center: [0mm,0mm] Radius: R }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Extrude Body { Profile: Section From: 0mm To: 8mm }
+ }
+ Template < Width: Length > Struct Plate {
+ Rect2 Outside { Center: [0mm,0mm] Size: [Width,20mm] }
+ Profile Section { Loop Outer { Outside |> TraceLoop } }
+ Extrude Body { Profile: Section From: 0mm To: 8mm }
+ }
+ Struct Selected = Disc<R: 20mm>
+}