@react-three/fiber 10.0.0-alpha.2 → 10.0.0-canary.164c7be
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/LICENSE +21 -21
- package/dist/index.cjs +1163 -1375
- package/dist/index.d.cts +1887 -1710
- package/dist/index.d.mts +1887 -1710
- package/dist/index.d.ts +1887 -1710
- package/dist/index.mjs +1124 -1354
- package/dist/legacy.cjs +1129 -1365
- package/dist/legacy.d.cts +1888 -1711
- package/dist/legacy.d.mts +1888 -1711
- package/dist/legacy.d.ts +1888 -1711
- package/dist/legacy.mjs +1090 -1344
- package/dist/webgpu/index.cjs +1720 -1486
- package/dist/webgpu/index.d.cts +2064 -1734
- package/dist/webgpu/index.d.mts +2064 -1734
- package/dist/webgpu/index.d.ts +2064 -1734
- package/dist/webgpu/index.mjs +1678 -1466
- package/package.json +4 -1
- package/readme.md +244 -318
package/dist/legacy.mjs
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import * as three from 'three';
|
|
2
|
-
import { WebGLRenderTarget, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1,
|
|
3
|
-
import { jsx, Fragment } from 'react/jsx-runtime';
|
|
2
|
+
import { WebGLRenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGLRenderer } from 'three';
|
|
3
|
+
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
|
|
4
4
|
import * as React from 'react';
|
|
5
|
-
import React__default, {
|
|
5
|
+
import React__default, { useLayoutEffect, useRef, useMemo, useEffect, useContext, useImperativeHandle, useCallback, useState } from 'react';
|
|
6
6
|
import useMeasure from 'react-use-measure';
|
|
7
7
|
import { useFiber, useContextBridge, traverseFiber, FiberProvider } from 'its-fine';
|
|
8
|
+
import { useThree as useThree$1, useLoader as useLoader$1, useFrame as useFrame$1, createPortal as createPortal$1, applyProps as applyProps$1, extend as extend$1 } from '@react-three/fiber';
|
|
9
|
+
import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
|
|
10
|
+
import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
|
|
11
|
+
import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js';
|
|
12
|
+
import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
|
|
13
|
+
import { GainMapLoader } from '@monogrid/gainmap-js';
|
|
8
14
|
import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
|
|
9
15
|
import { createWithEqualityFn } from 'zustand/traditional';
|
|
16
|
+
import { getScheduler } from '@pmndrs/scheduler';
|
|
17
|
+
export { Scheduler, getScheduler } from '@pmndrs/scheduler';
|
|
10
18
|
import { suspend, preload, clear } from 'suspend-react';
|
|
11
19
|
|
|
12
20
|
function _mergeNamespaces(n, m) {
|
|
@@ -45,9 +53,392 @@ const THREE = /*#__PURE__*/_mergeNamespaces({
|
|
|
45
53
|
WebGPURenderer: WebGPURenderer
|
|
46
54
|
}, [three]);
|
|
47
55
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
56
|
+
const primaryRegistry = /* @__PURE__ */ new Map();
|
|
57
|
+
const pendingSubscribers = /* @__PURE__ */ new Map();
|
|
58
|
+
function registerPrimary(id, renderer, store) {
|
|
59
|
+
if (primaryRegistry.has(id)) {
|
|
60
|
+
console.warn(`Canvas with id="${id}" already registered. Overwriting.`);
|
|
61
|
+
}
|
|
62
|
+
const entry = { renderer, store };
|
|
63
|
+
primaryRegistry.set(id, entry);
|
|
64
|
+
const subscribers = pendingSubscribers.get(id);
|
|
65
|
+
if (subscribers) {
|
|
66
|
+
subscribers.forEach((callback) => callback(entry));
|
|
67
|
+
pendingSubscribers.delete(id);
|
|
68
|
+
}
|
|
69
|
+
return () => {
|
|
70
|
+
const currentEntry = primaryRegistry.get(id);
|
|
71
|
+
if (currentEntry?.renderer === renderer) {
|
|
72
|
+
primaryRegistry.delete(id);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function getPrimary(id) {
|
|
77
|
+
return primaryRegistry.get(id);
|
|
78
|
+
}
|
|
79
|
+
function waitForPrimary(id, timeout = 5e3) {
|
|
80
|
+
const existing = primaryRegistry.get(id);
|
|
81
|
+
if (existing) {
|
|
82
|
+
return Promise.resolve(existing);
|
|
83
|
+
}
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const timeoutId = setTimeout(() => {
|
|
86
|
+
const subscribers = pendingSubscribers.get(id);
|
|
87
|
+
if (subscribers) {
|
|
88
|
+
const index = subscribers.indexOf(callback);
|
|
89
|
+
if (index !== -1) subscribers.splice(index, 1);
|
|
90
|
+
if (subscribers.length === 0) pendingSubscribers.delete(id);
|
|
91
|
+
}
|
|
92
|
+
reject(new Error(`Timeout waiting for canvas with id="${id}". Make sure a <Canvas id="${id}"> is mounted.`));
|
|
93
|
+
}, timeout);
|
|
94
|
+
const callback = (entry) => {
|
|
95
|
+
clearTimeout(timeoutId);
|
|
96
|
+
resolve(entry);
|
|
97
|
+
};
|
|
98
|
+
if (!pendingSubscribers.has(id)) {
|
|
99
|
+
pendingSubscribers.set(id, []);
|
|
100
|
+
}
|
|
101
|
+
pendingSubscribers.get(id).push(callback);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
function hasPrimary(id) {
|
|
105
|
+
return primaryRegistry.has(id);
|
|
106
|
+
}
|
|
107
|
+
function unregisterPrimary(id) {
|
|
108
|
+
primaryRegistry.delete(id);
|
|
109
|
+
}
|
|
110
|
+
function getPrimaryIds() {
|
|
111
|
+
return Array.from(primaryRegistry.keys());
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const presetsObj = {
|
|
115
|
+
apartment: "lebombo_1k.hdr",
|
|
116
|
+
city: "potsdamer_platz_1k.hdr",
|
|
117
|
+
dawn: "kiara_1_dawn_1k.hdr",
|
|
118
|
+
forest: "forest_slope_1k.hdr",
|
|
119
|
+
lobby: "st_fagans_interior_1k.hdr",
|
|
120
|
+
night: "dikhololo_night_1k.hdr",
|
|
121
|
+
park: "rooitou_park_1k.hdr",
|
|
122
|
+
studio: "studio_small_03_1k.hdr",
|
|
123
|
+
sunset: "venice_sunset_1k.hdr",
|
|
124
|
+
warehouse: "empty_warehouse_01_1k.hdr"
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const CUBEMAP_ROOT = "https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/";
|
|
128
|
+
const isArray = (arr) => Array.isArray(arr);
|
|
129
|
+
const defaultFiles = ["/px.png", "/nx.png", "/py.png", "/ny.png", "/pz.png", "/nz.png"];
|
|
130
|
+
function useEnvironment({
|
|
131
|
+
files = defaultFiles,
|
|
132
|
+
path = "",
|
|
133
|
+
preset = void 0,
|
|
134
|
+
colorSpace = void 0,
|
|
135
|
+
extensions
|
|
136
|
+
} = {}) {
|
|
137
|
+
if (preset) {
|
|
138
|
+
validatePreset(preset);
|
|
139
|
+
files = presetsObj[preset];
|
|
140
|
+
path = CUBEMAP_ROOT;
|
|
141
|
+
}
|
|
142
|
+
const multiFile = isArray(files);
|
|
143
|
+
const { extension, isCubemap } = getExtension(files);
|
|
144
|
+
const loader = getLoader$1(extension);
|
|
145
|
+
if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
|
|
146
|
+
const renderer = useThree$1((state) => state.renderer);
|
|
147
|
+
useLayoutEffect(() => {
|
|
148
|
+
if (extension !== "webp" && extension !== "jpg" && extension !== "jpeg") return;
|
|
149
|
+
function clearGainmapTexture() {
|
|
150
|
+
useLoader$1.clear(loader, multiFile ? [files] : files);
|
|
151
|
+
}
|
|
152
|
+
renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
|
|
153
|
+
}, [extension, files, loader, multiFile, renderer.domElement]);
|
|
154
|
+
const loaderResult = useLoader$1(
|
|
155
|
+
loader,
|
|
156
|
+
multiFile ? [files] : files,
|
|
157
|
+
(loader2) => {
|
|
158
|
+
if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
|
|
159
|
+
loader2.setRenderer?.(renderer);
|
|
160
|
+
}
|
|
161
|
+
loader2.setPath?.(path);
|
|
162
|
+
if (extensions) extensions(loader2);
|
|
163
|
+
}
|
|
164
|
+
);
|
|
165
|
+
let texture = multiFile ? (
|
|
166
|
+
// @ts-ignore
|
|
167
|
+
loaderResult[0]
|
|
168
|
+
) : loaderResult;
|
|
169
|
+
if (extension === "jpg" || extension === "jpeg" || extension === "webp") {
|
|
170
|
+
texture = texture.renderTarget?.texture;
|
|
171
|
+
}
|
|
172
|
+
texture.mapping = isCubemap ? CubeReflectionMapping : EquirectangularReflectionMapping;
|
|
173
|
+
texture.colorSpace = colorSpace ?? (isCubemap ? "srgb" : "srgb-linear");
|
|
174
|
+
return texture;
|
|
175
|
+
}
|
|
176
|
+
const preloadDefaultOptions = {
|
|
177
|
+
files: defaultFiles,
|
|
178
|
+
path: "",
|
|
179
|
+
preset: void 0,
|
|
180
|
+
extensions: void 0
|
|
181
|
+
};
|
|
182
|
+
useEnvironment.preload = (preloadOptions) => {
|
|
183
|
+
const options = { ...preloadDefaultOptions, ...preloadOptions };
|
|
184
|
+
let { files, path = "" } = options;
|
|
185
|
+
const { preset, extensions } = options;
|
|
186
|
+
if (preset) {
|
|
187
|
+
validatePreset(preset);
|
|
188
|
+
files = presetsObj[preset];
|
|
189
|
+
path = CUBEMAP_ROOT;
|
|
190
|
+
}
|
|
191
|
+
const { extension } = getExtension(files);
|
|
192
|
+
if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
|
|
193
|
+
throw new Error("useEnvironment: Preloading gainmaps is not supported");
|
|
194
|
+
}
|
|
195
|
+
const loader = getLoader$1(extension);
|
|
196
|
+
if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
|
|
197
|
+
useLoader$1.preload(loader, isArray(files) ? [files] : files, (loader2) => {
|
|
198
|
+
loader2.setPath?.(path);
|
|
199
|
+
if (extensions) extensions(loader2);
|
|
200
|
+
});
|
|
201
|
+
};
|
|
202
|
+
const clearDefaultOptins = {
|
|
203
|
+
files: defaultFiles,
|
|
204
|
+
preset: void 0
|
|
205
|
+
};
|
|
206
|
+
useEnvironment.clear = (clearOptions) => {
|
|
207
|
+
const options = { ...clearDefaultOptins, ...clearOptions };
|
|
208
|
+
let { files } = options;
|
|
209
|
+
const { preset } = options;
|
|
210
|
+
if (preset) {
|
|
211
|
+
validatePreset(preset);
|
|
212
|
+
files = presetsObj[preset];
|
|
213
|
+
}
|
|
214
|
+
const { extension } = getExtension(files);
|
|
215
|
+
const loader = getLoader$1(extension);
|
|
216
|
+
if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
|
|
217
|
+
useLoader$1.clear(loader, isArray(files) ? [files] : files);
|
|
218
|
+
};
|
|
219
|
+
function validatePreset(preset) {
|
|
220
|
+
if (!(preset in presetsObj)) throw new Error("Preset must be one of: " + Object.keys(presetsObj).join(", "));
|
|
221
|
+
}
|
|
222
|
+
function getExtension(files) {
|
|
223
|
+
const isCubemap = isArray(files) && files.length === 6;
|
|
224
|
+
const isGainmap = isArray(files) && files.length === 3 && files.some((file) => file.endsWith("json"));
|
|
225
|
+
const firstEntry = isArray(files) ? files[0] : files;
|
|
226
|
+
const extension = isCubemap ? "cube" : isGainmap ? "webp" : firstEntry.startsWith("data:application/exr") ? "exr" : firstEntry.startsWith("data:application/hdr") ? "hdr" : firstEntry.startsWith("data:image/jpeg") ? "jpg" : firstEntry.split(".").pop()?.split("?")?.shift()?.toLowerCase();
|
|
227
|
+
return { extension, isCubemap, isGainmap };
|
|
228
|
+
}
|
|
229
|
+
function getLoader$1(extension) {
|
|
230
|
+
const loader = extension === "cube" ? CubeTextureLoader : extension === "hdr" ? HDRLoader : extension === "exr" ? EXRLoader : extension === "jpg" || extension === "jpeg" ? UltraHDRLoader : extension === "webp" ? GainMapLoader : null;
|
|
231
|
+
return loader;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const isRef$1 = (obj) => obj.current && obj.current.isScene;
|
|
235
|
+
const resolveScene = (scene) => isRef$1(scene) ? scene.current : scene;
|
|
236
|
+
function setEnvProps(background, scene, defaultScene, texture, sceneProps = {}) {
|
|
237
|
+
sceneProps = {
|
|
238
|
+
backgroundBlurriness: 0,
|
|
239
|
+
backgroundIntensity: 1,
|
|
240
|
+
backgroundRotation: [0, 0, 0],
|
|
241
|
+
environmentIntensity: 1,
|
|
242
|
+
environmentRotation: [0, 0, 0],
|
|
243
|
+
...sceneProps
|
|
244
|
+
};
|
|
245
|
+
const target = resolveScene(scene || defaultScene);
|
|
246
|
+
const oldbg = target.background;
|
|
247
|
+
const oldenv = target.environment;
|
|
248
|
+
const oldSceneProps = {
|
|
249
|
+
// @ts-ignore
|
|
250
|
+
backgroundBlurriness: target.backgroundBlurriness,
|
|
251
|
+
// @ts-ignore
|
|
252
|
+
backgroundIntensity: target.backgroundIntensity,
|
|
253
|
+
// @ts-ignore
|
|
254
|
+
backgroundRotation: target.backgroundRotation?.clone?.() ?? [0, 0, 0],
|
|
255
|
+
// @ts-ignore
|
|
256
|
+
environmentIntensity: target.environmentIntensity,
|
|
257
|
+
// @ts-ignore
|
|
258
|
+
environmentRotation: target.environmentRotation?.clone?.() ?? [0, 0, 0]
|
|
259
|
+
};
|
|
260
|
+
if (background !== "only") target.environment = texture;
|
|
261
|
+
if (background) target.background = texture;
|
|
262
|
+
applyProps$1(target, sceneProps);
|
|
263
|
+
return () => {
|
|
264
|
+
if (background !== "only") target.environment = oldenv;
|
|
265
|
+
if (background) target.background = oldbg;
|
|
266
|
+
applyProps$1(target, oldSceneProps);
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function EnvironmentMap({ scene, background = false, map, ...config }) {
|
|
270
|
+
const defaultScene = useThree$1((state) => state.scene);
|
|
271
|
+
React.useLayoutEffect(() => {
|
|
272
|
+
if (map) return setEnvProps(background, scene, defaultScene, map, config);
|
|
273
|
+
});
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
function EnvironmentCube({
|
|
277
|
+
background = false,
|
|
278
|
+
scene,
|
|
279
|
+
blur,
|
|
280
|
+
backgroundBlurriness,
|
|
281
|
+
backgroundIntensity,
|
|
282
|
+
backgroundRotation,
|
|
283
|
+
environmentIntensity,
|
|
284
|
+
environmentRotation,
|
|
285
|
+
...rest
|
|
286
|
+
}) {
|
|
287
|
+
const texture = useEnvironment(rest);
|
|
288
|
+
const defaultScene = useThree$1((state) => state.scene);
|
|
289
|
+
React.useLayoutEffect(() => {
|
|
290
|
+
return setEnvProps(background, scene, defaultScene, texture, {
|
|
291
|
+
backgroundBlurriness: blur ?? backgroundBlurriness,
|
|
292
|
+
backgroundIntensity,
|
|
293
|
+
backgroundRotation,
|
|
294
|
+
environmentIntensity,
|
|
295
|
+
environmentRotation
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
React.useEffect(() => {
|
|
299
|
+
return () => {
|
|
300
|
+
texture.dispose();
|
|
301
|
+
};
|
|
302
|
+
}, [texture]);
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
function EnvironmentPortal({
|
|
306
|
+
children,
|
|
307
|
+
near = 0.1,
|
|
308
|
+
far = 1e3,
|
|
309
|
+
resolution = 256,
|
|
310
|
+
frames = 1,
|
|
311
|
+
map,
|
|
312
|
+
background = false,
|
|
313
|
+
blur,
|
|
314
|
+
backgroundBlurriness,
|
|
315
|
+
backgroundIntensity,
|
|
316
|
+
backgroundRotation,
|
|
317
|
+
environmentIntensity,
|
|
318
|
+
environmentRotation,
|
|
319
|
+
scene,
|
|
320
|
+
files,
|
|
321
|
+
path,
|
|
322
|
+
preset = void 0,
|
|
323
|
+
extensions
|
|
324
|
+
}) {
|
|
325
|
+
const gl = useThree$1((state) => state.gl);
|
|
326
|
+
const defaultScene = useThree$1((state) => state.scene);
|
|
327
|
+
const camera = React.useRef(null);
|
|
328
|
+
const [virtualScene] = React.useState(() => new Scene());
|
|
329
|
+
const fbo = React.useMemo(() => {
|
|
330
|
+
const fbo2 = new WebGLCubeRenderTarget(resolution);
|
|
331
|
+
fbo2.texture.type = HalfFloatType;
|
|
332
|
+
return fbo2;
|
|
333
|
+
}, [resolution]);
|
|
334
|
+
React.useEffect(() => {
|
|
335
|
+
return () => {
|
|
336
|
+
fbo.dispose();
|
|
337
|
+
};
|
|
338
|
+
}, [fbo]);
|
|
339
|
+
React.useLayoutEffect(() => {
|
|
340
|
+
if (frames === 1) {
|
|
341
|
+
const autoClear = gl.autoClear;
|
|
342
|
+
gl.autoClear = true;
|
|
343
|
+
camera.current.update(gl, virtualScene);
|
|
344
|
+
gl.autoClear = autoClear;
|
|
345
|
+
}
|
|
346
|
+
return setEnvProps(background, scene, defaultScene, fbo.texture, {
|
|
347
|
+
backgroundBlurriness: blur ?? backgroundBlurriness,
|
|
348
|
+
backgroundIntensity,
|
|
349
|
+
backgroundRotation,
|
|
350
|
+
environmentIntensity,
|
|
351
|
+
environmentRotation
|
|
352
|
+
});
|
|
353
|
+
}, [
|
|
354
|
+
children,
|
|
355
|
+
virtualScene,
|
|
356
|
+
fbo.texture,
|
|
357
|
+
scene,
|
|
358
|
+
defaultScene,
|
|
359
|
+
background,
|
|
360
|
+
frames,
|
|
361
|
+
gl,
|
|
362
|
+
blur,
|
|
363
|
+
backgroundBlurriness,
|
|
364
|
+
backgroundIntensity,
|
|
365
|
+
backgroundRotation,
|
|
366
|
+
environmentIntensity,
|
|
367
|
+
environmentRotation
|
|
368
|
+
]);
|
|
369
|
+
let count = 1;
|
|
370
|
+
useFrame$1(() => {
|
|
371
|
+
if (frames === Infinity || count < frames) {
|
|
372
|
+
const autoClear = gl.autoClear;
|
|
373
|
+
gl.autoClear = true;
|
|
374
|
+
camera.current.update(gl, virtualScene);
|
|
375
|
+
gl.autoClear = autoClear;
|
|
376
|
+
count++;
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
return /* @__PURE__ */ jsx(Fragment, { children: createPortal$1(
|
|
380
|
+
/* @__PURE__ */ jsxs(Fragment, { children: [
|
|
381
|
+
children,
|
|
382
|
+
/* @__PURE__ */ jsx("cubeCamera", { ref: camera, args: [near, far, fbo] }),
|
|
383
|
+
files || preset ? /* @__PURE__ */ jsx(EnvironmentCube, { background: true, files, preset, path, extensions }) : map ? /* @__PURE__ */ jsx(EnvironmentMap, { background: true, map, extensions }) : null
|
|
384
|
+
] }),
|
|
385
|
+
virtualScene
|
|
386
|
+
) });
|
|
387
|
+
}
|
|
388
|
+
function EnvironmentGround(props) {
|
|
389
|
+
const textureDefault = useEnvironment(props);
|
|
390
|
+
const texture = props.map || textureDefault;
|
|
391
|
+
React.useMemo(() => extend$1({ GroundProjectedEnvImpl: GroundedSkybox }), []);
|
|
392
|
+
React.useEffect(() => {
|
|
393
|
+
return () => {
|
|
394
|
+
textureDefault.dispose();
|
|
395
|
+
};
|
|
396
|
+
}, [textureDefault]);
|
|
397
|
+
const height = props.ground?.height ?? 15;
|
|
398
|
+
const radius = props.ground?.radius ?? 60;
|
|
399
|
+
const scale = props.ground?.scale ?? 1e3;
|
|
400
|
+
const args = React.useMemo(
|
|
401
|
+
() => [texture, height, radius],
|
|
402
|
+
[texture, height, radius]
|
|
403
|
+
);
|
|
404
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
405
|
+
/* @__PURE__ */ jsx(EnvironmentMap, { ...props, map: texture }),
|
|
406
|
+
/* @__PURE__ */ jsx("groundProjectedEnvImpl", { args, scale })
|
|
407
|
+
] });
|
|
408
|
+
}
|
|
409
|
+
function EnvironmentColor({ color, scene }) {
|
|
410
|
+
const defaultScene = useThree$1((state) => state.scene);
|
|
411
|
+
React.useLayoutEffect(() => {
|
|
412
|
+
if (color === void 0) return;
|
|
413
|
+
const target = resolveScene(scene || defaultScene);
|
|
414
|
+
const oldBg = target.background;
|
|
415
|
+
target.background = new Color(color);
|
|
416
|
+
return () => {
|
|
417
|
+
target.background = oldBg;
|
|
418
|
+
};
|
|
419
|
+
});
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
function EnvironmentDualSource(props) {
|
|
423
|
+
const { backgroundFiles, ...envProps } = props;
|
|
424
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
425
|
+
/* @__PURE__ */ jsx(EnvironmentCube, { ...envProps, background: false }),
|
|
426
|
+
/* @__PURE__ */ jsx(EnvironmentCube, { ...props, files: backgroundFiles, background: "only" })
|
|
427
|
+
] });
|
|
428
|
+
}
|
|
429
|
+
function Environment(props) {
|
|
430
|
+
if (props.color && !props.files && !props.preset && !props.map) {
|
|
431
|
+
return /* @__PURE__ */ jsx(EnvironmentColor, { ...props });
|
|
432
|
+
}
|
|
433
|
+
if (props.backgroundFiles && props.backgroundFiles !== props.files) {
|
|
434
|
+
return /* @__PURE__ */ jsx(EnvironmentDualSource, { ...props });
|
|
435
|
+
}
|
|
436
|
+
return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
var __defProp = Object.defineProperty;
|
|
440
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
441
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
51
442
|
const act = React["act"];
|
|
52
443
|
const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
|
|
53
444
|
function useMutableCallback(fn) {
|
|
@@ -79,7 +470,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
|
|
|
79
470
|
return _a = class extends React.Component {
|
|
80
471
|
constructor() {
|
|
81
472
|
super(...arguments);
|
|
82
|
-
__publicField
|
|
473
|
+
__publicField(this, "state", { error: false });
|
|
83
474
|
}
|
|
84
475
|
componentDidCatch(err) {
|
|
85
476
|
this.props.set(err);
|
|
@@ -87,7 +478,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
|
|
|
87
478
|
render() {
|
|
88
479
|
return this.state.error ? null : this.props.children;
|
|
89
480
|
}
|
|
90
|
-
}, __publicField
|
|
481
|
+
}, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
|
|
91
482
|
})();
|
|
92
483
|
|
|
93
484
|
const is = {
|
|
@@ -224,7 +615,8 @@ function prepare(target, root, type, props) {
|
|
|
224
615
|
object,
|
|
225
616
|
eventCount: 0,
|
|
226
617
|
handlers: {},
|
|
227
|
-
isHidden: false
|
|
618
|
+
isHidden: false,
|
|
619
|
+
deferredRefs: []
|
|
228
620
|
};
|
|
229
621
|
if (object) object.__r3f = instance;
|
|
230
622
|
}
|
|
@@ -273,7 +665,7 @@ function createOcclusionObserverNode(store, uniform) {
|
|
|
273
665
|
let occlusionSetupPromise = null;
|
|
274
666
|
function enableOcclusion(store) {
|
|
275
667
|
const state = store.getState();
|
|
276
|
-
const { internal, renderer
|
|
668
|
+
const { internal, renderer } = state;
|
|
277
669
|
if (internal.occlusionEnabled || occlusionSetupPromise) return;
|
|
278
670
|
const hasOcclusionSupport = typeof renderer?.isOccluded === "function";
|
|
279
671
|
if (!hasOcclusionSupport) {
|
|
@@ -436,6 +828,22 @@ function hasVisibilityHandlers(handlers) {
|
|
|
436
828
|
return !!(handlers.onFramed || handlers.onOccluded || handlers.onVisible);
|
|
437
829
|
}
|
|
438
830
|
|
|
831
|
+
const FROM_REF = Symbol.for("@react-three/fiber.fromRef");
|
|
832
|
+
function fromRef(ref) {
|
|
833
|
+
return { [FROM_REF]: ref };
|
|
834
|
+
}
|
|
835
|
+
function isFromRef(value) {
|
|
836
|
+
return value !== null && typeof value === "object" && FROM_REF in value;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
const ONCE = Symbol.for("@react-three/fiber.once");
|
|
840
|
+
function once(...args) {
|
|
841
|
+
return { [ONCE]: args.length ? args : true };
|
|
842
|
+
}
|
|
843
|
+
function isOnce(value) {
|
|
844
|
+
return value !== null && typeof value === "object" && ONCE in value;
|
|
845
|
+
}
|
|
846
|
+
|
|
439
847
|
const RESERVED_PROPS = [
|
|
440
848
|
"children",
|
|
441
849
|
"key",
|
|
@@ -506,7 +914,7 @@ function getMemoizedPrototype(root) {
|
|
|
506
914
|
ctor = new root.constructor();
|
|
507
915
|
MEMOIZED_PROTOTYPES.set(root.constructor, ctor);
|
|
508
916
|
}
|
|
509
|
-
} catch
|
|
917
|
+
} catch {
|
|
510
918
|
}
|
|
511
919
|
return ctor;
|
|
512
920
|
}
|
|
@@ -552,6 +960,25 @@ function applyProps(object, props) {
|
|
|
552
960
|
continue;
|
|
553
961
|
}
|
|
554
962
|
if (value === void 0) continue;
|
|
963
|
+
if (isFromRef(value)) {
|
|
964
|
+
instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
if (isOnce(value)) {
|
|
968
|
+
if (instance?.appliedOnce?.has(prop)) continue;
|
|
969
|
+
if (instance) {
|
|
970
|
+
instance.appliedOnce ?? (instance.appliedOnce = /* @__PURE__ */ new Set());
|
|
971
|
+
instance.appliedOnce.add(prop);
|
|
972
|
+
}
|
|
973
|
+
const { root: targetRoot, key: targetKey } = resolve(object, prop);
|
|
974
|
+
const args = value[ONCE];
|
|
975
|
+
if (typeof targetRoot[targetKey] === "function") {
|
|
976
|
+
targetRoot[targetKey](...args === true ? [] : args);
|
|
977
|
+
} else if (args !== true && args.length > 0) {
|
|
978
|
+
targetRoot[targetKey] = args[0];
|
|
979
|
+
}
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
555
982
|
let { root, key, target } = resolve(object, prop);
|
|
556
983
|
if (target === void 0 && (typeof root !== "object" || root === null)) {
|
|
557
984
|
throw Error(`R3F: Cannot set "${prop}". Ensure it is an object before setting "${key}".`);
|
|
@@ -574,7 +1001,10 @@ function applyProps(object, props) {
|
|
|
574
1001
|
else target.set(value);
|
|
575
1002
|
} else {
|
|
576
1003
|
root[key] = value;
|
|
577
|
-
if (
|
|
1004
|
+
if (key.endsWith("Node") && root.isMaterial) {
|
|
1005
|
+
root.needsUpdate = true;
|
|
1006
|
+
}
|
|
1007
|
+
if (rootState && rootState.renderer?.outputColorSpace === SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
|
|
578
1008
|
root[key].format === RGBAFormat && root[key].type === UnsignedByteType) {
|
|
579
1009
|
root[key].colorSpace = rootState.textureColorSpace;
|
|
580
1010
|
}
|
|
@@ -607,38 +1037,60 @@ function applyProps(object, props) {
|
|
|
607
1037
|
return object;
|
|
608
1038
|
}
|
|
609
1039
|
|
|
1040
|
+
const DEFAULT_POINTER_ID = 0;
|
|
1041
|
+
const XR_POINTER_ID_START = 1e3;
|
|
1042
|
+
function getPointerState(internal, pointerId) {
|
|
1043
|
+
let state = internal.pointerMap.get(pointerId);
|
|
1044
|
+
if (!state) {
|
|
1045
|
+
state = {
|
|
1046
|
+
hovered: /* @__PURE__ */ new Map(),
|
|
1047
|
+
captured: /* @__PURE__ */ new Map(),
|
|
1048
|
+
initialClick: [0, 0],
|
|
1049
|
+
initialHits: []
|
|
1050
|
+
};
|
|
1051
|
+
internal.pointerMap.set(pointerId, state);
|
|
1052
|
+
}
|
|
1053
|
+
return state;
|
|
1054
|
+
}
|
|
1055
|
+
function getPointerId(event) {
|
|
1056
|
+
return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
|
|
1057
|
+
}
|
|
610
1058
|
function makeId(event) {
|
|
611
1059
|
return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
|
|
612
1060
|
}
|
|
613
|
-
function releaseInternalPointerCapture(
|
|
614
|
-
const
|
|
1061
|
+
function releaseInternalPointerCapture(internal, obj, pointerId) {
|
|
1062
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1063
|
+
if (!pointerState) return;
|
|
1064
|
+
const captureData = pointerState.captured.get(obj);
|
|
615
1065
|
if (captureData) {
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
capturedMap.delete(pointerId);
|
|
619
|
-
captureData.target.releasePointerCapture(pointerId);
|
|
620
|
-
}
|
|
1066
|
+
pointerState.captured.delete(obj);
|
|
1067
|
+
captureData.target.releasePointerCapture(pointerId);
|
|
621
1068
|
}
|
|
622
1069
|
}
|
|
623
1070
|
function removeInteractivity(store, object) {
|
|
624
1071
|
const { internal } = store.getState();
|
|
625
1072
|
internal.interaction = internal.interaction.filter((o) => o !== object);
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
1073
|
+
for (const [pointerId, pointerState] of internal.pointerMap) {
|
|
1074
|
+
pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
|
|
1075
|
+
pointerState.hovered.forEach((value, key) => {
|
|
1076
|
+
if (value.eventObject === object || value.object === object) {
|
|
1077
|
+
pointerState.hovered.delete(key);
|
|
1078
|
+
}
|
|
1079
|
+
});
|
|
1080
|
+
if (pointerState.captured.has(object)) {
|
|
1081
|
+
releaseInternalPointerCapture(internal, object, pointerId);
|
|
630
1082
|
}
|
|
631
|
-
}
|
|
632
|
-
internal.capturedMap.forEach((captures, pointerId) => {
|
|
633
|
-
releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
|
|
634
|
-
});
|
|
1083
|
+
}
|
|
635
1084
|
unregisterVisibility(store, object);
|
|
636
1085
|
}
|
|
637
1086
|
function createEvents(store) {
|
|
638
|
-
function calculateDistance(event) {
|
|
1087
|
+
function calculateDistance(event, pointerId) {
|
|
639
1088
|
const { internal } = store.getState();
|
|
640
|
-
const
|
|
641
|
-
|
|
1089
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1090
|
+
if (!pointerState) return 0;
|
|
1091
|
+
const [initialX, initialY] = pointerState.initialClick;
|
|
1092
|
+
const dx = event.offsetX - initialX;
|
|
1093
|
+
const dy = event.offsetY - initialY;
|
|
642
1094
|
return Math.round(Math.sqrt(dx * dx + dy * dy));
|
|
643
1095
|
}
|
|
644
1096
|
function filterPointerEvents(objects) {
|
|
@@ -674,6 +1126,15 @@ function createEvents(store) {
|
|
|
674
1126
|
return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
|
|
675
1127
|
}
|
|
676
1128
|
let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
|
|
1129
|
+
const aInteractivePriority = a.object.userData?.interactivePriority;
|
|
1130
|
+
const bInteractivePriority = b.object.userData?.interactivePriority;
|
|
1131
|
+
if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
|
|
1132
|
+
if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
|
|
1133
|
+
if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
|
|
1134
|
+
if (aInteractivePriority !== bInteractivePriority) {
|
|
1135
|
+
return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
677
1138
|
const aState = getRootState(a.object);
|
|
678
1139
|
const bState = getRootState(b.object);
|
|
679
1140
|
const aPriority = aState?.events?.priority ?? 1;
|
|
@@ -695,9 +1156,13 @@ function createEvents(store) {
|
|
|
695
1156
|
eventObject = eventObject.parent;
|
|
696
1157
|
}
|
|
697
1158
|
}
|
|
698
|
-
if ("pointerId" in event
|
|
699
|
-
|
|
700
|
-
|
|
1159
|
+
if ("pointerId" in event) {
|
|
1160
|
+
const pointerId = event.pointerId;
|
|
1161
|
+
const pointerState = state.internal.pointerMap.get(pointerId);
|
|
1162
|
+
if (pointerState?.captured.size) {
|
|
1163
|
+
for (const captureData of pointerState.captured.values()) {
|
|
1164
|
+
if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
|
|
1165
|
+
}
|
|
701
1166
|
}
|
|
702
1167
|
}
|
|
703
1168
|
return intersections;
|
|
@@ -710,27 +1175,25 @@ function createEvents(store) {
|
|
|
710
1175
|
if (state) {
|
|
711
1176
|
const { raycaster, pointer, camera, internal } = state;
|
|
712
1177
|
const unprojectedPoint = new Vector3(pointer.x, pointer.y, 0).unproject(camera);
|
|
713
|
-
const hasPointerCapture = (id) =>
|
|
1178
|
+
const hasPointerCapture = (id) => {
|
|
1179
|
+
const pointerState = internal.pointerMap.get(id);
|
|
1180
|
+
return pointerState?.captured.has(hit.eventObject) ?? false;
|
|
1181
|
+
};
|
|
714
1182
|
const setPointerCapture = (id) => {
|
|
715
1183
|
const captureData = { intersection: hit, target: event.target };
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
} else {
|
|
719
|
-
internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
|
|
720
|
-
}
|
|
1184
|
+
const pointerState = getPointerState(internal, id);
|
|
1185
|
+
pointerState.captured.set(hit.eventObject, captureData);
|
|
721
1186
|
event.target.setPointerCapture(id);
|
|
722
1187
|
};
|
|
723
1188
|
const releasePointerCapture = (id) => {
|
|
724
|
-
|
|
725
|
-
if (captures) {
|
|
726
|
-
releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
|
|
727
|
-
}
|
|
1189
|
+
releaseInternalPointerCapture(internal, hit.eventObject, id);
|
|
728
1190
|
};
|
|
729
1191
|
const extractEventProps = {};
|
|
730
1192
|
for (const prop in event) {
|
|
731
1193
|
const property = event[prop];
|
|
732
1194
|
if (typeof property !== "function") extractEventProps[prop] = property;
|
|
733
1195
|
}
|
|
1196
|
+
const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
|
|
734
1197
|
const raycastEvent = {
|
|
735
1198
|
...hit,
|
|
736
1199
|
...extractEventProps,
|
|
@@ -741,18 +1204,19 @@ function createEvents(store) {
|
|
|
741
1204
|
unprojectedPoint,
|
|
742
1205
|
ray: raycaster.ray,
|
|
743
1206
|
camera,
|
|
1207
|
+
pointerId: eventPointerId,
|
|
744
1208
|
// Hijack stopPropagation, which just sets a flag
|
|
745
1209
|
stopPropagation() {
|
|
746
|
-
const
|
|
1210
|
+
const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
|
|
747
1211
|
if (
|
|
748
1212
|
// ...if this pointer hasn't been captured
|
|
749
|
-
!
|
|
750
|
-
|
|
1213
|
+
!pointerState?.captured.size || // ... or if the hit object is capturing the pointer
|
|
1214
|
+
pointerState.captured.has(hit.eventObject)
|
|
751
1215
|
) {
|
|
752
1216
|
raycastEvent.stopped = localState.stopped = true;
|
|
753
|
-
if (
|
|
1217
|
+
if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
|
|
754
1218
|
const higher = intersections.slice(0, intersections.indexOf(hit));
|
|
755
|
-
cancelPointer([...higher, hit]);
|
|
1219
|
+
cancelPointer([...higher, hit], eventPointerId);
|
|
756
1220
|
}
|
|
757
1221
|
}
|
|
758
1222
|
},
|
|
@@ -768,15 +1232,18 @@ function createEvents(store) {
|
|
|
768
1232
|
}
|
|
769
1233
|
return intersections;
|
|
770
1234
|
}
|
|
771
|
-
function cancelPointer(intersections) {
|
|
1235
|
+
function cancelPointer(intersections, pointerId) {
|
|
772
1236
|
const { internal } = store.getState();
|
|
773
|
-
|
|
1237
|
+
const pid = pointerId ?? DEFAULT_POINTER_ID;
|
|
1238
|
+
const pointerState = internal.pointerMap.get(pid);
|
|
1239
|
+
if (!pointerState) return;
|
|
1240
|
+
for (const [hoveredId, hoveredObj] of pointerState.hovered) {
|
|
774
1241
|
if (!intersections.length || !intersections.find(
|
|
775
1242
|
(hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
|
|
776
1243
|
)) {
|
|
777
1244
|
const eventObject = hoveredObj.eventObject;
|
|
778
1245
|
const instance = eventObject.__r3f;
|
|
779
|
-
|
|
1246
|
+
pointerState.hovered.delete(hoveredId);
|
|
780
1247
|
if (instance?.eventCount) {
|
|
781
1248
|
const handlers = instance.handlers;
|
|
782
1249
|
const data = { ...hoveredObj, intersections };
|
|
@@ -805,41 +1272,118 @@ function createEvents(store) {
|
|
|
805
1272
|
instance?.handlers.onDropMissed?.(event);
|
|
806
1273
|
}
|
|
807
1274
|
}
|
|
1275
|
+
function cleanupPointer(pointerId) {
|
|
1276
|
+
const { internal } = store.getState();
|
|
1277
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1278
|
+
if (pointerState) {
|
|
1279
|
+
for (const [, hoveredObj] of pointerState.hovered) {
|
|
1280
|
+
const eventObject = hoveredObj.eventObject;
|
|
1281
|
+
const instance = eventObject.__r3f;
|
|
1282
|
+
if (instance?.eventCount) {
|
|
1283
|
+
const handlers = instance.handlers;
|
|
1284
|
+
const data = { ...hoveredObj, intersections: [] };
|
|
1285
|
+
handlers.onPointerOut?.(data);
|
|
1286
|
+
handlers.onPointerLeave?.(data);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
internal.pointerMap.delete(pointerId);
|
|
1290
|
+
}
|
|
1291
|
+
internal.pointerDirty.delete(pointerId);
|
|
1292
|
+
}
|
|
1293
|
+
function processDeferredPointer(event, pointerId) {
|
|
1294
|
+
const state = store.getState();
|
|
1295
|
+
const { internal } = state;
|
|
1296
|
+
if (!state.events.enabled) return;
|
|
1297
|
+
const filter = filterPointerEvents;
|
|
1298
|
+
const hits = intersect(event, filter);
|
|
1299
|
+
cancelPointer(hits, pointerId);
|
|
1300
|
+
function onIntersect(data) {
|
|
1301
|
+
const eventObject = data.eventObject;
|
|
1302
|
+
const instance = eventObject.__r3f;
|
|
1303
|
+
if (!instance?.eventCount) return;
|
|
1304
|
+
const handlers = instance.handlers;
|
|
1305
|
+
if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
|
|
1306
|
+
const id = makeId(data);
|
|
1307
|
+
const pointerState = getPointerState(internal, pointerId);
|
|
1308
|
+
const hoveredItem = pointerState.hovered.get(id);
|
|
1309
|
+
if (!hoveredItem) {
|
|
1310
|
+
pointerState.hovered.set(id, data);
|
|
1311
|
+
handlers.onPointerOver?.(data);
|
|
1312
|
+
handlers.onPointerEnter?.(data);
|
|
1313
|
+
} else if (hoveredItem.stopped) {
|
|
1314
|
+
data.stopPropagation();
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
handlers.onPointerMove?.(data);
|
|
1318
|
+
}
|
|
1319
|
+
handleIntersects(hits, event, 0, onIntersect);
|
|
1320
|
+
}
|
|
808
1321
|
function handlePointer(name) {
|
|
809
1322
|
switch (name) {
|
|
810
1323
|
case "onPointerLeave":
|
|
811
|
-
case "onPointerCancel":
|
|
812
1324
|
case "onDragLeave":
|
|
813
1325
|
return () => cancelPointer([]);
|
|
1326
|
+
// Global cancel of these events
|
|
1327
|
+
case "onPointerCancel":
|
|
1328
|
+
return (event) => {
|
|
1329
|
+
const pointerId = getPointerId(event);
|
|
1330
|
+
cleanupPointer(pointerId);
|
|
1331
|
+
};
|
|
814
1332
|
case "onLostPointerCapture":
|
|
815
1333
|
return (event) => {
|
|
816
1334
|
const { internal } = store.getState();
|
|
817
|
-
|
|
1335
|
+
const pointerId = getPointerId(event);
|
|
1336
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1337
|
+
if (pointerState?.captured.size) {
|
|
818
1338
|
requestAnimationFrame(() => {
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
1339
|
+
const pointerState2 = internal.pointerMap.get(pointerId);
|
|
1340
|
+
if (pointerState2?.captured.size) {
|
|
1341
|
+
pointerState2.captured.clear();
|
|
822
1342
|
}
|
|
1343
|
+
cancelPointer([], pointerId);
|
|
823
1344
|
});
|
|
824
1345
|
}
|
|
825
1346
|
};
|
|
826
1347
|
}
|
|
827
1348
|
return function handleEvent(event) {
|
|
828
1349
|
const state = store.getState();
|
|
829
|
-
const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
|
|
1350
|
+
const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
|
|
1351
|
+
const pointerId = getPointerId(event);
|
|
830
1352
|
internal.lastEvent.current = event;
|
|
831
|
-
if (!
|
|
1353
|
+
if (!events.enabled) return;
|
|
832
1354
|
const isPointerMove = name === "onPointerMove";
|
|
833
1355
|
const isDragOver = name === "onDragOver";
|
|
834
1356
|
const isDrop = name === "onDrop";
|
|
835
1357
|
const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
|
|
1358
|
+
const isPointerDown = name === "onPointerDown";
|
|
1359
|
+
const isPointerUp = name === "onPointerUp";
|
|
1360
|
+
const isWheel = name === "onWheel";
|
|
1361
|
+
const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
|
|
1362
|
+
if (isPointerMove && canDeferRaycasts) {
|
|
1363
|
+
events.compute?.(event, state);
|
|
1364
|
+
internal.pointerDirty.set(pointerId, event);
|
|
1365
|
+
return;
|
|
1366
|
+
}
|
|
1367
|
+
if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
|
|
1368
|
+
events.compute?.(event, state);
|
|
1369
|
+
internal.pointerDirty.set(pointerId, event);
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
|
|
1373
|
+
const deferredEvent = internal.pointerDirty.get(pointerId);
|
|
1374
|
+
internal.pointerDirty.delete(pointerId);
|
|
1375
|
+
processDeferredPointer(deferredEvent, pointerId);
|
|
1376
|
+
}
|
|
836
1377
|
const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
|
|
837
1378
|
const hits = intersect(event, filter);
|
|
838
|
-
const delta = isClickEvent ? calculateDistance(event) : 0;
|
|
839
|
-
if (
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
1379
|
+
const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
|
|
1380
|
+
if (isPointerDown) {
|
|
1381
|
+
const pointerState2 = getPointerState(internal, pointerId);
|
|
1382
|
+
pointerState2.initialClick = [event.offsetX, event.offsetY];
|
|
1383
|
+
pointerState2.initialHits = hits.map((hit) => hit.eventObject);
|
|
1384
|
+
}
|
|
1385
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1386
|
+
const initialHits = pointerState?.initialHits ?? [];
|
|
843
1387
|
if (isClickEvent && !hits.length) {
|
|
844
1388
|
if (delta <= 2) {
|
|
845
1389
|
pointerMissed(event, internal.interaction);
|
|
@@ -854,7 +1398,9 @@ function createEvents(store) {
|
|
|
854
1398
|
dropMissed(event, internal.interaction);
|
|
855
1399
|
if (onDropMissed) onDropMissed(event);
|
|
856
1400
|
}
|
|
857
|
-
if (isPointerMove || isDragOver)
|
|
1401
|
+
if (isPointerMove || isDragOver) {
|
|
1402
|
+
cancelPointer(hits, pointerId);
|
|
1403
|
+
}
|
|
858
1404
|
function onIntersect(data) {
|
|
859
1405
|
const eventObject = data.eventObject;
|
|
860
1406
|
const instance = eventObject.__r3f;
|
|
@@ -863,9 +1409,10 @@ function createEvents(store) {
|
|
|
863
1409
|
if (isPointerMove) {
|
|
864
1410
|
if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
|
|
865
1411
|
const id = makeId(data);
|
|
866
|
-
const
|
|
1412
|
+
const pointerState2 = getPointerState(internal, pointerId);
|
|
1413
|
+
const hoveredItem = pointerState2.hovered.get(id);
|
|
867
1414
|
if (!hoveredItem) {
|
|
868
|
-
|
|
1415
|
+
pointerState2.hovered.set(id, data);
|
|
869
1416
|
handlers.onPointerOver?.(data);
|
|
870
1417
|
handlers.onPointerEnter?.(data);
|
|
871
1418
|
} else if (hoveredItem.stopped) {
|
|
@@ -875,9 +1422,10 @@ function createEvents(store) {
|
|
|
875
1422
|
handlers.onPointerMove?.(data);
|
|
876
1423
|
} else if (isDragOver) {
|
|
877
1424
|
const id = makeId(data);
|
|
878
|
-
const
|
|
1425
|
+
const pointerState2 = getPointerState(internal, pointerId);
|
|
1426
|
+
const hoveredItem = pointerState2.hovered.get(id);
|
|
879
1427
|
if (!hoveredItem) {
|
|
880
|
-
|
|
1428
|
+
pointerState2.hovered.set(id, data);
|
|
881
1429
|
handlers.onDragOverEnter?.(data);
|
|
882
1430
|
} else if (hoveredItem.stopped) {
|
|
883
1431
|
data.stopPropagation();
|
|
@@ -888,18 +1436,18 @@ function createEvents(store) {
|
|
|
888
1436
|
} else {
|
|
889
1437
|
const handler = handlers[name];
|
|
890
1438
|
if (handler) {
|
|
891
|
-
if (!isClickEvent ||
|
|
1439
|
+
if (!isClickEvent || initialHits.includes(eventObject)) {
|
|
892
1440
|
pointerMissed(
|
|
893
1441
|
event,
|
|
894
|
-
internal.interaction.filter((object) => !
|
|
1442
|
+
internal.interaction.filter((object) => !initialHits.includes(object))
|
|
895
1443
|
);
|
|
896
1444
|
handler(data);
|
|
897
1445
|
}
|
|
898
1446
|
} else {
|
|
899
|
-
if (isClickEvent &&
|
|
1447
|
+
if (isClickEvent && initialHits.includes(eventObject)) {
|
|
900
1448
|
pointerMissed(
|
|
901
1449
|
event,
|
|
902
|
-
internal.interaction.filter((object) => !
|
|
1450
|
+
internal.interaction.filter((object) => !initialHits.includes(object))
|
|
903
1451
|
);
|
|
904
1452
|
}
|
|
905
1453
|
}
|
|
@@ -908,7 +1456,15 @@ function createEvents(store) {
|
|
|
908
1456
|
handleIntersects(hits, event, delta, onIntersect);
|
|
909
1457
|
};
|
|
910
1458
|
}
|
|
911
|
-
|
|
1459
|
+
function flushDeferredPointers() {
|
|
1460
|
+
const { internal, events } = store.getState();
|
|
1461
|
+
if (!events.frameTimedRaycasts) return;
|
|
1462
|
+
for (const [pointerId, event] of internal.pointerDirty) {
|
|
1463
|
+
processDeferredPointer(event, pointerId);
|
|
1464
|
+
}
|
|
1465
|
+
internal.pointerDirty.clear();
|
|
1466
|
+
}
|
|
1467
|
+
return { handlePointer, flushDeferredPointers, processDeferredPointer };
|
|
912
1468
|
}
|
|
913
1469
|
const DOM_EVENTS = {
|
|
914
1470
|
onClick: ["click", false],
|
|
@@ -927,11 +1483,16 @@ const DOM_EVENTS = {
|
|
|
927
1483
|
onLostPointerCapture: ["lostpointercapture", true]
|
|
928
1484
|
};
|
|
929
1485
|
function createPointerEvents(store) {
|
|
930
|
-
const { handlePointer } = createEvents(store);
|
|
1486
|
+
const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
|
|
1487
|
+
let nextXRPointerId = XR_POINTER_ID_START;
|
|
1488
|
+
const xrPointers = /* @__PURE__ */ new Map();
|
|
931
1489
|
return {
|
|
932
1490
|
priority: 1,
|
|
933
1491
|
enabled: true,
|
|
934
|
-
|
|
1492
|
+
frameTimedRaycasts: true,
|
|
1493
|
+
alwaysFireOnScroll: true,
|
|
1494
|
+
updateOnFrame: false,
|
|
1495
|
+
compute(event, state) {
|
|
935
1496
|
state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
|
|
936
1497
|
state.raycaster.setFromCamera(state.pointer, state.camera);
|
|
937
1498
|
},
|
|
@@ -940,11 +1501,33 @@ function createPointerEvents(store) {
|
|
|
940
1501
|
(acc, key) => ({ ...acc, [key]: handlePointer(key) }),
|
|
941
1502
|
{}
|
|
942
1503
|
),
|
|
943
|
-
update: () => {
|
|
1504
|
+
update: (pointerId) => {
|
|
1505
|
+
const { events, internal } = store.getState();
|
|
1506
|
+
if (!events.handlers) return;
|
|
1507
|
+
if (pointerId !== void 0) {
|
|
1508
|
+
const event = internal.pointerDirty.get(pointerId);
|
|
1509
|
+
if (event) {
|
|
1510
|
+
internal.pointerDirty.delete(pointerId);
|
|
1511
|
+
processDeferredPointer(event, pointerId);
|
|
1512
|
+
} else if (internal.lastEvent?.current) {
|
|
1513
|
+
processDeferredPointer(internal.lastEvent.current, pointerId);
|
|
1514
|
+
}
|
|
1515
|
+
} else {
|
|
1516
|
+
flushDeferredPointers();
|
|
1517
|
+
if (internal.lastEvent?.current) {
|
|
1518
|
+
events.handlers.onPointerMove(internal.lastEvent.current);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
},
|
|
1522
|
+
flush: () => {
|
|
944
1523
|
const { events, internal } = store.getState();
|
|
945
|
-
|
|
1524
|
+
flushDeferredPointers();
|
|
1525
|
+
if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
|
|
1526
|
+
events.handlers.onPointerMove(internal.lastEvent.current);
|
|
1527
|
+
}
|
|
946
1528
|
},
|
|
947
1529
|
connect: (target) => {
|
|
1530
|
+
if (!target) return;
|
|
948
1531
|
const { set, events } = store.getState();
|
|
949
1532
|
events.disconnect?.();
|
|
950
1533
|
set((state) => ({ events: { ...state.events, connected: target } }));
|
|
@@ -968,6 +1551,32 @@ function createPointerEvents(store) {
|
|
|
968
1551
|
}
|
|
969
1552
|
set((state) => ({ events: { ...state.events, connected: void 0 } }));
|
|
970
1553
|
}
|
|
1554
|
+
},
|
|
1555
|
+
registerPointer: (config) => {
|
|
1556
|
+
const pointerId = nextXRPointerId++;
|
|
1557
|
+
xrPointers.set(pointerId, config);
|
|
1558
|
+
const { internal } = store.getState();
|
|
1559
|
+
getPointerState(internal, pointerId);
|
|
1560
|
+
return pointerId;
|
|
1561
|
+
},
|
|
1562
|
+
unregisterPointer: (pointerId) => {
|
|
1563
|
+
xrPointers.delete(pointerId);
|
|
1564
|
+
const { internal } = store.getState();
|
|
1565
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1566
|
+
if (pointerState) {
|
|
1567
|
+
for (const [, hoveredObj] of pointerState.hovered) {
|
|
1568
|
+
const eventObject = hoveredObj.eventObject;
|
|
1569
|
+
const instance = eventObject.__r3f;
|
|
1570
|
+
if (instance?.eventCount) {
|
|
1571
|
+
const handlers = instance.handlers;
|
|
1572
|
+
const data = { ...hoveredObj, intersections: [] };
|
|
1573
|
+
handlers.onPointerOut?.(data);
|
|
1574
|
+
handlers.onPointerLeave?.(data);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
internal.pointerMap.delete(pointerId);
|
|
1578
|
+
}
|
|
1579
|
+
internal.pointerDirty.delete(pointerId);
|
|
971
1580
|
}
|
|
972
1581
|
};
|
|
973
1582
|
}
|
|
@@ -1058,23 +1667,29 @@ const createStore = (invalidate, advance) => {
|
|
|
1058
1667
|
set,
|
|
1059
1668
|
get,
|
|
1060
1669
|
// Mock objects that have to be configured
|
|
1670
|
+
// primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
|
|
1671
|
+
primaryStore: null,
|
|
1061
1672
|
gl: null,
|
|
1062
1673
|
renderer: null,
|
|
1063
1674
|
camera: null,
|
|
1064
1675
|
frustum: new Frustum(),
|
|
1065
1676
|
autoUpdateFrustum: true,
|
|
1066
1677
|
raycaster: null,
|
|
1067
|
-
events: {
|
|
1678
|
+
events: {
|
|
1679
|
+
priority: 1,
|
|
1680
|
+
enabled: true,
|
|
1681
|
+
connected: false,
|
|
1682
|
+
frameTimedRaycasts: true,
|
|
1683
|
+
alwaysFireOnScroll: true,
|
|
1684
|
+
updateOnFrame: false
|
|
1685
|
+
},
|
|
1068
1686
|
scene: null,
|
|
1069
1687
|
rootScene: null,
|
|
1070
1688
|
xr: null,
|
|
1071
1689
|
inspector: null,
|
|
1072
1690
|
invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
|
|
1073
1691
|
advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
|
|
1074
|
-
|
|
1075
|
-
linear: false,
|
|
1076
|
-
flat: false,
|
|
1077
|
-
textureColorSpace: "srgb",
|
|
1692
|
+
textureColorSpace: SRGBColorSpace,
|
|
1078
1693
|
isLegacy: false,
|
|
1079
1694
|
webGPUSupported: false,
|
|
1080
1695
|
isNative: false,
|
|
@@ -1132,6 +1747,7 @@ const createStore = (invalidate, advance) => {
|
|
|
1132
1747
|
size: newSize,
|
|
1133
1748
|
viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
|
|
1134
1749
|
}));
|
|
1750
|
+
getScheduler().invalidate();
|
|
1135
1751
|
}
|
|
1136
1752
|
}
|
|
1137
1753
|
return;
|
|
@@ -1146,6 +1762,7 @@ const createStore = (invalidate, advance) => {
|
|
|
1146
1762
|
viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
|
|
1147
1763
|
_sizeImperative: true
|
|
1148
1764
|
}));
|
|
1765
|
+
getScheduler().invalidate();
|
|
1149
1766
|
},
|
|
1150
1767
|
setDpr: (dpr) => set((state2) => {
|
|
1151
1768
|
const resolved = calculateDpr(dpr);
|
|
@@ -1156,11 +1773,14 @@ const createStore = (invalidate, advance) => {
|
|
|
1156
1773
|
},
|
|
1157
1774
|
setError: (error) => set(() => ({ error })),
|
|
1158
1775
|
error: null,
|
|
1159
|
-
//* TSL State (managed via hooks: useUniforms, useNodes, useTextures,
|
|
1776
|
+
//* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
|
|
1160
1777
|
uniforms: {},
|
|
1161
1778
|
nodes: {},
|
|
1779
|
+
buffers: {},
|
|
1780
|
+
gpuStorage: {},
|
|
1162
1781
|
textures: /* @__PURE__ */ new Map(),
|
|
1163
|
-
|
|
1782
|
+
_textureRefs: /* @__PURE__ */ new Map(),
|
|
1783
|
+
renderPipeline: null,
|
|
1164
1784
|
passes: {},
|
|
1165
1785
|
_hmrVersion: 0,
|
|
1166
1786
|
_sizeImperative: false,
|
|
@@ -1169,12 +1789,16 @@ const createStore = (invalidate, advance) => {
|
|
|
1169
1789
|
internal: {
|
|
1170
1790
|
// Events
|
|
1171
1791
|
interaction: [],
|
|
1172
|
-
hovered: /* @__PURE__ */ new Map(),
|
|
1173
1792
|
subscribers: [],
|
|
1793
|
+
// Per-pointer state (new unified structure)
|
|
1794
|
+
pointerMap: /* @__PURE__ */ new Map(),
|
|
1795
|
+
pointerDirty: /* @__PURE__ */ new Map(),
|
|
1796
|
+
lastEvent: React.createRef(),
|
|
1797
|
+
// Deprecated but kept for backwards compatibility
|
|
1798
|
+
hovered: /* @__PURE__ */ new Map(),
|
|
1174
1799
|
initialClick: [0, 0],
|
|
1175
1800
|
initialHits: [],
|
|
1176
1801
|
capturedMap: /* @__PURE__ */ new Map(),
|
|
1177
|
-
lastEvent: React.createRef(),
|
|
1178
1802
|
// Visibility tracking (onFramed, onOccluded, onVisible)
|
|
1179
1803
|
visibilityRegistry: /* @__PURE__ */ new Map(),
|
|
1180
1804
|
// Occlusion system (WebGPU only)
|
|
@@ -1257,13 +1881,22 @@ const createStore = (invalidate, advance) => {
|
|
|
1257
1881
|
rootStore.subscribe(() => {
|
|
1258
1882
|
const { camera, size, viewport, set, internal } = rootStore.getState();
|
|
1259
1883
|
const actualRenderer = internal.actualRenderer;
|
|
1884
|
+
const canvasTarget = internal.canvasTarget;
|
|
1260
1885
|
if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
|
|
1261
1886
|
oldSize = size;
|
|
1262
1887
|
oldDpr = viewport.dpr;
|
|
1263
1888
|
updateCamera(camera, size);
|
|
1264
|
-
if (
|
|
1265
|
-
|
|
1266
|
-
|
|
1889
|
+
if (internal.isSecondary && canvasTarget) {
|
|
1890
|
+
if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
|
|
1891
|
+
canvasTarget.setSize(size.width, size.height, false);
|
|
1892
|
+
} else {
|
|
1893
|
+
if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
|
|
1894
|
+
actualRenderer.setSize(size.width, size.height, false);
|
|
1895
|
+
if (canvasTarget) {
|
|
1896
|
+
if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
|
|
1897
|
+
canvasTarget.setSize(size.width, size.height, false);
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1267
1900
|
}
|
|
1268
1901
|
if (camera !== oldCamera) {
|
|
1269
1902
|
oldCamera = camera;
|
|
@@ -1334,1038 +1967,6 @@ useLoader.clear = function(loader, input) {
|
|
|
1334
1967
|
};
|
|
1335
1968
|
useLoader.loader = getLoader;
|
|
1336
1969
|
|
|
1337
|
-
var __defProp$1 = Object.defineProperty;
|
|
1338
|
-
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
1339
|
-
var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1340
|
-
const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
|
|
1341
|
-
class PhaseGraph {
|
|
1342
|
-
constructor() {
|
|
1343
|
-
/** Ordered list of phase nodes */
|
|
1344
|
-
__publicField$1(this, "phases", []);
|
|
1345
|
-
/** Quick lookup by name */
|
|
1346
|
-
__publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
|
|
1347
|
-
/** Cached ordered names (invalidated on changes) */
|
|
1348
|
-
__publicField$1(this, "orderedNamesCache", null);
|
|
1349
|
-
this.initializeDefaultPhases();
|
|
1350
|
-
}
|
|
1351
|
-
//* Initialization --------------------------------
|
|
1352
|
-
initializeDefaultPhases() {
|
|
1353
|
-
for (const name of DEFAULT_PHASES) {
|
|
1354
|
-
const node = { name, isAutoGenerated: false };
|
|
1355
|
-
this.phases.push(node);
|
|
1356
|
-
this.phaseMap.set(name, node);
|
|
1357
|
-
}
|
|
1358
|
-
this.invalidateCache();
|
|
1359
|
-
}
|
|
1360
|
-
//* Public API --------------------------------
|
|
1361
|
-
/**
|
|
1362
|
-
* Add a named phase to the graph
|
|
1363
|
-
* @param name - Phase name (must be unique)
|
|
1364
|
-
* @param options - Position options (before or after another phase)
|
|
1365
|
-
*/
|
|
1366
|
-
addPhase(name, options = {}) {
|
|
1367
|
-
if (this.phaseMap.has(name)) {
|
|
1368
|
-
console.warn(`[useFrame] Phase "${name}" already exists`);
|
|
1369
|
-
return;
|
|
1370
|
-
}
|
|
1371
|
-
const { before, after } = options;
|
|
1372
|
-
const node = { name, isAutoGenerated: false };
|
|
1373
|
-
let insertIndex = this.phases.length;
|
|
1374
|
-
const targetIndex = this.getPhaseIndex(before ?? after);
|
|
1375
|
-
if (targetIndex !== -1) {
|
|
1376
|
-
insertIndex = before ? targetIndex : targetIndex + 1;
|
|
1377
|
-
} else {
|
|
1378
|
-
const constraintType = before ? "before" : "after";
|
|
1379
|
-
console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
|
|
1380
|
-
}
|
|
1381
|
-
this.phases.splice(insertIndex, 0, node);
|
|
1382
|
-
this.phaseMap.set(name, node);
|
|
1383
|
-
this.invalidateCache();
|
|
1384
|
-
}
|
|
1385
|
-
/**
|
|
1386
|
-
* Get ordered list of phase names
|
|
1387
|
-
*/
|
|
1388
|
-
getOrderedPhases() {
|
|
1389
|
-
if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
|
|
1390
|
-
return this.orderedNamesCache;
|
|
1391
|
-
}
|
|
1392
|
-
/**
|
|
1393
|
-
* Check if a phase exists
|
|
1394
|
-
*/
|
|
1395
|
-
hasPhase(name) {
|
|
1396
|
-
return this.phaseMap.has(name);
|
|
1397
|
-
}
|
|
1398
|
-
/**
|
|
1399
|
-
* Get the index of a phase (-1 if not found)
|
|
1400
|
-
*/
|
|
1401
|
-
getPhaseIndex(name) {
|
|
1402
|
-
if (!name) return -1;
|
|
1403
|
-
return this.phases.findIndex((p) => p.name === name);
|
|
1404
|
-
}
|
|
1405
|
-
/**
|
|
1406
|
-
* Ensure a phase exists, creating an auto-generated one if needed.
|
|
1407
|
-
* Used for resolving before/after constraints.
|
|
1408
|
-
*
|
|
1409
|
-
* @param name - The phase name to ensure exists
|
|
1410
|
-
* @returns The phase name (may be auto-generated like 'before:render')
|
|
1411
|
-
*/
|
|
1412
|
-
ensurePhase(name) {
|
|
1413
|
-
if (this.phaseMap.has(name)) return name;
|
|
1414
|
-
const node = { name, isAutoGenerated: true };
|
|
1415
|
-
this.phases.push(node);
|
|
1416
|
-
this.phaseMap.set(name, node);
|
|
1417
|
-
this.invalidateCache();
|
|
1418
|
-
return name;
|
|
1419
|
-
}
|
|
1420
|
-
/**
|
|
1421
|
-
* Resolve where a job with before/after constraints should go.
|
|
1422
|
-
* Creates auto-generated phases if needed.
|
|
1423
|
-
*
|
|
1424
|
-
* @param before - Phase(s) to run before
|
|
1425
|
-
* @param after - Phase(s) to run after
|
|
1426
|
-
* @returns The resolved phase name
|
|
1427
|
-
*/
|
|
1428
|
-
resolveConstraintPhase(before, after) {
|
|
1429
|
-
const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
|
|
1430
|
-
const afterArr = after ? Array.isArray(after) ? after : [after] : [];
|
|
1431
|
-
if (beforeArr.length > 0) {
|
|
1432
|
-
return this.ensureAutoPhase(beforeArr[0], "before", 0);
|
|
1433
|
-
}
|
|
1434
|
-
if (afterArr.length > 0) {
|
|
1435
|
-
return this.ensureAutoPhase(afterArr[0], "after", 1);
|
|
1436
|
-
}
|
|
1437
|
-
return "update";
|
|
1438
|
-
}
|
|
1439
|
-
/**
|
|
1440
|
-
* Ensure an auto-generated phase exists relative to a target phase.
|
|
1441
|
-
* Creates the phase if it doesn't exist, inserting it at the correct position.
|
|
1442
|
-
*
|
|
1443
|
-
* @param target - The target phase name to position relative to
|
|
1444
|
-
* @param prefix - Prefix for auto-generated phase name ('before' or 'after')
|
|
1445
|
-
* @param offset - Insertion offset (0 for before, 1 for after)
|
|
1446
|
-
* @returns The auto-generated phase name
|
|
1447
|
-
*/
|
|
1448
|
-
ensureAutoPhase(target, prefix, offset) {
|
|
1449
|
-
const autoName = `${prefix}:${target}`;
|
|
1450
|
-
if (this.phaseMap.has(autoName)) return autoName;
|
|
1451
|
-
const node = { name: autoName, isAutoGenerated: true };
|
|
1452
|
-
const targetIndex = this.getPhaseIndex(target);
|
|
1453
|
-
if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
|
|
1454
|
-
else this.phases.push(node);
|
|
1455
|
-
this.phaseMap.set(autoName, node);
|
|
1456
|
-
this.invalidateCache();
|
|
1457
|
-
return autoName;
|
|
1458
|
-
}
|
|
1459
|
-
// Internal --------------------------------
|
|
1460
|
-
invalidateCache() {
|
|
1461
|
-
this.orderedNamesCache = null;
|
|
1462
|
-
}
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
function rebuildSortedJobs(jobs, phaseGraph) {
|
|
1466
|
-
const orderedPhases = phaseGraph.getOrderedPhases();
|
|
1467
|
-
const buckets = /* @__PURE__ */ new Map();
|
|
1468
|
-
for (const phase of orderedPhases) {
|
|
1469
|
-
buckets.set(phase, []);
|
|
1470
|
-
}
|
|
1471
|
-
for (const job of jobs.values()) {
|
|
1472
|
-
if (!job.enabled) continue;
|
|
1473
|
-
let bucket = buckets.get(job.phase);
|
|
1474
|
-
if (!bucket) {
|
|
1475
|
-
bucket = [];
|
|
1476
|
-
buckets.set(job.phase, bucket);
|
|
1477
|
-
}
|
|
1478
|
-
bucket.push(job);
|
|
1479
|
-
}
|
|
1480
|
-
const sortedBuckets = [];
|
|
1481
|
-
for (const phase of orderedPhases) {
|
|
1482
|
-
const bucket = buckets.get(phase);
|
|
1483
|
-
if (!bucket || bucket.length === 0) continue;
|
|
1484
|
-
bucket.sort((a, b) => {
|
|
1485
|
-
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1486
|
-
return a.index - b.index;
|
|
1487
|
-
});
|
|
1488
|
-
sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
|
|
1489
|
-
}
|
|
1490
|
-
for (const [phase, bucket] of buckets) {
|
|
1491
|
-
if (!orderedPhases.includes(phase) && bucket.length > 0) {
|
|
1492
|
-
bucket.sort((a, b) => {
|
|
1493
|
-
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1494
|
-
return a.index - b.index;
|
|
1495
|
-
});
|
|
1496
|
-
sortedBuckets.push(bucket);
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
return sortedBuckets.flat();
|
|
1500
|
-
}
|
|
1501
|
-
function hasCrossJobConstraints(bucket) {
|
|
1502
|
-
const jobIds = new Set(bucket.map((j) => j.id));
|
|
1503
|
-
for (const job of bucket) {
|
|
1504
|
-
for (const ref of job.before) {
|
|
1505
|
-
if (jobIds.has(ref)) return true;
|
|
1506
|
-
}
|
|
1507
|
-
for (const ref of job.after) {
|
|
1508
|
-
if (jobIds.has(ref)) return true;
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
return false;
|
|
1512
|
-
}
|
|
1513
|
-
function topologicalSort(jobs) {
|
|
1514
|
-
const n = jobs.length;
|
|
1515
|
-
if (n <= 1) return jobs;
|
|
1516
|
-
const jobMap = /* @__PURE__ */ new Map();
|
|
1517
|
-
const inDegree = /* @__PURE__ */ new Map();
|
|
1518
|
-
const adjacency = /* @__PURE__ */ new Map();
|
|
1519
|
-
for (const job of jobs) {
|
|
1520
|
-
jobMap.set(job.id, job);
|
|
1521
|
-
inDegree.set(job.id, 0);
|
|
1522
|
-
adjacency.set(job.id, []);
|
|
1523
|
-
}
|
|
1524
|
-
for (const job of jobs) {
|
|
1525
|
-
for (const ref of job.before) {
|
|
1526
|
-
if (jobMap.has(ref)) {
|
|
1527
|
-
adjacency.get(job.id).push(ref);
|
|
1528
|
-
inDegree.set(ref, inDegree.get(ref) + 1);
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
for (const ref of job.after) {
|
|
1532
|
-
if (jobMap.has(ref)) {
|
|
1533
|
-
adjacency.get(ref).push(job.id);
|
|
1534
|
-
inDegree.set(job.id, inDegree.get(job.id) + 1);
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
}
|
|
1538
|
-
const queue = [];
|
|
1539
|
-
for (const job of jobs) {
|
|
1540
|
-
if (inDegree.get(job.id) === 0) {
|
|
1541
|
-
queue.push(job);
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
queue.sort((a, b) => {
|
|
1545
|
-
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1546
|
-
return a.index - b.index;
|
|
1547
|
-
});
|
|
1548
|
-
const result = [];
|
|
1549
|
-
while (queue.length > 0) {
|
|
1550
|
-
const job = queue.shift();
|
|
1551
|
-
result.push(job);
|
|
1552
|
-
const neighbors = adjacency.get(job.id) || [];
|
|
1553
|
-
for (const neighborId of neighbors) {
|
|
1554
|
-
const newDegree = inDegree.get(neighborId) - 1;
|
|
1555
|
-
inDegree.set(neighborId, newDegree);
|
|
1556
|
-
if (newDegree === 0) {
|
|
1557
|
-
const neighbor = jobMap.get(neighborId);
|
|
1558
|
-
insertSorted(queue, neighbor);
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1562
|
-
if (result.length !== n) {
|
|
1563
|
-
console.warn("[useFrame] Circular dependency detected in job constraints");
|
|
1564
|
-
const resultIds = new Set(result.map((j) => j.id));
|
|
1565
|
-
for (const job of jobs) {
|
|
1566
|
-
if (!resultIds.has(job.id)) result.push(job);
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
return result;
|
|
1570
|
-
}
|
|
1571
|
-
function insertSorted(arr, job) {
|
|
1572
|
-
let i = 0;
|
|
1573
|
-
while (i < arr.length) {
|
|
1574
|
-
const cmp = arr[i];
|
|
1575
|
-
if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
|
|
1576
|
-
break;
|
|
1577
|
-
}
|
|
1578
|
-
i++;
|
|
1579
|
-
}
|
|
1580
|
-
arr.splice(i, 0, job);
|
|
1581
|
-
}
|
|
1582
|
-
|
|
1583
|
-
function shouldRun(job, now) {
|
|
1584
|
-
if (!job.enabled) return false;
|
|
1585
|
-
if (!job.fps) return true;
|
|
1586
|
-
const minInterval = 1e3 / job.fps;
|
|
1587
|
-
const lastRun = job.lastRun ?? 0;
|
|
1588
|
-
const elapsed = now - lastRun;
|
|
1589
|
-
if (elapsed < minInterval) return false;
|
|
1590
|
-
if (job.drop) {
|
|
1591
|
-
job.lastRun = now;
|
|
1592
|
-
} else {
|
|
1593
|
-
const steps = Math.floor(elapsed / minInterval);
|
|
1594
|
-
job.lastRun = lastRun + steps * minInterval;
|
|
1595
|
-
if (job.lastRun < now - minInterval) {
|
|
1596
|
-
job.lastRun = now;
|
|
1597
|
-
}
|
|
1598
|
-
}
|
|
1599
|
-
return true;
|
|
1600
|
-
}
|
|
1601
|
-
function resetJobTiming(job) {
|
|
1602
|
-
job.lastRun = void 0;
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
var __defProp = Object.defineProperty;
|
|
1606
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
1607
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1608
|
-
const hmrData = (() => {
|
|
1609
|
-
if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
|
|
1610
|
-
if (typeof import_meta_hot !== "undefined") return import_meta_hot;
|
|
1611
|
-
try {
|
|
1612
|
-
return (0, eval)("import.meta.hot");
|
|
1613
|
-
} catch {
|
|
1614
|
-
return void 0;
|
|
1615
|
-
}
|
|
1616
|
-
})();
|
|
1617
|
-
const _Scheduler = class _Scheduler {
|
|
1618
|
-
//* Constructor ================================
|
|
1619
|
-
constructor() {
|
|
1620
|
-
//* Critical State ================================
|
|
1621
|
-
__publicField(this, "roots", /* @__PURE__ */ new Map());
|
|
1622
|
-
__publicField(this, "phaseGraph");
|
|
1623
|
-
__publicField(this, "loopState", {
|
|
1624
|
-
running: false,
|
|
1625
|
-
rafHandle: null,
|
|
1626
|
-
lastTime: null,
|
|
1627
|
-
// null = uninitialized, 0+ = valid timestamp
|
|
1628
|
-
frameCount: 0,
|
|
1629
|
-
elapsedTime: 0,
|
|
1630
|
-
createdAt: performance.now()
|
|
1631
|
-
});
|
|
1632
|
-
__publicField(this, "stoppedTime", 0);
|
|
1633
|
-
//* Private State ================================
|
|
1634
|
-
__publicField(this, "nextRootIndex", 0);
|
|
1635
|
-
__publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
|
|
1636
|
-
__publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
|
|
1637
|
-
__publicField(this, "nextGlobalIndex", 0);
|
|
1638
|
-
__publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
|
|
1639
|
-
__publicField(this, "nextJobIndex", 0);
|
|
1640
|
-
__publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
|
|
1641
|
-
__publicField(this, "pendingFrames", 0);
|
|
1642
|
-
__publicField(this, "_frameloop", "always");
|
|
1643
|
-
//* Independent Mode & Error Handling State ================================
|
|
1644
|
-
__publicField(this, "_independent", false);
|
|
1645
|
-
__publicField(this, "errorHandler", null);
|
|
1646
|
-
__publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
|
|
1647
|
-
//* Core Loop Execution Methods ================================
|
|
1648
|
-
/**
|
|
1649
|
-
* Main RAF loop callback.
|
|
1650
|
-
* Executes frame, handles demand mode, and schedules next frame.
|
|
1651
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
1652
|
-
* @returns {void}
|
|
1653
|
-
* @private
|
|
1654
|
-
*/
|
|
1655
|
-
__publicField(this, "loop", (timestamp) => {
|
|
1656
|
-
if (!this.loopState.running) return;
|
|
1657
|
-
this.executeFrame(timestamp);
|
|
1658
|
-
if (this._frameloop === "demand") {
|
|
1659
|
-
this.pendingFrames = Math.max(0, this.pendingFrames - 1);
|
|
1660
|
-
if (this.pendingFrames === 0) {
|
|
1661
|
-
this.notifyIdle(timestamp);
|
|
1662
|
-
return this.stop();
|
|
1663
|
-
}
|
|
1664
|
-
}
|
|
1665
|
-
this.loopState.rafHandle = requestAnimationFrame(this.loop);
|
|
1666
|
-
});
|
|
1667
|
-
this.phaseGraph = new PhaseGraph();
|
|
1668
|
-
}
|
|
1669
|
-
static get instance() {
|
|
1670
|
-
return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
|
|
1671
|
-
}
|
|
1672
|
-
static set instance(value) {
|
|
1673
|
-
globalThis[_Scheduler.INSTANCE_KEY] = value;
|
|
1674
|
-
}
|
|
1675
|
-
/**
|
|
1676
|
-
* Get the global scheduler instance (creates if doesn't exist).
|
|
1677
|
-
* Uses HMR data to preserve instance across hot reloads.
|
|
1678
|
-
* @returns {Scheduler} The singleton scheduler instance
|
|
1679
|
-
*/
|
|
1680
|
-
static get() {
|
|
1681
|
-
if (!_Scheduler.instance && hmrData?.data?.scheduler) {
|
|
1682
|
-
_Scheduler.instance = hmrData.data.scheduler;
|
|
1683
|
-
}
|
|
1684
|
-
if (!_Scheduler.instance) {
|
|
1685
|
-
_Scheduler.instance = new _Scheduler();
|
|
1686
|
-
if (hmrData?.data) {
|
|
1687
|
-
hmrData.data.scheduler = _Scheduler.instance;
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
return _Scheduler.instance;
|
|
1691
|
-
}
|
|
1692
|
-
/**
|
|
1693
|
-
* Reset the singleton instance. Stops the loop and clears all state.
|
|
1694
|
-
* Primarily used for testing to ensure clean state between tests.
|
|
1695
|
-
* @returns {void}
|
|
1696
|
-
*/
|
|
1697
|
-
static reset() {
|
|
1698
|
-
if (_Scheduler.instance) {
|
|
1699
|
-
_Scheduler.instance.stop();
|
|
1700
|
-
_Scheduler.instance = null;
|
|
1701
|
-
}
|
|
1702
|
-
if (hmrData?.data) {
|
|
1703
|
-
hmrData.data.scheduler = null;
|
|
1704
|
-
}
|
|
1705
|
-
}
|
|
1706
|
-
//* Getters & Setters ================================
|
|
1707
|
-
get phases() {
|
|
1708
|
-
return this.phaseGraph.getOrderedPhases();
|
|
1709
|
-
}
|
|
1710
|
-
get frameloop() {
|
|
1711
|
-
return this._frameloop;
|
|
1712
|
-
}
|
|
1713
|
-
set frameloop(mode) {
|
|
1714
|
-
if (this._frameloop === mode) return;
|
|
1715
|
-
const wasAlways = this._frameloop === "always";
|
|
1716
|
-
this._frameloop = mode;
|
|
1717
|
-
if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
|
|
1718
|
-
else if (mode !== "always" && wasAlways) this.stop();
|
|
1719
|
-
}
|
|
1720
|
-
get isRunning() {
|
|
1721
|
-
return this.loopState.running;
|
|
1722
|
-
}
|
|
1723
|
-
get isReady() {
|
|
1724
|
-
return this.roots.size > 0;
|
|
1725
|
-
}
|
|
1726
|
-
get independent() {
|
|
1727
|
-
return this._independent;
|
|
1728
|
-
}
|
|
1729
|
-
set independent(value) {
|
|
1730
|
-
this._independent = value;
|
|
1731
|
-
if (value) this.ensureDefaultRoot();
|
|
1732
|
-
}
|
|
1733
|
-
//* Root Management Methods ================================
|
|
1734
|
-
/**
|
|
1735
|
-
* Register a root (Canvas) with the scheduler.
|
|
1736
|
-
* The first root to register starts the RAF loop (if frameloop='always').
|
|
1737
|
-
* @param {string} id - Unique identifier for this root
|
|
1738
|
-
* @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
|
|
1739
|
-
* @returns {() => void} Unsubscribe function to remove this root
|
|
1740
|
-
*/
|
|
1741
|
-
registerRoot(id, options = {}) {
|
|
1742
|
-
if (this.roots.has(id)) {
|
|
1743
|
-
console.warn(`[Scheduler] Root "${id}" already registered`);
|
|
1744
|
-
return () => this.unregisterRoot(id);
|
|
1745
|
-
}
|
|
1746
|
-
const entry = {
|
|
1747
|
-
id,
|
|
1748
|
-
getState: options.getState ?? (() => ({})),
|
|
1749
|
-
jobs: /* @__PURE__ */ new Map(),
|
|
1750
|
-
sortedJobs: [],
|
|
1751
|
-
needsRebuild: false
|
|
1752
|
-
};
|
|
1753
|
-
if (options.onError) {
|
|
1754
|
-
this.errorHandler = options.onError;
|
|
1755
|
-
}
|
|
1756
|
-
this.roots.set(id, entry);
|
|
1757
|
-
if (this.roots.size === 1) {
|
|
1758
|
-
this.notifyRootReady();
|
|
1759
|
-
if (this._frameloop === "always") this.start();
|
|
1760
|
-
}
|
|
1761
|
-
return () => this.unregisterRoot(id);
|
|
1762
|
-
}
|
|
1763
|
-
/**
|
|
1764
|
-
* Unregister a root from the scheduler.
|
|
1765
|
-
* Cleans up all job state listeners for this root's jobs.
|
|
1766
|
-
* The last root to unregister stops the RAF loop.
|
|
1767
|
-
* @param {string} id - The root ID to unregister
|
|
1768
|
-
* @returns {void}
|
|
1769
|
-
*/
|
|
1770
|
-
unregisterRoot(id) {
|
|
1771
|
-
const root = this.roots.get(id);
|
|
1772
|
-
if (!root) return;
|
|
1773
|
-
for (const jobId of root.jobs.keys()) {
|
|
1774
|
-
this.jobStateListeners.delete(jobId);
|
|
1775
|
-
}
|
|
1776
|
-
this.roots.delete(id);
|
|
1777
|
-
if (this.roots.size === 0) {
|
|
1778
|
-
this.stop();
|
|
1779
|
-
this.errorHandler = null;
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
/**
|
|
1783
|
-
* Subscribe to be notified when a root becomes available.
|
|
1784
|
-
* Fires immediately if a root already exists.
|
|
1785
|
-
* @param {() => void} callback - Function called when first root registers
|
|
1786
|
-
* @returns {() => void} Unsubscribe function
|
|
1787
|
-
*/
|
|
1788
|
-
onRootReady(callback) {
|
|
1789
|
-
if (this.roots.size > 0) {
|
|
1790
|
-
callback();
|
|
1791
|
-
return () => {
|
|
1792
|
-
};
|
|
1793
|
-
}
|
|
1794
|
-
this.rootReadyCallbacks.add(callback);
|
|
1795
|
-
return () => this.rootReadyCallbacks.delete(callback);
|
|
1796
|
-
}
|
|
1797
|
-
/**
|
|
1798
|
-
* Notify all registered root-ready callbacks.
|
|
1799
|
-
* Called when the first root registers.
|
|
1800
|
-
* @returns {void}
|
|
1801
|
-
* @private
|
|
1802
|
-
*/
|
|
1803
|
-
notifyRootReady() {
|
|
1804
|
-
for (const cb of this.rootReadyCallbacks) {
|
|
1805
|
-
try {
|
|
1806
|
-
cb();
|
|
1807
|
-
} catch (error) {
|
|
1808
|
-
console.error("[Scheduler] Error in root-ready callback:", error);
|
|
1809
|
-
}
|
|
1810
|
-
}
|
|
1811
|
-
this.rootReadyCallbacks.clear();
|
|
1812
|
-
}
|
|
1813
|
-
/**
|
|
1814
|
-
* Ensure a default root exists for independent mode.
|
|
1815
|
-
* Creates a minimal root with no state provider.
|
|
1816
|
-
* @returns {void}
|
|
1817
|
-
* @private
|
|
1818
|
-
*/
|
|
1819
|
-
ensureDefaultRoot() {
|
|
1820
|
-
if (!this.roots.has("__default__")) {
|
|
1821
|
-
this.registerRoot("__default__");
|
|
1822
|
-
}
|
|
1823
|
-
}
|
|
1824
|
-
/**
|
|
1825
|
-
* Trigger error handling for job errors.
|
|
1826
|
-
* Uses the bound error handler if available, otherwise logs to console.
|
|
1827
|
-
* @param {Error} error - The error to handle
|
|
1828
|
-
* @returns {void}
|
|
1829
|
-
*/
|
|
1830
|
-
triggerError(error) {
|
|
1831
|
-
if (this.errorHandler) this.errorHandler(error);
|
|
1832
|
-
else console.error("[Scheduler]", error);
|
|
1833
|
-
}
|
|
1834
|
-
//* Phase Management Methods ================================
|
|
1835
|
-
/**
|
|
1836
|
-
* Add a named phase to the scheduler's execution order.
|
|
1837
|
-
* Marks all roots for rebuild to incorporate the new phase.
|
|
1838
|
-
* @param {string} name - The phase name (e.g., 'physics', 'postprocess')
|
|
1839
|
-
* @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
|
|
1840
|
-
* @returns {void}
|
|
1841
|
-
* @example
|
|
1842
|
-
* scheduler.addPhase('physics', { before: 'update' });
|
|
1843
|
-
* scheduler.addPhase('postprocess', { after: 'render' });
|
|
1844
|
-
*/
|
|
1845
|
-
addPhase(name, options) {
|
|
1846
|
-
this.phaseGraph.addPhase(name, options);
|
|
1847
|
-
for (const root of this.roots.values()) {
|
|
1848
|
-
root.needsRebuild = true;
|
|
1849
|
-
}
|
|
1850
|
-
}
|
|
1851
|
-
/**
|
|
1852
|
-
* Check if a phase exists in the scheduler.
|
|
1853
|
-
* @param {string} name - The phase name to check
|
|
1854
|
-
* @returns {boolean} True if the phase exists
|
|
1855
|
-
*/
|
|
1856
|
-
hasPhase(name) {
|
|
1857
|
-
return this.phaseGraph.hasPhase(name);
|
|
1858
|
-
}
|
|
1859
|
-
//* Global Job Registration Methods (Deprecated APIs) ================================
|
|
1860
|
-
/**
|
|
1861
|
-
* Register a global job that runs once per frame (not per-root).
|
|
1862
|
-
* Used internally by deprecated addEffect/addAfterEffect APIs.
|
|
1863
|
-
* @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
|
|
1864
|
-
* @param {string} id - Unique identifier for this global job
|
|
1865
|
-
* @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
|
|
1866
|
-
* @returns {() => void} Unsubscribe function to remove this global job
|
|
1867
|
-
* @deprecated Use useFrame with phases instead
|
|
1868
|
-
*/
|
|
1869
|
-
registerGlobal(phase, id, callback) {
|
|
1870
|
-
const job = { id, callback };
|
|
1871
|
-
if (phase === "before") {
|
|
1872
|
-
this.globalBeforeJobs.set(id, job);
|
|
1873
|
-
} else {
|
|
1874
|
-
this.globalAfterJobs.set(id, job);
|
|
1875
|
-
}
|
|
1876
|
-
return () => {
|
|
1877
|
-
if (phase === "before") this.globalBeforeJobs.delete(id);
|
|
1878
|
-
else this.globalAfterJobs.delete(id);
|
|
1879
|
-
};
|
|
1880
|
-
}
|
|
1881
|
-
//* Idle Callback Methods (Deprecated API) ================================
|
|
1882
|
-
/**
|
|
1883
|
-
* Register an idle callback that fires when the loop stops.
|
|
1884
|
-
* Used internally by deprecated addTail API.
|
|
1885
|
-
* @param {(timestamp: number) => void} callback - Function called when loop becomes idle
|
|
1886
|
-
* @returns {() => void} Unsubscribe function to remove this idle callback
|
|
1887
|
-
* @deprecated Use demand mode with invalidate() instead
|
|
1888
|
-
*/
|
|
1889
|
-
onIdle(callback) {
|
|
1890
|
-
this.idleCallbacks.add(callback);
|
|
1891
|
-
return () => this.idleCallbacks.delete(callback);
|
|
1892
|
-
}
|
|
1893
|
-
/**
|
|
1894
|
-
* Notify all registered idle callbacks.
|
|
1895
|
-
* Called when the loop stops in demand mode.
|
|
1896
|
-
* @param {number} timestamp - The RAF timestamp when idle occurred
|
|
1897
|
-
* @returns {void}
|
|
1898
|
-
* @private
|
|
1899
|
-
*/
|
|
1900
|
-
notifyIdle(timestamp) {
|
|
1901
|
-
for (const cb of this.idleCallbacks) {
|
|
1902
|
-
try {
|
|
1903
|
-
cb(timestamp);
|
|
1904
|
-
} catch (error) {
|
|
1905
|
-
console.error("[Scheduler] Error in idle callback:", error);
|
|
1906
|
-
}
|
|
1907
|
-
}
|
|
1908
|
-
}
|
|
1909
|
-
//* Job Registration & Management Methods ================================
|
|
1910
|
-
/**
|
|
1911
|
-
* Register a job (frame callback) with a specific root.
|
|
1912
|
-
* This is the core registration method used by useFrame internally.
|
|
1913
|
-
* @param {FrameNextCallback} callback - The function to call each frame
|
|
1914
|
-
* @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
|
|
1915
|
-
* @param {string} [options.rootId] - Target root ID (defaults to first registered root)
|
|
1916
|
-
* @param {string} [options.id] - Unique job ID (auto-generated if not provided)
|
|
1917
|
-
* @param {string} [options.phase] - Execution phase (defaults to 'update')
|
|
1918
|
-
* @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
|
|
1919
|
-
* @param {number} [options.fps] - FPS throttle limit
|
|
1920
|
-
* @param {boolean} [options.drop] - Drop frames when behind (default true)
|
|
1921
|
-
* @param {boolean} [options.enabled] - Whether job is active (default true)
|
|
1922
|
-
* @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
|
|
1923
|
-
* @returns {() => void} Unsubscribe function to remove this job
|
|
1924
|
-
*/
|
|
1925
|
-
register(callback, options = {}) {
|
|
1926
|
-
const rootId = options.rootId;
|
|
1927
|
-
const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
|
|
1928
|
-
if (!root) {
|
|
1929
|
-
console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
|
|
1930
|
-
return () => {
|
|
1931
|
-
};
|
|
1932
|
-
}
|
|
1933
|
-
const id = options.id ?? this.generateJobId();
|
|
1934
|
-
let phase = options.phase ?? "update";
|
|
1935
|
-
if (!options.phase && (options.before || options.after)) {
|
|
1936
|
-
phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
|
|
1937
|
-
}
|
|
1938
|
-
const before = this.normalizeConstraints(options.before);
|
|
1939
|
-
const after = this.normalizeConstraints(options.after);
|
|
1940
|
-
const job = {
|
|
1941
|
-
id,
|
|
1942
|
-
callback,
|
|
1943
|
-
phase,
|
|
1944
|
-
before,
|
|
1945
|
-
after,
|
|
1946
|
-
priority: options.priority ?? 0,
|
|
1947
|
-
index: this.nextJobIndex++,
|
|
1948
|
-
fps: options.fps,
|
|
1949
|
-
drop: options.drop ?? true,
|
|
1950
|
-
enabled: options.enabled ?? true,
|
|
1951
|
-
system: options.system ?? false
|
|
1952
|
-
};
|
|
1953
|
-
if (root.jobs.has(id)) {
|
|
1954
|
-
console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
|
|
1955
|
-
}
|
|
1956
|
-
root.jobs.set(id, job);
|
|
1957
|
-
root.needsRebuild = true;
|
|
1958
|
-
return () => this.unregister(id, root.id);
|
|
1959
|
-
}
|
|
1960
|
-
/**
|
|
1961
|
-
* Unregister a job by its ID.
|
|
1962
|
-
* Searches all roots if rootId is not provided.
|
|
1963
|
-
* @param {string} id - The job ID to unregister
|
|
1964
|
-
* @param {string} [rootId] - Optional root ID to search (searches all if not provided)
|
|
1965
|
-
* @returns {void}
|
|
1966
|
-
*/
|
|
1967
|
-
unregister(id, rootId) {
|
|
1968
|
-
const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
|
|
1969
|
-
if (root?.jobs.delete(id)) {
|
|
1970
|
-
root.needsRebuild = true;
|
|
1971
|
-
this.jobStateListeners.delete(id);
|
|
1972
|
-
}
|
|
1973
|
-
}
|
|
1974
|
-
/**
|
|
1975
|
-
* Update a job's options dynamically.
|
|
1976
|
-
* Searches all roots to find the job by ID.
|
|
1977
|
-
* Phase/constraint changes trigger a rebuild of the sorted job list.
|
|
1978
|
-
* @param {string} id - The job ID to update
|
|
1979
|
-
* @param {Partial<JobOptions>} options - The options to update
|
|
1980
|
-
* @returns {void}
|
|
1981
|
-
*/
|
|
1982
|
-
updateJob(id, options) {
|
|
1983
|
-
let job;
|
|
1984
|
-
let root;
|
|
1985
|
-
for (const r of this.roots.values()) {
|
|
1986
|
-
job = r.jobs.get(id);
|
|
1987
|
-
if (job) {
|
|
1988
|
-
root = r;
|
|
1989
|
-
break;
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
if (!job || !root) return;
|
|
1993
|
-
if (options.priority !== void 0) job.priority = options.priority;
|
|
1994
|
-
if (options.fps !== void 0) job.fps = options.fps;
|
|
1995
|
-
if (options.drop !== void 0) job.drop = options.drop;
|
|
1996
|
-
if (options.enabled !== void 0) {
|
|
1997
|
-
const wasEnabled = job.enabled;
|
|
1998
|
-
job.enabled = options.enabled;
|
|
1999
|
-
if (!wasEnabled && job.enabled) resetJobTiming(job);
|
|
2000
|
-
if (wasEnabled !== job.enabled) root.needsRebuild = true;
|
|
2001
|
-
}
|
|
2002
|
-
if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
|
|
2003
|
-
if (options.phase) job.phase = options.phase;
|
|
2004
|
-
if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
|
|
2005
|
-
if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
|
|
2006
|
-
root.needsRebuild = true;
|
|
2007
|
-
}
|
|
2008
|
-
}
|
|
2009
|
-
//* Job State Management Methods ================================
|
|
2010
|
-
/**
|
|
2011
|
-
* Check if a job is currently paused (disabled).
|
|
2012
|
-
* @param {string} id - The job ID to check
|
|
2013
|
-
* @returns {boolean} True if the job exists and is paused
|
|
2014
|
-
*/
|
|
2015
|
-
isJobPaused(id) {
|
|
2016
|
-
for (const root of this.roots.values()) {
|
|
2017
|
-
const job = root.jobs.get(id);
|
|
2018
|
-
if (job) return !job.enabled;
|
|
2019
|
-
}
|
|
2020
|
-
return false;
|
|
2021
|
-
}
|
|
2022
|
-
/**
|
|
2023
|
-
* Subscribe to state changes for a specific job.
|
|
2024
|
-
* Listener is called when job is paused or resumed.
|
|
2025
|
-
* @param {string} id - The job ID to subscribe to
|
|
2026
|
-
* @param {() => void} listener - Callback invoked on state changes
|
|
2027
|
-
* @returns {() => void} Unsubscribe function
|
|
2028
|
-
*/
|
|
2029
|
-
subscribeJobState(id, listener) {
|
|
2030
|
-
if (!this.jobStateListeners.has(id)) {
|
|
2031
|
-
this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
|
|
2032
|
-
}
|
|
2033
|
-
this.jobStateListeners.get(id).add(listener);
|
|
2034
|
-
return () => {
|
|
2035
|
-
this.jobStateListeners.get(id)?.delete(listener);
|
|
2036
|
-
if (this.jobStateListeners.get(id)?.size === 0) {
|
|
2037
|
-
this.jobStateListeners.delete(id);
|
|
2038
|
-
}
|
|
2039
|
-
};
|
|
2040
|
-
}
|
|
2041
|
-
/**
|
|
2042
|
-
* Notify all listeners that a job's state has changed.
|
|
2043
|
-
* @param {string} id - The job ID that changed
|
|
2044
|
-
* @returns {void}
|
|
2045
|
-
* @private
|
|
2046
|
-
*/
|
|
2047
|
-
notifyJobStateChange(id) {
|
|
2048
|
-
this.jobStateListeners.get(id)?.forEach((listener) => listener());
|
|
2049
|
-
}
|
|
2050
|
-
/**
|
|
2051
|
-
* Pause a job by ID (sets enabled=false).
|
|
2052
|
-
* Notifies any subscribed state listeners.
|
|
2053
|
-
* @param {string} id - The job ID to pause
|
|
2054
|
-
* @returns {void}
|
|
2055
|
-
*/
|
|
2056
|
-
pauseJob(id) {
|
|
2057
|
-
this.updateJob(id, { enabled: false });
|
|
2058
|
-
this.notifyJobStateChange(id);
|
|
2059
|
-
}
|
|
2060
|
-
/**
|
|
2061
|
-
* Resume a paused job by ID (sets enabled=true).
|
|
2062
|
-
* Resets job timing to prevent frame accumulation.
|
|
2063
|
-
* Notifies any subscribed state listeners.
|
|
2064
|
-
* @param {string} id - The job ID to resume
|
|
2065
|
-
* @returns {void}
|
|
2066
|
-
*/
|
|
2067
|
-
resumeJob(id) {
|
|
2068
|
-
this.updateJob(id, { enabled: true });
|
|
2069
|
-
this.notifyJobStateChange(id);
|
|
2070
|
-
}
|
|
2071
|
-
//* Frame Loop Control Methods ================================
|
|
2072
|
-
/**
|
|
2073
|
-
* Start the requestAnimationFrame loop.
|
|
2074
|
-
* Resets timing state (elapsedTime, frameCount) on start.
|
|
2075
|
-
* No-op if already running.
|
|
2076
|
-
* @returns {void}
|
|
2077
|
-
*/
|
|
2078
|
-
start() {
|
|
2079
|
-
if (this.loopState.running) return;
|
|
2080
|
-
const { elapsedTime, createdAt } = this.loopState;
|
|
2081
|
-
let adjustedCreated = 0;
|
|
2082
|
-
if (this.stoppedTime > 0) {
|
|
2083
|
-
adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
|
|
2084
|
-
this.stoppedTime = 0;
|
|
2085
|
-
}
|
|
2086
|
-
Object.assign(this.loopState, {
|
|
2087
|
-
running: true,
|
|
2088
|
-
elapsedTime: elapsedTime ?? 0,
|
|
2089
|
-
lastTime: performance.now(),
|
|
2090
|
-
createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
|
|
2091
|
-
frameCount: 0,
|
|
2092
|
-
rafHandle: requestAnimationFrame(this.loop)
|
|
2093
|
-
});
|
|
2094
|
-
}
|
|
2095
|
-
/**
|
|
2096
|
-
* Stop the requestAnimationFrame loop.
|
|
2097
|
-
* Cancels any pending RAF callback.
|
|
2098
|
-
* No-op if not running.
|
|
2099
|
-
* @returns {void}
|
|
2100
|
-
*/
|
|
2101
|
-
stop() {
|
|
2102
|
-
if (!this.loopState.running) return;
|
|
2103
|
-
this.loopState.running = false;
|
|
2104
|
-
if (this.loopState.rafHandle !== null) {
|
|
2105
|
-
cancelAnimationFrame(this.loopState.rafHandle);
|
|
2106
|
-
this.loopState.rafHandle = null;
|
|
2107
|
-
}
|
|
2108
|
-
this.stoppedTime = performance.now();
|
|
2109
|
-
}
|
|
2110
|
-
/**
|
|
2111
|
-
* Request frames to be rendered in demand mode.
|
|
2112
|
-
* Accumulates pending frames (capped at 60) and starts the loop if not running.
|
|
2113
|
-
* No-op if frameloop is not 'demand'.
|
|
2114
|
-
* @param {number} [frames=1] - Number of frames to request
|
|
2115
|
-
* @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
|
|
2116
|
-
* - `false` (default): Sets pending frames to the specified value (replaces existing count)
|
|
2117
|
-
* - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
|
|
2118
|
-
* @returns {void}
|
|
2119
|
-
* @example
|
|
2120
|
-
* // Request a single frame render
|
|
2121
|
-
* scheduler.invalidate();
|
|
2122
|
-
*
|
|
2123
|
-
* @example
|
|
2124
|
-
* // Request 5 frames (e.g., for animations)
|
|
2125
|
-
* scheduler.invalidate(5);
|
|
2126
|
-
*
|
|
2127
|
-
* @example
|
|
2128
|
-
* // Set pending frames to exactly 3 (don't stack with existing)
|
|
2129
|
-
* scheduler.invalidate(3, false);
|
|
2130
|
-
*
|
|
2131
|
-
* @example
|
|
2132
|
-
* // Add 2 more frames to existing pending count
|
|
2133
|
-
* scheduler.invalidate(2, true);
|
|
2134
|
-
*/
|
|
2135
|
-
invalidate(frames = 1, stackFrames = false) {
|
|
2136
|
-
if (this._frameloop !== "demand") return;
|
|
2137
|
-
const baseFrames = stackFrames ? this.pendingFrames : 0;
|
|
2138
|
-
this.pendingFrames = Math.min(60, baseFrames + frames);
|
|
2139
|
-
if (!this.loopState.running && this.pendingFrames > 0) this.start();
|
|
2140
|
-
}
|
|
2141
|
-
/**
|
|
2142
|
-
* Reset timing state for deterministic testing.
|
|
2143
|
-
* Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
|
|
2144
|
-
* @returns {void}
|
|
2145
|
-
*/
|
|
2146
|
-
resetTiming() {
|
|
2147
|
-
this.loopState.lastTime = null;
|
|
2148
|
-
this.loopState.frameCount = 0;
|
|
2149
|
-
this.loopState.elapsedTime = 0;
|
|
2150
|
-
this.loopState.createdAt = performance.now();
|
|
2151
|
-
}
|
|
2152
|
-
//* Manual Stepping Methods ================================
|
|
2153
|
-
/**
|
|
2154
|
-
* Manually execute a single frame for all roots.
|
|
2155
|
-
* Useful for frameloop='never' mode or testing scenarios.
|
|
2156
|
-
* @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
|
|
2157
|
-
* @returns {void}
|
|
2158
|
-
* @example
|
|
2159
|
-
* // Manual control mode
|
|
2160
|
-
* scheduler.frameloop = 'never';
|
|
2161
|
-
* scheduler.step(); // Execute one frame
|
|
2162
|
-
*/
|
|
2163
|
-
step(timestamp) {
|
|
2164
|
-
const now = timestamp ?? performance.now();
|
|
2165
|
-
this.executeFrame(now);
|
|
2166
|
-
}
|
|
2167
|
-
/**
|
|
2168
|
-
* Manually execute a single job by its ID.
|
|
2169
|
-
* Useful for testing individual job callbacks in isolation.
|
|
2170
|
-
* @param {string} id - The job ID to step
|
|
2171
|
-
* @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
|
|
2172
|
-
* @returns {void}
|
|
2173
|
-
*/
|
|
2174
|
-
stepJob(id, timestamp) {
|
|
2175
|
-
let job;
|
|
2176
|
-
let root;
|
|
2177
|
-
for (const r of this.roots.values()) {
|
|
2178
|
-
job = r.jobs.get(id);
|
|
2179
|
-
if (job) {
|
|
2180
|
-
root = r;
|
|
2181
|
-
break;
|
|
2182
|
-
}
|
|
2183
|
-
}
|
|
2184
|
-
if (!job || !root) {
|
|
2185
|
-
console.warn(`[Scheduler] Job "${id}" not found`);
|
|
2186
|
-
return;
|
|
2187
|
-
}
|
|
2188
|
-
const now = timestamp ?? performance.now();
|
|
2189
|
-
const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
|
|
2190
|
-
const delta = deltaMs / 1e3;
|
|
2191
|
-
const elapsed = now - this.loopState.createdAt;
|
|
2192
|
-
const providedState = root.getState?.() ?? {};
|
|
2193
|
-
const frameState = {
|
|
2194
|
-
...providedState,
|
|
2195
|
-
time: now,
|
|
2196
|
-
delta,
|
|
2197
|
-
elapsed,
|
|
2198
|
-
frame: this.loopState.frameCount
|
|
2199
|
-
};
|
|
2200
|
-
try {
|
|
2201
|
-
job.callback(frameState, delta);
|
|
2202
|
-
} catch (error) {
|
|
2203
|
-
console.error(`[Scheduler] Error in job "${job.id}":`, error);
|
|
2204
|
-
this.triggerError(error instanceof Error ? error : new Error(String(error)));
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
/**
|
|
2208
|
-
* Execute a single frame across all roots.
|
|
2209
|
-
* Order: globalBefore → each root's jobs → globalAfter
|
|
2210
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
2211
|
-
* @returns {void}
|
|
2212
|
-
* @private
|
|
2213
|
-
*/
|
|
2214
|
-
executeFrame(timestamp) {
|
|
2215
|
-
const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
|
|
2216
|
-
const delta = deltaMs / 1e3;
|
|
2217
|
-
this.loopState.lastTime = timestamp;
|
|
2218
|
-
this.loopState.frameCount++;
|
|
2219
|
-
this.loopState.elapsedTime += deltaMs;
|
|
2220
|
-
this.runGlobalJobs(this.globalBeforeJobs, timestamp);
|
|
2221
|
-
for (const root of this.roots.values()) {
|
|
2222
|
-
this.tickRoot(root, timestamp, delta);
|
|
2223
|
-
}
|
|
2224
|
-
this.runGlobalJobs(this.globalAfterJobs, timestamp);
|
|
2225
|
-
}
|
|
2226
|
-
/**
|
|
2227
|
-
* Run all global jobs from a job map.
|
|
2228
|
-
* Catches and logs errors without stopping execution.
|
|
2229
|
-
* @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
|
|
2230
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
2231
|
-
* @returns {void}
|
|
2232
|
-
* @private
|
|
2233
|
-
*/
|
|
2234
|
-
runGlobalJobs(jobs, timestamp) {
|
|
2235
|
-
for (const job of jobs.values()) {
|
|
2236
|
-
try {
|
|
2237
|
-
job.callback(timestamp);
|
|
2238
|
-
} catch (error) {
|
|
2239
|
-
console.error(`[Scheduler] Error in global job "${job.id}":`, error);
|
|
2240
|
-
}
|
|
2241
|
-
}
|
|
2242
|
-
}
|
|
2243
|
-
/**
|
|
2244
|
-
* Execute all jobs for a single root in sorted order.
|
|
2245
|
-
* Rebuilds sorted job list if needed, then dispatches each job.
|
|
2246
|
-
* Errors are caught and propagated via triggerError.
|
|
2247
|
-
* @param {RootEntry} root - The root entry to tick
|
|
2248
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
2249
|
-
* @param {number} delta - Time since last frame in seconds
|
|
2250
|
-
* @returns {void}
|
|
2251
|
-
* @private
|
|
2252
|
-
*/
|
|
2253
|
-
tickRoot(root, timestamp, delta) {
|
|
2254
|
-
if (root.needsRebuild) {
|
|
2255
|
-
root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
|
|
2256
|
-
root.needsRebuild = false;
|
|
2257
|
-
}
|
|
2258
|
-
const providedState = root.getState?.() ?? {};
|
|
2259
|
-
const frameState = {
|
|
2260
|
-
...providedState,
|
|
2261
|
-
time: timestamp,
|
|
2262
|
-
delta,
|
|
2263
|
-
elapsed: this.loopState.elapsedTime / 1e3,
|
|
2264
|
-
// Convert ms to seconds
|
|
2265
|
-
frame: this.loopState.frameCount
|
|
2266
|
-
};
|
|
2267
|
-
for (const job of root.sortedJobs) {
|
|
2268
|
-
if (!shouldRun(job, timestamp)) continue;
|
|
2269
|
-
try {
|
|
2270
|
-
job.callback(frameState, delta);
|
|
2271
|
-
} catch (error) {
|
|
2272
|
-
console.error(`[Scheduler] Error in job "${job.id}":`, error);
|
|
2273
|
-
this.triggerError(error instanceof Error ? error : new Error(String(error)));
|
|
2274
|
-
}
|
|
2275
|
-
}
|
|
2276
|
-
}
|
|
2277
|
-
//* Debug & Inspection Methods ================================
|
|
2278
|
-
/**
|
|
2279
|
-
* Get the total number of registered jobs across all roots.
|
|
2280
|
-
* Includes both per-root jobs and global before/after jobs.
|
|
2281
|
-
* @returns {number} Total job count
|
|
2282
|
-
*/
|
|
2283
|
-
getJobCount() {
|
|
2284
|
-
let count = 0;
|
|
2285
|
-
for (const root of this.roots.values()) {
|
|
2286
|
-
count += root.jobs.size;
|
|
2287
|
-
}
|
|
2288
|
-
return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
|
|
2289
|
-
}
|
|
2290
|
-
/**
|
|
2291
|
-
* Get all registered job IDs across all roots.
|
|
2292
|
-
* Includes both per-root jobs and global before/after jobs.
|
|
2293
|
-
* @returns {string[]} Array of all job IDs
|
|
2294
|
-
*/
|
|
2295
|
-
getJobIds() {
|
|
2296
|
-
const ids = [];
|
|
2297
|
-
for (const root of this.roots.values()) {
|
|
2298
|
-
ids.push(...root.jobs.keys());
|
|
2299
|
-
}
|
|
2300
|
-
ids.push(...this.globalBeforeJobs.keys());
|
|
2301
|
-
ids.push(...this.globalAfterJobs.keys());
|
|
2302
|
-
return ids;
|
|
2303
|
-
}
|
|
2304
|
-
/**
|
|
2305
|
-
* Get the number of registered roots (Canvas instances).
|
|
2306
|
-
* @returns {number} Number of registered roots
|
|
2307
|
-
*/
|
|
2308
|
-
getRootCount() {
|
|
2309
|
-
return this.roots.size;
|
|
2310
|
-
}
|
|
2311
|
-
/**
|
|
2312
|
-
* Check if any user (non-system) jobs are registered in a specific phase.
|
|
2313
|
-
* Used by the default render job to know if a user has taken over rendering.
|
|
2314
|
-
*
|
|
2315
|
-
* @param phase The phase to check
|
|
2316
|
-
* @param rootId Optional root ID to check (checks all roots if not provided)
|
|
2317
|
-
* @returns true if any user jobs exist in the phase
|
|
2318
|
-
*/
|
|
2319
|
-
hasUserJobsInPhase(phase, rootId) {
|
|
2320
|
-
const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
|
|
2321
|
-
return rootsToCheck.some((root) => {
|
|
2322
|
-
if (!root) return false;
|
|
2323
|
-
for (const job of root.jobs.values()) {
|
|
2324
|
-
if (job.phase === phase && !job.system && job.enabled) return true;
|
|
2325
|
-
}
|
|
2326
|
-
return false;
|
|
2327
|
-
});
|
|
2328
|
-
}
|
|
2329
|
-
//* Utility Methods ================================
|
|
2330
|
-
/**
|
|
2331
|
-
* Generate a unique root ID for automatic root registration.
|
|
2332
|
-
* @returns {string} A unique root ID in the format 'root_N'
|
|
2333
|
-
*/
|
|
2334
|
-
generateRootId() {
|
|
2335
|
-
return `root_${this.nextRootIndex++}`;
|
|
2336
|
-
}
|
|
2337
|
-
/**
|
|
2338
|
-
* Generate a unique job ID.
|
|
2339
|
-
* @returns {string} A unique job ID in the format 'job_N'
|
|
2340
|
-
* @private
|
|
2341
|
-
*/
|
|
2342
|
-
generateJobId() {
|
|
2343
|
-
return `job_${this.nextJobIndex}`;
|
|
2344
|
-
}
|
|
2345
|
-
/**
|
|
2346
|
-
* Normalize before/after constraints to a Set.
|
|
2347
|
-
* Handles undefined, single string, or array inputs.
|
|
2348
|
-
* @param {string | string[] | undefined} value - The constraint value(s)
|
|
2349
|
-
* @returns {Set<string>} Normalized Set of constraint strings
|
|
2350
|
-
* @private
|
|
2351
|
-
*/
|
|
2352
|
-
normalizeConstraints(value) {
|
|
2353
|
-
if (!value) return /* @__PURE__ */ new Set();
|
|
2354
|
-
if (Array.isArray(value)) return new Set(value);
|
|
2355
|
-
return /* @__PURE__ */ new Set([value]);
|
|
2356
|
-
}
|
|
2357
|
-
};
|
|
2358
|
-
//* Static State & Methods (Singleton Usage) ================================
|
|
2359
|
-
//* Cross-Bundle Singleton Key ==============================
|
|
2360
|
-
// Use Symbol.for() to ensure scheduler is shared across bundle boundaries
|
|
2361
|
-
// This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
|
|
2362
|
-
__publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
|
|
2363
|
-
let Scheduler = _Scheduler;
|
|
2364
|
-
const getScheduler = () => Scheduler.get();
|
|
2365
|
-
if (hmrData) {
|
|
2366
|
-
hmrData.accept?.();
|
|
2367
|
-
}
|
|
2368
|
-
|
|
2369
1970
|
function useFrame(callback, priorityOrOptions) {
|
|
2370
1971
|
const store = React.useContext(context);
|
|
2371
1972
|
const isInsideCanvas = store !== null;
|
|
@@ -2438,20 +2039,14 @@ function useFrame(callback, priorityOrOptions) {
|
|
|
2438
2039
|
}
|
|
2439
2040
|
};
|
|
2440
2041
|
} else {
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
unregisterJob = registerOutside();
|
|
2450
|
-
});
|
|
2451
|
-
return () => {
|
|
2452
|
-
unsubReady();
|
|
2453
|
-
unregisterJob?.();
|
|
2454
|
-
};
|
|
2042
|
+
return scheduler.register(
|
|
2043
|
+
(state, delta) => {
|
|
2044
|
+
const frameState = state;
|
|
2045
|
+
if (!frameState.renderer) return;
|
|
2046
|
+
callbackRef.current?.(frameState, delta);
|
|
2047
|
+
},
|
|
2048
|
+
{ id, ...options }
|
|
2049
|
+
);
|
|
2455
2050
|
}
|
|
2456
2051
|
}, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
|
|
2457
2052
|
const isPaused = React.useSyncExternalStore(
|
|
@@ -2542,22 +2137,29 @@ function buildFromCache(input, textureCache) {
|
|
|
2542
2137
|
function useTexture(input, optionsOrOnLoad) {
|
|
2543
2138
|
const renderer = useThree((state) => state.internal.actualRenderer);
|
|
2544
2139
|
const store = useStore();
|
|
2545
|
-
const textureCache = useThree((state) => state.textures);
|
|
2546
2140
|
const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
|
|
2547
|
-
const { onLoad, cache =
|
|
2141
|
+
const { onLoad, cache = true } = options;
|
|
2142
|
+
const onLoadRef = useRef(onLoad);
|
|
2143
|
+
onLoadRef.current = onLoad;
|
|
2144
|
+
const onLoadCalledForRef = useRef(null);
|
|
2548
2145
|
const urls = useMemo(() => getUrls(input), [input]);
|
|
2549
2146
|
const cachedResult = useMemo(() => {
|
|
2550
2147
|
if (!cache) return null;
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2148
|
+
const textures = store.getState().textures;
|
|
2149
|
+
if (!allUrlsCached(urls, textures)) return null;
|
|
2150
|
+
return buildFromCache(input, textures);
|
|
2151
|
+
}, [cache, urls, input, store]);
|
|
2554
2152
|
const loadedTextures = useLoader(
|
|
2555
2153
|
TextureLoader,
|
|
2556
2154
|
IsObject(input) ? Object.values(input) : input
|
|
2557
2155
|
);
|
|
2156
|
+
const inputKey = urls.join("\0");
|
|
2558
2157
|
useLayoutEffect(() => {
|
|
2559
|
-
if (
|
|
2560
|
-
|
|
2158
|
+
if (cachedResult) return;
|
|
2159
|
+
if (onLoadCalledForRef.current === inputKey) return;
|
|
2160
|
+
onLoadCalledForRef.current = inputKey;
|
|
2161
|
+
onLoadRef.current?.(loadedTextures);
|
|
2162
|
+
}, [cachedResult, loadedTextures, inputKey]);
|
|
2561
2163
|
useEffect(() => {
|
|
2562
2164
|
if (cachedResult) return;
|
|
2563
2165
|
if ("initTexture" in renderer) {
|
|
@@ -2590,8 +2192,6 @@ function useTexture(input, optionsOrOnLoad) {
|
|
|
2590
2192
|
}, [input, loadedTextures, cachedResult]);
|
|
2591
2193
|
useEffect(() => {
|
|
2592
2194
|
if (!cache) return;
|
|
2593
|
-
if (cachedResult) return;
|
|
2594
|
-
const set = store.setState;
|
|
2595
2195
|
const urlTextureMap = [];
|
|
2596
2196
|
if (typeof input === "string") {
|
|
2597
2197
|
urlTextureMap.push([input, mappedTextures]);
|
|
@@ -2605,18 +2205,32 @@ function useTexture(input, optionsOrOnLoad) {
|
|
|
2605
2205
|
urlTextureMap.push([url, textureRecord[key]]);
|
|
2606
2206
|
}
|
|
2607
2207
|
}
|
|
2608
|
-
|
|
2609
|
-
const
|
|
2610
|
-
let
|
|
2208
|
+
store.setState((state) => {
|
|
2209
|
+
const refs = new Map(state._textureRefs);
|
|
2210
|
+
let textures = state.textures;
|
|
2211
|
+
let added = false;
|
|
2611
2212
|
for (const [url, texture] of urlTextureMap) {
|
|
2612
|
-
if (!
|
|
2613
|
-
|
|
2614
|
-
|
|
2213
|
+
if (!textures.has(url)) {
|
|
2214
|
+
if (!added) {
|
|
2215
|
+
textures = new Map(textures);
|
|
2216
|
+
added = true;
|
|
2217
|
+
}
|
|
2218
|
+
textures.set(url, texture);
|
|
2615
2219
|
}
|
|
2220
|
+
refs.set(url, (refs.get(url) ?? 0) + 1);
|
|
2616
2221
|
}
|
|
2617
|
-
return
|
|
2222
|
+
return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
|
|
2618
2223
|
});
|
|
2619
|
-
|
|
2224
|
+
return () => store.setState((state) => {
|
|
2225
|
+
const refs = new Map(state._textureRefs);
|
|
2226
|
+
for (const [url] of urlTextureMap) {
|
|
2227
|
+
const next = (refs.get(url) ?? 0) - 1;
|
|
2228
|
+
if (next <= 0) refs.delete(url);
|
|
2229
|
+
else refs.set(url, next);
|
|
2230
|
+
}
|
|
2231
|
+
return { _textureRefs: refs };
|
|
2232
|
+
});
|
|
2233
|
+
}, [cache, input, mappedTextures, store]);
|
|
2620
2234
|
return mappedTextures;
|
|
2621
2235
|
}
|
|
2622
2236
|
useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
|
|
@@ -2632,106 +2246,90 @@ const Texture = ({
|
|
|
2632
2246
|
return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
|
|
2633
2247
|
};
|
|
2634
2248
|
|
|
2635
|
-
function
|
|
2636
|
-
if (entry instanceof Texture$1) return entry;
|
|
2637
|
-
if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
|
|
2638
|
-
return entry.value;
|
|
2639
|
-
}
|
|
2640
|
-
return null;
|
|
2641
|
-
}
|
|
2642
|
-
function useTextures() {
|
|
2249
|
+
function useTextures(selector) {
|
|
2643
2250
|
const store = useStore();
|
|
2644
|
-
|
|
2645
|
-
const set = store.setState;
|
|
2251
|
+
const registry = useMemo(() => {
|
|
2646
2252
|
const getState = store.getState;
|
|
2647
|
-
const
|
|
2648
|
-
|
|
2649
|
-
const newMap = new Map(state.textures);
|
|
2650
|
-
newMap.set(key, value);
|
|
2651
|
-
return { textures: newMap };
|
|
2652
|
-
});
|
|
2653
|
-
};
|
|
2654
|
-
const addMultiple = (items) => {
|
|
2655
|
-
set((state) => {
|
|
2656
|
-
const newMap = new Map(state.textures);
|
|
2657
|
-
const entries = items instanceof Map ? items.entries() : Object.entries(items);
|
|
2658
|
-
for (const [key, value] of entries) {
|
|
2659
|
-
newMap.set(key, value);
|
|
2660
|
-
}
|
|
2661
|
-
return { textures: newMap };
|
|
2662
|
-
});
|
|
2663
|
-
};
|
|
2664
|
-
const remove = (key) => {
|
|
2665
|
-
set((state) => {
|
|
2666
|
-
const newMap = new Map(state.textures);
|
|
2667
|
-
newMap.delete(key);
|
|
2668
|
-
return { textures: newMap };
|
|
2669
|
-
});
|
|
2670
|
-
};
|
|
2671
|
-
const removeMultiple = (keys) => {
|
|
2672
|
-
set((state) => {
|
|
2673
|
-
const newMap = new Map(state.textures);
|
|
2674
|
-
for (const key of keys) newMap.delete(key);
|
|
2675
|
-
return { textures: newMap };
|
|
2676
|
-
});
|
|
2677
|
-
};
|
|
2678
|
-
const dispose = (key) => {
|
|
2679
|
-
const entry = getState().textures.get(key);
|
|
2680
|
-
if (entry) {
|
|
2681
|
-
const tex = getTextureValue(entry);
|
|
2682
|
-
tex?.dispose();
|
|
2683
|
-
}
|
|
2684
|
-
remove(key);
|
|
2685
|
-
};
|
|
2686
|
-
const disposeMultiple = (keys) => {
|
|
2687
|
-
const textures = getState().textures;
|
|
2688
|
-
for (const key of keys) {
|
|
2689
|
-
const entry = textures.get(key);
|
|
2690
|
-
if (entry) {
|
|
2691
|
-
const tex = getTextureValue(entry);
|
|
2692
|
-
tex?.dispose();
|
|
2693
|
-
}
|
|
2694
|
-
}
|
|
2695
|
-
removeMultiple(keys);
|
|
2696
|
-
};
|
|
2697
|
-
const disposeAll = () => {
|
|
2698
|
-
const textures = getState().textures;
|
|
2699
|
-
for (const entry of textures.values()) {
|
|
2700
|
-
const tex = getTextureValue(entry);
|
|
2701
|
-
tex?.dispose();
|
|
2702
|
-
}
|
|
2703
|
-
set({ textures: /* @__PURE__ */ new Map() });
|
|
2704
|
-
};
|
|
2253
|
+
const setState = store.setState;
|
|
2254
|
+
const getOne = (key) => getState().textures.get(key);
|
|
2705
2255
|
return {
|
|
2706
|
-
|
|
2707
|
-
get textures() {
|
|
2256
|
+
get all() {
|
|
2708
2257
|
return getState().textures;
|
|
2709
2258
|
},
|
|
2710
|
-
|
|
2711
|
-
|
|
2259
|
+
get(input) {
|
|
2260
|
+
if (typeof input === "string") return getOne(input);
|
|
2261
|
+
if (Array.isArray(input)) return input.map(getOne);
|
|
2262
|
+
const out = {};
|
|
2263
|
+
for (const name in input) out[name] = getOne(input[name]);
|
|
2264
|
+
return out;
|
|
2265
|
+
},
|
|
2712
2266
|
has: (key) => getState().textures.has(key),
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2267
|
+
add(keyOrRecord, texture) {
|
|
2268
|
+
setState((state) => {
|
|
2269
|
+
const textures = new Map(state.textures);
|
|
2270
|
+
if (typeof keyOrRecord === "string") {
|
|
2271
|
+
textures.set(keyOrRecord, texture);
|
|
2272
|
+
} else {
|
|
2273
|
+
for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
|
|
2274
|
+
}
|
|
2275
|
+
return { textures };
|
|
2276
|
+
});
|
|
2277
|
+
},
|
|
2278
|
+
dispose(key, options) {
|
|
2279
|
+
const state = getState();
|
|
2280
|
+
const refs = state._textureRefs.get(key) ?? 0;
|
|
2281
|
+
if (refs > 0 && !options?.force) {
|
|
2282
|
+
console.warn(
|
|
2283
|
+
`[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
|
|
2284
|
+
);
|
|
2285
|
+
return false;
|
|
2286
|
+
}
|
|
2287
|
+
state.textures.get(key)?.dispose();
|
|
2288
|
+
setState((s) => {
|
|
2289
|
+
const textures = new Map(s.textures);
|
|
2290
|
+
textures.delete(key);
|
|
2291
|
+
const nextRefs = new Map(s._textureRefs);
|
|
2292
|
+
nextRefs.delete(key);
|
|
2293
|
+
return { textures, _textureRefs: nextRefs };
|
|
2294
|
+
});
|
|
2295
|
+
return true;
|
|
2296
|
+
},
|
|
2297
|
+
disposeAll() {
|
|
2298
|
+
for (const texture of getState().textures.values()) texture.dispose();
|
|
2299
|
+
setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
|
|
2300
|
+
}
|
|
2723
2301
|
};
|
|
2724
2302
|
}, [store]);
|
|
2303
|
+
const subscribe = selector ? () => selector(registry) : (state) => state.textures;
|
|
2304
|
+
const selected = useThree(subscribe);
|
|
2305
|
+
return selector ? selected : registry;
|
|
2725
2306
|
}
|
|
2726
2307
|
|
|
2727
|
-
function useRenderTarget(
|
|
2308
|
+
function useRenderTarget(widthOrOptions, heightOrOptions, options) {
|
|
2728
2309
|
const isLegacy = useThree((s) => s.isLegacy);
|
|
2729
2310
|
const size = useThree((s) => s.size);
|
|
2311
|
+
let width;
|
|
2312
|
+
let height;
|
|
2313
|
+
let opts;
|
|
2314
|
+
if (typeof widthOrOptions === "object") {
|
|
2315
|
+
opts = widthOrOptions;
|
|
2316
|
+
} else if (typeof widthOrOptions === "number") {
|
|
2317
|
+
width = widthOrOptions;
|
|
2318
|
+
if (typeof heightOrOptions === "object") {
|
|
2319
|
+
height = widthOrOptions;
|
|
2320
|
+
opts = heightOrOptions;
|
|
2321
|
+
} else if (typeof heightOrOptions === "number") {
|
|
2322
|
+
height = heightOrOptions;
|
|
2323
|
+
opts = options;
|
|
2324
|
+
} else {
|
|
2325
|
+
height = widthOrOptions;
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2730
2328
|
return useMemo(() => {
|
|
2731
2329
|
const w = width ?? size.width;
|
|
2732
2330
|
const h = height ?? size.height;
|
|
2733
|
-
return new WebGLRenderTarget(w, h,
|
|
2734
|
-
}, [width, height, size.width, size.height,
|
|
2331
|
+
return new WebGLRenderTarget(w, h, opts);
|
|
2332
|
+
}, [width, height, size.width, size.height, opts, isLegacy]);
|
|
2735
2333
|
}
|
|
2736
2334
|
|
|
2737
2335
|
function useStore() {
|
|
@@ -2781,7 +2379,7 @@ function addTail(callback) {
|
|
|
2781
2379
|
function invalidate(state, frames = 1, stackFrames = false) {
|
|
2782
2380
|
getScheduler().invalidate(frames, stackFrames);
|
|
2783
2381
|
}
|
|
2784
|
-
function advance(timestamp
|
|
2382
|
+
function advance(timestamp) {
|
|
2785
2383
|
getScheduler().step(timestamp);
|
|
2786
2384
|
}
|
|
2787
2385
|
|
|
@@ -14235,6 +13833,7 @@ function swapInstances() {
|
|
|
14235
13833
|
instance.object = instance.props.object ?? new target(...instance.props.args ?? []);
|
|
14236
13834
|
instance.object.__r3f = instance;
|
|
14237
13835
|
setFiberRef(fiber, instance.object);
|
|
13836
|
+
delete instance.appliedOnce;
|
|
14238
13837
|
applyProps(instance.object, instance.props);
|
|
14239
13838
|
if (instance.props.attach) {
|
|
14240
13839
|
attach(parent, instance);
|
|
@@ -14308,8 +13907,22 @@ const reconciler = /* @__PURE__ */ createReconciler({
|
|
|
14308
13907
|
const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
|
|
14309
13908
|
if (isTailSibling) swapInstances();
|
|
14310
13909
|
},
|
|
14311
|
-
finalizeInitialChildren: () =>
|
|
14312
|
-
|
|
13910
|
+
finalizeInitialChildren: (instance) => {
|
|
13911
|
+
for (const prop in instance.props) {
|
|
13912
|
+
if (isFromRef(instance.props[prop])) return true;
|
|
13913
|
+
}
|
|
13914
|
+
return false;
|
|
13915
|
+
},
|
|
13916
|
+
commitMount(instance) {
|
|
13917
|
+
const resolved = {};
|
|
13918
|
+
for (const prop in instance.props) {
|
|
13919
|
+
const value = instance.props[prop];
|
|
13920
|
+
if (isFromRef(value)) {
|
|
13921
|
+
const ref = value[FROM_REF];
|
|
13922
|
+
if (ref.current != null) resolved[prop] = ref.current;
|
|
13923
|
+
}
|
|
13924
|
+
}
|
|
13925
|
+
if (Object.keys(resolved).length) applyProps(instance.object, resolved);
|
|
14313
13926
|
},
|
|
14314
13927
|
getPublicInstance: (instance) => instance?.object,
|
|
14315
13928
|
prepareForCommit: () => null,
|
|
@@ -14530,6 +14143,9 @@ function createRoot(canvas) {
|
|
|
14530
14143
|
let resolve;
|
|
14531
14144
|
pending = new Promise((_resolve) => resolve = _resolve);
|
|
14532
14145
|
const {
|
|
14146
|
+
id: canvasId,
|
|
14147
|
+
primaryCanvas,
|
|
14148
|
+
scheduler: schedulerConfig,
|
|
14533
14149
|
gl: glConfig,
|
|
14534
14150
|
renderer: rendererConfig,
|
|
14535
14151
|
size: propsSize,
|
|
@@ -14537,10 +14153,6 @@ function createRoot(canvas) {
|
|
|
14537
14153
|
events,
|
|
14538
14154
|
onCreated: onCreatedCallback,
|
|
14539
14155
|
shadows = false,
|
|
14540
|
-
linear = false,
|
|
14541
|
-
flat = false,
|
|
14542
|
-
textureColorSpace = SRGBColorSpace,
|
|
14543
|
-
legacy = false,
|
|
14544
14156
|
orthographic = false,
|
|
14545
14157
|
frameloop = "always",
|
|
14546
14158
|
dpr = [1, 2],
|
|
@@ -14552,8 +14164,10 @@ function createRoot(canvas) {
|
|
|
14552
14164
|
onDropMissed,
|
|
14553
14165
|
autoUpdateFrustum = true,
|
|
14554
14166
|
occlusion = false,
|
|
14555
|
-
_sizeProps
|
|
14167
|
+
_sizeProps,
|
|
14168
|
+
forceEven
|
|
14556
14169
|
} = props;
|
|
14170
|
+
const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
|
|
14557
14171
|
const state = store.getState();
|
|
14558
14172
|
const defaultGLProps = {
|
|
14559
14173
|
canvas,
|
|
@@ -14566,15 +14180,25 @@ function createRoot(canvas) {
|
|
|
14566
14180
|
"WebGPURenderer (renderer prop) is not available in this build. Use @react-three/fiber or @react-three/fiber/webgpu instead."
|
|
14567
14181
|
);
|
|
14568
14182
|
}
|
|
14569
|
-
(state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
|
|
14183
|
+
const wantsGL = (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
|
|
14570
14184
|
if (glConfig && rendererConfig) {
|
|
14571
14185
|
throw new Error("Cannot use both gl and renderer props at the same time");
|
|
14572
14186
|
}
|
|
14573
14187
|
let renderer = state.internal.actualRenderer;
|
|
14188
|
+
if (primaryCanvas && !R3F_BUILD_WEBGPU) {
|
|
14189
|
+
throw new Error(
|
|
14190
|
+
"The `primaryCanvas` prop for multi-canvas rendering is only available with WebGPU. Use @react-three/fiber/webgpu instead."
|
|
14191
|
+
);
|
|
14192
|
+
}
|
|
14193
|
+
if (primaryCanvas && wantsGL) {
|
|
14194
|
+
throw new Error(
|
|
14195
|
+
"The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
|
|
14196
|
+
);
|
|
14197
|
+
}
|
|
14574
14198
|
if (!state.internal.actualRenderer) {
|
|
14575
14199
|
renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
|
|
14576
14200
|
state.internal.actualRenderer = renderer;
|
|
14577
|
-
state.set({ isLegacy: true, gl: renderer, renderer });
|
|
14201
|
+
state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
|
|
14578
14202
|
}
|
|
14579
14203
|
let raycaster = state.raycaster;
|
|
14580
14204
|
if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
|
|
@@ -14583,6 +14207,7 @@ function createRoot(canvas) {
|
|
|
14583
14207
|
if (!is.equ(params, raycaster.params, shallowLoose)) {
|
|
14584
14208
|
applyProps(raycaster, { params: { ...raycaster.params, ...params } });
|
|
14585
14209
|
}
|
|
14210
|
+
let tempCamera = state.camera;
|
|
14586
14211
|
if (!state.camera || state.camera === lastCamera && !is.equ(lastCamera, cameraOptions, shallowLoose)) {
|
|
14587
14212
|
lastCamera = cameraOptions;
|
|
14588
14213
|
const isCamera = cameraOptions?.isCamera;
|
|
@@ -14602,6 +14227,7 @@ function createRoot(canvas) {
|
|
|
14602
14227
|
if (!state.camera && !cameraOptions?.rotation) camera.lookAt(0, 0, 0);
|
|
14603
14228
|
}
|
|
14604
14229
|
state.set({ camera });
|
|
14230
|
+
tempCamera = camera;
|
|
14605
14231
|
raycaster.camera = camera;
|
|
14606
14232
|
}
|
|
14607
14233
|
if (!state.scene) {
|
|
@@ -14619,7 +14245,7 @@ function createRoot(canvas) {
|
|
|
14619
14245
|
rootScene: scene,
|
|
14620
14246
|
internal: { ...prev.internal, container: scene }
|
|
14621
14247
|
}));
|
|
14622
|
-
const camera =
|
|
14248
|
+
const camera = tempCamera;
|
|
14623
14249
|
if (camera && !camera.parent) scene.add(camera);
|
|
14624
14250
|
}
|
|
14625
14251
|
if (events && !state.events.handlers) {
|
|
@@ -14636,6 +14262,9 @@ function createRoot(canvas) {
|
|
|
14636
14262
|
if (_sizeProps !== void 0) {
|
|
14637
14263
|
state.set({ _sizeProps });
|
|
14638
14264
|
}
|
|
14265
|
+
if (forceEven !== void 0 && state.internal.forceEven !== forceEven) {
|
|
14266
|
+
state.set((prev) => ({ internal: { ...prev.internal, forceEven } }));
|
|
14267
|
+
}
|
|
14639
14268
|
const size = computeInitialSize(canvas, propsSize);
|
|
14640
14269
|
if (!state._sizeImperative && !is.equ(size, state.size, shallowLoose)) {
|
|
14641
14270
|
const wasImperative = state._sizeImperative;
|
|
@@ -14662,10 +14291,10 @@ function createRoot(canvas) {
|
|
|
14662
14291
|
lastConfiguredProps.performance = performance;
|
|
14663
14292
|
}
|
|
14664
14293
|
if (!state.xr) {
|
|
14665
|
-
const handleXRFrame = (timestamp,
|
|
14294
|
+
const handleXRFrame = (timestamp, _frame) => {
|
|
14666
14295
|
const state2 = store.getState();
|
|
14667
14296
|
if (state2.frameloop === "never") return;
|
|
14668
|
-
advance(timestamp
|
|
14297
|
+
advance(timestamp);
|
|
14669
14298
|
};
|
|
14670
14299
|
const actualRenderer = state.internal.actualRenderer;
|
|
14671
14300
|
const handleSessionChange = () => {
|
|
@@ -14677,16 +14306,16 @@ function createRoot(canvas) {
|
|
|
14677
14306
|
};
|
|
14678
14307
|
const xr = {
|
|
14679
14308
|
connect() {
|
|
14680
|
-
const { gl, renderer: renderer2
|
|
14681
|
-
const
|
|
14682
|
-
|
|
14683
|
-
|
|
14309
|
+
const { gl, renderer: renderer2 } = store.getState();
|
|
14310
|
+
const xrManager = (renderer2 || gl).xr;
|
|
14311
|
+
xrManager.addEventListener("sessionstart", handleSessionChange);
|
|
14312
|
+
xrManager.addEventListener("sessionend", handleSessionChange);
|
|
14684
14313
|
},
|
|
14685
14314
|
disconnect() {
|
|
14686
|
-
const { gl, renderer: renderer2
|
|
14687
|
-
const
|
|
14688
|
-
|
|
14689
|
-
|
|
14315
|
+
const { gl, renderer: renderer2 } = store.getState();
|
|
14316
|
+
const xrManager = (renderer2 || gl).xr;
|
|
14317
|
+
xrManager.removeEventListener("sessionstart", handleSessionChange);
|
|
14318
|
+
xrManager.removeEventListener("sessionend", handleSessionChange);
|
|
14690
14319
|
}
|
|
14691
14320
|
};
|
|
14692
14321
|
if (typeof renderer.xr?.addEventListener === "function") xr.connect();
|
|
@@ -14698,15 +14327,22 @@ function createRoot(canvas) {
|
|
|
14698
14327
|
const oldType = renderer.shadowMap.type;
|
|
14699
14328
|
renderer.shadowMap.enabled = !!shadows;
|
|
14700
14329
|
if (is.boo(shadows)) {
|
|
14701
|
-
renderer.shadowMap.type =
|
|
14330
|
+
renderer.shadowMap.type = PCFShadowMap;
|
|
14702
14331
|
} else if (is.str(shadows)) {
|
|
14332
|
+
if (shadows === "soft") {
|
|
14333
|
+
notifyDepreciated({
|
|
14334
|
+
heading: 'shadows="soft" is deprecated',
|
|
14335
|
+
body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
|
|
14336
|
+
link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
|
|
14337
|
+
});
|
|
14338
|
+
}
|
|
14703
14339
|
const types = {
|
|
14704
14340
|
basic: BasicShadowMap,
|
|
14705
14341
|
percentage: PCFShadowMap,
|
|
14706
|
-
soft:
|
|
14342
|
+
soft: PCFShadowMap,
|
|
14707
14343
|
variance: VSMShadowMap
|
|
14708
14344
|
};
|
|
14709
|
-
renderer.shadowMap.type = types[shadows] ??
|
|
14345
|
+
renderer.shadowMap.type = types[shadows] ?? PCFShadowMap;
|
|
14710
14346
|
} else if (is.obj(shadows)) {
|
|
14711
14347
|
Object.assign(renderer.shadowMap, shadows);
|
|
14712
14348
|
}
|
|
@@ -14714,47 +14350,69 @@ function createRoot(canvas) {
|
|
|
14714
14350
|
renderer.shadowMap.needsUpdate = true;
|
|
14715
14351
|
}
|
|
14716
14352
|
}
|
|
14717
|
-
{
|
|
14718
|
-
|
|
14719
|
-
|
|
14720
|
-
const flatChanged = flat !== lastConfiguredProps.flat;
|
|
14721
|
-
if (legacyChanged) {
|
|
14722
|
-
ColorManagement.enabled = !legacy;
|
|
14723
|
-
lastConfiguredProps.legacy = legacy;
|
|
14724
|
-
}
|
|
14725
|
-
if (!configured || linearChanged) {
|
|
14726
|
-
renderer.outputColorSpace = linear ? LinearSRGBColorSpace : SRGBColorSpace;
|
|
14727
|
-
lastConfiguredProps.linear = linear;
|
|
14728
|
-
}
|
|
14729
|
-
if (!configured || flatChanged) {
|
|
14730
|
-
renderer.toneMapping = flat ? NoToneMapping : ACESFilmicToneMapping;
|
|
14731
|
-
lastConfiguredProps.flat = flat;
|
|
14732
|
-
}
|
|
14733
|
-
if (legacyChanged && state.legacy !== legacy) state.set(() => ({ legacy }));
|
|
14734
|
-
if (linearChanged && state.linear !== linear) state.set(() => ({ linear }));
|
|
14735
|
-
if (flatChanged && state.flat !== flat) state.set(() => ({ flat }));
|
|
14353
|
+
if (!configured) {
|
|
14354
|
+
renderer.outputColorSpace = SRGBColorSpace;
|
|
14355
|
+
renderer.toneMapping = ACESFilmicToneMapping;
|
|
14736
14356
|
}
|
|
14737
14357
|
if (textureColorSpace !== lastConfiguredProps.textureColorSpace) {
|
|
14738
14358
|
if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
|
|
14739
14359
|
lastConfiguredProps.textureColorSpace = textureColorSpace;
|
|
14740
14360
|
}
|
|
14361
|
+
const r3fProps = ["textureColorSpace"];
|
|
14362
|
+
const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
|
|
14363
|
+
const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
|
|
14741
14364
|
if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
|
|
14742
|
-
|
|
14365
|
+
const glProps = {};
|
|
14366
|
+
for (const key in glConfig) {
|
|
14367
|
+
if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
|
|
14368
|
+
}
|
|
14369
|
+
applyProps(renderer, glProps);
|
|
14743
14370
|
}
|
|
14744
14371
|
if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
|
|
14745
14372
|
const currentRenderer = state.renderer;
|
|
14746
14373
|
if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
|
|
14747
|
-
|
|
14374
|
+
const rendererProps = {};
|
|
14375
|
+
for (const key in rendererConfig) {
|
|
14376
|
+
if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
|
|
14377
|
+
}
|
|
14378
|
+
applyProps(currentRenderer, rendererProps);
|
|
14748
14379
|
}
|
|
14749
14380
|
}
|
|
14750
14381
|
const scheduler = getScheduler();
|
|
14751
14382
|
const rootId = state.internal.rootId;
|
|
14752
14383
|
if (!rootId) {
|
|
14753
|
-
const newRootId = scheduler.generateRootId();
|
|
14384
|
+
const newRootId = canvasId || scheduler.generateRootId();
|
|
14754
14385
|
const unregisterRoot = scheduler.registerRoot(newRootId, {
|
|
14755
14386
|
getState: () => store.getState(),
|
|
14756
14387
|
onError: (err) => store.getState().setError(err)
|
|
14757
14388
|
});
|
|
14389
|
+
const unregisterCanvasTarget = scheduler.register(
|
|
14390
|
+
() => {
|
|
14391
|
+
const state2 = store.getState();
|
|
14392
|
+
if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
|
|
14393
|
+
const renderer2 = state2.internal.actualRenderer;
|
|
14394
|
+
renderer2.setCanvasTarget(state2.internal.canvasTarget);
|
|
14395
|
+
}
|
|
14396
|
+
},
|
|
14397
|
+
{
|
|
14398
|
+
id: `${newRootId}_canvasTarget`,
|
|
14399
|
+
rootId: newRootId,
|
|
14400
|
+
phase: "start",
|
|
14401
|
+
system: true
|
|
14402
|
+
}
|
|
14403
|
+
);
|
|
14404
|
+
const unregisterEventsFlush = scheduler.register(
|
|
14405
|
+
() => {
|
|
14406
|
+
const state2 = store.getState();
|
|
14407
|
+
state2.events.flush?.();
|
|
14408
|
+
},
|
|
14409
|
+
{
|
|
14410
|
+
id: `${newRootId}_events`,
|
|
14411
|
+
rootId: newRootId,
|
|
14412
|
+
phase: "input",
|
|
14413
|
+
system: true
|
|
14414
|
+
}
|
|
14415
|
+
);
|
|
14758
14416
|
const unregisterFrustum = scheduler.register(
|
|
14759
14417
|
() => {
|
|
14760
14418
|
const state2 = store.getState();
|
|
@@ -14765,7 +14423,7 @@ function createRoot(canvas) {
|
|
|
14765
14423
|
{
|
|
14766
14424
|
id: `${newRootId}_frustum`,
|
|
14767
14425
|
rootId: newRootId,
|
|
14768
|
-
|
|
14426
|
+
before: "render",
|
|
14769
14427
|
system: true
|
|
14770
14428
|
}
|
|
14771
14429
|
);
|
|
@@ -14777,7 +14435,7 @@ function createRoot(canvas) {
|
|
|
14777
14435
|
{
|
|
14778
14436
|
id: `${newRootId}_visibility`,
|
|
14779
14437
|
rootId: newRootId,
|
|
14780
|
-
|
|
14438
|
+
before: "render",
|
|
14781
14439
|
system: true,
|
|
14782
14440
|
after: `${newRootId}_frustum`
|
|
14783
14441
|
}
|
|
@@ -14789,18 +14447,22 @@ function createRoot(canvas) {
|
|
|
14789
14447
|
const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
|
|
14790
14448
|
if (userHandlesRender || state2.internal.priority) return;
|
|
14791
14449
|
try {
|
|
14792
|
-
if (state2.
|
|
14450
|
+
if (state2.renderPipeline?.render) state2.renderPipeline.render();
|
|
14793
14451
|
else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
|
|
14794
14452
|
} catch (error) {
|
|
14795
14453
|
state2.setError(error instanceof Error ? error : new Error(String(error)));
|
|
14796
14454
|
}
|
|
14797
14455
|
},
|
|
14798
14456
|
{
|
|
14799
|
-
|
|
14457
|
+
// Use canvas ID directly as job ID if available, otherwise use generated rootId
|
|
14458
|
+
id: canvasId || `${newRootId}_render`,
|
|
14800
14459
|
rootId: newRootId,
|
|
14801
14460
|
phase: "render",
|
|
14802
|
-
system: true
|
|
14461
|
+
system: true,
|
|
14803
14462
|
// Internal flag: this is a system job, not user-controlled
|
|
14463
|
+
// Apply scheduler config for render ordering and rate limiting
|
|
14464
|
+
...schedulerConfig?.after && { after: schedulerConfig.after },
|
|
14465
|
+
...schedulerConfig?.fps && { fps: schedulerConfig.fps }
|
|
14804
14466
|
}
|
|
14805
14467
|
);
|
|
14806
14468
|
state.set((state2) => ({
|
|
@@ -14809,6 +14471,8 @@ function createRoot(canvas) {
|
|
|
14809
14471
|
rootId: newRootId,
|
|
14810
14472
|
unregisterRoot: () => {
|
|
14811
14473
|
unregisterRoot();
|
|
14474
|
+
unregisterCanvasTarget();
|
|
14475
|
+
unregisterEventsFlush();
|
|
14812
14476
|
unregisterFrustum();
|
|
14813
14477
|
unregisterVisibility();
|
|
14814
14478
|
unregisterRender();
|
|
@@ -14867,15 +14531,24 @@ function unmountComponentAtNode(canvas, callback) {
|
|
|
14867
14531
|
const renderer = state.internal.actualRenderer;
|
|
14868
14532
|
const unregisterRoot = state.internal.unregisterRoot;
|
|
14869
14533
|
if (unregisterRoot) unregisterRoot();
|
|
14534
|
+
const unregisterPrimary = state.internal.unregisterPrimary;
|
|
14535
|
+
if (unregisterPrimary) unregisterPrimary();
|
|
14536
|
+
const canvasTarget = state.internal.canvasTarget;
|
|
14537
|
+
if (canvasTarget?.dispose) canvasTarget.dispose();
|
|
14870
14538
|
state.events.disconnect?.();
|
|
14871
14539
|
cleanupHelperGroup(root.store);
|
|
14872
|
-
renderer
|
|
14873
|
-
|
|
14874
|
-
|
|
14540
|
+
if (state.isLegacy && renderer) {
|
|
14541
|
+
;
|
|
14542
|
+
renderer.renderLists?.dispose?.();
|
|
14543
|
+
renderer.forceContextLoss?.();
|
|
14544
|
+
}
|
|
14545
|
+
if (!state.internal.isSecondary) {
|
|
14546
|
+
if (renderer?.xr) state.xr.disconnect();
|
|
14547
|
+
}
|
|
14875
14548
|
dispose(state.scene);
|
|
14876
14549
|
_roots.delete(canvas);
|
|
14877
14550
|
if (callback) callback(canvas);
|
|
14878
|
-
} catch
|
|
14551
|
+
} catch {
|
|
14879
14552
|
}
|
|
14880
14553
|
}, 500);
|
|
14881
14554
|
}
|
|
@@ -14883,36 +14556,34 @@ function unmountComponentAtNode(canvas, callback) {
|
|
|
14883
14556
|
}
|
|
14884
14557
|
}
|
|
14885
14558
|
function createPortal(children, container, state) {
|
|
14886
|
-
return /* @__PURE__ */ jsx(
|
|
14559
|
+
return /* @__PURE__ */ jsx(Portal, { children, container, state });
|
|
14887
14560
|
}
|
|
14888
|
-
function
|
|
14561
|
+
function Portal({ children, container, state }) {
|
|
14889
14562
|
const isRef = useCallback((obj) => obj && "current" in obj, []);
|
|
14890
|
-
const [resolvedContainer,
|
|
14563
|
+
const [resolvedContainer, _setResolvedContainer] = useState(() => {
|
|
14891
14564
|
if (isRef(container)) return container.current ?? null;
|
|
14892
14565
|
return container;
|
|
14893
14566
|
});
|
|
14567
|
+
const setResolvedContainer = useCallback(
|
|
14568
|
+
(newContainer) => {
|
|
14569
|
+
if (!newContainer || newContainer === resolvedContainer) return;
|
|
14570
|
+
_setResolvedContainer(isRef(newContainer) ? newContainer.current : newContainer);
|
|
14571
|
+
},
|
|
14572
|
+
[resolvedContainer, _setResolvedContainer, isRef]
|
|
14573
|
+
);
|
|
14894
14574
|
useMemo(() => {
|
|
14895
|
-
if (isRef(container)) {
|
|
14896
|
-
|
|
14897
|
-
|
|
14898
|
-
|
|
14899
|
-
const updated = container.current;
|
|
14900
|
-
if (updated && updated !== resolvedContainer) {
|
|
14901
|
-
setResolvedContainer(updated);
|
|
14902
|
-
}
|
|
14903
|
-
});
|
|
14904
|
-
} else if (current !== resolvedContainer) {
|
|
14905
|
-
setResolvedContainer(current);
|
|
14906
|
-
}
|
|
14907
|
-
} else if (container !== resolvedContainer) {
|
|
14908
|
-
setResolvedContainer(container);
|
|
14575
|
+
if (isRef(container) && !container.current) {
|
|
14576
|
+
return queueMicrotask(() => {
|
|
14577
|
+
setResolvedContainer(container.current);
|
|
14578
|
+
});
|
|
14909
14579
|
}
|
|
14910
|
-
|
|
14580
|
+
setResolvedContainer(container);
|
|
14581
|
+
}, [container, isRef, setResolvedContainer]);
|
|
14911
14582
|
if (!resolvedContainer) return /* @__PURE__ */ jsx(Fragment, {});
|
|
14912
14583
|
const portalKey = resolvedContainer.uuid ?? `portal-${resolvedContainer.id ?? "unknown"}`;
|
|
14913
|
-
return /* @__PURE__ */ jsx(
|
|
14584
|
+
return /* @__PURE__ */ jsx(PortalInner, { children, container: resolvedContainer, state }, portalKey);
|
|
14914
14585
|
}
|
|
14915
|
-
function
|
|
14586
|
+
function PortalInner({ state = {}, children, container }) {
|
|
14916
14587
|
const { events, size, injectScene = true, ...rest } = state;
|
|
14917
14588
|
const previousRoot = useStore();
|
|
14918
14589
|
const [raycaster] = useState(() => new Raycaster());
|
|
@@ -14933,11 +14604,12 @@ function Portal({ state = {}, children, container }) {
|
|
|
14933
14604
|
};
|
|
14934
14605
|
}, [portalScene, container, injectScene]);
|
|
14935
14606
|
const inject = useMutableCallback((rootState, injectState) => {
|
|
14607
|
+
const resolvedSize = { ...rootState.size, ...injectState.size, ...size };
|
|
14936
14608
|
let viewport = void 0;
|
|
14937
|
-
if (injectState.camera && size) {
|
|
14609
|
+
if (injectState.camera && (size || injectState.size)) {
|
|
14938
14610
|
const camera = injectState.camera;
|
|
14939
|
-
viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(),
|
|
14940
|
-
if (camera !== rootState.camera) updateCamera(camera,
|
|
14611
|
+
viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
|
|
14612
|
+
if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
|
|
14941
14613
|
}
|
|
14942
14614
|
return {
|
|
14943
14615
|
// The intersect consists of the previous root state
|
|
@@ -14954,7 +14626,7 @@ function Portal({ state = {}, children, container }) {
|
|
|
14954
14626
|
previousRoot,
|
|
14955
14627
|
// Events, size and viewport can be overridden by the inject layer
|
|
14956
14628
|
events: { ...rootState.events, ...injectState.events, ...events },
|
|
14957
|
-
size:
|
|
14629
|
+
size: resolvedSize,
|
|
14958
14630
|
viewport: { ...rootState.viewport, ...viewport },
|
|
14959
14631
|
// Layers are allowed to override events
|
|
14960
14632
|
setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
|
|
@@ -14966,9 +14638,13 @@ function Portal({ state = {}, children, container }) {
|
|
|
14966
14638
|
const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
|
|
14967
14639
|
const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
|
|
14968
14640
|
onMutate(previousRoot.getState());
|
|
14969
|
-
previousRoot.subscribe(onMutate);
|
|
14970
14641
|
return store;
|
|
14971
14642
|
}, [previousRoot, container]);
|
|
14643
|
+
useIsomorphicLayoutEffect(() => {
|
|
14644
|
+
const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
|
|
14645
|
+
const unsubscribe = previousRoot.subscribe(onMutate);
|
|
14646
|
+
return unsubscribe;
|
|
14647
|
+
}, [previousRoot, usePortalStore]);
|
|
14972
14648
|
return (
|
|
14973
14649
|
// @ts-ignore, reconciler types are not maintained
|
|
14974
14650
|
/* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
|
|
@@ -14982,21 +14658,59 @@ function flushSync(fn) {
|
|
|
14982
14658
|
return reconciler.flushSyncFromReconciler(fn);
|
|
14983
14659
|
}
|
|
14984
14660
|
|
|
14661
|
+
function parseBackground(background) {
|
|
14662
|
+
if (!background) return null;
|
|
14663
|
+
if (typeof background === "object" && !background.isColor) {
|
|
14664
|
+
const { backgroundMap, envMap, files, preset, ...rest } = background;
|
|
14665
|
+
return {
|
|
14666
|
+
...rest,
|
|
14667
|
+
preset,
|
|
14668
|
+
files: envMap || files,
|
|
14669
|
+
backgroundFiles: backgroundMap,
|
|
14670
|
+
background: true
|
|
14671
|
+
};
|
|
14672
|
+
}
|
|
14673
|
+
if (typeof background === "number") {
|
|
14674
|
+
return { color: background, background: true };
|
|
14675
|
+
}
|
|
14676
|
+
if (typeof background === "string") {
|
|
14677
|
+
if (background in presetsObj) {
|
|
14678
|
+
return { preset: background, background: true };
|
|
14679
|
+
}
|
|
14680
|
+
if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
|
|
14681
|
+
return { files: background, background: true };
|
|
14682
|
+
}
|
|
14683
|
+
return { color: background, background: true };
|
|
14684
|
+
}
|
|
14685
|
+
if (background.isColor) {
|
|
14686
|
+
return { color: background, background: true };
|
|
14687
|
+
}
|
|
14688
|
+
return null;
|
|
14689
|
+
}
|
|
14690
|
+
|
|
14691
|
+
function clearHmrCaches(store) {
|
|
14692
|
+
store.setState((state) => ({
|
|
14693
|
+
nodes: {},
|
|
14694
|
+
uniforms: {},
|
|
14695
|
+
buffers: {},
|
|
14696
|
+
gpuStorage: {},
|
|
14697
|
+
_hmrVersion: state._hmrVersion + 1
|
|
14698
|
+
}));
|
|
14699
|
+
}
|
|
14700
|
+
|
|
14985
14701
|
function CanvasImpl({
|
|
14986
14702
|
ref,
|
|
14987
14703
|
children,
|
|
14988
14704
|
fallback,
|
|
14989
14705
|
resize,
|
|
14990
14706
|
style,
|
|
14707
|
+
id,
|
|
14991
14708
|
gl,
|
|
14992
|
-
renderer,
|
|
14709
|
+
renderer: rendererProp,
|
|
14993
14710
|
events = createPointerEvents,
|
|
14994
14711
|
eventSource,
|
|
14995
14712
|
eventPrefix,
|
|
14996
14713
|
shadows,
|
|
14997
|
-
linear,
|
|
14998
|
-
flat,
|
|
14999
|
-
legacy,
|
|
15000
14714
|
orthographic,
|
|
15001
14715
|
frameloop,
|
|
15002
14716
|
dpr,
|
|
@@ -15004,6 +14718,8 @@ function CanvasImpl({
|
|
|
15004
14718
|
raycaster,
|
|
15005
14719
|
camera,
|
|
15006
14720
|
scene,
|
|
14721
|
+
autoUpdateFrustum,
|
|
14722
|
+
occlusion,
|
|
15007
14723
|
onPointerMissed,
|
|
15008
14724
|
onDragOverMissed,
|
|
15009
14725
|
onDropMissed,
|
|
@@ -15011,10 +14727,25 @@ function CanvasImpl({
|
|
|
15011
14727
|
hmr,
|
|
15012
14728
|
width,
|
|
15013
14729
|
height,
|
|
14730
|
+
background,
|
|
14731
|
+
forceEven,
|
|
15014
14732
|
...props
|
|
15015
14733
|
}) {
|
|
14734
|
+
const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
|
|
14735
|
+
let primaryCanvas;
|
|
14736
|
+
let scheduler;
|
|
14737
|
+
let renderer;
|
|
14738
|
+
if (isRendererConfig) {
|
|
14739
|
+
const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
|
|
14740
|
+
primaryCanvas = pc;
|
|
14741
|
+
scheduler = sc;
|
|
14742
|
+
renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
|
|
14743
|
+
} else {
|
|
14744
|
+
renderer = rendererProp;
|
|
14745
|
+
}
|
|
15016
14746
|
React.useMemo(() => extend(THREE), []);
|
|
15017
14747
|
const Bridge = useBridge();
|
|
14748
|
+
const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
|
|
15018
14749
|
const hasInitialSizeRef = React.useRef(false);
|
|
15019
14750
|
const measureConfig = React.useMemo(() => {
|
|
15020
14751
|
if (!hasInitialSizeRef.current) {
|
|
@@ -15031,15 +14762,20 @@ function CanvasImpl({
|
|
|
15031
14762
|
};
|
|
15032
14763
|
}, [resize, hasInitialSizeRef.current]);
|
|
15033
14764
|
const [containerRef, containerRect] = useMeasure(measureConfig);
|
|
15034
|
-
const effectiveSize = React.useMemo(
|
|
15035
|
-
|
|
15036
|
-
|
|
15037
|
-
|
|
14765
|
+
const effectiveSize = React.useMemo(() => {
|
|
14766
|
+
let w = width ?? containerRect.width;
|
|
14767
|
+
let h = height ?? containerRect.height;
|
|
14768
|
+
if (forceEven) {
|
|
14769
|
+
w = Math.ceil(w / 2) * 2;
|
|
14770
|
+
h = Math.ceil(h / 2) * 2;
|
|
14771
|
+
}
|
|
14772
|
+
return {
|
|
14773
|
+
width: w,
|
|
14774
|
+
height: h,
|
|
15038
14775
|
top: containerRect.top,
|
|
15039
14776
|
left: containerRect.left
|
|
15040
|
-
}
|
|
15041
|
-
|
|
15042
|
-
);
|
|
14777
|
+
};
|
|
14778
|
+
}, [width, height, containerRect, forceEven]);
|
|
15043
14779
|
if (!hasInitialSizeRef.current && effectiveSize.width > 0 && effectiveSize.height > 0) {
|
|
15044
14780
|
hasInitialSizeRef.current = true;
|
|
15045
14781
|
}
|
|
@@ -15079,23 +14815,26 @@ function CanvasImpl({
|
|
|
15079
14815
|
async function run() {
|
|
15080
14816
|
if (!effectActiveRef.current || !root.current) return;
|
|
15081
14817
|
await root.current.configure({
|
|
14818
|
+
id,
|
|
14819
|
+
primaryCanvas,
|
|
14820
|
+
scheduler,
|
|
15082
14821
|
gl,
|
|
15083
14822
|
renderer,
|
|
15084
14823
|
scene,
|
|
15085
14824
|
events,
|
|
15086
14825
|
shadows,
|
|
15087
|
-
linear,
|
|
15088
|
-
flat,
|
|
15089
|
-
legacy,
|
|
15090
14826
|
orthographic,
|
|
15091
14827
|
frameloop,
|
|
15092
14828
|
dpr,
|
|
15093
14829
|
performance,
|
|
15094
14830
|
raycaster,
|
|
15095
14831
|
camera,
|
|
14832
|
+
autoUpdateFrustum,
|
|
14833
|
+
occlusion,
|
|
15096
14834
|
size: effectiveSize,
|
|
15097
14835
|
// Store size props for reset functionality
|
|
15098
14836
|
_sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
|
|
14837
|
+
forceEven,
|
|
15099
14838
|
// Pass mutable reference to onPointerMissed so it's free to update
|
|
15100
14839
|
onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
|
|
15101
14840
|
onDragOverMissed: (...args) => handleDragOverMissed.current?.(...args),
|
|
@@ -15119,7 +14858,10 @@ function CanvasImpl({
|
|
|
15119
14858
|
});
|
|
15120
14859
|
if (!effectActiveRef.current || !root.current) return;
|
|
15121
14860
|
root.current.render(
|
|
15122
|
-
/* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */
|
|
14861
|
+
/* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
|
|
14862
|
+
backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
|
|
14863
|
+
children ?? null
|
|
14864
|
+
] }) }) })
|
|
15123
14865
|
);
|
|
15124
14866
|
}
|
|
15125
14867
|
run();
|
|
@@ -15146,20 +14888,15 @@ function CanvasImpl({
|
|
|
15146
14888
|
const canvas = canvasRef.current;
|
|
15147
14889
|
if (!canvas) return;
|
|
15148
14890
|
const handleHMR = () => {
|
|
15149
|
-
|
|
15150
|
-
|
|
15151
|
-
rootEntry
|
|
15152
|
-
|
|
15153
|
-
uniforms: {},
|
|
15154
|
-
_hmrVersion: state._hmrVersion + 1
|
|
15155
|
-
}));
|
|
15156
|
-
}
|
|
14891
|
+
queueMicrotask(() => {
|
|
14892
|
+
const rootEntry = _roots.get(canvas);
|
|
14893
|
+
if (rootEntry?.store) clearHmrCaches(rootEntry.store);
|
|
14894
|
+
});
|
|
15157
14895
|
};
|
|
15158
14896
|
if (typeof import.meta !== "undefined" && import.meta.hot) {
|
|
15159
14897
|
const hot = import.meta.hot;
|
|
15160
14898
|
hot.on("vite:afterUpdate", handleHMR);
|
|
15161
|
-
return () => hot.
|
|
15162
|
-
});
|
|
14899
|
+
return () => hot.off?.("vite:afterUpdate", handleHMR);
|
|
15163
14900
|
}
|
|
15164
14901
|
if (typeof module !== "undefined" && module.hot) {
|
|
15165
14902
|
const hot = module.hot;
|
|
@@ -15182,7 +14919,16 @@ function CanvasImpl({
|
|
|
15182
14919
|
...style
|
|
15183
14920
|
},
|
|
15184
14921
|
...props,
|
|
15185
|
-
children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
|
|
14922
|
+
children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
|
|
14923
|
+
"canvas",
|
|
14924
|
+
{
|
|
14925
|
+
ref: canvasRef,
|
|
14926
|
+
id,
|
|
14927
|
+
className: "r3f-canvas",
|
|
14928
|
+
style: { display: "block", width: "100%", height: "100%" },
|
|
14929
|
+
children: fallback
|
|
14930
|
+
}
|
|
14931
|
+
) })
|
|
15186
14932
|
}
|
|
15187
14933
|
);
|
|
15188
14934
|
}
|
|
@@ -15192,4 +14938,4 @@ function Canvas(props) {
|
|
|
15192
14938
|
|
|
15193
14939
|
extend(THREE);
|
|
15194
14940
|
|
|
15195
|
-
export { Block, Canvas, ErrorBoundary, IsObject, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS,
|
|
14941
|
+
export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
|