@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,1076 @@
1
+ import { type Object3D, Scene as ThreeScene, Vector2 } from "three";
2
+ import { createAssetLoader } from "./assets.js";
3
+ import { AutoBatch } from "./auto-batch.js";
4
+ import { CanvasLayer } from "./canvas-layer.js";
5
+ import { isComputeDriven } from "./compute-driven.js";
6
+ import { Registry } from "./entities.js";
7
+ import {
8
+ type IBootPhase,
9
+ type ILoopPhase,
10
+ clearScene,
11
+ runAll,
12
+ throwFirst,
13
+ } from "./game-boot-phase.js";
14
+ import { type DevToolsHost, installDevTools } from "./game-dev-tools.js";
15
+ import type { IGameFrameLoop } from "./game-frame-loop.js";
16
+ import { createCamera } from "./game-validate.js";
17
+ import type {
18
+ IGameObservationContribution,
19
+ IGamePluginHooks,
20
+ IGamePluginRuntime,
21
+ IGameRuntimeObservations,
22
+ PluginCleanup,
23
+ } from "./game.js";
24
+ import { InputMap } from "./input.js";
25
+ import { PhysicsInterpolation } from "./interpolation.js";
26
+ import {
27
+ reportLaunchFailure,
28
+ reportSceneLoadFailure,
29
+ watchDeviceLoss,
30
+ watchStartupStall,
31
+ } from "./launch-diagnostics.js";
32
+ import { type FixedStepLoop, createAfterPhysicsPhase } from "./loop.js";
33
+ import { MatrixWorldPass } from "./matrix-world.js";
34
+ import { ScenePicker } from "./picking.js";
35
+ import { getPlatform, hostDocument, hostWindow } from "./platform.js";
36
+ import { PointerEvents3D } from "./pointer-events.js";
37
+ import { debugRequested } from "./profiling/debug-telemetry.js";
38
+ import {
39
+ UNLIT_FOLIAGE_FIX,
40
+ formatUnlitFoliageWarning,
41
+ unlitFoliageWarning,
42
+ } from "./profiling/unlit-foliage-warning.js";
43
+ import { createRandom } from "./random.js";
44
+ import { RenderCameraCull } from "./render-camera-cull.js";
45
+ import type { VirtualShadowNode } from "./render/virtual-shadow.js";
46
+ import { SceneRenderProjection } from "./renderProjection.js";
47
+ import {
48
+ resolveMatrixWorldMode,
49
+ resolveRendererAlphaAntialiasing,
50
+ resolveRendererAntialias,
51
+ resolveRendererScaleSetting,
52
+ } from "./renderer-config.js";
53
+ import { rendererFacts } from "./renderer-facts.js";
54
+ import { createRenderer } from "./renderer.js";
55
+ import type { ICtx, IStartupStatus, IStartupTimeline } from "./scene.js";
56
+ import { Scheduler } from "./schedule.js";
57
+ import {
58
+ type IStartupOffscreenBytes,
59
+ STARTUP_OFFSCREEN_BYTES_MARKER,
60
+ measureStartupOffscreenBytes,
61
+ reportUnusedModelsLater,
62
+ } from "./startup-offscreen-bytes.js";
63
+ import {
64
+ type IStartupImageState,
65
+ STARTUP_COMPILE_BUDGET_MS,
66
+ STARTUP_STALL_MS,
67
+ type StartupCompile,
68
+ StartupReadiness,
69
+ } from "./startup-readiness.js";
70
+ import { Viewport } from "./viewport.js";
71
+ import {
72
+ type IWarmUpOptions,
73
+ type IWarmUpReport,
74
+ prepareSceneEnvironment,
75
+ sceneNeedsEnvironmentPreparation,
76
+ warmUpScene,
77
+ warmUpSceneWithCompletion,
78
+ } from "./warmup.js";
79
+
80
+ /** The global a native host reads to know the world is on screen; one spelling on both sides. */
81
+ const STARTUP_READY_GLOBAL = "__TN_STARTUP_READY__";
82
+
83
+ /**
84
+ * Drawn frames the state publish waits after startup readiness. Three, because a renderer keeps at
85
+ * most two frames on the GPU (the Wasm engine's gate declines a third), so the third drawn frame
86
+ * proves the first uncovered one has left it and the page can paint a state change over it.
87
+ */
88
+ export const STARTUP_HANDOFF_FRAMES = 3;
89
+
90
+ /** The GPU-selected main-pass count a streamed world publishes, read once per budget window. */
91
+ type GpuTally = () => { readonly instances: number; readonly triangles: number } | undefined;
92
+
93
+ export type IGameStartup<TState extends Record<string, unknown>, TPhysics> = NonNullable<
94
+ Awaited<ReturnType<typeof startGameWorld<TState, TPhysics>>>
95
+ >;
96
+
97
+ function createRuntimeObservations(): IGameRuntimeObservations {
98
+ const contributions = new Set<IGameObservationContribution>();
99
+ return {
100
+ contribute: (contribution) => {
101
+ contributions.add(contribution);
102
+ return () => contributions.delete(contribution);
103
+ },
104
+ contributions: () => [...contributions],
105
+ };
106
+ }
107
+
108
+ /** The first phase of `#boot`: everything up to the entered start scene. */
109
+
110
+ export async function startGameWorld<TState extends Record<string, unknown>, TPhysics>(
111
+ game: IBootPhase<TState, TPhysics>,
112
+ ) {
113
+ const progress = {
114
+ explicitWarmUpSettled: !game.warmUpConfiguredExplicitly(),
115
+ gpuTallyProvider: undefined as GpuTally | undefined,
116
+ offscreenBytes: undefined as IStartupOffscreenBytes | undefined,
117
+ projectionSettled: false,
118
+ renders: 0,
119
+ stateHandOffFrames: 0,
120
+ updates: 0,
121
+ warmUpStatus: undefined as IStartupStatus["warmup"] | undefined,
122
+ worldRendered: false,
123
+ };
124
+ const debug = debugRequested();
125
+ const bootSceneName = game.resumeScene ?? game.config.start;
126
+ game.resumeScene = undefined;
127
+ const SceneType = game.config.scenes[bootSceneName];
128
+ if (SceneType === undefined) throw new Error(`Unknown start scene '${bootSceneName}'.`);
129
+ game.connectUi();
130
+
131
+ const renderer = await createRenderer({
132
+ ...game.config.renderer,
133
+ canvas: game.config.canvas ?? game.config.renderer?.canvas,
134
+ preferWebGPU: game.config.renderer?.preferWebGPU,
135
+ // One rule on both runtimes, decided 2026-09-01 after a HiDPI desktop browser upscaled a
136
+ // DPR-1 web buffer into visible pixelation: the device's real density, with an explicit
137
+ // `renderer.pixelRatio` winning over it (the old branch silently clobbered that value).
138
+ // Headless capture lanes run at DPR 1 and are unaffected; the resolution scaler composes
139
+ // on top, so a density the GPU cannot afford is trimmed by rungs, not by the developer.
140
+ pixelRatio: game.config.renderer?.pixelRatio ?? globalThis.devicePixelRatio ?? 1,
141
+ antialias: resolveRendererAntialias(game.config.renderer, undefined, getPlatform().os),
142
+ alphaAntialiasing: resolveRendererAlphaAntialiasing(
143
+ game.config.renderer,
144
+ undefined,
145
+ getPlatform().os,
146
+ ),
147
+ ...resolveRendererScaleSetting(game.config.renderer, undefined, getPlatform().os),
148
+ source: game.config.renderer?.source ?? game.platform?.renderer,
149
+ });
150
+ if (game.aborted) {
151
+ renderer.dispose();
152
+ return;
153
+ }
154
+ game.renderer = renderer;
155
+ // Pushed first, so it runs last: nothing acquired after the renderer outlives it, and the
156
+ // presentation hold below lifts just before the renderer goes.
157
+ game.cleanup.push(() => {
158
+ renderer.dispose();
159
+ const mounted = game.platform;
160
+ if (mounted === undefined) renderer.domElement.remove?.();
161
+ else mounted.unmountCanvas(renderer.domElement);
162
+ game.renderer = undefined;
163
+ });
164
+ // Before anything draws for this startup, including the warm-up and every covered world frame: the owned
165
+ // engine keeps drawing, but presents nothing until a frame's shadow and exposure inputs are ready, so the
166
+ // player never sees the two unsettled pictures a cold post chain produced (measured 185 -> 124 -> 108 mean
167
+ // brightness). A renderer without the seam presents every frame exactly as before.
168
+ renderer.setPresentationHeld?.(true);
169
+ game.cleanup.push(() => renderer.setPresentationHeld?.(false));
170
+ const canvas = renderer.domElement;
171
+ const platform = game.platform;
172
+ const page = hostDocument();
173
+ if (platform !== undefined) platform.mountCanvas(canvas, game.config.container);
174
+ else if (game.config.container !== undefined && canvas.parentElement !== game.config.container)
175
+ game.config.container.append(canvas);
176
+ else if (canvas.parentElement === null && page !== undefined) page.body.append(canvas);
177
+
178
+ const inputTarget =
179
+ game.config.inputTarget ??
180
+ (platform === undefined ? (hostWindow() ?? canvas) : (platform.inputTarget ?? canvas));
181
+ // The store starts before the input and so stops after it: `stop()` releases the input, then the store.
182
+ game.state.start();
183
+ game.cleanup.push(() => game.state.stop());
184
+ const input = new InputMap(
185
+ game.config.input,
186
+ inputTarget,
187
+ canvas,
188
+ platform?.input,
189
+ game.config.contextMenu,
190
+ { gamepadDeadZone: game.config.gamepadDeadZone },
191
+ );
192
+ game.input = input;
193
+ game.cleanup.push(() => {
194
+ input.dispose();
195
+ game.input = undefined;
196
+ });
197
+ const threeScene = new ThreeScene();
198
+ // Pushed before the objects built on this scene, so it runs after they are released.
199
+ game.cleanup.push(() => clearScene(threeScene, game.computeDriven));
200
+ if (debug && "__debugTelemetry" in threeScene)
201
+ (threeScene as ThreeScene & { __debugTelemetry: boolean }).__debugTelemetry = true;
202
+ const camera = createCamera(game.config.camera);
203
+ const interpolation = new PhysicsInterpolation(game.config.physicsInterpolation);
204
+ game.interpolation = interpolation;
205
+ game.cleanup.push(() => {
206
+ interpolation.clear();
207
+ game.interpolation = undefined;
208
+ });
209
+ interpolation.track(camera);
210
+ const viewport = new Viewport({ camera, renderer: game.renderer, source: platform?.viewport });
211
+ game.viewport = viewport;
212
+ game.cleanup.push(() => {
213
+ viewport.dispose();
214
+ game.viewport = undefined;
215
+ });
216
+ const canvasLayer = new CanvasLayer(viewport);
217
+ game.cleanup.push(() => canvasLayer.dispose());
218
+ // The renderer goes to the asset loader so compiled KTX2 textures detect transcoding
219
+ // support against the real backend; a target that supports none fails right here.
220
+ const assets = createAssetLoader({ ...game.config.assets, renderer: renderer.raw });
221
+ if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
222
+ game.cleanup.push(() => assets.dispose());
223
+ const entities = new Registry();
224
+ const random = createRandom(game.config.seed);
225
+ const scheduler = new Scheduler();
226
+ const afterPhysicsPhase = createAfterPhysicsPhase();
227
+ const picker = new ScenePicker({
228
+ camera,
229
+ // Input reports window-relative client coordinates; the picker's NDC math is
230
+ // canvas-relative. Subtract the canvas page offset like replay.ts does for recorded
231
+ // pointers, or every pick lands displaced by wherever the canvas sits in the layout.
232
+ pointer: () => {
233
+ const position = input.raw.pointer.position;
234
+ const rect = (canvas as { getBoundingClientRect?: () => DOMRect }).getBoundingClientRect?.();
235
+ return rect === undefined
236
+ ? position
237
+ : new Vector2(position.x - rect.left, position.y - rect.top);
238
+ },
239
+ scene: threeScene,
240
+ viewport,
241
+ });
242
+ game.picker = picker;
243
+ game.cleanup.push(() => {
244
+ picker.dispose();
245
+ game.picker = undefined;
246
+ });
247
+ const pointerEvents = new PointerEvents3D({
248
+ screen: (position, target) => {
249
+ const rect = (canvas as { getBoundingClientRect?: () => DOMRect }).getBoundingClientRect?.();
250
+ return rect === undefined
251
+ ? target.copy(position)
252
+ : target.set(position.x - rect.left, position.y - rect.top);
253
+ },
254
+ });
255
+ game.pointerEvents = pointerEvents;
256
+ game.cleanup.push(() => {
257
+ pointerEvents.dispose();
258
+ game.pointerEvents = undefined;
259
+ });
260
+ const loopState: { current?: FixedStepLoop } = {};
261
+ // The engine owns the world-matrix walk, not three's renderer: on by default it does not recurse
262
+ // into a hidden subtree, and `renderer.matrixWorld: "all"` restores the every-node walk. The
263
+ // authored scene is marked once, here, so three never walks it a second time; the mirror scene
264
+ // is marked at the render site, where whichever root is drawn this frame is known.
265
+ const matrixWorldPass = new MatrixWorldPass({
266
+ mode: resolveMatrixWorldMode(game.config.renderer),
267
+ });
268
+ game.matrixWorld = matrixWorldPass;
269
+ game.cleanup.push(() => {
270
+ matrixWorldPass.dispose();
271
+ game.matrixWorld = undefined;
272
+ });
273
+ threeScene.matrixWorldAutoUpdate = false;
274
+ // Built before the context because `ctx.startup` reads it: a game asks what the framework's
275
+ // startup is doing, and the answer is this pass.
276
+ // The owned renderer retains its own velocity history; JS snapshots serve Three's accessors.
277
+ const { ownedEngine } = rendererFacts(renderer);
278
+ const projection = new SceneRenderProjection(threeScene, {
279
+ // The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
280
+ // names the material check beside accepting it, and the projection owns both readings.
281
+ projection: game.config.renderer?.projection,
282
+ velocity: () => !ownedEngine && (renderer.renderChainUsesPerObjectVelocity?.() ?? false),
283
+ matrixWorld: matrixWorldPass,
284
+ });
285
+ game.projection = projection;
286
+ const autoBatchConfig = game.config.autoBatch;
287
+ const autoBatch = new AutoBatch(threeScene, {
288
+ enabled: autoBatchConfig !== false,
289
+ entities,
290
+ ...(typeof autoBatchConfig === "object" ? autoBatchConfig : {}),
291
+ report: (line) =>
292
+ (game.config.frameBudget === false ? undefined : game.config.frameBudget?.report)?.(line) ??
293
+ console.info(line),
294
+ });
295
+ game.autoBatch = autoBatch;
296
+ // Runs before the scene is cleared (pushed after it), so the batches give their sources back first.
297
+ game.cleanup.push(() => autoBatch.reset());
298
+ // Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
299
+ // and measured whether or not the game narrows or declines it. Its decision is per camera, so
300
+ // a shadow caster and anything attached to the camera are never dropped on the main view alone.
301
+ const cameraCull = new RenderCameraCull({
302
+ minimumPixels: game.config.renderer?.minimumProjectedPixels,
303
+ });
304
+ game.cameraCull = cameraCull;
305
+ game.cleanup.push(() => {
306
+ cameraCull.dispose();
307
+ game.cameraCull = undefined;
308
+ });
309
+ /**
310
+ * Progress is a high-water mark over the measured load state, never a value that can fall.
311
+ *
312
+ * The ratio's denominator grows: a request registered after an earlier one settled shrinks
313
+ * `settled / requested`, and the file-count and byte branches can disagree across the switch
314
+ * the first weighed manifest entry triggers. Both make the bar jump backwards, which a player
315
+ * reads as the load restarting. Measured: a second texture requested after the first settled
316
+ * took the reported value from 0.7 to 0.35.
317
+ */
318
+ let reportedProgress = 0;
319
+ /** What the load state says right now. This may fall; `startup.progress` is what never does. */
320
+ const measuredProgress = (): number => {
321
+ if (progress.projectionSettled) return 1;
322
+ // A registered hold owns the last tenth. Without this the bar sat at 0.9 for the whole
323
+ // of the game's own tier and then jumped, which is the reading a player calls frozen.
324
+ if (startupReadiness.frameworkReady) {
325
+ const held = startupReadiness.holdReport.length;
326
+ if (held === 0) return 0.9;
327
+ const settled = held - startupReadiness.pendingHolds.length;
328
+ return 0.9 + 0.1 * (settled / held);
329
+ }
330
+ if (startupReadiness.compileSettled) return 0.9;
331
+ if (timeline.enteredMs !== undefined) return 0.8;
332
+ const { requested, requestedBytes, settled, settledBytes } = assets.progress;
333
+ // Bytes when the manifest knows them, files when it does not. A file count spends the
334
+ // same travel on a 4 KB icon as on a 710 MB model, which is how a bar reaches 92% and
335
+ // then stands still for the rest of the download.
336
+ if (requestedBytes > 0) return 0.7 * Math.min(1, settledBytes / requestedBytes);
337
+ return requested === 0 ? 0 : 0.7 * Math.min(1, settled / requested);
338
+ };
339
+ let markProjectionSettled: () => void = () => undefined;
340
+ let rejectProjection: (error: unknown) => void = () => undefined;
341
+ const projectionReady = new Promise<void>((resolve, reject) => {
342
+ markProjectionSettled = resolve;
343
+ rejectProjection = reject;
344
+ });
345
+ void projectionReady.catch(() => undefined);
346
+ const startupShadows = new Set<VirtualShadowNode>();
347
+ const startupReadiness = new StartupReadiness({
348
+ // An attached light with no shadow receiver never asks Three to update its maps.
349
+ settled: () =>
350
+ progress.worldRendered &&
351
+ [...startupShadows].every((node) => node.stats.frame === 0 || node.settled),
352
+ /**
353
+ * The second warm-up: everything a game attached while it held startup.
354
+ *
355
+ * The first pass runs at framework readiness, which for a streaming game is before most of
356
+ * the world exists. Without this, `hold()` buys a complete *picture* and leaves a scene whose
357
+ * every material still compiles on first sight — which is worse than the pop-in it replaced,
358
+ * because a compile stall lands while the player is walking rather than while they are
359
+ * waiting. Measured on a 46,190-instance forest: 8 pipelines warmed, then 28 main-thread
360
+ * tasks over 40 ms in a minute of play, the worst 267 ms.
361
+ *
362
+ * The report budget is a third of the compile budget because this pass runs after the player
363
+ * has already waited behind a curtain. If a compile has started when that budget expires,
364
+ * the readiness gate still joins that original operation within its existing bounded window;
365
+ * work that never started remains lazy.
366
+ */
367
+ afterHolds: async () => {
368
+ await warmUp("TN_STARTUP_WARMUP_HELD", Math.round(STARTUP_COMPILE_BUDGET_MS / 3), false);
369
+ },
370
+ /**
371
+ * The renderer's own answer, which no timer may stand in for: a world frame whose shadow inputs are
372
+ * initialized and whose meter has measured within 3% of its target. On the owned engine the hidden world
373
+ * keeps drawing behind the cover, so this becomes true on its own; a renderer without the seam answers
374
+ * true, and its launch is exactly what it was. The answer names the input it is short of, so a launch that
375
+ * reached its deadline (`STARTUP_IMAGE_TIMEOUT_MS`) reports which one never arrived.
376
+ */
377
+ imageReady: (): boolean | IStartupImageState => {
378
+ // A cover the game asked not to draw the world behind has no frame to wait for, and waiting would
379
+ // hold it open forever; every other game keeps drawing and reaches this on its own.
380
+ if (
381
+ canvasLayer.opaque &&
382
+ !canvasLayer.renderWorldDuringStartup &&
383
+ !canvasLayer.keepWorldRendering
384
+ )
385
+ return true;
386
+ return renderer.firstWorldFrame?.() ?? true;
387
+ },
388
+ });
389
+ game.cleanup.push(() => startupReadiness.cancel());
390
+ // Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
391
+ // script ran, not that a pixel reached the screen, so waiting on it never closed the race it
392
+ // was added for — it only made the losing side lose later, after up to 45 s of held frames.
393
+ // The race no longer exists: the native UI is now composited into the game's own frame, so the
394
+ // cover and the world share one swapchain and there is no second surface left to arrive late.
395
+ // The held loop starts before an explicit warm-up so the loading surface can animate. A native
396
+ // frame may therefore arrive while that pass is still awaiting a compile promise; keep first-use
397
+ // rendering and compute behind the same held boundary until the explicit pass has settled.
398
+ // A web UI is the loading surface on native and on the web. Its bridge must be both attached
399
+ // and announced ready: an attached but unrendered web view is not a cover the player can see.
400
+ // Keep this predicate tied to an actually attached and rendered web UI. The render path still
401
+ // lets a settled world render behind either kind of cover; only the unresolved first-use work
402
+ // is held, so a persistent HUD cannot stop the world pass after loading.
403
+ const startupCoverActive = (): boolean =>
404
+ !startupReadiness.ready &&
405
+ (canvasLayer.opaque || (game.uiReady && game.uiBridge?.hasPeer() === true));
406
+ // A draw the warm-up makes in a timer task is presented by the browser on its own, without the
407
+ // frame loop's overlay: a Wasm engine still baking the environment presents black, and the
408
+ // cover flickers against it. Paint the cover again in the same task.
409
+ const repaintCover = (): void => {
410
+ if (canvasLayer.opaque && canvasLayer.scene.children.length > 0)
411
+ renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
412
+ };
413
+ const timeline: { -readonly [K in keyof IStartupTimeline]: IStartupTimeline[K] } = {};
414
+ const now = (): number => globalThis.performance?.now() ?? Date.now();
415
+ /**
416
+ * A launch that stops making progress says so, on the page, instead of leaving a loading
417
+ * screen up forever. Measured on `midway-open-pacific`: a 104 s launch and then a lost GPU
418
+ * device, with the only account of either on a terminal the player does not have.
419
+ */
420
+ const stopStallWatch = watchStartupStall({
421
+ pending: () => [
422
+ ...assets.progress.pending,
423
+ ...startupReadiness.pendingHolds,
424
+ ...startupReadiness.pendingImage,
425
+ ],
426
+ progress: () => game.ctx?.startup.progress ?? 0,
427
+ workProgress: () => assets.progress.settled + startupReadiness.workProgress,
428
+ stallMs: STARTUP_STALL_MS,
429
+ });
430
+ game.cleanup.push(stopStallWatch);
431
+ watchDeviceLoss(
432
+ (
433
+ renderer.raw as {
434
+ backend?: { device?: { lost?: Promise<{ reason?: string; message?: string }> } };
435
+ }
436
+ ).backend?.device,
437
+ () => game.aborted || game.renderer !== renderer,
438
+ );
439
+ // Stamped when the FRAMEWORK is done, which is before `whenReady()` whenever the game has
440
+ // registered a `startup.hold()`. Two stamps, because one number cannot be both "what the
441
+ // framework cost" and "what the player waited for", and collapsing them is how a valley that
442
+ // took 8.8 s to appear reported 1.5 s.
443
+ void startupReadiness.whenFrameworkReady().then(() => {
444
+ if (game.aborted) return;
445
+ timeline.compileSettledMs ??= now();
446
+ timeline.frameworkReadyMs ??= now();
447
+ });
448
+ // What the gate was still waiting on: logged when it fails and when it reveals late.
449
+ const settlementDetail = () => ({
450
+ worldRendered: progress.worldRendered,
451
+ shadows: [...startupShadows].map((node) => {
452
+ try {
453
+ const frame = node.stats.frame;
454
+ const settled = node.settled;
455
+ return {
456
+ frame,
457
+ settled,
458
+ pending: frame !== 0 && !settled,
459
+ pendingInvalidations: node.tracker.pending,
460
+ };
461
+ } catch {
462
+ return { frame: null, settled: null, pending: null, pendingInvalidations: null };
463
+ }
464
+ }),
465
+ pendingHolds: startupReadiness.pendingHolds,
466
+ compileSettled: startupReadiness.compileSettled,
467
+ frameworkReady: startupReadiness.frameworkReady,
468
+ timeline: {
469
+ loadStartedMs: timeline.loadStartedMs ?? null,
470
+ enteredMs: timeline.enteredMs ?? null,
471
+ compileSettledMs: timeline.compileSettledMs ?? null,
472
+ frameworkReadyMs: timeline.frameworkReadyMs ?? null,
473
+ readyMs: timeline.readyMs ?? null,
474
+ },
475
+ });
476
+ void startupReadiness.whenReady().then(
477
+ () => {
478
+ if (game.aborted) return;
479
+ stopStallWatch();
480
+ // A bounded wait ran out and the world was revealed anyway; say what was still pending.
481
+ if (startupReadiness.timedOut !== undefined)
482
+ console.warn(
483
+ `TN_STARTUP_LATE:${JSON.stringify({ timedOut: startupReadiness.timedOut, ...settlementDetail() })}`,
484
+ );
485
+ // A renderer without first-use compilation settles without running the compile closure
486
+ // below, so the settle stamp is guaranteed here at the latest.
487
+ timeline.compileSettledMs ??= now();
488
+ timeline.frameworkReadyMs ??= now();
489
+ timeline.readyMs ??= now();
490
+ progress.projectionSettled = true;
491
+ // The first world frame the player sees is the next one this renderer draws, so the hold comes off
492
+ // here and only here: every exit before it (abort, dispose, a failed launch) leaves the cover up.
493
+ renderer.setPresentationHeld?.(false);
494
+ game.frameBudget?.markRevealed();
495
+ for (const node of startupShadows) node.startupCovered = false;
496
+ startupShadows.clear();
497
+ // What a game does on `whenReady()` (lift its cover, show its HUD) reaches the page with the
498
+ // world frame, not before it: see `STARTUP_HANDOFF_FRAMES`.
499
+ progress.stateHandOffFrames = STARTUP_HANDOFF_FRAMES;
500
+ markProjectionSettled();
501
+ // The reveal is the first moment the network is free and the player is playing: fill the
502
+ // rest of the release at idle priority from here, never before.
503
+ void assets.startBackgroundFill();
504
+ // A host capturing a frame has no other way to know the world is on screen. Counting frames
505
+ // cannot express it: on a software rasteriser the gate resolves on its bounded window rather
506
+ // than on five in-budget frames, so a fast 300-frame run finishes before the world is shown
507
+ // and captures the loading state. The native screenshot path waits on this flag.
508
+ (globalThis as Record<string, unknown>)[STARTUP_READY_GLOBAL] = true;
509
+ // Measurement only: what the reveal waited for that the spawn camera does not show. A throw
510
+ // here must cost the report, never the game that is already ready.
511
+ try {
512
+ progress.offscreenBytes = measureStartupOffscreenBytes(assets.resolved, threeScene, camera);
513
+ if (progress.offscreenBytes.offscreenBytes > 0)
514
+ (progress.offscreenBytes.warn ? console.warn : console.log)(
515
+ `${STARTUP_OFFSCREEN_BYTES_MARKER}:${JSON.stringify(progress.offscreenBytes)}`,
516
+ );
517
+ } catch (error) {
518
+ console.warn(
519
+ `${STARTUP_OFFSCREEN_BYTES_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`,
520
+ );
521
+ }
522
+ // Once, a minute on: an awaited model no scene object came from (TN_ASSET_UNUSED).
523
+ game.cleanup.push(
524
+ reportUnusedModelsLater(
525
+ new Map(assets.resolved),
526
+ threeScene,
527
+ () => game.aborted || game.renderer !== renderer,
528
+ ),
529
+ );
530
+ // Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
531
+ const unlit = unlitFoliageWarning(threeScene);
532
+ if (unlit !== undefined)
533
+ console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
534
+ },
535
+ (error: unknown) => {
536
+ if (game.aborted) return;
537
+ stopStallWatch();
538
+ rejectProjection(error);
539
+ reportLaunchFailure({ kind: "stalled", message: String(error) });
540
+ console.info(
541
+ `TN_STARTUP_SETTLEMENT:${JSON.stringify({ ...settlementDetail(), failedAtMs: now() })}`,
542
+ );
543
+ },
544
+ );
545
+ const warmUp = async (marker: string, budgetMs: number, stamp: boolean): Promise<void> => {
546
+ if (game.aborted || game.renderer === undefined) return;
547
+ let report: IWarmUpReport | undefined;
548
+ let heldCompletion: Promise<void> | undefined;
549
+ let failure: string | undefined;
550
+ let heldFailure: unknown;
551
+ let heldFailed = false;
552
+ try {
553
+ projection.reconcile();
554
+ // The frame loop's own walk, run here too because the warm-up draws before that loop does.
555
+ // Three is told not to walk the scene (`matrixWorldAutoUpdate = false`), and a declined
556
+ // projection returns from `reconcile()` without walking it, so without this the warm render
557
+ // compiles every pipeline against stale world matrices and the real frames then build the
558
+ // rest synchronously -- tens of seconds each on a software adapter, which loses the device.
559
+ game.matrixWorld?.apply(projection.root);
560
+ const options = game.warmUpOptions();
561
+ const result = await warmUpSceneWithCompletion(renderer, projection.root, camera, {
562
+ afterCoveredDraw: repaintCover,
563
+ budgetMs,
564
+ computeNodes: game.computeDriven.warmupNodes,
565
+ renderPasses: options.renderPasses,
566
+ includeHidden: options.includeHidden,
567
+ yieldFrame: options.yieldFrame,
568
+ });
569
+ report = result.report;
570
+ if (!stamp) heldCompletion = result.completion;
571
+ } catch (error) {
572
+ failure = error instanceof Error ? error.message : String(error);
573
+ if (!stamp) {
574
+ heldFailure = error;
575
+ heldFailed = true;
576
+ }
577
+ }
578
+ // With an explicit warm-up, this held pass is only the first half of startup. Stamp after
579
+ // the explicit pass so its own pipelines remain inside the settled boundary; without one,
580
+ // this is the only warm-up completion.
581
+ if (stamp || !game.warmUpConfiguredExplicitly()) renderer.warmUpSettled?.();
582
+ progress.warmUpStatus =
583
+ report === undefined
584
+ ? { status: "unavailable" }
585
+ : {
586
+ attempted: report.attempted,
587
+ candidates: report.candidates,
588
+ observed: report.observed,
589
+ status: report.observed.status,
590
+ };
591
+ if (stamp) timeline.compileSettledMs ??= now();
592
+ console.log(
593
+ `${marker}:${JSON.stringify(
594
+ report === undefined
595
+ ? { failed: failure ?? "unknown" }
596
+ : {
597
+ compiled: report.compiled,
598
+ pipelines: report.pipelines,
599
+ candidates: report.candidates,
600
+ attempted: report.attempted,
601
+ observed: report.observed,
602
+ slices: report.slices,
603
+ elapsedMs: Math.round(report.elapsedMs),
604
+ unsupported: report.unsupported,
605
+ abandoned: report.abandoned,
606
+ timedOut: report.timedOut,
607
+ computeCompiled: report.computeCompiled,
608
+ computeAbandoned: report.computeAbandoned,
609
+ computeUnsupported: report.computeUnsupported,
610
+ computeTimedOut: report.computeTimedOut,
611
+ passes: report.passes,
612
+ passPipelines: report.passPipelines,
613
+ cullingForced: report.cullingForced,
614
+ visibilityForced: report.visibilityForced,
615
+ cache: report.cache,
616
+ },
617
+ )}`,
618
+ );
619
+ if (heldFailed) throw heldFailure;
620
+ if (heldCompletion !== undefined) await heldCompletion;
621
+ };
622
+ const startupCompile: StartupCompile = async (): Promise<void> => {
623
+ await warmUp("TN_STARTUP_WARMUP", STARTUP_COMPILE_BUDGET_MS, true);
624
+ };
625
+ // A game with no cover skips the compile above, yet readiness still waits for the scene's
626
+ // environment: the owned engine skips every frame while it bakes, and a skipped frame is fast,
627
+ // so the frame window would pass before the world drew once. (An explicit warm-up bakes it.)
628
+ const startupEnvironment = (): StartupCompile | undefined =>
629
+ sceneNeedsEnvironmentPreparation(renderer, projection.root) ? bakeEnvironment : undefined;
630
+ const bakeEnvironment: StartupCompile = async (): Promise<void> => {
631
+ if (game.aborted) return;
632
+ await prepareSceneEnvironment(
633
+ renderer,
634
+ projection.root,
635
+ camera,
636
+ now() + STARTUP_COMPILE_BUDGET_MS,
637
+ repaintCover,
638
+ );
639
+ };
640
+ // The GPU-selected main-pass tally, registered by whichever streamed world is added to the
641
+ // scene. The frame budget reads it once per window; a world with no sample reports undefined, so
642
+ // the window carries nothing rather than a zero no frame selected.
643
+ const ctx: ICtx<TState, TPhysics> = {
644
+ get frameTime() {
645
+ return loopState.current?.frameTime ?? 0;
646
+ },
647
+ get alpha() {
648
+ return loopState.current?.alpha ?? 0;
649
+ },
650
+ interpolate: (object) => interpolation.track(object),
651
+ resetInterpolation: (object) => interpolation.reset(object),
652
+ add: (object) => {
653
+ // Narrowed through a plain `Object3D` rather than the type parameter: a type guard applied
654
+ // to `T` yields `T & IComputeDriven`, which TypeScript will not carry to the registry's
655
+ // `Object3D & IComputeDriven` without a cast. The local keeps the guard honest and the
656
+ // return keeps the caller's own type, so a game never casts back what it just built.
657
+ const node: Object3D = object;
658
+ threeScene.add(node);
659
+ if (typeof (node as { aerialPerspective?: unknown }).aerialPerspective === "function") {
660
+ game.hasDepthCoupledOutput = true;
661
+ }
662
+ if (isComputeDriven(node)) {
663
+ const activeRenderer = game.renderer;
664
+ if (activeRenderer === undefined)
665
+ throw new Error("Cannot add a compute-driven object before the game starts.");
666
+ game.computeDriven.add(node, activeRenderer);
667
+ }
668
+ // A streamed world that can say what the GPU selected, so `TN_FRAME_BUDGET` reports the
669
+ // GPU-selected main-pass count beside its pass record. The tally is asked for only when the
670
+ // frame budget is on: with it off and no validation, the world adds no readback at all.
671
+ const tallySource = node as {
672
+ enableGpuSceneTally?: () => void;
673
+ gpuSceneTally?: () =>
674
+ | { readonly instances: number; readonly triangles: number }
675
+ | undefined;
676
+ };
677
+ if (typeof tallySource.gpuSceneTally === "function") {
678
+ progress.gpuTallyProvider = tallySource.gpuSceneTally.bind(node);
679
+ if (game.config.frameBudget !== false) tallySource.enableGpuSceneTally?.();
680
+ }
681
+ return object;
682
+ },
683
+ assets,
684
+ after: (delay, callback) => scheduler.after(delay, callback),
685
+ afterPhysics: (callback) => afterPhysicsPhase.register(callback),
686
+ beforeRender: (callback) => {
687
+ if (typeof callback !== "function")
688
+ throw new Error("beforeRender requires a callback function.");
689
+ game.beforeRenderCallbacks.add(callback);
690
+ return () => game.beforeRenderCallbacks.delete(callback);
691
+ },
692
+ camera,
693
+ canvasLayer,
694
+ entities,
695
+ every: (callback) => scheduler.every(callback),
696
+ get fps() {
697
+ return loopState.current?.fps ?? 0;
698
+ },
699
+ goto: (name) => game.goto(name, ctx),
700
+ input: game.input,
701
+ pointer: pointerEvents,
702
+ physics: undefined as TPhysics,
703
+ random,
704
+ raycast: (options) => picker.raycast(options),
705
+ raycastAll: (options, target) => picker.raycastAll(options, target),
706
+ startup: {
707
+ get warmup() {
708
+ return progress.warmUpStatus;
709
+ },
710
+ get phase() {
711
+ // The projection is reconciled before the first world draw, but readiness is not reported
712
+ // until first-use work and a sustained in-budget window have completed. An opaque loading
713
+ // layer cannot turn `whenReady()` into a first-present signal while work is still waiting
714
+ // behind it.
715
+ if (progress.projectionSettled) return "ready" as const;
716
+ return "collapsing" as const;
717
+ },
718
+ // True once first-use compilation has settled, which is earlier than `phase === "ready"`
719
+ // and is the signal a game wants when it must not act during the launch. `phase` cannot
720
+ // express it: it is binary, and readiness additionally requires a sustained in-budget
721
+ // frame window that a software rasteriser can only ever let expire. A game gated on
722
+ // `phase` alone therefore does nothing for ~25s on such a lane — measured as a chase route
723
+ // of length 0.000000 where 6 was required, because the scenario ended first.
724
+ get compileSettled() {
725
+ return startupReadiness.compileSettled;
726
+ },
727
+ // Honest and monotonic: the asset ratio carries the first 70% while the start scene
728
+ // loads, entering the world is 80%, compile settling 90%, and only readiness is 1.
729
+ // Monotonicity is enforced rather than assumed — see the high-water mark above.
730
+ get progress() {
731
+ reportedProgress = Math.max(reportedProgress, measuredProgress());
732
+ return reportedProgress;
733
+ },
734
+ hold: (label, work, budgetMs, progress) => {
735
+ startupReadiness.hold(label, work, budgetMs, progress);
736
+ },
737
+ get timeline() {
738
+ return { ...timeline };
739
+ },
740
+ whenReady: () => projectionReady,
741
+ whenFrameworkReady: () => startupReadiness.whenFrameworkReady(),
742
+ },
743
+ renderer: game.renderer,
744
+ viewport,
745
+ scene: threeScene,
746
+ state: game.state,
747
+ tween: (target, properties, duration, options) =>
748
+ scheduler.tween(target, properties, duration, options),
749
+ };
750
+ game.ctx = ctx;
751
+ game.entities = entities;
752
+ game.scheduler = scheduler;
753
+ game.afterPhysicsPhase = afterPhysicsPhase;
754
+ // The scene-owned registries. Pushed after the autobatcher, so they empty before it resets (the
755
+ // order `#teardown` always had), and before the frame loop and plugins, so both release first.
756
+ game.cleanup.push(() => {
757
+ afterPhysicsPhase.clear();
758
+ game.beforeRenderCallbacks.clear();
759
+ scheduler.clear();
760
+ entities.clear();
761
+ game.afterPhysicsPhase = undefined;
762
+ game.scheduler = undefined;
763
+ game.entities = undefined;
764
+ });
765
+ const devToolsHost = platform === undefined ? hostWindow() : platform.devToolsHost;
766
+ game.cleanup.push(
767
+ installDevTools(entities, devToolsHost as DevToolsHost | undefined, () => game.geometryCapture),
768
+ );
769
+ game.scene = new SceneType();
770
+ game.sceneName = bootSceneName;
771
+
772
+ // The frame loop and scene entry see the narrower view; the compiler holds `IBootPhase` to it.
773
+ const loopPhase: ILoopPhase<TState, TPhysics> = game;
774
+ return Object.assign(progress, {
775
+ afterPhysicsPhase,
776
+ autoBatch,
777
+ camera,
778
+ canvasLayer,
779
+ ctx,
780
+ debug,
781
+ game: loopPhase,
782
+ input,
783
+ interpolation,
784
+ loopState,
785
+ now,
786
+ picker,
787
+ pointerEvents,
788
+ projection,
789
+ random,
790
+ renderer,
791
+ repaintCover,
792
+ scheduler,
793
+ startupCompile,
794
+ startupCoverActive,
795
+ startupEnvironment,
796
+ startupReadiness,
797
+ startupShadows,
798
+ threeScene,
799
+ timeline,
800
+ });
801
+ }
802
+
803
+ /** The last phase of `#boot`: the start scene's load and entry, the plugin gates, the release. */
804
+ export async function startScenes<TState extends Record<string, unknown>, TPhysics>(
805
+ startup: IGameStartup<TState, TPhysics>,
806
+ frameLoop: IGameFrameLoop,
807
+ ): Promise<void> {
808
+ const game = startup.game;
809
+ const {
810
+ camera,
811
+ ctx,
812
+ now,
813
+ projection,
814
+ random,
815
+ renderer,
816
+ repaintCover,
817
+ startupReadiness,
818
+ timeline,
819
+ } = startup;
820
+ const { geometryCapture, loop: gameLoop } = frameLoop;
821
+
822
+ const startGates: Array<{
823
+ readonly gate: Promise<void>;
824
+ readonly rejectEntered: (error: unknown) => void;
825
+ readonly resolveEntered: () => void;
826
+ }> = [];
827
+ let settleLoaded: (error?: unknown) => void = () => undefined;
828
+ const startLoaded = new Promise<void>((resolve, reject) => {
829
+ settleLoaded = (error) => (error === undefined ? resolve() : reject(error));
830
+ });
831
+ // A run with no setup never awaits it; a failed load is reported by start() itself.
832
+ void startLoaded.catch(() => undefined);
833
+ const runtime: IGamePluginRuntime = {
834
+ startSceneLoaded: () => startLoaded,
835
+ fixedStep: (ticks, options) =>
836
+ gameLoop.advance(ticks, { ...options, until: () => game.pendingSceneEnter !== undefined }),
837
+ sceneTransition: () =>
838
+ game.pendingSceneEnter?.then(
839
+ () => undefined,
840
+ () => undefined,
841
+ ),
842
+ frameCounts: () => ({ updates: startup.updates, renders: startup.renders }),
843
+ frameBudgetWindow: () => game.frameBudget?.window(),
844
+ freezeClock: (settleSteps) => gameLoop.freezeClock(settleSteps),
845
+ // Spend the settling pass once the world's scene is live: this boot runs through a loading scene, so
846
+ // a runtime that settled on its first live frame would settle the loading scene (playtest settle).
847
+ settleClock: (steps) => gameLoop.settleNow(steps),
848
+ renderCurrent: () => gameLoop.renderCurrentFrame(),
849
+ enableRuntimeDiagnostics: () => {
850
+ game.renderMetricsEnabled = true;
851
+ gameLoop.setCollectMetrics(true);
852
+ },
853
+ holdStart: (gate) => {
854
+ let rejectEntered: (error: unknown) => void = () => undefined;
855
+ let resolveEntered: () => void = () => undefined;
856
+ const entered = new Promise<void>((resolve, reject) => {
857
+ rejectEntered = reject;
858
+ resolveEntered = resolve;
859
+ });
860
+ startGates.push({ gate, rejectEntered, resolveEntered });
861
+ return entered;
862
+ },
863
+ geometryCapture: (request) => geometryCapture.request(request),
864
+ observations: createRuntimeObservations(),
865
+ ...(renderer.pipelineCensus === undefined ? {} : { pipelineCensus: renderer.pipelineCensus }),
866
+ tick: gameLoop.tick,
867
+ random,
868
+ rapier: null,
869
+ seed: game.config.seed ?? null,
870
+ startupCompileSettled: () => startupReadiness.compileSettled,
871
+ startupRevealed: () => game.uiRevealed,
872
+ startupTimeline: () => ({ ...timeline }),
873
+ startupOffscreenBytes: () => startup.offscreenBytes,
874
+ step: gameLoop.step,
875
+ runtimeDiagnosticsSeries: () => gameLoop.runtimeDiagnosticsSeries(),
876
+ };
877
+ Object.assign(runtime, {
878
+ _setClockMode: (mode: "fixed-step" | "wall-clock") => gameLoop._setClockMode(mode),
879
+ });
880
+ // Release order, newest push first (see `drainCleanup`): the loop stops, the scene exits, then every active
881
+ // plugin's `dispose`, then every plugin's setup cleanup, each group in the order its plugins were
882
+ // set up. Both plugin groups are pushed before the first `setup` runs, so a boot that aborts or
883
+ // throws inside the loop below still releases the plugins it had reached.
884
+ const pluginCleanups: PluginCleanup[] = [];
885
+ game.cleanup.push(() => throwFirst(runAll(pluginCleanups.splice(0))));
886
+ const disposed = new Set<IGamePluginHooks<TState, TPhysics>>();
887
+ game.cleanup.push(() => {
888
+ const active = game.activePlugins;
889
+ game.activePlugins = [];
890
+ throwFirst(
891
+ runAll(
892
+ active.map((plugin) => () => {
893
+ if (disposed.has(plugin)) return;
894
+ disposed.add(plugin);
895
+ plugin.dispose?.(ctx);
896
+ }),
897
+ ),
898
+ );
899
+ });
900
+ game.cleanup.push(() => {
901
+ try {
902
+ if (game.sceneEntered) game.scene?.exit(ctx);
903
+ } finally {
904
+ game.sceneFrame = undefined;
905
+ game.sceneEntered = false;
906
+ }
907
+ });
908
+ // Pushed last of all, so the loop stops before anything it drives is released.
909
+ game.cleanup.push(() => gameLoop.stop());
910
+ // A boot that throws must end exactly like an aborted boot: every cleanup attempted, every
911
+ // resource released — and the original error rethrown, not a teardown error standing in
912
+ // for it. The abort branches below stay outside these guards: they tear down themselves.
913
+ for (const plugin of game.config.plugins ?? []) {
914
+ let cleanup: PluginCleanup | undefined;
915
+ try {
916
+ cleanup = typeof plugin === "function" ? plugin(ctx) : await plugin.setup?.(ctx, runtime);
917
+ } catch (error) {
918
+ game.teardown();
919
+ throw error;
920
+ }
921
+ if (typeof plugin !== "function") game.activePlugins.push(plugin);
922
+ if (cleanup !== undefined) pluginCleanups.push(cleanup);
923
+ if (game.aborted) {
924
+ game.teardown();
925
+ return;
926
+ }
927
+ }
928
+ const scene = game.scene;
929
+ if (scene === undefined) {
930
+ game.teardown();
931
+ return;
932
+ }
933
+ // Held: the loop renders every frame from here but steps nothing. On native the render loop
934
+ // is the only thing that can put pixels on the screen, so an async load starts it before the
935
+ // await; a synchronous load has already completed and starts it after the call. Holding rather
936
+ // than simply starting keeps the determinism contract intact: no tick advances and no elapsed
937
+ // time is banked before the release below.
938
+ const startHeldLoop = (): void => {
939
+ gameLoop.setHeld(true);
940
+ gameLoop.start();
941
+ };
942
+ try {
943
+ timeline.loadStartedMs ??= now();
944
+ const loaded = scene.load(ctx);
945
+ startHeldLoop();
946
+ if (loaded !== undefined) await loaded;
947
+ settleLoaded();
948
+ } catch (error) {
949
+ reportSceneLoadFailure(error);
950
+ settleLoaded(error);
951
+ // A runner's describe waits on these: answer it with the failure now, as every other start
952
+ // failure below does, instead of leaving it to run out its whole handshake budget.
953
+ for (const startGate of startGates) startGate.rejectEntered(error);
954
+ game.teardown();
955
+ throw error;
956
+ }
957
+ if (game.aborted) {
958
+ game.teardown();
959
+ return;
960
+ }
961
+ // Plugins that need to mutate scene-load placeholders hold here. Setup must land before
962
+ // Scene.enter() transfers those values into authoritative physics/gameplay state.
963
+ if (startGates.length > 0) {
964
+ try {
965
+ await Promise.all(startGates.map(({ gate }) => gate));
966
+ } catch (error) {
967
+ for (const startGate of startGates) startGate.rejectEntered(error);
968
+ game.teardown();
969
+ throw error;
970
+ }
971
+ if (game.aborted) {
972
+ const error = new Error("Game start was aborted before the start scene entered.");
973
+ for (const startGate of startGates) startGate.rejectEntered(error);
974
+ game.teardown();
975
+ return;
976
+ }
977
+ }
978
+ try {
979
+ // A boot scene can navigate during enter(). Describe the destination's registered entities
980
+ // after it enters, while readiness and the full goto() still wait for first-use warm-up.
981
+ game.onStartSceneEntered = () => {
982
+ for (const startGate of startGates) startGate.resolveEntered();
983
+ };
984
+ game.enterScene(scene, ctx);
985
+ timeline.enteredMs ??= now();
986
+ void game.pendingSceneEnter?.catch((error: unknown) => {
987
+ for (const startGate of startGates) startGate.rejectEntered(error);
988
+ });
989
+ } catch (error) {
990
+ for (const startGate of startGates) startGate.rejectEntered(error);
991
+ game.teardown();
992
+ throw error;
993
+ }
994
+ if (game.aborted) {
995
+ game.teardown();
996
+ return;
997
+ }
998
+ // The scene is built and the loop is still held, which is the only window where compiling can
999
+ // cost frames nobody is playing. Warming up here rather than letting the first real frame do
1000
+ // it is what keeps a launch from freezing inside one 24-second frame. PRD-218.
1001
+ if (game.warmUpConfiguredExplicitly() && game.renderer !== undefined) {
1002
+ // Never fatal, and never able to hang the launch. This block sits between "the scene is
1003
+ // built" and "the game may start", so anything it does wrong is something the player
1004
+ // experiences as the game not starting -- which is exactly what the first version did: a
1005
+ // `compileAsync` that never resolved on a Pixel 8 left this `await` pending forever, the
1006
+ // loop stayed held, the simulation never advanced, and the game sat on its loading screen
1007
+ // with no error anywhere. A warm-up that fails must cost the launch its speed, never its
1008
+ // start, so the failure is reported and boot carries on.
1009
+ let report: IWarmUpReport | undefined;
1010
+ let failure: string | undefined;
1011
+ try {
1012
+ projection.reconcile();
1013
+ // Same walk as the held warm-up above: the explicit warm-up also draws before the frame
1014
+ // loop's own matrix pass, and a declined projection left the scene un-walked.
1015
+ game.matrixWorld?.apply(projection.root);
1016
+ const warmUpOptions: IWarmUpOptions = game.warmUpOptions();
1017
+ report = await warmUpScene(game.renderer, projection.root, camera, {
1018
+ afterCoveredDraw: repaintCover,
1019
+ ...warmUpOptions,
1020
+ computeNodes: [...(warmUpOptions.computeNodes ?? []), ...game.computeDriven.warmupNodes],
1021
+ });
1022
+ } catch (error) {
1023
+ failure = error instanceof Error ? error.message : String(error);
1024
+ }
1025
+ game.renderer.warmUpSettled?.();
1026
+ startup.warmUpStatus =
1027
+ report === undefined
1028
+ ? { status: "unavailable" }
1029
+ : {
1030
+ attempted: report.attempted,
1031
+ candidates: report.candidates,
1032
+ observed: report.observed,
1033
+ status: report.observed.status,
1034
+ };
1035
+ // One greppable line on every platform, so a device lane reads what the warm-up did without
1036
+ // instrumenting anything -- including the cases where it could do nothing, ran out of
1037
+ // budget, or threw.
1038
+ console.log(
1039
+ `TN_WARMUP:${JSON.stringify(
1040
+ report === undefined
1041
+ ? { failed: failure ?? "unknown" }
1042
+ : {
1043
+ compiled: report.compiled,
1044
+ pipelines: report.pipelines,
1045
+ candidates: report.candidates,
1046
+ attempted: report.attempted,
1047
+ observed: report.observed,
1048
+ slices: report.slices,
1049
+ elapsedMs: Math.round(report.elapsedMs),
1050
+ unsupported: report.unsupported,
1051
+ abandoned: report.abandoned,
1052
+ timedOut: report.timedOut,
1053
+ computeCompiled: report.computeCompiled,
1054
+ computeAbandoned: report.computeAbandoned,
1055
+ computeUnsupported: report.computeUnsupported,
1056
+ computeTimedOut: report.computeTimedOut,
1057
+ passes: report.passes,
1058
+ passPipelines: report.passPipelines,
1059
+ cullingForced: report.cullingForced,
1060
+ visibilityForced: report.visibilityForced,
1061
+ cache: report.cache,
1062
+ },
1063
+ )}`,
1064
+ );
1065
+ startup.explicitWarmUpSettled = true;
1066
+ if (game.aborted) {
1067
+ game.teardown();
1068
+ return;
1069
+ }
1070
+ }
1071
+ game.started = true;
1072
+ // Every gate has resolved and the scene has entered, so the simulation may move. The first
1073
+ // tick after this reads a single frame's dt, not one spanning the load.
1074
+ gameLoop.setHeld(false);
1075
+ gameLoop.start();
1076
+ }