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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,10 +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);
462
- const act = React__namespace["act"];
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);
463
467
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
464
468
  function useMutableCallback(fn) {
465
469
  const ref = React__namespace.useRef(fn);
@@ -490,7 +494,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
490
494
  return _a = class extends React__namespace.Component {
491
495
  constructor() {
492
496
  super(...arguments);
493
- __publicField$3(this, "state", { error: false });
497
+ __publicField$1(this, "state", { error: false });
494
498
  }
495
499
  componentDidCatch(err) {
496
500
  this.props.set(err);
@@ -498,7 +502,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
498
502
  render() {
499
503
  return this.state.error ? null : this.props.children;
500
504
  }
501
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
505
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
502
506
  })();
503
507
 
504
508
  const is = {
@@ -635,8 +639,7 @@ function prepare(target, root, type, props) {
635
639
  object,
636
640
  eventCount: 0,
637
641
  handlers: {},
638
- isHidden: false,
639
- deferredRefs: []
642
+ isHidden: false
640
643
  };
641
644
  if (object) object.__r3f = instance;
642
645
  }
@@ -793,6 +796,17 @@ function unregisterVisibility(store, object) {
793
796
  internal.visibilityRegistry.delete(object.uuid);
794
797
  internal.occlusionCache.delete(object);
795
798
  }
799
+ function updateVisibilityHandlers(store, object, handlers) {
800
+ const { internal } = store.getState();
801
+ const entry = internal.visibilityRegistry.get(object.uuid);
802
+ if (!entry) return false;
803
+ entry.handlers = handlers;
804
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
805
+ object.occlusionTest = true;
806
+ enableOcclusion(store);
807
+ }
808
+ return true;
809
+ }
796
810
  function checkVisibility(state) {
797
811
  const { internal, camera } = state;
798
812
  const registry = internal.visibilityRegistry;
@@ -953,9 +967,9 @@ function diffProps(instance, newProps) {
953
967
  const { root, key } = resolve(instance.object, prop);
954
968
  if (root.constructor && root.constructor.length === 0) {
955
969
  const ctor = getMemoizedPrototype(root);
956
- if (!is.und(ctor)) changedProps[key] = ctor[key];
970
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
957
971
  } else {
958
- changedProps[key] = 0;
972
+ changedProps[prop] = 0;
959
973
  }
960
974
  }
961
975
  return changedProps;
@@ -980,10 +994,7 @@ function applyProps(object, props) {
980
994
  continue;
981
995
  }
982
996
  if (value === void 0) continue;
983
- if (isFromRef(value)) {
984
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
985
- continue;
986
- }
997
+ if (isFromRef(value)) continue;
987
998
  if (isOnce(value)) {
988
999
  if (instance?.appliedOnce?.has(prop)) continue;
989
1000
  if (instance) {
@@ -1019,6 +1030,19 @@ function applyProps(object, props) {
1019
1030
  } else if (isVectorLike(target) && is.num(value)) {
1020
1031
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1021
1032
  else target.set(value);
1033
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1034
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1035
+ const uniforms = root.uniforms;
1036
+ const nextUniforms = value;
1037
+ for (const name in nextUniforms) {
1038
+ const uniform = nextUniforms[name];
1039
+ const targetUniform = uniforms[name];
1040
+ if (targetUniform) Object.assign(targetUniform, uniform);
1041
+ else {
1042
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1043
+ uniforms[name] = nextUniform;
1044
+ }
1045
+ }
1022
1046
  } else {
1023
1047
  root[key] = value;
1024
1048
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1037,6 +1061,9 @@ function applyProps(object, props) {
1037
1061
  if (instance.eventCount && object2.raycast !== null) {
1038
1062
  rootState.internal.interaction.push(object2);
1039
1063
  }
1064
+ }
1065
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1066
+ const object2 = instance.object;
1040
1067
  const root = findInitialRoot(instance);
1041
1068
  const visibilityHandlers = {
1042
1069
  onFramed: instance.handlers.onFramed,
@@ -1044,7 +1071,9 @@ function applyProps(object, props) {
1044
1071
  onVisible: instance.handlers.onVisible
1045
1072
  };
1046
1073
  if (hasVisibilityHandlers(visibilityHandlers)) {
1047
- registerVisibility(root, object2, visibilityHandlers);
1074
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1075
+ registerVisibility(root, object2, visibilityHandlers);
1076
+ }
1048
1077
  } else {
1049
1078
  unregisterVisibility(root, object2);
1050
1079
  }
@@ -1572,6 +1601,7 @@ function createPointerEvents(store) {
1572
1601
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1573
1602
  }
1574
1603
  },
1604
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1575
1605
  registerPointer: (config) => {
1576
1606
  const pointerId = nextXRPointerId++;
1577
1607
  xrPointers.set(pointerId, config);
@@ -1658,1229 +1688,206 @@ function notifyAlpha({ message, link }) {
1658
1688
  }
1659
1689
  }
1660
1690
 
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
- }
1691
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1692
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1693
+ if (!stack) return false;
1694
+ const caller = stack.split("\n")[callerDepth] ?? "";
1695
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1787
1696
  }
1788
1697
 
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);
1698
+ const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1699
+ const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
1700
+ const createStore = (invalidate, advance) => {
1701
+ const rootStore = traditional.createWithEqualityFn((set, get) => {
1702
+ const position = new webgpu.Vector3();
1703
+ const defaultTarget = new webgpu.Vector3();
1704
+ const tempTarget = new webgpu.Vector3();
1705
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1706
+ const { width, height, top, left } = size;
1707
+ const aspect = width / height;
1708
+ if (target.isVector3) tempTarget.copy(target);
1709
+ else tempTarget.set(...target);
1710
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1711
+ if (isOrthographicCamera(camera)) {
1712
+ return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
1713
+ } else {
1714
+ const fov = camera.fov * Math.PI / 180;
1715
+ const h = 2 * Math.tan(fov / 2) * distance;
1716
+ const w = h * (width / height);
1717
+ return { width: w, height: h, top, left, factor: width / w, distance, aspect };
1853
1718
  }
1854
1719
  }
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);
1720
+ let performanceTimeout = void 0;
1721
+ const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
1722
+ const pointer = new webgpu.Vector2();
1723
+ const rootState = {
1724
+ set,
1725
+ get,
1726
+ // Mock objects that have to be configured
1727
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1728
+ primaryStore: null,
1729
+ gl: null,
1730
+ renderer: null,
1731
+ camera: null,
1732
+ frustum: new webgpu.Frustum(),
1733
+ autoUpdateFrustum: true,
1734
+ raycaster: null,
1735
+ events: {
1736
+ priority: 1,
1737
+ enabled: true,
1738
+ connected: false,
1739
+ frameTimedRaycasts: true,
1740
+ alwaysFireOnScroll: true,
1741
+ updateOnFrame: false
1742
+ },
1743
+ scene: null,
1744
+ rootScene: null,
1745
+ xr: null,
1746
+ inspector: null,
1747
+ invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1748
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1749
+ textureColorSpace: webgpu.SRGBColorSpace,
1750
+ isLegacy: false,
1751
+ webGPUSupported: false,
1752
+ isNative: false,
1753
+ controls: null,
1754
+ pointer,
1755
+ mouse: pointer,
1756
+ frameloop: "always",
1757
+ onPointerMissed: void 0,
1758
+ onDragOverMissed: void 0,
1759
+ onDropMissed: void 0,
1760
+ performance: {
1761
+ current: 1,
1762
+ min: 0.5,
1763
+ max: 1,
1764
+ debounce: 200,
1765
+ regress: () => {
1766
+ const state2 = get();
1767
+ if (performanceTimeout) clearTimeout(performanceTimeout);
1768
+ if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
1769
+ performanceTimeout = setTimeout(
1770
+ () => setPerformanceCurrent(get().performance.max),
1771
+ state2.performance.debounce
1772
+ );
1773
+ }
1774
+ },
1775
+ size: { width: 0, height: 0, top: 0, left: 0 },
1776
+ viewport: {
1777
+ initialDpr: 0,
1778
+ dpr: 0,
1779
+ width: 0,
1780
+ height: 0,
1781
+ top: 0,
1782
+ left: 0,
1783
+ aspect: 0,
1784
+ distance: 0,
1785
+ factor: 0,
1786
+ getCurrentViewport
1787
+ },
1788
+ setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1789
+ setSize: (width, height, top, left) => {
1790
+ const state2 = get();
1791
+ if (width === void 0) {
1792
+ set({ _sizeImperative: false });
1793
+ if (state2._sizeProps) {
1794
+ const { width: propW, height: propH } = state2._sizeProps;
1795
+ if (propW !== void 0 || propH !== void 0) {
1796
+ const currentSize = state2.size;
1797
+ const newSize = {
1798
+ width: propW ?? currentSize.width,
1799
+ height: propH ?? currentSize.height,
1800
+ top: currentSize.top,
1801
+ left: currentSize.left
1802
+ };
1803
+ set((s) => ({
1804
+ size: newSize,
1805
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1806
+ }));
1807
+ scheduler.getScheduler().invalidate();
1808
+ }
1809
+ }
1810
+ return;
1811
+ }
1812
+ const w = width;
1813
+ const h = height ?? width;
1814
+ const t = top ?? state2.size.top;
1815
+ const l = left ?? state2.size.left;
1816
+ const size = { width: w, height: h, top: t, left: l };
1817
+ set((s) => ({
1818
+ size,
1819
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1820
+ _sizeImperative: true
1821
+ }));
1822
+ scheduler.getScheduler().invalidate();
1823
+ },
1824
+ setDpr: (dpr) => set((state2) => {
1825
+ const resolved = calculateDpr(dpr);
1826
+ return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
1827
+ }),
1828
+ setFrameloop: (frameloop = "always") => {
1829
+ set(() => ({ frameloop }));
1830
+ scheduler.getScheduler().frameloop = frameloop;
1831
+ },
1832
+ setError: (error) => set(() => ({ error })),
1833
+ error: null,
1834
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1835
+ uniforms: {},
1836
+ nodes: {},
1837
+ buffers: {},
1838
+ gpuStorage: {},
1839
+ textures: /* @__PURE__ */ new Map(),
1840
+ _textureRefs: /* @__PURE__ */ new Map(),
1841
+ renderPipeline: null,
1842
+ passes: {},
1843
+ _hmrVersion: 0,
1844
+ _sizeImperative: false,
1845
+ _sizeProps: null,
1846
+ previousRoot: void 0,
1847
+ internal: {
1848
+ // Events
1849
+ interaction: [],
1850
+ subscribers: [],
1851
+ // Per-pointer state (new unified structure)
1852
+ pointerMap: /* @__PURE__ */ new Map(),
1853
+ pointerDirty: /* @__PURE__ */ new Map(),
1854
+ lastEvent: React__namespace.createRef(),
1855
+ // Deprecated but kept for backwards compatibility
1856
+ hovered: /* @__PURE__ */ new Map(),
1857
+ initialClick: [0, 0],
1858
+ initialHits: [],
1859
+ capturedMap: /* @__PURE__ */ new Map(),
1860
+ // Visibility tracking (onFramed, onOccluded, onVisible)
1861
+ visibilityRegistry: /* @__PURE__ */ new Map(),
1862
+ // Occlusion system (WebGPU only)
1863
+ occlusionEnabled: false,
1864
+ occlusionObserver: null,
1865
+ occlusionCache: /* @__PURE__ */ new Map(),
1866
+ helperGroup: null,
1867
+ // Updates
1868
+ active: false,
1869
+ frames: 0,
1870
+ priority: 0,
1871
+ subscribe: (ref, priority, store) => {
1872
+ const internal = get().internal;
1873
+ internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1874
+ internal.subscribers.push({ ref, priority, store });
1875
+ internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1876
+ return () => {
1877
+ const internal2 = get().internal;
1878
+ if (internal2?.subscribers) {
1879
+ internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
1880
+ internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
1881
+ }
1882
+ };
1883
+ },
1884
+ // Renderer Storage (single source of truth)
1885
+ actualRenderer: null,
1886
+ // Scheduler for useFrameNext (initialized in renderer.tsx)
1887
+ scheduler: null
1859
1888
  }
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
- renderPipeline: null,
2835
- passes: {},
2836
- _hmrVersion: 0,
2837
- _sizeImperative: false,
2838
- _sizeProps: null,
2839
- previousRoot: void 0,
2840
- internal: {
2841
- // Events
2842
- interaction: [],
2843
- subscribers: [],
2844
- // Per-pointer state (new unified structure)
2845
- pointerMap: /* @__PURE__ */ new Map(),
2846
- pointerDirty: /* @__PURE__ */ new Map(),
2847
- lastEvent: React__namespace.createRef(),
2848
- // Deprecated but kept for backwards compatibility
2849
- hovered: /* @__PURE__ */ new Map(),
2850
- initialClick: [0, 0],
2851
- initialHits: [],
2852
- capturedMap: /* @__PURE__ */ new Map(),
2853
- // Visibility tracking (onFramed, onOccluded, onVisible)
2854
- visibilityRegistry: /* @__PURE__ */ new Map(),
2855
- // Occlusion system (WebGPU only)
2856
- occlusionEnabled: false,
2857
- occlusionObserver: null,
2858
- occlusionCache: /* @__PURE__ */ new Map(),
2859
- helperGroup: null,
2860
- // Updates
2861
- active: false,
2862
- frames: 0,
2863
- priority: 0,
2864
- subscribe: (ref, priority, store) => {
2865
- const internal = get().internal;
2866
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
2867
- internal.subscribers.push({ ref, priority, store });
2868
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
2869
- return () => {
2870
- const internal2 = get().internal;
2871
- if (internal2?.subscribers) {
2872
- internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
2873
- internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
2874
- }
2875
- };
2876
- },
2877
- // Renderer Storage (single source of truth)
2878
- actualRenderer: null,
2879
- // Scheduler for useFrameNext (initialized in renderer.tsx)
2880
- scheduler: null
2881
- }
2882
- };
2883
- return rootState;
1889
+ };
1890
+ return rootState;
2884
1891
  });
2885
1892
  const state = rootStore.getState();
2886
1893
  Object.defineProperty(state, "gl", {
@@ -2888,8 +1895,7 @@ const createStore = (invalidate, advance) => {
2888
1895
  const currentState = rootStore.getState();
2889
1896
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2890
1897
  const stack = new Error().stack || "";
2891
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2892
- if (!isInternalAccess) {
1898
+ if (!isInternalRendererAccess(stack)) {
2893
1899
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2894
1900
  notifyDepreciated({
2895
1901
  heading: "Accessing state.gl in WebGPU mode",
@@ -3002,26 +2008,32 @@ function loadingFn(extensions, onProgress) {
3002
2008
  );
3003
2009
  };
3004
2010
  }
3005
- function useLoader(loader, input, extensions, onProgress) {
3006
- const keys = Array.isArray(input) ? input : [input];
2011
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2012
+ const inputs = Array.isArray(input) ? input : [input];
2013
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
3007
2014
  const fn = loadingFn(extensions, onProgress);
3008
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2015
+ const results = cacheKeys.map(
2016
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2017
+ );
3009
2018
  return Array.isArray(input) ? results : results[0];
3010
2019
  }
3011
- useLoader.preload = function(loader, input, extensions, onProgress) {
3012
- const keys = Array.isArray(input) ? input : [input];
3013
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2020
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2021
+ const inputs = Array.isArray(input) ? input : [input];
2022
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2023
+ cacheKeys.forEach(
2024
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2025
+ );
3014
2026
  };
3015
- useLoader.clear = function(loader, input) {
3016
- const keys = Array.isArray(input) ? input : [input];
3017
- keys.forEach((key) => suspendReact.clear([loader, key]));
2027
+ useLoader.clear = function(loader, input, cacheKey) {
2028
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2029
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
3018
2030
  };
3019
2031
  useLoader.loader = getLoader;
3020
2032
 
3021
2033
  function useFrame(callback, priorityOrOptions) {
3022
2034
  const store = React__namespace.useContext(context);
3023
2035
  const isInsideCanvas = store !== null;
3024
- const scheduler = getScheduler();
2036
+ const scheduler$1 = scheduler.getScheduler();
3025
2037
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
3026
2038
  id: priorityOrOptions.id,
3027
2039
  phase: priorityOrOptions.phase,
@@ -3069,7 +2081,7 @@ function useFrame(callback, priorityOrOptions) {
3069
2081
  };
3070
2082
  callbackRef.current?.(mergedState, delta);
3071
2083
  };
3072
- const unregister = scheduler.register(wrappedCallback, {
2084
+ const unregister = scheduler$1.register(wrappedCallback, {
3073
2085
  id,
3074
2086
  rootId,
3075
2087
  ...options
@@ -3090,37 +2102,31 @@ function useFrame(callback, priorityOrOptions) {
3090
2102
  }
3091
2103
  };
3092
2104
  } else {
3093
- const registerOutside = () => {
3094
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3095
- };
3096
- if (scheduler.independent || scheduler.isReady) {
3097
- return registerOutside();
3098
- }
3099
- let unregisterJob = null;
3100
- const unsubReady = scheduler.onRootReady(() => {
3101
- unregisterJob = registerOutside();
3102
- });
3103
- return () => {
3104
- unsubReady();
3105
- unregisterJob?.();
3106
- };
2105
+ return scheduler$1.register(
2106
+ (state, delta) => {
2107
+ const frameState = state;
2108
+ if (!frameState.renderer) return;
2109
+ callbackRef.current?.(frameState, delta);
2110
+ },
2111
+ { id, ...options }
2112
+ );
3107
2113
  }
3108
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2114
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3109
2115
  const isPaused = React__namespace.useSyncExternalStore(
3110
2116
  // Subscribe function
3111
2117
  React__namespace.useCallback(
3112
2118
  (onStoreChange) => {
3113
- return getScheduler().subscribeJobState(id, onStoreChange);
2119
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3114
2120
  },
3115
2121
  [id]
3116
2122
  ),
3117
2123
  // getSnapshot function
3118
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2124
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3119
2125
  // getServerSnapshot function (SSR)
3120
2126
  React__namespace.useCallback(() => false, [])
3121
2127
  );
3122
2128
  const controls = React__namespace.useMemo(() => {
3123
- const scheduler2 = getScheduler();
2129
+ const scheduler2 = scheduler.getScheduler();
3124
2130
  return {
3125
2131
  /** The job's unique ID */
3126
2132
  id,
@@ -3135,7 +2141,7 @@ function useFrame(callback, priorityOrOptions) {
3135
2141
  * @param timestamp Optional timestamp (defaults to performance.now())
3136
2142
  */
3137
2143
  step: (timestamp) => {
3138
- getScheduler().stepJob(id, timestamp);
2144
+ scheduler.getScheduler().stepJob(id, timestamp);
3139
2145
  },
3140
2146
  /**
3141
2147
  * Manually step ALL jobs in the scheduler.
@@ -3143,20 +2149,20 @@ function useFrame(callback, priorityOrOptions) {
3143
2149
  * @param timestamp Optional timestamp (defaults to performance.now())
3144
2150
  */
3145
2151
  stepAll: (timestamp) => {
3146
- getScheduler().step(timestamp);
2152
+ scheduler.getScheduler().step(timestamp);
3147
2153
  },
3148
2154
  /**
3149
2155
  * Pause this job (set enabled=false).
3150
2156
  * Job remains registered but won't run.
3151
2157
  */
3152
2158
  pause: () => {
3153
- getScheduler().pauseJob(id);
2159
+ scheduler.getScheduler().pauseJob(id);
3154
2160
  },
3155
2161
  /**
3156
2162
  * Resume this job (set enabled=true).
3157
2163
  */
3158
2164
  resume: () => {
3159
- getScheduler().resumeJob(id);
2165
+ scheduler.getScheduler().resumeJob(id);
3160
2166
  },
3161
2167
  /**
3162
2168
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3194,18 +2200,18 @@ function buildFromCache(input, textureCache) {
3194
2200
  function useTexture(input, optionsOrOnLoad) {
3195
2201
  const renderer = useThree((state) => state.internal.actualRenderer);
3196
2202
  const store = useStore();
3197
- const textureCache = useThree((state) => state.textures);
3198
2203
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3199
- const { onLoad, cache = false } = options;
2204
+ const { onLoad, cache = true } = options;
3200
2205
  const onLoadRef = React.useRef(onLoad);
3201
2206
  onLoadRef.current = onLoad;
3202
2207
  const onLoadCalledForRef = React.useRef(null);
3203
2208
  const urls = React.useMemo(() => getUrls(input), [input]);
3204
2209
  const cachedResult = React.useMemo(() => {
3205
2210
  if (!cache) return null;
3206
- if (!allUrlsCached(urls, textureCache)) return null;
3207
- return buildFromCache(input, textureCache);
3208
- }, [cache, urls, textureCache, input]);
2211
+ const textures = store.getState().textures;
2212
+ if (!allUrlsCached(urls, textures)) return null;
2213
+ return buildFromCache(input, textures);
2214
+ }, [cache, urls, input, store]);
3209
2215
  const loadedTextures = useLoader(
3210
2216
  webgpu.TextureLoader,
3211
2217
  IsObject(input) ? Object.values(input) : input
@@ -3249,8 +2255,6 @@ function useTexture(input, optionsOrOnLoad) {
3249
2255
  }, [input, loadedTextures, cachedResult]);
3250
2256
  React.useEffect(() => {
3251
2257
  if (!cache) return;
3252
- if (cachedResult) return;
3253
- const set = store.setState;
3254
2258
  const urlTextureMap = [];
3255
2259
  if (typeof input === "string") {
3256
2260
  urlTextureMap.push([input, mappedTextures]);
@@ -3264,18 +2268,32 @@ function useTexture(input, optionsOrOnLoad) {
3264
2268
  urlTextureMap.push([url, textureRecord[key]]);
3265
2269
  }
3266
2270
  }
3267
- set((state) => {
3268
- const newMap = new Map(state.textures);
3269
- let changed = false;
2271
+ store.setState((state) => {
2272
+ const refs = new Map(state._textureRefs);
2273
+ let textures = state.textures;
2274
+ let added = false;
3270
2275
  for (const [url, texture] of urlTextureMap) {
3271
- if (!newMap.has(url)) {
3272
- newMap.set(url, texture);
3273
- changed = true;
2276
+ if (!textures.has(url)) {
2277
+ if (!added) {
2278
+ textures = new Map(textures);
2279
+ added = true;
2280
+ }
2281
+ textures.set(url, texture);
3274
2282
  }
2283
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3275
2284
  }
3276
- return changed ? { textures: newMap } : state;
2285
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3277
2286
  });
3278
- }, [cache, input, mappedTextures, store, cachedResult]);
2287
+ return () => store.setState((state) => {
2288
+ const refs = new Map(state._textureRefs);
2289
+ for (const [url] of urlTextureMap) {
2290
+ const next = (refs.get(url) ?? 0) - 1;
2291
+ if (next <= 0) refs.delete(url);
2292
+ else refs.set(url, next);
2293
+ }
2294
+ return { _textureRefs: refs };
2295
+ });
2296
+ }, [cache, input, mappedTextures, store]);
3279
2297
  return mappedTextures;
3280
2298
  }
3281
2299
  useTexture.preload = (url) => useLoader.preload(webgpu.TextureLoader, url);
@@ -3291,96 +2309,63 @@ const Texture = ({
3291
2309
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3292
2310
  };
3293
2311
 
3294
- function getTextureValue(entry) {
3295
- if (entry instanceof webgpu.Texture) return entry;
3296
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof webgpu.Texture) {
3297
- return entry.value;
3298
- }
3299
- return null;
3300
- }
3301
- function useTextures() {
2312
+ function useTextures(selector) {
3302
2313
  const store = useStore();
3303
- return React.useMemo(() => {
3304
- const set = store.setState;
2314
+ const registry = React.useMemo(() => {
3305
2315
  const getState = store.getState;
3306
- const add = (key, value) => {
3307
- set((state) => {
3308
- const newMap = new Map(state.textures);
3309
- newMap.set(key, value);
3310
- return { textures: newMap };
3311
- });
3312
- };
3313
- const addMultiple = (items) => {
3314
- set((state) => {
3315
- const newMap = new Map(state.textures);
3316
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3317
- for (const [key, value] of entries) {
3318
- newMap.set(key, value);
3319
- }
3320
- return { textures: newMap };
3321
- });
3322
- };
3323
- const remove = (key) => {
3324
- set((state) => {
3325
- const newMap = new Map(state.textures);
3326
- newMap.delete(key);
3327
- return { textures: newMap };
3328
- });
3329
- };
3330
- const removeMultiple = (keys) => {
3331
- set((state) => {
3332
- const newMap = new Map(state.textures);
3333
- for (const key of keys) newMap.delete(key);
3334
- return { textures: newMap };
3335
- });
3336
- };
3337
- const dispose = (key) => {
3338
- const entry = getState().textures.get(key);
3339
- if (entry) {
3340
- const tex = getTextureValue(entry);
3341
- tex?.dispose();
3342
- }
3343
- remove(key);
3344
- };
3345
- const disposeMultiple = (keys) => {
3346
- const textures = getState().textures;
3347
- for (const key of keys) {
3348
- const entry = textures.get(key);
3349
- if (entry) {
3350
- const tex = getTextureValue(entry);
3351
- tex?.dispose();
3352
- }
3353
- }
3354
- removeMultiple(keys);
3355
- };
3356
- const disposeAll = () => {
3357
- const textures = getState().textures;
3358
- for (const entry of textures.values()) {
3359
- const tex = getTextureValue(entry);
3360
- tex?.dispose();
3361
- }
3362
- set({ textures: /* @__PURE__ */ new Map() });
3363
- };
2316
+ const setState = store.setState;
2317
+ const getOne = (key) => getState().textures.get(key);
3364
2318
  return {
3365
- // Getter for the textures Map (reactive via getState)
3366
- get textures() {
2319
+ get all() {
3367
2320
  return getState().textures;
3368
2321
  },
3369
- // Read
3370
- get: (key) => getState().textures.get(key),
2322
+ get(input) {
2323
+ if (typeof input === "string") return getOne(input);
2324
+ if (Array.isArray(input)) return input.map(getOne);
2325
+ const out = {};
2326
+ for (const name in input) out[name] = getOne(input[name]);
2327
+ return out;
2328
+ },
3371
2329
  has: (key) => getState().textures.has(key),
3372
- // Write
3373
- add,
3374
- addMultiple,
3375
- // Remove (cache only)
3376
- remove,
3377
- removeMultiple,
3378
- // Dispose (GPU + cache)
3379
- dispose,
3380
- disposeMultiple,
3381
- disposeAll
2330
+ add(keyOrRecord, texture) {
2331
+ setState((state) => {
2332
+ const textures = new Map(state.textures);
2333
+ if (typeof keyOrRecord === "string") {
2334
+ textures.set(keyOrRecord, texture);
2335
+ } else {
2336
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2337
+ }
2338
+ return { textures };
2339
+ });
2340
+ },
2341
+ dispose(key, options) {
2342
+ const state = getState();
2343
+ const refs = state._textureRefs.get(key) ?? 0;
2344
+ if (refs > 0 && !options?.force) {
2345
+ console.warn(
2346
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2347
+ );
2348
+ return false;
2349
+ }
2350
+ state.textures.get(key)?.dispose();
2351
+ setState((s) => {
2352
+ const textures = new Map(s.textures);
2353
+ textures.delete(key);
2354
+ const nextRefs = new Map(s._textureRefs);
2355
+ nextRefs.delete(key);
2356
+ return { textures, _textureRefs: nextRefs };
2357
+ });
2358
+ return true;
2359
+ },
2360
+ disposeAll() {
2361
+ for (const texture of getState().textures.values()) texture.dispose();
2362
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2363
+ }
3382
2364
  };
3383
2365
  }, [store]);
2366
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2367
+ const selected = useThree(subscribe);
2368
+ return selector ? selected : registry;
3384
2369
  }
3385
2370
 
3386
2371
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3435,7 +2420,7 @@ function addEffect(callback) {
3435
2420
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3436
2421
  });
3437
2422
  const id = `legacy_effect_${effectId++}`;
3438
- return getScheduler().registerGlobal("before", id, callback);
2423
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3439
2424
  }
3440
2425
  function addAfterEffect(callback) {
3441
2426
  notifyDepreciated({
@@ -3444,7 +2429,7 @@ function addAfterEffect(callback) {
3444
2429
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3445
2430
  });
3446
2431
  const id = `legacy_afterEffect_${effectId++}`;
3447
- return getScheduler().registerGlobal("after", id, callback);
2432
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3448
2433
  }
3449
2434
  function addTail(callback) {
3450
2435
  notifyDepreciated({
@@ -3452,16 +2437,16 @@ function addTail(callback) {
3452
2437
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3453
2438
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3454
2439
  });
3455
- return getScheduler().onIdle(callback);
2440
+ return scheduler.getScheduler().onIdle(callback);
3456
2441
  }
3457
2442
  function invalidate(state, frames = 1, stackFrames = false) {
3458
- getScheduler().invalidate(frames, stackFrames);
2443
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3459
2444
  }
3460
2445
  function advance(timestamp) {
3461
- getScheduler().step(timestamp);
2446
+ scheduler.getScheduler().step(timestamp);
3462
2447
  }
3463
2448
 
3464
- const version = "10.0.0-alpha.2";
2449
+ const version = "10.0.0-alpha.3";
3465
2450
  const packageData = {
3466
2451
  version: version};
3467
2452
 
@@ -14717,7 +13702,7 @@ function n0() {
14717
13702
  var t0 = n0();
14718
13703
  const r0 = Xb(t0);
14719
13704
 
14720
- const t = 1, o = 8, r = 32, e = 2;
13705
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14721
13706
 
14722
13707
  function createReconciler(config) {
14723
13708
  const reconciler2 = r0(config);
@@ -14882,7 +13867,15 @@ function setFiberRef(fiber, publicInstance) {
14882
13867
  }
14883
13868
  }
14884
13869
  const reconstructed = [];
14885
- function swapInstances() {
13870
+ function flushReconstructedInstances() {
13871
+ if (reconstructed.length === 0) return;
13872
+ try {
13873
+ swapReconstructedInstances();
13874
+ } finally {
13875
+ reconstructed.length = 0;
13876
+ }
13877
+ }
13878
+ function swapReconstructedInstances() {
14886
13879
  for (const [instance] of reconstructed) {
14887
13880
  const parent = instance.parent;
14888
13881
  if (parent) {
@@ -14900,6 +13893,7 @@ function swapInstances() {
14900
13893
  }
14901
13894
  }
14902
13895
  if (instance.isHidden) unhideInstance(instance);
13896
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14903
13897
  if (instance.object.__r3f) delete instance.object.__r3f;
14904
13898
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14905
13899
  }
@@ -14912,6 +13906,8 @@ function swapInstances() {
14912
13906
  instance.object.__r3f = instance;
14913
13907
  setFiberRef(fiber, instance.object);
14914
13908
  delete instance.appliedOnce;
13909
+ instance.eventCount = 0;
13910
+ instance.handlers = {};
14915
13911
  applyProps(instance.object, instance.props);
14916
13912
  if (instance.props.attach) {
14917
13913
  attach(parent, instance);
@@ -14928,14 +13924,114 @@ function swapInstances() {
14928
13924
  invalidateInstance(instance);
14929
13925
  }
14930
13926
  }
14931
- reconstructed.length = 0;
14932
13927
  }
14933
13928
  const handleTextInstance = () => {
14934
13929
  };
14935
13930
  const NO_CONTEXT = {};
14936
13931
  let currentUpdatePriority = NoEventPriority;
14937
- const NoFlags = 0;
14938
- const Update = 4;
13932
+ function getEventPriority(type) {
13933
+ switch (type) {
13934
+ case "beforetoggle":
13935
+ case "cancel":
13936
+ case "click":
13937
+ case "close":
13938
+ case "contextmenu":
13939
+ case "copy":
13940
+ case "cut":
13941
+ case "auxclick":
13942
+ case "dblclick":
13943
+ case "dragend":
13944
+ case "dragstart":
13945
+ case "drop":
13946
+ case "focusin":
13947
+ case "focusout":
13948
+ case "input":
13949
+ case "invalid":
13950
+ case "keydown":
13951
+ case "keypress":
13952
+ case "keyup":
13953
+ case "mousedown":
13954
+ case "mouseup":
13955
+ case "paste":
13956
+ case "pause":
13957
+ case "play":
13958
+ case "pointercancel":
13959
+ case "pointerdown":
13960
+ case "pointerup":
13961
+ case "ratechange":
13962
+ case "reset":
13963
+ case "resize":
13964
+ case "seeked":
13965
+ case "submit":
13966
+ case "touchcancel":
13967
+ case "touchend":
13968
+ case "touchstart":
13969
+ case "volumechange":
13970
+ case "change":
13971
+ case "selectionchange":
13972
+ case "compositionstart":
13973
+ case "compositionend":
13974
+ case "compositionupdate":
13975
+ case "beforeinput":
13976
+ case "blur":
13977
+ case "fullscreenchange":
13978
+ case "focus":
13979
+ case "hashchange":
13980
+ case "popstate":
13981
+ case "select":
13982
+ case "selectstart":
13983
+ return e;
13984
+ case "drag":
13985
+ case "dragenter":
13986
+ case "dragexit":
13987
+ case "dragleave":
13988
+ case "dragover":
13989
+ case "mousemove":
13990
+ case "mouseout":
13991
+ case "mouseover":
13992
+ case "pointermove":
13993
+ case "pointerout":
13994
+ case "pointerover":
13995
+ case "scroll":
13996
+ case "touchmove":
13997
+ case "wheel":
13998
+ case "mouseenter":
13999
+ case "mouseleave":
14000
+ case "pointerenter":
14001
+ case "pointerleave":
14002
+ return o;
14003
+ case "message": {
14004
+ switch (Tb.unstable_getCurrentPriorityLevel()) {
14005
+ case Tb.unstable_ImmediatePriority:
14006
+ return e;
14007
+ case Tb.unstable_UserBlockingPriority:
14008
+ return o;
14009
+ case Tb.unstable_NormalPriority:
14010
+ case Tb.unstable_LowPriority:
14011
+ return r;
14012
+ case Tb.unstable_IdlePriority:
14013
+ return i$1;
14014
+ default:
14015
+ return r;
14016
+ }
14017
+ }
14018
+ default:
14019
+ return r;
14020
+ }
14021
+ }
14022
+ function scheduleMicrotask(callback) {
14023
+ if (typeof queueMicrotask === "function") {
14024
+ queueMicrotask(callback);
14025
+ } else if (typeof Promise !== "undefined") {
14026
+ Promise.resolve().then(callback).catch((error) => {
14027
+ setTimeout(() => {
14028
+ throw error;
14029
+ });
14030
+ });
14031
+ } else {
14032
+ setTimeout(callback);
14033
+ }
14034
+ }
14939
14035
  const reconciler = /* @__PURE__ */ createReconciler({
14940
14036
  isPrimaryRenderer: false,
14941
14037
  warnsIfNotActing: false,
@@ -14974,16 +14070,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14974
14070
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14975
14071
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14976
14072
  if (reconstruct) {
14977
- reconstructed.push([instance, { ...newProps }, fiber]);
14073
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14978
14074
  } else {
14979
14075
  const changedProps = diffProps(instance, newProps);
14980
- if (Object.keys(changedProps).length) {
14981
- Object.assign(instance.props, changedProps);
14982
- applyProps(instance.object, changedProps);
14983
- }
14076
+ const attach2 = instance.props.attach;
14077
+ instance.props = getInstanceProps(newProps);
14078
+ if (attach2 !== void 0) instance.props.attach = attach2;
14079
+ else delete instance.props.attach;
14080
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14984
14081
  }
14985
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14986
- if (isTailSibling) swapInstances();
14987
14082
  },
14988
14083
  finalizeInitialChildren: (instance) => {
14989
14084
  for (const prop in instance.props) {
@@ -15008,8 +14103,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15008
14103
  const target = container.getState().internal.container ?? container.getState().scene;
15009
14104
  return prepare(target, container, "", {});
15010
14105
  },
15011
- resetAfterCommit: () => {
15012
- },
14106
+ // Reconstructed instances are swapped once all mutations are committed,
14107
+ // before layout effects run so refs point to the new objects
14108
+ resetAfterCommit: flushReconstructedInstances,
15013
14109
  shouldSetTextContent: () => false,
15014
14110
  clearContainer: () => false,
15015
14111
  hideInstance,
@@ -15017,6 +14113,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15017
14113
  createTextInstance: handleTextInstance,
15018
14114
  hideTextInstance: handleTextInstance,
15019
14115
  unhideTextInstance: handleTextInstance,
14116
+ // Mirrors react-dom, which flushes discrete work in microtasks
14117
+ supportsMicrotasks: true,
14118
+ scheduleMicrotask,
15020
14119
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
15021
14120
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
15022
14121
  noTimeout: -1,
@@ -15057,28 +14156,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15057
14156
  },
15058
14157
  resolveUpdatePriority() {
15059
14158
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
15060
- switch (typeof window !== "undefined" && window.event?.type) {
15061
- case "click":
15062
- case "contextmenu":
15063
- case "dblclick":
15064
- case "dragenter":
15065
- case "dragleave":
15066
- case "drop":
15067
- case "pointercancel":
15068
- case "pointerdown":
15069
- case "pointerup":
15070
- return e;
15071
- case "dragover":
15072
- case "pointermove":
15073
- case "pointerout":
15074
- case "pointerover":
15075
- case "pointerenter":
15076
- case "pointerleave":
15077
- case "wheel":
15078
- return o;
15079
- default:
15080
- return r;
15081
- }
14159
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14160
+ if (eventType === void 0) return r;
14161
+ return getEventPriority(eventType);
15082
14162
  },
15083
14163
  resetFormInstance() {
15084
14164
  },
@@ -15127,11 +14207,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15127
14207
  cloneMutableTextInstance(textInstance) {
15128
14208
  return textInstance;
15129
14209
  },
14210
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14211
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14212
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14213
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14214
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14215
+ // Guarded by a test asserting a full render + unmount never reaches them.
15130
14216
  cloneRootViewTransitionContainer(_rootContainer) {
15131
- throw new Error("Not implemented.");
15132
14217
  },
15133
14218
  removeRootViewTransitionClone(_rootContainer, _clone) {
15134
- throw new Error("Not implemented.");
15135
14219
  },
15136
14220
  // https://github.com/facebook/react/pull/32465
15137
14221
  createFragmentInstance: (_fiber) => null,
@@ -15216,6 +14300,7 @@ function createRoot(canvas) {
15216
14300
  const lastConfiguredProps = {};
15217
14301
  let configured = false;
15218
14302
  let pending = null;
14303
+ let rendererSetup = null;
15219
14304
  return {
15220
14305
  async configure(props = {}) {
15221
14306
  let resolve;
@@ -15246,7 +14331,7 @@ function createRoot(canvas) {
15246
14331
  forceEven
15247
14332
  } = props;
15248
14333
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
15249
- const state = store.getState();
14334
+ let state = store.getState();
15250
14335
  const defaultGPUProps = {
15251
14336
  canvas,
15252
14337
  antialias: true
@@ -15260,52 +14345,64 @@ function createRoot(canvas) {
15260
14345
  throw new Error("Cannot use both gl and renderer props at the same time");
15261
14346
  }
15262
14347
  let renderer = state.internal.actualRenderer;
15263
- if (primaryCanvas && !state.internal.actualRenderer) {
15264
- const primary = await waitForPrimary(primaryCanvas);
15265
- renderer = primary.renderer;
15266
- state.internal.actualRenderer = renderer;
15267
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15268
- primary.store.setState((prev) => ({
15269
- internal: { ...prev.internal, isMultiCanvas: true }
15270
- }));
15271
- state.set((prev) => ({
15272
- webGPUSupported: primary.store.getState().webGPUSupported,
15273
- renderer,
15274
- primaryStore: primary.store,
15275
- internal: {
15276
- ...prev.internal,
15277
- canvasTarget,
15278
- isMultiCanvas: true,
15279
- isSecondary: true,
15280
- targetId: primaryCanvas
15281
- }
15282
- }));
15283
- } else if (!state.internal.actualRenderer) {
15284
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
15285
- if (!renderer.hasInitialized?.()) {
15286
- const size2 = computeInitialSize(canvas, propsSize);
15287
- if (size2.width > 0 && size2.height > 0) {
15288
- const pixelRatio = calculateDpr(dpr);
15289
- canvas.width = size2.width * pixelRatio;
15290
- canvas.height = size2.height * pixelRatio;
15291
- }
15292
- await renderer.init();
15293
- }
15294
- const backend = renderer.backend;
15295
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15296
- state.internal.actualRenderer = renderer;
15297
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15298
- if (canvasId && !state.internal.isSecondary) {
15299
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15300
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15301
- state.set((prev) => ({
15302
- internal: {
15303
- ...prev.internal,
15304
- canvasTarget,
15305
- unregisterPrimary
14348
+ if (!state.internal.actualRenderer) {
14349
+ if (!rendererSetup) {
14350
+ rendererSetup = (async () => {
14351
+ if (primaryCanvas) {
14352
+ const primary = await waitForPrimary(primaryCanvas);
14353
+ renderer = primary.renderer;
14354
+ state.internal.actualRenderer = renderer;
14355
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14356
+ primary.store.setState((prev) => ({
14357
+ internal: { ...prev.internal, isMultiCanvas: true }
14358
+ }));
14359
+ state.set((prev) => ({
14360
+ webGPUSupported: primary.store.getState().webGPUSupported,
14361
+ renderer,
14362
+ primaryStore: primary.store,
14363
+ internal: {
14364
+ ...prev.internal,
14365
+ canvasTarget,
14366
+ isMultiCanvas: true,
14367
+ isSecondary: true,
14368
+ targetId: primaryCanvas
14369
+ }
14370
+ }));
14371
+ } else {
14372
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14373
+ if (!renderer.hasInitialized?.()) {
14374
+ const size2 = computeInitialSize(canvas, propsSize);
14375
+ if (size2.width > 0 && size2.height > 0) {
14376
+ const pixelRatio = calculateDpr(dpr);
14377
+ canvas.width = size2.width * pixelRatio;
14378
+ canvas.height = size2.height * pixelRatio;
14379
+ }
14380
+ await renderer.init();
14381
+ }
14382
+ const backend = renderer.backend;
14383
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14384
+ state.internal.actualRenderer = renderer;
14385
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14386
+ if (canvasId && !state.internal.isSecondary) {
14387
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14388
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14389
+ state.set((prev) => ({
14390
+ internal: {
14391
+ ...prev.internal,
14392
+ canvasTarget,
14393
+ unregisterPrimary
14394
+ }
14395
+ }));
14396
+ }
15306
14397
  }
15307
- }));
14398
+ })().catch((err) => {
14399
+ rendererSetup = null;
14400
+ throw err;
14401
+ });
15308
14402
  }
14403
+ await rendererSetup;
14404
+ state = store.getState();
14405
+ renderer = state.internal.actualRenderer;
15309
14406
  }
15310
14407
  let raycaster = state.raycaster;
15311
14408
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -15485,15 +14582,15 @@ function createRoot(canvas) {
15485
14582
  applyProps(currentRenderer, rendererProps);
15486
14583
  }
15487
14584
  }
15488
- const scheduler = getScheduler();
14585
+ const scheduler$1 = scheduler.getScheduler();
15489
14586
  const rootId = state.internal.rootId;
15490
14587
  if (!rootId) {
15491
- const newRootId = canvasId || scheduler.generateRootId();
15492
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14588
+ const newRootId = canvasId || scheduler$1.generateRootId();
14589
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15493
14590
  getState: () => store.getState(),
15494
14591
  onError: (err) => store.getState().setError(err)
15495
14592
  });
15496
- const unregisterCanvasTarget = scheduler.register(
14593
+ const unregisterCanvasTarget = scheduler$1.register(
15497
14594
  () => {
15498
14595
  const state2 = store.getState();
15499
14596
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15508,7 +14605,7 @@ function createRoot(canvas) {
15508
14605
  system: true
15509
14606
  }
15510
14607
  );
15511
- const unregisterEventsFlush = scheduler.register(
14608
+ const unregisterEventsFlush = scheduler$1.register(
15512
14609
  () => {
15513
14610
  const state2 = store.getState();
15514
14611
  state2.events.flush?.();
@@ -15520,7 +14617,7 @@ function createRoot(canvas) {
15520
14617
  system: true
15521
14618
  }
15522
14619
  );
15523
- const unregisterFrustum = scheduler.register(
14620
+ const unregisterFrustum = scheduler$1.register(
15524
14621
  () => {
15525
14622
  const state2 = store.getState();
15526
14623
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15530,11 +14627,11 @@ function createRoot(canvas) {
15530
14627
  {
15531
14628
  id: `${newRootId}_frustum`,
15532
14629
  rootId: newRootId,
15533
- phase: "preRender",
14630
+ before: "render",
15534
14631
  system: true
15535
14632
  }
15536
14633
  );
15537
- const unregisterVisibility = scheduler.register(
14634
+ const unregisterVisibility = scheduler$1.register(
15538
14635
  () => {
15539
14636
  const state2 = store.getState();
15540
14637
  checkVisibility(state2);
@@ -15542,16 +14639,16 @@ function createRoot(canvas) {
15542
14639
  {
15543
14640
  id: `${newRootId}_visibility`,
15544
14641
  rootId: newRootId,
15545
- phase: "preRender",
14642
+ before: "render",
15546
14643
  system: true,
15547
14644
  after: `${newRootId}_frustum`
15548
14645
  }
15549
14646
  );
15550
- const unregisterRender = scheduler.register(
14647
+ const unregisterRender = scheduler$1.register(
15551
14648
  () => {
15552
14649
  const state2 = store.getState();
15553
14650
  const renderer2 = state2.internal.actualRenderer;
15554
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14651
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15555
14652
  if (userHandlesRender || state2.internal.priority) return;
15556
14653
  try {
15557
14654
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15584,11 +14681,11 @@ function createRoot(canvas) {
15584
14681
  unregisterVisibility();
15585
14682
  unregisterRender();
15586
14683
  },
15587
- scheduler
14684
+ scheduler: scheduler$1
15588
14685
  }
15589
14686
  }));
15590
14687
  }
15591
- scheduler.frameloop = frameloop;
14688
+ scheduler$1.frameloop = frameloop;
15592
14689
  onCreated = onCreatedCallback;
15593
14690
  configured = true;
15594
14691
  resolve();
@@ -15655,7 +14752,8 @@ function unmountComponentAtNode(canvas, callback) {
15655
14752
  dispose(state.scene);
15656
14753
  _roots.delete(canvas);
15657
14754
  if (callback) callback(canvas);
15658
- } catch {
14755
+ } catch (error) {
14756
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15659
14757
  }
15660
14758
  }, 500);
15661
14759
  }
@@ -15718,6 +14816,7 @@ function PortalInner({ state = {}, children, container }) {
15718
14816
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
15719
14817
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15720
14818
  }
14819
+ const set = injectState.set;
15721
14820
  return {
15722
14821
  // The intersect consists of the previous root state
15723
14822
  ...rootState,
@@ -15736,33 +14835,205 @@ function PortalInner({ state = {}, children, container }) {
15736
14835
  size: resolvedSize,
15737
14836
  viewport: { ...rootState.viewport, ...viewport },
15738
14837
  // Layers are allowed to override events
15739
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14838
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15740
14839
  // Container for child attachment - the portalScene (injected or container itself)
15741
14840
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15742
14841
  };
15743
14842
  });
15744
- const usePortalStore = React.useMemo(() => {
15745
- const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15746
- const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15747
- onMutate(previousRoot.getState());
15748
- return store;
15749
- }, [previousRoot, container]);
15750
- useIsomorphicLayoutEffect(() => {
15751
- const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
15752
- const unsubscribe = previousRoot.subscribe(onMutate);
15753
- return unsubscribe;
15754
- }, [previousRoot, usePortalStore]);
15755
- return (
15756
- // @ts-ignore, reconciler types are not maintained
15757
- /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
15758
- /* @__PURE__ */ jsxRuntime.jsx(context.Provider, { value: usePortalStore, children }),
15759
- usePortalStore,
15760
- null
15761
- ) })
15762
- );
14843
+ const usePortalStore = React.useMemo(() => {
14844
+ const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14845
+ const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14846
+ onMutate(previousRoot.getState());
14847
+ return store;
14848
+ }, [previousRoot, container]);
14849
+ useIsomorphicLayoutEffect(() => {
14850
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14851
+ const unsubscribe = previousRoot.subscribe(onMutate);
14852
+ return unsubscribe;
14853
+ }, [previousRoot, usePortalStore]);
14854
+ return (
14855
+ // @ts-ignore, reconciler types are not maintained
14856
+ /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
14857
+ /* @__PURE__ */ jsxRuntime.jsx(context.Provider, { value: usePortalStore, children }),
14858
+ usePortalStore,
14859
+ null
14860
+ ) })
14861
+ );
14862
+ }
14863
+ function flushSync(fn) {
14864
+ return reconciler.flushSyncFromReconciler(fn);
14865
+ }
14866
+
14867
+ function parseBackground(background) {
14868
+ if (!background) return null;
14869
+ if (typeof background === "object" && !background.isColor) {
14870
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14871
+ return {
14872
+ ...rest,
14873
+ preset,
14874
+ files: envMap || files,
14875
+ backgroundFiles: backgroundMap,
14876
+ background: true
14877
+ };
14878
+ }
14879
+ if (typeof background === "number") {
14880
+ return { color: background, background: true };
14881
+ }
14882
+ if (typeof background === "string") {
14883
+ if (background in presetsObj) {
14884
+ return { preset: background, background: true };
14885
+ }
14886
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14887
+ return { files: background, background: true };
14888
+ }
14889
+ return { color: background, background: true };
14890
+ }
14891
+ if (background.isColor) {
14892
+ return { color: background, background: true };
14893
+ }
14894
+ return null;
14895
+ }
14896
+
14897
+ function parseRendererConfig(rendererProp) {
14898
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14899
+ if (isRendererConfig) {
14900
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14901
+ return {
14902
+ primaryCanvas: pc,
14903
+ scheduler: sc,
14904
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14905
+ };
14906
+ }
14907
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14908
+ }
14909
+
14910
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14911
+ const ROOT_SCOPE = "";
14912
+ const registries = /* @__PURE__ */ new WeakMap();
14913
+ function getKindRegistry(store, kind) {
14914
+ let registry = registries.get(store);
14915
+ if (!registry) {
14916
+ registry = {
14917
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14918
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14919
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14920
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14921
+ };
14922
+ registries.set(store, registry);
14923
+ }
14924
+ return registry[kind];
14925
+ }
14926
+ function resolvePrimary$1(store) {
14927
+ return store.getState().primaryStore ?? store;
14928
+ }
14929
+ function isScopeValid(store, kind, scopeKey) {
14930
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14931
+ }
14932
+ function peekStaged(store, kind, scopeKey) {
14933
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14934
+ }
14935
+ function stageEntries(store, kind, scopeKey, entries) {
14936
+ const { staged } = getKindRegistry(store, kind);
14937
+ const current = staged.get(scopeKey);
14938
+ if (current) Object.assign(current, entries);
14939
+ else staged.set(scopeKey, { ...entries });
14940
+ }
14941
+ function readCommittedScope(map, scopeKey, isLeaf) {
14942
+ if (scopeKey === ROOT_SCOPE) {
14943
+ const leaves = {};
14944
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14945
+ return leaves;
14946
+ }
14947
+ const scopeData = map[scopeKey];
14948
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14949
+ return {};
14950
+ }
14951
+ function withStagedOverlay(store, kind, committed) {
14952
+ const { staged } = getKindRegistry(store, kind);
14953
+ if (staged.size === 0) return committed;
14954
+ const view = { ...committed };
14955
+ for (const [scopeKey, entries] of staged) {
14956
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14957
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14958
+ }
14959
+ return view;
14960
+ }
14961
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14962
+ const registry = getKindRegistry(store, kind);
14963
+ const staged = registry.staged.get(scopeKey);
14964
+ if (!staged) return;
14965
+ registry.staged.delete(scopeKey);
14966
+ const replace = !registry.valid.has(scopeKey);
14967
+ store.setState((state) => {
14968
+ const map = state[kind];
14969
+ if (scopeKey === ROOT_SCOPE) {
14970
+ if (!replace) return { [kind]: { ...map, ...staged } };
14971
+ const next = {};
14972
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14973
+ return { [kind]: { ...next, ...staged } };
14974
+ }
14975
+ const current = replace ? {} : map[scopeKey] ?? {};
14976
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14977
+ });
14978
+ registry.valid.add(scopeKey);
14979
+ }
14980
+ function invalidateResource(store, kind, scopeKey) {
14981
+ const registry = getKindRegistry(store, kind);
14982
+ if (scopeKey === void 0) {
14983
+ registry.valid.clear();
14984
+ registry.staged.clear();
14985
+ } else {
14986
+ registry.valid.delete(scopeKey);
14987
+ registry.staged.delete(scopeKey);
14988
+ }
14989
+ }
14990
+ function rebuildResource(store, kind, userScope) {
14991
+ const primary = resolvePrimary$1(store);
14992
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14993
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14994
+ }
14995
+ function invalidateAllResources(store) {
14996
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14997
+ }
14998
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14999
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
15000
+ if (staged) for (const name of names) delete staged[name];
15001
+ store.setState((state) => {
15002
+ const map = state[kind];
15003
+ if (scope) {
15004
+ const currentScope = { ...map[scope] };
15005
+ for (const name of names) delete currentScope[name];
15006
+ return { [kind]: { ...map, [scope]: currentScope } };
15007
+ }
15008
+ const next = { ...map };
15009
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
15010
+ return { [kind]: next };
15011
+ });
15763
15012
  }
15764
- function flushSync(fn) {
15765
- return reconciler.flushSyncFromReconciler(fn);
15013
+ function clearResourceEntries(store, kind, scope, isLeaf) {
15014
+ const registry = getKindRegistry(store, kind);
15015
+ if (scope && scope !== "root") registry.staged.delete(scope);
15016
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
15017
+ else registry.staged.clear();
15018
+ store.setState((state) => {
15019
+ const map = state[kind];
15020
+ if (scope && scope !== "root") {
15021
+ const { [scope]: _, ...rest } = map;
15022
+ return { [kind]: rest };
15023
+ }
15024
+ if (scope === "root") {
15025
+ const next = {};
15026
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
15027
+ return { [kind]: next };
15028
+ }
15029
+ return { [kind]: {} };
15030
+ });
15031
+ }
15032
+
15033
+ function clearHmrCaches(store) {
15034
+ const primary = store.getState().primaryStore ?? store;
15035
+ invalidateAllResources(primary);
15036
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
15766
15037
  }
15767
15038
 
15768
15039
  function CanvasImpl({
@@ -15785,6 +15056,8 @@ function CanvasImpl({
15785
15056
  raycaster,
15786
15057
  camera,
15787
15058
  scene,
15059
+ autoUpdateFrustum,
15060
+ occlusion,
15788
15061
  onPointerMissed,
15789
15062
  onDragOverMissed,
15790
15063
  onDropMissed,
@@ -15796,49 +15069,10 @@ function CanvasImpl({
15796
15069
  forceEven,
15797
15070
  ...props
15798
15071
  }) {
15799
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15800
- let primaryCanvas;
15801
- let scheduler;
15802
- let renderer;
15803
- if (isRendererConfig) {
15804
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15805
- primaryCanvas = pc;
15806
- scheduler = sc;
15807
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15808
- } else {
15809
- renderer = rendererProp;
15810
- }
15072
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15811
15073
  React__namespace.useMemo(() => extend(THREE), []);
15812
15074
  const Bridge = useBridge();
15813
- const backgroundProps = React__namespace.useMemo(() => {
15814
- if (!background) return null;
15815
- if (typeof background === "object" && !background.isColor) {
15816
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15817
- return {
15818
- ...rest,
15819
- preset,
15820
- files: envMap || files,
15821
- backgroundFiles: backgroundMap,
15822
- background: true
15823
- };
15824
- }
15825
- if (typeof background === "number") {
15826
- return { color: background, background: true };
15827
- }
15828
- if (typeof background === "string") {
15829
- if (background in presetsObj) {
15830
- return { preset: background, background: true };
15831
- }
15832
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15833
- return { files: background, background: true };
15834
- }
15835
- return { color: background, background: true };
15836
- }
15837
- if (background.isColor) {
15838
- return { color: background, background: true };
15839
- }
15840
- return null;
15841
- }, [background]);
15075
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15842
15076
  const hasInitialSizeRef = React__namespace.useRef(false);
15843
15077
  const measureConfig = React__namespace.useMemo(() => {
15844
15078
  if (!hasInitialSizeRef.current) {
@@ -15880,6 +15114,7 @@ function CanvasImpl({
15880
15114
  const handleDropMissed = useMutableCallback(onDropMissed);
15881
15115
  const [block, setBlock] = React__namespace.useState(false);
15882
15116
  const [error, setError] = React__namespace.useState(false);
15117
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15883
15118
  if (block) throw block;
15884
15119
  if (error) throw error;
15885
15120
  const root = React__namespace.useRef(null);
@@ -15887,6 +15122,7 @@ function CanvasImpl({
15887
15122
  const unsubscribeErrorRef = React__namespace.useRef(null);
15888
15123
  useIsomorphicLayoutEffect(() => {
15889
15124
  effectActiveRef.current = true;
15125
+ if (fallbackVisible) return;
15890
15126
  const canvas = canvasRef.current;
15891
15127
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15892
15128
  if (!root.current) {
@@ -15907,7 +15143,7 @@ function CanvasImpl({
15907
15143
  }
15908
15144
  async function run() {
15909
15145
  if (!effectActiveRef.current || !root.current) return;
15910
- await root.current.configure({
15146
+ const configured = await root.current.configure({
15911
15147
  id,
15912
15148
  primaryCanvas,
15913
15149
  scheduler,
@@ -15922,6 +15158,8 @@ function CanvasImpl({
15922
15158
  performance,
15923
15159
  raycaster,
15924
15160
  camera,
15161
+ autoUpdateFrustum,
15162
+ occlusion,
15925
15163
  size: effectiveSize,
15926
15164
  // Store size props for reset functionality
15927
15165
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15946,8 +15184,20 @@ function CanvasImpl({
15946
15184
  }
15947
15185
  onCreated?.(state);
15948
15186
  }
15949
- });
15950
- if (!effectActiveRef.current || !root.current) return;
15187
+ }).then(
15188
+ () => true,
15189
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15190
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15191
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15192
+ (setupError) => {
15193
+ if (effectActiveRef.current) {
15194
+ if (fallback != null) setFallbackVisible(true);
15195
+ else setError(setupError);
15196
+ }
15197
+ return false;
15198
+ }
15199
+ );
15200
+ if (!configured || !effectActiveRef.current || !root.current) return;
15951
15201
  root.current.render(
15952
15202
  /* @__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: [
15953
15203
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15981,14 +15231,7 @@ function CanvasImpl({
15981
15231
  const handleHMR = () => {
15982
15232
  queueMicrotask(() => {
15983
15233
  const rootEntry = _roots.get(canvas);
15984
- if (rootEntry?.store) {
15985
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15986
- rootEntry.store.setState((state) => ({
15987
- nodes: {},
15988
- uniforms: {},
15989
- _hmrVersion: state._hmrVersion + 1
15990
- }));
15991
- }
15234
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15992
15235
  });
15993
15236
  };
15994
15237
  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) {
@@ -16017,7 +15260,11 @@ function CanvasImpl({
16017
15260
  ...style
16018
15261
  },
16019
15262
  ...props,
16020
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15263
+ children: fallbackVisible ? (
15264
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15265
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15266
+ fallback
15267
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
16021
15268
  "canvas",
16022
15269
  {
16023
15270
  ref: canvasRef,
@@ -16099,35 +15346,50 @@ let ScopedStore = _ScopedStore;
16099
15346
  function createScopedStore(data) {
16100
15347
  return new ScopedStore(data);
16101
15348
  }
16102
- function createLazyCreatorState(state) {
15349
+ function createLazyCreatorState(state, store) {
16103
15350
  let _uniforms = null;
16104
15351
  let _nodes = null;
16105
15352
  let _buffers = null;
16106
15353
  let _gpuStorage = null;
15354
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
16107
15355
  return Object.create(state, {
16108
15356
  uniforms: {
16109
15357
  get() {
16110
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15358
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
16111
15359
  }
16112
15360
  },
16113
15361
  nodes: {
16114
15362
  get() {
16115
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15363
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
16116
15364
  }
16117
15365
  },
16118
15366
  buffers: {
16119
15367
  get() {
16120
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15368
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
16121
15369
  }
16122
15370
  },
16123
15371
  gpuStorage: {
16124
15372
  get() {
16125
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15373
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
16126
15374
  }
16127
15375
  }
16128
15376
  });
16129
15377
  }
16130
15378
 
15379
+ function resolvePrimary(local) {
15380
+ return local.getState().primaryStore ?? local;
15381
+ }
15382
+ function usePrimaryStore() {
15383
+ const local = useStore();
15384
+ const primary = local.getState().primaryStore;
15385
+ return React.useMemo(() => primary ?? local, [primary, local]);
15386
+ }
15387
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15388
+ const local = useStore();
15389
+ const primary = resolvePrimary(local);
15390
+ return primary(selector, equalityFn);
15391
+ }
15392
+
16131
15393
  function addTexture(set, key, value) {
16132
15394
  set((state) => {
16133
15395
  const newMap = new Map(state.textures);
@@ -16231,65 +15493,56 @@ function useCompareMemoize(value, deep) {
16231
15493
  return ref.current;
16232
15494
  }
16233
15495
 
15496
+ function useScopedResource(options) {
15497
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15498
+ const scopeKey = scope ?? ROOT_SCOPE;
15499
+ const version = store((s) => s._hmrVersion);
15500
+ const entries = React.useMemo(() => {
15501
+ const staged = peekStaged(store, kind, scopeKey);
15502
+ const reusable = isScopeValid(store, kind, scopeKey);
15503
+ const map = store.getState()[kind];
15504
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15505
+ const result = {};
15506
+ let fresh = null;
15507
+ for (const [name, candidate] of Object.entries(create())) {
15508
+ const existing = staged?.[name] ?? committed?.[name];
15509
+ if (existing !== void 0) {
15510
+ result[name] = existing;
15511
+ reconcile?.(existing, candidate);
15512
+ } else {
15513
+ const value = prepare ? prepare(name, candidate) : candidate;
15514
+ result[name] = value;
15515
+ (fresh ?? (fresh = {}))[name] = value;
15516
+ }
15517
+ }
15518
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15519
+ return result;
15520
+ }, [store, kind, scopeKey, version, input]);
15521
+ useIsomorphicLayoutEffect(() => {
15522
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15523
+ });
15524
+ return entries;
15525
+ }
15526
+
16234
15527
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16235
15528
  function useUniforms(creatorOrScope, scope) {
16236
- const store = useStore();
15529
+ const store = usePrimaryStore();
16237
15530
  const removeUniforms2 = React.useCallback(
16238
- (names, targetScope) => {
16239
- const nameArray = Array.isArray(names) ? names : [names];
16240
- store.setState((state) => {
16241
- if (targetScope) {
16242
- const currentScope = { ...state.uniforms[targetScope] };
16243
- for (const name of nameArray) delete currentScope[name];
16244
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
16245
- }
16246
- const uniforms2 = { ...state.uniforms };
16247
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
16248
- return { uniforms: uniforms2 };
16249
- });
16250
- },
15531
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
16251
15532
  [store]
16252
15533
  );
16253
15534
  const clearUniforms = React.useCallback(
16254
- (targetScope) => {
16255
- store.setState((state) => {
16256
- if (targetScope && targetScope !== "root") {
16257
- const { [targetScope]: _, ...rest } = state.uniforms;
16258
- return { uniforms: rest };
16259
- }
16260
- if (targetScope === "root") {
16261
- const uniforms2 = {};
16262
- for (const [key, value] of Object.entries(state.uniforms)) {
16263
- if (!isUniformNode$1(value)) uniforms2[key] = value;
16264
- }
16265
- return { uniforms: uniforms2 };
16266
- }
16267
- return { uniforms: {} };
16268
- });
16269
- },
15535
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
16270
15536
  [store]
16271
15537
  );
16272
15538
  const rebuildUniforms = React.useCallback(
16273
- (targetScope) => {
16274
- store.setState((state) => {
16275
- let newUniforms = {};
16276
- if (targetScope && targetScope !== "root") {
16277
- const { [targetScope]: _, ...rest } = state.uniforms;
16278
- newUniforms = rest;
16279
- } else if (targetScope === "root") {
16280
- for (const [key, value] of Object.entries(state.uniforms)) {
16281
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16282
- }
16283
- }
16284
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16285
- });
16286
- },
15539
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
16287
15540
  [store]
16288
15541
  );
16289
15542
  const inputForMemoization = React.useMemo(() => {
16290
15543
  let raw = creatorOrScope;
16291
15544
  if (is.fun(creatorOrScope)) {
16292
- const wrappedState = createLazyCreatorState(store.getState());
15545
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16293
15546
  raw = creatorOrScope(wrappedState);
16294
15547
  }
16295
15548
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -16303,80 +15556,44 @@ function useUniforms(creatorOrScope, scope) {
16303
15556
  }, [creatorOrScope, store]);
16304
15557
  const memoizedInput = useCompareMemoize(inputForMemoization);
16305
15558
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16306
- const storeUniforms = useThree((s) => s.uniforms);
16307
- const hmrVersion = useThree((s) => s._hmrVersion);
16308
- const readerDep = isReader ? storeUniforms : null;
16309
- const creatorDep = isReader ? null : hmrVersion;
16310
- const uniforms = React.useMemo(() => {
16311
- if (memoizedInput === void 0) {
16312
- return storeUniforms;
16313
- }
16314
- if (typeof memoizedInput === "string") {
16315
- const scopeData = storeUniforms[memoizedInput];
16316
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
16317
- return {};
16318
- }
16319
- const state = store.getState();
16320
- const set = store.setState;
16321
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
16322
- throw new Error("Invalid uniform input");
16323
- }
16324
- const created = memoizedInput;
16325
- const result = {};
16326
- let hasNewUniforms = false;
16327
- let targetRecord = state.uniforms;
16328
- if (scope) {
16329
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
16330
- targetRecord = state.uniforms[scope];
16331
- }
16332
- for (const [name, node] of Object.entries(created)) {
16333
- if (targetRecord[name]) {
16334
- result[name] = targetRecord[name];
16335
- const existingVal = result[name].value;
16336
- const newVal = vectorize(node);
16337
- let equals = newVal === existingVal;
16338
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
16339
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
16340
- equals = vectorEquals(existingVal, newVal);
16341
- } else if (isSameThreeType(existingVal, newVal)) {
16342
- equals = existingVal.equals(newVal);
16343
- }
15559
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15560
+ const created = useScopedResource({
15561
+ store,
15562
+ kind: "uniforms",
15563
+ scope: isReader ? void 0 : scope,
15564
+ isLeaf: isUniformNode$1,
15565
+ input: memoizedInput,
15566
+ create: () => {
15567
+ if (isReader) return {};
15568
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15569
+ return memoizedInput;
15570
+ },
15571
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15572
+ reconcile: (existing, candidate) => {
15573
+ const existingVal = existing.value;
15574
+ const newVal = vectorize(candidate);
15575
+ let equals = newVal === existingVal;
15576
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15577
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15578
+ equals = vectorEquals(existingVal, newVal);
15579
+ } else if (isSameThreeType(existingVal, newVal)) {
15580
+ equals = existingVal.equals(newVal);
16344
15581
  }
16345
- if (!equals) result[name].value = newVal;
16346
- } else {
16347
- result[name] = createUniform(name, node, scope);
16348
- hasNewUniforms = true;
16349
- }
16350
- }
16351
- if (hasNewUniforms) {
16352
- if (scope) {
16353
- set((s) => ({
16354
- uniforms: {
16355
- ...s.uniforms,
16356
- [scope]: { ...s.uniforms[scope], ...result }
16357
- }
16358
- }));
16359
- } else {
16360
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
16361
15582
  }
15583
+ if (!equals) existing.value = newVal;
16362
15584
  }
16363
- return result;
16364
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15585
+ });
15586
+ let uniforms = created;
15587
+ if (memoizedInput === void 0) {
15588
+ uniforms = storeUniforms;
15589
+ } else if (typeof memoizedInput === "string") {
15590
+ const scopeData = storeUniforms[memoizedInput];
15591
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15592
+ }
16365
15593
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16366
15594
  }
16367
15595
  function rebuildAllUniforms(store, scope) {
16368
- store.setState((state) => {
16369
- let newUniforms = {};
16370
- if (scope && scope !== "root") {
16371
- const { [scope]: _, ...rest } = state.uniforms;
16372
- newUniforms = rest;
16373
- } else if (scope === "root") {
16374
- for (const [key, value] of Object.entries(state.uniforms)) {
16375
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16376
- }
16377
- }
16378
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16379
- });
15596
+ rebuildResource(store, "uniforms", scope);
16380
15597
  }
16381
15598
  function removeUniforms(set, names, scope) {
16382
15599
  set((state) => {
@@ -16440,191 +15657,91 @@ function isSameThreeType(a, b) {
16440
15657
  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;
16441
15658
  }
16442
15659
 
15660
+ const uniformOf = tsl.uniform;
16443
15661
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16444
15662
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16445
15663
  function useUniform(name, value) {
16446
15664
  const store = useStore();
16447
- const hmrVersion = useThree((s) => s._hmrVersion);
16448
- return React.useMemo(() => {
16449
- const state = store.getState();
16450
- const set = store.setState;
16451
- const existing = state.uniforms[name];
16452
- if (existing && isUniformNode(existing)) {
15665
+ const registered = useScopedResource({
15666
+ store,
15667
+ kind: "uniforms",
15668
+ scope: void 0,
15669
+ isLeaf: isUniformNode,
15670
+ input: name,
15671
+ create: () => value === void 0 ? {} : { [name]: value },
15672
+ prepare: createNamedUniform,
15673
+ reconcile: (existing2) => {
16453
15674
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
16454
- existing.value = typeof value === "string" ? new webgpu.Color(value) : value;
15675
+ existing2.value = typeof value === "string" ? new webgpu.Color(value) : value;
16455
15676
  }
16456
- return existing;
16457
- }
16458
- if (value === void 0) {
16459
- throw new Error(
16460
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
16461
- );
16462
- }
16463
- if (isUniformNode(value)) {
16464
- const node2 = value;
16465
- if (typeof node2.setName === "function") {
16466
- node2.setName(name);
16467
- }
16468
- set((s) => ({
16469
- uniforms: { ...s.uniforms, [name]: node2 }
16470
- }));
16471
- return node2;
16472
- }
16473
- let node;
16474
- if (isTSLNode$1(value)) {
16475
- node = tsl.uniform(value);
16476
- } else if (typeof value === "string") {
16477
- node = tsl.uniform(new webgpu.Color(value));
16478
- } else {
16479
- node = tsl.uniform(value);
16480
- }
16481
- if (typeof node.setName === "function") {
16482
- node.setName(name);
16483
15677
  }
16484
- set((s) => ({
16485
- uniforms: {
16486
- ...s.uniforms,
16487
- [name]: node
16488
- }
16489
- }));
16490
- return node;
16491
- }, [store, name, hmrVersion]);
15678
+ });
15679
+ if (registered[name]) return registered[name];
15680
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15681
+ if (existing && isUniformNode(existing)) return existing;
15682
+ throw new Error(
15683
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15684
+ );
15685
+ }
15686
+ function createNamedUniform(name, value) {
15687
+ let node;
15688
+ if (isUniformNode(value)) {
15689
+ node = value;
15690
+ } else if (isTSLNode$1(value)) {
15691
+ node = uniformOf(value);
15692
+ } else if (typeof value === "string") {
15693
+ node = tsl.uniform(new webgpu.Color(value));
15694
+ } else {
15695
+ node = uniformOf(value);
15696
+ }
15697
+ if (typeof node.setName === "function") {
15698
+ node.setName(name);
15699
+ }
15700
+ return node;
16492
15701
  }
16493
15702
 
16494
15703
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16495
15704
  function useNodes(creatorOrScope, scope) {
16496
- const store = useStore();
15705
+ const store = usePrimaryStore();
16497
15706
  const removeNodes2 = React.useCallback(
16498
- (names, targetScope) => {
16499
- const nameArray = Array.isArray(names) ? names : [names];
16500
- store.setState((state) => {
16501
- if (targetScope) {
16502
- const currentScope = { ...state.nodes[targetScope] };
16503
- for (const name of nameArray) delete currentScope[name];
16504
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
16505
- }
16506
- const nodes2 = { ...state.nodes };
16507
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
16508
- return { nodes: nodes2 };
16509
- });
16510
- },
15707
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
16511
15708
  [store]
16512
15709
  );
16513
15710
  const clearNodes = React.useCallback(
16514
- (targetScope) => {
16515
- store.setState((state) => {
16516
- if (targetScope && targetScope !== "root") {
16517
- const { [targetScope]: _, ...rest } = state.nodes;
16518
- return { nodes: rest };
16519
- }
16520
- if (targetScope === "root") {
16521
- const nodes2 = {};
16522
- for (const [key, value] of Object.entries(state.nodes)) {
16523
- if (!isTSLNode(value)) nodes2[key] = value;
16524
- }
16525
- return { nodes: nodes2 };
16526
- }
16527
- return { nodes: {} };
16528
- });
16529
- },
15711
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
16530
15712
  [store]
16531
15713
  );
16532
15714
  const rebuildNodes = React.useCallback(
16533
- (targetScope) => {
16534
- store.setState((state) => {
16535
- let newNodes = state.nodes;
16536
- if (targetScope && targetScope !== "root") {
16537
- const { [targetScope]: _, ...rest } = state.nodes;
16538
- newNodes = rest;
16539
- } else if (targetScope === "root") {
16540
- newNodes = {};
16541
- for (const [key, value] of Object.entries(state.nodes)) {
16542
- if (!isTSLNode(value)) newNodes[key] = value;
16543
- }
16544
- } else {
16545
- newNodes = {};
16546
- }
16547
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16548
- });
16549
- },
15715
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
16550
15716
  [store]
16551
15717
  );
16552
15718
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16553
- const storeNodes = useThree((s) => s.nodes);
16554
- const hmrVersion = useThree((s) => s._hmrVersion);
16555
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16556
- const readerDep = isReader ? storeNodes : null;
16557
- const creatorDep = isReader ? null : hmrVersion;
16558
- const nodes = React.useMemo(() => {
16559
- if (creatorOrScope === void 0) {
16560
- return storeNodes;
16561
- }
16562
- if (typeof creatorOrScope === "string") {
16563
- const scopeData = storeNodes[creatorOrScope];
16564
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
16565
- return {};
16566
- }
16567
- const state = store.getState();
16568
- const set = store.setState;
16569
- const creator = creatorOrScope;
16570
- const wrappedState = createLazyCreatorState(state);
16571
- const created = creator(wrappedState);
16572
- const result = {};
16573
- let hasNewNodes = false;
16574
- if (scope) {
16575
- const currentScope = state.nodes[scope] ?? {};
16576
- for (const [name, node] of Object.entries(created)) {
16577
- if (currentScope[name]) {
16578
- result[name] = currentScope[name];
16579
- } else {
16580
- node.setName?.(`${scope}.${name}`);
16581
- result[name] = node;
16582
- hasNewNodes = true;
16583
- }
16584
- }
16585
- if (hasNewNodes) {
16586
- set((s) => ({
16587
- nodes: {
16588
- ...s.nodes,
16589
- [scope]: { ...s.nodes[scope], ...result }
16590
- }
16591
- }));
16592
- }
16593
- return result;
16594
- }
16595
- for (const [name, node] of Object.entries(created)) {
16596
- const existing = state.nodes[name];
16597
- if (existing && isTSLNode(existing)) {
16598
- result[name] = existing;
16599
- } else {
16600
- node.setName?.(name);
16601
- result[name] = node;
16602
- hasNewNodes = true;
16603
- }
16604
- }
16605
- if (hasNewNodes) {
16606
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15719
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15720
+ const created = useScopedResource({
15721
+ store,
15722
+ kind: "nodes",
15723
+ scope: isReader ? void 0 : scope,
15724
+ isLeaf: isTSLNode,
15725
+ create: () => {
15726
+ if (isReader) return {};
15727
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15728
+ },
15729
+ prepare: (name, node) => {
15730
+ node.setName?.(scope ? `${scope}.${name}` : name);
15731
+ return node;
16607
15732
  }
16608
- return result;
16609
- }, [store, scopeDep, readerDep, creatorDep]);
15733
+ });
15734
+ let nodes = created;
15735
+ if (creatorOrScope === void 0) {
15736
+ nodes = storeNodes;
15737
+ } else if (typeof creatorOrScope === "string") {
15738
+ const scopeData = storeNodes[creatorOrScope];
15739
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15740
+ }
16610
15741
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16611
15742
  }
16612
15743
  function rebuildAllNodes(store, scope) {
16613
- store.setState((state) => {
16614
- let newNodes = state.nodes;
16615
- if (scope && scope !== "root") {
16616
- const { [scope]: _, ...rest } = state.nodes;
16617
- newNodes = rest;
16618
- } else if (scope === "root") {
16619
- newNodes = {};
16620
- for (const [key, value] of Object.entries(state.nodes)) {
16621
- if (!isTSLNode(value)) newNodes[key] = value;
16622
- }
16623
- } else {
16624
- newNodes = {};
16625
- }
16626
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16627
- });
15744
+ rebuildResource(store, "nodes", scope);
16628
15745
  }
16629
15746
  function removeNodes(set, names, scope) {
16630
15747
  set((state) => {
@@ -16654,13 +15771,13 @@ function clearRootNodes(set) {
16654
15771
  });
16655
15772
  }
16656
15773
  function useLocalNodes(creator) {
16657
- const store = useStore();
16658
- const uniforms = useThree((s) => s.uniforms);
16659
- const nodes = useThree((s) => s.nodes);
16660
- const textures = useThree((s) => s.textures);
16661
- const hmrVersion = useThree((s) => s._hmrVersion);
15774
+ const store = usePrimaryStore();
15775
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15776
+ const nodes = usePrimaryThree((s) => s.nodes);
15777
+ const textures = usePrimaryThree((s) => s.textures);
15778
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16662
15779
  return React.useMemo(() => {
16663
- const wrappedState = createLazyCreatorState(store.getState());
15780
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16664
15781
  return creator(wrappedState);
16665
15782
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
16666
15783
  }
@@ -16679,60 +15796,17 @@ const disposeBuffer = (buffer) => {
16679
15796
  }
16680
15797
  };
16681
15798
  function useBuffers(creatorOrScope, scope) {
16682
- const store = useStore();
15799
+ const store = usePrimaryStore();
16683
15800
  const removeBuffers = React.useCallback(
16684
- (names, targetScope) => {
16685
- const nameArray = Array.isArray(names) ? names : [names];
16686
- store.setState((state) => {
16687
- if (targetScope) {
16688
- const currentScope = { ...state.buffers[targetScope] };
16689
- for (const name of nameArray) delete currentScope[name];
16690
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
16691
- }
16692
- const buffers2 = { ...state.buffers };
16693
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
16694
- return { buffers: buffers2 };
16695
- });
16696
- },
15801
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
16697
15802
  [store]
16698
15803
  );
16699
15804
  const clearBuffers = React.useCallback(
16700
- (targetScope) => {
16701
- store.setState((state) => {
16702
- if (targetScope && targetScope !== "root") {
16703
- const { [targetScope]: _, ...rest } = state.buffers;
16704
- return { buffers: rest };
16705
- }
16706
- if (targetScope === "root") {
16707
- const buffers2 = {};
16708
- for (const [key, value] of Object.entries(state.buffers)) {
16709
- if (!isBufferLike(value)) buffers2[key] = value;
16710
- }
16711
- return { buffers: buffers2 };
16712
- }
16713
- return { buffers: {} };
16714
- });
16715
- },
15805
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
16716
15806
  [store]
16717
15807
  );
16718
15808
  const rebuildBuffers = React.useCallback(
16719
- (targetScope) => {
16720
- store.setState((state) => {
16721
- let newBuffers = state.buffers;
16722
- if (targetScope && targetScope !== "root") {
16723
- const { [targetScope]: _, ...rest } = state.buffers;
16724
- newBuffers = rest;
16725
- } else if (targetScope === "root") {
16726
- newBuffers = {};
16727
- for (const [key, value] of Object.entries(state.buffers)) {
16728
- if (!isBufferLike(value)) newBuffers[key] = value;
16729
- }
16730
- } else {
16731
- newBuffers = {};
16732
- }
16733
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16734
- });
16735
- },
15809
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
16736
15810
  [store]
16737
15811
  );
16738
15812
  const disposeBuffers = React.useCallback(
@@ -16750,85 +15824,34 @@ function useBuffers(creatorOrScope, scope) {
16750
15824
  [store, removeBuffers]
16751
15825
  );
16752
15826
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16753
- const storeBuffers = useThree((s) => s.buffers);
16754
- const hmrVersion = useThree((s) => s._hmrVersion);
16755
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16756
- const readerDep = isReader ? storeBuffers : null;
16757
- const creatorDep = isReader ? null : hmrVersion;
16758
- const buffers = React.useMemo(() => {
16759
- if (creatorOrScope === void 0) {
16760
- return storeBuffers;
16761
- }
16762
- if (typeof creatorOrScope === "string") {
16763
- const scopeData = storeBuffers[creatorOrScope];
16764
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
16765
- return {};
16766
- }
16767
- const state = store.getState();
16768
- const set = store.setState;
16769
- const creator = creatorOrScope;
16770
- const wrappedState = createLazyCreatorState(state);
16771
- const created = creator(wrappedState);
16772
- const result = {};
16773
- let hasNewBuffers = false;
16774
- if (scope) {
16775
- const currentScope = state.buffers[scope] ?? {};
16776
- for (const [name, buffer] of Object.entries(created)) {
16777
- if (currentScope[name]) {
16778
- result[name] = currentScope[name];
16779
- } else {
16780
- if ("setName" in buffer && typeof buffer.setName === "function") {
16781
- buffer.setName(`${scope}.${name}`);
16782
- }
16783
- result[name] = buffer;
16784
- hasNewBuffers = true;
16785
- }
16786
- }
16787
- if (hasNewBuffers) {
16788
- set((s) => ({
16789
- buffers: {
16790
- ...s.buffers,
16791
- [scope]: { ...s.buffers[scope], ...result }
16792
- }
16793
- }));
16794
- }
16795
- return result;
16796
- }
16797
- for (const [name, buffer] of Object.entries(created)) {
16798
- const existing = state.buffers[name];
16799
- if (existing && isBufferLike(existing)) {
16800
- result[name] = existing;
16801
- } else {
16802
- if ("setName" in buffer && typeof buffer.setName === "function") {
16803
- buffer.setName(name);
16804
- }
16805
- result[name] = buffer;
16806
- hasNewBuffers = true;
15827
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15828
+ const created = useScopedResource({
15829
+ store,
15830
+ kind: "buffers",
15831
+ scope: isReader ? void 0 : scope,
15832
+ isLeaf: isBufferLike,
15833
+ create: () => {
15834
+ if (isReader) return {};
15835
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15836
+ },
15837
+ prepare: (name, buffer) => {
15838
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15839
+ buffer.setName(scope ? `${scope}.${name}` : name);
16807
15840
  }
15841
+ return buffer;
16808
15842
  }
16809
- if (hasNewBuffers) {
16810
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
16811
- }
16812
- return result;
16813
- }, [store, scopeDep, readerDep, creatorDep]);
15843
+ });
15844
+ let buffers = created;
15845
+ if (creatorOrScope === void 0) {
15846
+ buffers = storeBuffers;
15847
+ } else if (typeof creatorOrScope === "string") {
15848
+ const scopeData = storeBuffers[creatorOrScope];
15849
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15850
+ }
16814
15851
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16815
15852
  }
16816
15853
  function rebuildAllBuffers(store, scope) {
16817
- store.setState((state) => {
16818
- let newBuffers = state.buffers;
16819
- if (scope && scope !== "root") {
16820
- const { [scope]: _, ...rest } = state.buffers;
16821
- newBuffers = rest;
16822
- } else if (scope === "root") {
16823
- newBuffers = {};
16824
- for (const [key, value] of Object.entries(state.buffers)) {
16825
- if (!isBufferLike(value)) newBuffers[key] = value;
16826
- }
16827
- } else {
16828
- newBuffers = {};
16829
- }
16830
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16831
- });
15854
+ rebuildResource(store, "buffers", scope);
16832
15855
  }
16833
15856
 
16834
15857
  const isStorageLike = (value) => {
@@ -16845,60 +15868,17 @@ const disposeStorage = (storage) => {
16845
15868
  }
16846
15869
  };
16847
15870
  function useGPUStorage(creatorOrScope, scope) {
16848
- const store = useStore();
15871
+ const store = usePrimaryStore();
16849
15872
  const removeStorage = React.useCallback(
16850
- (names, targetScope) => {
16851
- const nameArray = Array.isArray(names) ? names : [names];
16852
- store.setState((state) => {
16853
- if (targetScope) {
16854
- const currentScope = { ...state.gpuStorage[targetScope] };
16855
- for (const name of nameArray) delete currentScope[name];
16856
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
16857
- }
16858
- const gpuStorage2 = { ...state.gpuStorage };
16859
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
16860
- return { gpuStorage: gpuStorage2 };
16861
- });
16862
- },
15873
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
16863
15874
  [store]
16864
15875
  );
16865
15876
  const clearStorage = React.useCallback(
16866
- (targetScope) => {
16867
- store.setState((state) => {
16868
- if (targetScope && targetScope !== "root") {
16869
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16870
- return { gpuStorage: rest };
16871
- }
16872
- if (targetScope === "root") {
16873
- const gpuStorage2 = {};
16874
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16875
- if (!isStorageLike(value)) gpuStorage2[key] = value;
16876
- }
16877
- return { gpuStorage: gpuStorage2 };
16878
- }
16879
- return { gpuStorage: {} };
16880
- });
16881
- },
15877
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
16882
15878
  [store]
16883
15879
  );
16884
15880
  const rebuildStorage = React.useCallback(
16885
- (targetScope) => {
16886
- store.setState((state) => {
16887
- let newStorage = state.gpuStorage;
16888
- if (targetScope && targetScope !== "root") {
16889
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16890
- newStorage = rest;
16891
- } else if (targetScope === "root") {
16892
- newStorage = {};
16893
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16894
- if (!isStorageLike(value)) newStorage[key] = value;
16895
- }
16896
- } else {
16897
- newStorage = {};
16898
- }
16899
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16900
- });
16901
- },
15881
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
16902
15882
  [store]
16903
15883
  );
16904
15884
  const disposeStorageFn = React.useCallback(
@@ -16916,73 +15896,34 @@ function useGPUStorage(creatorOrScope, scope) {
16916
15896
  [store, removeStorage]
16917
15897
  );
16918
15898
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16919
- const storeStorage = useThree((s) => s.gpuStorage);
16920
- const hmrVersion = useThree((s) => s._hmrVersion);
16921
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16922
- const readerDep = isReader ? storeStorage : null;
16923
- const creatorDep = isReader ? null : hmrVersion;
16924
- const gpuStorage = React.useMemo(() => {
16925
- if (creatorOrScope === void 0) {
16926
- return storeStorage;
16927
- }
16928
- if (typeof creatorOrScope === "string") {
16929
- const scopeData = storeStorage[creatorOrScope];
16930
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
16931
- return {};
16932
- }
16933
- const state = store.getState();
16934
- const set = store.setState;
16935
- const creator = creatorOrScope;
16936
- const wrappedState = createLazyCreatorState(state);
16937
- const created = creator(wrappedState);
16938
- const result = {};
16939
- let hasNewStorage = false;
16940
- if (scope) {
16941
- const currentScope = state.gpuStorage[scope] ?? {};
16942
- for (const [name, storage] of Object.entries(created)) {
16943
- if (currentScope[name]) {
16944
- result[name] = currentScope[name];
16945
- } else {
16946
- if ("setName" in storage && typeof storage.setName === "function") {
16947
- storage.setName(`${scope}.${name}`);
16948
- }
16949
- if ("name" in storage && typeof storage.name === "string") {
16950
- storage.name = `${scope}.${name}`;
16951
- }
16952
- result[name] = storage;
16953
- hasNewStorage = true;
16954
- }
16955
- }
16956
- if (hasNewStorage) {
16957
- set((s) => ({
16958
- gpuStorage: {
16959
- ...s.gpuStorage,
16960
- [scope]: { ...s.gpuStorage[scope], ...result }
16961
- }
16962
- }));
15899
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15900
+ const created = useScopedResource({
15901
+ store,
15902
+ kind: "gpuStorage",
15903
+ scope: isReader ? void 0 : scope,
15904
+ isLeaf: isStorageLike,
15905
+ create: () => {
15906
+ if (isReader) return {};
15907
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15908
+ },
15909
+ prepare: (name, storage) => {
15910
+ const label = scope ? `${scope}.${name}` : name;
15911
+ if ("setName" in storage && typeof storage.setName === "function") {
15912
+ storage.setName(label);
16963
15913
  }
16964
- return result;
16965
- }
16966
- for (const [name, storage] of Object.entries(created)) {
16967
- const existing = state.gpuStorage[name];
16968
- if (existing && isStorageLike(existing)) {
16969
- result[name] = existing;
16970
- } else {
16971
- if ("setName" in storage && typeof storage.setName === "function") {
16972
- storage.setName(name);
16973
- }
16974
- if ("name" in storage && typeof storage.name === "string") {
16975
- storage.name = name;
16976
- }
16977
- result[name] = storage;
16978
- hasNewStorage = true;
15914
+ if ("name" in storage && typeof storage.name === "string") {
15915
+ storage.name = label;
16979
15916
  }
15917
+ return storage;
16980
15918
  }
16981
- if (hasNewStorage) {
16982
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
16983
- }
16984
- return result;
16985
- }, [store, scopeDep, readerDep, creatorDep]);
15919
+ });
15920
+ let gpuStorage = created;
15921
+ if (creatorOrScope === void 0) {
15922
+ gpuStorage = storeStorage;
15923
+ } else if (typeof creatorOrScope === "string") {
15924
+ const scopeData = storeStorage[creatorOrScope];
15925
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15926
+ }
16986
15927
  return {
16987
15928
  ...gpuStorage,
16988
15929
  removeStorage,
@@ -16992,21 +15933,7 @@ function useGPUStorage(creatorOrScope, scope) {
16992
15933
  };
16993
15934
  }
16994
15935
  function rebuildAllStorage(store, scope) {
16995
- store.setState((state) => {
16996
- let newStorage = state.gpuStorage;
16997
- if (scope && scope !== "root") {
16998
- const { [scope]: _, ...rest } = state.gpuStorage;
16999
- newStorage = rest;
17000
- } else if (scope === "root") {
17001
- newStorage = {};
17002
- for (const [key, value] of Object.entries(state.gpuStorage)) {
17003
- if (!isStorageLike(value)) newStorage[key] = value;
17004
- }
17005
- } else {
17006
- newStorage = {};
17007
- }
17008
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
17009
- });
15936
+ rebuildResource(store, "gpuStorage", scope);
17010
15937
  }
17011
15938
 
17012
15939
  function useRenderPipeline(mainCB, setupCB) {
@@ -17047,12 +15974,12 @@ function useRenderPipeline(mainCB, setupCB) {
17047
15974
  const state = store.getState();
17048
15975
  const set = store.setState;
17049
15976
  try {
17050
- let pp = state.renderPipeline;
15977
+ let pipeline = state.renderPipeline;
17051
15978
  let currentPasses = { ...state.passes };
17052
- let justCreatedPP = false;
17053
- if (!pp) {
17054
- pp = new webgpu.PostProcessing(renderer);
17055
- justCreatedPP = true;
15979
+ let justCreatedPipeline = false;
15980
+ if (!pipeline) {
15981
+ pipeline = new webgpu.RenderPipeline(renderer);
15982
+ justCreatedPipeline = true;
17056
15983
  }
17057
15984
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
17058
15985
  let scenePass;
@@ -17063,9 +15990,9 @@ function useRenderPipeline(mainCB, setupCB) {
17063
15990
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
17064
15991
  }
17065
15992
  currentPasses.scenePass = scenePass;
17066
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
17067
- set({ renderPipeline: pp, passes: currentPasses });
17068
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15993
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15994
+ set({ renderPipeline: pipeline, passes: currentPasses });
15995
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
17069
15996
  if (shouldRunCallbacks) {
17070
15997
  if (setupCBRef.current) {
17071
15998
  const freshState = store.getState();
@@ -17086,7 +16013,7 @@ function useRenderPipeline(mainCB, setupCB) {
17086
16013
  callbacksRanRef.current = true;
17087
16014
  }
17088
16015
  } catch (error) {
17089
- console.error("[useRenderPipeline] Setup error:", error);
16016
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17090
16017
  }
17091
16018
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17092
16019
  const passes = useThree((s) => s.passes);
@@ -17104,6 +16031,8 @@ function useRenderPipeline(mainCB, setupCB) {
17104
16031
 
17105
16032
  extend(THREE);
17106
16033
 
16034
+ exports.Scheduler = scheduler.Scheduler;
16035
+ exports.getScheduler = scheduler.getScheduler;
17107
16036
  exports.Block = Block;
17108
16037
  exports.Canvas = Canvas;
17109
16038
  exports.Environment = Environment;
@@ -17119,10 +16048,8 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
17119
16048
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
17120
16049
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
17121
16050
  exports.RESERVED_PROPS = RESERVED_PROPS;
17122
- exports.Scheduler = Scheduler;
17123
16051
  exports.Texture = Texture;
17124
16052
  exports._roots = _roots;
17125
- exports.act = act;
17126
16053
  exports.addAfterEffect = addAfterEffect;
17127
16054
  exports.addEffect = addEffect;
17128
16055
  exports.addTail = addTail;
@@ -17155,7 +16082,6 @@ exports.getInstanceProps = getInstanceProps;
17155
16082
  exports.getPrimary = getPrimary;
17156
16083
  exports.getPrimaryIds = getPrimaryIds;
17157
16084
  exports.getRootState = getRootState;
17158
- exports.getScheduler = getScheduler;
17159
16085
  exports.getUuidPrefix = getUuidPrefix;
17160
16086
  exports.hasConstructor = hasConstructor;
17161
16087
  exports.hasPrimary = hasPrimary;