master
AdityaAngajala v0.12.8 160fd3c
// setHomeView's target (adom/wiki#237): Home orbits the point the host names,
// in the model's own frame, instead of the bounding-box center. Without a
// target nothing changes. Headless Chrome, bounded 120 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() + 120_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 + "]"); }
const left = () => Math.max(1000, deadline - Date.now());

// A box spanning x 0..2, y 0..1, z 0..0.5 in its own frame: lopsided on every
// axis, so a swapped or flipped axis would show in the numbers.
function boxGlb() {
  const xs = [0, 2], ys = [0, 1], zs = [0, 0.5], pos = [];
  for (const x of xs) for (const y of ys) for (const z of zs) pos.push(x, y, z);
  const faces = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]], idx = [];
  for (const [a, b, c, d] of faces) idx.push(a, b, c, a, c, d);
  const pb = Buffer.from(new Float32Array(pos).buffer), ib0 = Buffer.from(new Uint16Array(idx).buffer);
  const ib = Buffer.concat([ib0, Buffer.alloc((4 - (ib0.length % 4)) % 4)]), bin = Buffer.concat([pb, ib]);
  const json = { asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: "box" }],
    meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }], buffers: [{ byteLength: bin.length }],
    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: pb.length }, { buffer: 0, byteOffset: pb.length, byteLength: ib0.length }],
    accessors: [{ bufferView: 0, componentType: 5126, count: 8, type: "VEC3", min: [0, 0, 0], max: [2, 1, 0.5] }, { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" }] };
  let js = Buffer.from(JSON.stringify(json)); js = Buffer.concat([js, Buffer.alloc((4 - (js.length % 4)) % 4, 0x20)]);
  const head = Buffer.alloc(12); head.write("glTF", 0); head.writeUInt32LE(2, 4); head.writeUInt32LE(12 + 8 + js.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([head, ch(js.length, "JSON"), js, ch(bin.length, "BIN\0"), bin]);
}
const GLB = boxGlb();
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0}#w{width:640px;height:400px}</style></head><body><div id="w"></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  const v = window.Adom3DViewerBabylon9.init(document.getElementById('w'), { zUp: true, showViewCube: false, showGround: false, modelUrl: '/box.glb' });
  await v.whenReady();
  window.__v = v;
  window.__cam = () => { const c = v.getCamera(); return { alpha: c.alpha, beta: c.beta, radius: c.radius, target: c.target.asArray() }; };
  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 p = new URL(req.url, "http://x").pathname;
  if (p === "/t.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }
  if (p === "/box.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(GLB); }
  const f = join(DIST, p.replace(/^\/+/, ""));
  if (f.startsWith(DIST) && existsSync(f)) { res.writeHead(200, { "Content-Type": f.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(f)); }
  res.writeHead(404); res.end();
});
await new Promise(r => server.listen(0, "127.0.0.1", r));

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"] });
const near = (a, b, eps = 1e-3) => a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) < eps);
const fmt = (a) => "[" + a.map(x => x.toFixed(3)).join(", ") + "]";

try {
  const page = await browser.newPage();
  const errors = [];
  page.on("pageerror", e => errors.push(String(e && e.message || e)));
  await page.goto(`http://127.0.0.1:${server.address().port}/t.html`, { waitUntil: "load", timeout: left() });
  await page.waitForFunction(() => window.__ready === true, { timeout: left() });
  const home = (view) => page.evaluate((view) => { window.__v.setHomeView(view); window.__v.goHome(); return window.__cam(); }, view);

  section("without a target, Home aims at the bounding-box center (unchanged)");
  const plain = await home({ alpha: 0.6, beta: 1.1 });
  assert(near(plain.target, [1, 0.5, 0.25]), `target ${fmt(plain.target)} is the box center [1, 0.5, 0.25]`);
  assert(Math.abs(plain.alpha - 0.6) < 1e-6 && Math.abs(plain.beta - 1.1) < 1e-6, "with the host's angles");

  section("a target moves the orbit point, nothing else");
  const aimed = await home({ alpha: 0.6, beta: 1.1, target: [0.5, 0.2, 0.1] });
  assert(near(aimed.target, [0.5, 0.2, 0.1]), `target ${fmt(aimed.target)} is the host's [0.5, 0.2, 0.1], in the model's own frame`);
  assert(Math.abs(aimed.alpha - 0.6) < 1e-6 && Math.abs(aimed.beta - 1.1) < 1e-6, "the angles are the host's");
  assert(Math.abs(aimed.radius - plain.radius) < 1e-6, `the distance is the same framing (${aimed.radius.toFixed(3)})`);

  section("Home returns to it after the user moves");
  await page.evaluate(() => { const c = window.__v.getCamera(); c.alpha += 1; c.beta -= 0.3; c.setTarget(new c.target.constructor(1.9, 0.9, 0.4), false, false, true); });
  const back = await page.evaluate(() => { window.__v.goHome(); return window.__cam(); });
  assert(near(back.target, [0.5, 0.2, 0.1]) && Math.abs(back.alpha - 0.6) < 1e-6, `Home brings back target ${fmt(back.target)} and alpha ${back.alpha.toFixed(3)}`);

  section("a malformed target is ignored");
  for (const bad of [[1, 2], ["x", 0, 0], null, "1,2,3"]) {
    const r = await home({ alpha: 0.6, beta: 1.1, target: bad });
    assert(near(r.target, [1, 0.5, 0.25]), `target ${JSON.stringify(bad)} falls back to the center ${fmt(r.target)}`);
  }
  assert(errors.length === 0, `no page errors (${errors.join("; ").slice(0, 200)})`);
  await page.close();
} finally {
  await browser.close();
  server.close();
}
console.log(`\nhome target: ${passed} passed, ${failed} failed`);
if (failed) { for (const f of failures) console.log("  - " + f); process.exit(1); }