master
AdityaAngajala v0.13.0 12542ed
// adom/adom-3d-viewer#4 (Colby): pressing a view-cube face used to start the
// camera animation on mouse DOWN, so a press-and-drag on the cube fought the
// orbit. Now the face navigates on RELEASE within a few pixels of the press;
// a drag that starts on the cube orbits the model exactly like a drag that
// starts on the model. Headless Chrome, real pointer events, bounded 240 s.
import http from "node:http";
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");
const deadline = Date.now() + 240_000;
let passed = 0, failed = 0;
const failures = [];
function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }
function section(t) { console.log("\n  [" + t + "]"); }
function left() { return Math.max(1000, deadline - Date.now()); }
const sleep = (ms) => new Promise(r => setTimeout(r, ms));

function makeBoxGlb() {
  const pos = [], idx = [];
  const faces = [
    [[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]], [[1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, -1]],
    [[-1, 1, 1], [1, 1, 1], [1, 1, -1], [-1, 1, -1]], [[-1, -1, -1], [1, -1, -1], [1, -1, 1], [-1, -1, 1]],
    [[1, -1, 1], [1, -1, -1], [1, 1, -1], [1, 1, 1]], [[-1, -1, -1], [-1, -1, 1], [-1, 1, 1], [-1, 1, -1]],
  ];
  faces.forEach((f, fi) => { f.forEach(v => pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01)); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });
  const posBuf = Buffer.from(new Float32Array(pos).buffer);
  const idxBuf = Buffer.from(new Uint16Array(idx).buffer);
  const bin = Buffer.concat([posBuf, idxBuf, Buffer.alloc((4 - (idxBuf.length % 4)) % 4)]);
  const json = {
    asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: "chip_body" }],
    meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
    materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.9, 0.55, 0.1, 1], metallicFactor: 0.2, roughnessFactor: 0.5 } }],
    buffers: [{ byteLength: bin.length }],
    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],
    accessors: [{ bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },
      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" }],
  };
  let jsonBuf = Buffer.from(JSON.stringify(json)); jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);
  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);
  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };
  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);
}
const GLB = makeBoxGlb();

// 640x400: the cube viewport is 120x120 px in the top-right corner (the
// builder's 120 px minimum), so its center is 60 px in from the right edge
// and 60 px down. Every pointer test uses that point.
const W = 640, H = 400, CUBE = { x: W - 60, y: 60 };
const HARNESS = `<!doctype html><html><head><meta charset="utf-8">
<style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;width:${W}px;height:${H}px}</style>
</head><body><div id="wrap"></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  const v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: true, showGround: false, modelUrl: '/chip.glb' });
  await v.whenReady();
  window.__viewer = v;
  window.__cam = () => { const c = v.getCamera(); return { alpha: c.alpha, beta: c.beta, radius: c.radius }; };
  window.__setPose = (a, b) => { const c = v.getCamera(); c.alpha = a; c.beta = b; c.inertialAlphaOffset = 0; c.inertialBetaOffset = 0; };
  // Resolves once the camera has no animation, no inertia and the same pose
  // for five rendered frames in a row. Counted in frames, not milliseconds,
  // so a slow machine waits longer instead of reading the pose mid-move.
  window.__settled = () => new Promise(resolve => {
    const s = v.getScene(), c = v.getCamera();
    let last = '', still = 0;
    const o = s.onAfterRenderObservable.add(() => {
      const pose = [c.alpha, c.beta, c.radius].map(x => x.toFixed(5)).join();
      const busy = s.getAllAnimatablesByTarget(c).length > 0 || c.inertialAlphaOffset !== 0 || c.inertialBetaOffset !== 0 || c.inertialRadiusOffset !== 0;
      still = !busy && pose === last ? still + 1 : 0;
      last = pose;
      if (still >= 5) { s.onAfterRenderObservable.remove(o); resolve(); }
    });
  });
  window.__ready = true;
</script></body></html>`;

if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://x");
  if (url.pathname === "/cube.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }
  if (url.pathname === "/chip.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(GLB); }
  const file = join(DIST, url.pathname.replace(/^\/+/, ""));
  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }
  res.writeHead(404); res.end();
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
const port = server.address().port;

let puppeteer;
try { puppeteer = (await import("puppeteer-core")).default; }
catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }
function findChrome() {
  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;
  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");
  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }
  for (const p of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) if (existsSync(p)) return p;
  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");
}
const browser = await puppeteer.launch({
  executablePath: findChrome(), headless: true,
  args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"],
});

// The camera once any animation and inertia have run out (see __settled).
async function settled(page) {
  await page.evaluate(() => window.__settled());
  return page.evaluate(() => window.__cam());
}

// Press at (x, y), move by dx in steps, release; then let inertia settle.
async function drag(page, x, y, dx, steps = 10) {
  await page.mouse.move(x, y);
  await page.mouse.down();
  for (let i = 1; i <= steps; i++) { await page.mouse.move(x + (dx * i) / steps, y); await sleep(25); }
  await page.mouse.up();
  return settled(page);
}
const START = { alpha: 0.7, beta: 1.2 };
const wrap = (a) => Math.atan2(Math.sin(a), Math.cos(a));

// Every check runs at 1x and at 2x (a Retina screen): the scene renders at
// the display's pixel density while the cube's hit area stays in CSS pixels.
try {
 for (const dpr of [1, 2]) {
  const page = await browser.newPage();
  const errors = [];
  page.on("pageerror", e => errors.push(String(e && e.message || e)));
  await page.setViewport({ width: W, height: H, deviceScaleFactor: dpr });
  await page.goto(`http://127.0.0.1:${port}/cube.html`, { waitUntil: "load", timeout: left() });
  await page.waitForFunction(() => window.__ready === true, { timeout: left() });

  section(`at ${dpr}x the canvas renders at the display's pixel density`);
  const px = await page.evaluate(() => { const c = document.querySelector("#wrap canvas"); return { w: c.width, h: c.height, cw: c.clientWidth, ch: c.clientHeight }; });
  assert(px.w === px.cw * dpr && px.h === px.ch * dpr, `backing store ${px.w}x${px.h} for a ${px.cw}x${px.ch} canvas`);
  const box = await (await page.$("#wrap canvas")).boundingBox();
  const model = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
  const cube = { x: box.x + CUBE.x, y: box.y + CUBE.y };

  section("a press-and-drag that starts on the cube orbits the model, it does not snap to a face");
  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);
  await sleep(200);
  const onModel = await drag(page, model.x, model.y, 80);
  const dModel = wrap(onModel.alpha - START.alpha);
  assert(Math.abs(dModel) > 0.05, `a drag on the model orbits (alpha ${START.alpha} -> ${onModel.alpha.toFixed(3)})`);
  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);
  await sleep(200);
  const onCube = await drag(page, cube.x, cube.y, 80);
  const dCube = wrap(onCube.alpha - START.alpha);
  assert(Math.abs(dCube - dModel) < 0.08, `the same drag on the cube orbits by the same amount (model ${dModel.toFixed(3)}, cube ${dCube.toFixed(3)})`);
  assert(Math.abs(onCube.beta - onModel.beta) < 0.08, `and lands at the same beta (${onModel.beta.toFixed(3)} vs ${onCube.beta.toFixed(3)})`);

  section("a clean click on a face still navigates there, on release");
  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);
  await sleep(200);
  await page.mouse.move(cube.x, cube.y);
  await page.mouse.down();
  await sleep(120);
  const held = await page.evaluate(() => window.__cam());
  assert(Math.abs(wrap(held.alpha - START.alpha)) < 0.02 && Math.abs(held.beta - START.beta) < 0.02, `nothing moves while the button is held (${held.alpha.toFixed(3)}, ${held.beta.toFixed(3)})`);
  await page.mouse.up();
  const clicked = await settled(page);
  const movedBy = Math.abs(wrap(clicked.alpha - START.alpha)) + Math.abs(clicked.beta - START.beta);
  assert(movedBy > 0.15, `the release animates the camera to the face (moved ${movedBy.toFixed(3)} rad)`);
  // Face poses are axis-aligned in beta (0, PI/2, PI) or on a 45-degree edge/corner.
  const b = clicked.beta;
  const onGrid = [0, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI].some(g => Math.abs(b - g) < 0.05);
  assert(onGrid, `the landing beta is a cube pose (${b.toFixed(3)})`);

  section("a press that wanders off the face before release is not a click");
  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);
  await sleep(200);
  const wandered = await drag(page, cube.x, cube.y, 12, 3);
  const dW = wrap(wandered.alpha - START.alpha);
  assert(Math.abs(dW) < Math.abs(dModel) && Math.abs(dW) > 0.0, `a 12 px wander orbits a little (${dW.toFixed(3)}) instead of snapping`);
  const wbOnGrid = [0, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI].some(g => Math.abs(wandered.beta - g) < 0.01);
  assert(!wbOnGrid || Math.abs(wandered.beta - START.beta) < 0.1, `no snap animation ran (beta ${wandered.beta.toFixed(3)})`);

  section("hover and camera moves leave every cube colour where it started");
  // The cube's particle colours, as written to its mesh.
  const colours = () => page.evaluate(() => {
    const m = window.__viewer.getScene().getEngine().scenes.map(s => s.getMeshByName("viewCubeSPS")).find(Boolean);
    return m ? Array.from(m.getVerticesData("color") || []) : [];
  });
  const sameAs = (a, b) => a.length === b.length && a.length > 0 && a.every((x, i) => Math.abs(x - b[i]) < 1e-6);
  await page.mouse.move(model.x, model.y);
  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);
  await sleep(500);
  const before = await colours();
  assert(before.length > 0, `the cube mesh carries colours (${before.length} values)`);
  await page.mouse.move(cube.x, cube.y);
  await sleep(300);
  const hovered = await colours();
  assert(!sameAs(hovered, before), "hovering a face changes its colour");
  for (const pose of [{ alpha: 1.6, beta: 0.9 }, { alpha: -0.4, beta: 1.5 }, START]) {
    await page.evaluate((s) => window.__setPose(s.alpha, s.beta), pose);
    await sleep(250);
  }
  await page.mouse.move(model.x, model.y);
  await sleep(300);
  for (let i = 0; i < 3; i++) {
    await page.mouse.move(cube.x, cube.y); await sleep(150);
    await page.mouse.move(model.x, model.y); await sleep(150);
  }
  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);
  await sleep(500);
  assert(sameAs(await colours(), before), "after hovering, moving the camera under the pointer, and leaving, every colour is back to its value at the start");

  assert(errors.length === 0, `no page errors (${errors.join("; ").slice(0, 200)})`);
  await page.close();
 }
} finally {
  await browser.close();
  server.close();
}
console.log(`\nview cube: ${passed} passed, ${failed} failed`);
if (failed) { for (const f of failures) console.log("  - " + f); process.exit(1); }