Skip to content

Capture iPhone LiDAR and photos, reconstruct editable Three.js rooms, and explore them in a browser.

TypeScript
53.2 KB
Raw Blame
import * as THREE from 'three';
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
import type { PartContext } from '../parts/types';

/**
 * The workstation: live-edge black-walnut slab on a black 3-stage standing-desk frame, two BenQ
 * RD280U programming monitors (28.2" 3:2, one landscape, one portrait) with the MoonHalo ring
 * glowing on their backs, on a black pole mount with articulated arms; the Apple Magic Keyboard
 * (Touch ID + numeric keypad, black keys) and a Logitech MX Master 3S; the boom-arm mic at the
 * west end.
 *
 * Measured from the fused scan + photo projections (photos 13, 25, 26, 29, 88 projected onto the
 * desk plane): slab x 0.245..2.07, back edge z -0.865, live front edge z ≈ 0.155..0.172, top 0.825,
 * 52 mm thick; legs at x 0.35 / 1.98. Landscape monitor top 1.42, portrait 0.90..1.52.
 *
 * Textures: public/textures/office-v2/desk-slab-* (generated by the HD pass from Poly Haven CC0
 * walnut veneers + photo-matched banding/sapwood), desk-mon-* (photo crops of the real screens and
 * the stickered back).
 */

const TEX = '/textures/office-v2/';
export const SLAB = { x0: 0.245, x1: 2.07, back: -0.865, top: 0.825, thick: 0.052 };
/** texture frame of desk-slab-top.jpg (keep in sync with gen_slab.py) */
const UVF = { xa: 0.2, xb: 2.11, za: -0.9, zb: 0.21 };
const ease = (t: number) => t * t * (3 - 2 * t);
const clamp01 = (t: number) => Math.min(1, Math.max(0, t));
const smooth = (a: number, b: number, t: number) => ease(clamp01((t - a) / (b - a)));

/** live front edge (room z of the top rim) — keep in sync with gen_slab.py liveZ() */
export function liveZ(x: number) {
  const base = 0.166 + 0.006 * Math.sin(x * 5.3 + 0.9) + 0.0035 * Math.sin(x * 13.1 + 2.2) + 0.0014 * Math.sin(x * 41.0 + 0.4);
  const e0 = clamp01((x - SLAB.x0) / 0.16), e1 = clamp01((SLAB.x1 - x) / 0.16);
  return base - 0.012 * (1 - ease(e0)) - 0.01 * (1 - ease(e1));
}

// hashed value noise (deterministic)
function hash(i: number, j: number) {
  const s = Math.sin(i * 127.1 + j * 311.7) * 43758.5453;
  return s - Math.floor(s);
}
function vnoise(x: number, y: number) {
  const i = Math.floor(x), j = Math.floor(y), fx = x - i, fy = y - j;
  const u = ease(fx), v = ease(fy);
  const a = hash(i, j), b = hash(i + 1, j), c = hash(i, j + 1), d = hash(i + 1, j + 1);
  return (a * (1 - u) + b * u) * (1 - v) + (c * (1 - u) + d * u) * v - 0.5;
}

const loader = new THREE.TextureLoader();
const cache = new Map<string, THREE.Texture>();
/** textures are preloaded in build() (so captures never see a half-loaded slab); this just configures them */
function load(file: string, srgb = true, repeat = false) {
  const t = cache.get(file)!.clone();
  t.needsUpdate = true;
  t.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
  t.anisotropy = 8;
  if (repeat) t.wrapS = t.wrapT = THREE.RepeatWrapping;
  return t;
}

function canvasTex(w: number, h: number, draw: (c: CanvasRenderingContext2D, w: number, h: number) => void, srgb = true, repeat = false) {
  const cv = document.createElement('canvas');
  cv.width = w;
  cv.height = h;
  draw(cv.getContext('2d')!, w, h);
  const t = new THREE.CanvasTexture(cv);
  t.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
  t.anisotropy = 8;
  if (repeat) t.wrapS = t.wrapT = THREE.RepeatWrapping;
  return t;
}

/** tileable fine noise normal map (powder coat orange-peel, bead-blasted aluminium, plastic grain) */
function noiseNormal(size: number, scale: number, strength: number, seed: number) {
  return canvasTex(size, size, (c, w, h) => {
    const hgt = new Float32Array(w * h);
    for (let y = 0; y < h; y++)
      for (let x = 0; x < w; x++) {
        let v = 0, amp = 1, f = scale;
        for (let o = 0; o < 3; o++) {
          // periodic noise: wrap lattice at w/f
          const p = Math.max(1, Math.round(w / f));
          const X = (x / w) * p, Y = (y / h) * p;
          const i = Math.floor(X), j = Math.floor(Y), fx = X - i, fy = Y - j;
          const hh = (a: number, b: number) => hash(((a % p) + p) % p + seed * 17, ((b % p) + p) % p + seed * 31);
          const u = ease(fx), vv = ease(fy);
          v += amp * ((hh(i, j) * (1 - u) + hh(i + 1, j) * u) * (1 - vv) + (hh(i, j + 1) * (1 - u) + hh(i + 1, j + 1) * u) * vv);
          amp *= 0.5;
          f *= 2.3;
        }
        hgt[y * w + x] = v;
      }
    const img = c.createImageData(w, h);
    const H = (x: number, y: number) => hgt[((y + h) % h) * w + ((x + w) % w)];
    for (let y = 0; y < h; y++)
      for (let x = 0; x < w; x++) {
        const dx = (H(x + 1, y) - H(x - 1, y)) * strength, dy = (H(x, y + 1) - H(x, y - 1)) * strength;
        const n = new THREE.Vector3(-dx, dy, 1).normalize();
        const i = (y * w + x) * 4;
        img.data[i] = (n.x * 0.5 + 0.5) * 255;
        img.data[i + 1] = (n.y * 0.5 + 0.5) * 255;
        img.data[i + 2] = (n.z * 0.5 + 0.5) * 255;
        img.data[i + 3] = 255;
      }
    c.putImageData(img, 0, 0);
  }, false, true);
}

// ---------------------------------------------------------------------------------------------
// geometry helpers

type V3 = [number, number, number];
function T(x: number, y: number, z: number, ry = 0, rx = 0, rz = 0, s: V3 = [1, 1, 1]) {
  return new THREE.Matrix4().compose(new THREE.Vector3(x, y, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz, 'YXZ')), new THREE.Vector3(...s));
}
/** collects geometries per material and merges them into one mesh per material */
class Batch {
  lists = new Map<THREE.Material, THREE.BufferGeometry[]>();
  stack: THREE.Matrix4[] = [new THREE.Matrix4()];
  push(m: THREE.Matrix4) {
    this.stack.push(this.stack[this.stack.length - 1].clone().multiply(m));
  }
  pop() {
    this.stack.pop();
  }
  add(g: THREE.BufferGeometry, mat: THREE.Material, m?: THREE.Matrix4) {
    let geo = g.index ? g.toNonIndexed() : g.clone();
    for (const k of Object.keys(geo.attributes)) if (!['position', 'normal', 'uv'].includes(k)) geo.deleteAttribute(k);
    if (!geo.getAttribute('normal')) geo.computeVertexNormals();
    if (!geo.getAttribute('uv')) geo.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(geo.getAttribute('position').count * 2), 2));
    geo.clearGroups();
    const top = this.stack[this.stack.length - 1];
    geo = geo.applyMatrix4(m ? top.clone().multiply(m) : top);
    let list = this.lists.get(mat);
    if (!list) this.lists.set(mat, (list = []));
    list.push(geo);
  }
  build(group: THREE.Object3D, name: string, shadows = true) {
    for (const [mat, list] of this.lists) {
      const merged = mergeGeometries(list, false);
      if (!merged) continue;
      const mesh = new THREE.Mesh(merged, mat);
      mesh.castShadow = mesh.receiveShadow = shadows;
      mesh.name = `${name}:${mat.name || 'mat'}`;
      group.add(mesh);
    }
    this.lists.clear();
  }
}
const rb = (w: number, h: number, d: number, r: number, seg = 3) => new RoundedBoxGeometry(w, h, d, seg, Math.min(r, w / 2 - 0.0002, h / 2 - 0.0002, d / 2 - 0.0002));
const cyl = (rt: number, rbot: number, h: number, seg = 24, open = false) => new THREE.CylinderGeometry(rt, rbot, h, seg, 1, open);
/** cylinder between two points */
function rod(a: THREE.Vector3, b: THREE.Vector3, r: number, seg = 16, r2 = r) {
  const g = cyl(r2, r, a.distanceTo(b), seg);
  g.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), b.clone().sub(a).normalize()));
  g.translate((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2);
  return g;
}
/** rounded box spanning a→b (its long axis), width w (horizontal-ish), height h */
function beam(a: THREE.Vector3, b: THREE.Vector3, w: number, h: number, r: number, up = new THREE.Vector3(0, 1, 0)) {
  const len = a.distanceTo(b);
  const g = rb(w, h, len, r, 3);
  const m = new THREE.Matrix4().lookAt(b, a, up);
  m.setPosition(a.clone().add(b).multiplyScalar(0.5));
  g.applyMatrix4(m);
  return g;
}
/** extrude a 2D profile (x,y) by depth along +z, centred on z */
function extrude(pts: [number, number][], depth: number, bevel = 0.002, curveSegments = 6) {
  const s = new THREE.Shape(pts.map(([x, y]) => new THREE.Vector2(x, y)));
  const g = new THREE.ExtrudeGeometry(s, { depth: depth - 2 * bevel, bevelEnabled: bevel > 0, bevelThickness: bevel, bevelSize: bevel, bevelSegments: 2, curveSegments });
  g.translate(0, 0, -(depth - 2 * bevel) / 2);
  return g;
}
function roundedRectShape(w: number, h: number, r: number) {
  const s = new THREE.Shape();
  s.moveTo(-w / 2 + r, -h / 2);
  s.lineTo(w / 2 - r, -h / 2);
  s.quadraticCurveTo(w / 2, -h / 2, w / 2, -h / 2 + r);
  s.lineTo(w / 2, h / 2 - r);
  s.quadraticCurveTo(w / 2, h / 2, w / 2 - r, h / 2);
  s.lineTo(-w / 2 + r, h / 2);
  s.quadraticCurveTo(-w / 2, h / 2, -w / 2, h / 2 - r);
  s.lineTo(-w / 2, -h / 2 + r);
  s.quadraticCurveTo(-w / 2, -h / 2, -w / 2 + r, -h / 2);
  return s;
}
const tag = <O extends THREE.Object3D>(o: O, physics: Record<string, unknown>) => ((o.userData.physics = physics), o);

// =============================================================================================
// SLAB

type OP = { x: number; z: number; w: number; kind: 'back' | 'end' | 'live' };

function slabOutline(): OP[] {
  const { x0, x1, back } = SLAB;
  const pts: OP[] = [];
  const rNW = 0.045, rNE = 0.012, rF = 0.016;
  const arc = (cx: number, cz: number, r: number, a0: number, a1: number, n: number, w0: number, w1: number, k0: OP['kind'], k1: OP['kind']) => {
    for (let i = 0; i <= n; i++) {
      const t = i / n, a = a0 + (a1 - a0) * t;
      pts.push({ x: cx + Math.cos(a) * r, z: cz + Math.sin(a) * r, w: w0 + (w1 - w0) * ease(t), kind: t < 0.5 ? k0 : k1 });
    }
  };
  // back edge, west → east (z = back); CCW in (x, z)
  const nb = Math.ceil((x1 - rNE - (x0 + rNW)) / 0.02);
  for (let i = 1; i < nb; i++) pts.push({ x: x0 + rNW + ((x1 - rNE - x0 - rNW) * i) / nb, z: back, w: 0, kind: 'back' });
  arc(x1 - rNE, back + rNE, rNE, -Math.PI / 2, 0, 5, 0, 0, 'back', 'end');
  // east end, back → front
  const zF1 = liveZ(x1 - rF);
  const ne = Math.ceil((zF1 - rF - (back + rNE)) / 0.02);
  for (let i = 1; i < ne; i++) pts.push({ x: x1, z: back + rNE + ((zF1 - rF - back - rNE) * i) / ne, w: 0, kind: 'end' });
  arc(x1 - rF, zF1 - rF, rF, 0, Math.PI / 2, 7, 0, 1, 'end', 'live');
  // live front edge, east → west, 5 mm steps
  const nl = Math.ceil((x1 - x0 - 2 * rF) / 0.005);
  for (let i = 1; i < nl; i++) {
    const x = x1 - rF - ((x1 - x0 - 2 * rF) * i) / nl;
    pts.push({ x, z: liveZ(x), w: 1, kind: 'live' });
  }
  const zF0 = liveZ(x0 + rF);
  arc(x0 + rF, zF0 - rF, rF, Math.PI / 2, Math.PI, 7, 1, 0, 'live', 'end');
  // west end, front → back
  const nw = Math.ceil((zF0 - rF - (back + rNW)) / 0.02);
  for (let i = 1; i < nw; i++) pts.push({ x: x0, z: zF0 - rF - ((zF0 - rF - back - rNW) * i) / nw, w: 0, kind: 'end' });
  arc(x0 + rNW, back + rNW, rNW, Math.PI, 1.5 * Math.PI, 8, 0, 0, 'end', 'back');
  // drop the duplicate last point (== first of arc joins)
  return pts;
}

/** inward offset of the slab surface at outline weight w (live), depth fraction t (0 top … 1 bottom) */
function slabInset(p: OP, t: number) {
  const th = SLAB.thick, d = t * th;
  // cut edges: 2 mm eased arris top and bottom
  const cut = d < 0.002 ? 0.002 - Math.sqrt(Math.max(0, 0.002 * 0.002 - (0.002 - d) * (0.002 - d))) : d > th - 0.0015 ? 0.0015 - Math.sqrt(Math.max(0, 0.0015 * 0.0015 - (d - th + 0.0015) ** 2)) : 0;
  if (p.w <= 0) return cut;
  const s = p.x;
  const r = 0.009 + 0.003 * vnoise(s * 9, 1.3); // rounded rim
  const rim = d < r ? r - Math.sqrt(Math.max(0, r * r - (r - d) * (r - d))) : 0;
  const under = (0.02 + 0.012 * vnoise(s * 3.1, 7.7) + 0.006 * Math.sin(s * 8.3)) * Math.pow(smooth(0.22, 1.0, t), 1.25);
  const bumps = (0.0032 * vnoise(s * 55, t * 7) + 0.0022 * vnoise(s * 140, t * 16 + 4) + 0.0012 * vnoise(s * 400, t * 30)) * smooth(0.12, 0.35, t);
  // occasional deeper bark-scar gouges
  const g = vnoise(s * 18, 3.3);
  const gouge = g > 0.28 ? (g - 0.28) * 0.03 * smooth(0.3, 0.6, t) : 0;
  const live = rim + under + bumps + gouge;
  return cut * (1 - p.w) + live * p.w;
}

function slabGeometry() {
  const out = slabOutline();
  const N = out.length;
  // inward normals of the outline (CCW in x,z → left normal points inside)
  const inward = out.map((_, i) => {
    const a = out[(i - 1 + N) % N], b = out[(i + 1) % N];
    const tx = b.x - a.x, tz = b.z - a.z, l = Math.hypot(tx, tz) || 1;
    return [-tz / l, tx / l] as [number, number];
  });
  // sanity: CCW check (area > 0)
  let area = 0;
  for (let i = 0; i < N; i++) area += out[i].x * out[(i + 1) % N].z - out[(i + 1) % N].x * out[i].z;
  const flip = area < 0 ? -1 : 1;
  const ts = [0, 0.012, 0.035, 0.07, 0.12, 0.19, 0.28, 0.38, 0.48, 0.58, 0.68, 0.77, 0.85, 0.92, 0.965, 0.99, 1];
  const K = ts.length;
  const P: THREE.Vector3[][] = [];
  for (let k = 0; k < K; k++) {
    const row: THREE.Vector3[] = [];
    for (let i = 0; i < N; i++) {
      const p = out[i], inset = slabInset(p, ts[k]) * flip;
      row.push(new THREE.Vector3(p.x + inward[i][0] * inset, SLAB.top - ts[k] * SLAB.thick, p.z + inward[i][1] * inset));
    }
    P.push(row);
  }
  // analytic-ish normals from the grid (central differences, wrapping around the outline)
  const Nrm: THREE.Vector3[][] = [];
  for (let k = 0; k < K; k++) {
    const row: THREE.Vector3[] = [];
    for (let i = 0; i < N; i++) {
      const ds = P[k][(i + 1) % N].clone().sub(P[k][(i - 1 + N) % N]);
      const dt = P[Math.min(K - 1, k + 1)][i].clone().sub(P[Math.max(0, k - 1)][i]);
      const n = new THREE.Vector3().crossVectors(dt, ds).normalize();
      // ensure outward (away from the inward normal)
      if (n.x * inward[i][0] * flip + n.z * inward[i][1] * flip > 0) n.negate();
      row.push(n);
    }
    Nrm.push(row);
  }
  const uTop = (x: number) => (x - UVF.xa) / (UVF.xb - UVF.xa);
  const vTop = (z: number) => 1 - (z - UVF.za) / (UVF.zb - UVF.za);
  const pos: number[] = [], nor: number[] = [], uv: number[] = [];
  const groups: { start: number; count: number; mat: number }[] = [];
  let vcount = 0;
  const idx: number[] = [];
  const emitGroup = (mat: number, fn: () => void) => {
    const start = idx.length;
    fn();
    groups.push({ start, count: idx.length - start, mat });
  };
  const vert = (p: THREE.Vector3, n: THREE.Vector3, u: number, v: number) => {
    pos.push(p.x, p.y, p.z);
    nor.push(n.x, n.y, n.z);
    uv.push(u, v);
    return vcount++;
  };
  // --- sides: split into runs of the same material, each run gets its own vertex strip
  const matOf = (p: OP) => (p.kind === 'live' ? 1 : p.kind === 'end' ? 2 : 0);
  const runs: { mat: number; ids: number[] }[] = [];
  for (let i = 0; i < N; i++) {
    const m = matOf(out[i]);
    if (!runs.length || runs[runs.length - 1].mat !== m) runs.push({ mat: m, ids: [] });
    runs[runs.length - 1].ids.push(i);
  }
  // close each run with the first index of the next run so there are no gaps
  for (let r = 0; r < runs.length; r++) runs[r].ids.push(runs[(r + 1) % runs.length].ids[0]);
  if (runs.length > 1 && runs[0].mat === runs[runs.length - 1].mat) {
    // merge wrap-around run
    const last = runs.pop()!;
    runs[0].ids = [...last.ids.slice(0, -1), ...runs[0].ids];
  }
  const sideUV = (mat: number, i: number, k: number): [number, number] => {
    const p = out[i], t = ts[k];
    if (mat === 1) return [uTop(p.x), 1 - t];
    if (mat === 2) return [(p.z - UVF.za) / (UVF.xb - UVF.xa) + 0.13, 0.5 - (t * SLAB.thick) / (UVF.zb - UVF.za)];
    return [uTop(p.x), vTop(p.z) + (0.004 + t * 0.045) / (UVF.zb - UVF.za)];
  };
  for (const run of runs) {
    emitGroup(run.mat, () => {
      const base: number[][] = [];
      for (let k = 0; k < K; k++) base.push(run.ids.map((i) => vert(P[k][i], Nrm[k][i], ...sideUV(run.mat, i, k))));
      for (let k = 0; k < K - 1; k++)
        for (let j = 0; j < run.ids.length - 1; j++) {
          const a = base[k][j], b = base[k][j + 1], c = base[k + 1][j], d = base[k + 1][j + 1];
          if (flip > 0) idx.push(a, b, c, b, d, c);
          else idx.push(a, c, b, b, c, d);
        }
    });
  }
  // --- caps
  const cap = (k: number, up: boolean, mat: number) => {
    const contour = P[k].map((p) => new THREE.Vector2(p.x, p.z));
    const tris = THREE.ShapeUtils.triangulateShape(contour, []);
    const n = new THREE.Vector3(0, up ? 1 : -1, 0);
    emitGroup(mat, () => {
      const ids = P[k].map((p) => vert(p, n, uTop(p.x), vTop(p.z)));
      for (const [a, b, c] of tris) {
        // shape winding in (x,z): decide orientation so the face normal matches n
        const A = P[k][a], B = P[k][b], C = P[k][c];
        const ny = (B.z - A.z) * (C.x - A.x) - (B.x - A.x) * (C.z - A.z);
        if (ny > 0 === up) idx.push(ids[a], ids[b], ids[c]);
        else idx.push(ids[a], ids[c], ids[b]);
      }
    });
  };
  cap(0, true, 0);
  cap(K - 1, false, 3);
  const g = new THREE.BufferGeometry();
  g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
  g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
  g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
  g.setIndex(idx);
  for (const gr of groups) g.addGroup(gr.start, gr.count, gr.mat);
  return g;
}

// =============================================================================================
// MONITOR (BenQ RD280U: 610.4 × 427.8 mm, 87 mm deep; screen 596 × 397)

const MON = { w: 0.6104, h: 0.4278, sw: 0.5962, sh: 0.3975, top: 0.007, depth: 0.087 };

/** rear shell: a pillow that bulges from 12 mm at the rim to ~36 mm deep, local z ≤ 0 */
function monitorShell() {
  const nx = 48, ny = 36;
  const { w, h } = MON;
  const r = 0.008;
  const g = new THREE.PlaneGeometry(w, h, nx, ny);
  const p = g.getAttribute('position');
  for (let i = 0; i < p.count; i++) {
    const x = p.getX(i), y = p.getY(i);
    // distance to the rim (rounded rect), 0 at the edge
    const dx = w / 2 - Math.abs(x), dy = h / 2 - Math.abs(y);
    const dRim = Math.min(dx, dy);
    const depth = 0.013 + 0.024 * ease(clamp01(dRim / 0.13));
    p.setZ(i, depth); // becomes -depth after the rotateY(π) below
  }
  // shape the corners: pull outer vertices inside the rounded rect
  for (let i = 0; i < p.count; i++) {
    const x = p.getX(i), y = p.getY(i);
    const cx = w / 2 - r, cy = h / 2 - r;
    const ax = Math.abs(x), ay = Math.abs(y);
    if (ax > cx && ay > cy) {
      const vx = ax - cx, vy = ay - cy, l = Math.hypot(vx, vy);
      if (l > r) {
        p.setX(i, Math.sign(x) * (cx + (vx / l) * r));
        p.setY(i, Math.sign(y) * (cy + (vy / l) * r));
      }
    }
  }
  g.rotateY(Math.PI); // face -z (backwards)
  // after rotateY(π) x is mirrored; UVs stay as generated (u across the back as seen from behind)
  g.computeVertexNormals();
  return g;
}

/** side band joining the front bezel (z=0..-0.004) to the shell rim (z=-0.013) */
function monitorRim() {
  const s = roundedRectShape(MON.w - 0.0028, MON.h - 0.0028, 0.007); // inset so the silver bevel stays behind the black bezel
  const g = new THREE.ExtrudeGeometry(s, { depth: 0.012, bevelEnabled: true, bevelThickness: 0.0012, bevelSize: 0.0012, bevelSegments: 2, curveSegments: 6 });
  g.translate(0, 0, -0.0132);
  return g;
}

// =============================================================================================

export async function build(ctx: PartContext) {
  const root = new THREE.Group();
  root.name = 'desk';
  const files = ['desk-slab-top.jpg', 'desk-slab-top-nor.jpg', 'desk-slab-top-rough.jpg', 'desk-slab-edge.jpg', 'desk-slab-edge-nor.jpg', 'desk-mon-back-nor.jpg', 'desk-mon-back-stickers.jpg', 'desk-mon-wide.jpg', 'desk-mon-tall.jpg'];
  await Promise.all(files.map(async (f) => cache.set(f, await loader.loadAsync(TEX + f))));

  // ---------------------------------------------------------------- materials
  const topMap = load('desk-slab-top.jpg');
  const topNor = load('desk-slab-top-nor.jpg', false);
  const topRough = load('desk-slab-top-rough.jpg', false);
  const walnutTop = new THREE.MeshPhysicalMaterial({
    name: 'walnutTop', map: topMap, normalMap: topNor, normalScale: new THREE.Vector2(0.2, 0.2), roughnessMap: topRough, roughness: 1,
    clearcoat: 0.35, clearcoatRoughness: 0.3, specularIntensity: 0.3,
  });
  const walnutLive = new THREE.MeshPhysicalMaterial({
    name: 'walnutLive', map: load('desk-slab-edge.jpg'), normalMap: load('desk-slab-edge-nor.jpg', false), normalScale: new THREE.Vector2(1.4, 1.4),
    roughness: 0.62, clearcoat: 0.25, clearcoatRoughness: 0.45,
  });
  const walnutEnd = new THREE.MeshPhysicalMaterial({ name: 'walnutEnd', map: topMap, color: '#9a8070', normalMap: topNor, roughness: 0.55, clearcoat: 0.3, clearcoatRoughness: 0.4 });
  const walnutUnder = new THREE.MeshStandardMaterial({ name: 'walnutUnder', map: topMap, color: '#b8a898', roughness: 0.85 });

  const coatNor = noiseNormal(256, 24, 1.6, 3);
  coatNor.repeat.set(6, 6);
  const powder = new THREE.MeshPhysicalMaterial({ name: 'powder', color: '#17171a', roughness: 0.5, metalness: 0.25, normalMap: coatNor, normalScale: new THREE.Vector2(0.35, 0.35), clearcoat: 0.25, clearcoatRoughness: 0.5 });
  const armBlack = new THREE.MeshPhysicalMaterial({ name: 'armBlack', color: '#141416', roughness: 0.42, metalness: 0.3, normalMap: coatNor, normalScale: new THREE.Vector2(0.25, 0.25), clearcoat: 0.35, clearcoatRoughness: 0.35 });
  const plasticBlack = new THREE.MeshPhysicalMaterial({ name: 'plasticBlack', color: '#101012', roughness: 0.55, clearcoat: 0.1 });
  const rubber = new THREE.MeshStandardMaterial({ name: 'rubber', color: '#0b0b0c', roughness: 0.9 });
  const chrome = new THREE.MeshStandardMaterial({ name: 'chrome', color: '#d6d8dc', roughness: 0.18, metalness: 1 });
  const steel = new THREE.MeshStandardMaterial({ name: 'steel', color: '#b9bcc1', roughness: 0.32, metalness: 1 });
  const cableMat = new THREE.MeshStandardMaterial({ name: 'cable', color: '#0e0e10', roughness: 0.55 });
  const redCable = new THREE.MeshStandardMaterial({ name: 'redCable', color: '#9c1418', roughness: 0.5 });

  // ================================================================ SLAB + FRAME (static)
  const desk = new THREE.Group();
  desk.name = 'desk-slab-frame';
  tag(desk, { type: 'static' });
  root.add(desk);
  {
    const slab = new THREE.Mesh(slabGeometry(), [walnutTop, walnutLive, walnutEnd, walnutUnder]);
    slab.name = 'desk-slab';
    slab.castShadow = slab.receiveShadow = true;
    desk.add(slab);
  }
  const fb = new Batch();
  const BOT = SLAB.top - SLAB.thick; // underside of the slab (0.773)
  const LEGS = [0.35, 1.98];
  const ZC = -0.35; // frame centre line (front-back)
  for (const lx of LEGS) {
    // foot: tapered side profile, chamfered ends, 70 mm wide
    const L = 0.72, hC = 0.046, hE = 0.026;
    const prof: [number, number][] = [
      [-L / 2 + 0.012, 0.0], [L / 2 - 0.012, 0.0], [L / 2, hE * 0.55], [L / 2 - 0.008, hE], [0.07, hC], [-0.07, hC], [-L / 2 + 0.008, hE], [-L / 2, hE * 0.55],
    ];
    const foot = extrude(prof, 0.07, 0.003, 2);
    // profile x = along z, profile y = up, extrusion = x → rotate so extrusion axis is world x
    foot.rotateY(Math.PI / 2);
    fb.add(foot, powder, T(lx, 0.008, ZC));
    for (const dz of [-0.3, 0.3]) {
      fb.add(cyl(0.017, 0.019, 0.008, 20), rubber, T(lx, 0.004, ZC + dz));
      fb.add(cyl(0.006, 0.006, 0.01, 10), steel, T(lx, 0.012, ZC + dz));
    }
    // 3 columns (widest on top, motor housing at the top)
    const stages: [number, number, number, number][] = [
      // [w(x), d(z), y0, y1]
      [0.05, 0.072, 0.048, 0.3],
      [0.056, 0.079, 0.29, 0.52],
      [0.063, 0.087, 0.51, BOT - 0.03],
    ];
    for (const [w, d, y0, y1] of stages) {
      fb.add(rb(w, y1 - y0, d, 0.006, 2), powder, T(lx, (y0 + y1) / 2, ZC));
      // plastic bushing collar at the top of each inner stage
      fb.add(rb(w + 0.004, 0.012, d + 0.004, 0.004, 2), plasticBlack, T(lx, y1 - 0.004, ZC));
    }
    // column base plate on the foot
    fb.add(rb(0.07, 0.01, 0.11, 0.003, 2), powder, T(lx, 0.058, ZC));
    // top housing + mounting plate
    fb.add(rb(0.075, 0.03, 0.105, 0.006, 2), powder, T(lx, BOT - 0.015, ZC));
    // side bracket along z under the slab (C-channel look: flange + web)
    fb.add(rb(0.05, 0.004, 0.66, 0.002, 1), powder, T(lx, BOT - 0.002, ZC));
    fb.add(rb(0.004, 0.028, 0.66, 0.0015, 1), powder, T(lx - 0.023, BOT - 0.016, ZC));
    fb.add(rb(0.004, 0.028, 0.66, 0.0015, 1), powder, T(lx + 0.023, BOT - 0.016, ZC));
    for (const dz of [-0.3, -0.1, 0.1, 0.3]) fb.add(cyl(0.005, 0.005, 0.004, 10), steel, T(lx, BOT - 0.005, ZC + dz)); // screws
  }
  // crossbar (rectangular tube) between the column tops
  {
    const x0 = LEGS[0] + 0.04, x1 = LEGS[1] - 0.04;
    fb.add(rb(x1 - x0, 0.045, 0.055, 0.004, 2), powder, T((x0 + x1) / 2, BOT - 0.055, ZC));
    // controller box under the crossbar + cables to the motors
    fb.add(rb(0.19, 0.036, 0.085, 0.006, 2), plasticBlack, T(1.3, BOT - 0.098, ZC));
    const cp = (pts: V3[], r = 0.0035) => fb.add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts.map((p) => new THREE.Vector3(...p))), 40, r, 6), cableMat);
    cp([[1.2, BOT - 0.1, ZC + 0.04], [0.9, BOT - 0.12, ZC + 0.05], [0.5, BOT - 0.1, ZC + 0.05], [LEGS[0] + 0.04, BOT - 0.05, ZC + 0.04]]);
    cp([[1.4, BOT - 0.1, ZC + 0.04], [1.7, BOT - 0.12, ZC + 0.05], [LEGS[1] - 0.04, BOT - 0.05, ZC + 0.04]]);
    cp([[1.3, BOT - 0.1, ZC - 0.04], [1.32, BOT - 0.2, ZC - 0.08], [1.36, 0.25, ZC - 0.1], [1.4, 0.012, ZC - 0.2], [1.5, 0.012, -0.8]], 0.004);
    // hand controller at the front right under the edge (up/down + memory keys, LED display)
    const kx = 1.9, kz = liveZ(1.9) - 0.035;
    fb.add(rb(0.13, 0.022, 0.055, 0.008, 3), plasticBlack, T(kx, BOT - 0.012, kz));
    const disp = canvasTex(128, 48, (c, w, h) => {
      c.fillStyle = '#050505';
      c.fillRect(0, 0, w, h);
      c.fillStyle = '#ff3b2a';
      c.font = 'bold 34px monospace';
      c.textAlign = 'center';
      c.textBaseline = 'middle';
      c.fillText('32.5', w / 2, h / 2 + 2);
    });
    const dispMat = new THREE.MeshBasicMaterial({ name: 'deskDisplay', map: disp, toneMapped: false });
    const pl = new THREE.PlaneGeometry(0.03, 0.011);
    fb.add(pl, dispMat, T(kx - 0.03, BOT - 0.012, kz + 0.0277));
    for (let k = 0; k < 4; k++) fb.add(cyl(0.005, 0.005, 0.003, 12), rubber, T(kx + 0.005 + k * 0.014, BOT - 0.012, kz + 0.028, 0, Math.PI / 2));
  }
  fb.build(desk, 'desk-frame');

  // ================================================================ MONITORS + POLE MOUNT (static)
  const mounts = new THREE.Group();
  mounts.name = 'desk-monitors';
  tag(mounts, { type: 'static' });
  root.add(mounts);
  const mb = new Batch();
  const Y = SLAB.top;

  const backNor = load('desk-mon-back-nor.jpg', false);
  const shellMat = new THREE.MeshPhysicalMaterial({ name: 'monShell', color: '#b4b6ba', roughness: 0.42, metalness: 0.1, normalMap: backNor, normalScale: new THREE.Vector2(0.28, 0.28), clearcoat: 0.2, clearcoatRoughness: 0.35 });
  const shellStick = new THREE.MeshPhysicalMaterial({ name: 'monShellStickers', color: '#d2d3d6', map: load('desk-mon-back-stickers.jpg'), roughness: 0.42, metalness: 0.1, normalMap: backNor, normalScale: new THREE.Vector2(0.28, 0.28), clearcoat: 0.2, clearcoatRoughness: 0.35 });
  const rimMat = new THREE.MeshPhysicalMaterial({ name: 'monRim', color: '#c9cbce', roughness: 0.35, metalness: 0.2 });
  const bezel = new THREE.MeshPhysicalMaterial({ name: 'bezel', color: '#0a0a0b', roughness: 0.35, clearcoat: 0.4 });
  const recess = new THREE.MeshStandardMaterial({ name: 'monRecess', color: '#3a3b3e', roughness: 0.6, metalness: 0.2 });
  const halo = new THREE.MeshBasicMaterial({ name: 'moonHalo', color: '#ffffff', toneMapped: false });
  const glowTex = canvasTex(256, 256, (c, w, h) => {
    const g = c.createRadialGradient(w / 2, h / 2, w * 0.2, w / 2, h / 2, w / 2);
    g.addColorStop(0, 'rgba(255,255,255,1)');
    g.addColorStop(0.18, 'rgba(255,252,246,0.75)');
    g.addColorStop(0.5, 'rgba(255,248,238,0.22)');
    g.addColorStop(1, 'rgba(255,248,238,0)');
    c.fillStyle = g;
    c.fillRect(0, 0, w, h);
    c.clearRect(0, 0, 0, 0);
  });
  const glowMat = new THREE.MeshBasicMaterial({ name: 'haloGlow', map: glowTex, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false, opacity: 0.5, color: '#fff4e8' });
  const screenMat = (file: string, name: string) =>
    new THREE.MeshStandardMaterial({ name, color: '#050506', roughness: 0.5, emissive: '#ffffff', emissiveMap: load(file), emissiveIntensity: 1.05 });
  const wideScreen = screenMat('desk-mon-wide.jpg', 'screenWide');
  const tallScreen = screenMat('desk-mon-tall.jpg', 'screenTall');
  const logoTex = canvasTex(256, 64, (c, w, h) => {
    c.clearRect(0, 0, w, h);
    c.fillStyle = 'rgba(120,122,126,1)';
    c.font = 'bold 44px Helvetica, Arial, sans-serif';
    c.textAlign = 'center';
    c.textBaseline = 'middle';
    c.fillText('BenQ', w / 2, h / 2 + 2);
  });
  const logoMat = new THREE.MeshStandardMaterial({ name: 'benqLogo', map: logoTex, transparent: true, roughness: 0.3, metalness: 0.4, depthWrite: false });
  const frontLogoTex = canvasTex(128, 32, (c, w, h) => {
    c.clearRect(0, 0, w, h);
    c.fillStyle = 'rgba(160,160,165,1)';
    c.font = 'bold 22px Helvetica, Arial, sans-serif';
    c.textAlign = 'center';
    c.textBaseline = 'middle';
    c.fillText('BenQ', w / 2, h / 2 + 1);
  });
  const frontLogo = new THREE.MeshBasicMaterial({ name: 'benqFront', map: frontLogoTex, transparent: true, depthWrite: false, color: '#777' });

  const shellGeo = monitorShell();
  const rimGeo = monitorRim();
  /** one RD280U, local frame: origin = centre of the front face, +z toward the viewer, landscape */
  const monitor = (m: THREE.Matrix4, screen: THREE.Material, stickers: boolean, portrait: boolean) => {
    mb.push(m);
    if (portrait) mb.push(T(0, 0, 0, 0, 0, Math.PI / 2));
    // front bezel face + screen
    const face = new THREE.ShapeGeometry(roundedRectShape(MON.w, MON.h, 0.008), 6);
    mb.add(face, bezel, T(0, 0, -0.0005));
    mb.add(rimGeo, rimMat);
    const sy = MON.h / 2 - MON.top - MON.sh / 2;
    const scr = new THREE.PlaneGeometry(MON.sw, MON.sh);
    if (portrait) {
      // portrait content is authored upright: rotate UVs by 90° so the texture reads upright on screen
      const uv = scr.getAttribute('uv');
      for (let i = 0; i < uv.count; i++) {
        const u = uv.getX(i), v = uv.getY(i);
        uv.setXY(i, 1 - v, u);
      }
    }
    mb.add(scr, screen, T(0, sy, 0.0004));
    mb.add(new THREE.PlaneGeometry(0.03, 0.0075), frontLogo, T(0, -MON.h / 2 + 0.011, 0.0006));
    // rear shell
    mb.add(shellGeo, stickers ? shellStick : shellMat);
    // MoonHalo module: boss, glowing ring, recessed VESA well
    const boss = new THREE.LatheGeometry([[0.0, -0.037], [0.118, -0.037], [0.121, -0.041], [0.118, -0.05], [0.104, -0.052], [0.0, -0.052]].map(([r, z]) => new THREE.Vector2(r, z)), 64);
    boss.rotateX(Math.PI / 2); // lathe axis y → z (profile y ≤ 0 → behind the panel)
    mb.add(boss, shellMat);
    const ring = new THREE.RingGeometry(0.1, 0.1125, 72);
    mb.add(ring, halo, T(0, 0, -0.0515, Math.PI));
    const well = new THREE.CylinderGeometry(0.086, 0.086, 0.03, 48, 1, true);
    mb.add(well, recess, T(0, 0, -0.052, 0, Math.PI / 2));
    mb.add(new THREE.CircleGeometry(0.086, 48), recess, T(0, 0, -0.036, Math.PI));
    // VESA plate + tilt head inside the well
    mb.add(rb(0.1, 0.1, 0.008, 0.004, 1), armBlack, T(0, 0, -0.04));
    for (const [ax, ay] of [[-0.05, -0.05], [0.05, -0.05], [-0.05, 0.05], [0.05, 0.05]]) mb.add(cyl(0.004, 0.004, 0.004, 8), steel, T(ax * 0.9, ay * 0.9, -0.045, 0, Math.PI / 2));
    // I/O recess strip at the bottom of the back
    mb.add(rb(0.26, 0.022, 0.012, 0.004, 1), recess, T(0, -MON.h / 2 + 0.045, -0.024));
    // back logo
    mb.add(new THREE.PlaneGeometry(0.075, 0.019), logoMat, T(0, -MON.h / 2 + 0.085, -0.0335, Math.PI));
    if (portrait) mb.pop();
    mb.pop();
  };

  // monitor poses (front-face centre, yaw); measured from the scan + photos 13/14/25/26/29/88
  const wideM = T(1.16, 1.209, -0.39, 0.03, -0.03);
  const tallM = T(0.67, 1.2, -0.27, 0.45, -0.02);
  monitor(wideM, wideScreen, false, false);
  monitor(tallM, tallScreen, true, true);
  // glow decals on the shells around the halo (additive, no collider)
  const glow = new THREE.Group();
  glow.name = 'desk-halo-glow';
  tag(glow, { type: 'none' });
  root.add(glow);
  for (const m of [wideM, tallM]) {
    const q = new THREE.Mesh(new THREE.PlaneGeometry(0.5, 0.5), glowMat);
    q.applyMatrix4(m.clone().multiply(T(0, 0, -0.0395, Math.PI)));
    q.renderOrder = 2;
    glow.add(q);
  }

  // ---- pole mount: base plate on the desk, 35 mm pole, collars, articulated arms to both VESA heads
  const PX = 1.27, PZ = -0.58;
  mb.add(extrude([[-0.075, 0], [0.075, 0], [0.06, 0.012], [-0.06, 0.012]], 0.11, 0.003), armBlack, T(PX + 0.02, Y, PZ + 0.01, 0.3));
  mb.add(cyl(0.032, 0.036, 0.03, 28), armBlack, T(PX, Y + 0.027, PZ));
  const POLE_TOP = 1.335;
  mb.add(cyl(0.0175, 0.0175, POLE_TOP - Y - 0.03, 24), armBlack, T(PX, (Y + 0.03 + POLE_TOP) / 2, PZ));
  mb.add(cyl(0.019, 0.019, 0.012, 24), plasticBlack, T(PX, POLE_TOP + 0.006, PZ));
  const vesaPt = (m: THREE.Matrix4) => new THREE.Vector3(0, 0, -0.055).applyMatrix4(m);
  const arm = (yCollar: number, target: THREE.Vector3, bend: number, segH: number, w = 0.042, kr = 0.028) => {
    const P0 = new THREE.Vector3(PX, yCollar, PZ);
    mb.add(cyl(kr + 0.004, kr + 0.004, segH + 0.03, 28), armBlack, T(PX, yCollar, PZ));
    mb.add(cyl(0.012, 0.012, 0.008, 12), steel, T(PX + kr + 0.006, yCollar, PZ, 0, 0, Math.PI / 2)); // lock knob
    // elbow: offset sideways from the midpoint
    const mid = P0.clone().add(target).multiplyScalar(0.5);
    const dir = target.clone().sub(P0).setY(0).normalize();
    const side = new THREE.Vector3(-dir.z, 0, dir.x).multiplyScalar(bend);
    const E = mid.clone().add(side);
    E.y = yCollar;
    const V = target.clone();
    V.y = yCollar;
    mb.add(beam(P0, E, w, segH, 0.012), armBlack);
    mb.add(cyl(kr, kr, segH + 0.03, 28), armBlack, T(E.x, E.y, E.z));
    mb.add(cyl(kr * 0.7, kr * 0.7, 0.008, 20), plasticBlack, T(E.x, E.y + segH / 2 + 0.019, E.z));
    const dV = V.clone().sub(E).setY(0).normalize();
    const Vb = V.clone().addScaledVector(dV, -0.04);
    mb.add(beam(E, Vb, w * 0.9, segH * 0.85, 0.011), armBlack);
    // VESA head: vertical knuckle + tilt block into the monitor well
    mb.add(cyl(0.022, 0.022, 0.075, 24), armBlack, T(Vb.x, yCollar + 0.01, Vb.z));
    mb.add(beam(Vb, target, 0.035, 0.04, 0.008), armBlack);
    // cable clips
    mb.add(rb(0.02, 0.012, 0.03, 0.004), plasticBlack, T(E.x * 0.5 + P0.x * 0.5, yCollar + segH / 2 + 0.006, E.z * 0.5 + P0.z * 0.5));
  };
  arm(vesaPt(wideM).y, vesaPt(wideM), 0.07, 0.05);
  arm(0.97, vesaPt(tallM).setY(0.97), -0.1, 0.07, 0.056, 0.034); // the big gas-spring arm (photos 13/14)
  // the portrait VESA sits higher than the lower arm: vertical riser at its head
  {
    const v = vesaPt(tallM);
    const dV = v.clone().sub(new THREE.Vector3(PX, v.y, PZ)).setY(0).normalize();
    const b = v.clone().addScaledVector(dV, -0.04);
    mb.add(cyl(0.02, 0.02, v.y - 0.97 + 0.03, 24), armBlack, T(b.x, (v.y + 0.97) / 2, b.z));
    mb.add(beam(new THREE.Vector3(b.x, v.y, b.z), v, 0.035, 0.04, 0.008), armBlack);
  }
  // tall black pole from the desk top to the ceiling behind the east end of the landscape monitor
  // (triangulated from photos 13/14/88 at (1.45, -0.52); a light/camera boom clamps to it near the top)
  {
    const tx = 1.45, tz = -0.52, top = ctx.revision === 'october-7' ? 1.80 : ctx.ceiling;
    mb.add(cyl(0.045, 0.05, 0.012, 28), armBlack, T(tx, Y + 0.006, tz));
    mb.add(cyl(0.016, 0.016, top - Y - 0.03, 20), armBlack, T(tx, (Y + top) / 2, tz));
    mb.add(cyl(0.035, 0.035, 0.02, 24), rubber, T(tx, top - 0.01, tz));
    if (ctx.revision !== 'october-7') mb.add(cyl(0.024, 0.024, 0.06, 20), armBlack, T(tx, 1.86, tz));
    mb.add(cyl(0.02, 0.02, 0.07, 20), armBlack, T(tx, Y + 0.05, tz)); // height-adjust collar
    if (ctx.revision !== 'october-7') mb.add(beam(new THREE.Vector3(tx, 1.86, tz), new THREE.Vector3(tx - 0.22, 1.9, tz + 0.06), 0.022, 0.022, 0.006), armBlack);
  }
  // monitor cables: from the I/O strips down the pole to the back edge
  {
    const cp = (pts: V3[], mat: THREE.Material = cableMat, r = 0.0033) => mb.add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts.map((p) => new THREE.Vector3(...p))), 60, r, 6), mat);
    const wIO = new THREE.Vector3(0.05, -MON.h / 2 + 0.045, -0.03).applyMatrix4(wideM);
    const tIO = new THREE.Vector3(-MON.h / 2 + 0.045, 0.02, -0.03).applyMatrix4(tallM);
    for (const [k, off] of [[0, 0], [1, 0.012]] as const) {
      cp([[wIO.x + off, wIO.y, wIO.z], [wIO.x + 0.02 + off, wIO.y - 0.08, wIO.z - 0.06], [PX + 0.02, 1.05 - k * 0.02, PZ + 0.02], [PX + 0.025, Y + 0.12, PZ + 0.02], [PX + 0.04, Y + 0.005, PZ - 0.06], [PX + 0.05 + off, Y + 0.004, SLAB.back + 0.04], [PX + 0.05 + off, Y - 0.01, SLAB.back - 0.012], [PX + 0.06 + off, 0.45, SLAB.back - 0.02]]);
      cp([[tIO.x, tIO.y + off, tIO.z], [tIO.x + 0.04, tIO.y - 0.1, tIO.z - 0.03], [0.85, 0.95, -0.6], [0.95, Y + 0.004, -0.72 - off], [1.0 + off, Y + 0.004, SLAB.back + 0.03], [1.0 + off, Y - 0.012, SLAB.back - 0.012], [1.02 + off, 0.45, SLAB.back - 0.02]]);
    }
  }
  mb.build(mounts, 'desk-monitors');

  // soft glow of the two MoonHalo rings onto the shells / wall behind (off by default: every extra
  // forward light costs every lit pixel of the room; ?halolights turns them back on)
  if (new URLSearchParams(globalThis.location?.search ?? '').has('halolights')) for (const m of [wideM, tallM]) {
    const p = new THREE.Vector3(0, 0, -0.45).applyMatrix4(m);
    const l = new THREE.PointLight('#fff3e6', 0.18, 1.4, 2);
    l.position.copy(p);
    ctx.addLight(l);
  }

  // ================================================================ KEYBOARD (dynamic)
  {
    const kb = new THREE.Group();
    kb.name = 'desk-keyboard';
    tag(kb, { type: 'dynamic', mass: 0.39, shape: 'box' });
    const KW = 0.4187, KD = 0.1149;
    const bat = new Batch();
    const alu = new THREE.MeshPhysicalMaterial({ name: 'kbAlu', color: '#c4c5c8', roughness: 0.55, metalness: 0.7, normalMap: noiseNormal(128, 40, 0.6, 9), normalScale: new THREE.Vector2(0.15, 0.15) });
    const bottom = new THREE.MeshStandardMaterial({ name: 'kbBottom', color: '#e9e9e7', roughness: 0.5 });
    // wedge body: side profile (z → y), 4.1 mm at the front, 10.9 at the back
    // side profile (z → y): 4.1 mm at the front, 10.9 mm at the back (the 1.5 mm bevel grows the shape, so it is drawn inset)
    const bv = 0.0015;
    const prof: [number, number][] = [[-KD / 2 + bv, bv], [KD / 2 - bv, bv], [KD / 2 - bv, 0.0041 - bv], [KD / 2 - 0.005, 0.0046 - bv], [-KD / 2 + 0.004, 0.0107 - bv], [-KD / 2 + bv, 0.0103 - bv]];
    const body = extrude(prof.map(([z, y]) => [-z, y] as [number, number]), KW, bv, 2);
    body.rotateY(Math.PI / 2);
    bat.add(body, alu);
    bat.add(rb(KW - 0.02, 0.001, KD - 0.02, 0.0005, 1), bottom, T(0, -0.0003, 0));
    // keys (Apple extended layout); legends on a canvas mapped over the top
    const gapK = 0.0032, margin = 0.0082;
    type Key = { x: number; z: number; w: number; d: number; label: string };
    const keys: Key[] = [];
    const rowD = [0.62, 1, 1, 1, 1, 1];
    const rows: [number, string][][] = [
      [[1, 'esc'], [1, 'F1'], [1, 'F2'], [1, 'F3'], [1, 'F4'], [1, 'F5'], [1, 'F6'], [1, 'F7'], [1, 'F8'], [1, 'F9'], [1, 'F10'], [1, 'F11'], [1, 'F12'], [1, 'F13'], [1, '●']],
      [[1, '~'], [1, '1'], [1, '2'], [1, '3'], [1, '4'], [1, '5'], [1, '6'], [1, '7'], [1, '8'], [1, '9'], [1, '0'], [1, '-'], [1, '='], [2, 'delete']],
      [[1.5, 'tab'], [1, 'Q'], [1, 'W'], [1, 'E'], [1, 'R'], [1, 'T'], [1, 'Y'], [1, 'U'], [1, 'I'], [1, 'O'], [1, 'P'], [1, '['], [1, ']'], [1.5, '\\']],
      [[1.75, 'caps'], [1, 'A'], [1, 'S'], [1, 'D'], [1, 'F'], [1, 'G'], [1, 'H'], [1, 'J'], [1, 'K'], [1, 'L'], [1, ';'], [1, "'"], [2.25, 'return']],
      [[2.25, 'shift'], [1, 'Z'], [1, 'X'], [1, 'C'], [1, 'V'], [1, 'B'], [1, 'N'], [1, 'M'], [1, ','], [1, '.'], [1, '/'], [2.75, 'shift']],
      [[1.25, 'ctrl'], [1.25, 'opt'], [1.5, '⌘'], [6.5, ''], [1.5, '⌘'], [1.25, 'opt'], [1.75, '']],
    ];
    const navRows: [number, string][][] = [
      [[1, 'F14'], [1, 'F15'], [1, 'F16']],
      [[1, 'fn'], [1, '↖'], [1, '⇞']],
      [[1, '⌦'], [1, '↘'], [1, '⇟']],
      [],
      [[1, ''], [1, '▲'], [1, '']],
      [[1, '◀'], [1, '▼'], [1, '▶']],
    ];
    const numRows: [number, string][][] = [
      [[1, 'F17'], [1, 'F18'], [1, 'F19'], [1, '']],
      [[1, 'clear'], [1, '='], [1, '/'], [1, '*']],
      [[1, '7'], [1, '8'], [1, '9'], [1, '−']],
      [[1, '4'], [1, '5'], [1, '6'], [1, '+']],
      [[1, '1'], [1, '2'], [1, '3'], [1, '']],
      [[2, '0'], [1, '.'], [1, '']],
    ];
    const usable = KW - 2 * margin;
    const unitsW = 15 + 0.35 + 3 + 0.35 + 4;
    const P = usable / unitsW; // key pitch
    let zRow = -KD / 2 + margin * 0.9;
    const pitchZ = (KD - 2 * margin * 0.9) / (rowD.reduce((a, b) => a + b, 0));
    const xMain = -KW / 2 + margin, xNav = xMain + (15 + 0.35) * P, xNum = xNav + (3 + 0.35) * P;
    rows.forEach((row, r) => {
      const d = rowD[r] * pitchZ;
      /** lay keys left→right; `skip(i)` leaves a hole (no key) at that slot */
      const put = (list: [number, string][], x0: number, skip: (i: number) => boolean = () => false) => {
        let x = x0;
        list.forEach(([w, label], i) => {
          if (!skip(i)) keys.push({ x: x + (w * P) / 2, z: zRow + d / 2, w: w * P - gapK, d: d - gapK, label });
          x += w * P;
        });
      };
      put(row, xMain);
      put(navRows[r], xNav, (i) => r === 4 && i !== 1);
      // numeric keypad: the enter key spans the last two rows
      put(numRows[r], xNum, (i) => (r === 4 && i === 3) || (r === 5 && i === 2));
      if (r === 4) keys.push({ x: xNum + 3.5 * P, z: zRow + d, w: P - gapK, d: 2 * d - gapK, label: 'enter' });
      zRow += d;
    });
    const legend = canvasTex(2048, 560, (c, w, h) => {
      c.fillStyle = '#1b1b1d';
      c.fillRect(0, 0, w, h);
      const sx = w / KW, sz = h / KD;
      for (const k of keys) {
        const cx = (k.x + KW / 2) * sx, cz = (k.z + KD / 2) * sz;
        c.fillStyle = '#e8e8ea';
        const fs = k.label.length > 2 ? 15 : k.label.length === 2 ? 17 : 24;
        c.font = `${fs}px Helvetica, Arial, sans-serif`;
        c.textAlign = 'center';
        c.textBaseline = 'middle';
        c.fillText(k.label, cx, cz);
      }
    });
    const keyMat = new THREE.MeshStandardMaterial({ name: 'kbKeys', map: legend, roughness: 0.62 });
    const keyGeos: THREE.BufferGeometry[] = [];
    for (const k of keys) {
      const g = rb(k.w, 0.0022, k.d, 0.0012, 1);
      const yk = 0.0046 + ((KD / 2 - 0.005 - k.z) / (KD - 0.009)) * (0.0107 - 0.0046); // aluminium top under the key
      g.translate(k.x, yk + 0.0009 - 0.0011, k.z);
      keyGeos.push(g);
    }
    const keysG = mergeGeometries(keyGeos.map((g) => (g.index ? g.toNonIndexed() : g)), false)!;
    const kp = keysG.getAttribute('position');
    const kuv = new Float32Array(kp.count * 2);
    for (let i = 0; i < kp.count; i++) {
      kuv[i * 2] = (kp.getX(i) + KW / 2) / KW;
      kuv[i * 2 + 1] = 1 - (kp.getZ(i) + KD / 2) / KD;
    }
    keysG.setAttribute('uv', new THREE.BufferAttribute(kuv, 2));
    bat.add(keysG, keyMat);
    bat.build(kb, 'desk-keyboard');
    kb.position.set(1.135, Y, -0.112);
    kb.rotation.y = 0.012;
    root.add(kb);
  }

  // ================================================================ MOUSE (dynamic) — Logitech MX Master 3S, graphite
  {
    const mouse = new THREE.Group();
    mouse.name = 'desk-mouse';
    tag(mouse, { type: 'dynamic', mass: 0.141, shape: 'hull' });
    const shell = new THREE.MeshPhysicalMaterial({ name: 'mouseShell', color: '#1f2023', roughness: 0.62, clearcoat: 0.08, clearcoatRoughness: 0.6, normalMap: noiseNormal(128, 30, 0.8, 5), normalScale: new THREE.Vector2(0.2, 0.2) });
    const dark = new THREE.MeshStandardMaterial({ name: 'mouseDark', color: '#101012', roughness: 0.75 });
    // local frame: +z = front (buttons), +x = the mouse's LEFT (thumb side), +y up; mm → m
    const plan = new THREE.CatmullRomCurve3(
      ([[0, 62.4], [17, 60], [26, 50], [29, 32], [33, 12], [41.5, -6], [41, -27], [32, -47], [15, -60], [0, -62.4], [-15, -60], [-30, -49], [-38, -30], [-40.5, -10], [-36, 10], [-31, 30], [-27, 48], [-17, 59]] as [number, number][]).map(([x, z]) => new THREE.Vector3(x / 1000, 0, z / 1000)),
      true, 'centripetal',
    );
    const topH = (x: number, z: number) => {
      const X = x * 1000, Z = z * 1000;
      let h = 51 * Math.exp(-(((Z + 14) / 62) ** 2) - (((X - 2) / 70) ** 2));
      h *= 1 - 0.42 * smooth(24, 40, X) * (1 - smooth(20, 50, Math.abs(Z + 5))); // low thumb shelf
      h = Math.max(h, 26 - 0.1 * Math.abs(X));
      return h / 1000;
    };
    const NA = 96, NR = 26;
    const ring = plan.getSpacedPoints(NA);
    const pos: number[] = [];
    const idx: number[] = [];
    const g2 = (rho: number) => Math.pow(Math.max(0, 1 - Math.pow(rho, 5)), 0.42);
    for (let r = 0; r <= NR; r++) {
      const rho = r / NR;
      for (let a = 0; a < NA; a++) {
        const q = ring[a];
        const x = q.x * rho, z = q.z * rho;
        const y = r === NR ? 0.0015 : Math.max(0.0015, topH(x, z) * g2(rho));
        pos.push(x, y, z);
      }
    }
    for (let r = 0; r < NR; r++)
      for (let a = 0; a < NA; a++) {
        const i0 = r * NA + a, i1 = r * NA + ((a + 1) % NA), j0 = (r + 1) * NA + a, j1 = (r + 1) * NA + ((a + 1) % NA);
        idx.push(i0, j0, i1, i1, j0, j1);
      }
    // bottom: flat plate (the shell rim rolls under slightly)
    const c0 = pos.length / 3;
    pos.push(0, 0.0015, 0);
    for (let a = 0; a < NA; a++) idx.push(c0, NR * NA + a, NR * NA + ((a + 1) % NA));
    const body = new THREE.BufferGeometry();
    body.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
    body.setIndex(idx);
    // winding check: first top triangle normal should point up
    body.computeVertexNormals();
    const nrm = body.getAttribute('normal');
    if (nrm.getY(NA * 2) < 0) {
      for (let i = 0; i < idx.length; i += 3) [idx[i + 1], idx[i + 2]] = [idx[i + 2], idx[i + 1]];
      body.setIndex(idx);
      body.computeVertexNormals();
    }
    const mbat = new Batch();
    mbat.add(body, shell);
    mbat.add(new THREE.ShapeGeometry(new THREE.Shape(ring.map((q) => new THREE.Vector2(q.x * 0.97, -q.z * 0.97)))).rotateX(-Math.PI / 2), dark, T(0, 0.0012, 0));
    // surface helper for small parts
    const onTop = (x: number, z: number) => topH(x, z);
    // MagSpeed scroll wheel in its slot
    const wz = 0.036, wy = onTop(0, wz);
    mbat.add(rb(0.012, 0.004, 0.03, 0.0015, 1), dark, T(0, wy - 0.0012, wz));
    mbat.add(cyl(0.0105, 0.0105, 0.0078, 36), steel, T(0, wy - 0.007, wz, 0, 0, Math.PI / 2));
    // button split + side seams (thin dark strips following the shell)
    const seamA: THREE.Vector3[] = [];
    for (let k = 0; k <= 14; k++) {
      const z = 0.012 + k * 0.0027;
      seamA.push(new THREE.Vector3(0, onTop(0, z) * g2(z / 0.0624) + 0.00025, z));
    }
    mbat.add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(seamA.filter((p) => p.z < wz - 0.012 || p.z > wz + 0.012)), 20, 0.0006, 4), dark);
    // thumb wheel + back/forward buttons on the thumb side
    mbat.add(cyl(0.0115, 0.0115, 0.005, 28), dark, T(0.03, 0.021, 0.004, 0, 0.9, 0.35));
    mbat.add(rb(0.004, 0.006, 0.012, 0.002, 1), dark, T(0.036, 0.016, -0.014, 0.25));
    mbat.add(rb(0.004, 0.006, 0.012, 0.002, 1), dark, T(0.038, 0.016, -0.029, 0.25));
    mbat.add(rb(0.007, 0.0025, 0.01, 0.001, 1), dark, T(0, onTop(0, 0.004) + 0.0006, 0.004)); // mode-shift button
    mbat.build(mouse, 'desk-mouse');
    // front points north (-z): rotation π maps local +z → -z and the thumb side (+x) → west (-x)
    mouse.position.set(1.4, Y, -0.187);
    mouse.rotation.y = Math.PI + 0.12;
    root.add(mouse);
  }

  // ================================================================ BOOM-ARM MIC (static, clamped to the west end)
  {
    const micG = new THREE.Group();
    micG.name = 'desk-mic-boom';
    tag(micG, { type: 'static' });
    const bb = new Batch();
    const base = new THREE.Vector3(0.31, Y, 0.09); // triangulated from photos 28 + 29
    // desk insert: round flange + clamp screw under the edge
    bb.add(cyl(0.04, 0.043, 0.012, 32), armBlack, T(base.x, Y + 0.006, base.z));
    bb.add(cyl(0.012, 0.014, 0.05, 20), armBlack, T(base.x, Y + 0.037, base.z));
    bb.add(cyl(0.02, 0.02, 0.018, 20), armBlack, T(base.x, Y + 0.07, base.z));
    const pivot = new THREE.Vector3(base.x, Y + 0.085, base.z);
    const elbow = new THREE.Vector3(0.4, 1.38, 0.17); // photos 29 + 88
    const tip = new THREE.Vector3(0.58, 0.935, 0.25); // photos 28 + 29
    // mic centre triangulated at (0.68, 0.80, 0.33), grille aimed up toward the chair (photo 28)
    const micPos = new THREE.Vector3(0.675, 0.8, 0.33);
    const pair = (a: THREE.Vector3, b: THREE.Vector3, sep: number) => {
      const d = b.clone().sub(a).normalize();
      const n = new THREE.Vector3().crossVectors(d, new THREE.Vector3(0, 1, 0));
      if (n.lengthSq() < 1e-4) n.set(1, 0, 0);
      n.normalize().multiplyScalar(sep / 2);
      // two parallel square tubes of the RØDE-style arm
      bb.add(beam(a.clone().add(n), b.clone().add(n), 0.011, 0.011, 0.002, n.clone().normalize()), armBlack);
      bb.add(beam(a.clone().sub(n), b.clone().sub(n), 0.011, 0.011, 0.002, n.clone().normalize()), armBlack);
      return n;
    };
    const n1 = pair(pivot, elbow, 0.03);
    const n2 = pair(elbow, tip, 0.028);
    // joint hubs (round plates)
    const hub = (p: THREE.Vector3, n: THREE.Vector3, r: number) => {
      const g = cyl(r, r, 0.045, 32);
      g.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), n.clone().normalize()));
      bb.add(g, armBlack, T(p.x, p.y, p.z));
    };
    hub(pivot, n1, 0.022);
    hub(elbow, n1, 0.03);
    hub(tip, n2, 0.02);
    // springs inside the channels
    bb.add(new THREE.TubeGeometry(new THREE.LineCurve3(pivot.clone().lerp(elbow, 0.12), pivot.clone().lerp(elbow, 0.55)), 4, 0.004, 8), steel);
    bb.add(new THREE.TubeGeometry(new THREE.LineCurve3(elbow.clone().lerp(tip, 0.15), elbow.clone().lerp(tip, 0.5)), 4, 0.004, 8), steel);
    // Syntax sticker near the tip is too small to matter; red XLR cable clipped along the arm
    const cp = (pts: THREE.Vector3[], mat: THREE.Material, r = 0.0032) => bb.add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 80, r, 6), mat);
    const off = new THREE.Vector3(0, 0.012, 0);
    cp([
      micPos.clone().add(new THREE.Vector3(-0.01, -0.04, -0.05)), tip.clone().add(new THREE.Vector3(0.02, -0.05, 0.02)), tip.clone().lerp(elbow, 0.3).add(off), tip.clone().lerp(elbow, 0.75).add(off),
      elbow.clone().add(new THREE.Vector3(0, 0.03, 0.0)), elbow.clone().lerp(pivot, 0.3).add(off), elbow.clone().lerp(pivot, 0.8).add(off),
      new THREE.Vector3(base.x - 0.03, Y + 0.08, base.z + 0.02), new THREE.Vector3(base.x - 0.05, Y - 0.02, base.z + 0.06), new THREE.Vector3(0.24, 0.5, 0.12), new THREE.Vector3(0.3, 0.02, 0.1),
    ], redCable);
    // mic: dynamic end-address mic hanging in a yoke below the tip, grille facing up-south
    bb.add(rod(tip, new THREE.Vector3(tip.x + 0.03, tip.y - 0.07, tip.z + 0.03), 0.005, 10), steel);
    bb.add(rod(new THREE.Vector3(tip.x + 0.03, tip.y - 0.07, tip.z + 0.03), new THREE.Vector3(0, 0.11, -0.044).applyMatrix4(T(micPos.x, micPos.y, micPos.z, 0.21, -0.69)), 0.006, 10), armBlack);
    bb.push(T(micPos.x, micPos.y, micPos.z, 0.21, -0.69));
    const grilleTex = canvasTex(256, 256, (c, w, h) => {
      c.fillStyle = '#9a9ca1';
      c.fillRect(0, 0, w, h);
      c.fillStyle = '#2a2b2e';
      for (let y = 2; y < h; y += 6) for (let x = 2 + ((y / 6) % 2) * 3; x < w; x += 6) c.fillRect(x, y, 3, 3);
    }, true, true);
    grilleTex.repeat.set(3, 3);
    const grille = new THREE.MeshStandardMaterial({ name: 'micGrille', map: grilleTex, metalness: 0.85, roughness: 0.5 });
    const micBody = new THREE.MeshPhysicalMaterial({ name: 'micBody', color: '#161618', roughness: 0.35, metalness: 0.6, clearcoat: 0.3 });
    // body along local +z (front = grille): end-address dynamic mic, 52 mm body, silver mesh head
    const lathe = new THREE.LatheGeometry([[0, -0.1], [0.016, -0.1], [0.02, -0.094], [0.024, -0.07], [0.026, -0.02], [0.028, 0.012], [0.03, 0.016], [0, 0.016]].map(([r, y]) => new THREE.Vector2(r, y)), 36);
    lathe.rotateX(Math.PI / 2);
    bb.add(lathe, micBody);
    bb.add(cyl(0.031, 0.031, 0.05, 36, true), grille, T(0, 0, 0.041, 0, Math.PI / 2));
    const gr = new THREE.SphereGeometry(0.031, 36, 12, 0, Math.PI * 2, 0, Math.PI / 2);
    gr.rotateX(Math.PI / 2);
    bb.add(gr, grille, T(0, 0, 0.066, 0, 0, 0, [1, 1, 0.35]));
    bb.add(new THREE.TorusGeometry(0.031, 0.0022, 8, 36), micBody, T(0, 0, 0.017)); // grille collar
    bb.add(new THREE.TorusGeometry(0.031, 0.0018, 8, 36), micBody, T(0, 0, 0.066));
    // shock mount cage: two rings joined by four rods, elastic cords to the body, bracket to the boom
    for (const z of [-0.012, -0.075]) bb.add(new THREE.TorusGeometry(0.048, 0.0035, 8, 40), armBlack, T(0, 0, z));
    for (let k = 0; k < 4; k++) {
      const a2 = (k / 4) * Math.PI * 2 + Math.PI / 4;
      const c = Math.cos(a2) * 0.048, d = Math.sin(a2) * 0.048;
      bb.add(rod(new THREE.Vector3(c, d, -0.012), new THREE.Vector3(c, d, -0.075), 0.0028, 6), armBlack);
      for (const z of [-0.012, -0.075]) {
        const b2 = a2 + (z > -0.05 ? 0.6 : -0.6);
        bb.add(rod(new THREE.Vector3(c, d, z), new THREE.Vector3(Math.cos(b2) * 0.025, Math.sin(b2) * 0.025, z + (z > -0.05 ? -0.012 : 0.012)), 0.0012, 4), rubber);
      }
    }
    bb.add(rb(0.014, 0.05, 0.02, 0.004, 1), armBlack, T(0, 0.07, -0.044));
    bb.add(cyl(0.008, 0.008, 0.03, 12), steel, T(0, 0.098, -0.044));
    // XLR plug + cable out of the back
    bb.add(cyl(0.011, 0.012, 0.03, 16), micBody, T(0, 0, -0.114, 0, Math.PI / 2));
    bb.pop();
    bb.build(micG, 'desk-mic');
    root.add(micG);
  }

  return root;
}