@react-three/fiber 10.0.0-canary.1b98c17 → 10.0.0-canary.2c50459

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');
@@ -456,9 +457,9 @@ function Environment(props) {
456
457
  return props.ground ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props });
457
458
  }
458
459
 
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);
460
+ var __defProp$1 = Object.defineProperty;
461
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
462
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
462
463
  const act = React__namespace["act"];
463
464
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
464
465
  function useMutableCallback(fn) {
@@ -490,7 +491,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
490
491
  return _a = class extends React__namespace.Component {
491
492
  constructor() {
492
493
  super(...arguments);
493
- __publicField$3(this, "state", { error: false });
494
+ __publicField$1(this, "state", { error: false });
494
495
  }
495
496
  componentDidCatch(err) {
496
497
  this.props.set(err);
@@ -498,7 +499,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
498
499
  render() {
499
500
  return this.state.error ? null : this.props.children;
500
501
  }
501
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
502
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
502
503
  })();
503
504
 
504
505
  const is = {
@@ -1658,1038 +1659,6 @@ function notifyAlpha({ message, link }) {
1658
1659
  }
1659
1660
  }
1660
1661
 
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
- }
1787
- }
1788
-
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);
1853
- }
1854
- }
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);
1859
- }
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
1662
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
2694
1663
  const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
2695
1664
  const createStore = (invalidate, advance) => {
@@ -2799,7 +1768,7 @@ const createStore = (invalidate, advance) => {
2799
1768
  size: newSize,
2800
1769
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2801
1770
  }));
2802
- getScheduler().invalidate();
1771
+ scheduler.getScheduler().invalidate();
2803
1772
  }
2804
1773
  }
2805
1774
  return;
@@ -2814,7 +1783,7 @@ const createStore = (invalidate, advance) => {
2814
1783
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2815
1784
  _sizeImperative: true
2816
1785
  }));
2817
- getScheduler().invalidate();
1786
+ scheduler.getScheduler().invalidate();
2818
1787
  },
2819
1788
  setDpr: (dpr) => set((state2) => {
2820
1789
  const resolved = calculateDpr(dpr);
@@ -2831,6 +1800,7 @@ const createStore = (invalidate, advance) => {
2831
1800
  buffers: {},
2832
1801
  gpuStorage: {},
2833
1802
  textures: /* @__PURE__ */ new Map(),
1803
+ _textureRefs: /* @__PURE__ */ new Map(),
2834
1804
  renderPipeline: null,
2835
1805
  passes: {},
2836
1806
  _hmrVersion: 0,
@@ -3021,7 +1991,7 @@ useLoader.loader = getLoader;
3021
1991
  function useFrame(callback, priorityOrOptions) {
3022
1992
  const store = React__namespace.useContext(context);
3023
1993
  const isInsideCanvas = store !== null;
3024
- const scheduler = getScheduler();
1994
+ const scheduler$1 = scheduler.getScheduler();
3025
1995
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
3026
1996
  id: priorityOrOptions.id,
3027
1997
  phase: priorityOrOptions.phase,
@@ -3069,7 +2039,7 @@ function useFrame(callback, priorityOrOptions) {
3069
2039
  };
3070
2040
  callbackRef.current?.(mergedState, delta);
3071
2041
  };
3072
- const unregister = scheduler.register(wrappedCallback, {
2042
+ const unregister = scheduler$1.register(wrappedCallback, {
3073
2043
  id,
3074
2044
  rootId,
3075
2045
  ...options
@@ -3090,37 +2060,31 @@ function useFrame(callback, priorityOrOptions) {
3090
2060
  }
3091
2061
  };
3092
2062
  } 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
- };
2063
+ return scheduler$1.register(
2064
+ (state, delta) => {
2065
+ const frameState = state;
2066
+ if (!frameState.renderer) return;
2067
+ callbackRef.current?.(frameState, delta);
2068
+ },
2069
+ { id, ...options }
2070
+ );
3107
2071
  }
3108
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2072
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3109
2073
  const isPaused = React__namespace.useSyncExternalStore(
3110
2074
  // Subscribe function
3111
2075
  React__namespace.useCallback(
3112
2076
  (onStoreChange) => {
3113
- return getScheduler().subscribeJobState(id, onStoreChange);
2077
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3114
2078
  },
3115
2079
  [id]
3116
2080
  ),
3117
2081
  // getSnapshot function
3118
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2082
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3119
2083
  // getServerSnapshot function (SSR)
3120
2084
  React__namespace.useCallback(() => false, [])
3121
2085
  );
3122
2086
  const controls = React__namespace.useMemo(() => {
3123
- const scheduler2 = getScheduler();
2087
+ const scheduler2 = scheduler.getScheduler();
3124
2088
  return {
3125
2089
  /** The job's unique ID */
3126
2090
  id,
@@ -3135,7 +2099,7 @@ function useFrame(callback, priorityOrOptions) {
3135
2099
  * @param timestamp Optional timestamp (defaults to performance.now())
3136
2100
  */
3137
2101
  step: (timestamp) => {
3138
- getScheduler().stepJob(id, timestamp);
2102
+ scheduler.getScheduler().stepJob(id, timestamp);
3139
2103
  },
3140
2104
  /**
3141
2105
  * Manually step ALL jobs in the scheduler.
@@ -3143,20 +2107,20 @@ function useFrame(callback, priorityOrOptions) {
3143
2107
  * @param timestamp Optional timestamp (defaults to performance.now())
3144
2108
  */
3145
2109
  stepAll: (timestamp) => {
3146
- getScheduler().step(timestamp);
2110
+ scheduler.getScheduler().step(timestamp);
3147
2111
  },
3148
2112
  /**
3149
2113
  * Pause this job (set enabled=false).
3150
2114
  * Job remains registered but won't run.
3151
2115
  */
3152
2116
  pause: () => {
3153
- getScheduler().pauseJob(id);
2117
+ scheduler.getScheduler().pauseJob(id);
3154
2118
  },
3155
2119
  /**
3156
2120
  * Resume this job (set enabled=true).
3157
2121
  */
3158
2122
  resume: () => {
3159
- getScheduler().resumeJob(id);
2123
+ scheduler.getScheduler().resumeJob(id);
3160
2124
  },
3161
2125
  /**
3162
2126
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3194,18 +2158,18 @@ function buildFromCache(input, textureCache) {
3194
2158
  function useTexture(input, optionsOrOnLoad) {
3195
2159
  const renderer = useThree((state) => state.internal.actualRenderer);
3196
2160
  const store = useStore();
3197
- const textureCache = useThree((state) => state.textures);
3198
2161
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3199
- const { onLoad, cache = false } = options;
2162
+ const { onLoad, cache = true } = options;
3200
2163
  const onLoadRef = React.useRef(onLoad);
3201
2164
  onLoadRef.current = onLoad;
3202
2165
  const onLoadCalledForRef = React.useRef(null);
3203
2166
  const urls = React.useMemo(() => getUrls(input), [input]);
3204
2167
  const cachedResult = React.useMemo(() => {
3205
2168
  if (!cache) return null;
3206
- if (!allUrlsCached(urls, textureCache)) return null;
3207
- return buildFromCache(input, textureCache);
3208
- }, [cache, urls, textureCache, input]);
2169
+ const textures = store.getState().textures;
2170
+ if (!allUrlsCached(urls, textures)) return null;
2171
+ return buildFromCache(input, textures);
2172
+ }, [cache, urls, input, store]);
3209
2173
  const loadedTextures = useLoader(
3210
2174
  webgpu.TextureLoader,
3211
2175
  IsObject(input) ? Object.values(input) : input
@@ -3249,8 +2213,6 @@ function useTexture(input, optionsOrOnLoad) {
3249
2213
  }, [input, loadedTextures, cachedResult]);
3250
2214
  React.useEffect(() => {
3251
2215
  if (!cache) return;
3252
- if (cachedResult) return;
3253
- const set = store.setState;
3254
2216
  const urlTextureMap = [];
3255
2217
  if (typeof input === "string") {
3256
2218
  urlTextureMap.push([input, mappedTextures]);
@@ -3264,18 +2226,32 @@ function useTexture(input, optionsOrOnLoad) {
3264
2226
  urlTextureMap.push([url, textureRecord[key]]);
3265
2227
  }
3266
2228
  }
3267
- set((state) => {
3268
- const newMap = new Map(state.textures);
3269
- let changed = false;
2229
+ store.setState((state) => {
2230
+ const refs = new Map(state._textureRefs);
2231
+ let textures = state.textures;
2232
+ let added = false;
3270
2233
  for (const [url, texture] of urlTextureMap) {
3271
- if (!newMap.has(url)) {
3272
- newMap.set(url, texture);
3273
- changed = true;
2234
+ if (!textures.has(url)) {
2235
+ if (!added) {
2236
+ textures = new Map(textures);
2237
+ added = true;
2238
+ }
2239
+ textures.set(url, texture);
3274
2240
  }
2241
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3275
2242
  }
3276
- return changed ? { textures: newMap } : state;
2243
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3277
2244
  });
3278
- }, [cache, input, mappedTextures, store, cachedResult]);
2245
+ return () => store.setState((state) => {
2246
+ const refs = new Map(state._textureRefs);
2247
+ for (const [url] of urlTextureMap) {
2248
+ const next = (refs.get(url) ?? 0) - 1;
2249
+ if (next <= 0) refs.delete(url);
2250
+ else refs.set(url, next);
2251
+ }
2252
+ return { _textureRefs: refs };
2253
+ });
2254
+ }, [cache, input, mappedTextures, store]);
3279
2255
  return mappedTextures;
3280
2256
  }
3281
2257
  useTexture.preload = (url) => useLoader.preload(webgpu.TextureLoader, url);
@@ -3291,96 +2267,63 @@ const Texture = ({
3291
2267
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3292
2268
  };
3293
2269
 
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() {
2270
+ function useTextures(selector) {
3302
2271
  const store = useStore();
3303
- return React.useMemo(() => {
3304
- const set = store.setState;
2272
+ const registry = React.useMemo(() => {
3305
2273
  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
- };
2274
+ const setState = store.setState;
2275
+ const getOne = (key) => getState().textures.get(key);
3364
2276
  return {
3365
- // Getter for the textures Map (reactive via getState)
3366
- get textures() {
2277
+ get all() {
3367
2278
  return getState().textures;
3368
2279
  },
3369
- // Read
3370
- get: (key) => getState().textures.get(key),
2280
+ get(input) {
2281
+ if (typeof input === "string") return getOne(input);
2282
+ if (Array.isArray(input)) return input.map(getOne);
2283
+ const out = {};
2284
+ for (const name in input) out[name] = getOne(input[name]);
2285
+ return out;
2286
+ },
3371
2287
  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
2288
+ add(keyOrRecord, texture) {
2289
+ setState((state) => {
2290
+ const textures = new Map(state.textures);
2291
+ if (typeof keyOrRecord === "string") {
2292
+ textures.set(keyOrRecord, texture);
2293
+ } else {
2294
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2295
+ }
2296
+ return { textures };
2297
+ });
2298
+ },
2299
+ dispose(key, options) {
2300
+ const state = getState();
2301
+ const refs = state._textureRefs.get(key) ?? 0;
2302
+ if (refs > 0 && !options?.force) {
2303
+ console.warn(
2304
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2305
+ );
2306
+ return false;
2307
+ }
2308
+ state.textures.get(key)?.dispose();
2309
+ setState((s) => {
2310
+ const textures = new Map(s.textures);
2311
+ textures.delete(key);
2312
+ const nextRefs = new Map(s._textureRefs);
2313
+ nextRefs.delete(key);
2314
+ return { textures, _textureRefs: nextRefs };
2315
+ });
2316
+ return true;
2317
+ },
2318
+ disposeAll() {
2319
+ for (const texture of getState().textures.values()) texture.dispose();
2320
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2321
+ }
3382
2322
  };
3383
2323
  }, [store]);
2324
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2325
+ const selected = useThree(subscribe);
2326
+ return selector ? selected : registry;
3384
2327
  }
3385
2328
 
3386
2329
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3435,7 +2378,7 @@ function addEffect(callback) {
3435
2378
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3436
2379
  });
3437
2380
  const id = `legacy_effect_${effectId++}`;
3438
- return getScheduler().registerGlobal("before", id, callback);
2381
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3439
2382
  }
3440
2383
  function addAfterEffect(callback) {
3441
2384
  notifyDepreciated({
@@ -3444,7 +2387,7 @@ function addAfterEffect(callback) {
3444
2387
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3445
2388
  });
3446
2389
  const id = `legacy_afterEffect_${effectId++}`;
3447
- return getScheduler().registerGlobal("after", id, callback);
2390
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3448
2391
  }
3449
2392
  function addTail(callback) {
3450
2393
  notifyDepreciated({
@@ -3452,13 +2395,13 @@ function addTail(callback) {
3452
2395
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3453
2396
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3454
2397
  });
3455
- return getScheduler().onIdle(callback);
2398
+ return scheduler.getScheduler().onIdle(callback);
3456
2399
  }
3457
2400
  function invalidate(state, frames = 1, stackFrames = false) {
3458
- getScheduler().invalidate(frames, stackFrames);
2401
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3459
2402
  }
3460
2403
  function advance(timestamp) {
3461
- getScheduler().step(timestamp);
2404
+ scheduler.getScheduler().step(timestamp);
3462
2405
  }
3463
2406
 
3464
2407
  const version = "10.0.0-alpha.2";
@@ -15485,15 +14428,15 @@ function createRoot(canvas) {
15485
14428
  applyProps(currentRenderer, rendererProps);
15486
14429
  }
15487
14430
  }
15488
- const scheduler = getScheduler();
14431
+ const scheduler$1 = scheduler.getScheduler();
15489
14432
  const rootId = state.internal.rootId;
15490
14433
  if (!rootId) {
15491
- const newRootId = canvasId || scheduler.generateRootId();
15492
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14434
+ const newRootId = canvasId || scheduler$1.generateRootId();
14435
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15493
14436
  getState: () => store.getState(),
15494
14437
  onError: (err) => store.getState().setError(err)
15495
14438
  });
15496
- const unregisterCanvasTarget = scheduler.register(
14439
+ const unregisterCanvasTarget = scheduler$1.register(
15497
14440
  () => {
15498
14441
  const state2 = store.getState();
15499
14442
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15508,7 +14451,7 @@ function createRoot(canvas) {
15508
14451
  system: true
15509
14452
  }
15510
14453
  );
15511
- const unregisterEventsFlush = scheduler.register(
14454
+ const unregisterEventsFlush = scheduler$1.register(
15512
14455
  () => {
15513
14456
  const state2 = store.getState();
15514
14457
  state2.events.flush?.();
@@ -15520,7 +14463,7 @@ function createRoot(canvas) {
15520
14463
  system: true
15521
14464
  }
15522
14465
  );
15523
- const unregisterFrustum = scheduler.register(
14466
+ const unregisterFrustum = scheduler$1.register(
15524
14467
  () => {
15525
14468
  const state2 = store.getState();
15526
14469
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15530,11 +14473,11 @@ function createRoot(canvas) {
15530
14473
  {
15531
14474
  id: `${newRootId}_frustum`,
15532
14475
  rootId: newRootId,
15533
- phase: "preRender",
14476
+ before: "render",
15534
14477
  system: true
15535
14478
  }
15536
14479
  );
15537
- const unregisterVisibility = scheduler.register(
14480
+ const unregisterVisibility = scheduler$1.register(
15538
14481
  () => {
15539
14482
  const state2 = store.getState();
15540
14483
  checkVisibility(state2);
@@ -15542,16 +14485,16 @@ function createRoot(canvas) {
15542
14485
  {
15543
14486
  id: `${newRootId}_visibility`,
15544
14487
  rootId: newRootId,
15545
- phase: "preRender",
14488
+ before: "render",
15546
14489
  system: true,
15547
14490
  after: `${newRootId}_frustum`
15548
14491
  }
15549
14492
  );
15550
- const unregisterRender = scheduler.register(
14493
+ const unregisterRender = scheduler$1.register(
15551
14494
  () => {
15552
14495
  const state2 = store.getState();
15553
14496
  const renderer2 = state2.internal.actualRenderer;
15554
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14497
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15555
14498
  if (userHandlesRender || state2.internal.priority) return;
15556
14499
  try {
15557
14500
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15584,11 +14527,11 @@ function createRoot(canvas) {
15584
14527
  unregisterVisibility();
15585
14528
  unregisterRender();
15586
14529
  },
15587
- scheduler
14530
+ scheduler: scheduler$1
15588
14531
  }
15589
14532
  }));
15590
14533
  }
15591
- scheduler.frameloop = frameloop;
14534
+ scheduler$1.frameloop = frameloop;
15592
14535
  onCreated = onCreatedCallback;
15593
14536
  configured = true;
15594
14537
  resolve();
@@ -15765,6 +14708,46 @@ function flushSync(fn) {
15765
14708
  return reconciler.flushSyncFromReconciler(fn);
15766
14709
  }
15767
14710
 
14711
+ function parseBackground(background) {
14712
+ if (!background) return null;
14713
+ if (typeof background === "object" && !background.isColor) {
14714
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14715
+ return {
14716
+ ...rest,
14717
+ preset,
14718
+ files: envMap || files,
14719
+ backgroundFiles: backgroundMap,
14720
+ background: true
14721
+ };
14722
+ }
14723
+ if (typeof background === "number") {
14724
+ return { color: background, background: true };
14725
+ }
14726
+ if (typeof background === "string") {
14727
+ if (background in presetsObj) {
14728
+ return { preset: background, background: true };
14729
+ }
14730
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14731
+ return { files: background, background: true };
14732
+ }
14733
+ return { color: background, background: true };
14734
+ }
14735
+ if (background.isColor) {
14736
+ return { color: background, background: true };
14737
+ }
14738
+ return null;
14739
+ }
14740
+
14741
+ function clearHmrCaches(store) {
14742
+ store.setState((state) => ({
14743
+ nodes: {},
14744
+ uniforms: {},
14745
+ buffers: {},
14746
+ gpuStorage: {},
14747
+ _hmrVersion: state._hmrVersion + 1
14748
+ }));
14749
+ }
14750
+
15768
14751
  function CanvasImpl({
15769
14752
  ref,
15770
14753
  children,
@@ -15785,6 +14768,8 @@ function CanvasImpl({
15785
14768
  raycaster,
15786
14769
  camera,
15787
14770
  scene,
14771
+ autoUpdateFrustum,
14772
+ occlusion,
15788
14773
  onPointerMissed,
15789
14774
  onDragOverMissed,
15790
14775
  onDropMissed,
@@ -15810,35 +14795,7 @@ function CanvasImpl({
15810
14795
  }
15811
14796
  React__namespace.useMemo(() => extend(THREE), []);
15812
14797
  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]);
14798
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15842
14799
  const hasInitialSizeRef = React__namespace.useRef(false);
15843
14800
  const measureConfig = React__namespace.useMemo(() => {
15844
14801
  if (!hasInitialSizeRef.current) {
@@ -15922,6 +14879,8 @@ function CanvasImpl({
15922
14879
  performance,
15923
14880
  raycaster,
15924
14881
  camera,
14882
+ autoUpdateFrustum,
14883
+ occlusion,
15925
14884
  size: effectiveSize,
15926
14885
  // Store size props for reset functionality
15927
14886
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15981,14 +14940,7 @@ function CanvasImpl({
15981
14940
  const handleHMR = () => {
15982
14941
  queueMicrotask(() => {
15983
14942
  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
- }
14943
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15992
14944
  });
15993
14945
  };
15994
14946
  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) {
@@ -16128,6 +15080,20 @@ function createLazyCreatorState(state) {
16128
15080
  });
16129
15081
  }
16130
15082
 
15083
+ function resolvePrimary(local) {
15084
+ return local.getState().primaryStore ?? local;
15085
+ }
15086
+ function usePrimaryStore() {
15087
+ const local = useStore();
15088
+ const primary = local.getState().primaryStore;
15089
+ return React.useMemo(() => primary ?? local, [primary, local]);
15090
+ }
15091
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15092
+ const local = useStore();
15093
+ const primary = resolvePrimary(local);
15094
+ return primary(selector, equalityFn);
15095
+ }
15096
+
16131
15097
  function addTexture(set, key, value) {
16132
15098
  set((state) => {
16133
15099
  const newMap = new Map(state.textures);
@@ -16233,7 +15199,7 @@ function useCompareMemoize(value, deep) {
16233
15199
 
16234
15200
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16235
15201
  function useUniforms(creatorOrScope, scope) {
16236
- const store = useStore();
15202
+ const store = usePrimaryStore();
16237
15203
  const removeUniforms2 = React.useCallback(
16238
15204
  (names, targetScope) => {
16239
15205
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16303,8 +15269,8 @@ function useUniforms(creatorOrScope, scope) {
16303
15269
  }, [creatorOrScope, store]);
16304
15270
  const memoizedInput = useCompareMemoize(inputForMemoization);
16305
15271
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16306
- const storeUniforms = useThree((s) => s.uniforms);
16307
- const hmrVersion = useThree((s) => s._hmrVersion);
15272
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15273
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16308
15274
  const readerDep = isReader ? storeUniforms : null;
16309
15275
  const creatorDep = isReader ? null : hmrVersion;
16310
15276
  const uniforms = React.useMemo(() => {
@@ -16365,6 +15331,7 @@ function useUniforms(creatorOrScope, scope) {
16365
15331
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16366
15332
  }
16367
15333
  function rebuildAllUniforms(store, scope) {
15334
+ store = store.getState().primaryStore ?? store;
16368
15335
  store.setState((state) => {
16369
15336
  let newUniforms = {};
16370
15337
  if (scope && scope !== "root") {
@@ -16493,7 +15460,7 @@ function useUniform(name, value) {
16493
15460
 
16494
15461
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16495
15462
  function useNodes(creatorOrScope, scope) {
16496
- const store = useStore();
15463
+ const store = usePrimaryStore();
16497
15464
  const removeNodes2 = React.useCallback(
16498
15465
  (names, targetScope) => {
16499
15466
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16550,8 +15517,8 @@ function useNodes(creatorOrScope, scope) {
16550
15517
  [store]
16551
15518
  );
16552
15519
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16553
- const storeNodes = useThree((s) => s.nodes);
16554
- const hmrVersion = useThree((s) => s._hmrVersion);
15520
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15521
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16555
15522
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16556
15523
  const readerDep = isReader ? storeNodes : null;
16557
15524
  const creatorDep = isReader ? null : hmrVersion;
@@ -16610,6 +15577,7 @@ function useNodes(creatorOrScope, scope) {
16610
15577
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16611
15578
  }
16612
15579
  function rebuildAllNodes(store, scope) {
15580
+ store = store.getState().primaryStore ?? store;
16613
15581
  store.setState((state) => {
16614
15582
  let newNodes = state.nodes;
16615
15583
  if (scope && scope !== "root") {
@@ -16654,11 +15622,11 @@ function clearRootNodes(set) {
16654
15622
  });
16655
15623
  }
16656
15624
  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);
15625
+ const store = usePrimaryStore();
15626
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15627
+ const nodes = usePrimaryThree((s) => s.nodes);
15628
+ const textures = usePrimaryThree((s) => s.textures);
15629
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16662
15630
  return React.useMemo(() => {
16663
15631
  const wrappedState = createLazyCreatorState(store.getState());
16664
15632
  return creator(wrappedState);
@@ -16679,7 +15647,7 @@ const disposeBuffer = (buffer) => {
16679
15647
  }
16680
15648
  };
16681
15649
  function useBuffers(creatorOrScope, scope) {
16682
- const store = useStore();
15650
+ const store = usePrimaryStore();
16683
15651
  const removeBuffers = React.useCallback(
16684
15652
  (names, targetScope) => {
16685
15653
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16750,8 +15718,8 @@ function useBuffers(creatorOrScope, scope) {
16750
15718
  [store, removeBuffers]
16751
15719
  );
16752
15720
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16753
- const storeBuffers = useThree((s) => s.buffers);
16754
- const hmrVersion = useThree((s) => s._hmrVersion);
15721
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15722
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16755
15723
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16756
15724
  const readerDep = isReader ? storeBuffers : null;
16757
15725
  const creatorDep = isReader ? null : hmrVersion;
@@ -16814,6 +15782,7 @@ function useBuffers(creatorOrScope, scope) {
16814
15782
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16815
15783
  }
16816
15784
  function rebuildAllBuffers(store, scope) {
15785
+ store = store.getState().primaryStore ?? store;
16817
15786
  store.setState((state) => {
16818
15787
  let newBuffers = state.buffers;
16819
15788
  if (scope && scope !== "root") {
@@ -16845,7 +15814,7 @@ const disposeStorage = (storage) => {
16845
15814
  }
16846
15815
  };
16847
15816
  function useGPUStorage(creatorOrScope, scope) {
16848
- const store = useStore();
15817
+ const store = usePrimaryStore();
16849
15818
  const removeStorage = React.useCallback(
16850
15819
  (names, targetScope) => {
16851
15820
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16916,8 +15885,8 @@ function useGPUStorage(creatorOrScope, scope) {
16916
15885
  [store, removeStorage]
16917
15886
  );
16918
15887
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16919
- const storeStorage = useThree((s) => s.gpuStorage);
16920
- const hmrVersion = useThree((s) => s._hmrVersion);
15888
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15889
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16921
15890
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16922
15891
  const readerDep = isReader ? storeStorage : null;
16923
15892
  const creatorDep = isReader ? null : hmrVersion;
@@ -16992,6 +15961,7 @@ function useGPUStorage(creatorOrScope, scope) {
16992
15961
  };
16993
15962
  }
16994
15963
  function rebuildAllStorage(store, scope) {
15964
+ store = store.getState().primaryStore ?? store;
16995
15965
  store.setState((state) => {
16996
15966
  let newStorage = state.gpuStorage;
16997
15967
  if (scope && scope !== "root") {
@@ -17104,6 +16074,8 @@ function useRenderPipeline(mainCB, setupCB) {
17104
16074
 
17105
16075
  extend(THREE);
17106
16076
 
16077
+ exports.Scheduler = scheduler.Scheduler;
16078
+ exports.getScheduler = scheduler.getScheduler;
17107
16079
  exports.Block = Block;
17108
16080
  exports.Canvas = Canvas;
17109
16081
  exports.Environment = Environment;
@@ -17119,7 +16091,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
17119
16091
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
17120
16092
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
17121
16093
  exports.RESERVED_PROPS = RESERVED_PROPS;
17122
- exports.Scheduler = Scheduler;
17123
16094
  exports.Texture = Texture;
17124
16095
  exports._roots = _roots;
17125
16096
  exports.act = act;
@@ -17155,7 +16126,6 @@ exports.getInstanceProps = getInstanceProps;
17155
16126
  exports.getPrimary = getPrimary;
17156
16127
  exports.getPrimaryIds = getPrimaryIds;
17157
16128
  exports.getRootState = getRootState;
17158
- exports.getScheduler = getScheduler;
17159
16129
  exports.getUuidPrefix = getUuidPrefix;
17160
16130
  exports.hasConstructor = hasConstructor;
17161
16131
  exports.hasPrimary = hasPrimary;