@threenative/runtime-native 0.3.6 → 0.3.9

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.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/runtime-native",
3
- "version": "0.3.6",
3
+ "version": "0.3.9",
4
4
  "description": "ThreeNative-owned native host for desktop and Android",
5
5
  "keywords": [
6
6
  "threenative",
@@ -29,6 +29,8 @@
29
29
  "files": [
30
30
  "build/web/tn-native-engine-web.mjs",
31
31
  "build/web/tn-native-engine-web.wasm",
32
+ "build/web/tn-native-engine-web-threads.mjs",
33
+ "build/web/tn-native-engine-web-threads.wasm",
32
34
  "LICENSE",
33
35
  "NOTICE",
34
36
  "README.md",
@@ -78,15 +80,15 @@
78
80
  "publint": "0.3.22",
79
81
  "three": "0.185.1",
80
82
  "vitest": "4.1.10",
81
- "@threenative/playtest": "0.3.6"
83
+ "@threenative/playtest": "0.3.9"
82
84
  },
83
85
  "dependencies": {
84
86
  "pngjs": "7.0.0",
85
87
  "esbuild": "0.27.0",
86
88
  "typescript": "npm:@typescript/typescript6@6.0.2",
87
- "@threenative/three-native": "0.3.6",
88
- "@threenative/assets": "0.3.7",
89
- "@threenative/core": "0.3.6"
89
+ "@threenative/core": "0.3.9",
90
+ "@threenative/assets": "0.3.10",
91
+ "@threenative/three-native": "0.3.9"
90
92
  },
91
93
  "scripts": {
92
94
  "deps:download": "node scripts/download-deps.mjs",
@@ -94,6 +96,7 @@
94
96
  "deps:sbom": "node scripts/generate-native-sbom.mjs --out .runtime/sbom",
95
97
  "deps:sbom:check": "node scripts/generate-native-sbom.mjs --check --sbom .runtime/sbom/native-dependencies.cdx.json --inventory .runtime/sbom/native-license-inventory.json",
96
98
  "native:build": "node scripts/download-deps.mjs && node scripts/native-build.mjs",
99
+ "wasm:build": "node scripts/build-wasm.mjs",
97
100
  "native:coverage": "sh ../../scripts/xvfb.sh node scripts/measure-native-coverage.mjs",
98
101
  "native:test:cpp": "node scripts/measure-native-coverage.mjs --ctest",
99
102
  "native:test:asan": "node scripts/measure-native-coverage.mjs --sanitizers",
@@ -125,6 +125,32 @@ export function androidSigningGradleEnvironment(signing, environment = process.e
125
125
  };
126
126
  }
127
127
 
128
+ // Gradle 8.13, the wrapper this project pins, runs on JDK 23 or earlier. On a newer one it stops with
129
+ // the bare version string as its only message ("27.0.1.0.3" on JDK 27).
130
+ const ANDROID_GRADLE_NEWEST_JDK = 23;
131
+
132
+ /**
133
+ * The environment Gradle needs, decided where the tools can be measured: the SDK at the default path
134
+ * that `doctor` and `findAndroidBuildTool` already read, and a JDK Gradle can run on.
135
+ */
136
+ export function androidGradleEnvironment(environment = process.env, { home = homedir() } = {}) {
137
+ if (environment.ANDROID_HOME || environment.ANDROID_SDK_ROOT) return environment;
138
+ const sdk = join(home, 'Android', 'Sdk');
139
+ return existsSync(sdk) ? { ...environment, ANDROID_HOME: sdk } : environment;
140
+ }
141
+
142
+ /** Gradle on a JDK it cannot read prints only the version string, so a failure names the JDK itself. */
143
+ export function androidGradleFailure(status, environment = process.env, spawn = spawnSync) {
144
+ const java = environment.JAVA_HOME ? join(environment.JAVA_HOME, 'bin', 'java') : 'java';
145
+ const probe = spawn(java, ['-version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 5_000 });
146
+ const major = /version "(\d+)/u.exec(`${probe?.stdout ?? ''}${probe?.stderr ?? ''}`)?.[1];
147
+ const jdk =
148
+ major !== undefined && Number(major) > ANDROID_GRADLE_NEWEST_JDK
149
+ ? ` TN_ANDROID_JDK_UNSUPPORTED: ${java} is JDK ${major}, and Android builds run on JDK ${ANDROID_GRADLE_NEWEST_JDK} or earlier. Install JDK 17 and set JAVA_HOME to it.`
150
+ : '';
151
+ return `Gradle exited with code ${status ?? 'unknown'}.${jdk}`;
152
+ }
153
+
128
154
  /** Locate an Android build tool on `PATH`, then in the SDK's `build-tools/<version>/`. */
129
155
  export function findAndroidBuildTool(name, environment = process.env) {
130
156
  const suffix = process.platform === 'win32' ? '.bat' : '';
@@ -1152,19 +1178,17 @@ export async function packageAndroid(
1152
1178
  ];
1153
1179
  const args = process.platform === 'win32' ? baseArgs : [gradlew, ...baseArgs];
1154
1180
  const spawn = options.spawnSync ?? spawnSync;
1181
+ const gradleEnvironment = androidGradleEnvironment(environment);
1155
1182
  const result = spawn(command, args, {
1156
1183
  cwd: androidRoot,
1157
1184
  encoding: 'utf8',
1158
1185
  // The signing values reach Gradle only as project properties from the game's environment; the
1159
1186
  // keystore path was resolved against the consumer project above. Nothing here logs them.
1160
- ...(signing === undefined
1161
- ? {}
1162
- : { env: androidSigningGradleEnvironment(signing, environment) }),
1187
+ env: signing === undefined ? gradleEnvironment : androidSigningGradleEnvironment(signing, gradleEnvironment),
1163
1188
  stdio: 'inherit',
1164
1189
  });
1165
1190
  if (result.error) throw result.error;
1166
- if (result.status !== 0)
1167
- throw new Error(`Gradle exited with code ${result.status ?? 'unknown'}.`);
1191
+ if (result.status !== 0) throw new Error(androidGradleFailure(result.status, gradleEnvironment, spawn));
1168
1192
  const candidates = androidArtifactCandidates(packageRoot, request);
1169
1193
  const artifact = candidates.find((candidate) => existsSync(candidate));
1170
1194
  if (artifact === undefined) {
@@ -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, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';
6
+ import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, 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';
@@ -55,6 +55,13 @@ const SLOW_STARTUP_DELAY_MS = 5_100;
55
55
  const FRAME_SAMPLE_BATCH_SIZE = 30;
56
56
  // Android logcat truncates long lines, so native samples use a smaller JSON batch.
57
57
  const NATIVE_FRAME_SAMPLE_BATCH_SIZE = 5;
58
+ const collectorStartedAt = Date.now();
59
+ // One stderr line as each phase starts: the evidence JSON prints only at the end, so a run that a
60
+ // CI watchdog kills still names the phase it was in.
61
+ export function phaseLine(name, elapsedMs) {
62
+ return `TN_PROD_PHASE ${name} ${(elapsedMs / 1_000).toFixed(1)}s\n`;
63
+ }
64
+ const reportPhase = (name) => process.stderr.write(phaseLine(name, Date.now() - collectorStartedAt));
58
65
  // The wall-clock a paced fixed step gives each tick, so a synthetic workload's tick budget stands
59
66
  // in for the seconds it names and the host's render loop actually presents frames while it runs.
60
67
  const PRODUCTION_TICK_INTERVAL_MS = 1_000 / 60;
@@ -307,11 +314,13 @@ export async function collectProduction(options, context, runId) {
307
314
  const project = join(temporaryRoot, 'platformer');
308
315
  const startedAt = new Date().toISOString();
309
316
  try {
317
+ reportPhase('stage');
310
318
  await stageProductionProject(options, project, tools);
311
319
  tools.workloadSourceHash = await hashPath(join(project, 'src'));
312
320
  const scenarios = await writeRunScenarios(project, options);
313
321
  const artifactsRoot = join(project, 'artifacts', 'production');
314
322
  await mkdir(artifactsRoot, { recursive: true });
323
+ if (webDisplay !== undefined) reportPhase('web');
315
324
  const web = webDisplay === undefined ? undefined : await collectWeb(project, scenarios, artifactsRoot, options, tools, webDisplay);
316
325
  const native = nativeTargets.has(options.target) || options.target === 'desktop-pair'
317
326
  ? await collectNative(project, scenarios, artifactsRoot, options, tools)
@@ -478,14 +487,14 @@ async function packLocalPackage(directory, destination) {
478
487
  return join(destination, archive);
479
488
  }
480
489
 
481
- function packageSourceFlag(name) {
490
+ export function packageSourceFlag(name) {
482
491
  if (name === 'create-threenative') return '--cli-package';
483
- if (name === 'threenative-blender-mcp') return '--blender-mcp-package';
484
- if (name === 'threenative-engine-mcp') return '--engine-mcp-package';
485
492
  if (name.startsWith('@threenative/')) {
486
493
  const suffix = name.slice('@threenative/'.length);
487
494
  return `--threenative-${suffix}-package`;
488
495
  }
496
+ // scripts/workspace-packages.ts workspacePackageSourceFlag: an unscoped tool package drops its prefix.
497
+ if (name.startsWith('threenative-')) return `--${name.slice('threenative-'.length)}-package`;
489
498
  throw new Error(`TN_PROD_PACKAGE_FLAG_UNSUPPORTED: ${name}`);
490
499
  }
491
500
 
@@ -735,6 +744,7 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
735
744
 
736
745
  async function collectNative(project, scenarios, artifactsRoot, options, tools) {
737
746
  const target = options.target === 'desktop-pair' || options.target === 'desktop' ? 'desktop' : options.target.startsWith('ios') ? 'ios' : 'android';
747
+ reportPhase(`${target}-build`);
738
748
  await installNativeProfileEntry(project, target, options);
739
749
  const build = await prepareNativeWorkload(project, target, options);
740
750
  if (build.status !== 0) {
@@ -756,9 +766,11 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
756
766
  const runs = [];
757
767
  const startups = [];
758
768
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
769
+ reportPhase(`${target}-startup-${coldStart + 1}`);
759
770
  const startup = await runNativeScenario(project, target, scenarios.nativeStartupPath, join(artifactsRoot, `native-startup-${coldStart + 1}`), options, artifactPath, tools, scenarios.timeoutMs);
760
771
  startups.push(startup);
761
772
  for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
773
+ reportPhase(`${target}-workload-${coldStart + 1}-${repetition + 1}`);
762
774
  runs.push(await runNativeScenario(
763
775
  project,
764
776
  target,
@@ -849,7 +861,7 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
849
861
  const runner = await import(pathToFileURL(modulePath).href);
850
862
  const mailbox = new runner.LocalDeviceMailbox();
851
863
  const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath });
852
- const driver = createDesktopDriver(artifactPath, project, options, mailboxRoot);
864
+ const driver = createDesktopDriver(artifactPath, project, options, mailboxRoot, mailbox);
853
865
  const transport = {
854
866
  capabilities: innerTransport.capabilities,
855
867
  call: innerTransport.call.bind(innerTransport),
@@ -904,6 +916,9 @@ export function desktopFailureRun(error, consoleOutput, elapsedMs, cleanupError
904
916
  try { return sanitizeManifest(value); } catch { return fallback; }
905
917
  };
906
918
  const diagnostic = cleanupError?.diagnostic ?? error?.diagnostic;
919
+ // The code and the syscall name carry no path, so a redacted failure can still name its cause.
920
+ const cause = [/^(?:E[A-Z]{2,}|TN_[A-Z0-9_]+)\b/u.exec(error?.message ?? '')?.[0], /^[a-z]+$/u.exec(error?.syscall ?? '')?.[0]]
921
+ .filter(Boolean).join(' ');
907
922
  return {
908
923
  elapsedMs, status: 2, screenshot: undefined, series: undefined,
909
924
  report: {
@@ -911,7 +926,7 @@ export function desktopFailureRun(error, consoleOutput, elapsedMs, cleanupError
911
926
  diagnostics: [retain(diagnostic ?? {
912
927
  code: 'TN_PROD_PLAYTEST_FAILED', severity: 'error',
913
928
  message: error instanceof Error ? error.message : String(error),
914
- }, { code: 'TN_PROD_REDACTION', severity: 'error', message: 'Unsafe native error details withheld.' })],
929
+ }, { code: 'TN_PROD_REDACTION', severity: 'error', message: `Unsafe native error details withheld${cause ? ` (${cause})` : ''}.` })],
915
930
  observations: { console: consoleOutput.map((entry) => retain(entry, {
916
931
  type: 'error', text: 'TN_PROD_REDACTION: unsafe native console entry withheld.',
917
932
  })) },
@@ -949,7 +964,7 @@ async function readResolutionScaleSetting(project, options) {
949
964
  return rendererResolutionScaleSetting(config, options.target);
950
965
  }
951
966
 
952
- function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
967
+ function createDesktopDriver(artifactPath, project, options, mailboxRoot, mailbox) {
953
968
  let child;
954
969
  let output = '';
955
970
  let stopping;
@@ -970,12 +985,16 @@ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
970
985
  readFile: async (path) => readFile(path, 'utf8').catch((error) => error?.code === 'ENOENT' ? undefined : Promise.reject(error)),
971
986
  removeFile: async (path) => rm(path, { force: true }).catch(() => undefined),
972
987
  screenshot: async (path) => {
973
- const temporary = `${screenshotRequestPath}.tmp`;
974
- await writeFile(temporary, path, 'utf8');
975
- await rename(temporary, screenshotRequestPath);
988
+ await mailbox.write(screenshotRequestPath, path);
976
989
  const deadline = Date.now() + DESKTOP_SCREENSHOT_TIMEOUT_MS;
977
990
  while (Date.now() < deadline) {
978
991
  if (await nonBlankPng(path)) return;
992
+ // The host consumed the one request, so a blank capture stays blank until asked again. A frame read while
993
+ // pipelines still compile can be all zero (hosted Metal, run 41356903254).
994
+ if (await blankPng(path)) {
995
+ await rm(path, { force: true }).catch(() => undefined);
996
+ await mailbox.write(screenshotRequestPath, path);
997
+ }
979
998
  await new Promise((resolve) => setTimeout(resolve, 25));
980
999
  }
981
1000
  throw new Error('TN_PROD_NATIVE_SCREENSHOT_UNAVAILABLE');
@@ -2446,6 +2465,16 @@ async function nonBlankPng(path) {
2446
2465
  }
2447
2466
  }
2448
2467
 
2468
+ async function blankPng(path) {
2469
+ try {
2470
+ const value = await readFile(path);
2471
+ PNG.sync.read(value);
2472
+ return !isNonBlankFrame(value);
2473
+ } catch {
2474
+ return false;
2475
+ }
2476
+ }
2477
+
2449
2478
  function isNonBlankFrame(value) {
2450
2479
  if (!Buffer.isBuffer(value)) return false;
2451
2480
  try {
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { createHash } from 'node:crypto';
5
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
5
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
6
6
  import { basename, dirname, join, resolve } from 'node:path';
7
7
  import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  import { PNG } from 'pngjs';
@@ -13,7 +13,6 @@ import {
13
13
  parseLinkedLibraries,
14
14
  resolveContainer,
15
15
  } from './desktop-distribution.mjs';
16
- import { verifyStarterConsumerGameplay } from './verify-starter-consumer.mjs';
17
16
  import { inspectContainerBrand } from './inspect-container-brand.mjs';
18
17
  import { inspectMacosIcon } from './inspect-macos-icon.mjs';
19
18
 
@@ -36,7 +35,11 @@ const ASSET_PIXEL_FLOOR = 100;
36
35
  // pennant, against 0 in the same frame with the pennant cropped away.
37
36
  const PROOF_MAGENTA_MIN_MARGIN = 40;
38
37
  // Corroborating cyan, counted only inside the magenta bounds so the background cannot supply it.
39
- const PROOF_CYAN_MIN_MARGIN = 70;
38
+ // Under the Unreal default look (filmic tone curve, metered exposure; PRD-723) the pennant's cyan
39
+ // renders pale: measured on the lavapipe capture of Actions run 40214259234 it is rgb(195,240,243),
40
+ // a channel margin of 45, where the old look left 94 to 103. The magenta margin above is 40, and
41
+ // a margin of 40 keeps 463 of the pennant's cyan pixels where a margin of 70 kept 40.
42
+ const PROOF_CYAN_MIN_MARGIN = 40;
40
43
  const PROOF_CYAN_IN_BOUNDS_FLOOR = 50;
41
44
  // A proof region may occupy up to a quarter of a rendered frame; a wash that reaches almost every
42
45
  // part of the frame must not count as localized evidence.
@@ -300,7 +303,65 @@ function judgeStarterRun({ artifact, brand, frames, log, logPath, reportPath, sc
300
303
 
301
304
  export { desktopLaunchTarget };
302
305
 
303
- export function verifyStarterDesktop({ frames = 300, project = process.cwd() } = {}) {
306
+ function verifyOwnedDesktop({ frames, project, artifact, artifactDirectory, logPath, run, env }) {
307
+ const cli = join(project, 'node_modules', '@threenative', 'playtest', 'dist', 'runner', 'cli.js');
308
+ if (!existsSync(cli)) throw new Error(`TN_NATIVE_STARTER_RUNNER_MISSING: ${cli}`);
309
+ const temporary = mkdtempSync(join(artifactDirectory, 'smoke-'));
310
+ const scenario = join(temporary, 'native-smoke.playtest.json');
311
+ const captures = join(artifactDirectory, 'native-smoke');
312
+ const screenshot = join(captures, 'after.png');
313
+ const timeout = Number(env.TN_STARTER_TIMEOUT_MS ?? 300_000);
314
+ try {
315
+ rmSync(screenshot, { force: true });
316
+ writeFileSync(scenario, JSON.stringify({ name: 'native-smoke', schemaVersion: 1,
317
+ steps: [{ kind: 'wait', waitTicks: 1, label: 'native-smoke' }],
318
+ assert: { diagnostics: { runtimeReady: true, noConsoleErrors: true, noRuntimeDiagnostics: true } },
319
+ artifacts: { screenshots: 'after' } }));
320
+ const runner = [cli, scenario, '--target', 'desktop', '--project', project,
321
+ '--artifacts', captures, '--executable', artifact, '--host-arg', '--windowed'];
322
+ // The completion window admits only a VSYNC=0 player and, on Linux, a named display. The private
323
+ // Xvfb is that display unless the caller opted into the session's with TN_PLAYTEST_HOST_DISPLAY.
324
+ const linux = process.platform === 'linux';
325
+ const result = run(linux ? 'sh' : process.execPath, linux
326
+ ? [join(dirname(fileURLToPath(import.meta.url)), 'xvfb.sh'), 'env', 'TN_PLAYTEST_HOST_DISPLAY=1', process.execPath, ...runner]
327
+ : runner, {
328
+ cwd: project, encoding: 'utf8', timeout, maxBuffer: 32 * 1024 * 1024,
329
+ env: { ...env, TN_PLAYER_VSYNC: '0', TN_PLAYTEST_COMPLETION_WINDOW_LABEL: 'native-smoke',
330
+ TN_PLAYTEST_COMPLETION_WINDOW_MIN_FRAMES: String(frames),
331
+ TN_PLAYTEST_COMPLETION_WINDOW_TIMEOUT_MS: String(Math.max(1, timeout - 10_000)) },
332
+ });
333
+ writeFileSync(logPath, `${result.stdout ?? ''}\n${result.stderr ?? ''}`);
334
+ if (result.error || result.signal || result.status !== 0)
335
+ throw new Error(`TN_NATIVE_STARTER_SMOKE: runner failed: ${result.error?.message ?? result.signal ?? result.stderr ?? result.status}`);
336
+ const report = JSON.parse(result.stdout);
337
+ if (report?.pass !== true || !report.assertionResults?.length
338
+ || report.assertionResults.some((assertion) => assertion.pass !== true))
339
+ throw new Error('TN_NATIVE_STARTER_SMOKE: runner assertions missing or failed');
340
+ const completion = report.acquisition?.completionWindow;
341
+ const samples = completion?.samples;
342
+ if (completion?.source !== 'present-return' || completion.timebase !== 'steady-clock-ms'
343
+ || !Array.isArray(samples) || samples.length < frames || samples.some((sample, index) =>
344
+ !Number.isSafeInteger(sample.sequence) || sample.sequence < 1 || !Number.isFinite(sample.completedAtMs)
345
+ || sample.completedAtMs < 0 || (index > 0 && (sample.sequence !== samples[index - 1].sequence + 1
346
+ || sample.completedAtMs <= samples[index - 1].completedAtMs))))
347
+ throw new Error(`TN_NATIVE_STARTER_SMOKE: missing ${frames} contiguous native completion observations`);
348
+ const image = PNG.sync.read(readFileSync(screenshot));
349
+ const colors = new Set();
350
+ let opaque = 0;
351
+ for (let index = 0; index < image.data.length; index += 4) {
352
+ if (image.data[index + 3] !== 0) opaque += 1;
353
+ colors.add(image.data.readUInt32BE(index));
354
+ }
355
+ if (opaque === 0 || colors.size < 2) throw new Error('native smoke screenshot is blank');
356
+ return { artifact, gate: 'native-smoke', pass: true, frames: samples.length, requestedFrames: frames,
357
+ completion, screenshot, width: image.width, height: image.height, assertions: report.assertionResults };
358
+ } finally {
359
+ rmSync(temporary, { recursive: true, force: true });
360
+ }
361
+ }
362
+
363
+ export function verifyStarterDesktop({ frames = 300, project = process.cwd(), run = spawnSync, env = process.env } = {}) {
364
+ frames = frameCount(frames);
304
365
  const projectRoot = resolve(project);
305
366
  const manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
306
367
  const projectName = basename(String(manifest.name ?? 'starter').replace(/^@[^/]+\//u, ''));
@@ -318,13 +379,8 @@ export function verifyStarterDesktop({ frames = 300, project = process.cwd() } =
318
379
  // The engine player takes neither `--frames` nor `--screenshot` and prints none of the legacy
319
380
  // host's markers, so the playtest runner drives it (PRD-637). The report keeps the same path.
320
381
  if (isEnginePlayerLaunch(launch)) {
321
- const { row } = verifyStarterConsumerGameplay({ project: projectRoot, target: 'desktop' });
322
- const report = {
323
- artifact: launch,
324
- assertions: row.assertions,
325
- gate: 'consumer-playtest',
326
- pass: row.pass === true,
327
- };
382
+ const report = verifyOwnedDesktop({ frames, project: projectRoot, artifact: launch,
383
+ artifactDirectory, logPath, run, env });
328
384
  writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
329
385
  return report;
330
386
  }
@@ -469,8 +525,8 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar
469
525
  process.exit(0);
470
526
  }
471
527
  const report = options.root ? verifyStarterContainer(options) : verifyStarterDesktop(options);
472
- if (report.gate === 'consumer-playtest') {
473
- console.log(`starter desktop gate passed: engine player, ${report.assertions} playtest assertions`);
528
+ if (report.gate === 'native-smoke') {
529
+ console.log(`starter desktop gate passed: ${report.frames} native presents, ${report.assertions.length} playtest assertions, screenshot ${report.screenshot}`);
474
530
  process.exit(0);
475
531
  }
476
532
  const brand = report.brand === undefined || report.brand === null
package/scripts/xvfb.sh CHANGED
@@ -16,6 +16,17 @@ case "$(uname -s 2>/dev/null || echo unknown)" in
16
16
  *) exec "$@" ;;
17
17
  esac
18
18
 
19
+ # Preserve the same explicit host-display opt-in as the playtest runner.
20
+ case "${TN_PLAYTEST_HOST_DISPLAY:-}" in
21
+ 1|[tT][rR][uU][eE])
22
+ if [ -z "${DISPLAY:-}" ]; then
23
+ echo "TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: the requested host display requires DISPLAY." >&2
24
+ exit 2
25
+ fi
26
+ exec "$@"
27
+ ;;
28
+ esac
29
+
19
30
  if ! command -v Xvfb >/dev/null 2>&1; then
20
31
  echo "scripts/xvfb.sh: Xvfb is required for headless Linux runs and is not installed." >&2
21
32
  echo "scripts/xvfb.sh: install it (Debian/Ubuntu 'xvfb', Arch 'xorg-server-xvfb', Fedora" >&2
@@ -114,11 +125,24 @@ for candidate in xcompmgr picom compton; do
114
125
  done
115
126
 
116
127
  # Owning _NET_WM_CM_S0 takes a moment, and a command that reaches the runtime first sees a display
117
- # with no compositing manager and gets the refusal. The same quarter second the runner's TypeScript
118
- # path waits, followed by the same liveness check: a compositor that already died is not one we can
119
- # report as running, and the refusal then names the real state.
128
+ # with no compositing manager and gets the refusal. A compositor maps a window on the root as soon
129
+ # as it is up, so poll xwininfo for one, bounded at 5 seconds; without xwininfo fall back to the
130
+ # quarter second the runner's TypeScript path waits. Either way a compositor that already died is
131
+ # not one we can report as running, and the refusal then names the real state.
120
132
  if [ -n "$compositor_pid" ]; then
121
- sleep 0.25
133
+ if command -v xwininfo >/dev/null 2>&1; then
134
+ waited=0
135
+ while [ "$waited" -lt 50 ]; do
136
+ kill -0 "$compositor_pid" 2>/dev/null || break
137
+ case "$(xwininfo -root -children 2>/dev/null)" in
138
+ *[1-9]" child"*) break ;;
139
+ esac
140
+ sleep 0.1
141
+ waited=$((waited + 1))
142
+ done
143
+ else
144
+ sleep 0.25
145
+ fi
122
146
  if ! kill -0 "$compositor_pid" 2>/dev/null; then
123
147
  wait "$compositor_pid" 2>/dev/null || true
124
148
  compositor_pid=""
@@ -3,13 +3,17 @@
3
3
  // scalar uniforms read and write the native effect (`ao(...).radius.value`).
4
4
  import { unsupportedExport } from "../../../../three-native/src/refused.ts";
5
5
  import { definePostEffects } from "../../../../three-native/src/addons/post-effects.ts";
6
+ import { defineScreenSpaceGi } from "../../../../three-native/src/addons/screen-space.ts";
7
+ import { rtt, uniform } from "./core-tsl.mjs";
6
8
 
7
- export const { ao, denoise, smaa, bloom, traa, film, lut3D } = definePostEffects(globalThis.tsl);
9
+ // SSR uses the engine's native SSRNode port (post_effects.cpp, PRD-652); the Wasm browser
10
+ // exports its separate screen-space.ts implementation.
11
+ export const { ao, ssr, denoise, smaa, bloom, traa, film, lut3D } = definePostEffects(globalThis.tsl);
12
+ // Screen-space diffuse GI: authored over the engine TSL, shared with the Wasm back end.
13
+ export const ssgi = defineScreenSpaceGi({ ...globalThis.tsl, rtt, uniform });
8
14
 
9
15
  // The other display nodes need live addon-node construction and update scheduling, which the native
10
16
  // renderer lacks (it consumes cooked post graphs). They stay importable and refuse at use, by name.
11
17
  export const fxaa = unsupportedExport("fxaa");
12
18
  export const godrays = unsupportedExport("godrays");
13
- export const ssgi = unsupportedExport("ssgi");
14
- export const ssr = unsupportedExport("ssr");
15
19
  export const sharpen = unsupportedExport("sharpen");
@@ -1,7 +1,7 @@
1
1
  // The owned engine consumes verified TNPK entries, never browser loaders or network fallbacks.
2
2
  import { audio } from "./core-audio.mjs";
3
3
  export function createAssetLoader(options = {}) {
4
- if (Object.keys(options).some((key) => !["renderer", "basePath", "manifest", "sourcePath"].includes(key)))
4
+ if (Object.keys(options).some((key) => !["renderer", "basePath", "manifest", "sourcePath", "cache", "backgroundFill"].includes(key)))
5
5
  throw new Error("TN_NATIVE_ASSET_OPTIONS_UNSUPPORTED: this player accepts cooked package paths only");
6
6
  // core's fallback for a game without a manifest: the verbatim path, then `<sourcePath>/<path>`.
7
7
  const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/g, "");
@@ -55,5 +55,16 @@ export function createAssetLoader(options = {}) {
55
55
  resolve: async (path) => [resolved.get(path)?.url ?? `tnpk:${path}`],
56
56
  release: (kind, path) => cache.delete(`${kind}:${path}`),
57
57
  clear() { cache.clear(); resolved.clear(); },
58
+ // Final disposal releases decoder worker pools in core; the TNPK host owns no such pool.
59
+ // Keep this idempotent contract separate from clear(), which empties the reusable cache.
60
+ dispose() {},
61
+ // core's disk cache (PRD-743) is web-only: a native game reads its installed package, so the report
62
+ // says so and prefetch and the background fill have nothing to fetch. `cache: false` changes nothing here.
63
+ get cache() {
64
+ return { enabled: false, persisted: false, hits: 0, misses: 0, bytesOnDisk: 0, bytesTotal: 0, filling: false,
65
+ backgroundFill: false, reason: "native host reads installed files", clear: async () => {} };
66
+ },
67
+ prefetch: async () => ({ requested: 0, requestedBytes: 0, settled: 0, settledBytes: 0 }),
68
+ startBackgroundFill: async () => {},
58
69
  };
59
70
  }
@@ -13,6 +13,14 @@ const NativeCanvasTexture = globalThis.CanvasTexture;
13
13
  const sources = new WeakMap();
14
14
  const bitmaps = new WeakMap();
15
15
  const nativeFlipY = Object.getOwnPropertyDescriptor(NativeTexture.prototype, "flipY").set;
16
+ for (const Native of [NativeTexture, NativeDataTexture, NativeCanvasTexture, NativeVolumeTexture]) {
17
+ const clone = Native.prototype.clone;
18
+ Native.prototype.clone = function () {
19
+ const result = clone.call(this);
20
+ if (sources.has(this)) sources.set(result, sources.get(this));
21
+ return result;
22
+ };
23
+ }
16
24
 
17
25
  /** The package entry a URL names: `tnpk:<path>` and `<package>#<path>` from `assets.resolve`, or the path. */
18
26
  export function logicalPath(url) {
@@ -60,7 +68,13 @@ DataTexture.prototype = NativeDataTexture.prototype;
60
68
  Object.setPrototypeOf(DataTexture, NativeDataTexture);
61
69
 
62
70
  export function Data3DTexture(data = null, width = 1, height = 1, depth = 1) {
63
- const texture = Reflect.construct(NativeVolumeTexture, [data ?? undefined, width, height, depth], new.target ?? Data3DTexture);
71
+ // The engine's constructor takes bytes or floats: a Uint16Array's half-float bits go in on needsUpdate, after `type`.
72
+ const bits = data instanceof Uint16Array;
73
+ const texture = Reflect.construct(
74
+ NativeVolumeTexture,
75
+ [bits ? new Float32Array(data.length) : (data ?? undefined), width, height, depth],
76
+ new.target ?? Data3DTexture,
77
+ );
64
78
  if (data) sources.set(texture, { data, width, height, depth });
65
79
  return texture;
66
80
  }
@@ -292,3 +292,12 @@ export { Material };
292
292
  // three's blending constant "use the material's own blending" (constants.js). It is a value in three,
293
293
  // not an engine class, so it has no catalog entry; `new BlendMode(MaterialBlending)` names it.
294
294
  export const MaterialBlending = 6;
295
+
296
+ // three r185 constants that core's own modules compare against and the Wasm engine already exports
297
+ // with these catalog values. CustomToneMapping is the mode the tone-mapping library compiles
298
+ // (tone-mapping.ts); the depth and shadow-map values only label what the engine refuses or ignores.
299
+ export const LessEqualCompare = 515;
300
+ export const GreaterEqualCompare = 518;
301
+ export const CustomToneMapping = 5;
302
+ export const AlwaysDepth = 1;
303
+ export const VSMShadowMap = 3;
@@ -1,11 +1,13 @@
1
1
  // TSL authoring calls the native lazy graph; no upstream shader implementation enters the player.
2
- import { liveUniforms, withConstValues } from "../../../../three-native/src/tsl-uniforms.ts";
2
+ import { unsupportedExport } from "../../../../three-native/src/refused.ts";
3
+ import { booleanUniforms, liveUniforms, withConstValues } from "../../../../three-native/src/tsl-uniforms.ts";
3
4
  import { defineReflector } from "../../../../three-native/src/reflector.ts";
4
5
  import { definePass, markNormalTarget } from "../../../../three-native/src/pass-node.ts";
5
6
  import { BufferAttribute, Color, Object3D, PerspectiveCamera, Vector2, Vector3, Vector4 } from "./core-three.mjs";
6
- import { defineStorage } from "../../../../three-native/src/storage.ts";
7
+ import { defineStorage, defineStorageTextures } from "../../../../three-native/src/storage.ts";
7
8
  import { defineStruct } from "../../../../three-native/src/tsl-struct.ts";
8
9
  import { defineTslExtras } from "../../../../three-native/src/tsl-extras.ts";
10
+ import { withFnBuilder } from "../../../../three-native/src/fn-builder.ts";
9
11
 
10
12
  // r185's ConstNode.value on float(), vec3(), color() and the other constants (shared with the Wasm back end).
11
13
  const constants = { ...globalThis.tsl };
@@ -14,20 +16,22 @@ withConstValues(constants, { Vector2, Vector3, Vector4, Color });
14
16
  // three's `uniform.value = x` (shared with the Wasm back end): a number goes through at once; an
15
17
  // edited Color or VectorN goes through `syncUniforms`, which the renderer calls before each frame.
16
18
  const live = liveUniforms(globalThis.tsl.uniform, (node, lanes) => globalThis.tsl.setUniform(node, ...lanes));
17
- export const uniform = live.uniform;
19
+ // A boolean uniform (the exposure meter's `enabled`) is the live float compared with zero, as on the Wasm back end.
20
+ export const uniform = booleanUniforms(live.uniform, (scalar) => globalThis.tsl.notEqual(scalar, 0));
18
21
  export const uniformArray = live.uniformArray;
19
22
  export const reference = live.reference;
20
23
  export const syncUniforms = live.sync;
21
24
 
22
25
  export const { float, int, uint, vec2, vec3, color } = constants;
23
26
  export const vec4 = markNormalTarget(constants.vec4, globalThis.tsl.normalView);
27
+ export const Fn = withFnBuilder(globalThis.tsl.Fn);
24
28
  export const {
25
- atomicAdd, atomicStore, atomicLoad, Break, Continue, Return, log, lightShadowMatrix, attribute, uv, texture, renderOutput, Fn, If, Loop, luminance, viewZToOrthographicDepth, viewZToPerspectiveDepth, logarithmicDepthToViewZ, vertexIndex,
29
+ atomicAdd, atomicStore, atomicLoad, Break, Continue, Return, log, lightShadowMatrix, attribute, uv, renderOutput, If, Loop, luminance, viewZToOrthographicDepth, viewZToPerspectiveDepth, logarithmicDepthToViewZ, vertexIndex,
26
30
  add, sub, mul, div, negate, lessThan, greaterThan, equal, lessThanEqual, greaterThanEqual, and, or, not, all, any, abs, sin, cos,
27
31
  floor, fract, sqrt, exp, exp2, log2, normalize, length, min, max, pow, step, dot,
28
- distance, cross, mix, clamp, smoothstep, select, positionLocal, positionWorld,
29
- normalViewGeometry, instanceIndex, cameraViewMatrix, ivec2, nodeObject, reflect, textureLoad,
30
- mx_noise_float, mx_worley_noise_vec2, pmremTexture, texture3D,
32
+ distance, cross, mix, clamp, smoothstep, select, positionLocal, positionWorld, positionWorldDirection,
33
+ normalViewGeometry, instanceIndex, cameraViewMatrix, modelWorldMatrix, ivec2, uvec2, nodeObject, reflect, textureLoad, textureSize,
34
+ mx_noise_float, mx_worley_noise_float, mx_worley_noise_vec2, pmremTexture, texture3D,
31
35
  convertToTexture, screenUV, materialColor, materialEmissive, materialMetalness, materialRoughness,
32
36
  cameraPosition, cameraProjectionMatrix, cameraWorldMatrix, positionGeometry, normalWorld, varying,
33
37
  cameraNear, cameraFar, screenSize, depth, viewportSharedTexture, viewportDepthTexture, linearDepth, viewportLinearDepth,
@@ -39,6 +43,8 @@ export const {
39
43
  getViewPosition, frameGroup, renderGroup, objectGroup, transformNormalToView, property,
40
44
  } = globalThis.tsl;
41
45
 
46
+ export const { storageTexture, textureStore } = defineStorageTextures(globalThis.tsl);
47
+
42
48
  // three's storage buffers over engine BufferAttributes (shared with the Wasm back end): `storage`,
43
49
  // `instancedArray` and `attributeArray` build the engine's storage node, whose kernels `renderer.compute` runs.
44
50
  export const { storage, instancedArray, attributeArray, StorageBufferAttribute, StorageInstancedBufferAttribute } =
@@ -48,7 +54,7 @@ export const { storage, instancedArray, attributeArray, StorageBufferAttribute,
48
54
  // end); the player draws the scene and camera a pass is pointed at.
49
55
  // An offscreen `new PassNode(PassNode.COLOR, scene, camera)` owns a RenderTarget that the renderer draws before the
50
56
  // frame (updateSecondaryPasses, called from core-webgpu.mjs); only pass() publishes the frame's scene and camera.
51
- export const { pass, PassNode, updateSecondaryPasses, mrt, output, normalView, metalness, roughness } = definePass(
57
+ export const { pass, PassNode, updateSecondaryPasses, mrt, output, normalView, metalness, roughness, diffuseColor, emissive } = definePass(
52
58
  globalThis.tsl,
53
59
  (scene, camera) => {
54
60
  globalThis.tn.scene = scene;
@@ -78,3 +84,36 @@ export const rtt = defineRtt(globalThis.tsl.rtt, { NodeMaterial: globalThis.Node
78
84
 
79
85
  import { defineWgslFn } from "../../../../three-native/src/wgsl-fn.ts";
80
86
  export const wgslFn = defineWgslFn(globalThis.tsl.wgslFunction);
87
+
88
+ export function texture(value, ...args) {
89
+ const node = globalThis.tsl.texture(value, ...args);
90
+ let current = value;
91
+ return Object.defineProperty(node, "value", {
92
+ get: () => current,
93
+ set: (next) => {
94
+ if (next === current) return;
95
+ node.textureValue(next);
96
+ current = next;
97
+ },
98
+ });
99
+ }
100
+
101
+ export const {
102
+ EPSILON, INFINITY, PI, PI2, TWO_PI, HALF_PI, radians,
103
+ degrees, inverseSqrt, ceil, sinh, cosh, tan, tanh,
104
+ asin, asinh, acos, acosh, atanh, sign, round,
105
+ reciprocal, trunc, transpose, determinant, inverse, difference, pow2,
106
+ pow3, pow4, transformNormalByViewMatrix, transformNormalByInverseViewMatrix, cbrt, refract, faceForward,
107
+ rand, mixElement, smoothstepElement, stepElement, faceforward, inversesqrt, notEqual,
108
+ xor, bitAnd, bitNot, bitOr, bitXor, shiftLeft, shiftRight,
109
+ incrementBefore, decrementBefore, increment, decrement, mat3, mat4,
110
+ } = globalThis.tsl;
111
+
112
+ // Refused at use, as on Wasm: the engine draws a lamp's cube shadow taps (shadowFilterOptions) and the
113
+ // virtual shadow map (virtualShadowOptions) in C++, so the three-only bodies of core's soft-shadow.ts
114
+ // and VirtualShadowNode.setup name these and never call them here.
115
+ export const cubeTexture = unsupportedExport("cubeTexture");
116
+ export const Stack = unsupportedExport("Stack");
117
+ export const getShadowMaterial = unsupportedExport("getShadowMaterial");
118
+ export const shadow = unsupportedExport("shadow");
119
+ export const shadowPositionWorld = unsupportedExport("shadowPositionWorld");