@react-three/fiber 10.0.0-canary.aecbafb → 10.0.0-canary.b6c54f2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/legacy.cjs CHANGED
@@ -13,6 +13,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
13
13
  const gainmapJs = require('@monogrid/gainmap-js');
14
14
  const Tb = require('scheduler');
15
15
  const traditional = require('zustand/traditional');
16
+ const scheduler = require('@pmndrs/scheduler');
16
17
  const suspendReact = require('suspend-react');
17
18
 
18
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -61,9 +62,12 @@ const WebGPURenderer = class WebGPURenderer2 {
61
62
  }
62
63
  };
63
64
  const RenderTarget = null;
65
+ const CubeRenderTarget = null;
64
66
 
65
67
  const THREE = /*#__PURE__*/_mergeNamespaces({
66
68
  __proto__: null,
69
+ CubeRenderTarget: CubeRenderTarget,
70
+ CubeRenderTargetCompat: three.WebGLCubeRenderTarget,
67
71
  Inspector: Inspector,
68
72
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
69
73
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
@@ -169,7 +173,7 @@ function useEnvironment({
169
173
  fiber.useLoader.clear(loader, multiFile ? [files] : files);
170
174
  }
171
175
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
172
- }, [files, renderer.domElement]);
176
+ }, [extension, files, loader, multiFile, renderer.domElement]);
173
177
  const loaderResult = fiber.useLoader(
174
178
  loader,
175
179
  multiFile ? [files] : files,
@@ -341,15 +345,16 @@ function EnvironmentPortal({
341
345
  preset = void 0,
342
346
  extensions
343
347
  }) {
344
- const gl = fiber.useThree((state) => state.gl);
348
+ const renderer = fiber.useThree((state) => state.renderer);
349
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
345
350
  const defaultScene = fiber.useThree((state) => state.scene);
346
351
  const camera = React__namespace.useRef(null);
347
352
  const [virtualScene] = React__namespace.useState(() => new three.Scene());
348
353
  const fbo = React__namespace.useMemo(() => {
349
- const fbo2 = new three.WebGLCubeRenderTarget(resolution);
354
+ const fbo2 = isLegacy ? new three.WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
350
355
  fbo2.texture.type = three.HalfFloatType;
351
356
  return fbo2;
352
- }, [resolution]);
357
+ }, [resolution, isLegacy]);
353
358
  React__namespace.useEffect(() => {
354
359
  return () => {
355
360
  fbo.dispose();
@@ -357,10 +362,10 @@ function EnvironmentPortal({
357
362
  }, [fbo]);
358
363
  React__namespace.useLayoutEffect(() => {
359
364
  if (frames === 1) {
360
- const autoClear = gl.autoClear;
361
- gl.autoClear = true;
362
- camera.current.update(gl, virtualScene);
363
- gl.autoClear = autoClear;
365
+ const autoClear = renderer.autoClear;
366
+ renderer.autoClear = true;
367
+ camera.current.update(renderer, virtualScene);
368
+ renderer.autoClear = autoClear;
364
369
  }
365
370
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
366
371
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -369,14 +374,29 @@ function EnvironmentPortal({
369
374
  environmentIntensity,
370
375
  environmentRotation
371
376
  });
372
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
377
+ }, [
378
+ children,
379
+ virtualScene,
380
+ fbo.texture,
381
+ scene,
382
+ defaultScene,
383
+ background,
384
+ frames,
385
+ renderer,
386
+ blur,
387
+ backgroundBlurriness,
388
+ backgroundIntensity,
389
+ backgroundRotation,
390
+ environmentIntensity,
391
+ environmentRotation
392
+ ]);
373
393
  let count = 1;
374
394
  fiber.useFrame(() => {
375
395
  if (frames === Infinity || count < frames) {
376
- const autoClear = gl.autoClear;
377
- gl.autoClear = true;
378
- camera.current.update(gl, virtualScene);
379
- gl.autoClear = autoClear;
396
+ const autoClear = renderer.autoClear;
397
+ renderer.autoClear = true;
398
+ camera.current.update(renderer, virtualScene);
399
+ renderer.autoClear = autoClear;
380
400
  count++;
381
401
  }
382
402
  });
@@ -440,9 +460,9 @@ function Environment(props) {
440
460
  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 });
441
461
  }
442
462
 
443
- var __defProp$2 = Object.defineProperty;
444
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
445
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
463
+ var __defProp = Object.defineProperty;
464
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
465
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
446
466
  const act = React__namespace["act"];
447
467
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
448
468
  function useMutableCallback(fn) {
@@ -474,7 +494,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
474
494
  return _a = class extends React__namespace.Component {
475
495
  constructor() {
476
496
  super(...arguments);
477
- __publicField$2(this, "state", { error: false });
497
+ __publicField(this, "state", { error: false });
478
498
  }
479
499
  componentDidCatch(err) {
480
500
  this.props.set(err);
@@ -482,7 +502,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
482
502
  render() {
483
503
  return this.state.error ? null : this.props.children;
484
504
  }
485
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
505
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
506
  })();
487
507
 
488
508
  const is = {
@@ -619,8 +639,7 @@ function prepare(target, root, type, props) {
619
639
  object,
620
640
  eventCount: 0,
621
641
  handlers: {},
622
- isHidden: false,
623
- deferredRefs: []
642
+ isHidden: false
624
643
  };
625
644
  if (object) object.__r3f = instance;
626
645
  }
@@ -777,6 +796,17 @@ function unregisterVisibility(store, object) {
777
796
  internal.visibilityRegistry.delete(object.uuid);
778
797
  internal.occlusionCache.delete(object);
779
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
+ }
780
810
  function checkVisibility(state) {
781
811
  const { internal, camera } = state;
782
812
  const registry = internal.visibilityRegistry;
@@ -964,10 +994,7 @@ function applyProps(object, props) {
964
994
  continue;
965
995
  }
966
996
  if (value === void 0) continue;
967
- if (isFromRef(value)) {
968
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
969
- continue;
970
- }
997
+ if (isFromRef(value)) continue;
971
998
  if (isOnce(value)) {
972
999
  if (instance?.appliedOnce?.has(prop)) continue;
973
1000
  if (instance) {
@@ -1003,6 +1030,19 @@ function applyProps(object, props) {
1003
1030
  } else if (isVectorLike(target) && is.num(value)) {
1004
1031
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1005
1032
  else target.set(value);
1033
+ } else if (root instanceof three.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 three.Uniform ? uniform.clone() : new three.Uniform(uniform.value);
1043
+ uniforms[name] = nextUniform;
1044
+ }
1045
+ }
1006
1046
  } else {
1007
1047
  root[key] = value;
1008
1048
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1021,6 +1061,9 @@ function applyProps(object, props) {
1021
1061
  if (instance.eventCount && object2.raycast !== null) {
1022
1062
  rootState.internal.interaction.push(object2);
1023
1063
  }
1064
+ }
1065
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1066
+ const object2 = instance.object;
1024
1067
  const root = findInitialRoot(instance);
1025
1068
  const visibilityHandlers = {
1026
1069
  onFramed: instance.handlers.onFramed,
@@ -1028,7 +1071,9 @@ function applyProps(object, props) {
1028
1071
  onVisible: instance.handlers.onVisible
1029
1072
  };
1030
1073
  if (hasVisibilityHandlers(visibilityHandlers)) {
1031
- registerVisibility(root, object2, visibilityHandlers);
1074
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1075
+ registerVisibility(root, object2, visibilityHandlers);
1076
+ }
1032
1077
  } else {
1033
1078
  unregisterVisibility(root, object2);
1034
1079
  }
@@ -1296,7 +1341,7 @@ function createEvents(store) {
1296
1341
  }
1297
1342
  function processDeferredPointer(event, pointerId) {
1298
1343
  const state = store.getState();
1299
- const { onPointerMissed, onDragOverMissed, internal } = state;
1344
+ const { internal } = state;
1300
1345
  if (!state.events.enabled) return;
1301
1346
  const filter = filterPointerEvents;
1302
1347
  const hits = intersect(event, filter);
@@ -1531,6 +1576,7 @@ function createPointerEvents(store) {
1531
1576
  }
1532
1577
  },
1533
1578
  connect: (target) => {
1579
+ if (!target) return;
1534
1580
  const { set, events } = store.getState();
1535
1581
  events.disconnect?.();
1536
1582
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1555,6 +1601,7 @@ function createPointerEvents(store) {
1555
1601
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1556
1602
  }
1557
1603
  },
1604
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1558
1605
  registerPointer: (config) => {
1559
1606
  const pointerId = nextXRPointerId++;
1560
1607
  xrPointers.set(pointerId, config);
@@ -1641,1036 +1688,11 @@ function notifyAlpha({ message, link }) {
1641
1688
  }
1642
1689
  }
1643
1690
 
1644
- var __defProp$1 = Object.defineProperty;
1645
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1646
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1647
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1648
- class PhaseGraph {
1649
- constructor() {
1650
- /** Ordered list of phase nodes */
1651
- __publicField$1(this, "phases", []);
1652
- /** Quick lookup by name */
1653
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1654
- /** Cached ordered names (invalidated on changes) */
1655
- __publicField$1(this, "orderedNamesCache", null);
1656
- this.initializeDefaultPhases();
1657
- }
1658
- //* Initialization --------------------------------
1659
- initializeDefaultPhases() {
1660
- for (const name of DEFAULT_PHASES) {
1661
- const node = { name, isAutoGenerated: false };
1662
- this.phases.push(node);
1663
- this.phaseMap.set(name, node);
1664
- }
1665
- this.invalidateCache();
1666
- }
1667
- //* Public API --------------------------------
1668
- /**
1669
- * Add a named phase to the graph
1670
- * @param name - Phase name (must be unique)
1671
- * @param options - Position options (before or after another phase)
1672
- */
1673
- addPhase(name, options = {}) {
1674
- if (this.phaseMap.has(name)) {
1675
- console.warn(`[useFrame] Phase "${name}" already exists`);
1676
- return;
1677
- }
1678
- const { before, after } = options;
1679
- const node = { name, isAutoGenerated: false };
1680
- let insertIndex = this.phases.length;
1681
- const targetIndex = this.getPhaseIndex(before ?? after);
1682
- if (targetIndex !== -1) {
1683
- insertIndex = before ? targetIndex : targetIndex + 1;
1684
- } else {
1685
- const constraintType = before ? "before" : "after";
1686
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1687
- }
1688
- this.phases.splice(insertIndex, 0, node);
1689
- this.phaseMap.set(name, node);
1690
- this.invalidateCache();
1691
- }
1692
- /**
1693
- * Get ordered list of phase names
1694
- */
1695
- getOrderedPhases() {
1696
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1697
- return this.orderedNamesCache;
1698
- }
1699
- /**
1700
- * Check if a phase exists
1701
- */
1702
- hasPhase(name) {
1703
- return this.phaseMap.has(name);
1704
- }
1705
- /**
1706
- * Get the index of a phase (-1 if not found)
1707
- */
1708
- getPhaseIndex(name) {
1709
- if (!name) return -1;
1710
- return this.phases.findIndex((p) => p.name === name);
1711
- }
1712
- /**
1713
- * Ensure a phase exists, creating an auto-generated one if needed.
1714
- * Used for resolving before/after constraints.
1715
- *
1716
- * @param name - The phase name to ensure exists
1717
- * @returns The phase name (may be auto-generated like 'before:render')
1718
- */
1719
- ensurePhase(name) {
1720
- if (this.phaseMap.has(name)) return name;
1721
- const node = { name, isAutoGenerated: true };
1722
- this.phases.push(node);
1723
- this.phaseMap.set(name, node);
1724
- this.invalidateCache();
1725
- return name;
1726
- }
1727
- /**
1728
- * Resolve where a job with before/after constraints should go.
1729
- * Creates auto-generated phases if needed.
1730
- *
1731
- * @param before - Phase(s) to run before
1732
- * @param after - Phase(s) to run after
1733
- * @returns The resolved phase name
1734
- */
1735
- resolveConstraintPhase(before, after) {
1736
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1737
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1738
- if (beforeArr.length > 0) {
1739
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1740
- }
1741
- if (afterArr.length > 0) {
1742
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1743
- }
1744
- return "update";
1745
- }
1746
- /**
1747
- * Ensure an auto-generated phase exists relative to a target phase.
1748
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1749
- *
1750
- * @param target - The target phase name to position relative to
1751
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1752
- * @param offset - Insertion offset (0 for before, 1 for after)
1753
- * @returns The auto-generated phase name
1754
- */
1755
- ensureAutoPhase(target, prefix, offset) {
1756
- const autoName = `${prefix}:${target}`;
1757
- if (this.phaseMap.has(autoName)) return autoName;
1758
- const node = { name: autoName, isAutoGenerated: true };
1759
- const targetIndex = this.getPhaseIndex(target);
1760
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1761
- else this.phases.push(node);
1762
- this.phaseMap.set(autoName, node);
1763
- this.invalidateCache();
1764
- return autoName;
1765
- }
1766
- // Internal --------------------------------
1767
- invalidateCache() {
1768
- this.orderedNamesCache = null;
1769
- }
1770
- }
1771
-
1772
- function rebuildSortedJobs(jobs, phaseGraph) {
1773
- const orderedPhases = phaseGraph.getOrderedPhases();
1774
- const buckets = /* @__PURE__ */ new Map();
1775
- for (const phase of orderedPhases) {
1776
- buckets.set(phase, []);
1777
- }
1778
- for (const job of jobs.values()) {
1779
- if (!job.enabled) continue;
1780
- let bucket = buckets.get(job.phase);
1781
- if (!bucket) {
1782
- bucket = [];
1783
- buckets.set(job.phase, bucket);
1784
- }
1785
- bucket.push(job);
1786
- }
1787
- const sortedBuckets = [];
1788
- for (const phase of orderedPhases) {
1789
- const bucket = buckets.get(phase);
1790
- if (!bucket || bucket.length === 0) continue;
1791
- bucket.sort((a, b) => {
1792
- if (a.priority !== b.priority) return b.priority - a.priority;
1793
- return a.index - b.index;
1794
- });
1795
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1796
- }
1797
- for (const [phase, bucket] of buckets) {
1798
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1799
- bucket.sort((a, b) => {
1800
- if (a.priority !== b.priority) return b.priority - a.priority;
1801
- return a.index - b.index;
1802
- });
1803
- sortedBuckets.push(bucket);
1804
- }
1805
- }
1806
- return sortedBuckets.flat();
1807
- }
1808
- function hasCrossJobConstraints(bucket) {
1809
- const jobIds = new Set(bucket.map((j) => j.id));
1810
- for (const job of bucket) {
1811
- for (const ref of job.before) {
1812
- if (jobIds.has(ref)) return true;
1813
- }
1814
- for (const ref of job.after) {
1815
- if (jobIds.has(ref)) return true;
1816
- }
1817
- }
1818
- return false;
1819
- }
1820
- function topologicalSort(jobs) {
1821
- const n = jobs.length;
1822
- if (n <= 1) return jobs;
1823
- const jobMap = /* @__PURE__ */ new Map();
1824
- const inDegree = /* @__PURE__ */ new Map();
1825
- const adjacency = /* @__PURE__ */ new Map();
1826
- for (const job of jobs) {
1827
- jobMap.set(job.id, job);
1828
- inDegree.set(job.id, 0);
1829
- adjacency.set(job.id, []);
1830
- }
1831
- for (const job of jobs) {
1832
- for (const ref of job.before) {
1833
- if (jobMap.has(ref)) {
1834
- adjacency.get(job.id).push(ref);
1835
- inDegree.set(ref, inDegree.get(ref) + 1);
1836
- }
1837
- }
1838
- for (const ref of job.after) {
1839
- if (jobMap.has(ref)) {
1840
- adjacency.get(ref).push(job.id);
1841
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1842
- }
1843
- }
1844
- }
1845
- const queue = [];
1846
- for (const job of jobs) {
1847
- if (inDegree.get(job.id) === 0) {
1848
- queue.push(job);
1849
- }
1850
- }
1851
- queue.sort((a, b) => {
1852
- if (a.priority !== b.priority) return b.priority - a.priority;
1853
- return a.index - b.index;
1854
- });
1855
- const result = [];
1856
- while (queue.length > 0) {
1857
- const job = queue.shift();
1858
- result.push(job);
1859
- const neighbors = adjacency.get(job.id) || [];
1860
- for (const neighborId of neighbors) {
1861
- const newDegree = inDegree.get(neighborId) - 1;
1862
- inDegree.set(neighborId, newDegree);
1863
- if (newDegree === 0) {
1864
- const neighbor = jobMap.get(neighborId);
1865
- insertSorted(queue, neighbor);
1866
- }
1867
- }
1868
- }
1869
- if (result.length !== n) {
1870
- console.warn("[useFrame] Circular dependency detected in job constraints");
1871
- const resultIds = new Set(result.map((j) => j.id));
1872
- for (const job of jobs) {
1873
- if (!resultIds.has(job.id)) result.push(job);
1874
- }
1875
- }
1876
- return result;
1877
- }
1878
- function insertSorted(arr, job) {
1879
- let i = 0;
1880
- while (i < arr.length) {
1881
- const cmp = arr[i];
1882
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1883
- break;
1884
- }
1885
- i++;
1886
- }
1887
- arr.splice(i, 0, job);
1888
- }
1889
-
1890
- function shouldRun(job, now) {
1891
- if (!job.enabled) return false;
1892
- if (!job.fps) return true;
1893
- const minInterval = 1e3 / job.fps;
1894
- const lastRun = job.lastRun ?? 0;
1895
- const elapsed = now - lastRun;
1896
- if (elapsed < minInterval) return false;
1897
- if (job.drop) {
1898
- job.lastRun = now;
1899
- } else {
1900
- const steps = Math.floor(elapsed / minInterval);
1901
- job.lastRun = lastRun + steps * minInterval;
1902
- if (job.lastRun < now - minInterval) {
1903
- job.lastRun = now;
1904
- }
1905
- }
1906
- return true;
1907
- }
1908
- function resetJobTiming(job) {
1909
- job.lastRun = void 0;
1910
- }
1911
-
1912
- var __defProp = Object.defineProperty;
1913
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1914
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1915
- const hmrData = (() => {
1916
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1917
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1918
- try {
1919
- return (0, eval)("import.meta.hot");
1920
- } catch {
1921
- return void 0;
1922
- }
1923
- })();
1924
- const _Scheduler = class _Scheduler {
1925
- //* Constructor ================================
1926
- constructor() {
1927
- //* Critical State ================================
1928
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1929
- __publicField(this, "phaseGraph");
1930
- __publicField(this, "loopState", {
1931
- running: false,
1932
- rafHandle: null,
1933
- lastTime: null,
1934
- // null = uninitialized, 0+ = valid timestamp
1935
- frameCount: 0,
1936
- elapsedTime: 0,
1937
- createdAt: performance.now()
1938
- });
1939
- __publicField(this, "stoppedTime", 0);
1940
- //* Private State ================================
1941
- __publicField(this, "nextRootIndex", 0);
1942
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1943
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1944
- __publicField(this, "nextGlobalIndex", 0);
1945
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1946
- __publicField(this, "nextJobIndex", 0);
1947
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1948
- __publicField(this, "pendingFrames", 0);
1949
- __publicField(this, "_frameloop", "always");
1950
- //* Independent Mode & Error Handling State ================================
1951
- __publicField(this, "_independent", false);
1952
- __publicField(this, "errorHandler", null);
1953
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1954
- //* Core Loop Execution Methods ================================
1955
- /**
1956
- * Main RAF loop callback.
1957
- * Executes frame, handles demand mode, and schedules next frame.
1958
- * @param {number} timestamp - RAF timestamp in milliseconds
1959
- * @returns {void}
1960
- * @private
1961
- */
1962
- __publicField(this, "loop", (timestamp) => {
1963
- if (!this.loopState.running) return;
1964
- this.executeFrame(timestamp);
1965
- if (this._frameloop === "demand") {
1966
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1967
- if (this.pendingFrames === 0) {
1968
- this.notifyIdle(timestamp);
1969
- return this.stop();
1970
- }
1971
- }
1972
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1973
- });
1974
- this.phaseGraph = new PhaseGraph();
1975
- }
1976
- static get instance() {
1977
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1978
- }
1979
- static set instance(value) {
1980
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1981
- }
1982
- /**
1983
- * Get the global scheduler instance (creates if doesn't exist).
1984
- * Uses HMR data to preserve instance across hot reloads.
1985
- * @returns {Scheduler} The singleton scheduler instance
1986
- */
1987
- static get() {
1988
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1989
- _Scheduler.instance = hmrData.data.scheduler;
1990
- }
1991
- if (!_Scheduler.instance) {
1992
- _Scheduler.instance = new _Scheduler();
1993
- if (hmrData?.data) {
1994
- hmrData.data.scheduler = _Scheduler.instance;
1995
- }
1996
- }
1997
- return _Scheduler.instance;
1998
- }
1999
- /**
2000
- * Reset the singleton instance. Stops the loop and clears all state.
2001
- * Primarily used for testing to ensure clean state between tests.
2002
- * @returns {void}
2003
- */
2004
- static reset() {
2005
- if (_Scheduler.instance) {
2006
- _Scheduler.instance.stop();
2007
- _Scheduler.instance = null;
2008
- }
2009
- if (hmrData?.data) {
2010
- hmrData.data.scheduler = null;
2011
- }
2012
- }
2013
- //* Getters & Setters ================================
2014
- get phases() {
2015
- return this.phaseGraph.getOrderedPhases();
2016
- }
2017
- get frameloop() {
2018
- return this._frameloop;
2019
- }
2020
- set frameloop(mode) {
2021
- if (this._frameloop === mode) return;
2022
- const wasAlways = this._frameloop === "always";
2023
- this._frameloop = mode;
2024
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2025
- else if (mode !== "always" && wasAlways) this.stop();
2026
- }
2027
- get isRunning() {
2028
- return this.loopState.running;
2029
- }
2030
- get isReady() {
2031
- return this.roots.size > 0;
2032
- }
2033
- get independent() {
2034
- return this._independent;
2035
- }
2036
- set independent(value) {
2037
- this._independent = value;
2038
- if (value) this.ensureDefaultRoot();
2039
- }
2040
- //* Root Management Methods ================================
2041
- /**
2042
- * Register a root (Canvas) with the scheduler.
2043
- * The first root to register starts the RAF loop (if frameloop='always').
2044
- * @param {string} id - Unique identifier for this root
2045
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2046
- * @returns {() => void} Unsubscribe function to remove this root
2047
- */
2048
- registerRoot(id, options = {}) {
2049
- if (this.roots.has(id)) {
2050
- console.warn(`[Scheduler] Root "${id}" already registered`);
2051
- return () => this.unregisterRoot(id);
2052
- }
2053
- const entry = {
2054
- id,
2055
- getState: options.getState ?? (() => ({})),
2056
- jobs: /* @__PURE__ */ new Map(),
2057
- sortedJobs: [],
2058
- needsRebuild: false
2059
- };
2060
- if (options.onError) {
2061
- this.errorHandler = options.onError;
2062
- }
2063
- this.roots.set(id, entry);
2064
- if (this.roots.size === 1) {
2065
- this.notifyRootReady();
2066
- if (this._frameloop === "always") this.start();
2067
- }
2068
- return () => this.unregisterRoot(id);
2069
- }
2070
- /**
2071
- * Unregister a root from the scheduler.
2072
- * Cleans up all job state listeners for this root's jobs.
2073
- * The last root to unregister stops the RAF loop.
2074
- * @param {string} id - The root ID to unregister
2075
- * @returns {void}
2076
- */
2077
- unregisterRoot(id) {
2078
- const root = this.roots.get(id);
2079
- if (!root) return;
2080
- for (const jobId of root.jobs.keys()) {
2081
- this.jobStateListeners.delete(jobId);
2082
- }
2083
- this.roots.delete(id);
2084
- if (this.roots.size === 0) {
2085
- this.stop();
2086
- this.errorHandler = null;
2087
- }
2088
- }
2089
- /**
2090
- * Subscribe to be notified when a root becomes available.
2091
- * Fires immediately if a root already exists.
2092
- * @param {() => void} callback - Function called when first root registers
2093
- * @returns {() => void} Unsubscribe function
2094
- */
2095
- onRootReady(callback) {
2096
- if (this.roots.size > 0) {
2097
- callback();
2098
- return () => {
2099
- };
2100
- }
2101
- this.rootReadyCallbacks.add(callback);
2102
- return () => this.rootReadyCallbacks.delete(callback);
2103
- }
2104
- /**
2105
- * Notify all registered root-ready callbacks.
2106
- * Called when the first root registers.
2107
- * @returns {void}
2108
- * @private
2109
- */
2110
- notifyRootReady() {
2111
- for (const cb of this.rootReadyCallbacks) {
2112
- try {
2113
- cb();
2114
- } catch (error) {
2115
- console.error("[Scheduler] Error in root-ready callback:", error);
2116
- }
2117
- }
2118
- this.rootReadyCallbacks.clear();
2119
- }
2120
- /**
2121
- * Ensure a default root exists for independent mode.
2122
- * Creates a minimal root with no state provider.
2123
- * @returns {void}
2124
- * @private
2125
- */
2126
- ensureDefaultRoot() {
2127
- if (!this.roots.has("__default__")) {
2128
- this.registerRoot("__default__");
2129
- }
2130
- }
2131
- /**
2132
- * Trigger error handling for job errors.
2133
- * Uses the bound error handler if available, otherwise logs to console.
2134
- * @param {Error} error - The error to handle
2135
- * @returns {void}
2136
- */
2137
- triggerError(error) {
2138
- if (this.errorHandler) this.errorHandler(error);
2139
- else console.error("[Scheduler]", error);
2140
- }
2141
- //* Phase Management Methods ================================
2142
- /**
2143
- * Add a named phase to the scheduler's execution order.
2144
- * Marks all roots for rebuild to incorporate the new phase.
2145
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2146
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2147
- * @returns {void}
2148
- * @example
2149
- * scheduler.addPhase('physics', { before: 'update' });
2150
- * scheduler.addPhase('postprocess', { after: 'render' });
2151
- */
2152
- addPhase(name, options) {
2153
- this.phaseGraph.addPhase(name, options);
2154
- for (const root of this.roots.values()) {
2155
- root.needsRebuild = true;
2156
- }
2157
- }
2158
- /**
2159
- * Check if a phase exists in the scheduler.
2160
- * @param {string} name - The phase name to check
2161
- * @returns {boolean} True if the phase exists
2162
- */
2163
- hasPhase(name) {
2164
- return this.phaseGraph.hasPhase(name);
2165
- }
2166
- //* Global Job Registration Methods (Deprecated APIs) ================================
2167
- /**
2168
- * Register a global job that runs once per frame (not per-root).
2169
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2170
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2171
- * @param {string} id - Unique identifier for this global job
2172
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2173
- * @returns {() => void} Unsubscribe function to remove this global job
2174
- * @deprecated Use useFrame with phases instead
2175
- */
2176
- registerGlobal(phase, id, callback) {
2177
- const job = { id, callback };
2178
- if (phase === "before") {
2179
- this.globalBeforeJobs.set(id, job);
2180
- } else {
2181
- this.globalAfterJobs.set(id, job);
2182
- }
2183
- return () => {
2184
- if (phase === "before") this.globalBeforeJobs.delete(id);
2185
- else this.globalAfterJobs.delete(id);
2186
- };
2187
- }
2188
- //* Idle Callback Methods (Deprecated API) ================================
2189
- /**
2190
- * Register an idle callback that fires when the loop stops.
2191
- * Used internally by deprecated addTail API.
2192
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2193
- * @returns {() => void} Unsubscribe function to remove this idle callback
2194
- * @deprecated Use demand mode with invalidate() instead
2195
- */
2196
- onIdle(callback) {
2197
- this.idleCallbacks.add(callback);
2198
- return () => this.idleCallbacks.delete(callback);
2199
- }
2200
- /**
2201
- * Notify all registered idle callbacks.
2202
- * Called when the loop stops in demand mode.
2203
- * @param {number} timestamp - The RAF timestamp when idle occurred
2204
- * @returns {void}
2205
- * @private
2206
- */
2207
- notifyIdle(timestamp) {
2208
- for (const cb of this.idleCallbacks) {
2209
- try {
2210
- cb(timestamp);
2211
- } catch (error) {
2212
- console.error("[Scheduler] Error in idle callback:", error);
2213
- }
2214
- }
2215
- }
2216
- //* Job Registration & Management Methods ================================
2217
- /**
2218
- * Register a job (frame callback) with a specific root.
2219
- * This is the core registration method used by useFrame internally.
2220
- * @param {FrameNextCallback} callback - The function to call each frame
2221
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2222
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2223
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2224
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2225
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2226
- * @param {number} [options.fps] - FPS throttle limit
2227
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2228
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2229
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2230
- * @returns {() => void} Unsubscribe function to remove this job
2231
- */
2232
- register(callback, options = {}) {
2233
- const rootId = options.rootId;
2234
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2235
- if (!root) {
2236
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2237
- return () => {
2238
- };
2239
- }
2240
- const id = options.id ?? this.generateJobId();
2241
- let phase = options.phase ?? "update";
2242
- if (!options.phase && (options.before || options.after)) {
2243
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2244
- }
2245
- const before = this.normalizeConstraints(options.before);
2246
- const after = this.normalizeConstraints(options.after);
2247
- const job = {
2248
- id,
2249
- callback,
2250
- phase,
2251
- before,
2252
- after,
2253
- priority: options.priority ?? 0,
2254
- index: this.nextJobIndex++,
2255
- fps: options.fps,
2256
- drop: options.drop ?? true,
2257
- enabled: options.enabled ?? true,
2258
- system: options.system ?? false
2259
- };
2260
- if (root.jobs.has(id)) {
2261
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2262
- }
2263
- root.jobs.set(id, job);
2264
- root.needsRebuild = true;
2265
- return () => this.unregister(id, root.id);
2266
- }
2267
- /**
2268
- * Unregister a job by its ID.
2269
- * Searches all roots if rootId is not provided.
2270
- * @param {string} id - The job ID to unregister
2271
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2272
- * @returns {void}
2273
- */
2274
- unregister(id, rootId) {
2275
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2276
- if (root?.jobs.delete(id)) {
2277
- root.needsRebuild = true;
2278
- this.jobStateListeners.delete(id);
2279
- }
2280
- }
2281
- /**
2282
- * Update a job's options dynamically.
2283
- * Searches all roots to find the job by ID.
2284
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2285
- * @param {string} id - The job ID to update
2286
- * @param {Partial<JobOptions>} options - The options to update
2287
- * @returns {void}
2288
- */
2289
- updateJob(id, options) {
2290
- let job;
2291
- let root;
2292
- for (const r of this.roots.values()) {
2293
- job = r.jobs.get(id);
2294
- if (job) {
2295
- root = r;
2296
- break;
2297
- }
2298
- }
2299
- if (!job || !root) return;
2300
- if (options.priority !== void 0) job.priority = options.priority;
2301
- if (options.fps !== void 0) job.fps = options.fps;
2302
- if (options.drop !== void 0) job.drop = options.drop;
2303
- if (options.enabled !== void 0) {
2304
- const wasEnabled = job.enabled;
2305
- job.enabled = options.enabled;
2306
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2307
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2308
- }
2309
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2310
- if (options.phase) job.phase = options.phase;
2311
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2312
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2313
- root.needsRebuild = true;
2314
- }
2315
- }
2316
- //* Job State Management Methods ================================
2317
- /**
2318
- * Check if a job is currently paused (disabled).
2319
- * @param {string} id - The job ID to check
2320
- * @returns {boolean} True if the job exists and is paused
2321
- */
2322
- isJobPaused(id) {
2323
- for (const root of this.roots.values()) {
2324
- const job = root.jobs.get(id);
2325
- if (job) return !job.enabled;
2326
- }
2327
- return false;
2328
- }
2329
- /**
2330
- * Subscribe to state changes for a specific job.
2331
- * Listener is called when job is paused or resumed.
2332
- * @param {string} id - The job ID to subscribe to
2333
- * @param {() => void} listener - Callback invoked on state changes
2334
- * @returns {() => void} Unsubscribe function
2335
- */
2336
- subscribeJobState(id, listener) {
2337
- if (!this.jobStateListeners.has(id)) {
2338
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2339
- }
2340
- this.jobStateListeners.get(id).add(listener);
2341
- return () => {
2342
- this.jobStateListeners.get(id)?.delete(listener);
2343
- if (this.jobStateListeners.get(id)?.size === 0) {
2344
- this.jobStateListeners.delete(id);
2345
- }
2346
- };
2347
- }
2348
- /**
2349
- * Notify all listeners that a job's state has changed.
2350
- * @param {string} id - The job ID that changed
2351
- * @returns {void}
2352
- * @private
2353
- */
2354
- notifyJobStateChange(id) {
2355
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2356
- }
2357
- /**
2358
- * Pause a job by ID (sets enabled=false).
2359
- * Notifies any subscribed state listeners.
2360
- * @param {string} id - The job ID to pause
2361
- * @returns {void}
2362
- */
2363
- pauseJob(id) {
2364
- this.updateJob(id, { enabled: false });
2365
- this.notifyJobStateChange(id);
2366
- }
2367
- /**
2368
- * Resume a paused job by ID (sets enabled=true).
2369
- * Resets job timing to prevent frame accumulation.
2370
- * Notifies any subscribed state listeners.
2371
- * @param {string} id - The job ID to resume
2372
- * @returns {void}
2373
- */
2374
- resumeJob(id) {
2375
- this.updateJob(id, { enabled: true });
2376
- this.notifyJobStateChange(id);
2377
- }
2378
- //* Frame Loop Control Methods ================================
2379
- /**
2380
- * Start the requestAnimationFrame loop.
2381
- * Resets timing state (elapsedTime, frameCount) on start.
2382
- * No-op if already running.
2383
- * @returns {void}
2384
- */
2385
- start() {
2386
- if (this.loopState.running) return;
2387
- const { elapsedTime, createdAt } = this.loopState;
2388
- let adjustedCreated = 0;
2389
- if (this.stoppedTime > 0) {
2390
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2391
- this.stoppedTime = 0;
2392
- }
2393
- Object.assign(this.loopState, {
2394
- running: true,
2395
- elapsedTime: elapsedTime ?? 0,
2396
- lastTime: performance.now(),
2397
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2398
- frameCount: 0,
2399
- rafHandle: requestAnimationFrame(this.loop)
2400
- });
2401
- }
2402
- /**
2403
- * Stop the requestAnimationFrame loop.
2404
- * Cancels any pending RAF callback.
2405
- * No-op if not running.
2406
- * @returns {void}
2407
- */
2408
- stop() {
2409
- if (!this.loopState.running) return;
2410
- this.loopState.running = false;
2411
- if (this.loopState.rafHandle !== null) {
2412
- cancelAnimationFrame(this.loopState.rafHandle);
2413
- this.loopState.rafHandle = null;
2414
- }
2415
- this.stoppedTime = performance.now();
2416
- }
2417
- /**
2418
- * Request frames to be rendered in demand mode.
2419
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2420
- * No-op if frameloop is not 'demand'.
2421
- * @param {number} [frames=1] - Number of frames to request
2422
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2423
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2424
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2425
- * @returns {void}
2426
- * @example
2427
- * // Request a single frame render
2428
- * scheduler.invalidate();
2429
- *
2430
- * @example
2431
- * // Request 5 frames (e.g., for animations)
2432
- * scheduler.invalidate(5);
2433
- *
2434
- * @example
2435
- * // Set pending frames to exactly 3 (don't stack with existing)
2436
- * scheduler.invalidate(3, false);
2437
- *
2438
- * @example
2439
- * // Add 2 more frames to existing pending count
2440
- * scheduler.invalidate(2, true);
2441
- */
2442
- invalidate(frames = 1, stackFrames = false) {
2443
- if (this._frameloop !== "demand") return;
2444
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2445
- this.pendingFrames = Math.min(60, baseFrames + frames);
2446
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2447
- }
2448
- /**
2449
- * Reset timing state for deterministic testing.
2450
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2451
- * @returns {void}
2452
- */
2453
- resetTiming() {
2454
- this.loopState.lastTime = null;
2455
- this.loopState.frameCount = 0;
2456
- this.loopState.elapsedTime = 0;
2457
- this.loopState.createdAt = performance.now();
2458
- }
2459
- //* Manual Stepping Methods ================================
2460
- /**
2461
- * Manually execute a single frame for all roots.
2462
- * Useful for frameloop='never' mode or testing scenarios.
2463
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2464
- * @returns {void}
2465
- * @example
2466
- * // Manual control mode
2467
- * scheduler.frameloop = 'never';
2468
- * scheduler.step(); // Execute one frame
2469
- */
2470
- step(timestamp) {
2471
- const now = timestamp ?? performance.now();
2472
- this.executeFrame(now);
2473
- }
2474
- /**
2475
- * Manually execute a single job by its ID.
2476
- * Useful for testing individual job callbacks in isolation.
2477
- * @param {string} id - The job ID to step
2478
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2479
- * @returns {void}
2480
- */
2481
- stepJob(id, timestamp) {
2482
- let job;
2483
- let root;
2484
- for (const r of this.roots.values()) {
2485
- job = r.jobs.get(id);
2486
- if (job) {
2487
- root = r;
2488
- break;
2489
- }
2490
- }
2491
- if (!job || !root) {
2492
- console.warn(`[Scheduler] Job "${id}" not found`);
2493
- return;
2494
- }
2495
- const now = timestamp ?? performance.now();
2496
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2497
- const delta = deltaMs / 1e3;
2498
- const elapsed = now - this.loopState.createdAt;
2499
- const providedState = root.getState?.() ?? {};
2500
- const frameState = {
2501
- ...providedState,
2502
- time: now,
2503
- delta,
2504
- elapsed,
2505
- frame: this.loopState.frameCount
2506
- };
2507
- try {
2508
- job.callback(frameState, delta);
2509
- } catch (error) {
2510
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2511
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2512
- }
2513
- }
2514
- /**
2515
- * Execute a single frame across all roots.
2516
- * Order: globalBefore → each root's jobs → globalAfter
2517
- * @param {number} timestamp - RAF timestamp in milliseconds
2518
- * @returns {void}
2519
- * @private
2520
- */
2521
- executeFrame(timestamp) {
2522
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2523
- const delta = deltaMs / 1e3;
2524
- this.loopState.lastTime = timestamp;
2525
- this.loopState.frameCount++;
2526
- this.loopState.elapsedTime += deltaMs;
2527
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2528
- for (const root of this.roots.values()) {
2529
- this.tickRoot(root, timestamp, delta);
2530
- }
2531
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2532
- }
2533
- /**
2534
- * Run all global jobs from a job map.
2535
- * Catches and logs errors without stopping execution.
2536
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2537
- * @param {number} timestamp - RAF timestamp in milliseconds
2538
- * @returns {void}
2539
- * @private
2540
- */
2541
- runGlobalJobs(jobs, timestamp) {
2542
- for (const job of jobs.values()) {
2543
- try {
2544
- job.callback(timestamp);
2545
- } catch (error) {
2546
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2547
- }
2548
- }
2549
- }
2550
- /**
2551
- * Execute all jobs for a single root in sorted order.
2552
- * Rebuilds sorted job list if needed, then dispatches each job.
2553
- * Errors are caught and propagated via triggerError.
2554
- * @param {RootEntry} root - The root entry to tick
2555
- * @param {number} timestamp - RAF timestamp in milliseconds
2556
- * @param {number} delta - Time since last frame in seconds
2557
- * @returns {void}
2558
- * @private
2559
- */
2560
- tickRoot(root, timestamp, delta) {
2561
- if (root.needsRebuild) {
2562
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2563
- root.needsRebuild = false;
2564
- }
2565
- const providedState = root.getState?.() ?? {};
2566
- const frameState = {
2567
- ...providedState,
2568
- time: timestamp,
2569
- delta,
2570
- elapsed: this.loopState.elapsedTime / 1e3,
2571
- // Convert ms to seconds
2572
- frame: this.loopState.frameCount
2573
- };
2574
- for (const job of root.sortedJobs) {
2575
- if (!shouldRun(job, timestamp)) continue;
2576
- try {
2577
- job.callback(frameState, delta);
2578
- } catch (error) {
2579
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2580
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2581
- }
2582
- }
2583
- }
2584
- //* Debug & Inspection Methods ================================
2585
- /**
2586
- * Get the total number of registered jobs across all roots.
2587
- * Includes both per-root jobs and global before/after jobs.
2588
- * @returns {number} Total job count
2589
- */
2590
- getJobCount() {
2591
- let count = 0;
2592
- for (const root of this.roots.values()) {
2593
- count += root.jobs.size;
2594
- }
2595
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2596
- }
2597
- /**
2598
- * Get all registered job IDs across all roots.
2599
- * Includes both per-root jobs and global before/after jobs.
2600
- * @returns {string[]} Array of all job IDs
2601
- */
2602
- getJobIds() {
2603
- const ids = [];
2604
- for (const root of this.roots.values()) {
2605
- ids.push(...root.jobs.keys());
2606
- }
2607
- ids.push(...this.globalBeforeJobs.keys());
2608
- ids.push(...this.globalAfterJobs.keys());
2609
- return ids;
2610
- }
2611
- /**
2612
- * Get the number of registered roots (Canvas instances).
2613
- * @returns {number} Number of registered roots
2614
- */
2615
- getRootCount() {
2616
- return this.roots.size;
2617
- }
2618
- /**
2619
- * Check if any user (non-system) jobs are registered in a specific phase.
2620
- * Used by the default render job to know if a user has taken over rendering.
2621
- *
2622
- * @param phase The phase to check
2623
- * @param rootId Optional root ID to check (checks all roots if not provided)
2624
- * @returns true if any user jobs exist in the phase
2625
- */
2626
- hasUserJobsInPhase(phase, rootId) {
2627
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2628
- return rootsToCheck.some((root) => {
2629
- if (!root) return false;
2630
- for (const job of root.jobs.values()) {
2631
- if (job.phase === phase && !job.system && job.enabled) return true;
2632
- }
2633
- return false;
2634
- });
2635
- }
2636
- //* Utility Methods ================================
2637
- /**
2638
- * Generate a unique root ID for automatic root registration.
2639
- * @returns {string} A unique root ID in the format 'root_N'
2640
- */
2641
- generateRootId() {
2642
- return `root_${this.nextRootIndex++}`;
2643
- }
2644
- /**
2645
- * Generate a unique job ID.
2646
- * @returns {string} A unique job ID in the format 'job_N'
2647
- * @private
2648
- */
2649
- generateJobId() {
2650
- return `job_${this.nextJobIndex}`;
2651
- }
2652
- /**
2653
- * Normalize before/after constraints to a Set.
2654
- * Handles undefined, single string, or array inputs.
2655
- * @param {string | string[] | undefined} value - The constraint value(s)
2656
- * @returns {Set<string>} Normalized Set of constraint strings
2657
- * @private
2658
- */
2659
- normalizeConstraints(value) {
2660
- if (!value) return /* @__PURE__ */ new Set();
2661
- if (Array.isArray(value)) return new Set(value);
2662
- return /* @__PURE__ */ new Set([value]);
2663
- }
2664
- };
2665
- //* Static State & Methods (Singleton Usage) ================================
2666
- //* Cross-Bundle Singleton Key ==============================
2667
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2668
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2669
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2670
- let Scheduler = _Scheduler;
2671
- const getScheduler = () => Scheduler.get();
2672
- if (hmrData) {
2673
- hmrData.accept?.();
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));
2674
1696
  }
2675
1697
 
2676
1698
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2782,7 +1804,7 @@ const createStore = (invalidate, advance) => {
2782
1804
  size: newSize,
2783
1805
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2784
1806
  }));
2785
- getScheduler().invalidate();
1807
+ scheduler.getScheduler().invalidate();
2786
1808
  }
2787
1809
  }
2788
1810
  return;
@@ -2797,7 +1819,7 @@ const createStore = (invalidate, advance) => {
2797
1819
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2798
1820
  _sizeImperative: true
2799
1821
  }));
2800
- getScheduler().invalidate();
1822
+ scheduler.getScheduler().invalidate();
2801
1823
  },
2802
1824
  setDpr: (dpr) => set((state2) => {
2803
1825
  const resolved = calculateDpr(dpr);
@@ -2805,6 +1827,7 @@ const createStore = (invalidate, advance) => {
2805
1827
  }),
2806
1828
  setFrameloop: (frameloop = "always") => {
2807
1829
  set(() => ({ frameloop }));
1830
+ scheduler.getScheduler().frameloop = frameloop;
2808
1831
  },
2809
1832
  setError: (error) => set(() => ({ error })),
2810
1833
  error: null,
@@ -2814,6 +1837,7 @@ const createStore = (invalidate, advance) => {
2814
1837
  buffers: {},
2815
1838
  gpuStorage: {},
2816
1839
  textures: /* @__PURE__ */ new Map(),
1840
+ _textureRefs: /* @__PURE__ */ new Map(),
2817
1841
  renderPipeline: null,
2818
1842
  passes: {},
2819
1843
  _hmrVersion: 0,
@@ -2871,8 +1895,7 @@ const createStore = (invalidate, advance) => {
2871
1895
  const currentState = rootStore.getState();
2872
1896
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2873
1897
  const stack = new Error().stack || "";
2874
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2875
- if (!isInternalAccess) {
1898
+ if (!isInternalRendererAccess(stack)) {
2876
1899
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2877
1900
  notifyDepreciated({
2878
1901
  heading: "Accessing state.gl in WebGPU mode",
@@ -2920,14 +1943,16 @@ const createStore = (invalidate, advance) => {
2920
1943
  oldSize = size;
2921
1944
  oldDpr = viewport.dpr;
2922
1945
  updateCamera(camera, size);
2923
- if (canvasTarget) {
1946
+ if (internal.isSecondary && canvasTarget) {
2924
1947
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2925
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2926
- canvasTarget.setSize(size.width, size.height, updateStyle);
1948
+ canvasTarget.setSize(size.width, size.height, false);
2927
1949
  } else {
2928
1950
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2929
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2930
- actualRenderer.setSize(size.width, size.height, updateStyle);
1951
+ actualRenderer.setSize(size.width, size.height, false);
1952
+ if (canvasTarget) {
1953
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1954
+ canvasTarget.setSize(size.width, size.height, false);
1955
+ }
2931
1956
  }
2932
1957
  }
2933
1958
  if (camera !== oldCamera) {
@@ -2983,26 +2008,32 @@ function loadingFn(extensions, onProgress) {
2983
2008
  );
2984
2009
  };
2985
2010
  }
2986
- function useLoader(loader, input, extensions, onProgress) {
2987
- 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];
2988
2014
  const fn = loadingFn(extensions, onProgress);
2989
- 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
+ );
2990
2018
  return Array.isArray(input) ? results : results[0];
2991
2019
  }
2992
- useLoader.preload = function(loader, input, extensions, onProgress) {
2993
- const keys = Array.isArray(input) ? input : [input];
2994
- 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
+ );
2995
2026
  };
2996
- useLoader.clear = function(loader, input) {
2997
- const keys = Array.isArray(input) ? input : [input];
2998
- 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]));
2999
2030
  };
3000
2031
  useLoader.loader = getLoader;
3001
2032
 
3002
2033
  function useFrame(callback, priorityOrOptions) {
3003
2034
  const store = React__namespace.useContext(context);
3004
2035
  const isInsideCanvas = store !== null;
3005
- const scheduler = getScheduler();
2036
+ const scheduler$1 = scheduler.getScheduler();
3006
2037
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
3007
2038
  id: priorityOrOptions.id,
3008
2039
  phase: priorityOrOptions.phase,
@@ -3050,7 +2081,7 @@ function useFrame(callback, priorityOrOptions) {
3050
2081
  };
3051
2082
  callbackRef.current?.(mergedState, delta);
3052
2083
  };
3053
- const unregister = scheduler.register(wrappedCallback, {
2084
+ const unregister = scheduler$1.register(wrappedCallback, {
3054
2085
  id,
3055
2086
  rootId,
3056
2087
  ...options
@@ -3071,37 +2102,31 @@ function useFrame(callback, priorityOrOptions) {
3071
2102
  }
3072
2103
  };
3073
2104
  } else {
3074
- const registerOutside = () => {
3075
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3076
- };
3077
- if (scheduler.independent || scheduler.isReady) {
3078
- return registerOutside();
3079
- }
3080
- let unregisterJob = null;
3081
- const unsubReady = scheduler.onRootReady(() => {
3082
- unregisterJob = registerOutside();
3083
- });
3084
- return () => {
3085
- unsubReady();
3086
- unregisterJob?.();
3087
- };
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
+ );
3088
2113
  }
3089
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2114
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3090
2115
  const isPaused = React__namespace.useSyncExternalStore(
3091
2116
  // Subscribe function
3092
2117
  React__namespace.useCallback(
3093
2118
  (onStoreChange) => {
3094
- return getScheduler().subscribeJobState(id, onStoreChange);
2119
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3095
2120
  },
3096
2121
  [id]
3097
2122
  ),
3098
2123
  // getSnapshot function
3099
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2124
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3100
2125
  // getServerSnapshot function (SSR)
3101
2126
  React__namespace.useCallback(() => false, [])
3102
2127
  );
3103
2128
  const controls = React__namespace.useMemo(() => {
3104
- const scheduler2 = getScheduler();
2129
+ const scheduler2 = scheduler.getScheduler();
3105
2130
  return {
3106
2131
  /** The job's unique ID */
3107
2132
  id,
@@ -3116,7 +2141,7 @@ function useFrame(callback, priorityOrOptions) {
3116
2141
  * @param timestamp Optional timestamp (defaults to performance.now())
3117
2142
  */
3118
2143
  step: (timestamp) => {
3119
- getScheduler().stepJob(id, timestamp);
2144
+ scheduler.getScheduler().stepJob(id, timestamp);
3120
2145
  },
3121
2146
  /**
3122
2147
  * Manually step ALL jobs in the scheduler.
@@ -3124,20 +2149,20 @@ function useFrame(callback, priorityOrOptions) {
3124
2149
  * @param timestamp Optional timestamp (defaults to performance.now())
3125
2150
  */
3126
2151
  stepAll: (timestamp) => {
3127
- getScheduler().step(timestamp);
2152
+ scheduler.getScheduler().step(timestamp);
3128
2153
  },
3129
2154
  /**
3130
2155
  * Pause this job (set enabled=false).
3131
2156
  * Job remains registered but won't run.
3132
2157
  */
3133
2158
  pause: () => {
3134
- getScheduler().pauseJob(id);
2159
+ scheduler.getScheduler().pauseJob(id);
3135
2160
  },
3136
2161
  /**
3137
2162
  * Resume this job (set enabled=true).
3138
2163
  */
3139
2164
  resume: () => {
3140
- getScheduler().resumeJob(id);
2165
+ scheduler.getScheduler().resumeJob(id);
3141
2166
  },
3142
2167
  /**
3143
2168
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3175,18 +2200,18 @@ function buildFromCache(input, textureCache) {
3175
2200
  function useTexture(input, optionsOrOnLoad) {
3176
2201
  const renderer = useThree((state) => state.internal.actualRenderer);
3177
2202
  const store = useStore();
3178
- const textureCache = useThree((state) => state.textures);
3179
2203
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3180
- const { onLoad, cache = false } = options;
2204
+ const { onLoad, cache = true } = options;
3181
2205
  const onLoadRef = React.useRef(onLoad);
3182
2206
  onLoadRef.current = onLoad;
3183
2207
  const onLoadCalledForRef = React.useRef(null);
3184
2208
  const urls = React.useMemo(() => getUrls(input), [input]);
3185
2209
  const cachedResult = React.useMemo(() => {
3186
2210
  if (!cache) return null;
3187
- if (!allUrlsCached(urls, textureCache)) return null;
3188
- return buildFromCache(input, textureCache);
3189
- }, [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]);
3190
2215
  const loadedTextures = useLoader(
3191
2216
  three.TextureLoader,
3192
2217
  IsObject(input) ? Object.values(input) : input
@@ -3230,8 +2255,6 @@ function useTexture(input, optionsOrOnLoad) {
3230
2255
  }, [input, loadedTextures, cachedResult]);
3231
2256
  React.useEffect(() => {
3232
2257
  if (!cache) return;
3233
- if (cachedResult) return;
3234
- const set = store.setState;
3235
2258
  const urlTextureMap = [];
3236
2259
  if (typeof input === "string") {
3237
2260
  urlTextureMap.push([input, mappedTextures]);
@@ -3245,18 +2268,32 @@ function useTexture(input, optionsOrOnLoad) {
3245
2268
  urlTextureMap.push([url, textureRecord[key]]);
3246
2269
  }
3247
2270
  }
3248
- set((state) => {
3249
- const newMap = new Map(state.textures);
3250
- let changed = false;
2271
+ store.setState((state) => {
2272
+ const refs = new Map(state._textureRefs);
2273
+ let textures = state.textures;
2274
+ let added = false;
3251
2275
  for (const [url, texture] of urlTextureMap) {
3252
- if (!newMap.has(url)) {
3253
- newMap.set(url, texture);
3254
- changed = true;
2276
+ if (!textures.has(url)) {
2277
+ if (!added) {
2278
+ textures = new Map(textures);
2279
+ added = true;
2280
+ }
2281
+ textures.set(url, texture);
3255
2282
  }
2283
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3256
2284
  }
3257
- return changed ? { textures: newMap } : state;
2285
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3258
2286
  });
3259
- }, [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]);
3260
2297
  return mappedTextures;
3261
2298
  }
3262
2299
  useTexture.preload = (url) => useLoader.preload(three.TextureLoader, url);
@@ -3272,96 +2309,63 @@ const Texture = ({
3272
2309
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3273
2310
  };
3274
2311
 
3275
- function getTextureValue(entry) {
3276
- if (entry instanceof three.Texture) return entry;
3277
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof three.Texture) {
3278
- return entry.value;
3279
- }
3280
- return null;
3281
- }
3282
- function useTextures() {
2312
+ function useTextures(selector) {
3283
2313
  const store = useStore();
3284
- return React.useMemo(() => {
3285
- const set = store.setState;
2314
+ const registry = React.useMemo(() => {
3286
2315
  const getState = store.getState;
3287
- const add = (key, value) => {
3288
- set((state) => {
3289
- const newMap = new Map(state.textures);
3290
- newMap.set(key, value);
3291
- return { textures: newMap };
3292
- });
3293
- };
3294
- const addMultiple = (items) => {
3295
- set((state) => {
3296
- const newMap = new Map(state.textures);
3297
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3298
- for (const [key, value] of entries) {
3299
- newMap.set(key, value);
3300
- }
3301
- return { textures: newMap };
3302
- });
3303
- };
3304
- const remove = (key) => {
3305
- set((state) => {
3306
- const newMap = new Map(state.textures);
3307
- newMap.delete(key);
3308
- return { textures: newMap };
3309
- });
3310
- };
3311
- const removeMultiple = (keys) => {
3312
- set((state) => {
3313
- const newMap = new Map(state.textures);
3314
- for (const key of keys) newMap.delete(key);
3315
- return { textures: newMap };
3316
- });
3317
- };
3318
- const dispose = (key) => {
3319
- const entry = getState().textures.get(key);
3320
- if (entry) {
3321
- const tex = getTextureValue(entry);
3322
- tex?.dispose();
3323
- }
3324
- remove(key);
3325
- };
3326
- const disposeMultiple = (keys) => {
3327
- const textures = getState().textures;
3328
- for (const key of keys) {
3329
- const entry = textures.get(key);
3330
- if (entry) {
3331
- const tex = getTextureValue(entry);
3332
- tex?.dispose();
3333
- }
3334
- }
3335
- removeMultiple(keys);
3336
- };
3337
- const disposeAll = () => {
3338
- const textures = getState().textures;
3339
- for (const entry of textures.values()) {
3340
- const tex = getTextureValue(entry);
3341
- tex?.dispose();
3342
- }
3343
- set({ textures: /* @__PURE__ */ new Map() });
3344
- };
2316
+ const setState = store.setState;
2317
+ const getOne = (key) => getState().textures.get(key);
3345
2318
  return {
3346
- // Getter for the textures Map (reactive via getState)
3347
- get textures() {
2319
+ get all() {
3348
2320
  return getState().textures;
3349
2321
  },
3350
- // Read
3351
- 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
+ },
3352
2329
  has: (key) => getState().textures.has(key),
3353
- // Write
3354
- add,
3355
- addMultiple,
3356
- // Remove (cache only)
3357
- remove,
3358
- removeMultiple,
3359
- // Dispose (GPU + cache)
3360
- dispose,
3361
- disposeMultiple,
3362
- 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
+ }
3363
2364
  };
3364
2365
  }, [store]);
2366
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2367
+ const selected = useThree(subscribe);
2368
+ return selector ? selected : registry;
3365
2369
  }
3366
2370
 
3367
2371
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3416,7 +2420,7 @@ function addEffect(callback) {
3416
2420
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3417
2421
  });
3418
2422
  const id = `legacy_effect_${effectId++}`;
3419
- return getScheduler().registerGlobal("before", id, callback);
2423
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3420
2424
  }
3421
2425
  function addAfterEffect(callback) {
3422
2426
  notifyDepreciated({
@@ -3425,7 +2429,7 @@ function addAfterEffect(callback) {
3425
2429
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3426
2430
  });
3427
2431
  const id = `legacy_afterEffect_${effectId++}`;
3428
- return getScheduler().registerGlobal("after", id, callback);
2432
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3429
2433
  }
3430
2434
  function addTail(callback) {
3431
2435
  notifyDepreciated({
@@ -3433,16 +2437,16 @@ function addTail(callback) {
3433
2437
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3434
2438
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3435
2439
  });
3436
- return getScheduler().onIdle(callback);
2440
+ return scheduler.getScheduler().onIdle(callback);
3437
2441
  }
3438
2442
  function invalidate(state, frames = 1, stackFrames = false) {
3439
- getScheduler().invalidate(frames, stackFrames);
2443
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3440
2444
  }
3441
2445
  function advance(timestamp) {
3442
- getScheduler().step(timestamp);
2446
+ scheduler.getScheduler().step(timestamp);
3443
2447
  }
3444
2448
 
3445
- const version = "10.0.0-alpha.2";
2449
+ const version = "10.0.0-alpha.3";
3446
2450
  const packageData = {
3447
2451
  version: version};
3448
2452
 
@@ -14881,6 +13885,7 @@ function swapInstances() {
14881
13885
  }
14882
13886
  }
14883
13887
  if (instance.isHidden) unhideInstance(instance);
13888
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14884
13889
  if (instance.object.__r3f) delete instance.object.__r3f;
14885
13890
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14886
13891
  }
@@ -14893,6 +13898,8 @@ function swapInstances() {
14893
13898
  instance.object.__r3f = instance;
14894
13899
  setFiberRef(fiber, instance.object);
14895
13900
  delete instance.appliedOnce;
13901
+ instance.eventCount = 0;
13902
+ instance.handlers = {};
14896
13903
  applyProps(instance.object, instance.props);
14897
13904
  if (instance.props.attach) {
14898
13905
  attach(parent, instance);
@@ -15108,11 +14115,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15108
14115
  cloneMutableTextInstance(textInstance) {
15109
14116
  return textInstance;
15110
14117
  },
14118
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14119
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14120
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14121
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14122
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14123
+ // Guarded by a test asserting a full render + unmount never reaches them.
15111
14124
  cloneRootViewTransitionContainer(_rootContainer) {
15112
- throw new Error("Not implemented.");
15113
14125
  },
15114
14126
  removeRootViewTransitionClone(_rootContainer, _clone) {
15115
- throw new Error("Not implemented.");
15116
14127
  },
15117
14128
  // https://github.com/facebook/react/pull/32465
15118
14129
  createFragmentInstance: (_fiber) => null,
@@ -15197,6 +14208,7 @@ function createRoot(canvas) {
15197
14208
  const lastConfiguredProps = {};
15198
14209
  let configured = false;
15199
14210
  let pending = null;
14211
+ let rendererSetup = null;
15200
14212
  return {
15201
14213
  async configure(props = {}) {
15202
14214
  let resolve;
@@ -15212,7 +14224,6 @@ function createRoot(canvas) {
15212
14224
  events,
15213
14225
  onCreated: onCreatedCallback,
15214
14226
  shadows = false,
15215
- textureColorSpace = three.SRGBColorSpace,
15216
14227
  orthographic = false,
15217
14228
  frameloop = "always",
15218
14229
  dpr = [1, 2],
@@ -15227,7 +14238,8 @@ function createRoot(canvas) {
15227
14238
  _sizeProps,
15228
14239
  forceEven
15229
14240
  } = props;
15230
- const state = store.getState();
14241
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || three.SRGBColorSpace;
14242
+ let state = store.getState();
15231
14243
  const defaultGLProps = {
15232
14244
  canvas,
15233
14245
  powerPreference: "high-performance",
@@ -15255,9 +14267,21 @@ function createRoot(canvas) {
15255
14267
  );
15256
14268
  }
15257
14269
  if (!state.internal.actualRenderer) {
15258
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
15259
- state.internal.actualRenderer = renderer;
15260
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14270
+ if (!rendererSetup) {
14271
+ rendererSetup = (async () => {
14272
+ {
14273
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14274
+ state.internal.actualRenderer = renderer;
14275
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14276
+ }
14277
+ })().catch((err) => {
14278
+ rendererSetup = null;
14279
+ throw err;
14280
+ });
14281
+ }
14282
+ await rendererSetup;
14283
+ state = store.getState();
14284
+ renderer = state.internal.actualRenderer;
15261
14285
  }
15262
14286
  let raycaster = state.raycaster;
15263
14287
  if (!raycaster) state.set({ raycaster: raycaster = new three.Raycaster() });
@@ -15350,7 +14374,7 @@ function createRoot(canvas) {
15350
14374
  lastConfiguredProps.performance = performance;
15351
14375
  }
15352
14376
  if (!state.xr) {
15353
- const handleXRFrame = (timestamp, frame) => {
14377
+ const handleXRFrame = (timestamp, _frame) => {
15354
14378
  const state2 = store.getState();
15355
14379
  if (state2.frameloop === "never") return;
15356
14380
  advance(timestamp);
@@ -15386,15 +14410,22 @@ function createRoot(canvas) {
15386
14410
  const oldType = renderer.shadowMap.type;
15387
14411
  renderer.shadowMap.enabled = !!shadows;
15388
14412
  if (is.boo(shadows)) {
15389
- renderer.shadowMap.type = three.PCFSoftShadowMap;
14413
+ renderer.shadowMap.type = three.PCFShadowMap;
15390
14414
  } else if (is.str(shadows)) {
14415
+ if (shadows === "soft") {
14416
+ notifyDepreciated({
14417
+ heading: 'shadows="soft" is deprecated',
14418
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14419
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14420
+ });
14421
+ }
15391
14422
  const types = {
15392
14423
  basic: three.BasicShadowMap,
15393
14424
  percentage: three.PCFShadowMap,
15394
- soft: three.PCFSoftShadowMap,
14425
+ soft: three.PCFShadowMap,
15395
14426
  variance: three.VSMShadowMap
15396
14427
  };
15397
- renderer.shadowMap.type = types[shadows] ?? three.PCFSoftShadowMap;
14428
+ renderer.shadowMap.type = types[shadows] ?? three.PCFShadowMap;
15398
14429
  } else if (is.obj(shadows)) {
15399
14430
  Object.assign(renderer.shadowMap, shadows);
15400
14431
  }
@@ -15410,24 +14441,35 @@ function createRoot(canvas) {
15410
14441
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15411
14442
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15412
14443
  }
14444
+ const r3fProps = ["textureColorSpace"];
14445
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14446
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15413
14447
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15414
- applyProps(renderer, glConfig);
14448
+ const glProps = {};
14449
+ for (const key in glConfig) {
14450
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14451
+ }
14452
+ applyProps(renderer, glProps);
15415
14453
  }
15416
14454
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15417
14455
  const currentRenderer = state.renderer;
15418
14456
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15419
- applyProps(currentRenderer, rendererConfig);
14457
+ const rendererProps = {};
14458
+ for (const key in rendererConfig) {
14459
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14460
+ }
14461
+ applyProps(currentRenderer, rendererProps);
15420
14462
  }
15421
14463
  }
15422
- const scheduler = getScheduler();
14464
+ const scheduler$1 = scheduler.getScheduler();
15423
14465
  const rootId = state.internal.rootId;
15424
14466
  if (!rootId) {
15425
- const newRootId = canvasId || scheduler.generateRootId();
15426
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14467
+ const newRootId = canvasId || scheduler$1.generateRootId();
14468
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15427
14469
  getState: () => store.getState(),
15428
14470
  onError: (err) => store.getState().setError(err)
15429
14471
  });
15430
- const unregisterCanvasTarget = scheduler.register(
14472
+ const unregisterCanvasTarget = scheduler$1.register(
15431
14473
  () => {
15432
14474
  const state2 = store.getState();
15433
14475
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15442,7 +14484,7 @@ function createRoot(canvas) {
15442
14484
  system: true
15443
14485
  }
15444
14486
  );
15445
- const unregisterEventsFlush = scheduler.register(
14487
+ const unregisterEventsFlush = scheduler$1.register(
15446
14488
  () => {
15447
14489
  const state2 = store.getState();
15448
14490
  state2.events.flush?.();
@@ -15454,7 +14496,7 @@ function createRoot(canvas) {
15454
14496
  system: true
15455
14497
  }
15456
14498
  );
15457
- const unregisterFrustum = scheduler.register(
14499
+ const unregisterFrustum = scheduler$1.register(
15458
14500
  () => {
15459
14501
  const state2 = store.getState();
15460
14502
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15464,11 +14506,11 @@ function createRoot(canvas) {
15464
14506
  {
15465
14507
  id: `${newRootId}_frustum`,
15466
14508
  rootId: newRootId,
15467
- phase: "preRender",
14509
+ before: "render",
15468
14510
  system: true
15469
14511
  }
15470
14512
  );
15471
- const unregisterVisibility = scheduler.register(
14513
+ const unregisterVisibility = scheduler$1.register(
15472
14514
  () => {
15473
14515
  const state2 = store.getState();
15474
14516
  checkVisibility(state2);
@@ -15476,16 +14518,16 @@ function createRoot(canvas) {
15476
14518
  {
15477
14519
  id: `${newRootId}_visibility`,
15478
14520
  rootId: newRootId,
15479
- phase: "preRender",
14521
+ before: "render",
15480
14522
  system: true,
15481
14523
  after: `${newRootId}_frustum`
15482
14524
  }
15483
14525
  );
15484
- const unregisterRender = scheduler.register(
14526
+ const unregisterRender = scheduler$1.register(
15485
14527
  () => {
15486
14528
  const state2 = store.getState();
15487
14529
  const renderer2 = state2.internal.actualRenderer;
15488
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14530
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15489
14531
  if (userHandlesRender || state2.internal.priority) return;
15490
14532
  try {
15491
14533
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15518,11 +14560,11 @@ function createRoot(canvas) {
15518
14560
  unregisterVisibility();
15519
14561
  unregisterRender();
15520
14562
  },
15521
- scheduler
14563
+ scheduler: scheduler$1
15522
14564
  }
15523
14565
  }));
15524
14566
  }
15525
- scheduler.frameloop = frameloop;
14567
+ scheduler$1.frameloop = frameloop;
15526
14568
  onCreated = onCreatedCallback;
15527
14569
  configured = true;
15528
14570
  resolve();
@@ -15589,7 +14631,8 @@ function unmountComponentAtNode(canvas, callback) {
15589
14631
  dispose(state.scene);
15590
14632
  _roots.delete(canvas);
15591
14633
  if (callback) callback(canvas);
15592
- } catch {
14634
+ } catch (error) {
14635
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15593
14636
  }
15594
14637
  }, 500);
15595
14638
  }
@@ -15652,6 +14695,7 @@ function PortalInner({ state = {}, children, container }) {
15652
14695
  viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), resolvedSize);
15653
14696
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15654
14697
  }
14698
+ const set = injectState.set;
15655
14699
  return {
15656
14700
  // The intersect consists of the previous root state
15657
14701
  ...rootState,
@@ -15670,7 +14714,7 @@ function PortalInner({ state = {}, children, container }) {
15670
14714
  size: resolvedSize,
15671
14715
  viewport: { ...rootState.viewport, ...viewport },
15672
14716
  // Layers are allowed to override events
15673
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14717
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15674
14718
  // Container for child attachment - the portalScene (injected or container itself)
15675
14719
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15676
14720
  };
@@ -15699,6 +14743,81 @@ function flushSync(fn) {
15699
14743
  return reconciler.flushSyncFromReconciler(fn);
15700
14744
  }
15701
14745
 
14746
+ function parseBackground(background) {
14747
+ if (!background) return null;
14748
+ if (typeof background === "object" && !background.isColor) {
14749
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14750
+ return {
14751
+ ...rest,
14752
+ preset,
14753
+ files: envMap || files,
14754
+ backgroundFiles: backgroundMap,
14755
+ background: true
14756
+ };
14757
+ }
14758
+ if (typeof background === "number") {
14759
+ return { color: background, background: true };
14760
+ }
14761
+ if (typeof background === "string") {
14762
+ if (background in presetsObj) {
14763
+ return { preset: background, background: true };
14764
+ }
14765
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14766
+ return { files: background, background: true };
14767
+ }
14768
+ return { color: background, background: true };
14769
+ }
14770
+ if (background.isColor) {
14771
+ return { color: background, background: true };
14772
+ }
14773
+ return null;
14774
+ }
14775
+
14776
+ function parseRendererConfig(rendererProp) {
14777
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14778
+ if (isRendererConfig) {
14779
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14780
+ return {
14781
+ primaryCanvas: pc,
14782
+ scheduler: sc,
14783
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14784
+ };
14785
+ }
14786
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14787
+ }
14788
+
14789
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14790
+ const registries = /* @__PURE__ */ new WeakMap();
14791
+ function getKindRegistry(store, kind) {
14792
+ let registry = registries.get(store);
14793
+ if (!registry) {
14794
+ registry = {
14795
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14796
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14797
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14798
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14799
+ };
14800
+ registries.set(store, registry);
14801
+ }
14802
+ return registry[kind];
14803
+ }
14804
+ function invalidateResource(store, kind, scopeKey) {
14805
+ const registry = getKindRegistry(store, kind);
14806
+ {
14807
+ registry.valid.clear();
14808
+ registry.staged.clear();
14809
+ }
14810
+ }
14811
+ function invalidateAllResources(store) {
14812
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14813
+ }
14814
+
14815
+ function clearHmrCaches(store) {
14816
+ const primary = store.getState().primaryStore ?? store;
14817
+ invalidateAllResources(primary);
14818
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14819
+ }
14820
+
15702
14821
  function CanvasImpl({
15703
14822
  ref,
15704
14823
  children,
@@ -15719,6 +14838,8 @@ function CanvasImpl({
15719
14838
  raycaster,
15720
14839
  camera,
15721
14840
  scene,
14841
+ autoUpdateFrustum,
14842
+ occlusion,
15722
14843
  onPointerMissed,
15723
14844
  onDragOverMissed,
15724
14845
  onDropMissed,
@@ -15730,39 +14851,10 @@ function CanvasImpl({
15730
14851
  forceEven,
15731
14852
  ...props
15732
14853
  }) {
15733
- const { primaryCanvas, scheduler, ...rendererConfig } = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp) ? rendererProp : { primaryCanvas: void 0, scheduler: void 0 };
15734
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14854
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15735
14855
  React__namespace.useMemo(() => extend(THREE), []);
15736
14856
  const Bridge = useBridge();
15737
- const backgroundProps = React__namespace.useMemo(() => {
15738
- if (!background) return null;
15739
- if (typeof background === "object" && !background.isColor) {
15740
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15741
- return {
15742
- ...rest,
15743
- preset,
15744
- files: envMap || files,
15745
- backgroundFiles: backgroundMap,
15746
- background: true
15747
- };
15748
- }
15749
- if (typeof background === "number") {
15750
- return { color: background, background: true };
15751
- }
15752
- if (typeof background === "string") {
15753
- if (background in presetsObj) {
15754
- return { preset: background, background: true };
15755
- }
15756
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15757
- return { files: background, background: true };
15758
- }
15759
- return { color: background, background: true };
15760
- }
15761
- if (background.isColor) {
15762
- return { color: background, background: true };
15763
- }
15764
- return null;
15765
- }, [background]);
14857
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15766
14858
  const hasInitialSizeRef = React__namespace.useRef(false);
15767
14859
  const measureConfig = React__namespace.useMemo(() => {
15768
14860
  if (!hasInitialSizeRef.current) {
@@ -15804,6 +14896,7 @@ function CanvasImpl({
15804
14896
  const handleDropMissed = useMutableCallback(onDropMissed);
15805
14897
  const [block, setBlock] = React__namespace.useState(false);
15806
14898
  const [error, setError] = React__namespace.useState(false);
14899
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15807
14900
  if (block) throw block;
15808
14901
  if (error) throw error;
15809
14902
  const root = React__namespace.useRef(null);
@@ -15811,6 +14904,7 @@ function CanvasImpl({
15811
14904
  const unsubscribeErrorRef = React__namespace.useRef(null);
15812
14905
  useIsomorphicLayoutEffect(() => {
15813
14906
  effectActiveRef.current = true;
14907
+ if (fallbackVisible) return;
15814
14908
  const canvas = canvasRef.current;
15815
14909
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15816
14910
  if (!root.current) {
@@ -15831,7 +14925,7 @@ function CanvasImpl({
15831
14925
  }
15832
14926
  async function run() {
15833
14927
  if (!effectActiveRef.current || !root.current) return;
15834
- await root.current.configure({
14928
+ const configured = await root.current.configure({
15835
14929
  id,
15836
14930
  primaryCanvas,
15837
14931
  scheduler,
@@ -15846,6 +14940,8 @@ function CanvasImpl({
15846
14940
  performance,
15847
14941
  raycaster,
15848
14942
  camera,
14943
+ autoUpdateFrustum,
14944
+ occlusion,
15849
14945
  size: effectiveSize,
15850
14946
  // Store size props for reset functionality
15851
14947
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15870,8 +14966,20 @@ function CanvasImpl({
15870
14966
  }
15871
14967
  onCreated?.(state);
15872
14968
  }
15873
- });
15874
- if (!effectActiveRef.current || !root.current) return;
14969
+ }).then(
14970
+ () => true,
14971
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14972
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14973
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14974
+ (setupError) => {
14975
+ if (effectActiveRef.current) {
14976
+ if (fallback != null) setFallbackVisible(true);
14977
+ else setError(setupError);
14978
+ }
14979
+ return false;
14980
+ }
14981
+ );
14982
+ if (!configured || !effectActiveRef.current || !root.current) return;
15875
14983
  root.current.render(
15876
14984
  /* @__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: [
15877
14985
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15905,14 +15013,7 @@ function CanvasImpl({
15905
15013
  const handleHMR = () => {
15906
15014
  queueMicrotask(() => {
15907
15015
  const rootEntry = _roots.get(canvas);
15908
- if (rootEntry?.store) {
15909
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15910
- rootEntry.store.setState((state) => ({
15911
- nodes: {},
15912
- uniforms: {},
15913
- _hmrVersion: state._hmrVersion + 1
15914
- }));
15915
- }
15016
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15916
15017
  });
15917
15018
  };
15918
15019
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('legacy.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
@@ -15941,7 +15042,20 @@ function CanvasImpl({
15941
15042
  ...style
15942
15043
  },
15943
15044
  ...props,
15944
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx("canvas", { ref: canvasRef, id, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
15045
+ children: fallbackVisible ? (
15046
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15047
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15048
+ fallback
15049
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15050
+ "canvas",
15051
+ {
15052
+ ref: canvasRef,
15053
+ id,
15054
+ className: "r3f-canvas",
15055
+ style: { display: "block", width: "100%", height: "100%" },
15056
+ children: fallback
15057
+ }
15058
+ ) })
15945
15059
  }
15946
15060
  );
15947
15061
  }
@@ -15951,6 +15065,8 @@ function Canvas(props) {
15951
15065
 
15952
15066
  extend(THREE);
15953
15067
 
15068
+ exports.Scheduler = scheduler.Scheduler;
15069
+ exports.getScheduler = scheduler.getScheduler;
15954
15070
  exports.Block = Block;
15955
15071
  exports.Canvas = Canvas;
15956
15072
  exports.Environment = Environment;
@@ -15966,7 +15082,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15966
15082
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15967
15083
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15968
15084
  exports.RESERVED_PROPS = RESERVED_PROPS;
15969
- exports.Scheduler = Scheduler;
15970
15085
  exports.Texture = Texture;
15971
15086
  exports._roots = _roots;
15972
15087
  exports.act = act;
@@ -15996,7 +15111,6 @@ exports.getInstanceProps = getInstanceProps;
15996
15111
  exports.getPrimary = getPrimary;
15997
15112
  exports.getPrimaryIds = getPrimaryIds;
15998
15113
  exports.getRootState = getRootState;
15999
- exports.getScheduler = getScheduler;
16000
15114
  exports.getUuidPrefix = getUuidPrefix;
16001
15115
  exports.hasConstructor = hasConstructor;
16002
15116
  exports.hasPrimary = hasPrimary;