@threenative/core 0.3.12 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -0,0 +1,269 @@
1
+ import type { Scene as ThreeScene } from "three";
2
+ import type { AutoBatch } from "./auto-batch.js";
3
+ import { ComputeDrivenRegistry } from "./compute-driven.js";
4
+ import type { Registry } from "./entities.js";
5
+ import type { FrameBudget } from "./frame-budget.js";
6
+ import type { IGameConfig, IGamePlatformSource, IGamePluginHooks } from "./game.js";
7
+ import type { GeometryCapture } from "./geometry-capture.js";
8
+ import type { InputMap } from "./input.js";
9
+ import type { PhysicsInterpolation } from "./interpolation.js";
10
+ import type { IAfterPhysicsPhase } from "./loop.js";
11
+ import type { MatrixWorldPass } from "./matrix-world.js";
12
+ import type { ScenePicker } from "./picking.js";
13
+ import type { PointerEvents3D } from "./pointer-events.js";
14
+ import type { RenderCameraCull } from "./render-camera-cull.js";
15
+ import type { SceneRenderProjection } from "./renderProjection.js";
16
+ import type { IRendererLike } from "./renderer.js";
17
+ import type { ICtx, Scene, SceneFrame } from "./scene.js";
18
+ import type { Scheduler } from "./schedule.js";
19
+ import type { GameStore } from "./state.js";
20
+ import type { IUiBridge } from "./ui-bridge.js";
21
+ import type { Viewport } from "./viewport.js";
22
+ import type { IWarmUpOptions } from "./warmup.js";
23
+
24
+ /**
25
+ * The state the boot phases own: every resource a phase acquires, and every flag a phase reads.
26
+ * One object, assigned by name, so a phase that needs a field this lacks fails to compile.
27
+ */
28
+ export interface IBootState<TState extends Record<string, unknown>, TPhysics> {
29
+ /** Releases pushed as resources are acquired; `#teardown` drains them, newest first. */
30
+ readonly cleanup: Array<() => void>;
31
+ readonly computeDriven: ComputeDrivenRegistry;
32
+ readonly config: IGameConfig<TState, TPhysics>;
33
+ readonly state: GameStore<TState>;
34
+ /**
35
+ * Unlike afterPhysics, this seam's frame boundary is the world-render block, so it is a plain
36
+ * scene-owned set rather than a phase on the loop.
37
+ */
38
+ readonly beforeRenderCallbacks: Set<() => void>;
39
+ activePlugins: Array<IGamePluginHooks<TState, TPhysics>>;
40
+ aborted: boolean;
41
+ afterPhysicsPhase: IAfterPhysicsPhase | undefined;
42
+ autoBatch: AutoBatch | undefined;
43
+ /** Reused snapshot buffers, one per nesting depth, so a steady frame allocates no callback array. */
44
+ beforeRenderSnapshots: Array<Array<() => void>>;
45
+ beforeRenderDepth: number;
46
+ cameraCull: RenderCameraCull | undefined;
47
+ ctx: ICtx<TState, TPhysics> | undefined;
48
+ entities: Registry | undefined;
49
+ frameBudget: FrameBudget | undefined;
50
+ geometryCapture: GeometryCapture | undefined;
51
+ /**
52
+ * Depth-coupled output needs the scene hook before its pass; ordinary scenes retain the
53
+ * historical after-render hook so an atmosphere-free game has the same render path as HEAD.
54
+ */
55
+ hasDepthCoupledOutput: boolean;
56
+ input: InputMap | undefined;
57
+ interpolation: PhysicsInterpolation | undefined;
58
+ matrixWorld: MatrixWorldPass | undefined;
59
+ /** One-shot notification after the scene that owns the world has entered, before warm-up. */
60
+ onStartSceneEntered: (() => void) | undefined;
61
+ paused: boolean;
62
+ /** The full `goto()` transition, including first-use warm-up, or undefined when none is. */
63
+ pendingSceneEnter: Promise<void> | undefined;
64
+ picker: ScenePicker | undefined;
65
+ pointerEvents: PointerEvents3D | undefined;
66
+ projection: SceneRenderProjection | undefined;
67
+ renderer: IRendererLike | undefined;
68
+ /** Flipped only by a diagnostics consumer announcing itself; see enableRuntimeDiagnostics(). */
69
+ renderMetricsEnabled: boolean;
70
+ resumeScene: string | undefined;
71
+ scene: Scene<TState, TPhysics> | undefined;
72
+ sceneEntered: boolean;
73
+ sceneFrame: SceneFrame<TState, TPhysics> | undefined;
74
+ /** Bumped on every scene change, so a row id is stable exactly as long as the scene is. */
75
+ sceneGeneration: number;
76
+ /**
77
+ * The name of the scene currently entered. Carried across a hot update so a reload resumes
78
+ * where the session was, instead of restoring the game's state into its start scene.
79
+ */
80
+ sceneName: string | undefined;
81
+ scheduler: Scheduler | undefined;
82
+ started: boolean;
83
+ /** Startup readiness has begun its first-use gate; before that, it bakes the entered environment. */
84
+ startupGateStarted: boolean;
85
+ uiBridge: IUiBridge | undefined;
86
+ uiReady: boolean;
87
+ /** The loading cover has lifted and page UI may show state; see `UI_STARTUP_MESSAGE`. */
88
+ uiRevealed: boolean;
89
+ viewport: Viewport | undefined;
90
+ }
91
+
92
+ /** The game's own calls a phase makes, bound to the game. */
93
+ export interface IBootHost<TState extends Record<string, unknown>, TPhysics> {
94
+ connectUi(): IUiBridge;
95
+ enterScene(scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean;
96
+ goto(name: string, ctx: ICtx<TState, TPhysics>): Promise<void>;
97
+ postUiStartup(): void;
98
+ teardown(): void;
99
+ warmUpConfiguredExplicitly(): boolean;
100
+ warmUpOptions(): IWarmUpOptions;
101
+ }
102
+
103
+ /**
104
+ * The game's own platform source, else the one a worker host installed on the global scope: worker
105
+ * mode runs the unchanged portable entry, so it cannot pass `platform` here (PRD-752).
106
+ */
107
+ export interface IBootPlatform {
108
+ readonly platform: IGamePlatformSource | undefined;
109
+ }
110
+
111
+ export type IBootGame<TState extends Record<string, unknown>, TPhysics> = IBootHost<
112
+ TState,
113
+ TPhysics
114
+ > &
115
+ IBootPlatform &
116
+ IBootState<TState, TPhysics>;
117
+
118
+ /** What the frame loop and the scene-entry phase read from the game, and nothing else. */
119
+ export type ILoopPhase<TState extends Record<string, unknown>, TPhysics> = Pick<
120
+ IBootGame<TState, TPhysics>,
121
+ | "aborted"
122
+ | "activePlugins"
123
+ | "beforeRenderCallbacks"
124
+ | "beforeRenderDepth"
125
+ | "beforeRenderSnapshots"
126
+ | "cameraCull"
127
+ | "cleanup"
128
+ | "computeDriven"
129
+ | "config"
130
+ | "enterScene"
131
+ | "entities"
132
+ | "frameBudget"
133
+ | "geometryCapture"
134
+ | "hasDepthCoupledOutput"
135
+ | "input"
136
+ | "matrixWorld"
137
+ | "onStartSceneEntered"
138
+ | "paused"
139
+ | "pendingSceneEnter"
140
+ | "postUiStartup"
141
+ | "projection"
142
+ | "renderer"
143
+ | "renderMetricsEnabled"
144
+ | "scene"
145
+ | "sceneEntered"
146
+ | "sceneFrame"
147
+ | "sceneGeneration"
148
+ | "started"
149
+ | "startupGateStarted"
150
+ | "state"
151
+ | "teardown"
152
+ | "uiBridge"
153
+ | "uiRevealed"
154
+ | "warmUpConfiguredExplicitly"
155
+ | "warmUpOptions"
156
+ >;
157
+
158
+ /** What the startup phase reads and assigns: the loop's view, plus what only the world build touches. */
159
+ export type IBootPhase<TState extends Record<string, unknown>, TPhysics> = ILoopPhase<
160
+ TState,
161
+ TPhysics
162
+ > &
163
+ Pick<
164
+ IBootGame<TState, TPhysics>,
165
+ | "afterPhysicsPhase"
166
+ | "autoBatch"
167
+ | "connectUi"
168
+ | "ctx"
169
+ | "goto"
170
+ | "interpolation"
171
+ | "picker"
172
+ | "platform"
173
+ | "pointerEvents"
174
+ | "resumeScene"
175
+ | "sceneName"
176
+ | "scheduler"
177
+ | "uiReady"
178
+ | "viewport"
179
+ >;
180
+
181
+ /** The boot state at rest: nothing acquired, nothing paused, every flag down. */
182
+ export function createBootGame<TState extends Record<string, unknown>, TPhysics>(
183
+ input: Pick<IBootState<TState, TPhysics>, "config" | "state"> & IBootHost<TState, TPhysics>,
184
+ ): IBootGame<TState, TPhysics> {
185
+ const { config } = input;
186
+ return {
187
+ ...input,
188
+ activePlugins: [],
189
+ aborted: false,
190
+ afterPhysicsPhase: undefined,
191
+ autoBatch: undefined,
192
+ beforeRenderCallbacks: new Set(),
193
+ beforeRenderDepth: 0,
194
+ beforeRenderSnapshots: [],
195
+ cameraCull: undefined,
196
+ cleanup: [],
197
+ computeDriven: new ComputeDrivenRegistry(),
198
+ ctx: undefined,
199
+ entities: undefined,
200
+ frameBudget: undefined,
201
+ geometryCapture: undefined,
202
+ hasDepthCoupledOutput: false,
203
+ input: undefined,
204
+ interpolation: undefined,
205
+ matrixWorld: undefined,
206
+ onStartSceneEntered: undefined,
207
+ paused: false,
208
+ pendingSceneEnter: undefined,
209
+ picker: undefined,
210
+ get platform(): IGamePlatformSource | undefined {
211
+ return (
212
+ config.platform ??
213
+ (globalThis as { __tnGamePlatform?: IGamePlatformSource }).__tnGamePlatform
214
+ );
215
+ },
216
+ pointerEvents: undefined,
217
+ projection: undefined,
218
+ renderer: undefined,
219
+ renderMetricsEnabled: false,
220
+ resumeScene: undefined,
221
+ scene: undefined,
222
+ sceneEntered: false,
223
+ sceneFrame: undefined,
224
+ sceneGeneration: 0,
225
+ sceneName: undefined,
226
+ scheduler: undefined,
227
+ started: false,
228
+ startupGateStarted: false,
229
+ uiBridge: undefined,
230
+ uiReady: false,
231
+ uiRevealed: false,
232
+ viewport: undefined,
233
+ };
234
+ }
235
+
236
+ /** Runs every release even after one throws, and returns the failures in the order they came. */
237
+ export function runAll(releases: Iterable<() => void>): unknown[] {
238
+ const failures: unknown[] = [];
239
+ for (const release of releases) {
240
+ try {
241
+ release();
242
+ } catch (error) {
243
+ failures.push(error);
244
+ }
245
+ }
246
+ return failures;
247
+ }
248
+
249
+ /** The first failure is the original cause; a release throws that one after all have run. */
250
+ export function throwFirst(failures: readonly unknown[]): void {
251
+ if (failures.length > 0) throw failures[0];
252
+ }
253
+
254
+ /**
255
+ * Drains the cleanups, newest first, so a resource is released before anything it was built on.
256
+ * Each release that throws is collected and the rest still run.
257
+ */
258
+ export function drainCleanup(cleanup: Array<() => void>): unknown[] {
259
+ return runAll(cleanup.splice(0).reverse());
260
+ }
261
+
262
+ /** Empties the authored scene and everything it was reading from. */
263
+ export function clearScene(scene: ThreeScene, computeDriven: ComputeDrivenRegistry): void {
264
+ computeDriven.clear();
265
+ scene.clear();
266
+ scene.background = null;
267
+ scene.environment = null;
268
+ scene.fog = null;
269
+ }
@@ -1,5 +1,6 @@
1
1
  /// <reference path="./import-meta.d.ts" />
2
2
 
3
+ import { DEV_GLOBAL_KEY, type IDevTools, devGlobal } from "./dev-global.js";
3
4
  import type { EntitySnapshot, Registry } from "./entities.js";
4
5
  import type {
5
6
  GeometryCapture,
@@ -7,17 +8,8 @@ import type {
7
8
  IGeometryCaptureRequest,
8
9
  } from "./geometry-capture.js";
9
10
 
10
- interface IDevTools {
11
- snapshot(): EntitySnapshot;
12
- /**
13
- * Arms one per-object geometry capture for a development overlay. Absent until the game has a
14
- * render loop; the overlay treats that as "not ready", never as an empty scene.
15
- */
16
- geometry?(request?: IGeometryCaptureRequest): Promise<IGeometryCaptureReport>;
17
- }
18
-
19
11
  export type DevToolsHost = Record<string, unknown> &
20
- Partial<Record<"__THREENATIVE__", Partial<IDevTools>>>;
12
+ Partial<Record<typeof DEV_GLOBAL_KEY, Partial<IDevTools>>>;
21
13
 
22
14
  /**
23
15
  * The bundler's dev flag.
@@ -68,8 +60,9 @@ export function installDevTools(
68
60
  // this whole install from a production build, and a runtime `DEV_MODE` check cannot be stripped.
69
61
  const isDev = (import.meta as IImportMeta).env?.DEV === true;
70
62
  if (!isDev || host === undefined) return () => undefined;
63
+ const current = devGlobal(host) ?? {};
71
64
  const devTools: IDevTools = {
72
- ...host.__THREENATIVE__,
65
+ ...(current as Partial<IDevTools>),
73
66
  geometry: async (request) => {
74
67
  const capture = geometry();
75
68
  if (capture === undefined) {
@@ -82,12 +75,12 @@ export function installDevTools(
82
75
  },
83
76
  snapshot: () => entities.snapshot(),
84
77
  };
85
- host.__THREENATIVE__ = devTools;
78
+ host[DEV_GLOBAL_KEY] = devTools;
86
79
  return () => {
87
- if (host.__THREENATIVE__ !== devTools) return;
80
+ if (devGlobal(host) !== devTools) return;
88
81
  const remaining = Object.fromEntries(
89
82
  Object.entries(devTools).filter(([key]) => key !== "snapshot" && key !== "geometry"),
90
83
  );
91
- host.__THREENATIVE__ = Object.keys(remaining).length === 0 ? undefined : remaining;
84
+ host[DEV_GLOBAL_KEY] = Object.keys(remaining).length === 0 ? undefined : remaining;
92
85
  };
93
86
  }
@@ -1,7 +1,6 @@
1
- import type { AutoBatch } from "./auto-batch.js";
1
+ import { flushAnimationTicks } from "./animation-batch.js";
2
+ import { drawWorld } from "./auto-batch.js";
2
3
  import { updateClusteredMeshes } from "./clustered-mesh.js";
3
- import type { ComputeDrivenRegistry } from "./compute-driven.js";
4
- import type { Registry } from "./entities.js";
5
4
  import { FrameBudget } from "./frame-budget.js";
6
5
  import { isDevLaunch } from "./game-dev-tools.js";
7
6
  import {
@@ -12,17 +11,10 @@ import {
12
11
  } from "./game-renderer-metrics.js";
13
12
  import { STARTUP_HANDOFF_FRAMES } from "./game-startup.js";
14
13
  import type { IGameStartup } from "./game-startup.js";
15
- import type { IGameConfig, IGamePlatformSource, IGamePluginHooks, PluginCleanup } from "./game.js";
16
14
  import { GeometryCapture, rendererBackendIdentity } from "./geometry-capture.js";
17
- import type { InputMap } from "./input.js";
18
- import type { PhysicsInterpolation } from "./interpolation.js";
19
- import type { IAfterPhysicsPhase } from "./loop.js";
20
15
  import { FixedStepLoop, type IRenderPerformanceMetrics } from "./loop.js";
21
- import type { MatrixWorldPass } from "./matrix-world.js";
22
16
  import { updateModelLods } from "./model-lod.js";
23
- import type { ScenePicker } from "./picking.js";
24
17
  import { getPlatform } from "./platform.js";
25
- import type { PointerEvents3D } from "./pointer-events.js";
26
18
  import {
27
19
  FrameCounters,
28
20
  counterDeviceOf,
@@ -59,92 +51,24 @@ import {
59
51
  } from "./profiling/scene-warning.js";
60
52
  import { installSpanProbes } from "./profiling/span-probes.js";
61
53
  import { formatProjectionWindow } from "./projection-marker.js";
62
- import type { RenderCameraCull } from "./render-camera-cull.js";
63
54
  import { RenderPassBudget } from "./render-pass-budget.js";
64
55
  import type { VirtualShadowNode } from "./render/virtual-shadow.js";
65
- import type { SceneRenderProjection } from "./renderProjection.js";
66
56
  import { resolvePlatformResolutionFloor } from "./renderer-config.js";
67
- import type { IRendererLike } from "./renderer.js";
68
57
  import { rendererFrameGateSkips, rendererWorldPresented } from "./renderer.js";
69
58
  import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
70
- import type { ICtx, Scene, SceneFrame } from "./scene.js";
71
- import type { Scheduler } from "./schedule.js";
72
59
  import { STARTUP_STABLE_WINDOW_MS } from "./startup-readiness.js";
73
- import type { GameStore } from "./state.js";
74
60
  import {
75
61
  STATIC_TRANSFORM_MARKER,
76
62
  refreshStaticTransforms,
77
63
  staticRoots,
78
64
  staticTransformCensus,
79
65
  } from "./static-transform.js";
66
+ import { endSliceFrames, noteSliceFrame } from "./streaming.js";
80
67
  import { resolveTargetFps } from "./target-fps.js";
81
- import type { IUiBridge } from "./ui-bridge.js";
82
68
  import { UI_DEV_METRICS_MESSAGE } from "./ui-bridge.js";
83
- import type { Viewport } from "./viewport.js";
84
- import type { IWarmUpOptions } from "./warmup.js";
85
-
86
- /**
87
- * The game's own state, as a boot phase sees it: every member is the private field of the same
88
- * name, so a phase assigns and reads exactly what it did inside the class.
89
- */
90
- export interface IGameBootGame<TState extends Record<string, unknown>, TPhysics> {
91
- /** The cleanups `#teardown` drains in its own release step, in the order they were pushed. */
92
- readonly cleanup: Array<() => void>;
93
- readonly computeDriven: ComputeDrivenRegistry;
94
- readonly config: IGameConfig<TState, TPhysics>;
95
- readonly platform: IGamePlatformSource | undefined;
96
- readonly state: GameStore<TState>;
97
- readonly beforeRenderCallbacks: Set<() => void>;
98
- readonly activePlugins: Array<IGamePluginHooks<TState, TPhysics>>;
99
- readonly uiBridge: IUiBridge | undefined;
100
- readonly sceneFrame: SceneFrame<TState, TPhysics> | undefined;
101
- readonly sceneEntered: boolean;
102
- readonly sceneGeneration: number;
103
- readonly pendingSceneEnter: Promise<void> | undefined;
104
- readonly paused: boolean;
105
- readonly aborted: boolean;
106
- readonly uiReady: boolean;
107
- // Assigned by a phase, exactly as the field was.
108
- renderer: IRendererLike | undefined;
109
- scene: Scene<TState, TPhysics> | undefined;
110
- sceneName: string | undefined;
111
- ctx: ICtx<TState, TPhysics> | undefined;
112
- input: InputMap | undefined;
113
- viewport: Viewport | undefined;
114
- picker: ScenePicker | undefined;
115
- pointerEvents: PointerEvents3D | undefined;
116
- matrixWorld: MatrixWorldPass | undefined;
117
- projection: SceneRenderProjection | undefined;
118
- autoBatch: AutoBatch | undefined;
119
- cameraCull: RenderCameraCull | undefined;
120
- entities: Registry | undefined;
121
- scheduler: Scheduler | undefined;
122
- afterPhysicsPhase: IAfterPhysicsPhase | undefined;
123
- frameBudget: FrameBudget | undefined;
124
- interpolation: PhysicsInterpolation | undefined;
125
- geometryCapture: GeometryCapture | undefined;
126
- beforeRenderSnapshots: Array<Array<() => void>>;
127
- beforeRenderDepth: number;
128
- hasDepthCoupledOutput: boolean;
129
- startupGateStarted: boolean;
130
- onStartSceneEntered: (() => void) | undefined;
131
- renderMetricsEnabled: boolean;
132
- uiRevealed: boolean;
133
- started: boolean;
134
- resumeScene: string | undefined;
135
- connectUi(): IUiBridge;
136
- enterScene(scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean;
137
- goto(name: string, ctx: ICtx<TState, TPhysics>): Promise<void>;
138
- postUiStartup(): void;
139
- teardown(ctx?: ICtx<TState, TPhysics>): void;
140
- warmUpConfiguredExplicitly(): boolean;
141
- warmUpOptions(): IWarmUpOptions;
142
- }
143
69
 
144
70
  /** The frame loop, and the instruments that only exist while it runs. */
145
71
  export interface IGameFrameLoop {
146
- /** Stops the loop, where `#teardown` always stopped it. Its frame budget is `game.frameBudget`. */
147
- readonly dispose: PluginCleanup;
148
72
  readonly geometryCapture: GeometryCapture;
149
73
  readonly loop: FixedStepLoop;
150
74
  }
@@ -363,6 +287,12 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
363
287
  },
364
288
  });
365
289
  game.frameBudget = frameBudget;
290
+ // Built after the presentation hold goes up: until the reveal (`markRevealed` in game-startup),
291
+ // a window spans startup work, so it must not alert as a hot call in play. A startup that already
292
+ // settled has revealed, and its frames are play.
293
+ if (!startup.projectionSettled) frameBudget?.markCovered();
294
+ // The loop that reports into it stops first: `startScenes` pushes the loop's stop after this.
295
+ if (frameBudget !== undefined) game.cleanup.push(() => frameBudget.dispose());
366
296
  // Per-pass draws and triangles ride the frame budget's window by default. The same property
367
297
  // that makes `info.render` an aggregate — one reset per frame before the world render, and
368
298
  // nested shadow/reflection renders sharing that counter — is what this recorder unwinds.
@@ -588,11 +518,17 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
588
518
  game.beforeRenderDepth -= 1;
589
519
  }
590
520
  }
521
+ // A game is free to tick its rigs here instead of in the update stage (the skinned crowd does,
522
+ // to time its own spans); whatever it queued is advanced before the draw, not a frame after it.
523
+ flushAnimationTicks();
591
524
  interpolation.render(gameLoop.clockFrozen || game.paused ? 1 : alpha, () => {
592
525
  // Let a depth-coupled scene update its output node while the scene pass is still the
593
526
  // next render. Ordinary scenes keep the historical hook order and timing.
594
527
  const depthCoupledOutput = game.hasDepthCoupledOutput;
595
528
  if (depthCoupledOutput && game.sceneEntered) game.scene?.render(ctx);
529
+ // A depth-coupled scene may have ticked a rig while the scene pass was still the next
530
+ // render; it is drawn this frame, not the next.
531
+ if (depthCoupledOutput) flushAnimationTicks();
596
532
  // The engine's own walk owns the frame's world matrices, so the count starts here and
597
533
  // covers both applications below: the authored scene the projection reconciles from and
598
534
  // the root the renderer is actually handed.
@@ -648,6 +584,8 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
648
584
  // Added, not bracketed: the render call sits between the apply and the restore, and a
649
585
  // span that contained it would report the world pass as cull work.
650
586
  if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullApplyStart);
587
+ // The previous frame's capture, when the host drew that frame after its callback.
588
+ geometryCapture.settleDeferred();
651
589
  const capturing = geometryCapture.armed();
652
590
  if (capturing) {
653
591
  // The mirror is what the renderer sees; arming the authored scene would attribute the
@@ -677,7 +615,7 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
677
615
  if (scaler !== undefined) renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
678
616
  }
679
617
  const engineStart = readStages === undefined ? 0 : budgetNow();
680
- renderer.render(renderRoot, camera);
618
+ drawWorld(() => renderer.render(renderRoot, camera));
681
619
  const engineEnd = readStages === undefined ? 0 : budgetNow();
682
620
  startup.renders += 1;
683
621
  // Count declined frames without treating them as drawn-frame render cost.
@@ -716,7 +654,12 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
716
654
  if (worldPasses !== undefined && worldPasses.length > 0)
717
655
  frameBudget?.addRenderPasses(worldPasses);
718
656
  // After the passes are read, so the rows reconcile against this frame's own totals.
719
- if (capturing) geometryCapture.finishFrame(worldPasses ?? []);
657
+ if (capturing)
658
+ geometryCapture.finishFrame(worldPasses ?? [], {
659
+ drawsAfterFrame:
660
+ (renderer.raw as { drawsAfterFrame?: unknown } | undefined)?.drawsAfterFrame ===
661
+ true,
662
+ });
720
663
  // Resolve the GPU timestamps every frame, not once per reported window.
721
664
  //
722
665
  // `trackTimestamp` spends two queries per render pass, and three's pool holds 2048.
@@ -780,6 +723,14 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
780
723
  // fresh or not.
781
724
  renderer.noteGpuMainMs?.(gpuFrame.main, gpuFrame.frame);
782
725
  } else {
726
+ // A renderer the pass recorder cannot instrument (the owned engine) may time its own
727
+ // passes; its split rides on the sample, so `TN_FRAME_BUDGET` names the pass that costs.
728
+ if (gpuSample?.main !== undefined)
729
+ frameBudget?.addGpuBucketMs({
730
+ main: gpuSample.main,
731
+ shadow: gpuSample.shadow,
732
+ other: gpuSample.other,
733
+ });
783
734
  renderer.noteGpuMainMs?.(undefined);
784
735
  }
785
736
  if (!depthCoupledOutput && game.sceneEntered) game.scene?.render(ctx);
@@ -921,6 +872,9 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
921
872
  else scene.update(ctx, dt);
922
873
  startup.updates += 1;
923
874
  }
875
+ // A scene swap mid-update leaves rigs queued; they are advanced with the frame they belong to,
876
+ // before this early return can skip the flush and let the next frame's ticks pile on top of them.
877
+ flushAnimationTicks();
924
878
  if (game.scene !== scene || game.sceneFrame !== frame) return;
925
879
  for (const plugin of game.activePlugins) {
926
880
  if (debug && plugin.update !== undefined)
@@ -934,6 +888,13 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
934
888
  }
935
889
  if (debug) measureDebug("entities", "update", "Registry.sweep", () => game.entities?.sweep());
936
890
  else game.entities?.sweep();
891
+ // PRD-828: every rig the frame's update queued is advanced in one crossing, at the end of the
892
+ // update stage — after the game's own per-rig loops and before anything reads a pose.
893
+ if (debug)
894
+ measureDebug("animationTickBatch", "update", "flushAnimationTicks", () =>
895
+ flushAnimationTicks(),
896
+ );
897
+ else flushAnimationTicks();
937
898
  if (game.renderer !== undefined && game.sceneEntered) {
938
899
  if (debug)
939
900
  measureDebug(
@@ -952,6 +913,8 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
952
913
  // of 13 launches). Not a reset either: a GPU-bound world under the cover declines every other
953
914
  // frame, and a reset held every Hop launch to the 10 s window bound.
954
915
  onFrame: (frameMs) => {
916
+ // Slices streaming in after the reveal run once per frame, in the headroom this frame left.
917
+ noteSliceFrame(frameMs, heldTargetFps, startup.worldRendered && !startupCoverActive());
955
918
  const skips = rendererFrameGateSkips(renderer.raw);
956
919
  const declined = skips !== undefined && skips > readinessGateSkips;
957
920
  if (skips !== undefined) readinessGateSkips = skips;
@@ -986,9 +949,9 @@ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>
986
949
  step: game.config.step,
987
950
  });
988
951
  loopState.current = gameLoop;
952
+ game.cleanup.push(endSliceFrames);
989
953
 
990
954
  return {
991
- dispose: () => gameLoop.stop(),
992
955
  geometryCapture,
993
956
  loop: gameLoop,
994
957
  };