@threenative/runtime-native 0.3.4 → 0.3.5

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.
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env node
2
+ // PRD-531's VM artifact: the game bundle for the engine player on V8, explicitly selected.
3
+ import { randomUUID } from "node:crypto";
4
+ import { execFileSync } from "node:child_process";
5
+ import { existsSync, realpathSync, readFileSync } from "node:fs";
6
+ import { readFile, mkdir, writeFile, rename, unlink } from "node:fs/promises";
7
+ import { createRequire } from "node:module";
8
+ import { dirname, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const native = resolve(dirname(fileURLToPath(import.meta.url)), "..");
12
+ const repo = resolve(native, "../..");
13
+ const player = resolve(native, "src/engine/player");
14
+ const require = createRequire(resolve(native, "package.json"));
15
+ const { build } = require("esbuild");
16
+ const ts = require("typescript");
17
+ const core = dirname(require.resolve("@threenative/core/package.json"));
18
+ const threeNative = dirname(require.resolve("@threenative/three-native/package.json"));
19
+ const assetsEntry = resolve(dirname(require.resolve("@threenative/assets/package.json")), "dist/index.js");
20
+
21
+ // Player facades share source with sibling packages; installed packages need their resolved roots.
22
+ const packageImports = { name: "native-player-packages", setup(builder) {
23
+ builder.onResolve({ filter: /^\.\.\/\.\.\/\.\.\/\.\.\/(?:three-native|core)\/src\// }, (args) => {
24
+ if (!args.importer.startsWith(`${player}/`)) return;
25
+ const [, name, source] = /^\.\.\/\.\.\/\.\.\/\.\.\/(three-native|core)\/(.+)$/.exec(args.path);
26
+ return { path: resolve(name === "core" ? core : threeNative, source) };
27
+ });
28
+ } };
29
+
30
+ function rejectUpstream(metafile) {
31
+ const upstream = Object.keys(metafile.inputs).filter((file) => /(?:^|\/)node_modules\/three\//.test(file));
32
+ if (upstream.length) throw new Error(`TN_NATIVE_ENGINE_UPSTREAM: ${upstream.join(", ")}`);
33
+ }
34
+
35
+ function imports(source, specifier) {
36
+ const ast = ts.createSourceFile("game.ts", source, ts.ScriptTarget.Latest, true);
37
+ const names = new Set();
38
+ const namespaces = new Set();
39
+ const matches = (node) => ts.isStringLiteral(node) && node.text === specifier;
40
+ const bindings = (elements) => {
41
+ for (const item of elements) {
42
+ if (!item.isTypeOnly) names.add((item.propertyName ?? item.name).text);
43
+ }
44
+ };
45
+ function importDeclaration(node) {
46
+ if (!ts.isImportDeclaration(node)) return;
47
+ if (!matches(node.moduleSpecifier) || node.importClause?.isTypeOnly) return;
48
+ const clause = node.importClause;
49
+ if (clause?.name) names.add("default");
50
+ const named = clause?.namedBindings;
51
+ if (named && ts.isNamedImports(named)) bindings(named.elements);
52
+ else if (named) namespaces.add(named.name.text);
53
+ }
54
+ function exportDeclaration(node) {
55
+ if (!ts.isExportDeclaration(node)) return;
56
+ if (node.isTypeOnly || !node.moduleSpecifier || !matches(node.moduleSpecifier)) return;
57
+ if (node.exportClause && ts.isNamedExports(node.exportClause)) bindings(node.exportClause.elements);
58
+ }
59
+ function dynamicImport(node) {
60
+ if (!ts.isCallExpression(node) || node.expression.kind !== ts.SyntaxKind.ImportKeyword) return;
61
+ if (!matches(node.arguments[0])) return;
62
+ const expression = ts.isAwaitExpression(node.parent) ? node.parent : node;
63
+ const parent = expression.parent;
64
+ if (!ts.isVariableDeclaration(parent)) return;
65
+ if (ts.isObjectBindingPattern(parent.name)) bindings(parent.name.elements);
66
+ else if (ts.isIdentifier(parent.name)) namespaces.add(parent.name.text);
67
+ }
68
+ function visit(node) {
69
+ importDeclaration(node);
70
+ exportDeclaration(node);
71
+ dynamicImport(node);
72
+ ts.forEachChild(node, visit);
73
+ }
74
+ visit(ast);
75
+ function references(node) {
76
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && namespaces.has(node.expression.text))
77
+ names.add(node.name.text);
78
+ if (ts.isElementAccessExpression(node) && ts.isIdentifier(node.expression) && namespaces.has(node.expression.text)) {
79
+ if (ts.isStringLiteral(node.argumentExpression)) names.add(node.argumentExpression.text);
80
+ else names.add("*");
81
+ }
82
+ ts.forEachChild(node, references);
83
+ }
84
+ references(ast);
85
+ return [...names];
86
+ }
87
+
88
+ function unboundDiagnostic(specifier, name) {
89
+ let reason = "the native engine profile has no binding for this import";
90
+ if (specifier.startsWith("three/addons/tsl/display/"))
91
+ reason = "live addon-node construction and update scheduling are unbound; the native renderer currently consumes cooked post graphs";
92
+ else if (specifier.includes("GLTFLoader"))
93
+ reason = "the native cgltf loader has no V8 loader binding and does not decode glTF images or external buffers";
94
+ else if (/KTX2Loader|DRACOLoader|MeshoptDecoder|meshopt_decoder/.test(specifier))
95
+ reason = "the selected native engine asset path has no bound decoder/transcoder for this loader";
96
+ else if (specifier === "three-mesh-bvh")
97
+ reason = "the native MeshBVH answers raycastObject3D only; serialization, build strategies and GPU BVH are not bound";
98
+ else if (name === "DepthTexture")
99
+ reason = "native render targets do not expose a game-owned, sampleable depth attachment";
100
+ else if (specifier === "three/webgpu" || name === "RenderTarget")
101
+ reason = "native render targets, fullscreen draws and game-authored node lifecycle lack the required V8 renderer bindings";
102
+ else if (specifier === "three/tsl")
103
+ reason = ({
104
+ atomicAdd: "native IR supports atomics, but live storage nodes do not carry atomic element types or statement scheduling",
105
+ atomicStore: "native IR supports atomics, but live storage nodes do not carry atomic element types or statement scheduling",
106
+ lightShadowMatrix: "the live graph cannot bind an authored light's shadow matrix to its render light index",
107
+ rtt: "live RTT targets do not expose the requested filtering, renderTarget extent or update lifecycle",
108
+ wgslFn: "the live graph cannot compile and link an authored WGSL function with its typed arguments",
109
+ })[name] ?? "the native graph lacks this material/pass/history/storage context binding";
110
+ else if (name === "PropertyBinding" || name.endsWith("ConsoleFunction"))
111
+ reason = "native PropertyBinding exists, but its V8 object/static reflection and diagnostic console hook are unbound";
112
+ return `TN_NATIVE_ENGINE_UNBOUND: ${specifier}:${name} [${reason}]`;
113
+ }
114
+
115
+ /** Bundle the portable entry against native imports; publish nothing when a binding is absent. */
116
+ export async function bundleNativeEngine({ entry, outfile, boot = true, define = {}, host = boot }) {
117
+ let engineCommit;
118
+ try {
119
+ const git = (args) => execFileSync("git", args, { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
120
+ // Installed packages can sit inside somebody else's repository, or have no git at all.
121
+ if (realpathSync(git(["rev-parse", "--show-toplevel"])) === realpathSync(repo)
122
+ && JSON.parse(readFileSync(resolve(repo, "package.json"), "utf8")).name === "threenative"
123
+ && !git(["status", "--porcelain", "--untracked-files=normal", "--", "packages", "scripts", "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", ":(exclude,glob)packages/**/__tests__/**", ":(exclude,glob)packages/runtime-native/tests/**", ":(exclude,glob)scripts/__tests__/**"]))
124
+ engineCommit = git(["rev-parse", "HEAD"]);
125
+ } catch { /* Ordinary bundling does not require source provenance. */ }
126
+ entry = resolve(entry);
127
+ outfile = resolve(outfile);
128
+ if (entry === outfile) throw new Error("TN_NATIVE_ENGINE_OUTPUT: entry and output must differ");
129
+ // Tree-shake the game and packages first. Unused package exports must not enlarge the game's
130
+ // compatibility denominator merely because the package's index reexports them.
131
+ const game = await build({
132
+ entryPoints: [entry], bundle: true, write: false, format: "esm", platform: "neutral",
133
+ target: "es2022", conditions: ["threenative-native"], define: { "import.meta.env": "{}", ...define },
134
+ external: ["three", "three/*", "three-mesh-bvh", "three-mesh-bvh/*",
135
+ "@threenative/core", "@threenative/core/*"],
136
+ logLevel: "silent", metafile: true, sourcemap: "inline", sourcesContent: true,
137
+ // A script entry that imports core's loader by relative path (the load test's Fox) would inline the
138
+ // browser loader and its GLTFLoader; it reads the cooked package like core's own imports do.
139
+ plugins: [packageImports, { name: "native-assets", setup(builder) {
140
+ builder.onResolve({ filter: /(?:^|\/)assets\.js$/ }, (args) => {
141
+ if (resolve(args.resolveDir, args.path) === resolve(core, "src/assets.js"))
142
+ return { path: resolve(player, "core-assets.mjs"), external: true };
143
+ });
144
+ } }],
145
+ });
146
+ rejectUpstream(game.metafile);
147
+ const code = game.outputFiles[0].text;
148
+ const coreIndex = ts.createSourceFile("index.ts",
149
+ await readFile(resolve(core, "src/index.ts"), "utf8"), ts.ScriptTarget.Latest, true);
150
+ const coreExports = imports(code, "@threenative/core").map((name) => {
151
+ const declaration = coreIndex.statements.find((node) => ts.isExportDeclaration(node) &&
152
+ !node.isTypeOnly && node.exportClause && ts.isNamedExports(node.exportClause) &&
153
+ node.exportClause.elements.some((item) => !item.isTypeOnly && item.name.text === name));
154
+ if (!declaration?.moduleSpecifier)
155
+ throw new Error(`TN_NATIVE_ENGINE_UNBOUND: @threenative/core:${name}`);
156
+ const source = JSON.stringify(resolve(core, "src", declaration.moduleSpecifier.text));
157
+ if (name === "defineGame") return `import { defineGame as coreDefineGame } from ${source};
158
+ import { platform } from ${JSON.stringify(resolve(player, "core-host.mjs"))};
159
+ export function defineGame(options) { return coreDefineGame({ ...options, platform: options.platform ?? platform }); }`;
160
+ return `export { ${name} } from ${source};`;
161
+ }).join("\n");
162
+ const modules = {
163
+ three: resolve(player, "core-three.mjs"),
164
+ "three/webgpu": resolve(player, "core-webgpu.mjs"),
165
+ "three/tsl": resolve(player, "core-tsl.mjs"),
166
+ "three/addons/utils/SkeletonUtils.js": resolve(player, "core-three.mjs"),
167
+ "three/addons/geometries/RoundedBoxGeometry.js": resolve(player, "core-three.mjs"),
168
+ "three/addons/tsl/display/GTAONode.js": resolve(player, "core-addons.mjs"),
169
+ "three/addons/tsl/display/DenoiseNode.js": resolve(player, "core-addons.mjs"),
170
+ "three/addons/tsl/display/SMAANode.js": resolve(player, "core-addons.mjs"),
171
+ "three/addons/tsl/display/FilmNode.js": resolve(player, "core-addons.mjs"),
172
+ "three/addons/tsl/display/Lut3DNode.js": resolve(player, "core-addons.mjs"),
173
+ "three/addons/tsl/display/TRAANode.js": resolve(player, "core-addons.mjs"),
174
+ "three/addons/tsl/display/BloomNode.js": resolve(player, "core-addons.mjs"),
175
+ "three/addons/tsl/display/FXAANode.js": resolve(player, "core-addons.mjs"),
176
+ "three/addons/tsl/display/GodraysNode.js": resolve(player, "core-addons.mjs"),
177
+ "three/addons/tsl/display/SSGINode.js": resolve(player, "core-addons.mjs"),
178
+ "three/addons/tsl/display/SSRNode.js": resolve(player, "core-addons.mjs"),
179
+ "three/addons/tsl/display/SharpenNode.js": resolve(player, "core-addons.mjs"),
180
+ "three/addons/loaders/LUTCubeLoader.js": resolve(player, "core-lut.mjs"),
181
+ "three/addons/loaders/HDRLoader.js": resolve(player, "core-hdr.mjs"),
182
+ "three-mesh-bvh": resolve(threeNative, "src/addons/mesh-bvh.ts"),
183
+ "three/addons/utils/BufferGeometryUtils.js": resolve(threeNative, "src/addons/buffer-geometry-utils.ts"),
184
+ "three/addons/geometries/DecalGeometry.js": resolve(threeNative, "src/addons/decal-geometry.ts"),
185
+ };
186
+ const exports = new Map(await Promise.all(Object.values(modules).map(async (facade) => {
187
+ // A facade's own exports; `three` inside one (an addon over the engine) is the facade above.
188
+ const result = await build({ entryPoints: [facade], bundle: true, write: false, format: "esm",
189
+ metafile: true, logLevel: "silent", external: ["three"], plugins: [packageImports] });
190
+ return [facade, Object.values(result.metafile.outputs)[0].exports];
191
+ })));
192
+ const unresolved = new Map();
193
+ const bundled = await build({
194
+ stdin: { contents: boot
195
+ ? `import ${JSON.stringify(resolve(player, "core-host.mjs"))}; import game from "tn:game"; globalThis.tn.__booting = true; void game.start().then(() => { globalThis.tn.__booting = false; game.ctx.renderer.render(game.ctx.scene, game.ctx.camera); }).catch(error => { globalThis.tn.__startupError = String(error.stack ?? error); });`
196
+ : `${host ? `import ${JSON.stringify(resolve(player, "core-host.mjs"))}; ` : ""}import "tn:game";`, resolveDir: repo },
197
+ bundle: true, write: false, format: "iife", platform: "neutral", target: "es2022",
198
+ conditions: ["threenative-native"], define: { "import.meta.env": "{}", ...define }, metafile: true,
199
+ logLevel: "silent", outfile, sourcemap: "external", sourcesContent: true,
200
+ plugins: [packageImports, { name: "native-engine", setup(builder) {
201
+ builder.onResolve({ filter: /(?:^|\/)assets\.js$/ }, (args) => {
202
+ if (args.importer.startsWith(`${resolve(core, "src")}/`))
203
+ return { path: resolve(player, "core-assets.mjs") };
204
+ });
205
+ builder.onResolve({ filter: /^tn:game$/ }, () => ({ path: "game", namespace: "native-game" }));
206
+ builder.onLoad({ filter: /.*/, namespace: "native-game" }, () => ({ contents: code, resolveDir: repo }));
207
+ builder.onResolve({ filter: /^@threenative\/core$/ }, () => ({ path: "core", namespace: "native-core" }));
208
+ builder.onLoad({ filter: /.*/, namespace: "native-core" }, () => ({ contents: coreExports, resolveDir: repo }));
209
+ builder.onResolve({ filter: /^@threenative\/core\// }, (args) => ({
210
+ path: resolve(core, "src", `${args.path.split("/").at(-1)}.ts`),
211
+ }));
212
+ builder.onResolve({ filter: /^(three(?:\/|$)|three-mesh-bvh(?:\/|$))/ }, async (args) => {
213
+ const source = args.namespace === "native-game" ? code : await readFile(args.importer, "utf8");
214
+ const names = imports(source, args.path);
215
+ const path = JSON.stringify([args.path, names]);
216
+ unresolved.set(path, { specifier: args.path, names });
217
+ return { path, namespace: "native-import" };
218
+ });
219
+ builder.onLoad({ filter: /.*/, namespace: "native-import" }, async (args) => {
220
+ const { specifier, names } = unresolved.get(args.path);
221
+ // three ships each addon under `addons/` and under its older `examples/jsm/` path.
222
+ const facade = modules[specifier.replace(/^three\/examples\/jsm\//, "three/addons/")];
223
+ // Missing symbols are temporary compiler inputs only. Their unique diagnostics survive
224
+ // precisely when a live import uses them; the artifact is refused below, never emitted.
225
+ const known = exports.get(facade) ?? [];
226
+ return { contents: [
227
+ ...(facade ? [`export * from ${JSON.stringify(facade)};`] : []),
228
+ ...names.filter((name) => !known.includes(name)).map((name) => {
229
+ const error = JSON.stringify(unboundDiagnostic(specifier, name));
230
+ if (name === "*") return `throw new Error(${error});`;
231
+ if (name === "default") return `export default function() { throw new Error(${error}); }`;
232
+ return `export function ${name}() { throw new Error(${error}); }`;
233
+ }),
234
+ ...(!facade && names.length === 0 ? [`throw new Error(${JSON.stringify(unboundDiagnostic(specifier, "*"))});`] : []),
235
+ ].join("\n"), resolveDir: repo };
236
+ });
237
+ } }],
238
+ });
239
+ const output = bundled.outputFiles.find((file) => file.path === outfile).text;
240
+ const sourceMap = bundled.outputFiles.find((file) => file.path === `${outfile}.map`).text;
241
+ const missing = [...new Set(output.match(/TN_NATIVE_ENGINE_UNBOUND: [^"\n]+/g) ?? [])].sort();
242
+ if (missing.length) throw new Error(missing.join("\n"));
243
+ rejectUpstream(bundled.metafile);
244
+ await mkdir(dirname(outfile), { recursive: true });
245
+ const temporary = `${outfile}.${randomUUID()}.tmp`;
246
+ const temporaryMap = `${temporary}.map`;
247
+ try {
248
+ await writeFile(temporaryMap, sourceMap, { flag: "wx" });
249
+ await writeFile(temporary, output, { flag: "wx" });
250
+ await rename(temporaryMap, `${outfile}.map`);
251
+ await rename(temporary, outfile);
252
+ } finally {
253
+ await unlink(temporaryMap).catch((error) => { if (error.code !== "ENOENT") throw error; });
254
+ await unlink(temporary).catch((error) => { if (error.code !== "ENOENT") throw error; });
255
+ }
256
+ return { outfile, engineCommit, bytes: Buffer.byteLength(output), profile: { engine: "native", gameRuntime: "v8" } };
257
+ }
258
+
259
+ /**
260
+ * Cooks a project's assets for the native engine beside the game bundle: its own `assets` config,
261
+ * decoder-free (the engine's loaders decode no meshopt or KTX2), with the native package on, which
262
+ * the player reads from `<bundle dir>/native/assets.tnpk`. `source` overrides the config's source dir.
263
+ */
264
+ export async function cookNativeEngineAssets({ project, outfile, source }) {
265
+ project = resolve(project);
266
+ const config = resolve(project, "threenative.config.ts");
267
+ let assets = {};
268
+ if (existsSync(config)) {
269
+ const built = await build({ entryPoints: [config], bundle: true, write: false, format: "esm",
270
+ platform: "node", logLevel: "silent", packages: "external" });
271
+ const module = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString("base64")}`);
272
+ assets = module.default?.assets ?? {};
273
+ }
274
+ const { compileAssets } = await import(assetsEntry);
275
+ await compileAssets({ cwd: project, config: { ...assets, ...(source && { source: resolve(source) }), nativePackage: true }, platform: "desktop",
276
+ runtimeDecoders: { ktx2: false, meshopt: false } });
277
+ const output = resolve(project, assets.output ?? "public", "native/assets.tnpk");
278
+ const target = resolve(dirname(resolve(outfile)), "native/assets.tnpk");
279
+ await mkdir(dirname(target), { recursive: true });
280
+ await writeFile(target, await readFile(output));
281
+ return target;
282
+ }
283
+
284
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
285
+ const args = process.argv.slice(2);
286
+ const flags = new Map();
287
+ for (let i = 0; i < args.length; i += 2) {
288
+ if (!["--entry", "--out", "--engine", "--game-runtime", "--assets", "--asset-source"].includes(args[i]) || !args[i + 1] || flags.has(args[i]))
289
+ throw new Error(`TN_NATIVE_ENGINE_ARGS: invalid or repeated option ${args[i]}`);
290
+ flags.set(args[i], args[i + 1]);
291
+ }
292
+ if (flags.get("--engine") !== "native" || flags.get("--game-runtime") !== "v8" || !flags.get("--entry") || !flags.get("--out"))
293
+ throw new Error("Usage: bundle-native-engine.mjs --engine native --game-runtime v8 --entry <src/game.ts> --out <game.js> [--assets <project dir> [--asset-source <dir>]]");
294
+ try {
295
+ console.log(JSON.stringify(await bundleNativeEngine({ entry: flags.get("--entry"), outfile: flags.get("--out") })));
296
+ if (flags.has("--assets"))
297
+ console.log(JSON.stringify({ assets: await cookNativeEngineAssets({ project: flags.get("--assets"), outfile: flags.get("--out"),
298
+ source: flags.get("--asset-source") }) }));
299
+ } catch (error) {
300
+ console.error(error.message);
301
+ process.exitCode = 1;
302
+ }
303
+ }
@@ -148,52 +148,40 @@ function generateVFSHeader(files, outputPath) {
148
148
  }
149
149
 
150
150
  /**
151
- * Three's compressed-asset decoders that cannot run on a mobile native target.
152
- *
153
- * Android runs QuickJS and iOS runs JavaScriptCore without a WASM JIT: neither has
154
- * `WebAssembly`, so the Basis/zstd transcoder behind `KTX2Loader`, the Meshopt decoder and
155
- * Draco's wasm decoder have nothing to instantiate there. Their specifiers are static strings
156
- * inside `await import(...)`, so a bundler resolves and inlines them whether or not the game
157
- * ships a single compressed asset — which is how one `.ktx2`-free game came to fail
158
- * `TN_NATIVE_WASM_ON_MOBILE`. Replacing them here keeps that guard intact by keeping WASM out
159
- * of the bundle instead of by ignoring it.
160
- *
161
- * The replacements construct and configure exactly like the originals so a game that ships no
162
- * compressed asset boots normally (`createAssetLoader` builds the shared KTX2 loader eagerly);
163
- * they refuse, by name, only when asked to decode. A game whose compiled assets do need one is
164
- * refused earlier and louder, by `threenative build`, before this bundle is written.
151
+ * Decoder-free targets retain Three's raw KTX2 loader but refuse Basis and ZSTD decoding.
152
+ * A mobile bundle keeps full decoding only for a codec `--decoders` admits; raw KTX2 stays.
153
+ * `threenative build` resolves the list per engine (Android V8: ktx2,meshopt). Desktop QuickJS and an
154
+ * unknown desktop artifact use the same refusing stubs.
165
155
  */
166
156
  const MOBILE_KTX2_MESSAGE =
167
- // Deliberately never spells the WASM host object: `TN_NATIVE_WASM_ON_MOBILE` greps the
168
- // finished bundle for that identifier, and a refusal message must not read as the thing it
169
- // refuses.
170
- "TN_NATIVE_KTX2_UNSUPPORTED: this Android/iOS bundle carries no Basis transcoder, because the mobile native runtime has no WASM engine. Compiled .ktx2 textures cannot be decoded here; native compilation automatically keeps decoder-free authored textures, or keep compressed textures on the web target.";
157
+ // Never spell the WASM host global: the bundle guard must not mistake diagnostics for code.
158
+ "TN_NATIVE_KTX2_UNSUPPORTED: this decoder-free native bundle carries no qualified Basis or ZSTD decoder. Use GPU-ready KTX2 textures without supercompression, or keep transcoded textures on the web target.";
171
159
  const MOBILE_MESH_MESSAGE =
172
- "TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: this Android/iOS bundle carries no Meshopt or Draco decoder, because the mobile native runtime has no WASM engine. Compressed model geometry cannot be decoded here; native compilation keeps shared images and decoder-free model geometry, or keep compressed models on the web target.";
160
+ "TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: this decoder-free native bundle carries no qualified Meshopt or Draco decoder. Compressed model geometry cannot be decoded here; native compilation keeps shared images and decoder-free model geometry, or keep compressed models on the web target.";
173
161
 
174
162
  const MOBILE_DECODER_STUBS = [
175
163
  {
164
+ codec: 'ktx2',
176
165
  endsWith: '/examples/jsm/loaders/KTX2Loader.js',
177
- source: `const message = "${MOBILE_KTX2_MESSAGE}";
178
- export class KTX2Loader {
179
- constructor() { this.transcoderPath = ""; this.workerConfig = undefined; }
180
- setTranscoderPath(path) { this.transcoderPath = path; return this; }
181
- setWorkerLimit() { return this; }
182
- // Support detection is where core asks whether this platform can transcode at all. Throwing
183
- // is the documented "renderer exposed no surface to probe" answer: the asset loader resolves
184
- // its shared loader to undefined and the game boots without compressed textures.
185
- detectSupport() { throw new Error(message); }
186
- load(url, onLoad, onProgress, onError) {
187
- const error = new Error(\`\${message} (requested '\${url}')\`);
188
- if (typeof onError === "function") onError(error);
189
- else throw error;
190
- }
191
- parse() { throw new Error(message); }
192
- dispose() { return this; }
166
+ // The private query bypasses this exact-path replacement once; upstream owns raw parsing.
167
+ source: (id) => `import { KTX2Loader as RawKTX2Loader } from ${JSON.stringify(`${id}?threenative-raw-ktx2`)};
168
+ export class KTX2Loader extends RawKTX2Loader {
169
+ init() { return Promise.reject(new Error(${JSON.stringify(MOBILE_KTX2_MESSAGE)})); }
193
170
  }
194
171
  `,
195
172
  },
196
173
  {
174
+ codec: 'ktx2',
175
+ endsWith: '/examples/jsm/libs/zstddec.module.js',
176
+ source: `export class ZSTDDecoder {
177
+ // Upstream awaits init inside an async Promise executor; reject at decode to avoid hanging.
178
+ init() { return Promise.resolve(); }
179
+ decode() { throw new Error(${JSON.stringify(MOBILE_KTX2_MESSAGE)}); }
180
+ }
181
+ `,
182
+ },
183
+ {
184
+ codec: 'meshopt',
197
185
  endsWith: '/examples/jsm/libs/meshopt_decoder.module.js',
198
186
  source: `const message = "${MOBILE_MESH_MESSAGE}";
199
187
  function refuse() { throw new Error(message); }
@@ -210,6 +198,7 @@ export const MeshoptDecoder = {
210
198
  `,
211
199
  },
212
200
  {
201
+ codec: 'draco',
213
202
  endsWith: '/examples/jsm/loaders/DRACOLoader.js',
214
203
  source: `const message = "${MOBILE_MESH_MESSAGE}";
215
204
  export class DRACOLoader {
@@ -235,15 +224,18 @@ export class DRACOLoader {
235
224
  * the same file — `three/addons/...`, `three/examples/jsm/...`, or a relative import from
236
225
  * inside three — lands on the same replacement.
237
226
  */
238
- function mobileDecoderStub(id) {
227
+ function mobileDecoderStub(id, admitted) {
239
228
  const normalized = id.split('\\').join('/');
240
- return MOBILE_DECODER_STUBS.find((stub) => normalized.endsWith(stub.endsWith))?.source;
229
+ const stub = MOBILE_DECODER_STUBS.find(
230
+ (stub) => normalized.endsWith(stub.endsWith) && !admitted.includes(stub.codec),
231
+ );
232
+ return typeof stub?.source === 'function' ? stub.source(id) : stub?.source;
241
233
  }
242
234
 
243
235
  /**
244
236
  * Main
245
237
  */
246
- async function bundleProject(project, entryPoint, outputPath, target, nativeBackend) {
238
+ async function bundleProject(project, entryPoint, outputPath, target, nativeBackend, decoders = []) {
247
239
  const absoluteProject = resolve(project);
248
240
  const absoluteEntry = resolve(absoluteProject, entryPoint);
249
241
  const absoluteOutput = resolve(outputPath);
@@ -311,7 +303,7 @@ if (typeof globalThis.requestAnimationFrame === "function") {
311
303
  name: 'threenative-mobile-decoders',
312
304
  enforce: 'pre',
313
305
  load(id) {
314
- const stub = mobileDecoderStub(id);
306
+ const stub = mobileDecoderStub(id, decoders);
315
307
  return stub === undefined ? null : stub;
316
308
  },
317
309
  };
@@ -340,7 +332,7 @@ void game.start().catch((error) => console.error(
340
332
  root: absoluteProject,
341
333
  define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
342
334
  plugins:
343
- target === 'desktop'
335
+ target === 'desktop' && !nativeBackend
344
336
  ? [importMetaPlugin, nativeEntryPlugin]
345
337
  : [importMetaPlugin, mobileDecodersPlugin, nativeEntryPlugin],
346
338
  // One three, whatever the import graph looks like. The game resolves `three` beside itself
@@ -411,6 +403,7 @@ async function main() {
411
403
  let project = null;
412
404
  let target = null;
413
405
  let nativeBackend = false;
406
+ let decoders = [];
414
407
 
415
408
  for (let i = 0; i < args.length; i++) {
416
409
  if (args[i] === '--entry' && args[i + 1]) {
@@ -425,6 +418,10 @@ async function main() {
425
418
  target = args[++i];
426
419
  } else if (args[i] === '--native-backend') {
427
420
  nativeBackend = true;
421
+ } else if (args[i] === '--decoders' && args[i + 1] !== undefined) {
422
+ decoders = args[++i].split(',').filter((codec) => codec.length > 0);
423
+ const unknown = decoders.filter((codec) => !MOBILE_DECODER_STUBS.some((stub) => stub.codec === codec));
424
+ if (unknown.length > 0) throw new Error(`--decoders names unknown codec(s): ${unknown.join(', ')}`);
428
425
  }
429
426
  }
430
427
 
@@ -433,7 +430,7 @@ async function main() {
433
430
  if (!['android', 'desktop', 'ios'].includes(target)) {
434
431
  throw new Error('--project requires --target android|desktop|ios.');
435
432
  }
436
- await bundleProject(project, entryPoint, outputDir, target, nativeBackend);
433
+ await bundleProject(project, entryPoint, outputDir, target, nativeBackend, decoders);
437
434
  return;
438
435
  }
439
436
 
@@ -65,15 +65,21 @@ export function checkSourceList({ cmakeSource, sourceRoot, sourcePaths } = {}) {
65
65
  return { unlisted, missing, excluded: [...excluded].sort() };
66
66
  }
67
67
 
68
+ /** CMakeLists.txt plus the modules it includes (cmake/NativeEngine.cmake lists engine sources). */
69
+ export function readCmakeSource(packageRoot) {
70
+ const cmakeModules = join(packageRoot, "cmake");
71
+ const modules = readdirSync(cmakeModules)
72
+ .filter((name) => name.endsWith(".cmake"))
73
+ .sort()
74
+ .map((name) => readFileSync(join(cmakeModules, name), "utf8"));
75
+ return [readFileSync(join(packageRoot, "CMakeLists.txt"), "utf8"), ...modules].join("\n");
76
+ }
77
+
68
78
  function main() {
69
79
  const scriptDirectory = dirname(fileURLToPath(import.meta.url));
70
80
  const packageRoot = resolve(scriptDirectory, "..");
71
- const cmakePath = join(packageRoot, "CMakeLists.txt");
72
81
  const sourceRoot = join(packageRoot, "src");
73
- const report = checkSourceList({
74
- cmakeSource: readFileSync(cmakePath, "utf8"),
75
- sourceRoot,
76
- });
82
+ const report = checkSourceList({ cmakeSource: readCmakeSource(packageRoot), sourceRoot });
77
83
  if (report.unlisted.length > 0 || report.missing.length > 0) {
78
84
  if (report.unlisted.length > 0)
79
85
  console.error(`Unlisted native C++ sources: ${report.unlisted.join(", ")}`);
@@ -852,11 +852,16 @@ export function packageDesktopContainer({
852
852
  const format = desktopContainerFormat(platform);
853
853
  if (!output) throw new Error('TN_DESKTOP_OUTPUT_MISSING: packageDesktopContainer needs an output path.');
854
854
  assertFile(executable, 'desktop executable');
855
- if (uiRenderer === 'web') {
855
+ if (uiRenderer === 'web' || uiRenderer === 'native-css') {
856
856
  assertDirectory(uiDirectory, 'built UI bundle');
857
- if (!existsSync(join(uiDirectory, 'index.html'))) {
857
+ // The web renderer loads a page; the native-css renderer paints stylesheets in the game's own
858
+ // JS realm and ships no page at all.
859
+ if (uiRenderer === 'web' && !existsSync(join(uiDirectory, 'index.html'))) {
858
860
  throw new Error(`TN_UI_BUNDLE_MISSING: ${uiDirectory} has no index.html, which is the page the overlay loads.`);
859
861
  }
862
+ if (uiRenderer === 'native-css' && listFiles(uiDirectory).every((file) => !file.relative.endsWith('.css'))) {
863
+ throw new Error(`TN_UI_BUNDLE_MISSING: ui.renderer is "native-css" but ${uiDirectory} has no .css to paint.`);
864
+ }
860
865
  } else if (uiDirectory) {
861
866
  throw new Error(`TN_UI_BUNDLE_UNEXPECTED: a UI bundle was staged for a game whose ui.renderer is '${uiRenderer}'.`);
862
867
  }
@@ -890,15 +895,24 @@ export function packageDesktopContainer({
890
895
  record(paths.bundle);
891
896
 
892
897
  let ui = null;
893
- if (uiRenderer === 'web') {
898
+ if (uiRenderer === 'web' || uiRenderer === 'native-css') {
894
899
  for (const file of listFiles(uiDirectory)) {
895
900
  const destination = `${paths.ui}/${file.relative}`;
896
901
  mkdirSync(dirname(stage(destination)), { recursive: true });
897
902
  copyFileSync(file.absolute, stage(destination));
898
903
  record(destination);
899
904
  }
900
- ui = { directory: paths.ui, entry: `${paths.ui}/index.html` };
901
- if (!existsSync(stage(ui.entry))) throw new Error('TN_UI_BUNDLE_MISSING: no index.html staged for the web renderer.');
905
+ // The web renderer's entry is the page the overlay loads; the native-css one is its first
906
+ // stylesheet, which is what the manifest can name as a single required resource.
907
+ const entry =
908
+ uiRenderer === 'web'
909
+ ? 'index.html'
910
+ : listFiles(uiDirectory)
911
+ .map((file) => file.relative)
912
+ .sort()[0];
913
+ if (entry === undefined) throw new Error('TN_UI_BUNDLE_MISSING: nothing staged for the UI renderer.');
914
+ ui = { directory: paths.ui, entry: `${paths.ui}/${entry}` };
915
+ if (!existsSync(stage(ui.entry))) throw new Error(`TN_UI_BUNDLE_MISSING: no ${entry} staged for ${uiRenderer}.`);
902
916
  }
903
917
 
904
918
  const bundled = [];