@threenative/runtime-native 0.2.0 → 0.3.1

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,442 @@
1
+ /**
2
+ * Refuse to package a build whose assets the target cannot decode.
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * A game shipped 30 OGG files and three GLBs carrying WebP textures. Both are the correct choice
7
+ * for the web, both are what the default asset pipeline produces — `create-threenative`'s workflow
8
+ * emits OGG, and `gltf-transform optimize` emits WebP — and neither can be decoded by the Android
9
+ * runtime as it is built today. The APK built, installed and launched to a **black screen**: no
10
+ * crash, no tombstone, nothing in logcat but the present tick. It cost a day of bisection to find,
11
+ * and every fact needed to catch it was sitting in the first twelve bytes of the files the
12
+ * packager was already copying.
13
+ *
14
+ * So this reads them. It is the difference between a build that fails in one second naming the
15
+ * file and the command that fixes it, and a build that succeeds and hands a person a black screen.
16
+ *
17
+ * ## What it does not do
18
+ *
19
+ * It does not transcode. Transcoding needs `ffmpeg` and `gltf-transform` on the build host, which
20
+ * the packager cannot assume it has, and silently rewriting a game's assets is a bigger promise
21
+ * than refusing to package them. The message carries the exact command instead.
22
+ *
23
+ * It is also not the fix for a container the runtime *should* read. The first version of this file
24
+ * refused every Ogg Vorbis file and printed an ffmpeg line, and that advice was the bug wearing a
25
+ * hat: `.ogg` is what `create-threenative`'s workflow emits and what the browser half of the same
26
+ * source plays, so the answer was to teach the runtime Vorbis, not to teach every game a manual
27
+ * transcode step. It now decodes Ogg Vorbis (`src/audio/vorbis_impl.c`), and this file no longer
28
+ * has an opinion about it. What stays refused — MP3, AAC, FLAC, Opus — is refused because nothing
29
+ * native decodes it, on any target, and the message says so instead of blaming Android.
30
+ *
31
+ * `THREENATIVE_SKIP_ASSET_PREFLIGHT=1` turns the whole thing off, for the case where a runtime has
32
+ * been built with decoders this file does not know about yet.
33
+ */
34
+
35
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
36
+ import { join, posix, extname } from 'node:path';
37
+
38
+ /**
39
+ * What the runtime about to be packaged can decode, derived from the build rather than declared.
40
+ *
41
+ * The first version of this file refused every WebP texture for Android, saying "the android
42
+ * runtime is built without libwebp". That had been false since `62fac4d5` added `webp-source` to
43
+ * `androidDeps`: CMake builds libwebp from source under `MYSTRAL_HAS_WEBP` and the device logs
44
+ * `[Mystral] WebP format support: YES`. The claim was hardcoded, so it went stale the moment the
45
+ * build changed under it, and nothing could notice. Every capability here is therefore computed
46
+ * from the same facts CMake reads.
47
+ */
48
+
49
+ /** Mirrors the ANDROID branch of the libwebp block in CMakeLists.txt. */
50
+ export function deriveAndroidWebpSupport(runtimeSource) {
51
+ if (!runtimeSource || !existsSync(join(runtimeSource, 'CMakeLists.txt'))) {
52
+ return {
53
+ supported: false,
54
+ 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',
57
+ };
58
+ }
59
+ const sourceRoot = join(runtimeSource, 'third_party', 'webp-source');
60
+ // CMake globs libwebp-* and takes the first candidate that has a CMakeLists.txt and no lib/ —
61
+ // a lib/ means a prebuilt drop landed in the source destination, which builds nothing.
62
+ let candidates = [];
63
+ try {
64
+ candidates = readdirSync(sourceRoot, { withFileTypes: true })
65
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('libwebp-'))
66
+ .map((entry) => entry.name)
67
+ .sort();
68
+ } catch {
69
+ candidates = [];
70
+ }
71
+ const buildable = candidates.find(
72
+ (name) =>
73
+ existsSync(join(sourceRoot, name, 'CMakeLists.txt')) && !existsSync(join(sourceRoot, name, 'lib')),
74
+ );
75
+ if (buildable !== undefined) {
76
+ return {
77
+ supported: true,
78
+ reason: `third_party/webp-source/${buildable} is provisioned, so CMake builds libwebp into the Android runtime under MYSTRAL_HAS_WEBP`,
79
+ };
80
+ }
81
+ return {
82
+ supported: false,
83
+ reason:
84
+ 'third_party/webp-source carries no buildable libwebp-* source tree, so CMake prints ' +
85
+ '"libwebp not found" and the runtime reports "WebP format support: NO". Provision it with ' +
86
+ "'node scripts/download-deps.mjs --only webp-source'",
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Mirrors the non-Android, non-iOS branch of the same libwebp block: a prebuilt drop under
92
+ * `third_party/webp/libwebp-*` with both a library and headers, which is what CMake's
93
+ * `WEBP_LIBRARY AND WEBP_INCLUDE_DIR` requires before it defines `MYSTRAL_HAS_WEBP`.
94
+ */
95
+ export function deriveDesktopWebpSupport(runtimeSource) {
96
+ if (!runtimeSource || !existsSync(join(runtimeSource, 'CMakeLists.txt'))) {
97
+ return {
98
+ supported: false,
99
+ 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',
102
+ };
103
+ }
104
+ const prebuiltRoot = join(runtimeSource, 'third_party', 'webp');
105
+ let candidates = [];
106
+ try {
107
+ candidates = readdirSync(prebuiltRoot, { withFileTypes: true })
108
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('libwebp-'))
109
+ .map((entry) => entry.name)
110
+ .sort();
111
+ } catch {
112
+ candidates = [];
113
+ }
114
+ const usable = candidates.find((name) => {
115
+ const root = join(prebuiltRoot, name);
116
+ if (!existsSync(join(root, 'include'))) return false;
117
+ return ['libwebp.a', 'webp.lib', 'libwebp.lib', 'libwebp.so', 'libwebp.dylib'].some((library) =>
118
+ existsSync(join(root, 'lib', library)),
119
+ );
120
+ });
121
+ if (usable !== undefined) {
122
+ return {
123
+ supported: true,
124
+ reason: `third_party/webp/${usable} carries a library and headers, so CMake defines MYSTRAL_HAS_WEBP`,
125
+ };
126
+ }
127
+ return {
128
+ supported: false,
129
+ reason:
130
+ 'third_party/webp carries no libwebp-* prebuilt with both lib/ and include/, so CMake ' +
131
+ 'warns "libwebp library or headers not found" and the runtime reports "WebP format ' +
132
+ 'support: NO". Provision it with \'node scripts/download-deps.mjs --only webp\'',
133
+ };
134
+ }
135
+
136
+ /**
137
+ * iOS has no libwebp on any path, and that is a property of the build rather than of a directory:
138
+ * `CMakeLists.txt` excludes `IOS` from the prebuilt branch and the source branch is `ANDROID`-only.
139
+ * There is nothing to derive from the filesystem, so this states the exclusion and the three-leg
140
+ * sync test pins it against CMake — correcting the Android claim must not quietly make this one
141
+ * wrong in the other direction.
142
+ */
143
+ export function deriveIosWebpSupport() {
144
+ return {
145
+ supported: false,
146
+ reason:
147
+ 'CMakeLists.txt excludes IOS from the libwebp prebuilt branch and builds libwebp from ' +
148
+ 'source for ANDROID only, so no iOS runtime carries a WebP decoder',
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Fail closed: a caller that names no capabilities gets the most restrictive runtime, not the most
154
+ * permissive one. `stageAndroidAssets` derives the real set from the runtime it is about to pack.
155
+ */
156
+ export const NO_DECODERS = Object.freeze({
157
+ webp: Object.freeze({ supported: false, reason: 'no runtime capabilities were derived' }),
158
+ });
159
+
160
+ /** Extensions the runtime will hand to `decodeAudioData`. */
161
+ const AUDIO_EXTENSIONS = new Set(['.ogg', '.mp3', '.wav', '.m4a', '.aac', '.flac', '.opus']);
162
+
163
+ /**
164
+ * What `decodeAudioFile` implements, and therefore what every native target decodes.
165
+ *
166
+ * This is one decoder in one file (`src/audio/audio_context.cpp`), compiled into desktop, Android
167
+ * and iOS alike, so the answer does not vary by target the way libwebp does - there is no CMake
168
+ * option to derive it from. What can still go stale is *this list*, so
169
+ * `tests/audio-decode-ogg.test.mjs` fails when the containers named here and the containers
170
+ * `decodeAudioFile` sniffs stop agreeing.
171
+ */
172
+ export const NATIVE_AUDIO_CONTAINERS = Object.freeze(['RIFF/WAVE', 'Ogg Vorbis']);
173
+
174
+ /**
175
+ * What the file *is*, read from its bytes.
176
+ *
177
+ * Ogg is a container, not a codec: the same `.ogg` extension and the same `OggS` magic carry
178
+ * Vorbis, Opus and FLAC. The runtime decodes Vorbis and nothing else in that container, so a
179
+ * magic-number match alone would wave an Opus file straight through to a failure at game start.
180
+ * The codec identifier sits in the first page, after the 27-byte page header and its segment table.
181
+ */
182
+ export function detectAudioContainer(bytes) {
183
+ const ascii = (offset, text) => {
184
+ if (bytes.length < offset + text.length) return false;
185
+ for (let index = 0; index < text.length; index += 1)
186
+ if (bytes[offset + index] !== text.charCodeAt(index)) return false;
187
+ return true;
188
+ };
189
+ if (ascii(0, 'RIFF') && ascii(8, 'WAVE')) return 'RIFF/WAVE';
190
+ if (ascii(0, 'OggS')) {
191
+ if (bytes[28] === 0x01 && ascii(29, 'vorbis')) return 'Ogg Vorbis';
192
+ if (ascii(28, 'OpusHead')) return 'Ogg Opus';
193
+ if (bytes[28] === 0x7f && ascii(29, 'FLAC')) return 'Ogg FLAC';
194
+ return 'Ogg (unknown codec)';
195
+ }
196
+ if (ascii(0, 'ID3')) return 'MP3 (ID3)';
197
+ if (bytes.length >= 2 && bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0) return 'MP3';
198
+ if (ascii(0, 'fLaC')) return 'FLAC';
199
+ if (ascii(4, 'ftyp')) return 'MP4/M4A';
200
+ return 'an unknown format';
201
+ }
202
+
203
+ const GLB_MAGIC = 0x46546c67; // "glTF"
204
+ const GLB_CHUNK_JSON = 0x4e4f534a; // "JSON"
205
+
206
+ /**
207
+ * A file is decodable audio only if its bytes are a container `decodeAudioFile` implements.
208
+ *
209
+ * The decoder sniffs the header rather than the extension, which is why the hand-rolled workaround
210
+ * for the missing Vorbis decoder — transcoding to WAV *content* while keeping the `.ogg`
211
+ * filenames — worked at all. So the check is on the bytes too: a `.wav` carrying Opus fails, and
212
+ * an `.ogg` carrying WAV passes.
213
+ *
214
+ * The refusal names no platform. Every native target shares this decoder, so "the android target
215
+ * rejects it" was never the truth even when Android was the only target anyone had run — the same
216
+ * file fails on desktop and on iOS, and saying otherwise sent people hunting an Android problem.
217
+ */
218
+ function audioProblem(relativePath, bytes) {
219
+ const detected = detectAudioContainer(bytes);
220
+ if (NATIVE_AUDIO_CONTAINERS.includes(detected)) return undefined;
221
+ return {
222
+ file: relativePath,
223
+ reason: `is ${detected}; no native target decodes this container (the runtime decodes ${NATIVE_AUDIO_CONTAINERS.join(' and ')})`,
224
+ // Ogg Vorbis rather than WAV: roughly a tenth of the size, what the web build already ships,
225
+ // and now decoded natively, so one file serves both halves of the same source.
226
+ fix: `ffmpeg -y -i "${relativePath}" -c:a libvorbis -ar 44100 "${relativePath.replace(/\.[^.]*$/u, '')}.ogg"`,
227
+ };
228
+ }
229
+
230
+ function parseGlb(bytes) {
231
+ if (bytes.length < 12) return { error: 'the 12-byte header is truncated' };
232
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
233
+ if (view.getUint32(0, true) !== GLB_MAGIC) return { error: 'the header magic is not glTF' };
234
+ if (view.getUint32(4, true) !== 2) return { error: 'the version is not 2' };
235
+ const declaredLength = view.getUint32(8, true);
236
+ if (declaredLength !== bytes.length) {
237
+ return {
238
+ error: `the header declares ${declaredLength} bytes but the file contains ${bytes.length}`,
239
+ };
240
+ }
241
+
242
+ let offset = 12;
243
+ let json;
244
+ while (offset < bytes.length) {
245
+ if (offset + 8 > bytes.length) return { error: 'a chunk header is truncated' };
246
+ const length = view.getUint32(offset, true);
247
+ const kind = view.getUint32(offset + 4, true);
248
+ if (length % 4 !== 0) return { error: 'a chunk length is not 4-byte aligned' };
249
+ const start = offset + 8;
250
+ if (start + length > bytes.length) return { error: 'a chunk is truncated' };
251
+ if (offset === 12 && kind !== GLB_CHUNK_JSON) {
252
+ return { error: 'the first chunk is not the required JSON chunk' };
253
+ }
254
+ if (kind === GLB_CHUNK_JSON) {
255
+ if (json !== undefined) return { error: 'the file contains more than one JSON chunk' };
256
+ try {
257
+ json = JSON.parse(
258
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(start, start + length)),
259
+ );
260
+ } catch {
261
+ return { error: 'the JSON chunk is not valid UTF-8 JSON' };
262
+ }
263
+ if (json === null || typeof json !== 'object' || Array.isArray(json)) {
264
+ return { error: 'the JSON chunk is not a glTF object' };
265
+ }
266
+ }
267
+ offset = start + length;
268
+ }
269
+ if (json === undefined) return { error: 'the file has no JSON chunk' };
270
+ return { json };
271
+ }
272
+
273
+ /** The glTF JSON chunk of a `.glb`, or undefined when the file is not a GLB this can read. */
274
+ export function readGlbJson(bytes) {
275
+ return parseGlb(bytes).json;
276
+ }
277
+
278
+ /**
279
+ * Two things a GLB can carry that this target cannot draw.
280
+ *
281
+ * **WebP textures.** When the runtime carries no libwebp, the build says so (`libwebp not found`)
282
+ * and the runtime says so (`WebP format support: NO`), and both were ignored, because the only
283
+ * visible symptom is `THREE.GLTFLoader: Couldn't load texture blob:...` and two white models in an
284
+ * otherwise perfect scene. The shape of that failure is worth knowing: a broken loader loses
285
+ * *every* embedded texture, so "only two models are white" was already evidence the URLs were fine
286
+ * and the decode was not. Whether this runtime carries it is derived, never assumed — see
287
+ * `deriveAndroidWebpSupport`.
288
+ *
289
+ * **Interleaved vertex buffers.** `gltf-transform optimize` interleaves by default, and an
290
+ * interleaved buffer makes `THREE.WebGPURenderer` fail `createRenderPipeline` on every mesh. The
291
+ * fix is one flag, `--vertex-layout separate`, and it has been written down as folklore in more
292
+ * than one game's agent notes. Folklore does not stop a build; this does.
293
+ */
294
+ function glbProblems(relativePath, json, capabilities) {
295
+ const problems = [];
296
+ const webp = (json.images ?? []).filter((image) => image?.mimeType === 'image/webp').length;
297
+ if (webp > 0 && capabilities.webp.supported !== true) {
298
+ problems.push({
299
+ file: relativePath,
300
+ reason: `embeds ${webp} WebP texture${webp === 1 ? '' : 's'}, and ${capabilities.webp.reason}`,
301
+ fix:
302
+ `gltf-transform jpeg --formats '*' --quality 90 --vertex-layout separate "${relativePath}" "${relativePath}"` +
303
+ ` && gltf-transform png --formats webp --vertex-layout separate "${relativePath}" "${relativePath}"`,
304
+ });
305
+ }
306
+
307
+ // Interleaved means two or more attributes packed into the same buffer view, one vertex's worth
308
+ // at a time. It does NOT mean `byteStride > element`: glTF requires accessor byte offsets and
309
+ // strides to be 4-byte aligned, so a VEC3 of shorts is 6 bytes of data in an 8-byte slot in
310
+ // every separate-layout file `gltf-transform` produces. Testing the stride flagged all three of
311
+ // Bayview's rigged GLBs, which demonstrably render on WebGPU on both desktop and a Pixel 8 — a
312
+ // gate that fails on working assets is worse than no gate. Counting accessors per view is the
313
+ // thing interleaving actually is.
314
+ const accessors = json.accessors ?? [];
315
+ const attributesPerView = new Map();
316
+ for (const mesh of json.meshes ?? []) {
317
+ for (const primitive of mesh.primitives ?? []) {
318
+ for (const index of Object.values(primitive.attributes ?? {})) {
319
+ const view = accessors[index]?.bufferView;
320
+ if (view === undefined) continue;
321
+ const seen = attributesPerView.get(view) ?? new Set();
322
+ seen.add(index);
323
+ attributesPerView.set(view, seen);
324
+ }
325
+ }
326
+ }
327
+ let interleaved = 0;
328
+ for (const seen of attributesPerView.values()) if (seen.size > 1) interleaved += 1;
329
+ if (interleaved > 0) {
330
+ problems.push({
331
+ file: relativePath,
332
+ reason: `has ${interleaved} interleaved buffer view${interleaved === 1 ? '' : 's'}; WebGPU fails createRenderPipeline on every mesh that uses one`,
333
+ fix: `gltf-transform cp --vertex-layout separate "${relativePath}" "${relativePath}"`,
334
+ });
335
+ }
336
+ return problems;
337
+ }
338
+
339
+ function malformedGlbProblem(relativePath, reason) {
340
+ return {
341
+ file: relativePath,
342
+ reason: `is not a readable GLB: ${reason}`,
343
+ fix: `re-export or replace "${relativePath}" with a valid glTF 2.0 binary asset`,
344
+ };
345
+ }
346
+
347
+ function listFiles(directory, relative = '') {
348
+ const files = [];
349
+ for (const entry of readdirSync(join(directory, relative), { withFileTypes: true })) {
350
+ const path = relative ? posix.join(relative, entry.name) : entry.name;
351
+ if (entry.isDirectory()) files.push(...listFiles(directory, path));
352
+ else if (entry.isFile()) files.push(path);
353
+ }
354
+ return files.sort();
355
+ }
356
+
357
+ /**
358
+ * Every asset in `directory` the named target cannot read, as a list of problems.
359
+ *
360
+ * Returns rather than throws, so a caller can warn instead of failing and so this is testable
361
+ * without a filesystem full of broken fixtures.
362
+ */
363
+ export function findNativeAssetProblems(directory, capabilities = NO_DECODERS) {
364
+ if (!directory) return [];
365
+ let entries;
366
+ try {
367
+ if (!statSync(directory).isDirectory()) return [];
368
+ entries = listFiles(directory);
369
+ } catch {
370
+ return [];
371
+ }
372
+ const problems = [];
373
+ for (const file of entries) {
374
+ const extension = extname(file).toLowerCase();
375
+ const isAudio = AUDIO_EXTENSIONS.has(extension);
376
+ const isGlb = extension === '.glb';
377
+ if (!isAudio && !isGlb) continue;
378
+ let bytes;
379
+ try {
380
+ bytes = readFileSync(join(directory, file));
381
+ } catch {
382
+ if (isGlb) problems.push(malformedGlbProblem(file, 'the file could not be read'));
383
+ continue;
384
+ }
385
+ if (isAudio) {
386
+ const problem = audioProblem(file, bytes);
387
+ if (problem !== undefined) problems.push(problem);
388
+ continue;
389
+ }
390
+ const parsed = parseGlb(bytes);
391
+ if (parsed.json !== undefined) problems.push(...glbProblems(file, parsed.json, capabilities));
392
+ else problems.push(malformedGlbProblem(file, parsed.error));
393
+ }
394
+ return problems;
395
+ }
396
+
397
+ /** The message a person reads when the build stops: what, why, and the command that fixes it. */
398
+ export function formatAssetProblems(problems, target = 'android') {
399
+ const lines = [
400
+ `TN_NATIVE_ASSET_UNSUPPORTED: ${problems.length} asset${problems.length === 1 ? '' : 's'} cannot be decoded by the ${target} target.`,
401
+ '',
402
+ ];
403
+ for (const problem of problems) {
404
+ lines.push(` ${problem.file}`);
405
+ lines.push(` ${problem.reason}`);
406
+ lines.push(` fix: ${problem.fix}`);
407
+ lines.push('');
408
+ }
409
+ lines.push(
410
+ 'Convert into a staging copy of the asset directory and package that, so the web build keeps',
411
+ 'shipping whatever it likes. Set THREENATIVE_SKIP_ASSET_PREFLIGHT=1 to package anyway.',
412
+ );
413
+ return lines.join('\n');
414
+ }
415
+
416
+ /**
417
+ * Throw unless every asset in `directory` is decodable by `target`, or the caller opted out by env.
418
+ *
419
+ * Every packager calls this. Only the Android one did, which is how `package-desktop.mjs` and
420
+ * `package-ios.mjs` shipped builds that failed at game start on assets the packager had already
421
+ * read and copied — the same class of black screen, reached by a different door. The capability
422
+ * set is the caller's, because it is the caller that knows which runtime it is about to pack.
423
+ */
424
+ export function assertNativeAssetsDecodable(directory, { target, capabilities = NO_DECODERS } = {}) {
425
+ if (!target) throw new Error('assertNativeAssetsDecodable requires the target it is gating.');
426
+ if (process.env.THREENATIVE_SKIP_ASSET_PREFLIGHT === '1') return [];
427
+ const problems = findNativeAssetProblems(directory, capabilities);
428
+ if (problems.length > 0) throw new Error(formatAssetProblems(problems, target));
429
+ return problems;
430
+ }
431
+
432
+ /**
433
+ * The Android-shaped names the packager and the template gate already call, kept so a rename does
434
+ * not travel further than this change needs to. They are the same gate with the target filled in.
435
+ */
436
+ export function findAndroidAssetProblems(directory, capabilities = NO_DECODERS) {
437
+ return findNativeAssetProblems(directory, capabilities);
438
+ }
439
+
440
+ export function assertAndroidAssetsDecodable(directory, capabilities = NO_DECODERS) {
441
+ return assertNativeAssetsDecodable(directory, { target: 'android', capabilities });
442
+ }