@threenative/runtime-native 0.3.5 → 0.3.8

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.5",
3
+ "version": "0.3.8",
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.5"
83
+ "@threenative/playtest": "0.3.8"
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/assets": "0.3.6",
88
- "@threenative/core": "0.3.5",
89
- "@threenative/three-native": "0.3.5"
89
+ "@threenative/assets": "0.3.9",
90
+ "@threenative/three-native": "0.3.8",
91
+ "@threenative/core": "0.3.8"
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",
@@ -328,6 +328,8 @@ void game.start().catch((error) => console.error(
328
328
  },
329
329
  };
330
330
  mkdirSync(dirname(absoluteOutput), { recursive: true });
331
+ // Read by the project's own `createWebBrandPlugin`: this bundle is not a browser's.
332
+ process.env.THREENATIVE_NATIVE_BUNDLE = target;
331
333
  await build({
332
334
  root: absoluteProject,
333
335
  define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
@@ -33,6 +33,20 @@ import { tmpdir } from 'node:os';
33
33
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
34
34
  import { buildWindowsInstaller } from './windows-installer.mjs';
35
35
 
36
+ /**
37
+ * The file to launch for a desktop artifact. `threenative build --target desktop` writes a
38
+ * container directory (`dist-native/<name>/` holding the player, `game.js` and a launcher named
39
+ * `<name>`); an older build wrote the executable itself. Launching the directory exits 126.
40
+ */
41
+ export function desktopLaunchTarget(artifact, executableName) {
42
+ return statSync(artifact).isDirectory() ? join(artifact, executableName) : artifact;
43
+ }
44
+
45
+ /** Whether the launcher's folder holds the owned engine player, which has no `--frames` or `--screenshot`. */
46
+ export function isEnginePlayerLaunch(launch) {
47
+ return readdirSync(dirname(launch)).some((file) => file.startsWith('tn-native-engine-player'));
48
+ }
49
+
36
50
  export const CONTAINER_MANIFEST = 'threenative-container.json';
37
51
  export const CONTAINER_SCHEMA_VERSION = 1;
38
52
  export const DESKTOP_TARGETS = ['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'win32-x64'];
@@ -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 {
@@ -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) {
@@ -2,12 +2,17 @@
2
2
 
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { createHash } from 'node:crypto';
5
- import { existsSync, mkdirSync, readFileSync, realpathSync, 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';
9
9
 
10
- import { parseLinkedLibraries, resolveContainer } from './desktop-distribution.mjs';
10
+ import {
11
+ desktopLaunchTarget,
12
+ isEnginePlayerLaunch,
13
+ parseLinkedLibraries,
14
+ resolveContainer,
15
+ } from './desktop-distribution.mjs';
11
16
  import { inspectContainerBrand } from './inspect-container-brand.mjs';
12
17
  import { inspectMacosIcon } from './inspect-macos-icon.mjs';
13
18
 
@@ -30,7 +35,11 @@ const ASSET_PIXEL_FLOOR = 100;
30
35
  // pennant, against 0 in the same frame with the pennant cropped away.
31
36
  const PROOF_MAGENTA_MIN_MARGIN = 40;
32
37
  // Corroborating cyan, counted only inside the magenta bounds so the background cannot supply it.
33
- 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;
34
43
  const PROOF_CYAN_IN_BOUNDS_FLOOR = 50;
35
44
  // A proof region may occupy up to a quarter of a rendered frame; a wash that reaches almost every
36
45
  // part of the frame must not count as localized evidence.
@@ -292,7 +301,61 @@ function judgeStarterRun({ artifact, brand, frames, log, logPath, reportPath, sc
292
301
  return report;
293
302
  }
294
303
 
295
- export function verifyStarterDesktop({ frames = 300, project = process.cwd() } = {}) {
304
+ export { desktopLaunchTarget };
305
+
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 result = run(process.execPath, [cli, scenario, '--target', 'desktop', '--project', project,
321
+ '--artifacts', captures, '--executable', artifact, '--host-arg', '--windowed'], {
322
+ cwd: project, encoding: 'utf8', timeout, maxBuffer: 32 * 1024 * 1024,
323
+ env: { ...env, TN_PLAYTEST_COMPLETION_WINDOW_LABEL: 'native-smoke',
324
+ TN_PLAYTEST_COMPLETION_WINDOW_MIN_FRAMES: String(frames),
325
+ TN_PLAYTEST_COMPLETION_WINDOW_TIMEOUT_MS: String(Math.max(1, timeout - 10_000)) },
326
+ });
327
+ writeFileSync(logPath, `${result.stdout ?? ''}\n${result.stderr ?? ''}`);
328
+ if (result.error || result.signal || result.status !== 0)
329
+ throw new Error(`TN_NATIVE_STARTER_SMOKE: runner failed: ${result.error?.message ?? result.signal ?? result.stderr ?? result.status}`);
330
+ const report = JSON.parse(result.stdout);
331
+ if (report?.pass !== true || !report.assertionResults?.length
332
+ || report.assertionResults.some((assertion) => assertion.pass !== true))
333
+ throw new Error('TN_NATIVE_STARTER_SMOKE: runner assertions missing or failed');
334
+ const completion = report.acquisition?.completionWindow;
335
+ const samples = completion?.samples;
336
+ if (completion?.source !== 'present-return' || completion.timebase !== 'steady-clock-ms'
337
+ || !Array.isArray(samples) || samples.length < frames || samples.some((sample, index) =>
338
+ !Number.isSafeInteger(sample.sequence) || sample.sequence < 1 || !Number.isFinite(sample.completedAtMs)
339
+ || sample.completedAtMs < 0 || (index > 0 && (sample.sequence !== samples[index - 1].sequence + 1
340
+ || sample.completedAtMs <= samples[index - 1].completedAtMs))))
341
+ throw new Error(`TN_NATIVE_STARTER_SMOKE: missing ${frames} contiguous native completion observations`);
342
+ const image = PNG.sync.read(readFileSync(screenshot));
343
+ const colors = new Set();
344
+ let opaque = 0;
345
+ for (let index = 0; index < image.data.length; index += 4) {
346
+ if (image.data[index + 3] !== 0) opaque += 1;
347
+ colors.add(image.data.readUInt32BE(index));
348
+ }
349
+ if (opaque === 0 || colors.size < 2) throw new Error('native smoke screenshot is blank');
350
+ return { artifact, gate: 'native-smoke', pass: true, frames: samples.length, requestedFrames: frames,
351
+ completion, screenshot, width: image.width, height: image.height, assertions: report.assertionResults };
352
+ } finally {
353
+ rmSync(temporary, { recursive: true, force: true });
354
+ }
355
+ }
356
+
357
+ export function verifyStarterDesktop({ frames = 300, project = process.cwd(), run = spawnSync, env = process.env } = {}) {
358
+ frames = frameCount(frames);
296
359
  const projectRoot = resolve(project);
297
360
  const manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
298
361
  const projectName = basename(String(manifest.name ?? 'starter').replace(/^@[^/]+\//u, ''));
@@ -306,8 +369,17 @@ export function verifyStarterDesktop({ frames = 300, project = process.cwd() } =
306
369
  const logPath = join(artifactDirectory, 'starter-desktop.log');
307
370
  const reportPath = join(artifactDirectory, 'starter-desktop-report.json');
308
371
  mkdirSync(artifactDirectory, { recursive: true });
309
- const log = launchStarterExecutable(artifact, { frames, logPath, project: projectRoot, screenshot });
310
- return judgeStarterRun({ artifact, frames, log, logPath, reportPath, screenshot });
372
+ const launch = desktopLaunchTarget(artifact, executableName);
373
+ // The engine player takes neither `--frames` nor `--screenshot` and prints none of the legacy
374
+ // host's markers, so the playtest runner drives it (PRD-637). The report keeps the same path.
375
+ if (isEnginePlayerLaunch(launch)) {
376
+ const report = verifyOwnedDesktop({ frames, project: projectRoot, artifact: launch,
377
+ artifactDirectory, logPath, run, env });
378
+ writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
379
+ return report;
380
+ }
381
+ const log = launchStarterExecutable(launch, { frames, logPath, project: projectRoot, screenshot });
382
+ return judgeStarterRun({ artifact: launch, frames, log, logPath, reportPath, screenshot });
311
383
  }
312
384
 
313
385
  /**
@@ -447,6 +519,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar
447
519
  process.exit(0);
448
520
  }
449
521
  const report = options.root ? verifyStarterContainer(options) : verifyStarterDesktop(options);
522
+ if (report.gate === 'native-smoke') {
523
+ console.log(`starter desktop gate passed: ${report.frames} native presents, ${report.assertions.length} playtest assertions, screenshot ${report.screenshot}`);
524
+ process.exit(0);
525
+ }
450
526
  const brand = report.brand === undefined || report.brand === null
451
527
  ? 'brand NOT inspected (pass --config <resolved config json>)'
452
528
  : `brand ${report.brand.name?.name ?? 'unnamed'} verified`;
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");