← Commit history
v0.7.0
17 files changed
+1112−96
README.md+5−5docs/CONTENT-CONVENTIONS.md+44package.json+34−6src/ThreeDViewer.svelte+453−54src/lib/adom-babylon/3DViewer/SceneBuilder.ts+62−10src/lib/adom-babylon/3DViewer/ViewCubeBuilder.ts+40−8src/lib/adom-babylon/AdomStatics.ts+39−1src/lib/adom-babylon/Camera/AdomCamera.ts+7−11src/lib/adom-babylon/util/prefs.ts+47src/lib/adom-babylon/util/readiness.ts+31standalone.ts+49−1svelte.config.mjs+5test/wiki-sandbox.test.mjs+219vite.config.mts+24vite.standalone.config.mts+53wiki/install.shwiki/uninstall.shREADME.md+5−5@@ -79,25 +79,25 @@ window.Adom3DViewerBabylon9 = { `ViewerInstance` exposes: - `loadModel(url)` / `loadModelBytes(bytes, { extension? })` / `clearScene()` / `frameModel(fillFraction?)`-- `whenReady()` / `getReadyReport()` — the ready report (see "Sandboxed+- `whenReady()` / `getReadyReport()`: the ready report (see "Sandboxed frames" below): resolves once the first scene is up and reflects the current state on every later call; never rejects - `getScene()` / `getEngine()` / `getCamera()` / `getShadowGenerator()` - `addContentRoot(node, opts?)` / `removeContentRoot(node)` - `toggleDebugLayer()` / `showDebugLayer()` / `hideDebugLayer()` - `setGroundVisible(visible)` / `goHome()`-- `setBottomLight(on)` / `getBottomLightState()` — underside fill light, default off+- `setBottomLight(on)` / `getBottomLightState()`: underside fill light, default off - `setProjectionMode(ortho)` / `getProjectionMode()` - `toggleAxes("world" | "mesh-local", force?)` / `getAxesState()`-- `getLayers()` / `setLayerVisible(name, visible)` — layers, either declared by+- `getLayers()` / `setLayerVisible(name, visible)`: layers, either declared by the content via `extras.adomLayer` or matched against the built-in board vocabulary (`docs/CONTENT-CONVENTIONS.md`). Each entry carries `group` for sectioning and `declared` to say which source it came from. Empty for GLBs with fewer than two layers-- `captureScreenshot({ width?, height? })` — resolves to a PNG data URL.+- `captureScreenshot({ width?, height? })`: resolves to a PNG data URL. Renders through an offscreen target, so the result does not depend on the on-screen canvas size-- `setShadowRefreshRate(rate | null)` — pin the shadow map refresh rate;+- `setShadowRefreshRate(rate | null)`: pin the shadow map refresh rate; `null` restores automatic behaviour. Needed for content animated from outside the viewer, which `scene.animationGroups` cannot see - `destroy()`
docs/CONTENT-CONVENTIONS.md+44@@ -24,6 +24,50 @@ toolbar will group toggles by them. Anything else keeps its own name (underscores become spaces in labels). +## Declaring your own layers++The names above are a built-in vocabulary for printed circuit boards. They are+not the only vocabulary, and the viewer has no special knowledge of them beyond+this table.++Any GLB can declare its own layers by putting `adomLayer` in a node's glTF+`extras`. Use this when your model is not a PCB, or when its node names do not+match (and should not have to match) the board convention.++```json+{+ "name": "Mesh_014",+ "extras": {+ "adomLayer": { "key": "reels", "label": "Reels", "group": "Mechanism" }+ }+}+```++| Field | Required | Meaning |+|-------|----------|---------|+| `key` | yes | Stable identifier. What `setLayerVisible(key, ...)` takes. |+| `label` | no | Text shown in the panel. Defaults to the key with underscores as spaces. |+| `group` | no | Section heading in the panel. Layers sharing a group are listed together. |+| `hidden` | no | `true` starts the layer switched off, the way solder and paste do. |++Notes that matter in practice:++- `extras` may sit on the mesh **or an ancestor node**. Babylon splits+ multi-material primitives into child meshes, so declaring on the group that+ owns them is usually what you want, and works. The **nearest declaration+ wins**: an ancestor's layer covers its whole subtree except where a+ descendant declares (or name-matches) its own, so a declared group node and+ finer declarations under it compose instead of the ancestor swallowing them+ (adom/wiki#162).+- A declared layer **wins over the built-in vocabulary at the same node**, so+ a node that happens to be called `silk` can still declare itself something+ else.+- A model whose only detected layer is name-matched gets no panel (one layer+ is not worth a panel); a **declared** layer always surfaces, even alone.+- Ordering: built-in layers keep the order in the table above; declared layers+ follow in the order they appear in the file.+- Fewer than two layers means no panel. One layer is not a choice.+ ## Hover tooltips (adom/wiki #35) - Put a `tooltip` string in the glTF `extras` of the node or mesh:
package.json+34−6@@ -3,7 +3,39 @@ "version": "0.7.0", "description": "The Babylon 9.5 engine behind every component page's 3D tab on wiki.adom.inc. Versioned ESM bundle with GLB loading, view cube, layers toolbar, ground shadows, and Z-up CAD framing.", "type": "app",+ "main": "./dist/index.js",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts"+ }+ },+ "files": [+ "dist",+ "dist-standalone",+ "src",+ "standalone.ts"+ ],+ "scripts": {+ "build": "vite build",+ "build:standalone": "vite build --config vite.standalone.config.mts",+ "dev": "vite build --watch",+ "prepare": "npm run build",+ "test:sandbox": "node test/wiki-sandbox.test.mjs"+ }, "dependencies": {},+ "devDependencies": {+ "@sveltejs/vite-plugin-svelte": "^3.1.2",+ "svelte-check": "^3.8.6",+ "terser": "^5.46.2",+ "typescript": "^5.5.4",+ "vite": "^5.4.1"+ },+ "peerDependencies": {+ "svelte": "^4.0.0 || ^5.0.0"+ }, "slug": "adom-3d-viewer", "license": "MIT", "tags": [@@ -37,9 +69,5 @@ "prompt": "Download the 0.4.3 viewer bundle so my tool vendors a fixed build" } ],- "title": "Adom 3D Viewer",- "scripts": {- "install": "./install.sh",- "uninstall": "./uninstall.sh"- }-}+ "title": "Adom 3D Viewer"+}
src/ThreeDViewer.svelte+453−54@@ -11,6 +11,9 @@ import { SceneBuilder } from './lib/adom-babylon/3DViewer/SceneBuilder'; import * as AxisHelpers from './lib/adom-babylon/3DViewer/AxisHelpers'; import { ResizableLoadingScreen } from './lib/adom-babylon/ui/ResizableLoadingScreen';+ import { getPref, setPref, prefsBackend } from './lib/adom-babylon/util/prefs';+ import type { EnvironmentStatus } from './lib/adom-babylon/3DViewer/SceneBuilder';+ import type { ViewerHint, ViewerReadyReport } from './lib/adom-babylon/util/readiness'; import type { ViewCubeUICallbacks } from './lib/adom-babylon/3DViewer/ViewCubeBuilder'; import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; import type { TransformNode } from '@babylonjs/core/Meshes/transformNode';@@ -21,8 +24,138 @@ export let showViewCube: boolean = true; export let showGround: boolean = false; export let environmentUrl: string | undefined = undefined;+ /** Bytes of a Babylon .env file to use as the environment map, loaded+ * from memory (no blob URL, no fetch). For frames whose CSP forbids+ * both; the bundled studio map already loads this way. */+ export let environmentBytes: ArrayBufferView | undefined = undefined;+ /** 'none' skips the environment map (flat PBR lighting). */+ export let environment: 'studio' | 'none' = 'studio';+ /** Called once with the ready report: environment, camera, storage,+ * loading overlay, model, CSP violations, and actionable hints. Also+ * reachable as whenReady(). */+ export let onReady: ((report: ViewerReadyReport) => void) | undefined = undefined; /** Initial camera projection. Applied once when the viewer is ready. Use setProjectionMode() to change at runtime. */ export let initialViewMode: 'perspective' | 'orthographic' = 'perspective';+ /** Hover hook (adom/wiki#60 item 5). Called with the picked mesh and the+ * tooltip the viewer resolved for it. Return a string to override that+ * text, null to suppress the tooltip, or nothing to leave it alone.+ * Called with (null, null) when the pointer leaves any content mesh, so a+ * consumer driving its own highlight can clear it. */+ export let onMeshHover: ((mesh: any | null, tip: string | null) => string | null | void) | undefined = undefined;+ /** Called with the ground mesh after each rebuild, for consumers that want+ * their own ground material. The ground is recreated whenever the model is+ * reframed (it is sized from content bounds), so this is the reliable+ * place to reapply a style rather than setting it once from outside. */+ export let onGroundCreated: ((ground: any) => void) | undefined = undefined;++ // Readiness ledger (adom/adom-3d-viewer#5): a consumer in a sandboxed+ // frame cannot tell "painted" from "stuck behind the overlay" by counting+ // meshes, so the viewer reports the state explicitly, with hints that+ // name the fix instead of leaving a black canvas to interpret.+ let envStatus: EnvironmentStatus = { source: 'none', ready: false, error: null };+ let envResolve: ((s: EnvironmentStatus) => void) | null = null;+ const envSettled = new Promise<EnvironmentStatus>((r) => { envResolve = r; });+ const cspViolations: { directive: string; blocked: string }[] = [];+ let readyReport: ViewerReadyReport | null = null;+ let readyResolve: ((r: ViewerReadyReport) => void) | null = null;+ const readyPromise = new Promise<ViewerReadyReport>((r) => { readyResolve = r; });+ let lastModelError: string | null = null;+ let modelRequested = false;++ function onCspViolation(e: Event): void {+ const v = e as SecurityPolicyViolationEvent;+ cspViolations.push({ directive: v.effectiveDirective || v.violatedDirective || '?', blocked: v.blockedURI || '?' });+ }++ /** Resolves with the ready report once the first scene is up. Once ready,+ * every call rebuilds the report from the CURRENT state (a model loaded+ * later via loadModel/loadModelBytes shows up). Never rejects: failures+ * are in the report. */+ export function whenReady(): Promise<ViewerReadyReport> {+ return readyReport ? Promise.resolve(buildReadyReport()) : readyPromise;+ }+ /** The current report, or null before the scene is ready. */+ export function getReadyReport(): ViewerReadyReport | null {+ return readyReport ? buildReadyReport() : null;+ }++ function buildReadyReport(): ViewerReadyReport {+ const engine = AdomStatics.engine;+ const scene = AdomStatics.scene;+ const cam = AdomStatics.camera;+ const hints: ViewerHint[] = [];+ const storage = prefsBackend();+ const overlay = container && container.querySelector('#babylonjsLoadingDiv') ? 'visible' : 'hidden';+ // Count the LOADED content only (model roots and consumer-added+ // roots), never the rig (view cube, axes, ground).+ let meshes = 0, vertices = 0;+ if (scene) {+ const seen = new Set<AbstractMesh>();+ for (const root of [...loadedRootNodes, ...contentRoots]) {+ const all: AbstractMesh[] = [...(root as any).getChildMeshes ? (root as any).getChildMeshes(false) : []];+ if ((root as any).getTotalVertices) all.push(root as any);+ for (const m of all) {+ if (seen.has(m) || !m.getTotalVertices || m.getTotalVertices() === 0) continue;+ seen.add(m); meshes++; vertices += m.getTotalVertices();+ }+ }+ }+ const contextLost = !!(engine && (engine as any).isContextLost && (engine as any).isContextLost());+ if (storage === 'ephemeral') {+ hints.push({ code: 'STORAGE_EPHEMERAL', level: 'info',+ message: 'Browser storage is denied in this frame (a sandboxed origin); viewer preferences such as the camera mode are kept for this document only.',+ action: 'Nothing to do unless preferences must persist: then host the viewer in a frame that allows same-origin storage.' });+ }+ for (const v of cspViolations) {+ hints.push({ code: 'CSP_BLOCKED', level: 'error',+ message: `The frame's Content-Security-Policy blocked ${v.blocked} (${v.directive}).`,+ action: v.directive.startsWith('connect') || v.directive.startsWith('img')+ ? 'Serve the resource from the frame\'s own origin, or hand the viewer bytes instead of a URL: environmentBytes for the environment map, loadModelBytes() for the model.'+ : 'Load that resource from an origin the frame\'s CSP allows.',+ data: { directive: v.directive, blocked: v.blocked } });+ }+ if (!envStatus.ready && envStatus.source !== 'none') {+ hints.push({ code: envStatus.error ? 'ENVIRONMENT_FAILED' : 'ENVIRONMENT_PENDING', level: 'warning',+ message: envStatus.error ? `Environment map (${envStatus.source}) failed: ${envStatus.error}. PBR materials render without reflections until an environment is ready.`+ : `Environment map (${envStatus.source}) was still loading when the scene became ready.`,+ action: 'Pass environmentBytes (a .env file\'s bytes) or leave environmentUrl unset so the bundled studio map loads from memory.' });+ }+ if (lastModelError) {+ hints.push({ code: 'MODEL_LOAD_FAILED', level: 'error',+ message: `The model did not load: ${lastModelError}`,+ action: 'Check that the URL is reachable from this frame (CSP connect-src, authentication) or pass the bytes with loadModelBytes(bytes, { extension: ".glb" }).' });+ } else if (modelRequested && meshes === 0) {+ hints.push({ code: 'MODEL_EMPTY', level: 'warning',+ message: 'The model loaded but contains no geometry (0 vertices).',+ action: 'Inspect the GLB: it may carry only nodes, or its meshes may be in an unsupported form.' });+ }+ if (overlay === 'visible') {+ hints.push({ code: 'LOADING_OVERLAY_STUCK', level: 'error', message: 'The loading overlay is still shown after the scene reported ready.', action: 'Report this with the console output; the viewer hides the overlay in a finally block.' });+ }+ if (contextLost) {+ hints.push({ code: 'WEBGL_CONTEXT_LOST', level: 'error', message: 'The WebGL context is lost; nothing paints until it is restored.', action: 'Destroy and recreate the viewer, or wait for the browser to restore the context.' });+ }+ const ok = overlay === 'hidden' && !contextLost && !lastModelError && (envStatus.ready || envStatus.source === 'none')+ && cspViolations.length === 0 && (!modelRequested || meshes > 0);+ return {+ ok,+ engine: { webglVersion: engine ? (engine as any).webGLVersion || 0 : 0, contextLost },+ environment: { ...envStatus },+ camera: { ready: !!cam, mode: cam && cam.isOrthographic() ? 'orthographic' : 'perspective' },+ storage,+ loadingOverlay: overlay,+ model: { requested: modelRequested, loaded: modelRequested && !lastModelError && meshes > 0, meshes, vertices, error: lastModelError },+ cspViolations: cspViolations.slice(),+ hints,+ };+ }++ function settleReady(): void {+ if (readyReport) return;+ readyReport = buildReadyReport();+ try { onReady?.(readyReport); } catch (e) { console.error('[adom-3d-viewer] onReady hook threw', e); }+ readyResolve?.(readyReport);+ } let container: HTMLDivElement; let canvas: HTMLCanvasElement;@@ -102,6 +235,7 @@ // No tooltip while dragging/orbiting or while placing an orbit pivot. if (e.buttons !== 0 || pivotChordHeld) { meshTipText = null;+ notifyHoverOut(); return; } const now = performance.now();@@ -109,7 +243,22 @@ lastMeshPick = now; const pick = scene.pick(scene.pointerX, scene.pointerY, (m) => m.isPickable && m.isVisible); if (pick?.hit && pick.pickedMesh && belongsToContent(pick.pickedMesh)) {- const tip = tooltipForMesh(pick.pickedMesh);+ let tip = tooltipForMesh(pick.pickedMesh);+ // Consumer hook (adom/wiki#60 item 5). Runs on the pick the viewer+ // already does, so hovering costs nothing extra. Returning a string+ // overrides the tooltip text, null suppresses it, and undefined (the+ // common case, a listener that only wants to observe) leaves the+ // viewer's own resolution alone. A throwing listener must not take+ // the tooltip loop down with it.+ if (onMeshHover) {+ hoverWasOver = true;+ try {+ const r = onMeshHover(pick.pickedMesh, tip);+ if (r !== undefined) tip = r;+ } catch (e) {+ console.warn('[viewer] onMeshHover threw', e);+ }+ } if (tip) { const rect = container.getBoundingClientRect(); meshTipText = tip;@@ -118,65 +267,175 @@ meshTipFlip = meshTipX > rect.width - 220; return; }+ // A content mesh with no tooltip text is still a hover: the+ // consumer was already told about it above, so do not fire out.+ meshTipText = null;+ return; } meshTipText = null;+ notifyHoverOut(); } function onPointerLeaveCanvas(): void { meshTipText = null;+ notifyHoverOut();+ }++ // Fire the consumer hook once when the pointer stops being over a content+ // mesh. Edge-triggered, not per-frame: a highlight should clear once, and+ // a listener should not be called 60 times a second while hovering nothing.+ let hoverWasOver = false;+ function notifyHoverOut(): void {+ if (!hoverWasOver) return;+ hoverWasOver = false;+ if (!onMeshHover) return;+ try { onMeshHover(null, null); } catch (e) { console.warn('[viewer] onMeshHover threw', e); } } - // Layers toolbar (#48): GLBs whose meshes/groups follow the naming- // convention (docs/CONTENT-CONVENTIONS.md) get a slide-out panel with- // per-layer visibility toggles. Solder layers start hidden; everything- // else starts visible. Detection happens after each loadModel.- const LAYER_ORDER = [- 'fr4_board', 'pad_top', 'pad_bottom', 'solder_top', 'solder_bottom',- 'paste_top', 'paste_bottom', 'silk', 'silk_top', 'silk_bottom',- 'barrel', 'pin1_marker',+ // Layers: a GLB whose nodes declare layers gets a slide-out panel with+ // per-layer visibility toggles.+ //+ // A layer comes from one of two places, in this order:+ // 1. `extras.adomLayer = { key, label?, group?, hidden? }` on the node or+ // an ancestor, read the same way extras.tooltip already is.+ // 2. The built-in vocabulary below, matched against node names.+ //+ // The built-in vocabulary is DATA, in exactly the shape a GLB can declare+ // for itself. It is not a second code path. The viewer is a generic 3D+ // engine and should not know what a solder mask is; this table is here so+ // the existing PCB pipeline keeps working, and anything else can describe+ // its own layers without the engine learning a new domain.+ const BUILTIN_LAYERS: LayerSpec[] = [+ { key: 'fr4_board', label: 'FR4 board', group: 'Board' },+ { key: 'pad_top', label: 'Pads (top)', group: 'Copper' },+ { key: 'pad_bottom', label: 'Pads (bottom)', group: 'Copper' },+ { key: 'solder_top', label: 'Solder (top)', group: 'Process', hidden: true },+ { key: 'solder_bottom', label: 'Solder (bottom)', group: 'Process', hidden: true },+ { key: 'paste_top', label: 'Paste (top)', group: 'Process', hidden: true },+ { key: 'paste_bottom', label: 'Paste (bottom)', group: 'Process', hidden: true },+ { key: 'silk', label: 'Silkscreen', group: 'Markings' },+ { key: 'silk_top', label: 'Silkscreen (top)', group: 'Markings' },+ { key: 'silk_bottom', label: 'Silkscreen (bottom)', group: 'Markings' },+ { key: 'barrel', label: 'Plated barrel', group: 'Board' },+ { key: 'pin1_marker', label: 'Pin 1', group: 'Markings' }, ];- const LAYERS_DEFAULT_OFF = new Set(['solder_top', 'solder_bottom', 'paste_top', 'paste_bottom']);- let layers: { name: string; label: string; visible: boolean; meshes: AbstractMesh[] }[] = [];+ const BUILTIN_BY_KEY = new Map(BUILTIN_LAYERS.map(l => [l.key, l]));++ let layers: DetectedLayer[] = []; let layersPanelOpen = false; - function layerNameFor(node: any): string | null {- const n = (node.name || '').toLowerCase();- for (const key of LAYER_ORDER) {- if (n === key || n.startsWith(key + '_') || n.startsWith(key + '.')) return key;+ /** A declared layer, from glTF extras or the built-in vocabulary. */+ type LayerSpec = { key: string; label?: string; group?: string; hidden?: boolean };+ type DetectedLayer = {+ name: string; label: string; group: string | null;+ visible: boolean; meshes: AbstractMesh[]; declared: boolean;+ };++ /** Sanitize a declared spec: content is untrusted and ends up in the DOM. */+ function normalizeSpec(raw: any): LayerSpec | null {+ if (!raw || typeof raw !== 'object') return null;+ const key = typeof raw.key === 'string' ? raw.key.trim() : '';+ if (!key || key.length > 64) return null;+ const label = typeof raw.label === 'string' && raw.label.trim() ? raw.label.trim().slice(0, 64) : undefined;+ const group = typeof raw.group === 'string' && raw.group.trim() ? raw.group.trim().slice(0, 64) : undefined;+ return { key: key.slice(0, 64), label, group, hidden: raw.hidden === true };+ }++ /**+ * The layer a node belongs to, or null: the NEAREST declaration wins,+ * walking self then ancestors, checking extras before the name at each+ * level. Nearest-wins is what makes "declare on the group" (the doc's+ * advice) compose with finer declarations underneath it: an ancestor's+ * layer covers its subtree only where a descendant does not declare its+ * own. The old top-down grouping instead let the first matched ancestor+ * SWALLOW the whole subtree, so a model with a declared group node hid+ * every declaration below it (adom/wiki#162).+ */+ function layerSpecFor(node: any): LayerSpec | null {+ // extras may sit on the node or an ancestor: Babylon splits+ // multi-material primitives into child meshes, so the group that+ // carries the declaration is often the parent.+ let n: any = node;+ for (let depth = 0; n && depth < 6; depth++) {+ const spec = normalizeSpec(n.metadata?.gltf?.extras?.adomLayer);+ if (spec) return spec;+ const lower = (n.name || '').toLowerCase();+ for (const s of BUILTIN_LAYERS) {+ if (lower === s.key || lower.startsWith(s.key + '_') || lower.startsWith(s.key + '.')) return s;+ }+ if (n.name === '__root__') break;+ n = n.parent; } return null; } function detectLayers(): void {- const found = new Map<string, AbstractMesh[]>();+ const found = new Map<string, { spec: LayerSpec; meshes: AbstractMesh[]; seen: number }>();+ let seq = 0;+ // Per MESH, bottom-up: every mesh joins the layer of its nearest+ // declaring node (itself or an ancestor). No subtree short-circuit,+ // so sibling and nested declarations all surface. for (const root of loadedRootNodes) { const visit = (node: any) => {- const layer = layerNameFor(node);- if (layer) {- const meshes: AbstractMesh[] = [];- if (node.getTotalVertices?.() > 0) meshes.push(node);- if (node.getChildMeshes) meshes.push(...node.getChildMeshes(false).filter((m: AbstractMesh) => m.getTotalVertices && m.getTotalVertices() > 0));- if (meshes.length) {- found.set(layer, [...(found.get(layer) || []), ...meshes]);- return; // children are covered by this layer+ if (node.getTotalVertices?.() > 0) {+ const spec = layerSpecFor(node);+ if (spec) {+ const prev = found.get(spec.key);+ if (prev) prev.meshes.push(node);+ else found.set(spec.key, { spec, meshes: [node], seen: seq++ }); } } (node.getChildren?.() || []).forEach(visit); }; visit(root); }- layers = LAYER_ORDER.filter(k => found.has(k)).map(name => {- const visible = !LAYERS_DEFAULT_OFF.has(name);- const meshes = found.get(name)!;- meshes.forEach(m => { m.isVisible = visible; });- return { name, label: LAYER_LABELS[name] || name.replace(/_+/g, ' '), visible, meshes };- });- if (layers.length < 2) layers = [];++ // Order: built-in keys keep the vocabulary's order so PCB pages are+ // unchanged; declared layers follow, in the order they appear in the+ // file, which is the only ordering the content actually expresses.+ const rank = (key: string, seen: number) => {+ const i = BUILTIN_LAYERS.findIndex(l => l.key === key);+ return i >= 0 ? i : BUILTIN_LAYERS.length + seen;+ };+ layers = [...found.entries()]+ .sort((a, b) => rank(a[0], a[1].seen) - rank(b[0], b[1].seen))+ .map(([name, { spec, meshes }]) => {+ const visible = spec.hidden !== true;+ meshes.forEach(m => { m.isVisible = visible; });+ return {+ name,+ label: spec.label || LAYER_LABELS[name] || name.replace(/_+/g, ' '),+ group: spec.group || null,+ visible, meshes,+ declared: !BUILTIN_BY_KEY.has(name),+ };+ });+ // A lone NAME-matched layer is suppressed (a model that is entirely+ // "chip" does not deserve a panel), but a DECLARED layer always+ // surfaces: content that stamped extras asked for this, and hiding it+ // also made getLayers() lie during diagnosis (adom/wiki#162).+ if (layers.length < 2 && !layers.some(l => l.declared)) layers = []; if (layers.length === 0) layersPanelOpen = false; } - export function getLayers(): { name: string; label: string; visible: boolean }[] {- return layers.map(l => ({ name: l.name, label: l.label, visible: l.visible }));+ /** Panel sections, preserving layer order. Ungrouped layers come first. */+ function layerGroups(ls: DetectedLayer[]): { group: string | null; items: DetectedLayer[] }[] {+ const out: { group: string | null; items: DetectedLayer[] }[] = [];+ for (const l of ls) {+ const last = out[out.length - 1];+ if (last && last.group === l.group) last.items.push(l);+ else out.push({ group: l.group, items: [l] });+ }+ // A single section adds a heading for nothing.+ return out.length === 1 ? [{ group: null, items: out[0].items }] : out;+ }++ export function getLayers(): { name: string; label: string; group: string | null; visible: boolean; declared: boolean }[] {+ // group and declared are here so a consumer can render its own panel+ // without re-deriving what the engine already worked out. `declared`+ // distinguishes a layer the content asked for from one matched against+ // the built-in vocabulary.+ return layers.map(l => ({ name: l.name, label: l.label, group: l.group, visible: l.visible, declared: l.declared })); } export function setLayerVisible(name: string, visible: boolean): boolean {@@ -200,12 +459,8 @@ let pivotHintVisible = false; let pivotHintTimer: ReturnType<typeof setTimeout> | null = null; - function safeStorageGet(key: string): string | null {- try { return window.localStorage.getItem(key); } catch (e) { return null; }- }- function safeStorageSet(key: string, value: string): void {- try { window.localStorage.setItem(key, value); } catch (e) { /* sandboxed */ }- }+ const safeStorageGet = getPref;+ const safeStorageSet = setPref; function updatePivotChord(e: KeyboardEvent): void { const held = e.shiftKey && e.altKey;@@ -293,8 +548,21 @@ const loadingScreen = new ResizableLoadingScreen(canvas, 'Loading...', '#bfbfbf'); engine.loadingScreen = loadingScreen; engine.displayLoadingUI();+ document.addEventListener('securitypolicyviolation', onCspViolation); - await SceneBuilder.init(engine, { zUp, showViewCube, environmentUrl, viewCubeCallbacks });+ try {+ await SceneBuilder.init(engine, {+ zUp, showViewCube, environmentUrl, environmentBytes, environment, viewCubeCallbacks,+ onEnvironment: (s) => { envStatus = s; envResolve?.(s); },+ });+ } catch (e) {+ // The rig failed: report instead of leaving the overlay up forever.+ lastModelError = null;+ envStatus = { source: envStatus.source, ready: false, error: 'scene setup failed: ' + (e instanceof Error ? e.message : String(e)) };+ engine.hideLoadingUI();+ settleReady();+ return;+ } scene.executeWhenReady(async () => { engine.runRenderLoop(() => scene.render());@@ -307,10 +575,27 @@ isOrtho = cam.isOrthographic(); } - if (modelUrl) {- await loadModel(modelUrl);+ // The overlay comes down whatever happens to the model: a throw+ // here used to skip hideLoadingUI and leave the frame showing+ // "Loading..." over a rendered scene with no error anywhere.+ try {+ if (modelUrl) {+ modelRequested = true;+ await loadModel(modelUrl);+ }+ } catch (e) {+ lastModelError = e instanceof Error ? e.message : String(e);+ console.error('[adom-3d-viewer] model load failed', e);+ } finally {+ engine.hideLoadingUI(); }- engine.hideLoadingUI();+ // Give the environment map a bounded moment to settle so the+ // report says ready/failed rather than pending in the common case.+ await Promise.race([envSettled, new Promise((r) => setTimeout(r, 4000))]);+ // One rendered frame after the overlay is gone, so a screenshot+ // taken on ready shows the scene.+ scene.render();+ settleReady(); canvas.addEventListener('dblclick', onDoubleClick); canvas.addEventListener('pointermove', onPointerMoveTooltip);@@ -337,7 +622,6 @@ export async function loadModel(url: string): Promise<void> { const scene = AdomStatics.scene; if (!scene) return;- const shadowGenerator = AdomStatics.shadowGenerator; const lastSlash = url.lastIndexOf('/'); const rootUrl = lastSlash >= 0 ? url.substring(0, lastSlash + 1) : '';@@ -353,7 +637,41 @@ pluginExt = '.glb'; } - const result = await SceneLoader.ImportMeshAsync('', rootUrl, sceneFilename, scene, undefined, pluginExt);+ modelRequested = true;+ let result;+ try {+ result = await SceneLoader.ImportMeshAsync('', rootUrl, sceneFilename, scene, undefined, pluginExt);+ } catch (e) {+ lastModelError = e instanceof Error ? e.message : String(e);+ throw e;+ }+ lastModelError = null;+ attachLoadedModel(result);+ }++ /**+ * Load a model from bytes already in hand (a verified transfer, a+ * private-page fetch done by the host page, a generated GLB). Nothing+ * is fetched, so the frame's CSP never sees a URL.+ */+ export async function loadModelBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<void> {+ const scene = AdomStatics.scene;+ if (!scene) return;+ modelRequested = true;+ const ext = (options && options.extension) || '.glb';+ let result;+ try {+ result = await SceneLoader.ImportMeshAsync('', '', bytes, scene, undefined, ext);+ } catch (e) {+ lastModelError = e instanceof Error ? e.message : String(e);+ throw e;+ }+ lastModelError = null;+ attachLoadedModel(result);+ }++ function attachLoadedModel(result: { meshes: AbstractMesh[] }): void {+ const shadowGenerator = AdomStatics.shadowGenerator; maybeShowPivotHint(); // EXT_mesh_gpu_instancing (gltf-transform optimize's default) loads as@@ -480,6 +798,47 @@ return AdomStatics.shadowGenerator; } + /**+ * Pin the shadow map refresh rate, or pass null to restore automatic+ * behaviour (adom/wiki#60 item 7). Setting refreshRate straight on the+ * shadow map does not survive, because refreshShadows() runs on every+ * load, frame and layer toggle and reasserts its own choice. Auto only+ * looks at scene.animationGroups, so content a consumer animates from+ * outside the viewer needs this.+ *+ * v.setShadowRefreshRate(v.BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME)+ */+ export function setShadowRefreshRate(rate: number | null): void {+ AdomStatics.shadowRefreshRateOverride = rate;+ AdomStatics.refreshShadows();+ }++ /**+ * PNG data URL of the current view (adom/wiki#60 item 9).+ *+ * Renders through an offscreen target rather than reading the canvas, so+ * the result is independent of on-screen size and of whether the backbuffer+ * still holds the last frame. Omit width/height to capture at the canvas's+ * own resolution.+ */+ export async function captureScreenshot(options?: { width?: number; height?: number }): Promise<string> {+ const engine = AdomStatics.engine;+ const camera = AdomStatics.camera;+ if (!engine || !camera) throw new Error('viewer is not initialized');+ const w = options?.width || engine.getRenderWidth();+ const h = options?.height || engine.getRenderHeight();+ const { Tools } = await import('@babylonjs/core/Misc/tools');+ return await new Promise<string>((resolve, reject) => {+ try {+ Tools.CreateScreenshotUsingRenderTarget(+ engine as any, camera as any, { width: w, height: h },+ (data: string) => resolve(data),+ 'image/png', undefined, true,+ );+ } catch (e) { reject(e); }+ });+ }+ /** * Register a root (e.g. parent of spheres) so it is included in frameModel() and optional shadow setup. * Does not dispose the node on clearScene(); remove with removeContentRoot or dispose yourself.@@ -769,6 +1128,20 @@ ); } spotLight.direction = center.subtract(spotLight.position).normalize();+ // Shadow bias must track model scale like everything else in this+ // block: SceneBuilder's init values (bias 2e-7 normalized,+ // normalBias 8e-5 world units) are chip-scale — on a machine-sized+ // model they round to zero and PCF self-shadowing paints acne+ // blotches across large light surfaces (essemtec-puma's white+ // hood). bias is normalized to [shadowMinZ, shadowMaxZ] which is+ // already model-scaled below, so a modest constant works at every+ // size; normalBias is in WORLD units so it must scale with the+ // model diagonal.+ const shadowGenerator = AdomStatics.shadowGenerator;+ if (shadowGenerator) {+ shadowGenerator.bias = 0.0008;+ shadowGenerator.normalBias = modelSize * 0.004;+ } // Scale intensity with the square of distance (inverse-square falloff). // Hydrogen reference: 2M intensity at height 625 for ~200-unit models. const hydrogenRef = 625;@@ -816,6 +1189,17 @@ } else { groundMesh.position = new Vector3(center.x, worldMin.y, center.z); }+ // Consumer restyle point. The ground's GEOMETRY belongs to the+ // viewer, because it has to track content bounds and the zUp+ // convention, which is why it is rebuilt on every reframe rather+ // than toggled. Its APPEARANCE does not: that is a look, and looks+ // belong to whoever is embedding this. The callback fires after+ // every rebuild, so restyling here is durable in a way that+ // mutating the material from outside is not.+ if (onGroundCreated) {+ try { onGroundCreated(groundMesh); }+ catch (e) { console.warn('[viewer] onGroundCreated threw', e); }+ } } else if (groundMesh) { groundMesh.dispose(); groundMesh = null;@@ -895,6 +1279,7 @@ }); onDestroy(() => {+ document.removeEventListener('securitypolicyviolation', onCspViolation); canvas?.removeEventListener('dblclick', onDoubleClick); canvas?.removeEventListener('pointermove', onPointerMoveTooltip); canvas?.removeEventListener('pointerleave', onPointerLeaveCanvas);@@ -939,15 +1324,20 @@ </button> {#if layersPanelOpen} <div class="layers-panel">- {#each layers as layer (layer.name)}- <label class="layers-row">- <input- type="checkbox"- checked={layer.visible}- on:change={() => toggleLayerRow(layer.name)}- />- <span>{layer.label}</span>- </label>+ {#each layerGroups(layers) as section (section.group ?? '_')}+ {#if section.group}+ <div class="layers-group">{section.group}</div>+ {/if}+ {#each section.items as layer (layer.name)}+ <label class="layers-row">+ <input+ type="checkbox"+ checked={layer.visible}+ on:change={() => toggleLayerRow(layer.name)}+ />+ <span>{layer.label}</span>+ </label>+ {/each} {/each} </div> {/if}@@ -1066,6 +1456,15 @@ from { opacity: 0; transform: translateX(-8px); } to { opacity: 1; transform: translateX(0); } }+ .layers-group {+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ opacity: 0.55;+ padding: 6px 8px 2px;+ }+ .layers-group:first-child { padding-top: 2px; }+ .layers-row { display: flex; align-items: center;
src/lib/adom-babylon/3DViewer/SceneBuilder.ts+62−10@@ -13,13 +13,38 @@ import { AdomStatics } from '../AdomStatics'; import { STUDIO_ENV_BASE64 } from '../assets/studioEnv'; import { initAxisHelpers } from './AxisHelpers'; +export type EnvironmentSource = 'url' | 'injected-bytes' | 'bundled-studio' | 'none';++export interface EnvironmentStatus {+ source: EnvironmentSource;+ ready: boolean;+ error: string | null;+}+ export interface SceneBuilderOptions { zUp: boolean; showViewCube: boolean; environmentUrl?: string;+ /** The bytes of a Babylon .env file, used instead of a URL fetch or the+ * bundled studio map. Loads from memory: no blob URL, no network, so it+ * works under a CSP whose connect-src has no blob: or https: entry. */+ environmentBytes?: ArrayBufferView;+ /** 'none' skips the environment map entirely (PBR reflections fall back+ * to flat lighting; the gradient background is unaffected). */+ environment?: 'studio' | 'none';+ /** Fires when the environment map is ready or failed. */+ onEnvironment?: (status: EnvironmentStatus) => void; viewCubeCallbacks?: ViewCubeUICallbacks; } +/** Decode the bundled studio .env into bytes (a base64 data URL). */+export function studioEnvironmentBytes(): Uint8Array {+ const raw = atob(STUDIO_ENV_BASE64.split(',')[1]);+ const bytes = new Uint8Array(raw.length);+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);+ return bytes;+}+ export class SceneBuilder { static init(engine: Engine, options: SceneBuilderOptions = { zUp: true, showViewCube: true }): Promise<void> { if (!AdomStatics.scene) {@@ -27,7 +52,7 @@ export class SceneBuilder { return Promise.reject(new Error("Scene is undefined in AdomStatics.")); } const scene = AdomStatics.scene;- const { zUp, showViewCube, environmentUrl, viewCubeCallbacks } = options;+ const { zUp, showViewCube, environmentUrl, environmentBytes, environment, onEnvironment, viewCubeCallbacks } = options; return new Promise<void>((resolve, reject) => { try {@@ -87,17 +112,44 @@ export class SceneBuilder { AdomStatics.enforceShadowFilterCompat(); }); - // Studio environment map for PBR reflections + skybox.- // Bundled as base64 so consumers don't need to copy assets.- // environmentUrl prop lets them override with their own .env file.- if (environmentUrl) {+ // Studio environment map for PBR reflections. Bundled as+ // base64 so consumers don't need to copy assets; loaded from+ // MEMORY (Babylon's buffer option), never through a blob URL.+ // The wiki's sandboxed frames run under connect-src 'self'+ // data:, which blocks blob: fetches, and a failed environment+ // texture leaves every PBR material waiting: the chip never+ // paints (adom/adom-3d-viewer#5). environmentUrl still fetches+ // a caller's own .env; environmentBytes injects one; 'none'+ // skips the map.+ const report = (status: EnvironmentStatus) => { try { onEnvironment?.(status); } catch { /* consumer hook */ } };+ const fromBytes = (bytes: ArrayBufferView, source: EnvironmentSource) => {+ scene.environmentTexture = new CubeTexture('adom-studio.env', scene, {+ buffer: bytes,+ prefiltered: true,+ forcedExtension: '.env',+ onLoad: () => report({ source, ready: true, error: null }),+ onError: (message?: string) => report({ source, ready: false, error: message || 'environment map failed to load' }),+ });+ };+ if (environment === 'none') {+ scene.environmentTexture = null;+ report({ source: 'none', ready: true, error: null });+ } else if (environmentBytes) {+ fromBytes(environmentBytes, 'injected-bytes');+ } else if (environmentUrl) { scene.environmentTexture = CubeTexture.CreateFromPrefilteredData(environmentUrl, scene);+ const tex = scene.environmentTexture as CubeTexture;+ tex.onLoadObservable.addOnce(() => report({ source: 'url', ready: true, error: null }));+ // A URL the frame's CSP blocks fails silently at the+ // engine level (status 0). Fall back to the bundled studio+ // map so the model still paints, and say so.+ const internal = tex.getInternalTexture();+ internal?.onErrorObservable.addOnce((e: any) => {+ report({ source: 'url', ready: false, error: (e && e.message) || 'environmentUrl failed to load; using the bundled studio map' });+ fromBytes(studioEnvironmentBytes(), 'bundled-studio');+ }); } else {- const raw = atob(STUDIO_ENV_BASE64.split(',')[1]);- const bytes = new Uint8Array(raw.length);- for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);- const blobUrl = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));- scene.environmentTexture = new CubeTexture(blobUrl, scene, null, false, null, null, null, undefined, true, '.env');+ fromBytes(studioEnvironmentBytes(), 'bundled-studio'); } // 3d-viewer-design skill §3b — neutral steel-blue gradient.
src/lib/adom-babylon/3DViewer/ViewCubeBuilder.ts+40−8@@ -24,6 +24,8 @@ export interface ViewCubeUICallbacks { } export class ViewCubeBuilder {+ // One-shot log guard: a per-frame error must not spam the console (#79).+ private static _frameErrorLogged = false private static prevPick: number = -1 private static prevDarkened: number = -1 private static particleColorMap: Map<number, Color4> = new Map()@@ -210,6 +212,25 @@ export class ViewCubeBuilder { let buttonsAlpha = 0 mainScene.afterRender = () => {+ // adom/wiki#79: the cube used to vanish permanently, with no way back+ // short of a reload. scene2.render() is the LAST statement of this+ // handler, so ANY throw above it (hover/tooltip math, a texture swap,+ // pick state left inconsistent by a pointer that dragged off the+ // canvas) silently skipped the cube's render, every frame, forever.+ // The cube's chrome must never be able to take down the cube: run the+ // body defensively and render regardless.+ try {+ cubeFrameBody()+ } catch (e) {+ if (!ViewCubeBuilder._frameErrorLogged) {+ ViewCubeBuilder._frameErrorLogged = true+ console.warn("[view-cube] frame handler error (cube still renders):", e)+ }+ }+ try { scene2.render() } catch (e) { /* a dead cube must not kill the main scene */ }+ }++ const cubeFrameBody = () => { // The cube scene is right-handed (scene2.useRightHandedSystem). // When the MAIN scene is left-handed (zUp=false) the camera azimuth // has the opposite sense, so copying mainCamera.alpha verbatim makes@@ -343,7 +364,6 @@ export class ViewCubeBuilder { : (isOrtho ? vmOrthoNormal : vmPerspNormal) } - scene2.render() } const cr = 2 // Cube radius@@ -543,7 +563,8 @@ export class ViewCubeBuilder { return scene2 function cubeRayCollision(pickResult: PickingInfo) {- if (pickResult.faceId === -1) return+ if (!pickResult || pickResult.faceId === -1) return+ if (!pickResult.pickedPoint || !pickResult.ray) return const picked = sps.pickedParticle(pickResult) if (!picked) return@@ -554,17 +575,27 @@ export class ViewCubeBuilder { //where ray will pass through the box, but the other meshes are in the way let id = picked.idx let result = pickResult- while (id < 3 || 29 < id) {+ // Bounded: a pick that keeps missing (pointer dragged off the cube or+ // outside the canvas) must not spin, and a null pick must not throw+ // through the caller and leave highlight state inconsistent (#79).+ let guard = 0+ while ((id < 3 || 29 < id) && guard++ < 16) {+ if (!result.pickedPoint || !result.ray) return const ray = new Ray(- result.pickedPoint!.add(- result.ray!.direction.multiplyByFloats(0.001, 0.001, 0.001)+ result.pickedPoint.add(+ result.ray.direction.multiplyByFloats(0.001, 0.001, 0.001) ),- result.ray!.direction,+ result.ray.direction, 10 )- result = scene2.pickWithRay(ray)!- id = sps.pickedParticle(result)!.idx+ const next = scene2.pickWithRay(ray)+ if (!next) return+ const nextParticle = sps.pickedParticle(next)+ if (!nextParticle) return+ result = next+ id = nextParticle.idx }+ if (id < 3 || 29 < id) return return id }@@ -649,6 +680,7 @@ export class ViewCubeBuilder { } function highlightFromPointer(xOffset: number, yOffset: number, pickResult: PickingInfo) {+ if (!pickResult) return //Only ray-cast if pointer is in the viewcube viewport. //Uncomment other conditions if the viewcube is moved from the top right corner. const targetColor = new Color4(0.8, 0.8, 1, 0.3)
src/lib/adom-babylon/AdomStatics.ts+39−1@@ -31,7 +31,27 @@ export class AdomStatics { return; } - this.engine = new Engine(canvas, true, { useHighPrecisionFloats: true });+ // preserveDrawingBuffer + stencil: without them the backbuffer is+ // undefined after the frame is presented, so canvas.toDataURL() and+ // any consumer-side capture return a blank image (adom/wiki#60 item+ // 9). Babylon's own CreateScreenshotUsingRenderTarget re-renders into+ // an RTT and does not need this, but consumers reaching for the canvas+ // directly do, and the cost is one retained buffer.+ this.engine = new Engine(canvas, true, {+ useHighPrecisionFloats: true,+ preserveDrawingBuffer: true,+ stencil: true,+ });+ // Decode images (environment mip levels, GLB-embedded textures) as+ // ImageBitmaps instead of <img src="blob:...">. Babylon's default on+ // WebGL builds a blob URL per image, and a sandboxed frame whose CSP+ // has no blob: in img-src (the wiki's widget and readme frames)+ // blocks every one of them: the environment never uploads and the+ // materials wait forever (adom/adom-3d-viewer#5). createImageBitmap+ // takes the Blob directly; no URL, no fetch, nothing for a CSP to see.+ if (typeof createImageBitmap === 'function') {+ (this.engine as any)._features.forceBitmapOverHTMLImageElement = true;+ } this.scene = new Scene(this.engine); this.scene.useRightHandedSystem = zUp; @@ -102,6 +122,19 @@ export class AdomStatics { } } + /**+ * Consumer override for the shadow map refresh rate (adom/wiki#60 item 7).+ *+ * null means "auto": every frame for animated content, once for static.+ * Set a RenderTargetTexture.REFRESHRATE_* value to pin it. Without this an+ * external caller who set refreshRate through getShadowGenerator() had it+ * silently reverted by the next refreshShadows(), which fires on every+ * load, frame and layer toggle. Content driven from OUTSIDE the viewer+ * (a consumer animating an added content root) has no animationGroups on+ * the scene, so auto-detection cannot see it and guesses wrong.+ */+ public static shadowRefreshRateOverride: number | null = null;+ public static refreshShadows(): void { if (!this.shadowGenerator || !this.scene) return; const sg = this.shadowGenerator;@@ -110,6 +143,11 @@ export class AdomStatics { this.enforceShadowFilterCompat(); + if (this.shadowRefreshRateOverride !== null) {+ shadowMap.refreshRate = this.shadowRefreshRateOverride;+ return;+ }+ // Animated models (glTF animationGroups, e.g. a press-fit insertion or a // spin) need the shadow map re-rendered EVERY frame so the cast shadows // track the moving meshes. A one-shot render freezes the shadow at frame 0,
src/lib/adom-babylon/Camera/AdomCamera.ts+7−11@@ -1,4 +1,5 @@ import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';+import { getPref } from '../util/prefs'; import { Vector3 } from '@babylonjs/core/Maths/math.vector'; import { Scene } from '@babylonjs/core/scene'; import { KeyboardEventTypes, PointerEventTypes, type IKeyboardEvent } from '@babylonjs/core/Events';@@ -186,17 +187,12 @@ export class AdomCamera extends ArcRotateCamera{ this.beta = Math.PI / 4; this.zoomToMouseLocation = true; - // Load camera mode from localStorage, default to perspective.- // Guarded: a sandboxed iframe without allow-same-origin throws- // SecurityError on ANY storage access (even a read), and an- // exception here silently kills the whole scene rig (lights, env,- // ViewCube). Sandboxed embeds just get the default mode.- let savedMode: string | null = null;- try {- savedMode = typeof window !== 'undefined' ? window.localStorage.getItem('adom_camera_mode') : null;- } catch (e) {- savedMode = null;- }+ // Load camera mode from the viewer preferences, default to+ // perspective. A sandboxed iframe without allow-same-origin throws+ // SecurityError on ANY storage access (even a read), and an exception+ // here would silently kill the whole scene rig (lights, env, ViewCube);+ // the prefs module falls back to document-local memory there.+ const savedMode: string | null = getPref('adom_camera_mode'); if (savedMode === 'orthographic') { this.mode = ArcRotateCamera.ORTHOGRAPHIC_CAMERA; this.wasOrthoMode = true; // Initialize tracking flag
src/lib/adom-babylon/util/prefs.tsadded+47@@ -0,0 +1,47 @@+/**+ * Viewer preferences with a safe fallback. A sandboxed frame without+ * allow-same-origin (the wiki's widget and readme frames) throws a+ * SecurityError on ANY window.localStorage access, even a read. Preferences+ * then live in this document only: the viewer behaves the same, nothing is+ * remembered across loads, and the ready report says so (storage: ephemeral)+ * instead of the caller inferring it from a thrown exception.+ */+const memory = new Map<string, string>();+let backend: 'persistent' | 'ephemeral' | null = null;++function storage(): Storage | null {+ if (backend === 'ephemeral') return null;+ try {+ const s = typeof window !== 'undefined' ? window.localStorage : null;+ if (!s) { backend = 'ephemeral'; return null; }+ // A getter that resolves is not proof it works (private mode, quota+ // 0, denied by policy); a probe write settles it once.+ if (backend === null) {+ const k = '__adom_viewer_probe';+ s.setItem(k, '1');+ s.removeItem(k);+ backend = 'persistent';+ }+ return s;+ } catch {+ backend = 'ephemeral';+ return null;+ }+}++export function prefsBackend(): 'persistent' | 'ephemeral' {+ storage();+ return backend || 'ephemeral';+}++export function getPref(key: string): string | null {+ const s = storage();+ if (s) { try { return s.getItem(key); } catch { /* fall through */ } }+ return memory.has(key) ? memory.get(key)! : null;+}++export function setPref(key: string, value: string): void {+ const s = storage();+ if (s) { try { s.setItem(key, value); return; } catch { /* fall through */ } }+ memory.set(key, value);+}
src/lib/adom-babylon/util/readiness.tsadded+31@@ -0,0 +1,31 @@+import type { EnvironmentStatus } from '../3DViewer/SceneBuilder';++/** An actionable finding in the ready report. */+export interface ViewerHint {+ code: string;+ level: 'info' | 'warning' | 'error';+ message: string;+ action?: string;+ data?: Record<string, unknown>;+}++/**+ * What the viewer knows once its first scene is up (adom/adom-3d-viewer#5).+ * A consumer in a sandboxed frame cannot tell "painted" from "stuck behind+ * the overlay" by counting meshes; this says it outright, with hints that+ * name the fix.+ */+export interface ViewerReadyReport {+ /** True when the scene rendered, the overlay is gone, the environment is+ * ready (or deliberately absent), no CSP violation was recorded and any+ * requested model loaded with geometry. */+ ok: boolean;+ engine: { webglVersion: number; contextLost: boolean };+ environment: EnvironmentStatus;+ camera: { ready: boolean; mode: 'perspective' | 'orthographic' };+ storage: 'persistent' | 'ephemeral';+ loadingOverlay: 'hidden' | 'visible';+ model: { requested: boolean; loaded: boolean; meshes: number; vertices: number; error: string | null };+ cspViolations: { directive: string; blocked: string }[];+ hints: ViewerHint[];+}
standalone.ts+49−1@@ -1,3 +1,4 @@+declare const __VIEWER_VERSION__: string; /** * Standalone entry point for the Adom 3D Viewer. * Bundles Svelte + Babylon.js + the ThreeDViewer component into a single IIFE.@@ -17,6 +18,8 @@ if (typeof (globalThis as any).process === 'undefined') { } import ThreeDViewer from './src/ThreeDViewer.svelte';+import type { ViewerReadyReport } from './src/lib/adom-babylon/util/readiness';+export type { ViewerReadyReport, ViewerHint } from './src/lib/adom-babylon/util/readiness'; // Side-effect: registers the debugLayer getter on Scene. import '@babylonjs/core/Debug/debugLayer';@@ -36,6 +39,12 @@ import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; interface ViewerInstance { loadModel: (url: string) => Promise<void>;+ /** Load a model from bytes already in hand; nothing is fetched. */+ loadModelBytes: (bytes: ArrayBufferView, options?: { extension?: string }) => Promise<void>;+ /** Resolves with the ready report once the first scene is up (never+ * rejects: failures are in the report's hints). */+ whenReady: () => Promise<ViewerReadyReport & { version: string }>;+ getReadyReport: () => (ViewerReadyReport & { version: string }) | null; clearScene: () => void; frameModel: (fillFraction?: number) => void; getScene: () => Scene | null;@@ -59,18 +68,42 @@ interface ViewerInstance { getAxesState: () => { world: boolean; meshLocal: boolean }; /** Layers detected from the naming convention (docs/CONTENT-CONVENTIONS.md); * empty when the loaded GLB has fewer than two named layers. */- getLayers: () => { name: string; label: string; visible: boolean }[];+ /** Layers detected from glTF `extras.adomLayer`, or from the built-in+ * naming vocabulary. `group` sections the panel; `declared` is true when the+ * content asked for the layer rather than matching the built-in names. */+ getLayers: () => { name: string; label: string; group: string | null; visible: boolean; declared: boolean }[]; setLayerVisible: (name: string, visible: boolean) => boolean;+ /** Pin the shadow map refresh rate; null restores auto (adom/wiki#60 #7). */+ setShadowRefreshRate: (rate: number | null) => void;+ /** PNG data URL of the current view (adom/wiki#60 #9). */+ captureScreenshot: (options?: { width?: number; height?: number }) => Promise<string>; destroy: () => void; } +const withVersion = (r: ViewerReadyReport) => ({ ...r, version: __VIEWER_VERSION__ });+ function init(container: HTMLElement, options?: { zUp?: boolean; modelUrl?: string; showViewCube?: boolean; showGround?: boolean; environmentUrl?: string;+ /** Bytes of a Babylon .env file, loaded from memory (no blob URL, no+ * fetch). The bundled studio map already loads this way. */+ environmentBytes?: ArrayBufferView;+ /** 'none' skips the environment map. */+ environment?: 'studio' | 'none';+ /** Called once with the ready report (see whenReady). */+ onReady?: (report: ViewerReadyReport & { version: string }) => void; initialViewMode?: 'perspective' | 'orthographic';+ /** Hover hook (adom/wiki#60 #5). Return a string to override the tooltip,+ * null to suppress it, nothing to leave the viewer's own text alone.+ * Called with (null, null) when the pointer leaves content. */+ onMeshHover?: (mesh: any | null, tip: string | null) => string | null | void;+ /** Called with the ground mesh after each rebuild, for a custom ground look.+ * The ground is sized from content bounds and so is recreated on reframe;+ * this is the reliable place to reapply a style. */+ onGroundCreated?: (ground: any) => void; }): ViewerInstance { const opts = options || {}; @@ -82,12 +115,20 @@ function init(container: HTMLElement, options?: { showViewCube: opts.showViewCube !== undefined ? opts.showViewCube : true, showGround: opts.showGround !== undefined ? opts.showGround : false, environmentUrl: opts.environmentUrl,+ environmentBytes: opts.environmentBytes,+ environment: opts.environment || 'studio',+ onReady: opts.onReady ? (r: ViewerReadyReport) => opts.onReady!(withVersion(r)) : undefined, initialViewMode: opts.initialViewMode || 'perspective',+ onMeshHover: opts.onMeshHover,+ onGroundCreated: opts.onGroundCreated, }, }); return { loadModel: (url: string) => component.loadModel(url),+ loadModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.loadModelBytes(bytes, o),+ whenReady: () => component.whenReady().then(withVersion),+ getReadyReport: () => { const r = component.getReadyReport(); return r ? withVersion(r) : null; }, clearScene: () => component.clearScene(), frameModel: (fillFraction?: number) => component.frameModel(fillFraction), getScene: () => component.getScene(),@@ -107,6 +148,8 @@ function init(container: HTMLElement, options?: { getProjectionMode: () => component.getProjectionMode(), toggleAxes: (target: 'world' | 'mesh-local', enabled?: boolean) => component.toggleAxes(target, enabled), getAxesState: () => component.getAxesState(),+ setShadowRefreshRate: (rate: number | null) => component.setShadowRefreshRate(rate),+ captureScreenshot: (o?: { width?: number; height?: number }) => component.captureScreenshot(o), getLayers: () => component.getLayers(), setLayerVisible: (name: string, visible: boolean) => component.setLayerVisible(name, visible), destroy: () => component.$destroy(),@@ -246,5 +289,10 @@ if (!(window as any).BABYLON) { init, rotateYUpToZUp, addLaserEtch,+ // Runtime-discoverable build identity (adom/wiki#60 item 11). Injected from+ // package.json at build time, so it cannot drift from the published version+ // the way a hand-maintained constant does. A consumer that supports several+ // engine builds can branch on this instead of feature-sniffing.+ version: __VIEWER_VERSION__, BABYLON: BABYLON_CORE, };
svelte.config.mjsadded+5@@ -0,0 +1,5 @@+import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';++export default {+ preprocess: vitePreprocess(),+};
test/wiki-sandbox.test.mjsadded+219@@ -0,0 +1,219 @@+// adom/adom-3d-viewer#5 (John): the viewer must come up inside the wiki's+// sandboxed widget frame. That frame is an OPAQUE origin (sandbox without+// allow-same-origin: every storage access throws) under the wiki's widget+// CSP (connect-src 'self' data:, no blob:), so this test builds exactly that:+// an https server (the CSP allows script-src https: only) that serves the+// built bundle, a tiny GLB and a harness page carrying the wiki CSP header,+// framed with sandbox="allow-scripts" by an outer page. Headless Chrome with+// SwiftShader renders it; the checks are the ones the issue asks for: a+// ready report that says ok, the loading overlay dismissed, the environment+// map ready with no blob URL, ephemeral storage, no CSP violation, painted+// chip pixels in the canvas, then destroy/recreate three times.+//+// Bounded: every wait has a deadline; the whole run is capped at 120 s.+import http from "node:http";+import https from "node:https";+import { execSync } from "node:child_process";+import { existsSync, mkdtempSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve, extname } from "node:path";+import { fileURLToPath } from "node:url";+import { createRequire } from "node:module";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, "dist-standalone");+const require = createRequire(import.meta.url);+const deadline = Date.now() + 120_000;+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 + "]"); }++// The wiki's widget-frame CSP (git-wiki lib/router.js sandboxedHtmlCspParts+// with wasm: true and no registry origin). Read from the sibling checkout+// when present so drift is caught; the literal is the 2026-09-10 value.+const WIKI_CSP_LITERAL = [+ "sandbox allow-scripts allow-downloads allow-popups allow-popups-to-escape-sandbox",+ "default-src 'none'",+ "script-src 'unsafe-inline' 'wasm-unsafe-eval' https:",+ "style-src 'unsafe-inline' https:",+ "img-src data: https:",+ "media-src data: https:",+ "font-src data: https:",+ "frame-src https:",+ "connect-src 'self' data:",+ "form-action 'none'",+ "object-src 'none'",+ "base-uri 'none'",+].join("; ");+let WIKI_CSP = WIKI_CSP_LITERAL;+try {+ const routerPath = resolve(ROOT, "..", "git-wiki", "lib", "router.js");+ if (existsSync(routerPath)) {+ const { sandboxedHtmlCsp } = await import(routerPath);+ WIKI_CSP = sandboxedHtmlCsp([], { wasm: true });+ if (WIKI_CSP !== WIKI_CSP_LITERAL) console.log(" note: the wiki CSP differs from this test's literal; using the wiki's:\n " + WIKI_CSP);+ }+} catch { /* the literal stands */ }++// A minimal GLB: one unit box (24 vertices, 36 indices), so a painted+// scene has real geometry in the middle of the canvas.+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);+ const 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();++// The harness that runs INSIDE the sandboxed frame. It talks to the test+// only through window globals puppeteer reads from the frame's context.+const HARNESS = `<!doctype html><html><head><meta charset="utf-8">+<style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;width:640px;height:400px}</style>+</head><body><div id="wrap"></div>+<script type="module">+ window.__log = [];+ window.__viol = [];+ document.addEventListener('securitypolicyviolation', e => window.__viol.push((e.effectiveDirective || '?') + ' ' + (e.blockedURI || '?')));+ const orig = console.error; console.error = (...a) => { window.__log.push(a.map(String).join(' ')); orig(...a); };+ let storageThrows = false; try { window.localStorage.getItem('x'); } catch (e) { storageThrows = true; }+ window.__storageThrows = storageThrows;+ await import('/adom-3d-viewer-babylon9.esm.js');+ window.__runs = [];+ window.__create = async function(useBytes) {+ const wrap = document.getElementById('wrap');+ const opts = { zUp: true, showViewCube: true, showGround: false };+ if (!useBytes) opts.modelUrl = '/chip.glb';+ const v = window.Adom3DViewerBabylon9.init(wrap, opts);+ if (useBytes) { const bytes = new Uint8Array(await (await fetch('/chip.glb')).arrayBuffer()); await v.whenReady(); await v.loadModelBytes(bytes, { extension: '.glb' }); }+ const report = await v.whenReady();+ // paint check: sample the canvas centre for pixels that are neither the+ // gradient background nor black+ const canvas = wrap.querySelector('canvas');+ let painted = 0, total = 0;+ try {+ const url = await v.captureScreenshot({ width: 320, height: 200 });+ const img = new Image(); await new Promise((r, j) => { img.onload = r; img.onerror = j; img.src = url; });+ const c = document.createElement('canvas'); c.width = 320; c.height = 200; const ctx = c.getContext('2d'); ctx.drawImage(img, 0, 0);+ const d = ctx.getImageData(100, 60, 120, 80).data;+ for (let i = 0; i < d.length; i += 4) { total++; const r = d[i], g = d[i+1], b = d[i+2]; if (r > 120 && g > 60 && b < 90) painted++; }+ } catch (e) { window.__log.push('paint check failed: ' + e); }+ const overlay = !!wrap.querySelector('#babylonjsLoadingDiv');+ const out = { report, painted, total, overlay, hasCanvas: !!canvas };+ window.__runs.push(out);+ window.__viewer = v;+ return out;+ };+ window.__destroy = function() { try { window.__viewer.destroy(); } catch (e) { window.__log.push('destroy threw: ' + e); } window.__viewer = null; document.getElementById('wrap').innerHTML = ''; };+ window.__harnessReady = true;+</script></body></html>`;++const OUTER = (port) => `<!doctype html><html><body style="margin:0"><iframe id="f" sandbox="allow-scripts" src="https://localhost:${port}/harness.html" style="width:660px;height:420px;border:0"></iframe></body></html>`;++// self-signed cert for the https origin the CSP requires+const certDir = mkdtempSync(join(tmpdir(), "viewer-sandbox-"));+execSync(`openssl req -x509 -newkey rsa:2048 -nodes -keyout ${certDir}/key.pem -out ${certDir}/cert.pem -days 2 -subj "/CN=localhost" 2>/dev/null`);+const MIME = { ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".wasm": "application/wasm", ".glb": "model/gltf-binary", ".html": "text/html; charset=utf-8" };+let port = 0;+const server = https.createServer({ key: readFileSync(join(certDir, "key.pem")), cert: readFileSync(join(certDir, "cert.pem")) }, (req, res) => {+ const url = new URL(req.url, "https://localhost");+ if (url.pathname === "/harness.html") { res.writeHead(200, { "Content-Type": MIME[".html"], "Content-Security-Policy": WIKI_CSP, "Cache-Control": "no-store" }); return res.end(HARNESS); }+ if (url.pathname === "/outer.html") { res.writeHead(200, { "Content-Type": MIME[".html"] }); return res.end(OUTER(port)); }+ // An opaque origin fetches module scripts in CORS mode: the wiki's static+ // route answers with Access-Control-Allow-Origin: *, so this server does too.+ if (url.pathname === "/chip.glb") { res.writeHead(200, { "Content-Type": MIME[".glb"], "Access-Control-Allow-Origin": "*" }); return res.end(GLB); }+ const file = join(DIST, url.pathname.replace(/^\/+/, ""));+ if (!file.startsWith(DIST) || !existsSync(file)) { res.writeHead(404); return res.end("nope"); }+ res.writeHead(200, { "Content-Type": MIME[extname(file)] || "application/octet-stream", "X-Content-Type-Options": "nosniff", "Access-Control-Allow-Origin": "*" });+ res.end(readFileSync(file));+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+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 readdirSyncSafe(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+ for (const p of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) if (existsSync(p)) return p;+ throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+function readdirSyncSafe(d) { try { return require("node:fs").readdirSync(d); } catch { return []; } }+const browser = await puppeteer.launch({+ executablePath: findChrome(), headless: true,+ args: ["--no-sandbox", "--ignore-certificate-errors", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"],+});+try {+ section("the bundle boots in an opaque-origin frame under the wiki CSP");+ const page = await browser.newPage();+ const pageErrors = [];+ page.on("pageerror", e => pageErrors.push(String(e && e.message || e)));+ await page.goto(`https://localhost:${port}/outer.html`, { waitUntil: "load" });+ const frame = page.frames().find(f => f.url().includes("/harness.html"));+ assert(frame, "the sandboxed harness frame exists");+ await frame.waitForFunction("window.__harnessReady === true", { timeout: 30_000 });+ assert(await frame.evaluate(() => window.__storageThrows), "the frame really is opaque-origin: localStorage throws");+ assert(await frame.evaluate(() => typeof window.Adom3DViewerBabylon9 === "object" && typeof window.Adom3DViewerBabylon9.init === "function"), "bundle loaded (script-src https: satisfied)");+ const version = await frame.evaluate(() => window.Adom3DViewerBabylon9.version);+ assert(version === readFileSync(join(ROOT, "VERSION"), "utf8").trim(), `runtime version matches VERSION (${version})`);++ section("first viewer: ready report, overlay down, environment from memory, painted chip");+ const r1 = await frame.evaluate(() => window.__create(false));+ const rep = r1.report;+ assert(rep && rep.ok === true, `report.ok (${JSON.stringify(rep && rep.hints)})`);+ assert(rep.environment.source === "bundled-studio" && rep.environment.ready === true, `environment ready from the bundled bytes (${JSON.stringify(rep.environment)})`);+ assert(rep.storage === "ephemeral", "storage reported ephemeral");+ assert(rep.hints.some(h => h.code === "STORAGE_EPHEMERAL"), "the ephemeral storage hint names it");+ assert(rep.loadingOverlay === "hidden" && r1.overlay === false, "loading overlay dismissed");+ assert(rep.model.loaded && rep.model.meshes >= 1 && rep.model.vertices === 24, `model loaded (${rep.model.meshes} mesh, ${rep.model.vertices} vertices)`);+ assert(rep.cspViolations.length === 0, `no CSP violation recorded by the viewer (${JSON.stringify(rep.cspViolations)})`);+ const viol = await frame.evaluate(() => window.__viol);+ assert(viol.length === 0, `no securitypolicyviolation in the frame (${viol.join(" | ")})`);+ assert(rep.camera.ready && rep.camera.mode === "perspective", "camera ready in perspective");+ assert(r1.hasCanvas, "a canvas is in the frame");+ assert(r1.painted > r1.total * 0.05, `chip pixels painted in the centre (${r1.painted}/${r1.total})`);+ const errs = await frame.evaluate(() => window.__log);+ assert(!errs.some(l => /SecurityError|blob:|Refused to/.test(l)), `no storage/blob/CSP errors logged (${errs.slice(0, 3).join(" | ")})`);++ section("destroy and recreate, three times, alternating URL and bytes transport");+ for (let i = 0; i < 3; i++) {+ await frame.evaluate(() => window.__destroy());+ const gone = await frame.evaluate(() => !document.querySelector("#wrap canvas") && !document.querySelector("#babylonjsLoadingDiv"));+ assert(gone, `run ${i + 1}: destroy removed the canvas and any overlay`);+ const r = await frame.evaluate((useBytes) => window.__create(useBytes), i % 2 === 0);+ assert(r.report.ok === true, `run ${i + 1}: report.ok (${JSON.stringify(r.report.hints)})`);+ assert(r.report.model.loaded && r.report.model.vertices === 24, `run ${i + 1}: model loaded via ${i % 2 === 0 ? "bytes" : "url"}`);+ assert(r.overlay === false, `run ${i + 1}: overlay dismissed`);+ assert(r.painted > r.total * 0.05, `run ${i + 1}: chip painted (${r.painted}/${r.total})`);+ if (Date.now() > deadline) { assert(false, "deadline exceeded"); break; }+ }+ assert(pageErrors.length === 0, `no uncaught page errors (${pageErrors.slice(0, 2).join(" | ")})`);+} finally {+ await browser.close();+ server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { console.log("Failures:"); for (const f of failures) console.log(" - " + f); }+process.exit(failed ? 1 : 0);
vite.config.mtsadded+24@@ -0,0 +1,24 @@+import { defineConfig } from 'vite';+import { svelte } from '@sveltejs/vite-plugin-svelte';++export default defineConfig({+ plugins: [svelte()],+ build: {+ lib: {+ entry: 'src/index.ts',+ formats: ['es'],+ fileName: 'index',+ },+ rollupOptions: {+ external: ['svelte', '@babylonjs/core', '@babylonjs/loaders'],+ output: {+ globals: {+ svelte: 'svelte',+ '@babylonjs/core': 'BABYLON',+ '@babylonjs/loaders': 'BABYLON',+ },+ },+ },+ sourcemap: true,+ },+});
vite.standalone.config.mtsadded+53@@ -0,0 +1,53 @@+import { defineConfig } from 'vite';+import { svelte } from '@sveltejs/vite-plugin-svelte';+import { readFileSync } from 'fs';++// Babylon 9's @babylonjs/inspector module has circular imports that resolve+// to TDZ when collapsed into a single IIFE scope (regardless of minifier).+// Output ESM instead — module boundaries preserve the original import order+// so the inspector initializes cleanly. Consumers load via+// `<script type="module" src="adom-3d-viewer-babylon9.esm.js"></script>`.+export default defineConfig({+ plugins: [svelte({ compilerOptions: { css: 'injected' } })],+ // @babylonjs/inspector v9 pulls in React, which references the Node-only+ // `process.env.NODE_ENV` global at runtime. Vite injects this automatically+ // in `serve` and standard `build` modes but NOT in `lib` mode, so without+ // a define the inspector crashes with "process is not defined" the first+ // time the user opens it. Replacing the env lookup at bundle time strips+ // every `if (process.env.NODE_ENV !== 'production') warn(...)` branch+ // from React, which incidentally removes the only `process` references.+ define: {+ 'process.env.NODE_ENV': JSON.stringify('production'),+ // Single source of truth for the runtime `version` field: package.json.+ // Read at config load so a version bump needs no code edit.+ __VIEWER_VERSION__: JSON.stringify(+ JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version,+ ),+ },+ build: {+ lib: {+ entry: 'standalone.ts',+ formats: ['es'],+ name: 'Adom3DViewerBabylon9',+ fileName: () => 'adom-3d-viewer-babylon9.esm.js',+ },+ rollupOptions: {+ external: [],+ output: {+ // Allow `await import(...)` to produce separate chunks. The inspector+ // lazy-import lands in its own scope and avoids the+ // "object is not extensible" error when collapsed into the main bundle.+ inlineDynamicImports: false,+ chunkFileNames: 'chunk-[hash].js',+ },+ },+ outDir: 'dist-standalone',+ minify: 'esbuild',+ sourcemap: false,+ chunkSizeWarningLimit: 50000,+ target: 'es2020',+ },+ resolve: {+ dedupe: ['svelte', '@babylonjs/core'],+ },+});
wiki/install.shwiki/uninstall.sh