@threenative/runtime-native 0.3.3 → 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.
Files changed (39) hide show
  1. package/NOTICE +1 -1
  2. package/android/README.md +10 -0
  3. package/android/app/build.gradle.kts +23 -0
  4. package/android/app/src/main/java/com/mystral/engine/MystralActivity.java +87 -2
  5. package/android/app/src/main/java/com/mystral/engine/TnUiOverlay.java +170 -8
  6. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  7. package/build/web/tn-native-engine-web.mjs +2 -0
  8. package/build/web/tn-native-engine-web.wasm +0 -0
  9. package/package.json +20 -6
  10. package/scripts/asset-manifest.mjs +38 -19
  11. package/scripts/bundle-native-engine.mjs +303 -0
  12. package/scripts/bundle.mjs +38 -41
  13. package/scripts/check-source-list.mjs +11 -5
  14. package/scripts/desktop-distribution.mjs +19 -5
  15. package/scripts/inspect-macos-icon.mjs +169 -0
  16. package/scripts/install-prebuilt.mjs +33 -21
  17. package/scripts/package-android.mjs +64 -6
  18. package/scripts/package-desktop.mjs +51 -14
  19. package/scripts/package-engine-desktop.mjs +102 -0
  20. package/scripts/package-ios.mjs +36 -32
  21. package/scripts/physical-device-evidence.mjs +135 -1
  22. package/scripts/production-evidence.mjs +36 -9
  23. package/scripts/profile-production.mjs +696 -146
  24. package/scripts/qualify-physical-mobile.mjs +286 -69
  25. package/scripts/verify-starter-consumer.mjs +58 -8
  26. package/scripts/verify-starter-desktop-base.mjs +12 -2
  27. package/scripts/windows-installer.mjs +12 -5
  28. package/scripts/xvfb.sh +15 -0
  29. package/src/engine/player/core-addons.mjs +15 -0
  30. package/src/engine/player/core-assets.mjs +59 -0
  31. package/src/engine/player/core-audio.mjs +11 -0
  32. package/src/engine/player/core-hdr.mjs +29 -0
  33. package/src/engine/player/core-host.mjs +148 -0
  34. package/src/engine/player/core-lut.mjs +7 -0
  35. package/src/engine/player/core-textures.mjs +167 -0
  36. package/src/engine/player/core-three.mjs +294 -0
  37. package/src/engine/player/core-tsl.mjs +80 -0
  38. package/src/engine/player/core-unused.mjs +21 -0
  39. package/src/engine/player/core-webgpu.mjs +207 -0
@@ -0,0 +1,169 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import {
4
+ lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync,
5
+ } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { PNG } from 'pngjs';
9
+
10
+ const INVALID = 'TN_NATIVE_STARTER_CONTAINER_MACOS_ICON_INVALID';
11
+ const MISMATCH = 'TN_NATIVE_STARTER_CONTAINER_ICON_MISMATCH';
12
+ const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
13
+ const GENERATED_NAMES = [16, 32, 128, 256, 512].flatMap((size) => [
14
+ `icon_${size}x${size}.png`, `icon_${size}x${size}@2x.png`,
15
+ ]);
16
+
17
+ function assertIcns(bytes) {
18
+ if (bytes.length < 16 || bytes.toString('ascii', 0, 4) !== 'icns' ||
19
+ bytes.readUInt32BE(4) !== bytes.length) {
20
+ throw new Error(`${INVALID}: the packaged icon is not a complete, nonempty ICNS file.`);
21
+ }
22
+ for (let offset = 8; offset < bytes.length;) {
23
+ if (offset + 8 > bytes.length) throw new Error(`${INVALID}: truncated ICNS element.`);
24
+ const size = bytes.readUInt32BE(offset + 4);
25
+ if (size <= 8 || size > bytes.length - offset) {
26
+ throw new Error(`${INVALID}: invalid ICNS element length.`);
27
+ }
28
+ offset += size;
29
+ }
30
+ }
31
+
32
+ function iconTool(run, command, args) {
33
+ const result = run(command, args, { encoding: 'utf8', timeout: 30_000, maxBuffer: 1024 * 1024 });
34
+ if (result.error || result.status !== 0) {
35
+ throw new Error(
36
+ `${INVALID}: ${command} could not inspect the icon (${result.error?.message ?? result.status ?? 'no exit status'}). Run the brand verifier on macOS with iconutil and sips available; metadata alone is not icon proof.`,
37
+ );
38
+ }
39
+ }
40
+
41
+ function pngImage(path, pixels) {
42
+ const bytes = readFileSync(path);
43
+ // Bound the decoder by the representation's dimensions, not by untrusted IHDR allocation sizes.
44
+ if (bytes.length < 33 || bytes.length > 32 * 1024 * 1024 ||
45
+ !bytes.subarray(0, 8).equals(PNG_SIGNATURE) || bytes.readUInt32BE(8) !== 13 ||
46
+ bytes.toString('ascii', 12, 16) !== 'IHDR' ||
47
+ bytes.readUInt32BE(16) !== pixels || bytes.readUInt32BE(20) !== pixels) {
48
+ throw new Error(`${INVALID}: ${path} is not a ${pixels}x${pixels} PNG representation.`);
49
+ }
50
+ try {
51
+ return PNG.sync.read(bytes);
52
+ } catch (error) {
53
+ throw new Error(`${INVALID}: cannot decode ${path}: ${error.message}`);
54
+ }
55
+ }
56
+
57
+ /** Compare decoded RGBA, never PNG encoding, ancillary metadata, or a source-hash assertion. */
58
+ export function assertIconPixels(actual, expected, name) {
59
+ for (const image of [actual, expected]) {
60
+ if (!image || !Number.isInteger(image.width) || !Number.isInteger(image.height) ||
61
+ image.width < 1 || image.width > 1024 || image.height < 1 || image.height > 1024 ||
62
+ !Buffer.isBuffer(image.data) || image.data.length !== image.width * image.height * 4) {
63
+ throw new Error(`${INVALID}: ${name} has no complete decoded RGBA image.`);
64
+ }
65
+ }
66
+ if (actual.width !== expected.width || actual.height !== expected.height) {
67
+ throw new Error(`${MISMATCH}: decoded macOS icon ${name} dimensions differ from app.icon.`);
68
+ }
69
+ // Converters may discard hidden RGB beneath zero alpha. Canonicalize only invisible pixels;
70
+ // every visible channel, including partial transparency, must still match exactly.
71
+ const canonical = Buffer.from(actual.data);
72
+ for (let offset = 0; offset < canonical.length; offset += 4) {
73
+ const alpha = actual.data[offset + 3];
74
+ if (alpha !== expected.data[offset + 3] || (alpha !== 0 &&
75
+ !actual.data.subarray(offset, offset + 3).equals(expected.data.subarray(offset, offset + 3)))) {
76
+ throw new Error(`${MISMATCH}: decoded macOS icon ${name} differs from app.icon.`);
77
+ }
78
+ if (alpha === 0) canonical.fill(0, offset, offset + 3);
79
+ }
80
+ return createHash('sha256').update(canonical).digest('hex');
81
+ }
82
+
83
+ // Compare at the same conversion boundary. iconutil can normalize even visible colour values
84
+ // while encoding/decoding ICNS. Resized source PNG pixels alone are therefore not its output.
85
+ // Build the reference independently from app.icon with the packager's existing recipe, then
86
+ // decode both ICNS files. Exact visible RGBA comparison remains unchanged; no tolerance is added.
87
+ function referenceIconset(source, scratch, run) {
88
+ const inputs = join(scratch, 'reference.iconset');
89
+ mkdirSync(inputs);
90
+ for (const name of GENERATED_NAMES) {
91
+ const match = /^icon_(\d+)x\1(@2x)?\.png$/u.exec(name);
92
+ const pixels = String(Number(match[1]) * (match[2] ? 2 : 1));
93
+ const target = join(inputs, name);
94
+ iconTool(run, 'sips', ['-z', pixels, pixels, source, '--out', target]);
95
+ pngImage(target, Number(pixels));
96
+ }
97
+ const reference = join(scratch, 'reference.icns');
98
+ iconTool(run, 'iconutil', ['-c', 'icns', inputs, '-o', reference]);
99
+ assertIcns(readFileSync(reference));
100
+ const decoded = join(scratch, 'reference-decoded.iconset');
101
+ iconTool(run, 'iconutil', ['-c', 'iconset', '-o', decoded, reference]);
102
+ if (!lstatSync(decoded).isDirectory() || lstatSync(decoded).isSymbolicLink()) {
103
+ throw new Error(`${INVALID}: iconutil did not produce a reference iconset directory.`);
104
+ }
105
+ return decoded;
106
+ }
107
+
108
+ /**
109
+ * Read back every iconutil representation of the final .icns. The packager's PNG -> sips ->
110
+ * iconutil round trip is independently repeated for the authored source, then compared at decoded
111
+ * RGBA. Compression/metadata differences cannot pass for artwork or reject identical artwork. Authored .icns inputs must remain byte-identical and still
112
+ * decode successfully. This proves artifact content, not Finder/Dock appearance or a GUI launch.
113
+ * `run` is the same command-boundary seam used by desktop-distribution.mjs; production uses the OS.
114
+ */
115
+ export function inspectMacosIcon(icon, source, { run = spawnSync } = {}) {
116
+ const bytes = readFileSync(icon);
117
+ assertIcns(bytes);
118
+ const authoredIcns = source.endsWith('.icns'); // Match buildIcon's existing copy-vs-convert rule.
119
+ if (authoredIcns && !bytes.equals(readFileSync(source))) {
120
+ throw new Error(`${MISMATCH}: the packaged ICNS differs from the authored ICNS.`);
121
+ }
122
+ const scratch = mkdtempSync(join(tmpdir(), 'threenative-icon-inspection-'));
123
+ try {
124
+ const decoded = join(scratch, 'actual.iconset');
125
+ iconTool(run, 'iconutil', ['-c', 'iconset', '-o', decoded, icon]);
126
+ if (!lstatSync(decoded).isDirectory() || lstatSync(decoded).isSymbolicLink()) {
127
+ throw new Error(`${INVALID}: iconutil did not produce an iconset directory.`);
128
+ }
129
+ const entries = readdirSync(decoded, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
130
+ if (entries.length === 0 || entries.length > 32) {
131
+ throw new Error(`${INVALID}: iconutil produced no bounded set of icon representations.`);
132
+ }
133
+ if (!authoredIcns && GENERATED_NAMES.some((name) => !entries.some((entry) => entry.name === name))) {
134
+ throw new Error(`${INVALID}: the converted icon is missing a size or scale generated by the packager.`);
135
+ }
136
+ const references = authoredIcns ? undefined : referenceIconset(source, scratch, run);
137
+ const representations = [];
138
+ for (const entry of entries) {
139
+ const match = /^icon_(\d+)x\1(@2x)?\.png$/u.exec(entry.name);
140
+ const pixels = match ? Number(match[1]) * (match[2] ? 2 : 1) : 0;
141
+ if (!entry.isFile() || !match || pixels < 1 || pixels > 1024) {
142
+ throw new Error(`${INVALID}: unexpected iconutil output ${entry.name}.`);
143
+ }
144
+ const actual = pngImage(join(decoded, entry.name), pixels);
145
+ let expected = actual;
146
+ if (references !== undefined) {
147
+ const reference = join(references, entry.name);
148
+ const info = lstatSync(reference);
149
+ if (!info.isFile() || info.isSymbolicLink()) {
150
+ throw new Error(`${INVALID}: unexpected reference output ${entry.name}.`);
151
+ }
152
+ expected = pngImage(reference, pixels);
153
+ }
154
+ representations.push({
155
+ name: entry.name,
156
+ width: actual.width,
157
+ height: actual.height,
158
+ rgbaSha256: assertIconPixels(actual, expected, entry.name),
159
+ });
160
+ }
161
+ return { method: 'iconutil-decoded-rgba', representations };
162
+ } catch (error) {
163
+ if (error.message?.startsWith('TN_')) throw error;
164
+ throw new Error(`${INVALID}: could not read iconutil output: ${error.message}`);
165
+ } finally {
166
+ // Never modify the signed app or put scratch resources inside the distributed container.
167
+ rmSync(scratch, { recursive: true, force: true });
168
+ }
169
+ }
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
- import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
5
  import { dirname, join, resolve } from 'node:path';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { fileURLToPath } from 'node:url';
7
7
 
8
8
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
9
9
  const packageVersion = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')).version;
10
- export const RELEASE_REPOSITORY = 'ThreeNativeHQ/threenative';
10
+ export const RELEASE_REPOSITORY = 'ThreeNativeHQ/threenative-engine';
11
11
 
12
12
  /** Every asset a packaged consumer or native release workflow may request. */
13
13
  export const PREBUILT_ASSET_NAMES = Object.freeze({
@@ -24,11 +24,14 @@ export const PREBUILT_ASSET_NAMES = Object.freeze({
24
24
  'android-x86_64-v8': 'threenative-v8-android-x86_64.so',
25
25
  'android-x86_64-libcxx': 'threenative-libcxx-android-x86_64.so',
26
26
  'android-x86_64-v8-snapshot': 'threenative-v8-snapshot-android-x86_64.bin',
27
+ 'darwin-arm64-engine-player': 'threenative-engine-player-darwin-arm64',
27
28
  'darwin-arm64': 'threenative-runtime-darwin-arm64',
28
29
  'darwin-arm64-tools': 'threenative-tools-darwin-arm64',
29
30
  'ios-simulator-arm64': 'threenative-ios-simulator-arm64.zip',
31
+ 'linux-x64-engine-player': 'threenative-engine-player-linux-x64',
30
32
  'linux-x64': 'threenative-runtime-linux-x64',
31
33
  'linux-x64-tools': 'threenative-tools-linux-x64',
34
+ 'win32-x64-engine-player': 'threenative-engine-player-win32-x64.exe',
32
35
  'win32-x64': 'threenative-runtime-win32-x64.exe',
33
36
  'win32-x64-tools': 'threenative-tools-win32-x64.exe',
34
37
  });
@@ -49,7 +52,7 @@ export const PREBUILT_KEYS = Object.freeze(Object.keys(PREBUILT_ASSET_NAMES));
49
52
  * place of building every claimed row. Publishing it again is one entry, once the Apple identity
50
53
  * exists. Status and cost of every platform's signing inputs: `docs/RELEASE-SIGNING.md`.
51
54
  */
52
- export const UNPUBLISHED_PREBUILT_KEYS = Object.freeze(['darwin-arm64', 'darwin-arm64-tools']);
55
+ export const UNPUBLISHED_PREBUILT_KEYS = Object.freeze(['darwin-arm64', 'darwin-arm64-tools', 'darwin-arm64-engine-player']);
53
56
 
54
57
  /** The exact cohort a release publishes and a consumer may download. */
55
58
  export const PUBLISHED_PREBUILT_KEYS = Object.freeze(
@@ -99,7 +102,9 @@ function releaseFromManifest(manifest, key) {
99
102
  }
100
103
  const release = manifest?.artifacts?.[key];
101
104
  if (!release?.url || !release?.sha256) {
102
- throw new Error(`No prebuilt release asset is recorded for '${key}'.`);
105
+ const error = new Error(`No prebuilt release asset is recorded for '${key}'.`);
106
+ if (key.endsWith('-engine-player')) error.code = 'PREBUILT_RELEASE_UNPUBLISHED';
107
+ throw error;
103
108
  }
104
109
  if (typeof release.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(release.sha256)) {
105
110
  throw new Error(`Invalid prebuilt SHA-256 for '${key}'.`);
@@ -227,7 +232,7 @@ export function generateReleaseManifest(directory, { repository, tag, sourceSha,
227
232
  export function readRelease(manifestPath, key) {
228
233
  if (!existsSync(manifestPath)) {
229
234
  const error = new Error(`No prebuilt release manifest exists for '${key}'; this target remains OPEN.`);
230
- error.code = 'PREBUILT_RELEASE_MISSING';
235
+ error.code = key.endsWith('-engine-player') ? 'PREBUILT_RELEASE_UNPUBLISHED' : 'PREBUILT_RELEASE_MISSING';
231
236
  throw error;
232
237
  }
233
238
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
@@ -262,12 +267,15 @@ export function writeInstallStatus(status, statusPath = join(packageRoot, 'prebu
262
267
 
263
268
  function createInstallPlan(options) {
264
269
  const platform = options.platform ?? process.platform;
265
- const key = `${platform}-${options.arch ?? process.arch}`;
266
- const filename = platform === 'win32' ? 'threenative-runtime.exe' : 'threenative-runtime';
267
- const output = resolve(options.output ?? join(packageRoot, 'prebuilt', key, filename));
270
+ const platformId = `${platform}-${options.arch ?? process.arch}`;
271
+ const key = options.enginePlayer ? `${platformId}-engine-player` : platformId;
272
+ const filename = options.enginePlayer
273
+ ? `tn-native-engine-player-v8${platform === 'win32' ? '.exe' : ''}`
274
+ : platform === 'win32' ? 'threenative-runtime.exe' : 'threenative-runtime';
275
+ const output = resolve(options.output ?? join(packageRoot, 'prebuilt', platformId, filename));
268
276
  const statusPath = resolve(options.statusPath ?? (options.output
269
- ? join(dirname(output), 'install-status.json')
270
- : join(packageRoot, 'prebuilt', 'install-status.json')));
277
+ ? join(dirname(output), options.enginePlayer ? 'engine-player-install-status.json' : 'install-status.json')
278
+ : join(packageRoot, 'prebuilt', options.enginePlayer ? 'engine-player-install-status.json' : 'install-status.json')));
271
279
  if (output === statusPath) throw new Error('Prebuilt output and install status paths must differ.');
272
280
  const toolsOutput = join(dirname(output), toolsFilename(platform));
273
281
  if (toolsOutput === output) throw new Error('Prebuilt runtime and build tool helper paths must differ.');
@@ -278,7 +286,7 @@ function createInstallPlan(options) {
278
286
 
279
287
  function beginInstall(plan, arch) {
280
288
  rmSync(plan.output, { force: true });
281
- rmSync(plan.toolsOutput, { force: true });
289
+ if (plan.toolsKey) rmSync(plan.toolsOutput, { force: true });
282
290
  rmSync(plan.statusPath, { force: true });
283
291
  writeInstallStatus({ ...plan.status, ok: false, reason: 'installing' }, plan.statusPath);
284
292
  platformKey(plan.platform, arch);
@@ -296,20 +304,20 @@ function publishBinary(target, contents, platform) {
296
304
  }
297
305
  }
298
306
 
299
- // The success marker is written only once both binaries are in place: a desktop build that finds
307
+ // The success marker is written only once all requested binaries are in place: a desktop build that finds
300
308
  // the runtime but not the helper dies inside the packager with exit 127, which is exactly the
301
309
  // stale-success shape this install exists to prevent.
302
310
  function publishInstall(plan, contents, toolsContents) {
303
311
  publishBinary(plan.output, contents, plan.platform);
304
- publishBinary(plan.toolsOutput, toolsContents, plan.platform);
312
+ if (plan.toolsKey) publishBinary(plan.toolsOutput, toolsContents, plan.platform);
305
313
  writeInstallStatus({ ...plan.status, ok: true, reason: 'installed', sha256: sha256(contents),
306
- toolsSha256: sha256(toolsContents) }, plan.statusPath);
314
+ ...(plan.toolsKey ? { toolsSha256: sha256(toolsContents) } : {}) }, plan.statusPath);
307
315
  }
308
316
 
309
317
  function recordInstallFailure(plan, error) {
310
318
  try {
311
319
  rmSync(plan.output, { force: true });
312
- rmSync(plan.toolsOutput, { force: true });
320
+ if (plan.toolsKey) rmSync(plan.toolsOutput, { force: true });
313
321
  writeInstallStatus({ ...plan.status, ok: false,
314
322
  reason: error instanceof Error ? error.message : String(error) }, plan.statusPath);
315
323
  } catch (statusError) {
@@ -335,7 +343,7 @@ async function fetchRelease(manifestUrl, key) {
335
343
  const error = new Error(
336
344
  `Prebuilt release manifest fetch failed for '${key}' at ${url.href}: HTTP ${response.status}.`,
337
345
  );
338
- if (response.status === 404) error.code = 'PREBUILT_RELEASE_MISSING';
346
+ if (response.status === 404) error.code = key.endsWith('-engine-player') ? 'PREBUILT_RELEASE_UNPUBLISHED' : 'PREBUILT_RELEASE_MISSING';
339
347
  throw error;
340
348
  }
341
349
  return releaseFromManifest(validateReleaseManifest(await response.json()), key);
@@ -384,6 +392,7 @@ function isVerifiedInstall(plan, options) {
384
392
  const contents = readFileSync(plan.output);
385
393
  if (contents.length === 0 || (pinned?.size !== undefined && contents.length !== pinned.size)) return false;
386
394
  verifyChecksum(contents, status.sha256, plan.key);
395
+ if (!plan.toolsKey) return true;
387
396
  // A cached runtime without its verified helper is not a reusable desktop install.
388
397
  if (typeof status.toolsSha256 !== 'string') return false;
389
398
  const pinnedTools = manifestPath ? readRelease(resolve(manifestPath), plan.toolsKey) : undefined;
@@ -409,9 +418,9 @@ export async function installPrebuilt(options = {}) {
409
418
  // A failed retry must not leave an earlier binary usable or its old success marker intact.
410
419
  beginInstall(plan, options.arch);
411
420
  const contents = await downloadReleaseArtifact(plan.key, options);
412
- const toolsContents = await downloadReleaseArtifact(plan.toolsKey, options);
421
+ const toolsContents = plan.toolsKey ? await downloadReleaseArtifact(plan.toolsKey, options) : undefined;
413
422
  publishInstall(plan, contents, toolsContents);
414
- console.log(`Installed verified ThreeNative runtime and build tool helper for '${plan.key}'.`);
423
+ console.log(`Installed verified ThreeNative ${plan.toolsKey ? 'runtime and build tool helper' : 'engine player'} for '${plan.key}'.`);
415
424
  return plan.output;
416
425
  } catch (error) {
417
426
  recordInstallFailure(plan, error);
@@ -419,12 +428,15 @@ export async function installPrebuilt(options = {}) {
419
428
  }
420
429
  }
421
430
 
422
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
431
+ // Real paths on both sides: pnpm runs this hook through a symlinked `node_modules` path, and a
432
+ // plain comparison with the module's real URL silently skipped the install.
433
+ if (process.argv[1] && existsSync(process.argv[1]) &&
434
+ realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1])) {
423
435
  const sourceCheckout = existsSync(join(packageRoot, 'src')) && existsSync(join(packageRoot, 'CMakeLists.txt'));
424
436
  if (sourceCheckout) {
425
437
  console.log('ThreeNative runtime source checkout detected; prebuilt install is deferred to package testing.');
426
438
  } else {
427
- installPrebuilt()
439
+ installPrebuilt().then(() => installPrebuilt({ enginePlayer: true }))
428
440
  .catch((error) => {
429
441
  const reason = error instanceof Error ? error.message : String(error);
430
442
  // An unpublished release is a packaging-state fact, not a broken download. The web game
@@ -574,7 +574,7 @@ export function renderAndroidManifest(source, orientation = 'landscape') {
574
574
  rendered = upsertApplicationMetadata(
575
575
  rendered,
576
576
  'TN_UI_RENDERER',
577
- config.ui.renderer === 'web' ? 'web' : 'native',
577
+ mobileUiRenderer(config.ui.renderer),
578
578
  );
579
579
  rendered = upsertApplicationMetadata(rendered, 'TN_WINDOW_TITLE', '@string/window_title');
580
580
  rendered = upsertApplicationMetadata(rendered, 'TN_FULLSCREEN', String(config.display.fullscreen));
@@ -780,7 +780,7 @@ export function stageAndroidAssets(
780
780
  // Derived from the runtime this build is about to pack, not declared here. A hardcoded claim
781
781
  // goes stale the moment the build changes under it, which is exactly what happened to WebP.
782
782
  assertAndroidAssetsDecodable(assets, { webp: deriveAndroidWebpSupport(runtimeSource) });
783
- const files = selectManifestAssets(assets);
783
+ const { selected: files } = selectManifestAssets(assets);
784
784
  for (const file of files) {
785
785
  const output = join(destination, file);
786
786
  mkdirSync(dirname(output), { recursive: true });
@@ -789,6 +789,37 @@ export function stageAndroidAssets(
789
789
  return files;
790
790
  }
791
791
 
792
+ /**
793
+ * Flatten `ui.renderer` for the Android host, which reads a flat string.
794
+ *
795
+ * `native-css` survives the flattening: the activity reads it to extract the staged stylesheets
796
+ * and hand them to the runtime's CSS UI instead of attaching a WebView. Whether the runtime has
797
+ * that backend at all is `androidCssUiGradleArgs`'s question.
798
+ */
799
+ export function mobileUiRenderer(renderer) {
800
+ if (renderer === 'native-css') return 'native-css';
801
+ return renderer === 'web' ? 'web' : 'native';
802
+ }
803
+
804
+ /**
805
+ * The Gradle switch a `native-css` game needs, or a named refusal.
806
+ *
807
+ * The CSS UI is linked only when the runtime is compiled with `-PthreenativeCssUi=true`, which only
808
+ * a source build can do: no published Android prebuilt carries it, and a game packaged against one
809
+ * would install, launch and paint no HUD with clean logs.
810
+ */
811
+ export function androidCssUiGradleArgs(renderer, sourceCheckout) {
812
+ if (renderer !== 'native-css') return [];
813
+ if (!sourceCheckout) {
814
+ throw new Error(
815
+ 'TN_CSS_UI_HOST_MISSING: ui.renderer is "native-css" but the prebuilt Android runtime was not built with ' +
816
+ 'TN_ENABLE_CSS_UI (no published prebuilt has the CSS backend); build from a runtime source checkout ' +
817
+ 'with --allow-source-build, or choose another renderer.',
818
+ );
819
+ }
820
+ return ['-PthreenativeCssUi=true'];
821
+ }
822
+
792
823
  /**
793
824
  * Stage the built UI bundle so `WebViewAssetLoader` can serve it from an HTTPS-like origin.
794
825
  *
@@ -799,7 +830,7 @@ export function stageAndroidAssets(
799
830
  */
800
831
  export function stageAndroidUi(ui, renderer, destination) {
801
832
  rmSync(destination, { force: true, recursive: true });
802
- if (renderer !== 'web') {
833
+ if (renderer !== 'web' && renderer !== 'native-css') {
803
834
  if (ui) {
804
835
  throw new Error(
805
836
  `TN_UI_BUNDLE_UNEXPECTED: a UI bundle was staged for a game whose ui.renderer is '${renderer}'. ` +
@@ -810,13 +841,20 @@ export function stageAndroidUi(ui, renderer, destination) {
810
841
  }
811
842
  if (!ui || !existsSync(ui)) {
812
843
  throw new Error(
813
- `TN_UI_BUNDLE_MISSING: ui.renderer is "web" but no built UI was found at ${ui ?? '(not provided)'}. ` +
844
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "${renderer}" but no built UI was found at ${ui ?? '(not provided)'}. ` +
814
845
  'Build the UI before packaging, or set ui.renderer to "native".',
815
846
  );
816
847
  }
817
848
  if (!statSync(ui).isDirectory()) throw new Error(`TN_UI_BUNDLE_MISSING: not a directory: ${ui}`);
818
849
  const files = listFiles(ui);
819
- if (!files.includes('index.html')) {
850
+ // `native-css` stages stylesheets (and the fonts and images beside them) that the runtime's CSS
851
+ // engine paints; there is no page to load.
852
+ if (renderer === 'native-css' && !files.some((file) => file.endsWith('.css'))) {
853
+ throw new Error(
854
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "native-css" but ${ui} has no .css, which is what the native CSS engine paints.`,
855
+ );
856
+ }
857
+ if (renderer === 'web' && !files.includes('index.html')) {
820
858
  throw new Error(
821
859
  `TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`,
822
860
  );
@@ -950,6 +988,24 @@ function alignAndroidArchive(apkPath, options = {}) {
950
988
  const apksigner = zipalign === 'zipalign' ? 'apksigner' : join(dirname(zipalign), 'apksigner');
951
989
  const keystore =
952
990
  options.keystore ?? join(process.env.HOME ?? homedir(), '.android', 'debug.keystore');
991
+ // A fresh machine has no default debug key here even after Gradle's own debug build, so it is
992
+ // created with AGP's documented debug parameters. A keystore the consumer named is never invented.
993
+ if (options.keystore === undefined && !existsSync(keystore)) {
994
+ mkdirSync(dirname(keystore), { recursive: true });
995
+ const javaHome = process.env.JAVA_HOME;
996
+ const keytool =
997
+ javaHome && existsSync(join(javaHome, 'bin', 'keytool')) ? join(javaHome, 'bin', 'keytool') : 'keytool';
998
+ const keyResult = spawn(
999
+ keytool,
1000
+ ['-genkeypair', '-keystore', keystore, '-storepass', 'android', '-alias', 'androiddebugkey',
1001
+ '-keypass', 'android', '-keyalg', 'RSA', '-keysize', '2048', '-validity', '10000',
1002
+ '-dname', 'CN=Android Debug,O=Android,C=US'],
1003
+ { encoding: 'utf8', stdio: 'inherit' },
1004
+ );
1005
+ if (keyResult.error) throw keyResult.error;
1006
+ if (keyResult.status !== 0)
1007
+ throw new Error(`${keytool} could not create the debug keystore at ${keystore}.`);
1008
+ }
953
1009
  if (!existsSync(keystore))
954
1010
  throw new Error(
955
1011
  `Cannot re-sign the aligned APK: no keystore at ${keystore}. Run a Gradle debug build once ` +
@@ -1032,6 +1088,7 @@ export async function packageAndroid(
1032
1088
  }
1033
1089
  const declared = configValue(config, orientation);
1034
1090
  orientationValue(declared.display.orientation);
1091
+ const cssUiGradleArgs = androidCssUiGradleArgs(declared.ui.renderer, sourceCheckout);
1035
1092
  const gradlew = join(androidRoot, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew');
1036
1093
  if (!existsSync(gradlew)) throw new Error(`Android Gradle wrapper is missing: ${gradlew}`);
1037
1094
  if (!existsSync(bundle)) throw new Error(`Missing native bundle: ${bundle}`);
@@ -1072,7 +1129,7 @@ export async function packageAndroid(
1072
1129
  mkdirSync(dirname(assetBundle), { recursive: true });
1073
1130
  copyFileSync(bundle, assetBundle);
1074
1131
  stageAndroidAssets(assets, join(generatedAssets, 'game'), packageRoot);
1075
- stageAndroidUi(options.ui, declared.ui.renderer === 'web' ? 'web' : 'native', join(generatedAssets, 'ui'));
1132
+ stageAndroidUi(options.ui, mobileUiRenderer(declared.ui.renderer), join(generatedAssets, 'ui'));
1076
1133
  const restoreFiles = installAndroidFiles(declared, packageRoot);
1077
1134
  try {
1078
1135
  // The subject of the build, after branding rewrote it: the submission floor is a property of
@@ -1090,6 +1147,7 @@ export async function packageAndroid(
1090
1147
  '-x',
1091
1148
  'buildAndroidFirstProofBundle',
1092
1149
  ...androidAbiGradleArgs(request.mode, extraGradleArgs),
1150
+ ...cssUiGradleArgs,
1093
1151
  ...extraGradleArgs,
1094
1152
  ];
1095
1153
  const args = process.platform === 'win32' ? baseArgs : [gradlew, ...baseArgs];
@@ -19,7 +19,7 @@ import { basename, dirname, join, resolve } from 'node:path';
19
19
  import { fileURLToPath, pathToFileURL } from 'node:url';
20
20
 
21
21
  import { assertNativeAssetsDecodable, deriveDesktopWebpSupport } from './asset-preflight.mjs';
22
- import { selectManifestAssets } from './asset-manifest.mjs';
22
+ import { listFiles, selectManifestAssets } from './asset-manifest.mjs';
23
23
  import { installPrebuilt } from './install-prebuilt.mjs';
24
24
 
25
25
  // The container helper is imported lazily by the release path only, so a debug build never loads
@@ -137,6 +137,36 @@ export const DEFAULT_DESKTOP_CONFIG = {
137
137
  window: { title: 'ThreeNative', width: 1280, height: 720, maximized: false, resizable: true },
138
138
  };
139
139
 
140
+ /**
141
+ * The packaged config's UI renderer, unresolved values included. Anything but `web` and
142
+ * `native-css` stages no UI directory, which is the fail-closed shape: a value nobody defined
143
+ * ships no overlay rather than a guess.
144
+ */
145
+ function desktopUiRenderer(config) {
146
+ const renderer = config?.ui?.renderer;
147
+ return renderer === 'web' || renderer === 'native-css' ? renderer : 'native';
148
+ }
149
+
150
+ /**
151
+ * Refuse a `native-css` game packaged against a host with no CSS backend.
152
+ *
153
+ * The CSS UI is an opt-in CMake flag, so the published prebuilt carries no `css-ui` staticlib and
154
+ * would stage the stylesheets and then paint nothing over a working game — clean logs, blank HUD.
155
+ * The backend string in the host names the rasteriser it was linked with, and that literal only
156
+ * exists in a host built with `TN_ENABLE_CSS_UI=1`, so one byte scan is the whole check. Read in
157
+ * chunks: the runtime is ~120 MB and the literal can sit anywhere in it.
158
+ */
159
+ export function assertRuntimeHasCssUi(runtimePath) {
160
+ const marker = 'CPU rasteriser, no WebView';
161
+ const chunk = readFileSync(runtimePath);
162
+ if (chunk.includes(marker)) return;
163
+ throw new Error(
164
+ `TN_CSS_UI_HOST_MISSING: ui.renderer is "native-css" but ${runtimePath} was not built with ` +
165
+ 'TN_ENABLE_CSS_UI=1 (the published prebuilt host has no CSS backend); build the host from ' +
166
+ 'source or choose another renderer.',
167
+ );
168
+ }
169
+
140
170
  function readConfig(configPath) {
141
171
  if (configPath === undefined) return DEFAULT_DESKTOP_CONFIG;
142
172
  try {
@@ -215,8 +245,8 @@ async function packageDesktopRelease(options, runtime) {
215
245
  const { bundle, executable } = compileDesktopArtifact({ ...options, output: rawOutput }, runtime, {
216
246
  sidecar: true,
217
247
  });
218
- const uiRenderer = config.ui?.renderer === 'web' ? 'web' : 'native';
219
- const uiDirectory = uiRenderer === 'web' ? join(dirname(executable), 'ui') : undefined;
248
+ const uiRenderer = desktopUiRenderer(config);
249
+ const uiDirectory = uiRenderer === 'native' ? undefined : join(dirname(executable), 'ui');
220
250
  const discovered = options.dependencies === undefined
221
251
  ? classifyDependencies(discoverRuntimeDependencies(executable, { platform: process.platform, run: options.run }), {
222
252
  platform: process.platform,
@@ -281,11 +311,11 @@ function compileDesktopArtifact(options, runtime, { sidecar = false } = {}) {
281
311
  // real origin, the way `WebViewAssetLoader` does on Android, and it is the difference between
282
312
  // `fetch` behaving as it does on web and not. A game with the native UI renderer ships neither
283
313
  // the directory nor an overlay.
284
- stageDesktopUi(
285
- options.ui,
286
- options.config === undefined ? 'native' : readConfig(options.config).ui?.renderer ?? 'native',
287
- join(dirname(output), 'ui'),
288
- );
314
+ const uiRenderer = options.config === undefined ? 'native' : desktopUiRenderer(readConfig(options.config));
315
+ // Both paths reach here, so the CSS host check is one call: a `native-css` game needs a host
316
+ // that actually has the backend, whether it is the maintainer's build or the published one.
317
+ if (uiRenderer === 'native-css') assertRuntimeHasCssUi(runtime);
318
+ stageDesktopUi(options.ui, uiRenderer, join(dirname(output), 'ui'));
289
319
  const args = [
290
320
  'compile',
291
321
  stagedEntry,
@@ -329,7 +359,7 @@ function compileDesktopArtifact(options, runtime, { sidecar = false } = {}) {
329
359
  */
330
360
  export function stageDesktopUi(ui, renderer, destination) {
331
361
  rmSync(destination, { force: true, recursive: true });
332
- if (renderer !== 'web') {
362
+ if (renderer !== 'web' && renderer !== 'native-css') {
333
363
  if (ui) {
334
364
  throw new Error(
335
365
  `TN_UI_BUNDLE_UNEXPECTED: a UI bundle was staged for a game whose ui.renderer is '${renderer}'. ` +
@@ -340,16 +370,22 @@ export function stageDesktopUi(ui, renderer, destination) {
340
370
  }
341
371
  if (!ui || !existsSync(ui)) {
342
372
  throw new Error(
343
- `TN_UI_BUNDLE_MISSING: ui.renderer is "web" but no built UI was found at ${ui ?? '(not provided)'}. ` +
373
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "${renderer}" but no built UI was found at ${ui ?? '(not provided)'}. ` +
344
374
  'Build the UI before packaging, or set ui.renderer to "native".',
345
375
  );
346
376
  }
347
377
  if (!statSync(ui).isDirectory()) throw new Error(`TN_UI_BUNDLE_MISSING: not a directory: ${ui}`);
348
- if (!existsSync(join(ui, 'index.html'))) {
378
+ // `native-css` stages stylesheets the game's own JS realm paints, so there is no page to load.
379
+ if (renderer === 'web' && !existsSync(join(ui, 'index.html'))) {
349
380
  throw new Error(
350
381
  `TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`,
351
382
  );
352
383
  }
384
+ if (renderer === 'native-css' && !listFiles(ui).some((file) => file.endsWith('.css'))) {
385
+ throw new Error(
386
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "native-css" but ${ui} has no .css, which is what the native CSS engine paints.`,
387
+ );
388
+ }
353
389
  mkdirSync(destination, { recursive: true });
354
390
  cpSync(ui, destination, { recursive: true });
355
391
  return readdirSync(destination);
@@ -378,7 +414,7 @@ export function stageDesktopFiles(
378
414
  if (existsSync(join(assets, '.threenative'))) {
379
415
  throw new Error('TN_NATIVE_ASSET_RESERVED_PATH: public/.threenative is reserved.');
380
416
  }
381
- const selected = selectManifestAssets(assets);
417
+ const { selected } = selectManifestAssets(assets);
382
418
  for (const file of selected) {
383
419
  const output = join(staging, file);
384
420
  mkdirSync(dirname(output), { recursive: true });
@@ -393,8 +429,9 @@ export function stageDesktopFiles(
393
429
  const packaged = { ...config, app: { ...(config.app ?? {}) } };
394
430
  // Flattened deliberately. The embedded config is read by a small scanner in the C++ host, and
395
431
  // `renderer` already exists at the top level as the WebGPU preference — a nested lookup for a
396
- // second `renderer` would find the wrong one. Anything but "web" is the native renderer.
397
- packaged.uiRenderer = config.ui?.renderer === 'web' ? 'web' : 'native';
432
+ // second `renderer` would find the wrong one. Anything but "web"/"native-css" is the native
433
+ // renderer.
434
+ packaged.uiRenderer = desktopUiRenderer(config);
398
435
  packaged.maxFps = config.display?.maxFps ?? 60;
399
436
  if (icon !== undefined) {
400
437
  if (!existsSync(icon) || !statSync(icon).isFile()) {