// The page: draws the room, the robot and what it imagines, and turns clicks into edits for the worker.
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { ROOM, HAMPER, DEFAULT_FURNITURE } from "./core/mission.js";
const $ = id => document.getElementById(id);
const C = { ember: 0xe68e0d, forest: 0x5fb68b, shadow: 0xa07ce0, bone: 0xe8e3da, furn: 0x50545c, bg: 0x121212 };
const TOY_COLORS = [0xf06aa7, 0xf2c230, 0x5fb68b, 0x5aa2f0, 0xf08a3c, 0xb07cf0];
const PRESETS = { chair: { label: "Chair", w: 0.44, d: 0.44, h: 0.85 }, table: { label: "Table", w: 0.8, d: 0.8, h: 0.72 },
shelf: { label: "Shelf", w: 1.0, d: 0.35, h: 1.6 }, box: { label: "Box", w: 0.5, d: 0.5, h: 0.4 } };
// ------------------------------------------------------------------------------------------- scene
const canvas = $("view"), stage = canvas.parentElement;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
const scene = new THREE.Scene();
scene.background = new THREE.Color(C.bg);
const camera = new THREE.PerspectiveCamera(42, 1, 0.05, 60);
camera.up.set(0, 0, 1);
camera.position.set(0.9, -5.6, 5.0);
const controls = new OrbitControls(camera, canvas);
controls.target.set(-0.3, 0.05, 0.35);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI / 2 - 0.08;
controls.minDistance = 1.5; controls.maxDistance = 14;
const hemi = new THREE.HemisphereLight(0xfff6e8, 0x1a1a1a, 1.6); hemi.position.set(0, 0, 10); scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffffff, 1.6); sun.position.set(2.5, -3, 7); scene.add(sun);
const E = ROOM.floor.extent;
const floorTex = new THREE.CanvasTexture(drawFloor(1024));
floorTex.colorSpace = THREE.SRGBColorSpace;
floorTex.anisotropy = 4;
/** Our own floor, drawn in code: oak planks inside the walls, a rug and a play mat. 5 m across, room origin at the
* centre, +y up (the same convention as the reach map). */
function drawFloor(px) {
const cv = document.createElement("canvas"); cv.width = cv.height = px;
const g = cv.getContext("2d"), s = px / E, U = x => (x / E + 0.5) * px, V = y => (0.5 - y / E) * px;
let seed = 7; const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
g.fillStyle = "#151515"; g.fillRect(0, 0, px, px);
const [W, D] = ROOM.size, x0 = U(-W / 2), y0 = V(D / 2), w = W * s, h = D * s;
g.save(); g.beginPath(); g.rect(x0, y0, w, h); g.clip();
const plank = 0.16 * s; // 16 cm oak planks, staggered seams
for (let r = 0, y = y0; y < y0 + h; r++, y += plank) {
let x = x0 - rnd() * 1.4 * s;
while (x < x0 + w) {
const len = (0.9 + rnd() * 1.1) * s, tone = 150 + rnd() * 30;
g.fillStyle = `rgb(${tone + 22}, ${tone - 8}, ${tone - 52})`; g.fillRect(x, y, len, plank);
for (let k = 0; k < 3; k++) { // a little grain
g.strokeStyle = `rgba(90, 60, 30, ${0.08 + rnd() * 0.08})`; g.lineWidth = 1;
const gy = y + rnd() * plank; g.beginPath(); g.moveTo(x, gy); g.lineTo(x + len, gy + (rnd() - 0.5) * 3); g.stroke();
}
g.fillStyle = "rgba(60, 40, 20, 0.55)"; g.fillRect(x + len - 1, y, 1.2, plank);
x += len;
}
g.fillStyle = "rgba(60, 40, 20, 0.45)"; g.fillRect(x0, y, w, 1.2);
}
const round = (cx, cy, rw, rh, rad, fill, stroke) => { // rounded rectangle in metres
g.beginPath(); g.roundRect(U(cx - rw / 2), V(cy + rh / 2), rw * s, rh * s, rad * s);
g.fillStyle = fill; g.fill(); if (stroke) { g.lineWidth = 0.06 * s; g.strokeStyle = stroke; g.stroke(); }
};
round(-0.15, 0.15, 2.4, 1.7, 0.12, "#6f7f6a", "#55654f"); // the rug
g.globalAlpha = 0.18; for (let i = 0; i < 9; i++) round(-0.15, 0.15, 2.2 - i * 0.22, 1.5 - i * 0.15, 0.1, "transparent", "#e8e3da");
g.globalAlpha = 1;
const tiles = ["#c9a227", "#b8563a", "#3f7f9a", "#6c9a4a"]; // a play mat of foam tiles
for (let i = 0; i < 3; i++) for (let j = 0; j < 2; j++) round(1.55 + i * 0.3 - 0.3, 0.55 + j * 0.3, 0.29, 0.29, 0.03, tiles[(i + j) % 4]);
g.restore();
g.strokeStyle = "#e8e3da"; g.lineWidth = 0.05 * s; g.strokeRect(x0, y0, w, h); // skirting
return cv;
}
const floor = new THREE.Mesh(new THREE.PlaneGeometry(E, E), new THREE.MeshStandardMaterial({ map: floorTex, roughness: 1 }));
scene.add(floor);
// the reach map: line shadows (purple) and the band too close to the walls (dimmed)
const RN = 100, reachData = new Uint8Array(RN * RN * 4);
const reachTex = new THREE.DataTexture(reachData, RN, RN, THREE.RGBAFormat);
reachTex.magFilter = THREE.LinearFilter;
const reach = new THREE.Mesh(new THREE.PlaneGeometry(E, E), new THREE.MeshBasicMaterial({ map: reachTex, transparent: true, depthWrite: false }));
reach.position.z = 0.003; scene.add(reach);
function setReach(map) {
for (let r = 0; r < RN; r++) for (let c = 0; c < RN; c++) {
const v = map[r * RN + c], o = ((RN - 1 - r) * RN + c) * 4; // map row 0 = +y edge, texture row 0 = -y
const [R, G, B, A] = v === 3 ? [160, 124, 224, 125] : v === 1 ? [10, 10, 12, 150] : [0, 0, 0, 0];
reachData[o] = R; reachData[o + 1] = G; reachData[o + 2] = B; reachData[o + 3] = A;
}
reachTex.needsUpdate = true;
}
// low walls (cut away, so the room stays readable from any angle)
{ const [W, D] = ROOM.size, t = 0.06, hw = 0.35;
const wallMat = new THREE.MeshStandardMaterial({ color: 0x2a2826, roughness: 0.9 });
for (const [x, y, w, d] of [[0, D / 2 + t / 2, W + 2 * t, t], [0, -D / 2 - t / 2, W + 2 * t, t], [W / 2 + t / 2, 0, t, D], [-W / 2 - t / 2, 0, t, D]]) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, d, hw), wallMat); m.position.set(x, y, hw / 2); scene.add(m);
} }
// the four line anchors on posts
const postMat = new THREE.MeshStandardMaterial({ color: 0x3a3a3a, roughness: 0.8 });
for (const M of ROOM.mounts) {
const post = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, M[2], 10), postMat);
post.rotation.x = Math.PI / 2; post.position.set(M[0], M[1], M[2] / 2); scene.add(post);
const eye = new THREE.Mesh(new THREE.SphereGeometry(0.04, 16, 12), new THREE.MeshStandardMaterial({ color: C.ember }));
eye.position.set(...M); scene.add(eye);
}
const lineGeo = new THREE.BufferGeometry();
lineGeo.setAttribute("position", new THREE.BufferAttribute(new Float32Array(8 * 3), 3));
const lines = new THREE.LineSegments(lineGeo, new THREE.LineBasicMaterial({ color: 0xd8d2c6 }));
scene.add(lines);
// the robot: gantry, pole, gripper, two fingers (cablepilot stringman.yaml body numbers)
const robot = new THREE.Group(); scene.add(robot);
const dark = new THREE.MeshStandardMaterial({ color: 0x2b2b2b, roughness: 0.6 });
const bone = new THREE.MeshStandardMaterial({ color: C.bone, roughness: 0.5 });
const gantry = new THREE.Mesh(new THREE.BoxGeometry(0.09, 0.09, 0.08), dark); gantry.position.z = -0.02; robot.add(gantry);
const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.269, 8), bone);
pole.rotation.x = Math.PI / 2; pole.position.z = -0.1945; robot.add(pole);
const wrist = new THREE.Group(); robot.add(wrist);
const shell = new THREE.Mesh(new THREE.BoxGeometry(0.104, 0.07, 0.11), bone); shell.position.z = -0.3907; wrist.add(shell);
const fingers = [1, -1].map(side => {
const pivot = new THREE.Group(); pivot.position.set(0.025 * side, 0, -0.4047);
const f = new THREE.Mesh(new THREE.BoxGeometry(0.012, 0.044, 0.11), dark); f.position.z = -0.055;
pivot.add(f); wrist.add(pivot); return { pivot, side };
});
// the hamper (its four walls)
const hamper = new THREE.Group(); scene.add(hamper);
const wicker = new THREE.MeshStandardMaterial({ color: 0x8a6a45, roughness: 0.9 });
{ const i = HAMPER.half, t = 0.02, h = HAMPER.height;
for (const [x, y, w, d] of [[i + t / 2, 0, t, 2 * i + 2 * t], [-i - t / 2, 0, t, 2 * i + 2 * t], [0, i + t / 2, 2 * i, t], [0, -i - t / 2, 2 * i, t]]) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, d, h), wicker); m.position.set(x, y, h / 2); hamper.add(m);
}
hamper.position.set(ROOM.hamper[0], ROOM.hamper[1], 0); }
// what it imagines: the chosen plan (ember tube) and the best futures (forest lines)
const FUT = 12, futMat = new THREE.LineBasicMaterial({ color: C.forest, transparent: true, opacity: 0.75 });
const futures = Array.from({ length: FUT }, () => {
const g = new THREE.BufferGeometry(); g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(11 * 3), 3));
const l = new THREE.Line(g, futMat); scene.add(l); return l;
});
let planTube = null;
const planMat = new THREE.MeshBasicMaterial({ color: C.ember });
const goalRing = new THREE.Mesh(new THREE.RingGeometry(0.035, 0.05, 32), new THREE.MeshBasicMaterial({ color: C.ember, transparent: true, opacity: 0.7, side: THREE.DoubleSide }));
scene.add(goalRing);
// ------------------------------------------------------------------------------------------- furniture (the page owns the list)
let furniture = DEFAULT_FURNITURE.map(f => ({ ...f })), selected = null, nextF = 1;
const furnMeshes = new Map();
const furnMat = () => new THREE.MeshStandardMaterial({ color: C.furn, roughness: 0.85, transparent: true, opacity: 0.88 });
function syncFurnMesh(f) {
let m = furnMeshes.get(f.id);
if (!m) {
m = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), furnMat());
m.add(new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)), new THREE.LineBasicMaterial({ color: 0x8c8f96 })));
m.userData.id = f.id; scene.add(m); furnMeshes.set(f.id, m);
}
m.scale.set(2 * f.hx, 2 * f.hy, f.h); m.position.set(f.x, f.y, f.h / 2);
m.material.emissive.setHex(f.id === selected ? 0x2a1f3d : 0x000000);
}
function syncAllFurniture() {
for (const [id, m] of furnMeshes) if (!furniture.find(f => f.id === id)) { scene.remove(m); furnMeshes.delete(id); }
furniture.forEach(syncFurnMesh);
}
let sendTimer = null;
function sendFurniture(now = false) {
clearTimeout(sendTimer);
const go = () => worker.postMessage({ type: "furniture", list: furniture });
if (now) go(); else sendTimer = setTimeout(go, 90);
}
function renderFurnList() {
const box = $("furn"); box.textContent = "";
for (const f of furniture) {
const el = document.createElement("div"); el.className = "fi" + (f.id === selected ? " sel" : "");
el.innerHTML = `
`;
el.querySelector("b").textContent = f.label;
el.querySelector("button").onclick = () => { furniture = furniture.filter(g => g !== f); if (selected === f.id) selected = null; syncAllFurniture(); renderFurnList(); sendFurniture(true); };
if (f.id === selected) {
const s = document.createElement("div"); s.className = "sliders";
for (const [key, name, lo, hi] of [["w", "Width", 0.2, 2.0], ["d", "Depth", 0.2, 2.0], ["h", "Height", 0.2, 1.9]]) {
const val = key === "w" ? 2 * f.hx : key === "d" ? 2 * f.hy : f.h, id = `fs-${f.id}-${key}`;
s.insertAdjacentHTML("beforeend", ``);
}
s.querySelectorAll("input").forEach(inp => inp.oninput = () => {
const v = +inp.value, k = inp.id.split("-").pop();
if (k === "w") f.hx = v / 2; else if (k === "d") f.hy = v / 2; else f.h = v;
inp.nextElementSibling.textContent = v.toFixed(2) + " m"; syncFurnMesh(f); sendFurniture();
});
el.appendChild(s);
} else el.onclick = e => { if (e.target.tagName !== "BUTTON") { selected = f.id; syncAllFurniture(); renderFurnList(); } };
box.appendChild(el);
}
}
document.querySelectorAll("[data-add]").forEach(b => b.onclick = () => {
const p = PRESETS[b.dataset.add], f = { id: `${b.dataset.add}-${nextF++}`, label: p.label, x: 0.2 + 0.4 * (Math.random() - 0.5), y: 0.2 + 0.4 * (Math.random() - 0.5), hx: p.w / 2, hy: p.d / 2, h: p.h };
furniture.push(f); selected = f.id; syncAllFurniture(); renderFurnList(); sendFurniture(true);
});
// ------------------------------------------------------------------------------------------- toys
const toyMeshes = new Map();
const toyGeo = new THREE.BoxGeometry(0.05, 0.05, 0.05); // cablepilot's 4 cm toy blocks, drawn a touch larger
const targetRing = new THREE.Mesh(new THREE.RingGeometry(0.06, 0.075, 32), new THREE.MeshBasicMaterial({ color: C.ember, side: THREE.DoubleSide }));
targetRing.visible = false; scene.add(targetRing);
function syncToys(toys) {
for (const [id, m] of toyMeshes) if (!toys.find(t => t.id === id)) { scene.remove(m); toyMeshes.delete(id); }
for (const t of toys) {
let m = toyMeshes.get(t.id);
if (!m) {
const col = TOY_COLORS[t.id % TOY_COLORS.length];
m = new THREE.Mesh(toyGeo, new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 0.25, roughness: 0.4 }));
m.add(new THREE.LineSegments(new THREE.EdgesGeometry(toyGeo), new THREE.LineBasicMaterial({ color: 0xffffff })));
m.userData.id = t.id; scene.add(m); toyMeshes.set(t.id, m);
}
m.position.set(t.x, t.y, t.z + 0.005);
}
}
// ------------------------------------------------------------------------------------------- pointer: drag furniture, drop / take toys
const ray = new THREE.Raycaster(), ndc = new THREE.Vector2(), ground = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
let down = null, drag = null;
function pick(e) {
const r = canvas.getBoundingClientRect();
ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
ray.setFromCamera(ndc, camera);
}
function groundPoint() { const p = new THREE.Vector3(); return ray.ray.intersectPlane(ground, p) ? p : null; }
stage.addEventListener("pointerdown", e => {
if (e.target !== canvas || e.button !== 0) return;
pick(e); down = { x: e.clientX, y: e.clientY };
const hit = ray.intersectObjects([...furnMeshes.values()], false)[0];
if (hit) {
const f = furniture.find(g => g.id === hit.object.userData.id), p = groundPoint();
drag = { f, dx: p ? f.x - p.x : 0, dy: p ? f.y - p.y : 0 };
selected = f.id; syncAllFurniture(); renderFurnList();
controls.enabled = false; canvas.classList.add("grab"); canvas.setPointerCapture(e.pointerId);
}
}, { capture: true });
canvas.addEventListener("pointermove", e => {
if (!drag) return;
pick(e); const p = groundPoint(); if (!p) return;
drag.f.x = Math.max(-E / 2, Math.min(E / 2, p.x + drag.dx)); drag.f.y = Math.max(-E / 2, Math.min(E / 2, p.y + drag.dy));
syncFurnMesh(drag.f); sendFurniture();
});
window.addEventListener("pointerup", e => {
if (drag) { drag = null; controls.enabled = true; canvas.classList.remove("grab"); sendFurniture(true); down = null; return; }
if (!down || e.target !== canvas) { down = null; return; }
const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y); down = null;
if (moved > 6) return; // that was a view turn
pick(e);
const toyHit = ray.intersectObjects([...toyMeshes.values()], false)[0];
if (toyHit) { worker.postMessage({ type: "removeToy", id: toyHit.object.userData.id }); return; }
const p = groundPoint();
if (p && Math.abs(p.x) < E / 2 && Math.abs(p.y) < E / 2) worker.postMessage({ type: "addToy", x: p.x, y: p.y, autostart: false });
});
// ------------------------------------------------------------------------------------------- controls
const worker = new Worker("./worker.js", { type: "module" });
let running = false;
function setRunning(on) { running = on; $("run").textContent = on ? "Pause" : "Start"; $("phaseDot").classList.toggle("live", on); }
$("run").onclick = () => { setRunning(!running); worker.postMessage({ type: "run", on: running }); };
$("reset").onclick = () => worker.postMessage({ type: "reset" });
document.querySelectorAll("[data-speed]").forEach(b => b.onclick = () => {
document.querySelectorAll("[data-speed]").forEach(o => o.classList.toggle("on", o === b));
worker.postMessage({ type: "speed", v: +b.dataset.speed });
});
$("showShadow").onchange = e => { reach.visible = e.target.checked; };
const home = { pos: camera.position.clone(), target: controls.target.clone() };
$("follow").onchange = e => { if (!e.target.checked) { camera.position.copy(home.pos); controls.target.copy(home.target); } };
$("showFutures").onchange = e => { futures.forEach(l => (l.visible = e.target.checked)); };
let toastTimer;
function toast(text) { const t = $("toast"); t.textContent = text; t.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => (t.hidden = true), 3200); }
// ------------------------------------------------------------------------------------------- frames from the worker
let prevX = null, curX = null, tRecv = 0, interval = 200;
const SPLIT = [["noise", "#6f6a62", "sampling"], ["rollout", "#5fb68b", "imagining"], ["cost", "#e68e0d", "scoring"], ["update", "#a07ce0", "choosing"]];
$("split").insertAdjacentHTML("afterend", `${SPLIT.map(([, c, n]) => `${n}`).join("")}
`);
const TERMS = [["goal", "goal"], ["furniture", "furniture"], ["lines", "lines"], ["walls", "walls"], ["swing", "swing"], ["floor", "floor"]];
$("terms").innerHTML = TERMS.map(([k, n]) => `${n}0`).join("");
function onFrame(f) {
const now = performance.now();
if (curX) { interval = Math.min(1000, Math.max(30, now - tRecv)); prevX = curX; } else prevX = f.x;
curX = f.x; tRecv = now;
// lines, paths, goal
if (f.nominal.length) {
const pts = [gp(f.x), ...f.nominal].map(p => new THREE.Vector3(...p));
if (planTube) { planTube.geometry.dispose(); scene.remove(planTube); }
planTube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 40, 0.014, 8), planMat); scene.add(planTube);
f.rollouts.forEach((r, i) => {
if (i >= FUT) return;
const a = futures[i].geometry.attributes.position; const all = [gp(f.x), ...r];
all.forEach((p, k) => a.setXYZ(k, p[0], p[1], p[2])); a.needsUpdate = true; futures[i].geometry.computeBoundingSphere();
});
}
goalRing.position.set(f.goal[0], f.goal[1], f.goal[2] + 0.002);
syncToys(f.toys);
const tgt = f.toys.find(t => t.id === f.target);
targetRing.visible = !!tgt && tgt.state === "target";
if (tgt) targetRing.position.set(tgt.x, tgt.y, 0.006);
// panel
const total = f.toys.length, done = f.toys.filter(t => t.state === "delivered").length;
$("phase").textContent = f.label; $("toys").textContent = `${done}/${total}`;
$("clock").textContent = `${f.t.toFixed(0)} s`;
$("contacts").textContent = f.stats.contacts; $("contacts").classList.toggle("bad", f.stats.contacts > 0);
if (f.stats.plans) {
$("ms").textContent = f.stats.msPerPlan.toFixed(0);
$("fps").textContent = Math.round(129 / (f.stats.msPerPlan / 1000)).toLocaleString();
$("cpuToy").textContent = done ? (f.stats.planMs / 1000 / done).toFixed(1) : "–";
}
if (f.ms) $("split").innerHTML = SPLIT.map(([k, c]) => ``).join("");
if (f.terms) {
const scale = v => Math.min(100, 100 * Math.log10(1 + v) / 3);
for (const [k] of TERMS) {
const li = document.querySelector(`.terms li[data-k="${k}"]`), v = f.terms[k] || 0;
li.querySelector("i").style.width = scale(v) + "%"; li.querySelector(".v").textContent = v < 10 ? v.toFixed(1) : v.toFixed(0);
}
}
$("log").innerHTML = f.stats.events.slice().reverse().map(e => `${e.t.toFixed(0)} s ${e.what}`).join("");
}
const DG = -0.5147;
function axisOf(x) { const sx = x[6], sy = x[7]; return [sx, sy, Math.sqrt(Math.max(1e-6, 1 - sx * sx - sy * sy))]; }
function gp(x) { const a = axisOf(x); return [x[0] + DG * a[0], x[1] + DG * a[1], x[2] + DG * a[2]]; }
worker.onmessage = ({ data: d }) => {
if (d.type === "frame") onFrame(d);
else if (d.type === "reach") setReach(d.map);
else if (d.type === "toast") toast(d.text);
else if (d.type === "running") setRunning(d.on);
else if (d.type === "done") { setRunning(false); toast(`Every reachable toy is in the hamper, in ${d.t.toFixed(0)} s of robot time.`); }
else if (d.type === "ready" && new URLSearchParams(location.search).has("autorun")) {
const sp = new URLSearchParams(location.search).get("speed");
if (sp) { worker.postMessage({ type: "speed", v: +sp }); document.querySelectorAll("[data-speed]").forEach(o => o.classList.toggle("on", o.dataset.speed === sp)); }
if (new URLSearchParams(location.search).has("follow")) { $("follow").checked = true; }
setRunning(true); worker.postMessage({ type: "run", on: true });
}
};
worker.postMessage({ type: "init" });
syncAllFurniture(); renderFurnList(); sendFurniture(true);
// ------------------------------------------------------------------------------------------- draw loop (robot pose interpolated between ticks)
const up = new THREE.Vector3(0, 0, 1), q = new THREE.Quaternion(), tmp = new THREE.Vector3();
function draw() {
requestAnimationFrame(draw);
controls.update();
if (curX) {
const a = Math.min(1, (performance.now() - tRecv) / interval), x = curX.map((v, i) => prevX[i] + (v - prevX[i]) * a);
robot.position.set(x[0], x[1], x[2]);
q.setFromUnitVectors(up, tmp.set(...axisOf(x))); robot.quaternion.copy(q);
wrist.rotation.z = x[10];
const open = (1 - Math.max(0, Math.min(1, x[12]))) * 59 * Math.PI / 180;
fingers.forEach(({ pivot, side }) => (pivot.rotation.y = -side * open));
const pos = lineGeo.attributes.position;
ROOM.mounts.forEach((M, i) => { pos.setXYZ(2 * i, ...M); pos.setXYZ(2 * i + 1, x[0], x[1], x[2]); });
pos.needsUpdate = true;
if ($("follow").checked) { // glide the view towards the hand, keep the visitor's angle
const g = gp(x), want = new THREE.Vector3(g[0], g[1], Math.max(0.2, g[2]));
const off = camera.position.clone().sub(controls.target);
if (off.length() > 2.4) off.setLength(off.length() * 0.97);
controls.target.lerp(want, 0.06); camera.position.copy(controls.target).add(off);
}
}
renderer.render(scene, camera);
}
new ResizeObserver(() => {
const w = stage.clientWidth, h = stage.clientHeight;
renderer.setSize(w, h, false); camera.aspect = w / Math.max(1, h); camera.updateProjectionMatrix();
}).observe(stage);
draw();