@threenative/core 0.3.12 → 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 (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  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-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  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 +289 -1034
  20. package/dist/index.js +3096 -1305
  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-BYqKGAwo.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 +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
package/src/renderer.ts CHANGED
@@ -43,6 +43,7 @@ import {
43
43
  } from "./render/chain.js";
44
44
  import { type IResolutionSubrect, ResolutionSubrect } from "./render/resolution-subrect.js";
45
45
 
46
+ import { GPU_STALE_FRAME_LIMIT, GpuReadings } from "./gpu-readings.js";
46
47
  import type { IStartupImageState } from "./startup-readiness.js";
47
48
  import {
48
49
  type IStorageBufferLease,
@@ -155,6 +156,22 @@ export function prewarm(object: Object3D | readonly Object3D[]): void {
155
156
  }
156
157
  }
157
158
 
159
+ /** Where one resolved frame's GPU time went, when the renderer times its own passes (the owned engine). */
160
+ export interface IGpuFrameSplit {
161
+ /** The scene (main colour) pass. */
162
+ readonly main: number;
163
+ /** Every shadow map the frame drew: the sun's and the lamps'. */
164
+ readonly shadow: number;
165
+ /** Everything else: post chain, output, global illumination gather. */
166
+ readonly other: number;
167
+ }
168
+
169
+ /** One resolved GPU frame: its duration, the Three.js frame id it belongs to, and its pass split when known. */
170
+ export interface IGpuFrameSample extends Partial<IGpuFrameSplit> {
171
+ readonly frame: number;
172
+ readonly ms: number;
173
+ }
174
+
158
175
  export interface IRendererLike {
159
176
  readonly domElement: HTMLCanvasElement;
160
177
  readonly kind: RendererKind;
@@ -375,7 +392,7 @@ export interface IRendererLike {
375
392
  * resolve twice. Optional like `gpuFrameAge`, for stubs that implement only the drawing
376
393
  * contract. `createRenderer` always provides it.
377
394
  */
378
- gpuFrameSample?(): { readonly frame: number; readonly ms: number } | undefined;
395
+ gpuFrameSample?(): IGpuFrameSample | undefined;
379
396
  /**
380
397
  * Observes complete allocated render-query groups without changing ordinary sampling.
381
398
  * Frame IDs are Three query IDs, including any overlay draws; callers map world callbacks.
@@ -735,7 +752,7 @@ function wrapRenderer(
735
752
  */
736
753
  const currentFrame = (): number | undefined =>
737
754
  timestampFrame >= 0 ? timestampFrame : raw.info?.frame;
738
- const gpuFrameSample = (): { frame: number; ms: number } | undefined => {
755
+ const gpuFrameSample = (): IGpuFrameSample | undefined => {
739
756
  const frame = currentFrame();
740
757
  const frames = raw.backend?.getTimestampFrames?.("render");
741
758
  const sampled = frames?.[frames.length - 1];
@@ -752,7 +769,19 @@ function wrapRenderer(
752
769
  timestamp <= 0
753
770
  )
754
771
  return undefined;
755
- return { frame: sampled, ms: timestamp };
772
+ // The owned engine times its own passes (`info.engine.gpuSplit`); the split joins the sample
773
+ // only while it describes that same frame.
774
+ const split = (
775
+ raw.info as { engine?: { gpuSplit?: IGpuFrameSplit & { frame: number } } } | undefined
776
+ )?.engine?.gpuSplit;
777
+ if (split?.frame !== sampled) return { frame: sampled, ms: timestamp };
778
+ return {
779
+ frame: sampled,
780
+ ms: timestamp,
781
+ main: split.main,
782
+ shadow: split.shadow,
783
+ other: split.other,
784
+ };
756
785
  };
757
786
 
758
787
  /**
@@ -768,6 +797,20 @@ function wrapRenderer(
768
797
  };
769
798
 
770
799
  let renderingFrame = 0;
800
+ // three's `compileAsync` runs a viewport texture's `updateBefore`, which copies the framebuffer from
801
+ // a render context the compile never bound to a target, so the backend reads the canvas
802
+ // (rgba8unorm) into the scene copy (rgba16float) and logs a format error per refracting material.
803
+ // A compile draws no pixels: the copy it triggers outside a real frame is skipped, and a frame the
804
+ // compile yields to still copies.
805
+ const copyingBackend = raw.backend as
806
+ | { copyFramebufferToTexture?: (...args: unknown[]) => unknown }
807
+ | undefined;
808
+ const stockFramebufferCopy = copyingBackend?.copyFramebufferToTexture;
809
+ if (copyingBackend !== undefined && typeof stockFramebufferCopy === "function")
810
+ copyingBackend.copyFramebufferToTexture = (...args: unknown[]) =>
811
+ activeCompiles > 0 && renderingFrame === 0
812
+ ? undefined
813
+ : stockFramebufferCopy.apply(copyingBackend, args);
771
814
  let temporalUpscaleActive = false;
772
815
  const renderFrame = (scene: Object3D, camera: Camera): void => {
773
816
  const temporal = wrapped.temporalUpscale?.() === true;
@@ -834,32 +877,13 @@ function wrapRenderer(
834
877
  }
835
878
  };
836
879
  // The main pass's own GPU series, fed a frame at a time by `game.ts` because only the pass
837
- // recorder can attribute the render pool to its main call. Half/half smoothing, and a short
838
- // freshness window: the adaptive LOD loop reads this every half second and must not act on a
839
- // resolve that stopped landing.
840
- const mainSmoothing = 0.5;
841
- const mainStaleLimit = 8;
842
- let gpuMainEma: number | undefined;
880
+ // recorder can attribute the render pool to its main call. Half/half smoothing, and the engine's
881
+ // stale limit: the adaptive LOD loop reads this every half second and must not act on a resolve
882
+ // that stopped landing.
883
+ const mainReadings = new GpuReadings({ smoothing: 0.5, staleLimit: GPU_STALE_FRAME_LIMIT });
843
884
  let targetFps: number | undefined;
844
- let gpuMainStaleFrames = 0;
845
- let gpuMainLastFrame: number | undefined;
846
885
  const noteGpuMainMs = (ms: number | undefined, frame?: number): void => {
847
- const stale = (): void => {
848
- gpuMainStaleFrames += 1;
849
- if (gpuMainStaleFrames >= mainStaleLimit) gpuMainEma = undefined;
850
- };
851
- if (ms === undefined || !Number.isFinite(ms) || ms < 0) {
852
- stale();
853
- return;
854
- }
855
- // A repeated frame id is the previous resolve still in flight, not a new reading.
856
- if (frame !== undefined && frame === gpuMainLastFrame) {
857
- stale();
858
- return;
859
- }
860
- if (frame !== undefined) gpuMainLastFrame = frame;
861
- gpuMainStaleFrames = 0;
862
- gpuMainEma = gpuMainEma === undefined ? ms : gpuMainEma + (ms - gpuMainEma) * mainSmoothing;
886
+ mainReadings.note(ms, frame);
863
887
  };
864
888
  const wrapped: IRendererLike = {
865
889
  get compileCount() {
@@ -1051,7 +1075,7 @@ function wrapRenderer(
1051
1075
  );
1052
1076
  return gpuObservation;
1053
1077
  },
1054
- gpuMainMs: () => gpuMainEma,
1078
+ gpuMainMs: () => mainReadings.ema,
1055
1079
  noteGpuMainMs,
1056
1080
  targetFps: () => targetFps,
1057
1081
  noteTargetFps: (fps: number) => {
@@ -15,6 +15,7 @@
15
15
  */
16
16
 
17
17
  import type { GpuClass } from "./gpu-class.js";
18
+ import { GPU_READING_MAX_AGE_FRAMES, GPU_WINDOW_MIN_SAMPLES } from "./gpu-readings.js";
18
19
 
19
20
  /** How the active scale was arrived at, reported beside every fps number. */
20
21
  export type ScaleSource = "pinned" | "auto" | "auto-pinned";
@@ -104,9 +105,9 @@ export const RESOLUTION_SCALER = {
104
105
  downWindows: 1,
105
106
  upWindows: 4,
106
107
  /** Eight frames for the sampled GPU reading plus eight for asynchronous query resolution. */
107
- maxGpuAgeFrames: 16,
108
+ maxGpuAgeFrames: GPU_READING_MAX_AGE_FRAMES,
108
109
  /** Window GPU samples that make the window's own median fresh evidence; see `IScalerWindow.gpu`. */
109
- minWindowGpuSamples: 4,
110
+ minWindowGpuSamples: GPU_WINDOW_MIN_SAMPLES,
110
111
  /** The resize frame is itself a hitch and must never feed the controller. */
111
112
  cooldownWindows: 1,
112
113
  /** Continuous sub-rectangle changes are separated by this many rendered frames. */
@@ -0,0 +1,61 @@
1
+ /**
2
+ * What a scene entry checks, in one ordered list.
3
+ *
4
+ * Every audit a scene entry runs used to be welded into `Game.#enterScene` — the opacity
5
+ * convention, the render trap audit, the unlit foliage warning — so a fourth one meant editing the
6
+ * lifecycle file that every other feature already edits. A kit or a game can add its own here, and
7
+ * the order the list states is the order the warnings appear in.
8
+ *
9
+ * Nothing here decides how anything looks: each inspector reads the scene the game just entered and
10
+ * returns what a reader should be told about it.
11
+ */
12
+ import type { Object3D } from "three";
13
+ import { applyOpacityConvention } from "./profiling/opacity-convention.js";
14
+ import { renderTrapAudit } from "./profiling/render-trap-audit.js";
15
+ import {
16
+ UNLIT_FOLIAGE_FIX,
17
+ formatUnlitFoliageWarning,
18
+ unlitFoliageWarning,
19
+ } from "./profiling/unlit-foliage-warning.js";
20
+
21
+ /** One line a scene entry reports, and the console level it belongs at. */
22
+ export interface ISceneEntryFinding {
23
+ readonly level: "error" | "warn";
24
+ readonly line: string;
25
+ }
26
+
27
+ /** A check that runs once per scene entry, after the game's `enter()` has built the scene. */
28
+ export type SceneEntryInspector = (scene: Object3D) => readonly ISceneEntryFinding[];
29
+
30
+ /**
31
+ * The engine's own inspectors, in the order their findings must appear.
32
+ *
33
+ * The opacity convention runs first: it makes an author's opacity take effect, and the render trap
34
+ * audit then reports what that effect is — the other order reports the state before the convention.
35
+ */
36
+ export const SCENE_ENTRY_INSPECTORS: readonly SceneEntryInspector[] = [
37
+ (scene) => {
38
+ const line = applyOpacityConvention(scene);
39
+ return line === undefined ? [] : [{ level: "warn", line }];
40
+ },
41
+ (scene) => renderTrapAudit(scene).map((line) => ({ level: "error", line })),
42
+ (scene) => {
43
+ const warning = unlitFoliageWarning(scene);
44
+ return warning === undefined
45
+ ? []
46
+ : [{ level: "warn", line: `${formatUnlitFoliageWarning(warning)} ${UNLIT_FOLIAGE_FIX}` }];
47
+ },
48
+ ];
49
+
50
+ /** Runs every inspector against a scene the game has just entered, reporting each finding once. */
51
+ export function inspectSceneEntry(
52
+ scene: Object3D,
53
+ inspectors: readonly SceneEntryInspector[] = SCENE_ENTRY_INSPECTORS,
54
+ ): void {
55
+ for (const inspector of inspectors) {
56
+ for (const finding of inspector(scene)) {
57
+ if (finding.level === "error") console.error(finding.line);
58
+ else console.warn(finding.line);
59
+ }
60
+ }
61
+ }
package/src/snow-field.ts CHANGED
@@ -213,6 +213,7 @@ export function snowDiscFootprint(
213
213
  * recovery. It is a heightfield approximation — not granular snow, displaced-volume
214
214
  * conservation, avalanches, melting or a calibrated material law.
215
215
  * @situation leave footprints, tracks and tyre ruts in snow that persist and fill in over time
216
+ * @situation let a fresh snowfall slowly fill older tracks back in as the field recovers
216
217
  * @situation let a pushed sphere carve a connected track and a dropped one settle into a crater
217
218
  * @situation store snow deformation that rendered geometry and collision both read
218
219
  * @situation reset a snowfield between rounds or change its depth at runtime
@@ -166,3 +166,81 @@ export function measureStartupOffscreenBytes(
166
166
  warn: offscreenBytes > visibleBytes,
167
167
  };
168
168
  }
169
+
170
+ export const ASSET_UNUSED_MARKER = "TN_ASSET_UNUSED";
171
+
172
+ /**
173
+ * When to look: long enough for a game to build what its first minute needs, short enough that a
174
+ * playtest sees it. Not a game constant — the report states it, and a model the game builds later
175
+ * than this is still a launch wait to move, so the advice holds either way.
176
+ */
177
+ export const ASSET_UNUSED_AFTER_MS = 60_000;
178
+
179
+ export const ASSET_UNUSED_FIX =
180
+ "Nothing in the scene came from these models, which the reveal waited for. If nothing ever " +
181
+ "builds one, delete its load; if the game builds it later, ctx.assets.prefetch it after the " +
182
+ "reveal and load it then.";
183
+
184
+ /** Models the reveal waited for that no scene object came from, `sinceRevealMs` after the reveal. */
185
+ export interface IUnusedModels {
186
+ readonly bytes: number;
187
+ readonly files: readonly { readonly bytes: number; readonly path: string }[];
188
+ readonly fix: string;
189
+ readonly sinceRevealMs: number;
190
+ }
191
+
192
+ /**
193
+ * Which awaited models have no stamped object or geometry anywhere under `root`, hidden nodes
194
+ * included: a hidden hull is in use, a model nothing ever cloned is dead weight. `undefined` when
195
+ * every awaited model is in the scene. One stamp walk, no bounds and no frustum.
196
+ */
197
+ export function measureUnusedModels(
198
+ resolved: ReadonlyMap<string, IResolvedAsset>,
199
+ root: Object3D,
200
+ sinceRevealMs: number,
201
+ ): IUnusedModels | undefined {
202
+ const present = unbilled(() => {
203
+ const paths = new Set<string>();
204
+ root.traverse((object) => {
205
+ const geometry = (object as Object3D & { geometry?: { userData?: unknown } }).geometry;
206
+ for (const path of [stampOf(object.userData), stampOf(geometry?.userData)])
207
+ if (path !== undefined) paths.add(path);
208
+ });
209
+ return paths;
210
+ });
211
+ const files = [...resolved]
212
+ .filter(([path, asset]) => asset.kind === "model" && !present.has(path))
213
+ .map(([path, asset]) => ({ bytes: asset.bytes ?? 0, path }))
214
+ .sort((a, b) => b.bytes - a.bytes);
215
+ if (files.length === 0) return undefined;
216
+ return {
217
+ bytes: files.reduce((sum, file) => sum + file.bytes, 0),
218
+ files,
219
+ fix: ASSET_UNUSED_FIX,
220
+ sinceRevealMs,
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Report `TN_ASSET_UNUSED` once, `ASSET_UNUSED_AFTER_MS` after the reveal: the awaited models no
226
+ * scene object came from — a load the launch paid for that nothing drew (Midway paid 22.9 MB for
227
+ * three). Measurement only: a throw costs the report, never the game. Returns the cancel.
228
+ */
229
+ export function reportUnusedModelsLater(
230
+ awaited: ReadonlyMap<string, IResolvedAsset>,
231
+ root: Object3D,
232
+ gone: () => boolean,
233
+ ): () => void {
234
+ const timer = setTimeout(() => {
235
+ if (gone()) return;
236
+ try {
237
+ const unused = measureUnusedModels(awaited, root, ASSET_UNUSED_AFTER_MS);
238
+ if (unused !== undefined) console.warn(`${ASSET_UNUSED_MARKER}:${JSON.stringify(unused)}`);
239
+ } catch (error) {
240
+ console.warn(
241
+ `${ASSET_UNUSED_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`,
242
+ );
243
+ }
244
+ }, ASSET_UNUSED_AFTER_MS);
245
+ return () => clearTimeout(timer);
246
+ }
@@ -16,7 +16,7 @@
16
16
  * **Staticness is authored, never guessed.** A heuristic that decides an object has "not moved in
17
17
  * 60 frames" is a correctness bug with no reproduction, so nothing here watches gameplay. What the
18
18
  * engine does do is check the promise where it is cheap to check it: the root's own local transform
19
- * is compared against what was frozen, once per frame, and a root the author moved thaws and
19
+ * and its parent's world matrix are compared against what was frozen, once per frame, and a root the author moved thaws and
20
20
  * refreezes itself. That is O(static roots), not O(objects), and it turns the most common way to
21
21
  * get this wrong into a non-event. Writes deeper inside a frozen subtree are the author's to
22
22
  * announce with `invalidateStatic`, and `TN_RENDERLIST_VALIDATE=1` is what proves they did.
@@ -47,7 +47,9 @@ interface IFrozenRoot {
47
47
  */
48
48
  const frozen = new Map<Object3D, IFrozenRoot>();
49
49
 
50
- const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16;
50
+ /** Position, quaternion, scale, local matrix, then the parent's world matrix (identity with none). */
51
+ const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16 + 16;
52
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
51
53
 
52
54
  function writeSnapshot(root: Object3D, into: Float64Array): void {
53
55
  const position: Vector3 = root.position;
@@ -66,6 +68,12 @@ function writeSnapshot(root: Object3D, into: Float64Array): void {
66
68
  into[9] = scale.z;
67
69
  for (let element = 0; element < 16; element += 1)
68
70
  into[10 + element] = matrix.elements[element] ?? 0;
71
+ // The frozen world matrix is the parent's times the root's own, so a root attached after it froze,
72
+ // or one whose ancestor moved, is as stale as one the author moved. A streamed world freezes each
73
+ // draw before it joins the world root, and a seated world (`world.position.y = -ground`) drew
74
+ // every tree at the package's absolute height.
75
+ const parent = root.parent?.matrixWorld.elements ?? IDENTITY;
76
+ for (let element = 0; element < 16; element += 1) into[26 + element] = parent[element] ?? 0;
69
77
  }
70
78
 
71
79
  function snapshotMatches(root: Object3D, snapshot: Float64Array, scratch: Float64Array): boolean {
@@ -122,6 +130,15 @@ export function worldSilencedByFreeze(object: Object3D): boolean {
122
130
  return worldSilenced.has(object);
123
131
  }
124
132
 
133
+ /** Gives a frozen subtree its compose flags back, so the next update recomposes it. */
134
+ function thaw(root: Object3D): void {
135
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
136
+ root.traverse((child) => {
137
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
138
+ child.matrixWorldNeedsUpdate = true;
139
+ });
140
+ }
141
+
125
142
  /** Freezes the subtree in place and answers how many objects stopped recomposing. */
126
143
  function freeze(root: Object3D): number {
127
144
  root.updateMatrixWorld(true);
@@ -150,8 +167,11 @@ function freeze(root: Object3D): number {
150
167
  * `invalidateStatic` does and the reason a generator can emit the call unconditionally.
151
168
  */
152
169
  export function markStatic(root: Object3D): number {
153
- const objects = freeze(root);
154
170
  const existing = frozen.get(root);
171
+ // A second mark re-arms: thaw first, or `freeze`'s update skips the root's own world compose (the
172
+ // first freeze turned it off) and the subtree keeps the world matrix of its first parent.
173
+ if (existing !== undefined) thaw(root);
174
+ const objects = freeze(root);
155
175
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
156
176
  writeSnapshot(root, snapshot);
157
177
  const version = (existing?.version ?? 0) + 1;
@@ -186,17 +206,8 @@ export function unmarkStatic(root: Object3D): void {
186
206
  export function invalidateStatic(object: Object3D): number | undefined {
187
207
  let node: Object3D | null = object;
188
208
  while (node !== null) {
189
- if (frozen.has(node)) {
190
- // Thaw the flags first: `freeze` starts with a forced update, and an object left with
191
- // `matrixAutoUpdate` off would recompose its world matrix from a stale local one.
192
- const root = node;
193
- root.traverse((child) => {
194
- if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
195
- child.matrixWorldNeedsUpdate = true;
196
- });
197
- if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
198
- return markStatic(root);
199
- }
209
+ // `markStatic` thaws a frozen root before it freezes it again.
210
+ if (frozen.has(node)) return markStatic(node);
200
211
  node = node.parent;
201
212
  }
202
213
  return undefined;
@@ -244,11 +255,6 @@ export function refreshStaticTransforms(): void {
244
255
  if (frozen.size === 0) return;
245
256
  for (const entry of frozen.values()) {
246
257
  if (snapshotMatches(entry.root, entry.snapshot, scratch)) continue;
247
- if (worldSilenced.delete(entry.root)) entry.root.matrixWorldAutoUpdate = true;
248
- entry.root.traverse((child) => {
249
- if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
250
- child.matrixWorldNeedsUpdate = true;
251
- });
252
258
  markStatic(entry.root);
253
259
  rearmedSinceCensus += 1;
254
260
  }
@@ -0,0 +1,112 @@
1
+ import type { Mesh } from "three";
2
+
3
+ /** The material texture slots a model's images reach (glTF's own, plus the physical extensions). */
4
+ const TEXTURE_SLOTS = [
5
+ "map",
6
+ "normalMap",
7
+ "roughnessMap",
8
+ "metalnessMap",
9
+ "aoMap",
10
+ "emissiveMap",
11
+ "alphaMap",
12
+ "bumpMap",
13
+ "lightMap",
14
+ "displacementMap",
15
+ "clearcoatMap",
16
+ "clearcoatNormalMap",
17
+ "clearcoatRoughnessMap",
18
+ "sheenColorMap",
19
+ "sheenRoughnessMap",
20
+ "transmissionMap",
21
+ "thicknessMap",
22
+ "iridescenceMap",
23
+ "specularColorMap",
24
+ "specularIntensityMap",
25
+ ] as const;
26
+
27
+ type SlottedMaterial = Record<string, unknown> & { needsUpdate?: boolean };
28
+
29
+ type Releasable = { dispose?: () => void };
30
+
31
+ /** Texture state a game sets after load (sampler, transform, tags); the whole file keeps it. */
32
+ const CARRIED = [
33
+ "anisotropy",
34
+ "wrapS",
35
+ "wrapT",
36
+ "magFilter",
37
+ "minFilter",
38
+ "colorSpace",
39
+ "channel",
40
+ "rotation",
41
+ "matrixAutoUpdate",
42
+ "userData",
43
+ ] as const;
44
+ const CARRIED_VECTORS = ["offset", "repeat", "center", "matrix"] as const;
45
+
46
+ /** Gives `next` what the game set on `from`, so the swap changes the mips and nothing else. */
47
+ function carry(from: Record<string, unknown>, next: Record<string, unknown>): void {
48
+ for (const name of CARRIED) if (name in from) next[name] = from[name];
49
+ for (const name of CARRIED_VECTORS)
50
+ (next[name] as { copy?: (value: unknown) => void } | undefined)?.copy?.(from[name]);
51
+ }
52
+
53
+ const materialsOf = (mesh: Mesh | undefined): SlottedMaterial[] =>
54
+ ([] as unknown[]).concat(mesh?.material).filter(Boolean) as SlottedMaterial[];
55
+
56
+ /**
57
+ * PRD-860 Phase 2: the coarse model drew with each texture's resident mips; the full model parses
58
+ * with the whole files. Call this at the coarse load: it records the textures the coarse model
59
+ * brought. The returned function takes the full model's meshes when they land and puts the whole
60
+ * texture in every slot that still holds a recorded one, on whatever material the mesh has now, so a
61
+ * clone of the material takes it too while a texture or material the game set meanwhile stays. The
62
+ * whole texture takes what the game set on the resident one (anisotropy, wrap, transform). It
63
+ * releases the replaced resident textures and every full-model texture nothing took. With
64
+ * `swap: false` (no resident mips were served, so the coarse textures are already whole) it only
65
+ * releases the full model's copies. Returns how many slots swapped.
66
+ */
67
+ export function streamedTextureUpgrade(
68
+ coarse: readonly Mesh[],
69
+ ): (full: readonly Mesh[], swap: boolean) => number {
70
+ const loaded = coarse.map((mesh) =>
71
+ materialsOf(mesh).map((material) => TEXTURE_SLOTS.map((name) => material[name])),
72
+ );
73
+ return (full, swap) => {
74
+ const whole = new Map<Releasable, Releasable>();
75
+ const unused = new Set<Releasable>();
76
+ full.forEach((mesh, index) =>
77
+ materialsOf(mesh).forEach((material, slot) =>
78
+ TEXTURE_SLOTS.forEach((name, at) => {
79
+ const next = material[name] as Releasable | null | undefined;
80
+ const resident = loaded[index]?.[slot]?.[at] as Releasable | null | undefined;
81
+ if (!next || next === resident) return;
82
+ if (swap && resident) whole.set(resident, next);
83
+ else unused.add(next);
84
+ }),
85
+ ),
86
+ );
87
+ const replaced = new Set<Releasable>();
88
+ const taken = new Set<Releasable>();
89
+ let swapped = 0;
90
+ for (const mesh of whole.size > 0 ? coarse : [])
91
+ for (const material of materialsOf(mesh)) {
92
+ let changed = false;
93
+ for (const name of TEXTURE_SLOTS) {
94
+ const resident = material[name] as Releasable | null | undefined;
95
+ const next = resident ? whole.get(resident) : undefined;
96
+ if (resident === null || resident === undefined || next === undefined) continue;
97
+ if (!taken.has(next))
98
+ carry(resident as Record<string, unknown>, next as Record<string, unknown>);
99
+ material[name] = next;
100
+ replaced.add(resident);
101
+ taken.add(next);
102
+ swapped += 1;
103
+ changed = true;
104
+ }
105
+ if (changed) material.needsUpdate = true;
106
+ }
107
+ for (const next of whole.values()) unused.add(next);
108
+ for (const texture of replaced) texture.dispose?.();
109
+ for (const texture of unused) if (!taken.has(texture)) texture.dispose?.();
110
+ return swapped;
111
+ };
112
+ }
package/src/streaming.ts CHANGED
@@ -133,6 +133,65 @@ export const DEFAULT_CONCURRENCY = 6;
133
133
 
134
134
  const now = (): number => globalThis.performance?.now() ?? Date.now();
135
135
 
136
+ /** Kept back from a frame's headroom for the browser's own commit and the GPU process. */
137
+ const SLICE_FRAME_MARGIN_MS = 2;
138
+ /** A slice always gets this much, so a frame with no headroom still moves the list. */
139
+ const MIN_SLICE_BUDGET_MS = 1;
140
+ /** A loop that stops presenting (a hidden tab) must not stall a run: fall back to the host. */
141
+ const LOOP_FRAME_WAIT_MS = 250;
142
+
143
+ /**
144
+ * The game loop's frame pulse, for slices that run once the world is on screen.
145
+ *
146
+ * In Chrome a `scheduler.yield` continuation runs ahead of rendering, so a chain of 8 ms slices
147
+ * presents no frame until the scheduler's ~100 ms starvation guard fires. That is harmless behind
148
+ * a loading curtain and a 10 fps stutter in front of the player: Midway streaming its cockpit
149
+ * after the reveal read a 102 ms host gap at p95, against 9 ms with nothing streaming. So once
150
+ * the loop says the world is visible, a slice waits for the loop's next frame, then for one host
151
+ * yield so it runs after that frame commits, and spends only the headroom the frame left.
152
+ */
153
+ const loopFrames = {
154
+ visible: false,
155
+ budgetMs: DEFAULT_SLICE_BUDGET_MS,
156
+ waiters: [] as Array<() => void>,
157
+ };
158
+
159
+ /**
160
+ * Called by the frame loop after every frame callback: its wall time, the target rate and
161
+ * whether the world is on screen.
162
+ *
163
+ * @internal Shared with `game-frame-loop.ts`; not part of the public surface.
164
+ */
165
+ export function noteSliceFrame(frameMs: number, targetFps: number, visible: boolean): void {
166
+ loopFrames.visible = visible;
167
+ loopFrames.budgetMs =
168
+ targetFps > 0
169
+ ? Math.min(
170
+ DEFAULT_SLICE_BUDGET_MS,
171
+ Math.max(MIN_SLICE_BUDGET_MS, 1_000 / targetFps - frameMs - SLICE_FRAME_MARGIN_MS),
172
+ )
173
+ : DEFAULT_SLICE_BUDGET_MS;
174
+ for (const resolve of loopFrames.waiters.splice(0)) resolve();
175
+ }
176
+
177
+ /** The loop stopped: release every waiting slice and go back to the host yield. @internal */
178
+ export function endSliceFrames(): void {
179
+ noteSliceFrame(0, 0, false);
180
+ }
181
+
182
+ const nextLoopFrame = (): Promise<void> =>
183
+ new Promise<void>((resolve) => {
184
+ const timer = setTimeout(resolve, LOOP_FRAME_WAIT_MS);
185
+ loopFrames.waiters.push(() => {
186
+ clearTimeout(timer);
187
+ resolve();
188
+ });
189
+ }).then(yieldToHost);
190
+
191
+ const yieldSlice = (): Promise<void> => (loopFrames.visible ? nextLoopFrame() : yieldToHost());
192
+ const sliceBudget = (): number =>
193
+ loopFrames.visible ? loopFrames.budgetMs : DEFAULT_SLICE_BUDGET_MS;
194
+
136
195
  function assertWholeAtLeastOne(value: number, name: string, code: string): void {
137
196
  if (!Number.isInteger(value) || value < 1) {
138
197
  throw new Error(
@@ -166,8 +225,10 @@ export async function addInSlices<T>(
166
225
  assertWholeAtLeastOne(sliceSize, "sliceSize", "TN_ADD_SLICES_SLICE_INVALID");
167
226
  }
168
227
  const countSlices = sliceSize !== undefined;
169
- const sliceBudgetMs = countSlices ? undefined : DEFAULT_SLICE_BUDGET_MS;
170
- const yieldFrame = options.yieldFrame ?? yieldToHost;
228
+ // A game's own yield keeps the fixed budget: the frame pulse paces only the engine's yield.
229
+ const nextBudget = options.yieldFrame === undefined ? sliceBudget : () => DEFAULT_SLICE_BUDGET_MS;
230
+ let sliceBudgetMs = countSlices ? undefined : nextBudget();
231
+ const yieldFrame = options.yieldFrame ?? yieldSlice;
171
232
  const shouldContinue = options.while;
172
233
  const startedAt = now();
173
234
 
@@ -189,7 +250,10 @@ export async function addInSlices<T>(
189
250
  if (yieldAfter) {
190
251
  await yieldFrame();
191
252
  // The presented frame is not part of the next slice's work.
192
- if (sliceBudgetMs !== undefined) sliceStartedAt = now();
253
+ if (sliceBudgetMs !== undefined) {
254
+ sliceBudgetMs = nextBudget();
255
+ sliceStartedAt = now();
256
+ }
193
257
  }
194
258
  };
195
259
 
@@ -197,7 +261,7 @@ export async function addInSlices<T>(
197
261
  const sliceSpent = (): boolean =>
198
262
  sliceSize !== undefined
199
263
  ? added % sliceSize === 0
200
- : now() - sliceStartedAt >= DEFAULT_SLICE_BUDGET_MS;
264
+ : now() - sliceStartedAt >= Number(sliceBudgetMs);
201
265
 
202
266
  for (let index = 0; index < total; index += 1) {
203
267
  if (shouldContinue !== undefined && !shouldContinue()) {