@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
package/src/game.ts CHANGED
@@ -1,58 +1,38 @@
1
- import type { Scene as ThreeScene } from "three";
2
1
  import type { IAssetLoaderOptions } from "./assets.js";
3
- import type { AutoBatch, IAutoBatchConfig } from "./auto-batch.js";
4
- import { ComputeDrivenRegistry } from "./compute-driven.js";
2
+ import type { IAutoBatchConfig } from "./auto-batch.js";
5
3
  import type { IThreeNativeConfig } from "./config.js";
6
- import type { Registry } from "./entities.js";
7
- import type { FrameBudget, IFrameBudgetOptions, IFrameBudgetWindow } from "./frame-budget.js";
4
+ import type { IFrameBudgetOptions, IFrameBudgetWindow } from "./frame-budget.js";
5
+ import {
6
+ type IBootGame,
7
+ clearScene,
8
+ createBootGame,
9
+ drainCleanup,
10
+ throwFirst,
11
+ } from "./game-boot-phase.js";
8
12
  import { startFrameLoop } from "./game-frame-loop.js";
9
- import type { IGameBootGame } from "./game-frame-loop.js";
10
13
  import { startGameWorld, startScenes } from "./game-startup.js";
14
+ import { type IGameUiSeam, createGameUi } from "./game-ui.js";
11
15
  import { assertCarry, validateCameraConfig } from "./game-validate.js";
12
- import type {
13
- GeometryCapture,
14
- IGeometryCaptureReport,
15
- IGeometryCaptureRequest,
16
- } from "./geometry-capture.js";
16
+ import type { IGeometryCaptureReport, IGeometryCaptureRequest } from "./geometry-capture.js";
17
17
  import type { ContextMenuPolicy, InputBindings, InputMap } from "./input.js";
18
- import type { PhysicsInterpolation } from "./interpolation.js";
19
18
  import { reportLaunchFailure, reportSceneLoadFailure } from "./launch-diagnostics.js";
20
- import type { IAfterPhysicsPhase, IRenderPerformanceSample } from "./loop.js";
21
- import type { MatrixWorldPass } from "./matrix-world.js";
22
- import type { ScenePicker } from "./picking.js";
19
+ import type { IRenderPerformanceSample } from "./loop.js";
23
20
  import type { IPipelineCensus } from "./pipeline-census.js";
24
- import type { PointerEvents3D } from "./pointer-events.js";
25
- import { applyOpacityConvention } from "./profiling/opacity-convention.js";
26
- import { renderTrapAudit } from "./profiling/render-trap-audit.js";
27
- import {
28
- UNLIT_FOLIAGE_FIX,
29
- formatUnlitFoliageWarning,
30
- unlitFoliageWarning,
31
- } from "./profiling/unlit-foliage-warning.js";
32
21
  import { installQuietMarkers, uninstallQuietMarkers } from "./quiet-markers.js";
33
22
  import type { IRandom } from "./random.js";
34
- import type { RenderCameraCull } from "./render-camera-cull.js";
35
- import type { SceneRenderProjection } from "./renderProjection.js";
36
- import type { IRendererLike, IRendererOptions } from "./renderer.js";
37
- import type { ICtx, IStartupTimeline, Scene, SceneConstructor, SceneFrame } from "./scene.js";
38
- import type { Scheduler } from "./schedule.js";
23
+ import { type GameRendererConfig, adoptLegacyRenderKey } from "./renderer-config.js";
24
+ import type { IRendererOptions } from "./renderer.js";
25
+ import {
26
+ SCENE_ENTRY_INSPECTORS,
27
+ type SceneEntryInspector,
28
+ inspectSceneEntry,
29
+ } from "./scene-entry-inspectors.js";
30
+ import type { ICtx, IStartupTimeline, Scene, SceneConstructor } from "./scene.js";
39
31
  import type { IStartupOffscreenBytes } from "./startup-offscreen-bytes.js";
40
32
  import { STARTUP_COMPILE_BUDGET_MS } from "./startup-readiness.js";
41
33
  import { type GameStore, createGameStore } from "./state.js";
42
- import {
43
- type IUiBridge,
44
- UI_READY_INTENT,
45
- UI_STARTUP_MESSAGE,
46
- connectUiBridge,
47
- } from "./ui-bridge.js";
48
- import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
49
- import type { IViewportOptions, Viewport } from "./viewport.js";
50
- import {
51
- type IWarmUpOptions,
52
- prepareSceneEnvironment,
53
- warmUpComputeNodes,
54
- warmUpScene,
55
- } from "./warmup.js";
34
+ import type { IViewportOptions } from "./viewport.js";
35
+ import { type IWarmUpOptions, prepareSceneEnvironment, warmUpComputeNodes } from "./warmup.js";
56
36
 
57
37
  export type PluginCleanup = () => void;
58
38
 
@@ -229,6 +209,12 @@ export interface IGameConfig<
229
209
  * the browser menu over its canvas.
230
210
  */
231
211
  readonly contextMenu?: ContextMenuPolicy;
212
+ /**
213
+ * Radial dead zone for both controller sticks, `0`..`1`. Default `0.2`, the stock Enhanced Input
214
+ * value, so a worn stick resting at `0.08` reads zero instead of walking the character. A stick
215
+ * past the zone is rescaled so full tilt is still `1`. Pass `0` to read raw axes.
216
+ */
217
+ readonly gamepadDeadZone?: number;
232
218
  /**
233
219
  * Per-frame cost attribution, on by default. Every `reportEvery` presented frames the game
234
220
  * prints one `TN_FRAME_BUDGET` line naming where the frame went — present wait, simulation,
@@ -290,8 +276,20 @@ export interface IGameConfig<
290
276
  * 60 fps default rather than a scaler with no target.
291
277
  */
292
278
  readonly display?: NonNullable<IThreeNativeConfig["display"]>;
293
- readonly render?: NonNullable<IThreeNativeConfig["renderer"]>;
294
- readonly renderer?: IRendererOptions;
279
+ /**
280
+ * The project's renderer settings: `config.renderer` from `threenative.config.ts` beside the live
281
+ * renderer options, as one key.
282
+ *
283
+ * `render` once carried the portable half, so a game wrote `render: config.renderer` beside a
284
+ * second `renderer:` and the antialias and scale resolvers each fell back from one to the other.
285
+ * The keys are one now; `render` is adopted onto this one and reported as renamed.
286
+ */
287
+ readonly renderer?: GameRendererConfig;
288
+ /**
289
+ * @deprecated The retired name for {@link renderer}, adopted onto it and reported. Move the object
290
+ * to `renderer` with no other change.
291
+ */
292
+ readonly render?: GameRendererConfig;
295
293
  readonly seed?: number;
296
294
  readonly scenes: Record<string, SceneConstructor<TState, TPhysics>>;
297
295
  /**
@@ -380,19 +378,9 @@ export interface IGame<
380
378
  stop(): void;
381
379
  }
382
380
 
383
- function clearScene(scene: ThreeScene, computeDriven: ComputeDrivenRegistry): void {
384
- computeDriven.clear();
385
- scene.clear();
386
- scene.background = null;
387
- scene.environment = null;
388
- scene.fog = null;
389
- }
390
-
391
381
  class GameImpl<TState extends Record<string, unknown>, TPhysics>
392
382
  implements IGame<TState, TPhysics>
393
383
  {
394
- #config: IGameConfig<TState, TPhysics>;
395
-
396
384
  /**
397
385
  * Whether the caller asked for the pre-start warm-up *by hand*.
398
386
  *
@@ -415,106 +403,68 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
415
403
  * budget on macOS. Both are gone with the default back where it was.
416
404
  */
417
405
  #warmUpConfiguredExplicitly(): boolean {
418
- return this.#config.warmUp !== undefined && this.#config.warmUp !== false;
406
+ return this.#boot.config.warmUp !== undefined && this.#boot.config.warmUp !== false;
419
407
  }
420
408
 
421
409
  /** The warm-up options for the pre-start block, once an explicit opt-in has asked for it. */
422
410
  #warmUpOptions(): IWarmUpOptions {
423
- const configured = this.#config.warmUp;
411
+ const configured = this.#boot.config.warmUp;
424
412
  return configured === undefined || configured === true || configured === false
425
413
  ? {}
426
414
  : configured;
427
415
  }
428
- #ctx: ICtx<TState, TPhysics> | undefined;
429
- #scene: Scene<TState, TPhysics> | undefined;
430
- /** The name of the scene currently entered. Carried across a hot update so a reload resumes
431
- * where the session was, instead of restoring the game's state into its start scene. */
432
- #sceneName: string | undefined;
433
- #resumeScene: string | undefined;
434
- #sceneFrame: SceneFrame<TState, TPhysics> | undefined;
435
- #renderer: IRendererLike | undefined;
436
- #viewport: Viewport | undefined;
437
- #input: InputMap | undefined;
438
- #state: GameStore<TState>;
439
416
  #initialState: TState;
440
- #interpolation: PhysicsInterpolation | undefined;
441
- #projection: SceneRenderProjection | undefined;
442
- #autoBatch: AutoBatch | undefined;
443
- #cameraCull: RenderCameraCull | undefined;
444
- #matrixWorld: MatrixWorldPass | undefined;
445
- #cleanup: Array<() => void> = [];
446
- #computeDriven = new ComputeDrivenRegistry();
447
- #entities: Registry | undefined;
448
- #picker: ScenePicker | undefined;
449
- #pointerEvents: PointerEvents3D | undefined;
450
- #scheduler: Scheduler | undefined;
451
- #afterPhysicsPhase: IAfterPhysicsPhase | undefined;
452
- // Unlike afterPhysics, this seam's frame boundary is the world-render block below, so it is a
453
- // plain scene-owned set rather than a phase on the loop.
454
- #beforeRenderCallbacks = new Set<() => void>();
455
- // Reused snapshot buffers, one per nesting depth, so a steady frame allocates no callback array.
456
- #beforeRenderSnapshots: Array<Array<() => void>> = [];
457
- #beforeRenderDepth = 0;
458
- #frameBudget: FrameBudget | undefined;
459
- #geometryCapture: GeometryCapture | undefined;
460
- /** Bumped on every scene change, so a row id is stable exactly as long as the scene is. */
461
- #sceneGeneration = 0;
462
- #activePlugins: Array<IGamePluginHooks<TState, TPhysics>> = [];
463
- #disposedPlugins = new Set<IGamePluginHooks<TState, TPhysics>>();
464
417
  #pendingStart: Promise<void> | undefined;
465
- /** Releases the frame loop and its instruments, in the place `#teardown` always released them. */
466
- #frameLoopDispose: PluginCleanup | undefined;
467
- /** Releases what the startup phase started, in `#teardown`'s cleanups step. */
468
- #startupDispose: PluginCleanup | undefined;
469
- #aborted = false;
470
- #sceneEntered = false;
471
- /** Startup readiness has begun its first-use gate; before that, it bakes the entered environment. */
472
- #startupGateStarted = false;
473
- /** The full `goto()` transition, including first-use warm-up, or undefined when none is. */
474
- #pendingSceneEnter: Promise<void> | undefined;
475
- /** One-shot notification after the scene that owns the world has entered, before warm-up. */
476
- #onStartSceneEntered: (() => void) | undefined;
477
- #paused = false;
478
- #started = false;
479
- #uiBridge: IUiBridge | undefined;
480
- #uiPublisher: IUiStatePublisher | undefined;
481
- #uiReady = false;
482
- /** The loading cover has lifted and page UI may show state; see `UI_STARTUP_MESSAGE`. */
483
- #uiRevealed = false;
484
- // Flipped only by a diagnostics consumer announcing itself; see enableRuntimeDiagnostics().
485
- #renderMetricsEnabled = false;
486
- // Depth-coupled output needs the scene hook before its pass; ordinary scenes retain the
487
- // historical after-render hook so an atmosphere-free game has the same render path as HEAD.
488
- #hasDepthCoupledOutput = false;
418
+ /**
419
+ * What the boot phases read and assign. One plain object: a field a phase needs and this object
420
+ * lacks is a type error, never an `undefined` read at run time.
421
+ */
422
+ readonly #boot: IBootGame<TState, TPhysics>;
423
+
424
+ /** The scene-entry audits this game runs, in order. The engine's are the default. */
425
+ #sceneEntryInspectors: readonly SceneEntryInspector[] = SCENE_ENTRY_INSPECTORS;
426
+ readonly #ui: IGameUiSeam;
489
427
 
490
428
  constructor(config: IGameConfig<TState, TPhysics>) {
491
- this.#config = config;
492
- validateCameraConfig(config.camera);
493
- const startScene = this.#config.scenes[this.#config.start];
494
- if (startScene === undefined) throw new Error(`Unknown start scene '${this.#config.start}'.`);
429
+ // One key for the renderer settings: a game still on `render` is adopted, reported, and boots.
430
+ const resolved = adoptLegacyRenderKey(config);
431
+ validateCameraConfig(resolved.camera);
432
+ const startScene = resolved.scenes[resolved.start];
433
+ if (startScene === undefined) throw new Error(`Unknown start scene '${resolved.start}'.`);
495
434
  const initialState =
496
- this.#config.initialState ??
435
+ resolved.initialState ??
497
436
  (startScene as SceneConstructor<TState, TPhysics> & { initialState?: TState }).initialState;
498
437
  if (initialState === undefined) {
499
438
  throw new Error(
500
- `Scene '${this.#config.start}' must declare static initialState or provide config.initialState.`,
439
+ `Scene '${resolved.start}' must declare static initialState or provide config.initialState.`,
501
440
  );
502
441
  }
503
- this.#state = createGameStore(initialState, this.#config.stateFlushMs);
504
442
  this.#initialState = { ...initialState };
443
+ this.#boot = createBootGame({
444
+ config: resolved,
445
+ state: createGameStore(initialState, resolved.stateFlushMs),
446
+ connectUi: () => this.#ui.connect(),
447
+ enterScene: (scene, ctx) => this.#enterScene(scene, ctx),
448
+ goto: (name, ctx) => this.#goto(name, ctx),
449
+ postUiStartup: () => this.#ui.postStartup(),
450
+ teardown: () => this.#teardown(),
451
+ warmUpConfiguredExplicitly: () => this.#warmUpConfiguredExplicitly(),
452
+ warmUpOptions: () => this.#warmUpOptions(),
453
+ });
454
+ this.#ui = createGameUi(this.#boot);
505
455
  }
506
456
 
507
457
  get ctx(): ICtx<TState, TPhysics> | undefined {
508
- return this.#ctx;
458
+ return this.#boot.ctx;
509
459
  }
510
460
 
511
461
  get scene(): Scene<TState, TPhysics> | undefined {
512
- return this.#scene;
462
+ return this.#boot.scene;
513
463
  }
514
464
 
515
465
  /** The name of the entered scene, or undefined before `start()`. */
516
466
  get sceneName(): string | undefined {
517
- return this.#sceneName;
467
+ return this.#boot.sceneName;
518
468
  }
519
469
 
520
470
  /**
@@ -528,18 +478,18 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
528
478
  * `initialState`, which would discard the very state being restored.
529
479
  */
530
480
  resumeScene(name: string, options?: { readonly revealed?: boolean }): void {
531
- if (this.#config.scenes[name] === undefined) throw new Error(`Unknown scene '${name}'.`);
532
- this.#resumeScene = name;
481
+ if (this.#boot.config.scenes[name] === undefined) throw new Error(`Unknown scene '${name}'.`);
482
+ this.#boot.resumeScene = name;
533
483
  // An edit restarts the game, and its HUD would blank until this startup lifted the cover
534
484
  // again: seconds after every save on a slow GPU. A session that showed its HUD keeps it.
535
485
  // The updated module may have connected its UI already and told a waiting HUD to hide.
536
486
  if (options?.revealed !== true) return;
537
- this.#uiRevealed = true;
538
- if (this.#uiBridge?.hasPeer()) this.#postUiStartup();
487
+ this.#boot.uiRevealed = true;
488
+ if (this.#boot.uiBridge?.hasPeer()) this.#ui.postStartup();
539
489
  }
540
490
 
541
491
  get state(): GameStore<TState> {
542
- return this.#state;
492
+ return this.#boot.state;
543
493
  }
544
494
 
545
495
  /**
@@ -547,106 +497,65 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
547
497
  * connects early so the game can register intents. No state is serialized without a UI peer.
548
498
  */
549
499
  get ui(): IGameUi {
550
- const bridge = this.#connectUi();
551
- const ready = () => this.#uiReady;
552
- return {
553
- get connected() {
554
- return bridge.hasPeer() && ready();
555
- },
556
- onIntent: (listener) => onUiIntent(bridge, listener),
557
- publish: () => this.#uiPublisher?.publish(),
558
- };
559
- }
560
-
561
- #connectUi(): IUiBridge {
562
- if (this.#uiBridge !== undefined) return this.#uiBridge;
563
- const bridge = connectUiBridge({ end: "game" });
564
- this.#uiBridge = bridge;
565
- // The store already coalesces writes at flush. Deferring this again waits for the native
566
- // host's next microtask pump, after that frame's WebView event pump has already passed.
567
- // Ahead of the first state, which `publishUiState` sends at once when a UI is already waiting.
568
- if (bridge.hasPeer()) this.#postUiStartup();
569
- this.#uiPublisher = publishUiState(bridge, this.#state, { schedule: (flush) => flush() });
570
- onUiIntent(bridge, (intent) => {
571
- if (intent !== UI_READY_INTENT) return;
572
- this.#uiReady = true;
573
- // Before the state: a UI that mounts after the reveal must learn the cover is gone, and one
574
- // that mounts before it must learn to hide.
575
- this.#postUiStartup();
576
- // Publish immediately: the UI has just rendered against nothing, and waiting for the store's
577
- // next change would leave a HUD showing its initial values for up to a tick.
578
- this.#uiPublisher?.publish();
579
- });
580
- return bridge;
581
- }
582
-
583
- #postUiStartup(): void {
584
- this.#uiBridge?.post({
585
- type: UI_STARTUP_MESSAGE,
586
- phase: this.#uiRevealed ? "ready" : "covered",
587
- });
588
- }
589
-
590
- #disconnectUi(): void {
591
- this.#uiRevealed = false;
592
- this.#uiPublisher?.stop();
593
- this.#uiPublisher = undefined;
594
- this.#uiReady = false;
595
- this.#uiBridge?.close();
596
- this.#uiBridge = undefined;
500
+ return this.#ui.facade();
597
501
  }
598
502
 
599
503
  goto(name: string, options?: IGotoOptions<TState>): Promise<void> {
600
- if (this.#ctx === undefined) throw new Error("Cannot call game.goto() before start().");
504
+ if (this.#boot.ctx === undefined) throw new Error("Cannot call game.goto() before start().");
601
505
  // Validate before the reset: a typo'd scene name must not wipe the live session's state on
602
506
  // its way to throwing.
603
- const SceneType = this.#config.scenes[name];
507
+ const SceneType = this.#boot.config.scenes[name];
604
508
  if (SceneType === undefined) throw new Error(`Unknown scene '${name}'.`);
605
509
  const carry = options?.carry;
606
510
  if (carry !== undefined) assertCarry(carry);
607
511
  const destinationInitialState =
608
512
  (SceneType as SceneConstructor<TState, TPhysics> & { initialState?: TState }).initialState ??
609
513
  this.#initialState;
610
- this.#state.stop();
611
- this.#state.setState({ ...destinationInitialState, ...(carry as Partial<TState> | undefined) });
612
- this.#state.start();
613
- return this.#goto(name, this.#ctx);
514
+ this.#boot.state.stop();
515
+ this.#boot.state.setState({
516
+ ...destinationInitialState,
517
+ ...(carry as Partial<TState> | undefined),
518
+ });
519
+ this.#boot.state.start();
520
+ return this.#goto(name, this.#boot.ctx);
614
521
  }
615
522
 
616
523
  #goto(name: string, ctx: ICtx<TState, TPhysics>): Promise<void> {
617
- const SceneType = this.#config.scenes[name];
524
+ const SceneType = this.#boot.config.scenes[name];
618
525
  if (SceneType === undefined) throw new Error(`Unknown scene '${name}'.`);
619
526
 
620
- this.#hasDepthCoupledOutput = false;
621
- this.#sceneGeneration += 1;
527
+ this.#boot.hasDepthCoupledOutput = false;
528
+ this.#boot.sceneGeneration += 1;
622
529
  // The objects a pending capture armed are leaving the graph; a report about them would be
623
530
  // about a scene that no longer exists.
624
- this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_SCENE_EXIT: the scene changed mid-capture.");
625
- this.#sceneFrame = undefined;
626
- this.#afterPhysicsPhase?.clear();
627
- this.#beforeRenderCallbacks.clear();
628
- this.#interpolation?.clear();
629
- this.#interpolation?.track(ctx.camera);
630
- this.#scene?.exit(ctx);
631
- this.#pointerEvents?.clear();
632
- this.#sceneEntered = false;
633
- this.#scheduler?.clear();
634
- this.#entities?.clear();
635
- for (const plugin of this.#config.plugins ?? []) {
531
+ this.#boot.geometryCapture?.cancel(
532
+ "TN_GEOMETRY_CAPTURE_SCENE_EXIT: the scene changed mid-capture.",
533
+ );
534
+ this.#boot.sceneFrame = undefined;
535
+ this.#boot.afterPhysicsPhase?.clear();
536
+ this.#boot.beforeRenderCallbacks.clear();
537
+ this.#boot.interpolation?.clear();
538
+ this.#boot.interpolation?.track(ctx.camera);
539
+ this.#boot.scene?.exit(ctx);
540
+ this.#boot.pointerEvents?.clear();
541
+ this.#boot.sceneEntered = false;
542
+ this.#boot.scheduler?.clear();
543
+ this.#boot.entities?.clear();
544
+ for (const plugin of this.#boot.config.plugins ?? []) {
636
545
  if (typeof plugin !== "function") plugin.sceneExit?.(ctx);
637
546
  }
638
547
  // The projection holds batches built from the outgoing scene's geometry. Released before the
639
548
  // scene is cleared, so a scene change cannot leave the next level drawing the last one's
640
549
  // props — and released rather than rebuilt, because every source it referenced is about to go.
641
- this.#projection?.dispose();
550
+ this.#boot.projection?.dispose();
642
551
  // Put back anything the cull hid before the outgoing scene is cleared, so a scene change never
643
552
  // leaves an object invisible if the game keeps a reference to it.
644
- this.#cameraCull?.restore();
645
- this.#autoBatch?.reset();
646
- clearScene(ctx.scene, this.#computeDriven);
553
+ this.#boot.cameraCull?.restore();
554
+ this.#boot.autoBatch?.reset();
555
+ clearScene(ctx.scene, this.#boot.computeDriven);
647
556
  const scene = new SceneType();
648
- this.#scene = scene;
649
- this.#sceneName = name;
557
+ this.#boot.scene = scene;
558
+ this.#boot.sceneName = name;
650
559
  let loaded: ReturnType<Scene<TState, TPhysics>["load"]>;
651
560
  try {
652
561
  loaded = scene.load(ctx);
@@ -659,7 +568,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
659
568
  ? this.#enterTransitionScene(scene, ctx)
660
569
  : Promise.resolve(loaded).then(() => this.#enterTransitionScene(scene, ctx));
661
570
  const settled = (): void => {
662
- if (this.#pendingSceneEnter === transition) this.#pendingSceneEnter = undefined;
571
+ if (this.#boot.pendingSceneEnter === transition) this.#boot.pendingSceneEnter = undefined;
663
572
  };
664
573
  // Handled here as well as by the caller: a start scene that navigates inside `enter()` throws
665
574
  // its transition away, and the gate below still has to learn that no world arrived. The failure
@@ -672,7 +581,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
672
581
  message: `Scene '${name}' failed to load: ${error instanceof Error ? error.message : String(error)}`,
673
582
  });
674
583
  });
675
- this.#pendingSceneEnter = transition;
584
+ this.#boot.pendingSceneEnter = transition;
676
585
  return transition;
677
586
  }
678
587
 
@@ -682,27 +591,19 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
682
591
  throw new Error("Scene.enter() must return a frame function or undefined.");
683
592
  }
684
593
  // A boot scene may navigate synchronously; do not replace the frame installed by #goto().
685
- if (this.#scene !== scene) return false;
686
- this.#sceneFrame = typeof frame === "function" ? frame : undefined;
687
- this.#sceneEntered = true;
594
+ if (this.#boot.scene !== scene) return false;
595
+ this.#boot.sceneFrame = typeof frame === "function" ? frame : undefined;
596
+ this.#boot.sceneEntered = true;
688
597
  // What `enter()` built is what the warm-up compiles and the first frame draws, so it merges
689
598
  // now, before either: no frame is ever drawn unmerged, and the compile counts merged meshes,
690
599
  // not every source. Anything that moves afterwards is given back by the guard.
691
- this.#autoBatch?.settleNow();
692
- // Before the audit, so an opacity the convention made take effect is reported as a warning.
693
- const opacity = applyOpacityConvention(ctx.scene);
694
- if (opacity !== undefined) console.warn(opacity);
695
- for (const line of renderTrapAudit(ctx.scene)) console.error(line);
696
- // Cutout PBR with no image-based light renders as cardboard, and the compensating tint the
697
- // author reaches for is invisible in a screenshot review. Once per scene entry, right after
698
- // `enter()`: `load()` and `enter()` are where the game builds its meshes and sets its own
699
- // environment, so an earlier read would be a census of an empty scene and a later one would be
700
- // a census of a scene the author already fixed.
701
- const unlit = unlitFoliageWarning(ctx.scene);
702
- if (unlit !== undefined)
703
- console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
704
- const entered = this.#onStartSceneEntered;
705
- this.#onStartSceneEntered = undefined;
600
+ this.#boot.autoBatch?.settleNow();
601
+ // Every entry audit, in the order `scene-entry-inspectors.ts` states: the opacity convention
602
+ // first, so an opacity it made take effect is what the render trap audit then reports. Adding a
603
+ // fourth audit does not edit this file.
604
+ inspectSceneEntry(ctx.scene, this.#sceneEntryInspectors);
605
+ const entered = this.#boot.onStartSceneEntered;
606
+ this.#boot.onStartSceneEntered = undefined;
706
607
  entered?.();
707
608
  return true;
708
609
  }
@@ -714,10 +615,10 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
714
615
  // A load can finish after the game moved on or stopped. Check before `enter()`, because an
715
616
  // entry hook mutates the live Three.js scene and no later check can undo that. The check
716
617
  // inside `#enterScene` stays: an entry hook may itself navigate.
717
- if (this.#aborted || this.#ctx !== ctx || this.#scene !== scene) return;
618
+ if (this.#boot.aborted || this.#boot.ctx !== ctx || this.#boot.scene !== scene) return;
718
619
  if (!this.#enterScene(scene, ctx)) return;
719
- const renderer = this.#renderer;
720
- const nodes = this.#computeDriven.warmupNodes;
620
+ const renderer = this.#boot.renderer;
621
+ const nodes = this.#boot.computeDriven.warmupNodes;
721
622
  // Before startup readiness has begun, its own warm-up bakes the entered scene's environment.
722
623
  // Baking here too held the world pass for the whole bake: the runner kit's Boot calls
723
624
  // goto("run") from enter(), the bake took 35 s on SwiftShader (about 50 s on CI), the startup
@@ -725,19 +626,19 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
725
626
  // explicit warm-up runs once, right after the start scene, so a transition keeps its bake.
726
627
  const hasEnvironment =
727
628
  ctx.scene.environment?.isTexture === true &&
728
- (this.#startupGateStarted || this.#warmUpConfiguredExplicitly());
629
+ (this.#boot.startupGateStarted || this.#warmUpConfiguredExplicitly());
729
630
  if (renderer === undefined || (nodes.length === 0 && !hasEnvironment)) return;
730
- this.#sceneEntered = false;
631
+ this.#boot.sceneEntered = false;
731
632
  let report: Awaited<ReturnType<typeof warmUpComputeNodes>> | undefined;
732
633
  let environmentPrepared: boolean | undefined;
733
634
  let failure: string | undefined;
734
635
  try {
735
636
  const options = this.#warmUpOptions();
736
637
  if (hasEnvironment) {
737
- const projection = this.#projection;
638
+ const projection = this.#boot.projection;
738
639
  projection?.reconcile();
739
640
  const root = projection?.root ?? ctx.scene;
740
- this.#matrixWorld?.apply(root);
641
+ this.#boot.matrixWorld?.apply(root);
741
642
  // A new environment skips world draws until its retained bake has completed. Only the bake:
742
643
  // a whole-scene warm-up here held the runner kit's first frame for its 45 s budget on
743
644
  // SwiftShader, and the first world frame's startup warm-up compiles the scene anyway.
@@ -770,16 +671,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
770
671
  },
771
672
  )}`,
772
673
  );
773
- if (!this.#aborted && this.#scene === scene) this.#sceneEntered = true;
674
+ if (!this.#boot.aborted && this.#boot.scene === scene) this.#boot.sceneEntered = true;
774
675
  }
775
676
 
776
677
  start(): Promise<void> {
777
- if (this.#started) return Promise.resolve();
678
+ if (this.#boot.started) return Promise.resolve();
778
679
  if (this.#pendingStart !== undefined) return this.#pendingStart;
779
- this.#aborted = false;
680
+ this.#boot.aborted = false;
780
681
  installQuietMarkers();
781
- const pendingStart = this.#boot().catch((error: unknown) => {
782
- this.#disconnectUi();
682
+ const pendingStart = this.#launch().catch((error: unknown) => {
683
+ this.#ui.disconnect();
783
684
  throw error;
784
685
  });
785
686
  this.#pendingStart = pendingStart;
@@ -800,342 +701,57 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
800
701
  return pendingStart;
801
702
  }
802
703
 
803
- /**
804
- * The game's own platform source, else the one a worker host installed on the global scope:
805
- * worker mode runs the unchanged portable entry, so it cannot pass `platform` here (PRD-752).
806
- */
807
- get #platform(): IGamePlatformSource | undefined {
808
- return (
809
- this.#config.platform ??
810
- (globalThis as { __tnGamePlatform?: IGamePlatformSource }).__tnGamePlatform
811
- );
812
- }
813
-
814
- async #boot(): Promise<void> {
815
- const startup = await startGameWorld(this.#bootGame());
704
+ async #launch(): Promise<void> {
705
+ const startup = await startGameWorld(this.#boot);
816
706
  if (startup === undefined) return;
817
- this.#startupDispose = startup.dispose;
818
707
  const frameLoop = startFrameLoop(startup);
819
- this.#frameLoopDispose = frameLoop.dispose;
820
708
  await startScenes(startup, frameLoop);
821
709
  }
822
710
 
823
- /**
824
- * The boot's view of this game, for the two phases that live beside it.
825
- *
826
- * Every member is the private field of the same name, so a phase assigns and reads exactly
827
- * what `#boot` did: the same resources, in the same order, with nothing in between.
828
- */
829
- #bootGame(): IGameBootGame<TState, TPhysics> {
830
- return Object.defineProperties({} as IGameBootGame<TState, TPhysics>, {
831
- // The boot's own calls, bound to this game.
832
- connectUi: { value: (): IUiBridge => this.#connectUi() },
833
- enterScene: {
834
- value: (scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean =>
835
- this.#enterScene(scene, ctx),
836
- },
837
- goto: {
838
- value: (name: string, ctx: ICtx<TState, TPhysics>): Promise<void> => this.#goto(name, ctx),
839
- },
840
- postUiStartup: { value: (): void => this.#postUiStartup() },
841
- teardown: { value: (ctx?: ICtx<TState, TPhysics>): void => this.#teardown(ctx) },
842
- warmUpConfiguredExplicitly: { value: (): boolean => this.#warmUpConfiguredExplicitly() },
843
- warmUpOptions: { value: (): IWarmUpOptions => this.#warmUpOptions() },
844
- // Read through the field every time: a phase runs while `#boot` is still assigning it.
845
- cleanup: { get: () => this.#cleanup },
846
- computeDriven: { get: () => this.#computeDriven },
847
- config: { get: () => this.#config },
848
- platform: { get: () => this.#platform },
849
- state: { get: () => this.#state },
850
- beforeRenderCallbacks: { get: () => this.#beforeRenderCallbacks },
851
- activePlugins: { get: () => this.#activePlugins },
852
- uiBridge: { get: () => this.#uiBridge },
853
- sceneFrame: { get: () => this.#sceneFrame },
854
- sceneEntered: { get: () => this.#sceneEntered },
855
- sceneGeneration: { get: () => this.#sceneGeneration },
856
- pendingSceneEnter: { get: () => this.#pendingSceneEnter },
857
- paused: { get: () => this.#paused },
858
- aborted: { get: () => this.#aborted },
859
- uiReady: { get: () => this.#uiReady },
860
- // Assigned by a phase, exactly as `#boot` assigned the field.
861
- renderer: {
862
- get: () => this.#renderer,
863
- set: (value) => {
864
- this.#renderer = value;
865
- },
866
- },
867
- scene: {
868
- get: () => this.#scene,
869
- set: (value) => {
870
- this.#scene = value;
871
- },
872
- },
873
- sceneName: {
874
- get: () => this.#sceneName,
875
- set: (value) => {
876
- this.#sceneName = value;
877
- },
878
- },
879
- ctx: {
880
- get: () => this.#ctx,
881
- set: (value) => {
882
- this.#ctx = value;
883
- },
884
- },
885
- input: {
886
- get: () => this.#input,
887
- set: (value) => {
888
- this.#input = value;
889
- },
890
- },
891
- viewport: {
892
- get: () => this.#viewport,
893
- set: (value) => {
894
- this.#viewport = value;
895
- },
896
- },
897
- picker: {
898
- get: () => this.#picker,
899
- set: (value) => {
900
- this.#picker = value;
901
- },
902
- },
903
- pointerEvents: {
904
- get: () => this.#pointerEvents,
905
- set: (value) => {
906
- this.#pointerEvents = value;
907
- },
908
- },
909
- matrixWorld: {
910
- get: () => this.#matrixWorld,
911
- set: (value) => {
912
- this.#matrixWorld = value;
913
- },
914
- },
915
- projection: {
916
- get: () => this.#projection,
917
- set: (value) => {
918
- this.#projection = value;
919
- },
920
- },
921
- autoBatch: {
922
- get: () => this.#autoBatch,
923
- set: (value) => {
924
- this.#autoBatch = value;
925
- },
926
- },
927
- cameraCull: {
928
- get: () => this.#cameraCull,
929
- set: (value) => {
930
- this.#cameraCull = value;
931
- },
932
- },
933
- entities: {
934
- get: () => this.#entities,
935
- set: (value) => {
936
- this.#entities = value;
937
- },
938
- },
939
- scheduler: {
940
- get: () => this.#scheduler,
941
- set: (value) => {
942
- this.#scheduler = value;
943
- },
944
- },
945
- afterPhysicsPhase: {
946
- get: () => this.#afterPhysicsPhase,
947
- set: (value) => {
948
- this.#afterPhysicsPhase = value;
949
- },
950
- },
951
- frameBudget: {
952
- get: () => this.#frameBudget,
953
- set: (value) => {
954
- this.#frameBudget = value;
955
- },
956
- },
957
- interpolation: {
958
- get: () => this.#interpolation,
959
- set: (value) => {
960
- this.#interpolation = value;
961
- },
962
- },
963
- geometryCapture: {
964
- get: () => this.#geometryCapture,
965
- set: (value) => {
966
- this.#geometryCapture = value;
967
- },
968
- },
969
- beforeRenderSnapshots: {
970
- get: () => this.#beforeRenderSnapshots,
971
- set: (value) => {
972
- this.#beforeRenderSnapshots = value;
973
- },
974
- },
975
- beforeRenderDepth: {
976
- get: () => this.#beforeRenderDepth,
977
- set: (value) => {
978
- this.#beforeRenderDepth = value;
979
- },
980
- },
981
- hasDepthCoupledOutput: {
982
- get: () => this.#hasDepthCoupledOutput,
983
- set: (value) => {
984
- this.#hasDepthCoupledOutput = value;
985
- },
986
- },
987
- startupGateStarted: {
988
- get: () => this.#startupGateStarted,
989
- set: (value) => {
990
- this.#startupGateStarted = value;
991
- },
992
- },
993
- onStartSceneEntered: {
994
- get: () => this.#onStartSceneEntered,
995
- set: (value) => {
996
- this.#onStartSceneEntered = value;
997
- },
998
- },
999
- renderMetricsEnabled: {
1000
- get: () => this.#renderMetricsEnabled,
1001
- set: (value) => {
1002
- this.#renderMetricsEnabled = value;
1003
- },
1004
- },
1005
- uiRevealed: {
1006
- get: () => this.#uiRevealed,
1007
- set: (value) => {
1008
- this.#uiRevealed = value;
1009
- },
1010
- },
1011
- started: {
1012
- get: () => this.#started,
1013
- set: (value) => {
1014
- this.#started = value;
1015
- },
1016
- },
1017
- resumeScene: {
1018
- get: () => this.#resumeScene,
1019
- set: (value) => {
1020
- this.#resumeScene = value;
1021
- },
1022
- },
1023
- } satisfies Partial<Record<keyof IGameBootGame<TState, TPhysics>, PropertyDescriptor>>);
1024
- }
1025
-
1026
711
  pause(): void {
1027
- this.#paused = true;
712
+ this.#boot.paused = true;
1028
713
  }
1029
714
 
1030
715
  resume(): void {
1031
- this.#paused = false;
716
+ this.#boot.paused = false;
1032
717
  }
1033
718
 
1034
719
  stop(): void {
1035
- this.#aborted = true;
1036
- this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_STOPPED: the game stopped mid-capture.");
720
+ this.#boot.aborted = true;
721
+ this.#boot.geometryCapture?.cancel(
722
+ "TN_GEOMETRY_CAPTURE_STOPPED: the game stopped mid-capture.",
723
+ );
1037
724
  this.#teardown();
1038
725
  uninstallQuietMarkers();
1039
726
  }
1040
727
 
1041
- #disposePlugin(plugin: IGamePluginHooks<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): void {
1042
- if (this.#disposedPlugins.has(plugin)) return;
1043
- this.#disposedPlugins.add(plugin);
1044
- plugin.dispose?.(ctx);
1045
- }
1046
-
1047
- #teardown(startingCtx?: ICtx<TState, TPhysics>): void {
1048
- this.#onStartSceneEntered = undefined;
1049
- const ctx = this.#ctx ?? startingCtx;
1050
- // Teardown is failure-atomic: one throwing release must not strand the resources after it.
1051
- // Every attempt runs, errors are collected, and the first — the original cause — is thrown
1052
- // once all attempts and the final leak check have completed.
1053
- const failures: unknown[] = [];
1054
- this.#disconnectUi();
1055
- this.#frameLoopDispose?.();
1056
- this.#frameLoopDispose = undefined;
1057
- // After the loop that reports into it, and reached on every path: the field is set the moment
1058
- // the budget exists, so a launch that threw inside the frame-loop phase before it could answer
1059
- // still loses nothing here. This is the release the un-split `#teardown` performed.
1060
- this.#frameBudget?.dispose();
1061
- this.#afterPhysicsPhase?.clear();
1062
- this.#beforeRenderCallbacks.clear();
1063
- this.#interpolation?.clear();
1064
- this.#interpolation = undefined;
1065
- if (this.#sceneEntered && ctx !== undefined) {
1066
- try {
1067
- this.#scene?.exit(ctx);
1068
- } catch (error) {
1069
- failures.push(error);
1070
- }
1071
- }
1072
- this.#sceneFrame = undefined;
1073
- this.#sceneEntered = false;
1074
- this.#scheduler?.clear();
1075
- this.#entities?.clear();
1076
- this.#entities = undefined;
1077
- if (ctx !== undefined)
1078
- for (const plugin of this.#activePlugins) {
1079
- try {
1080
- this.#disposePlugin(plugin, ctx);
1081
- } catch (error) {
1082
- failures.push(error);
1083
- }
1084
- }
1085
- this.#activePlugins = [];
1086
- if (this.#startupDispose !== undefined) {
1087
- const release = this.#startupDispose;
1088
- this.#startupDispose = undefined;
1089
- try {
1090
- release();
1091
- } catch (error) {
1092
- failures.push(error);
1093
- }
1094
- }
1095
- for (const cleanup of this.#cleanup.splice(0)) {
1096
- try {
1097
- cleanup();
1098
- } catch (error) {
1099
- failures.push(error);
1100
- }
1101
- }
1102
- this.#autoBatch?.reset();
1103
- if (ctx !== undefined) clearScene(ctx.scene, this.#computeDriven);
1104
- this.#cameraCull?.dispose();
1105
- this.#cameraCull = undefined;
1106
- this.#matrixWorld?.dispose();
1107
- this.#matrixWorld = undefined;
1108
- this.#input?.dispose();
1109
- this.#state.stop();
1110
- ctx?.canvasLayer.dispose();
1111
- this.#viewport?.dispose();
1112
- const renderer = this.#renderer;
1113
- renderer?.dispose();
1114
- if (renderer !== undefined) {
1115
- const platform = this.#platform;
1116
- if (platform === undefined) renderer.domElement.remove?.();
1117
- else platform.unmountCanvas(renderer.domElement);
1118
- }
1119
- this.#renderer = undefined;
1120
- this.#viewport = undefined;
1121
- this.#input = undefined;
1122
- this.#scene = undefined;
1123
- this.#ctx = undefined;
1124
- this.#hasDepthCoupledOutput = false;
1125
- this.#pointerEvents?.dispose();
1126
- this.#pointerEvents = undefined;
1127
- this.#picker?.dispose();
1128
- this.#picker = undefined;
1129
- this.#scheduler = undefined;
1130
- this.#afterPhysicsPhase = undefined;
1131
- this.#disposedPlugins.clear();
1132
- this.#paused = false;
1133
- this.#started = false;
728
+ /**
729
+ * Releases everything the boot acquired. Each phase pushed its own release onto `cleanup` as it
730
+ * acquired the resource, and they run newest first (`drainCleanup`), so nothing is released while
731
+ * something built on it is still alive. The order the specs pin falls out of the push order:
732
+ * loop, scene exit, plugin `dispose`, plugin cleanups, input, store, renderer.
733
+ *
734
+ * The UI goes first and is not on the stack: its lifetime is the game's, not a boot's, and the
735
+ * scene exit and plugin `dispose` after it must not publish to a page that is leaving.
736
+ */
737
+ #teardown(): void {
738
+ const boot = this.#boot;
739
+ boot.onStartSceneEntered = undefined;
740
+ const ctx = boot.ctx;
741
+ this.#ui.disconnect();
742
+ // Failure-atomic: one throwing release does not strand the ones after it. The first failure,
743
+ // the original cause, is thrown once all have run and the leak check has completed.
744
+ const failures = drainCleanup(boot.cleanup);
745
+ boot.scene = undefined;
746
+ boot.ctx = undefined;
747
+ boot.hasDepthCoupledOutput = false;
748
+ boot.paused = false;
749
+ boot.started = false;
1134
750
  // Runs even when releases above failed; its verdict loses to a real cleanup error, which is
1135
751
  // the more actionable diagnosis of what went wrong while stopping.
1136
752
  if ((ctx?.scene.children.length ?? 0) > 0)
1137
753
  failures.push(new Error("IGame teardown leaked scene objects."));
1138
- if (failures.length > 0) throw failures[0];
754
+ throwFirst(failures);
1139
755
  }
1140
756
  }
1141
757