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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as webgpu from 'three/webgpu';
2
- import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
3
- import { WebGLRenderTarget, WebGLRenderer } from 'three';
2
+ import { CubeRenderTarget, RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
3
+ import { WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer } from 'three';
4
4
  import { Inspector } from 'three/addons/inspector/Inspector.js';
5
5
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
6
6
  import * as React from 'react';
@@ -15,6 +15,8 @@ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
15
15
  import { GainMapLoader } from '@monogrid/gainmap-js';
16
16
  import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
17
17
  import { createWithEqualityFn } from 'zustand/traditional';
18
+ import { getScheduler } from '@pmndrs/scheduler';
19
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
18
20
  import { suspend, preload, clear } from 'suspend-react';
19
21
 
20
22
  function _mergeNamespaces(n, m) {
@@ -34,10 +36,13 @@ const R3F_BUILD_WEBGPU = true;
34
36
 
35
37
  const THREE = /*#__PURE__*/_mergeNamespaces({
36
38
  __proto__: null,
39
+ CubeRenderTarget: CubeRenderTarget,
40
+ CubeRenderTargetCompat: CubeRenderTarget,
37
41
  Inspector: Inspector,
38
42
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
39
43
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
40
44
  RenderTargetCompat: RenderTarget,
45
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
41
46
  WebGLRenderTarget: WebGLRenderTarget,
42
47
  WebGLRenderer: WebGLRenderer
43
48
  }, [webgpu]);
@@ -311,15 +316,16 @@ function EnvironmentPortal({
311
316
  preset = void 0,
312
317
  extensions
313
318
  }) {
314
- const gl = useThree$1((state) => state.gl);
319
+ const renderer = useThree$1((state) => state.renderer);
320
+ const isLegacy = useThree$1((state) => state.isLegacy);
315
321
  const defaultScene = useThree$1((state) => state.scene);
316
322
  const camera = React.useRef(null);
317
323
  const [virtualScene] = React.useState(() => new Scene());
318
324
  const fbo = React.useMemo(() => {
319
- const fbo2 = new WebGLCubeRenderTarget(resolution);
325
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
320
326
  fbo2.texture.type = HalfFloatType;
321
327
  return fbo2;
322
- }, [resolution]);
328
+ }, [resolution, isLegacy]);
323
329
  React.useEffect(() => {
324
330
  return () => {
325
331
  fbo.dispose();
@@ -327,10 +333,10 @@ function EnvironmentPortal({
327
333
  }, [fbo]);
328
334
  React.useLayoutEffect(() => {
329
335
  if (frames === 1) {
330
- const autoClear = gl.autoClear;
331
- gl.autoClear = true;
332
- camera.current.update(gl, virtualScene);
333
- gl.autoClear = autoClear;
336
+ const autoClear = renderer.autoClear;
337
+ renderer.autoClear = true;
338
+ camera.current.update(renderer, virtualScene);
339
+ renderer.autoClear = autoClear;
334
340
  }
335
341
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
336
342
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -347,7 +353,7 @@ function EnvironmentPortal({
347
353
  defaultScene,
348
354
  background,
349
355
  frames,
350
- gl,
356
+ renderer,
351
357
  blur,
352
358
  backgroundBlurriness,
353
359
  backgroundIntensity,
@@ -358,10 +364,10 @@ function EnvironmentPortal({
358
364
  let count = 1;
359
365
  useFrame$1(() => {
360
366
  if (frames === Infinity || count < frames) {
361
- const autoClear = gl.autoClear;
362
- gl.autoClear = true;
363
- camera.current.update(gl, virtualScene);
364
- gl.autoClear = autoClear;
367
+ const autoClear = renderer.autoClear;
368
+ renderer.autoClear = true;
369
+ camera.current.update(renderer, virtualScene);
370
+ renderer.autoClear = autoClear;
365
371
  count++;
366
372
  }
367
373
  });
@@ -425,9 +431,9 @@ function Environment(props) {
425
431
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
426
432
  }
427
433
 
428
- var __defProp$2 = Object.defineProperty;
429
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
430
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
434
+ var __defProp = Object.defineProperty;
435
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
436
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
431
437
  const act = React["act"];
432
438
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
433
439
  function useMutableCallback(fn) {
@@ -459,7 +465,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
459
465
  return _a = class extends React.Component {
460
466
  constructor() {
461
467
  super(...arguments);
462
- __publicField$2(this, "state", { error: false });
468
+ __publicField(this, "state", { error: false });
463
469
  }
464
470
  componentDidCatch(err) {
465
471
  this.props.set(err);
@@ -467,7 +473,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
467
473
  render() {
468
474
  return this.state.error ? null : this.props.children;
469
475
  }
470
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
476
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
471
477
  })();
472
478
 
473
479
  const is = {
@@ -604,8 +610,7 @@ function prepare(target, root, type, props) {
604
610
  object,
605
611
  eventCount: 0,
606
612
  handlers: {},
607
- isHidden: false,
608
- deferredRefs: []
613
+ isHidden: false
609
614
  };
610
615
  if (object) object.__r3f = instance;
611
616
  }
@@ -762,6 +767,17 @@ function unregisterVisibility(store, object) {
762
767
  internal.visibilityRegistry.delete(object.uuid);
763
768
  internal.occlusionCache.delete(object);
764
769
  }
770
+ function updateVisibilityHandlers(store, object, handlers) {
771
+ const { internal } = store.getState();
772
+ const entry = internal.visibilityRegistry.get(object.uuid);
773
+ if (!entry) return false;
774
+ entry.handlers = handlers;
775
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
776
+ object.occlusionTest = true;
777
+ enableOcclusion(store);
778
+ }
779
+ return true;
780
+ }
765
781
  function checkVisibility(state) {
766
782
  const { internal, camera } = state;
767
783
  const registry = internal.visibilityRegistry;
@@ -949,10 +965,7 @@ function applyProps(object, props) {
949
965
  continue;
950
966
  }
951
967
  if (value === void 0) continue;
952
- if (isFromRef(value)) {
953
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
954
- continue;
955
- }
968
+ if (isFromRef(value)) continue;
956
969
  if (isOnce(value)) {
957
970
  if (instance?.appliedOnce?.has(prop)) continue;
958
971
  if (instance) {
@@ -988,6 +1001,19 @@ function applyProps(object, props) {
988
1001
  } else if (isVectorLike(target) && is.num(value)) {
989
1002
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
990
1003
  else target.set(value);
1004
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1005
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1006
+ const uniforms = root.uniforms;
1007
+ const nextUniforms = value;
1008
+ for (const name in nextUniforms) {
1009
+ const uniform = nextUniforms[name];
1010
+ const targetUniform = uniforms[name];
1011
+ if (targetUniform) Object.assign(targetUniform, uniform);
1012
+ else {
1013
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1014
+ uniforms[name] = nextUniform;
1015
+ }
1016
+ }
991
1017
  } else {
992
1018
  root[key] = value;
993
1019
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1006,6 +1032,9 @@ function applyProps(object, props) {
1006
1032
  if (instance.eventCount && object2.raycast !== null) {
1007
1033
  rootState.internal.interaction.push(object2);
1008
1034
  }
1035
+ }
1036
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1037
+ const object2 = instance.object;
1009
1038
  const root = findInitialRoot(instance);
1010
1039
  const visibilityHandlers = {
1011
1040
  onFramed: instance.handlers.onFramed,
@@ -1013,7 +1042,9 @@ function applyProps(object, props) {
1013
1042
  onVisible: instance.handlers.onVisible
1014
1043
  };
1015
1044
  if (hasVisibilityHandlers(visibilityHandlers)) {
1016
- registerVisibility(root, object2, visibilityHandlers);
1045
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1046
+ registerVisibility(root, object2, visibilityHandlers);
1047
+ }
1017
1048
  } else {
1018
1049
  unregisterVisibility(root, object2);
1019
1050
  }
@@ -1541,6 +1572,7 @@ function createPointerEvents(store) {
1541
1572
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1542
1573
  }
1543
1574
  },
1575
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1544
1576
  registerPointer: (config) => {
1545
1577
  const pointerId = nextXRPointerId++;
1546
1578
  xrPointers.set(pointerId, config);
@@ -1627,1036 +1659,11 @@ function notifyAlpha({ message, link }) {
1627
1659
  }
1628
1660
  }
1629
1661
 
1630
- var __defProp$1 = Object.defineProperty;
1631
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1632
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1633
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1634
- class PhaseGraph {
1635
- constructor() {
1636
- /** Ordered list of phase nodes */
1637
- __publicField$1(this, "phases", []);
1638
- /** Quick lookup by name */
1639
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1640
- /** Cached ordered names (invalidated on changes) */
1641
- __publicField$1(this, "orderedNamesCache", null);
1642
- this.initializeDefaultPhases();
1643
- }
1644
- //* Initialization --------------------------------
1645
- initializeDefaultPhases() {
1646
- for (const name of DEFAULT_PHASES) {
1647
- const node = { name, isAutoGenerated: false };
1648
- this.phases.push(node);
1649
- this.phaseMap.set(name, node);
1650
- }
1651
- this.invalidateCache();
1652
- }
1653
- //* Public API --------------------------------
1654
- /**
1655
- * Add a named phase to the graph
1656
- * @param name - Phase name (must be unique)
1657
- * @param options - Position options (before or after another phase)
1658
- */
1659
- addPhase(name, options = {}) {
1660
- if (this.phaseMap.has(name)) {
1661
- console.warn(`[useFrame] Phase "${name}" already exists`);
1662
- return;
1663
- }
1664
- const { before, after } = options;
1665
- const node = { name, isAutoGenerated: false };
1666
- let insertIndex = this.phases.length;
1667
- const targetIndex = this.getPhaseIndex(before ?? after);
1668
- if (targetIndex !== -1) {
1669
- insertIndex = before ? targetIndex : targetIndex + 1;
1670
- } else {
1671
- const constraintType = before ? "before" : "after";
1672
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1673
- }
1674
- this.phases.splice(insertIndex, 0, node);
1675
- this.phaseMap.set(name, node);
1676
- this.invalidateCache();
1677
- }
1678
- /**
1679
- * Get ordered list of phase names
1680
- */
1681
- getOrderedPhases() {
1682
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1683
- return this.orderedNamesCache;
1684
- }
1685
- /**
1686
- * Check if a phase exists
1687
- */
1688
- hasPhase(name) {
1689
- return this.phaseMap.has(name);
1690
- }
1691
- /**
1692
- * Get the index of a phase (-1 if not found)
1693
- */
1694
- getPhaseIndex(name) {
1695
- if (!name) return -1;
1696
- return this.phases.findIndex((p) => p.name === name);
1697
- }
1698
- /**
1699
- * Ensure a phase exists, creating an auto-generated one if needed.
1700
- * Used for resolving before/after constraints.
1701
- *
1702
- * @param name - The phase name to ensure exists
1703
- * @returns The phase name (may be auto-generated like 'before:render')
1704
- */
1705
- ensurePhase(name) {
1706
- if (this.phaseMap.has(name)) return name;
1707
- const node = { name, isAutoGenerated: true };
1708
- this.phases.push(node);
1709
- this.phaseMap.set(name, node);
1710
- this.invalidateCache();
1711
- return name;
1712
- }
1713
- /**
1714
- * Resolve where a job with before/after constraints should go.
1715
- * Creates auto-generated phases if needed.
1716
- *
1717
- * @param before - Phase(s) to run before
1718
- * @param after - Phase(s) to run after
1719
- * @returns The resolved phase name
1720
- */
1721
- resolveConstraintPhase(before, after) {
1722
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1723
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1724
- if (beforeArr.length > 0) {
1725
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1726
- }
1727
- if (afterArr.length > 0) {
1728
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1729
- }
1730
- return "update";
1731
- }
1732
- /**
1733
- * Ensure an auto-generated phase exists relative to a target phase.
1734
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1735
- *
1736
- * @param target - The target phase name to position relative to
1737
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1738
- * @param offset - Insertion offset (0 for before, 1 for after)
1739
- * @returns The auto-generated phase name
1740
- */
1741
- ensureAutoPhase(target, prefix, offset) {
1742
- const autoName = `${prefix}:${target}`;
1743
- if (this.phaseMap.has(autoName)) return autoName;
1744
- const node = { name: autoName, isAutoGenerated: true };
1745
- const targetIndex = this.getPhaseIndex(target);
1746
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1747
- else this.phases.push(node);
1748
- this.phaseMap.set(autoName, node);
1749
- this.invalidateCache();
1750
- return autoName;
1751
- }
1752
- // Internal --------------------------------
1753
- invalidateCache() {
1754
- this.orderedNamesCache = null;
1755
- }
1756
- }
1757
-
1758
- function rebuildSortedJobs(jobs, phaseGraph) {
1759
- const orderedPhases = phaseGraph.getOrderedPhases();
1760
- const buckets = /* @__PURE__ */ new Map();
1761
- for (const phase of orderedPhases) {
1762
- buckets.set(phase, []);
1763
- }
1764
- for (const job of jobs.values()) {
1765
- if (!job.enabled) continue;
1766
- let bucket = buckets.get(job.phase);
1767
- if (!bucket) {
1768
- bucket = [];
1769
- buckets.set(job.phase, bucket);
1770
- }
1771
- bucket.push(job);
1772
- }
1773
- const sortedBuckets = [];
1774
- for (const phase of orderedPhases) {
1775
- const bucket = buckets.get(phase);
1776
- if (!bucket || bucket.length === 0) continue;
1777
- bucket.sort((a, b) => {
1778
- if (a.priority !== b.priority) return b.priority - a.priority;
1779
- return a.index - b.index;
1780
- });
1781
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1782
- }
1783
- for (const [phase, bucket] of buckets) {
1784
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1785
- bucket.sort((a, b) => {
1786
- if (a.priority !== b.priority) return b.priority - a.priority;
1787
- return a.index - b.index;
1788
- });
1789
- sortedBuckets.push(bucket);
1790
- }
1791
- }
1792
- return sortedBuckets.flat();
1793
- }
1794
- function hasCrossJobConstraints(bucket) {
1795
- const jobIds = new Set(bucket.map((j) => j.id));
1796
- for (const job of bucket) {
1797
- for (const ref of job.before) {
1798
- if (jobIds.has(ref)) return true;
1799
- }
1800
- for (const ref of job.after) {
1801
- if (jobIds.has(ref)) return true;
1802
- }
1803
- }
1804
- return false;
1805
- }
1806
- function topologicalSort(jobs) {
1807
- const n = jobs.length;
1808
- if (n <= 1) return jobs;
1809
- const jobMap = /* @__PURE__ */ new Map();
1810
- const inDegree = /* @__PURE__ */ new Map();
1811
- const adjacency = /* @__PURE__ */ new Map();
1812
- for (const job of jobs) {
1813
- jobMap.set(job.id, job);
1814
- inDegree.set(job.id, 0);
1815
- adjacency.set(job.id, []);
1816
- }
1817
- for (const job of jobs) {
1818
- for (const ref of job.before) {
1819
- if (jobMap.has(ref)) {
1820
- adjacency.get(job.id).push(ref);
1821
- inDegree.set(ref, inDegree.get(ref) + 1);
1822
- }
1823
- }
1824
- for (const ref of job.after) {
1825
- if (jobMap.has(ref)) {
1826
- adjacency.get(ref).push(job.id);
1827
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1828
- }
1829
- }
1830
- }
1831
- const queue = [];
1832
- for (const job of jobs) {
1833
- if (inDegree.get(job.id) === 0) {
1834
- queue.push(job);
1835
- }
1836
- }
1837
- queue.sort((a, b) => {
1838
- if (a.priority !== b.priority) return b.priority - a.priority;
1839
- return a.index - b.index;
1840
- });
1841
- const result = [];
1842
- while (queue.length > 0) {
1843
- const job = queue.shift();
1844
- result.push(job);
1845
- const neighbors = adjacency.get(job.id) || [];
1846
- for (const neighborId of neighbors) {
1847
- const newDegree = inDegree.get(neighborId) - 1;
1848
- inDegree.set(neighborId, newDegree);
1849
- if (newDegree === 0) {
1850
- const neighbor = jobMap.get(neighborId);
1851
- insertSorted(queue, neighbor);
1852
- }
1853
- }
1854
- }
1855
- if (result.length !== n) {
1856
- console.warn("[useFrame] Circular dependency detected in job constraints");
1857
- const resultIds = new Set(result.map((j) => j.id));
1858
- for (const job of jobs) {
1859
- if (!resultIds.has(job.id)) result.push(job);
1860
- }
1861
- }
1862
- return result;
1863
- }
1864
- function insertSorted(arr, job) {
1865
- let i = 0;
1866
- while (i < arr.length) {
1867
- const cmp = arr[i];
1868
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1869
- break;
1870
- }
1871
- i++;
1872
- }
1873
- arr.splice(i, 0, job);
1874
- }
1875
-
1876
- function shouldRun(job, now) {
1877
- if (!job.enabled) return false;
1878
- if (!job.fps) return true;
1879
- const minInterval = 1e3 / job.fps;
1880
- const lastRun = job.lastRun ?? 0;
1881
- const elapsed = now - lastRun;
1882
- if (elapsed < minInterval - 1) return false;
1883
- if (job.drop) {
1884
- job.lastRun = now;
1885
- } else {
1886
- const steps = Math.floor(elapsed / minInterval);
1887
- job.lastRun = lastRun + steps * minInterval;
1888
- if (job.lastRun < now - minInterval) {
1889
- job.lastRun = now;
1890
- }
1891
- }
1892
- return true;
1893
- }
1894
- function resetJobTiming(job) {
1895
- job.lastRun = void 0;
1896
- }
1897
-
1898
- var __defProp = Object.defineProperty;
1899
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1900
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1901
- const hmrData = (() => {
1902
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1903
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1904
- try {
1905
- return (0, eval)("import.meta.hot");
1906
- } catch {
1907
- return void 0;
1908
- }
1909
- })();
1910
- const _Scheduler = class _Scheduler {
1911
- //* Constructor ================================
1912
- constructor() {
1913
- //* Critical State ================================
1914
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1915
- __publicField(this, "phaseGraph");
1916
- __publicField(this, "loopState", {
1917
- running: false,
1918
- rafHandle: null,
1919
- lastTime: null,
1920
- // null = uninitialized, 0+ = valid timestamp
1921
- frameCount: 0,
1922
- elapsedTime: 0,
1923
- createdAt: performance.now()
1924
- });
1925
- __publicField(this, "stoppedTime", 0);
1926
- //* Private State ================================
1927
- __publicField(this, "nextRootIndex", 0);
1928
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1929
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1930
- __publicField(this, "nextGlobalIndex", 0);
1931
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1932
- __publicField(this, "nextJobIndex", 0);
1933
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1934
- __publicField(this, "pendingFrames", 0);
1935
- __publicField(this, "_frameloop", "always");
1936
- //* Independent Mode & Error Handling State ================================
1937
- __publicField(this, "_independent", false);
1938
- __publicField(this, "errorHandler", null);
1939
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1940
- //* Core Loop Execution Methods ================================
1941
- /**
1942
- * Main RAF loop callback.
1943
- * Executes frame, handles demand mode, and schedules next frame.
1944
- * @param {number} timestamp - RAF timestamp in milliseconds
1945
- * @returns {void}
1946
- * @private
1947
- */
1948
- __publicField(this, "loop", (timestamp) => {
1949
- if (!this.loopState.running) return;
1950
- this.executeFrame(timestamp);
1951
- if (this._frameloop === "demand") {
1952
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1953
- if (this.pendingFrames === 0) {
1954
- this.notifyIdle(timestamp);
1955
- return this.stop();
1956
- }
1957
- }
1958
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1959
- });
1960
- this.phaseGraph = new PhaseGraph();
1961
- }
1962
- static get instance() {
1963
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1964
- }
1965
- static set instance(value) {
1966
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1967
- }
1968
- /**
1969
- * Get the global scheduler instance (creates if doesn't exist).
1970
- * Uses HMR data to preserve instance across hot reloads.
1971
- * @returns {Scheduler} The singleton scheduler instance
1972
- */
1973
- static get() {
1974
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1975
- _Scheduler.instance = hmrData.data.scheduler;
1976
- }
1977
- if (!_Scheduler.instance) {
1978
- _Scheduler.instance = new _Scheduler();
1979
- if (hmrData?.data) {
1980
- hmrData.data.scheduler = _Scheduler.instance;
1981
- }
1982
- }
1983
- return _Scheduler.instance;
1984
- }
1985
- /**
1986
- * Reset the singleton instance. Stops the loop and clears all state.
1987
- * Primarily used for testing to ensure clean state between tests.
1988
- * @returns {void}
1989
- */
1990
- static reset() {
1991
- if (_Scheduler.instance) {
1992
- _Scheduler.instance.stop();
1993
- _Scheduler.instance = null;
1994
- }
1995
- if (hmrData?.data) {
1996
- hmrData.data.scheduler = null;
1997
- }
1998
- }
1999
- //* Getters & Setters ================================
2000
- get phases() {
2001
- return this.phaseGraph.getOrderedPhases();
2002
- }
2003
- get frameloop() {
2004
- return this._frameloop;
2005
- }
2006
- set frameloop(mode) {
2007
- if (this._frameloop === mode) return;
2008
- const wasAlways = this._frameloop === "always";
2009
- this._frameloop = mode;
2010
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2011
- else if (mode !== "always" && wasAlways) this.stop();
2012
- }
2013
- get isRunning() {
2014
- return this.loopState.running;
2015
- }
2016
- get isReady() {
2017
- return this.roots.size > 0;
2018
- }
2019
- get independent() {
2020
- return this._independent;
2021
- }
2022
- set independent(value) {
2023
- this._independent = value;
2024
- if (value) this.ensureDefaultRoot();
2025
- }
2026
- //* Root Management Methods ================================
2027
- /**
2028
- * Register a root (Canvas) with the scheduler.
2029
- * The first root to register starts the RAF loop (if frameloop='always').
2030
- * @param {string} id - Unique identifier for this root
2031
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2032
- * @returns {() => void} Unsubscribe function to remove this root
2033
- */
2034
- registerRoot(id, options = {}) {
2035
- if (this.roots.has(id)) {
2036
- console.warn(`[Scheduler] Root "${id}" already registered`);
2037
- return () => this.unregisterRoot(id);
2038
- }
2039
- const entry = {
2040
- id,
2041
- getState: options.getState ?? (() => ({})),
2042
- jobs: /* @__PURE__ */ new Map(),
2043
- sortedJobs: [],
2044
- needsRebuild: false
2045
- };
2046
- if (options.onError) {
2047
- this.errorHandler = options.onError;
2048
- }
2049
- this.roots.set(id, entry);
2050
- if (this.roots.size === 1) {
2051
- this.notifyRootReady();
2052
- if (this._frameloop === "always") this.start();
2053
- }
2054
- return () => this.unregisterRoot(id);
2055
- }
2056
- /**
2057
- * Unregister a root from the scheduler.
2058
- * Cleans up all job state listeners for this root's jobs.
2059
- * The last root to unregister stops the RAF loop.
2060
- * @param {string} id - The root ID to unregister
2061
- * @returns {void}
2062
- */
2063
- unregisterRoot(id) {
2064
- const root = this.roots.get(id);
2065
- if (!root) return;
2066
- for (const jobId of root.jobs.keys()) {
2067
- this.jobStateListeners.delete(jobId);
2068
- }
2069
- this.roots.delete(id);
2070
- if (this.roots.size === 0) {
2071
- this.stop();
2072
- this.errorHandler = null;
2073
- }
2074
- }
2075
- /**
2076
- * Subscribe to be notified when a root becomes available.
2077
- * Fires immediately if a root already exists.
2078
- * @param {() => void} callback - Function called when first root registers
2079
- * @returns {() => void} Unsubscribe function
2080
- */
2081
- onRootReady(callback) {
2082
- if (this.roots.size > 0) {
2083
- callback();
2084
- return () => {
2085
- };
2086
- }
2087
- this.rootReadyCallbacks.add(callback);
2088
- return () => this.rootReadyCallbacks.delete(callback);
2089
- }
2090
- /**
2091
- * Notify all registered root-ready callbacks.
2092
- * Called when the first root registers.
2093
- * @returns {void}
2094
- * @private
2095
- */
2096
- notifyRootReady() {
2097
- for (const cb of this.rootReadyCallbacks) {
2098
- try {
2099
- cb();
2100
- } catch (error) {
2101
- console.error("[Scheduler] Error in root-ready callback:", error);
2102
- }
2103
- }
2104
- this.rootReadyCallbacks.clear();
2105
- }
2106
- /**
2107
- * Ensure a default root exists for independent mode.
2108
- * Creates a minimal root with no state provider.
2109
- * @returns {void}
2110
- * @private
2111
- */
2112
- ensureDefaultRoot() {
2113
- if (!this.roots.has("__default__")) {
2114
- this.registerRoot("__default__");
2115
- }
2116
- }
2117
- /**
2118
- * Trigger error handling for job errors.
2119
- * Uses the bound error handler if available, otherwise logs to console.
2120
- * @param {Error} error - The error to handle
2121
- * @returns {void}
2122
- */
2123
- triggerError(error) {
2124
- if (this.errorHandler) this.errorHandler(error);
2125
- else console.error("[Scheduler]", error);
2126
- }
2127
- //* Phase Management Methods ================================
2128
- /**
2129
- * Add a named phase to the scheduler's execution order.
2130
- * Marks all roots for rebuild to incorporate the new phase.
2131
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2132
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2133
- * @returns {void}
2134
- * @example
2135
- * scheduler.addPhase('physics', { before: 'update' });
2136
- * scheduler.addPhase('postprocess', { after: 'render' });
2137
- */
2138
- addPhase(name, options) {
2139
- this.phaseGraph.addPhase(name, options);
2140
- for (const root of this.roots.values()) {
2141
- root.needsRebuild = true;
2142
- }
2143
- }
2144
- /**
2145
- * Check if a phase exists in the scheduler.
2146
- * @param {string} name - The phase name to check
2147
- * @returns {boolean} True if the phase exists
2148
- */
2149
- hasPhase(name) {
2150
- return this.phaseGraph.hasPhase(name);
2151
- }
2152
- //* Global Job Registration Methods (Deprecated APIs) ================================
2153
- /**
2154
- * Register a global job that runs once per frame (not per-root).
2155
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2156
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2157
- * @param {string} id - Unique identifier for this global job
2158
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2159
- * @returns {() => void} Unsubscribe function to remove this global job
2160
- * @deprecated Use useFrame with phases instead
2161
- */
2162
- registerGlobal(phase, id, callback) {
2163
- const job = { id, callback };
2164
- if (phase === "before") {
2165
- this.globalBeforeJobs.set(id, job);
2166
- } else {
2167
- this.globalAfterJobs.set(id, job);
2168
- }
2169
- return () => {
2170
- if (phase === "before") this.globalBeforeJobs.delete(id);
2171
- else this.globalAfterJobs.delete(id);
2172
- };
2173
- }
2174
- //* Idle Callback Methods (Deprecated API) ================================
2175
- /**
2176
- * Register an idle callback that fires when the loop stops.
2177
- * Used internally by deprecated addTail API.
2178
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2179
- * @returns {() => void} Unsubscribe function to remove this idle callback
2180
- * @deprecated Use demand mode with invalidate() instead
2181
- */
2182
- onIdle(callback) {
2183
- this.idleCallbacks.add(callback);
2184
- return () => this.idleCallbacks.delete(callback);
2185
- }
2186
- /**
2187
- * Notify all registered idle callbacks.
2188
- * Called when the loop stops in demand mode.
2189
- * @param {number} timestamp - The RAF timestamp when idle occurred
2190
- * @returns {void}
2191
- * @private
2192
- */
2193
- notifyIdle(timestamp) {
2194
- for (const cb of this.idleCallbacks) {
2195
- try {
2196
- cb(timestamp);
2197
- } catch (error) {
2198
- console.error("[Scheduler] Error in idle callback:", error);
2199
- }
2200
- }
2201
- }
2202
- //* Job Registration & Management Methods ================================
2203
- /**
2204
- * Register a job (frame callback) with a specific root.
2205
- * This is the core registration method used by useFrame internally.
2206
- * @param {FrameNextCallback} callback - The function to call each frame
2207
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2208
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2209
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2210
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2211
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2212
- * @param {number} [options.fps] - FPS throttle limit
2213
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2214
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2215
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2216
- * @returns {() => void} Unsubscribe function to remove this job
2217
- */
2218
- register(callback, options = {}) {
2219
- const rootId = options.rootId;
2220
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2221
- if (!root) {
2222
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2223
- return () => {
2224
- };
2225
- }
2226
- const id = options.id ?? this.generateJobId();
2227
- let phase = options.phase ?? "update";
2228
- if (!options.phase && (options.before || options.after)) {
2229
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2230
- }
2231
- const before = this.normalizeConstraints(options.before);
2232
- const after = this.normalizeConstraints(options.after);
2233
- const job = {
2234
- id,
2235
- callback,
2236
- phase,
2237
- before,
2238
- after,
2239
- priority: options.priority ?? 0,
2240
- index: this.nextJobIndex++,
2241
- fps: options.fps,
2242
- drop: options.drop ?? true,
2243
- enabled: options.enabled ?? true,
2244
- system: options.system ?? false
2245
- };
2246
- if (root.jobs.has(id)) {
2247
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2248
- }
2249
- root.jobs.set(id, job);
2250
- root.needsRebuild = true;
2251
- return () => this.unregister(id, root.id);
2252
- }
2253
- /**
2254
- * Unregister a job by its ID.
2255
- * Searches all roots if rootId is not provided.
2256
- * @param {string} id - The job ID to unregister
2257
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2258
- * @returns {void}
2259
- */
2260
- unregister(id, rootId) {
2261
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2262
- if (root?.jobs.delete(id)) {
2263
- root.needsRebuild = true;
2264
- this.jobStateListeners.delete(id);
2265
- }
2266
- }
2267
- /**
2268
- * Update a job's options dynamically.
2269
- * Searches all roots to find the job by ID.
2270
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2271
- * @param {string} id - The job ID to update
2272
- * @param {Partial<JobOptions>} options - The options to update
2273
- * @returns {void}
2274
- */
2275
- updateJob(id, options) {
2276
- let job;
2277
- let root;
2278
- for (const r of this.roots.values()) {
2279
- job = r.jobs.get(id);
2280
- if (job) {
2281
- root = r;
2282
- break;
2283
- }
2284
- }
2285
- if (!job || !root) return;
2286
- if (options.priority !== void 0) job.priority = options.priority;
2287
- if (options.fps !== void 0) job.fps = options.fps;
2288
- if (options.drop !== void 0) job.drop = options.drop;
2289
- if (options.enabled !== void 0) {
2290
- const wasEnabled = job.enabled;
2291
- job.enabled = options.enabled;
2292
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2293
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2294
- }
2295
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2296
- if (options.phase) job.phase = options.phase;
2297
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2298
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2299
- root.needsRebuild = true;
2300
- }
2301
- }
2302
- //* Job State Management Methods ================================
2303
- /**
2304
- * Check if a job is currently paused (disabled).
2305
- * @param {string} id - The job ID to check
2306
- * @returns {boolean} True if the job exists and is paused
2307
- */
2308
- isJobPaused(id) {
2309
- for (const root of this.roots.values()) {
2310
- const job = root.jobs.get(id);
2311
- if (job) return !job.enabled;
2312
- }
2313
- return false;
2314
- }
2315
- /**
2316
- * Subscribe to state changes for a specific job.
2317
- * Listener is called when job is paused or resumed.
2318
- * @param {string} id - The job ID to subscribe to
2319
- * @param {() => void} listener - Callback invoked on state changes
2320
- * @returns {() => void} Unsubscribe function
2321
- */
2322
- subscribeJobState(id, listener) {
2323
- if (!this.jobStateListeners.has(id)) {
2324
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2325
- }
2326
- this.jobStateListeners.get(id).add(listener);
2327
- return () => {
2328
- this.jobStateListeners.get(id)?.delete(listener);
2329
- if (this.jobStateListeners.get(id)?.size === 0) {
2330
- this.jobStateListeners.delete(id);
2331
- }
2332
- };
2333
- }
2334
- /**
2335
- * Notify all listeners that a job's state has changed.
2336
- * @param {string} id - The job ID that changed
2337
- * @returns {void}
2338
- * @private
2339
- */
2340
- notifyJobStateChange(id) {
2341
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2342
- }
2343
- /**
2344
- * Pause a job by ID (sets enabled=false).
2345
- * Notifies any subscribed state listeners.
2346
- * @param {string} id - The job ID to pause
2347
- * @returns {void}
2348
- */
2349
- pauseJob(id) {
2350
- this.updateJob(id, { enabled: false });
2351
- this.notifyJobStateChange(id);
2352
- }
2353
- /**
2354
- * Resume a paused job by ID (sets enabled=true).
2355
- * Resets job timing to prevent frame accumulation.
2356
- * Notifies any subscribed state listeners.
2357
- * @param {string} id - The job ID to resume
2358
- * @returns {void}
2359
- */
2360
- resumeJob(id) {
2361
- this.updateJob(id, { enabled: true });
2362
- this.notifyJobStateChange(id);
2363
- }
2364
- //* Frame Loop Control Methods ================================
2365
- /**
2366
- * Start the requestAnimationFrame loop.
2367
- * Resets timing state (elapsedTime, frameCount) on start.
2368
- * No-op if already running.
2369
- * @returns {void}
2370
- */
2371
- start() {
2372
- if (this.loopState.running) return;
2373
- const { elapsedTime, createdAt } = this.loopState;
2374
- let adjustedCreated = 0;
2375
- if (this.stoppedTime > 0) {
2376
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2377
- this.stoppedTime = 0;
2378
- }
2379
- Object.assign(this.loopState, {
2380
- running: true,
2381
- elapsedTime: elapsedTime ?? 0,
2382
- lastTime: performance.now(),
2383
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2384
- frameCount: 0,
2385
- rafHandle: requestAnimationFrame(this.loop)
2386
- });
2387
- }
2388
- /**
2389
- * Stop the requestAnimationFrame loop.
2390
- * Cancels any pending RAF callback.
2391
- * No-op if not running.
2392
- * @returns {void}
2393
- */
2394
- stop() {
2395
- if (!this.loopState.running) return;
2396
- this.loopState.running = false;
2397
- if (this.loopState.rafHandle !== null) {
2398
- cancelAnimationFrame(this.loopState.rafHandle);
2399
- this.loopState.rafHandle = null;
2400
- }
2401
- this.stoppedTime = performance.now();
2402
- }
2403
- /**
2404
- * Request frames to be rendered in demand mode.
2405
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2406
- * No-op if frameloop is not 'demand'.
2407
- * @param {number} [frames=1] - Number of frames to request
2408
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2409
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2410
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2411
- * @returns {void}
2412
- * @example
2413
- * // Request a single frame render
2414
- * scheduler.invalidate();
2415
- *
2416
- * @example
2417
- * // Request 5 frames (e.g., for animations)
2418
- * scheduler.invalidate(5);
2419
- *
2420
- * @example
2421
- * // Set pending frames to exactly 3 (don't stack with existing)
2422
- * scheduler.invalidate(3, false);
2423
- *
2424
- * @example
2425
- * // Add 2 more frames to existing pending count
2426
- * scheduler.invalidate(2, true);
2427
- */
2428
- invalidate(frames = 1, stackFrames = false) {
2429
- if (this._frameloop !== "demand") return;
2430
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2431
- this.pendingFrames = Math.min(60, baseFrames + frames);
2432
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2433
- }
2434
- /**
2435
- * Reset timing state for deterministic testing.
2436
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2437
- * @returns {void}
2438
- */
2439
- resetTiming() {
2440
- this.loopState.lastTime = null;
2441
- this.loopState.frameCount = 0;
2442
- this.loopState.elapsedTime = 0;
2443
- this.loopState.createdAt = performance.now();
2444
- }
2445
- //* Manual Stepping Methods ================================
2446
- /**
2447
- * Manually execute a single frame for all roots.
2448
- * Useful for frameloop='never' mode or testing scenarios.
2449
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2450
- * @returns {void}
2451
- * @example
2452
- * // Manual control mode
2453
- * scheduler.frameloop = 'never';
2454
- * scheduler.step(); // Execute one frame
2455
- */
2456
- step(timestamp) {
2457
- const now = timestamp ?? performance.now();
2458
- this.executeFrame(now);
2459
- }
2460
- /**
2461
- * Manually execute a single job by its ID.
2462
- * Useful for testing individual job callbacks in isolation.
2463
- * @param {string} id - The job ID to step
2464
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2465
- * @returns {void}
2466
- */
2467
- stepJob(id, timestamp) {
2468
- let job;
2469
- let root;
2470
- for (const r of this.roots.values()) {
2471
- job = r.jobs.get(id);
2472
- if (job) {
2473
- root = r;
2474
- break;
2475
- }
2476
- }
2477
- if (!job || !root) {
2478
- console.warn(`[Scheduler] Job "${id}" not found`);
2479
- return;
2480
- }
2481
- const now = timestamp ?? performance.now();
2482
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2483
- const delta = deltaMs / 1e3;
2484
- const elapsed = now - this.loopState.createdAt;
2485
- const providedState = root.getState?.() ?? {};
2486
- const frameState = {
2487
- ...providedState,
2488
- time: now,
2489
- delta,
2490
- elapsed,
2491
- frame: this.loopState.frameCount
2492
- };
2493
- try {
2494
- job.callback(frameState, delta);
2495
- } catch (error) {
2496
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2497
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2498
- }
2499
- }
2500
- /**
2501
- * Execute a single frame across all roots.
2502
- * Order: globalBefore → each root's jobs → globalAfter
2503
- * @param {number} timestamp - RAF timestamp in milliseconds
2504
- * @returns {void}
2505
- * @private
2506
- */
2507
- executeFrame(timestamp) {
2508
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2509
- const delta = deltaMs / 1e3;
2510
- this.loopState.lastTime = timestamp;
2511
- this.loopState.frameCount++;
2512
- this.loopState.elapsedTime += deltaMs;
2513
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2514
- for (const root of this.roots.values()) {
2515
- this.tickRoot(root, timestamp, delta);
2516
- }
2517
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2518
- }
2519
- /**
2520
- * Run all global jobs from a job map.
2521
- * Catches and logs errors without stopping execution.
2522
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2523
- * @param {number} timestamp - RAF timestamp in milliseconds
2524
- * @returns {void}
2525
- * @private
2526
- */
2527
- runGlobalJobs(jobs, timestamp) {
2528
- for (const job of jobs.values()) {
2529
- try {
2530
- job.callback(timestamp);
2531
- } catch (error) {
2532
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2533
- }
2534
- }
2535
- }
2536
- /**
2537
- * Execute all jobs for a single root in sorted order.
2538
- * Rebuilds sorted job list if needed, then dispatches each job.
2539
- * Errors are caught and propagated via triggerError.
2540
- * @param {RootEntry} root - The root entry to tick
2541
- * @param {number} timestamp - RAF timestamp in milliseconds
2542
- * @param {number} delta - Time since last frame in seconds
2543
- * @returns {void}
2544
- * @private
2545
- */
2546
- tickRoot(root, timestamp, delta) {
2547
- if (root.needsRebuild) {
2548
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2549
- root.needsRebuild = false;
2550
- }
2551
- const providedState = root.getState?.() ?? {};
2552
- const frameState = {
2553
- ...providedState,
2554
- time: timestamp,
2555
- delta,
2556
- elapsed: this.loopState.elapsedTime / 1e3,
2557
- // Convert ms to seconds
2558
- frame: this.loopState.frameCount
2559
- };
2560
- for (const job of root.sortedJobs) {
2561
- if (!shouldRun(job, timestamp)) continue;
2562
- try {
2563
- job.callback(frameState, delta);
2564
- } catch (error) {
2565
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2566
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2567
- }
2568
- }
2569
- }
2570
- //* Debug & Inspection Methods ================================
2571
- /**
2572
- * Get the total number of registered jobs across all roots.
2573
- * Includes both per-root jobs and global before/after jobs.
2574
- * @returns {number} Total job count
2575
- */
2576
- getJobCount() {
2577
- let count = 0;
2578
- for (const root of this.roots.values()) {
2579
- count += root.jobs.size;
2580
- }
2581
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2582
- }
2583
- /**
2584
- * Get all registered job IDs across all roots.
2585
- * Includes both per-root jobs and global before/after jobs.
2586
- * @returns {string[]} Array of all job IDs
2587
- */
2588
- getJobIds() {
2589
- const ids = [];
2590
- for (const root of this.roots.values()) {
2591
- ids.push(...root.jobs.keys());
2592
- }
2593
- ids.push(...this.globalBeforeJobs.keys());
2594
- ids.push(...this.globalAfterJobs.keys());
2595
- return ids;
2596
- }
2597
- /**
2598
- * Get the number of registered roots (Canvas instances).
2599
- * @returns {number} Number of registered roots
2600
- */
2601
- getRootCount() {
2602
- return this.roots.size;
2603
- }
2604
- /**
2605
- * Check if any user (non-system) jobs are registered in a specific phase.
2606
- * Used by the default render job to know if a user has taken over rendering.
2607
- *
2608
- * @param phase The phase to check
2609
- * @param rootId Optional root ID to check (checks all roots if not provided)
2610
- * @returns true if any user jobs exist in the phase
2611
- */
2612
- hasUserJobsInPhase(phase, rootId) {
2613
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2614
- return rootsToCheck.some((root) => {
2615
- if (!root) return false;
2616
- for (const job of root.jobs.values()) {
2617
- if (job.phase === phase && !job.system && job.enabled) return true;
2618
- }
2619
- return false;
2620
- });
2621
- }
2622
- //* Utility Methods ================================
2623
- /**
2624
- * Generate a unique root ID for automatic root registration.
2625
- * @returns {string} A unique root ID in the format 'root_N'
2626
- */
2627
- generateRootId() {
2628
- return `root_${this.nextRootIndex++}`;
2629
- }
2630
- /**
2631
- * Generate a unique job ID.
2632
- * @returns {string} A unique job ID in the format 'job_N'
2633
- * @private
2634
- */
2635
- generateJobId() {
2636
- return `job_${this.nextJobIndex}`;
2637
- }
2638
- /**
2639
- * Normalize before/after constraints to a Set.
2640
- * Handles undefined, single string, or array inputs.
2641
- * @param {string | string[] | undefined} value - The constraint value(s)
2642
- * @returns {Set<string>} Normalized Set of constraint strings
2643
- * @private
2644
- */
2645
- normalizeConstraints(value) {
2646
- if (!value) return /* @__PURE__ */ new Set();
2647
- if (Array.isArray(value)) return new Set(value);
2648
- return /* @__PURE__ */ new Set([value]);
2649
- }
2650
- };
2651
- //* Static State & Methods (Singleton Usage) ================================
2652
- //* Cross-Bundle Singleton Key ==============================
2653
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2654
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2655
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2656
- let Scheduler = _Scheduler;
2657
- const getScheduler = () => Scheduler.get();
2658
- if (hmrData) {
2659
- hmrData.accept?.();
1662
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1663
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1664
+ if (!stack) return false;
1665
+ const caller = stack.split("\n")[callerDepth] ?? "";
1666
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2660
1667
  }
2661
1668
 
2662
1669
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2791,6 +1798,7 @@ const createStore = (invalidate, advance) => {
2791
1798
  }),
2792
1799
  setFrameloop: (frameloop = "always") => {
2793
1800
  set(() => ({ frameloop }));
1801
+ getScheduler().frameloop = frameloop;
2794
1802
  },
2795
1803
  setError: (error) => set(() => ({ error })),
2796
1804
  error: null,
@@ -2858,8 +1866,7 @@ const createStore = (invalidate, advance) => {
2858
1866
  const currentState = rootStore.getState();
2859
1867
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2860
1868
  const stack = new Error().stack || "";
2861
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2862
- if (!isInternalAccess) {
1869
+ if (!isInternalRendererAccess(stack)) {
2863
1870
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2864
1871
  notifyDepreciated({
2865
1872
  heading: "Accessing state.gl in WebGPU mode",
@@ -2972,19 +1979,25 @@ function loadingFn(extensions, onProgress) {
2972
1979
  );
2973
1980
  };
2974
1981
  }
2975
- function useLoader(loader, input, extensions, onProgress) {
2976
- const keys = Array.isArray(input) ? input : [input];
1982
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1983
+ const inputs = Array.isArray(input) ? input : [input];
1984
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2977
1985
  const fn = loadingFn(extensions, onProgress);
2978
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1986
+ const results = cacheKeys.map(
1987
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1988
+ );
2979
1989
  return Array.isArray(input) ? results : results[0];
2980
1990
  }
2981
- useLoader.preload = function(loader, input, extensions, onProgress) {
2982
- const keys = Array.isArray(input) ? input : [input];
2983
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
1991
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
1992
+ const inputs = Array.isArray(input) ? input : [input];
1993
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1994
+ cacheKeys.forEach(
1995
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
1996
+ );
2984
1997
  };
2985
- useLoader.clear = function(loader, input) {
2986
- const keys = Array.isArray(input) ? input : [input];
2987
- keys.forEach((key) => clear([loader, key]));
1998
+ useLoader.clear = function(loader, input, cacheKey) {
1999
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2000
+ cacheKeys.forEach((key) => clear([loader, key]));
2988
2001
  };
2989
2002
  useLoader.loader = getLoader;
2990
2003
 
@@ -3060,20 +2073,14 @@ function useFrame(callback, priorityOrOptions) {
3060
2073
  }
3061
2074
  };
3062
2075
  } else {
3063
- const registerOutside = () => {
3064
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3065
- };
3066
- if (scheduler.independent || scheduler.isReady) {
3067
- return registerOutside();
3068
- }
3069
- let unregisterJob = null;
3070
- const unsubReady = scheduler.onRootReady(() => {
3071
- unregisterJob = registerOutside();
3072
- });
3073
- return () => {
3074
- unsubReady();
3075
- unregisterJob?.();
3076
- };
2076
+ return scheduler.register(
2077
+ (state, delta) => {
2078
+ const frameState = state;
2079
+ if (!frameState.renderer) return;
2080
+ callbackRef.current?.(frameState, delta);
2081
+ },
2082
+ { id, ...options }
2083
+ );
3077
2084
  }
3078
2085
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3079
2086
  const isPaused = React.useSyncExternalStore(
@@ -3412,7 +2419,7 @@ function advance(timestamp) {
3412
2419
  getScheduler().step(timestamp);
3413
2420
  }
3414
2421
 
3415
- const version = "10.0.0-alpha.2";
2422
+ const version = "10.0.0-alpha.3";
3416
2423
  const packageData = {
3417
2424
  version: version};
3418
2425
 
@@ -14851,6 +13858,7 @@ function swapInstances() {
14851
13858
  }
14852
13859
  }
14853
13860
  if (instance.isHidden) unhideInstance(instance);
13861
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14854
13862
  if (instance.object.__r3f) delete instance.object.__r3f;
14855
13863
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14856
13864
  }
@@ -14863,6 +13871,8 @@ function swapInstances() {
14863
13871
  instance.object.__r3f = instance;
14864
13872
  setFiberRef(fiber, instance.object);
14865
13873
  delete instance.appliedOnce;
13874
+ instance.eventCount = 0;
13875
+ instance.handlers = {};
14866
13876
  applyProps(instance.object, instance.props);
14867
13877
  if (instance.props.attach) {
14868
13878
  attach(parent, instance);
@@ -15078,11 +14088,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15078
14088
  cloneMutableTextInstance(textInstance) {
15079
14089
  return textInstance;
15080
14090
  },
14091
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14092
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14093
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14094
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14095
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14096
+ // Guarded by a test asserting a full render + unmount never reaches them.
15081
14097
  cloneRootViewTransitionContainer(_rootContainer) {
15082
- throw new Error("Not implemented.");
15083
14098
  },
15084
14099
  removeRootViewTransitionClone(_rootContainer, _clone) {
15085
- throw new Error("Not implemented.");
15086
14100
  },
15087
14101
  // https://github.com/facebook/react/pull/32465
15088
14102
  createFragmentInstance: (_fiber) => null,
@@ -15167,6 +14181,7 @@ function createRoot(canvas) {
15167
14181
  const lastConfiguredProps = {};
15168
14182
  let configured = false;
15169
14183
  let pending = null;
14184
+ let rendererSetup = null;
15170
14185
  return {
15171
14186
  async configure(props = {}) {
15172
14187
  let resolve;
@@ -15197,7 +14212,7 @@ function createRoot(canvas) {
15197
14212
  forceEven
15198
14213
  } = props;
15199
14214
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15200
- const state = store.getState();
14215
+ let state = store.getState();
15201
14216
  const defaultGLProps = {
15202
14217
  canvas,
15203
14218
  powerPreference: "high-performance",
@@ -15225,56 +14240,68 @@ function createRoot(canvas) {
15225
14240
  "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
15226
14241
  );
15227
14242
  }
15228
- if (wantsGL && !state.internal.actualRenderer) {
15229
- renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
15230
- state.internal.actualRenderer = renderer;
15231
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
15232
- } else if (!wantsGL && primaryCanvas && !state.internal.actualRenderer) {
15233
- const primary = await waitForPrimary(primaryCanvas);
15234
- renderer = primary.renderer;
15235
- state.internal.actualRenderer = renderer;
15236
- const canvasTarget = new CanvasTarget(canvas);
15237
- primary.store.setState((prev) => ({
15238
- internal: { ...prev.internal, isMultiCanvas: true }
15239
- }));
15240
- state.set((prev) => ({
15241
- webGPUSupported: primary.store.getState().webGPUSupported,
15242
- renderer,
15243
- primaryStore: primary.store,
15244
- internal: {
15245
- ...prev.internal,
15246
- canvasTarget,
15247
- isMultiCanvas: true,
15248
- isSecondary: true,
15249
- targetId: primaryCanvas
15250
- }
15251
- }));
15252
- } else if (!wantsGL && !state.internal.actualRenderer) {
15253
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15254
- if (!renderer.hasInitialized?.()) {
15255
- const size2 = computeInitialSize(canvas, propsSize);
15256
- if (size2.width > 0 && size2.height > 0) {
15257
- const pixelRatio = calculateDpr(dpr);
15258
- canvas.width = size2.width * pixelRatio;
15259
- canvas.height = size2.height * pixelRatio;
15260
- }
15261
- await renderer.init();
15262
- }
15263
- const backend = renderer.backend;
15264
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15265
- state.internal.actualRenderer = renderer;
15266
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15267
- if (canvasId && !state.internal.isSecondary) {
15268
- const canvasTarget = new CanvasTarget(canvas);
15269
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15270
- state.set((prev) => ({
15271
- internal: {
15272
- ...prev.internal,
15273
- canvasTarget,
15274
- unregisterPrimary
14243
+ if (!state.internal.actualRenderer) {
14244
+ if (!rendererSetup) {
14245
+ rendererSetup = (async () => {
14246
+ if (wantsGL) {
14247
+ renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
14248
+ state.internal.actualRenderer = renderer;
14249
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14250
+ } else if (!wantsGL && primaryCanvas) {
14251
+ const primary = await waitForPrimary(primaryCanvas);
14252
+ renderer = primary.renderer;
14253
+ state.internal.actualRenderer = renderer;
14254
+ const canvasTarget = new CanvasTarget(canvas);
14255
+ primary.store.setState((prev) => ({
14256
+ internal: { ...prev.internal, isMultiCanvas: true }
14257
+ }));
14258
+ state.set((prev) => ({
14259
+ webGPUSupported: primary.store.getState().webGPUSupported,
14260
+ renderer,
14261
+ primaryStore: primary.store,
14262
+ internal: {
14263
+ ...prev.internal,
14264
+ canvasTarget,
14265
+ isMultiCanvas: true,
14266
+ isSecondary: true,
14267
+ targetId: primaryCanvas
14268
+ }
14269
+ }));
14270
+ } else if (!wantsGL) {
14271
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14272
+ if (!renderer.hasInitialized?.()) {
14273
+ const size2 = computeInitialSize(canvas, propsSize);
14274
+ if (size2.width > 0 && size2.height > 0) {
14275
+ const pixelRatio = calculateDpr(dpr);
14276
+ canvas.width = size2.width * pixelRatio;
14277
+ canvas.height = size2.height * pixelRatio;
14278
+ }
14279
+ await renderer.init();
14280
+ }
14281
+ const backend = renderer.backend;
14282
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14283
+ state.internal.actualRenderer = renderer;
14284
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14285
+ if (canvasId && !state.internal.isSecondary) {
14286
+ const canvasTarget = new CanvasTarget(canvas);
14287
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14288
+ state.set((prev) => ({
14289
+ internal: {
14290
+ ...prev.internal,
14291
+ canvasTarget,
14292
+ unregisterPrimary
14293
+ }
14294
+ }));
14295
+ }
15275
14296
  }
15276
- }));
14297
+ })().catch((err) => {
14298
+ rendererSetup = null;
14299
+ throw err;
14300
+ });
15277
14301
  }
14302
+ await rendererSetup;
14303
+ state = store.getState();
14304
+ renderer = state.internal.actualRenderer;
15278
14305
  }
15279
14306
  let raycaster = state.raycaster;
15280
14307
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15499,7 +14526,7 @@ function createRoot(canvas) {
15499
14526
  {
15500
14527
  id: `${newRootId}_frustum`,
15501
14528
  rootId: newRootId,
15502
- phase: "preRender",
14529
+ before: "render",
15503
14530
  system: true
15504
14531
  }
15505
14532
  );
@@ -15511,7 +14538,7 @@ function createRoot(canvas) {
15511
14538
  {
15512
14539
  id: `${newRootId}_visibility`,
15513
14540
  rootId: newRootId,
15514
- phase: "preRender",
14541
+ before: "render",
15515
14542
  system: true,
15516
14543
  after: `${newRootId}_frustum`
15517
14544
  }
@@ -15624,7 +14651,8 @@ function unmountComponentAtNode(canvas, callback) {
15624
14651
  dispose(state.scene);
15625
14652
  _roots.delete(canvas);
15626
14653
  if (callback) callback(canvas);
15627
- } catch {
14654
+ } catch (error) {
14655
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15628
14656
  }
15629
14657
  }, 500);
15630
14658
  }
@@ -15687,6 +14715,7 @@ function PortalInner({ state = {}, children, container }) {
15687
14715
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15688
14716
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15689
14717
  }
14718
+ const set = injectState.set;
15690
14719
  return {
15691
14720
  // The intersect consists of the previous root state
15692
14721
  ...rootState,
@@ -15705,7 +14734,7 @@ function PortalInner({ state = {}, children, container }) {
15705
14734
  size: resolvedSize,
15706
14735
  viewport: { ...rootState.viewport, ...viewport },
15707
14736
  // Layers are allowed to override events
15708
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14737
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15709
14738
  // Container for child attachment - the portalScene (injected or container itself)
15710
14739
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15711
14740
  };
@@ -15734,6 +14763,81 @@ function flushSync(fn) {
15734
14763
  return reconciler.flushSyncFromReconciler(fn);
15735
14764
  }
15736
14765
 
14766
+ function parseBackground(background) {
14767
+ if (!background) return null;
14768
+ if (typeof background === "object" && !background.isColor) {
14769
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14770
+ return {
14771
+ ...rest,
14772
+ preset,
14773
+ files: envMap || files,
14774
+ backgroundFiles: backgroundMap,
14775
+ background: true
14776
+ };
14777
+ }
14778
+ if (typeof background === "number") {
14779
+ return { color: background, background: true };
14780
+ }
14781
+ if (typeof background === "string") {
14782
+ if (background in presetsObj) {
14783
+ return { preset: background, background: true };
14784
+ }
14785
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14786
+ return { files: background, background: true };
14787
+ }
14788
+ return { color: background, background: true };
14789
+ }
14790
+ if (background.isColor) {
14791
+ return { color: background, background: true };
14792
+ }
14793
+ return null;
14794
+ }
14795
+
14796
+ function parseRendererConfig(rendererProp) {
14797
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14798
+ if (isRendererConfig) {
14799
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14800
+ return {
14801
+ primaryCanvas: pc,
14802
+ scheduler: sc,
14803
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14804
+ };
14805
+ }
14806
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14807
+ }
14808
+
14809
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14810
+ const registries = /* @__PURE__ */ new WeakMap();
14811
+ function getKindRegistry(store, kind) {
14812
+ let registry = registries.get(store);
14813
+ if (!registry) {
14814
+ registry = {
14815
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14816
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14817
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14818
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14819
+ };
14820
+ registries.set(store, registry);
14821
+ }
14822
+ return registry[kind];
14823
+ }
14824
+ function invalidateResource(store, kind, scopeKey) {
14825
+ const registry = getKindRegistry(store, kind);
14826
+ {
14827
+ registry.valid.clear();
14828
+ registry.staged.clear();
14829
+ }
14830
+ }
14831
+ function invalidateAllResources(store) {
14832
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14833
+ }
14834
+
14835
+ function clearHmrCaches(store) {
14836
+ const primary = store.getState().primaryStore ?? store;
14837
+ invalidateAllResources(primary);
14838
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14839
+ }
14840
+
15737
14841
  function CanvasImpl({
15738
14842
  ref,
15739
14843
  children,
@@ -15754,6 +14858,8 @@ function CanvasImpl({
15754
14858
  raycaster,
15755
14859
  camera,
15756
14860
  scene,
14861
+ autoUpdateFrustum,
14862
+ occlusion,
15757
14863
  onPointerMissed,
15758
14864
  onDragOverMissed,
15759
14865
  onDropMissed,
@@ -15765,49 +14871,10 @@ function CanvasImpl({
15765
14871
  forceEven,
15766
14872
  ...props
15767
14873
  }) {
15768
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15769
- let primaryCanvas;
15770
- let scheduler;
15771
- let renderer;
15772
- if (isRendererConfig) {
15773
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15774
- primaryCanvas = pc;
15775
- scheduler = sc;
15776
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15777
- } else {
15778
- renderer = rendererProp;
15779
- }
14874
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15780
14875
  React.useMemo(() => extend(THREE), []);
15781
14876
  const Bridge = useBridge();
15782
- const backgroundProps = React.useMemo(() => {
15783
- if (!background) return null;
15784
- if (typeof background === "object" && !background.isColor) {
15785
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15786
- return {
15787
- ...rest,
15788
- preset,
15789
- files: envMap || files,
15790
- backgroundFiles: backgroundMap,
15791
- background: true
15792
- };
15793
- }
15794
- if (typeof background === "number") {
15795
- return { color: background, background: true };
15796
- }
15797
- if (typeof background === "string") {
15798
- if (background in presetsObj) {
15799
- return { preset: background, background: true };
15800
- }
15801
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15802
- return { files: background, background: true };
15803
- }
15804
- return { color: background, background: true };
15805
- }
15806
- if (background.isColor) {
15807
- return { color: background, background: true };
15808
- }
15809
- return null;
15810
- }, [background]);
14877
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15811
14878
  const hasInitialSizeRef = React.useRef(false);
15812
14879
  const measureConfig = React.useMemo(() => {
15813
14880
  if (!hasInitialSizeRef.current) {
@@ -15849,6 +14916,7 @@ function CanvasImpl({
15849
14916
  const handleDropMissed = useMutableCallback(onDropMissed);
15850
14917
  const [block, setBlock] = React.useState(false);
15851
14918
  const [error, setError] = React.useState(false);
14919
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15852
14920
  if (block) throw block;
15853
14921
  if (error) throw error;
15854
14922
  const root = React.useRef(null);
@@ -15856,6 +14924,7 @@ function CanvasImpl({
15856
14924
  const unsubscribeErrorRef = React.useRef(null);
15857
14925
  useIsomorphicLayoutEffect(() => {
15858
14926
  effectActiveRef.current = true;
14927
+ if (fallbackVisible) return;
15859
14928
  const canvas = canvasRef.current;
15860
14929
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15861
14930
  if (!root.current) {
@@ -15876,7 +14945,7 @@ function CanvasImpl({
15876
14945
  }
15877
14946
  async function run() {
15878
14947
  if (!effectActiveRef.current || !root.current) return;
15879
- await root.current.configure({
14948
+ const configured = await root.current.configure({
15880
14949
  id,
15881
14950
  primaryCanvas,
15882
14951
  scheduler,
@@ -15891,6 +14960,8 @@ function CanvasImpl({
15891
14960
  performance,
15892
14961
  raycaster,
15893
14962
  camera,
14963
+ autoUpdateFrustum,
14964
+ occlusion,
15894
14965
  size: effectiveSize,
15895
14966
  // Store size props for reset functionality
15896
14967
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15915,8 +14986,20 @@ function CanvasImpl({
15915
14986
  }
15916
14987
  onCreated?.(state);
15917
14988
  }
15918
- });
15919
- if (!effectActiveRef.current || !root.current) return;
14989
+ }).then(
14990
+ () => true,
14991
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14992
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14993
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14994
+ (setupError) => {
14995
+ if (effectActiveRef.current) {
14996
+ if (fallback != null) setFallbackVisible(true);
14997
+ else setError(setupError);
14998
+ }
14999
+ return false;
15000
+ }
15001
+ );
15002
+ if (!configured || !effectActiveRef.current || !root.current) return;
15920
15003
  root.current.render(
15921
15004
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15922
15005
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15950,14 +15033,7 @@ function CanvasImpl({
15950
15033
  const handleHMR = () => {
15951
15034
  queueMicrotask(() => {
15952
15035
  const rootEntry = _roots.get(canvas);
15953
- if (rootEntry?.store) {
15954
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15955
- rootEntry.store.setState((state) => ({
15956
- nodes: {},
15957
- uniforms: {},
15958
- _hmrVersion: state._hmrVersion + 1
15959
- }));
15960
- }
15036
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15961
15037
  });
15962
15038
  };
15963
15039
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -15986,7 +15062,11 @@ function CanvasImpl({
15986
15062
  ...style
15987
15063
  },
15988
15064
  ...props,
15989
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15065
+ children: fallbackVisible ? (
15066
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15067
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15068
+ fallback
15069
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15990
15070
  "canvas",
15991
15071
  {
15992
15072
  ref: canvasRef,
@@ -16005,4 +15085,4 @@ function Canvas(props) {
16005
15085
 
16006
15086
  extend(THREE);
16007
15087
 
16008
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
15088
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };