@react-three/fiber 10.0.0-canary.c3fa45d → 10.0.0-canary.c5c1a94

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.
@@ -1,5 +1,5 @@
1
1
  import * as webgpu from 'three/webgpu';
2
- import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, PostProcessing } from 'three/webgpu';
2
+ import { CubeRenderTarget, RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, RenderPipeline } from 'three/webgpu';
3
3
  import { Inspector } from 'three/addons/inspector/Inspector.js';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
  import * as React from 'react';
@@ -12,8 +12,10 @@ import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
12
12
  import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js';
13
13
  import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
14
14
  import { GainMapLoader } from '@monogrid/gainmap-js';
15
- import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
15
+ import Tb, { unstable_getCurrentPriorityLevel, unstable_IdlePriority, unstable_LowPriority, unstable_NormalPriority, unstable_UserBlockingPriority, unstable_ImmediatePriority, unstable_scheduleCallback } from 'scheduler';
16
16
  import { createWithEqualityFn } from 'zustand/traditional';
17
+ import { getScheduler } from '@pmndrs/scheduler';
18
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
17
19
  import { suspend, preload, clear } from 'suspend-react';
18
20
  import { dequal } from 'dequal/lite';
19
21
  import 'zustand/shallow';
@@ -41,13 +43,16 @@ const WebGLRenderer = class WebGLRenderer2 {
41
43
  }
42
44
  };
43
45
  const WebGLRenderTarget = null;
46
+ const WebGLCubeRenderTarget = null;
44
47
 
45
48
  const THREE = /*#__PURE__*/_mergeNamespaces({
46
49
  __proto__: null,
50
+ CubeRenderTargetCompat: CubeRenderTarget,
47
51
  Inspector: Inspector,
48
52
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
49
53
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
50
54
  RenderTargetCompat: RenderTarget,
55
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
51
56
  WebGLRenderTarget: WebGLRenderTarget,
52
57
  WebGLRenderer: WebGLRenderer
53
58
  }, [webgpu]);
@@ -321,15 +326,16 @@ function EnvironmentPortal({
321
326
  preset = void 0,
322
327
  extensions
323
328
  }) {
324
- const gl = useThree$1((state) => state.gl);
329
+ const renderer = useThree$1((state) => state.renderer);
330
+ const isLegacy = useThree$1((state) => state.isLegacy);
325
331
  const defaultScene = useThree$1((state) => state.scene);
326
332
  const camera = React.useRef(null);
327
333
  const [virtualScene] = React.useState(() => new Scene());
328
334
  const fbo = React.useMemo(() => {
329
- const fbo2 = new WebGLCubeRenderTarget(resolution);
335
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
330
336
  fbo2.texture.type = HalfFloatType;
331
337
  return fbo2;
332
- }, [resolution]);
338
+ }, [resolution, isLegacy]);
333
339
  React.useEffect(() => {
334
340
  return () => {
335
341
  fbo.dispose();
@@ -337,10 +343,10 @@ function EnvironmentPortal({
337
343
  }, [fbo]);
338
344
  React.useLayoutEffect(() => {
339
345
  if (frames === 1) {
340
- const autoClear = gl.autoClear;
341
- gl.autoClear = true;
342
- camera.current.update(gl, virtualScene);
343
- gl.autoClear = autoClear;
346
+ const autoClear = renderer.autoClear;
347
+ renderer.autoClear = true;
348
+ camera.current.update(renderer, virtualScene);
349
+ renderer.autoClear = autoClear;
344
350
  }
345
351
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
346
352
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -357,7 +363,7 @@ function EnvironmentPortal({
357
363
  defaultScene,
358
364
  background,
359
365
  frames,
360
- gl,
366
+ renderer,
361
367
  blur,
362
368
  backgroundBlurriness,
363
369
  backgroundIntensity,
@@ -368,10 +374,10 @@ function EnvironmentPortal({
368
374
  let count = 1;
369
375
  useFrame$1(() => {
370
376
  if (frames === Infinity || count < frames) {
371
- const autoClear = gl.autoClear;
372
- gl.autoClear = true;
373
- camera.current.update(gl, virtualScene);
374
- gl.autoClear = autoClear;
377
+ const autoClear = renderer.autoClear;
378
+ renderer.autoClear = true;
379
+ camera.current.update(renderer, virtualScene);
380
+ renderer.autoClear = autoClear;
375
381
  count++;
376
382
  }
377
383
  });
@@ -435,10 +441,9 @@ function Environment(props) {
435
441
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
436
442
  }
437
443
 
438
- var __defProp$3 = Object.defineProperty;
439
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
440
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
441
- const act = React["act"];
444
+ var __defProp$1 = Object.defineProperty;
445
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
446
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
442
447
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
443
448
  function useMutableCallback(fn) {
444
449
  const ref = React.useRef(fn);
@@ -469,7 +474,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
469
474
  return _a = class extends React.Component {
470
475
  constructor() {
471
476
  super(...arguments);
472
- __publicField$3(this, "state", { error: false });
477
+ __publicField$1(this, "state", { error: false });
473
478
  }
474
479
  componentDidCatch(err) {
475
480
  this.props.set(err);
@@ -477,7 +482,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
477
482
  render() {
478
483
  return this.state.error ? null : this.props.children;
479
484
  }
480
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
485
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
481
486
  })();
482
487
 
483
488
  const is = {
@@ -614,8 +619,7 @@ function prepare(target, root, type, props) {
614
619
  object,
615
620
  eventCount: 0,
616
621
  handlers: {},
617
- isHidden: false,
618
- deferredRefs: []
622
+ isHidden: false
619
623
  };
620
624
  if (object) object.__r3f = instance;
621
625
  }
@@ -772,6 +776,17 @@ function unregisterVisibility(store, object) {
772
776
  internal.visibilityRegistry.delete(object.uuid);
773
777
  internal.occlusionCache.delete(object);
774
778
  }
779
+ function updateVisibilityHandlers(store, object, handlers) {
780
+ const { internal } = store.getState();
781
+ const entry = internal.visibilityRegistry.get(object.uuid);
782
+ if (!entry) return false;
783
+ entry.handlers = handlers;
784
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
785
+ object.occlusionTest = true;
786
+ enableOcclusion(store);
787
+ }
788
+ return true;
789
+ }
775
790
  function checkVisibility(state) {
776
791
  const { internal, camera } = state;
777
792
  const registry = internal.visibilityRegistry;
@@ -932,9 +947,9 @@ function diffProps(instance, newProps) {
932
947
  const { root, key } = resolve(instance.object, prop);
933
948
  if (root.constructor && root.constructor.length === 0) {
934
949
  const ctor = getMemoizedPrototype(root);
935
- if (!is.und(ctor)) changedProps[key] = ctor[key];
950
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
936
951
  } else {
937
- changedProps[key] = 0;
952
+ changedProps[prop] = 0;
938
953
  }
939
954
  }
940
955
  return changedProps;
@@ -959,10 +974,7 @@ function applyProps(object, props) {
959
974
  continue;
960
975
  }
961
976
  if (value === void 0) continue;
962
- if (isFromRef(value)) {
963
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
964
- continue;
965
- }
977
+ if (isFromRef(value)) continue;
966
978
  if (isOnce(value)) {
967
979
  if (instance?.appliedOnce?.has(prop)) continue;
968
980
  if (instance) {
@@ -998,6 +1010,19 @@ function applyProps(object, props) {
998
1010
  } else if (isVectorLike(target) && is.num(value)) {
999
1011
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1000
1012
  else target.set(value);
1013
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1014
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1015
+ const uniforms = root.uniforms;
1016
+ const nextUniforms = value;
1017
+ for (const name in nextUniforms) {
1018
+ const uniform = nextUniforms[name];
1019
+ const targetUniform = uniforms[name];
1020
+ if (targetUniform) Object.assign(targetUniform, uniform);
1021
+ else {
1022
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1023
+ uniforms[name] = nextUniform;
1024
+ }
1025
+ }
1001
1026
  } else {
1002
1027
  root[key] = value;
1003
1028
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1016,6 +1041,9 @@ function applyProps(object, props) {
1016
1041
  if (instance.eventCount && object2.raycast !== null) {
1017
1042
  rootState.internal.interaction.push(object2);
1018
1043
  }
1044
+ }
1045
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1046
+ const object2 = instance.object;
1019
1047
  const root = findInitialRoot(instance);
1020
1048
  const visibilityHandlers = {
1021
1049
  onFramed: instance.handlers.onFramed,
@@ -1023,7 +1051,9 @@ function applyProps(object, props) {
1023
1051
  onVisible: instance.handlers.onVisible
1024
1052
  };
1025
1053
  if (hasVisibilityHandlers(visibilityHandlers)) {
1026
- registerVisibility(root, object2, visibilityHandlers);
1054
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1055
+ registerVisibility(root, object2, visibilityHandlers);
1056
+ }
1027
1057
  } else {
1028
1058
  unregisterVisibility(root, object2);
1029
1059
  }
@@ -1551,6 +1581,7 @@ function createPointerEvents(store) {
1551
1581
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1552
1582
  }
1553
1583
  },
1584
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1554
1585
  registerPointer: (config) => {
1555
1586
  const pointerId = nextXRPointerId++;
1556
1587
  xrPointers.set(pointerId, config);
@@ -1637,1229 +1668,206 @@ function notifyAlpha({ message, link }) {
1637
1668
  }
1638
1669
  }
1639
1670
 
1640
- var __defProp$2 = Object.defineProperty;
1641
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1642
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1643
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1644
- class PhaseGraph {
1645
- constructor() {
1646
- /** Ordered list of phase nodes */
1647
- __publicField$2(this, "phases", []);
1648
- /** Quick lookup by name */
1649
- __publicField$2(this, "phaseMap", /* @__PURE__ */ new Map());
1650
- /** Cached ordered names (invalidated on changes) */
1651
- __publicField$2(this, "orderedNamesCache", null);
1652
- this.initializeDefaultPhases();
1653
- }
1654
- //* Initialization --------------------------------
1655
- initializeDefaultPhases() {
1656
- for (const name of DEFAULT_PHASES) {
1657
- const node = { name, isAutoGenerated: false };
1658
- this.phases.push(node);
1659
- this.phaseMap.set(name, node);
1660
- }
1661
- this.invalidateCache();
1662
- }
1663
- //* Public API --------------------------------
1664
- /**
1665
- * Add a named phase to the graph
1666
- * @param name - Phase name (must be unique)
1667
- * @param options - Position options (before or after another phase)
1668
- */
1669
- addPhase(name, options = {}) {
1670
- if (this.phaseMap.has(name)) {
1671
- console.warn(`[useFrame] Phase "${name}" already exists`);
1672
- return;
1673
- }
1674
- const { before, after } = options;
1675
- const node = { name, isAutoGenerated: false };
1676
- let insertIndex = this.phases.length;
1677
- const targetIndex = this.getPhaseIndex(before ?? after);
1678
- if (targetIndex !== -1) {
1679
- insertIndex = before ? targetIndex : targetIndex + 1;
1680
- } else {
1681
- const constraintType = before ? "before" : "after";
1682
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1683
- }
1684
- this.phases.splice(insertIndex, 0, node);
1685
- this.phaseMap.set(name, node);
1686
- this.invalidateCache();
1687
- }
1688
- /**
1689
- * Get ordered list of phase names
1690
- */
1691
- getOrderedPhases() {
1692
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1693
- return this.orderedNamesCache;
1694
- }
1695
- /**
1696
- * Check if a phase exists
1697
- */
1698
- hasPhase(name) {
1699
- return this.phaseMap.has(name);
1700
- }
1701
- /**
1702
- * Get the index of a phase (-1 if not found)
1703
- */
1704
- getPhaseIndex(name) {
1705
- if (!name) return -1;
1706
- return this.phases.findIndex((p) => p.name === name);
1707
- }
1708
- /**
1709
- * Ensure a phase exists, creating an auto-generated one if needed.
1710
- * Used for resolving before/after constraints.
1711
- *
1712
- * @param name - The phase name to ensure exists
1713
- * @returns The phase name (may be auto-generated like 'before:render')
1714
- */
1715
- ensurePhase(name) {
1716
- if (this.phaseMap.has(name)) return name;
1717
- const node = { name, isAutoGenerated: true };
1718
- this.phases.push(node);
1719
- this.phaseMap.set(name, node);
1720
- this.invalidateCache();
1721
- return name;
1722
- }
1723
- /**
1724
- * Resolve where a job with before/after constraints should go.
1725
- * Creates auto-generated phases if needed.
1726
- *
1727
- * @param before - Phase(s) to run before
1728
- * @param after - Phase(s) to run after
1729
- * @returns The resolved phase name
1730
- */
1731
- resolveConstraintPhase(before, after) {
1732
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1733
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1734
- if (beforeArr.length > 0) {
1735
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1736
- }
1737
- if (afterArr.length > 0) {
1738
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1739
- }
1740
- return "update";
1741
- }
1742
- /**
1743
- * Ensure an auto-generated phase exists relative to a target phase.
1744
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1745
- *
1746
- * @param target - The target phase name to position relative to
1747
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1748
- * @param offset - Insertion offset (0 for before, 1 for after)
1749
- * @returns The auto-generated phase name
1750
- */
1751
- ensureAutoPhase(target, prefix, offset) {
1752
- const autoName = `${prefix}:${target}`;
1753
- if (this.phaseMap.has(autoName)) return autoName;
1754
- const node = { name: autoName, isAutoGenerated: true };
1755
- const targetIndex = this.getPhaseIndex(target);
1756
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1757
- else this.phases.push(node);
1758
- this.phaseMap.set(autoName, node);
1759
- this.invalidateCache();
1760
- return autoName;
1761
- }
1762
- // Internal --------------------------------
1763
- invalidateCache() {
1764
- this.orderedNamesCache = null;
1765
- }
1671
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1672
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1673
+ if (!stack) return false;
1674
+ const caller = stack.split("\n")[callerDepth] ?? "";
1675
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1766
1676
  }
1767
1677
 
1768
- function rebuildSortedJobs(jobs, phaseGraph) {
1769
- const orderedPhases = phaseGraph.getOrderedPhases();
1770
- const buckets = /* @__PURE__ */ new Map();
1771
- for (const phase of orderedPhases) {
1772
- buckets.set(phase, []);
1773
- }
1774
- for (const job of jobs.values()) {
1775
- if (!job.enabled) continue;
1776
- let bucket = buckets.get(job.phase);
1777
- if (!bucket) {
1778
- bucket = [];
1779
- buckets.set(job.phase, bucket);
1780
- }
1781
- bucket.push(job);
1782
- }
1783
- const sortedBuckets = [];
1784
- for (const phase of orderedPhases) {
1785
- const bucket = buckets.get(phase);
1786
- if (!bucket || bucket.length === 0) continue;
1787
- bucket.sort((a, b) => {
1788
- if (a.priority !== b.priority) return b.priority - a.priority;
1789
- return a.index - b.index;
1790
- });
1791
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1792
- }
1793
- for (const [phase, bucket] of buckets) {
1794
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1795
- bucket.sort((a, b) => {
1796
- if (a.priority !== b.priority) return b.priority - a.priority;
1797
- return a.index - b.index;
1798
- });
1799
- sortedBuckets.push(bucket);
1800
- }
1801
- }
1802
- return sortedBuckets.flat();
1803
- }
1804
- function hasCrossJobConstraints(bucket) {
1805
- const jobIds = new Set(bucket.map((j) => j.id));
1806
- for (const job of bucket) {
1807
- for (const ref of job.before) {
1808
- if (jobIds.has(ref)) return true;
1809
- }
1810
- for (const ref of job.after) {
1811
- if (jobIds.has(ref)) return true;
1812
- }
1813
- }
1814
- return false;
1815
- }
1816
- function topologicalSort(jobs) {
1817
- const n = jobs.length;
1818
- if (n <= 1) return jobs;
1819
- const jobMap = /* @__PURE__ */ new Map();
1820
- const inDegree = /* @__PURE__ */ new Map();
1821
- const adjacency = /* @__PURE__ */ new Map();
1822
- for (const job of jobs) {
1823
- jobMap.set(job.id, job);
1824
- inDegree.set(job.id, 0);
1825
- adjacency.set(job.id, []);
1826
- }
1827
- for (const job of jobs) {
1828
- for (const ref of job.before) {
1829
- if (jobMap.has(ref)) {
1830
- adjacency.get(job.id).push(ref);
1831
- inDegree.set(ref, inDegree.get(ref) + 1);
1678
+ const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1679
+ const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
1680
+ const createStore = (invalidate, advance) => {
1681
+ const rootStore = createWithEqualityFn((set, get) => {
1682
+ const position = new Vector3();
1683
+ const defaultTarget = new Vector3();
1684
+ const tempTarget = new Vector3();
1685
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1686
+ const { width, height, top, left } = size;
1687
+ const aspect = width / height;
1688
+ if (target.isVector3) tempTarget.copy(target);
1689
+ else tempTarget.set(...target);
1690
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1691
+ if (isOrthographicCamera(camera)) {
1692
+ return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
1693
+ } else {
1694
+ const fov = camera.fov * Math.PI / 180;
1695
+ const h = 2 * Math.tan(fov / 2) * distance;
1696
+ const w = h * (width / height);
1697
+ return { width: w, height: h, top, left, factor: width / w, distance, aspect };
1832
1698
  }
1833
1699
  }
1834
- for (const ref of job.after) {
1835
- if (jobMap.has(ref)) {
1836
- adjacency.get(ref).push(job.id);
1837
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1700
+ let performanceTimeout = void 0;
1701
+ const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
1702
+ const pointer = new Vector2();
1703
+ const rootState = {
1704
+ set,
1705
+ get,
1706
+ // Mock objects that have to be configured
1707
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1708
+ primaryStore: null,
1709
+ gl: null,
1710
+ renderer: null,
1711
+ camera: null,
1712
+ frustum: new Frustum(),
1713
+ autoUpdateFrustum: true,
1714
+ raycaster: null,
1715
+ events: {
1716
+ priority: 1,
1717
+ enabled: true,
1718
+ connected: false,
1719
+ frameTimedRaycasts: true,
1720
+ alwaysFireOnScroll: true,
1721
+ updateOnFrame: false
1722
+ },
1723
+ scene: null,
1724
+ rootScene: null,
1725
+ xr: null,
1726
+ inspector: null,
1727
+ invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1728
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1729
+ textureColorSpace: SRGBColorSpace,
1730
+ isLegacy: false,
1731
+ webGPUSupported: false,
1732
+ isNative: false,
1733
+ controls: null,
1734
+ pointer,
1735
+ mouse: pointer,
1736
+ frameloop: "always",
1737
+ onPointerMissed: void 0,
1738
+ onDragOverMissed: void 0,
1739
+ onDropMissed: void 0,
1740
+ performance: {
1741
+ current: 1,
1742
+ min: 0.5,
1743
+ max: 1,
1744
+ debounce: 200,
1745
+ regress: () => {
1746
+ const state2 = get();
1747
+ if (performanceTimeout) clearTimeout(performanceTimeout);
1748
+ if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
1749
+ performanceTimeout = setTimeout(
1750
+ () => setPerformanceCurrent(get().performance.max),
1751
+ state2.performance.debounce
1752
+ );
1753
+ }
1754
+ },
1755
+ size: { width: 0, height: 0, top: 0, left: 0 },
1756
+ viewport: {
1757
+ initialDpr: 0,
1758
+ dpr: 0,
1759
+ width: 0,
1760
+ height: 0,
1761
+ top: 0,
1762
+ left: 0,
1763
+ aspect: 0,
1764
+ distance: 0,
1765
+ factor: 0,
1766
+ getCurrentViewport
1767
+ },
1768
+ setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1769
+ setSize: (width, height, top, left) => {
1770
+ const state2 = get();
1771
+ if (width === void 0) {
1772
+ set({ _sizeImperative: false });
1773
+ if (state2._sizeProps) {
1774
+ const { width: propW, height: propH } = state2._sizeProps;
1775
+ if (propW !== void 0 || propH !== void 0) {
1776
+ const currentSize = state2.size;
1777
+ const newSize = {
1778
+ width: propW ?? currentSize.width,
1779
+ height: propH ?? currentSize.height,
1780
+ top: currentSize.top,
1781
+ left: currentSize.left
1782
+ };
1783
+ set((s) => ({
1784
+ size: newSize,
1785
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1786
+ }));
1787
+ getScheduler().invalidate();
1788
+ }
1789
+ }
1790
+ return;
1791
+ }
1792
+ const w = width;
1793
+ const h = height ?? width;
1794
+ const t = top ?? state2.size.top;
1795
+ const l = left ?? state2.size.left;
1796
+ const size = { width: w, height: h, top: t, left: l };
1797
+ set((s) => ({
1798
+ size,
1799
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1800
+ _sizeImperative: true
1801
+ }));
1802
+ getScheduler().invalidate();
1803
+ },
1804
+ setDpr: (dpr) => set((state2) => {
1805
+ const resolved = calculateDpr(dpr);
1806
+ return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
1807
+ }),
1808
+ setFrameloop: (frameloop = "always") => {
1809
+ set(() => ({ frameloop }));
1810
+ getScheduler().frameloop = frameloop;
1811
+ },
1812
+ setError: (error) => set(() => ({ error })),
1813
+ error: null,
1814
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1815
+ uniforms: {},
1816
+ nodes: {},
1817
+ buffers: {},
1818
+ gpuStorage: {},
1819
+ textures: /* @__PURE__ */ new Map(),
1820
+ _textureRefs: /* @__PURE__ */ new Map(),
1821
+ renderPipeline: null,
1822
+ passes: {},
1823
+ _hmrVersion: 0,
1824
+ _sizeImperative: false,
1825
+ _sizeProps: null,
1826
+ previousRoot: void 0,
1827
+ internal: {
1828
+ // Events
1829
+ interaction: [],
1830
+ subscribers: [],
1831
+ // Per-pointer state (new unified structure)
1832
+ pointerMap: /* @__PURE__ */ new Map(),
1833
+ pointerDirty: /* @__PURE__ */ new Map(),
1834
+ lastEvent: React.createRef(),
1835
+ // Deprecated but kept for backwards compatibility
1836
+ hovered: /* @__PURE__ */ new Map(),
1837
+ initialClick: [0, 0],
1838
+ initialHits: [],
1839
+ capturedMap: /* @__PURE__ */ new Map(),
1840
+ // Visibility tracking (onFramed, onOccluded, onVisible)
1841
+ visibilityRegistry: /* @__PURE__ */ new Map(),
1842
+ // Occlusion system (WebGPU only)
1843
+ occlusionEnabled: false,
1844
+ occlusionObserver: null,
1845
+ occlusionCache: /* @__PURE__ */ new Map(),
1846
+ helperGroup: null,
1847
+ // Updates
1848
+ active: false,
1849
+ frames: 0,
1850
+ priority: 0,
1851
+ subscribe: (ref, priority, store) => {
1852
+ const internal = get().internal;
1853
+ internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1854
+ internal.subscribers.push({ ref, priority, store });
1855
+ internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1856
+ return () => {
1857
+ const internal2 = get().internal;
1858
+ if (internal2?.subscribers) {
1859
+ internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
1860
+ internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
1861
+ }
1862
+ };
1863
+ },
1864
+ // Renderer Storage (single source of truth)
1865
+ actualRenderer: null,
1866
+ // Scheduler for useFrameNext (initialized in renderer.tsx)
1867
+ scheduler: null
1838
1868
  }
1839
- }
1840
- }
1841
- const queue = [];
1842
- for (const job of jobs) {
1843
- if (inDegree.get(job.id) === 0) {
1844
- queue.push(job);
1845
- }
1846
- }
1847
- queue.sort((a, b) => {
1848
- if (a.priority !== b.priority) return b.priority - a.priority;
1849
- return a.index - b.index;
1850
- });
1851
- const result = [];
1852
- while (queue.length > 0) {
1853
- const job = queue.shift();
1854
- result.push(job);
1855
- const neighbors = adjacency.get(job.id) || [];
1856
- for (const neighborId of neighbors) {
1857
- const newDegree = inDegree.get(neighborId) - 1;
1858
- inDegree.set(neighborId, newDegree);
1859
- if (newDegree === 0) {
1860
- const neighbor = jobMap.get(neighborId);
1861
- insertSorted(queue, neighbor);
1862
- }
1863
- }
1864
- }
1865
- if (result.length !== n) {
1866
- console.warn("[useFrame] Circular dependency detected in job constraints");
1867
- const resultIds = new Set(result.map((j) => j.id));
1868
- for (const job of jobs) {
1869
- if (!resultIds.has(job.id)) result.push(job);
1870
- }
1871
- }
1872
- return result;
1873
- }
1874
- function insertSorted(arr, job) {
1875
- let i = 0;
1876
- while (i < arr.length) {
1877
- const cmp = arr[i];
1878
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1879
- break;
1880
- }
1881
- i++;
1882
- }
1883
- arr.splice(i, 0, job);
1884
- }
1885
-
1886
- function shouldRun(job, now) {
1887
- if (!job.enabled) return false;
1888
- if (!job.fps) return true;
1889
- const minInterval = 1e3 / job.fps;
1890
- const lastRun = job.lastRun ?? 0;
1891
- const elapsed = now - lastRun;
1892
- if (elapsed < minInterval - 1) return false;
1893
- if (job.drop) {
1894
- job.lastRun = now;
1895
- } else {
1896
- const steps = Math.floor(elapsed / minInterval);
1897
- job.lastRun = lastRun + steps * minInterval;
1898
- if (job.lastRun < now - minInterval) {
1899
- job.lastRun = now;
1900
- }
1901
- }
1902
- return true;
1903
- }
1904
- function resetJobTiming(job) {
1905
- job.lastRun = void 0;
1906
- }
1907
-
1908
- var __defProp$1 = Object.defineProperty;
1909
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1910
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1911
- const hmrData = (() => {
1912
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1913
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1914
- try {
1915
- return (0, eval)("import.meta.hot");
1916
- } catch {
1917
- return void 0;
1918
- }
1919
- })();
1920
- const _Scheduler = class _Scheduler {
1921
- //* Constructor ================================
1922
- constructor() {
1923
- //* Critical State ================================
1924
- __publicField$1(this, "roots", /* @__PURE__ */ new Map());
1925
- __publicField$1(this, "phaseGraph");
1926
- __publicField$1(this, "loopState", {
1927
- running: false,
1928
- rafHandle: null,
1929
- lastTime: null,
1930
- // null = uninitialized, 0+ = valid timestamp
1931
- frameCount: 0,
1932
- elapsedTime: 0,
1933
- createdAt: performance.now()
1934
- });
1935
- __publicField$1(this, "stoppedTime", 0);
1936
- //* Private State ================================
1937
- __publicField$1(this, "nextRootIndex", 0);
1938
- __publicField$1(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1939
- __publicField$1(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1940
- __publicField$1(this, "nextGlobalIndex", 0);
1941
- __publicField$1(this, "idleCallbacks", /* @__PURE__ */ new Set());
1942
- __publicField$1(this, "nextJobIndex", 0);
1943
- __publicField$1(this, "jobStateListeners", /* @__PURE__ */ new Map());
1944
- __publicField$1(this, "pendingFrames", 0);
1945
- __publicField$1(this, "_frameloop", "always");
1946
- //* Independent Mode & Error Handling State ================================
1947
- __publicField$1(this, "_independent", false);
1948
- __publicField$1(this, "errorHandler", null);
1949
- __publicField$1(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1950
- //* Core Loop Execution Methods ================================
1951
- /**
1952
- * Main RAF loop callback.
1953
- * Executes frame, handles demand mode, and schedules next frame.
1954
- * @param {number} timestamp - RAF timestamp in milliseconds
1955
- * @returns {void}
1956
- * @private
1957
- */
1958
- __publicField$1(this, "loop", (timestamp) => {
1959
- if (!this.loopState.running) return;
1960
- this.executeFrame(timestamp);
1961
- if (this._frameloop === "demand") {
1962
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1963
- if (this.pendingFrames === 0) {
1964
- this.notifyIdle(timestamp);
1965
- return this.stop();
1966
- }
1967
- }
1968
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1969
- });
1970
- this.phaseGraph = new PhaseGraph();
1971
- }
1972
- static get instance() {
1973
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1974
- }
1975
- static set instance(value) {
1976
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1977
- }
1978
- /**
1979
- * Get the global scheduler instance (creates if doesn't exist).
1980
- * Uses HMR data to preserve instance across hot reloads.
1981
- * @returns {Scheduler} The singleton scheduler instance
1982
- */
1983
- static get() {
1984
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1985
- _Scheduler.instance = hmrData.data.scheduler;
1986
- }
1987
- if (!_Scheduler.instance) {
1988
- _Scheduler.instance = new _Scheduler();
1989
- if (hmrData?.data) {
1990
- hmrData.data.scheduler = _Scheduler.instance;
1991
- }
1992
- }
1993
- return _Scheduler.instance;
1994
- }
1995
- /**
1996
- * Reset the singleton instance. Stops the loop and clears all state.
1997
- * Primarily used for testing to ensure clean state between tests.
1998
- * @returns {void}
1999
- */
2000
- static reset() {
2001
- if (_Scheduler.instance) {
2002
- _Scheduler.instance.stop();
2003
- _Scheduler.instance = null;
2004
- }
2005
- if (hmrData?.data) {
2006
- hmrData.data.scheduler = null;
2007
- }
2008
- }
2009
- //* Getters & Setters ================================
2010
- get phases() {
2011
- return this.phaseGraph.getOrderedPhases();
2012
- }
2013
- get frameloop() {
2014
- return this._frameloop;
2015
- }
2016
- set frameloop(mode) {
2017
- if (this._frameloop === mode) return;
2018
- const wasAlways = this._frameloop === "always";
2019
- this._frameloop = mode;
2020
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2021
- else if (mode !== "always" && wasAlways) this.stop();
2022
- }
2023
- get isRunning() {
2024
- return this.loopState.running;
2025
- }
2026
- get isReady() {
2027
- return this.roots.size > 0;
2028
- }
2029
- get independent() {
2030
- return this._independent;
2031
- }
2032
- set independent(value) {
2033
- this._independent = value;
2034
- if (value) this.ensureDefaultRoot();
2035
- }
2036
- //* Root Management Methods ================================
2037
- /**
2038
- * Register a root (Canvas) with the scheduler.
2039
- * The first root to register starts the RAF loop (if frameloop='always').
2040
- * @param {string} id - Unique identifier for this root
2041
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2042
- * @returns {() => void} Unsubscribe function to remove this root
2043
- */
2044
- registerRoot(id, options = {}) {
2045
- if (this.roots.has(id)) {
2046
- console.warn(`[Scheduler] Root "${id}" already registered`);
2047
- return () => this.unregisterRoot(id);
2048
- }
2049
- const entry = {
2050
- id,
2051
- getState: options.getState ?? (() => ({})),
2052
- jobs: /* @__PURE__ */ new Map(),
2053
- sortedJobs: [],
2054
- needsRebuild: false
2055
- };
2056
- if (options.onError) {
2057
- this.errorHandler = options.onError;
2058
- }
2059
- this.roots.set(id, entry);
2060
- if (this.roots.size === 1) {
2061
- this.notifyRootReady();
2062
- if (this._frameloop === "always") this.start();
2063
- }
2064
- return () => this.unregisterRoot(id);
2065
- }
2066
- /**
2067
- * Unregister a root from the scheduler.
2068
- * Cleans up all job state listeners for this root's jobs.
2069
- * The last root to unregister stops the RAF loop.
2070
- * @param {string} id - The root ID to unregister
2071
- * @returns {void}
2072
- */
2073
- unregisterRoot(id) {
2074
- const root = this.roots.get(id);
2075
- if (!root) return;
2076
- for (const jobId of root.jobs.keys()) {
2077
- this.jobStateListeners.delete(jobId);
2078
- }
2079
- this.roots.delete(id);
2080
- if (this.roots.size === 0) {
2081
- this.stop();
2082
- this.errorHandler = null;
2083
- }
2084
- }
2085
- /**
2086
- * Subscribe to be notified when a root becomes available.
2087
- * Fires immediately if a root already exists.
2088
- * @param {() => void} callback - Function called when first root registers
2089
- * @returns {() => void} Unsubscribe function
2090
- */
2091
- onRootReady(callback) {
2092
- if (this.roots.size > 0) {
2093
- callback();
2094
- return () => {
2095
- };
2096
- }
2097
- this.rootReadyCallbacks.add(callback);
2098
- return () => this.rootReadyCallbacks.delete(callback);
2099
- }
2100
- /**
2101
- * Notify all registered root-ready callbacks.
2102
- * Called when the first root registers.
2103
- * @returns {void}
2104
- * @private
2105
- */
2106
- notifyRootReady() {
2107
- for (const cb of this.rootReadyCallbacks) {
2108
- try {
2109
- cb();
2110
- } catch (error) {
2111
- console.error("[Scheduler] Error in root-ready callback:", error);
2112
- }
2113
- }
2114
- this.rootReadyCallbacks.clear();
2115
- }
2116
- /**
2117
- * Ensure a default root exists for independent mode.
2118
- * Creates a minimal root with no state provider.
2119
- * @returns {void}
2120
- * @private
2121
- */
2122
- ensureDefaultRoot() {
2123
- if (!this.roots.has("__default__")) {
2124
- this.registerRoot("__default__");
2125
- }
2126
- }
2127
- /**
2128
- * Trigger error handling for job errors.
2129
- * Uses the bound error handler if available, otherwise logs to console.
2130
- * @param {Error} error - The error to handle
2131
- * @returns {void}
2132
- */
2133
- triggerError(error) {
2134
- if (this.errorHandler) this.errorHandler(error);
2135
- else console.error("[Scheduler]", error);
2136
- }
2137
- //* Phase Management Methods ================================
2138
- /**
2139
- * Add a named phase to the scheduler's execution order.
2140
- * Marks all roots for rebuild to incorporate the new phase.
2141
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2142
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2143
- * @returns {void}
2144
- * @example
2145
- * scheduler.addPhase('physics', { before: 'update' });
2146
- * scheduler.addPhase('postprocess', { after: 'render' });
2147
- */
2148
- addPhase(name, options) {
2149
- this.phaseGraph.addPhase(name, options);
2150
- for (const root of this.roots.values()) {
2151
- root.needsRebuild = true;
2152
- }
2153
- }
2154
- /**
2155
- * Check if a phase exists in the scheduler.
2156
- * @param {string} name - The phase name to check
2157
- * @returns {boolean} True if the phase exists
2158
- */
2159
- hasPhase(name) {
2160
- return this.phaseGraph.hasPhase(name);
2161
- }
2162
- //* Global Job Registration Methods (Deprecated APIs) ================================
2163
- /**
2164
- * Register a global job that runs once per frame (not per-root).
2165
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2166
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2167
- * @param {string} id - Unique identifier for this global job
2168
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2169
- * @returns {() => void} Unsubscribe function to remove this global job
2170
- * @deprecated Use useFrame with phases instead
2171
- */
2172
- registerGlobal(phase, id, callback) {
2173
- const job = { id, callback };
2174
- if (phase === "before") {
2175
- this.globalBeforeJobs.set(id, job);
2176
- } else {
2177
- this.globalAfterJobs.set(id, job);
2178
- }
2179
- return () => {
2180
- if (phase === "before") this.globalBeforeJobs.delete(id);
2181
- else this.globalAfterJobs.delete(id);
2182
- };
2183
- }
2184
- //* Idle Callback Methods (Deprecated API) ================================
2185
- /**
2186
- * Register an idle callback that fires when the loop stops.
2187
- * Used internally by deprecated addTail API.
2188
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2189
- * @returns {() => void} Unsubscribe function to remove this idle callback
2190
- * @deprecated Use demand mode with invalidate() instead
2191
- */
2192
- onIdle(callback) {
2193
- this.idleCallbacks.add(callback);
2194
- return () => this.idleCallbacks.delete(callback);
2195
- }
2196
- /**
2197
- * Notify all registered idle callbacks.
2198
- * Called when the loop stops in demand mode.
2199
- * @param {number} timestamp - The RAF timestamp when idle occurred
2200
- * @returns {void}
2201
- * @private
2202
- */
2203
- notifyIdle(timestamp) {
2204
- for (const cb of this.idleCallbacks) {
2205
- try {
2206
- cb(timestamp);
2207
- } catch (error) {
2208
- console.error("[Scheduler] Error in idle callback:", error);
2209
- }
2210
- }
2211
- }
2212
- //* Job Registration & Management Methods ================================
2213
- /**
2214
- * Register a job (frame callback) with a specific root.
2215
- * This is the core registration method used by useFrame internally.
2216
- * @param {FrameNextCallback} callback - The function to call each frame
2217
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2218
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2219
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2220
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2221
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2222
- * @param {number} [options.fps] - FPS throttle limit
2223
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2224
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2225
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2226
- * @returns {() => void} Unsubscribe function to remove this job
2227
- */
2228
- register(callback, options = {}) {
2229
- const rootId = options.rootId;
2230
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2231
- if (!root) {
2232
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2233
- return () => {
2234
- };
2235
- }
2236
- const id = options.id ?? this.generateJobId();
2237
- let phase = options.phase ?? "update";
2238
- if (!options.phase && (options.before || options.after)) {
2239
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2240
- }
2241
- const before = this.normalizeConstraints(options.before);
2242
- const after = this.normalizeConstraints(options.after);
2243
- const job = {
2244
- id,
2245
- callback,
2246
- phase,
2247
- before,
2248
- after,
2249
- priority: options.priority ?? 0,
2250
- index: this.nextJobIndex++,
2251
- fps: options.fps,
2252
- drop: options.drop ?? true,
2253
- enabled: options.enabled ?? true,
2254
- system: options.system ?? false
2255
- };
2256
- if (root.jobs.has(id)) {
2257
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2258
- }
2259
- root.jobs.set(id, job);
2260
- root.needsRebuild = true;
2261
- return () => this.unregister(id, root.id);
2262
- }
2263
- /**
2264
- * Unregister a job by its ID.
2265
- * Searches all roots if rootId is not provided.
2266
- * @param {string} id - The job ID to unregister
2267
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2268
- * @returns {void}
2269
- */
2270
- unregister(id, rootId) {
2271
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2272
- if (root?.jobs.delete(id)) {
2273
- root.needsRebuild = true;
2274
- this.jobStateListeners.delete(id);
2275
- }
2276
- }
2277
- /**
2278
- * Update a job's options dynamically.
2279
- * Searches all roots to find the job by ID.
2280
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2281
- * @param {string} id - The job ID to update
2282
- * @param {Partial<JobOptions>} options - The options to update
2283
- * @returns {void}
2284
- */
2285
- updateJob(id, options) {
2286
- let job;
2287
- let root;
2288
- for (const r of this.roots.values()) {
2289
- job = r.jobs.get(id);
2290
- if (job) {
2291
- root = r;
2292
- break;
2293
- }
2294
- }
2295
- if (!job || !root) return;
2296
- if (options.priority !== void 0) job.priority = options.priority;
2297
- if (options.fps !== void 0) job.fps = options.fps;
2298
- if (options.drop !== void 0) job.drop = options.drop;
2299
- if (options.enabled !== void 0) {
2300
- const wasEnabled = job.enabled;
2301
- job.enabled = options.enabled;
2302
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2303
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2304
- }
2305
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2306
- if (options.phase) job.phase = options.phase;
2307
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2308
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2309
- root.needsRebuild = true;
2310
- }
2311
- }
2312
- //* Job State Management Methods ================================
2313
- /**
2314
- * Check if a job is currently paused (disabled).
2315
- * @param {string} id - The job ID to check
2316
- * @returns {boolean} True if the job exists and is paused
2317
- */
2318
- isJobPaused(id) {
2319
- for (const root of this.roots.values()) {
2320
- const job = root.jobs.get(id);
2321
- if (job) return !job.enabled;
2322
- }
2323
- return false;
2324
- }
2325
- /**
2326
- * Subscribe to state changes for a specific job.
2327
- * Listener is called when job is paused or resumed.
2328
- * @param {string} id - The job ID to subscribe to
2329
- * @param {() => void} listener - Callback invoked on state changes
2330
- * @returns {() => void} Unsubscribe function
2331
- */
2332
- subscribeJobState(id, listener) {
2333
- if (!this.jobStateListeners.has(id)) {
2334
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2335
- }
2336
- this.jobStateListeners.get(id).add(listener);
2337
- return () => {
2338
- this.jobStateListeners.get(id)?.delete(listener);
2339
- if (this.jobStateListeners.get(id)?.size === 0) {
2340
- this.jobStateListeners.delete(id);
2341
- }
2342
- };
2343
- }
2344
- /**
2345
- * Notify all listeners that a job's state has changed.
2346
- * @param {string} id - The job ID that changed
2347
- * @returns {void}
2348
- * @private
2349
- */
2350
- notifyJobStateChange(id) {
2351
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2352
- }
2353
- /**
2354
- * Pause a job by ID (sets enabled=false).
2355
- * Notifies any subscribed state listeners.
2356
- * @param {string} id - The job ID to pause
2357
- * @returns {void}
2358
- */
2359
- pauseJob(id) {
2360
- this.updateJob(id, { enabled: false });
2361
- this.notifyJobStateChange(id);
2362
- }
2363
- /**
2364
- * Resume a paused job by ID (sets enabled=true).
2365
- * Resets job timing to prevent frame accumulation.
2366
- * Notifies any subscribed state listeners.
2367
- * @param {string} id - The job ID to resume
2368
- * @returns {void}
2369
- */
2370
- resumeJob(id) {
2371
- this.updateJob(id, { enabled: true });
2372
- this.notifyJobStateChange(id);
2373
- }
2374
- //* Frame Loop Control Methods ================================
2375
- /**
2376
- * Start the requestAnimationFrame loop.
2377
- * Resets timing state (elapsedTime, frameCount) on start.
2378
- * No-op if already running.
2379
- * @returns {void}
2380
- */
2381
- start() {
2382
- if (this.loopState.running) return;
2383
- const { elapsedTime, createdAt } = this.loopState;
2384
- let adjustedCreated = 0;
2385
- if (this.stoppedTime > 0) {
2386
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2387
- this.stoppedTime = 0;
2388
- }
2389
- Object.assign(this.loopState, {
2390
- running: true,
2391
- elapsedTime: elapsedTime ?? 0,
2392
- lastTime: performance.now(),
2393
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2394
- frameCount: 0,
2395
- rafHandle: requestAnimationFrame(this.loop)
2396
- });
2397
- }
2398
- /**
2399
- * Stop the requestAnimationFrame loop.
2400
- * Cancels any pending RAF callback.
2401
- * No-op if not running.
2402
- * @returns {void}
2403
- */
2404
- stop() {
2405
- if (!this.loopState.running) return;
2406
- this.loopState.running = false;
2407
- if (this.loopState.rafHandle !== null) {
2408
- cancelAnimationFrame(this.loopState.rafHandle);
2409
- this.loopState.rafHandle = null;
2410
- }
2411
- this.stoppedTime = performance.now();
2412
- }
2413
- /**
2414
- * Request frames to be rendered in demand mode.
2415
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2416
- * No-op if frameloop is not 'demand'.
2417
- * @param {number} [frames=1] - Number of frames to request
2418
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2419
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2420
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2421
- * @returns {void}
2422
- * @example
2423
- * // Request a single frame render
2424
- * scheduler.invalidate();
2425
- *
2426
- * @example
2427
- * // Request 5 frames (e.g., for animations)
2428
- * scheduler.invalidate(5);
2429
- *
2430
- * @example
2431
- * // Set pending frames to exactly 3 (don't stack with existing)
2432
- * scheduler.invalidate(3, false);
2433
- *
2434
- * @example
2435
- * // Add 2 more frames to existing pending count
2436
- * scheduler.invalidate(2, true);
2437
- */
2438
- invalidate(frames = 1, stackFrames = false) {
2439
- if (this._frameloop !== "demand") return;
2440
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2441
- this.pendingFrames = Math.min(60, baseFrames + frames);
2442
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2443
- }
2444
- /**
2445
- * Reset timing state for deterministic testing.
2446
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2447
- * @returns {void}
2448
- */
2449
- resetTiming() {
2450
- this.loopState.lastTime = null;
2451
- this.loopState.frameCount = 0;
2452
- this.loopState.elapsedTime = 0;
2453
- this.loopState.createdAt = performance.now();
2454
- }
2455
- //* Manual Stepping Methods ================================
2456
- /**
2457
- * Manually execute a single frame for all roots.
2458
- * Useful for frameloop='never' mode or testing scenarios.
2459
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2460
- * @returns {void}
2461
- * @example
2462
- * // Manual control mode
2463
- * scheduler.frameloop = 'never';
2464
- * scheduler.step(); // Execute one frame
2465
- */
2466
- step(timestamp) {
2467
- const now = timestamp ?? performance.now();
2468
- this.executeFrame(now);
2469
- }
2470
- /**
2471
- * Manually execute a single job by its ID.
2472
- * Useful for testing individual job callbacks in isolation.
2473
- * @param {string} id - The job ID to step
2474
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2475
- * @returns {void}
2476
- */
2477
- stepJob(id, timestamp) {
2478
- let job;
2479
- let root;
2480
- for (const r of this.roots.values()) {
2481
- job = r.jobs.get(id);
2482
- if (job) {
2483
- root = r;
2484
- break;
2485
- }
2486
- }
2487
- if (!job || !root) {
2488
- console.warn(`[Scheduler] Job "${id}" not found`);
2489
- return;
2490
- }
2491
- const now = timestamp ?? performance.now();
2492
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2493
- const delta = deltaMs / 1e3;
2494
- const elapsed = now - this.loopState.createdAt;
2495
- const providedState = root.getState?.() ?? {};
2496
- const frameState = {
2497
- ...providedState,
2498
- time: now,
2499
- delta,
2500
- elapsed,
2501
- frame: this.loopState.frameCount
2502
- };
2503
- try {
2504
- job.callback(frameState, delta);
2505
- } catch (error) {
2506
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2507
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2508
- }
2509
- }
2510
- /**
2511
- * Execute a single frame across all roots.
2512
- * Order: globalBefore → each root's jobs → globalAfter
2513
- * @param {number} timestamp - RAF timestamp in milliseconds
2514
- * @returns {void}
2515
- * @private
2516
- */
2517
- executeFrame(timestamp) {
2518
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2519
- const delta = deltaMs / 1e3;
2520
- this.loopState.lastTime = timestamp;
2521
- this.loopState.frameCount++;
2522
- this.loopState.elapsedTime += deltaMs;
2523
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2524
- for (const root of this.roots.values()) {
2525
- this.tickRoot(root, timestamp, delta);
2526
- }
2527
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2528
- }
2529
- /**
2530
- * Run all global jobs from a job map.
2531
- * Catches and logs errors without stopping execution.
2532
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2533
- * @param {number} timestamp - RAF timestamp in milliseconds
2534
- * @returns {void}
2535
- * @private
2536
- */
2537
- runGlobalJobs(jobs, timestamp) {
2538
- for (const job of jobs.values()) {
2539
- try {
2540
- job.callback(timestamp);
2541
- } catch (error) {
2542
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2543
- }
2544
- }
2545
- }
2546
- /**
2547
- * Execute all jobs for a single root in sorted order.
2548
- * Rebuilds sorted job list if needed, then dispatches each job.
2549
- * Errors are caught and propagated via triggerError.
2550
- * @param {RootEntry} root - The root entry to tick
2551
- * @param {number} timestamp - RAF timestamp in milliseconds
2552
- * @param {number} delta - Time since last frame in seconds
2553
- * @returns {void}
2554
- * @private
2555
- */
2556
- tickRoot(root, timestamp, delta) {
2557
- if (root.needsRebuild) {
2558
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2559
- root.needsRebuild = false;
2560
- }
2561
- const providedState = root.getState?.() ?? {};
2562
- const frameState = {
2563
- ...providedState,
2564
- time: timestamp,
2565
- delta,
2566
- elapsed: this.loopState.elapsedTime / 1e3,
2567
- // Convert ms to seconds
2568
- frame: this.loopState.frameCount
2569
- };
2570
- for (const job of root.sortedJobs) {
2571
- if (!shouldRun(job, timestamp)) continue;
2572
- try {
2573
- job.callback(frameState, delta);
2574
- } catch (error) {
2575
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2576
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2577
- }
2578
- }
2579
- }
2580
- //* Debug & Inspection Methods ================================
2581
- /**
2582
- * Get the total number of registered jobs across all roots.
2583
- * Includes both per-root jobs and global before/after jobs.
2584
- * @returns {number} Total job count
2585
- */
2586
- getJobCount() {
2587
- let count = 0;
2588
- for (const root of this.roots.values()) {
2589
- count += root.jobs.size;
2590
- }
2591
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2592
- }
2593
- /**
2594
- * Get all registered job IDs across all roots.
2595
- * Includes both per-root jobs and global before/after jobs.
2596
- * @returns {string[]} Array of all job IDs
2597
- */
2598
- getJobIds() {
2599
- const ids = [];
2600
- for (const root of this.roots.values()) {
2601
- ids.push(...root.jobs.keys());
2602
- }
2603
- ids.push(...this.globalBeforeJobs.keys());
2604
- ids.push(...this.globalAfterJobs.keys());
2605
- return ids;
2606
- }
2607
- /**
2608
- * Get the number of registered roots (Canvas instances).
2609
- * @returns {number} Number of registered roots
2610
- */
2611
- getRootCount() {
2612
- return this.roots.size;
2613
- }
2614
- /**
2615
- * Check if any user (non-system) jobs are registered in a specific phase.
2616
- * Used by the default render job to know if a user has taken over rendering.
2617
- *
2618
- * @param phase The phase to check
2619
- * @param rootId Optional root ID to check (checks all roots if not provided)
2620
- * @returns true if any user jobs exist in the phase
2621
- */
2622
- hasUserJobsInPhase(phase, rootId) {
2623
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2624
- return rootsToCheck.some((root) => {
2625
- if (!root) return false;
2626
- for (const job of root.jobs.values()) {
2627
- if (job.phase === phase && !job.system && job.enabled) return true;
2628
- }
2629
- return false;
2630
- });
2631
- }
2632
- //* Utility Methods ================================
2633
- /**
2634
- * Generate a unique root ID for automatic root registration.
2635
- * @returns {string} A unique root ID in the format 'root_N'
2636
- */
2637
- generateRootId() {
2638
- return `root_${this.nextRootIndex++}`;
2639
- }
2640
- /**
2641
- * Generate a unique job ID.
2642
- * @returns {string} A unique job ID in the format 'job_N'
2643
- * @private
2644
- */
2645
- generateJobId() {
2646
- return `job_${this.nextJobIndex}`;
2647
- }
2648
- /**
2649
- * Normalize before/after constraints to a Set.
2650
- * Handles undefined, single string, or array inputs.
2651
- * @param {string | string[] | undefined} value - The constraint value(s)
2652
- * @returns {Set<string>} Normalized Set of constraint strings
2653
- * @private
2654
- */
2655
- normalizeConstraints(value) {
2656
- if (!value) return /* @__PURE__ */ new Set();
2657
- if (Array.isArray(value)) return new Set(value);
2658
- return /* @__PURE__ */ new Set([value]);
2659
- }
2660
- };
2661
- //* Static State & Methods (Singleton Usage) ================================
2662
- //* Cross-Bundle Singleton Key ==============================
2663
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2664
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2665
- __publicField$1(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2666
- let Scheduler = _Scheduler;
2667
- const getScheduler = () => Scheduler.get();
2668
- if (hmrData) {
2669
- hmrData.accept?.();
2670
- }
2671
-
2672
- const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
2673
- const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
2674
- const createStore = (invalidate, advance) => {
2675
- const rootStore = createWithEqualityFn((set, get) => {
2676
- const position = new Vector3();
2677
- const defaultTarget = new Vector3();
2678
- const tempTarget = new Vector3();
2679
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
2680
- const { width, height, top, left } = size;
2681
- const aspect = width / height;
2682
- if (target.isVector3) tempTarget.copy(target);
2683
- else tempTarget.set(...target);
2684
- const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
2685
- if (isOrthographicCamera(camera)) {
2686
- return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
2687
- } else {
2688
- const fov = camera.fov * Math.PI / 180;
2689
- const h = 2 * Math.tan(fov / 2) * distance;
2690
- const w = h * (width / height);
2691
- return { width: w, height: h, top, left, factor: width / w, distance, aspect };
2692
- }
2693
- }
2694
- let performanceTimeout = void 0;
2695
- const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
2696
- const pointer = new Vector2();
2697
- const rootState = {
2698
- set,
2699
- get,
2700
- // Mock objects that have to be configured
2701
- // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
2702
- primaryStore: null,
2703
- gl: null,
2704
- renderer: null,
2705
- camera: null,
2706
- frustum: new Frustum(),
2707
- autoUpdateFrustum: true,
2708
- raycaster: null,
2709
- events: {
2710
- priority: 1,
2711
- enabled: true,
2712
- connected: false,
2713
- frameTimedRaycasts: true,
2714
- alwaysFireOnScroll: true,
2715
- updateOnFrame: false
2716
- },
2717
- scene: null,
2718
- rootScene: null,
2719
- xr: null,
2720
- inspector: null,
2721
- invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
2722
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
2723
- textureColorSpace: SRGBColorSpace,
2724
- isLegacy: false,
2725
- webGPUSupported: false,
2726
- isNative: false,
2727
- controls: null,
2728
- pointer,
2729
- mouse: pointer,
2730
- frameloop: "always",
2731
- onPointerMissed: void 0,
2732
- onDragOverMissed: void 0,
2733
- onDropMissed: void 0,
2734
- performance: {
2735
- current: 1,
2736
- min: 0.5,
2737
- max: 1,
2738
- debounce: 200,
2739
- regress: () => {
2740
- const state2 = get();
2741
- if (performanceTimeout) clearTimeout(performanceTimeout);
2742
- if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
2743
- performanceTimeout = setTimeout(
2744
- () => setPerformanceCurrent(get().performance.max),
2745
- state2.performance.debounce
2746
- );
2747
- }
2748
- },
2749
- size: { width: 0, height: 0, top: 0, left: 0 },
2750
- viewport: {
2751
- initialDpr: 0,
2752
- dpr: 0,
2753
- width: 0,
2754
- height: 0,
2755
- top: 0,
2756
- left: 0,
2757
- aspect: 0,
2758
- distance: 0,
2759
- factor: 0,
2760
- getCurrentViewport
2761
- },
2762
- setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
2763
- setSize: (width, height, top, left) => {
2764
- const state2 = get();
2765
- if (width === void 0) {
2766
- set({ _sizeImperative: false });
2767
- if (state2._sizeProps) {
2768
- const { width: propW, height: propH } = state2._sizeProps;
2769
- if (propW !== void 0 || propH !== void 0) {
2770
- const currentSize = state2.size;
2771
- const newSize = {
2772
- width: propW ?? currentSize.width,
2773
- height: propH ?? currentSize.height,
2774
- top: currentSize.top,
2775
- left: currentSize.left
2776
- };
2777
- set((s) => ({
2778
- size: newSize,
2779
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2780
- }));
2781
- getScheduler().invalidate();
2782
- }
2783
- }
2784
- return;
2785
- }
2786
- const w = width;
2787
- const h = height ?? width;
2788
- const t = top ?? state2.size.top;
2789
- const l = left ?? state2.size.left;
2790
- const size = { width: w, height: h, top: t, left: l };
2791
- set((s) => ({
2792
- size,
2793
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2794
- _sizeImperative: true
2795
- }));
2796
- getScheduler().invalidate();
2797
- },
2798
- setDpr: (dpr) => set((state2) => {
2799
- const resolved = calculateDpr(dpr);
2800
- return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
2801
- }),
2802
- setFrameloop: (frameloop = "always") => {
2803
- set(() => ({ frameloop }));
2804
- },
2805
- setError: (error) => set(() => ({ error })),
2806
- error: null,
2807
- //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2808
- uniforms: {},
2809
- nodes: {},
2810
- buffers: {},
2811
- gpuStorage: {},
2812
- textures: /* @__PURE__ */ new Map(),
2813
- renderPipeline: null,
2814
- passes: {},
2815
- _hmrVersion: 0,
2816
- _sizeImperative: false,
2817
- _sizeProps: null,
2818
- previousRoot: void 0,
2819
- internal: {
2820
- // Events
2821
- interaction: [],
2822
- subscribers: [],
2823
- // Per-pointer state (new unified structure)
2824
- pointerMap: /* @__PURE__ */ new Map(),
2825
- pointerDirty: /* @__PURE__ */ new Map(),
2826
- lastEvent: React.createRef(),
2827
- // Deprecated but kept for backwards compatibility
2828
- hovered: /* @__PURE__ */ new Map(),
2829
- initialClick: [0, 0],
2830
- initialHits: [],
2831
- capturedMap: /* @__PURE__ */ new Map(),
2832
- // Visibility tracking (onFramed, onOccluded, onVisible)
2833
- visibilityRegistry: /* @__PURE__ */ new Map(),
2834
- // Occlusion system (WebGPU only)
2835
- occlusionEnabled: false,
2836
- occlusionObserver: null,
2837
- occlusionCache: /* @__PURE__ */ new Map(),
2838
- helperGroup: null,
2839
- // Updates
2840
- active: false,
2841
- frames: 0,
2842
- priority: 0,
2843
- subscribe: (ref, priority, store) => {
2844
- const internal = get().internal;
2845
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
2846
- internal.subscribers.push({ ref, priority, store });
2847
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
2848
- return () => {
2849
- const internal2 = get().internal;
2850
- if (internal2?.subscribers) {
2851
- internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
2852
- internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
2853
- }
2854
- };
2855
- },
2856
- // Renderer Storage (single source of truth)
2857
- actualRenderer: null,
2858
- // Scheduler for useFrameNext (initialized in renderer.tsx)
2859
- scheduler: null
2860
- }
2861
- };
2862
- return rootState;
1869
+ };
1870
+ return rootState;
2863
1871
  });
2864
1872
  const state = rootStore.getState();
2865
1873
  Object.defineProperty(state, "gl", {
@@ -2867,8 +1875,7 @@ const createStore = (invalidate, advance) => {
2867
1875
  const currentState = rootStore.getState();
2868
1876
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2869
1877
  const stack = new Error().stack || "";
2870
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2871
- if (!isInternalAccess) {
1878
+ if (!isInternalRendererAccess(stack)) {
2872
1879
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2873
1880
  notifyDepreciated({
2874
1881
  heading: "Accessing state.gl in WebGPU mode",
@@ -2981,19 +1988,25 @@ function loadingFn(extensions, onProgress) {
2981
1988
  );
2982
1989
  };
2983
1990
  }
2984
- function useLoader(loader, input, extensions, onProgress) {
2985
- const keys = Array.isArray(input) ? input : [input];
1991
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1992
+ const inputs = Array.isArray(input) ? input : [input];
1993
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2986
1994
  const fn = loadingFn(extensions, onProgress);
2987
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1995
+ const results = cacheKeys.map(
1996
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1997
+ );
2988
1998
  return Array.isArray(input) ? results : results[0];
2989
1999
  }
2990
- useLoader.preload = function(loader, input, extensions, onProgress) {
2991
- const keys = Array.isArray(input) ? input : [input];
2992
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
2000
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2001
+ const inputs = Array.isArray(input) ? input : [input];
2002
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2003
+ cacheKeys.forEach(
2004
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2005
+ );
2993
2006
  };
2994
- useLoader.clear = function(loader, input) {
2995
- const keys = Array.isArray(input) ? input : [input];
2996
- keys.forEach((key) => clear([loader, key]));
2007
+ useLoader.clear = function(loader, input, cacheKey) {
2008
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2009
+ cacheKeys.forEach((key) => clear([loader, key]));
2997
2010
  };
2998
2011
  useLoader.loader = getLoader;
2999
2012
 
@@ -3069,20 +2082,14 @@ function useFrame(callback, priorityOrOptions) {
3069
2082
  }
3070
2083
  };
3071
2084
  } else {
3072
- const registerOutside = () => {
3073
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3074
- };
3075
- if (scheduler.independent || scheduler.isReady) {
3076
- return registerOutside();
3077
- }
3078
- let unregisterJob = null;
3079
- const unsubReady = scheduler.onRootReady(() => {
3080
- unregisterJob = registerOutside();
3081
- });
3082
- return () => {
3083
- unsubReady();
3084
- unregisterJob?.();
3085
- };
2085
+ return scheduler.register(
2086
+ (state, delta) => {
2087
+ const frameState = state;
2088
+ if (!frameState.renderer) return;
2089
+ callbackRef.current?.(frameState, delta);
2090
+ },
2091
+ { id, ...options }
2092
+ );
3086
2093
  }
3087
2094
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3088
2095
  const isPaused = React.useSyncExternalStore(
@@ -3173,18 +2180,18 @@ function buildFromCache(input, textureCache) {
3173
2180
  function useTexture(input, optionsOrOnLoad) {
3174
2181
  const renderer = useThree((state) => state.internal.actualRenderer);
3175
2182
  const store = useStore();
3176
- const textureCache = useThree((state) => state.textures);
3177
2183
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3178
- const { onLoad, cache = false } = options;
2184
+ const { onLoad, cache = true } = options;
3179
2185
  const onLoadRef = useRef(onLoad);
3180
2186
  onLoadRef.current = onLoad;
3181
2187
  const onLoadCalledForRef = useRef(null);
3182
2188
  const urls = useMemo(() => getUrls(input), [input]);
3183
2189
  const cachedResult = useMemo(() => {
3184
2190
  if (!cache) return null;
3185
- if (!allUrlsCached(urls, textureCache)) return null;
3186
- return buildFromCache(input, textureCache);
3187
- }, [cache, urls, textureCache, input]);
2191
+ const textures = store.getState().textures;
2192
+ if (!allUrlsCached(urls, textures)) return null;
2193
+ return buildFromCache(input, textures);
2194
+ }, [cache, urls, input, store]);
3188
2195
  const loadedTextures = useLoader(
3189
2196
  TextureLoader,
3190
2197
  IsObject(input) ? Object.values(input) : input
@@ -3228,8 +2235,6 @@ function useTexture(input, optionsOrOnLoad) {
3228
2235
  }, [input, loadedTextures, cachedResult]);
3229
2236
  useEffect(() => {
3230
2237
  if (!cache) return;
3231
- if (cachedResult) return;
3232
- const set = store.setState;
3233
2238
  const urlTextureMap = [];
3234
2239
  if (typeof input === "string") {
3235
2240
  urlTextureMap.push([input, mappedTextures]);
@@ -3243,18 +2248,32 @@ function useTexture(input, optionsOrOnLoad) {
3243
2248
  urlTextureMap.push([url, textureRecord[key]]);
3244
2249
  }
3245
2250
  }
3246
- set((state) => {
3247
- const newMap = new Map(state.textures);
3248
- let changed = false;
2251
+ store.setState((state) => {
2252
+ const refs = new Map(state._textureRefs);
2253
+ let textures = state.textures;
2254
+ let added = false;
3249
2255
  for (const [url, texture] of urlTextureMap) {
3250
- if (!newMap.has(url)) {
3251
- newMap.set(url, texture);
3252
- changed = true;
2256
+ if (!textures.has(url)) {
2257
+ if (!added) {
2258
+ textures = new Map(textures);
2259
+ added = true;
2260
+ }
2261
+ textures.set(url, texture);
3253
2262
  }
2263
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3254
2264
  }
3255
- return changed ? { textures: newMap } : state;
2265
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3256
2266
  });
3257
- }, [cache, input, mappedTextures, store, cachedResult]);
2267
+ return () => store.setState((state) => {
2268
+ const refs = new Map(state._textureRefs);
2269
+ for (const [url] of urlTextureMap) {
2270
+ const next = (refs.get(url) ?? 0) - 1;
2271
+ if (next <= 0) refs.delete(url);
2272
+ else refs.set(url, next);
2273
+ }
2274
+ return { _textureRefs: refs };
2275
+ });
2276
+ }, [cache, input, mappedTextures, store]);
3258
2277
  return mappedTextures;
3259
2278
  }
3260
2279
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3270,96 +2289,63 @@ const Texture = ({
3270
2289
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3271
2290
  };
3272
2291
 
3273
- function getTextureValue(entry) {
3274
- if (entry instanceof Texture$1) return entry;
3275
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3276
- return entry.value;
3277
- }
3278
- return null;
3279
- }
3280
- function useTextures() {
2292
+ function useTextures(selector) {
3281
2293
  const store = useStore();
3282
- return useMemo(() => {
3283
- const set = store.setState;
2294
+ const registry = useMemo(() => {
3284
2295
  const getState = store.getState;
3285
- const add = (key, value) => {
3286
- set((state) => {
3287
- const newMap = new Map(state.textures);
3288
- newMap.set(key, value);
3289
- return { textures: newMap };
3290
- });
3291
- };
3292
- const addMultiple = (items) => {
3293
- set((state) => {
3294
- const newMap = new Map(state.textures);
3295
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3296
- for (const [key, value] of entries) {
3297
- newMap.set(key, value);
3298
- }
3299
- return { textures: newMap };
3300
- });
3301
- };
3302
- const remove = (key) => {
3303
- set((state) => {
3304
- const newMap = new Map(state.textures);
3305
- newMap.delete(key);
3306
- return { textures: newMap };
3307
- });
3308
- };
3309
- const removeMultiple = (keys) => {
3310
- set((state) => {
3311
- const newMap = new Map(state.textures);
3312
- for (const key of keys) newMap.delete(key);
3313
- return { textures: newMap };
3314
- });
3315
- };
3316
- const dispose = (key) => {
3317
- const entry = getState().textures.get(key);
3318
- if (entry) {
3319
- const tex = getTextureValue(entry);
3320
- tex?.dispose();
3321
- }
3322
- remove(key);
3323
- };
3324
- const disposeMultiple = (keys) => {
3325
- const textures = getState().textures;
3326
- for (const key of keys) {
3327
- const entry = textures.get(key);
3328
- if (entry) {
3329
- const tex = getTextureValue(entry);
3330
- tex?.dispose();
3331
- }
3332
- }
3333
- removeMultiple(keys);
3334
- };
3335
- const disposeAll = () => {
3336
- const textures = getState().textures;
3337
- for (const entry of textures.values()) {
3338
- const tex = getTextureValue(entry);
3339
- tex?.dispose();
3340
- }
3341
- set({ textures: /* @__PURE__ */ new Map() });
3342
- };
2296
+ const setState = store.setState;
2297
+ const getOne = (key) => getState().textures.get(key);
3343
2298
  return {
3344
- // Getter for the textures Map (reactive via getState)
3345
- get textures() {
2299
+ get all() {
3346
2300
  return getState().textures;
3347
2301
  },
3348
- // Read
3349
- get: (key) => getState().textures.get(key),
2302
+ get(input) {
2303
+ if (typeof input === "string") return getOne(input);
2304
+ if (Array.isArray(input)) return input.map(getOne);
2305
+ const out = {};
2306
+ for (const name in input) out[name] = getOne(input[name]);
2307
+ return out;
2308
+ },
3350
2309
  has: (key) => getState().textures.has(key),
3351
- // Write
3352
- add,
3353
- addMultiple,
3354
- // Remove (cache only)
3355
- remove,
3356
- removeMultiple,
3357
- // Dispose (GPU + cache)
3358
- dispose,
3359
- disposeMultiple,
3360
- disposeAll
2310
+ add(keyOrRecord, texture) {
2311
+ setState((state) => {
2312
+ const textures = new Map(state.textures);
2313
+ if (typeof keyOrRecord === "string") {
2314
+ textures.set(keyOrRecord, texture);
2315
+ } else {
2316
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2317
+ }
2318
+ return { textures };
2319
+ });
2320
+ },
2321
+ dispose(key, options) {
2322
+ const state = getState();
2323
+ const refs = state._textureRefs.get(key) ?? 0;
2324
+ if (refs > 0 && !options?.force) {
2325
+ console.warn(
2326
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2327
+ );
2328
+ return false;
2329
+ }
2330
+ state.textures.get(key)?.dispose();
2331
+ setState((s) => {
2332
+ const textures = new Map(s.textures);
2333
+ textures.delete(key);
2334
+ const nextRefs = new Map(s._textureRefs);
2335
+ nextRefs.delete(key);
2336
+ return { textures, _textureRefs: nextRefs };
2337
+ });
2338
+ return true;
2339
+ },
2340
+ disposeAll() {
2341
+ for (const texture of getState().textures.values()) texture.dispose();
2342
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2343
+ }
3361
2344
  };
3362
2345
  }, [store]);
2346
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2347
+ const selected = useThree(subscribe);
2348
+ return selector ? selected : registry;
3363
2349
  }
3364
2350
 
3365
2351
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3440,7 +2426,7 @@ function advance(timestamp) {
3440
2426
  getScheduler().step(timestamp);
3441
2427
  }
3442
2428
 
3443
- const version = "10.0.0-alpha.2";
2429
+ const version = "10.0.0-alpha.3";
3444
2430
  const packageData = {
3445
2431
  version: version};
3446
2432
 
@@ -14696,7 +13682,7 @@ function n0() {
14696
13682
  var t0 = n0();
14697
13683
  const r0 = Xb(t0);
14698
13684
 
14699
- const t = 1, o = 8, r = 32, e = 2;
13685
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14700
13686
 
14701
13687
  function createReconciler(config) {
14702
13688
  const reconciler2 = r0(config);
@@ -14861,7 +13847,15 @@ function setFiberRef(fiber, publicInstance) {
14861
13847
  }
14862
13848
  }
14863
13849
  const reconstructed = [];
14864
- function swapInstances() {
13850
+ function flushReconstructedInstances() {
13851
+ if (reconstructed.length === 0) return;
13852
+ try {
13853
+ swapReconstructedInstances();
13854
+ } finally {
13855
+ reconstructed.length = 0;
13856
+ }
13857
+ }
13858
+ function swapReconstructedInstances() {
14865
13859
  for (const [instance] of reconstructed) {
14866
13860
  const parent = instance.parent;
14867
13861
  if (parent) {
@@ -14879,6 +13873,7 @@ function swapInstances() {
14879
13873
  }
14880
13874
  }
14881
13875
  if (instance.isHidden) unhideInstance(instance);
13876
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14882
13877
  if (instance.object.__r3f) delete instance.object.__r3f;
14883
13878
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14884
13879
  }
@@ -14891,6 +13886,8 @@ function swapInstances() {
14891
13886
  instance.object.__r3f = instance;
14892
13887
  setFiberRef(fiber, instance.object);
14893
13888
  delete instance.appliedOnce;
13889
+ instance.eventCount = 0;
13890
+ instance.handlers = {};
14894
13891
  applyProps(instance.object, instance.props);
14895
13892
  if (instance.props.attach) {
14896
13893
  attach(parent, instance);
@@ -14907,14 +13904,114 @@ function swapInstances() {
14907
13904
  invalidateInstance(instance);
14908
13905
  }
14909
13906
  }
14910
- reconstructed.length = 0;
14911
13907
  }
14912
13908
  const handleTextInstance = () => {
14913
13909
  };
14914
13910
  const NO_CONTEXT = {};
14915
13911
  let currentUpdatePriority = NoEventPriority;
14916
- const NoFlags = 0;
14917
- const Update = 4;
13912
+ function getEventPriority(type) {
13913
+ switch (type) {
13914
+ case "beforetoggle":
13915
+ case "cancel":
13916
+ case "click":
13917
+ case "close":
13918
+ case "contextmenu":
13919
+ case "copy":
13920
+ case "cut":
13921
+ case "auxclick":
13922
+ case "dblclick":
13923
+ case "dragend":
13924
+ case "dragstart":
13925
+ case "drop":
13926
+ case "focusin":
13927
+ case "focusout":
13928
+ case "input":
13929
+ case "invalid":
13930
+ case "keydown":
13931
+ case "keypress":
13932
+ case "keyup":
13933
+ case "mousedown":
13934
+ case "mouseup":
13935
+ case "paste":
13936
+ case "pause":
13937
+ case "play":
13938
+ case "pointercancel":
13939
+ case "pointerdown":
13940
+ case "pointerup":
13941
+ case "ratechange":
13942
+ case "reset":
13943
+ case "resize":
13944
+ case "seeked":
13945
+ case "submit":
13946
+ case "touchcancel":
13947
+ case "touchend":
13948
+ case "touchstart":
13949
+ case "volumechange":
13950
+ case "change":
13951
+ case "selectionchange":
13952
+ case "compositionstart":
13953
+ case "compositionend":
13954
+ case "compositionupdate":
13955
+ case "beforeinput":
13956
+ case "blur":
13957
+ case "fullscreenchange":
13958
+ case "focus":
13959
+ case "hashchange":
13960
+ case "popstate":
13961
+ case "select":
13962
+ case "selectstart":
13963
+ return e;
13964
+ case "drag":
13965
+ case "dragenter":
13966
+ case "dragexit":
13967
+ case "dragleave":
13968
+ case "dragover":
13969
+ case "mousemove":
13970
+ case "mouseout":
13971
+ case "mouseover":
13972
+ case "pointermove":
13973
+ case "pointerout":
13974
+ case "pointerover":
13975
+ case "scroll":
13976
+ case "touchmove":
13977
+ case "wheel":
13978
+ case "mouseenter":
13979
+ case "mouseleave":
13980
+ case "pointerenter":
13981
+ case "pointerleave":
13982
+ return o;
13983
+ case "message": {
13984
+ switch (unstable_getCurrentPriorityLevel()) {
13985
+ case unstable_ImmediatePriority:
13986
+ return e;
13987
+ case unstable_UserBlockingPriority:
13988
+ return o;
13989
+ case unstable_NormalPriority:
13990
+ case unstable_LowPriority:
13991
+ return r;
13992
+ case unstable_IdlePriority:
13993
+ return i$1;
13994
+ default:
13995
+ return r;
13996
+ }
13997
+ }
13998
+ default:
13999
+ return r;
14000
+ }
14001
+ }
14002
+ function scheduleMicrotask(callback) {
14003
+ if (typeof queueMicrotask === "function") {
14004
+ queueMicrotask(callback);
14005
+ } else if (typeof Promise !== "undefined") {
14006
+ Promise.resolve().then(callback).catch((error) => {
14007
+ setTimeout(() => {
14008
+ throw error;
14009
+ });
14010
+ });
14011
+ } else {
14012
+ setTimeout(callback);
14013
+ }
14014
+ }
14918
14015
  const reconciler = /* @__PURE__ */ createReconciler({
14919
14016
  isPrimaryRenderer: false,
14920
14017
  warnsIfNotActing: false,
@@ -14953,16 +14050,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14953
14050
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14954
14051
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14955
14052
  if (reconstruct) {
14956
- reconstructed.push([instance, { ...newProps }, fiber]);
14053
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14957
14054
  } else {
14958
14055
  const changedProps = diffProps(instance, newProps);
14959
- if (Object.keys(changedProps).length) {
14960
- Object.assign(instance.props, changedProps);
14961
- applyProps(instance.object, changedProps);
14962
- }
14056
+ const attach2 = instance.props.attach;
14057
+ instance.props = getInstanceProps(newProps);
14058
+ if (attach2 !== void 0) instance.props.attach = attach2;
14059
+ else delete instance.props.attach;
14060
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14963
14061
  }
14964
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14965
- if (isTailSibling) swapInstances();
14966
14062
  },
14967
14063
  finalizeInitialChildren: (instance) => {
14968
14064
  for (const prop in instance.props) {
@@ -14987,8 +14083,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14987
14083
  const target = container.getState().internal.container ?? container.getState().scene;
14988
14084
  return prepare(target, container, "", {});
14989
14085
  },
14990
- resetAfterCommit: () => {
14991
- },
14086
+ // Reconstructed instances are swapped once all mutations are committed,
14087
+ // before layout effects run so refs point to the new objects
14088
+ resetAfterCommit: flushReconstructedInstances,
14992
14089
  shouldSetTextContent: () => false,
14993
14090
  clearContainer: () => false,
14994
14091
  hideInstance,
@@ -14996,6 +14093,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14996
14093
  createTextInstance: handleTextInstance,
14997
14094
  hideTextInstance: handleTextInstance,
14998
14095
  unhideTextInstance: handleTextInstance,
14096
+ // Mirrors react-dom, which flushes discrete work in microtasks
14097
+ supportsMicrotasks: true,
14098
+ scheduleMicrotask,
14999
14099
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
15000
14100
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
15001
14101
  noTimeout: -1,
@@ -15036,28 +14136,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15036
14136
  },
15037
14137
  resolveUpdatePriority() {
15038
14138
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
15039
- switch (typeof window !== "undefined" && window.event?.type) {
15040
- case "click":
15041
- case "contextmenu":
15042
- case "dblclick":
15043
- case "dragenter":
15044
- case "dragleave":
15045
- case "drop":
15046
- case "pointercancel":
15047
- case "pointerdown":
15048
- case "pointerup":
15049
- return e;
15050
- case "dragover":
15051
- case "pointermove":
15052
- case "pointerout":
15053
- case "pointerover":
15054
- case "pointerenter":
15055
- case "pointerleave":
15056
- case "wheel":
15057
- return o;
15058
- default:
15059
- return r;
15060
- }
14139
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14140
+ if (eventType === void 0) return r;
14141
+ return getEventPriority(eventType);
15061
14142
  },
15062
14143
  resetFormInstance() {
15063
14144
  },
@@ -15106,11 +14187,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15106
14187
  cloneMutableTextInstance(textInstance) {
15107
14188
  return textInstance;
15108
14189
  },
14190
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14191
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14192
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14193
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14194
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14195
+ // Guarded by a test asserting a full render + unmount never reaches them.
15109
14196
  cloneRootViewTransitionContainer(_rootContainer) {
15110
- throw new Error("Not implemented.");
15111
14197
  },
15112
14198
  removeRootViewTransitionClone(_rootContainer, _clone) {
15113
- throw new Error("Not implemented.");
15114
14199
  },
15115
14200
  // https://github.com/facebook/react/pull/32465
15116
14201
  createFragmentInstance: (_fiber) => null,
@@ -15195,6 +14280,7 @@ function createRoot(canvas) {
15195
14280
  const lastConfiguredProps = {};
15196
14281
  let configured = false;
15197
14282
  let pending = null;
14283
+ let rendererSetup = null;
15198
14284
  return {
15199
14285
  async configure(props = {}) {
15200
14286
  let resolve;
@@ -15225,7 +14311,7 @@ function createRoot(canvas) {
15225
14311
  forceEven
15226
14312
  } = props;
15227
14313
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15228
- const state = store.getState();
14314
+ let state = store.getState();
15229
14315
  const defaultGPUProps = {
15230
14316
  canvas,
15231
14317
  antialias: true
@@ -15239,52 +14325,64 @@ function createRoot(canvas) {
15239
14325
  throw new Error("Cannot use both gl and renderer props at the same time");
15240
14326
  }
15241
14327
  let renderer = state.internal.actualRenderer;
15242
- if (primaryCanvas && !state.internal.actualRenderer) {
15243
- const primary = await waitForPrimary(primaryCanvas);
15244
- renderer = primary.renderer;
15245
- state.internal.actualRenderer = renderer;
15246
- const canvasTarget = new CanvasTarget(canvas);
15247
- primary.store.setState((prev) => ({
15248
- internal: { ...prev.internal, isMultiCanvas: true }
15249
- }));
15250
- state.set((prev) => ({
15251
- webGPUSupported: primary.store.getState().webGPUSupported,
15252
- renderer,
15253
- primaryStore: primary.store,
15254
- internal: {
15255
- ...prev.internal,
15256
- canvasTarget,
15257
- isMultiCanvas: true,
15258
- isSecondary: true,
15259
- targetId: primaryCanvas
15260
- }
15261
- }));
15262
- } else if (!state.internal.actualRenderer) {
15263
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15264
- if (!renderer.hasInitialized?.()) {
15265
- const size2 = computeInitialSize(canvas, propsSize);
15266
- if (size2.width > 0 && size2.height > 0) {
15267
- const pixelRatio = calculateDpr(dpr);
15268
- canvas.width = size2.width * pixelRatio;
15269
- canvas.height = size2.height * pixelRatio;
15270
- }
15271
- await renderer.init();
15272
- }
15273
- const backend = renderer.backend;
15274
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15275
- state.internal.actualRenderer = renderer;
15276
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15277
- if (canvasId && !state.internal.isSecondary) {
15278
- const canvasTarget = new CanvasTarget(canvas);
15279
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15280
- state.set((prev) => ({
15281
- internal: {
15282
- ...prev.internal,
15283
- canvasTarget,
15284
- unregisterPrimary
14328
+ if (!state.internal.actualRenderer) {
14329
+ if (!rendererSetup) {
14330
+ rendererSetup = (async () => {
14331
+ if (primaryCanvas) {
14332
+ const primary = await waitForPrimary(primaryCanvas);
14333
+ renderer = primary.renderer;
14334
+ state.internal.actualRenderer = renderer;
14335
+ const canvasTarget = new CanvasTarget(canvas);
14336
+ primary.store.setState((prev) => ({
14337
+ internal: { ...prev.internal, isMultiCanvas: true }
14338
+ }));
14339
+ state.set((prev) => ({
14340
+ webGPUSupported: primary.store.getState().webGPUSupported,
14341
+ renderer,
14342
+ primaryStore: primary.store,
14343
+ internal: {
14344
+ ...prev.internal,
14345
+ canvasTarget,
14346
+ isMultiCanvas: true,
14347
+ isSecondary: true,
14348
+ targetId: primaryCanvas
14349
+ }
14350
+ }));
14351
+ } else {
14352
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14353
+ if (!renderer.hasInitialized?.()) {
14354
+ const size2 = computeInitialSize(canvas, propsSize);
14355
+ if (size2.width > 0 && size2.height > 0) {
14356
+ const pixelRatio = calculateDpr(dpr);
14357
+ canvas.width = size2.width * pixelRatio;
14358
+ canvas.height = size2.height * pixelRatio;
14359
+ }
14360
+ await renderer.init();
14361
+ }
14362
+ const backend = renderer.backend;
14363
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14364
+ state.internal.actualRenderer = renderer;
14365
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14366
+ if (canvasId && !state.internal.isSecondary) {
14367
+ const canvasTarget = new CanvasTarget(canvas);
14368
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14369
+ state.set((prev) => ({
14370
+ internal: {
14371
+ ...prev.internal,
14372
+ canvasTarget,
14373
+ unregisterPrimary
14374
+ }
14375
+ }));
14376
+ }
15285
14377
  }
15286
- }));
14378
+ })().catch((err) => {
14379
+ rendererSetup = null;
14380
+ throw err;
14381
+ });
15287
14382
  }
14383
+ await rendererSetup;
14384
+ state = store.getState();
14385
+ renderer = state.internal.actualRenderer;
15288
14386
  }
15289
14387
  let raycaster = state.raycaster;
15290
14388
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15509,7 +14607,7 @@ function createRoot(canvas) {
15509
14607
  {
15510
14608
  id: `${newRootId}_frustum`,
15511
14609
  rootId: newRootId,
15512
- phase: "preRender",
14610
+ before: "render",
15513
14611
  system: true
15514
14612
  }
15515
14613
  );
@@ -15521,7 +14619,7 @@ function createRoot(canvas) {
15521
14619
  {
15522
14620
  id: `${newRootId}_visibility`,
15523
14621
  rootId: newRootId,
15524
- phase: "preRender",
14622
+ before: "render",
15525
14623
  system: true,
15526
14624
  after: `${newRootId}_frustum`
15527
14625
  }
@@ -15634,7 +14732,8 @@ function unmountComponentAtNode(canvas, callback) {
15634
14732
  dispose(state.scene);
15635
14733
  _roots.delete(canvas);
15636
14734
  if (callback) callback(canvas);
15637
- } catch {
14735
+ } catch (error) {
14736
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15638
14737
  }
15639
14738
  }, 500);
15640
14739
  }
@@ -15697,6 +14796,7 @@ function PortalInner({ state = {}, children, container }) {
15697
14796
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15698
14797
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15699
14798
  }
14799
+ const set = injectState.set;
15700
14800
  return {
15701
14801
  // The intersect consists of the previous root state
15702
14802
  ...rootState,
@@ -15715,33 +14815,205 @@ function PortalInner({ state = {}, children, container }) {
15715
14815
  size: resolvedSize,
15716
14816
  viewport: { ...rootState.viewport, ...viewport },
15717
14817
  // Layers are allowed to override events
15718
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14818
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15719
14819
  // Container for child attachment - the portalScene (injected or container itself)
15720
14820
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15721
14821
  };
15722
14822
  });
15723
- const usePortalStore = useMemo(() => {
15724
- const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15725
- const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15726
- onMutate(previousRoot.getState());
15727
- return store;
15728
- }, [previousRoot, container]);
15729
- useIsomorphicLayoutEffect(() => {
15730
- const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
15731
- const unsubscribe = previousRoot.subscribe(onMutate);
15732
- return unsubscribe;
15733
- }, [previousRoot, usePortalStore]);
15734
- return (
15735
- // @ts-ignore, reconciler types are not maintained
15736
- /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
15737
- /* @__PURE__ */ jsx(context.Provider, { value: usePortalStore, children }),
15738
- usePortalStore,
15739
- null
15740
- ) })
15741
- );
14823
+ const usePortalStore = useMemo(() => {
14824
+ const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14825
+ const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14826
+ onMutate(previousRoot.getState());
14827
+ return store;
14828
+ }, [previousRoot, container]);
14829
+ useIsomorphicLayoutEffect(() => {
14830
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14831
+ const unsubscribe = previousRoot.subscribe(onMutate);
14832
+ return unsubscribe;
14833
+ }, [previousRoot, usePortalStore]);
14834
+ return (
14835
+ // @ts-ignore, reconciler types are not maintained
14836
+ /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
14837
+ /* @__PURE__ */ jsx(context.Provider, { value: usePortalStore, children }),
14838
+ usePortalStore,
14839
+ null
14840
+ ) })
14841
+ );
14842
+ }
14843
+ function flushSync(fn) {
14844
+ return reconciler.flushSyncFromReconciler(fn);
14845
+ }
14846
+
14847
+ function parseBackground(background) {
14848
+ if (!background) return null;
14849
+ if (typeof background === "object" && !background.isColor) {
14850
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14851
+ return {
14852
+ ...rest,
14853
+ preset,
14854
+ files: envMap || files,
14855
+ backgroundFiles: backgroundMap,
14856
+ background: true
14857
+ };
14858
+ }
14859
+ if (typeof background === "number") {
14860
+ return { color: background, background: true };
14861
+ }
14862
+ if (typeof background === "string") {
14863
+ if (background in presetsObj) {
14864
+ return { preset: background, background: true };
14865
+ }
14866
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14867
+ return { files: background, background: true };
14868
+ }
14869
+ return { color: background, background: true };
14870
+ }
14871
+ if (background.isColor) {
14872
+ return { color: background, background: true };
14873
+ }
14874
+ return null;
14875
+ }
14876
+
14877
+ function parseRendererConfig(rendererProp) {
14878
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14879
+ if (isRendererConfig) {
14880
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14881
+ return {
14882
+ primaryCanvas: pc,
14883
+ scheduler: sc,
14884
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14885
+ };
14886
+ }
14887
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14888
+ }
14889
+
14890
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14891
+ const ROOT_SCOPE = "";
14892
+ const registries = /* @__PURE__ */ new WeakMap();
14893
+ function getKindRegistry(store, kind) {
14894
+ let registry = registries.get(store);
14895
+ if (!registry) {
14896
+ registry = {
14897
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14898
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14899
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14900
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14901
+ };
14902
+ registries.set(store, registry);
14903
+ }
14904
+ return registry[kind];
14905
+ }
14906
+ function resolvePrimary$1(store) {
14907
+ return store.getState().primaryStore ?? store;
14908
+ }
14909
+ function isScopeValid(store, kind, scopeKey) {
14910
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14911
+ }
14912
+ function peekStaged(store, kind, scopeKey) {
14913
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14914
+ }
14915
+ function stageEntries(store, kind, scopeKey, entries) {
14916
+ const { staged } = getKindRegistry(store, kind);
14917
+ const current = staged.get(scopeKey);
14918
+ if (current) Object.assign(current, entries);
14919
+ else staged.set(scopeKey, { ...entries });
14920
+ }
14921
+ function readCommittedScope(map, scopeKey, isLeaf) {
14922
+ if (scopeKey === ROOT_SCOPE) {
14923
+ const leaves = {};
14924
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14925
+ return leaves;
14926
+ }
14927
+ const scopeData = map[scopeKey];
14928
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14929
+ return {};
14930
+ }
14931
+ function withStagedOverlay(store, kind, committed) {
14932
+ const { staged } = getKindRegistry(store, kind);
14933
+ if (staged.size === 0) return committed;
14934
+ const view = { ...committed };
14935
+ for (const [scopeKey, entries] of staged) {
14936
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14937
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14938
+ }
14939
+ return view;
14940
+ }
14941
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14942
+ const registry = getKindRegistry(store, kind);
14943
+ const staged = registry.staged.get(scopeKey);
14944
+ if (!staged) return;
14945
+ registry.staged.delete(scopeKey);
14946
+ const replace = !registry.valid.has(scopeKey);
14947
+ store.setState((state) => {
14948
+ const map = state[kind];
14949
+ if (scopeKey === ROOT_SCOPE) {
14950
+ if (!replace) return { [kind]: { ...map, ...staged } };
14951
+ const next = {};
14952
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14953
+ return { [kind]: { ...next, ...staged } };
14954
+ }
14955
+ const current = replace ? {} : map[scopeKey] ?? {};
14956
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14957
+ });
14958
+ registry.valid.add(scopeKey);
14959
+ }
14960
+ function invalidateResource(store, kind, scopeKey) {
14961
+ const registry = getKindRegistry(store, kind);
14962
+ if (scopeKey === void 0) {
14963
+ registry.valid.clear();
14964
+ registry.staged.clear();
14965
+ } else {
14966
+ registry.valid.delete(scopeKey);
14967
+ registry.staged.delete(scopeKey);
14968
+ }
14969
+ }
14970
+ function rebuildResource(store, kind, userScope) {
14971
+ const primary = resolvePrimary$1(store);
14972
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14973
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14974
+ }
14975
+ function invalidateAllResources(store) {
14976
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14977
+ }
14978
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14979
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
14980
+ if (staged) for (const name of names) delete staged[name];
14981
+ store.setState((state) => {
14982
+ const map = state[kind];
14983
+ if (scope) {
14984
+ const currentScope = { ...map[scope] };
14985
+ for (const name of names) delete currentScope[name];
14986
+ return { [kind]: { ...map, [scope]: currentScope } };
14987
+ }
14988
+ const next = { ...map };
14989
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
14990
+ return { [kind]: next };
14991
+ });
15742
14992
  }
15743
- function flushSync(fn) {
15744
- return reconciler.flushSyncFromReconciler(fn);
14993
+ function clearResourceEntries(store, kind, scope, isLeaf) {
14994
+ const registry = getKindRegistry(store, kind);
14995
+ if (scope && scope !== "root") registry.staged.delete(scope);
14996
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
14997
+ else registry.staged.clear();
14998
+ store.setState((state) => {
14999
+ const map = state[kind];
15000
+ if (scope && scope !== "root") {
15001
+ const { [scope]: _, ...rest } = map;
15002
+ return { [kind]: rest };
15003
+ }
15004
+ if (scope === "root") {
15005
+ const next = {};
15006
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
15007
+ return { [kind]: next };
15008
+ }
15009
+ return { [kind]: {} };
15010
+ });
15011
+ }
15012
+
15013
+ function clearHmrCaches(store) {
15014
+ const primary = store.getState().primaryStore ?? store;
15015
+ invalidateAllResources(primary);
15016
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
15745
15017
  }
15746
15018
 
15747
15019
  function CanvasImpl({
@@ -15764,6 +15036,8 @@ function CanvasImpl({
15764
15036
  raycaster,
15765
15037
  camera,
15766
15038
  scene,
15039
+ autoUpdateFrustum,
15040
+ occlusion,
15767
15041
  onPointerMissed,
15768
15042
  onDragOverMissed,
15769
15043
  onDropMissed,
@@ -15775,49 +15049,10 @@ function CanvasImpl({
15775
15049
  forceEven,
15776
15050
  ...props
15777
15051
  }) {
15778
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15779
- let primaryCanvas;
15780
- let scheduler;
15781
- let renderer;
15782
- if (isRendererConfig) {
15783
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15784
- primaryCanvas = pc;
15785
- scheduler = sc;
15786
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15787
- } else {
15788
- renderer = rendererProp;
15789
- }
15052
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15790
15053
  React.useMemo(() => extend(THREE), []);
15791
15054
  const Bridge = useBridge();
15792
- const backgroundProps = React.useMemo(() => {
15793
- if (!background) return null;
15794
- if (typeof background === "object" && !background.isColor) {
15795
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15796
- return {
15797
- ...rest,
15798
- preset,
15799
- files: envMap || files,
15800
- backgroundFiles: backgroundMap,
15801
- background: true
15802
- };
15803
- }
15804
- if (typeof background === "number") {
15805
- return { color: background, background: true };
15806
- }
15807
- if (typeof background === "string") {
15808
- if (background in presetsObj) {
15809
- return { preset: background, background: true };
15810
- }
15811
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15812
- return { files: background, background: true };
15813
- }
15814
- return { color: background, background: true };
15815
- }
15816
- if (background.isColor) {
15817
- return { color: background, background: true };
15818
- }
15819
- return null;
15820
- }, [background]);
15055
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15821
15056
  const hasInitialSizeRef = React.useRef(false);
15822
15057
  const measureConfig = React.useMemo(() => {
15823
15058
  if (!hasInitialSizeRef.current) {
@@ -15859,6 +15094,7 @@ function CanvasImpl({
15859
15094
  const handleDropMissed = useMutableCallback(onDropMissed);
15860
15095
  const [block, setBlock] = React.useState(false);
15861
15096
  const [error, setError] = React.useState(false);
15097
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15862
15098
  if (block) throw block;
15863
15099
  if (error) throw error;
15864
15100
  const root = React.useRef(null);
@@ -15866,6 +15102,7 @@ function CanvasImpl({
15866
15102
  const unsubscribeErrorRef = React.useRef(null);
15867
15103
  useIsomorphicLayoutEffect(() => {
15868
15104
  effectActiveRef.current = true;
15105
+ if (fallbackVisible) return;
15869
15106
  const canvas = canvasRef.current;
15870
15107
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15871
15108
  if (!root.current) {
@@ -15886,7 +15123,7 @@ function CanvasImpl({
15886
15123
  }
15887
15124
  async function run() {
15888
15125
  if (!effectActiveRef.current || !root.current) return;
15889
- await root.current.configure({
15126
+ const configured = await root.current.configure({
15890
15127
  id,
15891
15128
  primaryCanvas,
15892
15129
  scheduler,
@@ -15901,6 +15138,8 @@ function CanvasImpl({
15901
15138
  performance,
15902
15139
  raycaster,
15903
15140
  camera,
15141
+ autoUpdateFrustum,
15142
+ occlusion,
15904
15143
  size: effectiveSize,
15905
15144
  // Store size props for reset functionality
15906
15145
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15925,8 +15164,20 @@ function CanvasImpl({
15925
15164
  }
15926
15165
  onCreated?.(state);
15927
15166
  }
15928
- });
15929
- if (!effectActiveRef.current || !root.current) return;
15167
+ }).then(
15168
+ () => true,
15169
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15170
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15171
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15172
+ (setupError) => {
15173
+ if (effectActiveRef.current) {
15174
+ if (fallback != null) setFallbackVisible(true);
15175
+ else setError(setupError);
15176
+ }
15177
+ return false;
15178
+ }
15179
+ );
15180
+ if (!configured || !effectActiveRef.current || !root.current) return;
15930
15181
  root.current.render(
15931
15182
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15932
15183
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15960,14 +15211,7 @@ function CanvasImpl({
15960
15211
  const handleHMR = () => {
15961
15212
  queueMicrotask(() => {
15962
15213
  const rootEntry = _roots.get(canvas);
15963
- if (rootEntry?.store) {
15964
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15965
- rootEntry.store.setState((state) => ({
15966
- nodes: {},
15967
- uniforms: {},
15968
- _hmrVersion: state._hmrVersion + 1
15969
- }));
15970
- }
15214
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15971
15215
  });
15972
15216
  };
15973
15217
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -15996,7 +15240,11 @@ function CanvasImpl({
15996
15240
  ...style
15997
15241
  },
15998
15242
  ...props,
15999
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15243
+ children: fallbackVisible ? (
15244
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15245
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15246
+ fallback
15247
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
16000
15248
  "canvas",
16001
15249
  {
16002
15250
  ref: canvasRef,
@@ -16078,35 +15326,50 @@ let ScopedStore = _ScopedStore;
16078
15326
  function createScopedStore(data) {
16079
15327
  return new ScopedStore(data);
16080
15328
  }
16081
- function createLazyCreatorState(state) {
15329
+ function createLazyCreatorState(state, store) {
16082
15330
  let _uniforms = null;
16083
15331
  let _nodes = null;
16084
15332
  let _buffers = null;
16085
15333
  let _gpuStorage = null;
15334
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
16086
15335
  return Object.create(state, {
16087
15336
  uniforms: {
16088
15337
  get() {
16089
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15338
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
16090
15339
  }
16091
15340
  },
16092
15341
  nodes: {
16093
15342
  get() {
16094
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15343
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
16095
15344
  }
16096
15345
  },
16097
15346
  buffers: {
16098
15347
  get() {
16099
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15348
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
16100
15349
  }
16101
15350
  },
16102
15351
  gpuStorage: {
16103
15352
  get() {
16104
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15353
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
16105
15354
  }
16106
15355
  }
16107
15356
  });
16108
15357
  }
16109
15358
 
15359
+ function resolvePrimary(local) {
15360
+ return local.getState().primaryStore ?? local;
15361
+ }
15362
+ function usePrimaryStore() {
15363
+ const local = useStore();
15364
+ const primary = local.getState().primaryStore;
15365
+ return useMemo(() => primary ?? local, [primary, local]);
15366
+ }
15367
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15368
+ const local = useStore();
15369
+ const primary = resolvePrimary(local);
15370
+ return primary(selector, equalityFn);
15371
+ }
15372
+
16110
15373
  function addTexture(set, key, value) {
16111
15374
  set((state) => {
16112
15375
  const newMap = new Map(state.textures);
@@ -16210,65 +15473,56 @@ function useCompareMemoize(value, deep) {
16210
15473
  return ref.current;
16211
15474
  }
16212
15475
 
15476
+ function useScopedResource(options) {
15477
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15478
+ const scopeKey = scope ?? ROOT_SCOPE;
15479
+ const version = store((s) => s._hmrVersion);
15480
+ const entries = useMemo(() => {
15481
+ const staged = peekStaged(store, kind, scopeKey);
15482
+ const reusable = isScopeValid(store, kind, scopeKey);
15483
+ const map = store.getState()[kind];
15484
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15485
+ const result = {};
15486
+ let fresh = null;
15487
+ for (const [name, candidate] of Object.entries(create())) {
15488
+ const existing = staged?.[name] ?? committed?.[name];
15489
+ if (existing !== void 0) {
15490
+ result[name] = existing;
15491
+ reconcile?.(existing, candidate);
15492
+ } else {
15493
+ const value = prepare ? prepare(name, candidate) : candidate;
15494
+ result[name] = value;
15495
+ (fresh ?? (fresh = {}))[name] = value;
15496
+ }
15497
+ }
15498
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15499
+ return result;
15500
+ }, [store, kind, scopeKey, version, input]);
15501
+ useIsomorphicLayoutEffect(() => {
15502
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15503
+ });
15504
+ return entries;
15505
+ }
15506
+
16213
15507
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16214
15508
  function useUniforms(creatorOrScope, scope) {
16215
- const store = useStore();
15509
+ const store = usePrimaryStore();
16216
15510
  const removeUniforms2 = useCallback(
16217
- (names, targetScope) => {
16218
- const nameArray = Array.isArray(names) ? names : [names];
16219
- store.setState((state) => {
16220
- if (targetScope) {
16221
- const currentScope = { ...state.uniforms[targetScope] };
16222
- for (const name of nameArray) delete currentScope[name];
16223
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
16224
- }
16225
- const uniforms2 = { ...state.uniforms };
16226
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
16227
- return { uniforms: uniforms2 };
16228
- });
16229
- },
15511
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
16230
15512
  [store]
16231
15513
  );
16232
15514
  const clearUniforms = useCallback(
16233
- (targetScope) => {
16234
- store.setState((state) => {
16235
- if (targetScope && targetScope !== "root") {
16236
- const { [targetScope]: _, ...rest } = state.uniforms;
16237
- return { uniforms: rest };
16238
- }
16239
- if (targetScope === "root") {
16240
- const uniforms2 = {};
16241
- for (const [key, value] of Object.entries(state.uniforms)) {
16242
- if (!isUniformNode$1(value)) uniforms2[key] = value;
16243
- }
16244
- return { uniforms: uniforms2 };
16245
- }
16246
- return { uniforms: {} };
16247
- });
16248
- },
15515
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
16249
15516
  [store]
16250
15517
  );
16251
15518
  const rebuildUniforms = useCallback(
16252
- (targetScope) => {
16253
- store.setState((state) => {
16254
- let newUniforms = {};
16255
- if (targetScope && targetScope !== "root") {
16256
- const { [targetScope]: _, ...rest } = state.uniforms;
16257
- newUniforms = rest;
16258
- } else if (targetScope === "root") {
16259
- for (const [key, value] of Object.entries(state.uniforms)) {
16260
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16261
- }
16262
- }
16263
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16264
- });
16265
- },
15519
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
16266
15520
  [store]
16267
15521
  );
16268
15522
  const inputForMemoization = useMemo(() => {
16269
15523
  let raw = creatorOrScope;
16270
15524
  if (is.fun(creatorOrScope)) {
16271
- const wrappedState = createLazyCreatorState(store.getState());
15525
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16272
15526
  raw = creatorOrScope(wrappedState);
16273
15527
  }
16274
15528
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -16282,80 +15536,44 @@ function useUniforms(creatorOrScope, scope) {
16282
15536
  }, [creatorOrScope, store]);
16283
15537
  const memoizedInput = useCompareMemoize(inputForMemoization);
16284
15538
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16285
- const storeUniforms = useThree((s) => s.uniforms);
16286
- const hmrVersion = useThree((s) => s._hmrVersion);
16287
- const readerDep = isReader ? storeUniforms : null;
16288
- const creatorDep = isReader ? null : hmrVersion;
16289
- const uniforms = useMemo(() => {
16290
- if (memoizedInput === void 0) {
16291
- return storeUniforms;
16292
- }
16293
- if (typeof memoizedInput === "string") {
16294
- const scopeData = storeUniforms[memoizedInput];
16295
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
16296
- return {};
16297
- }
16298
- const state = store.getState();
16299
- const set = store.setState;
16300
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
16301
- throw new Error("Invalid uniform input");
16302
- }
16303
- const created = memoizedInput;
16304
- const result = {};
16305
- let hasNewUniforms = false;
16306
- let targetRecord = state.uniforms;
16307
- if (scope) {
16308
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
16309
- targetRecord = state.uniforms[scope];
16310
- }
16311
- for (const [name, node] of Object.entries(created)) {
16312
- if (targetRecord[name]) {
16313
- result[name] = targetRecord[name];
16314
- const existingVal = result[name].value;
16315
- const newVal = vectorize(node);
16316
- let equals = newVal === existingVal;
16317
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
16318
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
16319
- equals = vectorEquals(existingVal, newVal);
16320
- } else if (isSameThreeType(existingVal, newVal)) {
16321
- equals = existingVal.equals(newVal);
16322
- }
15539
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15540
+ const created = useScopedResource({
15541
+ store,
15542
+ kind: "uniforms",
15543
+ scope: isReader ? void 0 : scope,
15544
+ isLeaf: isUniformNode$1,
15545
+ input: memoizedInput,
15546
+ create: () => {
15547
+ if (isReader) return {};
15548
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15549
+ return memoizedInput;
15550
+ },
15551
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15552
+ reconcile: (existing, candidate) => {
15553
+ const existingVal = existing.value;
15554
+ const newVal = vectorize(candidate);
15555
+ let equals = newVal === existingVal;
15556
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15557
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15558
+ equals = vectorEquals(existingVal, newVal);
15559
+ } else if (isSameThreeType(existingVal, newVal)) {
15560
+ equals = existingVal.equals(newVal);
16323
15561
  }
16324
- if (!equals) result[name].value = newVal;
16325
- } else {
16326
- result[name] = createUniform(name, node, scope);
16327
- hasNewUniforms = true;
16328
- }
16329
- }
16330
- if (hasNewUniforms) {
16331
- if (scope) {
16332
- set((s) => ({
16333
- uniforms: {
16334
- ...s.uniforms,
16335
- [scope]: { ...s.uniforms[scope], ...result }
16336
- }
16337
- }));
16338
- } else {
16339
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
16340
15562
  }
15563
+ if (!equals) existing.value = newVal;
16341
15564
  }
16342
- return result;
16343
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15565
+ });
15566
+ let uniforms = created;
15567
+ if (memoizedInput === void 0) {
15568
+ uniforms = storeUniforms;
15569
+ } else if (typeof memoizedInput === "string") {
15570
+ const scopeData = storeUniforms[memoizedInput];
15571
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15572
+ }
16344
15573
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16345
15574
  }
16346
15575
  function rebuildAllUniforms(store, scope) {
16347
- store.setState((state) => {
16348
- let newUniforms = {};
16349
- if (scope && scope !== "root") {
16350
- const { [scope]: _, ...rest } = state.uniforms;
16351
- newUniforms = rest;
16352
- } else if (scope === "root") {
16353
- for (const [key, value] of Object.entries(state.uniforms)) {
16354
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16355
- }
16356
- }
16357
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16358
- });
15576
+ rebuildResource(store, "uniforms", scope);
16359
15577
  }
16360
15578
  function removeUniforms(set, names, scope) {
16361
15579
  set((state) => {
@@ -16419,191 +15637,91 @@ function isSameThreeType(a, b) {
16419
15637
  return obj_a.isColor && obj_b.isColor || obj_a.isMatrix3 && obj_b.isMatrix3 || obj_a.isMatrix4 && obj_b.isMatrix4 || obj_a.isEuler && obj_b.isEuler || obj_a.isQuaternion && obj_b.isQuaternion;
16420
15638
  }
16421
15639
 
15640
+ const uniformOf = uniform;
16422
15641
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16423
15642
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16424
15643
  function useUniform(name, value) {
16425
15644
  const store = useStore();
16426
- const hmrVersion = useThree((s) => s._hmrVersion);
16427
- return useMemo(() => {
16428
- const state = store.getState();
16429
- const set = store.setState;
16430
- const existing = state.uniforms[name];
16431
- if (existing && isUniformNode(existing)) {
15645
+ const registered = useScopedResource({
15646
+ store,
15647
+ kind: "uniforms",
15648
+ scope: void 0,
15649
+ isLeaf: isUniformNode,
15650
+ input: name,
15651
+ create: () => value === void 0 ? {} : { [name]: value },
15652
+ prepare: createNamedUniform,
15653
+ reconcile: (existing2) => {
16432
15654
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
16433
- existing.value = typeof value === "string" ? new Color(value) : value;
15655
+ existing2.value = typeof value === "string" ? new Color(value) : value;
16434
15656
  }
16435
- return existing;
16436
- }
16437
- if (value === void 0) {
16438
- throw new Error(
16439
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
16440
- );
16441
- }
16442
- if (isUniformNode(value)) {
16443
- const node2 = value;
16444
- if (typeof node2.setName === "function") {
16445
- node2.setName(name);
16446
- }
16447
- set((s) => ({
16448
- uniforms: { ...s.uniforms, [name]: node2 }
16449
- }));
16450
- return node2;
16451
- }
16452
- let node;
16453
- if (isTSLNode$1(value)) {
16454
- node = uniform(value);
16455
- } else if (typeof value === "string") {
16456
- node = uniform(new Color(value));
16457
- } else {
16458
- node = uniform(value);
16459
- }
16460
- if (typeof node.setName === "function") {
16461
- node.setName(name);
16462
15657
  }
16463
- set((s) => ({
16464
- uniforms: {
16465
- ...s.uniforms,
16466
- [name]: node
16467
- }
16468
- }));
16469
- return node;
16470
- }, [store, name, hmrVersion]);
15658
+ });
15659
+ if (registered[name]) return registered[name];
15660
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15661
+ if (existing && isUniformNode(existing)) return existing;
15662
+ throw new Error(
15663
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15664
+ );
15665
+ }
15666
+ function createNamedUniform(name, value) {
15667
+ let node;
15668
+ if (isUniformNode(value)) {
15669
+ node = value;
15670
+ } else if (isTSLNode$1(value)) {
15671
+ node = uniformOf(value);
15672
+ } else if (typeof value === "string") {
15673
+ node = uniform(new Color(value));
15674
+ } else {
15675
+ node = uniformOf(value);
15676
+ }
15677
+ if (typeof node.setName === "function") {
15678
+ node.setName(name);
15679
+ }
15680
+ return node;
16471
15681
  }
16472
15682
 
16473
15683
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16474
15684
  function useNodes(creatorOrScope, scope) {
16475
- const store = useStore();
15685
+ const store = usePrimaryStore();
16476
15686
  const removeNodes2 = useCallback(
16477
- (names, targetScope) => {
16478
- const nameArray = Array.isArray(names) ? names : [names];
16479
- store.setState((state) => {
16480
- if (targetScope) {
16481
- const currentScope = { ...state.nodes[targetScope] };
16482
- for (const name of nameArray) delete currentScope[name];
16483
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
16484
- }
16485
- const nodes2 = { ...state.nodes };
16486
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
16487
- return { nodes: nodes2 };
16488
- });
16489
- },
15687
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
16490
15688
  [store]
16491
15689
  );
16492
15690
  const clearNodes = useCallback(
16493
- (targetScope) => {
16494
- store.setState((state) => {
16495
- if (targetScope && targetScope !== "root") {
16496
- const { [targetScope]: _, ...rest } = state.nodes;
16497
- return { nodes: rest };
16498
- }
16499
- if (targetScope === "root") {
16500
- const nodes2 = {};
16501
- for (const [key, value] of Object.entries(state.nodes)) {
16502
- if (!isTSLNode(value)) nodes2[key] = value;
16503
- }
16504
- return { nodes: nodes2 };
16505
- }
16506
- return { nodes: {} };
16507
- });
16508
- },
15691
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
16509
15692
  [store]
16510
15693
  );
16511
15694
  const rebuildNodes = useCallback(
16512
- (targetScope) => {
16513
- store.setState((state) => {
16514
- let newNodes = state.nodes;
16515
- if (targetScope && targetScope !== "root") {
16516
- const { [targetScope]: _, ...rest } = state.nodes;
16517
- newNodes = rest;
16518
- } else if (targetScope === "root") {
16519
- newNodes = {};
16520
- for (const [key, value] of Object.entries(state.nodes)) {
16521
- if (!isTSLNode(value)) newNodes[key] = value;
16522
- }
16523
- } else {
16524
- newNodes = {};
16525
- }
16526
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16527
- });
16528
- },
15695
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
16529
15696
  [store]
16530
15697
  );
16531
15698
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16532
- const storeNodes = useThree((s) => s.nodes);
16533
- const hmrVersion = useThree((s) => s._hmrVersion);
16534
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16535
- const readerDep = isReader ? storeNodes : null;
16536
- const creatorDep = isReader ? null : hmrVersion;
16537
- const nodes = useMemo(() => {
16538
- if (creatorOrScope === void 0) {
16539
- return storeNodes;
16540
- }
16541
- if (typeof creatorOrScope === "string") {
16542
- const scopeData = storeNodes[creatorOrScope];
16543
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
16544
- return {};
16545
- }
16546
- const state = store.getState();
16547
- const set = store.setState;
16548
- const creator = creatorOrScope;
16549
- const wrappedState = createLazyCreatorState(state);
16550
- const created = creator(wrappedState);
16551
- const result = {};
16552
- let hasNewNodes = false;
16553
- if (scope) {
16554
- const currentScope = state.nodes[scope] ?? {};
16555
- for (const [name, node] of Object.entries(created)) {
16556
- if (currentScope[name]) {
16557
- result[name] = currentScope[name];
16558
- } else {
16559
- node.setName?.(`${scope}.${name}`);
16560
- result[name] = node;
16561
- hasNewNodes = true;
16562
- }
16563
- }
16564
- if (hasNewNodes) {
16565
- set((s) => ({
16566
- nodes: {
16567
- ...s.nodes,
16568
- [scope]: { ...s.nodes[scope], ...result }
16569
- }
16570
- }));
16571
- }
16572
- return result;
16573
- }
16574
- for (const [name, node] of Object.entries(created)) {
16575
- const existing = state.nodes[name];
16576
- if (existing && isTSLNode(existing)) {
16577
- result[name] = existing;
16578
- } else {
16579
- node.setName?.(name);
16580
- result[name] = node;
16581
- hasNewNodes = true;
16582
- }
16583
- }
16584
- if (hasNewNodes) {
16585
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15699
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15700
+ const created = useScopedResource({
15701
+ store,
15702
+ kind: "nodes",
15703
+ scope: isReader ? void 0 : scope,
15704
+ isLeaf: isTSLNode,
15705
+ create: () => {
15706
+ if (isReader) return {};
15707
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15708
+ },
15709
+ prepare: (name, node) => {
15710
+ node.setName?.(scope ? `${scope}.${name}` : name);
15711
+ return node;
16586
15712
  }
16587
- return result;
16588
- }, [store, scopeDep, readerDep, creatorDep]);
15713
+ });
15714
+ let nodes = created;
15715
+ if (creatorOrScope === void 0) {
15716
+ nodes = storeNodes;
15717
+ } else if (typeof creatorOrScope === "string") {
15718
+ const scopeData = storeNodes[creatorOrScope];
15719
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15720
+ }
16589
15721
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16590
15722
  }
16591
15723
  function rebuildAllNodes(store, scope) {
16592
- store.setState((state) => {
16593
- let newNodes = state.nodes;
16594
- if (scope && scope !== "root") {
16595
- const { [scope]: _, ...rest } = state.nodes;
16596
- newNodes = rest;
16597
- } else if (scope === "root") {
16598
- newNodes = {};
16599
- for (const [key, value] of Object.entries(state.nodes)) {
16600
- if (!isTSLNode(value)) newNodes[key] = value;
16601
- }
16602
- } else {
16603
- newNodes = {};
16604
- }
16605
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16606
- });
15724
+ rebuildResource(store, "nodes", scope);
16607
15725
  }
16608
15726
  function removeNodes(set, names, scope) {
16609
15727
  set((state) => {
@@ -16633,13 +15751,13 @@ function clearRootNodes(set) {
16633
15751
  });
16634
15752
  }
16635
15753
  function useLocalNodes(creator) {
16636
- const store = useStore();
16637
- const uniforms = useThree((s) => s.uniforms);
16638
- const nodes = useThree((s) => s.nodes);
16639
- const textures = useThree((s) => s.textures);
16640
- const hmrVersion = useThree((s) => s._hmrVersion);
15754
+ const store = usePrimaryStore();
15755
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15756
+ const nodes = usePrimaryThree((s) => s.nodes);
15757
+ const textures = usePrimaryThree((s) => s.textures);
15758
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16641
15759
  return useMemo(() => {
16642
- const wrappedState = createLazyCreatorState(store.getState());
15760
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16643
15761
  return creator(wrappedState);
16644
15762
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
16645
15763
  }
@@ -16658,60 +15776,17 @@ const disposeBuffer = (buffer) => {
16658
15776
  }
16659
15777
  };
16660
15778
  function useBuffers(creatorOrScope, scope) {
16661
- const store = useStore();
15779
+ const store = usePrimaryStore();
16662
15780
  const removeBuffers = useCallback(
16663
- (names, targetScope) => {
16664
- const nameArray = Array.isArray(names) ? names : [names];
16665
- store.setState((state) => {
16666
- if (targetScope) {
16667
- const currentScope = { ...state.buffers[targetScope] };
16668
- for (const name of nameArray) delete currentScope[name];
16669
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
16670
- }
16671
- const buffers2 = { ...state.buffers };
16672
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
16673
- return { buffers: buffers2 };
16674
- });
16675
- },
15781
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
16676
15782
  [store]
16677
15783
  );
16678
15784
  const clearBuffers = useCallback(
16679
- (targetScope) => {
16680
- store.setState((state) => {
16681
- if (targetScope && targetScope !== "root") {
16682
- const { [targetScope]: _, ...rest } = state.buffers;
16683
- return { buffers: rest };
16684
- }
16685
- if (targetScope === "root") {
16686
- const buffers2 = {};
16687
- for (const [key, value] of Object.entries(state.buffers)) {
16688
- if (!isBufferLike(value)) buffers2[key] = value;
16689
- }
16690
- return { buffers: buffers2 };
16691
- }
16692
- return { buffers: {} };
16693
- });
16694
- },
15785
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
16695
15786
  [store]
16696
15787
  );
16697
15788
  const rebuildBuffers = useCallback(
16698
- (targetScope) => {
16699
- store.setState((state) => {
16700
- let newBuffers = state.buffers;
16701
- if (targetScope && targetScope !== "root") {
16702
- const { [targetScope]: _, ...rest } = state.buffers;
16703
- newBuffers = rest;
16704
- } else if (targetScope === "root") {
16705
- newBuffers = {};
16706
- for (const [key, value] of Object.entries(state.buffers)) {
16707
- if (!isBufferLike(value)) newBuffers[key] = value;
16708
- }
16709
- } else {
16710
- newBuffers = {};
16711
- }
16712
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16713
- });
16714
- },
15789
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
16715
15790
  [store]
16716
15791
  );
16717
15792
  const disposeBuffers = useCallback(
@@ -16729,85 +15804,34 @@ function useBuffers(creatorOrScope, scope) {
16729
15804
  [store, removeBuffers]
16730
15805
  );
16731
15806
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16732
- const storeBuffers = useThree((s) => s.buffers);
16733
- const hmrVersion = useThree((s) => s._hmrVersion);
16734
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16735
- const readerDep = isReader ? storeBuffers : null;
16736
- const creatorDep = isReader ? null : hmrVersion;
16737
- const buffers = useMemo(() => {
16738
- if (creatorOrScope === void 0) {
16739
- return storeBuffers;
16740
- }
16741
- if (typeof creatorOrScope === "string") {
16742
- const scopeData = storeBuffers[creatorOrScope];
16743
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
16744
- return {};
16745
- }
16746
- const state = store.getState();
16747
- const set = store.setState;
16748
- const creator = creatorOrScope;
16749
- const wrappedState = createLazyCreatorState(state);
16750
- const created = creator(wrappedState);
16751
- const result = {};
16752
- let hasNewBuffers = false;
16753
- if (scope) {
16754
- const currentScope = state.buffers[scope] ?? {};
16755
- for (const [name, buffer] of Object.entries(created)) {
16756
- if (currentScope[name]) {
16757
- result[name] = currentScope[name];
16758
- } else {
16759
- if ("setName" in buffer && typeof buffer.setName === "function") {
16760
- buffer.setName(`${scope}.${name}`);
16761
- }
16762
- result[name] = buffer;
16763
- hasNewBuffers = true;
16764
- }
16765
- }
16766
- if (hasNewBuffers) {
16767
- set((s) => ({
16768
- buffers: {
16769
- ...s.buffers,
16770
- [scope]: { ...s.buffers[scope], ...result }
16771
- }
16772
- }));
16773
- }
16774
- return result;
16775
- }
16776
- for (const [name, buffer] of Object.entries(created)) {
16777
- const existing = state.buffers[name];
16778
- if (existing && isBufferLike(existing)) {
16779
- result[name] = existing;
16780
- } else {
16781
- if ("setName" in buffer && typeof buffer.setName === "function") {
16782
- buffer.setName(name);
16783
- }
16784
- result[name] = buffer;
16785
- hasNewBuffers = true;
15807
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15808
+ const created = useScopedResource({
15809
+ store,
15810
+ kind: "buffers",
15811
+ scope: isReader ? void 0 : scope,
15812
+ isLeaf: isBufferLike,
15813
+ create: () => {
15814
+ if (isReader) return {};
15815
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15816
+ },
15817
+ prepare: (name, buffer) => {
15818
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15819
+ buffer.setName(scope ? `${scope}.${name}` : name);
16786
15820
  }
15821
+ return buffer;
16787
15822
  }
16788
- if (hasNewBuffers) {
16789
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
16790
- }
16791
- return result;
16792
- }, [store, scopeDep, readerDep, creatorDep]);
15823
+ });
15824
+ let buffers = created;
15825
+ if (creatorOrScope === void 0) {
15826
+ buffers = storeBuffers;
15827
+ } else if (typeof creatorOrScope === "string") {
15828
+ const scopeData = storeBuffers[creatorOrScope];
15829
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15830
+ }
16793
15831
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16794
15832
  }
16795
15833
  function rebuildAllBuffers(store, scope) {
16796
- store.setState((state) => {
16797
- let newBuffers = state.buffers;
16798
- if (scope && scope !== "root") {
16799
- const { [scope]: _, ...rest } = state.buffers;
16800
- newBuffers = rest;
16801
- } else if (scope === "root") {
16802
- newBuffers = {};
16803
- for (const [key, value] of Object.entries(state.buffers)) {
16804
- if (!isBufferLike(value)) newBuffers[key] = value;
16805
- }
16806
- } else {
16807
- newBuffers = {};
16808
- }
16809
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16810
- });
15834
+ rebuildResource(store, "buffers", scope);
16811
15835
  }
16812
15836
 
16813
15837
  const isStorageLike = (value) => {
@@ -16824,60 +15848,17 @@ const disposeStorage = (storage) => {
16824
15848
  }
16825
15849
  };
16826
15850
  function useGPUStorage(creatorOrScope, scope) {
16827
- const store = useStore();
15851
+ const store = usePrimaryStore();
16828
15852
  const removeStorage = useCallback(
16829
- (names, targetScope) => {
16830
- const nameArray = Array.isArray(names) ? names : [names];
16831
- store.setState((state) => {
16832
- if (targetScope) {
16833
- const currentScope = { ...state.gpuStorage[targetScope] };
16834
- for (const name of nameArray) delete currentScope[name];
16835
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
16836
- }
16837
- const gpuStorage2 = { ...state.gpuStorage };
16838
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
16839
- return { gpuStorage: gpuStorage2 };
16840
- });
16841
- },
15853
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
16842
15854
  [store]
16843
15855
  );
16844
15856
  const clearStorage = useCallback(
16845
- (targetScope) => {
16846
- store.setState((state) => {
16847
- if (targetScope && targetScope !== "root") {
16848
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16849
- return { gpuStorage: rest };
16850
- }
16851
- if (targetScope === "root") {
16852
- const gpuStorage2 = {};
16853
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16854
- if (!isStorageLike(value)) gpuStorage2[key] = value;
16855
- }
16856
- return { gpuStorage: gpuStorage2 };
16857
- }
16858
- return { gpuStorage: {} };
16859
- });
16860
- },
15857
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
16861
15858
  [store]
16862
15859
  );
16863
15860
  const rebuildStorage = useCallback(
16864
- (targetScope) => {
16865
- store.setState((state) => {
16866
- let newStorage = state.gpuStorage;
16867
- if (targetScope && targetScope !== "root") {
16868
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16869
- newStorage = rest;
16870
- } else if (targetScope === "root") {
16871
- newStorage = {};
16872
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16873
- if (!isStorageLike(value)) newStorage[key] = value;
16874
- }
16875
- } else {
16876
- newStorage = {};
16877
- }
16878
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16879
- });
16880
- },
15861
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
16881
15862
  [store]
16882
15863
  );
16883
15864
  const disposeStorageFn = useCallback(
@@ -16895,73 +15876,34 @@ function useGPUStorage(creatorOrScope, scope) {
16895
15876
  [store, removeStorage]
16896
15877
  );
16897
15878
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16898
- const storeStorage = useThree((s) => s.gpuStorage);
16899
- const hmrVersion = useThree((s) => s._hmrVersion);
16900
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16901
- const readerDep = isReader ? storeStorage : null;
16902
- const creatorDep = isReader ? null : hmrVersion;
16903
- const gpuStorage = useMemo(() => {
16904
- if (creatorOrScope === void 0) {
16905
- return storeStorage;
16906
- }
16907
- if (typeof creatorOrScope === "string") {
16908
- const scopeData = storeStorage[creatorOrScope];
16909
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
16910
- return {};
16911
- }
16912
- const state = store.getState();
16913
- const set = store.setState;
16914
- const creator = creatorOrScope;
16915
- const wrappedState = createLazyCreatorState(state);
16916
- const created = creator(wrappedState);
16917
- const result = {};
16918
- let hasNewStorage = false;
16919
- if (scope) {
16920
- const currentScope = state.gpuStorage[scope] ?? {};
16921
- for (const [name, storage] of Object.entries(created)) {
16922
- if (currentScope[name]) {
16923
- result[name] = currentScope[name];
16924
- } else {
16925
- if ("setName" in storage && typeof storage.setName === "function") {
16926
- storage.setName(`${scope}.${name}`);
16927
- }
16928
- if ("name" in storage && typeof storage.name === "string") {
16929
- storage.name = `${scope}.${name}`;
16930
- }
16931
- result[name] = storage;
16932
- hasNewStorage = true;
16933
- }
16934
- }
16935
- if (hasNewStorage) {
16936
- set((s) => ({
16937
- gpuStorage: {
16938
- ...s.gpuStorage,
16939
- [scope]: { ...s.gpuStorage[scope], ...result }
16940
- }
16941
- }));
15879
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15880
+ const created = useScopedResource({
15881
+ store,
15882
+ kind: "gpuStorage",
15883
+ scope: isReader ? void 0 : scope,
15884
+ isLeaf: isStorageLike,
15885
+ create: () => {
15886
+ if (isReader) return {};
15887
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15888
+ },
15889
+ prepare: (name, storage) => {
15890
+ const label = scope ? `${scope}.${name}` : name;
15891
+ if ("setName" in storage && typeof storage.setName === "function") {
15892
+ storage.setName(label);
16942
15893
  }
16943
- return result;
16944
- }
16945
- for (const [name, storage] of Object.entries(created)) {
16946
- const existing = state.gpuStorage[name];
16947
- if (existing && isStorageLike(existing)) {
16948
- result[name] = existing;
16949
- } else {
16950
- if ("setName" in storage && typeof storage.setName === "function") {
16951
- storage.setName(name);
16952
- }
16953
- if ("name" in storage && typeof storage.name === "string") {
16954
- storage.name = name;
16955
- }
16956
- result[name] = storage;
16957
- hasNewStorage = true;
15894
+ if ("name" in storage && typeof storage.name === "string") {
15895
+ storage.name = label;
16958
15896
  }
15897
+ return storage;
16959
15898
  }
16960
- if (hasNewStorage) {
16961
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
16962
- }
16963
- return result;
16964
- }, [store, scopeDep, readerDep, creatorDep]);
15899
+ });
15900
+ let gpuStorage = created;
15901
+ if (creatorOrScope === void 0) {
15902
+ gpuStorage = storeStorage;
15903
+ } else if (typeof creatorOrScope === "string") {
15904
+ const scopeData = storeStorage[creatorOrScope];
15905
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15906
+ }
16965
15907
  return {
16966
15908
  ...gpuStorage,
16967
15909
  removeStorage,
@@ -16971,21 +15913,7 @@ function useGPUStorage(creatorOrScope, scope) {
16971
15913
  };
16972
15914
  }
16973
15915
  function rebuildAllStorage(store, scope) {
16974
- store.setState((state) => {
16975
- let newStorage = state.gpuStorage;
16976
- if (scope && scope !== "root") {
16977
- const { [scope]: _, ...rest } = state.gpuStorage;
16978
- newStorage = rest;
16979
- } else if (scope === "root") {
16980
- newStorage = {};
16981
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16982
- if (!isStorageLike(value)) newStorage[key] = value;
16983
- }
16984
- } else {
16985
- newStorage = {};
16986
- }
16987
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16988
- });
15916
+ rebuildResource(store, "gpuStorage", scope);
16989
15917
  }
16990
15918
 
16991
15919
  function useRenderPipeline(mainCB, setupCB) {
@@ -17026,12 +15954,12 @@ function useRenderPipeline(mainCB, setupCB) {
17026
15954
  const state = store.getState();
17027
15955
  const set = store.setState;
17028
15956
  try {
17029
- let pp = state.renderPipeline;
15957
+ let pipeline = state.renderPipeline;
17030
15958
  let currentPasses = { ...state.passes };
17031
- let justCreatedPP = false;
17032
- if (!pp) {
17033
- pp = new PostProcessing(renderer);
17034
- justCreatedPP = true;
15959
+ let justCreatedPipeline = false;
15960
+ if (!pipeline) {
15961
+ pipeline = new RenderPipeline(renderer);
15962
+ justCreatedPipeline = true;
17035
15963
  }
17036
15964
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
17037
15965
  let scenePass;
@@ -17042,9 +15970,9 @@ function useRenderPipeline(mainCB, setupCB) {
17042
15970
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
17043
15971
  }
17044
15972
  currentPasses.scenePass = scenePass;
17045
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
17046
- set({ renderPipeline: pp, passes: currentPasses });
17047
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15973
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15974
+ set({ renderPipeline: pipeline, passes: currentPasses });
15975
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
17048
15976
  if (shouldRunCallbacks) {
17049
15977
  if (setupCBRef.current) {
17050
15978
  const freshState = store.getState();
@@ -17065,7 +15993,7 @@ function useRenderPipeline(mainCB, setupCB) {
17065
15993
  callbacksRanRef.current = true;
17066
15994
  }
17067
15995
  } catch (error) {
17068
- console.error("[useRenderPipeline] Setup error:", error);
15996
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17069
15997
  }
17070
15998
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17071
15999
  const passes = useThree((s) => s.passes);
@@ -17083,4 +16011,4 @@ function useRenderPipeline(mainCB, setupCB) {
17083
16011
 
17084
16012
  extend(THREE);
17085
16013
 
17086
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
16014
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };