master
AdityaAngajala v0.13.0 12542ed
// Scene options a host sets at init(): animate, repeat and replayAnimations(),
// tooltips, axes, bottomLight, shadows, homeView and homeOnLoad. Each is
// checked against the default it changes.
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");
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 near = (a, b, eps = 1e-4) => Math.abs(a - b) < eps;

/** A GLB of one 2 cm cube. `extras` goes on the node; `seconds` adds a
 *  translation animation from x = 0 to x = 0.02 over that many seconds. */
function makeGlb(nodeName, { extras = null, seconds = 0 } = {}) {
  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 pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);
  const parts = [pad(Buffer.from(new Float32Array(pos).buffer)), pad(Buffer.from(new Uint16Array(idx).buffer))];
  if (seconds) parts.push(pad(Buffer.from(new Float32Array([0, seconds]).buffer)), pad(Buffer.from(new Float32Array([0, 0, 0, 0.02, 0, 0]).buffer)));
  const views = []; let off = 0;
  for (const p of parts) { views.push({ buffer: 0, byteOffset: off, byteLength: p.length }); off += p.length; }
  const bin = Buffer.concat(parts);
  const json = {
    asset: { version: "2.0" }, scene: 0,
    scenes: [{ nodes: [0] }],
    nodes: [{ name: nodeName, mesh: 0, ...(extras ? { extras } : {}) }],
    meshes: [{ name: "mesh", primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
    materials: [{ name: "mat", pbrMetallicRoughness: { baseColorFactor: [0.8, 0.5, 0.2, 1] } }],
    ...(seconds ? { animations: [{ name: "slide", samplers: [{ input: 2, output: 3, interpolation: "LINEAR" }], channels: [{ sampler: 0, target: { node: 0, path: "translation" } }] }] } : {}),
    buffers: [{ byteLength: bin.length }],
    bufferViews: views,
    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" },
      ...(seconds ? [{ bufferView: 2, componentType: 5126, count: 2, type: "SCALAR", min: [0], max: [seconds] }, { bufferView: 3, componentType: 5126, count: 2, type: "VEC3" }] : []),
    ],
  };
  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 MODELS = {
  "/slide.glb": makeGlb("Slider_part", { seconds: 0.3 }),
  "/plain.glb": makeGlb("Plain_part"),
  "/authored.glb": makeGlb("Authored_part", { extras: { tooltip: "Authored label" } }),
};
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  window.__tips = [];
  // A fresh viewer in #wrap with these options; the previous one is destroyed.
  window.__make = async (opts) => {
    if (window.__v) window.__v.destroy();
    window.__tips = [];
    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), {
      zUp: true, showViewCube: false, showHelp: false,
      onMeshHover: (mesh, tip) => { if (mesh) window.__tips.push(tip); },
      ...opts });
    await window.__v.whenReady();
  };
  window.__slide = () => {
    const s = window.__v.getScene(); const g = s.animationGroups[0]; const n = s.getTransformNodeByName("Slider_part") || s.getMeshByName("Slider_part");
    return { groups: s.animationGroups.length, playing: !!g && g.isPlaying, loop: !!g && g.loopAnimation, x: n ? n.position.x : null };
  };
  window.__cam = () => { const c = window.__v.getCamera(); return { alpha: c.alpha, beta: c.beta, radius: c.radius }; };
  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 (MODELS[url.pathname]) { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(MODELS[url.pathname]); }
  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }
  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; }
  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"] });
try {
  const page = await browser.newPage();
  const pageErrors = [];
  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));
  await page.setViewport({ width: 640, height: 400 });
  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });
  await page.waitForFunction("window.__ready === true", { timeout: 90000 });
  const run = (fn, ...args) => page.evaluate(fn, ...args);
  const wait = (ms) => new Promise(r => setTimeout(r, ms));
  // Babylon advances animations by rendered frames, so a loaded machine
  // stretches them: wait for the group to stop instead of a fixed time.
  const animationStops = () => page.waitForFunction("(() => { const g = window.__v.getScene().animationGroups[0]; return !!g && !g.isPlaying; })()", { timeout: 20000, polling: 100 }).catch(() => {});
  const make = (opts) => run((o) => window.__make(o), opts);
  const load = (url) => run(async (u) => { await window.__v.loadModel(u); }, url);
  // Hover the middle of the viewer a few times; the viewer picks at most every 50 ms.
  async function hoverTips() {
    await run(() => { window.__tips = []; });
    for (const [x, y] of [[318, 200], [320, 202], [322, 198], [320, 200]]) { await page.mouse.move(x, y); await wait(120); }
    const tips = await run(() => window.__tips.slice());
    await page.mouse.move(5, 5); await wait(120);
    return tips;
  }

  section("animate and repeat");
  await make({});
  await load("/slide.glb");
  await wait(900);
  let a = await run(() => window.__slide());
  assert(a.groups === 1 && a.playing && a.loop, `by default the model's animation keeps looping (${JSON.stringify(a)})`);
  assert(await run(() => window.__v.getAxesState().world) === true, "by default the world axes are on");
  assert(await run(() => window.__v.getBottomLightState()) === false, "by default the bottom light is off");
  assert(await run(() => window.__v.getScene().shadowsEnabled) === true, "by default shadows are on");

  await make({ animate: false });
  await load("/slide.glb");
  await wait(600);
  a = await run(() => window.__slide());
  assert(!a.playing && near(a.x, 0), `animate:false holds the animation at its first frame (${JSON.stringify(a)})`);
  assert(await run(() => window.__v.replayAnimations()) === true, "replayAnimations() returns true for an animated model");
  await animationStops();
  a = await run(() => window.__slide());
  assert(!a.playing && near(a.x, 0.02), `with animate:false a replay plays once and rests on the last frame (${JSON.stringify(a)})`);

  await make({ repeat: 2 });
  await load("/slide.glb");
  await run(() => { window.__ends = 0; window.__v.getScene().animationGroups[0].onAnimationGroupEndObservable.add(() => window.__ends++); });
  await animationStops();
  a = await run(() => window.__slide());
  let ends = await run(() => window.__ends);
  assert(!a.playing && near(a.x, 0.02) && ends === 2, `repeat:2 plays twice, then rests on the last frame (ends ${ends}, ${JSON.stringify(a)})`);
  await run(() => { window.__ends = 0; window.__v.replayAnimations(); });
  await animationStops();
  a = await run(() => window.__slide());
  ends = await run(() => window.__ends);
  assert(!a.playing && near(a.x, 0.02) && ends === 2, `a replay plays twice again (ends ${ends})`);

  await make({});
  await load("/plain.glb");
  assert(await run(() => window.__v.replayAnimations()) === false, "replayAnimations() returns false for a model without animation");

  section("tooltips");
  await make({});
  await load("/plain.glb");
  let tips = await hoverTips();
  assert(tips.length > 0 && tips.every(t => t === "Plain part"), `'all' labels a mesh by its readable name (${JSON.stringify(tips)})`);
  await make({ tooltips: "authored" });
  await load("/plain.glb");
  tips = await hoverTips();
  assert(tips.length > 0 && tips.every(t => t === null), `'authored' gives no label for a mesh without extras.tooltip (${JSON.stringify(tips)})`);
  await make({ tooltips: "authored" });
  await load("/authored.glb");
  tips = await hoverTips();
  assert(tips.length > 0 && tips.every(t => t === "Authored label"), `'authored' keeps extras.tooltip (${JSON.stringify(tips)})`);
  await make({ tooltips: "off" });
  await load("/authored.glb");
  tips = await hoverTips();
  assert(tips.length > 0 && tips.every(t => t === null), `'off' gives no label even with extras.tooltip, and onMeshHover still runs (${tips.length} hovers)`);

  section("axes, bottom light, shadows");
  await make({ axes: false, bottomLight: true, shadows: false });
  await load("/plain.glb");
  await run(() => window.__v.frameModel());
  const s = await run(() => ({ axes: window.__v.getAxesState().world, bottom: window.__v.getBottomLightState(), shadows: window.__v.getScene().shadowsEnabled,
    generator: window.__v.getShadowGenerator(), maps: window.__v.getScene().textures.filter(t => /_shadowMap$/.test(t.name)).length }));
  assert(s.axes === false, "axes:false starts with the world axes off, and a load keeps them off");
  assert(s.bottom === true, "bottomLight:true starts with the bottom light on");
  assert(s.shadows === false, "shadows:false keeps shadows off through a load and a reframe");
  assert(s.generator === null && s.maps === 0, `shadows:false creates no shadow generator and no shadow map (${s.maps} maps)`);

  section("homeView and homeOnLoad");
  const view = { alpha: 1.1, beta: 0.6, radiusScale: 2 };
  await make({ homeView: view, homeOnLoad: true });
  await load("/plain.glb");
  const opened = await run(() => window.__cam());
  assert(near(opened.alpha, 1.1) && near(opened.beta, 0.6), `homeOnLoad opens at the host's home view (${JSON.stringify(opened)})`);
  await run(() => { const c = window.__v.getCamera(); c.alpha = 0.2; c.beta = 1.2; window.__v.goHome(); });
  const back = await run(() => window.__cam());
  assert(near(back.alpha, 1.1) && near(back.beta, 0.6) && near(back.radius, opened.radius, 1e-6), "goHome() returns to the same view");
  await load("/authored.glb");
  const second = await run(() => window.__cam());
  assert(near(second.alpha, 1.1) && near(second.beta, 0.6), "a second load keeps the current angle (only the first load goes Home)");

  await run(async (v) => {
    window.__v.destroy();
    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showHelp: false, homeView: v, homeOnLoad: true });
    await window.__v.loadModel("/plain.glb");
  }, view);
  const early = await run(() => window.__cam());
  assert(near(early.alpha, 1.1) && near(early.beta, 0.6), `a load started right after init(), before the viewer is ready, also opens at the home view (${JSON.stringify(early)})`);

  await make({ homeOnLoad: true });
  await load("/plain.glb");
  const corner = await run(() => window.__cam());
  await run(() => window.__v.goHome());
  const corner2 = await run(() => window.__cam());
  assert(near(corner.alpha, corner2.alpha) && near(corner.beta, corner2.beta), "homeOnLoad without homeView opens at the cube corner, where Home goes");

  await make({ homeView: view });
  await load("/plain.glb");
  const plain = await run(() => window.__cam());
  assert(!near(plain.alpha, 1.1) || !near(plain.beta, 0.6), "without homeOnLoad the first load frames from the starting view, not Home");

  assert(pageErrors.length === 0, `no page errors (${pageErrors.join(" | ") || "none"})`);
} finally {
  await browser.close();
  server.close();
}
console.log(`\n${passed} passed, ${failed} failed`);
if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }