@react-three/fiber 10.0.0-alpha.2 → 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,8 +5,15 @@ 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
 
12
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -66,9 +73,392 @@ const THREE = /*#__PURE__*/_mergeNamespaces({
66
73
  WebGPURenderer: WebGPURenderer
67
74
  }, [three__namespace]);
68
75
 
69
- var __defProp$2 = Object.defineProperty;
70
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
71
- 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);
72
462
  const act = React__namespace["act"];
73
463
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
74
464
  function useMutableCallback(fn) {
@@ -100,7 +490,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
100
490
  return _a = class extends React__namespace.Component {
101
491
  constructor() {
102
492
  super(...arguments);
103
- __publicField$2(this, "state", { error: false });
493
+ __publicField(this, "state", { error: false });
104
494
  }
105
495
  componentDidCatch(err) {
106
496
  this.props.set(err);
@@ -108,7 +498,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
108
498
  render() {
109
499
  return this.state.error ? null : this.props.children;
110
500
  }
111
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
501
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
112
502
  })();
113
503
 
114
504
  const is = {
@@ -294,7 +684,7 @@ function createOcclusionObserverNode(store, uniform) {
294
684
  let occlusionSetupPromise = null;
295
685
  function enableOcclusion(store) {
296
686
  const state = store.getState();
297
- const { internal, renderer, rootScene } = state;
687
+ const { internal, renderer } = state;
298
688
  if (internal.occlusionEnabled || occlusionSetupPromise) return;
299
689
  const hasOcclusionSupport = typeof renderer?.isOccluded === "function";
300
690
  if (!hasOcclusionSupport) {
@@ -402,6 +792,17 @@ function unregisterVisibility(store, object) {
402
792
  internal.visibilityRegistry.delete(object.uuid);
403
793
  internal.occlusionCache.delete(object);
404
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
+ }
405
806
  function checkVisibility(state) {
406
807
  const { internal, camera } = state;
407
808
  const registry = internal.visibilityRegistry;
@@ -457,6 +858,22 @@ function hasVisibilityHandlers(handlers) {
457
858
  return !!(handlers.onFramed || handlers.onOccluded || handlers.onVisible);
458
859
  }
459
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
+
460
877
  const RESERVED_PROPS = [
461
878
  "children",
462
879
  "key",
@@ -527,7 +944,7 @@ function getMemoizedPrototype(root) {
527
944
  ctor = new root.constructor();
528
945
  MEMOIZED_PROTOTYPES.set(root.constructor, ctor);
529
946
  }
530
- } catch (e) {
947
+ } catch {
531
948
  }
532
949
  return ctor;
533
950
  }
@@ -573,6 +990,22 @@ function applyProps(object, props) {
573
990
  continue;
574
991
  }
575
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
+ }
576
1009
  let { root, key, target } = resolve(object, prop);
577
1010
  if (target === void 0 && (typeof root !== "object" || root === null)) {
578
1011
  throw Error(`R3F: Cannot set "${prop}". Ensure it is an object before setting "${key}".`);
@@ -593,9 +1026,25 @@ function applyProps(object, props) {
593
1026
  } else if (isVectorLike(target) && is.num(value)) {
594
1027
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
595
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
+ }
596
1042
  } else {
597
1043
  root[key] = value;
598
- 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
599
1048
  root[key].format === three.RGBAFormat && root[key].type === three.UnsignedByteType) {
600
1049
  root[key].colorSpace = rootState.textureColorSpace;
601
1050
  }
@@ -608,6 +1057,9 @@ function applyProps(object, props) {
608
1057
  if (instance.eventCount && object2.raycast !== null) {
609
1058
  rootState.internal.interaction.push(object2);
610
1059
  }
1060
+ }
1061
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1062
+ const object2 = instance.object;
611
1063
  const root = findInitialRoot(instance);
612
1064
  const visibilityHandlers = {
613
1065
  onFramed: instance.handlers.onFramed,
@@ -615,7 +1067,9 @@ function applyProps(object, props) {
615
1067
  onVisible: instance.handlers.onVisible
616
1068
  };
617
1069
  if (hasVisibilityHandlers(visibilityHandlers)) {
618
- registerVisibility(root, object2, visibilityHandlers);
1070
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1071
+ registerVisibility(root, object2, visibilityHandlers);
1072
+ }
619
1073
  } else {
620
1074
  unregisterVisibility(root, object2);
621
1075
  }
@@ -628,38 +1082,60 @@ function applyProps(object, props) {
628
1082
  return object;
629
1083
  }
630
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
+ }
631
1103
  function makeId(event) {
632
1104
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
633
1105
  }
634
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
635
- 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);
636
1110
  if (captureData) {
637
- captures.delete(obj);
638
- if (captures.size === 0) {
639
- capturedMap.delete(pointerId);
640
- captureData.target.releasePointerCapture(pointerId);
641
- }
1111
+ pointerState.captured.delete(obj);
1112
+ captureData.target.releasePointerCapture(pointerId);
642
1113
  }
643
1114
  }
644
1115
  function removeInteractivity(store, object) {
645
1116
  const { internal } = store.getState();
646
1117
  internal.interaction = internal.interaction.filter((o) => o !== object);
647
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
648
- internal.hovered.forEach((value, key) => {
649
- if (value.eventObject === object || value.object === object) {
650
- 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);
651
1127
  }
652
- });
653
- internal.capturedMap.forEach((captures, pointerId) => {
654
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
655
- });
1128
+ }
656
1129
  unregisterVisibility(store, object);
657
1130
  }
658
1131
  function createEvents(store) {
659
- function calculateDistance(event) {
1132
+ function calculateDistance(event, pointerId) {
660
1133
  const { internal } = store.getState();
661
- const dx = event.offsetX - internal.initialClick[0];
662
- 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;
663
1139
  return Math.round(Math.sqrt(dx * dx + dy * dy));
664
1140
  }
665
1141
  function filterPointerEvents(objects) {
@@ -695,6 +1171,15 @@ function createEvents(store) {
695
1171
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
696
1172
  }
697
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
+ }
698
1183
  const aState = getRootState(a.object);
699
1184
  const bState = getRootState(b.object);
700
1185
  const aPriority = aState?.events?.priority ?? 1;
@@ -716,9 +1201,13 @@ function createEvents(store) {
716
1201
  eventObject = eventObject.parent;
717
1202
  }
718
1203
  }
719
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
720
- for (const captureData of state.internal.capturedMap.get(event.pointerId).values()) {
721
- 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
+ }
722
1211
  }
723
1212
  }
724
1213
  return intersections;
@@ -731,27 +1220,25 @@ function createEvents(store) {
731
1220
  if (state) {
732
1221
  const { raycaster, pointer, camera, internal } = state;
733
1222
  const unprojectedPoint = new three.Vector3(pointer.x, pointer.y, 0).unproject(camera);
734
- 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
+ };
735
1227
  const setPointerCapture = (id) => {
736
1228
  const captureData = { intersection: hit, target: event.target };
737
- if (internal.capturedMap.has(id)) {
738
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
739
- } else {
740
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
741
- }
1229
+ const pointerState = getPointerState(internal, id);
1230
+ pointerState.captured.set(hit.eventObject, captureData);
742
1231
  event.target.setPointerCapture(id);
743
1232
  };
744
1233
  const releasePointerCapture = (id) => {
745
- const captures = internal.capturedMap.get(id);
746
- if (captures) {
747
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
748
- }
1234
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
749
1235
  };
750
1236
  const extractEventProps = {};
751
1237
  for (const prop in event) {
752
1238
  const property = event[prop];
753
1239
  if (typeof property !== "function") extractEventProps[prop] = property;
754
1240
  }
1241
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
755
1242
  const raycastEvent = {
756
1243
  ...hit,
757
1244
  ...extractEventProps,
@@ -762,18 +1249,19 @@ function createEvents(store) {
762
1249
  unprojectedPoint,
763
1250
  ray: raycaster.ray,
764
1251
  camera,
1252
+ pointerId: eventPointerId,
765
1253
  // Hijack stopPropagation, which just sets a flag
766
1254
  stopPropagation() {
767
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1255
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
768
1256
  if (
769
1257
  // ...if this pointer hasn't been captured
770
- !capturesForPointer || // ... or if the hit object is capturing the pointer
771
- capturesForPointer.has(hit.eventObject)
1258
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1259
+ pointerState.captured.has(hit.eventObject)
772
1260
  ) {
773
1261
  raycastEvent.stopped = localState.stopped = true;
774
- 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)) {
775
1263
  const higher = intersections.slice(0, intersections.indexOf(hit));
776
- cancelPointer([...higher, hit]);
1264
+ cancelPointer([...higher, hit], eventPointerId);
777
1265
  }
778
1266
  }
779
1267
  },
@@ -789,15 +1277,18 @@ function createEvents(store) {
789
1277
  }
790
1278
  return intersections;
791
1279
  }
792
- function cancelPointer(intersections) {
1280
+ function cancelPointer(intersections, pointerId) {
793
1281
  const { internal } = store.getState();
794
- 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) {
795
1286
  if (!intersections.length || !intersections.find(
796
1287
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
797
1288
  )) {
798
1289
  const eventObject = hoveredObj.eventObject;
799
1290
  const instance = eventObject.__r3f;
800
- internal.hovered.delete(makeId(hoveredObj));
1291
+ pointerState.hovered.delete(hoveredId);
801
1292
  if (instance?.eventCount) {
802
1293
  const handlers = instance.handlers;
803
1294
  const data = { ...hoveredObj, intersections };
@@ -826,41 +1317,118 @@ function createEvents(store) {
826
1317
  instance?.handlers.onDropMissed?.(event);
827
1318
  }
828
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
+ }
829
1366
  function handlePointer(name) {
830
1367
  switch (name) {
831
1368
  case "onPointerLeave":
832
- case "onPointerCancel":
833
1369
  case "onDragLeave":
834
1370
  return () => cancelPointer([]);
1371
+ // Global cancel of these events
1372
+ case "onPointerCancel":
1373
+ return (event) => {
1374
+ const pointerId = getPointerId(event);
1375
+ cleanupPointer(pointerId);
1376
+ };
835
1377
  case "onLostPointerCapture":
836
1378
  return (event) => {
837
1379
  const { internal } = store.getState();
838
- 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) {
839
1383
  requestAnimationFrame(() => {
840
- if (internal.capturedMap.has(event.pointerId)) {
841
- internal.capturedMap.delete(event.pointerId);
842
- cancelPointer([]);
1384
+ const pointerState2 = internal.pointerMap.get(pointerId);
1385
+ if (pointerState2?.captured.size) {
1386
+ pointerState2.captured.clear();
843
1387
  }
1388
+ cancelPointer([], pointerId);
844
1389
  });
845
1390
  }
846
1391
  };
847
1392
  }
848
1393
  return function handleEvent(event) {
849
1394
  const state = store.getState();
850
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1395
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1396
+ const pointerId = getPointerId(event);
851
1397
  internal.lastEvent.current = event;
852
- if (!state.events.enabled) return;
1398
+ if (!events.enabled) return;
853
1399
  const isPointerMove = name === "onPointerMove";
854
1400
  const isDragOver = name === "onDragOver";
855
1401
  const isDrop = name === "onDrop";
856
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
+ }
857
1422
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
858
1423
  const hits = intersect(event, filter);
859
- const delta = isClickEvent ? calculateDistance(event) : 0;
860
- if (name === "onPointerDown") {
861
- internal.initialClick = [event.offsetX, event.offsetY];
862
- internal.initialHits = hits.map((hit) => hit.eventObject);
863
- }
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 ?? [];
864
1432
  if (isClickEvent && !hits.length) {
865
1433
  if (delta <= 2) {
866
1434
  pointerMissed(event, internal.interaction);
@@ -875,7 +1443,9 @@ function createEvents(store) {
875
1443
  dropMissed(event, internal.interaction);
876
1444
  if (onDropMissed) onDropMissed(event);
877
1445
  }
878
- if (isPointerMove || isDragOver) cancelPointer(hits);
1446
+ if (isPointerMove || isDragOver) {
1447
+ cancelPointer(hits, pointerId);
1448
+ }
879
1449
  function onIntersect(data) {
880
1450
  const eventObject = data.eventObject;
881
1451
  const instance = eventObject.__r3f;
@@ -884,9 +1454,10 @@ function createEvents(store) {
884
1454
  if (isPointerMove) {
885
1455
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
886
1456
  const id = makeId(data);
887
- const hoveredItem = internal.hovered.get(id);
1457
+ const pointerState2 = getPointerState(internal, pointerId);
1458
+ const hoveredItem = pointerState2.hovered.get(id);
888
1459
  if (!hoveredItem) {
889
- internal.hovered.set(id, data);
1460
+ pointerState2.hovered.set(id, data);
890
1461
  handlers.onPointerOver?.(data);
891
1462
  handlers.onPointerEnter?.(data);
892
1463
  } else if (hoveredItem.stopped) {
@@ -896,9 +1467,10 @@ function createEvents(store) {
896
1467
  handlers.onPointerMove?.(data);
897
1468
  } else if (isDragOver) {
898
1469
  const id = makeId(data);
899
- const hoveredItem = internal.hovered.get(id);
1470
+ const pointerState2 = getPointerState(internal, pointerId);
1471
+ const hoveredItem = pointerState2.hovered.get(id);
900
1472
  if (!hoveredItem) {
901
- internal.hovered.set(id, data);
1473
+ pointerState2.hovered.set(id, data);
902
1474
  handlers.onDragOverEnter?.(data);
903
1475
  } else if (hoveredItem.stopped) {
904
1476
  data.stopPropagation();
@@ -909,18 +1481,18 @@ function createEvents(store) {
909
1481
  } else {
910
1482
  const handler = handlers[name];
911
1483
  if (handler) {
912
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1484
+ if (!isClickEvent || initialHits.includes(eventObject)) {
913
1485
  pointerMissed(
914
1486
  event,
915
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1487
+ internal.interaction.filter((object) => !initialHits.includes(object))
916
1488
  );
917
1489
  handler(data);
918
1490
  }
919
1491
  } else {
920
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1492
+ if (isClickEvent && initialHits.includes(eventObject)) {
921
1493
  pointerMissed(
922
1494
  event,
923
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1495
+ internal.interaction.filter((object) => !initialHits.includes(object))
924
1496
  );
925
1497
  }
926
1498
  }
@@ -929,7 +1501,15 @@ function createEvents(store) {
929
1501
  handleIntersects(hits, event, delta, onIntersect);
930
1502
  };
931
1503
  }
932
- 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 };
933
1513
  }
934
1514
  const DOM_EVENTS = {
935
1515
  onClick: ["click", false],
@@ -948,11 +1528,16 @@ const DOM_EVENTS = {
948
1528
  onLostPointerCapture: ["lostpointercapture", true]
949
1529
  };
950
1530
  function createPointerEvents(store) {
951
- const { handlePointer } = createEvents(store);
1531
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1532
+ let nextXRPointerId = XR_POINTER_ID_START;
1533
+ const xrPointers = /* @__PURE__ */ new Map();
952
1534
  return {
953
1535
  priority: 1,
954
1536
  enabled: true,
955
- compute(event, state, previous) {
1537
+ frameTimedRaycasts: true,
1538
+ alwaysFireOnScroll: true,
1539
+ updateOnFrame: false,
1540
+ compute(event, state) {
956
1541
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
957
1542
  state.raycaster.setFromCamera(state.pointer, state.camera);
958
1543
  },
@@ -961,11 +1546,33 @@ function createPointerEvents(store) {
961
1546
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
962
1547
  {}
963
1548
  ),
964
- update: () => {
1549
+ update: (pointerId) => {
965
1550
  const { events, internal } = store.getState();
966
- 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
+ }
967
1573
  },
968
1574
  connect: (target) => {
1575
+ if (!target) return;
969
1576
  const { set, events } = store.getState();
970
1577
  events.disconnect?.();
971
1578
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -989,6 +1596,33 @@ function createPointerEvents(store) {
989
1596
  }
990
1597
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
991
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);
992
1626
  }
993
1627
  };
994
1628
  }
@@ -1050,6 +1684,14 @@ function notifyAlpha({ message, link }) {
1050
1684
  }
1051
1685
  }
1052
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
+
1053
1695
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1054
1696
  const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
1055
1697
  const createStore = (invalidate, advance) => {
@@ -1079,23 +1721,29 @@ const createStore = (invalidate, advance) => {
1079
1721
  set,
1080
1722
  get,
1081
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,
1082
1726
  gl: null,
1083
1727
  renderer: null,
1084
1728
  camera: null,
1085
1729
  frustum: new three.Frustum(),
1086
1730
  autoUpdateFrustum: true,
1087
1731
  raycaster: null,
1088
- 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
+ },
1089
1740
  scene: null,
1090
1741
  rootScene: null,
1091
1742
  xr: null,
1092
1743
  inspector: null,
1093
1744
  invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1094
1745
  advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1095
- legacy: false,
1096
- linear: false,
1097
- flat: false,
1098
- textureColorSpace: "srgb",
1746
+ textureColorSpace: three.SRGBColorSpace,
1099
1747
  isLegacy: false,
1100
1748
  webGPUSupported: false,
1101
1749
  isNative: false,
@@ -1153,6 +1801,7 @@ const createStore = (invalidate, advance) => {
1153
1801
  size: newSize,
1154
1802
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1155
1803
  }));
1804
+ scheduler.getScheduler().invalidate();
1156
1805
  }
1157
1806
  }
1158
1807
  return;
@@ -1167,6 +1816,7 @@ const createStore = (invalidate, advance) => {
1167
1816
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1168
1817
  _sizeImperative: true
1169
1818
  }));
1819
+ scheduler.getScheduler().invalidate();
1170
1820
  },
1171
1821
  setDpr: (dpr) => set((state2) => {
1172
1822
  const resolved = calculateDpr(dpr);
@@ -1174,14 +1824,18 @@ const createStore = (invalidate, advance) => {
1174
1824
  }),
1175
1825
  setFrameloop: (frameloop = "always") => {
1176
1826
  set(() => ({ frameloop }));
1827
+ scheduler.getScheduler().frameloop = frameloop;
1177
1828
  },
1178
1829
  setError: (error) => set(() => ({ error })),
1179
1830
  error: null,
1180
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1831
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1181
1832
  uniforms: {},
1182
1833
  nodes: {},
1834
+ buffers: {},
1835
+ gpuStorage: {},
1183
1836
  textures: /* @__PURE__ */ new Map(),
1184
- postProcessing: null,
1837
+ _textureRefs: /* @__PURE__ */ new Map(),
1838
+ renderPipeline: null,
1185
1839
  passes: {},
1186
1840
  _hmrVersion: 0,
1187
1841
  _sizeImperative: false,
@@ -1190,12 +1844,16 @@ const createStore = (invalidate, advance) => {
1190
1844
  internal: {
1191
1845
  // Events
1192
1846
  interaction: [],
1193
- hovered: /* @__PURE__ */ new Map(),
1194
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(),
1195
1854
  initialClick: [0, 0],
1196
1855
  initialHits: [],
1197
1856
  capturedMap: /* @__PURE__ */ new Map(),
1198
- lastEvent: React__namespace.createRef(),
1199
1857
  // Visibility tracking (onFramed, onOccluded, onVisible)
1200
1858
  visibilityRegistry: /* @__PURE__ */ new Map(),
1201
1859
  // Occlusion system (WebGPU only)
@@ -1234,8 +1892,7 @@ const createStore = (invalidate, advance) => {
1234
1892
  const currentState = rootStore.getState();
1235
1893
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
1236
1894
  const stack = new Error().stack || "";
1237
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
1238
- if (!isInternalAccess) {
1895
+ if (!isInternalRendererAccess(stack)) {
1239
1896
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
1240
1897
  notifyDepreciated({
1241
1898
  heading: "Accessing state.gl in WebGPU mode",
@@ -1278,13 +1935,22 @@ const createStore = (invalidate, advance) => {
1278
1935
  rootStore.subscribe(() => {
1279
1936
  const { camera, size, viewport, set, internal } = rootStore.getState();
1280
1937
  const actualRenderer = internal.actualRenderer;
1938
+ const canvasTarget = internal.canvasTarget;
1281
1939
  if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
1282
1940
  oldSize = size;
1283
1941
  oldDpr = viewport.dpr;
1284
1942
  updateCamera(camera, size);
1285
- if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
1286
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
1287
- 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
+ }
1288
1954
  }
1289
1955
  if (camera !== oldCamera) {
1290
1956
  oldCamera = camera;
@@ -1339,1058 +2005,32 @@ function loadingFn(extensions, onProgress) {
1339
2005
  );
1340
2006
  };
1341
2007
  }
1342
- function useLoader(loader, input, extensions, onProgress) {
1343
- 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];
1344
2011
  const fn = loadingFn(extensions, onProgress);
1345
- 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
+ );
1346
2015
  return Array.isArray(input) ? results : results[0];
1347
2016
  }
1348
- useLoader.preload = function(loader, input, extensions, onProgress) {
1349
- const keys = Array.isArray(input) ? input : [input];
1350
- 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
+ );
1351
2023
  };
1352
- useLoader.clear = function(loader, input) {
1353
- const keys = Array.isArray(input) ? input : [input];
1354
- 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]));
1355
2027
  };
1356
2028
  useLoader.loader = getLoader;
1357
2029
 
1358
- var __defProp$1 = Object.defineProperty;
1359
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1360
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1361
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1362
- class PhaseGraph {
1363
- constructor() {
1364
- /** Ordered list of phase nodes */
1365
- __publicField$1(this, "phases", []);
1366
- /** Quick lookup by name */
1367
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1368
- /** Cached ordered names (invalidated on changes) */
1369
- __publicField$1(this, "orderedNamesCache", null);
1370
- this.initializeDefaultPhases();
1371
- }
1372
- //* Initialization --------------------------------
1373
- initializeDefaultPhases() {
1374
- for (const name of DEFAULT_PHASES) {
1375
- const node = { name, isAutoGenerated: false };
1376
- this.phases.push(node);
1377
- this.phaseMap.set(name, node);
1378
- }
1379
- this.invalidateCache();
1380
- }
1381
- //* Public API --------------------------------
1382
- /**
1383
- * Add a named phase to the graph
1384
- * @param name - Phase name (must be unique)
1385
- * @param options - Position options (before or after another phase)
1386
- */
1387
- addPhase(name, options = {}) {
1388
- if (this.phaseMap.has(name)) {
1389
- console.warn(`[useFrame] Phase "${name}" already exists`);
1390
- return;
1391
- }
1392
- const { before, after } = options;
1393
- const node = { name, isAutoGenerated: false };
1394
- let insertIndex = this.phases.length;
1395
- const targetIndex = this.getPhaseIndex(before ?? after);
1396
- if (targetIndex !== -1) {
1397
- insertIndex = before ? targetIndex : targetIndex + 1;
1398
- } else {
1399
- const constraintType = before ? "before" : "after";
1400
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1401
- }
1402
- this.phases.splice(insertIndex, 0, node);
1403
- this.phaseMap.set(name, node);
1404
- this.invalidateCache();
1405
- }
1406
- /**
1407
- * Get ordered list of phase names
1408
- */
1409
- getOrderedPhases() {
1410
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1411
- return this.orderedNamesCache;
1412
- }
1413
- /**
1414
- * Check if a phase exists
1415
- */
1416
- hasPhase(name) {
1417
- return this.phaseMap.has(name);
1418
- }
1419
- /**
1420
- * Get the index of a phase (-1 if not found)
1421
- */
1422
- getPhaseIndex(name) {
1423
- if (!name) return -1;
1424
- return this.phases.findIndex((p) => p.name === name);
1425
- }
1426
- /**
1427
- * Ensure a phase exists, creating an auto-generated one if needed.
1428
- * Used for resolving before/after constraints.
1429
- *
1430
- * @param name - The phase name to ensure exists
1431
- * @returns The phase name (may be auto-generated like 'before:render')
1432
- */
1433
- ensurePhase(name) {
1434
- if (this.phaseMap.has(name)) return name;
1435
- const node = { name, isAutoGenerated: true };
1436
- this.phases.push(node);
1437
- this.phaseMap.set(name, node);
1438
- this.invalidateCache();
1439
- return name;
1440
- }
1441
- /**
1442
- * Resolve where a job with before/after constraints should go.
1443
- * Creates auto-generated phases if needed.
1444
- *
1445
- * @param before - Phase(s) to run before
1446
- * @param after - Phase(s) to run after
1447
- * @returns The resolved phase name
1448
- */
1449
- resolveConstraintPhase(before, after) {
1450
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1451
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1452
- if (beforeArr.length > 0) {
1453
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1454
- }
1455
- if (afterArr.length > 0) {
1456
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1457
- }
1458
- return "update";
1459
- }
1460
- /**
1461
- * Ensure an auto-generated phase exists relative to a target phase.
1462
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1463
- *
1464
- * @param target - The target phase name to position relative to
1465
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1466
- * @param offset - Insertion offset (0 for before, 1 for after)
1467
- * @returns The auto-generated phase name
1468
- */
1469
- ensureAutoPhase(target, prefix, offset) {
1470
- const autoName = `${prefix}:${target}`;
1471
- if (this.phaseMap.has(autoName)) return autoName;
1472
- const node = { name: autoName, isAutoGenerated: true };
1473
- const targetIndex = this.getPhaseIndex(target);
1474
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1475
- else this.phases.push(node);
1476
- this.phaseMap.set(autoName, node);
1477
- this.invalidateCache();
1478
- return autoName;
1479
- }
1480
- // Internal --------------------------------
1481
- invalidateCache() {
1482
- this.orderedNamesCache = null;
1483
- }
1484
- }
1485
-
1486
- function rebuildSortedJobs(jobs, phaseGraph) {
1487
- const orderedPhases = phaseGraph.getOrderedPhases();
1488
- const buckets = /* @__PURE__ */ new Map();
1489
- for (const phase of orderedPhases) {
1490
- buckets.set(phase, []);
1491
- }
1492
- for (const job of jobs.values()) {
1493
- if (!job.enabled) continue;
1494
- let bucket = buckets.get(job.phase);
1495
- if (!bucket) {
1496
- bucket = [];
1497
- buckets.set(job.phase, bucket);
1498
- }
1499
- bucket.push(job);
1500
- }
1501
- const sortedBuckets = [];
1502
- for (const phase of orderedPhases) {
1503
- const bucket = buckets.get(phase);
1504
- if (!bucket || bucket.length === 0) continue;
1505
- bucket.sort((a, b) => {
1506
- if (a.priority !== b.priority) return b.priority - a.priority;
1507
- return a.index - b.index;
1508
- });
1509
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1510
- }
1511
- for (const [phase, bucket] of buckets) {
1512
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1513
- bucket.sort((a, b) => {
1514
- if (a.priority !== b.priority) return b.priority - a.priority;
1515
- return a.index - b.index;
1516
- });
1517
- sortedBuckets.push(bucket);
1518
- }
1519
- }
1520
- return sortedBuckets.flat();
1521
- }
1522
- function hasCrossJobConstraints(bucket) {
1523
- const jobIds = new Set(bucket.map((j) => j.id));
1524
- for (const job of bucket) {
1525
- for (const ref of job.before) {
1526
- if (jobIds.has(ref)) return true;
1527
- }
1528
- for (const ref of job.after) {
1529
- if (jobIds.has(ref)) return true;
1530
- }
1531
- }
1532
- return false;
1533
- }
1534
- function topologicalSort(jobs) {
1535
- const n = jobs.length;
1536
- if (n <= 1) return jobs;
1537
- const jobMap = /* @__PURE__ */ new Map();
1538
- const inDegree = /* @__PURE__ */ new Map();
1539
- const adjacency = /* @__PURE__ */ new Map();
1540
- for (const job of jobs) {
1541
- jobMap.set(job.id, job);
1542
- inDegree.set(job.id, 0);
1543
- adjacency.set(job.id, []);
1544
- }
1545
- for (const job of jobs) {
1546
- for (const ref of job.before) {
1547
- if (jobMap.has(ref)) {
1548
- adjacency.get(job.id).push(ref);
1549
- inDegree.set(ref, inDegree.get(ref) + 1);
1550
- }
1551
- }
1552
- for (const ref of job.after) {
1553
- if (jobMap.has(ref)) {
1554
- adjacency.get(ref).push(job.id);
1555
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1556
- }
1557
- }
1558
- }
1559
- const queue = [];
1560
- for (const job of jobs) {
1561
- if (inDegree.get(job.id) === 0) {
1562
- queue.push(job);
1563
- }
1564
- }
1565
- queue.sort((a, b) => {
1566
- if (a.priority !== b.priority) return b.priority - a.priority;
1567
- return a.index - b.index;
1568
- });
1569
- const result = [];
1570
- while (queue.length > 0) {
1571
- const job = queue.shift();
1572
- result.push(job);
1573
- const neighbors = adjacency.get(job.id) || [];
1574
- for (const neighborId of neighbors) {
1575
- const newDegree = inDegree.get(neighborId) - 1;
1576
- inDegree.set(neighborId, newDegree);
1577
- if (newDegree === 0) {
1578
- const neighbor = jobMap.get(neighborId);
1579
- insertSorted(queue, neighbor);
1580
- }
1581
- }
1582
- }
1583
- if (result.length !== n) {
1584
- console.warn("[useFrame] Circular dependency detected in job constraints");
1585
- const resultIds = new Set(result.map((j) => j.id));
1586
- for (const job of jobs) {
1587
- if (!resultIds.has(job.id)) result.push(job);
1588
- }
1589
- }
1590
- return result;
1591
- }
1592
- function insertSorted(arr, job) {
1593
- let i = 0;
1594
- while (i < arr.length) {
1595
- const cmp = arr[i];
1596
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1597
- break;
1598
- }
1599
- i++;
1600
- }
1601
- arr.splice(i, 0, job);
1602
- }
1603
-
1604
- function shouldRun(job, now) {
1605
- if (!job.enabled) return false;
1606
- if (!job.fps) return true;
1607
- const minInterval = 1e3 / job.fps;
1608
- const lastRun = job.lastRun ?? 0;
1609
- const elapsed = now - lastRun;
1610
- if (elapsed < minInterval) return false;
1611
- if (job.drop) {
1612
- job.lastRun = now;
1613
- } else {
1614
- const steps = Math.floor(elapsed / minInterval);
1615
- job.lastRun = lastRun + steps * minInterval;
1616
- if (job.lastRun < now - minInterval) {
1617
- job.lastRun = now;
1618
- }
1619
- }
1620
- return true;
1621
- }
1622
- function resetJobTiming(job) {
1623
- job.lastRun = void 0;
1624
- }
1625
-
1626
- var __defProp = Object.defineProperty;
1627
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1628
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1629
- const hmrData = (() => {
1630
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1631
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1632
- try {
1633
- return (0, eval)("import.meta.hot");
1634
- } catch {
1635
- return void 0;
1636
- }
1637
- })();
1638
- const _Scheduler = class _Scheduler {
1639
- //* Constructor ================================
1640
- constructor() {
1641
- //* Critical State ================================
1642
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1643
- __publicField(this, "phaseGraph");
1644
- __publicField(this, "loopState", {
1645
- running: false,
1646
- rafHandle: null,
1647
- lastTime: null,
1648
- // null = uninitialized, 0+ = valid timestamp
1649
- frameCount: 0,
1650
- elapsedTime: 0,
1651
- createdAt: performance.now()
1652
- });
1653
- __publicField(this, "stoppedTime", 0);
1654
- //* Private State ================================
1655
- __publicField(this, "nextRootIndex", 0);
1656
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1657
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1658
- __publicField(this, "nextGlobalIndex", 0);
1659
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1660
- __publicField(this, "nextJobIndex", 0);
1661
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1662
- __publicField(this, "pendingFrames", 0);
1663
- __publicField(this, "_frameloop", "always");
1664
- //* Independent Mode & Error Handling State ================================
1665
- __publicField(this, "_independent", false);
1666
- __publicField(this, "errorHandler", null);
1667
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1668
- //* Core Loop Execution Methods ================================
1669
- /**
1670
- * Main RAF loop callback.
1671
- * Executes frame, handles demand mode, and schedules next frame.
1672
- * @param {number} timestamp - RAF timestamp in milliseconds
1673
- * @returns {void}
1674
- * @private
1675
- */
1676
- __publicField(this, "loop", (timestamp) => {
1677
- if (!this.loopState.running) return;
1678
- this.executeFrame(timestamp);
1679
- if (this._frameloop === "demand") {
1680
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1681
- if (this.pendingFrames === 0) {
1682
- this.notifyIdle(timestamp);
1683
- return this.stop();
1684
- }
1685
- }
1686
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1687
- });
1688
- this.phaseGraph = new PhaseGraph();
1689
- }
1690
- static get instance() {
1691
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1692
- }
1693
- static set instance(value) {
1694
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1695
- }
1696
- /**
1697
- * Get the global scheduler instance (creates if doesn't exist).
1698
- * Uses HMR data to preserve instance across hot reloads.
1699
- * @returns {Scheduler} The singleton scheduler instance
1700
- */
1701
- static get() {
1702
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1703
- _Scheduler.instance = hmrData.data.scheduler;
1704
- }
1705
- if (!_Scheduler.instance) {
1706
- _Scheduler.instance = new _Scheduler();
1707
- if (hmrData?.data) {
1708
- hmrData.data.scheduler = _Scheduler.instance;
1709
- }
1710
- }
1711
- return _Scheduler.instance;
1712
- }
1713
- /**
1714
- * Reset the singleton instance. Stops the loop and clears all state.
1715
- * Primarily used for testing to ensure clean state between tests.
1716
- * @returns {void}
1717
- */
1718
- static reset() {
1719
- if (_Scheduler.instance) {
1720
- _Scheduler.instance.stop();
1721
- _Scheduler.instance = null;
1722
- }
1723
- if (hmrData?.data) {
1724
- hmrData.data.scheduler = null;
1725
- }
1726
- }
1727
- //* Getters & Setters ================================
1728
- get phases() {
1729
- return this.phaseGraph.getOrderedPhases();
1730
- }
1731
- get frameloop() {
1732
- return this._frameloop;
1733
- }
1734
- set frameloop(mode) {
1735
- if (this._frameloop === mode) return;
1736
- const wasAlways = this._frameloop === "always";
1737
- this._frameloop = mode;
1738
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1739
- else if (mode !== "always" && wasAlways) this.stop();
1740
- }
1741
- get isRunning() {
1742
- return this.loopState.running;
1743
- }
1744
- get isReady() {
1745
- return this.roots.size > 0;
1746
- }
1747
- get independent() {
1748
- return this._independent;
1749
- }
1750
- set independent(value) {
1751
- this._independent = value;
1752
- if (value) this.ensureDefaultRoot();
1753
- }
1754
- //* Root Management Methods ================================
1755
- /**
1756
- * Register a root (Canvas) with the scheduler.
1757
- * The first root to register starts the RAF loop (if frameloop='always').
1758
- * @param {string} id - Unique identifier for this root
1759
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1760
- * @returns {() => void} Unsubscribe function to remove this root
1761
- */
1762
- registerRoot(id, options = {}) {
1763
- if (this.roots.has(id)) {
1764
- console.warn(`[Scheduler] Root "${id}" already registered`);
1765
- return () => this.unregisterRoot(id);
1766
- }
1767
- const entry = {
1768
- id,
1769
- getState: options.getState ?? (() => ({})),
1770
- jobs: /* @__PURE__ */ new Map(),
1771
- sortedJobs: [],
1772
- needsRebuild: false
1773
- };
1774
- if (options.onError) {
1775
- this.errorHandler = options.onError;
1776
- }
1777
- this.roots.set(id, entry);
1778
- if (this.roots.size === 1) {
1779
- this.notifyRootReady();
1780
- if (this._frameloop === "always") this.start();
1781
- }
1782
- return () => this.unregisterRoot(id);
1783
- }
1784
- /**
1785
- * Unregister a root from the scheduler.
1786
- * Cleans up all job state listeners for this root's jobs.
1787
- * The last root to unregister stops the RAF loop.
1788
- * @param {string} id - The root ID to unregister
1789
- * @returns {void}
1790
- */
1791
- unregisterRoot(id) {
1792
- const root = this.roots.get(id);
1793
- if (!root) return;
1794
- for (const jobId of root.jobs.keys()) {
1795
- this.jobStateListeners.delete(jobId);
1796
- }
1797
- this.roots.delete(id);
1798
- if (this.roots.size === 0) {
1799
- this.stop();
1800
- this.errorHandler = null;
1801
- }
1802
- }
1803
- /**
1804
- * Subscribe to be notified when a root becomes available.
1805
- * Fires immediately if a root already exists.
1806
- * @param {() => void} callback - Function called when first root registers
1807
- * @returns {() => void} Unsubscribe function
1808
- */
1809
- onRootReady(callback) {
1810
- if (this.roots.size > 0) {
1811
- callback();
1812
- return () => {
1813
- };
1814
- }
1815
- this.rootReadyCallbacks.add(callback);
1816
- return () => this.rootReadyCallbacks.delete(callback);
1817
- }
1818
- /**
1819
- * Notify all registered root-ready callbacks.
1820
- * Called when the first root registers.
1821
- * @returns {void}
1822
- * @private
1823
- */
1824
- notifyRootReady() {
1825
- for (const cb of this.rootReadyCallbacks) {
1826
- try {
1827
- cb();
1828
- } catch (error) {
1829
- console.error("[Scheduler] Error in root-ready callback:", error);
1830
- }
1831
- }
1832
- this.rootReadyCallbacks.clear();
1833
- }
1834
- /**
1835
- * Ensure a default root exists for independent mode.
1836
- * Creates a minimal root with no state provider.
1837
- * @returns {void}
1838
- * @private
1839
- */
1840
- ensureDefaultRoot() {
1841
- if (!this.roots.has("__default__")) {
1842
- this.registerRoot("__default__");
1843
- }
1844
- }
1845
- /**
1846
- * Trigger error handling for job errors.
1847
- * Uses the bound error handler if available, otherwise logs to console.
1848
- * @param {Error} error - The error to handle
1849
- * @returns {void}
1850
- */
1851
- triggerError(error) {
1852
- if (this.errorHandler) this.errorHandler(error);
1853
- else console.error("[Scheduler]", error);
1854
- }
1855
- //* Phase Management Methods ================================
1856
- /**
1857
- * Add a named phase to the scheduler's execution order.
1858
- * Marks all roots for rebuild to incorporate the new phase.
1859
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1860
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1861
- * @returns {void}
1862
- * @example
1863
- * scheduler.addPhase('physics', { before: 'update' });
1864
- * scheduler.addPhase('postprocess', { after: 'render' });
1865
- */
1866
- addPhase(name, options) {
1867
- this.phaseGraph.addPhase(name, options);
1868
- for (const root of this.roots.values()) {
1869
- root.needsRebuild = true;
1870
- }
1871
- }
1872
- /**
1873
- * Check if a phase exists in the scheduler.
1874
- * @param {string} name - The phase name to check
1875
- * @returns {boolean} True if the phase exists
1876
- */
1877
- hasPhase(name) {
1878
- return this.phaseGraph.hasPhase(name);
1879
- }
1880
- //* Global Job Registration Methods (Deprecated APIs) ================================
1881
- /**
1882
- * Register a global job that runs once per frame (not per-root).
1883
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1884
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1885
- * @param {string} id - Unique identifier for this global job
1886
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1887
- * @returns {() => void} Unsubscribe function to remove this global job
1888
- * @deprecated Use useFrame with phases instead
1889
- */
1890
- registerGlobal(phase, id, callback) {
1891
- const job = { id, callback };
1892
- if (phase === "before") {
1893
- this.globalBeforeJobs.set(id, job);
1894
- } else {
1895
- this.globalAfterJobs.set(id, job);
1896
- }
1897
- return () => {
1898
- if (phase === "before") this.globalBeforeJobs.delete(id);
1899
- else this.globalAfterJobs.delete(id);
1900
- };
1901
- }
1902
- //* Idle Callback Methods (Deprecated API) ================================
1903
- /**
1904
- * Register an idle callback that fires when the loop stops.
1905
- * Used internally by deprecated addTail API.
1906
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
1907
- * @returns {() => void} Unsubscribe function to remove this idle callback
1908
- * @deprecated Use demand mode with invalidate() instead
1909
- */
1910
- onIdle(callback) {
1911
- this.idleCallbacks.add(callback);
1912
- return () => this.idleCallbacks.delete(callback);
1913
- }
1914
- /**
1915
- * Notify all registered idle callbacks.
1916
- * Called when the loop stops in demand mode.
1917
- * @param {number} timestamp - The RAF timestamp when idle occurred
1918
- * @returns {void}
1919
- * @private
1920
- */
1921
- notifyIdle(timestamp) {
1922
- for (const cb of this.idleCallbacks) {
1923
- try {
1924
- cb(timestamp);
1925
- } catch (error) {
1926
- console.error("[Scheduler] Error in idle callback:", error);
1927
- }
1928
- }
1929
- }
1930
- //* Job Registration & Management Methods ================================
1931
- /**
1932
- * Register a job (frame callback) with a specific root.
1933
- * This is the core registration method used by useFrame internally.
1934
- * @param {FrameNextCallback} callback - The function to call each frame
1935
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
1936
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
1937
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
1938
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
1939
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
1940
- * @param {number} [options.fps] - FPS throttle limit
1941
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
1942
- * @param {boolean} [options.enabled] - Whether job is active (default true)
1943
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
1944
- * @returns {() => void} Unsubscribe function to remove this job
1945
- */
1946
- register(callback, options = {}) {
1947
- const rootId = options.rootId;
1948
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
1949
- if (!root) {
1950
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
1951
- return () => {
1952
- };
1953
- }
1954
- const id = options.id ?? this.generateJobId();
1955
- let phase = options.phase ?? "update";
1956
- if (!options.phase && (options.before || options.after)) {
1957
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
1958
- }
1959
- const before = this.normalizeConstraints(options.before);
1960
- const after = this.normalizeConstraints(options.after);
1961
- const job = {
1962
- id,
1963
- callback,
1964
- phase,
1965
- before,
1966
- after,
1967
- priority: options.priority ?? 0,
1968
- index: this.nextJobIndex++,
1969
- fps: options.fps,
1970
- drop: options.drop ?? true,
1971
- enabled: options.enabled ?? true,
1972
- system: options.system ?? false
1973
- };
1974
- if (root.jobs.has(id)) {
1975
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
1976
- }
1977
- root.jobs.set(id, job);
1978
- root.needsRebuild = true;
1979
- return () => this.unregister(id, root.id);
1980
- }
1981
- /**
1982
- * Unregister a job by its ID.
1983
- * Searches all roots if rootId is not provided.
1984
- * @param {string} id - The job ID to unregister
1985
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
1986
- * @returns {void}
1987
- */
1988
- unregister(id, rootId) {
1989
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
1990
- if (root?.jobs.delete(id)) {
1991
- root.needsRebuild = true;
1992
- this.jobStateListeners.delete(id);
1993
- }
1994
- }
1995
- /**
1996
- * Update a job's options dynamically.
1997
- * Searches all roots to find the job by ID.
1998
- * Phase/constraint changes trigger a rebuild of the sorted job list.
1999
- * @param {string} id - The job ID to update
2000
- * @param {Partial<JobOptions>} options - The options to update
2001
- * @returns {void}
2002
- */
2003
- updateJob(id, options) {
2004
- let job;
2005
- let root;
2006
- for (const r of this.roots.values()) {
2007
- job = r.jobs.get(id);
2008
- if (job) {
2009
- root = r;
2010
- break;
2011
- }
2012
- }
2013
- if (!job || !root) return;
2014
- if (options.priority !== void 0) job.priority = options.priority;
2015
- if (options.fps !== void 0) job.fps = options.fps;
2016
- if (options.drop !== void 0) job.drop = options.drop;
2017
- if (options.enabled !== void 0) {
2018
- const wasEnabled = job.enabled;
2019
- job.enabled = options.enabled;
2020
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2021
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2022
- }
2023
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2024
- if (options.phase) job.phase = options.phase;
2025
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2026
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2027
- root.needsRebuild = true;
2028
- }
2029
- }
2030
- //* Job State Management Methods ================================
2031
- /**
2032
- * Check if a job is currently paused (disabled).
2033
- * @param {string} id - The job ID to check
2034
- * @returns {boolean} True if the job exists and is paused
2035
- */
2036
- isJobPaused(id) {
2037
- for (const root of this.roots.values()) {
2038
- const job = root.jobs.get(id);
2039
- if (job) return !job.enabled;
2040
- }
2041
- return false;
2042
- }
2043
- /**
2044
- * Subscribe to state changes for a specific job.
2045
- * Listener is called when job is paused or resumed.
2046
- * @param {string} id - The job ID to subscribe to
2047
- * @param {() => void} listener - Callback invoked on state changes
2048
- * @returns {() => void} Unsubscribe function
2049
- */
2050
- subscribeJobState(id, listener) {
2051
- if (!this.jobStateListeners.has(id)) {
2052
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2053
- }
2054
- this.jobStateListeners.get(id).add(listener);
2055
- return () => {
2056
- this.jobStateListeners.get(id)?.delete(listener);
2057
- if (this.jobStateListeners.get(id)?.size === 0) {
2058
- this.jobStateListeners.delete(id);
2059
- }
2060
- };
2061
- }
2062
- /**
2063
- * Notify all listeners that a job's state has changed.
2064
- * @param {string} id - The job ID that changed
2065
- * @returns {void}
2066
- * @private
2067
- */
2068
- notifyJobStateChange(id) {
2069
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2070
- }
2071
- /**
2072
- * Pause a job by ID (sets enabled=false).
2073
- * Notifies any subscribed state listeners.
2074
- * @param {string} id - The job ID to pause
2075
- * @returns {void}
2076
- */
2077
- pauseJob(id) {
2078
- this.updateJob(id, { enabled: false });
2079
- this.notifyJobStateChange(id);
2080
- }
2081
- /**
2082
- * Resume a paused job by ID (sets enabled=true).
2083
- * Resets job timing to prevent frame accumulation.
2084
- * Notifies any subscribed state listeners.
2085
- * @param {string} id - The job ID to resume
2086
- * @returns {void}
2087
- */
2088
- resumeJob(id) {
2089
- this.updateJob(id, { enabled: true });
2090
- this.notifyJobStateChange(id);
2091
- }
2092
- //* Frame Loop Control Methods ================================
2093
- /**
2094
- * Start the requestAnimationFrame loop.
2095
- * Resets timing state (elapsedTime, frameCount) on start.
2096
- * No-op if already running.
2097
- * @returns {void}
2098
- */
2099
- start() {
2100
- if (this.loopState.running) return;
2101
- const { elapsedTime, createdAt } = this.loopState;
2102
- let adjustedCreated = 0;
2103
- if (this.stoppedTime > 0) {
2104
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2105
- this.stoppedTime = 0;
2106
- }
2107
- Object.assign(this.loopState, {
2108
- running: true,
2109
- elapsedTime: elapsedTime ?? 0,
2110
- lastTime: performance.now(),
2111
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2112
- frameCount: 0,
2113
- rafHandle: requestAnimationFrame(this.loop)
2114
- });
2115
- }
2116
- /**
2117
- * Stop the requestAnimationFrame loop.
2118
- * Cancels any pending RAF callback.
2119
- * No-op if not running.
2120
- * @returns {void}
2121
- */
2122
- stop() {
2123
- if (!this.loopState.running) return;
2124
- this.loopState.running = false;
2125
- if (this.loopState.rafHandle !== null) {
2126
- cancelAnimationFrame(this.loopState.rafHandle);
2127
- this.loopState.rafHandle = null;
2128
- }
2129
- this.stoppedTime = performance.now();
2130
- }
2131
- /**
2132
- * Request frames to be rendered in demand mode.
2133
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2134
- * No-op if frameloop is not 'demand'.
2135
- * @param {number} [frames=1] - Number of frames to request
2136
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2137
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2138
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2139
- * @returns {void}
2140
- * @example
2141
- * // Request a single frame render
2142
- * scheduler.invalidate();
2143
- *
2144
- * @example
2145
- * // Request 5 frames (e.g., for animations)
2146
- * scheduler.invalidate(5);
2147
- *
2148
- * @example
2149
- * // Set pending frames to exactly 3 (don't stack with existing)
2150
- * scheduler.invalidate(3, false);
2151
- *
2152
- * @example
2153
- * // Add 2 more frames to existing pending count
2154
- * scheduler.invalidate(2, true);
2155
- */
2156
- invalidate(frames = 1, stackFrames = false) {
2157
- if (this._frameloop !== "demand") return;
2158
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2159
- this.pendingFrames = Math.min(60, baseFrames + frames);
2160
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2161
- }
2162
- /**
2163
- * Reset timing state for deterministic testing.
2164
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2165
- * @returns {void}
2166
- */
2167
- resetTiming() {
2168
- this.loopState.lastTime = null;
2169
- this.loopState.frameCount = 0;
2170
- this.loopState.elapsedTime = 0;
2171
- this.loopState.createdAt = performance.now();
2172
- }
2173
- //* Manual Stepping Methods ================================
2174
- /**
2175
- * Manually execute a single frame for all roots.
2176
- * Useful for frameloop='never' mode or testing scenarios.
2177
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2178
- * @returns {void}
2179
- * @example
2180
- * // Manual control mode
2181
- * scheduler.frameloop = 'never';
2182
- * scheduler.step(); // Execute one frame
2183
- */
2184
- step(timestamp) {
2185
- const now = timestamp ?? performance.now();
2186
- this.executeFrame(now);
2187
- }
2188
- /**
2189
- * Manually execute a single job by its ID.
2190
- * Useful for testing individual job callbacks in isolation.
2191
- * @param {string} id - The job ID to step
2192
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2193
- * @returns {void}
2194
- */
2195
- stepJob(id, timestamp) {
2196
- let job;
2197
- let root;
2198
- for (const r of this.roots.values()) {
2199
- job = r.jobs.get(id);
2200
- if (job) {
2201
- root = r;
2202
- break;
2203
- }
2204
- }
2205
- if (!job || !root) {
2206
- console.warn(`[Scheduler] Job "${id}" not found`);
2207
- return;
2208
- }
2209
- const now = timestamp ?? performance.now();
2210
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2211
- const delta = deltaMs / 1e3;
2212
- const elapsed = now - this.loopState.createdAt;
2213
- const providedState = root.getState?.() ?? {};
2214
- const frameState = {
2215
- ...providedState,
2216
- time: now,
2217
- delta,
2218
- elapsed,
2219
- frame: this.loopState.frameCount
2220
- };
2221
- try {
2222
- job.callback(frameState, delta);
2223
- } catch (error) {
2224
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2225
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2226
- }
2227
- }
2228
- /**
2229
- * Execute a single frame across all roots.
2230
- * Order: globalBefore → each root's jobs → globalAfter
2231
- * @param {number} timestamp - RAF timestamp in milliseconds
2232
- * @returns {void}
2233
- * @private
2234
- */
2235
- executeFrame(timestamp) {
2236
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2237
- const delta = deltaMs / 1e3;
2238
- this.loopState.lastTime = timestamp;
2239
- this.loopState.frameCount++;
2240
- this.loopState.elapsedTime += deltaMs;
2241
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2242
- for (const root of this.roots.values()) {
2243
- this.tickRoot(root, timestamp, delta);
2244
- }
2245
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2246
- }
2247
- /**
2248
- * Run all global jobs from a job map.
2249
- * Catches and logs errors without stopping execution.
2250
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2251
- * @param {number} timestamp - RAF timestamp in milliseconds
2252
- * @returns {void}
2253
- * @private
2254
- */
2255
- runGlobalJobs(jobs, timestamp) {
2256
- for (const job of jobs.values()) {
2257
- try {
2258
- job.callback(timestamp);
2259
- } catch (error) {
2260
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2261
- }
2262
- }
2263
- }
2264
- /**
2265
- * Execute all jobs for a single root in sorted order.
2266
- * Rebuilds sorted job list if needed, then dispatches each job.
2267
- * Errors are caught and propagated via triggerError.
2268
- * @param {RootEntry} root - The root entry to tick
2269
- * @param {number} timestamp - RAF timestamp in milliseconds
2270
- * @param {number} delta - Time since last frame in seconds
2271
- * @returns {void}
2272
- * @private
2273
- */
2274
- tickRoot(root, timestamp, delta) {
2275
- if (root.needsRebuild) {
2276
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2277
- root.needsRebuild = false;
2278
- }
2279
- const providedState = root.getState?.() ?? {};
2280
- const frameState = {
2281
- ...providedState,
2282
- time: timestamp,
2283
- delta,
2284
- elapsed: this.loopState.elapsedTime / 1e3,
2285
- // Convert ms to seconds
2286
- frame: this.loopState.frameCount
2287
- };
2288
- for (const job of root.sortedJobs) {
2289
- if (!shouldRun(job, timestamp)) continue;
2290
- try {
2291
- job.callback(frameState, delta);
2292
- } catch (error) {
2293
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2294
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2295
- }
2296
- }
2297
- }
2298
- //* Debug & Inspection Methods ================================
2299
- /**
2300
- * Get the total number of registered jobs across all roots.
2301
- * Includes both per-root jobs and global before/after jobs.
2302
- * @returns {number} Total job count
2303
- */
2304
- getJobCount() {
2305
- let count = 0;
2306
- for (const root of this.roots.values()) {
2307
- count += root.jobs.size;
2308
- }
2309
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2310
- }
2311
- /**
2312
- * Get all registered job IDs across all roots.
2313
- * Includes both per-root jobs and global before/after jobs.
2314
- * @returns {string[]} Array of all job IDs
2315
- */
2316
- getJobIds() {
2317
- const ids = [];
2318
- for (const root of this.roots.values()) {
2319
- ids.push(...root.jobs.keys());
2320
- }
2321
- ids.push(...this.globalBeforeJobs.keys());
2322
- ids.push(...this.globalAfterJobs.keys());
2323
- return ids;
2324
- }
2325
- /**
2326
- * Get the number of registered roots (Canvas instances).
2327
- * @returns {number} Number of registered roots
2328
- */
2329
- getRootCount() {
2330
- return this.roots.size;
2331
- }
2332
- /**
2333
- * Check if any user (non-system) jobs are registered in a specific phase.
2334
- * Used by the default render job to know if a user has taken over rendering.
2335
- *
2336
- * @param phase The phase to check
2337
- * @param rootId Optional root ID to check (checks all roots if not provided)
2338
- * @returns true if any user jobs exist in the phase
2339
- */
2340
- hasUserJobsInPhase(phase, rootId) {
2341
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2342
- return rootsToCheck.some((root) => {
2343
- if (!root) return false;
2344
- for (const job of root.jobs.values()) {
2345
- if (job.phase === phase && !job.system && job.enabled) return true;
2346
- }
2347
- return false;
2348
- });
2349
- }
2350
- //* Utility Methods ================================
2351
- /**
2352
- * Generate a unique root ID for automatic root registration.
2353
- * @returns {string} A unique root ID in the format 'root_N'
2354
- */
2355
- generateRootId() {
2356
- return `root_${this.nextRootIndex++}`;
2357
- }
2358
- /**
2359
- * Generate a unique job ID.
2360
- * @returns {string} A unique job ID in the format 'job_N'
2361
- * @private
2362
- */
2363
- generateJobId() {
2364
- return `job_${this.nextJobIndex}`;
2365
- }
2366
- /**
2367
- * Normalize before/after constraints to a Set.
2368
- * Handles undefined, single string, or array inputs.
2369
- * @param {string | string[] | undefined} value - The constraint value(s)
2370
- * @returns {Set<string>} Normalized Set of constraint strings
2371
- * @private
2372
- */
2373
- normalizeConstraints(value) {
2374
- if (!value) return /* @__PURE__ */ new Set();
2375
- if (Array.isArray(value)) return new Set(value);
2376
- return /* @__PURE__ */ new Set([value]);
2377
- }
2378
- };
2379
- //* Static State & Methods (Singleton Usage) ================================
2380
- //* Cross-Bundle Singleton Key ==============================
2381
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2382
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2383
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2384
- let Scheduler = _Scheduler;
2385
- const getScheduler = () => Scheduler.get();
2386
- if (hmrData) {
2387
- hmrData.accept?.();
2388
- }
2389
-
2390
2030
  function useFrame(callback, priorityOrOptions) {
2391
2031
  const store = React__namespace.useContext(context);
2392
2032
  const isInsideCanvas = store !== null;
2393
- const scheduler = getScheduler();
2033
+ const scheduler$1 = scheduler.getScheduler();
2394
2034
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2395
2035
  id: priorityOrOptions.id,
2396
2036
  phase: priorityOrOptions.phase,
@@ -2438,7 +2078,7 @@ function useFrame(callback, priorityOrOptions) {
2438
2078
  };
2439
2079
  callbackRef.current?.(mergedState, delta);
2440
2080
  };
2441
- const unregister = scheduler.register(wrappedCallback, {
2081
+ const unregister = scheduler$1.register(wrappedCallback, {
2442
2082
  id,
2443
2083
  rootId,
2444
2084
  ...options
@@ -2459,37 +2099,31 @@ function useFrame(callback, priorityOrOptions) {
2459
2099
  }
2460
2100
  };
2461
2101
  } else {
2462
- const registerOutside = () => {
2463
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2464
- };
2465
- if (scheduler.independent || scheduler.isReady) {
2466
- return registerOutside();
2467
- }
2468
- let unregisterJob = null;
2469
- const unsubReady = scheduler.onRootReady(() => {
2470
- unregisterJob = registerOutside();
2471
- });
2472
- return () => {
2473
- unsubReady();
2474
- unregisterJob?.();
2475
- };
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
+ );
2476
2110
  }
2477
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2111
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2478
2112
  const isPaused = React__namespace.useSyncExternalStore(
2479
2113
  // Subscribe function
2480
2114
  React__namespace.useCallback(
2481
2115
  (onStoreChange) => {
2482
- return getScheduler().subscribeJobState(id, onStoreChange);
2116
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
2483
2117
  },
2484
2118
  [id]
2485
2119
  ),
2486
2120
  // getSnapshot function
2487
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2121
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
2488
2122
  // getServerSnapshot function (SSR)
2489
2123
  React__namespace.useCallback(() => false, [])
2490
2124
  );
2491
2125
  const controls = React__namespace.useMemo(() => {
2492
- const scheduler2 = getScheduler();
2126
+ const scheduler2 = scheduler.getScheduler();
2493
2127
  return {
2494
2128
  /** The job's unique ID */
2495
2129
  id,
@@ -2504,7 +2138,7 @@ function useFrame(callback, priorityOrOptions) {
2504
2138
  * @param timestamp Optional timestamp (defaults to performance.now())
2505
2139
  */
2506
2140
  step: (timestamp) => {
2507
- getScheduler().stepJob(id, timestamp);
2141
+ scheduler.getScheduler().stepJob(id, timestamp);
2508
2142
  },
2509
2143
  /**
2510
2144
  * Manually step ALL jobs in the scheduler.
@@ -2512,20 +2146,20 @@ function useFrame(callback, priorityOrOptions) {
2512
2146
  * @param timestamp Optional timestamp (defaults to performance.now())
2513
2147
  */
2514
2148
  stepAll: (timestamp) => {
2515
- getScheduler().step(timestamp);
2149
+ scheduler.getScheduler().step(timestamp);
2516
2150
  },
2517
2151
  /**
2518
2152
  * Pause this job (set enabled=false).
2519
2153
  * Job remains registered but won't run.
2520
2154
  */
2521
2155
  pause: () => {
2522
- getScheduler().pauseJob(id);
2156
+ scheduler.getScheduler().pauseJob(id);
2523
2157
  },
2524
2158
  /**
2525
2159
  * Resume this job (set enabled=true).
2526
2160
  */
2527
2161
  resume: () => {
2528
- getScheduler().resumeJob(id);
2162
+ scheduler.getScheduler().resumeJob(id);
2529
2163
  },
2530
2164
  /**
2531
2165
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2563,22 +2197,29 @@ function buildFromCache(input, textureCache) {
2563
2197
  function useTexture(input, optionsOrOnLoad) {
2564
2198
  const renderer = useThree((state) => state.internal.actualRenderer);
2565
2199
  const store = useStore();
2566
- const textureCache = useThree((state) => state.textures);
2567
2200
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2568
- 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);
2569
2205
  const urls = React.useMemo(() => getUrls(input), [input]);
2570
2206
  const cachedResult = React.useMemo(() => {
2571
2207
  if (!cache) return null;
2572
- if (!allUrlsCached(urls, textureCache)) return null;
2573
- return buildFromCache(input, textureCache);
2574
- }, [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]);
2575
2212
  const loadedTextures = useLoader(
2576
2213
  three.TextureLoader,
2577
2214
  IsObject(input) ? Object.values(input) : input
2578
2215
  );
2216
+ const inputKey = urls.join("\0");
2579
2217
  React.useLayoutEffect(() => {
2580
- if (!cachedResult) onLoad?.(loadedTextures);
2581
- }, [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]);
2582
2223
  React.useEffect(() => {
2583
2224
  if (cachedResult) return;
2584
2225
  if ("initTexture" in renderer) {
@@ -2611,8 +2252,6 @@ function useTexture(input, optionsOrOnLoad) {
2611
2252
  }, [input, loadedTextures, cachedResult]);
2612
2253
  React.useEffect(() => {
2613
2254
  if (!cache) return;
2614
- if (cachedResult) return;
2615
- const set = store.setState;
2616
2255
  const urlTextureMap = [];
2617
2256
  if (typeof input === "string") {
2618
2257
  urlTextureMap.push([input, mappedTextures]);
@@ -2626,18 +2265,32 @@ function useTexture(input, optionsOrOnLoad) {
2626
2265
  urlTextureMap.push([url, textureRecord[key]]);
2627
2266
  }
2628
2267
  }
2629
- set((state) => {
2630
- const newMap = new Map(state.textures);
2631
- let changed = false;
2268
+ store.setState((state) => {
2269
+ const refs = new Map(state._textureRefs);
2270
+ let textures = state.textures;
2271
+ let added = false;
2632
2272
  for (const [url, texture] of urlTextureMap) {
2633
- if (!newMap.has(url)) {
2634
- newMap.set(url, texture);
2635
- changed = true;
2273
+ if (!textures.has(url)) {
2274
+ if (!added) {
2275
+ textures = new Map(textures);
2276
+ added = true;
2277
+ }
2278
+ textures.set(url, texture);
2636
2279
  }
2280
+ refs.set(url, (refs.get(url) ?? 0) + 1);
2637
2281
  }
2638
- 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 };
2639
2292
  });
2640
- }, [cache, input, mappedTextures, store, cachedResult]);
2293
+ }, [cache, input, mappedTextures, store]);
2641
2294
  return mappedTextures;
2642
2295
  }
2643
2296
  useTexture.preload = (url) => useLoader.preload(three.TextureLoader, url);
@@ -2653,106 +2306,90 @@ const Texture = ({
2653
2306
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
2654
2307
  };
2655
2308
 
2656
- function getTextureValue(entry) {
2657
- if (entry instanceof three.Texture) return entry;
2658
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof three.Texture) {
2659
- return entry.value;
2660
- }
2661
- return null;
2662
- }
2663
- function useTextures() {
2309
+ function useTextures(selector) {
2664
2310
  const store = useStore();
2665
- return React.useMemo(() => {
2666
- const set = store.setState;
2311
+ const registry = React.useMemo(() => {
2667
2312
  const getState = store.getState;
2668
- const add = (key, value) => {
2669
- set((state) => {
2670
- const newMap = new Map(state.textures);
2671
- newMap.set(key, value);
2672
- return { textures: newMap };
2673
- });
2674
- };
2675
- const addMultiple = (items) => {
2676
- set((state) => {
2677
- const newMap = new Map(state.textures);
2678
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
2679
- for (const [key, value] of entries) {
2680
- newMap.set(key, value);
2681
- }
2682
- return { textures: newMap };
2683
- });
2684
- };
2685
- const remove = (key) => {
2686
- set((state) => {
2687
- const newMap = new Map(state.textures);
2688
- newMap.delete(key);
2689
- return { textures: newMap };
2690
- });
2691
- };
2692
- const removeMultiple = (keys) => {
2693
- set((state) => {
2694
- const newMap = new Map(state.textures);
2695
- for (const key of keys) newMap.delete(key);
2696
- return { textures: newMap };
2697
- });
2698
- };
2699
- const dispose = (key) => {
2700
- const entry = getState().textures.get(key);
2701
- if (entry) {
2702
- const tex = getTextureValue(entry);
2703
- tex?.dispose();
2704
- }
2705
- remove(key);
2706
- };
2707
- const disposeMultiple = (keys) => {
2708
- const textures = getState().textures;
2709
- for (const key of keys) {
2710
- const entry = textures.get(key);
2711
- if (entry) {
2712
- const tex = getTextureValue(entry);
2713
- tex?.dispose();
2714
- }
2715
- }
2716
- removeMultiple(keys);
2717
- };
2718
- const disposeAll = () => {
2719
- const textures = getState().textures;
2720
- for (const entry of textures.values()) {
2721
- const tex = getTextureValue(entry);
2722
- tex?.dispose();
2723
- }
2724
- set({ textures: /* @__PURE__ */ new Map() });
2725
- };
2313
+ const setState = store.setState;
2314
+ const getOne = (key) => getState().textures.get(key);
2726
2315
  return {
2727
- // Getter for the textures Map (reactive via getState)
2728
- get textures() {
2316
+ get all() {
2729
2317
  return getState().textures;
2730
2318
  },
2731
- // Read
2732
- 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
+ },
2733
2326
  has: (key) => getState().textures.has(key),
2734
- // Write
2735
- add,
2736
- addMultiple,
2737
- // Remove (cache only)
2738
- remove,
2739
- removeMultiple,
2740
- // Dispose (GPU + cache)
2741
- dispose,
2742
- disposeMultiple,
2743
- 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
+ }
2744
2361
  };
2745
2362
  }, [store]);
2363
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2364
+ const selected = useThree(subscribe);
2365
+ return selector ? selected : registry;
2746
2366
  }
2747
2367
 
2748
- function useRenderTarget(width, height, options) {
2368
+ function useRenderTarget(widthOrOptions, heightOrOptions, options) {
2749
2369
  const isLegacy = useThree((s) => s.isLegacy);
2750
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
+ }
2751
2388
  return React.useMemo(() => {
2752
2389
  const w = width ?? size.width;
2753
2390
  const h = height ?? size.height;
2754
- return new three.WebGLRenderTarget(w, h, options);
2755
- }, [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]);
2756
2393
  }
2757
2394
 
2758
2395
  function useStore() {
@@ -2780,7 +2417,7 @@ function addEffect(callback) {
2780
2417
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2781
2418
  });
2782
2419
  const id = `legacy_effect_${effectId++}`;
2783
- return getScheduler().registerGlobal("before", id, callback);
2420
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
2784
2421
  }
2785
2422
  function addAfterEffect(callback) {
2786
2423
  notifyDepreciated({
@@ -2789,7 +2426,7 @@ function addAfterEffect(callback) {
2789
2426
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2790
2427
  });
2791
2428
  const id = `legacy_afterEffect_${effectId++}`;
2792
- return getScheduler().registerGlobal("after", id, callback);
2429
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
2793
2430
  }
2794
2431
  function addTail(callback) {
2795
2432
  notifyDepreciated({
@@ -2797,16 +2434,16 @@ function addTail(callback) {
2797
2434
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
2798
2435
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2799
2436
  });
2800
- return getScheduler().onIdle(callback);
2437
+ return scheduler.getScheduler().onIdle(callback);
2801
2438
  }
2802
2439
  function invalidate(state, frames = 1, stackFrames = false) {
2803
- getScheduler().invalidate(frames, stackFrames);
2440
+ scheduler.getScheduler().invalidate(frames, stackFrames);
2804
2441
  }
2805
- function advance(timestamp, runGlobalEffects = true, state, frame) {
2806
- getScheduler().step(timestamp);
2442
+ function advance(timestamp) {
2443
+ scheduler.getScheduler().step(timestamp);
2807
2444
  }
2808
2445
 
2809
- const version = "10.0.0-alpha.2";
2446
+ const version = "10.0.0-alpha.3";
2810
2447
  const packageData = {
2811
2448
  version: version};
2812
2449
 
@@ -14245,6 +13882,7 @@ function swapInstances() {
14245
13882
  }
14246
13883
  }
14247
13884
  if (instance.isHidden) unhideInstance(instance);
13885
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14248
13886
  if (instance.object.__r3f) delete instance.object.__r3f;
14249
13887
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14250
13888
  }
@@ -14256,6 +13894,9 @@ function swapInstances() {
14256
13894
  instance.object = instance.props.object ?? new target(...instance.props.args ?? []);
14257
13895
  instance.object.__r3f = instance;
14258
13896
  setFiberRef(fiber, instance.object);
13897
+ delete instance.appliedOnce;
13898
+ instance.eventCount = 0;
13899
+ instance.handlers = {};
14259
13900
  applyProps(instance.object, instance.props);
14260
13901
  if (instance.props.attach) {
14261
13902
  attach(parent, instance);
@@ -14329,8 +13970,22 @@ const reconciler = /* @__PURE__ */ createReconciler({
14329
13970
  const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14330
13971
  if (isTailSibling) swapInstances();
14331
13972
  },
14332
- finalizeInitialChildren: () => false,
14333
- 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);
14334
13989
  },
14335
13990
  getPublicInstance: (instance) => instance?.object,
14336
13991
  prepareForCommit: () => null,
@@ -14457,11 +14112,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14457
14112
  cloneMutableTextInstance(textInstance) {
14458
14113
  return textInstance;
14459
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.
14460
14121
  cloneRootViewTransitionContainer(_rootContainer) {
14461
- throw new Error("Not implemented.");
14462
14122
  },
14463
14123
  removeRootViewTransitionClone(_rootContainer, _clone) {
14464
- throw new Error("Not implemented.");
14465
14124
  },
14466
14125
  // https://github.com/facebook/react/pull/32465
14467
14126
  createFragmentInstance: (_fiber) => null,
@@ -14546,11 +14205,15 @@ function createRoot(canvas) {
14546
14205
  const lastConfiguredProps = {};
14547
14206
  let configured = false;
14548
14207
  let pending = null;
14208
+ let rendererSetup = null;
14549
14209
  return {
14550
14210
  async configure(props = {}) {
14551
14211
  let resolve;
14552
14212
  pending = new Promise((_resolve) => resolve = _resolve);
14553
14213
  const {
14214
+ id: canvasId,
14215
+ primaryCanvas,
14216
+ scheduler: schedulerConfig,
14554
14217
  gl: glConfig,
14555
14218
  renderer: rendererConfig,
14556
14219
  size: propsSize,
@@ -14558,10 +14221,6 @@ function createRoot(canvas) {
14558
14221
  events,
14559
14222
  onCreated: onCreatedCallback,
14560
14223
  shadows = false,
14561
- linear = false,
14562
- flat = false,
14563
- textureColorSpace = three.SRGBColorSpace,
14564
- legacy = false,
14565
14224
  orthographic = false,
14566
14225
  frameloop = "always",
14567
14226
  dpr = [1, 2],
@@ -14573,9 +14232,11 @@ function createRoot(canvas) {
14573
14232
  onDropMissed,
14574
14233
  autoUpdateFrustum = true,
14575
14234
  occlusion = false,
14576
- _sizeProps
14235
+ _sizeProps,
14236
+ forceEven
14577
14237
  } = props;
14578
- const state = store.getState();
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;
14239
+ let state = store.getState();
14579
14240
  const defaultGLProps = {
14580
14241
  canvas,
14581
14242
  powerPreference: "high-performance",
@@ -14587,15 +14248,37 @@ function createRoot(canvas) {
14587
14248
  "WebGPURenderer (renderer prop) is not available in this build. Use @react-three/fiber or @react-three/fiber/webgpu instead."
14588
14249
  );
14589
14250
  }
14590
- (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
14251
+ const wantsGL = (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
14591
14252
  if (glConfig && rendererConfig) {
14592
14253
  throw new Error("Cannot use both gl and renderer props at the same time");
14593
14254
  }
14594
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
+ }
14595
14266
  if (!state.internal.actualRenderer) {
14596
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14597
- state.internal.actualRenderer = renderer;
14598
- 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;
14599
14282
  }
14600
14283
  let raycaster = state.raycaster;
14601
14284
  if (!raycaster) state.set({ raycaster: raycaster = new three.Raycaster() });
@@ -14604,6 +14287,7 @@ function createRoot(canvas) {
14604
14287
  if (!is.equ(params, raycaster.params, shallowLoose)) {
14605
14288
  applyProps(raycaster, { params: { ...raycaster.params, ...params } });
14606
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) {
@@ -14657,6 +14342,9 @@ function createRoot(canvas) {
14657
14342
  if (_sizeProps !== void 0) {
14658
14343
  state.set({ _sizeProps });
14659
14344
  }
14345
+ if (forceEven !== void 0 && state.internal.forceEven !== forceEven) {
14346
+ state.set((prev) => ({ internal: { ...prev.internal, forceEven } }));
14347
+ }
14660
14348
  const size = computeInitialSize(canvas, propsSize);
14661
14349
  if (!state._sizeImperative && !is.equ(size, state.size, shallowLoose)) {
14662
14350
  const wasImperative = state._sizeImperative;
@@ -14683,10 +14371,10 @@ function createRoot(canvas) {
14683
14371
  lastConfiguredProps.performance = performance;
14684
14372
  }
14685
14373
  if (!state.xr) {
14686
- const handleXRFrame = (timestamp, frame) => {
14374
+ const handleXRFrame = (timestamp, _frame) => {
14687
14375
  const state2 = store.getState();
14688
14376
  if (state2.frameloop === "never") return;
14689
- advance(timestamp, true);
14377
+ advance(timestamp);
14690
14378
  };
14691
14379
  const actualRenderer = state.internal.actualRenderer;
14692
14380
  const handleSessionChange = () => {
@@ -14698,16 +14386,16 @@ function createRoot(canvas) {
14698
14386
  };
14699
14387
  const xr = {
14700
14388
  connect() {
14701
- const { gl, renderer: renderer2, isLegacy } = store.getState();
14702
- const actualRenderer2 = renderer2 || gl;
14703
- actualRenderer2.xr.addEventListener("sessionstart", handleSessionChange);
14704
- 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);
14705
14393
  },
14706
14394
  disconnect() {
14707
- const { gl, renderer: renderer2, isLegacy } = store.getState();
14708
- const actualRenderer2 = renderer2 || gl;
14709
- actualRenderer2.xr.removeEventListener("sessionstart", handleSessionChange);
14710
- 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);
14711
14399
  }
14712
14400
  };
14713
14401
  if (typeof renderer.xr?.addEventListener === "function") xr.connect();
@@ -14719,15 +14407,22 @@ function createRoot(canvas) {
14719
14407
  const oldType = renderer.shadowMap.type;
14720
14408
  renderer.shadowMap.enabled = !!shadows;
14721
14409
  if (is.boo(shadows)) {
14722
- renderer.shadowMap.type = three.PCFSoftShadowMap;
14410
+ renderer.shadowMap.type = three.PCFShadowMap;
14723
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
+ }
14724
14419
  const types = {
14725
14420
  basic: three.BasicShadowMap,
14726
14421
  percentage: three.PCFShadowMap,
14727
- soft: three.PCFSoftShadowMap,
14422
+ soft: three.PCFShadowMap,
14728
14423
  variance: three.VSMShadowMap
14729
14424
  };
14730
- renderer.shadowMap.type = types[shadows] ?? three.PCFSoftShadowMap;
14425
+ renderer.shadowMap.type = types[shadows] ?? three.PCFShadowMap;
14731
14426
  } else if (is.obj(shadows)) {
14732
14427
  Object.assign(renderer.shadowMap, shadows);
14733
14428
  }
@@ -14735,48 +14430,70 @@ function createRoot(canvas) {
14735
14430
  renderer.shadowMap.needsUpdate = true;
14736
14431
  }
14737
14432
  }
14738
- {
14739
- const legacyChanged = legacy !== lastConfiguredProps.legacy;
14740
- const linearChanged = linear !== lastConfiguredProps.linear;
14741
- const flatChanged = flat !== lastConfiguredProps.flat;
14742
- if (legacyChanged) {
14743
- three.ColorManagement.enabled = !legacy;
14744
- lastConfiguredProps.legacy = legacy;
14745
- }
14746
- if (!configured || linearChanged) {
14747
- renderer.outputColorSpace = linear ? three.LinearSRGBColorSpace : three.SRGBColorSpace;
14748
- lastConfiguredProps.linear = linear;
14749
- }
14750
- if (!configured || flatChanged) {
14751
- renderer.toneMapping = flat ? three.NoToneMapping : three.ACESFilmicToneMapping;
14752
- lastConfiguredProps.flat = flat;
14753
- }
14754
- if (legacyChanged && state.legacy !== legacy) state.set(() => ({ legacy }));
14755
- if (linearChanged && state.linear !== linear) state.set(() => ({ linear }));
14756
- if (flatChanged && state.flat !== flat) state.set(() => ({ flat }));
14433
+ if (!configured) {
14434
+ renderer.outputColorSpace = three.SRGBColorSpace;
14435
+ renderer.toneMapping = three.ACESFilmicToneMapping;
14757
14436
  }
14758
14437
  if (textureColorSpace !== lastConfiguredProps.textureColorSpace) {
14759
14438
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
14760
14439
  lastConfiguredProps.textureColorSpace = textureColorSpace;
14761
14440
  }
14441
+ const r3fProps = ["textureColorSpace"];
14442
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14443
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
14762
14444
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
14763
- applyProps(renderer, glConfig);
14445
+ const glProps = {};
14446
+ for (const key in glConfig) {
14447
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14448
+ }
14449
+ applyProps(renderer, glProps);
14764
14450
  }
14765
14451
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
14766
14452
  const currentRenderer = state.renderer;
14767
14453
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
14768
- 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);
14769
14459
  }
14770
14460
  }
14771
- const scheduler = getScheduler();
14461
+ const scheduler$1 = scheduler.getScheduler();
14772
14462
  const rootId = state.internal.rootId;
14773
14463
  if (!rootId) {
14774
- const newRootId = scheduler.generateRootId();
14775
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14464
+ const newRootId = canvasId || scheduler$1.generateRootId();
14465
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
14776
14466
  getState: () => store.getState(),
14777
14467
  onError: (err) => store.getState().setError(err)
14778
14468
  });
14779
- 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(
14780
14497
  () => {
14781
14498
  const state2 = store.getState();
14782
14499
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -14786,11 +14503,11 @@ function createRoot(canvas) {
14786
14503
  {
14787
14504
  id: `${newRootId}_frustum`,
14788
14505
  rootId: newRootId,
14789
- phase: "preRender",
14506
+ before: "render",
14790
14507
  system: true
14791
14508
  }
14792
14509
  );
14793
- const unregisterVisibility = scheduler.register(
14510
+ const unregisterVisibility = scheduler$1.register(
14794
14511
  () => {
14795
14512
  const state2 = store.getState();
14796
14513
  checkVisibility(state2);
@@ -14798,30 +14515,34 @@ function createRoot(canvas) {
14798
14515
  {
14799
14516
  id: `${newRootId}_visibility`,
14800
14517
  rootId: newRootId,
14801
- phase: "preRender",
14518
+ before: "render",
14802
14519
  system: true,
14803
14520
  after: `${newRootId}_frustum`
14804
14521
  }
14805
14522
  );
14806
- const unregisterRender = scheduler.register(
14523
+ const unregisterRender = scheduler$1.register(
14807
14524
  () => {
14808
14525
  const state2 = store.getState();
14809
14526
  const renderer2 = state2.internal.actualRenderer;
14810
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14527
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
14811
14528
  if (userHandlesRender || state2.internal.priority) return;
14812
14529
  try {
14813
- if (state2.postProcessing?.render) state2.postProcessing.render();
14530
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
14814
14531
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
14815
14532
  } catch (error) {
14816
14533
  state2.setError(error instanceof Error ? error : new Error(String(error)));
14817
14534
  }
14818
14535
  },
14819
14536
  {
14820
- id: `${newRootId}_render`,
14537
+ // Use canvas ID directly as job ID if available, otherwise use generated rootId
14538
+ id: canvasId || `${newRootId}_render`,
14821
14539
  rootId: newRootId,
14822
14540
  phase: "render",
14823
- system: true
14541
+ system: true,
14824
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 }
14825
14546
  }
14826
14547
  );
14827
14548
  state.set((state2) => ({
@@ -14830,15 +14551,17 @@ function createRoot(canvas) {
14830
14551
  rootId: newRootId,
14831
14552
  unregisterRoot: () => {
14832
14553
  unregisterRoot();
14554
+ unregisterCanvasTarget();
14555
+ unregisterEventsFlush();
14833
14556
  unregisterFrustum();
14834
14557
  unregisterVisibility();
14835
14558
  unregisterRender();
14836
14559
  },
14837
- scheduler
14560
+ scheduler: scheduler$1
14838
14561
  }
14839
14562
  }));
14840
14563
  }
14841
- scheduler.frameloop = frameloop;
14564
+ scheduler$1.frameloop = frameloop;
14842
14565
  onCreated = onCreatedCallback;
14843
14566
  configured = true;
14844
14567
  resolve();
@@ -14888,15 +14611,24 @@ function unmountComponentAtNode(canvas, callback) {
14888
14611
  const renderer = state.internal.actualRenderer;
14889
14612
  const unregisterRoot = state.internal.unregisterRoot;
14890
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();
14891
14618
  state.events.disconnect?.();
14892
14619
  cleanupHelperGroup(root.store);
14893
- renderer?.renderLists?.dispose?.();
14894
- renderer?.forceContextLoss?.();
14895
- 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
+ }
14896
14628
  dispose(state.scene);
14897
14629
  _roots.delete(canvas);
14898
14630
  if (callback) callback(canvas);
14899
- } catch (e) {
14631
+ } catch {
14900
14632
  }
14901
14633
  }, 500);
14902
14634
  }
@@ -14904,36 +14636,34 @@ function unmountComponentAtNode(canvas, callback) {
14904
14636
  }
14905
14637
  }
14906
14638
  function createPortal(children, container, state) {
14907
- return /* @__PURE__ */ jsxRuntime.jsx(PortalWrapper, { children, container, state });
14639
+ return /* @__PURE__ */ jsxRuntime.jsx(Portal, { children, container, state });
14908
14640
  }
14909
- function PortalWrapper({ children, container, state }) {
14641
+ function Portal({ children, container, state }) {
14910
14642
  const isRef = React.useCallback((obj) => obj && "current" in obj, []);
14911
- const [resolvedContainer, setResolvedContainer] = React.useState(() => {
14643
+ const [resolvedContainer, _setResolvedContainer] = React.useState(() => {
14912
14644
  if (isRef(container)) return container.current ?? null;
14913
14645
  return container;
14914
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
+ );
14915
14654
  React.useMemo(() => {
14916
- if (isRef(container)) {
14917
- const current = container.current;
14918
- if (!current) {
14919
- queueMicrotask(() => {
14920
- const updated = container.current;
14921
- if (updated && updated !== resolvedContainer) {
14922
- setResolvedContainer(updated);
14923
- }
14924
- });
14925
- } else if (current !== resolvedContainer) {
14926
- setResolvedContainer(current);
14927
- }
14928
- } else if (container !== resolvedContainer) {
14929
- setResolvedContainer(container);
14655
+ if (isRef(container) && !container.current) {
14656
+ return queueMicrotask(() => {
14657
+ setResolvedContainer(container.current);
14658
+ });
14930
14659
  }
14931
- }, [container, resolvedContainer, isRef]);
14660
+ setResolvedContainer(container);
14661
+ }, [container, isRef, setResolvedContainer]);
14932
14662
  if (!resolvedContainer) return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, {});
14933
14663
  const portalKey = resolvedContainer.uuid ?? `portal-${resolvedContainer.id ?? "unknown"}`;
14934
- return /* @__PURE__ */ jsxRuntime.jsx(Portal, { children, container: resolvedContainer, state }, portalKey);
14664
+ return /* @__PURE__ */ jsxRuntime.jsx(PortalInner, { children, container: resolvedContainer, state }, portalKey);
14935
14665
  }
14936
- function Portal({ state = {}, children, container }) {
14666
+ function PortalInner({ state = {}, children, container }) {
14937
14667
  const { events, size, injectScene = true, ...rest } = state;
14938
14668
  const previousRoot = useStore();
14939
14669
  const [raycaster] = React.useState(() => new three.Raycaster());
@@ -14954,12 +14684,14 @@ function Portal({ state = {}, children, container }) {
14954
14684
  };
14955
14685
  }, [portalScene, container, injectScene]);
14956
14686
  const inject = useMutableCallback((rootState, injectState) => {
14687
+ const resolvedSize = { ...rootState.size, ...injectState.size, ...size };
14957
14688
  let viewport = void 0;
14958
- if (injectState.camera && size) {
14689
+ if (injectState.camera && (size || injectState.size)) {
14959
14690
  const camera = injectState.camera;
14960
- viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), size);
14961
- 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);
14962
14693
  }
14694
+ const set = injectState.set;
14963
14695
  return {
14964
14696
  // The intersect consists of the previous root state
14965
14697
  ...rootState,
@@ -14975,10 +14707,10 @@ function Portal({ state = {}, children, container }) {
14975
14707
  previousRoot,
14976
14708
  // Events, size and viewport can be overridden by the inject layer
14977
14709
  events: { ...rootState.events, ...injectState.events, ...events },
14978
- size: { ...rootState.size, ...size },
14710
+ size: resolvedSize,
14979
14711
  viewport: { ...rootState.viewport, ...viewport },
14980
14712
  // Layers are allowed to override events
14981
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14713
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14982
14714
  // Container for child attachment - the portalScene (injected or container itself)
14983
14715
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
14984
14716
  };
@@ -14987,9 +14719,13 @@ function Portal({ state = {}, children, container }) {
14987
14719
  const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14988
14720
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14989
14721
  onMutate(previousRoot.getState());
14990
- previousRoot.subscribe(onMutate);
14991
14722
  return store;
14992
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]);
14993
14729
  return (
14994
14730
  // @ts-ignore, reconciler types are not maintained
14995
14731
  /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
@@ -15003,21 +14739,72 @@ function flushSync(fn) {
15003
14739
  return reconciler.flushSyncFromReconciler(fn);
15004
14740
  }
15005
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
+
15006
14795
  function CanvasImpl({
15007
14796
  ref,
15008
14797
  children,
15009
14798
  fallback,
15010
14799
  resize,
15011
14800
  style,
14801
+ id,
15012
14802
  gl,
15013
- renderer,
14803
+ renderer: rendererProp,
15014
14804
  events = createPointerEvents,
15015
14805
  eventSource,
15016
14806
  eventPrefix,
15017
14807
  shadows,
15018
- linear,
15019
- flat,
15020
- legacy,
15021
14808
  orthographic,
15022
14809
  frameloop,
15023
14810
  dpr,
@@ -15025,6 +14812,8 @@ function CanvasImpl({
15025
14812
  raycaster,
15026
14813
  camera,
15027
14814
  scene,
14815
+ autoUpdateFrustum,
14816
+ occlusion,
15028
14817
  onPointerMissed,
15029
14818
  onDragOverMissed,
15030
14819
  onDropMissed,
@@ -15032,10 +14821,14 @@ function CanvasImpl({
15032
14821
  hmr,
15033
14822
  width,
15034
14823
  height,
14824
+ background,
14825
+ forceEven,
15035
14826
  ...props
15036
14827
  }) {
14828
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15037
14829
  React__namespace.useMemo(() => extend(THREE), []);
15038
14830
  const Bridge = useBridge();
14831
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15039
14832
  const hasInitialSizeRef = React__namespace.useRef(false);
15040
14833
  const measureConfig = React__namespace.useMemo(() => {
15041
14834
  if (!hasInitialSizeRef.current) {
@@ -15052,15 +14845,20 @@ function CanvasImpl({
15052
14845
  };
15053
14846
  }, [resize, hasInitialSizeRef.current]);
15054
14847
  const [containerRef, containerRect] = useMeasure__default(measureConfig);
15055
- const effectiveSize = React__namespace.useMemo(
15056
- () => ({
15057
- width: width ?? containerRect.width,
15058
- height: height ?? containerRect.height,
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,
15059
14858
  top: containerRect.top,
15060
14859
  left: containerRect.left
15061
- }),
15062
- [width, height, containerRect]
15063
- );
14860
+ };
14861
+ }, [width, height, containerRect, forceEven]);
15064
14862
  if (!hasInitialSizeRef.current && effectiveSize.width > 0 && effectiveSize.height > 0) {
15065
14863
  hasInitialSizeRef.current = true;
15066
14864
  }
@@ -15072,6 +14870,7 @@ function CanvasImpl({
15072
14870
  const handleDropMissed = useMutableCallback(onDropMissed);
15073
14871
  const [block, setBlock] = React__namespace.useState(false);
15074
14872
  const [error, setError] = React__namespace.useState(false);
14873
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15075
14874
  if (block) throw block;
15076
14875
  if (error) throw error;
15077
14876
  const root = React__namespace.useRef(null);
@@ -15079,6 +14878,7 @@ function CanvasImpl({
15079
14878
  const unsubscribeErrorRef = React__namespace.useRef(null);
15080
14879
  useIsomorphicLayoutEffect(() => {
15081
14880
  effectActiveRef.current = true;
14881
+ if (fallbackVisible) return;
15082
14882
  const canvas = canvasRef.current;
15083
14883
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15084
14884
  if (!root.current) {
@@ -15099,24 +14899,27 @@ function CanvasImpl({
15099
14899
  }
15100
14900
  async function run() {
15101
14901
  if (!effectActiveRef.current || !root.current) return;
15102
- await root.current.configure({
14902
+ const configured = await root.current.configure({
14903
+ id,
14904
+ primaryCanvas,
14905
+ scheduler,
15103
14906
  gl,
15104
14907
  renderer,
15105
14908
  scene,
15106
14909
  events,
15107
14910
  shadows,
15108
- linear,
15109
- flat,
15110
- legacy,
15111
14911
  orthographic,
15112
14912
  frameloop,
15113
14913
  dpr,
15114
14914
  performance,
15115
14915
  raycaster,
15116
14916
  camera,
14917
+ autoUpdateFrustum,
14918
+ occlusion,
15117
14919
  size: effectiveSize,
15118
14920
  // Store size props for reset functionality
15119
14921
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
14922
+ forceEven,
15120
14923
  // Pass mutable reference to onPointerMissed so it's free to update
15121
14924
  onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
15122
14925
  onDragOverMissed: (...args) => handleDragOverMissed.current?.(...args),
@@ -15137,10 +14940,25 @@ function CanvasImpl({
15137
14940
  }
15138
14941
  onCreated?.(state);
15139
14942
  }
15140
- });
15141
- 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;
15142
14957
  root.current.render(
15143
- /* @__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
+ ] }) }) })
15144
14962
  );
15145
14963
  }
15146
14964
  run();
@@ -15167,20 +14985,15 @@ function CanvasImpl({
15167
14985
  const canvas = canvasRef.current;
15168
14986
  if (!canvas) return;
15169
14987
  const handleHMR = () => {
15170
- const rootEntry = _roots.get(canvas);
15171
- if (rootEntry?.store) {
15172
- rootEntry.store.setState((state) => ({
15173
- nodes: {},
15174
- uniforms: {},
15175
- _hmrVersion: state._hmrVersion + 1
15176
- }));
15177
- }
14988
+ queueMicrotask(() => {
14989
+ const rootEntry = _roots.get(canvas);
14990
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
14991
+ });
15178
14992
  };
15179
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) {
15180
14994
  const hot = undefined;
15181
14995
  hot.on("vite:afterUpdate", handleHMR);
15182
- return () => hot.dispose?.(() => {
15183
- });
14996
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
15184
14997
  }
15185
14998
  if (typeof module !== "undefined" && module.hot) {
15186
14999
  const hot = module.hot;
@@ -15203,7 +15016,20 @@ function CanvasImpl({
15203
15016
  ...style
15204
15017
  },
15205
15018
  ...props,
15206
- 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
+ ) })
15207
15033
  }
15208
15034
  );
15209
15035
  }
@@ -15213,15 +15039,23 @@ function Canvas(props) {
15213
15039
 
15214
15040
  extend(THREE);
15215
15041
 
15042
+ exports.Scheduler = scheduler.Scheduler;
15043
+ exports.getScheduler = scheduler.getScheduler;
15216
15044
  exports.Block = Block;
15217
15045
  exports.Canvas = Canvas;
15046
+ exports.Environment = Environment;
15047
+ exports.EnvironmentCube = EnvironmentCube;
15048
+ exports.EnvironmentMap = EnvironmentMap;
15049
+ exports.EnvironmentPortal = EnvironmentPortal;
15218
15050
  exports.ErrorBoundary = ErrorBoundary;
15051
+ exports.FROM_REF = FROM_REF;
15219
15052
  exports.IsObject = IsObject;
15053
+ exports.ONCE = ONCE;
15054
+ exports.Portal = Portal;
15220
15055
  exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15221
15056
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15222
15057
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15223
15058
  exports.RESERVED_PROPS = RESERVED_PROPS;
15224
- exports.Scheduler = Scheduler;
15225
15059
  exports.Texture = Texture;
15226
15060
  exports._roots = _roots;
15227
15061
  exports.act = act;
@@ -15246,30 +15080,40 @@ exports.events = createPointerEvents;
15246
15080
  exports.extend = extend;
15247
15081
  exports.findInitialRoot = findInitialRoot;
15248
15082
  exports.flushSync = flushSync;
15083
+ exports.fromRef = fromRef;
15249
15084
  exports.getInstanceProps = getInstanceProps;
15085
+ exports.getPrimary = getPrimary;
15086
+ exports.getPrimaryIds = getPrimaryIds;
15250
15087
  exports.getRootState = getRootState;
15251
- exports.getScheduler = getScheduler;
15252
15088
  exports.getUuidPrefix = getUuidPrefix;
15253
15089
  exports.hasConstructor = hasConstructor;
15090
+ exports.hasPrimary = hasPrimary;
15254
15091
  exports.invalidate = invalidate;
15255
15092
  exports.invalidateInstance = invalidateInstance;
15256
15093
  exports.is = is;
15257
15094
  exports.isColorRepresentation = isColorRepresentation;
15258
15095
  exports.isCopyable = isCopyable;
15096
+ exports.isFromRef = isFromRef;
15259
15097
  exports.isObject3D = isObject3D;
15098
+ exports.isOnce = isOnce;
15260
15099
  exports.isOrthographicCamera = isOrthographicCamera;
15261
15100
  exports.isRef = isRef;
15262
15101
  exports.isRenderer = isRenderer;
15263
15102
  exports.isTexture = isTexture;
15264
15103
  exports.isVectorLike = isVectorLike;
15104
+ exports.once = once;
15265
15105
  exports.prepare = prepare;
15106
+ exports.presetsObj = presetsObj;
15266
15107
  exports.reconciler = reconciler;
15108
+ exports.registerPrimary = registerPrimary;
15267
15109
  exports.removeInteractivity = removeInteractivity;
15268
15110
  exports.resolve = resolve;
15269
15111
  exports.unmountComponentAtNode = unmountComponentAtNode;
15112
+ exports.unregisterPrimary = unregisterPrimary;
15270
15113
  exports.updateCamera = updateCamera;
15271
15114
  exports.updateFrustum = updateFrustum;
15272
15115
  exports.useBridge = useBridge;
15116
+ exports.useEnvironment = useEnvironment;
15273
15117
  exports.useFrame = useFrame;
15274
15118
  exports.useGraph = useGraph;
15275
15119
  exports.useInstanceHandle = useInstanceHandle;
@@ -15281,3 +15125,4 @@ exports.useStore = useStore;
15281
15125
  exports.useTexture = useTexture;
15282
15126
  exports.useTextures = useTextures;
15283
15127
  exports.useThree = useThree;
15128
+ exports.waitForPrimary = waitForPrimary;