// A steam locomotive with WORKING WALSCHAERTS VALVE GEAR — built with
// antics-modelkit from npm.
//
// The reason this asset exists: a loco's motion is not an animation, it is a
// LINKAGE. Nine rods per side, each a fixed length, each pinned to two others,
// and every one of their positions falls out of a single number — how far the
// wheel has turned. Keyframing that is a losing game; solving it is forty lines,
// and then it is right at every angle, at every speed, in both directions.
//
// The kinematics live in `gear.js`, which has no dependencies and is imported by
// this file AND by the demo page. See the note at the top of it for why.
//
// 1 unit = 1 metre. This is a small 0-6-0 side-tank engine, about 9m over
// buffers and 3.7m to the top of the chimney.
import { box, extrude, merge, facet, array, sit, rect } from "antics-modelkit";
import { D, T, REST_TH, motion, motionTop, crankPin, aimX, lateralOf, RIG } from "./gear.js";
import { tubeY, tubeX, tubeZ, rod } from "./shape.js";

const at = (g, x, y, z) => { g.translate(x, y, z); return g; };

/**
 * A driving wheel, centred on its axle, in the plane the loco runs in.
 *
 * The tyre is an EXTRUDED ANNULUS rather than a disc, because the spokes are
 * what makes it read as a locomotive wheel rather than a road roller — and one
 * hole in an extrude is safe. (Two would leave the cap slit: three's
 * ear-clipping bridges each hole to the outer contour and the bridge edges
 * appear twice.)
 */
function wheel(r, width, spokes, bossSide = 1) {
  const ring = (rad, n = 28) =>
    Array.from({ length: n }, (_, i) => {
      const a = (i / n) * T;
      return [Math.cos(a) * rad, Math.sin(a) * rad];
    });
  const rimInner = r - 0.10;
  const tyre = extrude(ring(r), { holes: [ring(rimInner).reverse()], depth: width, curveSegments: 1 });
  tyre.rotateY(Math.PI / 2);   // the disc's own +Z (its thickness) becomes world +X

  const hubR = 0.15;
  const parts = [tyre, tubeX(hubR, width * 1.5, 12)];
  for (let i = 0; i < spokes; i++) {
    const a = (i / spokes) * T;
    // A spoke spans hub to rim. Its LENGTH is derived from the two radii it
    // joins, not typed — change the wheel and the spokes still reach.
    const spanned = rimInner - hubR * 0.8;
    const s = box(width * 0.42, spanned, 0.05);
    s.translate(0, hubR * 0.8, 0);
    s.rotateX(-a);             // about the axle, so the spoke lies in the wheel
    parts.push(s);
  }
  // The crank pin boss, standing proud on the OUTSIDE face. Its position comes
  // from crankR — the same constant the kinematics turn into a piston stroke —
  // so the rods cannot end up pinned somewhere the wheel has no pin.
  // AS LONG AS WHAT IT CARRIES. It was 132mm, which reached the connecting rod
  // and nothing else; the coupling rod now sits outboard of that, so the pin
  // runs from the wheel's own face out past both of them.
  parts.push(at(tubeX(0.062, D.crankPinLen, 10), bossSide * (D.crankPinMid - D.wheelInset), 0, D.crankR));
  return merge(parts);
}

function locomotive() {
  const parts = [];
  const push = (name, geo, color, mat = {}) =>
    parts.push({ name, geometry: facet(geo), color, ...mat });

  const P = {
    green: 0x1d4a35, black: 0x16181b, red: 0x7e2a20, buffer: 0x8f2a1c,
    steel: 0xbcc3cb, brass: 0xb08a3a, frame: 0x24262a, tyre: 0x1a1c1f,
  };
  const W = D.wheelInset, HALF = D.gauge / 2;

  // ── FRAMES AND FOOTPLATE ──────────────────────────────────────────────────
  // The frames are what everything else bolts to, so they are built first and
  // every height below is measured off the same two numbers.
  // THE PLATE STANDS ABOVE THE MOTION, and is told so rather than told a number.
  // At a typed 1.02 the radius rod, the expansion link and the combination lever
  // all swept straight through it and through the side tanks that stand on it —
  // six hundred sample points inside the tanks at the worst angle. `motionTop`
  // is the highest the outside gear reaches, so shortening the link or dropping
  // the valve now lowers the plate with it instead of leaving a number behind
  // that used to be right.
  const frameY = 0.86, frameTop = motionTop();
  // The FRONT of the engine is wherever the cylinders end, plus a margin — the
  // cylinder position is itself derived from how far the crosshead travels, so
  // a longer main rod moves the buffer beam and the smokebox with it rather
  // than leaving them behind for the piston rod to poke through.
  const zNose = D.cylinderZ + D.cylinderLen / 2;
  const bodyZ0 = -2.55, bodyZ1 = zNose + 0.06;
  // DEEP ENOUGH TO REACH THE PLATE. At 300mm the frames stopped 360mm short of
  // the running board, and since they are the only thing in the middle of the
  // engine you were looking straight THROUGH it in that band — a strip of
  // background between the wheels and the bodywork along the whole side. Real
  // frames are deep plates; these are at x ±0.60 and the outside motion works
  // at ±0.86, so deepening them fills the daylight without hiding any of it.
  const frameSide = (sx) =>
    at(box(0.04, frameTop - frameY, bodyZ1 - bodyZ0), sx * 0.60, frameY, (bodyZ0 + bodyZ1) / 2);
  // Stretcher between them at the top, so the pair reads as a frame and not as
  // two loose plates when you look along the engine.
  //
  // ONCE. It was inside `frameSide`, so both calls emitted it and the part
  // carried the same box twice in the same place: two coincident shells, every
  // edge shared by four triangles instead of two. Nothing rendered wrong — it is
  // z-fighting you cannot see because the two surfaces are identical — but it
  // made the whole part read as an open surface, and the clearance check will
  // not ask about a part it cannot decide the inside of. So the one member the
  // valve gear runs closest to was exempt from the check, silently.
  const stretcher = at(box(1.20, 0.05, bodyZ1 - bodyZ0), 0, frameTop - 0.05, (bodyZ0 + bodyZ1) / 2);
  // WIDE ENOUGH TO COVER THE MOTION BRACKET, which stands further outboard than
  // anything else and was hanging 17mm past the edge of the plate it hangs from.
  const boardHalf = D.crossheadX + D.bracketX + 0.05;
  push("frames", merge([frameSide(1), frameSide(-1), stretcher,
    // Running board — the walkway along each side, above the wheels.
    at(box(boardHalf * 2, 0.05, bodyZ1 - bodyZ0 + 0.3), 0, frameTop, (bodyZ0 + bodyZ1) / 2),
  ]), P.frame, { roughness: 0.6, metallic: 0.3 });

  // ── THE VALANCE ───────────────────────────────────────────────────────────
  //
  // A plate hung from the edge of the running board. SHALLOW, on purpose: the
  // first one dropped 500mm with arches cut over each axle, and it closed the
  // gap by burying the valve gear — which is the one thing this asset exists to
  // show. The frames behind now fill the daylight, so all this has to do is
  // give the board an edge and a shadow line instead of leaving it a sheet of
  // paper seen end-on.
  const valDrop = 0.17;
  push("valance", merge([-1, 1].map((sx) => merge([
    at(box(0.03, valDrop, bodyZ1 - bodyZ0 + 0.30), sx * (boardHalf - 0.015), frameTop - valDrop, (bodyZ0 + bodyZ1) / 2),
    // A bead along its lower edge, which is what catches the light on a real one.
    at(box(0.05, 0.035, bodyZ1 - bodyZ0 + 0.30), sx * (boardHalf - 0.015), frameTop - valDrop, (bodyZ0 + bodyZ1) / 2),
  ]))), P.green, { roughness: 0.45 });

  // Steps up to the cab — small, and the detail that gives the whole side a
  // sense of scale because everyone knows how big a step is.
  //
  // BEHIND WHAT THE COUPLING ROD SWEEPS. The rod TRANSLATES with the crank, so
  // its rear boss reaches axleZ[0] - crankR - bossR = -1.88, and the hanger sat
  // at -1.80. At rest the rod is at -1.60 and clears it by 200mm, which is why
  // this was invisible to everything that looks at one pose.
  const stepZ = bodyZ0 + 0.35;
  push("steps", merge([-1, 1].map((sx) => merge([
    // The hanger first, from under the valance down — without it the treads
    // floated, which the build said in as many words.
    ...[-1, 1].map((e) => at(box(0.035, valDrop + 0.56, 0.05), sx * (boardHalf - 0.06),
      frameTop - valDrop - 0.56, stepZ + e * 0.20)),
    ...[0, 1].map((i) => at(box(0.10, 0.028, 0.46), sx * (boardHalf - 0.085),
      frameTop - valDrop - 0.50 + i * 0.26, stepZ)),
  ]))), P.frame, { roughness: 0.6 });

  // Buffer beams at each end, with buffers. The front one is the part the model
  // declares as its face.
  // BOTH BEAMS THE SAME DISTANCE OUT. The rear one was at 0.28 against the
  // front's 0.14, and the running board only overhangs 0.15 — so it hung 85mm
  // clear of the engine, touching nothing. The build said so in its summary for
  // twelve builds while I was grepping that summary for the word FAIL.
  const beamOut = 0.14;
  for (const [nm, z, sgn] of [["smokebox", bodyZ1 + beamOut, 1], ["rear", bodyZ0 - beamOut, -1]]) {
    push(`bufferBeam${nm === "smokebox" ? "F" : "R"}`, merge([
      at(box(2.44, 0.42, 0.09), 0, frameTop - 0.10, z),
      ...[-1, 1].map((sx) => at(tubeZ(0.085, 0.24, 10), sx * 0.86, frameTop - 0.10, z + sgn * 0.14)),
    ]), P.buffer, { roughness: 0.7 });
  }

  // ── BOILER, SMOKEBOX, CHIMNEY ─────────────────────────────────────────────
  // THE BOILER SITS ON THE PLATE, and the plate is set by the motion under it.
  // Left at a typed 1.94 while the plate rose to clear the valve gear, the
  // boiler ended up half under its own running plate and entirely behind the
  // tanks — the engine came out a green box on wheels with a chimney. Everything
  // above the frames is derived from `frameTop` now, so the bodywork follows the
  // mechanism instead of having to be re-typed each time the mechanism moves.
  const boilerR = 0.62, boilerY = frameTop + boilerR + 0.08;
  const smokeZ0 = 2.30, smokeZ1 = bodyZ1 - 0.02;
  push("boiler", at(tubeZ(boilerR, smokeZ0 + 0.35, 18), 0, boilerY, (smokeZ0 + 0.35) / 2 - 0.35),
    P.green, { roughness: 0.42 });
  push("smokebox", merge([
    at(tubeZ(boilerR * 1.02, smokeZ1 - smokeZ0, 18), 0, boilerY, (smokeZ0 + smokeZ1) / 2),
    at(tubeZ(boilerR * 1.06, 0.06, 18), 0, boilerY, smokeZ1),   // the front ring
  ]), P.black, { roughness: 0.55 });
  // The chimney stands ON the smokebox, so its base is derived from the boiler's
  // own radius rather than typed at a height that happens to look right.
  const chimZ = (smokeZ0 + smokeZ1) / 2 + 0.10;
  push("chimney", merge([
    at(tubeY(0.19, 0.46, 12), 0, boilerY + boilerR * 0.86, chimZ),
    at(tubeY(0.235, 0.10, 12), 0, boilerY + boilerR * 0.86 + 0.40, chimZ),
  ]), P.black, { roughness: 0.5 });
  push("dome", merge([
    at(tubeY(0.24, 0.26, 12), 0, boilerY + boilerR * 0.88, 0.35),
    at(tubeY(0.14, 0.10, 10), 0, boilerY + boilerR * 0.88 + 0.24, 0.35),
  ]), P.brass, { roughness: 0.28, metallic: 0.85 });
  // ON THE BOILER. At z = -0.95 it stood 600mm behind the boiler's own rear end
  // and touched nothing — the build had been saying so, naming boilerBands as
  // its nearest neighbour, which is the tell: a part whose NEAREST thing is not
  // the thing it is bolted to is not bolted to anything.
  push("safetyValve", at(tubeY(0.10, 0.24, 8), 0, boilerY + boilerR * 0.90, -0.18),
    P.brass, { roughness: 0.3, metallic: 0.85 });
  // Boiler bands — the one detail that says "boiler" at a distance.
  push("boilerBands", array(at(tubeZ(boilerR * 1.03, 0.05, 18), 0, boilerY, 0),
    [{ pos: [0, 0, -0.75] }, { pos: [0, 0, 0.45] }, { pos: [0, 0, 1.35] }]),
    P.black, { roughness: 0.5 });

  // ── SIDE TANKS AND CAB ────────────────────────────────────────────────────
  // A SIDE TANK COMES UP TO ABOUT THE BOILER CENTRE. Any taller and it hides the
  // boiler, which is the one shape that says what kind of engine this is.
  // ON the running board, not level with its UNDERSIDE. `frameTop` is where the
  // board starts and the board is 50mm thick, so tanks and cab standing at
  // frameTop were sunk their full depth into it — and their undersides were
  // coplanar with the board's underside, both facing down, 2.86 square metres of
  // two surfaces claiming one place. It renders as flickering hatching from any
  // low angle and reads as a lighting artefact.
  const boardTop = frameTop + 0.05;
  const tankY = boardTop, tankH = boilerY - boardTop, tankZ0 = -0.30, tankZ1 = smokeZ0 - 0.05;
  push("tanks", merge([-1, 1].map((sx) =>
    at(box(0.56, tankH, tankZ1 - tankZ0), sx * 0.82, tankY, (tankZ0 + tankZ1) / 2))),
    P.green, { roughness: 0.42 });

  const cabZ0 = bodyZ0 + 0.10, cabZ1 = -0.30, cabH = 1.62;
  // The cab sides carry a cut-out, and the spectacle plate a round window. Each
  // is ONE hole in its own extrude — see the note on the wheel.
  // EXTRUDE LAYS ITS OUTLINE OUT FROM THE ORIGIN, so an extruded panel is placed
  // by an EDGE and never by its centre — and after `rotateY(PI/2)` the outline's
  // +X runs along −Z, so the edge it starts at is its FRONT one. Placed at the
  // cab's midpoint the way a box() would be, the two sides landed a whole metre
  // behind the roof and the back sheet: the cab had no walls across its front
  // half at all, and from the side you looked straight through the engine.
  //
  // Measured, not seen — the sides spanned z −3.53..−1.38 while everything else
  // in the same part spanned −2.57..−0.30. In a render it reads as a shading
  // oddity around the tank joint, which is not where the problem is.
  const cabSide = (sx) => {
    const g = extrude(rect(cabZ1 - cabZ0, cabH, 0, 0), {
      holes: [rect(0.62, 0.52, 0.28, 0.72).reverse()], depth: 0.05, curveSegments: 1,
    });
    g.rotateY(Math.PI / 2);
    // ON the running board, each side inside its OWN edge. Placed at sx * 1.10
    // the panel's 50mm of depth always ran toward +x, so the right-hand side
    // stood 42mm PROUD of the board and the left sat 7mm inside it — asymmetric
    // on a symmetric engine, and the overhanging strip put the cab's underside
    // coplanar with the tanks' in open air, both facing down. An asymmetric
    // answer to a symmetric question is the shape of a placement bug.
    return at(g, sx > 0 ? boardHalf - 0.05 : -boardHalf, tankY, cabZ1);
  };
  // THE SPECTACLE PLATE, which the first draft left out — and a cab open at the
  // front is not a missing detail, it is a HOLE. From the side you looked
  // straight through the gap between the tank and the cab and out the far side,
  // with the boiler's back end floating in the middle of it. That is the
  // cottage-with-no-gable-end failure exactly: every part present, correct and
  // closed, and the assembly not enclosing anything.
  //
  // Two panels, one window each, rather than one panel with two — three's
  // ear-clipping bridges each hole to the outer contour, and the second bridge
  // leaves the extrude's cap slit open.
  const spectacle = (sx) => {
    const g = extrude(rect(1.04, cabH, 0, 0), {
      holes: [rect(0.46, 0.44, 0.30, 0.80).reverse()], depth: 0.05, curveSegments: 1,
    });
    // extrude() lays the rect out from x = 0, so each panel is placed by the
    // edge it starts at rather than by its centre — the version that shifted
    // both panels by the same signed amount covered −0.52 to 1.06 and left a
    // third of the cab front open on one side only.
    // AND SET BACK BY ITS OWN DEPTH. extrude() runs the depth toward +z, so
    // placed AT cabZ1 the plate stood forward of the cab front, inside the tanks
    // — their footprints overlapped and both undersides sat on the board in one
    // plane, facing down. Two panels sharing a floor is not a defect; two panels
    // sharing a floor AND a footprint is two surfaces in one place.
    return at(g, sx > 0 ? 0.02 : -1.06, tankY, cabZ1 - 0.05);
  };
  push("cab", merge([
    cabSide(1), cabSide(-1),
    spectacle(1), spectacle(-1),
    at(box(2.24, cabH, 0.06), 0, tankY, cabZ0 + 0.03),                    // back sheet
    // The roof overhangs the BACK, the way a cab roof does for the crew, and is
    // flush at the front where it meets the spectacle plate.
    at(box(2.30, 0.07, cabZ1 - cabZ0 + 0.12), 0, tankY + cabH, (cabZ0 + cabZ1) / 2 - 0.06),
  ]), P.green, { roughness: 0.42 });

  // ── WHEELS ────────────────────────────────────────────────────────────────
  // Origin AT THE AXLE, so the demo spins them with one rotation and nothing
  // has to know where the wheel was drawn.
  // A WHEEL PER SIDE, not one wheel mirrored. `scale(-1, 1, 1)` is the obvious
  // way to face the crank boss outward on the other side and it REVERSES THE
  // WINDING — the kit's own check caught all three right-hand wheels as
  // inside-out, which renders as invisible rather than as wrong. Passing which
  // side the boss stands on costs nothing and cannot flip a normal.
  const wg = { 1: wheel(D.wheelR, D.wheelWidth, D.spokes, 1), "-1": wheel(D.wheelR, D.wheelWidth, D.spokes, -1) };
  D.axleZ.forEach((z, i) => {
    for (const sx of [-1, 1]) {
      // IN ITS OWN FRAME: centred on the axle, crank boss at th = 0. The rig
      // puts it where it goes and turns it to REST_TH, and the kit bakes that —
      // so the .glb still shows a locomotive whose connecting rod is pinned to
      // the boss it is actually pinned to, without this file knowing the angle.
      push(`wheel${sx > 0 ? "L" : "R"}${i}`, wg[sx].clone(), P.red, { roughness: 0.5 });
    }
    // Long enough to reach INTO both hubs. At 1.7x the inset it stopped 25mm
    // short of each one and the gate said so on every build.
    push(`axle${i}`, at(tubeX(0.075, W * 2.05, 10), 0, D.wheelR, z), P.frame, { roughness: 0.5 });
  });

  // ── CYLINDERS AND MOTION BRACKET (static) ─────────────────────────────────
  for (const sx of [-1, 1]) {
    const s = sx > 0 ? "L" : "R";
    push(`cylinder${s}`, merge([
      at(tubeZ(D.cylinderR, D.cylinderLen, 14), sx * D.crossheadX, D.pistonY, D.cylinderZ),
      at(box(0.30, 0.30, D.cylinderLen * 1.04), sx * D.crossheadX, D.pistonY - 0.15, D.cylinderZ),
      // The steam chest, which is where the valve the gear drives actually goes.
      at(tubeZ(0.135, D.cylinderLen * 0.86, 12), sx * D.crossheadX, D.valveY, D.cylinderZ),
    ]), P.black, { roughness: 0.45, metallic: 0.3 });

    // Guide bars: the crosshead slides between them, so their span is the piston
    // stroke plus the crosshead — derived, not measured off the render.
    // AS LONG AS THE CROSSHEAD'S OWN TRAVEL, placed on it. Measured back from the
    // cylinder they were a fixed 1.05m starting 950mm behind a casting that has
    // since moved, so they reached back over the main rod's swing and the rod
    // passed through them.
    // Long enough for the crosshead BLOCK at each extreme and no longer, and
    // ASYMMETRIC — the bars need room ahead of the crosshead for the gland and
    // almost none behind it, while behind is exactly where the main rod and the
    // coupling rod swing. A symmetric length reached back into both.
    const g0 = D.minCrossZ - 0.055, g1 = D.maxCrossZ + 0.20;
    push(`guideBars${s}`, merge([-1, 1].map((dy) =>
      at(box(0.03, 0.045, g1 - g0), sx * D.crossheadX, D.pistonY + dy * 0.150 - 0.045 / 2, (g0 + g1) / 2))),
      P.steel, { roughness: 0.3, metallic: 0.8 });

    // The bracket the expansion link swings on.
    // HUNG FROM ABOVE, not stood on from below — a bracket dropping 440mm under
    // its trunnion reaches into the main rod's sweep, and the rod went through
    // it. And OUTBOARD of the whole motion, with a trunnion pin reaching back
    // in to the link: on the link's own plane the two were one solid.
    const bx = sx * (D.crossheadX + D.bracketX);
    push(`linkBracket${s}`, merge([
      at(box(0.04, frameTop - D.linkTrunnion.y + 0.06, 0.12), bx, D.linkTrunnion.y - 0.06, D.linkTrunnion.z),
      at(box(0.04, 0.07, 0.62), bx, frameTop - 0.07, D.linkTrunnion.z + 0.30),
      // The pin the link actually swings on, spanning bracket to link.
      at(tubeX(0.032, D.bracketX + 0.06, 8), sx * (D.crossheadX + D.bracketX / 2 + 0.01),
        D.linkTrunnion.y, D.linkTrunnion.z),
    ]), P.frame, { roughness: 0.5, metallic: 0.4 });
  }

  // ── THE MOTION ────────────────────────────────────────────────────────────
  //
  // Every part below is drawn in its own LOCAL frame — origin at its pivot,
  // running +Z — and nothing here places it. `RIG` in gear.js says where each
  // one goes at a given crank angle, `modelkit build` bakes the rest pose out of
  // that, and the demo drives the same rig every frame.
  //
  // This file used to bake by hand and the demo used to un-bake by hand, which
  // is one mechanism described twice in opposite directions. Both descriptions
  // had to carry the same lateral offsets from `OUTBOARD`, and un-baking the
  // wrong x left the offset in the geometry AND applied it again from the pose.
  const motionMat = { roughness: 0.26, metallic: 0.9 };

  for (const sx of [-1, 1]) {
    const s = sx > 0 ? "L" : "R";

    const span = D.axleZ[2] - D.axleZ[0];
    push(`couplingRod${s}`, rod(span, 0.075, 0.032, D.couplingRodBoss), P.steel, motionMat);
    push(`mainRod${s}`, rod(D.mainRodLen, 0.085, 0.042, D.mainRodBoss), P.steel, motionMat);

    // Crosshead: the block, plus the piston rod running back into the cylinder
    // and the union link reaching forward to the combination lever. All three
    // move together, so they are one part — and all three are measured from the
    // crosshead pin, which is this part's origin.
    push(`crosshead${s}`, merge([
      at(box(0.10, 0.20, 0.24), 0, -0.20 / 2, 0),
      at(tubeZ(0.045, D.pistonRodLen, 10), 0, 0, D.pistonRodLen / 2),
      rod(D.unionLinkLen, 0.05, 0.03, 0.045),
    ]), P.steel, motionMat);

    push(`returnCrank${s}`, rod(D.returnCrankLen, 0.06, 0.034, 0.052), P.steel, motionMat);
    push(`eccentricRod${s}`, rod(D.eccentricRodLen, 0.055, 0.030, 0.050), P.steel, motionMat);

    // The expansion link: a slotted arc pivoting on its trunnion. Its local +Z
    // runs from the trunnion DOWN to the bottom pin, so the rig aims it like
    // every other part rather than needing its own convention. It reaches
    // `linkTop` BACK past its own pivot to carry the top pin, which is why the
    // frame check asks whether its pins are on the steel rather than whether the
    // steel stops at them.
    push(`expansionLink${s}`, merge([
      at(box(0.05, 0.16, D.linkBottom + D.linkTop), 0, -0.16 / 2, (D.linkBottom - D.linkTop) / 2),
      // 50mm long, not 110. The bracket's own trunnion pin already spans the
      // gap from the bracket in to this plane, and a boss reaching 55mm each way
      // put the link's outer face inside the coupling rod at 110mm.
      tubeX(0.06, 0.05, 10),
      // The pin bosses, 50mm rather than 90 for the same reason as the trunnion:
      // at 90 they reached 45mm each way from a plane only 94mm clear of the
      // coupling rod, and the coupling rod cannot move — it is outboard of the
      // connecting rod on a pin only so long. A boss is sized by what is beside
      // it, not by what looks like a boss.
      at(tubeX(0.05, 0.05, 8), 0, 0, D.linkBottom),
      at(tubeX(0.05, 0.05, 8), 0, 0, -D.linkTop),
    ]), P.steel, motionMat);

    push(`radiusRod${s}`, rod(D.radiusRodLen, 0.05, 0.028, 0.046), P.steel, motionMat);
    push(`combLever${s}`, rod(D.combLowToTop, 0.07, 0.030, 0.048), P.steel, motionMat);
    push(`valveRod${s}`, rod(D.valveRodLen, 0.045, 0.026, 0.042), P.steel, motionMat);
  }

  // ── STANDING ON THE RAIL ──────────────────────────────────────────────────
  //
  // Asserted by the gate's `stands`, not here, and that is a consequence of the
  // rig: the moving parts in this file are at their own origins until the kit
  // bakes them, so the lowest point of what is in `parts` right now is not the
  // lowest point of the locomotive. The gate measures it after the bake, which
  // is the only moment the answer means anything.
  //
  // Deliberately NOT sit(). Every moving part's geometry carries its pivot at a
  // known place, and the rig re-derives those pivots from gear.js; a translate
  // applied to the assembly and not to the rig would put every rod a centimetre
  // out of its bearing. The wheels are built with their centres at wheelR, so
  // the tread already touches y = 0 — asserted rather than assumed.

  return {
    category: "vehicle",
    front: "smokebox",
    stands: true,
    parts,
    motion: RIG,
    anchors: {
      // What a page placing this needs, and what the demo uses to frame it.
      chimney: [0, 2.90, chimZ],
      cab: [0, tankY + 0.4, (cabZ0 + cabZ1) / 2],
      coupler: [0, frameTop - 0.10, bodyZ0 - 0.42],
      buffer: [0, frameTop - 0.10, bodyZ1 + 0.28],
    },
  };
}

export const loco = () => locomotive();
