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