master
AdityaAngajala
v0.12.8
160fd3c
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
// Lights carried INSIDE a GLB (adom/adom-3d-viewer#7). John's LED component
// models ship a KHR_lights_punctual spot inside an Adom.LED.State group with
// the emissive lens skin. The viewer budgets them (Babylon lights at most
// maxSimultaneousLights per material, and the rig already uses three), never
// rescales their photometry, keeps shadows off, gives every declared group a
// toggle, and treats each placement as its own light.
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); } }
const eq = (a, b, msg) => assert(a === b, `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);
function section(t) { console.log("\n [" + t + "]"); }
/**
* A GLB with `count` LED placements. Every placement is an Adom.LED.State
* group holding an emissive lens mesh and a light node; all of them REFERENCE
* THE SAME glTF light index, which is what a board assembled from one LED file
* looks like, and the case where a shared light object would switch every LED
* at once. `parentScale` puts the whole thing under a scaled node.
*/
function makeLedGlb(count, { parentScale = null, spacing = 0.01 } = {}) {
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.001, v[1] * 0.001, v[2] * 0.001)); 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 nodes = [], sceneNodes = [];
for (let i = 0; i < count; i++) {
const state = nodes.length;
nodes.push(null); // placeholder, filled after its children exist
const lens = nodes.length;
nodes.push({ name: "Adom.LED.Emission", mesh: 0, extras: { adomRole: "led-emission", defaultEnabled: true } });
const light = nodes.length;
nodes.push({ name: "Adom.LED.Light", extensions: { KHR_lights_punctual: { light: 0 } }, extras: { adomRole: "led-light" } });
nodes[state] = { name: "Adom.LED.State", translation: [i * spacing, 0, 0], children: [lens, light], extras: { adomRole: "led-state", defaultEnabled: true } };
sceneNodes.push(state);
}
// An MPN marking outside the LED groups: an independent toggle.
const mpn = nodes.length;
nodes.push({ name: "Adom.LaserEtch.MPN", mesh: 0, translation: [0, 0.004, 0], extras: { adomRole: "mpn-marking", defaultEnabled: true } });
sceneNodes.push(mpn);
let roots = sceneNodes;
if (parentScale) {
const wrap = nodes.length;
nodes.push({ name: "scaled_group", scale: [parentScale, parentScale, parentScale], children: sceneNodes });
roots = [wrap];
}
const json = {
asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: roots }],
extensionsUsed: ["KHR_lights_punctual"],
extensions: { KHR_lights_punctual: { lights: [{ name: "Adom.LED.Light", type: "spot", color: [0, 1, 0.1], intensity: 0.000075, range: 0.015, spot: { innerConeAngle: 0.97, outerConeAngle: 1.48 } }] } },
nodes,
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
materials: [{ name: "Adom.LED.Emissive.green", pbrMetallicRoughness: { baseColorFactor: [0.2, 1, 0.3, 1] }, emissiveFactor: [0, 1, 0] }],
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.001, -0.001, -0.001], max: [0.001, 0.001, 0.001] }, { 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 MODELS = {
"/one.glb": makeLedGlb(1),
"/two.glb": makeLedGlb(2),
"/many.glb": makeLedGlb(8),
"/scaled.glb": makeLedGlb(1, { parentScale: 1000 }),
};
const HARNESS = (model, budget) => `<!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, showHelp: false, modelUrl: '${model}'${budget === undefined ? "" : `, lightBudget: ${budget}`} });
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 (MODELS[url.pathname]) { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(MODELS[url.pathname]); }
if (url.pathname === "/view.html") {
const model = url.searchParams.get("model") || "/one.glb";
const budget = url.searchParams.has("budget") ? Number(url.searchParams.get("budget")) : undefined;
res.writeHead(200, { "Content-Type": "text/html" });
return res.end(HARNESS(model, budget));
}
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"] });
const warnings = [];
async function open(query) {
const page = await browser.newPage();
page.on("console", m => { if (m.type() === "warning" || m.type() === "warn") warnings.push(m.text()); });
await page.setViewport({ width: 640, height: 400 });
await page.goto(`http://127.0.0.1:${port}/view.html?${query}`, { waitUntil: "load", timeout: 90000 });
await page.waitForFunction("window.__ready === true", { timeout: 90000 });
await new Promise(r => setTimeout(r, 600));
return page;
}
try {
section("the GLB's own light survives the import untouched");
{
const page = await open("model=/one.glb");
const d = await page.evaluate(() => {
const v = window.__viewer, s = v.getScene();
return {
lights: v.getContentLights(),
sceneLights: s.lights.length,
shadowEnabled: s.lights.filter(l => l.name === "Adom.LED.Light").map(l => l.shadowEnabled),
contentMax: [...new Set(s.materials.filter(m => (m.name || "").startsWith("Adom.LED.Emissive")).map(m => m.maxSimultaneousLights))],
budget: v.getLightBudget(),
};
});
eq(d.lights.length, 1, "one content light");
eq(d.lights[0].range, 0.015, "range is the authored 15 mm, not rescaled");
eq(d.lights[0].intensity, 0.000075, "intensity is the authored candela");
eq(d.lights[0].role, "led-light", "its adomRole is reported");
eq(d.lights[0].active, true, "and it is lit");
assert(d.shadowEnabled.every(x => x === false), "no per-LED shadows");
eq(d.budget, 4, "default budget of 4");
assert(d.contentMax.every(m => m >= 7), `content materials allow the viewer's lights plus the budget (got ${d.contentMax})`);
await page.close();
}
section("a light under a scaled node is called out, never silently rescaled");
{
warnings.length = 0;
const page = await open("model=/scaled.glb");
const lights = await page.evaluate(() => window.__viewer.getContentLights());
eq(lights[0].range, 0.015, "the viewer still does not touch the range");
assert(warnings.some(w => /scaled 1000/.test(w) && /do not follow a node matrix/.test(w)), `the author is warned (${warnings.slice(0, 2).join(" | ")})`);
await page.close();
}
section("each placement is its own light and its own switch");
{
const page = await open("model=/two.glb");
const before = await page.evaluate(() => ({ states: window.__viewer.getStateGroups(), lights: window.__viewer.getContentLights() }));
eq(before.lights.length, 2, "two placements sharing one glTF light index load as two lights");
eq(before.states.length, 2, "two switchable roles: the LED state and the MPN");
const led = before.states.find(g => g.key === "led-state");
eq(led.label, "LED State", "the row is named after the group");
eq(led.instances.length, 2, "with both placements behind it");
const after = await page.evaluate(() => {
window.__viewer.setStateInstanceEnabled("led-state", 0, false);
return { lights: window.__viewer.getContentLights(), states: window.__viewer.getStateGroups() };
});
eq(after.lights.filter(l => l.active).length, 1, "switching one placement off leaves the other lit");
eq(after.states.find(g => g.key === "led-state").instances.map(i => i.enabled).join(","), "false,true", "and only that placement is off");
const both = await page.evaluate(() => {
window.__viewer.setStateGroupEnabled("led-state", false);
const geometryOff = window.__viewer.getScene().meshes.filter(m => m.name.startsWith("Adom.LED.Emission")).every(m => !m.isEnabled());
return { lit: window.__viewer.getContentLights().filter(l => l.active).length, geometryOff };
});
eq(both.lit, 0, "switching the role off takes every LED light with it");
assert(both.geometryOff, "and the lens geometry goes with it");
const mpn = await page.evaluate(() => {
window.__viewer.setStateGroupEnabled("mpn-marking", false);
return { mpnOff: window.__viewer.getScene().meshes.filter(m => m.name.startsWith("Adom.LaserEtch.MPN")).every(m => !m.isEnabled()), lights: window.__viewer.getContentLights().length };
});
assert(mpn.mpnOff, "the MPN toggles independently");
eq(mpn.lights, 2, "and touches no lights");
await page.close();
}
section("the choice is remembered, like every other viewer preference");
{
// With every group off nothing would show, and saved choices that leave
// nothing on screen are ignored (state-scope.test.mjs); keep the MPN on.
const prev = await open("model=/two.glb");
await prev.evaluate(() => { window.__viewer.setStateGroupEnabled("led-state", false); window.__viewer.setStateGroupEnabled("mpn-marking", true); });
await prev.close();
const page = await open("model=/two.glb");
const back = await page.evaluate(() => window.__viewer.getStateGroups().map(g => `${g.key}:${g.enabled}`).join(","));
assert(/led-state:false/.test(back), `a group switched off in the last session comes back off (${back})`);
await page.evaluate(() => { window.__viewer.setStateGroupEnabled("led-state", true); window.__viewer.setStateGroupEnabled("mpn-marking", true); });
await page.close();
}
section("a board full of LEDs stays within the light budget");
{
const page = await open("model=/many.glb");
const d = await page.evaluate(() => ({ lights: window.__viewer.getContentLights(), budget: window.__viewer.getLightBudget() }));
eq(d.lights.length, 8, "eight placements");
eq(d.lights.filter(l => l.active).length, d.budget, "only the budget is lit at once");
assert(d.lights.every(l => l.range === 0.015), "the unlit ones keep their photometry (they are switched, not edited)");
const two = await page.evaluate(() => { window.__viewer.setLightBudget(2); return window.__viewer.getContentLights().filter(l => l.active).length; });
eq(two, 2, "a smaller budget lights fewer");
const none = await page.evaluate(() => { window.__viewer.setContentLightsEnabled(false); return window.__viewer.getContentLights().filter(l => l.active).length; });
eq(none, 0, "and they can all be switched off");
const geometryStillThere = await page.evaluate(() => window.__viewer.getScene().meshes.filter(m => m.name.startsWith("Adom.LED.Emission")).every(m => m.isEnabled()));
assert(geometryStillThere, "the emissive lenses keep glowing either way");
await page.close();
}
section("the budget follows the camera");
{
const page = await open("model=/many.glb&budget=2");
const d = await page.evaluate(async () => {
const v = window.__viewer, cam = v.getCamera(), s = v.getScene();
const lit = () => v.getContentLights().filter(l => l.active).map(l => +l.position.x.toFixed(4)).sort((a, b) => a - b);
const xs = v.getContentLights().map(l => +l.position.x.toFixed(4)).sort((a, b) => a - b);
const look = async (x) => {
const t = cam.target.clone(); t.x = x; t.y = 0; t.z = 0; cam.setTarget(t);
for (let i = 0; i < 4; i++) { s.render(); await new Promise(r => setTimeout(r, 140)); }
return lit();
};
const near = await look(xs[0]);
const far = await look(xs[xs.length - 1]);
return { xs, near, far };
});
eq(d.near.length, 2, "two lit at a time");
assert(d.near.join(",") !== d.far.join(","), `looking elsewhere lights different LEDs (${d.near} then ${d.far})`);
assert(d.near.includes(d.xs[0]) && d.far.includes(d.xs[d.xs.length - 1]), `the LEDs nearest what you are looking at are the lit ones (${d.near} / ${d.far})`);
await page.close();
}
section("loading another model does not leave the old lights behind");
{
const page = await open("model=/two.glb");
const d = await page.evaluate(async () => {
const v = window.__viewer;
const before = v.getScene().lights.length;
v.clearScene();
const afterClear = v.getScene().lights.length;
await v.loadModel("/one.glb");
await new Promise(r => setTimeout(r, 300));
return { before, afterClear, afterLoad: v.getContentLights().length, sceneLights: v.getScene().lights.length };
});
eq(d.afterClear, d.before - 2, "clearScene disposes the content lights");
eq(d.afterLoad, 1, "the next model brings its own");
eq(d.sceneLights, d.before - 1, "and nothing accumulates");
await page.close();
}
section("a GLB with no lights is untouched");
{
const page = await open("model=/one.glb");
const ok = await page.evaluate(() => {
const v = window.__viewer;
v.clearScene();
return { lights: v.getContentLights().length, states: v.getStateGroups().length };
});
eq(ok.lights, 0, "no content lights after a clear");
eq(ok.states, 0, "and no state rows");
await page.close();
}
} finally {
await browser.close();
server.close();
}
console.log(`\n=== content lights ===\n${passed} passed, ${failed} failed`);
if (failed) { console.log(failures.map(f => " - " + f).join("\n")); process.exit(1); }