@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/index.cjs CHANGED
@@ -15,6 +15,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
15
15
  const gainmapJs = require('@monogrid/gainmap-js');
16
16
  const Tb = require('scheduler');
17
17
  const traditional = require('zustand/traditional');
18
+ const scheduler = require('@pmndrs/scheduler');
18
19
  const suspendReact = require('suspend-react');
19
20
 
20
21
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -55,10 +56,13 @@ const R3F_BUILD_WEBGPU = true;
55
56
 
56
57
  const THREE = /*#__PURE__*/_mergeNamespaces({
57
58
  __proto__: null,
59
+ CubeRenderTarget: webgpu.CubeRenderTarget,
60
+ CubeRenderTargetCompat: webgpu.CubeRenderTarget,
58
61
  Inspector: Inspector_js.Inspector,
59
62
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
60
63
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
61
64
  RenderTargetCompat: webgpu.RenderTarget,
65
+ WebGLCubeRenderTarget: three.WebGLCubeRenderTarget,
62
66
  WebGLRenderTarget: three.WebGLRenderTarget,
63
67
  WebGLRenderer: three.WebGLRenderer
64
68
  }, [webgpu__namespace]);
@@ -160,7 +164,7 @@ function useEnvironment({
160
164
  fiber.useLoader.clear(loader, multiFile ? [files] : files);
161
165
  }
162
166
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
163
- }, [files, renderer.domElement]);
167
+ }, [extension, files, loader, multiFile, renderer.domElement]);
164
168
  const loaderResult = fiber.useLoader(
165
169
  loader,
166
170
  multiFile ? [files] : files,
@@ -332,15 +336,16 @@ function EnvironmentPortal({
332
336
  preset = void 0,
333
337
  extensions
334
338
  }) {
335
- const gl = fiber.useThree((state) => state.gl);
339
+ const renderer = fiber.useThree((state) => state.renderer);
340
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
336
341
  const defaultScene = fiber.useThree((state) => state.scene);
337
342
  const camera = React__namespace.useRef(null);
338
343
  const [virtualScene] = React__namespace.useState(() => new webgpu.Scene());
339
344
  const fbo = React__namespace.useMemo(() => {
340
- const fbo2 = new webgpu.WebGLCubeRenderTarget(resolution);
345
+ const fbo2 = isLegacy ? new three.WebGLCubeRenderTarget(resolution) : new webgpu.CubeRenderTarget(resolution);
341
346
  fbo2.texture.type = webgpu.HalfFloatType;
342
347
  return fbo2;
343
- }, [resolution]);
348
+ }, [resolution, isLegacy]);
344
349
  React__namespace.useEffect(() => {
345
350
  return () => {
346
351
  fbo.dispose();
@@ -348,10 +353,10 @@ function EnvironmentPortal({
348
353
  }, [fbo]);
349
354
  React__namespace.useLayoutEffect(() => {
350
355
  if (frames === 1) {
351
- const autoClear = gl.autoClear;
352
- gl.autoClear = true;
353
- camera.current.update(gl, virtualScene);
354
- gl.autoClear = autoClear;
356
+ const autoClear = renderer.autoClear;
357
+ renderer.autoClear = true;
358
+ camera.current.update(renderer, virtualScene);
359
+ renderer.autoClear = autoClear;
355
360
  }
356
361
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
357
362
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -360,14 +365,29 @@ function EnvironmentPortal({
360
365
  environmentIntensity,
361
366
  environmentRotation
362
367
  });
363
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
368
+ }, [
369
+ children,
370
+ virtualScene,
371
+ fbo.texture,
372
+ scene,
373
+ defaultScene,
374
+ background,
375
+ frames,
376
+ renderer,
377
+ blur,
378
+ backgroundBlurriness,
379
+ backgroundIntensity,
380
+ backgroundRotation,
381
+ environmentIntensity,
382
+ environmentRotation
383
+ ]);
364
384
  let count = 1;
365
385
  fiber.useFrame(() => {
366
386
  if (frames === Infinity || count < frames) {
367
- const autoClear = gl.autoClear;
368
- gl.autoClear = true;
369
- camera.current.update(gl, virtualScene);
370
- gl.autoClear = autoClear;
387
+ const autoClear = renderer.autoClear;
388
+ renderer.autoClear = true;
389
+ camera.current.update(renderer, virtualScene);
390
+ renderer.autoClear = autoClear;
371
391
  count++;
372
392
  }
373
393
  });
@@ -431,9 +451,9 @@ function Environment(props) {
431
451
  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 });
432
452
  }
433
453
 
434
- var __defProp$2 = Object.defineProperty;
435
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
436
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
454
+ var __defProp = Object.defineProperty;
455
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
456
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
437
457
  const act = React__namespace["act"];
438
458
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
439
459
  function useMutableCallback(fn) {
@@ -465,7 +485,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
465
485
  return _a = class extends React__namespace.Component {
466
486
  constructor() {
467
487
  super(...arguments);
468
- __publicField$2(this, "state", { error: false });
488
+ __publicField(this, "state", { error: false });
469
489
  }
470
490
  componentDidCatch(err) {
471
491
  this.props.set(err);
@@ -473,7 +493,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
473
493
  render() {
474
494
  return this.state.error ? null : this.props.children;
475
495
  }
476
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
496
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
477
497
  })();
478
498
 
479
499
  const is = {
@@ -610,8 +630,7 @@ function prepare(target, root, type, props) {
610
630
  object,
611
631
  eventCount: 0,
612
632
  handlers: {},
613
- isHidden: false,
614
- deferredRefs: []
633
+ isHidden: false
615
634
  };
616
635
  if (object) object.__r3f = instance;
617
636
  }
@@ -768,6 +787,17 @@ function unregisterVisibility(store, object) {
768
787
  internal.visibilityRegistry.delete(object.uuid);
769
788
  internal.occlusionCache.delete(object);
770
789
  }
790
+ function updateVisibilityHandlers(store, object, handlers) {
791
+ const { internal } = store.getState();
792
+ const entry = internal.visibilityRegistry.get(object.uuid);
793
+ if (!entry) return false;
794
+ entry.handlers = handlers;
795
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
796
+ object.occlusionTest = true;
797
+ enableOcclusion(store);
798
+ }
799
+ return true;
800
+ }
771
801
  function checkVisibility(state) {
772
802
  const { internal, camera } = state;
773
803
  const registry = internal.visibilityRegistry;
@@ -955,10 +985,7 @@ function applyProps(object, props) {
955
985
  continue;
956
986
  }
957
987
  if (value === void 0) continue;
958
- if (isFromRef(value)) {
959
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
960
- continue;
961
- }
988
+ if (isFromRef(value)) continue;
962
989
  if (isOnce(value)) {
963
990
  if (instance?.appliedOnce?.has(prop)) continue;
964
991
  if (instance) {
@@ -994,6 +1021,19 @@ function applyProps(object, props) {
994
1021
  } else if (isVectorLike(target) && is.num(value)) {
995
1022
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
996
1023
  else target.set(value);
1024
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1025
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1026
+ const uniforms = root.uniforms;
1027
+ const nextUniforms = value;
1028
+ for (const name in nextUniforms) {
1029
+ const uniform = nextUniforms[name];
1030
+ const targetUniform = uniforms[name];
1031
+ if (targetUniform) Object.assign(targetUniform, uniform);
1032
+ else {
1033
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1034
+ uniforms[name] = nextUniform;
1035
+ }
1036
+ }
997
1037
  } else {
998
1038
  root[key] = value;
999
1039
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1012,6 +1052,9 @@ function applyProps(object, props) {
1012
1052
  if (instance.eventCount && object2.raycast !== null) {
1013
1053
  rootState.internal.interaction.push(object2);
1014
1054
  }
1055
+ }
1056
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1057
+ const object2 = instance.object;
1015
1058
  const root = findInitialRoot(instance);
1016
1059
  const visibilityHandlers = {
1017
1060
  onFramed: instance.handlers.onFramed,
@@ -1019,7 +1062,9 @@ function applyProps(object, props) {
1019
1062
  onVisible: instance.handlers.onVisible
1020
1063
  };
1021
1064
  if (hasVisibilityHandlers(visibilityHandlers)) {
1022
- registerVisibility(root, object2, visibilityHandlers);
1065
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1066
+ registerVisibility(root, object2, visibilityHandlers);
1067
+ }
1023
1068
  } else {
1024
1069
  unregisterVisibility(root, object2);
1025
1070
  }
@@ -1287,7 +1332,7 @@ function createEvents(store) {
1287
1332
  }
1288
1333
  function processDeferredPointer(event, pointerId) {
1289
1334
  const state = store.getState();
1290
- const { onPointerMissed, onDragOverMissed, internal } = state;
1335
+ const { internal } = state;
1291
1336
  if (!state.events.enabled) return;
1292
1337
  const filter = filterPointerEvents;
1293
1338
  const hits = intersect(event, filter);
@@ -1522,6 +1567,7 @@ function createPointerEvents(store) {
1522
1567
  }
1523
1568
  },
1524
1569
  connect: (target) => {
1570
+ if (!target) return;
1525
1571
  const { set, events } = store.getState();
1526
1572
  events.disconnect?.();
1527
1573
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1546,6 +1592,7 @@ function createPointerEvents(store) {
1546
1592
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1547
1593
  }
1548
1594
  },
1595
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1549
1596
  registerPointer: (config) => {
1550
1597
  const pointerId = nextXRPointerId++;
1551
1598
  xrPointers.set(pointerId, config);
@@ -1632,1036 +1679,11 @@ function notifyAlpha({ message, link }) {
1632
1679
  }
1633
1680
  }
1634
1681
 
1635
- var __defProp$1 = Object.defineProperty;
1636
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1637
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1638
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1639
- class PhaseGraph {
1640
- constructor() {
1641
- /** Ordered list of phase nodes */
1642
- __publicField$1(this, "phases", []);
1643
- /** Quick lookup by name */
1644
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1645
- /** Cached ordered names (invalidated on changes) */
1646
- __publicField$1(this, "orderedNamesCache", null);
1647
- this.initializeDefaultPhases();
1648
- }
1649
- //* Initialization --------------------------------
1650
- initializeDefaultPhases() {
1651
- for (const name of DEFAULT_PHASES) {
1652
- const node = { name, isAutoGenerated: false };
1653
- this.phases.push(node);
1654
- this.phaseMap.set(name, node);
1655
- }
1656
- this.invalidateCache();
1657
- }
1658
- //* Public API --------------------------------
1659
- /**
1660
- * Add a named phase to the graph
1661
- * @param name - Phase name (must be unique)
1662
- * @param options - Position options (before or after another phase)
1663
- */
1664
- addPhase(name, options = {}) {
1665
- if (this.phaseMap.has(name)) {
1666
- console.warn(`[useFrame] Phase "${name}" already exists`);
1667
- return;
1668
- }
1669
- const { before, after } = options;
1670
- const node = { name, isAutoGenerated: false };
1671
- let insertIndex = this.phases.length;
1672
- const targetIndex = this.getPhaseIndex(before ?? after);
1673
- if (targetIndex !== -1) {
1674
- insertIndex = before ? targetIndex : targetIndex + 1;
1675
- } else {
1676
- const constraintType = before ? "before" : "after";
1677
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1678
- }
1679
- this.phases.splice(insertIndex, 0, node);
1680
- this.phaseMap.set(name, node);
1681
- this.invalidateCache();
1682
- }
1683
- /**
1684
- * Get ordered list of phase names
1685
- */
1686
- getOrderedPhases() {
1687
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1688
- return this.orderedNamesCache;
1689
- }
1690
- /**
1691
- * Check if a phase exists
1692
- */
1693
- hasPhase(name) {
1694
- return this.phaseMap.has(name);
1695
- }
1696
- /**
1697
- * Get the index of a phase (-1 if not found)
1698
- */
1699
- getPhaseIndex(name) {
1700
- if (!name) return -1;
1701
- return this.phases.findIndex((p) => p.name === name);
1702
- }
1703
- /**
1704
- * Ensure a phase exists, creating an auto-generated one if needed.
1705
- * Used for resolving before/after constraints.
1706
- *
1707
- * @param name - The phase name to ensure exists
1708
- * @returns The phase name (may be auto-generated like 'before:render')
1709
- */
1710
- ensurePhase(name) {
1711
- if (this.phaseMap.has(name)) return name;
1712
- const node = { name, isAutoGenerated: true };
1713
- this.phases.push(node);
1714
- this.phaseMap.set(name, node);
1715
- this.invalidateCache();
1716
- return name;
1717
- }
1718
- /**
1719
- * Resolve where a job with before/after constraints should go.
1720
- * Creates auto-generated phases if needed.
1721
- *
1722
- * @param before - Phase(s) to run before
1723
- * @param after - Phase(s) to run after
1724
- * @returns The resolved phase name
1725
- */
1726
- resolveConstraintPhase(before, after) {
1727
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1728
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1729
- if (beforeArr.length > 0) {
1730
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1731
- }
1732
- if (afterArr.length > 0) {
1733
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1734
- }
1735
- return "update";
1736
- }
1737
- /**
1738
- * Ensure an auto-generated phase exists relative to a target phase.
1739
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1740
- *
1741
- * @param target - The target phase name to position relative to
1742
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1743
- * @param offset - Insertion offset (0 for before, 1 for after)
1744
- * @returns The auto-generated phase name
1745
- */
1746
- ensureAutoPhase(target, prefix, offset) {
1747
- const autoName = `${prefix}:${target}`;
1748
- if (this.phaseMap.has(autoName)) return autoName;
1749
- const node = { name: autoName, isAutoGenerated: true };
1750
- const targetIndex = this.getPhaseIndex(target);
1751
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1752
- else this.phases.push(node);
1753
- this.phaseMap.set(autoName, node);
1754
- this.invalidateCache();
1755
- return autoName;
1756
- }
1757
- // Internal --------------------------------
1758
- invalidateCache() {
1759
- this.orderedNamesCache = null;
1760
- }
1761
- }
1762
-
1763
- function rebuildSortedJobs(jobs, phaseGraph) {
1764
- const orderedPhases = phaseGraph.getOrderedPhases();
1765
- const buckets = /* @__PURE__ */ new Map();
1766
- for (const phase of orderedPhases) {
1767
- buckets.set(phase, []);
1768
- }
1769
- for (const job of jobs.values()) {
1770
- if (!job.enabled) continue;
1771
- let bucket = buckets.get(job.phase);
1772
- if (!bucket) {
1773
- bucket = [];
1774
- buckets.set(job.phase, bucket);
1775
- }
1776
- bucket.push(job);
1777
- }
1778
- const sortedBuckets = [];
1779
- for (const phase of orderedPhases) {
1780
- const bucket = buckets.get(phase);
1781
- if (!bucket || bucket.length === 0) continue;
1782
- bucket.sort((a, b) => {
1783
- if (a.priority !== b.priority) return b.priority - a.priority;
1784
- return a.index - b.index;
1785
- });
1786
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1787
- }
1788
- for (const [phase, bucket] of buckets) {
1789
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1790
- bucket.sort((a, b) => {
1791
- if (a.priority !== b.priority) return b.priority - a.priority;
1792
- return a.index - b.index;
1793
- });
1794
- sortedBuckets.push(bucket);
1795
- }
1796
- }
1797
- return sortedBuckets.flat();
1798
- }
1799
- function hasCrossJobConstraints(bucket) {
1800
- const jobIds = new Set(bucket.map((j) => j.id));
1801
- for (const job of bucket) {
1802
- for (const ref of job.before) {
1803
- if (jobIds.has(ref)) return true;
1804
- }
1805
- for (const ref of job.after) {
1806
- if (jobIds.has(ref)) return true;
1807
- }
1808
- }
1809
- return false;
1810
- }
1811
- function topologicalSort(jobs) {
1812
- const n = jobs.length;
1813
- if (n <= 1) return jobs;
1814
- const jobMap = /* @__PURE__ */ new Map();
1815
- const inDegree = /* @__PURE__ */ new Map();
1816
- const adjacency = /* @__PURE__ */ new Map();
1817
- for (const job of jobs) {
1818
- jobMap.set(job.id, job);
1819
- inDegree.set(job.id, 0);
1820
- adjacency.set(job.id, []);
1821
- }
1822
- for (const job of jobs) {
1823
- for (const ref of job.before) {
1824
- if (jobMap.has(ref)) {
1825
- adjacency.get(job.id).push(ref);
1826
- inDegree.set(ref, inDegree.get(ref) + 1);
1827
- }
1828
- }
1829
- for (const ref of job.after) {
1830
- if (jobMap.has(ref)) {
1831
- adjacency.get(ref).push(job.id);
1832
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1833
- }
1834
- }
1835
- }
1836
- const queue = [];
1837
- for (const job of jobs) {
1838
- if (inDegree.get(job.id) === 0) {
1839
- queue.push(job);
1840
- }
1841
- }
1842
- queue.sort((a, b) => {
1843
- if (a.priority !== b.priority) return b.priority - a.priority;
1844
- return a.index - b.index;
1845
- });
1846
- const result = [];
1847
- while (queue.length > 0) {
1848
- const job = queue.shift();
1849
- result.push(job);
1850
- const neighbors = adjacency.get(job.id) || [];
1851
- for (const neighborId of neighbors) {
1852
- const newDegree = inDegree.get(neighborId) - 1;
1853
- inDegree.set(neighborId, newDegree);
1854
- if (newDegree === 0) {
1855
- const neighbor = jobMap.get(neighborId);
1856
- insertSorted(queue, neighbor);
1857
- }
1858
- }
1859
- }
1860
- if (result.length !== n) {
1861
- console.warn("[useFrame] Circular dependency detected in job constraints");
1862
- const resultIds = new Set(result.map((j) => j.id));
1863
- for (const job of jobs) {
1864
- if (!resultIds.has(job.id)) result.push(job);
1865
- }
1866
- }
1867
- return result;
1868
- }
1869
- function insertSorted(arr, job) {
1870
- let i = 0;
1871
- while (i < arr.length) {
1872
- const cmp = arr[i];
1873
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1874
- break;
1875
- }
1876
- i++;
1877
- }
1878
- arr.splice(i, 0, job);
1879
- }
1880
-
1881
- function shouldRun(job, now) {
1882
- if (!job.enabled) return false;
1883
- if (!job.fps) return true;
1884
- const minInterval = 1e3 / job.fps;
1885
- const lastRun = job.lastRun ?? 0;
1886
- const elapsed = now - lastRun;
1887
- if (elapsed < minInterval) return false;
1888
- if (job.drop) {
1889
- job.lastRun = now;
1890
- } else {
1891
- const steps = Math.floor(elapsed / minInterval);
1892
- job.lastRun = lastRun + steps * minInterval;
1893
- if (job.lastRun < now - minInterval) {
1894
- job.lastRun = now;
1895
- }
1896
- }
1897
- return true;
1898
- }
1899
- function resetJobTiming(job) {
1900
- job.lastRun = void 0;
1901
- }
1902
-
1903
- var __defProp = Object.defineProperty;
1904
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1905
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1906
- const hmrData = (() => {
1907
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1908
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1909
- try {
1910
- return (0, eval)("import.meta.hot");
1911
- } catch {
1912
- return void 0;
1913
- }
1914
- })();
1915
- const _Scheduler = class _Scheduler {
1916
- //* Constructor ================================
1917
- constructor() {
1918
- //* Critical State ================================
1919
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1920
- __publicField(this, "phaseGraph");
1921
- __publicField(this, "loopState", {
1922
- running: false,
1923
- rafHandle: null,
1924
- lastTime: null,
1925
- // null = uninitialized, 0+ = valid timestamp
1926
- frameCount: 0,
1927
- elapsedTime: 0,
1928
- createdAt: performance.now()
1929
- });
1930
- __publicField(this, "stoppedTime", 0);
1931
- //* Private State ================================
1932
- __publicField(this, "nextRootIndex", 0);
1933
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1934
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1935
- __publicField(this, "nextGlobalIndex", 0);
1936
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1937
- __publicField(this, "nextJobIndex", 0);
1938
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1939
- __publicField(this, "pendingFrames", 0);
1940
- __publicField(this, "_frameloop", "always");
1941
- //* Independent Mode & Error Handling State ================================
1942
- __publicField(this, "_independent", false);
1943
- __publicField(this, "errorHandler", null);
1944
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1945
- //* Core Loop Execution Methods ================================
1946
- /**
1947
- * Main RAF loop callback.
1948
- * Executes frame, handles demand mode, and schedules next frame.
1949
- * @param {number} timestamp - RAF timestamp in milliseconds
1950
- * @returns {void}
1951
- * @private
1952
- */
1953
- __publicField(this, "loop", (timestamp) => {
1954
- if (!this.loopState.running) return;
1955
- this.executeFrame(timestamp);
1956
- if (this._frameloop === "demand") {
1957
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1958
- if (this.pendingFrames === 0) {
1959
- this.notifyIdle(timestamp);
1960
- return this.stop();
1961
- }
1962
- }
1963
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1964
- });
1965
- this.phaseGraph = new PhaseGraph();
1966
- }
1967
- static get instance() {
1968
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1969
- }
1970
- static set instance(value) {
1971
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1972
- }
1973
- /**
1974
- * Get the global scheduler instance (creates if doesn't exist).
1975
- * Uses HMR data to preserve instance across hot reloads.
1976
- * @returns {Scheduler} The singleton scheduler instance
1977
- */
1978
- static get() {
1979
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1980
- _Scheduler.instance = hmrData.data.scheduler;
1981
- }
1982
- if (!_Scheduler.instance) {
1983
- _Scheduler.instance = new _Scheduler();
1984
- if (hmrData?.data) {
1985
- hmrData.data.scheduler = _Scheduler.instance;
1986
- }
1987
- }
1988
- return _Scheduler.instance;
1989
- }
1990
- /**
1991
- * Reset the singleton instance. Stops the loop and clears all state.
1992
- * Primarily used for testing to ensure clean state between tests.
1993
- * @returns {void}
1994
- */
1995
- static reset() {
1996
- if (_Scheduler.instance) {
1997
- _Scheduler.instance.stop();
1998
- _Scheduler.instance = null;
1999
- }
2000
- if (hmrData?.data) {
2001
- hmrData.data.scheduler = null;
2002
- }
2003
- }
2004
- //* Getters & Setters ================================
2005
- get phases() {
2006
- return this.phaseGraph.getOrderedPhases();
2007
- }
2008
- get frameloop() {
2009
- return this._frameloop;
2010
- }
2011
- set frameloop(mode) {
2012
- if (this._frameloop === mode) return;
2013
- const wasAlways = this._frameloop === "always";
2014
- this._frameloop = mode;
2015
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2016
- else if (mode !== "always" && wasAlways) this.stop();
2017
- }
2018
- get isRunning() {
2019
- return this.loopState.running;
2020
- }
2021
- get isReady() {
2022
- return this.roots.size > 0;
2023
- }
2024
- get independent() {
2025
- return this._independent;
2026
- }
2027
- set independent(value) {
2028
- this._independent = value;
2029
- if (value) this.ensureDefaultRoot();
2030
- }
2031
- //* Root Management Methods ================================
2032
- /**
2033
- * Register a root (Canvas) with the scheduler.
2034
- * The first root to register starts the RAF loop (if frameloop='always').
2035
- * @param {string} id - Unique identifier for this root
2036
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2037
- * @returns {() => void} Unsubscribe function to remove this root
2038
- */
2039
- registerRoot(id, options = {}) {
2040
- if (this.roots.has(id)) {
2041
- console.warn(`[Scheduler] Root "${id}" already registered`);
2042
- return () => this.unregisterRoot(id);
2043
- }
2044
- const entry = {
2045
- id,
2046
- getState: options.getState ?? (() => ({})),
2047
- jobs: /* @__PURE__ */ new Map(),
2048
- sortedJobs: [],
2049
- needsRebuild: false
2050
- };
2051
- if (options.onError) {
2052
- this.errorHandler = options.onError;
2053
- }
2054
- this.roots.set(id, entry);
2055
- if (this.roots.size === 1) {
2056
- this.notifyRootReady();
2057
- if (this._frameloop === "always") this.start();
2058
- }
2059
- return () => this.unregisterRoot(id);
2060
- }
2061
- /**
2062
- * Unregister a root from the scheduler.
2063
- * Cleans up all job state listeners for this root's jobs.
2064
- * The last root to unregister stops the RAF loop.
2065
- * @param {string} id - The root ID to unregister
2066
- * @returns {void}
2067
- */
2068
- unregisterRoot(id) {
2069
- const root = this.roots.get(id);
2070
- if (!root) return;
2071
- for (const jobId of root.jobs.keys()) {
2072
- this.jobStateListeners.delete(jobId);
2073
- }
2074
- this.roots.delete(id);
2075
- if (this.roots.size === 0) {
2076
- this.stop();
2077
- this.errorHandler = null;
2078
- }
2079
- }
2080
- /**
2081
- * Subscribe to be notified when a root becomes available.
2082
- * Fires immediately if a root already exists.
2083
- * @param {() => void} callback - Function called when first root registers
2084
- * @returns {() => void} Unsubscribe function
2085
- */
2086
- onRootReady(callback) {
2087
- if (this.roots.size > 0) {
2088
- callback();
2089
- return () => {
2090
- };
2091
- }
2092
- this.rootReadyCallbacks.add(callback);
2093
- return () => this.rootReadyCallbacks.delete(callback);
2094
- }
2095
- /**
2096
- * Notify all registered root-ready callbacks.
2097
- * Called when the first root registers.
2098
- * @returns {void}
2099
- * @private
2100
- */
2101
- notifyRootReady() {
2102
- for (const cb of this.rootReadyCallbacks) {
2103
- try {
2104
- cb();
2105
- } catch (error) {
2106
- console.error("[Scheduler] Error in root-ready callback:", error);
2107
- }
2108
- }
2109
- this.rootReadyCallbacks.clear();
2110
- }
2111
- /**
2112
- * Ensure a default root exists for independent mode.
2113
- * Creates a minimal root with no state provider.
2114
- * @returns {void}
2115
- * @private
2116
- */
2117
- ensureDefaultRoot() {
2118
- if (!this.roots.has("__default__")) {
2119
- this.registerRoot("__default__");
2120
- }
2121
- }
2122
- /**
2123
- * Trigger error handling for job errors.
2124
- * Uses the bound error handler if available, otherwise logs to console.
2125
- * @param {Error} error - The error to handle
2126
- * @returns {void}
2127
- */
2128
- triggerError(error) {
2129
- if (this.errorHandler) this.errorHandler(error);
2130
- else console.error("[Scheduler]", error);
2131
- }
2132
- //* Phase Management Methods ================================
2133
- /**
2134
- * Add a named phase to the scheduler's execution order.
2135
- * Marks all roots for rebuild to incorporate the new phase.
2136
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2137
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2138
- * @returns {void}
2139
- * @example
2140
- * scheduler.addPhase('physics', { before: 'update' });
2141
- * scheduler.addPhase('postprocess', { after: 'render' });
2142
- */
2143
- addPhase(name, options) {
2144
- this.phaseGraph.addPhase(name, options);
2145
- for (const root of this.roots.values()) {
2146
- root.needsRebuild = true;
2147
- }
2148
- }
2149
- /**
2150
- * Check if a phase exists in the scheduler.
2151
- * @param {string} name - The phase name to check
2152
- * @returns {boolean} True if the phase exists
2153
- */
2154
- hasPhase(name) {
2155
- return this.phaseGraph.hasPhase(name);
2156
- }
2157
- //* Global Job Registration Methods (Deprecated APIs) ================================
2158
- /**
2159
- * Register a global job that runs once per frame (not per-root).
2160
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2161
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2162
- * @param {string} id - Unique identifier for this global job
2163
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2164
- * @returns {() => void} Unsubscribe function to remove this global job
2165
- * @deprecated Use useFrame with phases instead
2166
- */
2167
- registerGlobal(phase, id, callback) {
2168
- const job = { id, callback };
2169
- if (phase === "before") {
2170
- this.globalBeforeJobs.set(id, job);
2171
- } else {
2172
- this.globalAfterJobs.set(id, job);
2173
- }
2174
- return () => {
2175
- if (phase === "before") this.globalBeforeJobs.delete(id);
2176
- else this.globalAfterJobs.delete(id);
2177
- };
2178
- }
2179
- //* Idle Callback Methods (Deprecated API) ================================
2180
- /**
2181
- * Register an idle callback that fires when the loop stops.
2182
- * Used internally by deprecated addTail API.
2183
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2184
- * @returns {() => void} Unsubscribe function to remove this idle callback
2185
- * @deprecated Use demand mode with invalidate() instead
2186
- */
2187
- onIdle(callback) {
2188
- this.idleCallbacks.add(callback);
2189
- return () => this.idleCallbacks.delete(callback);
2190
- }
2191
- /**
2192
- * Notify all registered idle callbacks.
2193
- * Called when the loop stops in demand mode.
2194
- * @param {number} timestamp - The RAF timestamp when idle occurred
2195
- * @returns {void}
2196
- * @private
2197
- */
2198
- notifyIdle(timestamp) {
2199
- for (const cb of this.idleCallbacks) {
2200
- try {
2201
- cb(timestamp);
2202
- } catch (error) {
2203
- console.error("[Scheduler] Error in idle callback:", error);
2204
- }
2205
- }
2206
- }
2207
- //* Job Registration & Management Methods ================================
2208
- /**
2209
- * Register a job (frame callback) with a specific root.
2210
- * This is the core registration method used by useFrame internally.
2211
- * @param {FrameNextCallback} callback - The function to call each frame
2212
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2213
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2214
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2215
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2216
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2217
- * @param {number} [options.fps] - FPS throttle limit
2218
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2219
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2220
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2221
- * @returns {() => void} Unsubscribe function to remove this job
2222
- */
2223
- register(callback, options = {}) {
2224
- const rootId = options.rootId;
2225
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2226
- if (!root) {
2227
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2228
- return () => {
2229
- };
2230
- }
2231
- const id = options.id ?? this.generateJobId();
2232
- let phase = options.phase ?? "update";
2233
- if (!options.phase && (options.before || options.after)) {
2234
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2235
- }
2236
- const before = this.normalizeConstraints(options.before);
2237
- const after = this.normalizeConstraints(options.after);
2238
- const job = {
2239
- id,
2240
- callback,
2241
- phase,
2242
- before,
2243
- after,
2244
- priority: options.priority ?? 0,
2245
- index: this.nextJobIndex++,
2246
- fps: options.fps,
2247
- drop: options.drop ?? true,
2248
- enabled: options.enabled ?? true,
2249
- system: options.system ?? false
2250
- };
2251
- if (root.jobs.has(id)) {
2252
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2253
- }
2254
- root.jobs.set(id, job);
2255
- root.needsRebuild = true;
2256
- return () => this.unregister(id, root.id);
2257
- }
2258
- /**
2259
- * Unregister a job by its ID.
2260
- * Searches all roots if rootId is not provided.
2261
- * @param {string} id - The job ID to unregister
2262
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2263
- * @returns {void}
2264
- */
2265
- unregister(id, rootId) {
2266
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2267
- if (root?.jobs.delete(id)) {
2268
- root.needsRebuild = true;
2269
- this.jobStateListeners.delete(id);
2270
- }
2271
- }
2272
- /**
2273
- * Update a job's options dynamically.
2274
- * Searches all roots to find the job by ID.
2275
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2276
- * @param {string} id - The job ID to update
2277
- * @param {Partial<JobOptions>} options - The options to update
2278
- * @returns {void}
2279
- */
2280
- updateJob(id, options) {
2281
- let job;
2282
- let root;
2283
- for (const r of this.roots.values()) {
2284
- job = r.jobs.get(id);
2285
- if (job) {
2286
- root = r;
2287
- break;
2288
- }
2289
- }
2290
- if (!job || !root) return;
2291
- if (options.priority !== void 0) job.priority = options.priority;
2292
- if (options.fps !== void 0) job.fps = options.fps;
2293
- if (options.drop !== void 0) job.drop = options.drop;
2294
- if (options.enabled !== void 0) {
2295
- const wasEnabled = job.enabled;
2296
- job.enabled = options.enabled;
2297
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2298
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2299
- }
2300
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2301
- if (options.phase) job.phase = options.phase;
2302
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2303
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2304
- root.needsRebuild = true;
2305
- }
2306
- }
2307
- //* Job State Management Methods ================================
2308
- /**
2309
- * Check if a job is currently paused (disabled).
2310
- * @param {string} id - The job ID to check
2311
- * @returns {boolean} True if the job exists and is paused
2312
- */
2313
- isJobPaused(id) {
2314
- for (const root of this.roots.values()) {
2315
- const job = root.jobs.get(id);
2316
- if (job) return !job.enabled;
2317
- }
2318
- return false;
2319
- }
2320
- /**
2321
- * Subscribe to state changes for a specific job.
2322
- * Listener is called when job is paused or resumed.
2323
- * @param {string} id - The job ID to subscribe to
2324
- * @param {() => void} listener - Callback invoked on state changes
2325
- * @returns {() => void} Unsubscribe function
2326
- */
2327
- subscribeJobState(id, listener) {
2328
- if (!this.jobStateListeners.has(id)) {
2329
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2330
- }
2331
- this.jobStateListeners.get(id).add(listener);
2332
- return () => {
2333
- this.jobStateListeners.get(id)?.delete(listener);
2334
- if (this.jobStateListeners.get(id)?.size === 0) {
2335
- this.jobStateListeners.delete(id);
2336
- }
2337
- };
2338
- }
2339
- /**
2340
- * Notify all listeners that a job's state has changed.
2341
- * @param {string} id - The job ID that changed
2342
- * @returns {void}
2343
- * @private
2344
- */
2345
- notifyJobStateChange(id) {
2346
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2347
- }
2348
- /**
2349
- * Pause a job by ID (sets enabled=false).
2350
- * Notifies any subscribed state listeners.
2351
- * @param {string} id - The job ID to pause
2352
- * @returns {void}
2353
- */
2354
- pauseJob(id) {
2355
- this.updateJob(id, { enabled: false });
2356
- this.notifyJobStateChange(id);
2357
- }
2358
- /**
2359
- * Resume a paused job by ID (sets enabled=true).
2360
- * Resets job timing to prevent frame accumulation.
2361
- * Notifies any subscribed state listeners.
2362
- * @param {string} id - The job ID to resume
2363
- * @returns {void}
2364
- */
2365
- resumeJob(id) {
2366
- this.updateJob(id, { enabled: true });
2367
- this.notifyJobStateChange(id);
2368
- }
2369
- //* Frame Loop Control Methods ================================
2370
- /**
2371
- * Start the requestAnimationFrame loop.
2372
- * Resets timing state (elapsedTime, frameCount) on start.
2373
- * No-op if already running.
2374
- * @returns {void}
2375
- */
2376
- start() {
2377
- if (this.loopState.running) return;
2378
- const { elapsedTime, createdAt } = this.loopState;
2379
- let adjustedCreated = 0;
2380
- if (this.stoppedTime > 0) {
2381
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2382
- this.stoppedTime = 0;
2383
- }
2384
- Object.assign(this.loopState, {
2385
- running: true,
2386
- elapsedTime: elapsedTime ?? 0,
2387
- lastTime: performance.now(),
2388
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2389
- frameCount: 0,
2390
- rafHandle: requestAnimationFrame(this.loop)
2391
- });
2392
- }
2393
- /**
2394
- * Stop the requestAnimationFrame loop.
2395
- * Cancels any pending RAF callback.
2396
- * No-op if not running.
2397
- * @returns {void}
2398
- */
2399
- stop() {
2400
- if (!this.loopState.running) return;
2401
- this.loopState.running = false;
2402
- if (this.loopState.rafHandle !== null) {
2403
- cancelAnimationFrame(this.loopState.rafHandle);
2404
- this.loopState.rafHandle = null;
2405
- }
2406
- this.stoppedTime = performance.now();
2407
- }
2408
- /**
2409
- * Request frames to be rendered in demand mode.
2410
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2411
- * No-op if frameloop is not 'demand'.
2412
- * @param {number} [frames=1] - Number of frames to request
2413
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2414
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2415
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2416
- * @returns {void}
2417
- * @example
2418
- * // Request a single frame render
2419
- * scheduler.invalidate();
2420
- *
2421
- * @example
2422
- * // Request 5 frames (e.g., for animations)
2423
- * scheduler.invalidate(5);
2424
- *
2425
- * @example
2426
- * // Set pending frames to exactly 3 (don't stack with existing)
2427
- * scheduler.invalidate(3, false);
2428
- *
2429
- * @example
2430
- * // Add 2 more frames to existing pending count
2431
- * scheduler.invalidate(2, true);
2432
- */
2433
- invalidate(frames = 1, stackFrames = false) {
2434
- if (this._frameloop !== "demand") return;
2435
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2436
- this.pendingFrames = Math.min(60, baseFrames + frames);
2437
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2438
- }
2439
- /**
2440
- * Reset timing state for deterministic testing.
2441
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2442
- * @returns {void}
2443
- */
2444
- resetTiming() {
2445
- this.loopState.lastTime = null;
2446
- this.loopState.frameCount = 0;
2447
- this.loopState.elapsedTime = 0;
2448
- this.loopState.createdAt = performance.now();
2449
- }
2450
- //* Manual Stepping Methods ================================
2451
- /**
2452
- * Manually execute a single frame for all roots.
2453
- * Useful for frameloop='never' mode or testing scenarios.
2454
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2455
- * @returns {void}
2456
- * @example
2457
- * // Manual control mode
2458
- * scheduler.frameloop = 'never';
2459
- * scheduler.step(); // Execute one frame
2460
- */
2461
- step(timestamp) {
2462
- const now = timestamp ?? performance.now();
2463
- this.executeFrame(now);
2464
- }
2465
- /**
2466
- * Manually execute a single job by its ID.
2467
- * Useful for testing individual job callbacks in isolation.
2468
- * @param {string} id - The job ID to step
2469
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2470
- * @returns {void}
2471
- */
2472
- stepJob(id, timestamp) {
2473
- let job;
2474
- let root;
2475
- for (const r of this.roots.values()) {
2476
- job = r.jobs.get(id);
2477
- if (job) {
2478
- root = r;
2479
- break;
2480
- }
2481
- }
2482
- if (!job || !root) {
2483
- console.warn(`[Scheduler] Job "${id}" not found`);
2484
- return;
2485
- }
2486
- const now = timestamp ?? performance.now();
2487
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2488
- const delta = deltaMs / 1e3;
2489
- const elapsed = now - this.loopState.createdAt;
2490
- const providedState = root.getState?.() ?? {};
2491
- const frameState = {
2492
- ...providedState,
2493
- time: now,
2494
- delta,
2495
- elapsed,
2496
- frame: this.loopState.frameCount
2497
- };
2498
- try {
2499
- job.callback(frameState, delta);
2500
- } catch (error) {
2501
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2502
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2503
- }
2504
- }
2505
- /**
2506
- * Execute a single frame across all roots.
2507
- * Order: globalBefore → each root's jobs → globalAfter
2508
- * @param {number} timestamp - RAF timestamp in milliseconds
2509
- * @returns {void}
2510
- * @private
2511
- */
2512
- executeFrame(timestamp) {
2513
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2514
- const delta = deltaMs / 1e3;
2515
- this.loopState.lastTime = timestamp;
2516
- this.loopState.frameCount++;
2517
- this.loopState.elapsedTime += deltaMs;
2518
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2519
- for (const root of this.roots.values()) {
2520
- this.tickRoot(root, timestamp, delta);
2521
- }
2522
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2523
- }
2524
- /**
2525
- * Run all global jobs from a job map.
2526
- * Catches and logs errors without stopping execution.
2527
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2528
- * @param {number} timestamp - RAF timestamp in milliseconds
2529
- * @returns {void}
2530
- * @private
2531
- */
2532
- runGlobalJobs(jobs, timestamp) {
2533
- for (const job of jobs.values()) {
2534
- try {
2535
- job.callback(timestamp);
2536
- } catch (error) {
2537
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2538
- }
2539
- }
2540
- }
2541
- /**
2542
- * Execute all jobs for a single root in sorted order.
2543
- * Rebuilds sorted job list if needed, then dispatches each job.
2544
- * Errors are caught and propagated via triggerError.
2545
- * @param {RootEntry} root - The root entry to tick
2546
- * @param {number} timestamp - RAF timestamp in milliseconds
2547
- * @param {number} delta - Time since last frame in seconds
2548
- * @returns {void}
2549
- * @private
2550
- */
2551
- tickRoot(root, timestamp, delta) {
2552
- if (root.needsRebuild) {
2553
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2554
- root.needsRebuild = false;
2555
- }
2556
- const providedState = root.getState?.() ?? {};
2557
- const frameState = {
2558
- ...providedState,
2559
- time: timestamp,
2560
- delta,
2561
- elapsed: this.loopState.elapsedTime / 1e3,
2562
- // Convert ms to seconds
2563
- frame: this.loopState.frameCount
2564
- };
2565
- for (const job of root.sortedJobs) {
2566
- if (!shouldRun(job, timestamp)) continue;
2567
- try {
2568
- job.callback(frameState, delta);
2569
- } catch (error) {
2570
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2571
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2572
- }
2573
- }
2574
- }
2575
- //* Debug & Inspection Methods ================================
2576
- /**
2577
- * Get the total number of registered jobs across all roots.
2578
- * Includes both per-root jobs and global before/after jobs.
2579
- * @returns {number} Total job count
2580
- */
2581
- getJobCount() {
2582
- let count = 0;
2583
- for (const root of this.roots.values()) {
2584
- count += root.jobs.size;
2585
- }
2586
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2587
- }
2588
- /**
2589
- * Get all registered job IDs across all roots.
2590
- * Includes both per-root jobs and global before/after jobs.
2591
- * @returns {string[]} Array of all job IDs
2592
- */
2593
- getJobIds() {
2594
- const ids = [];
2595
- for (const root of this.roots.values()) {
2596
- ids.push(...root.jobs.keys());
2597
- }
2598
- ids.push(...this.globalBeforeJobs.keys());
2599
- ids.push(...this.globalAfterJobs.keys());
2600
- return ids;
2601
- }
2602
- /**
2603
- * Get the number of registered roots (Canvas instances).
2604
- * @returns {number} Number of registered roots
2605
- */
2606
- getRootCount() {
2607
- return this.roots.size;
2608
- }
2609
- /**
2610
- * Check if any user (non-system) jobs are registered in a specific phase.
2611
- * Used by the default render job to know if a user has taken over rendering.
2612
- *
2613
- * @param phase The phase to check
2614
- * @param rootId Optional root ID to check (checks all roots if not provided)
2615
- * @returns true if any user jobs exist in the phase
2616
- */
2617
- hasUserJobsInPhase(phase, rootId) {
2618
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2619
- return rootsToCheck.some((root) => {
2620
- if (!root) return false;
2621
- for (const job of root.jobs.values()) {
2622
- if (job.phase === phase && !job.system && job.enabled) return true;
2623
- }
2624
- return false;
2625
- });
2626
- }
2627
- //* Utility Methods ================================
2628
- /**
2629
- * Generate a unique root ID for automatic root registration.
2630
- * @returns {string} A unique root ID in the format 'root_N'
2631
- */
2632
- generateRootId() {
2633
- return `root_${this.nextRootIndex++}`;
2634
- }
2635
- /**
2636
- * Generate a unique job ID.
2637
- * @returns {string} A unique job ID in the format 'job_N'
2638
- * @private
2639
- */
2640
- generateJobId() {
2641
- return `job_${this.nextJobIndex}`;
2642
- }
2643
- /**
2644
- * Normalize before/after constraints to a Set.
2645
- * Handles undefined, single string, or array inputs.
2646
- * @param {string | string[] | undefined} value - The constraint value(s)
2647
- * @returns {Set<string>} Normalized Set of constraint strings
2648
- * @private
2649
- */
2650
- normalizeConstraints(value) {
2651
- if (!value) return /* @__PURE__ */ new Set();
2652
- if (Array.isArray(value)) return new Set(value);
2653
- return /* @__PURE__ */ new Set([value]);
2654
- }
2655
- };
2656
- //* Static State & Methods (Singleton Usage) ================================
2657
- //* Cross-Bundle Singleton Key ==============================
2658
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2659
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2660
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2661
- let Scheduler = _Scheduler;
2662
- const getScheduler = () => Scheduler.get();
2663
- if (hmrData) {
2664
- hmrData.accept?.();
1682
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1683
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1684
+ if (!stack) return false;
1685
+ const caller = stack.split("\n")[callerDepth] ?? "";
1686
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2665
1687
  }
2666
1688
 
2667
1689
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2773,7 +1795,7 @@ const createStore = (invalidate, advance) => {
2773
1795
  size: newSize,
2774
1796
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2775
1797
  }));
2776
- getScheduler().invalidate();
1798
+ scheduler.getScheduler().invalidate();
2777
1799
  }
2778
1800
  }
2779
1801
  return;
@@ -2788,7 +1810,7 @@ const createStore = (invalidate, advance) => {
2788
1810
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2789
1811
  _sizeImperative: true
2790
1812
  }));
2791
- getScheduler().invalidate();
1813
+ scheduler.getScheduler().invalidate();
2792
1814
  },
2793
1815
  setDpr: (dpr) => set((state2) => {
2794
1816
  const resolved = calculateDpr(dpr);
@@ -2796,6 +1818,7 @@ const createStore = (invalidate, advance) => {
2796
1818
  }),
2797
1819
  setFrameloop: (frameloop = "always") => {
2798
1820
  set(() => ({ frameloop }));
1821
+ scheduler.getScheduler().frameloop = frameloop;
2799
1822
  },
2800
1823
  setError: (error) => set(() => ({ error })),
2801
1824
  error: null,
@@ -2805,6 +1828,7 @@ const createStore = (invalidate, advance) => {
2805
1828
  buffers: {},
2806
1829
  gpuStorage: {},
2807
1830
  textures: /* @__PURE__ */ new Map(),
1831
+ _textureRefs: /* @__PURE__ */ new Map(),
2808
1832
  renderPipeline: null,
2809
1833
  passes: {},
2810
1834
  _hmrVersion: 0,
@@ -2862,8 +1886,7 @@ const createStore = (invalidate, advance) => {
2862
1886
  const currentState = rootStore.getState();
2863
1887
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2864
1888
  const stack = new Error().stack || "";
2865
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2866
- if (!isInternalAccess) {
1889
+ if (!isInternalRendererAccess(stack)) {
2867
1890
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2868
1891
  notifyDepreciated({
2869
1892
  heading: "Accessing state.gl in WebGPU mode",
@@ -2911,14 +1934,16 @@ const createStore = (invalidate, advance) => {
2911
1934
  oldSize = size;
2912
1935
  oldDpr = viewport.dpr;
2913
1936
  updateCamera(camera, size);
2914
- if (canvasTarget) {
1937
+ if (internal.isSecondary && canvasTarget) {
2915
1938
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2916
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2917
- canvasTarget.setSize(size.width, size.height, updateStyle);
1939
+ canvasTarget.setSize(size.width, size.height, false);
2918
1940
  } else {
2919
1941
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2920
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2921
- actualRenderer.setSize(size.width, size.height, updateStyle);
1942
+ actualRenderer.setSize(size.width, size.height, false);
1943
+ if (canvasTarget) {
1944
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1945
+ canvasTarget.setSize(size.width, size.height, false);
1946
+ }
2922
1947
  }
2923
1948
  }
2924
1949
  if (camera !== oldCamera) {
@@ -2974,26 +1999,32 @@ function loadingFn(extensions, onProgress) {
2974
1999
  );
2975
2000
  };
2976
2001
  }
2977
- function useLoader(loader, input, extensions, onProgress) {
2978
- const keys = Array.isArray(input) ? input : [input];
2002
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2003
+ const inputs = Array.isArray(input) ? input : [input];
2004
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2979
2005
  const fn = loadingFn(extensions, onProgress);
2980
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2006
+ const results = cacheKeys.map(
2007
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2008
+ );
2981
2009
  return Array.isArray(input) ? results : results[0];
2982
2010
  }
2983
- useLoader.preload = function(loader, input, extensions, onProgress) {
2984
- const keys = Array.isArray(input) ? input : [input];
2985
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2011
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2012
+ const inputs = Array.isArray(input) ? input : [input];
2013
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2014
+ cacheKeys.forEach(
2015
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2016
+ );
2986
2017
  };
2987
- useLoader.clear = function(loader, input) {
2988
- const keys = Array.isArray(input) ? input : [input];
2989
- keys.forEach((key) => suspendReact.clear([loader, key]));
2018
+ useLoader.clear = function(loader, input, cacheKey) {
2019
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2020
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
2990
2021
  };
2991
2022
  useLoader.loader = getLoader;
2992
2023
 
2993
2024
  function useFrame(callback, priorityOrOptions) {
2994
2025
  const store = React__namespace.useContext(context);
2995
2026
  const isInsideCanvas = store !== null;
2996
- const scheduler = getScheduler();
2027
+ const scheduler$1 = scheduler.getScheduler();
2997
2028
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2998
2029
  id: priorityOrOptions.id,
2999
2030
  phase: priorityOrOptions.phase,
@@ -3041,7 +2072,7 @@ function useFrame(callback, priorityOrOptions) {
3041
2072
  };
3042
2073
  callbackRef.current?.(mergedState, delta);
3043
2074
  };
3044
- const unregister = scheduler.register(wrappedCallback, {
2075
+ const unregister = scheduler$1.register(wrappedCallback, {
3045
2076
  id,
3046
2077
  rootId,
3047
2078
  ...options
@@ -3062,37 +2093,31 @@ function useFrame(callback, priorityOrOptions) {
3062
2093
  }
3063
2094
  };
3064
2095
  } else {
3065
- const registerOutside = () => {
3066
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3067
- };
3068
- if (scheduler.independent || scheduler.isReady) {
3069
- return registerOutside();
3070
- }
3071
- let unregisterJob = null;
3072
- const unsubReady = scheduler.onRootReady(() => {
3073
- unregisterJob = registerOutside();
3074
- });
3075
- return () => {
3076
- unsubReady();
3077
- unregisterJob?.();
3078
- };
2096
+ return scheduler$1.register(
2097
+ (state, delta) => {
2098
+ const frameState = state;
2099
+ if (!frameState.renderer) return;
2100
+ callbackRef.current?.(frameState, delta);
2101
+ },
2102
+ { id, ...options }
2103
+ );
3079
2104
  }
3080
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2105
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3081
2106
  const isPaused = React__namespace.useSyncExternalStore(
3082
2107
  // Subscribe function
3083
2108
  React__namespace.useCallback(
3084
2109
  (onStoreChange) => {
3085
- return getScheduler().subscribeJobState(id, onStoreChange);
2110
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3086
2111
  },
3087
2112
  [id]
3088
2113
  ),
3089
2114
  // getSnapshot function
3090
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2115
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3091
2116
  // getServerSnapshot function (SSR)
3092
2117
  React__namespace.useCallback(() => false, [])
3093
2118
  );
3094
2119
  const controls = React__namespace.useMemo(() => {
3095
- const scheduler2 = getScheduler();
2120
+ const scheduler2 = scheduler.getScheduler();
3096
2121
  return {
3097
2122
  /** The job's unique ID */
3098
2123
  id,
@@ -3107,7 +2132,7 @@ function useFrame(callback, priorityOrOptions) {
3107
2132
  * @param timestamp Optional timestamp (defaults to performance.now())
3108
2133
  */
3109
2134
  step: (timestamp) => {
3110
- getScheduler().stepJob(id, timestamp);
2135
+ scheduler.getScheduler().stepJob(id, timestamp);
3111
2136
  },
3112
2137
  /**
3113
2138
  * Manually step ALL jobs in the scheduler.
@@ -3115,20 +2140,20 @@ function useFrame(callback, priorityOrOptions) {
3115
2140
  * @param timestamp Optional timestamp (defaults to performance.now())
3116
2141
  */
3117
2142
  stepAll: (timestamp) => {
3118
- getScheduler().step(timestamp);
2143
+ scheduler.getScheduler().step(timestamp);
3119
2144
  },
3120
2145
  /**
3121
2146
  * Pause this job (set enabled=false).
3122
2147
  * Job remains registered but won't run.
3123
2148
  */
3124
2149
  pause: () => {
3125
- getScheduler().pauseJob(id);
2150
+ scheduler.getScheduler().pauseJob(id);
3126
2151
  },
3127
2152
  /**
3128
2153
  * Resume this job (set enabled=true).
3129
2154
  */
3130
2155
  resume: () => {
3131
- getScheduler().resumeJob(id);
2156
+ scheduler.getScheduler().resumeJob(id);
3132
2157
  },
3133
2158
  /**
3134
2159
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3166,18 +2191,18 @@ function buildFromCache(input, textureCache) {
3166
2191
  function useTexture(input, optionsOrOnLoad) {
3167
2192
  const renderer = useThree((state) => state.internal.actualRenderer);
3168
2193
  const store = useStore();
3169
- const textureCache = useThree((state) => state.textures);
3170
2194
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3171
- const { onLoad, cache = false } = options;
2195
+ const { onLoad, cache = true } = options;
3172
2196
  const onLoadRef = React.useRef(onLoad);
3173
2197
  onLoadRef.current = onLoad;
3174
2198
  const onLoadCalledForRef = React.useRef(null);
3175
2199
  const urls = React.useMemo(() => getUrls(input), [input]);
3176
2200
  const cachedResult = React.useMemo(() => {
3177
2201
  if (!cache) return null;
3178
- if (!allUrlsCached(urls, textureCache)) return null;
3179
- return buildFromCache(input, textureCache);
3180
- }, [cache, urls, textureCache, input]);
2202
+ const textures = store.getState().textures;
2203
+ if (!allUrlsCached(urls, textures)) return null;
2204
+ return buildFromCache(input, textures);
2205
+ }, [cache, urls, input, store]);
3181
2206
  const loadedTextures = useLoader(
3182
2207
  webgpu.TextureLoader,
3183
2208
  IsObject(input) ? Object.values(input) : input
@@ -3221,8 +2246,6 @@ function useTexture(input, optionsOrOnLoad) {
3221
2246
  }, [input, loadedTextures, cachedResult]);
3222
2247
  React.useEffect(() => {
3223
2248
  if (!cache) return;
3224
- if (cachedResult) return;
3225
- const set = store.setState;
3226
2249
  const urlTextureMap = [];
3227
2250
  if (typeof input === "string") {
3228
2251
  urlTextureMap.push([input, mappedTextures]);
@@ -3236,18 +2259,32 @@ function useTexture(input, optionsOrOnLoad) {
3236
2259
  urlTextureMap.push([url, textureRecord[key]]);
3237
2260
  }
3238
2261
  }
3239
- set((state) => {
3240
- const newMap = new Map(state.textures);
3241
- let changed = false;
2262
+ store.setState((state) => {
2263
+ const refs = new Map(state._textureRefs);
2264
+ let textures = state.textures;
2265
+ let added = false;
3242
2266
  for (const [url, texture] of urlTextureMap) {
3243
- if (!newMap.has(url)) {
3244
- newMap.set(url, texture);
3245
- changed = true;
2267
+ if (!textures.has(url)) {
2268
+ if (!added) {
2269
+ textures = new Map(textures);
2270
+ added = true;
2271
+ }
2272
+ textures.set(url, texture);
3246
2273
  }
2274
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3247
2275
  }
3248
- return changed ? { textures: newMap } : state;
2276
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3249
2277
  });
3250
- }, [cache, input, mappedTextures, store, cachedResult]);
2278
+ return () => store.setState((state) => {
2279
+ const refs = new Map(state._textureRefs);
2280
+ for (const [url] of urlTextureMap) {
2281
+ const next = (refs.get(url) ?? 0) - 1;
2282
+ if (next <= 0) refs.delete(url);
2283
+ else refs.set(url, next);
2284
+ }
2285
+ return { _textureRefs: refs };
2286
+ });
2287
+ }, [cache, input, mappedTextures, store]);
3251
2288
  return mappedTextures;
3252
2289
  }
3253
2290
  useTexture.preload = (url) => useLoader.preload(webgpu.TextureLoader, url);
@@ -3263,96 +2300,63 @@ const Texture = ({
3263
2300
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3264
2301
  };
3265
2302
 
3266
- function getTextureValue(entry) {
3267
- if (entry instanceof webgpu.Texture) return entry;
3268
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof webgpu.Texture) {
3269
- return entry.value;
3270
- }
3271
- return null;
3272
- }
3273
- function useTextures() {
2303
+ function useTextures(selector) {
3274
2304
  const store = useStore();
3275
- return React.useMemo(() => {
3276
- const set = store.setState;
2305
+ const registry = React.useMemo(() => {
3277
2306
  const getState = store.getState;
3278
- const add = (key, value) => {
3279
- set((state) => {
3280
- const newMap = new Map(state.textures);
3281
- newMap.set(key, value);
3282
- return { textures: newMap };
3283
- });
3284
- };
3285
- const addMultiple = (items) => {
3286
- set((state) => {
3287
- const newMap = new Map(state.textures);
3288
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3289
- for (const [key, value] of entries) {
3290
- newMap.set(key, value);
3291
- }
3292
- return { textures: newMap };
3293
- });
3294
- };
3295
- const remove = (key) => {
3296
- set((state) => {
3297
- const newMap = new Map(state.textures);
3298
- newMap.delete(key);
3299
- return { textures: newMap };
3300
- });
3301
- };
3302
- const removeMultiple = (keys) => {
3303
- set((state) => {
3304
- const newMap = new Map(state.textures);
3305
- for (const key of keys) newMap.delete(key);
3306
- return { textures: newMap };
3307
- });
3308
- };
3309
- const dispose = (key) => {
3310
- const entry = getState().textures.get(key);
3311
- if (entry) {
3312
- const tex = getTextureValue(entry);
3313
- tex?.dispose();
3314
- }
3315
- remove(key);
3316
- };
3317
- const disposeMultiple = (keys) => {
3318
- const textures = getState().textures;
3319
- for (const key of keys) {
3320
- const entry = textures.get(key);
3321
- if (entry) {
3322
- const tex = getTextureValue(entry);
3323
- tex?.dispose();
3324
- }
3325
- }
3326
- removeMultiple(keys);
3327
- };
3328
- const disposeAll = () => {
3329
- const textures = getState().textures;
3330
- for (const entry of textures.values()) {
3331
- const tex = getTextureValue(entry);
3332
- tex?.dispose();
3333
- }
3334
- set({ textures: /* @__PURE__ */ new Map() });
3335
- };
2307
+ const setState = store.setState;
2308
+ const getOne = (key) => getState().textures.get(key);
3336
2309
  return {
3337
- // Getter for the textures Map (reactive via getState)
3338
- get textures() {
2310
+ get all() {
3339
2311
  return getState().textures;
3340
2312
  },
3341
- // Read
3342
- get: (key) => getState().textures.get(key),
2313
+ get(input) {
2314
+ if (typeof input === "string") return getOne(input);
2315
+ if (Array.isArray(input)) return input.map(getOne);
2316
+ const out = {};
2317
+ for (const name in input) out[name] = getOne(input[name]);
2318
+ return out;
2319
+ },
3343
2320
  has: (key) => getState().textures.has(key),
3344
- // Write
3345
- add,
3346
- addMultiple,
3347
- // Remove (cache only)
3348
- remove,
3349
- removeMultiple,
3350
- // Dispose (GPU + cache)
3351
- dispose,
3352
- disposeMultiple,
3353
- disposeAll
2321
+ add(keyOrRecord, texture) {
2322
+ setState((state) => {
2323
+ const textures = new Map(state.textures);
2324
+ if (typeof keyOrRecord === "string") {
2325
+ textures.set(keyOrRecord, texture);
2326
+ } else {
2327
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2328
+ }
2329
+ return { textures };
2330
+ });
2331
+ },
2332
+ dispose(key, options) {
2333
+ const state = getState();
2334
+ const refs = state._textureRefs.get(key) ?? 0;
2335
+ if (refs > 0 && !options?.force) {
2336
+ console.warn(
2337
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2338
+ );
2339
+ return false;
2340
+ }
2341
+ state.textures.get(key)?.dispose();
2342
+ setState((s) => {
2343
+ const textures = new Map(s.textures);
2344
+ textures.delete(key);
2345
+ const nextRefs = new Map(s._textureRefs);
2346
+ nextRefs.delete(key);
2347
+ return { textures, _textureRefs: nextRefs };
2348
+ });
2349
+ return true;
2350
+ },
2351
+ disposeAll() {
2352
+ for (const texture of getState().textures.values()) texture.dispose();
2353
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2354
+ }
3354
2355
  };
3355
2356
  }, [store]);
2357
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2358
+ const selected = useThree(subscribe);
2359
+ return selector ? selected : registry;
3356
2360
  }
3357
2361
 
3358
2362
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3409,7 +2413,7 @@ function addEffect(callback) {
3409
2413
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3410
2414
  });
3411
2415
  const id = `legacy_effect_${effectId++}`;
3412
- return getScheduler().registerGlobal("before", id, callback);
2416
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3413
2417
  }
3414
2418
  function addAfterEffect(callback) {
3415
2419
  notifyDepreciated({
@@ -3418,7 +2422,7 @@ function addAfterEffect(callback) {
3418
2422
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3419
2423
  });
3420
2424
  const id = `legacy_afterEffect_${effectId++}`;
3421
- return getScheduler().registerGlobal("after", id, callback);
2425
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3422
2426
  }
3423
2427
  function addTail(callback) {
3424
2428
  notifyDepreciated({
@@ -3426,16 +2430,16 @@ function addTail(callback) {
3426
2430
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3427
2431
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3428
2432
  });
3429
- return getScheduler().onIdle(callback);
2433
+ return scheduler.getScheduler().onIdle(callback);
3430
2434
  }
3431
2435
  function invalidate(state, frames = 1, stackFrames = false) {
3432
- getScheduler().invalidate(frames, stackFrames);
2436
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3433
2437
  }
3434
2438
  function advance(timestamp) {
3435
- getScheduler().step(timestamp);
2439
+ scheduler.getScheduler().step(timestamp);
3436
2440
  }
3437
2441
 
3438
- const version = "10.0.0-alpha.2";
2442
+ const version = "10.0.0-alpha.3";
3439
2443
  const packageData = {
3440
2444
  version: version};
3441
2445
 
@@ -14874,6 +13878,7 @@ function swapInstances() {
14874
13878
  }
14875
13879
  }
14876
13880
  if (instance.isHidden) unhideInstance(instance);
13881
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14877
13882
  if (instance.object.__r3f) delete instance.object.__r3f;
14878
13883
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14879
13884
  }
@@ -14886,6 +13891,8 @@ function swapInstances() {
14886
13891
  instance.object.__r3f = instance;
14887
13892
  setFiberRef(fiber, instance.object);
14888
13893
  delete instance.appliedOnce;
13894
+ instance.eventCount = 0;
13895
+ instance.handlers = {};
14889
13896
  applyProps(instance.object, instance.props);
14890
13897
  if (instance.props.attach) {
14891
13898
  attach(parent, instance);
@@ -15101,11 +14108,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15101
14108
  cloneMutableTextInstance(textInstance) {
15102
14109
  return textInstance;
15103
14110
  },
14111
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14112
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14113
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14114
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14115
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14116
+ // Guarded by a test asserting a full render + unmount never reaches them.
15104
14117
  cloneRootViewTransitionContainer(_rootContainer) {
15105
- throw new Error("Not implemented.");
15106
14118
  },
15107
14119
  removeRootViewTransitionClone(_rootContainer, _clone) {
15108
- throw new Error("Not implemented.");
15109
14120
  },
15110
14121
  // https://github.com/facebook/react/pull/32465
15111
14122
  createFragmentInstance: (_fiber) => null,
@@ -15190,6 +14201,7 @@ function createRoot(canvas) {
15190
14201
  const lastConfiguredProps = {};
15191
14202
  let configured = false;
15192
14203
  let pending = null;
14204
+ let rendererSetup = null;
15193
14205
  return {
15194
14206
  async configure(props = {}) {
15195
14207
  let resolve;
@@ -15205,7 +14217,6 @@ function createRoot(canvas) {
15205
14217
  events,
15206
14218
  onCreated: onCreatedCallback,
15207
14219
  shadows = false,
15208
- textureColorSpace = webgpu.SRGBColorSpace,
15209
14220
  orthographic = false,
15210
14221
  frameloop = "always",
15211
14222
  dpr = [1, 2],
@@ -15220,7 +14231,8 @@ function createRoot(canvas) {
15220
14231
  _sizeProps,
15221
14232
  forceEven
15222
14233
  } = props;
15223
- const state = store.getState();
14234
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
14235
+ let state = store.getState();
15224
14236
  const defaultGLProps = {
15225
14237
  canvas,
15226
14238
  powerPreference: "high-performance",
@@ -15248,56 +14260,68 @@ function createRoot(canvas) {
15248
14260
  "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
15249
14261
  );
15250
14262
  }
15251
- if (wantsGL && !state.internal.actualRenderer) {
15252
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
15253
- state.internal.actualRenderer = renderer;
15254
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
15255
- } else if (!wantsGL && primaryCanvas && !state.internal.actualRenderer) {
15256
- const primary = await waitForPrimary(primaryCanvas);
15257
- renderer = primary.renderer;
15258
- state.internal.actualRenderer = renderer;
15259
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15260
- primary.store.setState((prev) => ({
15261
- internal: { ...prev.internal, isMultiCanvas: true }
15262
- }));
15263
- state.set((prev) => ({
15264
- webGPUSupported: primary.store.getState().webGPUSupported,
15265
- renderer,
15266
- primaryStore: primary.store,
15267
- internal: {
15268
- ...prev.internal,
15269
- canvasTarget,
15270
- isMultiCanvas: true,
15271
- isSecondary: true,
15272
- targetId: primaryCanvas
15273
- }
15274
- }));
15275
- } else if (!wantsGL && !state.internal.actualRenderer) {
15276
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
15277
- if (!renderer.hasInitialized?.()) {
15278
- const size2 = computeInitialSize(canvas, propsSize);
15279
- if (size2.width > 0 && size2.height > 0) {
15280
- const pixelRatio = calculateDpr(dpr);
15281
- canvas.width = size2.width * pixelRatio;
15282
- canvas.height = size2.height * pixelRatio;
15283
- }
15284
- await renderer.init();
15285
- }
15286
- const backend = renderer.backend;
15287
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15288
- state.internal.actualRenderer = renderer;
15289
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15290
- if (canvasId && !state.internal.isSecondary) {
15291
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15292
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15293
- state.set((prev) => ({
15294
- internal: {
15295
- ...prev.internal,
15296
- canvasTarget,
15297
- unregisterPrimary
14263
+ if (!state.internal.actualRenderer) {
14264
+ if (!rendererSetup) {
14265
+ rendererSetup = (async () => {
14266
+ if (wantsGL) {
14267
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14268
+ state.internal.actualRenderer = renderer;
14269
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14270
+ } else if (!wantsGL && primaryCanvas) {
14271
+ const primary = await waitForPrimary(primaryCanvas);
14272
+ renderer = primary.renderer;
14273
+ state.internal.actualRenderer = renderer;
14274
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14275
+ primary.store.setState((prev) => ({
14276
+ internal: { ...prev.internal, isMultiCanvas: true }
14277
+ }));
14278
+ state.set((prev) => ({
14279
+ webGPUSupported: primary.store.getState().webGPUSupported,
14280
+ renderer,
14281
+ primaryStore: primary.store,
14282
+ internal: {
14283
+ ...prev.internal,
14284
+ canvasTarget,
14285
+ isMultiCanvas: true,
14286
+ isSecondary: true,
14287
+ targetId: primaryCanvas
14288
+ }
14289
+ }));
14290
+ } else if (!wantsGL) {
14291
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14292
+ if (!renderer.hasInitialized?.()) {
14293
+ const size2 = computeInitialSize(canvas, propsSize);
14294
+ if (size2.width > 0 && size2.height > 0) {
14295
+ const pixelRatio = calculateDpr(dpr);
14296
+ canvas.width = size2.width * pixelRatio;
14297
+ canvas.height = size2.height * pixelRatio;
14298
+ }
14299
+ await renderer.init();
14300
+ }
14301
+ const backend = renderer.backend;
14302
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14303
+ state.internal.actualRenderer = renderer;
14304
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14305
+ if (canvasId && !state.internal.isSecondary) {
14306
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14307
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14308
+ state.set((prev) => ({
14309
+ internal: {
14310
+ ...prev.internal,
14311
+ canvasTarget,
14312
+ unregisterPrimary
14313
+ }
14314
+ }));
14315
+ }
15298
14316
  }
15299
- }));
14317
+ })().catch((err) => {
14318
+ rendererSetup = null;
14319
+ throw err;
14320
+ });
15300
14321
  }
14322
+ await rendererSetup;
14323
+ state = store.getState();
14324
+ renderer = state.internal.actualRenderer;
15301
14325
  }
15302
14326
  let raycaster = state.raycaster;
15303
14327
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -15390,7 +14414,7 @@ function createRoot(canvas) {
15390
14414
  lastConfiguredProps.performance = performance;
15391
14415
  }
15392
14416
  if (!state.xr) {
15393
- const handleXRFrame = (timestamp, frame) => {
14417
+ const handleXRFrame = (timestamp, _frame) => {
15394
14418
  const state2 = store.getState();
15395
14419
  if (state2.frameloop === "never") return;
15396
14420
  advance(timestamp);
@@ -15426,15 +14450,22 @@ function createRoot(canvas) {
15426
14450
  const oldType = renderer.shadowMap.type;
15427
14451
  renderer.shadowMap.enabled = !!shadows;
15428
14452
  if (is.boo(shadows)) {
15429
- renderer.shadowMap.type = webgpu.PCFSoftShadowMap;
14453
+ renderer.shadowMap.type = webgpu.PCFShadowMap;
15430
14454
  } else if (is.str(shadows)) {
14455
+ if (shadows === "soft") {
14456
+ notifyDepreciated({
14457
+ heading: 'shadows="soft" is deprecated',
14458
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14459
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14460
+ });
14461
+ }
15431
14462
  const types = {
15432
14463
  basic: webgpu.BasicShadowMap,
15433
14464
  percentage: webgpu.PCFShadowMap,
15434
- soft: webgpu.PCFSoftShadowMap,
14465
+ soft: webgpu.PCFShadowMap,
15435
14466
  variance: webgpu.VSMShadowMap
15436
14467
  };
15437
- renderer.shadowMap.type = types[shadows] ?? webgpu.PCFSoftShadowMap;
14468
+ renderer.shadowMap.type = types[shadows] ?? webgpu.PCFShadowMap;
15438
14469
  } else if (is.obj(shadows)) {
15439
14470
  Object.assign(renderer.shadowMap, shadows);
15440
14471
  }
@@ -15450,24 +14481,35 @@ function createRoot(canvas) {
15450
14481
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15451
14482
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15452
14483
  }
14484
+ const r3fProps = ["textureColorSpace"];
14485
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14486
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15453
14487
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15454
- applyProps(renderer, glConfig);
14488
+ const glProps = {};
14489
+ for (const key in glConfig) {
14490
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14491
+ }
14492
+ applyProps(renderer, glProps);
15455
14493
  }
15456
14494
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15457
14495
  const currentRenderer = state.renderer;
15458
14496
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15459
- applyProps(currentRenderer, rendererConfig);
14497
+ const rendererProps = {};
14498
+ for (const key in rendererConfig) {
14499
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14500
+ }
14501
+ applyProps(currentRenderer, rendererProps);
15460
14502
  }
15461
14503
  }
15462
- const scheduler = getScheduler();
14504
+ const scheduler$1 = scheduler.getScheduler();
15463
14505
  const rootId = state.internal.rootId;
15464
14506
  if (!rootId) {
15465
- const newRootId = canvasId || scheduler.generateRootId();
15466
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14507
+ const newRootId = canvasId || scheduler$1.generateRootId();
14508
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15467
14509
  getState: () => store.getState(),
15468
14510
  onError: (err) => store.getState().setError(err)
15469
14511
  });
15470
- const unregisterCanvasTarget = scheduler.register(
14512
+ const unregisterCanvasTarget = scheduler$1.register(
15471
14513
  () => {
15472
14514
  const state2 = store.getState();
15473
14515
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15482,7 +14524,7 @@ function createRoot(canvas) {
15482
14524
  system: true
15483
14525
  }
15484
14526
  );
15485
- const unregisterEventsFlush = scheduler.register(
14527
+ const unregisterEventsFlush = scheduler$1.register(
15486
14528
  () => {
15487
14529
  const state2 = store.getState();
15488
14530
  state2.events.flush?.();
@@ -15494,7 +14536,7 @@ function createRoot(canvas) {
15494
14536
  system: true
15495
14537
  }
15496
14538
  );
15497
- const unregisterFrustum = scheduler.register(
14539
+ const unregisterFrustum = scheduler$1.register(
15498
14540
  () => {
15499
14541
  const state2 = store.getState();
15500
14542
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15504,11 +14546,11 @@ function createRoot(canvas) {
15504
14546
  {
15505
14547
  id: `${newRootId}_frustum`,
15506
14548
  rootId: newRootId,
15507
- phase: "preRender",
14549
+ before: "render",
15508
14550
  system: true
15509
14551
  }
15510
14552
  );
15511
- const unregisterVisibility = scheduler.register(
14553
+ const unregisterVisibility = scheduler$1.register(
15512
14554
  () => {
15513
14555
  const state2 = store.getState();
15514
14556
  checkVisibility(state2);
@@ -15516,16 +14558,16 @@ function createRoot(canvas) {
15516
14558
  {
15517
14559
  id: `${newRootId}_visibility`,
15518
14560
  rootId: newRootId,
15519
- phase: "preRender",
14561
+ before: "render",
15520
14562
  system: true,
15521
14563
  after: `${newRootId}_frustum`
15522
14564
  }
15523
14565
  );
15524
- const unregisterRender = scheduler.register(
14566
+ const unregisterRender = scheduler$1.register(
15525
14567
  () => {
15526
14568
  const state2 = store.getState();
15527
14569
  const renderer2 = state2.internal.actualRenderer;
15528
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14570
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15529
14571
  if (userHandlesRender || state2.internal.priority) return;
15530
14572
  try {
15531
14573
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15558,11 +14600,11 @@ function createRoot(canvas) {
15558
14600
  unregisterVisibility();
15559
14601
  unregisterRender();
15560
14602
  },
15561
- scheduler
14603
+ scheduler: scheduler$1
15562
14604
  }
15563
14605
  }));
15564
14606
  }
15565
- scheduler.frameloop = frameloop;
14607
+ scheduler$1.frameloop = frameloop;
15566
14608
  onCreated = onCreatedCallback;
15567
14609
  configured = true;
15568
14610
  resolve();
@@ -15629,7 +14671,8 @@ function unmountComponentAtNode(canvas, callback) {
15629
14671
  dispose(state.scene);
15630
14672
  _roots.delete(canvas);
15631
14673
  if (callback) callback(canvas);
15632
- } catch {
14674
+ } catch (error) {
14675
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15633
14676
  }
15634
14677
  }, 500);
15635
14678
  }
@@ -15692,6 +14735,7 @@ function PortalInner({ state = {}, children, container }) {
15692
14735
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
15693
14736
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15694
14737
  }
14738
+ const set = injectState.set;
15695
14739
  return {
15696
14740
  // The intersect consists of the previous root state
15697
14741
  ...rootState,
@@ -15710,7 +14754,7 @@ function PortalInner({ state = {}, children, container }) {
15710
14754
  size: resolvedSize,
15711
14755
  viewport: { ...rootState.viewport, ...viewport },
15712
14756
  // Layers are allowed to override events
15713
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14757
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15714
14758
  // Container for child attachment - the portalScene (injected or container itself)
15715
14759
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15716
14760
  };
@@ -15739,6 +14783,81 @@ function flushSync(fn) {
15739
14783
  return reconciler.flushSyncFromReconciler(fn);
15740
14784
  }
15741
14785
 
14786
+ function parseBackground(background) {
14787
+ if (!background) return null;
14788
+ if (typeof background === "object" && !background.isColor) {
14789
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14790
+ return {
14791
+ ...rest,
14792
+ preset,
14793
+ files: envMap || files,
14794
+ backgroundFiles: backgroundMap,
14795
+ background: true
14796
+ };
14797
+ }
14798
+ if (typeof background === "number") {
14799
+ return { color: background, background: true };
14800
+ }
14801
+ if (typeof background === "string") {
14802
+ if (background in presetsObj) {
14803
+ return { preset: background, background: true };
14804
+ }
14805
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14806
+ return { files: background, background: true };
14807
+ }
14808
+ return { color: background, background: true };
14809
+ }
14810
+ if (background.isColor) {
14811
+ return { color: background, background: true };
14812
+ }
14813
+ return null;
14814
+ }
14815
+
14816
+ function parseRendererConfig(rendererProp) {
14817
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14818
+ if (isRendererConfig) {
14819
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14820
+ return {
14821
+ primaryCanvas: pc,
14822
+ scheduler: sc,
14823
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14824
+ };
14825
+ }
14826
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14827
+ }
14828
+
14829
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14830
+ const registries = /* @__PURE__ */ new WeakMap();
14831
+ function getKindRegistry(store, kind) {
14832
+ let registry = registries.get(store);
14833
+ if (!registry) {
14834
+ registry = {
14835
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14836
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14837
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14838
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14839
+ };
14840
+ registries.set(store, registry);
14841
+ }
14842
+ return registry[kind];
14843
+ }
14844
+ function invalidateResource(store, kind, scopeKey) {
14845
+ const registry = getKindRegistry(store, kind);
14846
+ {
14847
+ registry.valid.clear();
14848
+ registry.staged.clear();
14849
+ }
14850
+ }
14851
+ function invalidateAllResources(store) {
14852
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14853
+ }
14854
+
14855
+ function clearHmrCaches(store) {
14856
+ const primary = store.getState().primaryStore ?? store;
14857
+ invalidateAllResources(primary);
14858
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14859
+ }
14860
+
15742
14861
  function CanvasImpl({
15743
14862
  ref,
15744
14863
  children,
@@ -15759,6 +14878,8 @@ function CanvasImpl({
15759
14878
  raycaster,
15760
14879
  camera,
15761
14880
  scene,
14881
+ autoUpdateFrustum,
14882
+ occlusion,
15762
14883
  onPointerMissed,
15763
14884
  onDragOverMissed,
15764
14885
  onDropMissed,
@@ -15770,39 +14891,10 @@ function CanvasImpl({
15770
14891
  forceEven,
15771
14892
  ...props
15772
14893
  }) {
15773
- 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 };
15774
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14894
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15775
14895
  React__namespace.useMemo(() => extend(THREE), []);
15776
14896
  const Bridge = useBridge();
15777
- const backgroundProps = React__namespace.useMemo(() => {
15778
- if (!background) return null;
15779
- if (typeof background === "object" && !background.isColor) {
15780
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15781
- return {
15782
- ...rest,
15783
- preset,
15784
- files: envMap || files,
15785
- backgroundFiles: backgroundMap,
15786
- background: true
15787
- };
15788
- }
15789
- if (typeof background === "number") {
15790
- return { color: background, background: true };
15791
- }
15792
- if (typeof background === "string") {
15793
- if (background in presetsObj) {
15794
- return { preset: background, background: true };
15795
- }
15796
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15797
- return { files: background, background: true };
15798
- }
15799
- return { color: background, background: true };
15800
- }
15801
- if (background.isColor) {
15802
- return { color: background, background: true };
15803
- }
15804
- return null;
15805
- }, [background]);
14897
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15806
14898
  const hasInitialSizeRef = React__namespace.useRef(false);
15807
14899
  const measureConfig = React__namespace.useMemo(() => {
15808
14900
  if (!hasInitialSizeRef.current) {
@@ -15844,6 +14936,7 @@ function CanvasImpl({
15844
14936
  const handleDropMissed = useMutableCallback(onDropMissed);
15845
14937
  const [block, setBlock] = React__namespace.useState(false);
15846
14938
  const [error, setError] = React__namespace.useState(false);
14939
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15847
14940
  if (block) throw block;
15848
14941
  if (error) throw error;
15849
14942
  const root = React__namespace.useRef(null);
@@ -15851,6 +14944,7 @@ function CanvasImpl({
15851
14944
  const unsubscribeErrorRef = React__namespace.useRef(null);
15852
14945
  useIsomorphicLayoutEffect(() => {
15853
14946
  effectActiveRef.current = true;
14947
+ if (fallbackVisible) return;
15854
14948
  const canvas = canvasRef.current;
15855
14949
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15856
14950
  if (!root.current) {
@@ -15871,7 +14965,7 @@ function CanvasImpl({
15871
14965
  }
15872
14966
  async function run() {
15873
14967
  if (!effectActiveRef.current || !root.current) return;
15874
- await root.current.configure({
14968
+ const configured = await root.current.configure({
15875
14969
  id,
15876
14970
  primaryCanvas,
15877
14971
  scheduler,
@@ -15886,6 +14980,8 @@ function CanvasImpl({
15886
14980
  performance,
15887
14981
  raycaster,
15888
14982
  camera,
14983
+ autoUpdateFrustum,
14984
+ occlusion,
15889
14985
  size: effectiveSize,
15890
14986
  // Store size props for reset functionality
15891
14987
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15910,8 +15006,20 @@ function CanvasImpl({
15910
15006
  }
15911
15007
  onCreated?.(state);
15912
15008
  }
15913
- });
15914
- if (!effectActiveRef.current || !root.current) return;
15009
+ }).then(
15010
+ () => true,
15011
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15012
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15013
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15014
+ (setupError) => {
15015
+ if (effectActiveRef.current) {
15016
+ if (fallback != null) setFallbackVisible(true);
15017
+ else setError(setupError);
15018
+ }
15019
+ return false;
15020
+ }
15021
+ );
15022
+ if (!configured || !effectActiveRef.current || !root.current) return;
15915
15023
  root.current.render(
15916
15024
  /* @__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: [
15917
15025
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15945,14 +15053,7 @@ function CanvasImpl({
15945
15053
  const handleHMR = () => {
15946
15054
  queueMicrotask(() => {
15947
15055
  const rootEntry = _roots.get(canvas);
15948
- if (rootEntry?.store) {
15949
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15950
- rootEntry.store.setState((state) => ({
15951
- nodes: {},
15952
- uniforms: {},
15953
- _hmrVersion: state._hmrVersion + 1
15954
- }));
15955
- }
15056
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15956
15057
  });
15957
15058
  };
15958
15059
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
@@ -15981,7 +15082,20 @@ function CanvasImpl({
15981
15082
  ...style
15982
15083
  },
15983
15084
  ...props,
15984
- 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 }) })
15085
+ children: fallbackVisible ? (
15086
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15087
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15088
+ fallback
15089
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15090
+ "canvas",
15091
+ {
15092
+ ref: canvasRef,
15093
+ id,
15094
+ className: "r3f-canvas",
15095
+ style: { display: "block", width: "100%", height: "100%" },
15096
+ children: fallback
15097
+ }
15098
+ ) })
15985
15099
  }
15986
15100
  );
15987
15101
  }
@@ -15991,6 +15105,8 @@ function Canvas(props) {
15991
15105
 
15992
15106
  extend(THREE);
15993
15107
 
15108
+ exports.Scheduler = scheduler.Scheduler;
15109
+ exports.getScheduler = scheduler.getScheduler;
15994
15110
  exports.Block = Block;
15995
15111
  exports.Canvas = Canvas;
15996
15112
  exports.Environment = Environment;
@@ -16006,7 +15122,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
16006
15122
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
16007
15123
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
16008
15124
  exports.RESERVED_PROPS = RESERVED_PROPS;
16009
- exports.Scheduler = Scheduler;
16010
15125
  exports.Texture = Texture;
16011
15126
  exports._roots = _roots;
16012
15127
  exports.act = act;
@@ -16036,7 +15151,6 @@ exports.getInstanceProps = getInstanceProps;
16036
15151
  exports.getPrimary = getPrimary;
16037
15152
  exports.getPrimaryIds = getPrimaryIds;
16038
15153
  exports.getRootState = getRootState;
16039
- exports.getScheduler = getScheduler;
16040
15154
  exports.getUuidPrefix = getUuidPrefix;
16041
15155
  exports.hasConstructor = hasConstructor;
16042
15156
  exports.hasPrimary = hasPrimary;