@threenative/core 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
package/src/assets.ts CHANGED
@@ -13,9 +13,17 @@ import {
13
13
  type TextureLoader,
14
14
  type Wrapping,
15
15
  } from "three";
16
+ import {
17
+ type AssetPriority,
18
+ type IAssetCacheReport,
19
+ PRIORITY_ORDER,
20
+ canonicalUrl,
21
+ createAssetCache,
22
+ } from "./asset-cache.js";
16
23
  import { TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin } from "./clustered-mesh.js";
17
24
  import { GEOMETRY_ASSET_KEY } from "./geometry-capture.js";
18
25
  import { DiscreteLodPlugin, type IModelLodPolicy, TN_DISCRETE_LOD } from "./model-lod.js";
26
+ import { countDebug, debugRequested, measureDebug } from "./profiling/debug-telemetry.js";
19
27
 
20
28
  export interface IAssetLoaderOptions {
21
29
  readonly basePath?: string;
@@ -46,6 +54,42 @@ export interface IAssetLoaderOptions {
46
54
  * than silently uploading decoded RGBA.
47
55
  */
48
56
  readonly renderer?: unknown;
57
+ /**
58
+ * Keep compiled asset bytes on disk between visits. On by default where the Cache API exists;
59
+ * `false` is the named override. A native host has no Cache API and reports the cache off with
60
+ * the reason "native host reads installed files", so the native load path is unchanged.
61
+ */
62
+ readonly cache?: boolean;
63
+ /**
64
+ * Download the rest of the manifest after the reveal, at idle priority. On by default;
65
+ * `false` is the named override. It stops by itself when the browser reports
66
+ * `navigator.connection.saveData`.
67
+ */
68
+ readonly backgroundFill?: boolean;
69
+ }
70
+
71
+ /** What one request is worth relative to the rest of the loader's queue. */
72
+ export interface IAssetRequestOptions {
73
+ /**
74
+ * `now` for a file the running scene awaits, `soon` for a prefetch. The loader's own direct
75
+ * calls default to `now`.
76
+ */
77
+ readonly priority?: AssetPriority;
78
+ }
79
+
80
+ /** What a `prefetch` asked for and what the download produced. */
81
+ export interface IAssetPrefetchProgress {
82
+ readonly requested: number;
83
+ readonly requestedBytes: number;
84
+ readonly settled: number;
85
+ /** Bytes served by the load, from disk or network; not a claim that the disk kept them. */
86
+ readonly settledBytes: number;
87
+ }
88
+
89
+ /** The cache report plus the one action a settings screen needs. */
90
+ export interface IAssetCacheState extends IAssetCacheReport {
91
+ /** Delete every byte this release stored, for a "free 1.8 GB" button. */
92
+ clear(): Promise<void>;
49
93
  }
50
94
 
51
95
  /** The structural slice of three's `KTX2Loader` core depends on. */
@@ -78,7 +122,27 @@ export interface ICompressedTextureSupport {
78
122
  export type AssetSource = "manifest" | "source";
79
123
 
80
124
  /** Where one settled load's bytes actually came from. */
125
+ /** One downloaded file of a load, with the size the manifest records for it. */
126
+ export interface IResolvedFile {
127
+ readonly bytes: number;
128
+ readonly url: string;
129
+ }
130
+
81
131
  export interface IResolvedAsset {
132
+ /**
133
+ * The manifest's size for this path, set once the load settled and the manifest named one.
134
+ * Absent for a game with no manifest, an external url, or an entry the compile step wrote
135
+ * without a size, so absent means unknown and never zero.
136
+ */
137
+ readonly bytes?: number;
138
+ /**
139
+ * Every sized file the load downloaded: its own output first, then the shared images and
140
+ * lightmaps the manifest lists for it. Set with `bytes`. Two models that share an image list
141
+ * the same url, so a byte total dedupes by url.
142
+ */
143
+ readonly files?: readonly IResolvedFile[];
144
+ /** What the load was asked for; set once the load settled. */
145
+ readonly kind?: AssetKind;
82
146
  readonly url: string;
83
147
  readonly via: AssetSource;
84
148
  }
@@ -116,7 +180,7 @@ function configuredTexture(texture: Texture, options: ITextureOptions): Texture
116
180
 
117
181
  export interface IAssetLoader {
118
182
  readonly compressedTextures?: ICompressedTextureSupport;
119
- model<T = unknown>(path: string): Promise<T>;
183
+ model<T = unknown>(path: string, options?: IAssetRequestOptions): Promise<T>;
120
184
  /**
121
185
  * Load a texture, optionally configured in one call.
122
186
  *
@@ -136,6 +200,23 @@ export interface IAssetLoader {
136
200
  * hard-code a hashed output name, which changes on every rebuild.
137
201
  */
138
202
  resolve(path: string): Promise<readonly string[]>;
203
+ /**
204
+ * What is on disk right now: hits, misses, bytes stored and the whole release's size. A loading
205
+ * view can show "1.2 of 2.0 GB on disk" without new code, and `enabled` is false with a `reason`
206
+ * on a native host or when the game passed `assets.cache: false`.
207
+ */
208
+ readonly cache: IAssetCacheState;
209
+ /**
210
+ * Download the next scene's files to disk at `soon` priority, so its `load()` reads them back
211
+ * without a cold fetch. Stores bytes only: no decode, no GPU memory. Resolves at once on native,
212
+ * where the files are already installed, and reports how many bytes the request served.
213
+ */
214
+ prefetch(paths: readonly string[]): Promise<IAssetPrefetchProgress>;
215
+ /**
216
+ * Start the post-reveal idle fill. The engine calls this when `ctx.startup.whenReady()` settles;
217
+ * a game that drives a loader outside `defineGame` may call it after its own reveal.
218
+ */
219
+ startBackgroundFill(): Promise<void>;
139
220
  /**
140
221
  * How many loads this loader has been asked for and how many have settled (resolved or
141
222
  * rejected). A loading view reads the ratio; the runtime folds it into `ctx.startup.progress`
@@ -172,6 +253,12 @@ export interface IAssetLoader {
172
253
  */
173
254
  readonly resolved: ReadonlyMap<string, IResolvedAsset>;
174
255
  clear(): void;
256
+ /**
257
+ * Final release, called by the game's teardown. Frees the decoder worker pools this loader
258
+ * owns; `clear()` stays reusable because a live game may empty its cache between levels.
259
+ * Idempotent.
260
+ */
261
+ dispose(): void;
175
262
  }
176
263
 
177
264
  /**
@@ -355,6 +442,10 @@ interface IAssetEntry {
355
442
  loaded: boolean;
356
443
  promise: Promise<unknown>;
357
444
  released: boolean;
445
+ /** The most urgent priority any caller asked for; the download starts at it. */
446
+ priority: AssetPriority;
447
+ /** The candidate url the load is downloading, so a later, more urgent caller can promote it. */
448
+ url?: string;
358
449
  value?: unknown;
359
450
  }
360
451
 
@@ -419,17 +510,19 @@ function declaredExtensions(data: ArrayBuffer): ReadonlySet<string> {
419
510
  }
420
511
  }
421
512
 
422
- async function fetchModelBytes(url: string): Promise<ArrayBuffer> {
423
- let response: Response;
513
+ async function fetchModelBytes(
514
+ url: string,
515
+ cache: ReturnType<typeof createAssetCache>,
516
+ expectedBytes: number | undefined,
517
+ priority: AssetPriority,
518
+ ): Promise<ArrayBuffer> {
424
519
  try {
425
- response = await fetch(url);
520
+ return await cache.fetchBytes(url, priority, expectedBytes);
426
521
  } catch (error) {
427
522
  throw new Error(
428
523
  `Failed to load model '${url}': ${error instanceof Error ? error.message : String(error)}.`,
429
524
  );
430
525
  }
431
- if (!response.ok) throw new Error(`Failed to load model '${url}': ${response.status}.`);
432
- return response.arrayBuffer();
433
526
  }
434
527
 
435
528
  /**
@@ -451,17 +544,45 @@ async function fetchModelBytes(url: string): Promise<ArrayBuffer> {
451
544
  * it flipped instead. Both land on the pixels `TextureLoader` would have produced; getting this
452
545
  * wrong turns every standalone texture upside down with no error anywhere.
453
546
  */
454
- async function loadBitmapTexture(url: string, renderer: unknown): Promise<Texture> {
455
- const response = await fetch(url);
456
- if (!response.ok) throw new Error(`Failed to load texture '${url}': ${response.status}.`);
457
- const blob = new Blob([await response.arrayBuffer()]);
547
+ async function loadBitmapTexture(
548
+ url: string,
549
+ renderer: unknown,
550
+ cache: ReturnType<typeof createAssetCache>,
551
+ expectedBytes: number | undefined,
552
+ priority: AssetPriority,
553
+ ): Promise<Texture> {
554
+ let data: ArrayBuffer;
555
+ try {
556
+ data = await cache.fetchBytes(url, priority, expectedBytes);
557
+ } catch (error) {
558
+ throw new Error(
559
+ `Failed to load texture '${url}': ${error instanceof Error ? error.message : String(error)}.`,
560
+ );
561
+ }
562
+ const blob = new Blob([data]);
458
563
  // No renderer means the native host or a bare-node load, both of which flip at upload.
459
564
  const flipsAtUpload =
460
565
  renderer === undefined ||
461
566
  (renderer as { isWebGPURenderer?: boolean }).isWebGPURenderer === true;
462
- const bitmap = await (flipsAtUpload
567
+ const debug = debugRequested();
568
+ const start = debug ? performanceNow() : 0;
569
+ const pending = flipsAtUpload
463
570
  ? createImageBitmap(blob)
464
- : createImageBitmap(blob, { imageOrientation: "flipY" }));
571
+ : createImageBitmap(blob, { imageOrientation: "flipY" });
572
+ if (debug) {
573
+ const elapsed = performanceNow() - start;
574
+ countDebug("textureDecodeDispatchMs", elapsed, "loading", "loadBitmapTexture (all URLs)", "ms");
575
+ countDebug(`textureDecode.${url}DispatchMs`, elapsed, "loading", url, "ms");
576
+ }
577
+ const bitmap = await pending;
578
+ if (debug) {
579
+ const caller = "loadBitmapTexture (all URLs)";
580
+ const elapsed = performanceNow() - start;
581
+ countDebug("textureDecodes", 1, "loading", caller);
582
+ countDebug("textureDecodeBytes", data.byteLength, "loading", caller, "bytes");
583
+ countDebug("textureDecodeWallMs", elapsed, "loading", caller, "async-ms");
584
+ countDebug(`textureDecode.${url}WallMs`, elapsed, "loading", url, "async-ms");
585
+ }
465
586
  const texture = new Texture(bitmap);
466
587
  texture.flipY = flipsAtUpload;
467
588
  texture.needsUpdate = true;
@@ -763,14 +884,69 @@ export function reconcileMirroredClips(root: Object3D, clips: readonly Animation
763
884
  }
764
885
 
765
886
  export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoader {
887
+ const debug = debugRequested();
766
888
  const basePath = options.basePath ?? "";
767
889
  // `assets` is what `@threenative/assets` compiles from unless a project says otherwise, so it is
768
890
  // where an unbaked game's files are. A project that moved its sources passes `sourcePath`.
769
891
  const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/gu, "");
770
892
  const manifestUrl = resolvePath(basePath, options.manifest ?? "assets.manifest.json");
893
+ const assetCache = createAssetCache({
894
+ enabled: options.cache,
895
+ backgroundFill: options.backgroundFill,
896
+ // A different manifest url is a different game on the same origin, and must not delete this
897
+ // one's cache at startup. Two urls of the same page (`/` and `/index.html`) read the same one.
898
+ namespace: canonicalUrl(manifestUrl),
899
+ });
900
+ /** The urls the background fill warms, in manifest order, with the sizes the manifest records. */
901
+ const fillEntries = (manifest: IAssetManifest): readonly { bytes?: number; url: string }[] => {
902
+ const byUrl = new Map<string, { bytes?: number; url: string }>();
903
+ const add = (output: unknown, bytes: unknown): void => {
904
+ // The disk keeps only a file whose size the manifest records, so an unsized one would be
905
+ // downloaded and thrown away on every visit.
906
+ if (typeof output !== "string" || !isSize(bytes)) return;
907
+ const url = resolvePath(basePath, output);
908
+ if (byUrl.has(url)) return;
909
+ byUrl.set(url, { bytes, url });
910
+ };
911
+ for (const entry of Object.values(manifest.entries)) {
912
+ if (!isRecord(entry)) continue;
913
+ add(entry.output, entry.bytes);
914
+ // A model's external textures and a lightmap are separate files in the same release, so the
915
+ // fill warms them too: otherwise a second visit still re-downloads every texture.
916
+ if (Array.isArray(entry.lightmaps)) {
917
+ for (const lightmap of entry.lightmaps) {
918
+ if (isRecord(lightmap)) add(lightmap.output, lightmap.bytes);
919
+ }
920
+ }
921
+ if (Array.isArray(entry.sharedImages)) {
922
+ for (const image of entry.sharedImages) {
923
+ if (isRecord(image)) add(image.output, image.bytes);
924
+ }
925
+ }
926
+ }
927
+ return [...byUrl.values()];
928
+ };
771
929
  let manifestRequest: Promise<IAssetManifest | undefined> | undefined;
772
930
  const manifestOnce = (): Promise<IAssetManifest | undefined> => {
773
- if (manifestRequest === undefined) manifestRequest = readManifest(manifestUrl);
931
+ if (manifestRequest === undefined) {
932
+ manifestRequest = readManifest(manifestUrl)
933
+ .catch((error: unknown) => {
934
+ // A malformed manifest still has to release the fill gate; otherwise a game that awaits
935
+ // the documented `startBackgroundFill()` promise waits forever.
936
+ assetCache.setManifest([]);
937
+ throw error;
938
+ })
939
+ .then((manifest) => {
940
+ if (manifest !== undefined) {
941
+ const entries = fillEntries(manifest);
942
+ assetCache.setManifest(entries);
943
+ } else {
944
+ // No manifest means nothing is content-addressed, so the cache stays out of the way.
945
+ assetCache.setManifest([]);
946
+ }
947
+ return manifest;
948
+ });
949
+ }
774
950
  return manifestRequest;
775
951
  };
776
952
  // Detection still runs exactly once, but `ready` only makes unsupported compressed textures a
@@ -796,6 +972,7 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
796
972
  surfaces: new WeakSet(),
797
973
  textures: new WeakSet(),
798
974
  };
975
+ let loaderDisposed = false;
799
976
 
800
977
  const loadCompiledKtx2 = async (url: string): Promise<Texture> => {
801
978
  if (compressedTextures === undefined) {
@@ -914,14 +1091,26 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
914
1091
  ): Promise<T> => {
915
1092
  const failures: string[] = [];
916
1093
  for (const url of urls) {
1094
+ const start = debug ? performanceNow() : 0;
917
1095
  try {
918
- const value = await load(url);
1096
+ const value = await (debug
1097
+ ? measureDebug(`assetDispatch.${url}`, "loading", url, () => load(url))
1098
+ : load(url));
919
1099
  // Recorded here, where the winner is known and nowhere else: a caller that asks which
920
1100
  // url served its bytes gets the one that did, not the first one that was tried.
921
1101
  resolvedAssets.set(path, { url, via });
922
1102
  return value;
923
1103
  } catch (error) {
924
1104
  failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
1105
+ } finally {
1106
+ if (debug)
1107
+ countDebug(
1108
+ `assetLoad.${url}WallMs`,
1109
+ performanceNow() - start,
1110
+ "loading",
1111
+ url,
1112
+ "async-ms",
1113
+ );
925
1114
  }
926
1115
  }
927
1116
  throw new Error(
@@ -949,18 +1138,52 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
949
1138
  return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
950
1139
  };
951
1140
 
952
- const cached = <T>(kind: string, path: string, load: (url: string) => Promise<T>): Promise<T> => {
1141
+ /** The shared images and lightmaps a path's load downloads beside its own file, with sizes. */
1142
+ const auxiliaryOf = async (path: string): Promise<IResolvedFile[]> => {
1143
+ if (isExternalAssetPath(path)) return [];
1144
+ const entry = (await manifestOnce())?.entries[path];
1145
+ if (!isRecord(entry)) return [];
1146
+ const files: IResolvedFile[] = [];
1147
+ for (const key of ["sharedImages", "lightmaps"] as const) {
1148
+ const outputs = entry[key];
1149
+ if (!Array.isArray(outputs)) continue;
1150
+ for (const output of outputs) {
1151
+ if (!isRecord(output) || typeof output.output !== "string") continue;
1152
+ const bytes = output.bytes;
1153
+ if (typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0)
1154
+ files.push({ bytes, url: resolvePath(basePath, output.output) });
1155
+ }
1156
+ }
1157
+ return files;
1158
+ };
1159
+
1160
+ const cached = <T>(
1161
+ kind: string,
1162
+ path: string,
1163
+ load: (url: string, priority: AssetPriority) => Promise<T>,
1164
+ priority: AssetPriority = "now",
1165
+ ): Promise<T> => {
953
1166
  const key = `${kind}:${path}`;
954
1167
  const existing = cache.get(key);
955
- if (existing !== undefined) return existing.promise as Promise<T>;
1168
+ if (existing !== undefined) {
1169
+ // The world asked at `soon` and the scene now awaits the same file: without the promotion
1170
+ // the scene waits behind every queued prefetch.
1171
+ if (!existing.loaded && PRIORITY_ORDER[priority] < PRIORITY_ORDER[existing.priority]) {
1172
+ existing.priority = priority;
1173
+ if (existing.url !== undefined) assetCache.promote(existing.url, priority);
1174
+ }
1175
+ return existing.promise as Promise<T>;
1176
+ }
956
1177
  requested += 1;
957
1178
  // The size is only knowable once the manifest lands, so this load's weight joins the
958
1179
  // denominator a tick later than its count. Recorded here rather than inside the load chain
959
1180
  // so a load that fails still contributes the same weight to both sides of the ratio.
960
1181
  let weight = 0;
961
- const weighed = bytesOf(path).then(
962
- (bytes) => {
1182
+ let auxiliary: readonly IResolvedFile[] = [];
1183
+ const weighed = Promise.all([bytesOf(path), auxiliaryOf(path)]).then(
1184
+ ([bytes, files]) => {
963
1185
  weight = bytes;
1186
+ auxiliary = files;
964
1187
  requestedBytes += bytes;
965
1188
  },
966
1189
  () => undefined,
@@ -973,14 +1196,22 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
973
1196
  disposed: false,
974
1197
  kind: kind as AssetKind,
975
1198
  loaded: false,
1199
+ priority,
976
1200
  promise: Promise.resolve()
977
1201
  .then(() => resolveCandidates(path))
978
- .then((candidates) => loadFirst(path, candidates, load)),
1202
+ .then((candidates) =>
1203
+ loadFirst(path, candidates, (url) => {
1204
+ entry.url = url;
1205
+ return load(url, entry.priority);
1206
+ }),
1207
+ ),
979
1208
  released: false,
980
1209
  };
981
1210
  entry.promise = entry.promise.then((value) => {
982
1211
  entry.loaded = true;
983
1212
  entry.value = value;
1213
+ const record = resolvedAssets.get(path);
1214
+ if (record !== undefined) resolvedAssets.set(path, { ...record, kind: kind as AssetKind });
984
1215
  if (entry.released) disposeEntry(entry, disposed);
985
1216
  return value;
986
1217
  });
@@ -993,6 +1224,14 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
993
1224
  pending.delete(path);
994
1225
  void weighed.then(() => {
995
1226
  settledBytes += weight;
1227
+ // Only a load that resolved has a record; a rejected one has no bytes to attribute.
1228
+ const record = resolvedAssets.get(path);
1229
+ if (record !== undefined && weight > 0)
1230
+ resolvedAssets.set(path, {
1231
+ ...record,
1232
+ bytes: weight,
1233
+ files: [{ bytes: weight, url: record.url }, ...auxiliary],
1234
+ });
996
1235
  });
997
1236
  if (traceStart !== 0) {
998
1237
  console.log(
@@ -1020,6 +1259,78 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1020
1259
  );
1021
1260
  };
1022
1261
 
1262
+ /**
1263
+ * Warm the disk with the named logical paths at `soon` priority. Resolves once every candidate
1264
+ * settles; a path the manifest does not list is skipped rather than failing the whole prefetch.
1265
+ */
1266
+ const prefetchPaths = async (paths: readonly string[]): Promise<IAssetPrefetchProgress> => {
1267
+ if (!assetCache.enabled) {
1268
+ return {
1269
+ requested: paths.length,
1270
+ requestedBytes: 0,
1271
+ settled: paths.length,
1272
+ settledBytes: 0,
1273
+ };
1274
+ }
1275
+ const manifest = await manifestOnce().catch(() => undefined);
1276
+ // No manifest means no content-addressed output, so there is nothing the cache may keep and
1277
+ // nothing to warm. Reporting the paths as settled is honest; downloading them would not be.
1278
+ if (manifest === undefined) {
1279
+ return {
1280
+ requested: paths.length,
1281
+ requestedBytes: 0,
1282
+ settled: paths.length,
1283
+ settledBytes: 0,
1284
+ };
1285
+ }
1286
+ const targets: { bytes?: number; url: string }[] = [];
1287
+ const addOutput = (output: unknown, bytes: unknown): void => {
1288
+ // An unsized file cannot be kept on disk, so prefetching it would only waste the link.
1289
+ if (typeof output !== "string" || !isSize(bytes)) return;
1290
+ targets.push({ bytes, url: resolvePath(basePath, output) });
1291
+ };
1292
+ for (const path of paths) {
1293
+ let urls: readonly string[];
1294
+ try {
1295
+ urls = (await resolveCandidates(path)).urls;
1296
+ } catch {
1297
+ continue;
1298
+ }
1299
+ const size = await bytesOf(path);
1300
+ for (const url of urls) targets.push({ url, ...(size > 0 ? { bytes: size } : {}) });
1301
+ // A model's external textures and a lightmap are separate files; prefetching the model
1302
+ // alone would leave the deferred tier fetching the textures again over the network.
1303
+ const entry = manifest.entries[path];
1304
+ if (!isRecord(entry)) continue;
1305
+ for (const key of ["lightmaps", "sharedImages"] as const) {
1306
+ const outputs = entry[key];
1307
+ if (!Array.isArray(outputs)) continue;
1308
+ for (const output of outputs) {
1309
+ if (!isRecord(output)) continue;
1310
+ addOutput(output.output, output.bytes);
1311
+ }
1312
+ }
1313
+ }
1314
+ // One entry per url, so a candidate list with two spellings still costs one download.
1315
+ const unique = [...new Map(targets.map((target) => [target.url, target])).values()];
1316
+ const results = await Promise.allSettled(
1317
+ unique.map((target) => assetCache.fetchBytes(target.url, "soon", target.bytes)),
1318
+ );
1319
+ let settled = 0;
1320
+ let settledBytes = 0;
1321
+ results.forEach((result, index) => {
1322
+ if (result.status !== "fulfilled") return;
1323
+ settled += 1;
1324
+ settledBytes += unique[index]?.bytes ?? result.value.byteLength;
1325
+ });
1326
+ return {
1327
+ requested: unique.length,
1328
+ requestedBytes: unique.reduce((sum, target) => sum + (target.bytes ?? 0), 0),
1329
+ settled,
1330
+ settledBytes,
1331
+ };
1332
+ };
1333
+
1023
1334
  return {
1024
1335
  audio: (path) =>
1025
1336
  cached("audio", path, async (url) => {
@@ -1032,145 +1343,178 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1032
1343
  cache.clear();
1033
1344
  entries.forEach(releaseEntry);
1034
1345
  },
1346
+ dispose: () => {
1347
+ if (loaderDisposed) return;
1348
+ loaderDisposed = true;
1349
+ assetCache.dispose();
1350
+ // Three's KTX2Loader owns the decoder worker pool. Resolving the shared promise can fail
1351
+ // when no loader was built; that is not a teardown failure.
1352
+ void compressedTextures?.loader
1353
+ .then((shared) => {
1354
+ (shared as (IKTX2LoaderLike & { dispose?: () => void }) | undefined)?.dispose?.();
1355
+ })
1356
+ .catch(() => undefined);
1357
+ },
1035
1358
  ...(compressedTextures === undefined ? {} : { compressedTextures }),
1036
- model: <T = unknown>(path: string) =>
1037
- cached<T>("model", path, async (url) => {
1038
- if (options.model !== undefined) {
1039
- const value = (await options.model(url)) as T;
1040
- stampAssetProvenance(value, path);
1041
- await attachCompiledLightmaps(path, value);
1042
- return value;
1043
- }
1044
- // Fetched here rather than through the loader so the declared extensions decide which
1045
- // decoders load: a game never pays for a codec its assets do not use, and no WASM is
1046
- // instantiated on platforms that never load a compressed model. Both the compiled and
1047
- // the uncompiled path take this one code path.
1048
- const data = await fetchModelBytes(url);
1049
- const extensions = declaredExtensions(data);
1050
- const { GLTFLoader } = await import("three/addons/loaders/GLTFLoader.js");
1051
- const loader = new GLTFLoader();
1052
- // Both glTF texture extensions use the same support-detected instance as texture().
1053
- const astcExtension = "EXT_texture_astc";
1054
- const hasBasis = extensions.has("KHR_texture_basisu");
1055
- const hasAstc = extensions.has(astcExtension);
1056
- let shared: IKTX2LoaderLike | undefined;
1057
- if (compressedTextures !== undefined && (hasBasis || hasAstc)) {
1058
- try {
1059
- shared = await compressedTextures.loader;
1060
- } catch (error) {
1061
- // Only ASTC-only models may select their ordinary fallback on capability refusal.
1062
- // Import/setup failures and the existing Basis contract still reject unchanged.
1063
- if (
1064
- hasBasis ||
1065
- !(error instanceof Error) ||
1066
- !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:")
1067
- )
1068
- throw error;
1359
+ model: <T = unknown>(path: string, request?: IAssetRequestOptions) =>
1360
+ cached<T>(
1361
+ "model",
1362
+ path,
1363
+ async (url, priority) => {
1364
+ if (options.model !== undefined) {
1365
+ const value = (await options.model(url)) as T;
1366
+ stampAssetProvenance(value, path);
1367
+ await attachCompiledLightmaps(path, value);
1368
+ return value;
1069
1369
  }
1070
- if (shared !== undefined) {
1071
- loader.setKTX2Loader(shared as unknown as Parameters<typeof loader.setKTX2Loader>[0]);
1072
- }
1073
- }
1074
- if (hasAstc) {
1075
- const astcLoader = shared;
1076
- const astcSupported = hasAstcSupport(astcLoader);
1077
- // EXT_texture_astc is an official vendor draft. Borrow Three's Basis plugin handoff,
1078
- // but raw ASTC cannot use Basis's format fallback and needs this explicit GPU guard.
1079
- loader.register((parser) => {
1080
- if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
1081
- throw new Error(
1082
- "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support.",
1083
- );
1370
+ // Fetched here rather than through the loader so the declared extensions decide which
1371
+ // decoders load: a game never pays for a codec its assets do not use, and no WASM is
1372
+ // instantiated on platforms that never load a compressed model. Both the compiled and
1373
+ // the uncompiled path take this one code path.
1374
+ const expected = await bytesOf(path);
1375
+ const data = await fetchModelBytes(
1376
+ url,
1377
+ assetCache,
1378
+ expected > 0 ? expected : undefined,
1379
+ priority,
1380
+ );
1381
+ const extensions = declaredExtensions(data);
1382
+ const { GLTFLoader } = await import("three/addons/loaders/GLTFLoader.js");
1383
+ const loader = new GLTFLoader();
1384
+ // Both glTF texture extensions use the same support-detected instance as texture().
1385
+ const astcExtension = "EXT_texture_astc";
1386
+ const hasBasis = extensions.has("KHR_texture_basisu");
1387
+ const hasAstc = extensions.has(astcExtension);
1388
+ let shared: IKTX2LoaderLike | undefined;
1389
+ if (compressedTextures !== undefined && (hasBasis || hasAstc)) {
1390
+ try {
1391
+ shared = await compressedTextures.loader;
1392
+ } catch (error) {
1393
+ // Only ASTC-only models may select their ordinary fallback on capability refusal.
1394
+ // Import/setup failures and the existing Basis contract still reject unchanged.
1395
+ if (
1396
+ hasBasis ||
1397
+ !(error instanceof Error) ||
1398
+ !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:")
1399
+ )
1400
+ throw error;
1401
+ }
1402
+ if (shared !== undefined) {
1403
+ loader.setKTX2Loader(shared as unknown as Parameters<typeof loader.setKTX2Loader>[0]);
1084
1404
  }
1085
- return {
1086
- name: astcExtension,
1087
- loadTexture(textureIndex) {
1088
- const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
1089
- if (extension === undefined || !astcSupported || astcLoader === undefined)
1090
- return null;
1091
- return parser.loadTextureImage(
1092
- textureIndex,
1093
- extension.source,
1094
- astcLoader as NonNullable<Parameters<typeof loader.setKTX2Loader>[0]>,
1405
+ }
1406
+ if (hasAstc) {
1407
+ const astcLoader = shared;
1408
+ const astcSupported = hasAstcSupport(astcLoader);
1409
+ // EXT_texture_astc is an official vendor draft. Borrow Three's Basis plugin handoff,
1410
+ // but raw ASTC cannot use Basis's format fallback and needs this explicit GPU guard.
1411
+ loader.register((parser) => {
1412
+ if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
1413
+ throw new Error(
1414
+ "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support.",
1095
1415
  );
1096
- },
1097
- };
1098
- });
1099
- }
1100
- // three's own decoder embeds its WASM; it compiles only once a compressed model is
1101
- // actually loaded. The native bundle inlines this branch (no runtime import remains),
1102
- // and the host shims WebAssembly.
1103
- if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
1104
- const { MeshoptDecoder } = await import("three/addons/libs/meshopt_decoder.module.js");
1105
- loader.setMeshoptDecoder(MeshoptDecoder);
1106
- }
1107
- // Draco is an input format only: the compile step re-emits Draco assets as Meshopt,
1108
- // so this serves uncompiled Draco files dropped into a web root. The decoder wasm is
1109
- // served from `<basePath>draco/` by convention, like `basis/`.
1110
- // The cluster DAG the asset pipeline baked in. Registered only when the file declares it,
1111
- // so a game whose models are ordinary meshes never pays for the plugin — and a game whose
1112
- // models are not gets a plain `Mesh`, with no runtime switch either way.
1113
- if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
1114
- loader.register((parser) => new VirtualGeometryPlugin(parser as never) as never);
1115
- }
1116
- // The discrete chain the asset pipeline baked in. Registered only when the file declares it,
1117
- // so a game with no auto LOD never pays for the plugin. Levels are built after the quantized
1118
- // positions are widened, so the derived geometries share the widened attributes.
1119
- // The Wasm engine's loader hosts this plugin too, and sets `failClosed`: a chain it cannot
1120
- // deliver rejects the load there instead of being logged.
1121
- const discreteLod = extensions.has(TN_DISCRETE_LOD)
1122
- ? new DiscreteLodPlugin({
1123
- failClosed: (loader as { failClosed?: boolean }).failClosed === true,
1124
- })
1125
- : undefined;
1126
- if (discreteLod !== undefined) {
1127
- const plugin = discreteLod;
1128
- loader.register((parser) => {
1129
- plugin.setParser(parser as never);
1130
- return plugin as never;
1131
- });
1132
- }
1133
- if (extensions.has(DRACO_EXTENSION)) {
1134
- const { DRACOLoader } = await import("three/addons/loaders/DRACOLoader.js");
1135
- const dracoLoader = new DRACOLoader();
1136
- dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
1137
- loader.setDRACOLoader(dracoLoader);
1138
- }
1139
- const value = await new Promise<T>((resolve, reject) =>
1140
- loader.parse(data, resourcePathOf(url), resolve as never, reject),
1141
- );
1142
- // Before the game ever sees it: a quantized POSITION is a trap for every ordinary
1143
- // three.js geometry call. See `widenQuantizedPositions`.
1144
- const root = modelRoot(value);
1145
- if (root !== undefined) widenQuantizedPositions(root);
1146
- // And a normalized scalar is a trap for the WebGPU pipeline. See `widenNormalizedScalars`.
1147
- if (root !== undefined) widenNormalizedScalars(root);
1148
- // Built here, after both widenings, so the derived levels share the widened base
1149
- // attributes instead of pinning the quantized ones.
1150
- if (root !== undefined && discreteLod !== undefined)
1151
- discreteLod.attach(root, await discretePolicy(path));
1152
- // Before the game ever sees it: clips z-mirrored against their own bind pose play every
1153
- // animal backwards, silently. See `reconcileMirroredClips`.
1154
- const clips = modelClips(value);
1155
- if (root !== undefined && clips.length > 0 && reconcileMirroredClips(root, clips)) {
1156
- // A warning, not an info line: every file this fires on is a defect in whatever wrote
1157
- // it, and a repair that reads as routine is a repair nobody ever removes the cause of.
1158
- // The Unreal importer's own reader of ActorX PSA keys once produced exactly this on
1159
- // every skeletal mesh it converted, unnoticed for as long as the line said `info`.
1160
- const cause =
1161
- "its clips are mirrored against its own bind pose, and the loader un-mirrored them " +
1162
- "so the game plays forwards. The file is wrong, not the game: re-import it with a " +
1163
- "current converter and this stops.";
1164
- console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} — ${cause}`);
1165
- }
1166
- stampAssetProvenance(value, path);
1167
- await attachCompiledLightmaps(path, value);
1168
- return value;
1169
- }),
1416
+ }
1417
+ return {
1418
+ name: astcExtension,
1419
+ loadTexture(textureIndex) {
1420
+ const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
1421
+ if (extension === undefined || !astcSupported || astcLoader === undefined)
1422
+ return null;
1423
+ return parser.loadTextureImage(
1424
+ textureIndex,
1425
+ extension.source,
1426
+ astcLoader as NonNullable<Parameters<typeof loader.setKTX2Loader>[0]>,
1427
+ );
1428
+ },
1429
+ };
1430
+ });
1431
+ }
1432
+ // three's own decoder embeds its WASM; it compiles only once a compressed model is
1433
+ // actually loaded. The native bundle inlines this branch (no runtime import remains),
1434
+ // and the host shims WebAssembly.
1435
+ if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
1436
+ const { MeshoptDecoder } = await import("three/addons/libs/meshopt_decoder.module.js");
1437
+ loader.setMeshoptDecoder(MeshoptDecoder);
1438
+ }
1439
+ // Draco is an input format only: the compile step re-emits Draco assets as Meshopt,
1440
+ // so this serves uncompiled Draco files dropped into a web root. The decoder wasm is
1441
+ // served from `<basePath>draco/` by convention, like `basis/`.
1442
+ // The cluster DAG the asset pipeline baked in. Registered only when the file declares it,
1443
+ // so a game whose models are ordinary meshes never pays for the plugin — and a game whose
1444
+ // models are not gets a plain `Mesh`, with no runtime switch either way.
1445
+ if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
1446
+ loader.register((parser) => new VirtualGeometryPlugin(parser as never) as never);
1447
+ }
1448
+ // The discrete chain the asset pipeline baked in. Registered only when the file declares it,
1449
+ // so a game with no auto LOD never pays for the plugin. Levels are built after the quantized
1450
+ // positions are widened, so the derived geometries share the widened attributes.
1451
+ // The Wasm engine's loader hosts this plugin too, and sets `failClosed`: a chain it cannot
1452
+ // deliver rejects the load there instead of being logged.
1453
+ const discreteLod = extensions.has(TN_DISCRETE_LOD)
1454
+ ? new DiscreteLodPlugin({
1455
+ failClosed: (loader as { failClosed?: boolean }).failClosed === true,
1456
+ })
1457
+ : undefined;
1458
+ if (discreteLod !== undefined) {
1459
+ const plugin = discreteLod;
1460
+ loader.register((parser) => {
1461
+ plugin.setParser(parser as never);
1462
+ return plugin as never;
1463
+ });
1464
+ }
1465
+ if (extensions.has(DRACO_EXTENSION)) {
1466
+ const { DRACOLoader } = await import("three/addons/loaders/DRACOLoader.js");
1467
+ const dracoLoader = new DRACOLoader();
1468
+ dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
1469
+ loader.setDRACOLoader(dracoLoader);
1470
+ }
1471
+ const value = await new Promise<T>((resolve, reject) =>
1472
+ loader.parse(data, resourcePathOf(url), resolve as never, reject),
1473
+ );
1474
+ // Before the game ever sees it: a quantized POSITION is a trap for every ordinary
1475
+ // three.js geometry call. See `widenQuantizedPositions`.
1476
+ const root = modelRoot(value);
1477
+ if (root !== undefined) widenQuantizedPositions(root);
1478
+ // And a normalized scalar is a trap for the WebGPU pipeline. See `widenNormalizedScalars`.
1479
+ if (root !== undefined) widenNormalizedScalars(root);
1480
+ // Built here, after both widenings, so the derived levels share the widened base
1481
+ // attributes instead of pinning the quantized ones.
1482
+ if (root !== undefined && discreteLod !== undefined)
1483
+ discreteLod.attach(root, await discretePolicy(path));
1484
+ // Before the game ever sees it: clips z-mirrored against their own bind pose play every
1485
+ // animal backwards, silently. See `reconcileMirroredClips`.
1486
+ const clips = modelClips(value);
1487
+ if (root !== undefined && clips.length > 0 && reconcileMirroredClips(root, clips)) {
1488
+ // A warning, not an info line: every file this fires on is a defect in whatever wrote
1489
+ // it, and a repair that reads as routine is a repair nobody ever removes the cause of.
1490
+ // The Unreal importer's own reader of ActorX PSA keys once produced exactly this on
1491
+ // every skeletal mesh it converted, unnoticed for as long as the line said `info`.
1492
+ const cause =
1493
+ "its clips are mirrored against its own bind pose, and the loader un-mirrored them " +
1494
+ "so the game plays forwards. The file is wrong, not the game: re-import it with a " +
1495
+ "current converter and this stops.";
1496
+ console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} — ${cause}`);
1497
+ }
1498
+ stampAssetProvenance(value, path);
1499
+ await attachCompiledLightmaps(path, value);
1500
+ return value;
1501
+ },
1502
+ request?.priority ?? "now",
1503
+ ),
1504
+ get cache() {
1505
+ return { ...assetCache.report, clear: () => assetCache.clear() };
1506
+ },
1170
1507
  get progress() {
1171
1508
  return { pending: [...pending], requested, requestedBytes, settled, settledBytes };
1172
1509
  },
1510
+ prefetch: prefetchPaths,
1173
1511
  resolve: async (path) => (await resolveCandidates(path)).urls,
1512
+ startBackgroundFill: () => {
1513
+ // The fill needs the manifest even when the scene loaded nothing through this loader yet;
1514
+ // a failed read is the documented no-manifest case and simply leaves the fill empty.
1515
+ void manifestOnce().catch(() => undefined);
1516
+ return assetCache.startFill();
1517
+ },
1174
1518
  // A copy per read, like `progress`: a caller inspecting the record must not be able to
1175
1519
  // rewrite what the loader reports for the next asset that settles.
1176
1520
  get resolved(): ReadonlyMap<string, IResolvedAsset> {
@@ -1185,7 +1529,7 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1185
1529
  return true;
1186
1530
  },
1187
1531
  texture: async (path, textureOptions) => {
1188
- const texture = await cached("texture", path, async (url) => {
1532
+ const texture = await cached("texture", path, async (url, priority) => {
1189
1533
  if (options.texture !== undefined) return options.texture(url);
1190
1534
  // Compiled output carries the content-addressed extension: anything ending in .ktx2
1191
1535
  // goes through the shared KTX2 loader, everything else stays on TextureLoader.
@@ -1193,9 +1537,17 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1193
1537
  return loadCompiledKtx2(url);
1194
1538
  }
1195
1539
  if (typeof createImageBitmap === "function") {
1196
- return loadBitmapTexture(url, options.renderer);
1540
+ const expected = await bytesOf(path);
1541
+ return loadBitmapTexture(
1542
+ url,
1543
+ options.renderer,
1544
+ assetCache,
1545
+ expected > 0 ? expected : undefined,
1546
+ priority,
1547
+ );
1197
1548
  }
1198
1549
  const { TextureLoader: Loader } = await import("three");
1550
+ if (debug) countDebug("textureMainThreadDecodeFallbacks", 1, "loading", url);
1199
1551
  return loadWith(new Loader() as TextureLoader, url);
1200
1552
  });
1201
1553
  return textureOptions === undefined ? texture : configuredTexture(texture, textureOptions);
@@ -1215,6 +1567,11 @@ function disposeModel(value: unknown, disposed: IResourceDisposalSets): void {
1215
1567
  root.traverse((object) => {
1216
1568
  const renderable = object as Object3D & { geometry?: unknown; [key: string]: unknown };
1217
1569
  disposeResource(renderable.geometry, disposed.geometries);
1570
+ const skeleton = renderable.skeleton as { boneTexture?: unknown } | undefined;
1571
+ // A SkinnedMesh's skeleton owns a bone texture allocated on renderer paths that lack
1572
+ // float textures (the WebGL2 fallback). Dispose it with the model, and share ownership
1573
+ // with every other material/texture reference through the same set.
1574
+ disposeTexture(skeleton?.boneTexture, disposed);
1218
1575
  disposeSurface(renderable["ma" + "terial"], disposed);
1219
1576
  });
1220
1577
  }
@@ -1242,6 +1599,13 @@ function stampAssetProvenance(value: unknown, logicalPath: string): void {
1242
1599
  const existing = userData[GEOMETRY_ASSET_KEY];
1243
1600
  if (typeof existing === "string" && existing !== "") continue;
1244
1601
  userData[GEOMETRY_ASSET_KEY] = logicalPath;
1602
+ // An instanced batch is built from a model's geometry and the root never enters the scene, so
1603
+ // the geometry carries the stamp too. `BufferGeometry.copy` shares `userData`, so clones keep it.
1604
+ root.traverse((object) => {
1605
+ const geometry = (object as Object3D & { geometry?: { userData?: Record<string, unknown> } })
1606
+ .geometry;
1607
+ if (geometry?.userData !== undefined) geometry.userData[GEOMETRY_ASSET_KEY] ??= logicalPath;
1608
+ });
1245
1609
  }
1246
1610
  }
1247
1611
 
@@ -1298,6 +1662,11 @@ function isTexture(value: unknown): value is Texture {
1298
1662
  return value instanceof Texture || (isRecord(value) && value.isTexture === true);
1299
1663
  }
1300
1664
 
1665
+ /** A byte count the manifest recorded: the disk cache keeps only a file with one. */
1666
+ function isSize(bytes: unknown): bytes is number {
1667
+ return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0;
1668
+ }
1669
+
1301
1670
  function isRecord(value: unknown): value is Record<string, unknown> {
1302
1671
  return typeof value === "object" && value !== null;
1303
1672
  }