@threenative/core 0.3.4 → 0.3.5
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.
- package/capabilities.json +1505 -79
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12423 -4955
- package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
- package/dist/playtest.d.ts +6 -10
- package/dist/playtest.js +47 -24
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +766 -73
- package/dist/world.js +9307 -3543
- package/gpl/recipes/export_world.py +18 -1
- package/mcp/blender-server.mjs +7 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +2 -2
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +6594 -700
- package/scripts/apply-three-patch.mjs +62 -4
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2390 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +564 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +839 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
package/src/assets.ts
ADDED
|
@@ -0,0 +1,1303 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AnimationClip,
|
|
3
|
+
type AudioLoader,
|
|
4
|
+
type Bone,
|
|
5
|
+
BufferAttribute,
|
|
6
|
+
type BufferGeometry,
|
|
7
|
+
Mesh,
|
|
8
|
+
NoColorSpace,
|
|
9
|
+
Object3D,
|
|
10
|
+
RGBA_ASTC_4x4_Format,
|
|
11
|
+
SRGBColorSpace,
|
|
12
|
+
Texture,
|
|
13
|
+
type TextureLoader,
|
|
14
|
+
type Wrapping,
|
|
15
|
+
} from "three";
|
|
16
|
+
import { TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin } from "./clustered-mesh.js";
|
|
17
|
+
import { GEOMETRY_ASSET_KEY } from "./geometry-capture.js";
|
|
18
|
+
import { DiscreteLodPlugin, type IModelLodPolicy, TN_DISCRETE_LOD } from "./model-lod.js";
|
|
19
|
+
|
|
20
|
+
export interface IAssetLoaderOptions {
|
|
21
|
+
readonly basePath?: string;
|
|
22
|
+
/**
|
|
23
|
+
* URL of the manifest written by the asset compile step (`public/assets.manifest.json`).
|
|
24
|
+
* Defaults to `assets.manifest.json` resolved against `basePath`. A logical path is resolved
|
|
25
|
+
* to its compiled output through it; a manifest that is absent — 404 or unfetchable — falls
|
|
26
|
+
* back to loading every path verbatim, while one that is served malformed or with an unknown
|
|
27
|
+
* version throws.
|
|
28
|
+
*/
|
|
29
|
+
readonly manifest?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Directory the game's uncompiled assets live in, relative to `basePath`.
|
|
32
|
+
*
|
|
33
|
+
* Only consulted when there is no manifest, and only after the verbatim path has been tried. It
|
|
34
|
+
* is what makes the delete-test possible: remove everything the asset pipeline produced and the
|
|
35
|
+
* game still finds `assets/rock.png` where the author put it, just slower and uncompressed.
|
|
36
|
+
* Defaults to the compile step's own default source directory.
|
|
37
|
+
*/
|
|
38
|
+
readonly sourcePath?: string;
|
|
39
|
+
readonly model?: (url: string) => Promise<unknown>;
|
|
40
|
+
readonly texture?: (url: string) => Promise<Texture>;
|
|
41
|
+
readonly audio?: (url: string) => Promise<AudioBuffer>;
|
|
42
|
+
/**
|
|
43
|
+
* The live renderer (`IRendererLike.raw`), handed to `KTX2Loader.detectSupport()` exactly
|
|
44
|
+
* once so compiled KTX2 textures transcode to a format this machine's GPU actually supports.
|
|
45
|
+
* Required for games whose textures compile to `.ktx2`; without it such a load throws rather
|
|
46
|
+
* than silently uploading decoded RGBA.
|
|
47
|
+
*/
|
|
48
|
+
readonly renderer?: unknown;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The structural slice of three's `KTX2Loader` core depends on. */
|
|
52
|
+
export interface IKTX2LoaderLike {
|
|
53
|
+
detectSupport(renderer: unknown): unknown;
|
|
54
|
+
load(
|
|
55
|
+
url: string,
|
|
56
|
+
onLoad: (texture: Texture) => void,
|
|
57
|
+
onProgress?: (event: ProgressEvent<EventTarget>) => void,
|
|
58
|
+
onError?: (error: unknown) => void,
|
|
59
|
+
): unknown;
|
|
60
|
+
setTranscoderPath(path: string): unknown;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Present only when a renderer was handed to the asset loader. `ready` settles once support
|
|
65
|
+
* detection ran; it rejects naming the renderer and platform when no compressed format is
|
|
66
|
+
* supported, and `defineGame` awaits it during boot so such a target fails at construction.
|
|
67
|
+
*/
|
|
68
|
+
export interface ICompressedTextureSupport {
|
|
69
|
+
/**
|
|
70
|
+
* The one shared instance, also handed to `GLTFLoader.setKTX2Loader()` for models. Resolves
|
|
71
|
+
* `undefined` when the renderer exposed no surface to probe (see `createKtx2Loader`).
|
|
72
|
+
*/
|
|
73
|
+
readonly loader: Promise<IKTX2LoaderLike | undefined>;
|
|
74
|
+
readonly ready: Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Which pipeline served a logical path: the compile step's manifest, or the project's own files. */
|
|
78
|
+
export type AssetSource = "manifest" | "source";
|
|
79
|
+
|
|
80
|
+
/** Where one settled load's bytes actually came from. */
|
|
81
|
+
export interface IResolvedAsset {
|
|
82
|
+
readonly url: string;
|
|
83
|
+
readonly via: AssetSource;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface ITextureOptions {
|
|
87
|
+
/**
|
|
88
|
+
* The pixels are data, not colour: a normal map, a roughness map, a mask. Data textures are
|
|
89
|
+
* sampled without a colour-space conversion, which is wrong for an albedo and right for these.
|
|
90
|
+
* Left out, the copy is sRGB — the space an image file is authored in. A loader leaves a plain
|
|
91
|
+
* image linear, which washes out every albedo, so an options call never inherits that.
|
|
92
|
+
*/
|
|
93
|
+
readonly data?: boolean;
|
|
94
|
+
// A normal or roughness map asking only for `wrap` still passes `data: true`: options always pick
|
|
95
|
+
// the space. The configured copy is outside the cache, so `release` cannot reclaim it — dispose it
|
|
96
|
+
// with the material that uses it.
|
|
97
|
+
/** Both axes at once. Absent leaves the loaded texture's own wrapping. */
|
|
98
|
+
readonly wrap?: Wrapping;
|
|
99
|
+
/** Tiling counts, one for both axes or one per axis. Absent leaves the loaded texture's own. */
|
|
100
|
+
readonly repeat?: number | readonly [number, number];
|
|
101
|
+
/** Samples to take at grazing angles. Absent leaves the loaded texture's own. */
|
|
102
|
+
readonly anisotropy?: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** What `texture(path, options)` hands back: the cached instance untouched, or a configured copy. */
|
|
106
|
+
function configuredTexture(texture: Texture, options: ITextureOptions): Texture {
|
|
107
|
+
const copy = texture.clone();
|
|
108
|
+
copy.colorSpace = options.data === true ? NoColorSpace : SRGBColorSpace;
|
|
109
|
+
if (options.wrap !== undefined) copy.wrapS = copy.wrapT = options.wrap;
|
|
110
|
+
const { repeat } = options;
|
|
111
|
+
if (typeof repeat === "number") copy.repeat.setScalar(repeat);
|
|
112
|
+
else if (repeat !== undefined) copy.repeat.set(repeat[0], repeat[1]);
|
|
113
|
+
if (options.anisotropy !== undefined) copy.anisotropy = options.anisotropy;
|
|
114
|
+
return copy;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface IAssetLoader {
|
|
118
|
+
readonly compressedTextures?: ICompressedTextureSupport;
|
|
119
|
+
model<T = unknown>(path: string): Promise<T>;
|
|
120
|
+
/**
|
|
121
|
+
* Load a texture, optionally configured in one call.
|
|
122
|
+
*
|
|
123
|
+
* @situation set color space, wrap, repeat or anisotropy on a loaded texture
|
|
124
|
+
*
|
|
125
|
+
* With no options this is the shared cached instance, exactly as before. With options it is a
|
|
126
|
+
* copy of it: the cached texture is shared by every other caller of that path, and a wrap or a
|
|
127
|
+
* colour-space write on it would silently change how another material draws.
|
|
128
|
+
*/
|
|
129
|
+
texture(path: string, options?: ITextureOptions): Promise<Texture>;
|
|
130
|
+
audio(path: string): Promise<AudioBuffer>;
|
|
131
|
+
release(kind: "audio" | "model" | "texture", path: string): boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Where a logical path is served from, in the order worth trying — the manifest's
|
|
134
|
+
* content-addressed output when a manifest exists, otherwise the verbatim and source paths.
|
|
135
|
+
* For loaders this surface does not wrap (an HDR sky, a font, a data file) — a game must never
|
|
136
|
+
* hard-code a hashed output name, which changes on every rebuild.
|
|
137
|
+
*/
|
|
138
|
+
resolve(path: string): Promise<readonly string[]>;
|
|
139
|
+
/**
|
|
140
|
+
* How many loads this loader has been asked for and how many have settled (resolved or
|
|
141
|
+
* rejected). A loading view reads the ratio; the runtime folds it into `ctx.startup.progress`
|
|
142
|
+
* while the start scene loads, so the bar moves with the bytes instead of jumping 0 to 1.
|
|
143
|
+
*
|
|
144
|
+
* `requestedBytes` and `settledBytes` are the same ledger weighed by the `bytes` the compile
|
|
145
|
+
* step already records for every manifest entry, and they are what a loading bar should read.
|
|
146
|
+
* A file count treats a 710 MB model and a 4 KB icon alike: one real game's bar reached 92%
|
|
147
|
+
* on eleven small assets and then stood still for the entire download of the twelfth. Both
|
|
148
|
+
* stay 0 for a game with no manifest, where no size is knowable before the bytes arrive.
|
|
149
|
+
*/
|
|
150
|
+
readonly progress: {
|
|
151
|
+
/**
|
|
152
|
+
* The logical paths asked for and not yet settled, in request order. A loading screen that
|
|
153
|
+
* only shows a ratio cannot say *what* it is waiting for, which is the difference between
|
|
154
|
+
* "still loading" and "stuck on `akagi.glb`" — and a stall report that names nothing is a
|
|
155
|
+
* bug report nobody can act on.
|
|
156
|
+
*/
|
|
157
|
+
readonly pending: readonly string[];
|
|
158
|
+
readonly requested: number;
|
|
159
|
+
readonly requestedBytes: number;
|
|
160
|
+
readonly settled: number;
|
|
161
|
+
readonly settledBytes: number;
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Where each settled load was actually served from, keyed by the logical path asked for.
|
|
165
|
+
*
|
|
166
|
+
* `progress` counts loads and cannot say which of a path's candidate urls answered, so a game
|
|
167
|
+
* whose manifest 404s and a game whose manifest named the output look identical from the game's
|
|
168
|
+
* own side — which is how an unreadable manifest became a silent uncompiled fallback on the
|
|
169
|
+
* native hosts, where a failed read arrives as a rejected fetch rather than a 404. `via` is
|
|
170
|
+
* `"manifest"` only for the compiled output the manifest named; `"source"` is the verbatim or
|
|
171
|
+
* source-directory path, and an external url, which no manifest governs.
|
|
172
|
+
*/
|
|
173
|
+
readonly resolved: ReadonlyMap<string, IResolvedAsset>;
|
|
174
|
+
clear(): void;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The manifest the asset compile step writes, read structurally: core needs only `version` and
|
|
179
|
+
* each entry's `output`, and must not depend on the build-time package for the rest.
|
|
180
|
+
*/
|
|
181
|
+
interface IAssetManifest {
|
|
182
|
+
readonly entries: Readonly<Record<string, unknown>>;
|
|
183
|
+
readonly version: number;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface ICompiledLightmap {
|
|
187
|
+
readonly materialTargets: readonly string[];
|
|
188
|
+
readonly output: string;
|
|
189
|
+
readonly texCoord: number;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const MANIFEST_VERSION = 1;
|
|
193
|
+
const ASTC_FORMAT = "astc4x4";
|
|
194
|
+
|
|
195
|
+
function entryUsesKtx2(entry: unknown): boolean {
|
|
196
|
+
if (!isRecord(entry)) return false;
|
|
197
|
+
if (typeof entry.output === "string" && /\.ktx2$/iu.test(entry.output)) return true;
|
|
198
|
+
if (
|
|
199
|
+
Array.isArray(entry.extensions) &&
|
|
200
|
+
entry.extensions.some(
|
|
201
|
+
(extension) => extension === "KHR_texture_basisu" || extension === "EXT_texture_astc",
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
return true;
|
|
205
|
+
const embeddedTextures = entry.embeddedTextures;
|
|
206
|
+
if (
|
|
207
|
+
isRecord(embeddedTextures) &&
|
|
208
|
+
isRecord(embeddedTextures.formats) &&
|
|
209
|
+
Object.values(embeddedTextures.formats).some(
|
|
210
|
+
(format) => typeof format === "string" && format !== "none",
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
return true;
|
|
214
|
+
return [entry.lightmaps, entry.sharedImages].some(
|
|
215
|
+
(outputs) =>
|
|
216
|
+
Array.isArray(outputs) &&
|
|
217
|
+
outputs.some(
|
|
218
|
+
(item) =>
|
|
219
|
+
isRecord(item) && typeof item.output === "string" && /\.ktx2$/iu.test(item.output),
|
|
220
|
+
),
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
interface IManifestAstcAsset {
|
|
225
|
+
readonly logicalPath: string;
|
|
226
|
+
readonly output: string;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function manifestOutput(entry: Record<string, unknown>, fallback: string): string {
|
|
230
|
+
return typeof entry.output === "string" ? entry.output : fallback;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function firstRawAstcAsset(logicalPath: string, entry: unknown): IManifestAstcAsset | undefined {
|
|
234
|
+
if (!isRecord(entry)) return undefined;
|
|
235
|
+
const output = manifestOutput(entry, logicalPath);
|
|
236
|
+
if (entry.format === ASTC_FORMAT) return { logicalPath, output };
|
|
237
|
+
if (Array.isArray(entry.lightmaps)) {
|
|
238
|
+
const lightmap = entry.lightmaps.find((item) => isRecord(item) && item.format === ASTC_FORMAT);
|
|
239
|
+
if (isRecord(lightmap)) return { logicalPath, output: manifestOutput(lightmap, output) };
|
|
240
|
+
}
|
|
241
|
+
if (Array.isArray(entry.sharedImages)) {
|
|
242
|
+
const sharedImage = entry.sharedImages.find(
|
|
243
|
+
(item) => isRecord(item) && item.codec === ASTC_FORMAT,
|
|
244
|
+
);
|
|
245
|
+
if (isRecord(sharedImage)) return { logicalPath, output: manifestOutput(sharedImage, output) };
|
|
246
|
+
}
|
|
247
|
+
const embeddedTextures = entry.embeddedTextures;
|
|
248
|
+
if (
|
|
249
|
+
isRecord(embeddedTextures) &&
|
|
250
|
+
isRecord(embeddedTextures.formats) &&
|
|
251
|
+
Object.values(embeddedTextures.formats).some((format) => format === ASTC_FORMAT)
|
|
252
|
+
)
|
|
253
|
+
return { logicalPath, output };
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function firstRawAstcManifestAsset(
|
|
258
|
+
manifest: IAssetManifest | undefined,
|
|
259
|
+
): IManifestAstcAsset | undefined {
|
|
260
|
+
for (const [logicalPath, entry] of Object.entries(manifest?.entries ?? {})) {
|
|
261
|
+
const asset = firstRawAstcAsset(logicalPath, entry);
|
|
262
|
+
if (asset !== undefined) return asset;
|
|
263
|
+
}
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function compiledLightmaps(entry: unknown, logicalPath: string): readonly ICompiledLightmap[] {
|
|
268
|
+
if (!isRecord(entry) || entry.lightmaps === undefined) return [];
|
|
269
|
+
if (!Array.isArray(entry.lightmaps)) {
|
|
270
|
+
throw new Error(
|
|
271
|
+
`TN_ASSETS_LIGHTMAP_MANIFEST_INVALID: '${logicalPath}' lightmaps must be an array.`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
return entry.lightmaps.map((lightmap, index) => {
|
|
275
|
+
if (
|
|
276
|
+
!isRecord(lightmap) ||
|
|
277
|
+
typeof lightmap.output !== "string" ||
|
|
278
|
+
lightmap.texCoord !== 1 ||
|
|
279
|
+
!Array.isArray(lightmap.materialTargets) ||
|
|
280
|
+
!lightmap.materialTargets.every((target) => typeof target === "string")
|
|
281
|
+
) {
|
|
282
|
+
throw new Error(
|
|
283
|
+
`TN_ASSETS_LIGHTMAP_MANIFEST_INVALID: '${logicalPath}' lightmaps[${String(index)}] must name output, texCoord 1, and string materialTargets.`,
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return {
|
|
287
|
+
materialTargets: lightmap.materialTargets,
|
|
288
|
+
output: lightmap.output,
|
|
289
|
+
texCoord: lightmap.texCoord,
|
|
290
|
+
};
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function isExternalAssetPath(path: string): boolean {
|
|
295
|
+
return /^(?:[a-z]+:)?\/\//iu.test(path) || path.startsWith("data:");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function resolvePath(basePath: string, path: string): string {
|
|
299
|
+
if (isExternalAssetPath(path)) return path;
|
|
300
|
+
if (basePath.length === 0) return path;
|
|
301
|
+
return `${basePath.replace(/\/$/u, "")}/${path.replace(/^\//u, "")}`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Reads the compile step's manifest. A 404 — or a url that cannot be fetched at all, which is
|
|
306
|
+
* how "no manifest" presents in bare-node tests and on hosts without a web root — is the
|
|
307
|
+
* documented no-manifest case and resolves to `undefined`. Anything that *is* served must be a
|
|
308
|
+
* valid version-1 manifest; anything else throws.
|
|
309
|
+
*/
|
|
310
|
+
async function readManifest(url: string): Promise<IAssetManifest | undefined> {
|
|
311
|
+
let response: Response;
|
|
312
|
+
try {
|
|
313
|
+
response = await fetch(url);
|
|
314
|
+
} catch {
|
|
315
|
+
return undefined;
|
|
316
|
+
}
|
|
317
|
+
if (response.status === 404) return undefined;
|
|
318
|
+
if (!response.ok) throw new Error(`Failed to load asset manifest '${url}': ${response.status}.`);
|
|
319
|
+
// SPA dev servers commonly return the app shell with status 200 for an unknown asset path.
|
|
320
|
+
// That response is the same as a missing manifest, not a malformed manifest supplied by the
|
|
321
|
+
// asset pipeline.
|
|
322
|
+
if (response.headers.get("content-type")?.toLowerCase().includes("text/html") === true)
|
|
323
|
+
return undefined;
|
|
324
|
+
let parsed: unknown;
|
|
325
|
+
try {
|
|
326
|
+
parsed = await response.json();
|
|
327
|
+
} catch {
|
|
328
|
+
throw new Error(`Asset manifest '${url}' does not contain valid JSON.`);
|
|
329
|
+
}
|
|
330
|
+
if (!isRecord(parsed) || parsed.version !== MANIFEST_VERSION || !isRecord(parsed.entries)) {
|
|
331
|
+
throw new Error(
|
|
332
|
+
`Asset manifest '${url}' must be version ${MANIFEST_VERSION} with an 'entries' object.`,
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
// An asset-free build still serves an empty manifest (so nothing 404s); it lists nothing, so it
|
|
336
|
+
// must not become authoritative over files a project serves verbatim from `public/`.
|
|
337
|
+
if (Object.keys(parsed.entries).length === 0) return undefined;
|
|
338
|
+
return parsed as unknown as IAssetManifest;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
type LoaderLike<T> = {
|
|
342
|
+
load: (
|
|
343
|
+
url: string,
|
|
344
|
+
onLoad: (value: T) => void,
|
|
345
|
+
onProgress?: (event: ProgressEvent<EventTarget>) => void,
|
|
346
|
+
onError?: (error: unknown) => void,
|
|
347
|
+
) => unknown;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
type AssetKind = "audio" | "model" | "texture";
|
|
351
|
+
|
|
352
|
+
interface IAssetEntry {
|
|
353
|
+
disposed: boolean;
|
|
354
|
+
kind: AssetKind;
|
|
355
|
+
loaded: boolean;
|
|
356
|
+
promise: Promise<unknown>;
|
|
357
|
+
released: boolean;
|
|
358
|
+
value?: unknown;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** The candidate urls for a logical path, and the pipeline that produced them. */
|
|
362
|
+
interface ICandidateUrls {
|
|
363
|
+
readonly urls: readonly string[];
|
|
364
|
+
readonly via: AssetSource;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
interface IDisposableResource {
|
|
368
|
+
dispose(): void;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
interface IResourceDisposalSets {
|
|
372
|
+
geometries: WeakSet<object>;
|
|
373
|
+
surfaces: WeakSet<object>;
|
|
374
|
+
textures: WeakSet<object>;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function loadWith<T>(loader: LoaderLike<T>, url: string): Promise<T> {
|
|
378
|
+
return new Promise((resolve, reject) => loader.load(url, resolve, undefined, reject));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Extensions whose presence in a model's `extensionsUsed`/`extensionsRequired` triggers lazy
|
|
383
|
+
* decoder wiring. Read off the fetched bytes rather than out of the compile step's manifest
|
|
384
|
+
* so uncompiled paths and compiled outputs take exactly one code path.
|
|
385
|
+
*/
|
|
386
|
+
const MESHOPT_EXTENSIONS: readonly string[] = [
|
|
387
|
+
"EXT_meshopt_compression",
|
|
388
|
+
"KHR_meshopt_compression",
|
|
389
|
+
];
|
|
390
|
+
const DRACO_EXTENSION = "KHR_draco_mesh_compression";
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Reads `extensionsUsed`/`extensionsRequired` from a `.glb` or `.gltf` payload without full
|
|
394
|
+
* parsing. Malformed input yields an empty set here; GLTFLoader itself fails on it with its
|
|
395
|
+
* own error moments later.
|
|
396
|
+
*/
|
|
397
|
+
function declaredExtensions(data: ArrayBuffer): ReadonlySet<string> {
|
|
398
|
+
try {
|
|
399
|
+
const bytes = new Uint8Array(data);
|
|
400
|
+
const magic = String.fromCharCode(bytes[0] ?? 0, bytes[1] ?? 0, bytes[2] ?? 0, bytes[3] ?? 0);
|
|
401
|
+
const json =
|
|
402
|
+
magic === "glTF"
|
|
403
|
+
? JSON.parse(
|
|
404
|
+
new TextDecoder().decode(
|
|
405
|
+
bytes.subarray(20, 20 + new DataView(data).getUint32(12, true)),
|
|
406
|
+
),
|
|
407
|
+
)
|
|
408
|
+
: JSON.parse(new TextDecoder().decode(bytes));
|
|
409
|
+
return new Set([
|
|
410
|
+
...(typeof json.extensionsUsed === "object" && Array.isArray(json.extensionsUsed)
|
|
411
|
+
? (json.extensionsUsed as string[])
|
|
412
|
+
: []),
|
|
413
|
+
...(typeof json.extensionsRequired === "object" && Array.isArray(json.extensionsRequired)
|
|
414
|
+
? (json.extensionsRequired as string[])
|
|
415
|
+
: []),
|
|
416
|
+
]);
|
|
417
|
+
} catch {
|
|
418
|
+
return new Set();
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async function fetchModelBytes(url: string): Promise<ArrayBuffer> {
|
|
423
|
+
let response: Response;
|
|
424
|
+
try {
|
|
425
|
+
response = await fetch(url);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
throw new Error(
|
|
428
|
+
`Failed to load model '${url}': ${error instanceof Error ? error.message : String(error)}.`,
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
if (!response.ok) throw new Error(`Failed to load model '${url}': ${response.status}.`);
|
|
432
|
+
return response.arrayBuffer();
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Loads a texture with its pixels already decoded, off the main thread.
|
|
437
|
+
*
|
|
438
|
+
* `TextureLoader` hands the bytes to an `<img>`, whose `onload` fires before the pixels exist:
|
|
439
|
+
* `await ctx.assets.texture()` therefore resolves early and the decode lands later, on the main
|
|
440
|
+
* thread, at the first GPU upload — after the loading screen has lifted, in the middle of play.
|
|
441
|
+
* Measured over 16 real game textures (38 MB, 126 MB decoded), the decode is 397 ms through
|
|
442
|
+
* `<img>` and 153 ms through `createImageBitmap`. three's own `GLTFLoader` already prefers
|
|
443
|
+
* `ImageBitmapLoader` for a model's embedded textures, so before this the same file decoded
|
|
444
|
+
* off-thread inside a model and on the main thread when a game loaded it directly.
|
|
445
|
+
*
|
|
446
|
+
* **Orientation is the trap.** `TextureLoader` leaves `flipY` true and the backend flips at
|
|
447
|
+
* upload, which is the orientation every existing game is authored against. WebGPU can flip an
|
|
448
|
+
* `ImageBitmap` at copy time and does, so that branch keeps `flipY` and asks for the natural
|
|
449
|
+
* orientation — which is also what the native host has always done. WebGL2 cannot flip an
|
|
450
|
+
* `ImageBitmap` at all and silently ignores `flipY`, so that branch asks the browser to decode
|
|
451
|
+
* it flipped instead. Both land on the pixels `TextureLoader` would have produced; getting this
|
|
452
|
+
* wrong turns every standalone texture upside down with no error anywhere.
|
|
453
|
+
*/
|
|
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()]);
|
|
458
|
+
// No renderer means the native host or a bare-node load, both of which flip at upload.
|
|
459
|
+
const flipsAtUpload =
|
|
460
|
+
renderer === undefined ||
|
|
461
|
+
(renderer as { isWebGPURenderer?: boolean }).isWebGPURenderer === true;
|
|
462
|
+
const bitmap = await (flipsAtUpload
|
|
463
|
+
? createImageBitmap(blob)
|
|
464
|
+
: createImageBitmap(blob, { imageOrientation: "flipY" }));
|
|
465
|
+
const texture = new Texture(bitmap);
|
|
466
|
+
texture.flipY = flipsAtUpload;
|
|
467
|
+
texture.needsUpdate = true;
|
|
468
|
+
return texture;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** True when the caller asked for per-asset timing; read once per settle, not per frame. */
|
|
472
|
+
function assetTraceEnabled(): boolean {
|
|
473
|
+
// quality-allow: the playtest runner sets this global by its exact name.
|
|
474
|
+
// biome-ignore lint/style/useNamingConvention: a global the playtest runner sets by this exact name.
|
|
475
|
+
return (globalThis as { __TN_ASSET_TRACE__?: unknown }).__TN_ASSET_TRACE__ === true;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function performanceNow(): number {
|
|
479
|
+
return globalThis.performance?.now() ?? Date.now();
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function resourcePathOf(url: string): string {
|
|
483
|
+
const slash = url.lastIndexOf("/");
|
|
484
|
+
return slash === -1 ? "" : url.slice(0, slash + 1);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function platformName(): string {
|
|
488
|
+
const nav = (globalThis as { navigator?: { userAgent?: string } }).navigator;
|
|
489
|
+
return nav?.userAgent ?? "unknown platform";
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function attachLightmap(value: unknown, specification: ICompiledLightmap, texture: Texture): void {
|
|
493
|
+
const targets = new Set(specification.materialTargets);
|
|
494
|
+
let assignments = 0;
|
|
495
|
+
for (const root of modelRoots(value)) {
|
|
496
|
+
root.traverse((object) => {
|
|
497
|
+
const renderable = object as Object3D & {
|
|
498
|
+
geometry?: { getAttribute(name: string): unknown };
|
|
499
|
+
material?: unknown;
|
|
500
|
+
};
|
|
501
|
+
const materials = Array.isArray(renderable.material)
|
|
502
|
+
? renderable.material
|
|
503
|
+
: [renderable.material];
|
|
504
|
+
for (const material of materials) {
|
|
505
|
+
if (!isRecord(material) || !targets.has(String(material.name ?? ""))) continue;
|
|
506
|
+
if (
|
|
507
|
+
renderable.geometry?.getAttribute(`uv${String(specification.texCoord)}`) === undefined
|
|
508
|
+
) {
|
|
509
|
+
throw new Error(
|
|
510
|
+
`TN_ASSETS_LIGHTMAP_UV2_MISSING: material '${String(material.name ?? "")}' has no TEXCOORD_1 geometry.`,
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
material.lightMap = texture;
|
|
514
|
+
material.needsUpdate = true;
|
|
515
|
+
assignments += 1;
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
if (assignments === 0) {
|
|
520
|
+
throw new Error(
|
|
521
|
+
`TN_ASSETS_LIGHTMAP_TARGET_MISSING: no loaded material matches ${JSON.stringify(specification.materialTargets)}.`,
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Builds the one shared `KTX2Loader`: transcoder served from the compile step's copy under
|
|
528
|
+
* `<basePath>basis/`, support detected against the real renderer exactly once. Resolves
|
|
529
|
+
* `undefined` when the renderer cannot be probed at all — neither a WebGPU feature surface
|
|
530
|
+
* nor WebGL extensions, which is what minimal stubs and exotic backends look like. A
|
|
531
|
+
* renderer that probes fine but supports no compressed format rejects: three's own loader
|
|
532
|
+
* would silently fall back to an uncompressed RGBA32 upload, which is precisely the 16 MB
|
|
533
|
+
* this exists to prevent, so the failure happens here, naming the renderer and platform.
|
|
534
|
+
*/
|
|
535
|
+
function transcoderWorkers(): number {
|
|
536
|
+
const cores = (globalThis.navigator as { hardwareConcurrency?: number } | undefined)
|
|
537
|
+
?.hardwareConcurrency;
|
|
538
|
+
return typeof cores === "number" && cores > 0 ? Math.max(2, Math.min(8, cores - 2)) : 4;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
export async function createKtx2Loader(options: {
|
|
542
|
+
basePath?: string;
|
|
543
|
+
renderer: unknown;
|
|
544
|
+
}): Promise<IKTX2LoaderLike | undefined> {
|
|
545
|
+
const { KTX2Loader } = await import("three/addons/loaders/KTX2Loader.js");
|
|
546
|
+
const loader = new KTX2Loader();
|
|
547
|
+
loader.setTranscoderPath(resolvePath(options.basePath ?? "", "basis/"));
|
|
548
|
+
// three's default is 4 transcoder workers; a streamed world decodes hundreds of textures while
|
|
549
|
+
// it moves, so use the machine's cores (leaving two for the main thread and the compositor).
|
|
550
|
+
loader.setWorkerLimit(transcoderWorkers());
|
|
551
|
+
let config: Record<string, boolean> | undefined;
|
|
552
|
+
try {
|
|
553
|
+
// The structural contract is what matters; three's own parameter type is narrower than
|
|
554
|
+
// every renderer-shaped object core accepts (including platform sources and test stubs).
|
|
555
|
+
loader.detectSupport(options.renderer as Parameters<typeof loader.detectSupport>[0]);
|
|
556
|
+
config = (loader as unknown as { workerConfig?: Record<string, boolean> }).workerConfig;
|
|
557
|
+
} catch {
|
|
558
|
+
return undefined;
|
|
559
|
+
}
|
|
560
|
+
const supported = config === undefined ? [] : Object.values(config).filter(Boolean);
|
|
561
|
+
if (supported.length === 0) {
|
|
562
|
+
const kind =
|
|
563
|
+
(options.renderer as { isWebGPURenderer?: boolean } | undefined)?.isWebGPURenderer === true
|
|
564
|
+
? "webgpu"
|
|
565
|
+
: "webgl2";
|
|
566
|
+
throw new Error(
|
|
567
|
+
`TN_ASSETS_KTX2_UNSUPPORTED: the ${kind} renderer on ${platformName()} supports no compressed texture format; compiled KTX2 textures cannot be transcoded here.`,
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
return loader as unknown as IKTX2LoaderLike;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function hasAstcSupport(loader: IKTX2LoaderLike | undefined): boolean {
|
|
574
|
+
return (
|
|
575
|
+
(loader as (IKTX2LoaderLike & { workerConfig?: { astcSupported?: boolean } }) | undefined)
|
|
576
|
+
?.workerConfig?.astcSupported === true
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function astcUnsupported(asset: IManifestAstcAsset): Error {
|
|
581
|
+
return new Error(
|
|
582
|
+
`TN_ASSETS_ASTC_UNSUPPORTED: '${asset.logicalPath}' uses raw ASTC 4x4 output '${asset.output}', but the renderer lacks ASTC texture-compression support.`,
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async function prepareCompressedTextures(
|
|
587
|
+
manifest: IAssetManifest | undefined,
|
|
588
|
+
loader: Promise<IKTX2LoaderLike | undefined>,
|
|
589
|
+
): Promise<void> {
|
|
590
|
+
const astcAsset = firstRawAstcManifestAsset(manifest);
|
|
591
|
+
if (astcAsset !== undefined) {
|
|
592
|
+
try {
|
|
593
|
+
const shared = await loader;
|
|
594
|
+
if (!hasAstcSupport(shared)) throw astcUnsupported(astcAsset);
|
|
595
|
+
} catch (error) {
|
|
596
|
+
if (error instanceof Error && error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:")) {
|
|
597
|
+
throw astcUnsupported(astcAsset);
|
|
598
|
+
}
|
|
599
|
+
throw error;
|
|
600
|
+
}
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
if (Object.values(manifest?.entries ?? {}).some(entryUsesKtx2)) await loader;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Widen every quantized `POSITION` a loaded model carries back to float32.
|
|
608
|
+
*
|
|
609
|
+
* The asset pipeline emits `KHR_mesh_quantization`, so positions arrive as *normalized* int16:
|
|
610
|
+
* each component encodes a value in [-1, 1] and the real metre scale lives on the node (or, for a
|
|
611
|
+
* skinned mesh, in the inverse bind matrices). That is a correct glTF file and three renders it
|
|
612
|
+
* correctly — but it is a landmine for the game, because three's own geometry helpers write back
|
|
613
|
+
* through `BufferAttribute.setXYZ`, which **re-normalizes and clamps to +/-1**. `applyMatrix4`,
|
|
614
|
+
* `translate`, `scale`, `rotateX/Y/Z`, `center` and `toNonIndexed` all take that path. A game that
|
|
615
|
+
* bakes a node transform into an imported prop — the most ordinary thing there is to do with one —
|
|
616
|
+
* gets every vertex past 1 unit slammed onto the faces of the unit cube, with no error, no warning
|
|
617
|
+
* and a perfectly valid draw of ruined geometry. Wildwood lost 99.7% of a pine's canopy that way.
|
|
618
|
+
*
|
|
619
|
+
* Widening costs 2 bytes per component in RAM and changes nothing on screen: the values written are
|
|
620
|
+
* exactly what `getX/getY/getZ` already returned. The wire payload keeps the pipeline's win.
|
|
621
|
+
*
|
|
622
|
+
* Meshopt-compressed models decode to `InterleavedBufferAttribute`, which is not a `BufferAttribute`
|
|
623
|
+
* at all — an `instanceof BufferAttribute` guard here silently skips every compressed model, which
|
|
624
|
+
* is most of them. Read through the attribute interface both types share instead.
|
|
625
|
+
*/
|
|
626
|
+
function widenQuantizedPositions(root: Object3D): void {
|
|
627
|
+
const widened = new Set<BufferGeometry>();
|
|
628
|
+
root.traverse((object) => {
|
|
629
|
+
if (!(object instanceof Mesh)) return;
|
|
630
|
+
const geometry = object.geometry as BufferGeometry;
|
|
631
|
+
if (widened.has(geometry)) return;
|
|
632
|
+
const position = geometry.getAttribute("position");
|
|
633
|
+
if (position === undefined) return;
|
|
634
|
+
const plain = position instanceof BufferAttribute;
|
|
635
|
+
if (plain && !position.normalized && position.array instanceof Float32Array) return;
|
|
636
|
+
const values = new Float32Array(position.count * 3);
|
|
637
|
+
for (let index = 0; index < position.count; index += 1) {
|
|
638
|
+
values[index * 3] = position.getX(index);
|
|
639
|
+
values[index * 3 + 1] = position.getY(index);
|
|
640
|
+
values[index * 3 + 2] = position.getZ(index);
|
|
641
|
+
}
|
|
642
|
+
geometry.setAttribute("position", new BufferAttribute(values, 3));
|
|
643
|
+
widened.add(geometry);
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Widens every normalized one-component integer attribute to float. three picks a one-component
|
|
649
|
+
* WebGPU vertex format from the array type alone and ignores `normalized`, so a cooked scalar in
|
|
650
|
+
* [0, 1] — a baked wind weight, say — reaches the pipeline as `uint16` where a TSL float attribute
|
|
651
|
+
* expects a float, and the pipeline fails to build. Same values, read through `getX`, so a meshopt
|
|
652
|
+
* interleaved attribute widens too.
|
|
653
|
+
*/
|
|
654
|
+
function widenNormalizedScalars(root: Object3D): void {
|
|
655
|
+
const widened = new Set<BufferGeometry>();
|
|
656
|
+
root.traverse((object) => {
|
|
657
|
+
if (!(object instanceof Mesh)) return;
|
|
658
|
+
const geometry = object.geometry as BufferGeometry;
|
|
659
|
+
if (widened.has(geometry)) return;
|
|
660
|
+
widened.add(geometry);
|
|
661
|
+
for (const [name, attribute] of Object.entries(geometry.attributes)) {
|
|
662
|
+
if (attribute.itemSize !== 1 || !attribute.normalized) continue;
|
|
663
|
+
const values = new Float32Array(attribute.count);
|
|
664
|
+
for (let index = 0; index < attribute.count; index += 1)
|
|
665
|
+
values[index] = attribute.getX(index);
|
|
666
|
+
geometry.setAttribute(name, new BufferAttribute(values, 1));
|
|
667
|
+
}
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** The `{ scene }` a GLTF result carries, when it carries one. */
|
|
672
|
+
function modelRoot(value: unknown): Object3D | undefined {
|
|
673
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
674
|
+
const scene = (value as { scene?: unknown }).scene;
|
|
675
|
+
return scene instanceof Object3D ? scene : undefined;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** The `{ animations }` a GLTF result carries, when it carries well-formed ones. */
|
|
679
|
+
function modelClips(value: unknown): readonly AnimationClip[] {
|
|
680
|
+
if (typeof value !== "object" || value === null) return [];
|
|
681
|
+
const animations = (value as { animations?: unknown }).animations;
|
|
682
|
+
return Array.isArray(animations) ? (animations as AnimationClip[]) : [];
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** Below this a bone's bind translation along Z carries no vote: there is nothing to negate. */
|
|
686
|
+
const MIRROR_VOTE_FLOOR = 1e-6;
|
|
687
|
+
/** A translation track must actually hold the offset for its vote to count, not pass through zero. */
|
|
688
|
+
const MIRROR_VOTE_HOLD = 0.25;
|
|
689
|
+
/** The share of voting bones that must read mirrored before the loader repairs the clips. */
|
|
690
|
+
const MIRROR_VOTE_SHARE = 0.8;
|
|
691
|
+
/** Fewer voting bones than this cannot carry the decision, whatever they read. */
|
|
692
|
+
const MIRROR_VOTE_MINIMUM = 4;
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Repair an exported rig whose clips are Z-mirrored against its own bind pose, in place.
|
|
696
|
+
*
|
|
697
|
+
* The signature (PRD-324, the whole Wildwood animal pack): the file's bind faces its own +Z, but
|
|
698
|
+
* every animation track is expressed in a Z-mirrored frame — position tracks hold `(x, y, −z)`
|
|
699
|
+
* where the bind holds `(x, y, z)`, and quaternion tracks hold `(−x, −y, z, w)`, the conjugation
|
|
700
|
+
* of the same mirror. Played as authored, every animal faces backwards with its spine folded:
|
|
701
|
+
* head behind pelvis, healthy bone lengths, zero errors anywhere.
|
|
702
|
+
*
|
|
703
|
+
* An exporter writes exactly this when it converts a rig's bind to one convention and forgets its
|
|
704
|
+
* animation tracks. The loader repairs it before the game ever sees it: detection votes per
|
|
705
|
+
* tracked bone on whether the clip's translation Z sits negated against the bind, and only an
|
|
706
|
+
* overwhelming vote (at least `MIRROR_VOTE_MINIMUM` bones, `MIRROR_VOTE_SHARE` of them) converts
|
|
707
|
+
* every track — positions negate Z, quaternions negate X and Y, once, across all clips. A file
|
|
708
|
+
* that does not carry the signature is left byte-identical.
|
|
709
|
+
*/
|
|
710
|
+
export function reconcileMirroredClips(root: Object3D, clips: readonly AnimationClip[]): boolean {
|
|
711
|
+
if (clips.length === 0) return false;
|
|
712
|
+
const bones = new Map<string, Bone>();
|
|
713
|
+
root.traverse((object) => {
|
|
714
|
+
if ((object as Bone).isBone === true) bones.set(object.name, object as Bone);
|
|
715
|
+
});
|
|
716
|
+
if (bones.size === 0) return false;
|
|
717
|
+
|
|
718
|
+
let voters = 0;
|
|
719
|
+
let mirrored = 0;
|
|
720
|
+
for (const clip of clips) {
|
|
721
|
+
for (const track of clip.tracks) {
|
|
722
|
+
const dot = track.name.lastIndexOf(".");
|
|
723
|
+
if (track.name.slice(dot + 1) !== "position") continue;
|
|
724
|
+
const bone = bones.get(track.name.slice(0, dot));
|
|
725
|
+
if (bone === undefined) continue;
|
|
726
|
+
const bindZ = bone.position.z;
|
|
727
|
+
if (Math.abs(bindZ) < MIRROR_VOTE_FLOOR) continue;
|
|
728
|
+
const values = track.values;
|
|
729
|
+
let sum = 0;
|
|
730
|
+
let count = 0;
|
|
731
|
+
for (let index = 2; index < values.length; index += 3) {
|
|
732
|
+
sum += values[index] ?? 0;
|
|
733
|
+
count += 1;
|
|
734
|
+
}
|
|
735
|
+
if (count === 0) continue;
|
|
736
|
+
const meanZ = sum / count;
|
|
737
|
+
// A track that never holds the offset votes neither way.
|
|
738
|
+
if (Math.abs(meanZ) < Math.abs(bindZ) * MIRROR_VOTE_HOLD) continue;
|
|
739
|
+
voters += 1;
|
|
740
|
+
if (Math.abs(meanZ + bindZ) < Math.abs(meanZ - bindZ)) mirrored += 1;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if (voters < MIRROR_VOTE_MINIMUM || mirrored / voters < MIRROR_VOTE_SHARE) return false;
|
|
744
|
+
|
|
745
|
+
for (const clip of clips) {
|
|
746
|
+
for (const track of clip.tracks) {
|
|
747
|
+
const dot = track.name.lastIndexOf(".");
|
|
748
|
+
const property = track.name.slice(dot + 1);
|
|
749
|
+
const values = track.values;
|
|
750
|
+
if (property === "position") {
|
|
751
|
+
for (let index = 2; index < values.length; index += 3) {
|
|
752
|
+
values[index] = -(values[index] ?? 0);
|
|
753
|
+
}
|
|
754
|
+
} else if (property === "quaternion") {
|
|
755
|
+
for (let index = 0; index < values.length; index += 4) {
|
|
756
|
+
values[index] = -(values[index] ?? 0);
|
|
757
|
+
values[index + 1] = -(values[index + 1] ?? 0);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return true;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoader {
|
|
766
|
+
const basePath = options.basePath ?? "";
|
|
767
|
+
// `assets` is what `@threenative/assets` compiles from unless a project says otherwise, so it is
|
|
768
|
+
// where an unbaked game's files are. A project that moved its sources passes `sourcePath`.
|
|
769
|
+
const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/gu, "");
|
|
770
|
+
const manifestUrl = resolvePath(basePath, options.manifest ?? "assets.manifest.json");
|
|
771
|
+
let manifestRequest: Promise<IAssetManifest | undefined> | undefined;
|
|
772
|
+
const manifestOnce = (): Promise<IAssetManifest | undefined> => {
|
|
773
|
+
if (manifestRequest === undefined) manifestRequest = readManifest(manifestUrl);
|
|
774
|
+
return manifestRequest;
|
|
775
|
+
};
|
|
776
|
+
// Detection still runs exactly once, but `ready` only makes unsupported compressed textures a
|
|
777
|
+
// boot error when this build actually published KTX2 output. Native-safe manifests and the
|
|
778
|
+
// no-manifest fallback must not fail merely because a renderer exposes no compressed format.
|
|
779
|
+
const compressedTextures =
|
|
780
|
+
options.renderer === undefined
|
|
781
|
+
? undefined
|
|
782
|
+
: (() => {
|
|
783
|
+
const loader = createKtx2Loader({ basePath, renderer: options.renderer });
|
|
784
|
+
const ready = manifestOnce().then((manifest) =>
|
|
785
|
+
prepareCompressedTextures(manifest, loader),
|
|
786
|
+
);
|
|
787
|
+
loader.catch(() => undefined);
|
|
788
|
+
ready.catch(() => undefined);
|
|
789
|
+
return { loader, ready };
|
|
790
|
+
})();
|
|
791
|
+
const cache = new Map<string, IAssetEntry>();
|
|
792
|
+
/** Logical path → the url that actually served it, and the pipeline that url came from. */
|
|
793
|
+
const resolvedAssets = new Map<string, IResolvedAsset>();
|
|
794
|
+
const disposed: IResourceDisposalSets = {
|
|
795
|
+
geometries: new WeakSet(),
|
|
796
|
+
surfaces: new WeakSet(),
|
|
797
|
+
textures: new WeakSet(),
|
|
798
|
+
};
|
|
799
|
+
|
|
800
|
+
const loadCompiledKtx2 = async (url: string): Promise<Texture> => {
|
|
801
|
+
if (compressedTextures === undefined) {
|
|
802
|
+
throw new Error(
|
|
803
|
+
`TN_ASSETS_KTX2_NO_RENDERER: '${url}' is compiled compressed output; construct the asset loader with { renderer } so KTX2 support can be detected.`,
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
const shared = await compressedTextures.loader;
|
|
807
|
+
if (shared === undefined) {
|
|
808
|
+
throw new Error(
|
|
809
|
+
`TN_ASSETS_KTX2_UNPROBED: '${url}' is compiled compressed output but the provided renderer exposes no support-detection surface (neither WebGPU features nor WebGL extensions).`,
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
const texture = await loadWith(shared, url);
|
|
813
|
+
if (texture.format === RGBA_ASTC_4x4_Format && !hasAstcSupport(shared)) {
|
|
814
|
+
texture.dispose();
|
|
815
|
+
throw new Error(
|
|
816
|
+
`TN_ASSETS_ASTC_UNSUPPORTED: '${url}' contains raw ASTC 4x4 but the renderer lacks ASTC texture-compression support.`,
|
|
817
|
+
);
|
|
818
|
+
}
|
|
819
|
+
return texture;
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
const attachCompiledLightmaps = async (logicalPath: string, value: unknown): Promise<void> => {
|
|
823
|
+
if (isExternalAssetPath(logicalPath)) return;
|
|
824
|
+
const manifest = await manifestOnce();
|
|
825
|
+
const lightmaps = compiledLightmaps(manifest?.entries[logicalPath], logicalPath);
|
|
826
|
+
for (const specification of lightmaps) {
|
|
827
|
+
const resolved = resolvePath(basePath, specification.output);
|
|
828
|
+
let texture: Texture;
|
|
829
|
+
try {
|
|
830
|
+
texture = await loadCompiledKtx2(resolved);
|
|
831
|
+
} catch (error) {
|
|
832
|
+
throw new Error(
|
|
833
|
+
`TN_ASSETS_LIGHTMAP_MISSING: could not load '${resolved}': ${error instanceof Error ? error.message : String(error)}`,
|
|
834
|
+
);
|
|
835
|
+
}
|
|
836
|
+
texture.channel = specification.texCoord;
|
|
837
|
+
try {
|
|
838
|
+
attachLightmap(value, specification, texture);
|
|
839
|
+
} catch (error) {
|
|
840
|
+
texture.dispose();
|
|
841
|
+
throw error;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
// Cache keys stay on the logical path so `release` matches whatever was loaded with or
|
|
847
|
+
// without a manifest; loaders always receive the fully resolved url.
|
|
848
|
+
/**
|
|
849
|
+
* The resolved runtime selection budget an asset was cooked with, read from the manifest entry.
|
|
850
|
+
* Absent — no manifest, an older cook, or a disabled asset — selects the built-in default budget
|
|
851
|
+
* so an extension-bearing file still refines and coarsens sensibly.
|
|
852
|
+
*/
|
|
853
|
+
const discretePolicy = async (logicalPath: string): Promise<IModelLodPolicy | undefined> => {
|
|
854
|
+
if (isExternalAssetPath(logicalPath)) return undefined;
|
|
855
|
+
const manifest = await manifestOnce();
|
|
856
|
+
const entry = manifest?.entries[logicalPath];
|
|
857
|
+
const lod = isRecord(entry) ? entry.lod : undefined;
|
|
858
|
+
const runtime = isRecord(lod) ? lod.runtime : undefined;
|
|
859
|
+
if (
|
|
860
|
+
!isRecord(runtime) ||
|
|
861
|
+
typeof runtime.maxPixelError !== "number" ||
|
|
862
|
+
typeof runtime.hysteresis !== "number"
|
|
863
|
+
) {
|
|
864
|
+
return undefined;
|
|
865
|
+
}
|
|
866
|
+
return { hysteresis: runtime.hysteresis, maxPixelError: runtime.maxPixelError };
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Where a logical path might live, in the order worth trying.
|
|
871
|
+
*
|
|
872
|
+
* With a manifest there is exactly one answer, and a path the manifest does not list is an
|
|
873
|
+
* error rather than a guess. Without one there are two, and both are real games:
|
|
874
|
+
*
|
|
875
|
+
* - a project with **no asset pipeline** puts its files straight into `public/` and refers to
|
|
876
|
+
* them by name, so the verbatim path is right;
|
|
877
|
+
* - a project **whose compiled output has been removed** still has its sources under
|
|
878
|
+
* `assets/`, and the content-addressed name the manifest would have given is gone with it.
|
|
879
|
+
*
|
|
880
|
+
* The second case is the delete-test — *delete the entire baked output and the game runs
|
|
881
|
+
* identically, just slower* — and it could not pass while only the first was tried: the loader
|
|
882
|
+
* asked for `/rock.png`, which exists nowhere in a compiled project, and the game never booted.
|
|
883
|
+
*/
|
|
884
|
+
const resolveCandidates = async (path: string): Promise<ICandidateUrls> => {
|
|
885
|
+
if (isExternalAssetPath(path)) return { urls: [path], via: "source" };
|
|
886
|
+
const manifest = await manifestOnce();
|
|
887
|
+
if (manifest !== undefined) {
|
|
888
|
+
const listed = manifest.entries[path];
|
|
889
|
+
const output = isRecord(listed) ? listed.output : undefined;
|
|
890
|
+
if (typeof output !== "string") {
|
|
891
|
+
throw new Error(`Asset '${path}' is not listed in the asset manifest '${manifestUrl}'.`);
|
|
892
|
+
}
|
|
893
|
+
return { urls: [resolvePath(basePath, output)], via: "manifest" };
|
|
894
|
+
}
|
|
895
|
+
const verbatim = resolvePath(basePath, path);
|
|
896
|
+
if (sourcePath === "") return { urls: [verbatim], via: "source" };
|
|
897
|
+
const fromSource = resolvePath(basePath, `${sourcePath}/${path}`);
|
|
898
|
+
return fromSource === verbatim
|
|
899
|
+
? { urls: [verbatim], via: "source" }
|
|
900
|
+
: { urls: [verbatim, fromSource], via: "source" };
|
|
901
|
+
};
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* Loads from the first candidate that works, and names every one it tried when none do.
|
|
905
|
+
*
|
|
906
|
+
* A single combined error matters more than it looks: the failure this replaces reported only
|
|
907
|
+
* the last url, so "the game cannot find its texture" read as one missing file rather than as
|
|
908
|
+
* two places that were looked at and neither had it.
|
|
909
|
+
*/
|
|
910
|
+
const loadFirst = async <T>(
|
|
911
|
+
path: string,
|
|
912
|
+
{ urls, via }: ICandidateUrls,
|
|
913
|
+
load: (url: string) => Promise<T>,
|
|
914
|
+
): Promise<T> => {
|
|
915
|
+
const failures: string[] = [];
|
|
916
|
+
for (const url of urls) {
|
|
917
|
+
try {
|
|
918
|
+
const value = await load(url);
|
|
919
|
+
// Recorded here, where the winner is known and nowhere else: a caller that asks which
|
|
920
|
+
// url served its bytes gets the one that did, not the first one that was tried.
|
|
921
|
+
resolvedAssets.set(path, { url, via });
|
|
922
|
+
return value;
|
|
923
|
+
} catch (error) {
|
|
924
|
+
failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
throw new Error(
|
|
928
|
+
`TN_ASSETS_UNRESOLVED: '${path}' could not be loaded from ${urls.length} candidate url(s): ${failures.join("; ")}`,
|
|
929
|
+
);
|
|
930
|
+
};
|
|
931
|
+
|
|
932
|
+
let requested = 0;
|
|
933
|
+
let requestedBytes = 0;
|
|
934
|
+
let settled = 0;
|
|
935
|
+
let settledBytes = 0;
|
|
936
|
+
/** Logical paths asked for and not yet settled, in request order — what a loading view names. */
|
|
937
|
+
const pending = new Set<string>();
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* The compiled size of a logical path, or 0 when it is not knowable — no manifest, an external
|
|
941
|
+
* url, or an entry the compile step wrote without a size. Zero is the honest answer and keeps
|
|
942
|
+
* both byte counters at zero, which is the signal a reader uses to fall back to the file ratio.
|
|
943
|
+
*/
|
|
944
|
+
const bytesOf = async (path: string): Promise<number> => {
|
|
945
|
+
if (isExternalAssetPath(path)) return 0;
|
|
946
|
+
const manifest = await manifestOnce();
|
|
947
|
+
const entry = manifest?.entries[path];
|
|
948
|
+
const bytes = isRecord(entry) ? entry.bytes : undefined;
|
|
949
|
+
return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
const cached = <T>(kind: string, path: string, load: (url: string) => Promise<T>): Promise<T> => {
|
|
953
|
+
const key = `${kind}:${path}`;
|
|
954
|
+
const existing = cache.get(key);
|
|
955
|
+
if (existing !== undefined) return existing.promise as Promise<T>;
|
|
956
|
+
requested += 1;
|
|
957
|
+
// The size is only knowable once the manifest lands, so this load's weight joins the
|
|
958
|
+
// denominator a tick later than its count. Recorded here rather than inside the load chain
|
|
959
|
+
// so a load that fails still contributes the same weight to both sides of the ratio.
|
|
960
|
+
let weight = 0;
|
|
961
|
+
const weighed = bytesOf(path).then(
|
|
962
|
+
(bytes) => {
|
|
963
|
+
weight = bytes;
|
|
964
|
+
requestedBytes += bytes;
|
|
965
|
+
},
|
|
966
|
+
() => undefined,
|
|
967
|
+
);
|
|
968
|
+
// Opt-in per-asset timing, off by default and free when off: a launch that is slow because of
|
|
969
|
+
// *which* asset is slow cannot be told from the group totals a game logs, and the engine is the
|
|
970
|
+
// only place that sees every settle. Set `globalThis.__TN_ASSET_TRACE__ = true` before boot.
|
|
971
|
+
const traceStart = assetTraceEnabled() ? performanceNow() : 0;
|
|
972
|
+
const entry: IAssetEntry = {
|
|
973
|
+
disposed: false,
|
|
974
|
+
kind: kind as AssetKind,
|
|
975
|
+
loaded: false,
|
|
976
|
+
promise: Promise.resolve()
|
|
977
|
+
.then(() => resolveCandidates(path))
|
|
978
|
+
.then((candidates) => loadFirst(path, candidates, load)),
|
|
979
|
+
released: false,
|
|
980
|
+
};
|
|
981
|
+
entry.promise = entry.promise.then((value) => {
|
|
982
|
+
entry.loaded = true;
|
|
983
|
+
entry.value = value;
|
|
984
|
+
if (entry.released) disposeEntry(entry, disposed);
|
|
985
|
+
return value;
|
|
986
|
+
});
|
|
987
|
+
entry.promise.catch(() => {
|
|
988
|
+
if (cache.get(key) === entry) cache.delete(key);
|
|
989
|
+
});
|
|
990
|
+
pending.add(path);
|
|
991
|
+
const note = (): void => {
|
|
992
|
+
settled += 1;
|
|
993
|
+
pending.delete(path);
|
|
994
|
+
void weighed.then(() => {
|
|
995
|
+
settledBytes += weight;
|
|
996
|
+
});
|
|
997
|
+
if (traceStart !== 0) {
|
|
998
|
+
console.log(
|
|
999
|
+
`TN_ASSET:${JSON.stringify({
|
|
1000
|
+
bytes: weight,
|
|
1001
|
+
kind,
|
|
1002
|
+
ms: Math.round((performanceNow() - traceStart) * 10) / 10,
|
|
1003
|
+
path,
|
|
1004
|
+
})}`,
|
|
1005
|
+
);
|
|
1006
|
+
}
|
|
1007
|
+
};
|
|
1008
|
+
entry.promise.then(note, note);
|
|
1009
|
+
cache.set(key, entry);
|
|
1010
|
+
return entry.promise as Promise<T>;
|
|
1011
|
+
};
|
|
1012
|
+
|
|
1013
|
+
const releaseEntry = (entry: IAssetEntry): void => {
|
|
1014
|
+
entry.released = true;
|
|
1015
|
+
if (entry.loaded) disposeEntry(entry, disposed);
|
|
1016
|
+
else
|
|
1017
|
+
void entry.promise.then(
|
|
1018
|
+
() => disposeEntry(entry, disposed),
|
|
1019
|
+
() => undefined,
|
|
1020
|
+
);
|
|
1021
|
+
};
|
|
1022
|
+
|
|
1023
|
+
return {
|
|
1024
|
+
audio: (path) =>
|
|
1025
|
+
cached("audio", path, async (url) => {
|
|
1026
|
+
if (options.audio !== undefined) return options.audio(url);
|
|
1027
|
+
const { AudioLoader: Loader } = await import("three");
|
|
1028
|
+
return loadWith(new Loader() as AudioLoader, url);
|
|
1029
|
+
}),
|
|
1030
|
+
clear: () => {
|
|
1031
|
+
const entries = [...cache.values()];
|
|
1032
|
+
cache.clear();
|
|
1033
|
+
entries.forEach(releaseEntry);
|
|
1034
|
+
},
|
|
1035
|
+
...(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;
|
|
1069
|
+
}
|
|
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
|
+
);
|
|
1084
|
+
}
|
|
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]>,
|
|
1095
|
+
);
|
|
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
|
+
}),
|
|
1170
|
+
get progress() {
|
|
1171
|
+
return { pending: [...pending], requested, requestedBytes, settled, settledBytes };
|
|
1172
|
+
},
|
|
1173
|
+
resolve: async (path) => (await resolveCandidates(path)).urls,
|
|
1174
|
+
// A copy per read, like `progress`: a caller inspecting the record must not be able to
|
|
1175
|
+
// rewrite what the loader reports for the next asset that settles.
|
|
1176
|
+
get resolved(): ReadonlyMap<string, IResolvedAsset> {
|
|
1177
|
+
return new Map(resolvedAssets);
|
|
1178
|
+
},
|
|
1179
|
+
release: (kind, path) => {
|
|
1180
|
+
const key = `${kind}:${path}`;
|
|
1181
|
+
const entry = cache.get(key);
|
|
1182
|
+
if (entry === undefined) return false;
|
|
1183
|
+
cache.delete(key);
|
|
1184
|
+
releaseEntry(entry);
|
|
1185
|
+
return true;
|
|
1186
|
+
},
|
|
1187
|
+
texture: async (path, textureOptions) => {
|
|
1188
|
+
const texture = await cached("texture", path, async (url) => {
|
|
1189
|
+
if (options.texture !== undefined) return options.texture(url);
|
|
1190
|
+
// Compiled output carries the content-addressed extension: anything ending in .ktx2
|
|
1191
|
+
// goes through the shared KTX2 loader, everything else stays on TextureLoader.
|
|
1192
|
+
if (/\.ktx2$/iu.test(url)) {
|
|
1193
|
+
return loadCompiledKtx2(url);
|
|
1194
|
+
}
|
|
1195
|
+
if (typeof createImageBitmap === "function") {
|
|
1196
|
+
return loadBitmapTexture(url, options.renderer);
|
|
1197
|
+
}
|
|
1198
|
+
const { TextureLoader: Loader } = await import("three");
|
|
1199
|
+
return loadWith(new Loader() as TextureLoader, url);
|
|
1200
|
+
});
|
|
1201
|
+
return textureOptions === undefined ? texture : configuredTexture(texture, textureOptions);
|
|
1202
|
+
},
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
function disposeEntry(entry: IAssetEntry, disposed: IResourceDisposalSets): void {
|
|
1207
|
+
if (entry.disposed || !entry.loaded) return;
|
|
1208
|
+
entry.disposed = true;
|
|
1209
|
+
if (entry.kind === "model") disposeModel(entry.value, disposed);
|
|
1210
|
+
else if (entry.kind === "texture") disposeTexture(entry.value, disposed);
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
function disposeModel(value: unknown, disposed: IResourceDisposalSets): void {
|
|
1214
|
+
for (const root of modelRoots(value)) {
|
|
1215
|
+
root.traverse((object) => {
|
|
1216
|
+
const renderable = object as Object3D & { geometry?: unknown; [key: string]: unknown };
|
|
1217
|
+
disposeResource(renderable.geometry, disposed.geometries);
|
|
1218
|
+
disposeSurface(renderable["ma" + "terial"], disposed);
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
function modelRoots(value: unknown): Object3D[] {
|
|
1224
|
+
if (value instanceof Object3D) return [value];
|
|
1225
|
+
if (!isRecord(value)) return [];
|
|
1226
|
+
const roots = [value.scene, ...(Array.isArray(value.scenes) ? value.scenes : [])];
|
|
1227
|
+
return roots.filter((root): root is Object3D => root instanceof Object3D);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/**
|
|
1231
|
+
* Stamp the logical path the caller asked for onto the model roots a game adds to the scene.
|
|
1232
|
+
*
|
|
1233
|
+
* The stamp lives on the root and never on its descendants: three's `Object3D.copy` deep-copies
|
|
1234
|
+
* `userData`, so one stamp survives `.clone()` and every skeleton-safe clone an animation helper
|
|
1235
|
+
* makes — a clone keeps its provenance without the game annotating anything by hand. A result that
|
|
1236
|
+
* is a bare `Object3D` is stamped directly; a `Texture` or `AudioBuffer` is no `Object3D` root and
|
|
1237
|
+
* gets nothing. An existing non-empty stamp is never overwritten.
|
|
1238
|
+
*/
|
|
1239
|
+
function stampAssetProvenance(value: unknown, logicalPath: string): void {
|
|
1240
|
+
for (const root of modelRoots(value)) {
|
|
1241
|
+
const userData = root.userData as Record<string, unknown>;
|
|
1242
|
+
const existing = userData[GEOMETRY_ASSET_KEY];
|
|
1243
|
+
if (typeof existing === "string" && existing !== "") continue;
|
|
1244
|
+
userData[GEOMETRY_ASSET_KEY] = logicalPath;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function disposeSurface(value: unknown, disposed: IResourceDisposalSets): void {
|
|
1249
|
+
if (Array.isArray(value)) {
|
|
1250
|
+
for (const surface of value) disposeSurface(surface, disposed);
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
if (!isRecord(value)) return;
|
|
1254
|
+
if (disposed.surfaces.has(value)) return;
|
|
1255
|
+
disposeSurfaceTextures(value, disposed, new WeakSet<object>());
|
|
1256
|
+
disposeResource(value, disposed.surfaces);
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
function disposeSurfaceTextures(
|
|
1260
|
+
value: unknown,
|
|
1261
|
+
disposed: IResourceDisposalSets,
|
|
1262
|
+
visited: WeakSet<object>,
|
|
1263
|
+
): void {
|
|
1264
|
+
if (isTexture(value)) {
|
|
1265
|
+
disposeTexture(value, disposed);
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
if (typeof value !== "object" || value === null || visited.has(value)) return;
|
|
1269
|
+
visited.add(value);
|
|
1270
|
+
if (Array.isArray(value)) {
|
|
1271
|
+
for (const item of value) disposeSurfaceTextures(item, disposed, visited);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
for (const item of Object.values(value)) disposeSurfaceTextures(item, disposed, visited);
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
function disposeTexture(value: unknown, disposed: IResourceDisposalSets): void {
|
|
1278
|
+
if (!isDisposable(value) || disposed.textures.has(value)) return;
|
|
1279
|
+
disposed.textures.add(value);
|
|
1280
|
+
value.dispose();
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
function disposeResource(value: unknown, disposed: WeakSet<object>): void {
|
|
1284
|
+
if (!isDisposable(value) || disposed.has(value)) return;
|
|
1285
|
+
disposed.add(value);
|
|
1286
|
+
value.dispose();
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
function isDisposable(value: unknown): value is IDisposableResource & object {
|
|
1290
|
+
return (
|
|
1291
|
+
typeof value === "object" &&
|
|
1292
|
+
value !== null &&
|
|
1293
|
+
typeof (value as { dispose?: unknown }).dispose === "function"
|
|
1294
|
+
);
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function isTexture(value: unknown): value is Texture {
|
|
1298
|
+
return value instanceof Texture || (isRecord(value) && value.isTexture === true);
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1302
|
+
return typeof value === "object" && value !== null;
|
|
1303
|
+
}
|