@threenative/core 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.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
package/src/game.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  Vector2,
8
8
  } from "three";
9
9
  import { type IAssetLoaderOptions, createAssetLoader } from "./assets.js";
10
+ import { AutoBatch, type IAutoBatchConfig } from "./auto-batch.js";
10
11
  import { CanvasLayer } from "./canvas-layer.js";
11
12
  import { updateClusteredMeshes } from "./clustered-mesh.js";
12
13
  import { ComputeDrivenRegistry, isComputeDriven } from "./compute-driven.js";
@@ -33,9 +34,19 @@ import { MatrixWorldPass } from "./matrix-world.js";
33
34
  import { updateModelLods } from "./model-lod.js";
34
35
  import { ScenePicker } from "./picking.js";
35
36
  import type { IPipelineCensus } from "./pipeline-census.js";
36
- import { getPlatform } from "./platform.js";
37
+ import { getPlatform, hostDocument, hostWindow } from "./platform.js";
37
38
  import { PointerEvents3D } from "./pointer-events.js";
38
- import { FrameCounters, counterDeviceOf } from "./profiling/FrameCounters.js";
39
+ import {
40
+ FrameCounters,
41
+ counterDeviceOf,
42
+ createCrossingReader,
43
+ createEngineCounterReader,
44
+ } from "./profiling/FrameCounters.js";
45
+ import {
46
+ createStageReader,
47
+ createWorkReader,
48
+ stageMetersRequested,
49
+ } from "./profiling/FrameStages.js";
39
50
  import {
40
51
  SPANS,
41
52
  SpanRecorder,
@@ -47,6 +58,12 @@ import {
47
58
  spanNow,
48
59
  spansRequested,
49
60
  } from "./profiling/Spans.js";
61
+ import {
62
+ countDebug,
63
+ debugRequested,
64
+ measureDebug,
65
+ observeDebugGc,
66
+ } from "./profiling/debug-telemetry.js";
50
67
  import { applyOpacityConvention } from "./profiling/opacity-convention.js";
51
68
  import {
52
69
  RenderListValidator,
@@ -67,6 +84,7 @@ import {
67
84
  unlitFoliageWarning,
68
85
  } from "./profiling/unlit-foliage-warning.js";
69
86
  import { formatProjectionWindow } from "./projection-marker.js";
87
+ import { installQuietMarkers, uninstallQuietMarkers } from "./quiet-markers.js";
70
88
  import { type IRandom, createRandom } from "./random.js";
71
89
  import { RenderCameraCull } from "./render-camera-cull.js";
72
90
  import { RenderPassBudget } from "./render-pass-budget.js";
@@ -83,6 +101,8 @@ import {
83
101
  type IRendererOptions,
84
102
  type RendererKind,
85
103
  createRenderer,
104
+ rendererFrameGateSkips,
105
+ rendererWorldPresented,
86
106
  } from "./renderer.js";
87
107
  import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
88
108
  import type {
@@ -95,7 +115,14 @@ import type {
95
115
  } from "./scene.js";
96
116
  import { Scheduler } from "./schedule.js";
97
117
  import {
118
+ type IStartupOffscreenBytes,
119
+ STARTUP_OFFSCREEN_BYTES_MARKER,
120
+ measureStartupOffscreenBytes,
121
+ } from "./startup-offscreen-bytes.js";
122
+ import {
123
+ type IStartupImageState,
98
124
  STARTUP_COMPILE_BUDGET_MS,
125
+ STARTUP_STABLE_WINDOW_MS,
99
126
  STARTUP_STALL_MS,
100
127
  type StartupCompile,
101
128
  StartupReadiness,
@@ -112,6 +139,7 @@ import {
112
139
  type IUiBridge,
113
140
  UI_DEV_METRICS_MESSAGE,
114
141
  UI_READY_INTENT,
142
+ UI_STARTUP_MESSAGE,
115
143
  connectUiBridge,
116
144
  } from "./ui-bridge.js";
117
145
  import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
@@ -119,6 +147,8 @@ import { type IViewportOptions, Viewport } from "./viewport.js";
119
147
  import {
120
148
  type IWarmUpOptions,
121
149
  type IWarmUpReport,
150
+ prepareSceneEnvironment,
151
+ sceneNeedsEnvironmentPreparation,
122
152
  warmUpComputeNodes,
123
153
  warmUpScene,
124
154
  } from "./warmup.js";
@@ -200,6 +230,12 @@ export interface IGamePluginRuntime {
200
230
  * they read are the ones the world actually has. The frame loop remains held throughout.
201
231
  */
202
232
  readonly holdStart?: (gate: Promise<void>) => Promise<void>;
233
+ /**
234
+ * Settles when the start scene's `load()` has finished, so its entities are registered. A runner's
235
+ * pre-entry setup awaits it: setup names entities `load()` adds, and an async `load()` (a texture
236
+ * or a model fetch) is still pending when the runner first attaches. Rejects when `load()` throws.
237
+ */
238
+ readonly startSceneLoaded?: () => Promise<void>;
203
239
  readonly observations: IGameRuntimeObservations;
204
240
  readonly tick: () => number;
205
241
  readonly runtimeDiagnosticsSeries?: () => readonly IRenderPerformanceSample[];
@@ -215,8 +251,12 @@ export interface IGamePluginRuntime {
215
251
  * must be reported rather than inferred from a phase that cannot distinguish the two.
216
252
  */
217
253
  readonly startupCompileSettled?: () => boolean;
254
+ /** The loading cover has lifted: the startup hand-off finished and page UI shows state. */
255
+ readonly startupRevealed?: () => boolean;
218
256
  /** When the startup milestones happened, for the playtest bridge's startup observation. */
219
257
  readonly startupTimeline?: () => IStartupTimeline;
258
+ /** What the reveal waited for that the spawn camera does not show; absent until the reveal. */
259
+ readonly startupOffscreenBytes?: () => IStartupOffscreenBytes | undefined;
220
260
  /** The renderer-owned bounded pipeline capture, when the renderer has not been opted out. */
221
261
  readonly pipelineCensus?: () => IPipelineCensus;
222
262
  /**
@@ -356,6 +396,15 @@ export type GamePlugin<
356
396
  */
357
397
  const STARTUP_READY_GLOBAL = "__TN_STARTUP_READY__";
358
398
 
399
+ /**
400
+ * Drawn frames the state publish waits after startup readiness. The page paints a state change on
401
+ * the next vsync, but the canvas frame that lifts the cover reaches the screen only when the GPU has
402
+ * drawn it: Lantern Vale's HUD (`loaded` on `whenReady()`) painted one frame over its loading cover.
403
+ * Three, because a renderer keeps at most two frames on the GPU (the Wasm engine's gate declines a
404
+ * third), so the third drawn frame proves the first uncovered one has left the GPU.
405
+ */
406
+ const STARTUP_HANDOFF_FRAMES = 3;
407
+
359
408
  export interface IGameConfig<
360
409
  TState extends Record<string, unknown> = Record<string, unknown>,
361
410
  TPhysics = undefined,
@@ -379,6 +428,13 @@ export interface IGameConfig<
379
428
  * assertion, because turning a convention off must not turn its measurement off.
380
429
  */
381
430
  readonly frameBudget?: IFrameBudgetOptions | false;
431
+ /**
432
+ * Static meshes that share a material merge into one draw once the scene has settled, on by
433
+ * default and reported as `TN_AUTO_BATCH`. A mesh the game later moves, hides or re-materials
434
+ * comes back at once. `false` turns the pass off; `userData.batch = "off"` on a mesh or any
435
+ * ancestor keeps just that subtree out.
436
+ */
437
+ readonly autoBatch?: boolean | IAutoBatchConfig;
382
438
  readonly initialState?: TState;
383
439
  /**
384
440
  * The **pre-start** shader warm-up. Off by default, and that is not the same as no warm-up.
@@ -504,8 +560,11 @@ export interface IGame<
504
560
  readonly ui: IGameUi;
505
561
  /** Rebuilds the requested scene from its initial state, then merges an optional carry patch. */
506
562
  goto(name: string, options?: IGotoOptions<TState>): Promise<void>;
507
- /** Boot into `name` instead of `config.start` on the next `start()`. Hot reload's restore path. */
508
- resumeScene(name: string): void;
563
+ /**
564
+ * Boot into `name` instead of `config.start` on the next `start()`. Hot reload's restore path.
565
+ * `revealed`: the session already showed its HUD, so the restarted game keeps the cover lifted.
566
+ */
567
+ resumeScene(name: string, options?: { readonly revealed?: boolean }): void;
509
568
  start(): Promise<void>;
510
569
  pause(): void;
511
570
  resume(): void;
@@ -589,13 +648,6 @@ function rendererDrawCallCount(raw: unknown): number | undefined {
589
648
  return typeof calls === "number" && Number.isFinite(calls) && calls >= 0 ? calls : undefined;
590
649
  }
591
650
 
592
- /** Cumulative render() calls the renderer declined to draw (the Wasm web engine's frame gate), when it counts them. */
593
- function rendererFrameGateSkips(raw: unknown): number | undefined {
594
- const info = (raw as { info?: { engine?: { frameGateSkips?: unknown } } } | null)?.info;
595
- const skips = info?.engine?.frameGateSkips;
596
- return typeof skips === "number" && Number.isFinite(skips) ? skips : undefined;
597
- }
598
-
599
651
  function rendererPerformanceMetrics(raw: unknown): {
600
652
  drawCalls?: number;
601
653
  triangles?: number;
@@ -722,6 +774,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
722
774
  #loop: FixedStepLoop | undefined;
723
775
  #interpolation: PhysicsInterpolation | undefined;
724
776
  #projection: SceneRenderProjection | undefined;
777
+ #autoBatch: AutoBatch | undefined;
725
778
  #cameraCull: RenderCameraCull | undefined;
726
779
  #matrixWorld: MatrixWorldPass | undefined;
727
780
  #cleanup: Array<() => void> = [];
@@ -746,19 +799,19 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
746
799
  #pendingStart: Promise<void> | undefined;
747
800
  #aborted = false;
748
801
  #sceneEntered = false;
749
- /**
750
- * The scene a `goto()` is loading right now, or undefined when none is.
751
- *
752
- * Between a `goto()` and its `enter()` the registry is cleared and nothing owns the world, so a
753
- * reader that needs the world's entities has to wait for this rather than for the scene it
754
- * navigated from. The playtest handshake reads exactly that.
755
- */
802
+ /** Startup readiness has begun its first-use gate; before that, it bakes the entered environment. */
803
+ #startupGateStarted = false;
804
+ /** The full `goto()` transition, including first-use warm-up, or undefined when none is. */
756
805
  #pendingSceneEnter: Promise<void> | undefined;
806
+ /** One-shot notification after the scene that owns the world has entered, before warm-up. */
807
+ #onStartSceneEntered: (() => void) | undefined;
757
808
  #paused = false;
758
809
  #started = false;
759
810
  #uiBridge: IUiBridge | undefined;
760
811
  #uiPublisher: IUiStatePublisher | undefined;
761
812
  #uiReady = false;
813
+ /** The loading cover has lifted and page UI may show state; see `UI_STARTUP_MESSAGE`. */
814
+ #uiRevealed = false;
762
815
  // Flipped only by a diagnostics consumer announcing itself; see enableRuntimeDiagnostics().
763
816
  #renderMetricsEnabled = false;
764
817
  // Depth-coupled output needs the scene hook before its pass; ordinary scenes retain the
@@ -805,9 +858,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
805
858
  * available here: it throws before `start()`, and it resets state to the destination's
806
859
  * `initialState`, which would discard the very state being restored.
807
860
  */
808
- resumeScene(name: string): void {
861
+ resumeScene(name: string, options?: { readonly revealed?: boolean }): void {
809
862
  if (this.#config.scenes[name] === undefined) throw new Error(`Unknown scene '${name}'.`);
810
863
  this.#resumeScene = name;
864
+ // An edit restarts the game, and its HUD would blank until this startup lifted the cover
865
+ // again: seconds after every save on a slow GPU. A session that showed its HUD keeps it.
866
+ // The updated module may have connected its UI already and told a waiting HUD to hide.
867
+ if (options?.revealed !== true) return;
868
+ this.#uiRevealed = true;
869
+ if (this.#uiBridge?.hasPeer()) this.#postUiStartup();
811
870
  }
812
871
 
813
872
  get state(): GameStore<TState> {
@@ -836,10 +895,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
836
895
  this.#uiBridge = bridge;
837
896
  // The store already coalesces writes at flush. Deferring this again waits for the native
838
897
  // host's next microtask pump, after that frame's WebView event pump has already passed.
898
+ // Ahead of the first state, which `publishUiState` sends at once when a UI is already waiting.
899
+ if (bridge.hasPeer()) this.#postUiStartup();
839
900
  this.#uiPublisher = publishUiState(bridge, this.#state, { schedule: (flush) => flush() });
840
901
  onUiIntent(bridge, (intent) => {
841
902
  if (intent !== UI_READY_INTENT) return;
842
903
  this.#uiReady = true;
904
+ // Before the state: a UI that mounts after the reveal must learn the cover is gone, and one
905
+ // that mounts before it must learn to hide.
906
+ this.#postUiStartup();
843
907
  // Publish immediately: the UI has just rendered against nothing, and waiting for the store's
844
908
  // next change would leave a HUD showing its initial values for up to a tick.
845
909
  this.#uiPublisher?.publish();
@@ -847,7 +911,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
847
911
  return bridge;
848
912
  }
849
913
 
914
+ #postUiStartup(): void {
915
+ this.#uiBridge?.post({
916
+ type: UI_STARTUP_MESSAGE,
917
+ phase: this.#uiRevealed ? "ready" : "covered",
918
+ });
919
+ }
920
+
850
921
  #disconnectUi(): void {
922
+ this.#uiRevealed = false;
851
923
  this.#uiPublisher?.stop();
852
924
  this.#uiPublisher = undefined;
853
925
  this.#uiReady = false;
@@ -901,6 +973,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
901
973
  // Put back anything the cull hid before the outgoing scene is cleared, so a scene change never
902
974
  // leaves an object invisible if the game keeps a reference to it.
903
975
  this.#cameraCull?.restore();
976
+ this.#autoBatch?.reset();
904
977
  clearScene(ctx.scene, this.#computeDriven);
905
978
  const scene = new SceneType();
906
979
  this.#scene = scene;
@@ -937,6 +1010,10 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
937
1010
  if (this.#scene !== scene) return false;
938
1011
  this.#sceneFrame = typeof frame === "function" ? frame : undefined;
939
1012
  this.#sceneEntered = true;
1013
+ // What `enter()` built is what the warm-up compiles and the first frame draws, so it merges
1014
+ // now, before either: no frame is ever drawn unmerged, and the compile counts merged meshes,
1015
+ // not every source. Anything that moves afterwards is given back by the guard.
1016
+ this.#autoBatch?.settleNow();
940
1017
  // Before the audit, so an opacity the convention made take effect is reported as a warning.
941
1018
  const opacity = applyOpacityConvention(ctx.scene);
942
1019
  if (opacity !== undefined) console.warn(opacity);
@@ -949,6 +1026,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
949
1026
  const unlit = unlitFoliageWarning(ctx.scene);
950
1027
  if (unlit !== undefined)
951
1028
  console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
1029
+ const entered = this.#onStartSceneEntered;
1030
+ this.#onStartSceneEntered = undefined;
1031
+ entered?.();
952
1032
  return true;
953
1033
  }
954
1034
 
@@ -956,27 +1036,62 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
956
1036
  scene: Scene<TState, TPhysics>,
957
1037
  ctx: ICtx<TState, TPhysics>,
958
1038
  ): Promise<void> {
1039
+ // A load can finish after the game moved on or stopped. Check before `enter()`, because an
1040
+ // entry hook mutates the live Three.js scene and no later check can undo that. The check
1041
+ // inside `#enterScene` stays: an entry hook may itself navigate.
1042
+ if (this.#aborted || this.#ctx !== ctx || this.#scene !== scene) return;
959
1043
  if (!this.#enterScene(scene, ctx)) return;
960
1044
  const renderer = this.#renderer;
961
1045
  const nodes = this.#computeDriven.warmupNodes;
962
- if (renderer === undefined || nodes.length === 0) return;
1046
+ // Before startup readiness has begun, its own warm-up bakes the entered scene's environment.
1047
+ // Baking here too held the world pass for the whole bake: the runner kit's Boot calls
1048
+ // goto("run") from enter(), the bake took 35 s on SwiftShader (about 50 s on CI), the startup
1049
+ // warm-up then prepared it again, and the launch sat at 80% until TN_STARTUP_STALLED. An
1050
+ // explicit warm-up runs once, right after the start scene, so a transition keeps its bake.
1051
+ const hasEnvironment =
1052
+ ctx.scene.environment?.isTexture === true &&
1053
+ (this.#startupGateStarted || this.#warmUpConfiguredExplicitly());
1054
+ if (renderer === undefined || (nodes.length === 0 && !hasEnvironment)) return;
963
1055
  this.#sceneEntered = false;
964
1056
  let report: Awaited<ReturnType<typeof warmUpComputeNodes>> | undefined;
1057
+ let environmentPrepared: boolean | undefined;
965
1058
  let failure: string | undefined;
966
1059
  try {
967
- report = await warmUpComputeNodes(renderer, nodes, this.#warmUpOptions());
1060
+ const options = this.#warmUpOptions();
1061
+ if (hasEnvironment) {
1062
+ const projection = this.#projection;
1063
+ projection?.reconcile();
1064
+ const root = projection?.root ?? ctx.scene;
1065
+ this.#matrixWorld?.apply(root);
1066
+ // A new environment skips world draws until its retained bake has completed. Only the bake:
1067
+ // a whole-scene warm-up here held the runner kit's first frame for its 45 s budget on
1068
+ // SwiftShader, and the first world frame's startup warm-up compiles the scene anyway.
1069
+ const now = globalThis.performance?.now() ?? Date.now();
1070
+ environmentPrepared = await prepareSceneEnvironment(
1071
+ renderer,
1072
+ root,
1073
+ ctx.camera,
1074
+ now + (options.budgetMs ?? STARTUP_COMPILE_BUDGET_MS),
1075
+ );
1076
+ }
1077
+ if (nodes.length > 0) report = await warmUpComputeNodes(renderer, nodes, options);
968
1078
  } catch (error) {
969
1079
  failure = error instanceof Error ? error.message : String(error);
970
1080
  }
971
1081
  console.log(
972
- `TN_TRANSITION_COMPUTE_WARMUP:${JSON.stringify(
973
- report === undefined
1082
+ `${hasEnvironment ? "TN_TRANSITION_WARMUP" : "TN_TRANSITION_COMPUTE_WARMUP"}:${JSON.stringify(
1083
+ failure !== undefined || (report === undefined && environmentPrepared === undefined)
974
1084
  ? { failed: failure ?? "unknown" }
975
1085
  : {
976
- compiled: report.compiled,
977
- abandoned: report.abandoned,
978
- unsupported: report.unsupported,
979
- timedOut: report.timedOut,
1086
+ ...(environmentPrepared === undefined ? {} : { environmentPrepared }),
1087
+ ...(report === undefined
1088
+ ? {}
1089
+ : {
1090
+ compiled: report.compiled,
1091
+ abandoned: report.abandoned,
1092
+ unsupported: report.unsupported,
1093
+ timedOut: report.timedOut,
1094
+ }),
980
1095
  },
981
1096
  )}`,
982
1097
  );
@@ -987,6 +1102,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
987
1102
  if (this.#started) return Promise.resolve();
988
1103
  if (this.#pendingStart !== undefined) return this.#pendingStart;
989
1104
  this.#aborted = false;
1105
+ installQuietMarkers();
990
1106
  const pendingStart = this.#boot().catch((error: unknown) => {
991
1107
  this.#disconnectUi();
992
1108
  throw error;
@@ -1009,7 +1125,19 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1009
1125
  return pendingStart;
1010
1126
  }
1011
1127
 
1128
+ /**
1129
+ * The game's own platform source, else the one a worker host installed on the global scope:
1130
+ * worker mode runs the unchanged portable entry, so it cannot pass `platform` here (PRD-752).
1131
+ */
1132
+ get #platform(): IGamePlatformSource | undefined {
1133
+ return (
1134
+ this.#config.platform ??
1135
+ (globalThis as { __tnGamePlatform?: IGamePlatformSource }).__tnGamePlatform
1136
+ );
1137
+ }
1138
+
1012
1139
  async #boot(): Promise<void> {
1140
+ const debug = debugRequested();
1013
1141
  const bootSceneName = this.#resumeScene ?? this.#config.start;
1014
1142
  this.#resumeScene = undefined;
1015
1143
  const SceneType = this.#config.scenes[bootSceneName];
@@ -1041,31 +1169,33 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1041
1169
  this.#config.renderer?.resolutionScale,
1042
1170
  getPlatform().os,
1043
1171
  ),
1044
- source: this.#config.renderer?.source ?? this.#config.platform?.renderer,
1172
+ source: this.#config.renderer?.source ?? this.#platform?.renderer,
1045
1173
  });
1046
1174
  if (this.#aborted) {
1047
1175
  renderer.dispose();
1048
1176
  return;
1049
1177
  }
1050
1178
  this.#renderer = renderer;
1179
+ // Before anything draws for this startup, including the warm-up and every covered world frame: the owned
1180
+ // engine keeps drawing, but presents nothing until a frame's shadow and exposure inputs are ready, so the
1181
+ // player never sees the two unsettled pictures a cold post chain produced (measured 185 -> 124 -> 108 mean
1182
+ // brightness). A renderer without the seam presents every frame exactly as before.
1183
+ renderer.setPresentationHeld?.(true);
1184
+ this.#cleanup.push(() => renderer.setPresentationHeld?.(false));
1051
1185
  const canvas = renderer.domElement;
1052
- const platform = this.#config.platform;
1186
+ const platform = this.#platform;
1187
+ const page = hostDocument();
1053
1188
  if (platform !== undefined) platform.mountCanvas(canvas, this.#config.container);
1054
1189
  else if (
1055
1190
  this.#config.container !== undefined &&
1056
1191
  canvas.parentElement !== this.#config.container
1057
1192
  )
1058
1193
  this.#config.container.append(canvas);
1059
- else if (canvas.parentElement === null && typeof document !== "undefined")
1060
- document.body.append(canvas);
1194
+ else if (canvas.parentElement === null && page !== undefined) page.body.append(canvas);
1061
1195
 
1062
1196
  const inputTarget =
1063
1197
  this.#config.inputTarget ??
1064
- (platform === undefined
1065
- ? typeof window === "undefined"
1066
- ? canvas
1067
- : window
1068
- : (platform.inputTarget ?? canvas));
1198
+ (platform === undefined ? (hostWindow() ?? canvas) : (platform.inputTarget ?? canvas));
1069
1199
  this.#input = new InputMap(
1070
1200
  this.#config.input,
1071
1201
  inputTarget,
@@ -1075,6 +1205,8 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1075
1205
  );
1076
1206
  this.#state.start();
1077
1207
  const threeScene = new ThreeScene();
1208
+ if (debug && "__debugTelemetry" in threeScene)
1209
+ (threeScene as ThreeScene & { __debugTelemetry: boolean }).__debugTelemetry = true;
1078
1210
  const camera = createCamera(this.#config.camera);
1079
1211
  const interpolation = new PhysicsInterpolation(this.#config.physicsInterpolation);
1080
1212
  this.#interpolation = interpolation;
@@ -1086,6 +1218,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1086
1218
  // support against the real backend; a target that supports none fails right here.
1087
1219
  const assets = createAssetLoader({ ...this.#config.assets, renderer: renderer.raw });
1088
1220
  if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
1221
+ this.#cleanup.push(() => assets.dispose());
1089
1222
  const entities = new Registry();
1090
1223
  const random = createRandom(this.#config.seed);
1091
1224
  const scheduler = new Scheduler();
@@ -1132,14 +1265,28 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1132
1265
  threeScene.matrixWorldAutoUpdate = false;
1133
1266
  // Built before the context because `ctx.startup` reads it: a game asks what the framework's
1134
1267
  // startup is doing, and the answer is this pass.
1268
+ // The owned renderer retains its own velocity history; JS snapshots serve Three's accessors.
1269
+ const engineInfo = (renderer.raw as { info?: object }).info;
1270
+ const ownedEngine = engineInfo !== undefined && "engine" in engineInfo;
1135
1271
  const projection = new SceneRenderProjection(threeScene, {
1136
1272
  // The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
1137
1273
  // names the material check beside accepting it, and the projection owns both readings.
1138
1274
  projection: this.#config.render?.projection,
1139
- velocity: () => renderer.renderChainUsesPerObjectVelocity?.() ?? false,
1275
+ velocity: () => !ownedEngine && (renderer.renderChainUsesPerObjectVelocity?.() ?? false),
1140
1276
  matrixWorld: matrixWorldPass,
1141
1277
  });
1142
1278
  this.#projection = projection;
1279
+ const autoBatchConfig = this.#config.autoBatch;
1280
+ const autoBatch = new AutoBatch(threeScene, {
1281
+ enabled: autoBatchConfig !== false,
1282
+ entities,
1283
+ ...(typeof autoBatchConfig === "object" ? autoBatchConfig : {}),
1284
+ report: (line) =>
1285
+ (this.#config.frameBudget === false ? undefined : this.#config.frameBudget?.report)?.(
1286
+ line,
1287
+ ) ?? console.info(line),
1288
+ });
1289
+ this.#autoBatch = autoBatch;
1143
1290
  // Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
1144
1291
  // and measured whether or not the game narrows or declines it. Its decision is per camera, so
1145
1292
  // a shadow caster and anything attached to the camera are never dropped on the main view alone.
@@ -1148,6 +1295,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1148
1295
  });
1149
1296
  this.#cameraCull = cameraCull;
1150
1297
  let projectionSettled = false;
1298
+ let offscreenBytes: IStartupOffscreenBytes | undefined;
1151
1299
  /**
1152
1300
  * Progress is a high-water mark over the measured load state, never a value that can fall.
1153
1301
  *
@@ -1180,6 +1328,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1180
1328
  };
1181
1329
  let worldRendered = false;
1182
1330
  let loadingFramePresented = false;
1331
+ let stateHandOffFrames = 0;
1183
1332
  let markProjectionSettled: () => void = () => undefined;
1184
1333
  const projectionReady = new Promise<void>((resolve) => {
1185
1334
  markProjectionSettled = resolve;
@@ -1203,6 +1352,24 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1203
1352
  afterHolds: async () => {
1204
1353
  await warmUp("TN_STARTUP_WARMUP_HELD", Math.round(STARTUP_COMPILE_BUDGET_MS / 3), false);
1205
1354
  },
1355
+ /**
1356
+ * The renderer's own answer, which no timer may stand in for: a world frame whose shadow inputs are
1357
+ * initialized and whose meter has measured within 3% of its target. On the owned engine the hidden world
1358
+ * keeps drawing behind the cover, so this becomes true on its own; a renderer without the seam answers
1359
+ * true, and its launch is exactly what it was. The answer names the input it is short of, so a launch that
1360
+ * reached its deadline (`STARTUP_IMAGE_TIMEOUT_MS`) reports which one never arrived.
1361
+ */
1362
+ imageReady: (): boolean | IStartupImageState => {
1363
+ // A cover the game asked not to draw the world behind has no frame to wait for, and waiting would
1364
+ // hold it open forever; every other game keeps drawing and reaches this on its own.
1365
+ if (
1366
+ canvasLayer.opaque &&
1367
+ !canvasLayer.renderWorldDuringStartup &&
1368
+ !canvasLayer.keepWorldRendering
1369
+ )
1370
+ return true;
1371
+ return renderer.firstWorldFrame?.() ?? true;
1372
+ },
1206
1373
  });
1207
1374
  // Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
1208
1375
  // script ran, not that a pixel reached the screen, so waiting on it never closed the race it
@@ -1221,6 +1388,13 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1221
1388
  const startupCoverActive = (): boolean =>
1222
1389
  !startupReadiness.ready &&
1223
1390
  (canvasLayer.opaque || (this.#uiReady && this.#uiBridge?.hasPeer() === true));
1391
+ // A draw the warm-up makes in a timer task is presented by the browser on its own, without the
1392
+ // frame loop's overlay: a Wasm engine still baking the environment presents black, and the
1393
+ // cover flickers against it. Paint the cover again in the same task.
1394
+ const repaintCover = (): void => {
1395
+ if (canvasLayer.opaque && canvasLayer.scene.children.length > 0)
1396
+ renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
1397
+ };
1224
1398
  const timeline: { -readonly [K in keyof IStartupTimeline]: IStartupTimeline[K] } = {};
1225
1399
  let warmUpStatus: IStartupStatus["warmup"];
1226
1400
  const now = (): number => globalThis.performance?.now() ?? Date.now();
@@ -1230,17 +1404,23 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1230
1404
  * device, with the only account of either on a terminal the player does not have.
1231
1405
  */
1232
1406
  const stopStallWatch = watchStartupStall({
1233
- pending: () => [...assets.progress.pending, ...startupReadiness.pendingHolds],
1407
+ pending: () => [
1408
+ ...assets.progress.pending,
1409
+ ...startupReadiness.pendingHolds,
1410
+ ...startupReadiness.pendingImage,
1411
+ ],
1234
1412
  progress: () => this.#ctx?.startup.progress ?? 0,
1235
1413
  workProgress: () => assets.progress.settled + startupReadiness.workProgress,
1236
1414
  stallMs: STARTUP_STALL_MS,
1237
1415
  });
1416
+ this.#cleanup.push(stopStallWatch);
1238
1417
  watchDeviceLoss(
1239
1418
  (
1240
1419
  renderer.raw as {
1241
1420
  backend?: { device?: { lost?: Promise<{ reason?: string; message?: string }> } };
1242
1421
  }
1243
1422
  ).backend?.device,
1423
+ () => this.#aborted || this.#renderer !== renderer,
1244
1424
  );
1245
1425
  // Stamped when the FRAMEWORK is done, which is before `whenReady()` whenever the game has
1246
1426
  // registered a `startup.hold()`. Two stamps, because one number cannot be both "what the
@@ -1258,12 +1438,34 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1258
1438
  timeline.frameworkReadyMs ??= now();
1259
1439
  timeline.readyMs ??= now();
1260
1440
  projectionSettled = true;
1441
+ // The first world frame the player sees is the next one this renderer draws, so the hold comes off
1442
+ // here and only here: every exit before it (abort, dispose, a failed launch) leaves the cover up.
1443
+ renderer.setPresentationHeld?.(false);
1444
+ // What a game does on `whenReady()` (lift its cover, show its HUD) reaches the page with the
1445
+ // world frame, not before it: see `STARTUP_HANDOFF_FRAMES`.
1446
+ stateHandOffFrames = STARTUP_HANDOFF_FRAMES;
1261
1447
  markProjectionSettled();
1448
+ // The reveal is the first moment the network is free and the player is playing: fill the
1449
+ // rest of the release at idle priority from here, never before.
1450
+ void assets.startBackgroundFill();
1262
1451
  // A host capturing a frame has no other way to know the world is on screen. Counting frames
1263
1452
  // cannot express it: on a software rasteriser the gate resolves on its bounded window rather
1264
1453
  // than on five in-budget frames, so a fast 300-frame run finishes before the world is shown
1265
1454
  // and captures the loading state. The native screenshot path waits on this flag.
1266
1455
  (globalThis as Record<string, unknown>)[STARTUP_READY_GLOBAL] = true;
1456
+ // Measurement only: what the reveal waited for that the spawn camera does not show. A throw
1457
+ // here must cost the report, never the game that is already ready.
1458
+ try {
1459
+ offscreenBytes = measureStartupOffscreenBytes(assets.resolved, threeScene, camera);
1460
+ if (offscreenBytes.offscreenBytes > 0)
1461
+ (offscreenBytes.warn ? console.warn : console.log)(
1462
+ `${STARTUP_OFFSCREEN_BYTES_MARKER}:${JSON.stringify(offscreenBytes)}`,
1463
+ );
1464
+ } catch (error) {
1465
+ console.warn(
1466
+ `${STARTUP_OFFSCREEN_BYTES_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`,
1467
+ );
1468
+ }
1267
1469
  // Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
1268
1470
  const unlit = unlitFoliageWarning(threeScene);
1269
1471
  if (unlit !== undefined)
@@ -1282,6 +1484,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1282
1484
  // rest synchronously -- tens of seconds each on a software adapter, which loses the device.
1283
1485
  this.#matrixWorld?.apply(projection.root);
1284
1486
  report = await warmUpScene(renderer, projection.root, camera, {
1487
+ afterCoveredDraw: repaintCover,
1285
1488
  budgetMs,
1286
1489
  computeNodes: this.#computeDriven.warmupNodes,
1287
1490
  renderPasses: this.#warmUpOptions().renderPasses,
@@ -1335,6 +1538,21 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1335
1538
  const startupCompile: StartupCompile = async (): Promise<void> => {
1336
1539
  await warmUp("TN_STARTUP_WARMUP", STARTUP_COMPILE_BUDGET_MS, true);
1337
1540
  };
1541
+ // A game with no cover skips the compile above, yet readiness still waits for the scene's
1542
+ // environment: the owned engine skips every frame while it bakes, and a skipped frame is fast,
1543
+ // so the frame window would pass before the world drew once. (An explicit warm-up bakes it.)
1544
+ const startupEnvironment = (): StartupCompile | undefined =>
1545
+ sceneNeedsEnvironmentPreparation(renderer, projection.root) ? bakeEnvironment : undefined;
1546
+ const bakeEnvironment: StartupCompile = async (): Promise<void> => {
1547
+ if (this.#aborted) return;
1548
+ await prepareSceneEnvironment(
1549
+ renderer,
1550
+ projection.root,
1551
+ camera,
1552
+ now() + STARTUP_COMPILE_BUDGET_MS,
1553
+ repaintCover,
1554
+ );
1555
+ };
1338
1556
  // The GPU-selected main-pass tally, registered by whichever streamed world is added to the
1339
1557
  // scene. The frame budget reads it once per window; a world with no sample reports undefined, so
1340
1558
  // the window carries nothing rather than a zero no frame selected.
@@ -1452,12 +1670,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1452
1670
  this.#entities = entities;
1453
1671
  this.#scheduler = scheduler;
1454
1672
  this.#afterPhysicsPhase = afterPhysicsPhase;
1455
- const devToolsHost =
1456
- platform === undefined
1457
- ? typeof window === "undefined"
1458
- ? undefined
1459
- : window
1460
- : platform.devToolsHost;
1673
+ const devToolsHost = platform === undefined ? hostWindow() : platform.devToolsHost;
1461
1674
  this.#cleanup.push(
1462
1675
  installDevTools(
1463
1676
  entities,
@@ -1476,24 +1689,25 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1476
1689
  let heldTargetFps = initialTarget.targetFps;
1477
1690
  // Frame-share budgets elsewhere (the world's adaptive LOD) read the target, not the last frame.
1478
1691
  renderer.noteTargetFps?.(initialTarget.targetFps);
1479
- const scaler =
1480
- renderer.surface().scaleSource === "auto" && initialTarget.targetFps > 0
1692
+ const automaticScale = renderer.surface().scaleSource === "auto";
1693
+ const createScaler = () =>
1694
+ automaticScale && heldTargetFps > 0
1481
1695
  ? new ResolutionScaler({
1482
1696
  // Phones keep the device ladder; a desktop stops before its bottom, where a picture
1483
1697
  // with nothing reconstructing it stops being a faster frame and becomes a blur.
1484
1698
  minScale: resolvePlatformResolutionFloor(getPlatform().os),
1485
1699
  // The adapter family picks the first rung; the first eligible window still decides.
1486
1700
  start:
1487
- renderer.gpuClass === undefined
1701
+ renderer.temporalUpscaleStartScale?.() ??
1702
+ (renderer.gpuClass === undefined
1488
1703
  ? undefined
1489
- : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class],
1490
- targetFps: initialTarget.targetFps,
1491
- // No floor lift from motion data: consuming velocity is not upscaling. Three's TRAA
1492
- // accumulates at the canvas's own size, so lifting the floor for it let a forest frame
1493
- // fall to 0.23 (442x248 on a 1920x1080 canvas). Only a stage that reconstructs a
1494
- // display-resolution frame may pass `temporalUpscale`, and none ships today.
1704
+ : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class]),
1705
+ targetFps: heldTargetFps,
1706
+ temporalUpscale: () => renderer.temporalUpscale?.() === true,
1495
1707
  })
1496
1708
  : undefined;
1709
+ let scaler = createScaler();
1710
+ let temporalStartApplied = renderer.temporalUpscale?.() === true;
1497
1711
  // A class that starts below the ceiling must draw there from the first frame; the scaler only
1498
1712
  // reports a scale, and nothing else would apply it until a window steps.
1499
1713
  if (scaler !== undefined && scaler.scale !== 1)
@@ -1563,7 +1777,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1563
1777
  if (projection !== undefined) {
1564
1778
  reportInfo(
1565
1779
  formatProjectionWindow(
1566
- projection.report,
1780
+ projection.windowReport,
1567
1781
  reported.window,
1568
1782
  lastWorldDrawCalls,
1569
1783
  this.#cameraCull?.report,
@@ -1577,19 +1791,22 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1577
1791
  // same frames and a reader can subtract one from the other without a second clock.
1578
1792
  const spanWindow = spans?.window();
1579
1793
  if (spanWindow !== undefined) reportInfo(formatSpansWindow(spanWindow));
1580
- // The scene-shape verdict, on by default, from the census the frame already took.
1581
- // An agent building a scene of the wrong shape reads it in the log before a human
1582
- // ever plays the game and calls it slow.
1794
+ // The scene-shape verdict, on by default in a debug launch, from the census the
1795
+ // frame already took. An agent building a scene of the wrong shape reads it in the
1796
+ // log before a human ever plays the game and calls it slow.
1583
1797
  const staticCensus = staticTransformCensus();
1584
1798
  if (staticCensus.roots > 0)
1585
1799
  reportInfo(`${STATIC_TRANSFORM_MARKER}:${JSON.stringify(staticCensus)}`);
1586
1800
  const validation = renderListValidator?.report();
1587
1801
  if (validation !== undefined) reportInfo(formatValidationReport(validation));
1588
- const warning = sceneWarning(
1589
- reported,
1590
- describeSceneShape(reported, this.#cameraCull?.report),
1591
- target.targetFps,
1592
- );
1802
+ const warning = devMetricsEnabled
1803
+ ? sceneWarning(
1804
+ reported,
1805
+ describeSceneShape(reported, this.#cameraCull?.report),
1806
+ target.targetFps,
1807
+ renderer.gpuClass?.class,
1808
+ )
1809
+ : undefined;
1593
1810
  if (warning !== undefined) reportWarning(formatSceneWarning(warning));
1594
1811
  // The same sentence goes to the UI on a dev launch, so a human watching the window
1595
1812
  // and an agent reading the log are told the same thing at the same time. No frame
@@ -1669,6 +1886,12 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1669
1886
  // work a shipped build must not pay for a diagnostic it did not ask for.
1670
1887
  const frameCounters =
1671
1888
  spans === undefined ? undefined : FrameCounters.install(counterDeviceOf(renderer.raw));
1889
+ // The engine's own ABI crossings ride every budget window, not the spans flag: one difference of
1890
+ // two reads per frame, and the series a fix for repeated crossings is judged on.
1891
+ const bridgeCrossings = createCrossingReader();
1892
+ // Every engine work counter, per frame, when a playtest bounds them (PRD-748 engine-cost row).
1893
+ const engineCounters = createEngineCounterReader();
1894
+ if (debug) engineCounters();
1672
1895
  // The parity oracle for the static freeze. Off by default and expensive on purpose: it
1673
1896
  // recomputes every world matrix the long way and throws on the first that disagrees with what
1674
1897
  // the frame is about to draw.
@@ -1682,10 +1905,22 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1682
1905
  });
1683
1906
  }
1684
1907
  if (frameCounters !== undefined) this.#cleanup.push(() => frameCounters.uninstall());
1908
+ if (debug) {
1909
+ const stopGc = observeDebugGc();
1910
+ if (stopGc !== undefined) this.#cleanup.push(stopGc);
1911
+ }
1685
1912
  // Holds no hook and does no work between requests, so an idle game pays nothing for it.
1686
1913
  const geometryCapture = new GeometryCapture();
1687
1914
  this.#geometryCapture = geometryCapture;
1688
1915
  const budgetNow = (): number => globalThis.performance?.now() ?? Date.now();
1916
+ // The stage meters split the render phase (PRD-771): three clock reads a frame and one difference of the
1917
+ // engine's running totals. Decided once; `?tnStages=0` turns the whole path off, here and in the engine.
1918
+ const stageMeters = frameBudget !== undefined && stageMetersRequested();
1919
+ const readStages = stageMeters ? createStageReader(() => renderer.raw) : undefined;
1920
+ const readWork = stageMeters ? createWorkReader(() => renderer.raw) : undefined;
1921
+ if (!stageMeters)
1922
+ (renderer.raw as { setStageMeters?: (enabled: boolean) => void }).setStageMeters?.(false);
1923
+ let computeStageMs = 0;
1689
1924
  // The dev verdict is decided once per launch, and sent when it changes rather than on a timer:
1690
1925
  // a chip that re-sent an unchanged sentence four times a second would pay a JSON round trip to
1691
1926
  // say nothing new.
@@ -1694,6 +1929,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1694
1929
  let updates = 0;
1695
1930
  let renders = 0;
1696
1931
  let lastGateSkips = 0;
1932
+ let readinessGateSkips = 0;
1697
1933
  const gameLoop: FixedStepLoop = new FixedStepLoop({
1698
1934
  interpolation,
1699
1935
  ...(frameBudget === undefined ? {} : { budget: frameBudget }),
@@ -1709,6 +1945,13 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1709
1945
  },
1710
1946
  onRender: (alpha) => {
1711
1947
  observeCompilation();
1948
+ // Before the first world pass compiles anything: the merged meshes it compiles are the ones
1949
+ // the player will see. A scene that has not entered has nothing built to settle.
1950
+ if (this.#sceneEntered) {
1951
+ if (debug)
1952
+ measureDebug("autoBatch", "renderer", "AutoBatch.update", () => autoBatch.update());
1953
+ else autoBatch.update();
1954
+ }
1712
1955
  renderPassBudget?.beginFrame();
1713
1956
  // Runs on web as well as native, so the two stay one behaviour rather than diverging into
1714
1957
  // a fast path nobody tests. When the world is drawn, reconciliation happens immediately
@@ -1727,13 +1970,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1727
1970
  const mustPresentLoader =
1728
1971
  firstWorldPass && canvasLayer.opaque && loaderHasPixels && !loadingFramePresented;
1729
1972
  if (firstWorldPass && !explicitWarmUpPending) {
1973
+ this.#startupGateStarted = true;
1730
1974
  // `startupCompile` is the fallback that compiles inside the readiness gate. When warm-up
1731
1975
  // is on it has already happened behind the loading screen, so running it again here
1732
1976
  // would pay the same cost twice.
1733
1977
  startupReadiness.start(
1734
- startupCoverActive() && !this.#warmUpConfiguredExplicitly()
1735
- ? startupCompile
1736
- : undefined,
1978
+ this.#warmUpConfiguredExplicitly()
1979
+ ? undefined
1980
+ : startupCoverActive()
1981
+ ? startupCompile
1982
+ : startupEnvironment(),
1737
1983
  );
1738
1984
  }
1739
1985
  // Ordinary render compute waits for startup readiness. Streaming explicitly opts in
@@ -1747,6 +1993,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1747
1993
  (!startupCoverActive() || startupReadiness.compileSettled)
1748
1994
  ) {
1749
1995
  const computeStart = frameBudget === undefined ? 0 : budgetNow();
1996
+ computeStageMs = 0;
1750
1997
  beginSpan(SPANS.compute);
1751
1998
  try {
1752
1999
  // The render camera comes with it, because a render-cadence consumer that culls by the
@@ -1761,13 +2008,20 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1761
2008
  } finally {
1762
2009
  endSpan(SPANS.compute);
1763
2010
  }
1764
- frameBudget?.addRender(budgetNow() - computeStart);
2011
+ computeStageMs = frameBudget === undefined ? 0 : budgetNow() - computeStart;
2012
+ frameBudget?.addRender(computeStageMs);
1765
2013
  }
1766
2014
  const waitingForFirstUse =
1767
2015
  firstWorldPass &&
1768
2016
  (explicitWarmUpPending || (startupCoverActive() && !startupReadiness.compileSettled));
1769
2017
  let worldPasses: ReturnType<RenderPassBudget["passes"]> | undefined;
2018
+ // Before the scene has entered, the world pass runs only under an opaque cover. With nothing
2019
+ // over it, the draw presents the clear colour: Hop Garden showed three black frames during
2020
+ // `load()` for 0.5 s when the page mounted the canvas. Under the cover it is what compiles the
2021
+ // world's pipelines inside the load: skipped, Hop's 10 s first-use compile landed after a
2022
+ // playtest's setup had released enter(), and setup.place runs failed.
1770
2023
  if (
2024
+ (this.#sceneEntered || canvasLayer.opaque) &&
1771
2025
  !mustPresentLoader &&
1772
2026
  !waitingForFirstUse &&
1773
2027
  (!canvasLayer.opaque ||
@@ -1784,6 +2038,17 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1784
2038
  // Before anything walks: a frozen subtree whose author moved its root thaws here, so the
1785
2039
  // walk that follows sees a transform nobody had to remember to announce.
1786
2040
  refreshStaticTransforms();
2041
+ // Camera-rate metadata is an input to scene-owned beforeRender work and the projection
2042
+ // palette write, not a post-draw observation. Publish it before either can skip a rig;
2043
+ // this pass observes animation only and does not decide draw visibility.
2044
+ const drawingBufferHeight = renderer.surface().drawingBufferHeight;
2045
+ const cullPrepareStart = spans === undefined ? 0 : spanNow();
2046
+ this.#cameraCull?.prepareAnimation(
2047
+ this.#projection?.root ?? threeScene,
2048
+ camera,
2049
+ drawingBufferHeight,
2050
+ );
2051
+ if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullPrepareStart);
1787
2052
  // Scene prep that must read the frame's last solved state before the projection packs and
1788
2053
  // the renderer draws. Inside the world-render block it cannot land on a held loader frame.
1789
2054
  if (this.#beforeRenderCallbacks.size > 0) {
@@ -1797,7 +2062,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1797
2062
  for (const callback of this.#beforeRenderCallbacks) snapshot.push(callback);
1798
2063
  beginSpan(SPANS.beforeRender);
1799
2064
  try {
1800
- for (const callback of snapshot) callback();
2065
+ for (const callback of snapshot) {
2066
+ if (debug)
2067
+ measureDebug(
2068
+ `beforeRender.${callback.name || "anonymous"}`,
2069
+ "update",
2070
+ callback.name || "ctx.beforeRender",
2071
+ callback,
2072
+ );
2073
+ else callback();
2074
+ }
1801
2075
  } finally {
1802
2076
  endSpan(SPANS.beforeRender);
1803
2077
  this.#beforeRenderDepth -= 1;
@@ -1847,12 +2121,17 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1847
2121
  } finally {
1848
2122
  endSpan(SPANS.lod);
1849
2123
  }
2124
+ const renderRoot = this.#projection?.root ?? threeScene;
2125
+ // The cull reads the matrices the renderer will draw. Projection exact proxies carry the
2126
+ // authored world matrix in their local matrix, so their own world walk must precede both
2127
+ // the cull and the render rather than following the cull.
2128
+ renderRoot.matrixWorldAutoUpdate = false;
2129
+ this.#matrixWorld?.apply(renderRoot);
1850
2130
  // Projected-size cull, per render camera, default on. It writes only `object.visible` —
1851
2131
  // the one per-frame flag the projection's batch key ignores — and restores what it hid
1852
2132
  // immediately after the draw, so the authored scene is untouched between frames. The
1853
2133
  // renderer walks the same root the projection is about to draw, so a declined projection
1854
2134
  // and an active one both get the gate.
1855
- const drawingBufferHeight = renderer.surface().drawingBufferHeight;
1856
2135
  const cullApplyStart = spans === undefined ? 0 : spanNow();
1857
2136
  this.#cameraCull?.apply(
1858
2137
  this.#projection?.root ?? threeScene,
@@ -1884,13 +2163,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1884
2163
  : { backend: rendererBackendIdentity(renderer.raw) as string }),
1885
2164
  });
1886
2165
  }
1887
- const renderRoot = this.#projection?.root ?? threeScene;
1888
- // three's renderer walks whatever scene it is handed, so it is told not to: the pass above
1889
- // is the walk. Handing it the mirror sets the mirror scene's flag; the authored scene was
1890
- // marked at construction.
1891
- renderRoot.matrixWorldAutoUpdate = false;
1892
- this.#matrixWorld?.apply(renderRoot);
2166
+ // Scene.enter installs the chain after the scaler is created; choose its tier before its first draw.
2167
+ if (!temporalStartApplied && scaler !== undefined && renderer.temporalUpscale?.()) {
2168
+ scaler = createScaler();
2169
+ temporalStartApplied = true;
2170
+ if (scaler !== undefined)
2171
+ renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
2172
+ }
2173
+ const engineStart = readStages === undefined ? 0 : budgetNow();
1893
2174
  renderer.render(renderRoot, camera);
2175
+ const engineEnd = readStages === undefined ? 0 : budgetNow();
1894
2176
  renders += 1;
1895
2177
  // Count declined frames without treating them as drawn-frame render cost.
1896
2178
  const gateSkips = rendererFrameGateSkips(renderer.raw);
@@ -1911,7 +2193,17 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1911
2193
  if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullRestoreStart);
1912
2194
  this.#projection?.commit();
1913
2195
  renderer.observeRenderChainFrame?.();
1914
- frameBudget?.addRender(budgetNow() - renderStart);
2196
+ if (frameBudget !== undefined) {
2197
+ const renderEnd = budgetNow();
2198
+ frameBudget.addRender(renderEnd - renderStart);
2199
+ const stages = readStages?.(
2200
+ computeStageMs + (engineStart - renderStart),
2201
+ engineEnd - engineStart,
2202
+ renderEnd - engineEnd,
2203
+ );
2204
+ if (stages !== undefined) frameBudget.addStages(stages);
2205
+ }
2206
+ computeStageMs = 0;
1915
2207
  // Read the split before the overlay renders: the overlay is its own draw, not part of the
1916
2208
  // world pass, and the budget window already accounts for it in its own phase.
1917
2209
  worldPasses = renderPassBudget?.passes();
@@ -2004,7 +2296,8 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2004
2296
  }
2005
2297
  if (mustPresentLoader) loadingFramePresented = true;
2006
2298
  // Include state written by beforeRender and Scene.render in this frame's UI snapshot.
2007
- if (this.#config.stateFlushMs === undefined) this.#state.flush();
2299
+ if (this.#config.stateFlushMs === undefined && stateHandOffFrames === 0)
2300
+ this.#state.flush();
2008
2301
  // Every frame, including one whose canvas layer is empty: the native UI is composited into
2009
2302
  // the game's own frame whether or not the game draws a HUD of its own, so a frame that
2010
2303
  // skipped this would report work it did pay as `residual`. The host reports what the
@@ -2015,8 +2308,31 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2015
2308
  // The boundary counts ride the span flag, but the simulation tick does not need them: it is
2016
2309
  // fed every frame so a plain `TN_FRAME_BUDGET` log can join a window's start and end ticks
2017
2310
  // without `TN_FRAME_SPANS`. `addCounters` keeps the last tick a caller did provide.
2311
+ const crossings = bridgeCrossings();
2312
+ if (debug) {
2313
+ const matrix = this.#matrixWorld?.report;
2314
+ if (matrix !== undefined)
2315
+ countDebug("matrixWorldVisits", matrix.visited, "scene", "MatrixWorldPass");
2316
+ const cull = this.#cameraCull?.report;
2317
+ if (cull !== undefined) {
2318
+ countDebug("cullConsidered", cull.considered, "renderer", "RenderCameraCull");
2319
+ countDebug("cullRejected", cull.culled, "renderer", "RenderCameraCull");
2320
+ }
2321
+ const batch = autoBatch.census;
2322
+ countDebug("autoBatchSources", batch.meshes, "renderer", "AutoBatch.census");
2323
+ countDebug("autoBatchDraws", batch.draws, "renderer", "AutoBatch.census");
2324
+ countDebug("autoBatchRefused", batch.refused, "renderer", "AutoBatch.census");
2325
+ countDebug("autoBatchUnsettled", batch.unsettled, "renderer", "AutoBatch.census");
2326
+ }
2327
+ const boundary = frameCounters?.read();
2328
+ const engine = engineCounters();
2329
+ // The owned engine's work counts; a JS back end with its own queue counters (`boundary`) outranks them.
2330
+ const work = readWork?.(crossings);
2018
2331
  frameBudget?.addCounters({
2019
- ...(frameCounters?.read() ?? {}),
2332
+ ...(work ?? {}),
2333
+ ...(boundary ?? {}),
2334
+ ...(crossings === undefined ? {} : { bridgeCrossings: crossings }),
2335
+ ...(engine === undefined ? {} : { engine }),
2020
2336
  simulationTick: gameLoop.tick(),
2021
2337
  });
2022
2338
  const uiHost = globalThis as { __tnUiCompositeMs?: () => number };
@@ -2046,34 +2362,127 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2046
2362
  },
2047
2363
  onAfterPhysics: (dt) => {
2048
2364
  if (this.#paused) return;
2049
- afterPhysicsPhase.run(dt);
2365
+ if (debug)
2366
+ measureDebug("afterPhysics", "update", "afterPhysicsPhase.run", () =>
2367
+ afterPhysicsPhase.run(dt),
2368
+ );
2369
+ else afterPhysicsPhase.run(dt);
2050
2370
  },
2051
2371
  onUpdate: (dt) => {
2052
2372
  if (this.#paused) return;
2053
- this.#input?.tick();
2054
- scheduler.tick(dt);
2055
- pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
2056
- for (const plugin of this.#activePlugins) plugin.beforeUpdate?.(ctx, dt);
2373
+ if (debug) {
2374
+ measureDebug("input", "update", "Input.tick", () => this.#input?.tick());
2375
+ measureDebug("scheduler", "update", "Scheduler.tick", () => scheduler.tick(dt));
2376
+ measureDebug("picking", "update", "PointerEvents3D.tick", () =>
2377
+ pointerEvents.tick(
2378
+ input.raw.pointers,
2379
+ picker,
2380
+ input.raw.pointer,
2381
+ input.raw.pointerEdges,
2382
+ ),
2383
+ );
2384
+ } else {
2385
+ this.#input?.tick();
2386
+ scheduler.tick(dt);
2387
+ pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
2388
+ }
2389
+ for (const plugin of this.#activePlugins) {
2390
+ if (debug && plugin.beforeUpdate !== undefined)
2391
+ measureDebug(
2392
+ `beforeUpdate.${this.#activePlugins.indexOf(plugin)}.${plugin.beforeUpdate.name || "anonymous"}`,
2393
+ "update",
2394
+ `plugins[${this.#activePlugins.indexOf(plugin)}].${plugin.beforeUpdate.name || "beforeUpdate"}`,
2395
+ () => plugin.beforeUpdate?.(ctx, dt),
2396
+ );
2397
+ else plugin.beforeUpdate?.(ctx, dt);
2398
+ }
2057
2399
  const scene = this.#scene;
2058
2400
  const frame = this.#sceneFrame;
2059
- if (frame !== undefined) {
2060
- frame(ctx, dt);
2401
+ if (this.#sceneEntered && frame !== undefined) {
2402
+ if (debug)
2403
+ measureDebug(
2404
+ "sceneCallbacks",
2405
+ "update",
2406
+ `${scene?.constructor.name}.${frame.name || "frame"}`,
2407
+ () => frame(ctx, dt),
2408
+ );
2409
+ else frame(ctx, dt);
2061
2410
  updates += 1;
2062
2411
  }
2063
2412
  // An async goto() installs the incoming scene before its load resolves; until enter()
2064
2413
  // has run there is no gameplay to step and a game-overridden update() would run against
2065
2414
  // a cleared graph.
2066
2415
  else if (this.#sceneEntered && scene !== undefined) {
2067
- scene.update(ctx, dt);
2416
+ if (debug)
2417
+ measureDebug("sceneCallbacks", "update", `${scene.constructor.name}.update`, () =>
2418
+ scene.update(ctx, dt),
2419
+ );
2420
+ else scene.update(ctx, dt);
2068
2421
  updates += 1;
2069
2422
  }
2070
2423
  if (this.#scene !== scene || this.#sceneFrame !== frame) return;
2071
- for (const plugin of this.#activePlugins) plugin.update?.(ctx, dt);
2072
- this.#entities?.sweep();
2073
- if (this.#renderer !== undefined && this.#sceneEntered)
2074
- this.#computeDriven.process(this.#renderer);
2424
+ for (const plugin of this.#activePlugins) {
2425
+ if (debug && plugin.update !== undefined)
2426
+ measureDebug(
2427
+ `plugins.${this.#activePlugins.indexOf(plugin)}.${plugin.update.name || "anonymous"}`,
2428
+ "update",
2429
+ `plugins[${this.#activePlugins.indexOf(plugin)}].${plugin.update.name || "update"}`,
2430
+ () => plugin.update?.(ctx, dt),
2431
+ );
2432
+ else plugin.update?.(ctx, dt);
2433
+ }
2434
+ if (debug)
2435
+ measureDebug("entities", "update", "Registry.sweep", () => this.#entities?.sweep());
2436
+ else this.#entities?.sweep();
2437
+ if (this.#renderer !== undefined && this.#sceneEntered) {
2438
+ if (debug)
2439
+ measureDebug(
2440
+ "computeDriven",
2441
+ "update",
2442
+ "ComputeDriven.process",
2443
+ () => this.#renderer && this.#computeDriven.process(this.#renderer),
2444
+ );
2445
+ else this.#computeDriven.process(this.#renderer);
2446
+ }
2447
+ },
2448
+ // A frame the renderer declined to draw (the Wasm engine's gate: two frames still on the GPU)
2449
+ // is no frame at all for the readiness window. Counted, five cheap declined frames closed the
2450
+ // window while the first world frame was still compiling on the GPU, so the cover lifted and
2451
+ // the player saw a 0.9 s stall and then a first frame with unmetered exposure (Hop Garden, 4
2452
+ // of 13 launches). Not a reset either: a GPU-bound world under the cover declines every other
2453
+ // frame, and a reset held every Hop launch to the 10 s window bound.
2454
+ onFrame: (frameMs) => {
2455
+ const skips = rendererFrameGateSkips(renderer.raw);
2456
+ const declined = skips !== undefined && skips > readinessGateSkips;
2457
+ if (skips !== undefined) readinessGateSkips = skips;
2458
+ if (!declined) startupReadiness.observe(frameMs);
2459
+ // Bounded like every other startup wait: a renderer that retires no frame (hosted CI's
2460
+ // SwiftShader declined 73 of 73 after readiness) would otherwise keep the HUD covered for
2461
+ // the whole session. Past the window the cover lifts anyway, and says why.
2462
+ const handOffWaitedMs = now() - (timeline.readyMs ?? now());
2463
+ const handOffBounded = handOffWaitedMs >= STARTUP_STABLE_WINDOW_MS;
2464
+ // A draw the gate accepted is only queued: the cover lifts once the GPU has finished the first world frame.
2465
+ const worldOnDisplay = rendererWorldPresented(renderer.raw) !== false;
2466
+ if (stateHandOffFrames > 0 && ((!declined && worldOnDisplay) || handOffBounded)) {
2467
+ if (handOffBounded) {
2468
+ console.warn(
2469
+ `TN_STARTUP_HANDOFF_BOUNDED:${JSON.stringify({
2470
+ retiredFrames: STARTUP_HANDOFF_FRAMES - stateHandOffFrames,
2471
+ requiredFrames: STARTUP_HANDOFF_FRAMES,
2472
+ waitedMs: Math.round(handOffWaitedMs),
2473
+ reason:
2474
+ "the GPU retired fewer frames than the hand-off needs; the cover lifted at the bound",
2475
+ })}`,
2476
+ );
2477
+ stateHandOffFrames = 0;
2478
+ } else stateHandOffFrames -= 1;
2479
+ // The frame the held state publishes again is the frame the cover is gone.
2480
+ if (stateHandOffFrames === 0) {
2481
+ this.#uiRevealed = true;
2482
+ if (this.#uiBridge?.hasPeer()) this.#postUiStartup();
2483
+ }
2484
+ }
2075
2485
  },
2076
- onFrame: (frameMs) => startupReadiness.observe(frameMs),
2077
2486
  step: this.#config.step,
2078
2487
  });
2079
2488
  loopState.current = gameLoop;
@@ -2083,7 +2492,14 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2083
2492
  readonly rejectEntered: (error: unknown) => void;
2084
2493
  readonly resolveEntered: () => void;
2085
2494
  }> = [];
2495
+ let settleLoaded: (error?: unknown) => void = () => undefined;
2496
+ const startLoaded = new Promise<void>((resolve, reject) => {
2497
+ settleLoaded = (error) => (error === undefined ? resolve() : reject(error));
2498
+ });
2499
+ // A run with no setup never awaits it; a failed load is reported by start() itself.
2500
+ void startLoaded.catch(() => undefined);
2086
2501
  const runtime: IGamePluginRuntime = {
2502
+ startSceneLoaded: () => startLoaded,
2087
2503
  fixedStep: (ticks, options) =>
2088
2504
  gameLoop.advance(ticks, { ...options, until: () => this.#pendingSceneEnter !== undefined }),
2089
2505
  sceneTransition: () =>
@@ -2117,7 +2533,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2117
2533
  rapier: null,
2118
2534
  seed: this.#config.seed ?? null,
2119
2535
  startupCompileSettled: () => startupReadiness.compileSettled,
2536
+ startupRevealed: () => this.#uiRevealed,
2120
2537
  startupTimeline: () => ({ ...timeline }),
2538
+ startupOffscreenBytes: () => offscreenBytes,
2121
2539
  step: gameLoop.step,
2122
2540
  runtimeDiagnosticsSeries: () => gameLoop.runtimeDiagnosticsSeries(),
2123
2541
  };
@@ -2162,7 +2580,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2162
2580
  const loaded = scene.load(ctx);
2163
2581
  startHeldLoop();
2164
2582
  if (loaded !== undefined) await loaded;
2583
+ settleLoaded();
2165
2584
  } catch (error) {
2585
+ settleLoaded(error);
2166
2586
  this.#teardown(ctx);
2167
2587
  throw error;
2168
2588
  }
@@ -2188,21 +2608,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2188
2608
  }
2189
2609
  }
2190
2610
  try {
2191
- this.#enterScene(scene, ctx);
2192
- timeline.enteredMs ??= now();
2193
- // A start scene that navigates inside `enter()` — every `boot` template does — has handed the
2194
- // run a world that is still in `load()`, and the entity registry is empty until it enters.
2195
- // Releasing the gate there described a game that had not been built yet, so every
2196
- // entity-derived capability was read off nothing. The gate follows the scene that entered.
2197
- const worldEntered = this.#pendingSceneEnter;
2198
- const entered = (): void => {
2611
+ // A boot scene can navigate during enter(). Describe the destination's registered entities
2612
+ // after it enters, while readiness and the full goto() still wait for first-use warm-up.
2613
+ this.#onStartSceneEntered = () => {
2199
2614
  for (const startGate of startGates) startGate.resolveEntered();
2200
2615
  };
2201
- if (worldEntered === undefined) entered();
2202
- else
2203
- void worldEntered.then(entered, (error: unknown) => {
2204
- for (const startGate of startGates) startGate.rejectEntered(error);
2205
- });
2616
+ this.#enterScene(scene, ctx);
2617
+ timeline.enteredMs ??= now();
2618
+ void this.#pendingSceneEnter?.catch((error: unknown) => {
2619
+ for (const startGate of startGates) startGate.rejectEntered(error);
2620
+ });
2206
2621
  } catch (error) {
2207
2622
  for (const startGate of startGates) startGate.rejectEntered(error);
2208
2623
  this.#teardown(ctx);
@@ -2232,6 +2647,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2232
2647
  this.#matrixWorld?.apply(projection.root);
2233
2648
  const warmUpOptions: IWarmUpOptions = this.#warmUpOptions();
2234
2649
  report = await warmUpScene(this.#renderer, projection.root, camera, {
2650
+ afterCoveredDraw: repaintCover,
2235
2651
  ...warmUpOptions,
2236
2652
  computeNodes: [...(warmUpOptions.computeNodes ?? []), ...this.#computeDriven.warmupNodes],
2237
2653
  });
@@ -2302,6 +2718,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2302
2718
  this.#aborted = true;
2303
2719
  this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_STOPPED: the game stopped mid-capture.");
2304
2720
  this.#teardown();
2721
+ uninstallQuietMarkers();
2305
2722
  }
2306
2723
 
2307
2724
  #disposePlugin(plugin: IGamePluginHooks<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): void {
@@ -2311,6 +2728,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2311
2728
  }
2312
2729
 
2313
2730
  #teardown(startingCtx?: ICtx<TState, TPhysics>): void {
2731
+ this.#onStartSceneEntered = undefined;
2314
2732
  const ctx = this.#ctx ?? startingCtx;
2315
2733
  // Teardown is failure-atomic: one throwing release must not strand the resources after it.
2316
2734
  // Every attempt runs, errors are collected, and the first — the original cause — is thrown
@@ -2351,6 +2769,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2351
2769
  failures.push(error);
2352
2770
  }
2353
2771
  }
2772
+ this.#autoBatch?.reset();
2354
2773
  if (ctx !== undefined) clearScene(ctx.scene, this.#computeDriven);
2355
2774
  this.#cameraCull?.dispose();
2356
2775
  this.#cameraCull = undefined;
@@ -2363,8 +2782,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2363
2782
  const renderer = this.#renderer;
2364
2783
  renderer?.dispose();
2365
2784
  if (renderer !== undefined) {
2366
- if (this.#config.platform === undefined) renderer.domElement.remove?.();
2367
- else this.#config.platform.unmountCanvas(renderer.domElement);
2785
+ const platform = this.#platform;
2786
+ if (platform === undefined) renderer.domElement.remove?.();
2787
+ else platform.unmountCanvas(renderer.domElement);
2368
2788
  }
2369
2789
  this.#renderer = undefined;
2370
2790
  this.#viewport = undefined;