← Commit history
Merge PR #245: Pause rendering for hidden and offscreen 3D viewers
2 files changed
+103−1
src/ThreeDViewer.svelte+31−1@@ -768,6 +768,10 @@ } } + // Keep one render callback and suspend it while this viewer is not visible.+ // Visible scenes retain continuous rendering for camera inertia and GLB states.+ let renderVisibilityCleanup: (() => void) | undefined;+ let destroyed = false; async function initViewer() { if (!canvas || !container) return; await AdomStatics.init(canvas, zUp);@@ -800,7 +804,31 @@ } scene.executeWhenReady(async () => {- engine.runRenderLoop(() => scene.render());+ if (destroyed) return;+ let intersects = true;+ let running = false;+ const render = () => scene.render();+ const syncRendering = () => {+ const shouldRun = !destroyed && !document.hidden && intersects;+ if (shouldRun === running) return;+ running = shouldRun;+ if (running) engine.runRenderLoop(render);+ else engine.stopRenderLoop(render);+ };+ const observer = typeof IntersectionObserver === 'undefined' ? null :+ new IntersectionObserver(entries => {+ intersects = entries.some(entry => entry.isIntersecting);+ syncRendering();+ });+ observer?.observe(container);+ document.addEventListener('visibilitychange', syncRendering);+ renderVisibilityCleanup = () => {+ observer?.disconnect();+ document.removeEventListener('visibilitychange', syncRendering);+ engine.stopRenderLoop(render);+ running = false;+ };+ syncRendering(); const cam = AdomStatics.camera; if (cam && initialViewMode === 'orthographic' && !cam.isOrthographic()) {@@ -1579,6 +1607,8 @@ }); onDestroy(() => {+ destroyed = true;+ renderVisibilityCleanup?.(); document.removeEventListener('securitypolicyviolation', onCspViolation); canvas?.removeEventListener('dblclick', onDoubleClick); canvas?.removeEventListener('pointermove', onPointerMoveTooltip);
test/visibility.test.mjsadded+72@@ -0,0 +1,72 @@+// The ? button, the controls card and the one-time Shift+Alt tip (Colby,+// 2026-09-16): every consumer gets a small ? in the corner; its card leads+// with Shift+Alt+click to set the center of rotation; the tip bubble shows+// once per browser when the first model is ready; showHelp:false hides it all.+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, "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);+ let a=await count();await sleep(500);assert(await count()>a,'visible viewer renders');+ await page.evaluate(()=>document.querySelector('#host').style.transform='translateY(2000px)');await sleep(300);+ a=await count();await sleep(500);assert((await count())===a,'offscreen viewer pauses');+ await page.evaluate(()=>document.querySelector('#host').style.transform='');await sleep(300);+ a=await count();await sleep(500);assert(await count()>a,'visible viewer resumes');+ await page.evaluate(()=>{Object.defineProperty(document,'hidden',{configurable:true,get:()=>true});document.dispatchEvent(new Event('visibilitychange'));});+ await sleep(100);a=await count();await sleep(400);assert((await count())===a,'hidden document pauses');+ await page.evaluate(()=>{Object.defineProperty(document,'hidden',{configurable:true,get:()=>false});document.dispatchEvent(new Event('visibilitychange'));});+ a=await count();await sleep(500);assert(await count()>a,'document resume works');+ await page.evaluate(()=>window.__viewer.destroy());await sleep(200);a=await count();await sleep(300);assert((await count())===a,'destroy stops renders');+ console.log({passed,failed,failures});if(failed)process.exitCode=1;+} finally {await browser.close();server.close();}