@threenative/runtime-native 0.3.4 → 0.3.6

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 (33) 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 +52 -1
  5. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  6. package/build/web/tn-native-engine-web.mjs +2 -0
  7. package/build/web/tn-native-engine-web.wasm +0 -0
  8. package/package.json +18 -6
  9. package/scripts/bundle-native-engine.mjs +303 -0
  10. package/scripts/bundle.mjs +40 -41
  11. package/scripts/check-source-list.mjs +11 -5
  12. package/scripts/desktop-distribution.mjs +33 -5
  13. package/scripts/install-prebuilt.mjs +27 -18
  14. package/scripts/package-android.mjs +63 -5
  15. package/scripts/package-desktop.mjs +50 -13
  16. package/scripts/package-engine-desktop.mjs +102 -0
  17. package/scripts/package-ios.mjs +6 -1
  18. package/scripts/profile-production.mjs +64 -9
  19. package/scripts/verify-starter-consumer.mjs +6 -5
  20. package/scripts/verify-starter-desktop-base.mjs +30 -4
  21. package/scripts/windows-installer.mjs +12 -5
  22. package/scripts/xvfb.sh +15 -0
  23. package/src/engine/player/core-addons.mjs +15 -0
  24. package/src/engine/player/core-assets.mjs +59 -0
  25. package/src/engine/player/core-audio.mjs +11 -0
  26. package/src/engine/player/core-hdr.mjs +29 -0
  27. package/src/engine/player/core-host.mjs +148 -0
  28. package/src/engine/player/core-lut.mjs +7 -0
  29. package/src/engine/player/core-textures.mjs +167 -0
  30. package/src/engine/player/core-three.mjs +294 -0
  31. package/src/engine/player/core-tsl.mjs +80 -0
  32. package/src/engine/player/core-unused.mjs +21 -0
  33. package/src/engine/player/core-webgpu.mjs +207 -0
@@ -7,7 +7,7 @@ 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);
@@ -427,7 +436,7 @@ if (process.argv[1] && existsSync(process.argv[1]) &&
427
436
  if (sourceCheckout) {
428
437
  console.log('ThreeNative runtime source checkout detected; prebuilt install is deferred to package testing.');
429
438
  } else {
430
- installPrebuilt()
439
+ installPrebuilt().then(() => installPrebuilt({ enginePlayer: true }))
431
440
  .catch((error) => {
432
441
  const reason = error instanceof Error ? error.message : String(error);
433
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));
@@ -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);
@@ -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()) {
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // Desktop package for a game with `engine: "threenative"`: the V8 engine player, the game bundled on the
3
+ // engine's own three, its cooked assets and its built UI, in one directory with a launcher. The
4
+ // player reads `native/assets.tnpk` and `ui/index.html` beside the bundle, so the layout is the contract.
5
+ import { createHash } from "node:crypto";
6
+ import { readFileSync, readdirSync, chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
7
+ import { basename, join, resolve } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+ import { bundleNativeEngine, cookNativeEngineAssets } from "./bundle-native-engine.mjs";
10
+
11
+ const PLAYER = "tn-native-engine-player-v8";
12
+
13
+ /** The launcher: the window opens with the game's title and size, and every argument reaches the player. */
14
+ export function launcher(width, height, title) {
15
+ return [
16
+ "#!/bin/sh",
17
+ 'DIR=$(cd "$(dirname "$0")" && pwd)',
18
+ ...(title ? [`TN_PLAYER_TITLE=\${TN_PLAYER_TITLE:-'${title.replaceAll("'", "'\\''")}'}`, "export TN_PLAYER_TITLE"] : []),
19
+ `: "\${TN_PLAYER_WIDTH:=${width}}"`,
20
+ `: "\${TN_PLAYER_HEIGHT:=${height}}"`,
21
+ "export TN_PLAYER_WIDTH TN_PLAYER_HEIGHT",
22
+ `exec "$DIR/${PLAYER}" "$DIR/game.js" "$@"`,
23
+ "",
24
+ ].join("\n");
25
+ }
26
+
27
+ /**
28
+ * Writes `output` as a directory: `<name>` (launcher), the player, `game.js`, `native/assets.tnpk`
29
+ * and, for a web UI, `ui/`. `bundle` and `cook` are the engine bundler's, injectable for the unit test.
30
+ */
31
+ export async function packageEngineDesktop(
32
+ { project, entry, player, ui, output, buildReceipt, width = 1280, height = 720, title },
33
+ { bundle = bundleNativeEngine, cook = cookNativeEngineAssets } = {},
34
+ ) {
35
+ if (!player || !existsSync(player)) {
36
+ throw new Error(
37
+ `TN_ENGINE_PLAYER_MISSING: engine "threenative" on desktop needs the engine player (${PLAYER}) at ${player ?? "(not set)"}.Build it (cmake --preset tn-linux -B build/tn-engine-ui -DTN_ENGINE_ONLY=ON -DTN_ENGINE_PLAYER=ON -DTN_ENGINE_PLAYER_UI_OVERLAY=ON) and set THREENATIVE_ENGINE_PLAYER, or set engine: "threejs" in threenative.config.ts to package with the legacy host.`,
38
+ );
39
+ }
40
+ rmSync(output, { force: true, recursive: true });
41
+ mkdirSync(output, { recursive: true });
42
+ const outfile = join(output, "game.js");
43
+ const bundled = await bundle({ entry, outfile });
44
+ await cook({ project, outfile });
45
+ copyFileSync(player, join(output, PLAYER));
46
+ chmodSync(join(output, PLAYER), 0o755);
47
+ if (ui) {
48
+ if (!existsSync(join(ui, "index.html")))
49
+ throw new Error(`TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`);
50
+ cpSync(ui, join(output, "ui"), { recursive: true });
51
+ }
52
+ const start = join(output, basename(output));
53
+ writeFileSync(start, launcher(width, height, title));
54
+ chmodSync(start, 0o755);
55
+ if (buildReceipt) {
56
+ const receipt = JSON.parse(readFileSync(buildReceipt, "utf8"));
57
+ if (receipt.buildProtocol !== "midway-clean-build-v1" || !/^[a-f0-9]{40}$/.test(bundled?.engineCommit)
58
+ || receipt.engineCommit !== bundled.engineCommit
59
+ || receipt.playerSha256 !== createHash("sha256").update(readFileSync(join(output, PLAYER))).digest("hex"))
60
+ throw new Error("TN_ENGINE_PROVENANCE_INVALID: rebuild packages/player from a clean matching engine checkout");
61
+ const artifacts = {};
62
+ const visit = (dir, prefix = "") => {
63
+ for (const item of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
64
+ const relative = prefix + item.name;
65
+ if (item.isDirectory()) visit(join(dir, item.name), `${relative}/`);
66
+ else if (item.isFile()) artifacts[relative] = createHash("sha256").update(readFileSync(join(dir, item.name))).digest("hex");
67
+ else throw new Error(`TN_ENGINE_PROVENANCE_SYMLINK: ${relative}`);
68
+ }
69
+ };
70
+ visit(output);
71
+ const directorySha256 = createHash("sha256").update(Object.entries(artifacts).map(([file, digest]) => `${file} ${digest}`).join("\n")).digest("hex");
72
+ writeFileSync(join(output, "midway-provenance.json"), JSON.stringify({ buildProtocol: receipt.buildProtocol, engineCommit: bundled.engineCommit, artifacts, directorySha256 }));
73
+ }
74
+ console.log(`ThreeNative desktop artifact: ${output}`);
75
+ return output;
76
+ }
77
+
78
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
79
+ const args = process.argv.slice(2);
80
+ const flags = new Map();
81
+ for (let i = 0; i < args.length; i += 2) {
82
+ if (!["--project", "--entry", "--player", "--ui", "--output", "--build-receipt", "--width", "--height", "--title"].includes(args[i]) || !args[i + 1] || flags.has(args[i]))
83
+ throw new Error(`TN_ENGINE_PACKAGE_ARGS: invalid or repeated option ${args[i]}`);
84
+ flags.set(args[i], args[i + 1]);
85
+ }
86
+ try {
87
+ await packageEngineDesktop({
88
+ project: flags.get("--project"),
89
+ entry: flags.get("--entry"),
90
+ player: flags.get("--player"),
91
+ ui: flags.get("--ui"),
92
+ output: flags.get("--output"),
93
+ buildReceipt: flags.get("--build-receipt"),
94
+ width: flags.has("--width") ? Number(flags.get("--width")) : undefined,
95
+ height: flags.has("--height") ? Number(flags.get("--height")) : undefined,
96
+ title: flags.get("--title"),
97
+ });
98
+ } catch (error) {
99
+ console.error(error instanceof Error ? error.message : String(error));
100
+ process.exitCode = 1;
101
+ }
102
+ }
@@ -20,6 +20,7 @@ import { createRequire } from 'node:module';
20
20
  import { spawnSync } from 'node:child_process';
21
21
  import { assertNativeAssetsDecodable, deriveIosWebpSupport } from './asset-preflight.mjs';
22
22
  import { listFiles, selectManifestAssets } from './asset-manifest.mjs';
23
+ import { mobileUiRenderer } from './package-android.mjs';
23
24
  import { downloadReleaseArtifact } from './install-prebuilt.mjs';
24
25
 
25
26
  export const NATIVE_ORIENTATIONS = ['landscape', 'portrait', 'sensor'];
@@ -513,7 +514,11 @@ export function stageIosSimulatorApp({
513
514
  const game = join(output, 'game');
514
515
  rmSync(game, { force: true, recursive: true });
515
516
  mkdirSync(game, { recursive: true });
516
- stageIosUi(ui, declared.ui?.renderer === 'web' ? 'web' : 'native', join(output, 'ui'));
517
+ // The CSS UI has an Android build and no iOS one yet: refused by name, not flattened to native.
518
+ if (declared.ui?.renderer === 'native-css') {
519
+ throw new Error('TN_UI_RENDERER_UNSUPPORTED: ui.renderer "native-css" has no iOS build');
520
+ }
521
+ stageIosUi(ui, mobileUiRenderer(declared.ui?.renderer), join(output, 'ui'));
517
522
  const plist = join(output, 'Info.plist');
518
523
  const infoPlist = readIosInfoPlist(plist, convertInfoPlist);
519
524
  writeFileSync(plist, renderIosInfoPlist(infoPlist.source, declared));
@@ -3,7 +3,7 @@
3
3
  import { createServer } from 'node:http';
4
4
  import { execFile, execFileSync, spawn } from 'node:child_process';
5
5
  import { existsSync } from 'node:fs';
6
- import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';
6
+ import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';
7
7
  import { createRequire } from 'node:module';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
@@ -1085,6 +1085,23 @@ export async function installNativeProfileEntry(project, target, options) {
1085
1085
  await writeFile(profileMarkerPath, profileMarker);
1086
1086
  await writeFile(entryPath, source);
1087
1087
  await setNativeProfileEntry(project, 'src/profile-native-entry.ts', options.renderSize);
1088
+ if (target === 'desktop') await pinThreejsDesktopHost(project);
1089
+ }
1090
+
1091
+ /**
1092
+ * A desktop profile launches the Three.js host's packaged executable (`mystral`), but a config that
1093
+ * sets no `engine` now builds a directory around the V8 engine player. Name the override in the
1094
+ * staged copy, once, and leave an `engine` the game declares as authored.
1095
+ */
1096
+ export async function pinThreejsDesktopHost(project) {
1097
+ const configPath = join(project, 'threenative.config.ts');
1098
+ const config = await readFile(configPath, 'utf8').catch(() => undefined);
1099
+ if (config === undefined || /^\s*["']?engine["']?\s*:/mu.test(config)) return;
1100
+ const opening = /(?:=|export default)\s*\{/u;
1101
+ if (!opening.test(config)) {
1102
+ throw new ProductionEvidenceError('TN_PROD_ENGINE_PIN_FAILED', `${configPath} has no config object to pin engine: "threejs" into.`);
1103
+ }
1104
+ await writeFile(configPath, config.replace(opening, '$&\n engine: "threejs",'));
1088
1105
  }
1089
1106
 
1090
1107
  export async function setNativeProfileEntry(project, entry, renderSize = undefined) {
@@ -1712,6 +1729,7 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1712
1729
  dirty: context.sourceState.dirty,
1713
1730
  ...(context.sourceState.diffSha === undefined ? {} : { diffSha: context.sourceState.diffSha }),
1714
1731
  sha: context.sourceSha,
1732
+ ...(context.sourceState.rawStatus === undefined ? {} : { snapshot: { rawStatus: context.sourceState.rawStatus, normalizedTrackedFiles: context.sourceState.normalizedTrackedFiles } }),
1715
1733
  },
1716
1734
  target,
1717
1735
  timestamps: { endedAt: new Date().toISOString(), startedAt },
@@ -2271,15 +2289,52 @@ function applyNegativeControl(input, control) {
2271
2289
  return evidence;
2272
2290
  }
2273
2291
 
2274
- async function currentSourceState() {
2292
+ export async function currentSourceState(root = commandRoot, execute = execFileAsync) {
2275
2293
  try {
2276
- const [{ stdout: sha }, { stdout: status }, { stdout: diff }] = await Promise.all([
2277
- execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: commandRoot }),
2278
- execFileAsync('git', ['status', '--porcelain'], { cwd: commandRoot }),
2279
- execFileAsync('git', ['diff', 'HEAD'], { cwd: commandRoot }),
2280
- ]);
2281
- const dirty = status.trim().length > 0;
2282
- return { dirty, ...(dirty ? { diffSha: sha256(Buffer.from(diff)) } : {}), sha: sha.trim() };
2294
+ // Git can report an LF rewrite of a CRLF checkout as modified even though its
2295
+ // normalized candidate blob is identical. Preserve that raw status and prove
2296
+ // each byte identity explicitly; an empty diff alone never grants cleanliness.
2297
+ const git = async (...args) => (await execute('git', ['--literal-pathspecs', ...args], { cwd: root })).stdout;
2298
+ const sha = (await git('rev-parse', 'HEAD')).trim();
2299
+ const rawStatus = await git('status', '--porcelain=v1', '-z', '--untracked-files=all');
2300
+ const diff = await git('diff', '--no-ext-diff', '--no-textconv', 'HEAD');
2301
+ let dirty = rawStatus.length > 0;
2302
+ const normalizedTrackedFiles = [];
2303
+ const entries = rawStatus.split('\0').filter(Boolean);
2304
+ if (dirty && diff === '' && entries.every((entry) => entry.startsWith(' M '))) {
2305
+ for (const entry of entries) {
2306
+ const name = entry.slice(3);
2307
+ const file = join(root, name);
2308
+ if (!(await lstat(file)).isFile()) break;
2309
+ const head = /^(100644|100755) blob ([a-f0-9]{40,64})\t/u.exec(await git('ls-tree', '-z', 'HEAD', '--', name));
2310
+ const index = /^(100644|100755) ([a-f0-9]{40,64}) 0\t/u.exec(await git('ls-files', '--stage', '-z', '--', name));
2311
+ if (!head || !index || head[1] !== index[1] || head[2] !== index[2]) break;
2312
+ const raw = await readFile(file);
2313
+ const before = sha256(raw);
2314
+ const { stdout: headBytes } = await execute('git', ['cat-file', 'blob', head[2]], { cwd: root, encoding: 'buffer', maxBuffer: 16 * 1024 * 1024 });
2315
+ // Restrict the accepted transformation to line endings. Git clean filters
2316
+ // or working-tree encodings must never conceal executable byte changes.
2317
+ const lfBytes = Buffer.from(raw.toString('latin1').replace(/\r\n/gu, '\n'), 'latin1');
2318
+ if (!Buffer.isBuffer(headBytes) || !lfBytes.equals(headBytes)) break;
2319
+ const worktreeBlob = (await git('hash-object', `--path=${name}`, '--', name)).trim();
2320
+ if (worktreeBlob !== head[2] || sha256(await readFile(file)) !== before) break;
2321
+ normalizedTrackedFiles.push({ path: name, headBlob: head[2], worktreeBlob, rawSha256: before, normalization: 'crlf-to-lf-only' });
2322
+ }
2323
+ dirty = normalizedTrackedFiles.length !== entries.length;
2324
+ }
2325
+ // A changing tree or HEAD is never a coherent candidate snapshot.
2326
+ if ((await git('rev-parse', 'HEAD')).trim() !== sha ||
2327
+ (await git('status', '--porcelain=v1', '-z', '--untracked-files=all')) !== rawStatus) dirty = true;
2328
+ if (!dirty && normalizedTrackedFiles.length) {
2329
+ for (const proof of normalizedTrackedFiles) {
2330
+ const file = join(root, proof.path);
2331
+ if (!(await lstat(file)).isFile() || sha256(await readFile(file)) !== proof.rawSha256) dirty = true;
2332
+ }
2333
+ if ((await git('diff', '--no-ext-diff', '--no-textconv', 'HEAD')) !== '') dirty = true;
2334
+ if ((await git('rev-parse', 'HEAD')).trim() !== sha ||
2335
+ (await git('status', '--porcelain=v1', '-z', '--untracked-files=all')) !== rawStatus) dirty = true;
2336
+ }
2337
+ return { dirty, ...(dirty ? { diffSha: sha256(Buffer.from(diff)) } : {}), sha, rawStatus, normalizedTrackedFiles };
2283
2338
  } catch {
2284
2339
  return { dirty: true, diffSha: sha256(Buffer.from('source-state-unavailable')), sha: '0000000' };
2285
2340
  }
@@ -6,6 +6,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFi
6
6
  import { release as osRelease } from 'node:os';
7
7
  import { basename, join, resolve } from 'node:path';
8
8
  import { pathToFileURL } from 'node:url';
9
+ import { desktopLaunchTarget } from './desktop-distribution.mjs';
9
10
 
10
11
  export const CONSUMER_GAMEPLAY_SCENARIO = 'playtests/production-readiness.playtest.json';
11
12
  export const CONSUMER_REQUIRED_TARGETS = ['desktop', 'android'];
@@ -379,11 +380,11 @@ function discoverConsumerArtifact(projectRoot, target) {
379
380
  if (target === 'desktop') {
380
381
  const manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
381
382
  const name = basename(String(manifest.name ?? 'starter').replace(/^@[^/]+\//u, ''));
382
- return join(
383
- projectRoot,
384
- 'dist-native',
385
- `${name}${process.platform === 'win32' ? '.exe' : ''}`,
386
- );
383
+ const executable = `${name}${process.platform === 'win32' ? '.exe' : ''}`;
384
+ const artifact = join(projectRoot, 'dist-native', executable);
385
+ // A missing artifact stays the caller's `ARTIFACT_MISSING`; a container directory (PRD-637) is
386
+ // run through its launcher.
387
+ return existsSync(artifact) ? desktopLaunchTarget(artifact, executable) : artifact;
387
388
  }
388
389
  const apks = consumerArtifactFiles(join(projectRoot, 'dist-native'), (file) => file.endsWith('.apk'));
389
390
  if (apks.length === 0) {