@threenative/runtime-native 0.3.2 → 0.3.4

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.
@@ -1,5 +1,5 @@
1
1
  // Top-level build file for MystralNative Android project
2
2
  plugins {
3
- id("com.android.application") version "8.2.2" apply false
3
+ id("com.android.application") version "8.11.1" apply false
4
4
  id("org.jetbrains.kotlin.android") version "1.9.22" apply false
5
5
  }
@@ -1,6 +1,6 @@
1
1
  distributionBase=GRADLE_USER_HOME
2
2
  distributionPath=wrapper/dists
3
- distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
4
- distributionSha256Sum=9d926787066a081739e8200858338b4a69e837c3a821a33aca9db09dd4a41026
3
+ distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
4
+ distributionSha256Sum=20f1b1176237254a6fc204d8434196fa11a4cfb387567519c61556e8710aed78
5
5
  zipStoreBase=GRADLE_USER_HOME
6
6
  zipStorePath=wrapper/dists
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@threenative/runtime-native",
3
- "version": "0.3.2",
4
- "description": "ThreeNative-owned native host for desktop, Android, and iOS",
3
+ "version": "0.3.4",
4
+ "description": "ThreeNative-owned native host for desktop and Android",
5
5
  "keywords": [
6
6
  "threenative",
7
7
  "native",
@@ -42,10 +42,17 @@
42
42
  "android/gradle/wrapper/gradle-wrapper.properties",
43
43
  "android/gradlew",
44
44
  "android/settings.gradle.kts",
45
+ "scripts/asset-manifest.mjs",
45
46
  "scripts/asset-preflight.mjs",
46
47
  "scripts/bundle.mjs",
48
+ "scripts/check-android-16kb-alignment.mjs",
47
49
  "scripts/check-source-list.mjs",
50
+ "scripts/desktop-distribution.mjs",
51
+ "scripts/windows-installer.mjs",
52
+ "scripts/windows-installer.nsi",
48
53
  "scripts/device-preflight.mjs",
54
+ "scripts/inspect-container-brand.mjs",
55
+ "scripts/inspect-macos-icon.mjs",
49
56
  "scripts/install-prebuilt.mjs",
50
57
  "scripts/package-android.mjs",
51
58
  "scripts/package-desktop.mjs",
@@ -54,7 +61,10 @@
54
61
  "scripts/production-evidence.mjs",
55
62
  "scripts/profile-production.mjs",
56
63
  "scripts/qualify-physical-mobile.mjs",
64
+ "scripts/verify-starter-consumer.mjs",
65
+ "scripts/verify-starter-desktop-base.mjs",
57
66
  "scripts/verify-starter-desktop.mjs",
67
+ "scripts/verify-windows-installer.mjs",
58
68
  "scripts/xvfb.sh"
59
69
  ],
60
70
  "devDependencies": {
@@ -62,7 +72,7 @@
62
72
  "publint": "0.3.22",
63
73
  "three": "0.185.1",
64
74
  "vitest": "4.1.10",
65
- "@threenative/playtest": "0.3.2"
75
+ "@threenative/playtest": "0.3.4"
66
76
  },
67
77
  "dependencies": {
68
78
  "pngjs": "7.0.0"
@@ -81,9 +91,12 @@
81
91
  "native:physics:parity": "pnpm --dir ../.. exec vitest run packages/physics/__tests__/parity.spec.ts && cargo test --manifest-path native/physics/Cargo.toml --lib --test parity -- --nocapture",
82
92
  "native:physics:parity:device": "node scripts/verify-android-physics-parity.mjs",
83
93
  "native:qualify:physical": "node scripts/qualify-physical-mobile.mjs",
84
- "native:verify:desktop": "node scripts/verify-desktop-audio.mjs && node scripts/verify-desktop-stability.mjs && node scripts/verify-desktop-core.mjs && node scripts/verify-desktop-physics.mjs && sh ../../scripts/xvfb.sh node scripts/verify-native-contracts.mjs && pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-loading.mjs",
94
+ "native:verify:desktop": "node scripts/verify-desktop-audio.mjs && node scripts/verify-desktop-stability.mjs && node scripts/verify-desktop-core.mjs && node scripts/verify-desktop-physics.mjs && sh ../../scripts/xvfb.sh node scripts/verify-native-contracts.mjs && pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-loading.mjs && sh ../../scripts/xvfb.sh node scripts/verify-desktop-ui-frame.mjs && vitest run --config vitest.config.ts tests/external-bundle-discovery.test.mjs",
95
+ "native:verify:metahuman": "node scripts/verify-desktop-metahuman.mjs",
85
96
  "native:verify:loading": "pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-loading.mjs",
97
+ "native:verify:ui-frame": "pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-ui-frame.mjs",
86
98
  "native:verify:android:multitouch": "pnpm --dir ../playtest build && node scripts/verify-android-multitouch.mjs",
99
+ "native:verify:android:artifact": "node scripts/check-android-16kb-alignment.mjs",
87
100
  "profile:production": "node scripts/profile-production.mjs",
88
101
  "parity": "node conformance/run-conformance.mjs",
89
102
  "install": "node scripts/install-prebuilt.mjs",
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Which files in a compiled asset directory the packagers stage.
3
+ *
4
+ * `threenative build` compiles a project's assets into its output root (`public/`) beside a
5
+ * manifest (`assets.manifest.json`) and a receipt (`bake.receipt.json`). Copying only what the
6
+ * build named was the first attempt and it broke real games: measured on real sandbox builds,
7
+ * `public/` holds hand-placed runtime files the manifest never names — wildwood's 536 files
8
+ * including `audio/*.ogg`, fps-framework's 100 `.glb`/`.jpg`, lumen-hall's and menu-spike's
9
+ * `basis/basis_transcoder.*`. Dropping those breaks KTX2 on native.
10
+ *
11
+ * So the rule is inverted: keep everything EXCEPT what is provably not shipped, and print every skip.
12
+ *
13
+ * 1. Editor and VCS leftovers anywhere in the tree, by basename — `*.orig`, `*.rej`, `*.bak`,
14
+ * `*.swp`, `*~`, `.DS_Store`, `Thumbs.db`, `.gitkeep`.
15
+ * 2. Digest outputs, only when a manifest is present: any `<stem>.<8 hex>.<ext>` the current
16
+ * manifest and receipt do not name. That is the compiler's own naming space, so a file wearing
17
+ * it is a cook output — and one this cook did not emit is a leftover of a previous one, whose
18
+ * bytes no game loads. It is reported with the file it would have replaced when a same-stem,
19
+ * same-extension sibling does exist.
20
+ * 3. Everything else, including hand-placed files and the bookkeeping the runtime needs
21
+ * (the manifest and the bake receipt both ship, as they did before this rule).
22
+ *
23
+ * A file the manifest names but disk lacks fails closed with `TN_ASSETS_MANIFEST_MISSING`. With
24
+ * no manifest, rule 1 still applies and rule 2 does not.
25
+ *
26
+ * One selector, every target: the three native packagers stage through this function, and
27
+ * `threenative build --target web` deletes the `dropped` set from the Vite outDir, which copies
28
+ * the whole output root.
29
+ */
30
+
31
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
32
+ import { basename, dirname, join, posix } from "node:path";
33
+
34
+ export const ASSET_MANIFEST_NAME = "assets.manifest.json";
35
+ const RECEIPT_NAME = "bake.receipt.json";
36
+
37
+ /** Basenames that are always an editor's or a VCS's dropping, never a shipped asset. */
38
+ const LEFTOVER_NAMES = new Set([".DS_Store", "Thumbs.db", ".gitkeep"]);
39
+ const LEFTOVER_SUFFIXES = [".orig", ".rej", ".bak", ".swp", "~"];
40
+ /** `<stem>.<8 lowercase hex>.<ext>` — the shape `threenative build` writes a compiled digest as. */
41
+ const DIGEST = /^(?<stem>.+)\.(?<hash>[0-9a-f]{8})\.(?<ext>[^.]+)$/u;
42
+
43
+ /**
44
+ * Every file under `directory`, as `/`-separated paths relative to it, sorted.
45
+ *
46
+ * A symlink or any other non-file entry is refused rather than silently dropped: a package that
47
+ * quietly omits an input is the failure this whole file exists to prevent.
48
+ */
49
+ export function listFiles(directory, relative = "") {
50
+ const files = [];
51
+ for (const entry of readdirSync(join(directory, relative), { withFileTypes: true })) {
52
+ const path = relative ? posix.join(relative, entry.name) : entry.name;
53
+ if (entry.isDirectory()) files.push(...listFiles(directory, path));
54
+ else if (entry.isFile()) files.push(path);
55
+ else throw new Error(`Unsupported asset entry: ${join(directory, path)}`);
56
+ }
57
+ return files.sort();
58
+ }
59
+
60
+ /** The paths one manifest entry names beyond its own `output`: array fields carrying records. */
61
+ function entryOutputs(entry) {
62
+ if (!entry || typeof entry !== "object") return [];
63
+ const outputs = [];
64
+ if (typeof entry.output === "string") outputs.push(entry.output);
65
+ for (const field of Object.values(entry)) {
66
+ if (!Array.isArray(field)) continue;
67
+ for (const auxiliary of field) {
68
+ if (
69
+ auxiliary &&
70
+ typeof auxiliary === "object" &&
71
+ typeof auxiliary.output === "string"
72
+ )
73
+ outputs.push(auxiliary.output);
74
+ }
75
+ }
76
+ return outputs;
77
+ }
78
+
79
+ /** The payloads the bake's receipt owns beyond the manifest, or none when it is absent or unreadable. */
80
+ function readReceiptOutputs(receiptPath) {
81
+ if (!existsSync(receiptPath)) return [];
82
+ try {
83
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
84
+ return Array.isArray(receipt?.outputs)
85
+ ? receipt.outputs.flatMap((output) =>
86
+ typeof output?.path === "string" ? [output.path] : [],
87
+ )
88
+ : [];
89
+ } catch {
90
+ // A corrupt receipt must not fail the package; the manifest still governs, and it is the file
91
+ // the runtime reads. The receipt's own bytes still ship with the rest of the directory.
92
+ return [];
93
+ }
94
+ }
95
+
96
+ /** An editor's or VCS's dropping, keyed by basename anywhere in the tree. */
97
+ function isEditorLeftover(file) {
98
+ const name = basename(file);
99
+ return LEFTOVER_NAMES.has(name) || LEFTOVER_SUFFIXES.some((suffix) => name.endsWith(suffix));
100
+ }
101
+
102
+ /** The `<stem>, <hash>, <ext>` a digest-shaped basename carries, or `null` when it is not one. */
103
+ function digestParts(file) {
104
+ const match = DIGEST.exec(basename(file));
105
+ return match === null
106
+ ? null
107
+ : { stem: match.groups.stem, hash: match.groups.hash, ext: match.groups.ext };
108
+ }
109
+
110
+ /**
111
+ * The manifest-named path that supersedes `file`, or `null` when nothing does.
112
+ *
113
+ * Only a same-directory named file with the same `<stem>` and `<ext>` but a different hash
114
+ * supersedes; the answer is only used to name the replacement in the skip line.
115
+ */
116
+ function supersededBy(file, named) {
117
+ const digest = digestParts(file);
118
+ if (digest === null) return null;
119
+ const directory = dirname(file);
120
+ for (const candidate of [...named].sort()) {
121
+ if (candidate === file || dirname(candidate) !== directory) continue;
122
+ const other = digestParts(candidate);
123
+ if (other !== null && other.stem === digest.stem && other.ext === digest.ext) return candidate;
124
+ }
125
+ return null;
126
+ }
127
+
128
+ /**
129
+ * What one packaging run stages: the files to copy, the files it dropped, and how many of the
130
+ * kept ones no manifest or receipt declared — a hand-placed runtime file, which is legitimate
131
+ * and is reported so the number is never a surprise inside an APK.
132
+ */
133
+ export function selectManifestAssets(assets, { log = console.log } = {}) {
134
+ const manifestPath = join(assets, ASSET_MANIFEST_NAME);
135
+ const hasManifest = existsSync(manifestPath);
136
+ const named = new Set();
137
+ if (hasManifest) {
138
+ let manifest;
139
+ try {
140
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
141
+ } catch (error) {
142
+ throw new Error(
143
+ `TN_ASSETS_MANIFEST_INVALID: '${manifestPath}' is not valid JSON: ${
144
+ error instanceof Error ? error.message : String(error)
145
+ }`,
146
+ );
147
+ }
148
+ if (
149
+ manifest?.version !== 1 ||
150
+ typeof manifest.entries !== "object" ||
151
+ manifest.entries === null ||
152
+ Array.isArray(manifest.entries)
153
+ ) {
154
+ throw new Error(`TN_ASSETS_MANIFEST_INVALID: '${manifestPath}' must hold version 1 entries.`);
155
+ }
156
+ for (const entry of Object.values(manifest.entries))
157
+ for (const output of entryOutputs(entry)) named.add(output);
158
+ for (const output of readReceiptOutputs(join(assets, RECEIPT_NAME))) named.add(output);
159
+ }
160
+
161
+ const present = listFiles(assets);
162
+ if (hasManifest) {
163
+ for (const file of [...named].sort()) {
164
+ if (!present.includes(file)) {
165
+ throw new Error(
166
+ `TN_ASSETS_MANIFEST_MISSING: '${file}' is named by '${ASSET_MANIFEST_NAME}' but was not found under ${assets}.`,
167
+ );
168
+ }
169
+ }
170
+ }
171
+
172
+ const selected = [];
173
+ const dropped = [];
174
+ const unmanaged = [];
175
+ for (const file of present) {
176
+ if (hasManifest && named.has(file)) {
177
+ selected.push(file);
178
+ continue;
179
+ }
180
+ if (isEditorLeftover(file)) {
181
+ log(`ThreeNative packaging: skipped ${file} (editor leftover)`);
182
+ dropped.push(file);
183
+ continue;
184
+ }
185
+ if (hasManifest && digestParts(file) !== null) {
186
+ const superseding = supersededBy(file, named);
187
+ log(
188
+ `ThreeNative packaging: skipped ${file} (cook output this build does not declare${
189
+ superseding === null ? "" : `, superseded by ${superseding}`
190
+ })`,
191
+ );
192
+ dropped.push(file);
193
+ continue;
194
+ }
195
+ selected.push(file);
196
+ if (!named.has(file)) unmanaged.push(file);
197
+ }
198
+ // Only a project with a manifest can be unmanaged relative to one; without it, the whole
199
+ // directory is hand-placed by definition and the line would name every file in the game.
200
+ if (hasManifest && unmanaged.length > 0) {
201
+ const bytes = unmanaged.reduce((total, file) => total + statSync(join(assets, file)).size, 0);
202
+ log(
203
+ `ThreeNative packaging: ${unmanaged.length} unmanaged file(s), ${bytes} bytes, are not declared by ${ASSET_MANIFEST_NAME}.`,
204
+ );
205
+ return { dropped, selected, unmanagedBytes: bytes, unmanagedFiles: unmanaged.length };
206
+ }
207
+ return { dropped, selected, unmanagedBytes: 0, unmanagedFiles: 0 };
208
+ }
209
+
@@ -32,7 +32,9 @@
32
32
  * been built with decoders this file does not know about yet.
33
33
  */
34
34
 
35
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
35
+ import { spawnSync } from 'node:child_process';
36
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
37
+ import { tmpdir } from 'node:os';
36
38
  import { join, posix, extname } from 'node:path';
37
39
 
38
40
  /**
@@ -46,14 +48,110 @@ import { join, posix, extname } from 'node:path';
46
48
  * from the same facts CMake reads.
47
49
  */
48
50
 
51
+
52
+ /**
53
+ * What the INSTALLED runtime can decode, asked of the binary that will actually run the game.
54
+ *
55
+ * The derivations below read a source checkout, which a consumer does not have: installing the
56
+ * published tarball is the supported path, and there `deriveDesktopWebpSupport` could only say
57
+ * "I cannot tell" — and then refused, which is the same hardcoded staleness this file exists to
58
+ * prevent, only pointing the other way. A release built WITH libwebp was rejecting the very
59
+ * WebP-packed GLBs the documented `gltf-transform webp` pipeline produces.
60
+ *
61
+ * So ask it. The runtime already answers this question on every boot, in
62
+ * `src/runtime-scripts/image-support-init.js`, by the same `canvas.toDataURL("image/webp")` test
63
+ * @loaders.gl uses. Running that one line under `--no-sdl` needs no display and no GPU window,
64
+ * reports the selected desktop binary's compiled feature. It is not Android/device evidence.
65
+ */
66
+
67
+ /**
68
+ * The packaged runtime executable inside an installed prebuilt, for the host running this build.
69
+ *
70
+ * Keyed by the host, never by "whichever prebuilt directory is listed first". An installed release
71
+ * can carry several keys at once, and only the host's own can be executed: asking a win32-x64
72
+ * binary on Linux answers nothing, and asking a desktop binary about Android answers the wrong
73
+ * question confidently. `package-desktop.mjs` refuses any key but the host's, so this is the
74
+ * binary that will run the game.
75
+ */
76
+ function prebuiltExecutable(runtimeRoot, key = `${process.platform}-${process.arch}`) {
77
+ if (!runtimeRoot) return undefined;
78
+ // Host keyed: the installer names desktop payloads by OS and architecture, and a neighbouring
79
+ // target's executable cannot establish support for the host that will run this build. The
80
+ // candidate has to be a file, not a directory.
81
+ const prebuilt = join(runtimeRoot, 'prebuilt', key);
82
+ try {
83
+ for (const name of ['threenative-runtime', 'threenative-runtime.exe', 'mystral', 'mystral.exe']) {
84
+ const candidate = join(prebuilt, name);
85
+ if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
86
+ }
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ /**
94
+ * Ask an installed prebuilt runtime which image decoders it was built with.
95
+ *
96
+ * Returns `undefined` when there is nothing to ask or the question could not be put — the caller
97
+ * then keeps its existing refusal, so a probe that cannot run never *grants* support.
98
+ */
99
+ export function probePrebuiltDecoders(runtimeRoot, options = {}) {
100
+ const executable = options.executable ?? prebuiltExecutable(runtimeRoot, options.key);
101
+ if (executable === undefined || !existsSync(executable)) return undefined;
102
+ let directory;
103
+ try {
104
+ if (!statSync(executable).isFile()) return undefined;
105
+ directory = mkdtempSync(join(tmpdir(), 'tn-decoder-probe-'));
106
+ const script = join(directory, 'probe.js');
107
+ writeFileSync(
108
+ script,
109
+ 'const c = document.createElement("canvas");\n' +
110
+ 'const webp = c && c.toDataURL ? c.toDataURL("image/webp").indexOf("data:image/webp") === 0 : false;\n' +
111
+ 'console.log(`TN_DECODERS:{"webp":${webp}}`);\n',
112
+ );
113
+ const run = (options.spawn ?? spawnSync)(executable, ['run', script, '--no-sdl', '--frames', '1', '--quiet'], {
114
+ encoding: 'utf8',
115
+ timeout: options.timeoutMs ?? 30_000,
116
+ maxBuffer: 64 * 1024,
117
+ // The feature probe must neither inherit a display nor launch an unrelated game bundle.
118
+ env: { ...process.env, DISPLAY: undefined, WAYLAND_DISPLAY: undefined, MYSTRAL_BUNDLE: undefined },
119
+ });
120
+ // A run that failed to spawn, crashed, timed out or was signalled answers nothing. A decoder
121
+ // line salvaged from a failed run is not the binary's verdict, and reading one as an answer
122
+ // would let a broken probe grant support the runtime does not have.
123
+ if (run.error || run.signal || run.status !== 0) return undefined;
124
+ // Native console.log emits "[log] "; accept only that owned prefix or a plain receipt.
125
+ // A quoted diagnostic, duplicate receipt, malformed payload or absent field is not evidence.
126
+ const output = `${run.stdout ?? ''}\n${run.stderr ?? ''}`;
127
+ const lines = [...output.matchAll(/^(?:\[log\] )?TN_DECODERS:(\{[^\r\n]*\})\r?$/gmu)];
128
+ if (lines.length !== 1) return undefined;
129
+ const payload = JSON.parse(lines[0][1]);
130
+ if (Object.keys(payload).length !== 1 || typeof payload.webp !== 'boolean') return undefined;
131
+ return { webp: payload.webp, executable };
132
+ } catch {
133
+ return undefined;
134
+ } finally {
135
+ // The probe script is a temporary file, not an artifact: leaving one per build behind fills
136
+ // the packaging host's temp directory over a session of repeated builds.
137
+ if (directory !== undefined) rmSync(directory, { force: true, recursive: true });
138
+ }
139
+ }
140
+
49
141
  /** Mirrors the ANDROID branch of the libwebp block in CMakeLists.txt. */
50
142
  export function deriveAndroidWebpSupport(runtimeSource) {
51
143
  if (!runtimeSource || !existsSync(join(runtimeSource, 'CMakeLists.txt'))) {
144
+ // Deliberately no probe here. The desktop branch asks the binary that will run the game; the
145
+ // Android runtime is an arm64 payload this host cannot execute, so the only executable a probe
146
+ // could reach is the host's desktop build — a different CMake configuration answering a
147
+ // different question. Granting Android WebP from it would be the same stale claim this file
148
+ // exists to prevent, arrived at by a longer route. Unknown stays unknown.
52
149
  return {
53
150
  supported: false,
54
151
  reason:
55
- `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, and a prebuilt ` +
56
- 'Android release does not declare which decoders it was built with',
152
+ `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, a prebuilt ` +
153
+ 'Android release does not declare which decoders it was built with, and no host binary ' +
154
+ 'can answer for it',
57
155
  };
58
156
  }
59
157
  const sourceRoot = join(runtimeSource, 'third_party', 'webp-source');
@@ -92,13 +190,46 @@ export function deriveAndroidWebpSupport(runtimeSource) {
92
190
  * `third_party/webp/libwebp-*` with both a library and headers, which is what CMake's
93
191
  * `WEBP_LIBRARY AND WEBP_INCLUDE_DIR` requires before it defines `MYSTRAL_HAS_WEBP`.
94
192
  */
95
- export function deriveDesktopWebpSupport(runtimeSource) {
193
+ export function deriveDesktopWebpSupport(runtimeSource, runtimeExecutable = undefined) {
194
+ // A selected runtime outranks anything a directory listing suggests, source checkout or not: it
195
+ // is the binary this container ships and the one that will decode the player's textures. A
196
+ // checkout can hold libwebp sources downloaded *after* that binary was built — `download-deps
197
+ // --only webp` then a repackage is a normal sequence — and reading the directory would grant
198
+ // WebP for a runtime compiled without MYSTRAL_HAS_WEBP, turning a build-time refusal into a
199
+ // texture that fails at play.
200
+ if (runtimeExecutable !== undefined) {
201
+ const probed = probePrebuiltDecoders(runtimeSource, { executable: runtimeExecutable });
202
+ if (probed !== undefined) {
203
+ return {
204
+ supported: probed.webp,
205
+ reason: `${probed.executable} answers the @loaders.gl WebP decode test with ` +
206
+ `${probed.webp ? 'YES' : 'NO'}`,
207
+ };
208
+ }
209
+ // Fail closed. A probe that could not run has granted nothing, and falling back to the source
210
+ // tree here would grant support from files this binary may never have been compiled against.
211
+ return {
212
+ supported: false,
213
+ reason:
214
+ `${runtimeExecutable} is the runtime selected for this build and could not answer the ` +
215
+ '@loaders.gl WebP decode test, so nothing can claim WebP support on its behalf',
216
+ };
217
+ }
96
218
  if (!runtimeSource || !existsSync(join(runtimeSource, 'CMakeLists.txt'))) {
219
+ // No source checkout and no selected runtime: this is an installed release, so ask the host's
220
+ // own prebuilt rather than refusing what it may well decode.
221
+ const probed = probePrebuiltDecoders(runtimeSource);
222
+ if (probed !== undefined) {
223
+ return {
224
+ supported: probed.webp,
225
+ reason: `${probed.executable} answers the @loaders.gl WebP decode test with ` +
226
+ `${probed.webp ? 'YES' : 'NO'}`,
227
+ };
228
+ }
97
229
  return {
98
230
  supported: false,
99
231
  reason:
100
- `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, and a prebuilt ` +
101
- 'desktop release does not declare which decoders it was built with',
232
+ `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, a prebuilt desktop release does not declare which decoders it was built with, and its runtime could not be probed`,
102
233
  };
103
234
  }
104
235
  const prebuiltRoot = join(runtimeSource, 'third_party', 'webp');
@@ -243,7 +243,7 @@ function mobileDecoderStub(id) {
243
243
  /**
244
244
  * Main
245
245
  */
246
- async function bundleProject(project, entryPoint, outputPath, target) {
246
+ async function bundleProject(project, entryPoint, outputPath, target, nativeBackend) {
247
247
  const absoluteProject = resolve(project);
248
248
  const absoluteEntry = resolve(absoluteProject, entryPoint);
249
249
  const absoluteOutput = resolve(outputPath);
@@ -350,8 +350,13 @@ void game.start().catch((error) => console.error(
350
350
  // material is not the copy the renderer pushed onto, and the first material build on the phone
351
351
  // dies with "No stack defined for assign operation". `mergeConfig` concatenates arrays, so a
352
352
  // project that dedupes its own packages keeps every one of them.
353
+ // The native physics backend is selected where the runtime has no WebAssembly to run Rapier
354
+ // as WASM: every mobile target, and any desktop host whose engine is not V8. `threenative
355
+ // build` reads that capability from the runtime binary it will package and passes
356
+ // `--native-backend`; a direct call without it keeps the historical desktop backend. The
357
+ // choice is one export map here rather than a platform branch in game code.
353
358
  resolve:
354
- target === 'desktop'
359
+ target === 'desktop' && !nativeBackend
355
360
  ? { dedupe: ['three'] }
356
361
  : { conditions: ['threenative-native'], dedupe: ['three'] },
357
362
  configFile: existsSync(join(absoluteProject, 'vite.config.ts'))
@@ -364,14 +369,26 @@ void game.start().catch((error) => console.error(
364
369
  fileName: () => basename(absoluteOutput),
365
370
  formats: ['es'],
366
371
  },
367
- minify: false,
372
+ // Minified for the shipped asset (roughly half the raw bytes). `keepNames` is not optional:
373
+ // core reads `backend.constructor.name` for the renderer's backend stamp (`renderer.ts`,
374
+ // `geometry-capture.ts`), and the runtime's structured-clone description reads
375
+ // `value.constructor.name` (`url-worker-polyfill.js`). Without it those class names mangle
376
+ // and the reports lie. `comments.legal` keeps the bundled dependencies' `@license`/SPDX
377
+ // banners minification would otherwise strip; sourcemaps stay off, as today.
378
+ minify: true,
368
379
  outDir: dirname(absoluteOutput),
369
380
  rollupOptions: {
370
381
  input: virtualEntry,
371
382
  output: {
372
- banner: `/* TN_NATIVE_BUNDLE_SCOPE */\n(() => {\n${nativePrelude}`,
383
+ // `/*!` makes the scope marker a legal comment, the one class the minifier keeps.
384
+ banner: `/*! TN_NATIVE_BUNDLE_SCOPE */\n(() => {\n${nativePrelude}`,
373
385
  codeSplitting: false,
374
386
  footer: '})();',
387
+ // Vite's lib path defaults the minifier to `{ codegen: false }` for an ES lib, which
388
+ // mangles identifiers but keeps every newline and indent. Force the full pass.
389
+ minify: true,
390
+ keepNames: true,
391
+ comments: { legal: true },
375
392
  },
376
393
  },
377
394
  target: 'es2022',
@@ -393,6 +410,7 @@ async function main() {
393
410
  let outputDir = 'dist';
394
411
  let project = null;
395
412
  let target = null;
413
+ let nativeBackend = false;
396
414
 
397
415
  for (let i = 0; i < args.length; i++) {
398
416
  if (args[i] === '--entry' && args[i + 1]) {
@@ -405,6 +423,8 @@ async function main() {
405
423
  project = args[++i];
406
424
  } else if (args[i] === '--target' && args[i + 1]) {
407
425
  target = args[++i];
426
+ } else if (args[i] === '--native-backend') {
427
+ nativeBackend = true;
408
428
  }
409
429
  }
410
430
 
@@ -413,7 +433,7 @@ async function main() {
413
433
  if (!['android', 'desktop', 'ios'].includes(target)) {
414
434
  throw new Error('--project requires --target android|desktop|ios.');
415
435
  }
416
- await bundleProject(project, entryPoint, outputDir, target);
436
+ await bundleProject(project, entryPoint, outputDir, target, nativeBackend);
417
437
  return;
418
438
  }
419
439