master
AdityaAngajala v0.12.8 160fd3c
// Render lifecycle (adom/adom-3d-viewer#10, PR #1): a viewer renders while
// it is visible, stops submitting frames when its canvas leaves the viewport
// or the document is hidden, resumes when it comes back, and releases its
// render callback and observers when destroyed.
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 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), 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();
const HARNESS = (showHelp) => `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#host{position:relative;width:640px;height:400px}#wrap{position:absolute;inset:0}</style></head><body><div id="host"><div id="wrap"></div></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  const v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showGround: false, modelUrl: '/chip.glb'${showHelp ? "" : ", showHelp: false"} });
  await v.whenReady(); window.__viewer = v; 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 === "/help.html" || url.pathname === "/nohelp.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS(url.pathname === "/help.html")); }
  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; }
  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();await page.setViewport({width:800,height:600});
 await page.goto(`http://127.0.0.1:${port}/help.html`);await page.waitForFunction(()=>window.__ready,{timeout:90000});
 await page.evaluate(()=>{window.framesSeen=0;window.__viewer.getScene().onAfterRenderObservable.add(()=>window.framesSeen++);});
 const count=()=>page.evaluate(()=>window.framesSeen);
 // A pause takes effect a frame or more after its cause (a frame in flight, the
 // IntersectionObserver callback after the next layout), so a pause check waits
 // up to 5 s for the count to settle, then requires it to hold still.
 const settles=async()=>{let a=await count();const end=Date.now()+5000;while(Date.now()<end){await sleep(400);const b=await count();if(b===a)return true;a=b;}return false;};
 const stays=async(ms)=>{const a=await count();await sleep(ms);return (await count())===a;};
 const advances=async()=>{const a=await count();const end=Date.now()+5000;while(Date.now()<end){await sleep(100);if((await count())>a)return true;}return false;};
 assert(await advances(),'visible viewer renders');
 await page.evaluate(()=>document.querySelector('#host').style.transform='translateY(2000px)');
 assert(await settles()&&await stays(500),'offscreen viewer pauses');
 await page.evaluate(()=>document.querySelector('#host').style.transform='');
 assert(await advances(),'visible viewer resumes');
 await page.evaluate(()=>{Object.defineProperty(document,'hidden',{configurable:true,get:()=>true});document.dispatchEvent(new Event('visibilitychange'));});
 assert(await settles()&&await stays(400),'hidden document pauses');
 await page.evaluate(()=>{Object.defineProperty(document,'hidden',{configurable:true,get:()=>false});document.dispatchEvent(new Event('visibilitychange'));});
 assert(await advances(),'document resume works');
 await page.evaluate(()=>window.__viewer.destroy());
 assert(await settles()&&await stays(300),'destroy stops renders');
 console.log({passed,failed,failures});if(failed)process.exitCode=1;
} finally {await browser.close();server.close();}