@react-three/fiber 10.0.0-alpha.1 → 10.0.0-canary.164c7be

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