@react-three/fiber 10.0.0-canary.d6fdf72 → 10.0.0-canary.e881a4a

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.
@@ -14,6 +14,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
14
14
  const gainmapJs = require('@monogrid/gainmap-js');
15
15
  const Tb = require('scheduler');
16
16
  const traditional = require('zustand/traditional');
17
+ const scheduler = require('@pmndrs/scheduler');
17
18
  const suspendReact = require('suspend-react');
18
19
  const lite = require('dequal/lite');
19
20
  require('zustand/shallow');
@@ -62,13 +63,16 @@ const WebGLRenderer = class WebGLRenderer2 {
62
63
  }
63
64
  };
64
65
  const WebGLRenderTarget = null;
66
+ const WebGLCubeRenderTarget = null;
65
67
 
66
68
  const THREE = /*#__PURE__*/_mergeNamespaces({
67
69
  __proto__: null,
70
+ CubeRenderTargetCompat: webgpu.CubeRenderTarget,
68
71
  Inspector: Inspector_js.Inspector,
69
72
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
70
73
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
71
74
  RenderTargetCompat: webgpu.RenderTarget,
75
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
72
76
  WebGLRenderTarget: WebGLRenderTarget,
73
77
  WebGLRenderer: WebGLRenderer
74
78
  }, [webgpu__namespace]);
@@ -342,15 +346,16 @@ function EnvironmentPortal({
342
346
  preset = void 0,
343
347
  extensions
344
348
  }) {
345
- const gl = fiber.useThree((state) => state.gl);
349
+ const renderer = fiber.useThree((state) => state.renderer);
350
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
346
351
  const defaultScene = fiber.useThree((state) => state.scene);
347
352
  const camera = React__namespace.useRef(null);
348
353
  const [virtualScene] = React__namespace.useState(() => new webgpu.Scene());
349
354
  const fbo = React__namespace.useMemo(() => {
350
- const fbo2 = new webgpu.WebGLCubeRenderTarget(resolution);
355
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new webgpu.CubeRenderTarget(resolution);
351
356
  fbo2.texture.type = webgpu.HalfFloatType;
352
357
  return fbo2;
353
- }, [resolution]);
358
+ }, [resolution, isLegacy]);
354
359
  React__namespace.useEffect(() => {
355
360
  return () => {
356
361
  fbo.dispose();
@@ -358,10 +363,10 @@ function EnvironmentPortal({
358
363
  }, [fbo]);
359
364
  React__namespace.useLayoutEffect(() => {
360
365
  if (frames === 1) {
361
- const autoClear = gl.autoClear;
362
- gl.autoClear = true;
363
- camera.current.update(gl, virtualScene);
364
- gl.autoClear = autoClear;
366
+ const autoClear = renderer.autoClear;
367
+ renderer.autoClear = true;
368
+ camera.current.update(renderer, virtualScene);
369
+ renderer.autoClear = autoClear;
365
370
  }
366
371
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
367
372
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -378,7 +383,7 @@ function EnvironmentPortal({
378
383
  defaultScene,
379
384
  background,
380
385
  frames,
381
- gl,
386
+ renderer,
382
387
  blur,
383
388
  backgroundBlurriness,
384
389
  backgroundIntensity,
@@ -389,10 +394,10 @@ function EnvironmentPortal({
389
394
  let count = 1;
390
395
  fiber.useFrame(() => {
391
396
  if (frames === Infinity || count < frames) {
392
- const autoClear = gl.autoClear;
393
- gl.autoClear = true;
394
- camera.current.update(gl, virtualScene);
395
- gl.autoClear = autoClear;
397
+ const autoClear = renderer.autoClear;
398
+ renderer.autoClear = true;
399
+ camera.current.update(renderer, virtualScene);
400
+ renderer.autoClear = autoClear;
396
401
  count++;
397
402
  }
398
403
  });
@@ -456,9 +461,9 @@ function Environment(props) {
456
461
  return props.ground ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props });
457
462
  }
458
463
 
459
- var __defProp$3 = Object.defineProperty;
460
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
461
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
464
+ var __defProp$1 = Object.defineProperty;
465
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
466
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
462
467
  const act = React__namespace["act"];
463
468
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
464
469
  function useMutableCallback(fn) {
@@ -490,7 +495,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
490
495
  return _a = class extends React__namespace.Component {
491
496
  constructor() {
492
497
  super(...arguments);
493
- __publicField$3(this, "state", { error: false });
498
+ __publicField$1(this, "state", { error: false });
494
499
  }
495
500
  componentDidCatch(err) {
496
501
  this.props.set(err);
@@ -498,7 +503,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
498
503
  render() {
499
504
  return this.state.error ? null : this.props.children;
500
505
  }
501
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
506
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
502
507
  })();
503
508
 
504
509
  const is = {
@@ -635,8 +640,7 @@ function prepare(target, root, type, props) {
635
640
  object,
636
641
  eventCount: 0,
637
642
  handlers: {},
638
- isHidden: false,
639
- deferredRefs: []
643
+ isHidden: false
640
644
  };
641
645
  if (object) object.__r3f = instance;
642
646
  }
@@ -793,6 +797,17 @@ function unregisterVisibility(store, object) {
793
797
  internal.visibilityRegistry.delete(object.uuid);
794
798
  internal.occlusionCache.delete(object);
795
799
  }
800
+ function updateVisibilityHandlers(store, object, handlers) {
801
+ const { internal } = store.getState();
802
+ const entry = internal.visibilityRegistry.get(object.uuid);
803
+ if (!entry) return false;
804
+ entry.handlers = handlers;
805
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
806
+ object.occlusionTest = true;
807
+ enableOcclusion(store);
808
+ }
809
+ return true;
810
+ }
796
811
  function checkVisibility(state) {
797
812
  const { internal, camera } = state;
798
813
  const registry = internal.visibilityRegistry;
@@ -980,10 +995,7 @@ function applyProps(object, props) {
980
995
  continue;
981
996
  }
982
997
  if (value === void 0) continue;
983
- if (isFromRef(value)) {
984
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
985
- continue;
986
- }
998
+ if (isFromRef(value)) continue;
987
999
  if (isOnce(value)) {
988
1000
  if (instance?.appliedOnce?.has(prop)) continue;
989
1001
  if (instance) {
@@ -1019,6 +1031,19 @@ function applyProps(object, props) {
1019
1031
  } else if (isVectorLike(target) && is.num(value)) {
1020
1032
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1021
1033
  else target.set(value);
1034
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1035
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1036
+ const uniforms = root.uniforms;
1037
+ const nextUniforms = value;
1038
+ for (const name in nextUniforms) {
1039
+ const uniform = nextUniforms[name];
1040
+ const targetUniform = uniforms[name];
1041
+ if (targetUniform) Object.assign(targetUniform, uniform);
1042
+ else {
1043
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1044
+ uniforms[name] = nextUniform;
1045
+ }
1046
+ }
1022
1047
  } else {
1023
1048
  root[key] = value;
1024
1049
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1037,6 +1062,9 @@ function applyProps(object, props) {
1037
1062
  if (instance.eventCount && object2.raycast !== null) {
1038
1063
  rootState.internal.interaction.push(object2);
1039
1064
  }
1065
+ }
1066
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1067
+ const object2 = instance.object;
1040
1068
  const root = findInitialRoot(instance);
1041
1069
  const visibilityHandlers = {
1042
1070
  onFramed: instance.handlers.onFramed,
@@ -1044,7 +1072,9 @@ function applyProps(object, props) {
1044
1072
  onVisible: instance.handlers.onVisible
1045
1073
  };
1046
1074
  if (hasVisibilityHandlers(visibilityHandlers)) {
1047
- registerVisibility(root, object2, visibilityHandlers);
1075
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1076
+ registerVisibility(root, object2, visibilityHandlers);
1077
+ }
1048
1078
  } else {
1049
1079
  unregisterVisibility(root, object2);
1050
1080
  }
@@ -1572,6 +1602,7 @@ function createPointerEvents(store) {
1572
1602
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1573
1603
  }
1574
1604
  },
1605
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1575
1606
  registerPointer: (config) => {
1576
1607
  const pointerId = nextXRPointerId++;
1577
1608
  xrPointers.set(pointerId, config);
@@ -1658,1230 +1689,206 @@ function notifyAlpha({ message, link }) {
1658
1689
  }
1659
1690
  }
1660
1691
 
1661
- var __defProp$2 = Object.defineProperty;
1662
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1663
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1664
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1665
- class PhaseGraph {
1666
- constructor() {
1667
- /** Ordered list of phase nodes */
1668
- __publicField$2(this, "phases", []);
1669
- /** Quick lookup by name */
1670
- __publicField$2(this, "phaseMap", /* @__PURE__ */ new Map());
1671
- /** Cached ordered names (invalidated on changes) */
1672
- __publicField$2(this, "orderedNamesCache", null);
1673
- this.initializeDefaultPhases();
1674
- }
1675
- //* Initialization --------------------------------
1676
- initializeDefaultPhases() {
1677
- for (const name of DEFAULT_PHASES) {
1678
- const node = { name, isAutoGenerated: false };
1679
- this.phases.push(node);
1680
- this.phaseMap.set(name, node);
1681
- }
1682
- this.invalidateCache();
1683
- }
1684
- //* Public API --------------------------------
1685
- /**
1686
- * Add a named phase to the graph
1687
- * @param name - Phase name (must be unique)
1688
- * @param options - Position options (before or after another phase)
1689
- */
1690
- addPhase(name, options = {}) {
1691
- if (this.phaseMap.has(name)) {
1692
- console.warn(`[useFrame] Phase "${name}" already exists`);
1693
- return;
1694
- }
1695
- const { before, after } = options;
1696
- const node = { name, isAutoGenerated: false };
1697
- let insertIndex = this.phases.length;
1698
- const targetIndex = this.getPhaseIndex(before ?? after);
1699
- if (targetIndex !== -1) {
1700
- insertIndex = before ? targetIndex : targetIndex + 1;
1701
- } else {
1702
- const constraintType = before ? "before" : "after";
1703
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1704
- }
1705
- this.phases.splice(insertIndex, 0, node);
1706
- this.phaseMap.set(name, node);
1707
- this.invalidateCache();
1708
- }
1709
- /**
1710
- * Get ordered list of phase names
1711
- */
1712
- getOrderedPhases() {
1713
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1714
- return this.orderedNamesCache;
1715
- }
1716
- /**
1717
- * Check if a phase exists
1718
- */
1719
- hasPhase(name) {
1720
- return this.phaseMap.has(name);
1721
- }
1722
- /**
1723
- * Get the index of a phase (-1 if not found)
1724
- */
1725
- getPhaseIndex(name) {
1726
- if (!name) return -1;
1727
- return this.phases.findIndex((p) => p.name === name);
1728
- }
1729
- /**
1730
- * Ensure a phase exists, creating an auto-generated one if needed.
1731
- * Used for resolving before/after constraints.
1732
- *
1733
- * @param name - The phase name to ensure exists
1734
- * @returns The phase name (may be auto-generated like 'before:render')
1735
- */
1736
- ensurePhase(name) {
1737
- if (this.phaseMap.has(name)) return name;
1738
- const node = { name, isAutoGenerated: true };
1739
- this.phases.push(node);
1740
- this.phaseMap.set(name, node);
1741
- this.invalidateCache();
1742
- return name;
1743
- }
1744
- /**
1745
- * Resolve where a job with before/after constraints should go.
1746
- * Creates auto-generated phases if needed.
1747
- *
1748
- * @param before - Phase(s) to run before
1749
- * @param after - Phase(s) to run after
1750
- * @returns The resolved phase name
1751
- */
1752
- resolveConstraintPhase(before, after) {
1753
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1754
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1755
- if (beforeArr.length > 0) {
1756
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1757
- }
1758
- if (afterArr.length > 0) {
1759
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1760
- }
1761
- return "update";
1762
- }
1763
- /**
1764
- * Ensure an auto-generated phase exists relative to a target phase.
1765
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1766
- *
1767
- * @param target - The target phase name to position relative to
1768
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1769
- * @param offset - Insertion offset (0 for before, 1 for after)
1770
- * @returns The auto-generated phase name
1771
- */
1772
- ensureAutoPhase(target, prefix, offset) {
1773
- const autoName = `${prefix}:${target}`;
1774
- if (this.phaseMap.has(autoName)) return autoName;
1775
- const node = { name: autoName, isAutoGenerated: true };
1776
- const targetIndex = this.getPhaseIndex(target);
1777
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1778
- else this.phases.push(node);
1779
- this.phaseMap.set(autoName, node);
1780
- this.invalidateCache();
1781
- return autoName;
1782
- }
1783
- // Internal --------------------------------
1784
- invalidateCache() {
1785
- this.orderedNamesCache = null;
1786
- }
1692
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1693
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1694
+ if (!stack) return false;
1695
+ const caller = stack.split("\n")[callerDepth] ?? "";
1696
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1787
1697
  }
1788
1698
 
1789
- function rebuildSortedJobs(jobs, phaseGraph) {
1790
- const orderedPhases = phaseGraph.getOrderedPhases();
1791
- const buckets = /* @__PURE__ */ new Map();
1792
- for (const phase of orderedPhases) {
1793
- buckets.set(phase, []);
1794
- }
1795
- for (const job of jobs.values()) {
1796
- if (!job.enabled) continue;
1797
- let bucket = buckets.get(job.phase);
1798
- if (!bucket) {
1799
- bucket = [];
1800
- buckets.set(job.phase, bucket);
1801
- }
1802
- bucket.push(job);
1803
- }
1804
- const sortedBuckets = [];
1805
- for (const phase of orderedPhases) {
1806
- const bucket = buckets.get(phase);
1807
- if (!bucket || bucket.length === 0) continue;
1808
- bucket.sort((a, b) => {
1809
- if (a.priority !== b.priority) return b.priority - a.priority;
1810
- return a.index - b.index;
1811
- });
1812
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1813
- }
1814
- for (const [phase, bucket] of buckets) {
1815
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1816
- bucket.sort((a, b) => {
1817
- if (a.priority !== b.priority) return b.priority - a.priority;
1818
- return a.index - b.index;
1819
- });
1820
- sortedBuckets.push(bucket);
1821
- }
1822
- }
1823
- return sortedBuckets.flat();
1824
- }
1825
- function hasCrossJobConstraints(bucket) {
1826
- const jobIds = new Set(bucket.map((j) => j.id));
1827
- for (const job of bucket) {
1828
- for (const ref of job.before) {
1829
- if (jobIds.has(ref)) return true;
1830
- }
1831
- for (const ref of job.after) {
1832
- if (jobIds.has(ref)) return true;
1833
- }
1834
- }
1835
- return false;
1836
- }
1837
- function topologicalSort(jobs) {
1838
- const n = jobs.length;
1839
- if (n <= 1) return jobs;
1840
- const jobMap = /* @__PURE__ */ new Map();
1841
- const inDegree = /* @__PURE__ */ new Map();
1842
- const adjacency = /* @__PURE__ */ new Map();
1843
- for (const job of jobs) {
1844
- jobMap.set(job.id, job);
1845
- inDegree.set(job.id, 0);
1846
- adjacency.set(job.id, []);
1847
- }
1848
- for (const job of jobs) {
1849
- for (const ref of job.before) {
1850
- if (jobMap.has(ref)) {
1851
- adjacency.get(job.id).push(ref);
1852
- inDegree.set(ref, inDegree.get(ref) + 1);
1699
+ const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1700
+ const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
1701
+ const createStore = (invalidate, advance) => {
1702
+ const rootStore = traditional.createWithEqualityFn((set, get) => {
1703
+ const position = new webgpu.Vector3();
1704
+ const defaultTarget = new webgpu.Vector3();
1705
+ const tempTarget = new webgpu.Vector3();
1706
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1707
+ const { width, height, top, left } = size;
1708
+ const aspect = width / height;
1709
+ if (target.isVector3) tempTarget.copy(target);
1710
+ else tempTarget.set(...target);
1711
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1712
+ if (isOrthographicCamera(camera)) {
1713
+ return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
1714
+ } else {
1715
+ const fov = camera.fov * Math.PI / 180;
1716
+ const h = 2 * Math.tan(fov / 2) * distance;
1717
+ const w = h * (width / height);
1718
+ return { width: w, height: h, top, left, factor: width / w, distance, aspect };
1853
1719
  }
1854
1720
  }
1855
- for (const ref of job.after) {
1856
- if (jobMap.has(ref)) {
1857
- adjacency.get(ref).push(job.id);
1858
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1721
+ let performanceTimeout = void 0;
1722
+ const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
1723
+ const pointer = new webgpu.Vector2();
1724
+ const rootState = {
1725
+ set,
1726
+ get,
1727
+ // Mock objects that have to be configured
1728
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1729
+ primaryStore: null,
1730
+ gl: null,
1731
+ renderer: null,
1732
+ camera: null,
1733
+ frustum: new webgpu.Frustum(),
1734
+ autoUpdateFrustum: true,
1735
+ raycaster: null,
1736
+ events: {
1737
+ priority: 1,
1738
+ enabled: true,
1739
+ connected: false,
1740
+ frameTimedRaycasts: true,
1741
+ alwaysFireOnScroll: true,
1742
+ updateOnFrame: false
1743
+ },
1744
+ scene: null,
1745
+ rootScene: null,
1746
+ xr: null,
1747
+ inspector: null,
1748
+ invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1749
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1750
+ textureColorSpace: webgpu.SRGBColorSpace,
1751
+ isLegacy: false,
1752
+ webGPUSupported: false,
1753
+ isNative: false,
1754
+ controls: null,
1755
+ pointer,
1756
+ mouse: pointer,
1757
+ frameloop: "always",
1758
+ onPointerMissed: void 0,
1759
+ onDragOverMissed: void 0,
1760
+ onDropMissed: void 0,
1761
+ performance: {
1762
+ current: 1,
1763
+ min: 0.5,
1764
+ max: 1,
1765
+ debounce: 200,
1766
+ regress: () => {
1767
+ const state2 = get();
1768
+ if (performanceTimeout) clearTimeout(performanceTimeout);
1769
+ if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
1770
+ performanceTimeout = setTimeout(
1771
+ () => setPerformanceCurrent(get().performance.max),
1772
+ state2.performance.debounce
1773
+ );
1774
+ }
1775
+ },
1776
+ size: { width: 0, height: 0, top: 0, left: 0 },
1777
+ viewport: {
1778
+ initialDpr: 0,
1779
+ dpr: 0,
1780
+ width: 0,
1781
+ height: 0,
1782
+ top: 0,
1783
+ left: 0,
1784
+ aspect: 0,
1785
+ distance: 0,
1786
+ factor: 0,
1787
+ getCurrentViewport
1788
+ },
1789
+ setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1790
+ setSize: (width, height, top, left) => {
1791
+ const state2 = get();
1792
+ if (width === void 0) {
1793
+ set({ _sizeImperative: false });
1794
+ if (state2._sizeProps) {
1795
+ const { width: propW, height: propH } = state2._sizeProps;
1796
+ if (propW !== void 0 || propH !== void 0) {
1797
+ const currentSize = state2.size;
1798
+ const newSize = {
1799
+ width: propW ?? currentSize.width,
1800
+ height: propH ?? currentSize.height,
1801
+ top: currentSize.top,
1802
+ left: currentSize.left
1803
+ };
1804
+ set((s) => ({
1805
+ size: newSize,
1806
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1807
+ }));
1808
+ scheduler.getScheduler().invalidate();
1809
+ }
1810
+ }
1811
+ return;
1812
+ }
1813
+ const w = width;
1814
+ const h = height ?? width;
1815
+ const t = top ?? state2.size.top;
1816
+ const l = left ?? state2.size.left;
1817
+ const size = { width: w, height: h, top: t, left: l };
1818
+ set((s) => ({
1819
+ size,
1820
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1821
+ _sizeImperative: true
1822
+ }));
1823
+ scheduler.getScheduler().invalidate();
1824
+ },
1825
+ setDpr: (dpr) => set((state2) => {
1826
+ const resolved = calculateDpr(dpr);
1827
+ return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
1828
+ }),
1829
+ setFrameloop: (frameloop = "always") => {
1830
+ set(() => ({ frameloop }));
1831
+ scheduler.getScheduler().frameloop = frameloop;
1832
+ },
1833
+ setError: (error) => set(() => ({ error })),
1834
+ error: null,
1835
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1836
+ uniforms: {},
1837
+ nodes: {},
1838
+ buffers: {},
1839
+ gpuStorage: {},
1840
+ textures: /* @__PURE__ */ new Map(),
1841
+ _textureRefs: /* @__PURE__ */ new Map(),
1842
+ renderPipeline: null,
1843
+ passes: {},
1844
+ _hmrVersion: 0,
1845
+ _sizeImperative: false,
1846
+ _sizeProps: null,
1847
+ previousRoot: void 0,
1848
+ internal: {
1849
+ // Events
1850
+ interaction: [],
1851
+ subscribers: [],
1852
+ // Per-pointer state (new unified structure)
1853
+ pointerMap: /* @__PURE__ */ new Map(),
1854
+ pointerDirty: /* @__PURE__ */ new Map(),
1855
+ lastEvent: React__namespace.createRef(),
1856
+ // Deprecated but kept for backwards compatibility
1857
+ hovered: /* @__PURE__ */ new Map(),
1858
+ initialClick: [0, 0],
1859
+ initialHits: [],
1860
+ capturedMap: /* @__PURE__ */ new Map(),
1861
+ // Visibility tracking (onFramed, onOccluded, onVisible)
1862
+ visibilityRegistry: /* @__PURE__ */ new Map(),
1863
+ // Occlusion system (WebGPU only)
1864
+ occlusionEnabled: false,
1865
+ occlusionObserver: null,
1866
+ occlusionCache: /* @__PURE__ */ new Map(),
1867
+ helperGroup: null,
1868
+ // Updates
1869
+ active: false,
1870
+ frames: 0,
1871
+ priority: 0,
1872
+ subscribe: (ref, priority, store) => {
1873
+ const internal = get().internal;
1874
+ internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1875
+ internal.subscribers.push({ ref, priority, store });
1876
+ internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1877
+ return () => {
1878
+ const internal2 = get().internal;
1879
+ if (internal2?.subscribers) {
1880
+ internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
1881
+ internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
1882
+ }
1883
+ };
1884
+ },
1885
+ // Renderer Storage (single source of truth)
1886
+ actualRenderer: null,
1887
+ // Scheduler for useFrameNext (initialized in renderer.tsx)
1888
+ scheduler: null
1859
1889
  }
1860
- }
1861
- }
1862
- const queue = [];
1863
- for (const job of jobs) {
1864
- if (inDegree.get(job.id) === 0) {
1865
- queue.push(job);
1866
- }
1867
- }
1868
- queue.sort((a, b) => {
1869
- if (a.priority !== b.priority) return b.priority - a.priority;
1870
- return a.index - b.index;
1871
- });
1872
- const result = [];
1873
- while (queue.length > 0) {
1874
- const job = queue.shift();
1875
- result.push(job);
1876
- const neighbors = adjacency.get(job.id) || [];
1877
- for (const neighborId of neighbors) {
1878
- const newDegree = inDegree.get(neighborId) - 1;
1879
- inDegree.set(neighborId, newDegree);
1880
- if (newDegree === 0) {
1881
- const neighbor = jobMap.get(neighborId);
1882
- insertSorted(queue, neighbor);
1883
- }
1884
- }
1885
- }
1886
- if (result.length !== n) {
1887
- console.warn("[useFrame] Circular dependency detected in job constraints");
1888
- const resultIds = new Set(result.map((j) => j.id));
1889
- for (const job of jobs) {
1890
- if (!resultIds.has(job.id)) result.push(job);
1891
- }
1892
- }
1893
- return result;
1894
- }
1895
- function insertSorted(arr, job) {
1896
- let i = 0;
1897
- while (i < arr.length) {
1898
- const cmp = arr[i];
1899
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1900
- break;
1901
- }
1902
- i++;
1903
- }
1904
- arr.splice(i, 0, job);
1905
- }
1906
-
1907
- function shouldRun(job, now) {
1908
- if (!job.enabled) return false;
1909
- if (!job.fps) return true;
1910
- const minInterval = 1e3 / job.fps;
1911
- const lastRun = job.lastRun ?? 0;
1912
- const elapsed = now - lastRun;
1913
- if (elapsed < minInterval - 1) return false;
1914
- if (job.drop) {
1915
- job.lastRun = now;
1916
- } else {
1917
- const steps = Math.floor(elapsed / minInterval);
1918
- job.lastRun = lastRun + steps * minInterval;
1919
- if (job.lastRun < now - minInterval) {
1920
- job.lastRun = now;
1921
- }
1922
- }
1923
- return true;
1924
- }
1925
- function resetJobTiming(job) {
1926
- job.lastRun = void 0;
1927
- }
1928
-
1929
- var __defProp$1 = Object.defineProperty;
1930
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1931
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1932
- const hmrData = (() => {
1933
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1934
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1935
- try {
1936
- return (0, eval)("import.meta.hot");
1937
- } catch {
1938
- return void 0;
1939
- }
1940
- })();
1941
- const _Scheduler = class _Scheduler {
1942
- //* Constructor ================================
1943
- constructor() {
1944
- //* Critical State ================================
1945
- __publicField$1(this, "roots", /* @__PURE__ */ new Map());
1946
- __publicField$1(this, "phaseGraph");
1947
- __publicField$1(this, "loopState", {
1948
- running: false,
1949
- rafHandle: null,
1950
- lastTime: null,
1951
- // null = uninitialized, 0+ = valid timestamp
1952
- frameCount: 0,
1953
- elapsedTime: 0,
1954
- createdAt: performance.now()
1955
- });
1956
- __publicField$1(this, "stoppedTime", 0);
1957
- //* Private State ================================
1958
- __publicField$1(this, "nextRootIndex", 0);
1959
- __publicField$1(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1960
- __publicField$1(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1961
- __publicField$1(this, "nextGlobalIndex", 0);
1962
- __publicField$1(this, "idleCallbacks", /* @__PURE__ */ new Set());
1963
- __publicField$1(this, "nextJobIndex", 0);
1964
- __publicField$1(this, "jobStateListeners", /* @__PURE__ */ new Map());
1965
- __publicField$1(this, "pendingFrames", 0);
1966
- __publicField$1(this, "_frameloop", "always");
1967
- //* Independent Mode & Error Handling State ================================
1968
- __publicField$1(this, "_independent", false);
1969
- __publicField$1(this, "errorHandler", null);
1970
- __publicField$1(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1971
- //* Core Loop Execution Methods ================================
1972
- /**
1973
- * Main RAF loop callback.
1974
- * Executes frame, handles demand mode, and schedules next frame.
1975
- * @param {number} timestamp - RAF timestamp in milliseconds
1976
- * @returns {void}
1977
- * @private
1978
- */
1979
- __publicField$1(this, "loop", (timestamp) => {
1980
- if (!this.loopState.running) return;
1981
- this.executeFrame(timestamp);
1982
- if (this._frameloop === "demand") {
1983
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1984
- if (this.pendingFrames === 0) {
1985
- this.notifyIdle(timestamp);
1986
- return this.stop();
1987
- }
1988
- }
1989
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1990
- });
1991
- this.phaseGraph = new PhaseGraph();
1992
- }
1993
- static get instance() {
1994
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1995
- }
1996
- static set instance(value) {
1997
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1998
- }
1999
- /**
2000
- * Get the global scheduler instance (creates if doesn't exist).
2001
- * Uses HMR data to preserve instance across hot reloads.
2002
- * @returns {Scheduler} The singleton scheduler instance
2003
- */
2004
- static get() {
2005
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
2006
- _Scheduler.instance = hmrData.data.scheduler;
2007
- }
2008
- if (!_Scheduler.instance) {
2009
- _Scheduler.instance = new _Scheduler();
2010
- if (hmrData?.data) {
2011
- hmrData.data.scheduler = _Scheduler.instance;
2012
- }
2013
- }
2014
- return _Scheduler.instance;
2015
- }
2016
- /**
2017
- * Reset the singleton instance. Stops the loop and clears all state.
2018
- * Primarily used for testing to ensure clean state between tests.
2019
- * @returns {void}
2020
- */
2021
- static reset() {
2022
- if (_Scheduler.instance) {
2023
- _Scheduler.instance.stop();
2024
- _Scheduler.instance = null;
2025
- }
2026
- if (hmrData?.data) {
2027
- hmrData.data.scheduler = null;
2028
- }
2029
- }
2030
- //* Getters & Setters ================================
2031
- get phases() {
2032
- return this.phaseGraph.getOrderedPhases();
2033
- }
2034
- get frameloop() {
2035
- return this._frameloop;
2036
- }
2037
- set frameloop(mode) {
2038
- if (this._frameloop === mode) return;
2039
- const wasAlways = this._frameloop === "always";
2040
- this._frameloop = mode;
2041
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2042
- else if (mode !== "always" && wasAlways) this.stop();
2043
- }
2044
- get isRunning() {
2045
- return this.loopState.running;
2046
- }
2047
- get isReady() {
2048
- return this.roots.size > 0;
2049
- }
2050
- get independent() {
2051
- return this._independent;
2052
- }
2053
- set independent(value) {
2054
- this._independent = value;
2055
- if (value) this.ensureDefaultRoot();
2056
- }
2057
- //* Root Management Methods ================================
2058
- /**
2059
- * Register a root (Canvas) with the scheduler.
2060
- * The first root to register starts the RAF loop (if frameloop='always').
2061
- * @param {string} id - Unique identifier for this root
2062
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2063
- * @returns {() => void} Unsubscribe function to remove this root
2064
- */
2065
- registerRoot(id, options = {}) {
2066
- if (this.roots.has(id)) {
2067
- console.warn(`[Scheduler] Root "${id}" already registered`);
2068
- return () => this.unregisterRoot(id);
2069
- }
2070
- const entry = {
2071
- id,
2072
- getState: options.getState ?? (() => ({})),
2073
- jobs: /* @__PURE__ */ new Map(),
2074
- sortedJobs: [],
2075
- needsRebuild: false
2076
- };
2077
- if (options.onError) {
2078
- this.errorHandler = options.onError;
2079
- }
2080
- this.roots.set(id, entry);
2081
- if (this.roots.size === 1) {
2082
- this.notifyRootReady();
2083
- if (this._frameloop === "always") this.start();
2084
- }
2085
- return () => this.unregisterRoot(id);
2086
- }
2087
- /**
2088
- * Unregister a root from the scheduler.
2089
- * Cleans up all job state listeners for this root's jobs.
2090
- * The last root to unregister stops the RAF loop.
2091
- * @param {string} id - The root ID to unregister
2092
- * @returns {void}
2093
- */
2094
- unregisterRoot(id) {
2095
- const root = this.roots.get(id);
2096
- if (!root) return;
2097
- for (const jobId of root.jobs.keys()) {
2098
- this.jobStateListeners.delete(jobId);
2099
- }
2100
- this.roots.delete(id);
2101
- if (this.roots.size === 0) {
2102
- this.stop();
2103
- this.errorHandler = null;
2104
- }
2105
- }
2106
- /**
2107
- * Subscribe to be notified when a root becomes available.
2108
- * Fires immediately if a root already exists.
2109
- * @param {() => void} callback - Function called when first root registers
2110
- * @returns {() => void} Unsubscribe function
2111
- */
2112
- onRootReady(callback) {
2113
- if (this.roots.size > 0) {
2114
- callback();
2115
- return () => {
2116
- };
2117
- }
2118
- this.rootReadyCallbacks.add(callback);
2119
- return () => this.rootReadyCallbacks.delete(callback);
2120
- }
2121
- /**
2122
- * Notify all registered root-ready callbacks.
2123
- * Called when the first root registers.
2124
- * @returns {void}
2125
- * @private
2126
- */
2127
- notifyRootReady() {
2128
- for (const cb of this.rootReadyCallbacks) {
2129
- try {
2130
- cb();
2131
- } catch (error) {
2132
- console.error("[Scheduler] Error in root-ready callback:", error);
2133
- }
2134
- }
2135
- this.rootReadyCallbacks.clear();
2136
- }
2137
- /**
2138
- * Ensure a default root exists for independent mode.
2139
- * Creates a minimal root with no state provider.
2140
- * @returns {void}
2141
- * @private
2142
- */
2143
- ensureDefaultRoot() {
2144
- if (!this.roots.has("__default__")) {
2145
- this.registerRoot("__default__");
2146
- }
2147
- }
2148
- /**
2149
- * Trigger error handling for job errors.
2150
- * Uses the bound error handler if available, otherwise logs to console.
2151
- * @param {Error} error - The error to handle
2152
- * @returns {void}
2153
- */
2154
- triggerError(error) {
2155
- if (this.errorHandler) this.errorHandler(error);
2156
- else console.error("[Scheduler]", error);
2157
- }
2158
- //* Phase Management Methods ================================
2159
- /**
2160
- * Add a named phase to the scheduler's execution order.
2161
- * Marks all roots for rebuild to incorporate the new phase.
2162
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2163
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2164
- * @returns {void}
2165
- * @example
2166
- * scheduler.addPhase('physics', { before: 'update' });
2167
- * scheduler.addPhase('postprocess', { after: 'render' });
2168
- */
2169
- addPhase(name, options) {
2170
- this.phaseGraph.addPhase(name, options);
2171
- for (const root of this.roots.values()) {
2172
- root.needsRebuild = true;
2173
- }
2174
- }
2175
- /**
2176
- * Check if a phase exists in the scheduler.
2177
- * @param {string} name - The phase name to check
2178
- * @returns {boolean} True if the phase exists
2179
- */
2180
- hasPhase(name) {
2181
- return this.phaseGraph.hasPhase(name);
2182
- }
2183
- //* Global Job Registration Methods (Deprecated APIs) ================================
2184
- /**
2185
- * Register a global job that runs once per frame (not per-root).
2186
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2187
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2188
- * @param {string} id - Unique identifier for this global job
2189
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2190
- * @returns {() => void} Unsubscribe function to remove this global job
2191
- * @deprecated Use useFrame with phases instead
2192
- */
2193
- registerGlobal(phase, id, callback) {
2194
- const job = { id, callback };
2195
- if (phase === "before") {
2196
- this.globalBeforeJobs.set(id, job);
2197
- } else {
2198
- this.globalAfterJobs.set(id, job);
2199
- }
2200
- return () => {
2201
- if (phase === "before") this.globalBeforeJobs.delete(id);
2202
- else this.globalAfterJobs.delete(id);
2203
- };
2204
- }
2205
- //* Idle Callback Methods (Deprecated API) ================================
2206
- /**
2207
- * Register an idle callback that fires when the loop stops.
2208
- * Used internally by deprecated addTail API.
2209
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2210
- * @returns {() => void} Unsubscribe function to remove this idle callback
2211
- * @deprecated Use demand mode with invalidate() instead
2212
- */
2213
- onIdle(callback) {
2214
- this.idleCallbacks.add(callback);
2215
- return () => this.idleCallbacks.delete(callback);
2216
- }
2217
- /**
2218
- * Notify all registered idle callbacks.
2219
- * Called when the loop stops in demand mode.
2220
- * @param {number} timestamp - The RAF timestamp when idle occurred
2221
- * @returns {void}
2222
- * @private
2223
- */
2224
- notifyIdle(timestamp) {
2225
- for (const cb of this.idleCallbacks) {
2226
- try {
2227
- cb(timestamp);
2228
- } catch (error) {
2229
- console.error("[Scheduler] Error in idle callback:", error);
2230
- }
2231
- }
2232
- }
2233
- //* Job Registration & Management Methods ================================
2234
- /**
2235
- * Register a job (frame callback) with a specific root.
2236
- * This is the core registration method used by useFrame internally.
2237
- * @param {FrameNextCallback} callback - The function to call each frame
2238
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2239
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2240
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2241
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2242
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2243
- * @param {number} [options.fps] - FPS throttle limit
2244
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2245
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2246
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2247
- * @returns {() => void} Unsubscribe function to remove this job
2248
- */
2249
- register(callback, options = {}) {
2250
- const rootId = options.rootId;
2251
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2252
- if (!root) {
2253
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2254
- return () => {
2255
- };
2256
- }
2257
- const id = options.id ?? this.generateJobId();
2258
- let phase = options.phase ?? "update";
2259
- if (!options.phase && (options.before || options.after)) {
2260
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2261
- }
2262
- const before = this.normalizeConstraints(options.before);
2263
- const after = this.normalizeConstraints(options.after);
2264
- const job = {
2265
- id,
2266
- callback,
2267
- phase,
2268
- before,
2269
- after,
2270
- priority: options.priority ?? 0,
2271
- index: this.nextJobIndex++,
2272
- fps: options.fps,
2273
- drop: options.drop ?? true,
2274
- enabled: options.enabled ?? true,
2275
- system: options.system ?? false
2276
- };
2277
- if (root.jobs.has(id)) {
2278
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2279
- }
2280
- root.jobs.set(id, job);
2281
- root.needsRebuild = true;
2282
- return () => this.unregister(id, root.id);
2283
- }
2284
- /**
2285
- * Unregister a job by its ID.
2286
- * Searches all roots if rootId is not provided.
2287
- * @param {string} id - The job ID to unregister
2288
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2289
- * @returns {void}
2290
- */
2291
- unregister(id, rootId) {
2292
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2293
- if (root?.jobs.delete(id)) {
2294
- root.needsRebuild = true;
2295
- this.jobStateListeners.delete(id);
2296
- }
2297
- }
2298
- /**
2299
- * Update a job's options dynamically.
2300
- * Searches all roots to find the job by ID.
2301
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2302
- * @param {string} id - The job ID to update
2303
- * @param {Partial<JobOptions>} options - The options to update
2304
- * @returns {void}
2305
- */
2306
- updateJob(id, options) {
2307
- let job;
2308
- let root;
2309
- for (const r of this.roots.values()) {
2310
- job = r.jobs.get(id);
2311
- if (job) {
2312
- root = r;
2313
- break;
2314
- }
2315
- }
2316
- if (!job || !root) return;
2317
- if (options.priority !== void 0) job.priority = options.priority;
2318
- if (options.fps !== void 0) job.fps = options.fps;
2319
- if (options.drop !== void 0) job.drop = options.drop;
2320
- if (options.enabled !== void 0) {
2321
- const wasEnabled = job.enabled;
2322
- job.enabled = options.enabled;
2323
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2324
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2325
- }
2326
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2327
- if (options.phase) job.phase = options.phase;
2328
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2329
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2330
- root.needsRebuild = true;
2331
- }
2332
- }
2333
- //* Job State Management Methods ================================
2334
- /**
2335
- * Check if a job is currently paused (disabled).
2336
- * @param {string} id - The job ID to check
2337
- * @returns {boolean} True if the job exists and is paused
2338
- */
2339
- isJobPaused(id) {
2340
- for (const root of this.roots.values()) {
2341
- const job = root.jobs.get(id);
2342
- if (job) return !job.enabled;
2343
- }
2344
- return false;
2345
- }
2346
- /**
2347
- * Subscribe to state changes for a specific job.
2348
- * Listener is called when job is paused or resumed.
2349
- * @param {string} id - The job ID to subscribe to
2350
- * @param {() => void} listener - Callback invoked on state changes
2351
- * @returns {() => void} Unsubscribe function
2352
- */
2353
- subscribeJobState(id, listener) {
2354
- if (!this.jobStateListeners.has(id)) {
2355
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2356
- }
2357
- this.jobStateListeners.get(id).add(listener);
2358
- return () => {
2359
- this.jobStateListeners.get(id)?.delete(listener);
2360
- if (this.jobStateListeners.get(id)?.size === 0) {
2361
- this.jobStateListeners.delete(id);
2362
- }
2363
- };
2364
- }
2365
- /**
2366
- * Notify all listeners that a job's state has changed.
2367
- * @param {string} id - The job ID that changed
2368
- * @returns {void}
2369
- * @private
2370
- */
2371
- notifyJobStateChange(id) {
2372
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2373
- }
2374
- /**
2375
- * Pause a job by ID (sets enabled=false).
2376
- * Notifies any subscribed state listeners.
2377
- * @param {string} id - The job ID to pause
2378
- * @returns {void}
2379
- */
2380
- pauseJob(id) {
2381
- this.updateJob(id, { enabled: false });
2382
- this.notifyJobStateChange(id);
2383
- }
2384
- /**
2385
- * Resume a paused job by ID (sets enabled=true).
2386
- * Resets job timing to prevent frame accumulation.
2387
- * Notifies any subscribed state listeners.
2388
- * @param {string} id - The job ID to resume
2389
- * @returns {void}
2390
- */
2391
- resumeJob(id) {
2392
- this.updateJob(id, { enabled: true });
2393
- this.notifyJobStateChange(id);
2394
- }
2395
- //* Frame Loop Control Methods ================================
2396
- /**
2397
- * Start the requestAnimationFrame loop.
2398
- * Resets timing state (elapsedTime, frameCount) on start.
2399
- * No-op if already running.
2400
- * @returns {void}
2401
- */
2402
- start() {
2403
- if (this.loopState.running) return;
2404
- const { elapsedTime, createdAt } = this.loopState;
2405
- let adjustedCreated = 0;
2406
- if (this.stoppedTime > 0) {
2407
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2408
- this.stoppedTime = 0;
2409
- }
2410
- Object.assign(this.loopState, {
2411
- running: true,
2412
- elapsedTime: elapsedTime ?? 0,
2413
- lastTime: performance.now(),
2414
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2415
- frameCount: 0,
2416
- rafHandle: requestAnimationFrame(this.loop)
2417
- });
2418
- }
2419
- /**
2420
- * Stop the requestAnimationFrame loop.
2421
- * Cancels any pending RAF callback.
2422
- * No-op if not running.
2423
- * @returns {void}
2424
- */
2425
- stop() {
2426
- if (!this.loopState.running) return;
2427
- this.loopState.running = false;
2428
- if (this.loopState.rafHandle !== null) {
2429
- cancelAnimationFrame(this.loopState.rafHandle);
2430
- this.loopState.rafHandle = null;
2431
- }
2432
- this.stoppedTime = performance.now();
2433
- }
2434
- /**
2435
- * Request frames to be rendered in demand mode.
2436
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2437
- * No-op if frameloop is not 'demand'.
2438
- * @param {number} [frames=1] - Number of frames to request
2439
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2440
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2441
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2442
- * @returns {void}
2443
- * @example
2444
- * // Request a single frame render
2445
- * scheduler.invalidate();
2446
- *
2447
- * @example
2448
- * // Request 5 frames (e.g., for animations)
2449
- * scheduler.invalidate(5);
2450
- *
2451
- * @example
2452
- * // Set pending frames to exactly 3 (don't stack with existing)
2453
- * scheduler.invalidate(3, false);
2454
- *
2455
- * @example
2456
- * // Add 2 more frames to existing pending count
2457
- * scheduler.invalidate(2, true);
2458
- */
2459
- invalidate(frames = 1, stackFrames = false) {
2460
- if (this._frameloop !== "demand") return;
2461
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2462
- this.pendingFrames = Math.min(60, baseFrames + frames);
2463
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2464
- }
2465
- /**
2466
- * Reset timing state for deterministic testing.
2467
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2468
- * @returns {void}
2469
- */
2470
- resetTiming() {
2471
- this.loopState.lastTime = null;
2472
- this.loopState.frameCount = 0;
2473
- this.loopState.elapsedTime = 0;
2474
- this.loopState.createdAt = performance.now();
2475
- }
2476
- //* Manual Stepping Methods ================================
2477
- /**
2478
- * Manually execute a single frame for all roots.
2479
- * Useful for frameloop='never' mode or testing scenarios.
2480
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2481
- * @returns {void}
2482
- * @example
2483
- * // Manual control mode
2484
- * scheduler.frameloop = 'never';
2485
- * scheduler.step(); // Execute one frame
2486
- */
2487
- step(timestamp) {
2488
- const now = timestamp ?? performance.now();
2489
- this.executeFrame(now);
2490
- }
2491
- /**
2492
- * Manually execute a single job by its ID.
2493
- * Useful for testing individual job callbacks in isolation.
2494
- * @param {string} id - The job ID to step
2495
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2496
- * @returns {void}
2497
- */
2498
- stepJob(id, timestamp) {
2499
- let job;
2500
- let root;
2501
- for (const r of this.roots.values()) {
2502
- job = r.jobs.get(id);
2503
- if (job) {
2504
- root = r;
2505
- break;
2506
- }
2507
- }
2508
- if (!job || !root) {
2509
- console.warn(`[Scheduler] Job "${id}" not found`);
2510
- return;
2511
- }
2512
- const now = timestamp ?? performance.now();
2513
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2514
- const delta = deltaMs / 1e3;
2515
- const elapsed = now - this.loopState.createdAt;
2516
- const providedState = root.getState?.() ?? {};
2517
- const frameState = {
2518
- ...providedState,
2519
- time: now,
2520
- delta,
2521
- elapsed,
2522
- frame: this.loopState.frameCount
2523
- };
2524
- try {
2525
- job.callback(frameState, delta);
2526
- } catch (error) {
2527
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2528
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2529
- }
2530
- }
2531
- /**
2532
- * Execute a single frame across all roots.
2533
- * Order: globalBefore → each root's jobs → globalAfter
2534
- * @param {number} timestamp - RAF timestamp in milliseconds
2535
- * @returns {void}
2536
- * @private
2537
- */
2538
- executeFrame(timestamp) {
2539
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2540
- const delta = deltaMs / 1e3;
2541
- this.loopState.lastTime = timestamp;
2542
- this.loopState.frameCount++;
2543
- this.loopState.elapsedTime += deltaMs;
2544
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2545
- for (const root of this.roots.values()) {
2546
- this.tickRoot(root, timestamp, delta);
2547
- }
2548
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2549
- }
2550
- /**
2551
- * Run all global jobs from a job map.
2552
- * Catches and logs errors without stopping execution.
2553
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2554
- * @param {number} timestamp - RAF timestamp in milliseconds
2555
- * @returns {void}
2556
- * @private
2557
- */
2558
- runGlobalJobs(jobs, timestamp) {
2559
- for (const job of jobs.values()) {
2560
- try {
2561
- job.callback(timestamp);
2562
- } catch (error) {
2563
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2564
- }
2565
- }
2566
- }
2567
- /**
2568
- * Execute all jobs for a single root in sorted order.
2569
- * Rebuilds sorted job list if needed, then dispatches each job.
2570
- * Errors are caught and propagated via triggerError.
2571
- * @param {RootEntry} root - The root entry to tick
2572
- * @param {number} timestamp - RAF timestamp in milliseconds
2573
- * @param {number} delta - Time since last frame in seconds
2574
- * @returns {void}
2575
- * @private
2576
- */
2577
- tickRoot(root, timestamp, delta) {
2578
- if (root.needsRebuild) {
2579
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2580
- root.needsRebuild = false;
2581
- }
2582
- const providedState = root.getState?.() ?? {};
2583
- const frameState = {
2584
- ...providedState,
2585
- time: timestamp,
2586
- delta,
2587
- elapsed: this.loopState.elapsedTime / 1e3,
2588
- // Convert ms to seconds
2589
- frame: this.loopState.frameCount
2590
- };
2591
- for (const job of root.sortedJobs) {
2592
- if (!shouldRun(job, timestamp)) continue;
2593
- try {
2594
- job.callback(frameState, delta);
2595
- } catch (error) {
2596
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2597
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2598
- }
2599
- }
2600
- }
2601
- //* Debug & Inspection Methods ================================
2602
- /**
2603
- * Get the total number of registered jobs across all roots.
2604
- * Includes both per-root jobs and global before/after jobs.
2605
- * @returns {number} Total job count
2606
- */
2607
- getJobCount() {
2608
- let count = 0;
2609
- for (const root of this.roots.values()) {
2610
- count += root.jobs.size;
2611
- }
2612
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2613
- }
2614
- /**
2615
- * Get all registered job IDs across all roots.
2616
- * Includes both per-root jobs and global before/after jobs.
2617
- * @returns {string[]} Array of all job IDs
2618
- */
2619
- getJobIds() {
2620
- const ids = [];
2621
- for (const root of this.roots.values()) {
2622
- ids.push(...root.jobs.keys());
2623
- }
2624
- ids.push(...this.globalBeforeJobs.keys());
2625
- ids.push(...this.globalAfterJobs.keys());
2626
- return ids;
2627
- }
2628
- /**
2629
- * Get the number of registered roots (Canvas instances).
2630
- * @returns {number} Number of registered roots
2631
- */
2632
- getRootCount() {
2633
- return this.roots.size;
2634
- }
2635
- /**
2636
- * Check if any user (non-system) jobs are registered in a specific phase.
2637
- * Used by the default render job to know if a user has taken over rendering.
2638
- *
2639
- * @param phase The phase to check
2640
- * @param rootId Optional root ID to check (checks all roots if not provided)
2641
- * @returns true if any user jobs exist in the phase
2642
- */
2643
- hasUserJobsInPhase(phase, rootId) {
2644
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2645
- return rootsToCheck.some((root) => {
2646
- if (!root) return false;
2647
- for (const job of root.jobs.values()) {
2648
- if (job.phase === phase && !job.system && job.enabled) return true;
2649
- }
2650
- return false;
2651
- });
2652
- }
2653
- //* Utility Methods ================================
2654
- /**
2655
- * Generate a unique root ID for automatic root registration.
2656
- * @returns {string} A unique root ID in the format 'root_N'
2657
- */
2658
- generateRootId() {
2659
- return `root_${this.nextRootIndex++}`;
2660
- }
2661
- /**
2662
- * Generate a unique job ID.
2663
- * @returns {string} A unique job ID in the format 'job_N'
2664
- * @private
2665
- */
2666
- generateJobId() {
2667
- return `job_${this.nextJobIndex}`;
2668
- }
2669
- /**
2670
- * Normalize before/after constraints to a Set.
2671
- * Handles undefined, single string, or array inputs.
2672
- * @param {string | string[] | undefined} value - The constraint value(s)
2673
- * @returns {Set<string>} Normalized Set of constraint strings
2674
- * @private
2675
- */
2676
- normalizeConstraints(value) {
2677
- if (!value) return /* @__PURE__ */ new Set();
2678
- if (Array.isArray(value)) return new Set(value);
2679
- return /* @__PURE__ */ new Set([value]);
2680
- }
2681
- };
2682
- //* Static State & Methods (Singleton Usage) ================================
2683
- //* Cross-Bundle Singleton Key ==============================
2684
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2685
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2686
- __publicField$1(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2687
- let Scheduler = _Scheduler;
2688
- const getScheduler = () => Scheduler.get();
2689
- if (hmrData) {
2690
- hmrData.accept?.();
2691
- }
2692
-
2693
- const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
2694
- const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
2695
- const createStore = (invalidate, advance) => {
2696
- const rootStore = traditional.createWithEqualityFn((set, get) => {
2697
- const position = new webgpu.Vector3();
2698
- const defaultTarget = new webgpu.Vector3();
2699
- const tempTarget = new webgpu.Vector3();
2700
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
2701
- const { width, height, top, left } = size;
2702
- const aspect = width / height;
2703
- if (target.isVector3) tempTarget.copy(target);
2704
- else tempTarget.set(...target);
2705
- const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
2706
- if (isOrthographicCamera(camera)) {
2707
- return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
2708
- } else {
2709
- const fov = camera.fov * Math.PI / 180;
2710
- const h = 2 * Math.tan(fov / 2) * distance;
2711
- const w = h * (width / height);
2712
- return { width: w, height: h, top, left, factor: width / w, distance, aspect };
2713
- }
2714
- }
2715
- let performanceTimeout = void 0;
2716
- const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
2717
- const pointer = new webgpu.Vector2();
2718
- const rootState = {
2719
- set,
2720
- get,
2721
- // Mock objects that have to be configured
2722
- // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
2723
- primaryStore: null,
2724
- gl: null,
2725
- renderer: null,
2726
- camera: null,
2727
- frustum: new webgpu.Frustum(),
2728
- autoUpdateFrustum: true,
2729
- raycaster: null,
2730
- events: {
2731
- priority: 1,
2732
- enabled: true,
2733
- connected: false,
2734
- frameTimedRaycasts: true,
2735
- alwaysFireOnScroll: true,
2736
- updateOnFrame: false
2737
- },
2738
- scene: null,
2739
- rootScene: null,
2740
- xr: null,
2741
- inspector: null,
2742
- invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
2743
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
2744
- textureColorSpace: webgpu.SRGBColorSpace,
2745
- isLegacy: false,
2746
- webGPUSupported: false,
2747
- isNative: false,
2748
- controls: null,
2749
- pointer,
2750
- mouse: pointer,
2751
- frameloop: "always",
2752
- onPointerMissed: void 0,
2753
- onDragOverMissed: void 0,
2754
- onDropMissed: void 0,
2755
- performance: {
2756
- current: 1,
2757
- min: 0.5,
2758
- max: 1,
2759
- debounce: 200,
2760
- regress: () => {
2761
- const state2 = get();
2762
- if (performanceTimeout) clearTimeout(performanceTimeout);
2763
- if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
2764
- performanceTimeout = setTimeout(
2765
- () => setPerformanceCurrent(get().performance.max),
2766
- state2.performance.debounce
2767
- );
2768
- }
2769
- },
2770
- size: { width: 0, height: 0, top: 0, left: 0 },
2771
- viewport: {
2772
- initialDpr: 0,
2773
- dpr: 0,
2774
- width: 0,
2775
- height: 0,
2776
- top: 0,
2777
- left: 0,
2778
- aspect: 0,
2779
- distance: 0,
2780
- factor: 0,
2781
- getCurrentViewport
2782
- },
2783
- setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
2784
- setSize: (width, height, top, left) => {
2785
- const state2 = get();
2786
- if (width === void 0) {
2787
- set({ _sizeImperative: false });
2788
- if (state2._sizeProps) {
2789
- const { width: propW, height: propH } = state2._sizeProps;
2790
- if (propW !== void 0 || propH !== void 0) {
2791
- const currentSize = state2.size;
2792
- const newSize = {
2793
- width: propW ?? currentSize.width,
2794
- height: propH ?? currentSize.height,
2795
- top: currentSize.top,
2796
- left: currentSize.left
2797
- };
2798
- set((s) => ({
2799
- size: newSize,
2800
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2801
- }));
2802
- getScheduler().invalidate();
2803
- }
2804
- }
2805
- return;
2806
- }
2807
- const w = width;
2808
- const h = height ?? width;
2809
- const t = top ?? state2.size.top;
2810
- const l = left ?? state2.size.left;
2811
- const size = { width: w, height: h, top: t, left: l };
2812
- set((s) => ({
2813
- size,
2814
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2815
- _sizeImperative: true
2816
- }));
2817
- getScheduler().invalidate();
2818
- },
2819
- setDpr: (dpr) => set((state2) => {
2820
- const resolved = calculateDpr(dpr);
2821
- return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
2822
- }),
2823
- setFrameloop: (frameloop = "always") => {
2824
- set(() => ({ frameloop }));
2825
- },
2826
- setError: (error) => set(() => ({ error })),
2827
- error: null,
2828
- //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2829
- uniforms: {},
2830
- nodes: {},
2831
- buffers: {},
2832
- gpuStorage: {},
2833
- textures: /* @__PURE__ */ new Map(),
2834
- _textureRefs: /* @__PURE__ */ new Map(),
2835
- renderPipeline: null,
2836
- passes: {},
2837
- _hmrVersion: 0,
2838
- _sizeImperative: false,
2839
- _sizeProps: null,
2840
- previousRoot: void 0,
2841
- internal: {
2842
- // Events
2843
- interaction: [],
2844
- subscribers: [],
2845
- // Per-pointer state (new unified structure)
2846
- pointerMap: /* @__PURE__ */ new Map(),
2847
- pointerDirty: /* @__PURE__ */ new Map(),
2848
- lastEvent: React__namespace.createRef(),
2849
- // Deprecated but kept for backwards compatibility
2850
- hovered: /* @__PURE__ */ new Map(),
2851
- initialClick: [0, 0],
2852
- initialHits: [],
2853
- capturedMap: /* @__PURE__ */ new Map(),
2854
- // Visibility tracking (onFramed, onOccluded, onVisible)
2855
- visibilityRegistry: /* @__PURE__ */ new Map(),
2856
- // Occlusion system (WebGPU only)
2857
- occlusionEnabled: false,
2858
- occlusionObserver: null,
2859
- occlusionCache: /* @__PURE__ */ new Map(),
2860
- helperGroup: null,
2861
- // Updates
2862
- active: false,
2863
- frames: 0,
2864
- priority: 0,
2865
- subscribe: (ref, priority, store) => {
2866
- const internal = get().internal;
2867
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
2868
- internal.subscribers.push({ ref, priority, store });
2869
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
2870
- return () => {
2871
- const internal2 = get().internal;
2872
- if (internal2?.subscribers) {
2873
- internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
2874
- internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
2875
- }
2876
- };
2877
- },
2878
- // Renderer Storage (single source of truth)
2879
- actualRenderer: null,
2880
- // Scheduler for useFrameNext (initialized in renderer.tsx)
2881
- scheduler: null
2882
- }
2883
- };
2884
- return rootState;
1890
+ };
1891
+ return rootState;
2885
1892
  });
2886
1893
  const state = rootStore.getState();
2887
1894
  Object.defineProperty(state, "gl", {
@@ -2889,8 +1896,7 @@ const createStore = (invalidate, advance) => {
2889
1896
  const currentState = rootStore.getState();
2890
1897
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2891
1898
  const stack = new Error().stack || "";
2892
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2893
- if (!isInternalAccess) {
1899
+ if (!isInternalRendererAccess(stack)) {
2894
1900
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2895
1901
  notifyDepreciated({
2896
1902
  heading: "Accessing state.gl in WebGPU mode",
@@ -3003,26 +2009,32 @@ function loadingFn(extensions, onProgress) {
3003
2009
  );
3004
2010
  };
3005
2011
  }
3006
- function useLoader(loader, input, extensions, onProgress) {
3007
- const keys = Array.isArray(input) ? input : [input];
2012
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2013
+ const inputs = Array.isArray(input) ? input : [input];
2014
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
3008
2015
  const fn = loadingFn(extensions, onProgress);
3009
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2016
+ const results = cacheKeys.map(
2017
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2018
+ );
3010
2019
  return Array.isArray(input) ? results : results[0];
3011
2020
  }
3012
- useLoader.preload = function(loader, input, extensions, onProgress) {
3013
- const keys = Array.isArray(input) ? input : [input];
3014
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2021
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2022
+ const inputs = Array.isArray(input) ? input : [input];
2023
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2024
+ cacheKeys.forEach(
2025
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2026
+ );
3015
2027
  };
3016
- useLoader.clear = function(loader, input) {
3017
- const keys = Array.isArray(input) ? input : [input];
3018
- keys.forEach((key) => suspendReact.clear([loader, key]));
2028
+ useLoader.clear = function(loader, input, cacheKey) {
2029
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2030
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
3019
2031
  };
3020
2032
  useLoader.loader = getLoader;
3021
2033
 
3022
2034
  function useFrame(callback, priorityOrOptions) {
3023
2035
  const store = React__namespace.useContext(context);
3024
2036
  const isInsideCanvas = store !== null;
3025
- const scheduler = getScheduler();
2037
+ const scheduler$1 = scheduler.getScheduler();
3026
2038
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
3027
2039
  id: priorityOrOptions.id,
3028
2040
  phase: priorityOrOptions.phase,
@@ -3070,7 +2082,7 @@ function useFrame(callback, priorityOrOptions) {
3070
2082
  };
3071
2083
  callbackRef.current?.(mergedState, delta);
3072
2084
  };
3073
- const unregister = scheduler.register(wrappedCallback, {
2085
+ const unregister = scheduler$1.register(wrappedCallback, {
3074
2086
  id,
3075
2087
  rootId,
3076
2088
  ...options
@@ -3091,37 +2103,31 @@ function useFrame(callback, priorityOrOptions) {
3091
2103
  }
3092
2104
  };
3093
2105
  } else {
3094
- const registerOutside = () => {
3095
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3096
- };
3097
- if (scheduler.independent || scheduler.isReady) {
3098
- return registerOutside();
3099
- }
3100
- let unregisterJob = null;
3101
- const unsubReady = scheduler.onRootReady(() => {
3102
- unregisterJob = registerOutside();
3103
- });
3104
- return () => {
3105
- unsubReady();
3106
- unregisterJob?.();
3107
- };
2106
+ return scheduler$1.register(
2107
+ (state, delta) => {
2108
+ const frameState = state;
2109
+ if (!frameState.renderer) return;
2110
+ callbackRef.current?.(frameState, delta);
2111
+ },
2112
+ { id, ...options }
2113
+ );
3108
2114
  }
3109
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2115
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3110
2116
  const isPaused = React__namespace.useSyncExternalStore(
3111
2117
  // Subscribe function
3112
2118
  React__namespace.useCallback(
3113
2119
  (onStoreChange) => {
3114
- return getScheduler().subscribeJobState(id, onStoreChange);
2120
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3115
2121
  },
3116
2122
  [id]
3117
2123
  ),
3118
2124
  // getSnapshot function
3119
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2125
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3120
2126
  // getServerSnapshot function (SSR)
3121
2127
  React__namespace.useCallback(() => false, [])
3122
2128
  );
3123
2129
  const controls = React__namespace.useMemo(() => {
3124
- const scheduler2 = getScheduler();
2130
+ const scheduler2 = scheduler.getScheduler();
3125
2131
  return {
3126
2132
  /** The job's unique ID */
3127
2133
  id,
@@ -3136,7 +2142,7 @@ function useFrame(callback, priorityOrOptions) {
3136
2142
  * @param timestamp Optional timestamp (defaults to performance.now())
3137
2143
  */
3138
2144
  step: (timestamp) => {
3139
- getScheduler().stepJob(id, timestamp);
2145
+ scheduler.getScheduler().stepJob(id, timestamp);
3140
2146
  },
3141
2147
  /**
3142
2148
  * Manually step ALL jobs in the scheduler.
@@ -3144,20 +2150,20 @@ function useFrame(callback, priorityOrOptions) {
3144
2150
  * @param timestamp Optional timestamp (defaults to performance.now())
3145
2151
  */
3146
2152
  stepAll: (timestamp) => {
3147
- getScheduler().step(timestamp);
2153
+ scheduler.getScheduler().step(timestamp);
3148
2154
  },
3149
2155
  /**
3150
2156
  * Pause this job (set enabled=false).
3151
2157
  * Job remains registered but won't run.
3152
2158
  */
3153
2159
  pause: () => {
3154
- getScheduler().pauseJob(id);
2160
+ scheduler.getScheduler().pauseJob(id);
3155
2161
  },
3156
2162
  /**
3157
2163
  * Resume this job (set enabled=true).
3158
2164
  */
3159
2165
  resume: () => {
3160
- getScheduler().resumeJob(id);
2166
+ scheduler.getScheduler().resumeJob(id);
3161
2167
  },
3162
2168
  /**
3163
2169
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3415,7 +2421,7 @@ function addEffect(callback) {
3415
2421
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3416
2422
  });
3417
2423
  const id = `legacy_effect_${effectId++}`;
3418
- return getScheduler().registerGlobal("before", id, callback);
2424
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3419
2425
  }
3420
2426
  function addAfterEffect(callback) {
3421
2427
  notifyDepreciated({
@@ -3424,7 +2430,7 @@ function addAfterEffect(callback) {
3424
2430
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3425
2431
  });
3426
2432
  const id = `legacy_afterEffect_${effectId++}`;
3427
- return getScheduler().registerGlobal("after", id, callback);
2433
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3428
2434
  }
3429
2435
  function addTail(callback) {
3430
2436
  notifyDepreciated({
@@ -3432,16 +2438,16 @@ function addTail(callback) {
3432
2438
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3433
2439
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3434
2440
  });
3435
- return getScheduler().onIdle(callback);
2441
+ return scheduler.getScheduler().onIdle(callback);
3436
2442
  }
3437
2443
  function invalidate(state, frames = 1, stackFrames = false) {
3438
- getScheduler().invalidate(frames, stackFrames);
2444
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3439
2445
  }
3440
2446
  function advance(timestamp) {
3441
- getScheduler().step(timestamp);
2447
+ scheduler.getScheduler().step(timestamp);
3442
2448
  }
3443
2449
 
3444
- const version = "10.0.0-alpha.2";
2450
+ const version = "10.0.0-alpha.3";
3445
2451
  const packageData = {
3446
2452
  version: version};
3447
2453
 
@@ -14880,6 +13886,7 @@ function swapInstances() {
14880
13886
  }
14881
13887
  }
14882
13888
  if (instance.isHidden) unhideInstance(instance);
13889
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14883
13890
  if (instance.object.__r3f) delete instance.object.__r3f;
14884
13891
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14885
13892
  }
@@ -14892,6 +13899,8 @@ function swapInstances() {
14892
13899
  instance.object.__r3f = instance;
14893
13900
  setFiberRef(fiber, instance.object);
14894
13901
  delete instance.appliedOnce;
13902
+ instance.eventCount = 0;
13903
+ instance.handlers = {};
14895
13904
  applyProps(instance.object, instance.props);
14896
13905
  if (instance.props.attach) {
14897
13906
  attach(parent, instance);
@@ -15107,11 +14116,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15107
14116
  cloneMutableTextInstance(textInstance) {
15108
14117
  return textInstance;
15109
14118
  },
14119
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14120
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14121
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14122
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14123
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14124
+ // Guarded by a test asserting a full render + unmount never reaches them.
15110
14125
  cloneRootViewTransitionContainer(_rootContainer) {
15111
- throw new Error("Not implemented.");
15112
14126
  },
15113
14127
  removeRootViewTransitionClone(_rootContainer, _clone) {
15114
- throw new Error("Not implemented.");
15115
14128
  },
15116
14129
  // https://github.com/facebook/react/pull/32465
15117
14130
  createFragmentInstance: (_fiber) => null,
@@ -15196,6 +14209,7 @@ function createRoot(canvas) {
15196
14209
  const lastConfiguredProps = {};
15197
14210
  let configured = false;
15198
14211
  let pending = null;
14212
+ let rendererSetup = null;
15199
14213
  return {
15200
14214
  async configure(props = {}) {
15201
14215
  let resolve;
@@ -15226,7 +14240,7 @@ function createRoot(canvas) {
15226
14240
  forceEven
15227
14241
  } = props;
15228
14242
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
15229
- const state = store.getState();
14243
+ let state = store.getState();
15230
14244
  const defaultGPUProps = {
15231
14245
  canvas,
15232
14246
  antialias: true
@@ -15240,52 +14254,64 @@ function createRoot(canvas) {
15240
14254
  throw new Error("Cannot use both gl and renderer props at the same time");
15241
14255
  }
15242
14256
  let renderer = state.internal.actualRenderer;
15243
- if (primaryCanvas && !state.internal.actualRenderer) {
15244
- const primary = await waitForPrimary(primaryCanvas);
15245
- renderer = primary.renderer;
15246
- state.internal.actualRenderer = renderer;
15247
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15248
- primary.store.setState((prev) => ({
15249
- internal: { ...prev.internal, isMultiCanvas: true }
15250
- }));
15251
- state.set((prev) => ({
15252
- webGPUSupported: primary.store.getState().webGPUSupported,
15253
- renderer,
15254
- primaryStore: primary.store,
15255
- internal: {
15256
- ...prev.internal,
15257
- canvasTarget,
15258
- isMultiCanvas: true,
15259
- isSecondary: true,
15260
- targetId: primaryCanvas
15261
- }
15262
- }));
15263
- } else if (!state.internal.actualRenderer) {
15264
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
15265
- if (!renderer.hasInitialized?.()) {
15266
- const size2 = computeInitialSize(canvas, propsSize);
15267
- if (size2.width > 0 && size2.height > 0) {
15268
- const pixelRatio = calculateDpr(dpr);
15269
- canvas.width = size2.width * pixelRatio;
15270
- canvas.height = size2.height * pixelRatio;
15271
- }
15272
- await renderer.init();
15273
- }
15274
- const backend = renderer.backend;
15275
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15276
- state.internal.actualRenderer = renderer;
15277
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15278
- if (canvasId && !state.internal.isSecondary) {
15279
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15280
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15281
- state.set((prev) => ({
15282
- internal: {
15283
- ...prev.internal,
15284
- canvasTarget,
15285
- unregisterPrimary
14257
+ if (!state.internal.actualRenderer) {
14258
+ if (!rendererSetup) {
14259
+ rendererSetup = (async () => {
14260
+ if (primaryCanvas) {
14261
+ const primary = await waitForPrimary(primaryCanvas);
14262
+ renderer = primary.renderer;
14263
+ state.internal.actualRenderer = renderer;
14264
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14265
+ primary.store.setState((prev) => ({
14266
+ internal: { ...prev.internal, isMultiCanvas: true }
14267
+ }));
14268
+ state.set((prev) => ({
14269
+ webGPUSupported: primary.store.getState().webGPUSupported,
14270
+ renderer,
14271
+ primaryStore: primary.store,
14272
+ internal: {
14273
+ ...prev.internal,
14274
+ canvasTarget,
14275
+ isMultiCanvas: true,
14276
+ isSecondary: true,
14277
+ targetId: primaryCanvas
14278
+ }
14279
+ }));
14280
+ } else {
14281
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14282
+ if (!renderer.hasInitialized?.()) {
14283
+ const size2 = computeInitialSize(canvas, propsSize);
14284
+ if (size2.width > 0 && size2.height > 0) {
14285
+ const pixelRatio = calculateDpr(dpr);
14286
+ canvas.width = size2.width * pixelRatio;
14287
+ canvas.height = size2.height * pixelRatio;
14288
+ }
14289
+ await renderer.init();
14290
+ }
14291
+ const backend = renderer.backend;
14292
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14293
+ state.internal.actualRenderer = renderer;
14294
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14295
+ if (canvasId && !state.internal.isSecondary) {
14296
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14297
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14298
+ state.set((prev) => ({
14299
+ internal: {
14300
+ ...prev.internal,
14301
+ canvasTarget,
14302
+ unregisterPrimary
14303
+ }
14304
+ }));
14305
+ }
15286
14306
  }
15287
- }));
14307
+ })().catch((err) => {
14308
+ rendererSetup = null;
14309
+ throw err;
14310
+ });
15288
14311
  }
14312
+ await rendererSetup;
14313
+ state = store.getState();
14314
+ renderer = state.internal.actualRenderer;
15289
14315
  }
15290
14316
  let raycaster = state.raycaster;
15291
14317
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -15465,15 +14491,15 @@ function createRoot(canvas) {
15465
14491
  applyProps(currentRenderer, rendererProps);
15466
14492
  }
15467
14493
  }
15468
- const scheduler = getScheduler();
14494
+ const scheduler$1 = scheduler.getScheduler();
15469
14495
  const rootId = state.internal.rootId;
15470
14496
  if (!rootId) {
15471
- const newRootId = canvasId || scheduler.generateRootId();
15472
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14497
+ const newRootId = canvasId || scheduler$1.generateRootId();
14498
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15473
14499
  getState: () => store.getState(),
15474
14500
  onError: (err) => store.getState().setError(err)
15475
14501
  });
15476
- const unregisterCanvasTarget = scheduler.register(
14502
+ const unregisterCanvasTarget = scheduler$1.register(
15477
14503
  () => {
15478
14504
  const state2 = store.getState();
15479
14505
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15488,7 +14514,7 @@ function createRoot(canvas) {
15488
14514
  system: true
15489
14515
  }
15490
14516
  );
15491
- const unregisterEventsFlush = scheduler.register(
14517
+ const unregisterEventsFlush = scheduler$1.register(
15492
14518
  () => {
15493
14519
  const state2 = store.getState();
15494
14520
  state2.events.flush?.();
@@ -15500,7 +14526,7 @@ function createRoot(canvas) {
15500
14526
  system: true
15501
14527
  }
15502
14528
  );
15503
- const unregisterFrustum = scheduler.register(
14529
+ const unregisterFrustum = scheduler$1.register(
15504
14530
  () => {
15505
14531
  const state2 = store.getState();
15506
14532
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15510,11 +14536,11 @@ function createRoot(canvas) {
15510
14536
  {
15511
14537
  id: `${newRootId}_frustum`,
15512
14538
  rootId: newRootId,
15513
- phase: "preRender",
14539
+ before: "render",
15514
14540
  system: true
15515
14541
  }
15516
14542
  );
15517
- const unregisterVisibility = scheduler.register(
14543
+ const unregisterVisibility = scheduler$1.register(
15518
14544
  () => {
15519
14545
  const state2 = store.getState();
15520
14546
  checkVisibility(state2);
@@ -15522,16 +14548,16 @@ function createRoot(canvas) {
15522
14548
  {
15523
14549
  id: `${newRootId}_visibility`,
15524
14550
  rootId: newRootId,
15525
- phase: "preRender",
14551
+ before: "render",
15526
14552
  system: true,
15527
14553
  after: `${newRootId}_frustum`
15528
14554
  }
15529
14555
  );
15530
- const unregisterRender = scheduler.register(
14556
+ const unregisterRender = scheduler$1.register(
15531
14557
  () => {
15532
14558
  const state2 = store.getState();
15533
14559
  const renderer2 = state2.internal.actualRenderer;
15534
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14560
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15535
14561
  if (userHandlesRender || state2.internal.priority) return;
15536
14562
  try {
15537
14563
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15564,11 +14590,11 @@ function createRoot(canvas) {
15564
14590
  unregisterVisibility();
15565
14591
  unregisterRender();
15566
14592
  },
15567
- scheduler
14593
+ scheduler: scheduler$1
15568
14594
  }
15569
14595
  }));
15570
14596
  }
15571
- scheduler.frameloop = frameloop;
14597
+ scheduler$1.frameloop = frameloop;
15572
14598
  onCreated = onCreatedCallback;
15573
14599
  configured = true;
15574
14600
  resolve();
@@ -15635,7 +14661,8 @@ function unmountComponentAtNode(canvas, callback) {
15635
14661
  dispose(state.scene);
15636
14662
  _roots.delete(canvas);
15637
14663
  if (callback) callback(canvas);
15638
- } catch {
14664
+ } catch (error) {
14665
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15639
14666
  }
15640
14667
  }, 500);
15641
14668
  }
@@ -15698,6 +14725,7 @@ function PortalInner({ state = {}, children, container }) {
15698
14725
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
15699
14726
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15700
14727
  }
14728
+ const set = injectState.set;
15701
14729
  return {
15702
14730
  // The intersect consists of the previous root state
15703
14731
  ...rootState,
@@ -15716,33 +14744,205 @@ function PortalInner({ state = {}, children, container }) {
15716
14744
  size: resolvedSize,
15717
14745
  viewport: { ...rootState.viewport, ...viewport },
15718
14746
  // Layers are allowed to override events
15719
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14747
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15720
14748
  // Container for child attachment - the portalScene (injected or container itself)
15721
14749
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15722
14750
  };
15723
14751
  });
15724
- const usePortalStore = React.useMemo(() => {
15725
- const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15726
- const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15727
- onMutate(previousRoot.getState());
15728
- return store;
15729
- }, [previousRoot, container]);
15730
- useIsomorphicLayoutEffect(() => {
15731
- const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
15732
- const unsubscribe = previousRoot.subscribe(onMutate);
15733
- return unsubscribe;
15734
- }, [previousRoot, usePortalStore]);
15735
- return (
15736
- // @ts-ignore, reconciler types are not maintained
15737
- /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
15738
- /* @__PURE__ */ jsxRuntime.jsx(context.Provider, { value: usePortalStore, children }),
15739
- usePortalStore,
15740
- null
15741
- ) })
15742
- );
14752
+ const usePortalStore = React.useMemo(() => {
14753
+ const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14754
+ const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14755
+ onMutate(previousRoot.getState());
14756
+ return store;
14757
+ }, [previousRoot, container]);
14758
+ useIsomorphicLayoutEffect(() => {
14759
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14760
+ const unsubscribe = previousRoot.subscribe(onMutate);
14761
+ return unsubscribe;
14762
+ }, [previousRoot, usePortalStore]);
14763
+ return (
14764
+ // @ts-ignore, reconciler types are not maintained
14765
+ /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
14766
+ /* @__PURE__ */ jsxRuntime.jsx(context.Provider, { value: usePortalStore, children }),
14767
+ usePortalStore,
14768
+ null
14769
+ ) })
14770
+ );
14771
+ }
14772
+ function flushSync(fn) {
14773
+ return reconciler.flushSyncFromReconciler(fn);
14774
+ }
14775
+
14776
+ function parseBackground(background) {
14777
+ if (!background) return null;
14778
+ if (typeof background === "object" && !background.isColor) {
14779
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14780
+ return {
14781
+ ...rest,
14782
+ preset,
14783
+ files: envMap || files,
14784
+ backgroundFiles: backgroundMap,
14785
+ background: true
14786
+ };
14787
+ }
14788
+ if (typeof background === "number") {
14789
+ return { color: background, background: true };
14790
+ }
14791
+ if (typeof background === "string") {
14792
+ if (background in presetsObj) {
14793
+ return { preset: background, background: true };
14794
+ }
14795
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14796
+ return { files: background, background: true };
14797
+ }
14798
+ return { color: background, background: true };
14799
+ }
14800
+ if (background.isColor) {
14801
+ return { color: background, background: true };
14802
+ }
14803
+ return null;
14804
+ }
14805
+
14806
+ function parseRendererConfig(rendererProp) {
14807
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14808
+ if (isRendererConfig) {
14809
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14810
+ return {
14811
+ primaryCanvas: pc,
14812
+ scheduler: sc,
14813
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14814
+ };
14815
+ }
14816
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14817
+ }
14818
+
14819
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14820
+ const ROOT_SCOPE = "";
14821
+ const registries = /* @__PURE__ */ new WeakMap();
14822
+ function getKindRegistry(store, kind) {
14823
+ let registry = registries.get(store);
14824
+ if (!registry) {
14825
+ registry = {
14826
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14827
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14828
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14829
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14830
+ };
14831
+ registries.set(store, registry);
14832
+ }
14833
+ return registry[kind];
14834
+ }
14835
+ function resolvePrimary$1(store) {
14836
+ return store.getState().primaryStore ?? store;
14837
+ }
14838
+ function isScopeValid(store, kind, scopeKey) {
14839
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14840
+ }
14841
+ function peekStaged(store, kind, scopeKey) {
14842
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14843
+ }
14844
+ function stageEntries(store, kind, scopeKey, entries) {
14845
+ const { staged } = getKindRegistry(store, kind);
14846
+ const current = staged.get(scopeKey);
14847
+ if (current) Object.assign(current, entries);
14848
+ else staged.set(scopeKey, { ...entries });
14849
+ }
14850
+ function readCommittedScope(map, scopeKey, isLeaf) {
14851
+ if (scopeKey === ROOT_SCOPE) {
14852
+ const leaves = {};
14853
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14854
+ return leaves;
14855
+ }
14856
+ const scopeData = map[scopeKey];
14857
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14858
+ return {};
14859
+ }
14860
+ function withStagedOverlay(store, kind, committed) {
14861
+ const { staged } = getKindRegistry(store, kind);
14862
+ if (staged.size === 0) return committed;
14863
+ const view = { ...committed };
14864
+ for (const [scopeKey, entries] of staged) {
14865
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14866
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14867
+ }
14868
+ return view;
14869
+ }
14870
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14871
+ const registry = getKindRegistry(store, kind);
14872
+ const staged = registry.staged.get(scopeKey);
14873
+ if (!staged) return;
14874
+ registry.staged.delete(scopeKey);
14875
+ const replace = !registry.valid.has(scopeKey);
14876
+ store.setState((state) => {
14877
+ const map = state[kind];
14878
+ if (scopeKey === ROOT_SCOPE) {
14879
+ if (!replace) return { [kind]: { ...map, ...staged } };
14880
+ const next = {};
14881
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14882
+ return { [kind]: { ...next, ...staged } };
14883
+ }
14884
+ const current = replace ? {} : map[scopeKey] ?? {};
14885
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14886
+ });
14887
+ registry.valid.add(scopeKey);
14888
+ }
14889
+ function invalidateResource(store, kind, scopeKey) {
14890
+ const registry = getKindRegistry(store, kind);
14891
+ if (scopeKey === void 0) {
14892
+ registry.valid.clear();
14893
+ registry.staged.clear();
14894
+ } else {
14895
+ registry.valid.delete(scopeKey);
14896
+ registry.staged.delete(scopeKey);
14897
+ }
14898
+ }
14899
+ function rebuildResource(store, kind, userScope) {
14900
+ const primary = resolvePrimary$1(store);
14901
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14902
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14903
+ }
14904
+ function invalidateAllResources(store) {
14905
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14906
+ }
14907
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14908
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
14909
+ if (staged) for (const name of names) delete staged[name];
14910
+ store.setState((state) => {
14911
+ const map = state[kind];
14912
+ if (scope) {
14913
+ const currentScope = { ...map[scope] };
14914
+ for (const name of names) delete currentScope[name];
14915
+ return { [kind]: { ...map, [scope]: currentScope } };
14916
+ }
14917
+ const next = { ...map };
14918
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
14919
+ return { [kind]: next };
14920
+ });
15743
14921
  }
15744
- function flushSync(fn) {
15745
- return reconciler.flushSyncFromReconciler(fn);
14922
+ function clearResourceEntries(store, kind, scope, isLeaf) {
14923
+ const registry = getKindRegistry(store, kind);
14924
+ if (scope && scope !== "root") registry.staged.delete(scope);
14925
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
14926
+ else registry.staged.clear();
14927
+ store.setState((state) => {
14928
+ const map = state[kind];
14929
+ if (scope && scope !== "root") {
14930
+ const { [scope]: _, ...rest } = map;
14931
+ return { [kind]: rest };
14932
+ }
14933
+ if (scope === "root") {
14934
+ const next = {};
14935
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14936
+ return { [kind]: next };
14937
+ }
14938
+ return { [kind]: {} };
14939
+ });
14940
+ }
14941
+
14942
+ function clearHmrCaches(store) {
14943
+ const primary = store.getState().primaryStore ?? store;
14944
+ invalidateAllResources(primary);
14945
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
15746
14946
  }
15747
14947
 
15748
14948
  function CanvasImpl({
@@ -15765,6 +14965,8 @@ function CanvasImpl({
15765
14965
  raycaster,
15766
14966
  camera,
15767
14967
  scene,
14968
+ autoUpdateFrustum,
14969
+ occlusion,
15768
14970
  onPointerMissed,
15769
14971
  onDragOverMissed,
15770
14972
  onDropMissed,
@@ -15776,49 +14978,10 @@ function CanvasImpl({
15776
14978
  forceEven,
15777
14979
  ...props
15778
14980
  }) {
15779
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15780
- let primaryCanvas;
15781
- let scheduler;
15782
- let renderer;
15783
- if (isRendererConfig) {
15784
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15785
- primaryCanvas = pc;
15786
- scheduler = sc;
15787
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15788
- } else {
15789
- renderer = rendererProp;
15790
- }
14981
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15791
14982
  React__namespace.useMemo(() => extend(THREE), []);
15792
14983
  const Bridge = useBridge();
15793
- const backgroundProps = React__namespace.useMemo(() => {
15794
- if (!background) return null;
15795
- if (typeof background === "object" && !background.isColor) {
15796
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15797
- return {
15798
- ...rest,
15799
- preset,
15800
- files: envMap || files,
15801
- backgroundFiles: backgroundMap,
15802
- background: true
15803
- };
15804
- }
15805
- if (typeof background === "number") {
15806
- return { color: background, background: true };
15807
- }
15808
- if (typeof background === "string") {
15809
- if (background in presetsObj) {
15810
- return { preset: background, background: true };
15811
- }
15812
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15813
- return { files: background, background: true };
15814
- }
15815
- return { color: background, background: true };
15816
- }
15817
- if (background.isColor) {
15818
- return { color: background, background: true };
15819
- }
15820
- return null;
15821
- }, [background]);
14984
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15822
14985
  const hasInitialSizeRef = React__namespace.useRef(false);
15823
14986
  const measureConfig = React__namespace.useMemo(() => {
15824
14987
  if (!hasInitialSizeRef.current) {
@@ -15860,6 +15023,7 @@ function CanvasImpl({
15860
15023
  const handleDropMissed = useMutableCallback(onDropMissed);
15861
15024
  const [block, setBlock] = React__namespace.useState(false);
15862
15025
  const [error, setError] = React__namespace.useState(false);
15026
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15863
15027
  if (block) throw block;
15864
15028
  if (error) throw error;
15865
15029
  const root = React__namespace.useRef(null);
@@ -15867,6 +15031,7 @@ function CanvasImpl({
15867
15031
  const unsubscribeErrorRef = React__namespace.useRef(null);
15868
15032
  useIsomorphicLayoutEffect(() => {
15869
15033
  effectActiveRef.current = true;
15034
+ if (fallbackVisible) return;
15870
15035
  const canvas = canvasRef.current;
15871
15036
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15872
15037
  if (!root.current) {
@@ -15887,7 +15052,7 @@ function CanvasImpl({
15887
15052
  }
15888
15053
  async function run() {
15889
15054
  if (!effectActiveRef.current || !root.current) return;
15890
- await root.current.configure({
15055
+ const configured = await root.current.configure({
15891
15056
  id,
15892
15057
  primaryCanvas,
15893
15058
  scheduler,
@@ -15902,6 +15067,8 @@ function CanvasImpl({
15902
15067
  performance,
15903
15068
  raycaster,
15904
15069
  camera,
15070
+ autoUpdateFrustum,
15071
+ occlusion,
15905
15072
  size: effectiveSize,
15906
15073
  // Store size props for reset functionality
15907
15074
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15926,8 +15093,20 @@ function CanvasImpl({
15926
15093
  }
15927
15094
  onCreated?.(state);
15928
15095
  }
15929
- });
15930
- if (!effectActiveRef.current || !root.current) return;
15096
+ }).then(
15097
+ () => true,
15098
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15099
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15100
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15101
+ (setupError) => {
15102
+ if (effectActiveRef.current) {
15103
+ if (fallback != null) setFallbackVisible(true);
15104
+ else setError(setupError);
15105
+ }
15106
+ return false;
15107
+ }
15108
+ );
15109
+ if (!configured || !effectActiveRef.current || !root.current) return;
15931
15110
  root.current.render(
15932
15111
  /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: [
15933
15112
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15961,14 +15140,7 @@ function CanvasImpl({
15961
15140
  const handleHMR = () => {
15962
15141
  queueMicrotask(() => {
15963
15142
  const rootEntry = _roots.get(canvas);
15964
- if (rootEntry?.store) {
15965
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15966
- rootEntry.store.setState((state) => ({
15967
- nodes: {},
15968
- uniforms: {},
15969
- _hmrVersion: state._hmrVersion + 1
15970
- }));
15971
- }
15143
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15972
15144
  });
15973
15145
  };
15974
15146
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
@@ -15997,7 +15169,11 @@ function CanvasImpl({
15997
15169
  ...style
15998
15170
  },
15999
15171
  ...props,
16000
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15172
+ children: fallbackVisible ? (
15173
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15174
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15175
+ fallback
15176
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
16001
15177
  "canvas",
16002
15178
  {
16003
15179
  ref: canvasRef,
@@ -16079,35 +15255,50 @@ let ScopedStore = _ScopedStore;
16079
15255
  function createScopedStore(data) {
16080
15256
  return new ScopedStore(data);
16081
15257
  }
16082
- function createLazyCreatorState(state) {
15258
+ function createLazyCreatorState(state, store) {
16083
15259
  let _uniforms = null;
16084
15260
  let _nodes = null;
16085
15261
  let _buffers = null;
16086
15262
  let _gpuStorage = null;
15263
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
16087
15264
  return Object.create(state, {
16088
15265
  uniforms: {
16089
15266
  get() {
16090
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15267
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
16091
15268
  }
16092
15269
  },
16093
15270
  nodes: {
16094
15271
  get() {
16095
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15272
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
16096
15273
  }
16097
15274
  },
16098
15275
  buffers: {
16099
15276
  get() {
16100
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15277
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
16101
15278
  }
16102
15279
  },
16103
15280
  gpuStorage: {
16104
15281
  get() {
16105
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15282
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
16106
15283
  }
16107
15284
  }
16108
15285
  });
16109
15286
  }
16110
15287
 
15288
+ function resolvePrimary(local) {
15289
+ return local.getState().primaryStore ?? local;
15290
+ }
15291
+ function usePrimaryStore() {
15292
+ const local = useStore();
15293
+ const primary = local.getState().primaryStore;
15294
+ return React.useMemo(() => primary ?? local, [primary, local]);
15295
+ }
15296
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15297
+ const local = useStore();
15298
+ const primary = resolvePrimary(local);
15299
+ return primary(selector, equalityFn);
15300
+ }
15301
+
16111
15302
  function addTexture(set, key, value) {
16112
15303
  set((state) => {
16113
15304
  const newMap = new Map(state.textures);
@@ -16211,65 +15402,56 @@ function useCompareMemoize(value, deep) {
16211
15402
  return ref.current;
16212
15403
  }
16213
15404
 
15405
+ function useScopedResource(options) {
15406
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15407
+ const scopeKey = scope ?? ROOT_SCOPE;
15408
+ const version = store((s) => s._hmrVersion);
15409
+ const entries = React.useMemo(() => {
15410
+ const staged = peekStaged(store, kind, scopeKey);
15411
+ const reusable = isScopeValid(store, kind, scopeKey);
15412
+ const map = store.getState()[kind];
15413
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15414
+ const result = {};
15415
+ let fresh = null;
15416
+ for (const [name, candidate] of Object.entries(create())) {
15417
+ const existing = staged?.[name] ?? committed?.[name];
15418
+ if (existing !== void 0) {
15419
+ result[name] = existing;
15420
+ reconcile?.(existing, candidate);
15421
+ } else {
15422
+ const value = prepare ? prepare(name, candidate) : candidate;
15423
+ result[name] = value;
15424
+ (fresh ?? (fresh = {}))[name] = value;
15425
+ }
15426
+ }
15427
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15428
+ return result;
15429
+ }, [store, kind, scopeKey, version, input]);
15430
+ useIsomorphicLayoutEffect(() => {
15431
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15432
+ });
15433
+ return entries;
15434
+ }
15435
+
16214
15436
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16215
15437
  function useUniforms(creatorOrScope, scope) {
16216
- const store = useStore();
15438
+ const store = usePrimaryStore();
16217
15439
  const removeUniforms2 = React.useCallback(
16218
- (names, targetScope) => {
16219
- const nameArray = Array.isArray(names) ? names : [names];
16220
- store.setState((state) => {
16221
- if (targetScope) {
16222
- const currentScope = { ...state.uniforms[targetScope] };
16223
- for (const name of nameArray) delete currentScope[name];
16224
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
16225
- }
16226
- const uniforms2 = { ...state.uniforms };
16227
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
16228
- return { uniforms: uniforms2 };
16229
- });
16230
- },
15440
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
16231
15441
  [store]
16232
15442
  );
16233
15443
  const clearUniforms = React.useCallback(
16234
- (targetScope) => {
16235
- store.setState((state) => {
16236
- if (targetScope && targetScope !== "root") {
16237
- const { [targetScope]: _, ...rest } = state.uniforms;
16238
- return { uniforms: rest };
16239
- }
16240
- if (targetScope === "root") {
16241
- const uniforms2 = {};
16242
- for (const [key, value] of Object.entries(state.uniforms)) {
16243
- if (!isUniformNode$1(value)) uniforms2[key] = value;
16244
- }
16245
- return { uniforms: uniforms2 };
16246
- }
16247
- return { uniforms: {} };
16248
- });
16249
- },
15444
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
16250
15445
  [store]
16251
15446
  );
16252
15447
  const rebuildUniforms = React.useCallback(
16253
- (targetScope) => {
16254
- store.setState((state) => {
16255
- let newUniforms = {};
16256
- if (targetScope && targetScope !== "root") {
16257
- const { [targetScope]: _, ...rest } = state.uniforms;
16258
- newUniforms = rest;
16259
- } else if (targetScope === "root") {
16260
- for (const [key, value] of Object.entries(state.uniforms)) {
16261
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16262
- }
16263
- }
16264
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16265
- });
16266
- },
15448
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
16267
15449
  [store]
16268
15450
  );
16269
15451
  const inputForMemoization = React.useMemo(() => {
16270
15452
  let raw = creatorOrScope;
16271
15453
  if (is.fun(creatorOrScope)) {
16272
- const wrappedState = createLazyCreatorState(store.getState());
15454
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16273
15455
  raw = creatorOrScope(wrappedState);
16274
15456
  }
16275
15457
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -16283,80 +15465,44 @@ function useUniforms(creatorOrScope, scope) {
16283
15465
  }, [creatorOrScope, store]);
16284
15466
  const memoizedInput = useCompareMemoize(inputForMemoization);
16285
15467
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16286
- const storeUniforms = useThree((s) => s.uniforms);
16287
- const hmrVersion = useThree((s) => s._hmrVersion);
16288
- const readerDep = isReader ? storeUniforms : null;
16289
- const creatorDep = isReader ? null : hmrVersion;
16290
- const uniforms = React.useMemo(() => {
16291
- if (memoizedInput === void 0) {
16292
- return storeUniforms;
16293
- }
16294
- if (typeof memoizedInput === "string") {
16295
- const scopeData = storeUniforms[memoizedInput];
16296
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
16297
- return {};
16298
- }
16299
- const state = store.getState();
16300
- const set = store.setState;
16301
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
16302
- throw new Error("Invalid uniform input");
16303
- }
16304
- const created = memoizedInput;
16305
- const result = {};
16306
- let hasNewUniforms = false;
16307
- let targetRecord = state.uniforms;
16308
- if (scope) {
16309
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
16310
- targetRecord = state.uniforms[scope];
16311
- }
16312
- for (const [name, node] of Object.entries(created)) {
16313
- if (targetRecord[name]) {
16314
- result[name] = targetRecord[name];
16315
- const existingVal = result[name].value;
16316
- const newVal = vectorize(node);
16317
- let equals = newVal === existingVal;
16318
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
16319
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
16320
- equals = vectorEquals(existingVal, newVal);
16321
- } else if (isSameThreeType(existingVal, newVal)) {
16322
- equals = existingVal.equals(newVal);
16323
- }
15468
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15469
+ const created = useScopedResource({
15470
+ store,
15471
+ kind: "uniforms",
15472
+ scope: isReader ? void 0 : scope,
15473
+ isLeaf: isUniformNode$1,
15474
+ input: memoizedInput,
15475
+ create: () => {
15476
+ if (isReader) return {};
15477
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15478
+ return memoizedInput;
15479
+ },
15480
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15481
+ reconcile: (existing, candidate) => {
15482
+ const existingVal = existing.value;
15483
+ const newVal = vectorize(candidate);
15484
+ let equals = newVal === existingVal;
15485
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15486
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15487
+ equals = vectorEquals(existingVal, newVal);
15488
+ } else if (isSameThreeType(existingVal, newVal)) {
15489
+ equals = existingVal.equals(newVal);
16324
15490
  }
16325
- if (!equals) result[name].value = newVal;
16326
- } else {
16327
- result[name] = createUniform(name, node, scope);
16328
- hasNewUniforms = true;
16329
- }
16330
- }
16331
- if (hasNewUniforms) {
16332
- if (scope) {
16333
- set((s) => ({
16334
- uniforms: {
16335
- ...s.uniforms,
16336
- [scope]: { ...s.uniforms[scope], ...result }
16337
- }
16338
- }));
16339
- } else {
16340
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
16341
15491
  }
15492
+ if (!equals) existing.value = newVal;
16342
15493
  }
16343
- return result;
16344
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15494
+ });
15495
+ let uniforms = created;
15496
+ if (memoizedInput === void 0) {
15497
+ uniforms = storeUniforms;
15498
+ } else if (typeof memoizedInput === "string") {
15499
+ const scopeData = storeUniforms[memoizedInput];
15500
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15501
+ }
16345
15502
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16346
15503
  }
16347
15504
  function rebuildAllUniforms(store, scope) {
16348
- store.setState((state) => {
16349
- let newUniforms = {};
16350
- if (scope && scope !== "root") {
16351
- const { [scope]: _, ...rest } = state.uniforms;
16352
- newUniforms = rest;
16353
- } else if (scope === "root") {
16354
- for (const [key, value] of Object.entries(state.uniforms)) {
16355
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16356
- }
16357
- }
16358
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16359
- });
15505
+ rebuildResource(store, "uniforms", scope);
16360
15506
  }
16361
15507
  function removeUniforms(set, names, scope) {
16362
15508
  set((state) => {
@@ -16420,191 +15566,91 @@ function isSameThreeType(a, b) {
16420
15566
  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;
16421
15567
  }
16422
15568
 
15569
+ const uniformOf = tsl.uniform;
16423
15570
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16424
15571
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16425
15572
  function useUniform(name, value) {
16426
15573
  const store = useStore();
16427
- const hmrVersion = useThree((s) => s._hmrVersion);
16428
- return React.useMemo(() => {
16429
- const state = store.getState();
16430
- const set = store.setState;
16431
- const existing = state.uniforms[name];
16432
- if (existing && isUniformNode(existing)) {
15574
+ const registered = useScopedResource({
15575
+ store,
15576
+ kind: "uniforms",
15577
+ scope: void 0,
15578
+ isLeaf: isUniformNode,
15579
+ input: name,
15580
+ create: () => value === void 0 ? {} : { [name]: value },
15581
+ prepare: createNamedUniform,
15582
+ reconcile: (existing2) => {
16433
15583
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
16434
- existing.value = typeof value === "string" ? new webgpu.Color(value) : value;
15584
+ existing2.value = typeof value === "string" ? new webgpu.Color(value) : value;
16435
15585
  }
16436
- return existing;
16437
- }
16438
- if (value === void 0) {
16439
- throw new Error(
16440
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
16441
- );
16442
- }
16443
- if (isUniformNode(value)) {
16444
- const node2 = value;
16445
- if (typeof node2.setName === "function") {
16446
- node2.setName(name);
16447
- }
16448
- set((s) => ({
16449
- uniforms: { ...s.uniforms, [name]: node2 }
16450
- }));
16451
- return node2;
16452
- }
16453
- let node;
16454
- if (isTSLNode$1(value)) {
16455
- node = tsl.uniform(value);
16456
- } else if (typeof value === "string") {
16457
- node = tsl.uniform(new webgpu.Color(value));
16458
- } else {
16459
- node = tsl.uniform(value);
16460
- }
16461
- if (typeof node.setName === "function") {
16462
- node.setName(name);
16463
15586
  }
16464
- set((s) => ({
16465
- uniforms: {
16466
- ...s.uniforms,
16467
- [name]: node
16468
- }
16469
- }));
16470
- return node;
16471
- }, [store, name, hmrVersion]);
15587
+ });
15588
+ if (registered[name]) return registered[name];
15589
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15590
+ if (existing && isUniformNode(existing)) return existing;
15591
+ throw new Error(
15592
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15593
+ );
15594
+ }
15595
+ function createNamedUniform(name, value) {
15596
+ let node;
15597
+ if (isUniformNode(value)) {
15598
+ node = value;
15599
+ } else if (isTSLNode$1(value)) {
15600
+ node = uniformOf(value);
15601
+ } else if (typeof value === "string") {
15602
+ node = tsl.uniform(new webgpu.Color(value));
15603
+ } else {
15604
+ node = uniformOf(value);
15605
+ }
15606
+ if (typeof node.setName === "function") {
15607
+ node.setName(name);
15608
+ }
15609
+ return node;
16472
15610
  }
16473
15611
 
16474
15612
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16475
15613
  function useNodes(creatorOrScope, scope) {
16476
- const store = useStore();
15614
+ const store = usePrimaryStore();
16477
15615
  const removeNodes2 = React.useCallback(
16478
- (names, targetScope) => {
16479
- const nameArray = Array.isArray(names) ? names : [names];
16480
- store.setState((state) => {
16481
- if (targetScope) {
16482
- const currentScope = { ...state.nodes[targetScope] };
16483
- for (const name of nameArray) delete currentScope[name];
16484
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
16485
- }
16486
- const nodes2 = { ...state.nodes };
16487
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
16488
- return { nodes: nodes2 };
16489
- });
16490
- },
15616
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
16491
15617
  [store]
16492
15618
  );
16493
15619
  const clearNodes = React.useCallback(
16494
- (targetScope) => {
16495
- store.setState((state) => {
16496
- if (targetScope && targetScope !== "root") {
16497
- const { [targetScope]: _, ...rest } = state.nodes;
16498
- return { nodes: rest };
16499
- }
16500
- if (targetScope === "root") {
16501
- const nodes2 = {};
16502
- for (const [key, value] of Object.entries(state.nodes)) {
16503
- if (!isTSLNode(value)) nodes2[key] = value;
16504
- }
16505
- return { nodes: nodes2 };
16506
- }
16507
- return { nodes: {} };
16508
- });
16509
- },
15620
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
16510
15621
  [store]
16511
15622
  );
16512
15623
  const rebuildNodes = React.useCallback(
16513
- (targetScope) => {
16514
- store.setState((state) => {
16515
- let newNodes = state.nodes;
16516
- if (targetScope && targetScope !== "root") {
16517
- const { [targetScope]: _, ...rest } = state.nodes;
16518
- newNodes = rest;
16519
- } else if (targetScope === "root") {
16520
- newNodes = {};
16521
- for (const [key, value] of Object.entries(state.nodes)) {
16522
- if (!isTSLNode(value)) newNodes[key] = value;
16523
- }
16524
- } else {
16525
- newNodes = {};
16526
- }
16527
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16528
- });
16529
- },
15624
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
16530
15625
  [store]
16531
15626
  );
16532
15627
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16533
- const storeNodes = useThree((s) => s.nodes);
16534
- const hmrVersion = useThree((s) => s._hmrVersion);
16535
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16536
- const readerDep = isReader ? storeNodes : null;
16537
- const creatorDep = isReader ? null : hmrVersion;
16538
- const nodes = React.useMemo(() => {
16539
- if (creatorOrScope === void 0) {
16540
- return storeNodes;
16541
- }
16542
- if (typeof creatorOrScope === "string") {
16543
- const scopeData = storeNodes[creatorOrScope];
16544
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
16545
- return {};
16546
- }
16547
- const state = store.getState();
16548
- const set = store.setState;
16549
- const creator = creatorOrScope;
16550
- const wrappedState = createLazyCreatorState(state);
16551
- const created = creator(wrappedState);
16552
- const result = {};
16553
- let hasNewNodes = false;
16554
- if (scope) {
16555
- const currentScope = state.nodes[scope] ?? {};
16556
- for (const [name, node] of Object.entries(created)) {
16557
- if (currentScope[name]) {
16558
- result[name] = currentScope[name];
16559
- } else {
16560
- node.setName?.(`${scope}.${name}`);
16561
- result[name] = node;
16562
- hasNewNodes = true;
16563
- }
16564
- }
16565
- if (hasNewNodes) {
16566
- set((s) => ({
16567
- nodes: {
16568
- ...s.nodes,
16569
- [scope]: { ...s.nodes[scope], ...result }
16570
- }
16571
- }));
16572
- }
16573
- return result;
16574
- }
16575
- for (const [name, node] of Object.entries(created)) {
16576
- const existing = state.nodes[name];
16577
- if (existing && isTSLNode(existing)) {
16578
- result[name] = existing;
16579
- } else {
16580
- node.setName?.(name);
16581
- result[name] = node;
16582
- hasNewNodes = true;
16583
- }
16584
- }
16585
- if (hasNewNodes) {
16586
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15628
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15629
+ const created = useScopedResource({
15630
+ store,
15631
+ kind: "nodes",
15632
+ scope: isReader ? void 0 : scope,
15633
+ isLeaf: isTSLNode,
15634
+ create: () => {
15635
+ if (isReader) return {};
15636
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15637
+ },
15638
+ prepare: (name, node) => {
15639
+ node.setName?.(scope ? `${scope}.${name}` : name);
15640
+ return node;
16587
15641
  }
16588
- return result;
16589
- }, [store, scopeDep, readerDep, creatorDep]);
15642
+ });
15643
+ let nodes = created;
15644
+ if (creatorOrScope === void 0) {
15645
+ nodes = storeNodes;
15646
+ } else if (typeof creatorOrScope === "string") {
15647
+ const scopeData = storeNodes[creatorOrScope];
15648
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15649
+ }
16590
15650
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16591
15651
  }
16592
15652
  function rebuildAllNodes(store, scope) {
16593
- store.setState((state) => {
16594
- let newNodes = state.nodes;
16595
- if (scope && scope !== "root") {
16596
- const { [scope]: _, ...rest } = state.nodes;
16597
- newNodes = rest;
16598
- } else if (scope === "root") {
16599
- newNodes = {};
16600
- for (const [key, value] of Object.entries(state.nodes)) {
16601
- if (!isTSLNode(value)) newNodes[key] = value;
16602
- }
16603
- } else {
16604
- newNodes = {};
16605
- }
16606
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16607
- });
15653
+ rebuildResource(store, "nodes", scope);
16608
15654
  }
16609
15655
  function removeNodes(set, names, scope) {
16610
15656
  set((state) => {
@@ -16634,13 +15680,13 @@ function clearRootNodes(set) {
16634
15680
  });
16635
15681
  }
16636
15682
  function useLocalNodes(creator) {
16637
- const store = useStore();
16638
- const uniforms = useThree((s) => s.uniforms);
16639
- const nodes = useThree((s) => s.nodes);
16640
- const textures = useThree((s) => s.textures);
16641
- const hmrVersion = useThree((s) => s._hmrVersion);
15683
+ const store = usePrimaryStore();
15684
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15685
+ const nodes = usePrimaryThree((s) => s.nodes);
15686
+ const textures = usePrimaryThree((s) => s.textures);
15687
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16642
15688
  return React.useMemo(() => {
16643
- const wrappedState = createLazyCreatorState(store.getState());
15689
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16644
15690
  return creator(wrappedState);
16645
15691
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
16646
15692
  }
@@ -16659,60 +15705,17 @@ const disposeBuffer = (buffer) => {
16659
15705
  }
16660
15706
  };
16661
15707
  function useBuffers(creatorOrScope, scope) {
16662
- const store = useStore();
15708
+ const store = usePrimaryStore();
16663
15709
  const removeBuffers = React.useCallback(
16664
- (names, targetScope) => {
16665
- const nameArray = Array.isArray(names) ? names : [names];
16666
- store.setState((state) => {
16667
- if (targetScope) {
16668
- const currentScope = { ...state.buffers[targetScope] };
16669
- for (const name of nameArray) delete currentScope[name];
16670
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
16671
- }
16672
- const buffers2 = { ...state.buffers };
16673
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
16674
- return { buffers: buffers2 };
16675
- });
16676
- },
15710
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
16677
15711
  [store]
16678
15712
  );
16679
15713
  const clearBuffers = React.useCallback(
16680
- (targetScope) => {
16681
- store.setState((state) => {
16682
- if (targetScope && targetScope !== "root") {
16683
- const { [targetScope]: _, ...rest } = state.buffers;
16684
- return { buffers: rest };
16685
- }
16686
- if (targetScope === "root") {
16687
- const buffers2 = {};
16688
- for (const [key, value] of Object.entries(state.buffers)) {
16689
- if (!isBufferLike(value)) buffers2[key] = value;
16690
- }
16691
- return { buffers: buffers2 };
16692
- }
16693
- return { buffers: {} };
16694
- });
16695
- },
15714
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
16696
15715
  [store]
16697
15716
  );
16698
15717
  const rebuildBuffers = React.useCallback(
16699
- (targetScope) => {
16700
- store.setState((state) => {
16701
- let newBuffers = state.buffers;
16702
- if (targetScope && targetScope !== "root") {
16703
- const { [targetScope]: _, ...rest } = state.buffers;
16704
- newBuffers = rest;
16705
- } else if (targetScope === "root") {
16706
- newBuffers = {};
16707
- for (const [key, value] of Object.entries(state.buffers)) {
16708
- if (!isBufferLike(value)) newBuffers[key] = value;
16709
- }
16710
- } else {
16711
- newBuffers = {};
16712
- }
16713
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16714
- });
16715
- },
15718
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
16716
15719
  [store]
16717
15720
  );
16718
15721
  const disposeBuffers = React.useCallback(
@@ -16730,85 +15733,34 @@ function useBuffers(creatorOrScope, scope) {
16730
15733
  [store, removeBuffers]
16731
15734
  );
16732
15735
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16733
- const storeBuffers = useThree((s) => s.buffers);
16734
- const hmrVersion = useThree((s) => s._hmrVersion);
16735
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16736
- const readerDep = isReader ? storeBuffers : null;
16737
- const creatorDep = isReader ? null : hmrVersion;
16738
- const buffers = React.useMemo(() => {
16739
- if (creatorOrScope === void 0) {
16740
- return storeBuffers;
16741
- }
16742
- if (typeof creatorOrScope === "string") {
16743
- const scopeData = storeBuffers[creatorOrScope];
16744
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
16745
- return {};
16746
- }
16747
- const state = store.getState();
16748
- const set = store.setState;
16749
- const creator = creatorOrScope;
16750
- const wrappedState = createLazyCreatorState(state);
16751
- const created = creator(wrappedState);
16752
- const result = {};
16753
- let hasNewBuffers = false;
16754
- if (scope) {
16755
- const currentScope = state.buffers[scope] ?? {};
16756
- for (const [name, buffer] of Object.entries(created)) {
16757
- if (currentScope[name]) {
16758
- result[name] = currentScope[name];
16759
- } else {
16760
- if ("setName" in buffer && typeof buffer.setName === "function") {
16761
- buffer.setName(`${scope}.${name}`);
16762
- }
16763
- result[name] = buffer;
16764
- hasNewBuffers = true;
16765
- }
16766
- }
16767
- if (hasNewBuffers) {
16768
- set((s) => ({
16769
- buffers: {
16770
- ...s.buffers,
16771
- [scope]: { ...s.buffers[scope], ...result }
16772
- }
16773
- }));
16774
- }
16775
- return result;
16776
- }
16777
- for (const [name, buffer] of Object.entries(created)) {
16778
- const existing = state.buffers[name];
16779
- if (existing && isBufferLike(existing)) {
16780
- result[name] = existing;
16781
- } else {
16782
- if ("setName" in buffer && typeof buffer.setName === "function") {
16783
- buffer.setName(name);
16784
- }
16785
- result[name] = buffer;
16786
- hasNewBuffers = true;
15736
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15737
+ const created = useScopedResource({
15738
+ store,
15739
+ kind: "buffers",
15740
+ scope: isReader ? void 0 : scope,
15741
+ isLeaf: isBufferLike,
15742
+ create: () => {
15743
+ if (isReader) return {};
15744
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15745
+ },
15746
+ prepare: (name, buffer) => {
15747
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15748
+ buffer.setName(scope ? `${scope}.${name}` : name);
16787
15749
  }
15750
+ return buffer;
16788
15751
  }
16789
- if (hasNewBuffers) {
16790
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
16791
- }
16792
- return result;
16793
- }, [store, scopeDep, readerDep, creatorDep]);
15752
+ });
15753
+ let buffers = created;
15754
+ if (creatorOrScope === void 0) {
15755
+ buffers = storeBuffers;
15756
+ } else if (typeof creatorOrScope === "string") {
15757
+ const scopeData = storeBuffers[creatorOrScope];
15758
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15759
+ }
16794
15760
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16795
15761
  }
16796
15762
  function rebuildAllBuffers(store, scope) {
16797
- store.setState((state) => {
16798
- let newBuffers = state.buffers;
16799
- if (scope && scope !== "root") {
16800
- const { [scope]: _, ...rest } = state.buffers;
16801
- newBuffers = rest;
16802
- } else if (scope === "root") {
16803
- newBuffers = {};
16804
- for (const [key, value] of Object.entries(state.buffers)) {
16805
- if (!isBufferLike(value)) newBuffers[key] = value;
16806
- }
16807
- } else {
16808
- newBuffers = {};
16809
- }
16810
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16811
- });
15763
+ rebuildResource(store, "buffers", scope);
16812
15764
  }
16813
15765
 
16814
15766
  const isStorageLike = (value) => {
@@ -16825,60 +15777,17 @@ const disposeStorage = (storage) => {
16825
15777
  }
16826
15778
  };
16827
15779
  function useGPUStorage(creatorOrScope, scope) {
16828
- const store = useStore();
15780
+ const store = usePrimaryStore();
16829
15781
  const removeStorage = React.useCallback(
16830
- (names, targetScope) => {
16831
- const nameArray = Array.isArray(names) ? names : [names];
16832
- store.setState((state) => {
16833
- if (targetScope) {
16834
- const currentScope = { ...state.gpuStorage[targetScope] };
16835
- for (const name of nameArray) delete currentScope[name];
16836
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
16837
- }
16838
- const gpuStorage2 = { ...state.gpuStorage };
16839
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
16840
- return { gpuStorage: gpuStorage2 };
16841
- });
16842
- },
15782
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
16843
15783
  [store]
16844
15784
  );
16845
15785
  const clearStorage = React.useCallback(
16846
- (targetScope) => {
16847
- store.setState((state) => {
16848
- if (targetScope && targetScope !== "root") {
16849
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16850
- return { gpuStorage: rest };
16851
- }
16852
- if (targetScope === "root") {
16853
- const gpuStorage2 = {};
16854
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16855
- if (!isStorageLike(value)) gpuStorage2[key] = value;
16856
- }
16857
- return { gpuStorage: gpuStorage2 };
16858
- }
16859
- return { gpuStorage: {} };
16860
- });
16861
- },
15786
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
16862
15787
  [store]
16863
15788
  );
16864
15789
  const rebuildStorage = React.useCallback(
16865
- (targetScope) => {
16866
- store.setState((state) => {
16867
- let newStorage = state.gpuStorage;
16868
- if (targetScope && targetScope !== "root") {
16869
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16870
- newStorage = rest;
16871
- } else if (targetScope === "root") {
16872
- newStorage = {};
16873
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16874
- if (!isStorageLike(value)) newStorage[key] = value;
16875
- }
16876
- } else {
16877
- newStorage = {};
16878
- }
16879
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16880
- });
16881
- },
15790
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
16882
15791
  [store]
16883
15792
  );
16884
15793
  const disposeStorageFn = React.useCallback(
@@ -16896,73 +15805,34 @@ function useGPUStorage(creatorOrScope, scope) {
16896
15805
  [store, removeStorage]
16897
15806
  );
16898
15807
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16899
- const storeStorage = useThree((s) => s.gpuStorage);
16900
- const hmrVersion = useThree((s) => s._hmrVersion);
16901
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16902
- const readerDep = isReader ? storeStorage : null;
16903
- const creatorDep = isReader ? null : hmrVersion;
16904
- const gpuStorage = React.useMemo(() => {
16905
- if (creatorOrScope === void 0) {
16906
- return storeStorage;
16907
- }
16908
- if (typeof creatorOrScope === "string") {
16909
- const scopeData = storeStorage[creatorOrScope];
16910
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
16911
- return {};
16912
- }
16913
- const state = store.getState();
16914
- const set = store.setState;
16915
- const creator = creatorOrScope;
16916
- const wrappedState = createLazyCreatorState(state);
16917
- const created = creator(wrappedState);
16918
- const result = {};
16919
- let hasNewStorage = false;
16920
- if (scope) {
16921
- const currentScope = state.gpuStorage[scope] ?? {};
16922
- for (const [name, storage] of Object.entries(created)) {
16923
- if (currentScope[name]) {
16924
- result[name] = currentScope[name];
16925
- } else {
16926
- if ("setName" in storage && typeof storage.setName === "function") {
16927
- storage.setName(`${scope}.${name}`);
16928
- }
16929
- if ("name" in storage && typeof storage.name === "string") {
16930
- storage.name = `${scope}.${name}`;
16931
- }
16932
- result[name] = storage;
16933
- hasNewStorage = true;
16934
- }
16935
- }
16936
- if (hasNewStorage) {
16937
- set((s) => ({
16938
- gpuStorage: {
16939
- ...s.gpuStorage,
16940
- [scope]: { ...s.gpuStorage[scope], ...result }
16941
- }
16942
- }));
15808
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15809
+ const created = useScopedResource({
15810
+ store,
15811
+ kind: "gpuStorage",
15812
+ scope: isReader ? void 0 : scope,
15813
+ isLeaf: isStorageLike,
15814
+ create: () => {
15815
+ if (isReader) return {};
15816
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15817
+ },
15818
+ prepare: (name, storage) => {
15819
+ const label = scope ? `${scope}.${name}` : name;
15820
+ if ("setName" in storage && typeof storage.setName === "function") {
15821
+ storage.setName(label);
16943
15822
  }
16944
- return result;
16945
- }
16946
- for (const [name, storage] of Object.entries(created)) {
16947
- const existing = state.gpuStorage[name];
16948
- if (existing && isStorageLike(existing)) {
16949
- result[name] = existing;
16950
- } else {
16951
- if ("setName" in storage && typeof storage.setName === "function") {
16952
- storage.setName(name);
16953
- }
16954
- if ("name" in storage && typeof storage.name === "string") {
16955
- storage.name = name;
16956
- }
16957
- result[name] = storage;
16958
- hasNewStorage = true;
15823
+ if ("name" in storage && typeof storage.name === "string") {
15824
+ storage.name = label;
16959
15825
  }
15826
+ return storage;
16960
15827
  }
16961
- if (hasNewStorage) {
16962
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
16963
- }
16964
- return result;
16965
- }, [store, scopeDep, readerDep, creatorDep]);
15828
+ });
15829
+ let gpuStorage = created;
15830
+ if (creatorOrScope === void 0) {
15831
+ gpuStorage = storeStorage;
15832
+ } else if (typeof creatorOrScope === "string") {
15833
+ const scopeData = storeStorage[creatorOrScope];
15834
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15835
+ }
16966
15836
  return {
16967
15837
  ...gpuStorage,
16968
15838
  removeStorage,
@@ -16972,21 +15842,7 @@ function useGPUStorage(creatorOrScope, scope) {
16972
15842
  };
16973
15843
  }
16974
15844
  function rebuildAllStorage(store, scope) {
16975
- store.setState((state) => {
16976
- let newStorage = state.gpuStorage;
16977
- if (scope && scope !== "root") {
16978
- const { [scope]: _, ...rest } = state.gpuStorage;
16979
- newStorage = rest;
16980
- } else if (scope === "root") {
16981
- newStorage = {};
16982
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16983
- if (!isStorageLike(value)) newStorage[key] = value;
16984
- }
16985
- } else {
16986
- newStorage = {};
16987
- }
16988
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16989
- });
15845
+ rebuildResource(store, "gpuStorage", scope);
16990
15846
  }
16991
15847
 
16992
15848
  function useRenderPipeline(mainCB, setupCB) {
@@ -17027,12 +15883,12 @@ function useRenderPipeline(mainCB, setupCB) {
17027
15883
  const state = store.getState();
17028
15884
  const set = store.setState;
17029
15885
  try {
17030
- let pp = state.renderPipeline;
15886
+ let pipeline = state.renderPipeline;
17031
15887
  let currentPasses = { ...state.passes };
17032
- let justCreatedPP = false;
17033
- if (!pp) {
17034
- pp = new webgpu.PostProcessing(renderer);
17035
- justCreatedPP = true;
15888
+ let justCreatedPipeline = false;
15889
+ if (!pipeline) {
15890
+ pipeline = new webgpu.RenderPipeline(renderer);
15891
+ justCreatedPipeline = true;
17036
15892
  }
17037
15893
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
17038
15894
  let scenePass;
@@ -17043,9 +15899,9 @@ function useRenderPipeline(mainCB, setupCB) {
17043
15899
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
17044
15900
  }
17045
15901
  currentPasses.scenePass = scenePass;
17046
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
17047
- set({ renderPipeline: pp, passes: currentPasses });
17048
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15902
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15903
+ set({ renderPipeline: pipeline, passes: currentPasses });
15904
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
17049
15905
  if (shouldRunCallbacks) {
17050
15906
  if (setupCBRef.current) {
17051
15907
  const freshState = store.getState();
@@ -17066,7 +15922,7 @@ function useRenderPipeline(mainCB, setupCB) {
17066
15922
  callbacksRanRef.current = true;
17067
15923
  }
17068
15924
  } catch (error) {
17069
- console.error("[useRenderPipeline] Setup error:", error);
15925
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17070
15926
  }
17071
15927
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17072
15928
  const passes = useThree((s) => s.passes);
@@ -17084,6 +15940,8 @@ function useRenderPipeline(mainCB, setupCB) {
17084
15940
 
17085
15941
  extend(THREE);
17086
15942
 
15943
+ exports.Scheduler = scheduler.Scheduler;
15944
+ exports.getScheduler = scheduler.getScheduler;
17087
15945
  exports.Block = Block;
17088
15946
  exports.Canvas = Canvas;
17089
15947
  exports.Environment = Environment;
@@ -17099,7 +15957,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
17099
15957
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
17100
15958
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
17101
15959
  exports.RESERVED_PROPS = RESERVED_PROPS;
17102
- exports.Scheduler = Scheduler;
17103
15960
  exports.Texture = Texture;
17104
15961
  exports._roots = _roots;
17105
15962
  exports.act = act;
@@ -17135,7 +15992,6 @@ exports.getInstanceProps = getInstanceProps;
17135
15992
  exports.getPrimary = getPrimary;
17136
15993
  exports.getPrimaryIds = getPrimaryIds;
17137
15994
  exports.getRootState = getRootState;
17138
- exports.getScheduler = getScheduler;
17139
15995
  exports.getUuidPrefix = getUuidPrefix;
17140
15996
  exports.hasConstructor = hasConstructor;
17141
15997
  exports.hasPrimary = hasPrimary;