@displayxr/inline3d-tools 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,194 @@
1
- # Temporary Holding Version
1
+ # @displayxr/inline3d-tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tools for building glasses-free 3D web pages on
4
+ [`@displayxr/inline3d`](https://www.npmjs.com/package/@displayxr/inline3d), for any coding agent
5
+ or a human: a headless page checker, a glTF/GLB asset check, page scaffolds, optional paid asset
6
+ generation with provenance, and a stdio [MCP](https://modelcontextprotocol.io) server exposing the
7
+ same operations. [`AGENTS.md`](AGENTS.md) is the matching authoring checklist for agents.
8
+
9
+ Needs Node ≥ 18. `check` also needs a local Chrome or Chromium. Always run an **exact version**:
10
+
11
+ ```sh
12
+ npx -y @displayxr/inline3d-tools@0.1.0 <command> ...
13
+ ```
14
+
15
+ ## CLI
16
+
17
+ | command | what it does |
18
+ |---|---|
19
+ | `check <url \| dir \| page.html> [--root <dir>] [--max-texture 4096] [--timeout ms] [--viewport WxH] [--no-fallback] [--json] [--out report.json]` | Loads the page in headless Chrome inside a fake DisplayXR Browser (two real eye views) and again plain, and reports pass/fail per rule. Exit 0 pass (warnings allowed), 1 a check failed, 2 the checker could not run. [Details](#check). |
20
+ | `assets <file.glb\|file.gltf> [--target tablet\|desktop] [--json]` | Is this model ready for an inline-3D page: missing files, decoders, triangles, draw calls, units/pivot, textures and decoded GPU memory, alpha-BLEND and metal/glass materials, file size, animations. Exit 0 / 1 (a FAIL) / 2 (unreadable). No network. |
21
+ | `assets prep <in> <out.glb> [--metres 0.01] [--decimate 0.5] [--blender <path>]` | Converts FBX/OBJ/STL/PLY/DAE/.blend (or fixes a glTF) with your **already installed** Blender, headless: applies transforms, scales to metres, decimates, recentres, exports one GLB. Never installs Blender. |
22
+ | `scaffold <esm\|vite> <dir> [--title "..."] [--name <npm-name>] [--force]` | Copies a known-good page: one persistent canvas, a cover that always comes off, a mono 2D fallback, exact pins (`esm`: import map, no build; `vite`: `package.json`). Never overwrites without `--force`. The untouched template passes every `check` rule. |
23
+ | `gen providers` | Which generator adapters have an API key in the environment (names and presence only). |
24
+ | `gen run <meshy\|tripo\|openai> --kind <text-to-3d\|image-to-3d\|image> --prompt "..." [--image <url>] [--size WxH] --out <file> --confirm-paid` | **Paid.** One call to the provider with your own key, writes the file and an `ASSETS.md` row. Without `--confirm-paid` it makes no call and prints the cost estimate (exit 4); without the key, exit 3. |
25
+ | `gen provenance --file <f> --source "..." --license "..." [--notes "..."]` | Appends a row to `ASSETS.md` in the working directory. |
26
+ | `mcp` | Starts the stdio MCP server. |
27
+
28
+ ## MCP server
29
+
30
+ `inline3d-tools mcp` speaks MCP over stdio and exposes:
31
+
32
+ | tool | what | side effects |
33
+ |---|---|---|
34
+ | `check` | `target`, `root?`, `max_texture?`, `timeout_ms?`, `viewport?`, `fallback?` → the report (text + structured) | starts and closes a headless Chrome; loads the page |
35
+ | `asset_check` | `file`, `target?` → the report | none |
36
+ | `scaffold` | `flavour`, `dir`, `title?`, `name?`, `force?` | writes the template files |
37
+ | `gen_providers` | → adapters and key presence (never a key) | none |
38
+ | `gen_run` | `adapter`, `kind`, `prompt?`, `image?`, `size?`, `out`, **`confirm_paid`** (required) | **paid** provider call only when `confirm_paid` is `true`; writes the file + `ASSETS.md` |
39
+ | `gen_provenance` | `file`, `source`, `license`, `notes?` | appends to `ASSETS.md` |
40
+ | `authoring_guide` | → [`AGENTS.md`](AGENTS.md) | none |
41
+
42
+ Relative paths resolve against the server's **working directory**: start it in the project root
43
+ (Codex: set `cwd`). `gen_run` with `confirm_paid: false` returns the cost estimate and makes no call;
44
+ an agent passes `true` only after the user approved that one call. Keys come from the server's
45
+ environment only and are redacted from every tool result.
46
+
47
+ ### Claude Code
48
+
49
+ ```sh
50
+ claude mcp add inline3d-tools -- npx -y @displayxr/inline3d-tools@0.1.0 mcp
51
+ ```
52
+
53
+ or in a project's `.mcp.json`:
54
+
55
+ ```json
56
+ {
57
+ "mcpServers": {
58
+ "inline3d-tools": {
59
+ "command": "npx",
60
+ "args": ["-y", "@displayxr/inline3d-tools@0.1.0", "mcp"]
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ (The [`displayxr-inline3d` Claude Code plugin](https://github.com/DisplayXR/displayxr-web/tree/main/plugins/displayxr-inline3d) does not need the
67
+ server: its skills run the CLI. The server is an optional add-on.)
68
+
69
+ ### OpenAI Codex
70
+
71
+ **Use the MCP server in Codex.** MCP servers run outside Codex's sandbox; a shell `check` does not:
72
+ its local file server fails with `listen EPERM 127.0.0.1` in the default sandbox, so a shell run
73
+ needs you to approve running it outside the sandbox. In `~/.codex/config.toml` (or a trusted project's `.codex/config.toml`), one
74
+ `[mcp_servers.<name>]` table per server, as in the
75
+ [Codex MCP documentation](https://developers.openai.com/codex/mcp):
76
+
77
+ ```toml
78
+ [mcp_servers.inline3d-tools]
79
+ command = "npx"
80
+ args = ["-y", "@displayxr/inline3d-tools@0.1.0", "mcp"]
81
+ # cwd = "/path/to/your/project" # relative paths in tool calls resolve here
82
+ startup_timeout_sec = 30 # first run downloads the package (default 10)
83
+ tool_timeout_sec = 180 # a page check takes 10-60 s; generation can take minutes (default 60)
84
+ # Only if you use the optional paid generators: forward these from your shell.
85
+ # env_vars = ["MESHY_API_KEY", "TRIPO_API_KEY", "OPENAI_API_KEY"]
86
+ ```
87
+
88
+ or `codex mcp add inline3d-tools -- npx -y @displayxr/inline3d-tools@0.1.0 mcp`. Codex reads
89
+ [`AGENTS.md`](AGENTS.md) files from the project: copy this package's into yours (or call the
90
+ `authoring_guide` tool).
91
+
92
+ ### Cursor
93
+
94
+ In `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project):
95
+
96
+ ```json
97
+ {
98
+ "mcpServers": {
99
+ "inline3d-tools": {
100
+ "command": "npx",
101
+ "args": ["-y", "@displayxr/inline3d-tools@0.1.0", "mcp"]
102
+ }
103
+ }
104
+ }
105
+ ```
106
+
107
+ ## What it runs, sends and fetches
108
+
109
+ Nothing runs in the background and nothing is sent anywhere by default. Every network call is one
110
+ you or the agent makes on purpose, and the paid ones need an explicit confirmation per call.
111
+
112
+ | command / tool | runs | network | writes |
113
+ |---|---|---|---|
114
+ | `npx -y @displayxr/inline3d-tools@<v>` | `npx` | the npm registry, to fetch this package and its pinned dependencies (first run; then npm's cache) | npm's cache |
115
+ | `check` | `node` + a headless Chrome it starts (local install, or `CHROME=`) and closes; a static file server on `127.0.0.1`, random port, when you pass a directory | whatever the page under test loads (for example its CDN imports); nothing else | a throwaway Chrome profile in the OS temp directory, deleted when Chrome closes; a JSON report only with `--out` |
116
+ | `assets` | `node`, reads a GLB/glTF | none | none |
117
+ | `assets prep` | your installed Blender, headless, with `lib/assets/blender/prep.py` | none | the output file you name |
118
+ | `scaffold` | `node` | none | the template files, in the directory you name |
119
+ | `gen providers` | `node` | none | none |
120
+ | `gen run` (optional, paid) | `node` | `api.meshy.ai`, `api.tripo3d.ai` or `api.openai.com` (the adapter you pick), with your prompt or image URL and your key for that provider; then downloads the result from the URL the provider returns | the output file and a row in `ASSETS.md` |
121
+ | `gen provenance` | `node` | none | a row in `ASSETS.md` |
122
+ | `mcp` | `node`, the stdio server; each tool as above | as above | as above |
123
+
124
+ `gen run` refuses to call a provider without `--confirm-paid` (MCP: `confirm_paid: true`). It reads
125
+ each key from the environment only, never prints, logs or writes one, and redacts long tokens from
126
+ provider error messages. DisplayXR receives nothing from this package: no telemetry, no accounts.
127
+ Prompts and images you send to a generator are governed by that provider's terms.
128
+
129
+ ### Generator keys (optional)
130
+
131
+ | Adapter | Variable | Makes |
132
+ |---|---|---|
133
+ | `meshy` | `MESHY_API_KEY` | text/image → GLB model |
134
+ | `tripo` | `TRIPO_API_KEY` | text/image → GLB model |
135
+ | `openai` | `OPENAI_API_KEY` | images (textures, posters, backdrops); model via `OPENAI_IMAGE_MODEL`, default `gpt-image-2.5-flare` |
136
+
137
+ Set them in the environment the tool runs in (your shell profile, or your MCP client's env
138
+ forwarding). Never paste a key into an agent chat.
139
+
140
+ ## check
141
+
142
+ ```sh
143
+ npx -y @displayxr/inline3d-tools@0.1.0 check <url | dir | page.html> [--root <dir>] [--max-texture 4096] [--json] [--out report.json]
144
+ ```
145
+
146
+ Needs Node ≥ 18 and a local Chrome (`CHROME=/path/to/chrome` overrides the default location). It
147
+ speaks the DevTools protocol over a pipe, so it opens no port, and it closes the
148
+ Chrome it started. Exit code 0 = pass (warnings allowed), 1 = a check failed, 2 = the checker could
149
+ not run.
150
+
151
+ The fake environment gives the SDK what the DisplayXR Browser gives it (`navigator.xr`
152
+ `inline-3d` session, `XRDisplayLayer`, display info, rendering modes), with **geometric** views: two
153
+ eyes 63 mm apart at 0.65 m from a 0.3456 m wide panel, off-axis frusta through the canvas's own
154
+ rect, scaled by the page's display or camera rig as the runtime does. A subject on the glass has zero
155
+ disparity, so the checker can measure depth in millimetres of screen disparity.
156
+
157
+ | check | how | real or approximate |
158
+ |---|---|---|
159
+ | (a) `session` | an `inline-3d` session, an open layer, frames with two views, pixels in the canvas | real |
160
+ | (b) `stereo` | the two halves of the committed buffer are not identical, a shift aligns them, and textured blocks match across eyes | real (a flat plane at one depth is a WARN) |
161
+ | (c) `eyes-not-blank` | each eye holds more than 0.3 % of something other than one colour | real |
162
+ | (d) `no-flat-sbs` | a woven buffer whose halves are not two views of one scene; any visible img/canvas/video showing a packed pair, in either run; join-window exposure (WARN) | heuristic on pixels |
163
+ | (e) `buffer` | `canvas.width/height` vs `drawingBufferWidth/Height`; with `--max-texture 4096` Chrome really clamps (`--webgl_or_caps_max_texture_size_limit_4096`) and the GL limits read 4096 | real |
164
+ | (f) `css` | computed filter / opacity / mask / clip-path / blend / backdrop-filter / non-translate transform on the canvas and every ancestor, sampled over time; border/radius/shadow and running animations WARN | real |
165
+ | (f) `single-session` | concurrent live sessions, a canvas registered twice, overlapping woven canvases | real |
166
+ | (f) `overlay` | grid hit-test (pointer-events forced on) for opaque elements above the canvas after `firstWoven`; a cover present at registration and still there = "never came off"; then a **scroll sweep** over the whole page: chrome that passes over a tile with a filter, blend mode or 3D context, a whole-tile frost, or a section painted over the whole tile. Partial chrome (sticky header, buy card), opaque or translucent, passes: current browsers occlude by draw order | real, grid-sampled |
167
+ | (f) `layer-lost` | ends the session, then compares each canvas with what it showed before: unchanged = the page left its side-by-side pair up (no-op `onLayerLost`) | real |
168
+ | (g) `console` | console errors, uncaught exceptions, HTTP ≥ 400, GL errors, failed shader compile/link | real |
169
+ | (h) `fallback-2d` | second run without the fake: no errors, and each canvas that wove shows something | real |
170
+ | `detection` | runtime `isSessionSupported('inline-3d')` calls; static scan of same-origin scripts for it and for UA sniffing next to "DisplayXR" | approximate |
171
+ | `pins` | import-map CDN URLs and `package.json` versions for the SDK, playcanvas and three are exact | approximate |
172
+ | `depth` | block-matched disparity of the primary canvas, in mm of screen disparity, against the Shibata comfort zone at 0.65 m; subject entirely off the glass | approximate |
173
+
174
+ Also reported: the rig (display/camera and its fields) and, for a camera rig, the comfort number
175
+ `ipdFactor × metersToVirtual × convergenceDiopters × 0.65`.
176
+
177
+ **Blind spots.** It is not a panel: no weave, no real compositor join, no eye tracking, no crosstalk.
178
+ Views come from the most recently created layer, so a page with several tiles on different rigs is
179
+ approximated by one. Heuristics on pixels can be fooled by unusual content (repeating patterns,
180
+ huge disparity, a page that animates wildly between snapshots). Lazy tiles below the fold are
181
+ found by scrolling, which a page may react to. CDN-hosted samples need the network.
182
+
183
+ ## Development
184
+
185
+ From the repository root: `npm test` runs these unit tests with the SDK's; `npm run test:plugin:e2e`
186
+ runs the checker end to end on the repo's samples (needs Chrome). In this folder, `npm ci` installs
187
+ the MCP SDK so `test/mcp.test.mjs` runs too. After editing a plugin skill or bumping the version,
188
+ run `node tools/inline3d-tools/scripts/sync-agents.mjs` (regenerates `AGENTS.md` and the plugin's
189
+ pins; CI checks it). Publishing: `tools-vX.Y.Z` tags, see
190
+ [`.github/workflows/tools-publish.yml`](https://github.com/DisplayXR/displayxr-web/blob/main/.github/workflows/tools-publish.yml).
191
+
192
+ ## License
193
+
194
+ Apache-2.0.
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // inline3d-tools — tools for @displayxr/inline3d pages, for any coding agent or a human.
3
+ //
4
+ // inline3d-tools check <url | dir | page.html> [--root <dir>] [--max-texture 4096] [--json] [--out f]
5
+ // inline3d-tools assets <file.glb|file.gltf> [--target tablet|desktop] [--json]
6
+ // inline3d-tools assets prep <in> <out.glb> [--metres <m>] [--decimate <r>] [--blender <path>]
7
+ // inline3d-tools gen providers | run <adapter> ... --confirm-paid | provenance --file ...
8
+ // inline3d-tools scaffold <esm|vite> <target-dir> [--title "..."] [--name <npm-name>] [--force]
9
+ // inline3d-tools mcp stdio MCP server with the same operations
10
+ import { readFileSync } from 'node:fs';
11
+
12
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
13
+ const USAGE = `inline3d-tools ${VERSION}: tools for @displayxr/inline3d pages
14
+
15
+ check <url | dir | page.html> [...] headless check: fake DisplayXR Browser + plain 2D run
16
+ assets <file.glb|file.gltf> [...] glTF/GLB budget + readiness check (no network)
17
+ assets prep <in> <out.glb> [...] convert/fix with an already-installed Blender
18
+ gen providers | run | provenance optional paid generation (your keys, --confirm-paid) + ASSETS.md
19
+ scaffold <esm|vite> <target-dir> [...] copy a known-good page template
20
+ mcp stdio MCP server exposing the same operations
21
+
22
+ <command> --help for its options. Docs: https://github.com/DisplayXR/displayxr-web/tree/main/tools/inline3d-tools`;
23
+
24
+ const [cmd, ...rest] = process.argv.slice(2);
25
+ let code;
26
+ switch (cmd) {
27
+ case 'check': code = await (await import('../lib/check/cli.mjs')).main(rest); break;
28
+ case 'assets':
29
+ code = rest[0] === 'prep'
30
+ ? (await import('../lib/assets/prep.mjs')).main(rest.slice(1))
31
+ : (await import('../lib/assets/asset-check.mjs')).main(rest);
32
+ break;
33
+ case 'gen': code = await (await import('../lib/gen.mjs')).main(rest); break;
34
+ case 'scaffold': code = (await import('../lib/scaffold.mjs')).main(rest); break;
35
+ case 'mcp': code = await (await import('../lib/mcp.mjs')).main(); break;
36
+ case '--version': case '-v': console.log(VERSION); code = 0; break;
37
+ case undefined: case 'help': case '--help': case '-h': console.log(USAGE); code = 0; break;
38
+ default: console.error(`unknown command "${cmd}"\n\n${USAGE}`); code = 2;
39
+ }
40
+ if (code !== undefined) process.exitCode = code;
@@ -0,0 +1,262 @@
1
+ // inline3d-tools assets — is this glTF/GLB ready for an inline-3D page on a glasses-free 3D display?
2
+ // Zero dependencies: reads the glTF JSON, the accessor bounds and the image headers itself.
3
+ //
4
+ // inline3d-tools assets <file.glb|file.gltf> [--json] [--target desktop|tablet]
5
+ //
6
+ // Exit 0 = no FAIL (WARNs allowed), 1 = at least one FAIL, 2 = could not read the file.
7
+ import { readFileSync, existsSync, statSync } from 'node:fs';
8
+ import { resolve, dirname, join, extname } from 'node:path';
9
+
10
+ export const ASSET_USAGE = 'usage: inline3d-tools assets <file.glb|file.gltf> [--json] [--target desktop|tablet]\n inline3d-tools assets prep <in> <out.glb> [--metres <m>] [--decimate <ratio>] [--blender <path>]';
11
+
12
+ // Budgets. Tablet = the weakest supported device class (Adreno 740-class, MAX_TEXTURE_SIZE 4096).
13
+ // Both eyes render the whole scene, so a model costs twice what it costs on a 2D page.
14
+ export const BUDGETS = {
15
+ tablet: { tris: 300_000, trisFail: 1_500_000, tex: 2048, texFail: 4096, texMB: 128, fileMB: 25 },
16
+ desktop: { tris: 1_000_000, trisFail: 5_000_000, tex: 4096, texFail: 8192, texMB: 512, fileMB: 60 },
17
+ };
18
+
19
+ // ------------------------------------------------------------------------------ load
20
+ function load(path) {
21
+ const abs = resolve(path);
22
+ const buf = readFileSync(abs);
23
+ const ext = extname(abs).toLowerCase();
24
+ let json, bin = null;
25
+ if (buf.readUInt32LE(0) === 0x46546c67) { // 'glTF'
26
+ const len = buf.readUInt32LE(8);
27
+ let off = 12;
28
+ while (off < len) {
29
+ const clen = buf.readUInt32LE(off), ctype = buf.readUInt32LE(off + 4);
30
+ const data = buf.subarray(off + 8, off + 8 + clen);
31
+ if (ctype === 0x4e4f534a) json = JSON.parse(data.toString('utf8'));
32
+ else if (ctype === 0x004e4942) bin = data;
33
+ off += 8 + clen;
34
+ }
35
+ } else if (ext === '.gltf' || buf[0] === 0x7b) {
36
+ json = JSON.parse(buf.toString('utf8'));
37
+ } else throw new Error('not a glTF/GLB file');
38
+ return { abs, dir: dirname(abs), json, bin, bytes: buf.length };
39
+ }
40
+
41
+ // The bytes of a buffer / image, or null with a reason.
42
+ function bufferBytes(g, i) {
43
+ const b = g.json.buffers?.[i];
44
+ if (!b) return { err: `buffer ${i} missing` };
45
+ if (b.uri === undefined) return g.bin ? { data: g.bin } : { err: 'GLB without a BIN chunk' };
46
+ if (b.uri.startsWith('data:')) return { data: Buffer.from(b.uri.split(',')[1], 'base64') };
47
+ const p = join(g.dir, decodeURIComponent(b.uri));
48
+ return existsSync(p) ? { data: readFileSync(p), external: b.uri } : { err: `missing file ${b.uri}`, external: b.uri };
49
+ }
50
+ function imageBytes(g, img) {
51
+ if (img.bufferView !== undefined) {
52
+ const bv = g.json.bufferViews[img.bufferView];
53
+ const b = bufferBytes(g, bv.buffer);
54
+ if (!b.data) return b;
55
+ return { data: b.data.subarray(bv.byteOffset || 0, (bv.byteOffset || 0) + bv.byteLength) };
56
+ }
57
+ if (!img.uri) return { err: 'image with no source' };
58
+ if (img.uri.startsWith('data:')) return { data: Buffer.from(img.uri.split(',')[1], 'base64') };
59
+ const p = join(g.dir, decodeURIComponent(img.uri));
60
+ return existsSync(p) ? { data: readFileSync(p), external: img.uri } : { err: `missing file ${img.uri}`, external: img.uri };
61
+ }
62
+
63
+ // Width/height from PNG, JPEG, WebP, KTX2 headers.
64
+ function imageSize(d) {
65
+ if (!d || d.length < 24) return null;
66
+ if (d[0] === 0x89 && d[1] === 0x50) return { w: d.readUInt32BE(16), h: d.readUInt32BE(20), fmt: 'png' };
67
+ if (d[0] === 0xff && d[1] === 0xd8) {
68
+ let o = 2;
69
+ while (o + 9 < d.length) {
70
+ if (d[o] !== 0xff) { o++; continue; }
71
+ const m = d[o + 1], len = d.readUInt16BE(o + 2);
72
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { w: d.readUInt16BE(o + 7), h: d.readUInt16BE(o + 5), fmt: 'jpeg' };
73
+ o += 2 + len;
74
+ }
75
+ return null;
76
+ }
77
+ if (d.toString('ascii', 0, 4) === 'RIFF' && d.toString('ascii', 8, 12) === 'WEBP') {
78
+ const k = d.toString('ascii', 12, 16);
79
+ if (k === 'VP8 ') return { w: d.readUInt16LE(26) & 0x3fff, h: d.readUInt16LE(28) & 0x3fff, fmt: 'webp' };
80
+ if (k === 'VP8L') { const b = d.readUInt32LE(21); return { w: (b & 0x3fff) + 1, h: ((b >> 14) & 0x3fff) + 1, fmt: 'webp' }; }
81
+ if (k === 'VP8X') return { w: 1 + d.readUIntLE(24, 3), h: 1 + d.readUIntLE(27, 3), fmt: 'webp' };
82
+ }
83
+ if (d[0] === 0xab && d.toString('ascii', 1, 4) === 'KTX') return { w: d.readUInt32LE(20), h: d.readUInt32LE(24), fmt: 'ktx2' };
84
+ return null;
85
+ }
86
+
87
+ // ------------------------------------------------------------------------------ maths
88
+ const I4 = () => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
89
+ function mul(a, b) { // column-major a*b
90
+ const o = new Array(16).fill(0);
91
+ for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) for (let k = 0; k < 4; k++) o[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
92
+ return o;
93
+ }
94
+ function trs(n) {
95
+ if (n.matrix) return n.matrix.slice();
96
+ const [x, y, z, w] = n.rotation || [0, 0, 0, 1];
97
+ const [sx, sy, sz] = n.scale || [1, 1, 1];
98
+ const [tx, ty, tz] = n.translation || [0, 0, 0];
99
+ return [
100
+ (1 - 2 * (y * y + z * z)) * sx, 2 * (x * y + z * w) * sx, 2 * (x * z - y * w) * sx, 0,
101
+ 2 * (x * y - z * w) * sy, (1 - 2 * (x * x + z * z)) * sy, 2 * (y * z + x * w) * sy, 0,
102
+ 2 * (x * z + y * w) * sz, 2 * (y * z - x * w) * sz, (1 - 2 * (x * x + y * y)) * sz, 0,
103
+ tx, ty, tz, 1,
104
+ ];
105
+ }
106
+ const xf = (m, p) => [0, 1, 2].map((r) => m[r] * p[0] + m[4 + r] * p[1] + m[8 + r] * p[2] + m[12 + r]);
107
+
108
+ // ------------------------------------------------------------------------------ checks
109
+ function run(g, target) {
110
+ const BUDGET = BUDGETS[target];
111
+ const J = g.json;
112
+ const out = [];
113
+ const add = (id, status, summary, extra = {}) => out.push({ id, status, summary, ...extra });
114
+ const info = {};
115
+
116
+ // spec version + external files
117
+ if (!J.asset || !/^2\./.test(J.asset.version || '')) add('gltf2', 'fail', `asset.version is ${J.asset?.version}: only glTF 2.0 loads`);
118
+ const missing = [];
119
+ for (let i = 0; i < (J.buffers || []).length; i++) { const b = bufferBytes(g, i); if (b.err) missing.push(b.err); }
120
+ for (const img of J.images || []) { const b = imageBytes(g, img); if (b.err) missing.push(b.err); }
121
+ const externals = [...(J.buffers || []), ...(J.images || [])].filter((x) => x.uri && !x.uri.startsWith('data:')).map((x) => x.uri);
122
+ if (missing.length) add('files', 'fail', `${missing[0]}${missing.length > 1 ? ` (+${missing.length - 1} more)` : ''}: a .gltf is several files; deploy every one (or pack a single .glb: gltf-transform copy in.gltf out.glb)`);
123
+ else add('files', externals.length ? 'warn' : 'pass', externals.length ? `${externals.length} external file(s) (${externals.slice(0, 3).join(', ')}): ship them all, or pack a single .glb` : 'self-contained');
124
+
125
+ // extensions that need decoders the page must serve
126
+ const req = J.extensionsRequired || [];
127
+ const used = J.extensionsUsed || [];
128
+ const decoders = [];
129
+ if (used.includes('KHR_draco_mesh_compression')) decoders.push('Draco: serve three/examples/jsm/libs/draco/ at /draco/ (or set decoderPath)');
130
+ if (used.includes('KHR_texture_basisu')) decoders.push('KTX2/Basis: serve three/examples/jsm/libs/basis/ at /basis/');
131
+ if (used.includes('EXT_meshopt_compression')) decoders.push('meshopt: add the meshoptimizer package (import map / package.json), no served files');
132
+ add('decoders', decoders.length ? 'warn' : 'pass', decoders.length ? decoders.join('; ') : 'no compression extension needs a decoder', { doc: 'node_modules/@displayxr/inline3d/docs/authoring-inline-3d.md#compressed-gltf' });
133
+ const unknown = req.filter((e) => !['KHR_draco_mesh_compression', 'KHR_texture_basisu', 'EXT_meshopt_compression', 'KHR_mesh_quantization', 'KHR_texture_transform', 'KHR_materials_emissive_strength', 'EXT_texture_webp'].includes(e));
134
+ if (unknown.length) add('required-ext', 'warn', `extensionsRequired includes ${unknown.join(', ')}: check the engine supports it, or the model will not load`);
135
+
136
+ // geometry: triangles, draw calls, bounds
137
+ let tris = 0, prims = 0;
138
+ const meshTris = new Map();
139
+ (J.meshes || []).forEach((m, mi) => {
140
+ let t = 0;
141
+ for (const p of m.primitives || []) {
142
+ prims++;
143
+ const mode = p.mode ?? 4;
144
+ const count = p.indices !== undefined ? J.accessors[p.indices].count : J.accessors[p.attributes.POSITION]?.count || 0;
145
+ if (mode === 4) t += count / 3; else if (mode === 5 || mode === 6) t += Math.max(0, count - 2);
146
+ }
147
+ meshTris.set(mi, t);
148
+ });
149
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
150
+ let instances = 0;
151
+ const scene = J.scenes?.[J.scene ?? 0];
152
+ const visit = (ni, parent) => {
153
+ const n = J.nodes[ni];
154
+ const m = mul(parent, trs(n));
155
+ if (n.mesh !== undefined) {
156
+ instances++;
157
+ tris += meshTris.get(n.mesh) || 0;
158
+ for (const p of J.meshes[n.mesh].primitives || []) {
159
+ const a = J.accessors[p.attributes.POSITION];
160
+ if (!a || !a.min || !a.max) continue;
161
+ // KHR_mesh_quantization: normalized integer positions; min/max are in raw integer units.
162
+ const q = a.normalized ? 1 / ({ 5120: 127, 5121: 255, 5122: 32767, 5123: 65535 }[a.componentType] || 1) : 1;
163
+ for (let k = 0; k < 8; k++) {
164
+ const c = [k & 1 ? a.max[0] * q : a.min[0] * q, k & 2 ? a.max[1] * q : a.min[1] * q, k & 4 ? a.max[2] * q : a.min[2] * q];
165
+ const w = xf(m, c);
166
+ for (let d = 0; d < 3; d++) { lo[d] = Math.min(lo[d], w[d]); hi[d] = Math.max(hi[d], w[d]); }
167
+ }
168
+ }
169
+ }
170
+ for (const c of n.children || []) visit(c, m);
171
+ };
172
+ for (const ni of scene?.nodes || []) visit(ni, I4());
173
+ tris = Math.round(tris);
174
+ info.triangles = tris; info.primitives = prims; info.meshInstances = instances;
175
+ if (tris > BUDGET.trisFail) add('triangles', 'fail', `${tris.toLocaleString()} triangles: both eyes draw them, far over the ${target} budget (${BUDGET.tris.toLocaleString()}). Decimate (gltf-transform simplify, or Blender's Decimate)`);
176
+ else if (tris > BUDGET.tris) add('triangles', 'warn', `${tris.toLocaleString()} triangles: over the ${target} budget of ${BUDGET.tris.toLocaleString()} (both eyes draw them). gltf-transform simplify --ratio 0.5 --error 0.001`);
177
+ else add('triangles', 'pass', `${tris.toLocaleString()} triangles`);
178
+ if (prims > 300) add('draw-calls', 'warn', `${prims} primitives (draw calls x2 eyes): merge by material (gltf-transform join / flatten)`);
179
+
180
+ if (isFinite(lo[0])) {
181
+ const size = [0, 1, 2].map((d) => hi[d] - lo[d]);
182
+ const centre = [0, 1, 2].map((d) => (hi[d] + lo[d]) / 2);
183
+ const maxDim = Math.max(...size);
184
+ info.bounds = { size: size.map((v) => +v.toPrecision(4)), centre: centre.map((v) => +v.toPrecision(4)), unitsGuess: maxDim > 50 ? 'centimetres or millimetres?' : 'metres' };
185
+ // addModel frames the subject on the glass by its bounds, so units and offset do not break the
186
+ // page — but a page that places the model in its own scene (addScene) needs metres, centred.
187
+ const st = maxDim > 50 || maxDim < 0.005 ? 'warn' : 'pass';
188
+ add('scale', st, `${size.map((v) => v.toPrecision(3)).join(' x ')} (units), centre ${centre.map((v) => v.toPrecision(3)).join(', ')}` +
189
+ (st === 'warn' ? `: ${maxDim > 50 ? 'probably centimetres/millimetres' : 'tiny'}. addModel frames it anyway; for your own scene rescale to real-world metres (gltf-transform transform... or Blender: apply scale)` : ''));
190
+ const off = Math.hypot(...centre) / Math.max(1e-9, maxDim);
191
+ if (off > 0.5) add('pivot', 'warn', `the bounds centre is ${off.toFixed(1)} x the model's size away from its origin: turning it by its origin swings it off the glass. Recentre (gltf-transform center --pivot center)`);
192
+ } else add('scale', 'warn', 'no POSITION min/max to measure the bounds');
193
+
194
+ // textures
195
+ const texInfo = [];
196
+ let texBytes = 0, worst = 0;
197
+ for (const [i, img] of (J.images || []).entries()) {
198
+ const b = imageBytes(g, img);
199
+ const s = b.data ? imageSize(b.data) : null;
200
+ if (!s) { texInfo.push({ i, name: img.name || img.uri || `image ${i}`, size: null }); continue; }
201
+ worst = Math.max(worst, s.w, s.h);
202
+ texBytes += s.w * s.h * 4 * 1.33;
203
+ texInfo.push({ i, name: img.name || img.uri || `image ${i}`, w: s.w, h: s.h, fmt: s.fmt });
204
+ }
205
+ info.textures = texInfo;
206
+ const texMB = texBytes / 1048576;
207
+ if (worst > BUDGET.texFail) add('textures', 'fail', `a ${worst}px texture: over ${BUDGET.texFail} the GPU on a ${target} cannot load it. gltf-transform resize --width ${BUDGET.tex} --height ${BUDGET.tex}`);
208
+ else if (worst > BUDGET.tex || texMB > BUDGET.texMB) add('textures', 'warn', `largest texture ${worst}px, ~${texMB.toFixed(0)} MB of GPU memory once decoded: resize to ${BUDGET.tex} (gltf-transform resize) and compress (gltf-transform webp, or ktx2 with served /basis/)`);
209
+ else add('textures', 'pass', `${texInfo.length} texture(s), largest ${worst || 0}px, ~${texMB.toFixed(0)} MB decoded`);
210
+
211
+ // materials that look wrong on a 3D display
212
+ const mats = J.materials || [];
213
+ const blend = mats.filter((m) => m.alphaMode === 'BLEND').length;
214
+ const metal = mats.filter((m) => (m.pbrMetallicRoughness?.metallicFactor ?? 1) > 0.6 && !m.pbrMetallicRoughness?.metallicRoughnessTexture).length;
215
+ const glass = mats.filter((m) => m.extensions && (m.extensions.KHR_materials_transmission || m.extensions.KHR_materials_volume)).length;
216
+ const notes = [];
217
+ if (blend) notes.push(`${blend} alpha-BLEND material(s): sorting errors show as depth errors in stereo; use MASK for cut-outs`);
218
+ if (metal || glass) notes.push(`${metal ? `${metal} metallic` : ''}${metal && glass ? ' and ' : ''}${glass ? `${glass} glass/transmission` : ''} material(s): they need an image-based environment to read (addModel's default 'room'/'neutral', or envMap; not 'studio', a punctual rig), or they render dark`);
219
+ add('materials', notes.length ? 'warn' : 'pass', notes.length ? notes.join('; ') : `${mats.length} material(s), opaque/mask only`);
220
+
221
+ // file size
222
+ const fileMB = (g.bytes + (externals.length ? externals.reduce((s, u) => { try { return s + statSync(join(g.dir, decodeURIComponent(u))).size; } catch { return s; } }, 0) : 0)) / 1048576;
223
+ info.fileMB = +fileMB.toFixed(2);
224
+ if (fileMB > BUDGET.fileMB) add('file-size', 'warn', `${fileMB.toFixed(1)} MB to download: gltf-transform optimize in.glb out.glb --compress meshopt --texture-compress webp`);
225
+ else add('file-size', 'pass', `${fileMB.toFixed(1)} MB`);
226
+
227
+ // animation (fine, but say so: a moving subject swings off the glass)
228
+ if ((J.animations || []).length) add('animation', 'warn', `${J.animations.length} animation(s): keep the motion's forward swing small (it leaves the glass); addModel plays none unless you ask`);
229
+
230
+ const verdict = out.some((c) => c.status === 'fail') ? 'fail' : out.some((c) => c.status === 'warn') ? 'warn' : 'pass';
231
+ return { file: g.abs, target, verdict, checks: out, info, generator: J.asset?.generator || null };
232
+ }
233
+
234
+ // Throws when the file cannot be read; otherwise returns the report.
235
+ export function assetCheck(file, { target = 'tablet' } = {}) {
236
+ if (!BUDGETS[target]) throw new Error(`unknown target ${target} (tablet | desktop)`);
237
+ let g;
238
+ try { g = load(file); } catch (e) { throw new Error(`cannot read ${file}: ${e.message}`); }
239
+ return run(g, target);
240
+ }
241
+
242
+ export function formatAssetReport(r) {
243
+ const lines = [`asset-check ${r.file} (target: ${r.target})`];
244
+ for (const c of r.checks) lines.push(` ${c.status.toUpperCase().padEnd(4)} ${c.id.padEnd(12)} ${c.summary}`);
245
+ lines.push(` verdict: ${r.verdict.toUpperCase()}`);
246
+ return lines.join('\n');
247
+ }
248
+
249
+ // Returns the exit code.
250
+ export function main(argv) {
251
+ const ti = argv.indexOf('--target');
252
+ const target = ti >= 0 ? argv[ti + 1] || 'tablet' : 'tablet';
253
+ const file = argv.find((a, i) => !a.startsWith('--') && !(ti >= 0 && i === ti + 1));
254
+ const asJson = argv.includes('--json');
255
+ if (argv.includes('--help') || argv.includes('-h')) { console.log(ASSET_USAGE); return 0; }
256
+ if (!file) { console.error(ASSET_USAGE); return 2; }
257
+ if (!BUDGETS[target]) { console.error(`unknown --target ${target}`); return 2; }
258
+ let r;
259
+ try { r = assetCheck(file, { target }); } catch (e) { console.error(`asset-check: ${e.message}`); return 2; }
260
+ console.log(asJson ? JSON.stringify(r, null, 1) : formatAssetReport(r));
261
+ return r.verdict === 'fail' ? 1 : 0;
262
+ }
@@ -0,0 +1,74 @@
1
+ # Headless Blender asset prep for inline-3D pages. Run ONLY with a Blender that is already installed:
2
+ #
3
+ # blender -b --factory-startup -P prep.py -- <in.(fbx|obj|stl|ply|dae|blend|glb|gltf)> <out.glb> [--decimate 0.5] [--metres 0.01]
4
+ #
5
+ # Imports the file, applies transforms, optionally scales to metres (--metres = how many metres
6
+ # one source unit is, e.g. 0.01 for centimetres) and decimates, recentres the bounds on the origin,
7
+ # and exports a single binary .glb (+Y up, as glTF expects).
8
+ import sys, os
9
+ import bpy
10
+ from mathutils import Vector
11
+
12
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
13
+ if len(argv) < 2:
14
+ print("usage: blender -b --factory-startup -P prep.py -- <in> <out.glb> [--decimate R] [--metres S]")
15
+ sys.exit(2)
16
+ src, dst = argv[0], argv[1]
17
+ def opt(name, default=None):
18
+ return float(argv[argv.index(name) + 1]) if name in argv else default
19
+ ratio = opt("--decimate")
20
+ metres = opt("--metres")
21
+
22
+ bpy.ops.wm.read_factory_settings(use_empty=True)
23
+ ext = os.path.splitext(src)[1].lower()
24
+ if ext == ".blend":
25
+ bpy.ops.wm.open_mainfile(filepath=src)
26
+ elif ext in (".glb", ".gltf"):
27
+ bpy.ops.import_scene.gltf(filepath=src)
28
+ elif ext == ".fbx":
29
+ bpy.ops.import_scene.fbx(filepath=src)
30
+ elif ext == ".obj":
31
+ bpy.ops.wm.obj_import(filepath=src)
32
+ elif ext == ".stl":
33
+ bpy.ops.wm.stl_import(filepath=src)
34
+ elif ext == ".ply":
35
+ bpy.ops.wm.ply_import(filepath=src)
36
+ elif ext == ".dae":
37
+ bpy.ops.wm.collada_import(filepath=src)
38
+ else:
39
+ print(f"unsupported input {ext}")
40
+ sys.exit(2)
41
+
42
+ meshes = [o for o in bpy.context.scene.objects if o.type == "MESH"]
43
+ if not meshes:
44
+ print("no mesh objects in the file")
45
+ sys.exit(1)
46
+ bpy.ops.object.select_all(action="DESELECT")
47
+ for o in meshes:
48
+ o.select_set(True)
49
+ bpy.context.view_layer.objects.active = meshes[0]
50
+ if metres:
51
+ for o in meshes:
52
+ o.scale = o.scale * metres
53
+ bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
54
+
55
+ if ratio and 0 < ratio < 1:
56
+ for o in meshes:
57
+ m = o.modifiers.new("Decimate", "DECIMATE")
58
+ m.ratio = ratio
59
+ bpy.context.view_layer.objects.active = o
60
+ bpy.ops.object.modifier_apply(modifier=m.name)
61
+
62
+ # Recentre the combined bounds on the origin (the subject straddles the glass on a display rig).
63
+ lo = Vector((1e30, 1e30, 1e30)); hi = Vector((-1e30, -1e30, -1e30))
64
+ for o in meshes:
65
+ for c in o.bound_box:
66
+ w = o.matrix_world @ Vector(c)
67
+ lo = Vector(map(min, lo, w)); hi = Vector(map(max, hi, w))
68
+ centre = (lo + hi) / 2
69
+ for o in meshes:
70
+ o.location -= centre
71
+
72
+ bpy.ops.export_scene.gltf(filepath=dst, export_format="GLB", use_selection=True, export_apply=True, export_yup=True)
73
+ tris = sum(len(p.vertices) - 2 for o in meshes for p in o.data.polygons)
74
+ print(f"prep.py: wrote {dst}; ~{tris} triangles; size {tuple(round(v, 4) for v in (hi - lo))}")
@@ -0,0 +1,50 @@
1
+ // inline3d-tools assets prep — run the bundled Blender script (blender/prep.py) headless, ONLY with a
2
+ // Blender that is already installed. Never downloads or installs Blender.
3
+ //
4
+ // inline3d-tools assets prep <in.(fbx|obj|stl|ply|dae|blend|glb|gltf)> <out.glb> [--metres 0.01] [--decimate 0.5] [--blender <path>]
5
+ import { existsSync, readdirSync } from 'node:fs';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ export const PREP_PY = join(dirname(fileURLToPath(import.meta.url)), 'blender', 'prep.py');
11
+
12
+ // --blender, then $BLENDER, then `blender` on PATH, then the default install locations.
13
+ export function findBlender(explicit) {
14
+ const cands = [explicit, process.env.BLENDER].filter(Boolean);
15
+ for (const c of cands) if (existsSync(c)) return c;
16
+ const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['blender'], { encoding: 'utf8' });
17
+ if (which.status === 0 && which.stdout.trim()) return which.stdout.trim().split(/\r?\n/)[0];
18
+ if (process.platform === 'darwin') {
19
+ const p = '/Applications/Blender.app/Contents/MacOS/Blender';
20
+ if (existsSync(p)) return p;
21
+ }
22
+ if (process.platform === 'win32') {
23
+ const root = 'C:\\Program Files\\Blender Foundation';
24
+ try {
25
+ for (const d of readdirSync(root).sort().reverse()) {
26
+ const p = join(root, d, 'blender.exe');
27
+ if (existsSync(p)) return p;
28
+ }
29
+ } catch { /* not installed */ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ // Returns the exit code (2 = bad arguments or no Blender).
35
+ export function main(argv) {
36
+ const val = (k) => { const i = argv.indexOf(`--${k}`); return i >= 0 ? argv[i + 1] : undefined; };
37
+ const pos = argv.filter((a, i) => !a.startsWith('--') && !['--metres', '--decimate', '--blender'].includes(argv[i - 1]));
38
+ const [src, dst] = pos;
39
+ if (!src || !dst) { console.error('usage: inline3d-tools assets prep <in> <out.glb> [--metres <m>] [--decimate <ratio>] [--blender <path>]'); return 2; }
40
+ const blender = findBlender(val('blender'));
41
+ if (!blender) {
42
+ console.error('no Blender found (--blender, $BLENDER, PATH, default install path). This tool never installs it: ask for a GLB instead, or install Blender yourself.');
43
+ return 2;
44
+ }
45
+ const extra = [];
46
+ if (val('metres')) extra.push('--metres', val('metres'));
47
+ if (val('decimate')) extra.push('--decimate', val('decimate'));
48
+ const r = spawnSync(blender, ['-b', '--factory-startup', '-P', PREP_PY, '--', src, dst, ...extra], { stdio: 'inherit' });
49
+ return r.status ?? 1;
50
+ }