master
AdityaAngajala
v0.12.8
160fd3c
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
// Replacing the shown model (adom/adom-3d-viewer#11). loadModel() is additive
// by design (a second call shows both models: John's harness meshes doubled
// that way); replaceModel() swaps, disposing everything the earlier model
// brought: meshes, materials, textures, animation groups, skeletons and the
// layer inventory. Repeated replacement keeps the scene the same size, the
// later of two overlapping replacements wins, a failed load keeps the current
// model, and clearScene() releases materials and textures too.
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(JSON.stringify(a) === JSON.stringify(b), `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);
function section(t) { console.log("\n [" + t + "]"); }
// A 1x1 PNG, for a textured material.
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
/** A GLB of named cubes; `textured` gives them a textured material, `animated` a translation animation. */
function makeGlb(prefix, names, { textured = false, animated = false } = {}) {
const pos = [], uv = [], 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); }); uv.push(0, 0, 1, 0, 1, 1, 0, 1); 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 posBuf = pad(Buffer.from(new Float32Array(pos).buffer));
const uvBuf = pad(Buffer.from(new Float32Array(uv).buffer));
const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));
const times = pad(Buffer.from(new Float32Array([0, 1]).buffer));
const trans = pad(Buffer.from(new Float32Array([0, 0, 0, 0.02, 0, 0]).buffer));
const png = pad(PNG);
const parts = [posBuf, uvBuf, idxBuf, times, trans, png];
const views = []; let off = 0;
for (const p of parts) { views.push({ buffer: 0, byteOffset: off, byteLength: p.length }); off += p.length; }
views[5].byteLength = PNG.length;
const bin = Buffer.concat(parts);
const json = {
asset: { version: "2.0" }, scene: 0,
scenes: [{ nodes: names.map((_, i) => i) }],
nodes: names.map((n, i) => ({ name: `${prefix}_${n}`, mesh: 0, translation: [i * 0.03, 0, 0] })),
meshes: [{ name: `${prefix}_mesh`, primitives: [{ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0 }] }],
materials: [{ name: `${prefix}_mat`, pbrMetallicRoughness: textured ? { baseColorTexture: { index: 0 } } : { baseColorFactor: [0.8, 0.5, 0.2, 1] } }],
...(textured ? { textures: [{ source: 0, name: `${prefix}_tex` }], images: [{ name: `${prefix}_img`, bufferView: 5, mimeType: "image/png" }] } : {}),
...(animated ? { animations: [{ name: `${prefix}_anim`, samplers: [{ input: 3, output: 4, 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: 5126, count: uv.length / 2, type: "VEC2" },
{ bufferView: 2, componentType: 5123, count: idx.length, type: "SCALAR" },
{ bufferView: 3, componentType: 5126, count: 2, type: "SCALAR", min: [0], max: [1] },
{ bufferView: 4, 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 = {
// The old harness: two sensor wires, textured and animated.
"/old.glb": makeGlb("OldWire", ["sense", "return"], { textured: true, animated: true }),
// The new export: a different set of parts.
"/new.glb": makeGlb("NewPart", ["body", "lid", "screw"]),
};
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;inset:0;width:640px;height:400px}</style></head><body><div id="wrap"></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: true, showHelp: false });
await v.whenReady(); window.__viewer = v;
// What the scene holds that a model brought (names carry the model prefix).
window.__census = () => {
const s = v.getScene();
const pick = (list) => list.map(x => x.name).filter(n => /^(OldWire|NewPart)/.test(n)).sort();
return { meshes: pick(s.meshes), materials: pick(s.materials), textures: s.textures.filter(t => /OldWire|NewPart/.test(t.name || "")).length,
animationGroups: s.animationGroups.filter(g => /OldWire|NewPart/.test(g.name)).length, totalMeshes: s.meshes.length, totalMaterials: s.materials.length,
totalTextures: s.textures.length, camera: !!v.getCamera() };
};
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();
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 census = () => run(() => window.__census());
section("loadModel is additive (the doubled-harness case)");
await run(async () => { await window.__viewer.loadModel("/old.glb"); await window.__viewer.loadModel("/new.glb"); });
let c = await census();
assert(c.meshes.some(n => n.startsWith("OldWire")) && c.meshes.some(n => n.startsWith("NewPart")), "both models are in the scene after two loadModel calls");
section("replaceModel swaps: nothing of the old model stays");
await run(async () => { await window.__viewer.replaceModel("/old.glb"); });
c = await census();
assert(c.meshes.every(n => n.startsWith("OldWire")) && c.meshes.length > 0, "only the replacing model's meshes");
eq(c.animationGroups, 1, "its animation group is there");
assert(c.textures >= 1, "its texture is there");
await run(async () => { await window.__viewer.replaceModel("/new.glb"); });
c = await census();
eq(c.meshes.filter(n => n.startsWith("OldWire")), [], "no old wire meshes");
eq(c.materials.filter(n => n.startsWith("OldWire")), [], "no old materials");
eq(c.textures, 0, "no old textures");
eq(c.animationGroups, 0, "no old animation groups");
assert(c.meshes.some(n => n === "NewPart_body"), "the new model is shown");
assert(c.camera, "the camera (viewer controls) stays");
section("repeated replacement keeps the scene the same size");
const sizes = [];
for (let i = 0; i < 6; i++) {
await run(async (u) => { await window.__viewer.replaceModel(u); }, i % 2 ? "/new.glb" : "/old.glb");
const k = await census();
sizes.push([k.totalMeshes, k.totalMaterials, k.totalTextures]);
}
eq(sizes[2], sizes[0], "old -> new -> old: the same counts as the first old");
eq(sizes[4], sizes[0], "and again");
eq(sizes[5], sizes[3], "new counts stable too");
section("bytes replace the same way");
await run(async () => { const b = new Uint8Array(await (await fetch("/old.glb")).arrayBuffer()); await window.__viewer.replaceModelBytes(b, { extension: ".glb" }); });
c = await census();
assert(c.meshes.length > 0 && c.meshes.every(n => n.startsWith("OldWire")), "replaceModelBytes leaves only the new bytes' model");
section("the later of two overlapping replacements wins");
await run(async () => { const v = window.__viewer; await Promise.all([v.replaceModel("/new.glb"), v.replaceModel("/old.glb")]); });
c = await census();
assert(c.meshes.length > 0 && c.meshes.every(n => n.startsWith("OldWire")), `only the second call's model (${c.meshes.join(",")})`);
section("a failed replacement keeps the current model");
const err = await run(async () => { try { await window.__viewer.replaceModel("/missing.glb"); return null; } catch (e) { return String(e && e.message || e); } });
assert(!!err, "the failure is reported to the caller");
c = await census();
assert(c.meshes.length > 0 && c.meshes.every(n => n.startsWith("OldWire")), "the current model is still shown");
section("addModel is the explicit additive load; clearScene releases everything");
await run(async () => { await window.__viewer.addModel("/new.glb"); });
c = await census();
assert(c.meshes.some(n => n.startsWith("OldWire")) && c.meshes.some(n => n.startsWith("NewPart")), "addModel shows both");
await run(() => window.__viewer.clearScene());
c = await census();
eq(c.meshes, [], "no model meshes after clearScene");
eq(c.materials, [], "no model materials after clearScene");
eq([c.textures, c.animationGroups], [0, 0], "no model textures or animations after clearScene");
} finally {
await browser.close();
server.close();
}
console.log(`\n=== replace ===\n${passed} passed, ${failed} failed`);
if (failures.length) for (const f of failures) console.log(" - " + f);
process.exit(failed ? 1 : 0);