@react-three/fiber 10.0.0-alpha.1 → 10.0.0-canary.0706a92

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/dist/legacy.cjs CHANGED
@@ -5,10 +5,18 @@ const jsxRuntime = require('react/jsx-runtime');
5
5
  const React = require('react');
6
6
  const useMeasure = require('react-use-measure');
7
7
  const itsFine = require('its-fine');
8
+ const fiber = require('@react-three/fiber');
9
+ const GroundedSkybox_js = require('three/examples/jsm/objects/GroundedSkybox.js');
10
+ const HDRLoader_js = require('three/examples/jsm/loaders/HDRLoader.js');
11
+ const EXRLoader_js = require('three/examples/jsm/loaders/EXRLoader.js');
12
+ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js');
13
+ const gainmapJs = require('@monogrid/gainmap-js');
8
14
  const Tb = require('scheduler');
9
15
  const traditional = require('zustand/traditional');
16
+ const scheduler = require('@pmndrs/scheduler');
10
17
  const suspendReact = require('suspend-react');
11
18
 
19
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
20
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
13
21
 
14
22
  function _interopNamespaceCompat(e) {
@@ -65,9 +73,392 @@ const THREE = /*#__PURE__*/_mergeNamespaces({
65
73
  WebGPURenderer: WebGPURenderer
66
74
  }, [three__namespace]);
67
75
 
68
- var __defProp$2 = Object.defineProperty;
69
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
70
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
76
+ const primaryRegistry = /* @__PURE__ */ new Map();
77
+ const pendingSubscribers = /* @__PURE__ */ new Map();
78
+ function registerPrimary(id, renderer, store) {
79
+ if (primaryRegistry.has(id)) {
80
+ console.warn(`Canvas with id="${id}" already registered. Overwriting.`);
81
+ }
82
+ const entry = { renderer, store };
83
+ primaryRegistry.set(id, entry);
84
+ const subscribers = pendingSubscribers.get(id);
85
+ if (subscribers) {
86
+ subscribers.forEach((callback) => callback(entry));
87
+ pendingSubscribers.delete(id);
88
+ }
89
+ return () => {
90
+ const currentEntry = primaryRegistry.get(id);
91
+ if (currentEntry?.renderer === renderer) {
92
+ primaryRegistry.delete(id);
93
+ }
94
+ };
95
+ }
96
+ function getPrimary(id) {
97
+ return primaryRegistry.get(id);
98
+ }
99
+ function waitForPrimary(id, timeout = 5e3) {
100
+ const existing = primaryRegistry.get(id);
101
+ if (existing) {
102
+ return Promise.resolve(existing);
103
+ }
104
+ return new Promise((resolve, reject) => {
105
+ const timeoutId = setTimeout(() => {
106
+ const subscribers = pendingSubscribers.get(id);
107
+ if (subscribers) {
108
+ const index = subscribers.indexOf(callback);
109
+ if (index !== -1) subscribers.splice(index, 1);
110
+ if (subscribers.length === 0) pendingSubscribers.delete(id);
111
+ }
112
+ reject(new Error(`Timeout waiting for canvas with id="${id}". Make sure a <Canvas id="${id}"> is mounted.`));
113
+ }, timeout);
114
+ const callback = (entry) => {
115
+ clearTimeout(timeoutId);
116
+ resolve(entry);
117
+ };
118
+ if (!pendingSubscribers.has(id)) {
119
+ pendingSubscribers.set(id, []);
120
+ }
121
+ pendingSubscribers.get(id).push(callback);
122
+ });
123
+ }
124
+ function hasPrimary(id) {
125
+ return primaryRegistry.has(id);
126
+ }
127
+ function unregisterPrimary(id) {
128
+ primaryRegistry.delete(id);
129
+ }
130
+ function getPrimaryIds() {
131
+ return Array.from(primaryRegistry.keys());
132
+ }
133
+
134
+ const presetsObj = {
135
+ apartment: "lebombo_1k.hdr",
136
+ city: "potsdamer_platz_1k.hdr",
137
+ dawn: "kiara_1_dawn_1k.hdr",
138
+ forest: "forest_slope_1k.hdr",
139
+ lobby: "st_fagans_interior_1k.hdr",
140
+ night: "dikhololo_night_1k.hdr",
141
+ park: "rooitou_park_1k.hdr",
142
+ studio: "studio_small_03_1k.hdr",
143
+ sunset: "venice_sunset_1k.hdr",
144
+ warehouse: "empty_warehouse_01_1k.hdr"
145
+ };
146
+
147
+ const CUBEMAP_ROOT = "https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/";
148
+ const isArray = (arr) => Array.isArray(arr);
149
+ const defaultFiles = ["/px.png", "/nx.png", "/py.png", "/ny.png", "/pz.png", "/nz.png"];
150
+ function useEnvironment({
151
+ files = defaultFiles,
152
+ path = "",
153
+ preset = void 0,
154
+ colorSpace = void 0,
155
+ extensions
156
+ } = {}) {
157
+ if (preset) {
158
+ validatePreset(preset);
159
+ files = presetsObj[preset];
160
+ path = CUBEMAP_ROOT;
161
+ }
162
+ const multiFile = isArray(files);
163
+ const { extension, isCubemap } = getExtension(files);
164
+ const loader = getLoader$1(extension);
165
+ if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
166
+ const renderer = fiber.useThree((state) => state.renderer);
167
+ React.useLayoutEffect(() => {
168
+ if (extension !== "webp" && extension !== "jpg" && extension !== "jpeg") return;
169
+ function clearGainmapTexture() {
170
+ fiber.useLoader.clear(loader, multiFile ? [files] : files);
171
+ }
172
+ renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
173
+ }, [extension, files, loader, multiFile, renderer.domElement]);
174
+ const loaderResult = fiber.useLoader(
175
+ loader,
176
+ multiFile ? [files] : files,
177
+ (loader2) => {
178
+ if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
179
+ loader2.setRenderer?.(renderer);
180
+ }
181
+ loader2.setPath?.(path);
182
+ if (extensions) extensions(loader2);
183
+ }
184
+ );
185
+ let texture = multiFile ? (
186
+ // @ts-ignore
187
+ loaderResult[0]
188
+ ) : loaderResult;
189
+ if (extension === "jpg" || extension === "jpeg" || extension === "webp") {
190
+ texture = texture.renderTarget?.texture;
191
+ }
192
+ texture.mapping = isCubemap ? three.CubeReflectionMapping : three.EquirectangularReflectionMapping;
193
+ texture.colorSpace = colorSpace ?? (isCubemap ? "srgb" : "srgb-linear");
194
+ return texture;
195
+ }
196
+ const preloadDefaultOptions = {
197
+ files: defaultFiles,
198
+ path: "",
199
+ preset: void 0,
200
+ extensions: void 0
201
+ };
202
+ useEnvironment.preload = (preloadOptions) => {
203
+ const options = { ...preloadDefaultOptions, ...preloadOptions };
204
+ let { files, path = "" } = options;
205
+ const { preset, extensions } = options;
206
+ if (preset) {
207
+ validatePreset(preset);
208
+ files = presetsObj[preset];
209
+ path = CUBEMAP_ROOT;
210
+ }
211
+ const { extension } = getExtension(files);
212
+ if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
213
+ throw new Error("useEnvironment: Preloading gainmaps is not supported");
214
+ }
215
+ const loader = getLoader$1(extension);
216
+ if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
217
+ fiber.useLoader.preload(loader, isArray(files) ? [files] : files, (loader2) => {
218
+ loader2.setPath?.(path);
219
+ if (extensions) extensions(loader2);
220
+ });
221
+ };
222
+ const clearDefaultOptins = {
223
+ files: defaultFiles,
224
+ preset: void 0
225
+ };
226
+ useEnvironment.clear = (clearOptions) => {
227
+ const options = { ...clearDefaultOptins, ...clearOptions };
228
+ let { files } = options;
229
+ const { preset } = options;
230
+ if (preset) {
231
+ validatePreset(preset);
232
+ files = presetsObj[preset];
233
+ }
234
+ const { extension } = getExtension(files);
235
+ const loader = getLoader$1(extension);
236
+ if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
237
+ fiber.useLoader.clear(loader, isArray(files) ? [files] : files);
238
+ };
239
+ function validatePreset(preset) {
240
+ if (!(preset in presetsObj)) throw new Error("Preset must be one of: " + Object.keys(presetsObj).join(", "));
241
+ }
242
+ function getExtension(files) {
243
+ const isCubemap = isArray(files) && files.length === 6;
244
+ const isGainmap = isArray(files) && files.length === 3 && files.some((file) => file.endsWith("json"));
245
+ const firstEntry = isArray(files) ? files[0] : files;
246
+ 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();
247
+ return { extension, isCubemap, isGainmap };
248
+ }
249
+ function getLoader$1(extension) {
250
+ const loader = extension === "cube" ? three.CubeTextureLoader : extension === "hdr" ? HDRLoader_js.HDRLoader : extension === "exr" ? EXRLoader_js.EXRLoader : extension === "jpg" || extension === "jpeg" ? UltraHDRLoader_js.UltraHDRLoader : extension === "webp" ? gainmapJs.GainMapLoader : null;
251
+ return loader;
252
+ }
253
+
254
+ const isRef$1 = (obj) => obj.current && obj.current.isScene;
255
+ const resolveScene = (scene) => isRef$1(scene) ? scene.current : scene;
256
+ function setEnvProps(background, scene, defaultScene, texture, sceneProps = {}) {
257
+ sceneProps = {
258
+ backgroundBlurriness: 0,
259
+ backgroundIntensity: 1,
260
+ backgroundRotation: [0, 0, 0],
261
+ environmentIntensity: 1,
262
+ environmentRotation: [0, 0, 0],
263
+ ...sceneProps
264
+ };
265
+ const target = resolveScene(scene || defaultScene);
266
+ const oldbg = target.background;
267
+ const oldenv = target.environment;
268
+ const oldSceneProps = {
269
+ // @ts-ignore
270
+ backgroundBlurriness: target.backgroundBlurriness,
271
+ // @ts-ignore
272
+ backgroundIntensity: target.backgroundIntensity,
273
+ // @ts-ignore
274
+ backgroundRotation: target.backgroundRotation?.clone?.() ?? [0, 0, 0],
275
+ // @ts-ignore
276
+ environmentIntensity: target.environmentIntensity,
277
+ // @ts-ignore
278
+ environmentRotation: target.environmentRotation?.clone?.() ?? [0, 0, 0]
279
+ };
280
+ if (background !== "only") target.environment = texture;
281
+ if (background) target.background = texture;
282
+ fiber.applyProps(target, sceneProps);
283
+ return () => {
284
+ if (background !== "only") target.environment = oldenv;
285
+ if (background) target.background = oldbg;
286
+ fiber.applyProps(target, oldSceneProps);
287
+ };
288
+ }
289
+ function EnvironmentMap({ scene, background = false, map, ...config }) {
290
+ const defaultScene = fiber.useThree((state) => state.scene);
291
+ React__namespace.useLayoutEffect(() => {
292
+ if (map) return setEnvProps(background, scene, defaultScene, map, config);
293
+ });
294
+ return null;
295
+ }
296
+ function EnvironmentCube({
297
+ background = false,
298
+ scene,
299
+ blur,
300
+ backgroundBlurriness,
301
+ backgroundIntensity,
302
+ backgroundRotation,
303
+ environmentIntensity,
304
+ environmentRotation,
305
+ ...rest
306
+ }) {
307
+ const texture = useEnvironment(rest);
308
+ const defaultScene = fiber.useThree((state) => state.scene);
309
+ React__namespace.useLayoutEffect(() => {
310
+ return setEnvProps(background, scene, defaultScene, texture, {
311
+ backgroundBlurriness: blur ?? backgroundBlurriness,
312
+ backgroundIntensity,
313
+ backgroundRotation,
314
+ environmentIntensity,
315
+ environmentRotation
316
+ });
317
+ });
318
+ React__namespace.useEffect(() => {
319
+ return () => {
320
+ texture.dispose();
321
+ };
322
+ }, [texture]);
323
+ return null;
324
+ }
325
+ function EnvironmentPortal({
326
+ children,
327
+ near = 0.1,
328
+ far = 1e3,
329
+ resolution = 256,
330
+ frames = 1,
331
+ map,
332
+ background = false,
333
+ blur,
334
+ backgroundBlurriness,
335
+ backgroundIntensity,
336
+ backgroundRotation,
337
+ environmentIntensity,
338
+ environmentRotation,
339
+ scene,
340
+ files,
341
+ path,
342
+ preset = void 0,
343
+ extensions
344
+ }) {
345
+ const gl = fiber.useThree((state) => state.gl);
346
+ const defaultScene = fiber.useThree((state) => state.scene);
347
+ const camera = React__namespace.useRef(null);
348
+ const [virtualScene] = React__namespace.useState(() => new three.Scene());
349
+ const fbo = React__namespace.useMemo(() => {
350
+ const fbo2 = new three.WebGLCubeRenderTarget(resolution);
351
+ fbo2.texture.type = three.HalfFloatType;
352
+ return fbo2;
353
+ }, [resolution]);
354
+ React__namespace.useEffect(() => {
355
+ return () => {
356
+ fbo.dispose();
357
+ };
358
+ }, [fbo]);
359
+ React__namespace.useLayoutEffect(() => {
360
+ if (frames === 1) {
361
+ const autoClear = gl.autoClear;
362
+ gl.autoClear = true;
363
+ camera.current.update(gl, virtualScene);
364
+ gl.autoClear = autoClear;
365
+ }
366
+ return setEnvProps(background, scene, defaultScene, fbo.texture, {
367
+ backgroundBlurriness: blur ?? backgroundBlurriness,
368
+ backgroundIntensity,
369
+ backgroundRotation,
370
+ environmentIntensity,
371
+ environmentRotation
372
+ });
373
+ }, [
374
+ children,
375
+ virtualScene,
376
+ fbo.texture,
377
+ scene,
378
+ defaultScene,
379
+ background,
380
+ frames,
381
+ gl,
382
+ blur,
383
+ backgroundBlurriness,
384
+ backgroundIntensity,
385
+ backgroundRotation,
386
+ environmentIntensity,
387
+ environmentRotation
388
+ ]);
389
+ let count = 1;
390
+ fiber.useFrame(() => {
391
+ if (frames === Infinity || count < frames) {
392
+ const autoClear = gl.autoClear;
393
+ gl.autoClear = true;
394
+ camera.current.update(gl, virtualScene);
395
+ gl.autoClear = autoClear;
396
+ count++;
397
+ }
398
+ });
399
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: fiber.createPortal(
400
+ /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
401
+ children,
402
+ /* @__PURE__ */ jsxRuntime.jsx("cubeCamera", { ref: camera, args: [near, far, fbo] }),
403
+ files || preset ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { background: true, files, preset, path, extensions }) : map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { background: true, map, extensions }) : null
404
+ ] }),
405
+ virtualScene
406
+ ) });
407
+ }
408
+ function EnvironmentGround(props) {
409
+ const textureDefault = useEnvironment(props);
410
+ const texture = props.map || textureDefault;
411
+ React__namespace.useMemo(() => fiber.extend({ GroundProjectedEnvImpl: GroundedSkybox_js.GroundedSkybox }), []);
412
+ React__namespace.useEffect(() => {
413
+ return () => {
414
+ textureDefault.dispose();
415
+ };
416
+ }, [textureDefault]);
417
+ const height = props.ground?.height ?? 15;
418
+ const radius = props.ground?.radius ?? 60;
419
+ const scale = props.ground?.scale ?? 1e3;
420
+ const args = React__namespace.useMemo(
421
+ () => [texture, height, radius],
422
+ [texture, height, radius]
423
+ );
424
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
425
+ /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props, map: texture }),
426
+ /* @__PURE__ */ jsxRuntime.jsx("groundProjectedEnvImpl", { args, scale })
427
+ ] });
428
+ }
429
+ function EnvironmentColor({ color, scene }) {
430
+ const defaultScene = fiber.useThree((state) => state.scene);
431
+ React__namespace.useLayoutEffect(() => {
432
+ if (color === void 0) return;
433
+ const target = resolveScene(scene || defaultScene);
434
+ const oldBg = target.background;
435
+ target.background = new three.Color(color);
436
+ return () => {
437
+ target.background = oldBg;
438
+ };
439
+ });
440
+ return null;
441
+ }
442
+ function EnvironmentDualSource(props) {
443
+ const { backgroundFiles, ...envProps } = props;
444
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
445
+ /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...envProps, background: false }),
446
+ /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props, files: backgroundFiles, background: "only" })
447
+ ] });
448
+ }
449
+ function Environment(props) {
450
+ if (props.color && !props.files && !props.preset && !props.map) {
451
+ return /* @__PURE__ */ jsxRuntime.jsx(EnvironmentColor, { ...props });
452
+ }
453
+ if (props.backgroundFiles && props.backgroundFiles !== props.files) {
454
+ return /* @__PURE__ */ jsxRuntime.jsx(EnvironmentDualSource, { ...props });
455
+ }
456
+ return props.ground ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props });
457
+ }
458
+
459
+ var __defProp = Object.defineProperty;
460
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
461
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
71
462
  const act = React__namespace["act"];
72
463
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
73
464
  function useMutableCallback(fn) {
@@ -99,7 +490,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
99
490
  return _a = class extends React__namespace.Component {
100
491
  constructor() {
101
492
  super(...arguments);
102
- __publicField$2(this, "state", { error: false });
493
+ __publicField(this, "state", { error: false });
103
494
  }
104
495
  componentDidCatch(err) {
105
496
  this.props.set(err);
@@ -107,7 +498,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
107
498
  render() {
108
499
  return this.state.error ? null : this.props.children;
109
500
  }
110
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
501
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
111
502
  })();
112
503
 
113
504
  const is = {
@@ -293,7 +684,7 @@ function createOcclusionObserverNode(store, uniform) {
293
684
  let occlusionSetupPromise = null;
294
685
  function enableOcclusion(store) {
295
686
  const state = store.getState();
296
- const { internal, renderer, rootScene } = state;
687
+ const { internal, renderer } = state;
297
688
  if (internal.occlusionEnabled || occlusionSetupPromise) return;
298
689
  const hasOcclusionSupport = typeof renderer?.isOccluded === "function";
299
690
  if (!hasOcclusionSupport) {
@@ -401,6 +792,17 @@ function unregisterVisibility(store, object) {
401
792
  internal.visibilityRegistry.delete(object.uuid);
402
793
  internal.occlusionCache.delete(object);
403
794
  }
795
+ function updateVisibilityHandlers(store, object, handlers) {
796
+ const { internal } = store.getState();
797
+ const entry = internal.visibilityRegistry.get(object.uuid);
798
+ if (!entry) return false;
799
+ entry.handlers = handlers;
800
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
801
+ object.occlusionTest = true;
802
+ enableOcclusion(store);
803
+ }
804
+ return true;
805
+ }
404
806
  function checkVisibility(state) {
405
807
  const { internal, camera } = state;
406
808
  const registry = internal.visibilityRegistry;
@@ -456,6 +858,22 @@ function hasVisibilityHandlers(handlers) {
456
858
  return !!(handlers.onFramed || handlers.onOccluded || handlers.onVisible);
457
859
  }
458
860
 
861
+ const FROM_REF = Symbol.for("@react-three/fiber.fromRef");
862
+ function fromRef(ref) {
863
+ return { [FROM_REF]: ref };
864
+ }
865
+ function isFromRef(value) {
866
+ return value !== null && typeof value === "object" && FROM_REF in value;
867
+ }
868
+
869
+ const ONCE = Symbol.for("@react-three/fiber.once");
870
+ function once(...args) {
871
+ return { [ONCE]: args.length ? args : true };
872
+ }
873
+ function isOnce(value) {
874
+ return value !== null && typeof value === "object" && ONCE in value;
875
+ }
876
+
459
877
  const RESERVED_PROPS = [
460
878
  "children",
461
879
  "key",
@@ -526,7 +944,7 @@ function getMemoizedPrototype(root) {
526
944
  ctor = new root.constructor();
527
945
  MEMOIZED_PROTOTYPES.set(root.constructor, ctor);
528
946
  }
529
- } catch (e) {
947
+ } catch {
530
948
  }
531
949
  return ctor;
532
950
  }
@@ -557,7 +975,7 @@ function applyProps(object, props) {
557
975
  const rootState = instance && findInitialRoot(instance).getState();
558
976
  const prevHandlers = instance?.eventCount;
559
977
  for (const prop in props) {
560
- let value = props[prop];
978
+ const value = props[prop];
561
979
  if (RESERVED_PROPS.includes(prop)) continue;
562
980
  if (instance && EVENT_REGEX.test(prop)) {
563
981
  if (typeof value === "function") instance.handlers[prop] = value;
@@ -572,6 +990,22 @@ function applyProps(object, props) {
572
990
  continue;
573
991
  }
574
992
  if (value === void 0) continue;
993
+ if (isFromRef(value)) continue;
994
+ if (isOnce(value)) {
995
+ if (instance?.appliedOnce?.has(prop)) continue;
996
+ if (instance) {
997
+ instance.appliedOnce ?? (instance.appliedOnce = /* @__PURE__ */ new Set());
998
+ instance.appliedOnce.add(prop);
999
+ }
1000
+ const { root: targetRoot, key: targetKey } = resolve(object, prop);
1001
+ const args = value[ONCE];
1002
+ if (typeof targetRoot[targetKey] === "function") {
1003
+ targetRoot[targetKey](...args === true ? [] : args);
1004
+ } else if (args !== true && args.length > 0) {
1005
+ targetRoot[targetKey] = args[0];
1006
+ }
1007
+ continue;
1008
+ }
575
1009
  let { root, key, target } = resolve(object, prop);
576
1010
  if (target === void 0 && (typeof root !== "object" || root === null)) {
577
1011
  throw Error(`R3F: Cannot set "${prop}". Ensure it is an object before setting "${key}".`);
@@ -592,9 +1026,25 @@ function applyProps(object, props) {
592
1026
  } else if (isVectorLike(target) && is.num(value)) {
593
1027
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
594
1028
  else target.set(value);
1029
+ } else if (root instanceof three.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1030
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1031
+ const uniforms = root.uniforms;
1032
+ const nextUniforms = value;
1033
+ for (const name in nextUniforms) {
1034
+ const uniform = nextUniforms[name];
1035
+ const targetUniform = uniforms[name];
1036
+ if (targetUniform) Object.assign(targetUniform, uniform);
1037
+ else {
1038
+ const nextUniform = uniform instanceof three.Uniform ? uniform.clone() : new three.Uniform(uniform.value);
1039
+ uniforms[name] = nextUniform;
1040
+ }
1041
+ }
595
1042
  } else {
596
1043
  root[key] = value;
597
- if (rootState && !rootState.linear && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
1044
+ if (key.endsWith("Node") && root.isMaterial) {
1045
+ root.needsUpdate = true;
1046
+ }
1047
+ if (rootState && rootState.renderer?.outputColorSpace === three.SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
598
1048
  root[key].format === three.RGBAFormat && root[key].type === three.UnsignedByteType) {
599
1049
  root[key].colorSpace = rootState.textureColorSpace;
600
1050
  }
@@ -607,6 +1057,9 @@ function applyProps(object, props) {
607
1057
  if (instance.eventCount && object2.raycast !== null) {
608
1058
  rootState.internal.interaction.push(object2);
609
1059
  }
1060
+ }
1061
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1062
+ const object2 = instance.object;
610
1063
  const root = findInitialRoot(instance);
611
1064
  const visibilityHandlers = {
612
1065
  onFramed: instance.handlers.onFramed,
@@ -614,7 +1067,9 @@ function applyProps(object, props) {
614
1067
  onVisible: instance.handlers.onVisible
615
1068
  };
616
1069
  if (hasVisibilityHandlers(visibilityHandlers)) {
617
- registerVisibility(root, object2, visibilityHandlers);
1070
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1071
+ registerVisibility(root, object2, visibilityHandlers);
1072
+ }
618
1073
  } else {
619
1074
  unregisterVisibility(root, object2);
620
1075
  }
@@ -627,38 +1082,60 @@ function applyProps(object, props) {
627
1082
  return object;
628
1083
  }
629
1084
 
1085
+ const DEFAULT_POINTER_ID = 0;
1086
+ const XR_POINTER_ID_START = 1e3;
1087
+ function getPointerState(internal, pointerId) {
1088
+ let state = internal.pointerMap.get(pointerId);
1089
+ if (!state) {
1090
+ state = {
1091
+ hovered: /* @__PURE__ */ new Map(),
1092
+ captured: /* @__PURE__ */ new Map(),
1093
+ initialClick: [0, 0],
1094
+ initialHits: []
1095
+ };
1096
+ internal.pointerMap.set(pointerId, state);
1097
+ }
1098
+ return state;
1099
+ }
1100
+ function getPointerId(event) {
1101
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1102
+ }
630
1103
  function makeId(event) {
631
1104
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
632
1105
  }
633
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
634
- const captureData = captures.get(obj);
1106
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1107
+ const pointerState = internal.pointerMap.get(pointerId);
1108
+ if (!pointerState) return;
1109
+ const captureData = pointerState.captured.get(obj);
635
1110
  if (captureData) {
636
- captures.delete(obj);
637
- if (captures.size === 0) {
638
- capturedMap.delete(pointerId);
639
- captureData.target.releasePointerCapture(pointerId);
640
- }
1111
+ pointerState.captured.delete(obj);
1112
+ captureData.target.releasePointerCapture(pointerId);
641
1113
  }
642
1114
  }
643
1115
  function removeInteractivity(store, object) {
644
1116
  const { internal } = store.getState();
645
1117
  internal.interaction = internal.interaction.filter((o) => o !== object);
646
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
647
- internal.hovered.forEach((value, key) => {
648
- if (value.eventObject === object || value.object === object) {
649
- internal.hovered.delete(key);
1118
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1119
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1120
+ pointerState.hovered.forEach((value, key) => {
1121
+ if (value.eventObject === object || value.object === object) {
1122
+ pointerState.hovered.delete(key);
1123
+ }
1124
+ });
1125
+ if (pointerState.captured.has(object)) {
1126
+ releaseInternalPointerCapture(internal, object, pointerId);
650
1127
  }
651
- });
652
- internal.capturedMap.forEach((captures, pointerId) => {
653
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
654
- });
1128
+ }
655
1129
  unregisterVisibility(store, object);
656
1130
  }
657
1131
  function createEvents(store) {
658
- function calculateDistance(event) {
1132
+ function calculateDistance(event, pointerId) {
659
1133
  const { internal } = store.getState();
660
- const dx = event.offsetX - internal.initialClick[0];
661
- const dy = event.offsetY - internal.initialClick[1];
1134
+ const pointerState = internal.pointerMap.get(pointerId);
1135
+ if (!pointerState) return 0;
1136
+ const [initialX, initialY] = pointerState.initialClick;
1137
+ const dx = event.offsetX - initialX;
1138
+ const dy = event.offsetY - initialY;
662
1139
  return Math.round(Math.sqrt(dx * dx + dy * dy));
663
1140
  }
664
1141
  function filterPointerEvents(objects) {
@@ -694,6 +1171,15 @@ function createEvents(store) {
694
1171
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
695
1172
  }
696
1173
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1174
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1175
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1176
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1177
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1178
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1179
+ if (aInteractivePriority !== bInteractivePriority) {
1180
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1181
+ }
1182
+ }
697
1183
  const aState = getRootState(a.object);
698
1184
  const bState = getRootState(b.object);
699
1185
  const aPriority = aState?.events?.priority ?? 1;
@@ -709,14 +1195,19 @@ function createEvents(store) {
709
1195
  for (const hit of hits) {
710
1196
  let eventObject = hit.object;
711
1197
  while (eventObject) {
712
- if (eventObject.__r3f?.eventCount)
1198
+ if (eventObject.__r3f?.eventCount) {
713
1199
  intersections.push({ ...hit, eventObject });
1200
+ }
714
1201
  eventObject = eventObject.parent;
715
1202
  }
716
1203
  }
717
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
718
- for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) {
719
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1204
+ if ("pointerId" in event) {
1205
+ const pointerId = event.pointerId;
1206
+ const pointerState = state.internal.pointerMap.get(pointerId);
1207
+ if (pointerState?.captured.size) {
1208
+ for (const captureData of pointerState.captured.values()) {
1209
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1210
+ }
720
1211
  }
721
1212
  }
722
1213
  return intersections;
@@ -729,28 +1220,26 @@ function createEvents(store) {
729
1220
  if (state) {
730
1221
  const { raycaster, pointer, camera, internal } = state;
731
1222
  const unprojectedPoint = new three.Vector3(pointer.x, pointer.y, 0).unproject(camera);
732
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1223
+ const hasPointerCapture = (id) => {
1224
+ const pointerState = internal.pointerMap.get(id);
1225
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1226
+ };
733
1227
  const setPointerCapture = (id) => {
734
1228
  const captureData = { intersection: hit, target: event.target };
735
- if (internal.capturedMap.has(id)) {
736
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
737
- } else {
738
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
739
- }
1229
+ const pointerState = getPointerState(internal, id);
1230
+ pointerState.captured.set(hit.eventObject, captureData);
740
1231
  event.target.setPointerCapture(id);
741
1232
  };
742
1233
  const releasePointerCapture = (id) => {
743
- const captures = internal.capturedMap.get(id);
744
- if (captures) {
745
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
746
- }
1234
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
747
1235
  };
748
- let extractEventProps = {};
749
- for (let prop in event) {
750
- let property = event[prop];
1236
+ const extractEventProps = {};
1237
+ for (const prop in event) {
1238
+ const property = event[prop];
751
1239
  if (typeof property !== "function") extractEventProps[prop] = property;
752
1240
  }
753
- let raycastEvent = {
1241
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1242
+ const raycastEvent = {
754
1243
  ...hit,
755
1244
  ...extractEventProps,
756
1245
  pointer,
@@ -760,18 +1249,19 @@ function createEvents(store) {
760
1249
  unprojectedPoint,
761
1250
  ray: raycaster.ray,
762
1251
  camera,
1252
+ pointerId: eventPointerId,
763
1253
  // Hijack stopPropagation, which just sets a flag
764
1254
  stopPropagation() {
765
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1255
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
766
1256
  if (
767
1257
  // ...if this pointer hasn't been captured
768
- !capturesForPointer || // ... or if the hit object is capturing the pointer
769
- capturesForPointer.has(hit.eventObject)
1258
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1259
+ pointerState.captured.has(hit.eventObject)
770
1260
  ) {
771
1261
  raycastEvent.stopped = localState.stopped = true;
772
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1262
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
773
1263
  const higher = intersections.slice(0, intersections.indexOf(hit));
774
- cancelPointer([...higher, hit]);
1264
+ cancelPointer([...higher, hit], eventPointerId);
775
1265
  }
776
1266
  }
777
1267
  },
@@ -787,15 +1277,18 @@ function createEvents(store) {
787
1277
  }
788
1278
  return intersections;
789
1279
  }
790
- function cancelPointer(intersections) {
1280
+ function cancelPointer(intersections, pointerId) {
791
1281
  const { internal } = store.getState();
792
- for (const hoveredObj of internal.hovered.values()) {
1282
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1283
+ const pointerState = internal.pointerMap.get(pid);
1284
+ if (!pointerState) return;
1285
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
793
1286
  if (!intersections.length || !intersections.find(
794
1287
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
795
1288
  )) {
796
1289
  const eventObject = hoveredObj.eventObject;
797
1290
  const instance = eventObject.__r3f;
798
- internal.hovered.delete(makeId(hoveredObj));
1291
+ pointerState.hovered.delete(hoveredId);
799
1292
  if (instance?.eventCount) {
800
1293
  const handlers = instance.handlers;
801
1294
  const data = { ...hoveredObj, intersections };
@@ -824,41 +1317,118 @@ function createEvents(store) {
824
1317
  instance?.handlers.onDropMissed?.(event);
825
1318
  }
826
1319
  }
1320
+ function cleanupPointer(pointerId) {
1321
+ const { internal } = store.getState();
1322
+ const pointerState = internal.pointerMap.get(pointerId);
1323
+ if (pointerState) {
1324
+ for (const [, hoveredObj] of pointerState.hovered) {
1325
+ const eventObject = hoveredObj.eventObject;
1326
+ const instance = eventObject.__r3f;
1327
+ if (instance?.eventCount) {
1328
+ const handlers = instance.handlers;
1329
+ const data = { ...hoveredObj, intersections: [] };
1330
+ handlers.onPointerOut?.(data);
1331
+ handlers.onPointerLeave?.(data);
1332
+ }
1333
+ }
1334
+ internal.pointerMap.delete(pointerId);
1335
+ }
1336
+ internal.pointerDirty.delete(pointerId);
1337
+ }
1338
+ function processDeferredPointer(event, pointerId) {
1339
+ const state = store.getState();
1340
+ const { internal } = state;
1341
+ if (!state.events.enabled) return;
1342
+ const filter = filterPointerEvents;
1343
+ const hits = intersect(event, filter);
1344
+ cancelPointer(hits, pointerId);
1345
+ function onIntersect(data) {
1346
+ const eventObject = data.eventObject;
1347
+ const instance = eventObject.__r3f;
1348
+ if (!instance?.eventCount) return;
1349
+ const handlers = instance.handlers;
1350
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1351
+ const id = makeId(data);
1352
+ const pointerState = getPointerState(internal, pointerId);
1353
+ const hoveredItem = pointerState.hovered.get(id);
1354
+ if (!hoveredItem) {
1355
+ pointerState.hovered.set(id, data);
1356
+ handlers.onPointerOver?.(data);
1357
+ handlers.onPointerEnter?.(data);
1358
+ } else if (hoveredItem.stopped) {
1359
+ data.stopPropagation();
1360
+ }
1361
+ }
1362
+ handlers.onPointerMove?.(data);
1363
+ }
1364
+ handleIntersects(hits, event, 0, onIntersect);
1365
+ }
827
1366
  function handlePointer(name) {
828
1367
  switch (name) {
829
1368
  case "onPointerLeave":
830
- case "onPointerCancel":
831
1369
  case "onDragLeave":
832
1370
  return () => cancelPointer([]);
1371
+ // Global cancel of these events
1372
+ case "onPointerCancel":
1373
+ return (event) => {
1374
+ const pointerId = getPointerId(event);
1375
+ cleanupPointer(pointerId);
1376
+ };
833
1377
  case "onLostPointerCapture":
834
1378
  return (event) => {
835
1379
  const { internal } = store.getState();
836
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1380
+ const pointerId = getPointerId(event);
1381
+ const pointerState = internal.pointerMap.get(pointerId);
1382
+ if (pointerState?.captured.size) {
837
1383
  requestAnimationFrame(() => {
838
- if (internal.capturedMap.has(event.pointerId)) {
839
- internal.capturedMap.delete(event.pointerId);
840
- cancelPointer([]);
1384
+ const pointerState2 = internal.pointerMap.get(pointerId);
1385
+ if (pointerState2?.captured.size) {
1386
+ pointerState2.captured.clear();
841
1387
  }
1388
+ cancelPointer([], pointerId);
842
1389
  });
843
1390
  }
844
1391
  };
845
1392
  }
846
1393
  return function handleEvent(event) {
847
1394
  const state = store.getState();
848
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1395
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1396
+ const pointerId = getPointerId(event);
849
1397
  internal.lastEvent.current = event;
850
- if (!state.events.enabled) return;
1398
+ if (!events.enabled) return;
851
1399
  const isPointerMove = name === "onPointerMove";
852
1400
  const isDragOver = name === "onDragOver";
853
1401
  const isDrop = name === "onDrop";
854
1402
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1403
+ const isPointerDown = name === "onPointerDown";
1404
+ const isPointerUp = name === "onPointerUp";
1405
+ const isWheel = name === "onWheel";
1406
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1407
+ if (isPointerMove && canDeferRaycasts) {
1408
+ events.compute?.(event, state);
1409
+ internal.pointerDirty.set(pointerId, event);
1410
+ return;
1411
+ }
1412
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1413
+ events.compute?.(event, state);
1414
+ internal.pointerDirty.set(pointerId, event);
1415
+ return;
1416
+ }
1417
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1418
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1419
+ internal.pointerDirty.delete(pointerId);
1420
+ processDeferredPointer(deferredEvent, pointerId);
1421
+ }
855
1422
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
856
1423
  const hits = intersect(event, filter);
857
- const delta = isClickEvent ? calculateDistance(event) : 0;
858
- if (name === "onPointerDown") {
859
- internal.initialClick = [event.offsetX, event.offsetY];
860
- internal.initialHits = hits.map((hit) => hit.eventObject);
861
- }
1424
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1425
+ if (isPointerDown) {
1426
+ const pointerState2 = getPointerState(internal, pointerId);
1427
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1428
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1429
+ }
1430
+ const pointerState = internal.pointerMap.get(pointerId);
1431
+ const initialHits = pointerState?.initialHits ?? [];
862
1432
  if (isClickEvent && !hits.length) {
863
1433
  if (delta <= 2) {
864
1434
  pointerMissed(event, internal.interaction);
@@ -873,7 +1443,9 @@ function createEvents(store) {
873
1443
  dropMissed(event, internal.interaction);
874
1444
  if (onDropMissed) onDropMissed(event);
875
1445
  }
876
- if (isPointerMove || isDragOver) cancelPointer(hits);
1446
+ if (isPointerMove || isDragOver) {
1447
+ cancelPointer(hits, pointerId);
1448
+ }
877
1449
  function onIntersect(data) {
878
1450
  const eventObject = data.eventObject;
879
1451
  const instance = eventObject.__r3f;
@@ -882,9 +1454,10 @@ function createEvents(store) {
882
1454
  if (isPointerMove) {
883
1455
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
884
1456
  const id = makeId(data);
885
- const hoveredItem = internal.hovered.get(id);
1457
+ const pointerState2 = getPointerState(internal, pointerId);
1458
+ const hoveredItem = pointerState2.hovered.get(id);
886
1459
  if (!hoveredItem) {
887
- internal.hovered.set(id, data);
1460
+ pointerState2.hovered.set(id, data);
888
1461
  handlers.onPointerOver?.(data);
889
1462
  handlers.onPointerEnter?.(data);
890
1463
  } else if (hoveredItem.stopped) {
@@ -894,9 +1467,10 @@ function createEvents(store) {
894
1467
  handlers.onPointerMove?.(data);
895
1468
  } else if (isDragOver) {
896
1469
  const id = makeId(data);
897
- const hoveredItem = internal.hovered.get(id);
1470
+ const pointerState2 = getPointerState(internal, pointerId);
1471
+ const hoveredItem = pointerState2.hovered.get(id);
898
1472
  if (!hoveredItem) {
899
- internal.hovered.set(id, data);
1473
+ pointerState2.hovered.set(id, data);
900
1474
  handlers.onDragOverEnter?.(data);
901
1475
  } else if (hoveredItem.stopped) {
902
1476
  data.stopPropagation();
@@ -907,18 +1481,18 @@ function createEvents(store) {
907
1481
  } else {
908
1482
  const handler = handlers[name];
909
1483
  if (handler) {
910
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1484
+ if (!isClickEvent || initialHits.includes(eventObject)) {
911
1485
  pointerMissed(
912
1486
  event,
913
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1487
+ internal.interaction.filter((object) => !initialHits.includes(object))
914
1488
  );
915
1489
  handler(data);
916
1490
  }
917
1491
  } else {
918
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1492
+ if (isClickEvent && initialHits.includes(eventObject)) {
919
1493
  pointerMissed(
920
1494
  event,
921
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1495
+ internal.interaction.filter((object) => !initialHits.includes(object))
922
1496
  );
923
1497
  }
924
1498
  }
@@ -927,7 +1501,15 @@ function createEvents(store) {
927
1501
  handleIntersects(hits, event, delta, onIntersect);
928
1502
  };
929
1503
  }
930
- return { handlePointer };
1504
+ function flushDeferredPointers() {
1505
+ const { internal, events } = store.getState();
1506
+ if (!events.frameTimedRaycasts) return;
1507
+ for (const [pointerId, event] of internal.pointerDirty) {
1508
+ processDeferredPointer(event, pointerId);
1509
+ }
1510
+ internal.pointerDirty.clear();
1511
+ }
1512
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
931
1513
  }
932
1514
  const DOM_EVENTS = {
933
1515
  onClick: ["click", false],
@@ -946,11 +1528,16 @@ const DOM_EVENTS = {
946
1528
  onLostPointerCapture: ["lostpointercapture", true]
947
1529
  };
948
1530
  function createPointerEvents(store) {
949
- const { handlePointer } = createEvents(store);
1531
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1532
+ let nextXRPointerId = XR_POINTER_ID_START;
1533
+ const xrPointers = /* @__PURE__ */ new Map();
950
1534
  return {
951
1535
  priority: 1,
952
1536
  enabled: true,
953
- compute(event, state, previous) {
1537
+ frameTimedRaycasts: true,
1538
+ alwaysFireOnScroll: true,
1539
+ updateOnFrame: false,
1540
+ compute(event, state) {
954
1541
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
955
1542
  state.raycaster.setFromCamera(state.pointer, state.camera);
956
1543
  },
@@ -959,11 +1546,33 @@ function createPointerEvents(store) {
959
1546
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
960
1547
  {}
961
1548
  ),
962
- update: () => {
1549
+ update: (pointerId) => {
963
1550
  const { events, internal } = store.getState();
964
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1551
+ if (!events.handlers) return;
1552
+ if (pointerId !== void 0) {
1553
+ const event = internal.pointerDirty.get(pointerId);
1554
+ if (event) {
1555
+ internal.pointerDirty.delete(pointerId);
1556
+ processDeferredPointer(event, pointerId);
1557
+ } else if (internal.lastEvent?.current) {
1558
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1559
+ }
1560
+ } else {
1561
+ flushDeferredPointers();
1562
+ if (internal.lastEvent?.current) {
1563
+ events.handlers.onPointerMove(internal.lastEvent.current);
1564
+ }
1565
+ }
1566
+ },
1567
+ flush: () => {
1568
+ const { events, internal } = store.getState();
1569
+ flushDeferredPointers();
1570
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1571
+ events.handlers.onPointerMove(internal.lastEvent.current);
1572
+ }
965
1573
  },
966
1574
  connect: (target) => {
1575
+ if (!target) return;
967
1576
  const { set, events } = store.getState();
968
1577
  events.disconnect?.();
969
1578
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -987,6 +1596,33 @@ function createPointerEvents(store) {
987
1596
  }
988
1597
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
989
1598
  }
1599
+ },
1600
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1601
+ registerPointer: (config) => {
1602
+ const pointerId = nextXRPointerId++;
1603
+ xrPointers.set(pointerId, config);
1604
+ const { internal } = store.getState();
1605
+ getPointerState(internal, pointerId);
1606
+ return pointerId;
1607
+ },
1608
+ unregisterPointer: (pointerId) => {
1609
+ xrPointers.delete(pointerId);
1610
+ const { internal } = store.getState();
1611
+ const pointerState = internal.pointerMap.get(pointerId);
1612
+ if (pointerState) {
1613
+ for (const [, hoveredObj] of pointerState.hovered) {
1614
+ const eventObject = hoveredObj.eventObject;
1615
+ const instance = eventObject.__r3f;
1616
+ if (instance?.eventCount) {
1617
+ const handlers = instance.handlers;
1618
+ const data = { ...hoveredObj, intersections: [] };
1619
+ handlers.onPointerOut?.(data);
1620
+ handlers.onPointerLeave?.(data);
1621
+ }
1622
+ }
1623
+ internal.pointerMap.delete(pointerId);
1624
+ }
1625
+ internal.pointerDirty.delete(pointerId);
990
1626
  }
991
1627
  };
992
1628
  }
@@ -1048,6 +1684,14 @@ function notifyAlpha({ message, link }) {
1048
1684
  }
1049
1685
  }
1050
1686
 
1687
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1688
+ const INTERNAL_FIBER_MARKERS = ["packages/fiber/src", "packages/fiber/dist", "@react-three/fiber", "@react-three_fiber"];
1689
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1690
+ if (!stack) return false;
1691
+ const caller = stack.split("\n")[callerDepth] ?? "";
1692
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m)) || INTERNAL_FIBER_MARKERS.some((m) => caller.includes(m));
1693
+ }
1694
+
1051
1695
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1052
1696
  const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
1053
1697
  const createStore = (invalidate, advance) => {
@@ -1077,23 +1721,29 @@ const createStore = (invalidate, advance) => {
1077
1721
  set,
1078
1722
  get,
1079
1723
  // Mock objects that have to be configured
1724
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1725
+ primaryStore: null,
1080
1726
  gl: null,
1081
1727
  renderer: null,
1082
1728
  camera: null,
1083
1729
  frustum: new three.Frustum(),
1084
1730
  autoUpdateFrustum: true,
1085
1731
  raycaster: null,
1086
- events: { priority: 1, enabled: true, connected: false },
1732
+ events: {
1733
+ priority: 1,
1734
+ enabled: true,
1735
+ connected: false,
1736
+ frameTimedRaycasts: true,
1737
+ alwaysFireOnScroll: true,
1738
+ updateOnFrame: false
1739
+ },
1087
1740
  scene: null,
1088
1741
  rootScene: null,
1089
1742
  xr: null,
1090
1743
  inspector: null,
1091
1744
  invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1092
1745
  advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1093
- legacy: false,
1094
- linear: false,
1095
- flat: false,
1096
- textureColorSpace: "srgb",
1746
+ textureColorSpace: three.SRGBColorSpace,
1097
1747
  isLegacy: false,
1098
1748
  webGPUSupported: false,
1099
1749
  isNative: false,
@@ -1133,10 +1783,40 @@ const createStore = (invalidate, advance) => {
1133
1783
  getCurrentViewport
1134
1784
  },
1135
1785
  setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1136
- setSize: (width, height, top = 0, left = 0) => {
1137
- const camera = get().camera;
1138
- const size = { width, height, top, left };
1139
- set((state2) => ({ size, viewport: { ...state2.viewport, ...getCurrentViewport(camera, defaultTarget, size) } }));
1786
+ setSize: (width, height, top, left) => {
1787
+ const state2 = get();
1788
+ if (width === void 0) {
1789
+ set({ _sizeImperative: false });
1790
+ if (state2._sizeProps) {
1791
+ const { width: propW, height: propH } = state2._sizeProps;
1792
+ if (propW !== void 0 || propH !== void 0) {
1793
+ const currentSize = state2.size;
1794
+ const newSize = {
1795
+ width: propW ?? currentSize.width,
1796
+ height: propH ?? currentSize.height,
1797
+ top: currentSize.top,
1798
+ left: currentSize.left
1799
+ };
1800
+ set((s) => ({
1801
+ size: newSize,
1802
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1803
+ }));
1804
+ scheduler.getScheduler().invalidate();
1805
+ }
1806
+ }
1807
+ return;
1808
+ }
1809
+ const w = width;
1810
+ const h = height ?? width;
1811
+ const t = top ?? state2.size.top;
1812
+ const l = left ?? state2.size.left;
1813
+ const size = { width: w, height: h, top: t, left: l };
1814
+ set((s) => ({
1815
+ size,
1816
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1817
+ _sizeImperative: true
1818
+ }));
1819
+ scheduler.getScheduler().invalidate();
1140
1820
  },
1141
1821
  setDpr: (dpr) => set((state2) => {
1142
1822
  const resolved = calculateDpr(dpr);
@@ -1144,25 +1824,36 @@ const createStore = (invalidate, advance) => {
1144
1824
  }),
1145
1825
  setFrameloop: (frameloop = "always") => {
1146
1826
  set(() => ({ frameloop }));
1827
+ scheduler.getScheduler().frameloop = frameloop;
1147
1828
  },
1148
1829
  setError: (error) => set(() => ({ error })),
1149
1830
  error: null,
1150
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1831
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1151
1832
  uniforms: {},
1152
1833
  nodes: {},
1834
+ buffers: {},
1835
+ gpuStorage: {},
1153
1836
  textures: /* @__PURE__ */ new Map(),
1154
- postProcessing: null,
1837
+ _textureRefs: /* @__PURE__ */ new Map(),
1838
+ renderPipeline: null,
1155
1839
  passes: {},
1840
+ _hmrVersion: 0,
1841
+ _sizeImperative: false,
1842
+ _sizeProps: null,
1156
1843
  previousRoot: void 0,
1157
1844
  internal: {
1158
1845
  // Events
1159
1846
  interaction: [],
1160
- hovered: /* @__PURE__ */ new Map(),
1161
1847
  subscribers: [],
1848
+ // Per-pointer state (new unified structure)
1849
+ pointerMap: /* @__PURE__ */ new Map(),
1850
+ pointerDirty: /* @__PURE__ */ new Map(),
1851
+ lastEvent: React__namespace.createRef(),
1852
+ // Deprecated but kept for backwards compatibility
1853
+ hovered: /* @__PURE__ */ new Map(),
1162
1854
  initialClick: [0, 0],
1163
1855
  initialHits: [],
1164
1856
  capturedMap: /* @__PURE__ */ new Map(),
1165
- lastEvent: React__namespace.createRef(),
1166
1857
  // Visibility tracking (onFramed, onOccluded, onVisible)
1167
1858
  visibilityRegistry: /* @__PURE__ */ new Map(),
1168
1859
  // Occlusion system (WebGPU only)
@@ -1201,8 +1892,7 @@ const createStore = (invalidate, advance) => {
1201
1892
  const currentState = rootStore.getState();
1202
1893
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
1203
1894
  const stack = new Error().stack || "";
1204
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
1205
- if (!isInternalAccess) {
1895
+ if (!isInternalRendererAccess(stack)) {
1206
1896
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
1207
1897
  notifyDepreciated({
1208
1898
  heading: "Accessing state.gl in WebGPU mode",
@@ -1245,13 +1935,22 @@ const createStore = (invalidate, advance) => {
1245
1935
  rootStore.subscribe(() => {
1246
1936
  const { camera, size, viewport, set, internal } = rootStore.getState();
1247
1937
  const actualRenderer = internal.actualRenderer;
1938
+ const canvasTarget = internal.canvasTarget;
1248
1939
  if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
1249
1940
  oldSize = size;
1250
1941
  oldDpr = viewport.dpr;
1251
1942
  updateCamera(camera, size);
1252
- if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
1253
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
1254
- actualRenderer.setSize(size.width, size.height, updateStyle);
1943
+ if (internal.isSecondary && canvasTarget) {
1944
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1945
+ canvasTarget.setSize(size.width, size.height, false);
1946
+ } else {
1947
+ if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
1948
+ actualRenderer.setSize(size.width, size.height, false);
1949
+ if (canvasTarget) {
1950
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1951
+ canvasTarget.setSize(size.width, size.height, false);
1952
+ }
1953
+ }
1255
1954
  }
1256
1955
  if (camera !== oldCamera) {
1257
1956
  oldCamera = camera;
@@ -1306,1057 +2005,32 @@ function loadingFn(extensions, onProgress) {
1306
2005
  );
1307
2006
  };
1308
2007
  }
1309
- function useLoader(loader, input, extensions, onProgress) {
1310
- const keys = Array.isArray(input) ? input : [input];
2008
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2009
+ const inputs = Array.isArray(input) ? input : [input];
2010
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1311
2011
  const fn = loadingFn(extensions, onProgress);
1312
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2012
+ const results = cacheKeys.map(
2013
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2014
+ );
1313
2015
  return Array.isArray(input) ? results : results[0];
1314
2016
  }
1315
- useLoader.preload = function(loader, input, extensions, onProgress) {
1316
- const keys = Array.isArray(input) ? input : [input];
1317
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2017
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2018
+ const inputs = Array.isArray(input) ? input : [input];
2019
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2020
+ cacheKeys.forEach(
2021
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2022
+ );
1318
2023
  };
1319
- useLoader.clear = function(loader, input) {
1320
- const keys = Array.isArray(input) ? input : [input];
1321
- keys.forEach((key) => suspendReact.clear([loader, key]));
2024
+ useLoader.clear = function(loader, input, cacheKey) {
2025
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2026
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
1322
2027
  };
1323
2028
  useLoader.loader = getLoader;
1324
2029
 
1325
- var __defProp$1 = Object.defineProperty;
1326
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1327
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1328
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1329
- class PhaseGraph {
1330
- constructor() {
1331
- /** Ordered list of phase nodes */
1332
- __publicField$1(this, "phases", []);
1333
- /** Quick lookup by name */
1334
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1335
- /** Cached ordered names (invalidated on changes) */
1336
- __publicField$1(this, "orderedNamesCache", null);
1337
- this.initializeDefaultPhases();
1338
- }
1339
- //* Initialization --------------------------------
1340
- initializeDefaultPhases() {
1341
- for (const name of DEFAULT_PHASES) {
1342
- const node = { name, isAutoGenerated: false };
1343
- this.phases.push(node);
1344
- this.phaseMap.set(name, node);
1345
- }
1346
- this.invalidateCache();
1347
- }
1348
- //* Public API --------------------------------
1349
- /**
1350
- * Add a named phase to the graph
1351
- * @param name - Phase name (must be unique)
1352
- * @param options - Position options (before or after another phase)
1353
- */
1354
- addPhase(name, options = {}) {
1355
- if (this.phaseMap.has(name)) {
1356
- console.warn(`[useFrame] Phase "${name}" already exists`);
1357
- return;
1358
- }
1359
- const { before, after } = options;
1360
- const node = { name, isAutoGenerated: false };
1361
- let insertIndex = this.phases.length;
1362
- const targetIndex = this.getPhaseIndex(before ?? after);
1363
- if (targetIndex !== -1) insertIndex = before ? targetIndex : targetIndex + 1;
1364
- else {
1365
- const constraintType = before ? "before" : "after";
1366
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1367
- }
1368
- this.phases.splice(insertIndex, 0, node);
1369
- this.phaseMap.set(name, node);
1370
- this.invalidateCache();
1371
- }
1372
- /**
1373
- * Get ordered list of phase names
1374
- */
1375
- getOrderedPhases() {
1376
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1377
- return this.orderedNamesCache;
1378
- }
1379
- /**
1380
- * Check if a phase exists
1381
- */
1382
- hasPhase(name) {
1383
- return this.phaseMap.has(name);
1384
- }
1385
- /**
1386
- * Get the index of a phase (-1 if not found)
1387
- */
1388
- getPhaseIndex(name) {
1389
- if (!name) return -1;
1390
- return this.phases.findIndex((p) => p.name === name);
1391
- }
1392
- /**
1393
- * Ensure a phase exists, creating an auto-generated one if needed.
1394
- * Used for resolving before/after constraints.
1395
- *
1396
- * @param name - The phase name to ensure exists
1397
- * @returns The phase name (may be auto-generated like 'before:render')
1398
- */
1399
- ensurePhase(name) {
1400
- if (this.phaseMap.has(name)) return name;
1401
- const node = { name, isAutoGenerated: true };
1402
- this.phases.push(node);
1403
- this.phaseMap.set(name, node);
1404
- this.invalidateCache();
1405
- return name;
1406
- }
1407
- /**
1408
- * Resolve where a job with before/after constraints should go.
1409
- * Creates auto-generated phases if needed.
1410
- *
1411
- * @param before - Phase(s) to run before
1412
- * @param after - Phase(s) to run after
1413
- * @returns The resolved phase name
1414
- */
1415
- resolveConstraintPhase(before, after) {
1416
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1417
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1418
- if (beforeArr.length > 0) {
1419
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1420
- }
1421
- if (afterArr.length > 0) {
1422
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1423
- }
1424
- return "update";
1425
- }
1426
- /**
1427
- * Ensure an auto-generated phase exists relative to a target phase.
1428
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1429
- *
1430
- * @param target - The target phase name to position relative to
1431
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1432
- * @param offset - Insertion offset (0 for before, 1 for after)
1433
- * @returns The auto-generated phase name
1434
- */
1435
- ensureAutoPhase(target, prefix, offset) {
1436
- const autoName = `${prefix}:${target}`;
1437
- if (this.phaseMap.has(autoName)) return autoName;
1438
- const node = { name: autoName, isAutoGenerated: true };
1439
- const targetIndex = this.getPhaseIndex(target);
1440
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1441
- else this.phases.push(node);
1442
- this.phaseMap.set(autoName, node);
1443
- this.invalidateCache();
1444
- return autoName;
1445
- }
1446
- // Internal --------------------------------
1447
- invalidateCache() {
1448
- this.orderedNamesCache = null;
1449
- }
1450
- }
1451
-
1452
- function rebuildSortedJobs(jobs, phaseGraph) {
1453
- const orderedPhases = phaseGraph.getOrderedPhases();
1454
- const buckets = /* @__PURE__ */ new Map();
1455
- for (const phase of orderedPhases) {
1456
- buckets.set(phase, []);
1457
- }
1458
- for (const job of jobs.values()) {
1459
- if (!job.enabled) continue;
1460
- let bucket = buckets.get(job.phase);
1461
- if (!bucket) {
1462
- bucket = [];
1463
- buckets.set(job.phase, bucket);
1464
- }
1465
- bucket.push(job);
1466
- }
1467
- const sortedBuckets = [];
1468
- for (const phase of orderedPhases) {
1469
- const bucket = buckets.get(phase);
1470
- if (!bucket || bucket.length === 0) continue;
1471
- bucket.sort((a, b) => {
1472
- if (a.priority !== b.priority) return b.priority - a.priority;
1473
- return a.index - b.index;
1474
- });
1475
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1476
- }
1477
- for (const [phase, bucket] of buckets) {
1478
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1479
- bucket.sort((a, b) => {
1480
- if (a.priority !== b.priority) return b.priority - a.priority;
1481
- return a.index - b.index;
1482
- });
1483
- sortedBuckets.push(bucket);
1484
- }
1485
- }
1486
- return sortedBuckets.flat();
1487
- }
1488
- function hasCrossJobConstraints(bucket) {
1489
- const jobIds = new Set(bucket.map((j) => j.id));
1490
- for (const job of bucket) {
1491
- for (const ref of job.before) {
1492
- if (jobIds.has(ref)) return true;
1493
- }
1494
- for (const ref of job.after) {
1495
- if (jobIds.has(ref)) return true;
1496
- }
1497
- }
1498
- return false;
1499
- }
1500
- function topologicalSort(jobs) {
1501
- const n = jobs.length;
1502
- if (n <= 1) return jobs;
1503
- const jobMap = /* @__PURE__ */ new Map();
1504
- const inDegree = /* @__PURE__ */ new Map();
1505
- const adjacency = /* @__PURE__ */ new Map();
1506
- for (const job of jobs) {
1507
- jobMap.set(job.id, job);
1508
- inDegree.set(job.id, 0);
1509
- adjacency.set(job.id, []);
1510
- }
1511
- for (const job of jobs) {
1512
- for (const ref of job.before) {
1513
- if (jobMap.has(ref)) {
1514
- adjacency.get(job.id).push(ref);
1515
- inDegree.set(ref, inDegree.get(ref) + 1);
1516
- }
1517
- }
1518
- for (const ref of job.after) {
1519
- if (jobMap.has(ref)) {
1520
- adjacency.get(ref).push(job.id);
1521
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1522
- }
1523
- }
1524
- }
1525
- const queue = [];
1526
- for (const job of jobs) {
1527
- if (inDegree.get(job.id) === 0) {
1528
- queue.push(job);
1529
- }
1530
- }
1531
- queue.sort((a, b) => {
1532
- if (a.priority !== b.priority) return b.priority - a.priority;
1533
- return a.index - b.index;
1534
- });
1535
- const result = [];
1536
- while (queue.length > 0) {
1537
- const job = queue.shift();
1538
- result.push(job);
1539
- const neighbors = adjacency.get(job.id) || [];
1540
- for (const neighborId of neighbors) {
1541
- const newDegree = inDegree.get(neighborId) - 1;
1542
- inDegree.set(neighborId, newDegree);
1543
- if (newDegree === 0) {
1544
- const neighbor = jobMap.get(neighborId);
1545
- insertSorted(queue, neighbor);
1546
- }
1547
- }
1548
- }
1549
- if (result.length !== n) {
1550
- console.warn("[useFrame] Circular dependency detected in job constraints");
1551
- const resultIds = new Set(result.map((j) => j.id));
1552
- for (const job of jobs) {
1553
- if (!resultIds.has(job.id)) result.push(job);
1554
- }
1555
- }
1556
- return result;
1557
- }
1558
- function insertSorted(arr, job) {
1559
- let i = 0;
1560
- while (i < arr.length) {
1561
- const cmp = arr[i];
1562
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1563
- break;
1564
- }
1565
- i++;
1566
- }
1567
- arr.splice(i, 0, job);
1568
- }
1569
-
1570
- function shouldRun(job, now) {
1571
- if (!job.enabled) return false;
1572
- if (!job.fps) return true;
1573
- const minInterval = 1e3 / job.fps;
1574
- const lastRun = job.lastRun ?? 0;
1575
- const elapsed = now - lastRun;
1576
- if (elapsed < minInterval) return false;
1577
- if (job.drop) {
1578
- job.lastRun = now;
1579
- } else {
1580
- const steps = Math.floor(elapsed / minInterval);
1581
- job.lastRun = lastRun + steps * minInterval;
1582
- if (job.lastRun < now - minInterval) {
1583
- job.lastRun = now;
1584
- }
1585
- }
1586
- return true;
1587
- }
1588
- function resetJobTiming(job) {
1589
- job.lastRun = void 0;
1590
- }
1591
-
1592
- var __defProp = Object.defineProperty;
1593
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1594
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1595
- const hmrData = (() => {
1596
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1597
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1598
- try {
1599
- return (0, eval)("import.meta.hot");
1600
- } catch {
1601
- return void 0;
1602
- }
1603
- })();
1604
- const _Scheduler = class _Scheduler {
1605
- //* Constructor ================================
1606
- constructor() {
1607
- //* Critical State ================================
1608
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1609
- __publicField(this, "phaseGraph");
1610
- __publicField(this, "loopState", {
1611
- running: false,
1612
- rafHandle: null,
1613
- lastTime: null,
1614
- // null = uninitialized, 0+ = valid timestamp
1615
- frameCount: 0,
1616
- elapsedTime: 0,
1617
- createdAt: performance.now()
1618
- });
1619
- __publicField(this, "stoppedTime", 0);
1620
- //* Private State ================================
1621
- __publicField(this, "nextRootIndex", 0);
1622
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1623
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1624
- __publicField(this, "nextGlobalIndex", 0);
1625
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1626
- __publicField(this, "nextJobIndex", 0);
1627
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1628
- __publicField(this, "pendingFrames", 0);
1629
- __publicField(this, "_frameloop", "always");
1630
- //* Independent Mode & Error Handling State ================================
1631
- __publicField(this, "_independent", false);
1632
- __publicField(this, "errorHandler", null);
1633
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1634
- //* Core Loop Execution Methods ================================
1635
- /**
1636
- * Main RAF loop callback.
1637
- * Executes frame, handles demand mode, and schedules next frame.
1638
- * @param {number} timestamp - RAF timestamp in milliseconds
1639
- * @returns {void}
1640
- * @private
1641
- */
1642
- __publicField(this, "loop", (timestamp) => {
1643
- if (!this.loopState.running) return;
1644
- this.executeFrame(timestamp);
1645
- if (this._frameloop === "demand") {
1646
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1647
- if (this.pendingFrames === 0) {
1648
- this.notifyIdle(timestamp);
1649
- return this.stop();
1650
- }
1651
- }
1652
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1653
- });
1654
- this.phaseGraph = new PhaseGraph();
1655
- }
1656
- static get instance() {
1657
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1658
- }
1659
- static set instance(value) {
1660
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1661
- }
1662
- /**
1663
- * Get the global scheduler instance (creates if doesn't exist).
1664
- * Uses HMR data to preserve instance across hot reloads.
1665
- * @returns {Scheduler} The singleton scheduler instance
1666
- */
1667
- static get() {
1668
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1669
- _Scheduler.instance = hmrData.data.scheduler;
1670
- }
1671
- if (!_Scheduler.instance) {
1672
- _Scheduler.instance = new _Scheduler();
1673
- if (hmrData?.data) {
1674
- hmrData.data.scheduler = _Scheduler.instance;
1675
- }
1676
- }
1677
- return _Scheduler.instance;
1678
- }
1679
- /**
1680
- * Reset the singleton instance. Stops the loop and clears all state.
1681
- * Primarily used for testing to ensure clean state between tests.
1682
- * @returns {void}
1683
- */
1684
- static reset() {
1685
- if (_Scheduler.instance) {
1686
- _Scheduler.instance.stop();
1687
- _Scheduler.instance = null;
1688
- }
1689
- if (hmrData?.data) {
1690
- hmrData.data.scheduler = null;
1691
- }
1692
- }
1693
- //* Getters & Setters ================================
1694
- get phases() {
1695
- return this.phaseGraph.getOrderedPhases();
1696
- }
1697
- get frameloop() {
1698
- return this._frameloop;
1699
- }
1700
- set frameloop(mode) {
1701
- if (this._frameloop === mode) return;
1702
- const wasAlways = this._frameloop === "always";
1703
- this._frameloop = mode;
1704
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1705
- else if (mode !== "always" && wasAlways) this.stop();
1706
- }
1707
- get isRunning() {
1708
- return this.loopState.running;
1709
- }
1710
- get isReady() {
1711
- return this.roots.size > 0;
1712
- }
1713
- get independent() {
1714
- return this._independent;
1715
- }
1716
- set independent(value) {
1717
- this._independent = value;
1718
- if (value) this.ensureDefaultRoot();
1719
- }
1720
- //* Root Management Methods ================================
1721
- /**
1722
- * Register a root (Canvas) with the scheduler.
1723
- * The first root to register starts the RAF loop (if frameloop='always').
1724
- * @param {string} id - Unique identifier for this root
1725
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1726
- * @returns {() => void} Unsubscribe function to remove this root
1727
- */
1728
- registerRoot(id, options = {}) {
1729
- if (this.roots.has(id)) {
1730
- console.warn(`[Scheduler] Root "${id}" already registered`);
1731
- return () => this.unregisterRoot(id);
1732
- }
1733
- const entry = {
1734
- id,
1735
- getState: options.getState ?? (() => ({})),
1736
- jobs: /* @__PURE__ */ new Map(),
1737
- sortedJobs: [],
1738
- needsRebuild: false
1739
- };
1740
- if (options.onError) {
1741
- this.errorHandler = options.onError;
1742
- }
1743
- this.roots.set(id, entry);
1744
- if (this.roots.size === 1) {
1745
- this.notifyRootReady();
1746
- if (this._frameloop === "always") this.start();
1747
- }
1748
- return () => this.unregisterRoot(id);
1749
- }
1750
- /**
1751
- * Unregister a root from the scheduler.
1752
- * Cleans up all job state listeners for this root's jobs.
1753
- * The last root to unregister stops the RAF loop.
1754
- * @param {string} id - The root ID to unregister
1755
- * @returns {void}
1756
- */
1757
- unregisterRoot(id) {
1758
- const root = this.roots.get(id);
1759
- if (!root) return;
1760
- for (const jobId of root.jobs.keys()) {
1761
- this.jobStateListeners.delete(jobId);
1762
- }
1763
- this.roots.delete(id);
1764
- if (this.roots.size === 0) {
1765
- this.stop();
1766
- this.errorHandler = null;
1767
- }
1768
- }
1769
- /**
1770
- * Subscribe to be notified when a root becomes available.
1771
- * Fires immediately if a root already exists.
1772
- * @param {() => void} callback - Function called when first root registers
1773
- * @returns {() => void} Unsubscribe function
1774
- */
1775
- onRootReady(callback) {
1776
- if (this.roots.size > 0) {
1777
- callback();
1778
- return () => {
1779
- };
1780
- }
1781
- this.rootReadyCallbacks.add(callback);
1782
- return () => this.rootReadyCallbacks.delete(callback);
1783
- }
1784
- /**
1785
- * Notify all registered root-ready callbacks.
1786
- * Called when the first root registers.
1787
- * @returns {void}
1788
- * @private
1789
- */
1790
- notifyRootReady() {
1791
- for (const cb of this.rootReadyCallbacks) {
1792
- try {
1793
- cb();
1794
- } catch (error) {
1795
- console.error("[Scheduler] Error in root-ready callback:", error);
1796
- }
1797
- }
1798
- this.rootReadyCallbacks.clear();
1799
- }
1800
- /**
1801
- * Ensure a default root exists for independent mode.
1802
- * Creates a minimal root with no state provider.
1803
- * @returns {void}
1804
- * @private
1805
- */
1806
- ensureDefaultRoot() {
1807
- if (!this.roots.has("__default__")) {
1808
- this.registerRoot("__default__");
1809
- }
1810
- }
1811
- /**
1812
- * Trigger error handling for job errors.
1813
- * Uses the bound error handler if available, otherwise logs to console.
1814
- * @param {Error} error - The error to handle
1815
- * @returns {void}
1816
- */
1817
- triggerError(error) {
1818
- if (this.errorHandler) this.errorHandler(error);
1819
- else console.error("[Scheduler]", error);
1820
- }
1821
- //* Phase Management Methods ================================
1822
- /**
1823
- * Add a named phase to the scheduler's execution order.
1824
- * Marks all roots for rebuild to incorporate the new phase.
1825
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1826
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1827
- * @returns {void}
1828
- * @example
1829
- * scheduler.addPhase('physics', { before: 'update' });
1830
- * scheduler.addPhase('postprocess', { after: 'render' });
1831
- */
1832
- addPhase(name, options) {
1833
- this.phaseGraph.addPhase(name, options);
1834
- for (const root of this.roots.values()) {
1835
- root.needsRebuild = true;
1836
- }
1837
- }
1838
- /**
1839
- * Check if a phase exists in the scheduler.
1840
- * @param {string} name - The phase name to check
1841
- * @returns {boolean} True if the phase exists
1842
- */
1843
- hasPhase(name) {
1844
- return this.phaseGraph.hasPhase(name);
1845
- }
1846
- //* Global Job Registration Methods (Deprecated APIs) ================================
1847
- /**
1848
- * Register a global job that runs once per frame (not per-root).
1849
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1850
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1851
- * @param {string} id - Unique identifier for this global job
1852
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1853
- * @returns {() => void} Unsubscribe function to remove this global job
1854
- * @deprecated Use useFrame with phases instead
1855
- */
1856
- registerGlobal(phase, id, callback) {
1857
- const job = { id, callback };
1858
- if (phase === "before") {
1859
- this.globalBeforeJobs.set(id, job);
1860
- } else {
1861
- this.globalAfterJobs.set(id, job);
1862
- }
1863
- return () => {
1864
- if (phase === "before") this.globalBeforeJobs.delete(id);
1865
- else this.globalAfterJobs.delete(id);
1866
- };
1867
- }
1868
- //* Idle Callback Methods (Deprecated API) ================================
1869
- /**
1870
- * Register an idle callback that fires when the loop stops.
1871
- * Used internally by deprecated addTail API.
1872
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
1873
- * @returns {() => void} Unsubscribe function to remove this idle callback
1874
- * @deprecated Use demand mode with invalidate() instead
1875
- */
1876
- onIdle(callback) {
1877
- this.idleCallbacks.add(callback);
1878
- return () => this.idleCallbacks.delete(callback);
1879
- }
1880
- /**
1881
- * Notify all registered idle callbacks.
1882
- * Called when the loop stops in demand mode.
1883
- * @param {number} timestamp - The RAF timestamp when idle occurred
1884
- * @returns {void}
1885
- * @private
1886
- */
1887
- notifyIdle(timestamp) {
1888
- for (const cb of this.idleCallbacks) {
1889
- try {
1890
- cb(timestamp);
1891
- } catch (error) {
1892
- console.error("[Scheduler] Error in idle callback:", error);
1893
- }
1894
- }
1895
- }
1896
- //* Job Registration & Management Methods ================================
1897
- /**
1898
- * Register a job (frame callback) with a specific root.
1899
- * This is the core registration method used by useFrame internally.
1900
- * @param {FrameNextCallback} callback - The function to call each frame
1901
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
1902
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
1903
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
1904
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
1905
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
1906
- * @param {number} [options.fps] - FPS throttle limit
1907
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
1908
- * @param {boolean} [options.enabled] - Whether job is active (default true)
1909
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
1910
- * @returns {() => void} Unsubscribe function to remove this job
1911
- */
1912
- register(callback, options = {}) {
1913
- const rootId = options.rootId;
1914
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
1915
- if (!root) {
1916
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
1917
- return () => {
1918
- };
1919
- }
1920
- const id = options.id ?? this.generateJobId();
1921
- let phase = options.phase ?? "update";
1922
- if (!options.phase && (options.before || options.after)) {
1923
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
1924
- }
1925
- const before = this.normalizeConstraints(options.before);
1926
- const after = this.normalizeConstraints(options.after);
1927
- const job = {
1928
- id,
1929
- callback,
1930
- phase,
1931
- before,
1932
- after,
1933
- priority: options.priority ?? 0,
1934
- index: this.nextJobIndex++,
1935
- fps: options.fps,
1936
- drop: options.drop ?? true,
1937
- enabled: options.enabled ?? true,
1938
- system: options.system ?? false
1939
- };
1940
- if (root.jobs.has(id)) {
1941
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
1942
- }
1943
- root.jobs.set(id, job);
1944
- root.needsRebuild = true;
1945
- return () => this.unregister(id, root.id);
1946
- }
1947
- /**
1948
- * Unregister a job by its ID.
1949
- * Searches all roots if rootId is not provided.
1950
- * @param {string} id - The job ID to unregister
1951
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
1952
- * @returns {void}
1953
- */
1954
- unregister(id, rootId) {
1955
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
1956
- if (root?.jobs.delete(id)) {
1957
- root.needsRebuild = true;
1958
- this.jobStateListeners.delete(id);
1959
- }
1960
- }
1961
- /**
1962
- * Update a job's options dynamically.
1963
- * Searches all roots to find the job by ID.
1964
- * Phase/constraint changes trigger a rebuild of the sorted job list.
1965
- * @param {string} id - The job ID to update
1966
- * @param {Partial<JobOptions>} options - The options to update
1967
- * @returns {void}
1968
- */
1969
- updateJob(id, options) {
1970
- let job;
1971
- let root;
1972
- for (const r of this.roots.values()) {
1973
- job = r.jobs.get(id);
1974
- if (job) {
1975
- root = r;
1976
- break;
1977
- }
1978
- }
1979
- if (!job || !root) return;
1980
- if (options.priority !== void 0) job.priority = options.priority;
1981
- if (options.fps !== void 0) job.fps = options.fps;
1982
- if (options.drop !== void 0) job.drop = options.drop;
1983
- if (options.enabled !== void 0) {
1984
- const wasEnabled = job.enabled;
1985
- job.enabled = options.enabled;
1986
- if (!wasEnabled && job.enabled) resetJobTiming(job);
1987
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
1988
- }
1989
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
1990
- if (options.phase) job.phase = options.phase;
1991
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
1992
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
1993
- root.needsRebuild = true;
1994
- }
1995
- }
1996
- //* Job State Management Methods ================================
1997
- /**
1998
- * Check if a job is currently paused (disabled).
1999
- * @param {string} id - The job ID to check
2000
- * @returns {boolean} True if the job exists and is paused
2001
- */
2002
- isJobPaused(id) {
2003
- for (const root of this.roots.values()) {
2004
- const job = root.jobs.get(id);
2005
- if (job) return !job.enabled;
2006
- }
2007
- return false;
2008
- }
2009
- /**
2010
- * Subscribe to state changes for a specific job.
2011
- * Listener is called when job is paused or resumed.
2012
- * @param {string} id - The job ID to subscribe to
2013
- * @param {() => void} listener - Callback invoked on state changes
2014
- * @returns {() => void} Unsubscribe function
2015
- */
2016
- subscribeJobState(id, listener) {
2017
- if (!this.jobStateListeners.has(id)) {
2018
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2019
- }
2020
- this.jobStateListeners.get(id).add(listener);
2021
- return () => {
2022
- this.jobStateListeners.get(id)?.delete(listener);
2023
- if (this.jobStateListeners.get(id)?.size === 0) {
2024
- this.jobStateListeners.delete(id);
2025
- }
2026
- };
2027
- }
2028
- /**
2029
- * Notify all listeners that a job's state has changed.
2030
- * @param {string} id - The job ID that changed
2031
- * @returns {void}
2032
- * @private
2033
- */
2034
- notifyJobStateChange(id) {
2035
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2036
- }
2037
- /**
2038
- * Pause a job by ID (sets enabled=false).
2039
- * Notifies any subscribed state listeners.
2040
- * @param {string} id - The job ID to pause
2041
- * @returns {void}
2042
- */
2043
- pauseJob(id) {
2044
- this.updateJob(id, { enabled: false });
2045
- this.notifyJobStateChange(id);
2046
- }
2047
- /**
2048
- * Resume a paused job by ID (sets enabled=true).
2049
- * Resets job timing to prevent frame accumulation.
2050
- * Notifies any subscribed state listeners.
2051
- * @param {string} id - The job ID to resume
2052
- * @returns {void}
2053
- */
2054
- resumeJob(id) {
2055
- this.updateJob(id, { enabled: true });
2056
- this.notifyJobStateChange(id);
2057
- }
2058
- //* Frame Loop Control Methods ================================
2059
- /**
2060
- * Start the requestAnimationFrame loop.
2061
- * Resets timing state (elapsedTime, frameCount) on start.
2062
- * No-op if already running.
2063
- * @returns {void}
2064
- */
2065
- start() {
2066
- if (this.loopState.running) return;
2067
- const { elapsedTime, createdAt } = this.loopState;
2068
- let adjustedCreated = 0;
2069
- if (this.stoppedTime > 0) {
2070
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2071
- this.stoppedTime = 0;
2072
- }
2073
- Object.assign(this.loopState, {
2074
- running: true,
2075
- elapsedTime: elapsedTime ?? 0,
2076
- lastTime: performance.now(),
2077
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2078
- frameCount: 0,
2079
- rafHandle: requestAnimationFrame(this.loop)
2080
- });
2081
- }
2082
- /**
2083
- * Stop the requestAnimationFrame loop.
2084
- * Cancels any pending RAF callback.
2085
- * No-op if not running.
2086
- * @returns {void}
2087
- */
2088
- stop() {
2089
- if (!this.loopState.running) return;
2090
- this.loopState.running = false;
2091
- if (this.loopState.rafHandle !== null) {
2092
- cancelAnimationFrame(this.loopState.rafHandle);
2093
- this.loopState.rafHandle = null;
2094
- }
2095
- this.stoppedTime = performance.now();
2096
- }
2097
- /**
2098
- * Request frames to be rendered in demand mode.
2099
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2100
- * No-op if frameloop is not 'demand'.
2101
- * @param {number} [frames=1] - Number of frames to request
2102
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2103
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2104
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2105
- * @returns {void}
2106
- * @example
2107
- * // Request a single frame render
2108
- * scheduler.invalidate();
2109
- *
2110
- * @example
2111
- * // Request 5 frames (e.g., for animations)
2112
- * scheduler.invalidate(5);
2113
- *
2114
- * @example
2115
- * // Set pending frames to exactly 3 (don't stack with existing)
2116
- * scheduler.invalidate(3, false);
2117
- *
2118
- * @example
2119
- * // Add 2 more frames to existing pending count
2120
- * scheduler.invalidate(2, true);
2121
- */
2122
- invalidate(frames = 1, stackFrames = false) {
2123
- if (this._frameloop !== "demand") return;
2124
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2125
- this.pendingFrames = Math.min(60, baseFrames + frames);
2126
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2127
- }
2128
- /**
2129
- * Reset timing state for deterministic testing.
2130
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2131
- * @returns {void}
2132
- */
2133
- resetTiming() {
2134
- this.loopState.lastTime = null;
2135
- this.loopState.frameCount = 0;
2136
- this.loopState.elapsedTime = 0;
2137
- this.loopState.createdAt = performance.now();
2138
- }
2139
- //* Manual Stepping Methods ================================
2140
- /**
2141
- * Manually execute a single frame for all roots.
2142
- * Useful for frameloop='never' mode or testing scenarios.
2143
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2144
- * @returns {void}
2145
- * @example
2146
- * // Manual control mode
2147
- * scheduler.frameloop = 'never';
2148
- * scheduler.step(); // Execute one frame
2149
- */
2150
- step(timestamp) {
2151
- const now = timestamp ?? performance.now();
2152
- this.executeFrame(now);
2153
- }
2154
- /**
2155
- * Manually execute a single job by its ID.
2156
- * Useful for testing individual job callbacks in isolation.
2157
- * @param {string} id - The job ID to step
2158
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2159
- * @returns {void}
2160
- */
2161
- stepJob(id, timestamp) {
2162
- let job;
2163
- let root;
2164
- for (const r of this.roots.values()) {
2165
- job = r.jobs.get(id);
2166
- if (job) {
2167
- root = r;
2168
- break;
2169
- }
2170
- }
2171
- if (!job || !root) {
2172
- console.warn(`[Scheduler] Job "${id}" not found`);
2173
- return;
2174
- }
2175
- const now = timestamp ?? performance.now();
2176
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2177
- const delta = deltaMs / 1e3;
2178
- const elapsed = now - this.loopState.createdAt;
2179
- const providedState = root.getState?.() ?? {};
2180
- const frameState = {
2181
- ...providedState,
2182
- time: now,
2183
- delta,
2184
- elapsed,
2185
- frame: this.loopState.frameCount
2186
- };
2187
- try {
2188
- job.callback(frameState, delta);
2189
- } catch (error) {
2190
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2191
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2192
- }
2193
- }
2194
- /**
2195
- * Execute a single frame across all roots.
2196
- * Order: globalBefore → each root's jobs → globalAfter
2197
- * @param {number} timestamp - RAF timestamp in milliseconds
2198
- * @returns {void}
2199
- * @private
2200
- */
2201
- executeFrame(timestamp) {
2202
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2203
- const delta = deltaMs / 1e3;
2204
- this.loopState.lastTime = timestamp;
2205
- this.loopState.frameCount++;
2206
- this.loopState.elapsedTime += deltaMs;
2207
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2208
- for (const root of this.roots.values()) {
2209
- this.tickRoot(root, timestamp, delta);
2210
- }
2211
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2212
- }
2213
- /**
2214
- * Run all global jobs from a job map.
2215
- * Catches and logs errors without stopping execution.
2216
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2217
- * @param {number} timestamp - RAF timestamp in milliseconds
2218
- * @returns {void}
2219
- * @private
2220
- */
2221
- runGlobalJobs(jobs, timestamp) {
2222
- for (const job of jobs.values()) {
2223
- try {
2224
- job.callback(timestamp);
2225
- } catch (error) {
2226
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2227
- }
2228
- }
2229
- }
2230
- /**
2231
- * Execute all jobs for a single root in sorted order.
2232
- * Rebuilds sorted job list if needed, then dispatches each job.
2233
- * Errors are caught and propagated via triggerError.
2234
- * @param {RootEntry} root - The root entry to tick
2235
- * @param {number} timestamp - RAF timestamp in milliseconds
2236
- * @param {number} delta - Time since last frame in seconds
2237
- * @returns {void}
2238
- * @private
2239
- */
2240
- tickRoot(root, timestamp, delta) {
2241
- if (root.needsRebuild) {
2242
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2243
- root.needsRebuild = false;
2244
- }
2245
- const providedState = root.getState?.() ?? {};
2246
- const frameState = {
2247
- ...providedState,
2248
- time: timestamp,
2249
- delta,
2250
- elapsed: this.loopState.elapsedTime / 1e3,
2251
- // Convert ms to seconds
2252
- frame: this.loopState.frameCount
2253
- };
2254
- for (const job of root.sortedJobs) {
2255
- if (!shouldRun(job, timestamp)) continue;
2256
- try {
2257
- job.callback(frameState, delta);
2258
- } catch (error) {
2259
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2260
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2261
- }
2262
- }
2263
- }
2264
- //* Debug & Inspection Methods ================================
2265
- /**
2266
- * Get the total number of registered jobs across all roots.
2267
- * Includes both per-root jobs and global before/after jobs.
2268
- * @returns {number} Total job count
2269
- */
2270
- getJobCount() {
2271
- let count = 0;
2272
- for (const root of this.roots.values()) {
2273
- count += root.jobs.size;
2274
- }
2275
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2276
- }
2277
- /**
2278
- * Get all registered job IDs across all roots.
2279
- * Includes both per-root jobs and global before/after jobs.
2280
- * @returns {string[]} Array of all job IDs
2281
- */
2282
- getJobIds() {
2283
- const ids = [];
2284
- for (const root of this.roots.values()) {
2285
- ids.push(...root.jobs.keys());
2286
- }
2287
- ids.push(...this.globalBeforeJobs.keys());
2288
- ids.push(...this.globalAfterJobs.keys());
2289
- return ids;
2290
- }
2291
- /**
2292
- * Get the number of registered roots (Canvas instances).
2293
- * @returns {number} Number of registered roots
2294
- */
2295
- getRootCount() {
2296
- return this.roots.size;
2297
- }
2298
- /**
2299
- * Check if any user (non-system) jobs are registered in a specific phase.
2300
- * Used by the default render job to know if a user has taken over rendering.
2301
- *
2302
- * @param phase The phase to check
2303
- * @param rootId Optional root ID to check (checks all roots if not provided)
2304
- * @returns true if any user jobs exist in the phase
2305
- */
2306
- hasUserJobsInPhase(phase, rootId) {
2307
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2308
- return rootsToCheck.some((root) => {
2309
- if (!root) return false;
2310
- for (const job of root.jobs.values()) {
2311
- if (job.phase === phase && !job.system && job.enabled) return true;
2312
- }
2313
- return false;
2314
- });
2315
- }
2316
- //* Utility Methods ================================
2317
- /**
2318
- * Generate a unique root ID for automatic root registration.
2319
- * @returns {string} A unique root ID in the format 'root_N'
2320
- */
2321
- generateRootId() {
2322
- return `root_${this.nextRootIndex++}`;
2323
- }
2324
- /**
2325
- * Generate a unique job ID.
2326
- * @returns {string} A unique job ID in the format 'job_N'
2327
- * @private
2328
- */
2329
- generateJobId() {
2330
- return `job_${this.nextJobIndex}`;
2331
- }
2332
- /**
2333
- * Normalize before/after constraints to a Set.
2334
- * Handles undefined, single string, or array inputs.
2335
- * @param {string | string[] | undefined} value - The constraint value(s)
2336
- * @returns {Set<string>} Normalized Set of constraint strings
2337
- * @private
2338
- */
2339
- normalizeConstraints(value) {
2340
- if (!value) return /* @__PURE__ */ new Set();
2341
- if (Array.isArray(value)) return new Set(value);
2342
- return /* @__PURE__ */ new Set([value]);
2343
- }
2344
- };
2345
- //* Static State & Methods (Singleton Usage) ================================
2346
- //* Cross-Bundle Singleton Key ==============================
2347
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2348
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2349
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2350
- let Scheduler = _Scheduler;
2351
- const getScheduler = () => Scheduler.get();
2352
- if (hmrData) {
2353
- hmrData.accept?.();
2354
- }
2355
-
2356
2030
  function useFrame(callback, priorityOrOptions) {
2357
2031
  const store = React__namespace.useContext(context);
2358
2032
  const isInsideCanvas = store !== null;
2359
- const scheduler = getScheduler();
2033
+ const scheduler$1 = scheduler.getScheduler();
2360
2034
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2361
2035
  id: priorityOrOptions.id,
2362
2036
  phase: priorityOrOptions.phase,
@@ -2404,7 +2078,7 @@ function useFrame(callback, priorityOrOptions) {
2404
2078
  };
2405
2079
  callbackRef.current?.(mergedState, delta);
2406
2080
  };
2407
- const unregister = scheduler.register(wrappedCallback, {
2081
+ const unregister = scheduler$1.register(wrappedCallback, {
2408
2082
  id,
2409
2083
  rootId,
2410
2084
  ...options
@@ -2425,37 +2099,31 @@ function useFrame(callback, priorityOrOptions) {
2425
2099
  }
2426
2100
  };
2427
2101
  } else {
2428
- const registerOutside = () => {
2429
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2430
- };
2431
- if (scheduler.independent || scheduler.isReady) {
2432
- return registerOutside();
2433
- }
2434
- let unregisterJob = null;
2435
- const unsubReady = scheduler.onRootReady(() => {
2436
- unregisterJob = registerOutside();
2437
- });
2438
- return () => {
2439
- unsubReady();
2440
- unregisterJob?.();
2441
- };
2102
+ return scheduler$1.register(
2103
+ (state, delta) => {
2104
+ const frameState = state;
2105
+ if (!frameState.renderer) return;
2106
+ callbackRef.current?.(frameState, delta);
2107
+ },
2108
+ { id, ...options }
2109
+ );
2442
2110
  }
2443
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2111
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2444
2112
  const isPaused = React__namespace.useSyncExternalStore(
2445
2113
  // Subscribe function
2446
2114
  React__namespace.useCallback(
2447
2115
  (onStoreChange) => {
2448
- return getScheduler().subscribeJobState(id, onStoreChange);
2116
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
2449
2117
  },
2450
2118
  [id]
2451
2119
  ),
2452
2120
  // getSnapshot function
2453
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2121
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
2454
2122
  // getServerSnapshot function (SSR)
2455
2123
  React__namespace.useCallback(() => false, [])
2456
2124
  );
2457
2125
  const controls = React__namespace.useMemo(() => {
2458
- const scheduler2 = getScheduler();
2126
+ const scheduler2 = scheduler.getScheduler();
2459
2127
  return {
2460
2128
  /** The job's unique ID */
2461
2129
  id,
@@ -2470,7 +2138,7 @@ function useFrame(callback, priorityOrOptions) {
2470
2138
  * @param timestamp Optional timestamp (defaults to performance.now())
2471
2139
  */
2472
2140
  step: (timestamp) => {
2473
- getScheduler().stepJob(id, timestamp);
2141
+ scheduler.getScheduler().stepJob(id, timestamp);
2474
2142
  },
2475
2143
  /**
2476
2144
  * Manually step ALL jobs in the scheduler.
@@ -2478,20 +2146,20 @@ function useFrame(callback, priorityOrOptions) {
2478
2146
  * @param timestamp Optional timestamp (defaults to performance.now())
2479
2147
  */
2480
2148
  stepAll: (timestamp) => {
2481
- getScheduler().step(timestamp);
2149
+ scheduler.getScheduler().step(timestamp);
2482
2150
  },
2483
2151
  /**
2484
2152
  * Pause this job (set enabled=false).
2485
2153
  * Job remains registered but won't run.
2486
2154
  */
2487
2155
  pause: () => {
2488
- getScheduler().pauseJob(id);
2156
+ scheduler.getScheduler().pauseJob(id);
2489
2157
  },
2490
2158
  /**
2491
2159
  * Resume this job (set enabled=true).
2492
2160
  */
2493
2161
  resume: () => {
2494
- getScheduler().resumeJob(id);
2162
+ scheduler.getScheduler().resumeJob(id);
2495
2163
  },
2496
2164
  /**
2497
2165
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2529,22 +2197,29 @@ function buildFromCache(input, textureCache) {
2529
2197
  function useTexture(input, optionsOrOnLoad) {
2530
2198
  const renderer = useThree((state) => state.internal.actualRenderer);
2531
2199
  const store = useStore();
2532
- const textureCache = useThree((state) => state.textures);
2533
2200
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2534
- const { onLoad, cache = false } = options;
2201
+ const { onLoad, cache = true } = options;
2202
+ const onLoadRef = React.useRef(onLoad);
2203
+ onLoadRef.current = onLoad;
2204
+ const onLoadCalledForRef = React.useRef(null);
2535
2205
  const urls = React.useMemo(() => getUrls(input), [input]);
2536
2206
  const cachedResult = React.useMemo(() => {
2537
2207
  if (!cache) return null;
2538
- if (!allUrlsCached(urls, textureCache)) return null;
2539
- return buildFromCache(input, textureCache);
2540
- }, [cache, urls, textureCache, input]);
2208
+ const textures = store.getState().textures;
2209
+ if (!allUrlsCached(urls, textures)) return null;
2210
+ return buildFromCache(input, textures);
2211
+ }, [cache, urls, input, store]);
2541
2212
  const loadedTextures = useLoader(
2542
2213
  three.TextureLoader,
2543
2214
  IsObject(input) ? Object.values(input) : input
2544
2215
  );
2216
+ const inputKey = urls.join("\0");
2545
2217
  React.useLayoutEffect(() => {
2546
- if (!cachedResult) onLoad?.(loadedTextures);
2547
- }, [onLoad, cachedResult, loadedTextures]);
2218
+ if (cachedResult) return;
2219
+ if (onLoadCalledForRef.current === inputKey) return;
2220
+ onLoadCalledForRef.current = inputKey;
2221
+ onLoadRef.current?.(loadedTextures);
2222
+ }, [cachedResult, loadedTextures, inputKey]);
2548
2223
  React.useEffect(() => {
2549
2224
  if (cachedResult) return;
2550
2225
  if ("initTexture" in renderer) {
@@ -2577,8 +2252,6 @@ function useTexture(input, optionsOrOnLoad) {
2577
2252
  }, [input, loadedTextures, cachedResult]);
2578
2253
  React.useEffect(() => {
2579
2254
  if (!cache) return;
2580
- if (cachedResult) return;
2581
- const set = store.setState;
2582
2255
  const urlTextureMap = [];
2583
2256
  if (typeof input === "string") {
2584
2257
  urlTextureMap.push([input, mappedTextures]);
@@ -2592,18 +2265,32 @@ function useTexture(input, optionsOrOnLoad) {
2592
2265
  urlTextureMap.push([url, textureRecord[key]]);
2593
2266
  }
2594
2267
  }
2595
- set((state) => {
2596
- const newMap = new Map(state.textures);
2597
- let changed = false;
2268
+ store.setState((state) => {
2269
+ const refs = new Map(state._textureRefs);
2270
+ let textures = state.textures;
2271
+ let added = false;
2598
2272
  for (const [url, texture] of urlTextureMap) {
2599
- if (!newMap.has(url)) {
2600
- newMap.set(url, texture);
2601
- changed = true;
2273
+ if (!textures.has(url)) {
2274
+ if (!added) {
2275
+ textures = new Map(textures);
2276
+ added = true;
2277
+ }
2278
+ textures.set(url, texture);
2602
2279
  }
2280
+ refs.set(url, (refs.get(url) ?? 0) + 1);
2603
2281
  }
2604
- return changed ? { textures: newMap } : state;
2282
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2283
+ });
2284
+ return () => store.setState((state) => {
2285
+ const refs = new Map(state._textureRefs);
2286
+ for (const [url] of urlTextureMap) {
2287
+ const next = (refs.get(url) ?? 0) - 1;
2288
+ if (next <= 0) refs.delete(url);
2289
+ else refs.set(url, next);
2290
+ }
2291
+ return { _textureRefs: refs };
2605
2292
  });
2606
- }, [cache, input, mappedTextures, store, cachedResult]);
2293
+ }, [cache, input, mappedTextures, store]);
2607
2294
  return mappedTextures;
2608
2295
  }
2609
2296
  useTexture.preload = (url) => useLoader.preload(three.TextureLoader, url);
@@ -2619,106 +2306,90 @@ const Texture = ({
2619
2306
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
2620
2307
  };
2621
2308
 
2622
- function getTextureValue(entry) {
2623
- if (entry instanceof three.Texture) return entry;
2624
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof three.Texture) {
2625
- return entry.value;
2626
- }
2627
- return null;
2628
- }
2629
- function useTextures() {
2309
+ function useTextures(selector) {
2630
2310
  const store = useStore();
2631
- return React.useMemo(() => {
2632
- const set = store.setState;
2311
+ const registry = React.useMemo(() => {
2633
2312
  const getState = store.getState;
2634
- const add = (key, value) => {
2635
- set((state) => {
2636
- const newMap = new Map(state.textures);
2637
- newMap.set(key, value);
2638
- return { textures: newMap };
2639
- });
2640
- };
2641
- const addMultiple = (items) => {
2642
- set((state) => {
2643
- const newMap = new Map(state.textures);
2644
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
2645
- for (const [key, value] of entries) {
2646
- newMap.set(key, value);
2647
- }
2648
- return { textures: newMap };
2649
- });
2650
- };
2651
- const remove = (key) => {
2652
- set((state) => {
2653
- const newMap = new Map(state.textures);
2654
- newMap.delete(key);
2655
- return { textures: newMap };
2656
- });
2657
- };
2658
- const removeMultiple = (keys) => {
2659
- set((state) => {
2660
- const newMap = new Map(state.textures);
2661
- for (const key of keys) newMap.delete(key);
2662
- return { textures: newMap };
2663
- });
2664
- };
2665
- const dispose = (key) => {
2666
- const entry = getState().textures.get(key);
2667
- if (entry) {
2668
- const tex = getTextureValue(entry);
2669
- tex?.dispose();
2670
- }
2671
- remove(key);
2672
- };
2673
- const disposeMultiple = (keys) => {
2674
- const textures = getState().textures;
2675
- for (const key of keys) {
2676
- const entry = textures.get(key);
2677
- if (entry) {
2678
- const tex = getTextureValue(entry);
2679
- tex?.dispose();
2680
- }
2681
- }
2682
- removeMultiple(keys);
2683
- };
2684
- const disposeAll = () => {
2685
- const textures = getState().textures;
2686
- for (const entry of textures.values()) {
2687
- const tex = getTextureValue(entry);
2688
- tex?.dispose();
2689
- }
2690
- set({ textures: /* @__PURE__ */ new Map() });
2691
- };
2313
+ const setState = store.setState;
2314
+ const getOne = (key) => getState().textures.get(key);
2692
2315
  return {
2693
- // Getter for the textures Map (reactive via getState)
2694
- get textures() {
2316
+ get all() {
2695
2317
  return getState().textures;
2696
2318
  },
2697
- // Read
2698
- get: (key) => getState().textures.get(key),
2319
+ get(input) {
2320
+ if (typeof input === "string") return getOne(input);
2321
+ if (Array.isArray(input)) return input.map(getOne);
2322
+ const out = {};
2323
+ for (const name in input) out[name] = getOne(input[name]);
2324
+ return out;
2325
+ },
2699
2326
  has: (key) => getState().textures.has(key),
2700
- // Write
2701
- add,
2702
- addMultiple,
2703
- // Remove (cache only)
2704
- remove,
2705
- removeMultiple,
2706
- // Dispose (GPU + cache)
2707
- dispose,
2708
- disposeMultiple,
2709
- disposeAll
2327
+ add(keyOrRecord, texture) {
2328
+ setState((state) => {
2329
+ const textures = new Map(state.textures);
2330
+ if (typeof keyOrRecord === "string") {
2331
+ textures.set(keyOrRecord, texture);
2332
+ } else {
2333
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2334
+ }
2335
+ return { textures };
2336
+ });
2337
+ },
2338
+ dispose(key, options) {
2339
+ const state = getState();
2340
+ const refs = state._textureRefs.get(key) ?? 0;
2341
+ if (refs > 0 && !options?.force) {
2342
+ console.warn(
2343
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2344
+ );
2345
+ return false;
2346
+ }
2347
+ state.textures.get(key)?.dispose();
2348
+ setState((s) => {
2349
+ const textures = new Map(s.textures);
2350
+ textures.delete(key);
2351
+ const nextRefs = new Map(s._textureRefs);
2352
+ nextRefs.delete(key);
2353
+ return { textures, _textureRefs: nextRefs };
2354
+ });
2355
+ return true;
2356
+ },
2357
+ disposeAll() {
2358
+ for (const texture of getState().textures.values()) texture.dispose();
2359
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2360
+ }
2710
2361
  };
2711
2362
  }, [store]);
2363
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2364
+ const selected = useThree(subscribe);
2365
+ return selector ? selected : registry;
2712
2366
  }
2713
2367
 
2714
- function useRenderTarget(width, height, options) {
2368
+ function useRenderTarget(widthOrOptions, heightOrOptions, options) {
2715
2369
  const isLegacy = useThree((s) => s.isLegacy);
2716
2370
  const size = useThree((s) => s.size);
2371
+ let width;
2372
+ let height;
2373
+ let opts;
2374
+ if (typeof widthOrOptions === "object") {
2375
+ opts = widthOrOptions;
2376
+ } else if (typeof widthOrOptions === "number") {
2377
+ width = widthOrOptions;
2378
+ if (typeof heightOrOptions === "object") {
2379
+ height = widthOrOptions;
2380
+ opts = heightOrOptions;
2381
+ } else if (typeof heightOrOptions === "number") {
2382
+ height = heightOrOptions;
2383
+ opts = options;
2384
+ } else {
2385
+ height = widthOrOptions;
2386
+ }
2387
+ }
2717
2388
  return React.useMemo(() => {
2718
2389
  const w = width ?? size.width;
2719
2390
  const h = height ?? size.height;
2720
- return new three.WebGLRenderTarget(w, h, options);
2721
- }, [width, height, size.width, size.height, options, isLegacy]);
2391
+ return new three.WebGLRenderTarget(w, h, opts);
2392
+ }, [width, height, size.width, size.height, opts, isLegacy]);
2722
2393
  }
2723
2394
 
2724
2395
  function useStore() {
@@ -2746,7 +2417,7 @@ function addEffect(callback) {
2746
2417
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2747
2418
  });
2748
2419
  const id = `legacy_effect_${effectId++}`;
2749
- return getScheduler().registerGlobal("before", id, callback);
2420
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
2750
2421
  }
2751
2422
  function addAfterEffect(callback) {
2752
2423
  notifyDepreciated({
@@ -2755,7 +2426,7 @@ function addAfterEffect(callback) {
2755
2426
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2756
2427
  });
2757
2428
  const id = `legacy_afterEffect_${effectId++}`;
2758
- return getScheduler().registerGlobal("after", id, callback);
2429
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
2759
2430
  }
2760
2431
  function addTail(callback) {
2761
2432
  notifyDepreciated({
@@ -2763,33 +2434,23 @@ function addTail(callback) {
2763
2434
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
2764
2435
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2765
2436
  });
2766
- return getScheduler().onIdle(callback);
2437
+ return scheduler.getScheduler().onIdle(callback);
2767
2438
  }
2768
2439
  function invalidate(state, frames = 1, stackFrames = false) {
2769
- getScheduler().invalidate(frames, stackFrames);
2440
+ scheduler.getScheduler().invalidate(frames, stackFrames);
2770
2441
  }
2771
- function advance(timestamp, runGlobalEffects = true, state, frame) {
2772
- getScheduler().step(timestamp);
2442
+ function advance(timestamp) {
2443
+ scheduler.getScheduler().step(timestamp);
2773
2444
  }
2774
2445
 
2775
- const version = "10.0.0-alpha.1";
2446
+ const version = "10.0.0-alpha.3";
2776
2447
  const packageData = {
2777
2448
  version: version};
2778
2449
 
2779
2450
  function Xb(Tt) {
2780
2451
  return Tt && Tt.__esModule && Object.prototype.hasOwnProperty.call(Tt, "default") ? Tt.default : Tt;
2781
2452
  }
2782
- var Rm = { exports: {} }, Og = { exports: {} };
2783
- /**
2784
- * @license React
2785
- * react-reconciler.production.js
2786
- *
2787
- * Copyright (c) Meta Platforms, Inc. and affiliates.
2788
- *
2789
- * This source code is licensed under the MIT license found in the
2790
- * LICENSE file in the root directory of this source tree.
2791
- */
2792
- var _b;
2453
+ var Rm = { exports: {} }, Og = { exports: {} }, _b;
2793
2454
  function Kb() {
2794
2455
  return _b || (_b = 1, (function(Tt) {
2795
2456
  Tt.exports = function(m) {
@@ -3861,7 +3522,6 @@ Error generating stack: ` + l.message + `
3861
3522
  if (J === cl || J === jc) throw J;
3862
3523
  var Ge = Yn(29, J, null, P.mode);
3863
3524
  return Ge.lanes = H, Ge.return = P, Ge;
3864
- } finally {
3865
3525
  }
3866
3526
  };
3867
3527
  }
@@ -4515,7 +4175,6 @@ Error generating stack: ` + l.message + `
4515
4175
  var h = r.lastRenderedState, y = d(h, a);
4516
4176
  if (c.hasEagerState = true, c.eagerState = y, jn(y, h)) return go(t, r, c, 0), Ne === null && Bn(), false;
4517
4177
  } catch {
4518
- } finally {
4519
4178
  }
4520
4179
  if (a = yo(t, r, c, l), a !== null) return nt(a, t, l), ns(a, r, l), true;
4521
4180
  }
@@ -6936,10 +6595,7 @@ Error generating stack: ` + l.message + `
6936
6595
  function vr(t, r) {
6937
6596
  Sf(t, r), (t = t.alternate) && Sf(t, r);
6938
6597
  }
6939
- var ie = {}, Fm = React__default, tt = Tb__default, Lt = Object.assign, hc = Symbol.for("react.element"), zs = Symbol.for("react.transitional.element"), sa = Symbol.for("react.portal"), $a = Symbol.for("react.fragment"), kf = Symbol.for("react.strict_mode"), Cs = Symbol.for("react.profiler"), mc = Symbol.for("react.consumer"), Io = Symbol.for("react.context"), Zi = Symbol.for("react.forward_ref"), Va = Symbol.for("react.suspense"), Te = Symbol.for("react.suspense_list"), wf = Symbol.for("react.memo"), ua = Symbol.for("react.lazy");
6940
- var gc = Symbol.for("react.activity");
6941
- var $r = Symbol.for("react.memo_cache_sentinel");
6942
- var Pf = Symbol.iterator, xf = Symbol.for("react.client.reference"), ca = Array.isArray, M = Fm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Yp = m.rendererVersion, zf = m.rendererPackageName, Cf = m.extraDevToolsConfig, Ts = m.getPublicInstance, Hm = m.getRootHostContext, Xp = m.getChildHostContext, Am = m.prepareForCommit, _s = m.resetAfterCommit, Vr = m.createInstance;
6598
+ var ie = {}, Fm = React__default, tt = Tb__default, Lt = Object.assign, hc = Symbol.for("react.element"), zs = Symbol.for("react.transitional.element"), sa = Symbol.for("react.portal"), $a = Symbol.for("react.fragment"), kf = Symbol.for("react.strict_mode"), Cs = Symbol.for("react.profiler"), mc = Symbol.for("react.consumer"), Io = Symbol.for("react.context"), Zi = Symbol.for("react.forward_ref"), Va = Symbol.for("react.suspense"), Te = Symbol.for("react.suspense_list"), wf = Symbol.for("react.memo"), ua = Symbol.for("react.lazy"), gc = Symbol.for("react.activity"), $r = Symbol.for("react.memo_cache_sentinel"), Pf = Symbol.iterator, xf = Symbol.for("react.client.reference"), ca = Array.isArray, M = Fm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Yp = m.rendererVersion, zf = m.rendererPackageName, Cf = m.extraDevToolsConfig, Ts = m.getPublicInstance, Hm = m.getRootHostContext, Xp = m.getChildHostContext, Am = m.prepareForCommit, _s = m.resetAfterCommit, Vr = m.createInstance;
6943
6599
  m.cloneMutableInstance;
6944
6600
  var yc = m.appendInitialChild, Kp = m.finalizeInitialChildren, Rs = m.shouldSetTextContent, bc = m.createTextInstance;
6945
6601
  m.cloneMutableTextInstance;
@@ -7308,17 +6964,7 @@ No matching component was found for:
7308
6964
  }, Tt.exports.default = Tt.exports, Object.defineProperty(Tt.exports, "__esModule", { value: true });
7309
6965
  })(Og)), Og.exports;
7310
6966
  }
7311
- var Mg = { exports: {} };
7312
- /**
7313
- * @license React
7314
- * react-reconciler.development.js
7315
- *
7316
- * Copyright (c) Meta Platforms, Inc. and affiliates.
7317
- *
7318
- * This source code is licensed under the MIT license found in the
7319
- * LICENSE file in the root directory of this source tree.
7320
- */
7321
- var Rb;
6967
+ var Mg = { exports: {} }, Rb;
7322
6968
  function e0() {
7323
6969
  return Rb || (Rb = 1, (function(Tt) {
7324
6970
  process.env.NODE_ENV !== "production" && (Tt.exports = function(m) {
@@ -13085,10 +12731,7 @@ Check the render method of %s.`, G(di) || "Unknown")), i = zo(n), i.payload = {
13085
12731
  function Ic() {
13086
12732
  return di;
13087
12733
  }
13088
- var le = {}, qm = React__default, St = Tb__default, ze = Object.assign, Uh = Symbol.for("react.element"), Ho = Symbol.for("react.transitional.element"), Ao = Symbol.for("react.portal"), ol = Symbol.for("react.fragment"), Lc = Symbol.for("react.strict_mode"), Uf = Symbol.for("react.profiler"), ei = Symbol.for("react.consumer"), on = Symbol.for("react.context"), jn = Symbol.for("react.forward_ref"), Nc = Symbol.for("react.suspense"), Bf = Symbol.for("react.suspense_list"), al = Symbol.for("react.memo"), kt = Symbol.for("react.lazy");
13089
- var Ds = Symbol.for("react.activity");
13090
- var Bh = Symbol.for("react.memo_cache_sentinel");
13091
- var ni = Symbol.iterator, il = Symbol.for("react.client.reference"), fn = Array.isArray, x = qm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Jt = m.rendererVersion, Zt = m.rendererPackageName, jo = m.extraDevToolsConfig, ot = m.getPublicInstance, Zr = m.getRootHostContext, Dn = m.getChildHostContext, Ws = m.prepareForCommit, pa = m.resetAfterCommit, Fc = m.createInstance;
12734
+ var le = {}, qm = React__default, St = Tb__default, ze = Object.assign, Uh = Symbol.for("react.element"), Ho = Symbol.for("react.transitional.element"), Ao = Symbol.for("react.portal"), ol = Symbol.for("react.fragment"), Lc = Symbol.for("react.strict_mode"), Uf = Symbol.for("react.profiler"), ei = Symbol.for("react.consumer"), on = Symbol.for("react.context"), jn = Symbol.for("react.forward_ref"), Nc = Symbol.for("react.suspense"), Bf = Symbol.for("react.suspense_list"), al = Symbol.for("react.memo"), kt = Symbol.for("react.lazy"), Ds = Symbol.for("react.activity"), Bh = Symbol.for("react.memo_cache_sentinel"), ni = Symbol.iterator, il = Symbol.for("react.client.reference"), fn = Array.isArray, x = qm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Jt = m.rendererVersion, Zt = m.rendererPackageName, jo = m.extraDevToolsConfig, ot = m.getPublicInstance, Zr = m.getRootHostContext, Dn = m.getChildHostContext, Ws = m.prepareForCommit, pa = m.resetAfterCommit, Fc = m.createInstance;
13092
12735
  m.cloneMutableInstance;
13093
12736
  var bn = m.appendInitialChild, Ue = m.finalizeInitialChildren, ue = m.shouldSetTextContent, Do = m.createTextInstance;
13094
12737
  m.cloneMutableTextInstance;
@@ -14056,15 +13699,6 @@ function n0() {
14056
13699
  var t0 = n0();
14057
13700
  const r0 = Xb(t0);
14058
13701
 
14059
- /**
14060
- * @license React
14061
- * react-reconciler-constants.production.js
14062
- *
14063
- * Copyright (c) Meta Platforms, Inc. and affiliates.
14064
- *
14065
- * This source code is licensed under the MIT license found in the
14066
- * LICENSE file in the root directory of this source tree.
14067
- */
14068
13702
  const t = 1, o = 8, r = 32, e = 2;
14069
13703
 
14070
13704
  function createReconciler(config) {
@@ -14091,10 +13725,11 @@ function extend(objects) {
14091
13725
  function validateInstance(type, props) {
14092
13726
  const name = toPascalCase(type);
14093
13727
  const target = catalogue[name];
14094
- if (type !== "primitive" && !target)
13728
+ if (type !== "primitive" && !target) {
14095
13729
  throw new Error(
14096
13730
  `R3F: ${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`
14097
13731
  );
13732
+ }
14098
13733
  if (type === "primitive" && !props.object) throw new Error(`R3F: Primitives without 'object' are invalid!`);
14099
13734
  if (props.args !== void 0 && !Array.isArray(props.args)) throw new Error("R3F: The args prop must be an array!");
14100
13735
  }
@@ -14247,6 +13882,7 @@ function swapInstances() {
14247
13882
  }
14248
13883
  }
14249
13884
  if (instance.isHidden) unhideInstance(instance);
13885
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14250
13886
  if (instance.object.__r3f) delete instance.object.__r3f;
14251
13887
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14252
13888
  }
@@ -14258,6 +13894,9 @@ function swapInstances() {
14258
13894
  instance.object = instance.props.object ?? new target(...instance.props.args ?? []);
14259
13895
  instance.object.__r3f = instance;
14260
13896
  setFiberRef(fiber, instance.object);
13897
+ delete instance.appliedOnce;
13898
+ instance.eventCount = 0;
13899
+ instance.handlers = {};
14261
13900
  applyProps(instance.object, instance.props);
14262
13901
  if (instance.props.attach) {
14263
13902
  attach(parent, instance);
@@ -14331,8 +13970,22 @@ const reconciler = /* @__PURE__ */ createReconciler({
14331
13970
  const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14332
13971
  if (isTailSibling) swapInstances();
14333
13972
  },
14334
- finalizeInitialChildren: () => false,
14335
- commitMount() {
13973
+ finalizeInitialChildren: (instance) => {
13974
+ for (const prop in instance.props) {
13975
+ if (isFromRef(instance.props[prop])) return true;
13976
+ }
13977
+ return false;
13978
+ },
13979
+ commitMount(instance) {
13980
+ const resolved = {};
13981
+ for (const prop in instance.props) {
13982
+ const value = instance.props[prop];
13983
+ if (isFromRef(value)) {
13984
+ const ref = value[FROM_REF];
13985
+ if (ref.current != null) resolved[prop] = ref.current;
13986
+ }
13987
+ }
13988
+ if (Object.keys(resolved).length) applyProps(instance.object, resolved);
14336
13989
  },
14337
13990
  getPublicInstance: (instance) => instance?.object,
14338
13991
  prepareForCommit: () => null,
@@ -14459,11 +14112,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14459
14112
  cloneMutableTextInstance(textInstance) {
14460
14113
  return textInstance;
14461
14114
  },
14115
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14116
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14117
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14118
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14119
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14120
+ // Guarded by a test asserting a full render + unmount never reaches them.
14462
14121
  cloneRootViewTransitionContainer(_rootContainer) {
14463
- throw new Error("Not implemented.");
14464
14122
  },
14465
14123
  removeRootViewTransitionClone(_rootContainer, _clone) {
14466
- throw new Error("Not implemented.");
14467
14124
  },
14468
14125
  // https://github.com/facebook/react/pull/32465
14469
14126
  createFragmentInstance: (_fiber) => null,
@@ -14545,14 +14202,18 @@ function createRoot(canvas) {
14545
14202
  if (!prevRoot) _roots.set(canvas, { fiber, store });
14546
14203
  let onCreated;
14547
14204
  let lastCamera;
14548
- let lastConfiguredProps = {};
14205
+ const lastConfiguredProps = {};
14549
14206
  let configured = false;
14550
14207
  let pending = null;
14208
+ let rendererSetup = null;
14551
14209
  return {
14552
14210
  async configure(props = {}) {
14553
14211
  let resolve;
14554
14212
  pending = new Promise((_resolve) => resolve = _resolve);
14555
- let {
14213
+ const {
14214
+ id: canvasId,
14215
+ primaryCanvas,
14216
+ scheduler: schedulerConfig,
14556
14217
  gl: glConfig,
14557
14218
  renderer: rendererConfig,
14558
14219
  size: propsSize,
@@ -14560,10 +14221,6 @@ function createRoot(canvas) {
14560
14221
  events,
14561
14222
  onCreated: onCreatedCallback,
14562
14223
  shadows = false,
14563
- linear = false,
14564
- flat = false,
14565
- textureColorSpace = three.SRGBColorSpace,
14566
- legacy = false,
14567
14224
  orthographic = false,
14568
14225
  frameloop = "always",
14569
14226
  dpr = [1, 2],
@@ -14574,8 +14231,11 @@ function createRoot(canvas) {
14574
14231
  onDragOverMissed,
14575
14232
  onDropMissed,
14576
14233
  autoUpdateFrustum = true,
14577
- occlusion = false
14234
+ occlusion = false,
14235
+ _sizeProps,
14236
+ forceEven
14578
14237
  } = props;
14238
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || three.SRGBColorSpace;
14579
14239
  let state = store.getState();
14580
14240
  const defaultGLProps = {
14581
14241
  canvas,
@@ -14588,22 +14248,46 @@ function createRoot(canvas) {
14588
14248
  "WebGPURenderer (renderer prop) is not available in this build. Use @react-three/fiber or @react-three/fiber/webgpu instead."
14589
14249
  );
14590
14250
  }
14591
- (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
14251
+ const wantsGL = (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
14592
14252
  if (glConfig && rendererConfig) {
14593
14253
  throw new Error("Cannot use both gl and renderer props at the same time");
14594
14254
  }
14595
14255
  let renderer = state.internal.actualRenderer;
14256
+ if (primaryCanvas && !R3F_BUILD_WEBGPU) {
14257
+ throw new Error(
14258
+ "The `primaryCanvas` prop for multi-canvas rendering is only available with WebGPU. Use @react-three/fiber/webgpu instead."
14259
+ );
14260
+ }
14261
+ if (primaryCanvas && wantsGL) {
14262
+ throw new Error(
14263
+ "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
14264
+ );
14265
+ }
14596
14266
  if (!state.internal.actualRenderer) {
14597
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14598
- state.internal.actualRenderer = renderer;
14599
- state.set({ isLegacy: true, gl: renderer, renderer });
14267
+ if (!rendererSetup) {
14268
+ rendererSetup = (async () => {
14269
+ {
14270
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14271
+ state.internal.actualRenderer = renderer;
14272
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14273
+ }
14274
+ })().catch((err) => {
14275
+ rendererSetup = null;
14276
+ throw err;
14277
+ });
14278
+ }
14279
+ await rendererSetup;
14280
+ state = store.getState();
14281
+ renderer = state.internal.actualRenderer;
14600
14282
  }
14601
14283
  let raycaster = state.raycaster;
14602
14284
  if (!raycaster) state.set({ raycaster: raycaster = new three.Raycaster() });
14603
14285
  const { params, ...options } = raycastOptions || {};
14604
14286
  if (!is.equ(options, raycaster, shallowLoose)) applyProps(raycaster, { ...options });
14605
- if (!is.equ(params, raycaster.params, shallowLoose))
14287
+ if (!is.equ(params, raycaster.params, shallowLoose)) {
14606
14288
  applyProps(raycaster, { params: { ...raycaster.params, ...params } });
14289
+ }
14290
+ let tempCamera = state.camera;
14607
14291
  if (!state.camera || state.camera === lastCamera && !is.equ(lastCamera, cameraOptions, shallowLoose)) {
14608
14292
  lastCamera = cameraOptions;
14609
14293
  const isCamera = cameraOptions?.isCamera;
@@ -14623,6 +14307,7 @@ function createRoot(canvas) {
14623
14307
  if (!state.camera && !cameraOptions?.rotation) camera.lookAt(0, 0, 0);
14624
14308
  }
14625
14309
  state.set({ camera });
14310
+ tempCamera = camera;
14626
14311
  raycaster.camera = camera;
14627
14312
  }
14628
14313
  if (!state.scene) {
@@ -14640,7 +14325,7 @@ function createRoot(canvas) {
14640
14325
  rootScene: scene,
14641
14326
  internal: { ...prev.internal, container: scene }
14642
14327
  }));
14643
- const camera = state.camera;
14328
+ const camera = tempCamera;
14644
14329
  if (camera && !camera.parent) scene.add(camera);
14645
14330
  }
14646
14331
  if (events && !state.events.handlers) {
@@ -14654,9 +14339,17 @@ function createRoot(canvas) {
14654
14339
  wasEnabled = enabled;
14655
14340
  });
14656
14341
  }
14342
+ if (_sizeProps !== void 0) {
14343
+ state.set({ _sizeProps });
14344
+ }
14345
+ if (forceEven !== void 0 && state.internal.forceEven !== forceEven) {
14346
+ state.set((prev) => ({ internal: { ...prev.internal, forceEven } }));
14347
+ }
14657
14348
  const size = computeInitialSize(canvas, propsSize);
14658
- if (!is.equ(size, state.size, shallowLoose)) {
14349
+ if (!state._sizeImperative && !is.equ(size, state.size, shallowLoose)) {
14350
+ const wasImperative = state._sizeImperative;
14659
14351
  state.setSize(size.width, size.height, size.top, size.left);
14352
+ if (!wasImperative) state.set({ _sizeImperative: false });
14660
14353
  }
14661
14354
  if (dpr !== void 0 && !is.equ(dpr, lastConfiguredProps.dpr, shallowLoose)) {
14662
14355
  state.setDpr(dpr);
@@ -14678,10 +14371,10 @@ function createRoot(canvas) {
14678
14371
  lastConfiguredProps.performance = performance;
14679
14372
  }
14680
14373
  if (!state.xr) {
14681
- const handleXRFrame = (timestamp, frame) => {
14374
+ const handleXRFrame = (timestamp, _frame) => {
14682
14375
  const state2 = store.getState();
14683
14376
  if (state2.frameloop === "never") return;
14684
- advance(timestamp, true);
14377
+ advance(timestamp);
14685
14378
  };
14686
14379
  const actualRenderer = state.internal.actualRenderer;
14687
14380
  const handleSessionChange = () => {
@@ -14693,16 +14386,16 @@ function createRoot(canvas) {
14693
14386
  };
14694
14387
  const xr = {
14695
14388
  connect() {
14696
- const { gl, renderer: renderer2, isLegacy } = store.getState();
14697
- const actualRenderer2 = renderer2 || gl;
14698
- actualRenderer2.xr.addEventListener("sessionstart", handleSessionChange);
14699
- actualRenderer2.xr.addEventListener("sessionend", handleSessionChange);
14389
+ const { gl, renderer: renderer2 } = store.getState();
14390
+ const xrManager = (renderer2 || gl).xr;
14391
+ xrManager.addEventListener("sessionstart", handleSessionChange);
14392
+ xrManager.addEventListener("sessionend", handleSessionChange);
14700
14393
  },
14701
14394
  disconnect() {
14702
- const { gl, renderer: renderer2, isLegacy } = store.getState();
14703
- const actualRenderer2 = renderer2 || gl;
14704
- actualRenderer2.xr.removeEventListener("sessionstart", handleSessionChange);
14705
- actualRenderer2.xr.removeEventListener("sessionend", handleSessionChange);
14395
+ const { gl, renderer: renderer2 } = store.getState();
14396
+ const xrManager = (renderer2 || gl).xr;
14397
+ xrManager.removeEventListener("sessionstart", handleSessionChange);
14398
+ xrManager.removeEventListener("sessionend", handleSessionChange);
14706
14399
  }
14707
14400
  };
14708
14401
  if (typeof renderer.xr?.addEventListener === "function") xr.connect();
@@ -14714,62 +14407,93 @@ function createRoot(canvas) {
14714
14407
  const oldType = renderer.shadowMap.type;
14715
14408
  renderer.shadowMap.enabled = !!shadows;
14716
14409
  if (is.boo(shadows)) {
14717
- renderer.shadowMap.type = three.PCFSoftShadowMap;
14410
+ renderer.shadowMap.type = three.PCFShadowMap;
14718
14411
  } else if (is.str(shadows)) {
14412
+ if (shadows === "soft") {
14413
+ notifyDepreciated({
14414
+ heading: 'shadows="soft" is deprecated',
14415
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14416
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14417
+ });
14418
+ }
14719
14419
  const types = {
14720
14420
  basic: three.BasicShadowMap,
14721
14421
  percentage: three.PCFShadowMap,
14722
- soft: three.PCFSoftShadowMap,
14422
+ soft: three.PCFShadowMap,
14723
14423
  variance: three.VSMShadowMap
14724
14424
  };
14725
- renderer.shadowMap.type = types[shadows] ?? three.PCFSoftShadowMap;
14425
+ renderer.shadowMap.type = types[shadows] ?? three.PCFShadowMap;
14726
14426
  } else if (is.obj(shadows)) {
14727
14427
  Object.assign(renderer.shadowMap, shadows);
14728
14428
  }
14729
- if (oldEnabled !== renderer.shadowMap.enabled || oldType !== renderer.shadowMap.type)
14429
+ if (oldEnabled !== renderer.shadowMap.enabled || oldType !== renderer.shadowMap.type) {
14730
14430
  renderer.shadowMap.needsUpdate = true;
14731
- }
14732
- {
14733
- const legacyChanged = legacy !== lastConfiguredProps.legacy;
14734
- const linearChanged = linear !== lastConfiguredProps.linear;
14735
- const flatChanged = flat !== lastConfiguredProps.flat;
14736
- if (legacyChanged) {
14737
- three.ColorManagement.enabled = !legacy;
14738
- lastConfiguredProps.legacy = legacy;
14739
14431
  }
14740
- if (!configured || linearChanged) {
14741
- renderer.outputColorSpace = linear ? three.LinearSRGBColorSpace : three.SRGBColorSpace;
14742
- lastConfiguredProps.linear = linear;
14743
- }
14744
- if (!configured || flatChanged) {
14745
- renderer.toneMapping = flat ? three.NoToneMapping : three.ACESFilmicToneMapping;
14746
- lastConfiguredProps.flat = flat;
14747
- }
14748
- if (legacyChanged && state.legacy !== legacy) state.set(() => ({ legacy }));
14749
- if (linearChanged && state.linear !== linear) state.set(() => ({ linear }));
14750
- if (flatChanged && state.flat !== flat) state.set(() => ({ flat }));
14432
+ }
14433
+ if (!configured) {
14434
+ renderer.outputColorSpace = three.SRGBColorSpace;
14435
+ renderer.toneMapping = three.ACESFilmicToneMapping;
14751
14436
  }
14752
14437
  if (textureColorSpace !== lastConfiguredProps.textureColorSpace) {
14753
14438
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
14754
14439
  lastConfiguredProps.textureColorSpace = textureColorSpace;
14755
14440
  }
14756
- if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose))
14757
- applyProps(renderer, glConfig);
14441
+ const r3fProps = ["textureColorSpace"];
14442
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14443
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
14444
+ if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
14445
+ const glProps = {};
14446
+ for (const key in glConfig) {
14447
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14448
+ }
14449
+ applyProps(renderer, glProps);
14450
+ }
14758
14451
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
14759
14452
  const currentRenderer = state.renderer;
14760
14453
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
14761
- applyProps(currentRenderer, rendererConfig);
14454
+ const rendererProps = {};
14455
+ for (const key in rendererConfig) {
14456
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14457
+ }
14458
+ applyProps(currentRenderer, rendererProps);
14762
14459
  }
14763
14460
  }
14764
- const scheduler = getScheduler();
14461
+ const scheduler$1 = scheduler.getScheduler();
14765
14462
  const rootId = state.internal.rootId;
14766
14463
  if (!rootId) {
14767
- const newRootId = scheduler.generateRootId();
14768
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14464
+ const newRootId = canvasId || scheduler$1.generateRootId();
14465
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
14769
14466
  getState: () => store.getState(),
14770
14467
  onError: (err) => store.getState().setError(err)
14771
14468
  });
14772
- const unregisterFrustum = scheduler.register(
14469
+ const unregisterCanvasTarget = scheduler$1.register(
14470
+ () => {
14471
+ const state2 = store.getState();
14472
+ if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
14473
+ const renderer2 = state2.internal.actualRenderer;
14474
+ renderer2.setCanvasTarget(state2.internal.canvasTarget);
14475
+ }
14476
+ },
14477
+ {
14478
+ id: `${newRootId}_canvasTarget`,
14479
+ rootId: newRootId,
14480
+ phase: "start",
14481
+ system: true
14482
+ }
14483
+ );
14484
+ const unregisterEventsFlush = scheduler$1.register(
14485
+ () => {
14486
+ const state2 = store.getState();
14487
+ state2.events.flush?.();
14488
+ },
14489
+ {
14490
+ id: `${newRootId}_events`,
14491
+ rootId: newRootId,
14492
+ phase: "input",
14493
+ system: true
14494
+ }
14495
+ );
14496
+ const unregisterFrustum = scheduler$1.register(
14773
14497
  () => {
14774
14498
  const state2 = store.getState();
14775
14499
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -14779,11 +14503,11 @@ function createRoot(canvas) {
14779
14503
  {
14780
14504
  id: `${newRootId}_frustum`,
14781
14505
  rootId: newRootId,
14782
- phase: "preRender",
14506
+ before: "render",
14783
14507
  system: true
14784
14508
  }
14785
14509
  );
14786
- const unregisterVisibility = scheduler.register(
14510
+ const unregisterVisibility = scheduler$1.register(
14787
14511
  () => {
14788
14512
  const state2 = store.getState();
14789
14513
  checkVisibility(state2);
@@ -14791,30 +14515,34 @@ function createRoot(canvas) {
14791
14515
  {
14792
14516
  id: `${newRootId}_visibility`,
14793
14517
  rootId: newRootId,
14794
- phase: "preRender",
14518
+ before: "render",
14795
14519
  system: true,
14796
14520
  after: `${newRootId}_frustum`
14797
14521
  }
14798
14522
  );
14799
- const unregisterRender = scheduler.register(
14523
+ const unregisterRender = scheduler$1.register(
14800
14524
  () => {
14801
14525
  const state2 = store.getState();
14802
14526
  const renderer2 = state2.internal.actualRenderer;
14803
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14527
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
14804
14528
  if (userHandlesRender || state2.internal.priority) return;
14805
14529
  try {
14806
- if (state2.postProcessing?.render) state2.postProcessing.render();
14530
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
14807
14531
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
14808
14532
  } catch (error) {
14809
14533
  state2.setError(error instanceof Error ? error : new Error(String(error)));
14810
14534
  }
14811
14535
  },
14812
14536
  {
14813
- id: `${newRootId}_render`,
14537
+ // Use canvas ID directly as job ID if available, otherwise use generated rootId
14538
+ id: canvasId || `${newRootId}_render`,
14814
14539
  rootId: newRootId,
14815
14540
  phase: "render",
14816
- system: true
14541
+ system: true,
14817
14542
  // Internal flag: this is a system job, not user-controlled
14543
+ // Apply scheduler config for render ordering and rate limiting
14544
+ ...schedulerConfig?.after && { after: schedulerConfig.after },
14545
+ ...schedulerConfig?.fps && { fps: schedulerConfig.fps }
14818
14546
  }
14819
14547
  );
14820
14548
  state.set((state2) => ({
@@ -14823,15 +14551,17 @@ function createRoot(canvas) {
14823
14551
  rootId: newRootId,
14824
14552
  unregisterRoot: () => {
14825
14553
  unregisterRoot();
14554
+ unregisterCanvasTarget();
14555
+ unregisterEventsFlush();
14826
14556
  unregisterFrustum();
14827
14557
  unregisterVisibility();
14828
14558
  unregisterRender();
14829
14559
  },
14830
- scheduler
14560
+ scheduler: scheduler$1
14831
14561
  }
14832
14562
  }));
14833
14563
  }
14834
- scheduler.frameloop = frameloop;
14564
+ scheduler$1.frameloop = frameloop;
14835
14565
  onCreated = onCreatedCallback;
14836
14566
  configured = true;
14837
14567
  resolve();
@@ -14881,15 +14611,24 @@ function unmountComponentAtNode(canvas, callback) {
14881
14611
  const renderer = state.internal.actualRenderer;
14882
14612
  const unregisterRoot = state.internal.unregisterRoot;
14883
14613
  if (unregisterRoot) unregisterRoot();
14614
+ const unregisterPrimary = state.internal.unregisterPrimary;
14615
+ if (unregisterPrimary) unregisterPrimary();
14616
+ const canvasTarget = state.internal.canvasTarget;
14617
+ if (canvasTarget?.dispose) canvasTarget.dispose();
14884
14618
  state.events.disconnect?.();
14885
14619
  cleanupHelperGroup(root.store);
14886
- renderer?.renderLists?.dispose?.();
14887
- renderer?.forceContextLoss?.();
14888
- if (renderer?.xr) state.xr.disconnect();
14620
+ if (state.isLegacy && renderer) {
14621
+ ;
14622
+ renderer.renderLists?.dispose?.();
14623
+ renderer.forceContextLoss?.();
14624
+ }
14625
+ if (!state.internal.isSecondary) {
14626
+ if (renderer?.xr) state.xr.disconnect();
14627
+ }
14889
14628
  dispose(state.scene);
14890
14629
  _roots.delete(canvas);
14891
14630
  if (callback) callback(canvas);
14892
- } catch (e) {
14631
+ } catch {
14893
14632
  }
14894
14633
  }, 500);
14895
14634
  }
@@ -14897,36 +14636,34 @@ function unmountComponentAtNode(canvas, callback) {
14897
14636
  }
14898
14637
  }
14899
14638
  function createPortal(children, container, state) {
14900
- return /* @__PURE__ */ jsxRuntime.jsx(PortalWrapper, { children, container, state });
14639
+ return /* @__PURE__ */ jsxRuntime.jsx(Portal, { children, container, state });
14901
14640
  }
14902
- function PortalWrapper({ children, container, state }) {
14641
+ function Portal({ children, container, state }) {
14903
14642
  const isRef = React.useCallback((obj) => obj && "current" in obj, []);
14904
- const [resolvedContainer, setResolvedContainer] = React.useState(() => {
14643
+ const [resolvedContainer, _setResolvedContainer] = React.useState(() => {
14905
14644
  if (isRef(container)) return container.current ?? null;
14906
14645
  return container;
14907
14646
  });
14647
+ const setResolvedContainer = React.useCallback(
14648
+ (newContainer) => {
14649
+ if (!newContainer || newContainer === resolvedContainer) return;
14650
+ _setResolvedContainer(isRef(newContainer) ? newContainer.current : newContainer);
14651
+ },
14652
+ [resolvedContainer, _setResolvedContainer, isRef]
14653
+ );
14908
14654
  React.useMemo(() => {
14909
- if (isRef(container)) {
14910
- const current = container.current;
14911
- if (!current) {
14912
- queueMicrotask(() => {
14913
- const updated = container.current;
14914
- if (updated && updated !== resolvedContainer) {
14915
- setResolvedContainer(updated);
14916
- }
14917
- });
14918
- } else if (current !== resolvedContainer) {
14919
- setResolvedContainer(current);
14920
- }
14921
- } else if (container !== resolvedContainer) {
14922
- setResolvedContainer(container);
14655
+ if (isRef(container) && !container.current) {
14656
+ return queueMicrotask(() => {
14657
+ setResolvedContainer(container.current);
14658
+ });
14923
14659
  }
14924
- }, [container, resolvedContainer, isRef]);
14660
+ setResolvedContainer(container);
14661
+ }, [container, isRef, setResolvedContainer]);
14925
14662
  if (!resolvedContainer) return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, {});
14926
14663
  const portalKey = resolvedContainer.uuid ?? `portal-${resolvedContainer.id ?? "unknown"}`;
14927
- return /* @__PURE__ */ jsxRuntime.jsx(Portal, { children, container: resolvedContainer, state }, portalKey);
14664
+ return /* @__PURE__ */ jsxRuntime.jsx(PortalInner, { children, container: resolvedContainer, state }, portalKey);
14928
14665
  }
14929
- function Portal({ state = {}, children, container }) {
14666
+ function PortalInner({ state = {}, children, container }) {
14930
14667
  const { events, size, injectScene = true, ...rest } = state;
14931
14668
  const previousRoot = useStore();
14932
14669
  const [raycaster] = React.useState(() => new three.Raycaster());
@@ -14947,12 +14684,14 @@ function Portal({ state = {}, children, container }) {
14947
14684
  };
14948
14685
  }, [portalScene, container, injectScene]);
14949
14686
  const inject = useMutableCallback((rootState, injectState) => {
14687
+ const resolvedSize = { ...rootState.size, ...injectState.size, ...size };
14950
14688
  let viewport = void 0;
14951
- if (injectState.camera && size) {
14689
+ if (injectState.camera && (size || injectState.size)) {
14952
14690
  const camera = injectState.camera;
14953
- viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), size);
14954
- if (camera !== rootState.camera) updateCamera(camera, size);
14691
+ viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), resolvedSize);
14692
+ if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
14955
14693
  }
14694
+ const set = injectState.set;
14956
14695
  return {
14957
14696
  // The intersect consists of the previous root state
14958
14697
  ...rootState,
@@ -14968,10 +14707,10 @@ function Portal({ state = {}, children, container }) {
14968
14707
  previousRoot,
14969
14708
  // Events, size and viewport can be overridden by the inject layer
14970
14709
  events: { ...rootState.events, ...injectState.events, ...events },
14971
- size: { ...rootState.size, ...size },
14710
+ size: resolvedSize,
14972
14711
  viewport: { ...rootState.viewport, ...viewport },
14973
14712
  // Layers are allowed to override events
14974
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14713
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14975
14714
  // Container for child attachment - the portalScene (injected or container itself)
14976
14715
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
14977
14716
  };
@@ -14980,9 +14719,13 @@ function Portal({ state = {}, children, container }) {
14980
14719
  const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14981
14720
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14982
14721
  onMutate(previousRoot.getState());
14983
- previousRoot.subscribe(onMutate);
14984
14722
  return store;
14985
14723
  }, [previousRoot, container]);
14724
+ useIsomorphicLayoutEffect(() => {
14725
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14726
+ const unsubscribe = previousRoot.subscribe(onMutate);
14727
+ return unsubscribe;
14728
+ }, [previousRoot, usePortalStore]);
14986
14729
  return (
14987
14730
  // @ts-ignore, reconciler types are not maintained
14988
14731
  /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
@@ -14996,21 +14739,72 @@ function flushSync(fn) {
14996
14739
  return reconciler.flushSyncFromReconciler(fn);
14997
14740
  }
14998
14741
 
14742
+ function parseBackground(background) {
14743
+ if (!background) return null;
14744
+ if (typeof background === "object" && !background.isColor) {
14745
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14746
+ return {
14747
+ ...rest,
14748
+ preset,
14749
+ files: envMap || files,
14750
+ backgroundFiles: backgroundMap,
14751
+ background: true
14752
+ };
14753
+ }
14754
+ if (typeof background === "number") {
14755
+ return { color: background, background: true };
14756
+ }
14757
+ if (typeof background === "string") {
14758
+ if (background in presetsObj) {
14759
+ return { preset: background, background: true };
14760
+ }
14761
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14762
+ return { files: background, background: true };
14763
+ }
14764
+ return { color: background, background: true };
14765
+ }
14766
+ if (background.isColor) {
14767
+ return { color: background, background: true };
14768
+ }
14769
+ return null;
14770
+ }
14771
+
14772
+ function parseRendererConfig(rendererProp) {
14773
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14774
+ if (isRendererConfig) {
14775
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14776
+ return {
14777
+ primaryCanvas: pc,
14778
+ scheduler: sc,
14779
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14780
+ };
14781
+ }
14782
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14783
+ }
14784
+
14785
+ function clearHmrCaches(store) {
14786
+ store.setState((state) => ({
14787
+ nodes: {},
14788
+ uniforms: {},
14789
+ buffers: {},
14790
+ gpuStorage: {},
14791
+ _hmrVersion: state._hmrVersion + 1
14792
+ }));
14793
+ }
14794
+
14999
14795
  function CanvasImpl({
15000
14796
  ref,
15001
14797
  children,
15002
14798
  fallback,
15003
14799
  resize,
15004
14800
  style,
14801
+ id,
15005
14802
  gl,
15006
- renderer,
14803
+ renderer: rendererProp,
15007
14804
  events = createPointerEvents,
15008
14805
  eventSource,
15009
14806
  eventPrefix,
15010
14807
  shadows,
15011
- linear,
15012
- flat,
15013
- legacy,
15014
14808
  orthographic,
15015
14809
  frameloop,
15016
14810
  dpr,
@@ -15018,14 +14812,23 @@ function CanvasImpl({
15018
14812
  raycaster,
15019
14813
  camera,
15020
14814
  scene,
14815
+ autoUpdateFrustum,
14816
+ occlusion,
15021
14817
  onPointerMissed,
15022
14818
  onDragOverMissed,
15023
14819
  onDropMissed,
15024
14820
  onCreated,
14821
+ hmr,
14822
+ width,
14823
+ height,
14824
+ background,
14825
+ forceEven,
15025
14826
  ...props
15026
14827
  }) {
14828
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15027
14829
  React__namespace.useMemo(() => extend(THREE), []);
15028
14830
  const Bridge = useBridge();
14831
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15029
14832
  const hasInitialSizeRef = React__namespace.useRef(false);
15030
14833
  const measureConfig = React__namespace.useMemo(() => {
15031
14834
  if (!hasInitialSizeRef.current) {
@@ -15042,7 +14845,21 @@ function CanvasImpl({
15042
14845
  };
15043
14846
  }, [resize, hasInitialSizeRef.current]);
15044
14847
  const [containerRef, containerRect] = useMeasure__default(measureConfig);
15045
- if (!hasInitialSizeRef.current && containerRect.width > 0 && containerRect.height > 0) {
14848
+ const effectiveSize = React__namespace.useMemo(() => {
14849
+ let w = width ?? containerRect.width;
14850
+ let h = height ?? containerRect.height;
14851
+ if (forceEven) {
14852
+ w = Math.ceil(w / 2) * 2;
14853
+ h = Math.ceil(h / 2) * 2;
14854
+ }
14855
+ return {
14856
+ width: w,
14857
+ height: h,
14858
+ top: containerRect.top,
14859
+ left: containerRect.left
14860
+ };
14861
+ }, [width, height, containerRect, forceEven]);
14862
+ if (!hasInitialSizeRef.current && effectiveSize.width > 0 && effectiveSize.height > 0) {
15046
14863
  hasInitialSizeRef.current = true;
15047
14864
  }
15048
14865
  const canvasRef = React__namespace.useRef(null);
@@ -15053,6 +14870,7 @@ function CanvasImpl({
15053
14870
  const handleDropMissed = useMutableCallback(onDropMissed);
15054
14871
  const [block, setBlock] = React__namespace.useState(false);
15055
14872
  const [error, setError] = React__namespace.useState(false);
14873
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15056
14874
  if (block) throw block;
15057
14875
  if (error) throw error;
15058
14876
  const root = React__namespace.useRef(null);
@@ -15060,8 +14878,9 @@ function CanvasImpl({
15060
14878
  const unsubscribeErrorRef = React__namespace.useRef(null);
15061
14879
  useIsomorphicLayoutEffect(() => {
15062
14880
  effectActiveRef.current = true;
14881
+ if (fallbackVisible) return;
15063
14882
  const canvas = canvasRef.current;
15064
- if (containerRect.width > 0 && containerRect.height > 0 && canvas) {
14883
+ if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15065
14884
  if (!root.current) {
15066
14885
  root.current = createRoot(canvas);
15067
14886
  notifyAlpha({
@@ -15080,22 +14899,27 @@ function CanvasImpl({
15080
14899
  }
15081
14900
  async function run() {
15082
14901
  if (!effectActiveRef.current || !root.current) return;
15083
- await root.current.configure({
14902
+ const configured = await root.current.configure({
14903
+ id,
14904
+ primaryCanvas,
14905
+ scheduler,
15084
14906
  gl,
15085
14907
  renderer,
15086
14908
  scene,
15087
14909
  events,
15088
14910
  shadows,
15089
- linear,
15090
- flat,
15091
- legacy,
15092
14911
  orthographic,
15093
14912
  frameloop,
15094
14913
  dpr,
15095
14914
  performance,
15096
14915
  raycaster,
15097
14916
  camera,
15098
- size: containerRect,
14917
+ autoUpdateFrustum,
14918
+ occlusion,
14919
+ size: effectiveSize,
14920
+ // Store size props for reset functionality
14921
+ _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
14922
+ forceEven,
15099
14923
  // Pass mutable reference to onPointerMissed so it's free to update
15100
14924
  onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
15101
14925
  onDragOverMissed: (...args) => handleDragOverMissed.current?.(...args),
@@ -15116,10 +14940,25 @@ function CanvasImpl({
15116
14940
  }
15117
14941
  onCreated?.(state);
15118
14942
  }
15119
- });
15120
- if (!effectActiveRef.current || !root.current) return;
14943
+ }).then(
14944
+ () => true,
14945
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14946
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14947
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14948
+ (setupError) => {
14949
+ if (effectActiveRef.current) {
14950
+ if (fallback != null) setFallbackVisible(true);
14951
+ else setError(setupError);
14952
+ }
14953
+ return false;
14954
+ }
14955
+ );
14956
+ if (!configured || !effectActiveRef.current || !root.current) return;
15121
14957
  root.current.render(
15122
- /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsx(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: children ?? null }) }) })
14958
+ /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: [
14959
+ backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
14960
+ children ?? null
14961
+ ] }) }) })
15123
14962
  );
15124
14963
  }
15125
14964
  run();
@@ -15141,6 +14980,28 @@ function CanvasImpl({
15141
14980
  };
15142
14981
  }
15143
14982
  }, []);
14983
+ React__namespace.useEffect(() => {
14984
+ if (hmr === false) return;
14985
+ const canvas = canvasRef.current;
14986
+ if (!canvas) return;
14987
+ const handleHMR = () => {
14988
+ queueMicrotask(() => {
14989
+ const rootEntry = _roots.get(canvas);
14990
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
14991
+ });
14992
+ };
14993
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('legacy.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
14994
+ const hot = undefined;
14995
+ hot.on("vite:afterUpdate", handleHMR);
14996
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
14997
+ }
14998
+ if (typeof module !== "undefined" && module.hot) {
14999
+ const hot = module.hot;
15000
+ hot.addStatusHandler((status) => {
15001
+ if (status === "idle") handleHMR();
15002
+ });
15003
+ }
15004
+ }, [hmr]);
15144
15005
  const pointerEvents = eventSource ? "none" : "auto";
15145
15006
  return /* @__PURE__ */ jsxRuntime.jsx(
15146
15007
  "div",
@@ -15155,7 +15016,20 @@ function CanvasImpl({
15155
15016
  ...style
15156
15017
  },
15157
15018
  ...props,
15158
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx("canvas", { ref: canvasRef, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
15019
+ children: fallbackVisible ? (
15020
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15021
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15022
+ fallback
15023
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15024
+ "canvas",
15025
+ {
15026
+ ref: canvasRef,
15027
+ id,
15028
+ className: "r3f-canvas",
15029
+ style: { display: "block", width: "100%", height: "100%" },
15030
+ children: fallback
15031
+ }
15032
+ ) })
15159
15033
  }
15160
15034
  );
15161
15035
  }
@@ -15165,15 +15039,23 @@ function Canvas(props) {
15165
15039
 
15166
15040
  extend(THREE);
15167
15041
 
15042
+ exports.Scheduler = scheduler.Scheduler;
15043
+ exports.getScheduler = scheduler.getScheduler;
15168
15044
  exports.Block = Block;
15169
15045
  exports.Canvas = Canvas;
15046
+ exports.Environment = Environment;
15047
+ exports.EnvironmentCube = EnvironmentCube;
15048
+ exports.EnvironmentMap = EnvironmentMap;
15049
+ exports.EnvironmentPortal = EnvironmentPortal;
15170
15050
  exports.ErrorBoundary = ErrorBoundary;
15051
+ exports.FROM_REF = FROM_REF;
15171
15052
  exports.IsObject = IsObject;
15053
+ exports.ONCE = ONCE;
15054
+ exports.Portal = Portal;
15172
15055
  exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15173
15056
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15174
15057
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15175
15058
  exports.RESERVED_PROPS = RESERVED_PROPS;
15176
- exports.Scheduler = Scheduler;
15177
15059
  exports.Texture = Texture;
15178
15060
  exports._roots = _roots;
15179
15061
  exports.act = act;
@@ -15198,30 +15080,40 @@ exports.events = createPointerEvents;
15198
15080
  exports.extend = extend;
15199
15081
  exports.findInitialRoot = findInitialRoot;
15200
15082
  exports.flushSync = flushSync;
15083
+ exports.fromRef = fromRef;
15201
15084
  exports.getInstanceProps = getInstanceProps;
15085
+ exports.getPrimary = getPrimary;
15086
+ exports.getPrimaryIds = getPrimaryIds;
15202
15087
  exports.getRootState = getRootState;
15203
- exports.getScheduler = getScheduler;
15204
15088
  exports.getUuidPrefix = getUuidPrefix;
15205
15089
  exports.hasConstructor = hasConstructor;
15090
+ exports.hasPrimary = hasPrimary;
15206
15091
  exports.invalidate = invalidate;
15207
15092
  exports.invalidateInstance = invalidateInstance;
15208
15093
  exports.is = is;
15209
15094
  exports.isColorRepresentation = isColorRepresentation;
15210
15095
  exports.isCopyable = isCopyable;
15096
+ exports.isFromRef = isFromRef;
15211
15097
  exports.isObject3D = isObject3D;
15098
+ exports.isOnce = isOnce;
15212
15099
  exports.isOrthographicCamera = isOrthographicCamera;
15213
15100
  exports.isRef = isRef;
15214
15101
  exports.isRenderer = isRenderer;
15215
15102
  exports.isTexture = isTexture;
15216
15103
  exports.isVectorLike = isVectorLike;
15104
+ exports.once = once;
15217
15105
  exports.prepare = prepare;
15106
+ exports.presetsObj = presetsObj;
15218
15107
  exports.reconciler = reconciler;
15108
+ exports.registerPrimary = registerPrimary;
15219
15109
  exports.removeInteractivity = removeInteractivity;
15220
15110
  exports.resolve = resolve;
15221
15111
  exports.unmountComponentAtNode = unmountComponentAtNode;
15112
+ exports.unregisterPrimary = unregisterPrimary;
15222
15113
  exports.updateCamera = updateCamera;
15223
15114
  exports.updateFrustum = updateFrustum;
15224
15115
  exports.useBridge = useBridge;
15116
+ exports.useEnvironment = useEnvironment;
15225
15117
  exports.useFrame = useFrame;
15226
15118
  exports.useGraph = useGraph;
15227
15119
  exports.useInstanceHandle = useInstanceHandle;
@@ -15233,3 +15125,4 @@ exports.useStore = useStore;
15233
15125
  exports.useTexture = useTexture;
15234
15126
  exports.useTextures = useTextures;
15235
15127
  exports.useThree = useThree;
15128
+ exports.waitForPrimary = waitForPrimary;