@threenative/core 0.3.10 → 0.3.12

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