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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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';
@@ -13,8 +13,10 @@ import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
13
13
  import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js';
14
14
  import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
15
15
  import { GainMapLoader } from '@monogrid/gainmap-js';
16
- import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
16
+ import Tb, { unstable_getCurrentPriorityLevel, unstable_IdlePriority, unstable_LowPriority, unstable_NormalPriority, unstable_UserBlockingPriority, unstable_ImmediatePriority, unstable_scheduleCallback } 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,10 +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);
431
- const act = React["act"];
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);
432
437
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
433
438
  function useMutableCallback(fn) {
434
439
  const ref = React.useRef(fn);
@@ -459,7 +464,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
459
464
  return _a = class extends React.Component {
460
465
  constructor() {
461
466
  super(...arguments);
462
- __publicField$2(this, "state", { error: false });
467
+ __publicField(this, "state", { error: false });
463
468
  }
464
469
  componentDidCatch(err) {
465
470
  this.props.set(err);
@@ -467,7 +472,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
467
472
  render() {
468
473
  return this.state.error ? null : this.props.children;
469
474
  }
470
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
475
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
471
476
  })();
472
477
 
473
478
  const is = {
@@ -604,8 +609,7 @@ function prepare(target, root, type, props) {
604
609
  object,
605
610
  eventCount: 0,
606
611
  handlers: {},
607
- isHidden: false,
608
- deferredRefs: []
612
+ isHidden: false
609
613
  };
610
614
  if (object) object.__r3f = instance;
611
615
  }
@@ -762,6 +766,17 @@ function unregisterVisibility(store, object) {
762
766
  internal.visibilityRegistry.delete(object.uuid);
763
767
  internal.occlusionCache.delete(object);
764
768
  }
769
+ function updateVisibilityHandlers(store, object, handlers) {
770
+ const { internal } = store.getState();
771
+ const entry = internal.visibilityRegistry.get(object.uuid);
772
+ if (!entry) return false;
773
+ entry.handlers = handlers;
774
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
775
+ object.occlusionTest = true;
776
+ enableOcclusion(store);
777
+ }
778
+ return true;
779
+ }
765
780
  function checkVisibility(state) {
766
781
  const { internal, camera } = state;
767
782
  const registry = internal.visibilityRegistry;
@@ -922,9 +937,9 @@ function diffProps(instance, newProps) {
922
937
  const { root, key } = resolve(instance.object, prop);
923
938
  if (root.constructor && root.constructor.length === 0) {
924
939
  const ctor = getMemoizedPrototype(root);
925
- if (!is.und(ctor)) changedProps[key] = ctor[key];
940
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
926
941
  } else {
927
- changedProps[key] = 0;
942
+ changedProps[prop] = 0;
928
943
  }
929
944
  }
930
945
  return changedProps;
@@ -949,10 +964,7 @@ function applyProps(object, props) {
949
964
  continue;
950
965
  }
951
966
  if (value === void 0) continue;
952
- if (isFromRef(value)) {
953
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
954
- continue;
955
- }
967
+ if (isFromRef(value)) continue;
956
968
  if (isOnce(value)) {
957
969
  if (instance?.appliedOnce?.has(prop)) continue;
958
970
  if (instance) {
@@ -988,6 +1000,19 @@ function applyProps(object, props) {
988
1000
  } else if (isVectorLike(target) && is.num(value)) {
989
1001
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
990
1002
  else target.set(value);
1003
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1004
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1005
+ const uniforms = root.uniforms;
1006
+ const nextUniforms = value;
1007
+ for (const name in nextUniforms) {
1008
+ const uniform = nextUniforms[name];
1009
+ const targetUniform = uniforms[name];
1010
+ if (targetUniform) Object.assign(targetUniform, uniform);
1011
+ else {
1012
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1013
+ uniforms[name] = nextUniform;
1014
+ }
1015
+ }
991
1016
  } else {
992
1017
  root[key] = value;
993
1018
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1006,6 +1031,9 @@ function applyProps(object, props) {
1006
1031
  if (instance.eventCount && object2.raycast !== null) {
1007
1032
  rootState.internal.interaction.push(object2);
1008
1033
  }
1034
+ }
1035
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1036
+ const object2 = instance.object;
1009
1037
  const root = findInitialRoot(instance);
1010
1038
  const visibilityHandlers = {
1011
1039
  onFramed: instance.handlers.onFramed,
@@ -1013,7 +1041,9 @@ function applyProps(object, props) {
1013
1041
  onVisible: instance.handlers.onVisible
1014
1042
  };
1015
1043
  if (hasVisibilityHandlers(visibilityHandlers)) {
1016
- registerVisibility(root, object2, visibilityHandlers);
1044
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1045
+ registerVisibility(root, object2, visibilityHandlers);
1046
+ }
1017
1047
  } else {
1018
1048
  unregisterVisibility(root, object2);
1019
1049
  }
@@ -1541,6 +1571,7 @@ function createPointerEvents(store) {
1541
1571
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1542
1572
  }
1543
1573
  },
1574
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1544
1575
  registerPointer: (config) => {
1545
1576
  const pointerId = nextXRPointerId++;
1546
1577
  xrPointers.set(pointerId, config);
@@ -1627,1036 +1658,11 @@ function notifyAlpha({ message, link }) {
1627
1658
  }
1628
1659
  }
1629
1660
 
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?.();
1661
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1662
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1663
+ if (!stack) return false;
1664
+ const caller = stack.split("\n")[callerDepth] ?? "";
1665
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2660
1666
  }
2661
1667
 
2662
1668
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2791,6 +1797,7 @@ const createStore = (invalidate, advance) => {
2791
1797
  }),
2792
1798
  setFrameloop: (frameloop = "always") => {
2793
1799
  set(() => ({ frameloop }));
1800
+ getScheduler().frameloop = frameloop;
2794
1801
  },
2795
1802
  setError: (error) => set(() => ({ error })),
2796
1803
  error: null,
@@ -2800,6 +1807,7 @@ const createStore = (invalidate, advance) => {
2800
1807
  buffers: {},
2801
1808
  gpuStorage: {},
2802
1809
  textures: /* @__PURE__ */ new Map(),
1810
+ _textureRefs: /* @__PURE__ */ new Map(),
2803
1811
  renderPipeline: null,
2804
1812
  passes: {},
2805
1813
  _hmrVersion: 0,
@@ -2857,8 +1865,7 @@ const createStore = (invalidate, advance) => {
2857
1865
  const currentState = rootStore.getState();
2858
1866
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2859
1867
  const stack = new Error().stack || "";
2860
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2861
- if (!isInternalAccess) {
1868
+ if (!isInternalRendererAccess(stack)) {
2862
1869
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2863
1870
  notifyDepreciated({
2864
1871
  heading: "Accessing state.gl in WebGPU mode",
@@ -2971,19 +1978,25 @@ function loadingFn(extensions, onProgress) {
2971
1978
  );
2972
1979
  };
2973
1980
  }
2974
- function useLoader(loader, input, extensions, onProgress) {
2975
- const keys = Array.isArray(input) ? input : [input];
1981
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1982
+ const inputs = Array.isArray(input) ? input : [input];
1983
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2976
1984
  const fn = loadingFn(extensions, onProgress);
2977
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1985
+ const results = cacheKeys.map(
1986
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1987
+ );
2978
1988
  return Array.isArray(input) ? results : results[0];
2979
1989
  }
2980
- useLoader.preload = function(loader, input, extensions, onProgress) {
2981
- const keys = Array.isArray(input) ? input : [input];
2982
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
1990
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
1991
+ const inputs = Array.isArray(input) ? input : [input];
1992
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1993
+ cacheKeys.forEach(
1994
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
1995
+ );
2983
1996
  };
2984
- useLoader.clear = function(loader, input) {
2985
- const keys = Array.isArray(input) ? input : [input];
2986
- keys.forEach((key) => clear([loader, key]));
1997
+ useLoader.clear = function(loader, input, cacheKey) {
1998
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1999
+ cacheKeys.forEach((key) => clear([loader, key]));
2987
2000
  };
2988
2001
  useLoader.loader = getLoader;
2989
2002
 
@@ -3059,20 +2072,14 @@ function useFrame(callback, priorityOrOptions) {
3059
2072
  }
3060
2073
  };
3061
2074
  } else {
3062
- const registerOutside = () => {
3063
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3064
- };
3065
- if (scheduler.independent || scheduler.isReady) {
3066
- return registerOutside();
3067
- }
3068
- let unregisterJob = null;
3069
- const unsubReady = scheduler.onRootReady(() => {
3070
- unregisterJob = registerOutside();
3071
- });
3072
- return () => {
3073
- unsubReady();
3074
- unregisterJob?.();
3075
- };
2075
+ return scheduler.register(
2076
+ (state, delta) => {
2077
+ const frameState = state;
2078
+ if (!frameState.renderer) return;
2079
+ callbackRef.current?.(frameState, delta);
2080
+ },
2081
+ { id, ...options }
2082
+ );
3076
2083
  }
3077
2084
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3078
2085
  const isPaused = React.useSyncExternalStore(
@@ -3163,18 +2170,18 @@ function buildFromCache(input, textureCache) {
3163
2170
  function useTexture(input, optionsOrOnLoad) {
3164
2171
  const renderer = useThree((state) => state.internal.actualRenderer);
3165
2172
  const store = useStore();
3166
- const textureCache = useThree((state) => state.textures);
3167
2173
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3168
- const { onLoad, cache = false } = options;
2174
+ const { onLoad, cache = true } = options;
3169
2175
  const onLoadRef = useRef(onLoad);
3170
2176
  onLoadRef.current = onLoad;
3171
2177
  const onLoadCalledForRef = useRef(null);
3172
2178
  const urls = useMemo(() => getUrls(input), [input]);
3173
2179
  const cachedResult = useMemo(() => {
3174
2180
  if (!cache) return null;
3175
- if (!allUrlsCached(urls, textureCache)) return null;
3176
- return buildFromCache(input, textureCache);
3177
- }, [cache, urls, textureCache, input]);
2181
+ const textures = store.getState().textures;
2182
+ if (!allUrlsCached(urls, textures)) return null;
2183
+ return buildFromCache(input, textures);
2184
+ }, [cache, urls, input, store]);
3178
2185
  const loadedTextures = useLoader(
3179
2186
  TextureLoader,
3180
2187
  IsObject(input) ? Object.values(input) : input
@@ -3218,8 +2225,6 @@ function useTexture(input, optionsOrOnLoad) {
3218
2225
  }, [input, loadedTextures, cachedResult]);
3219
2226
  useEffect(() => {
3220
2227
  if (!cache) return;
3221
- if (cachedResult) return;
3222
- const set = store.setState;
3223
2228
  const urlTextureMap = [];
3224
2229
  if (typeof input === "string") {
3225
2230
  urlTextureMap.push([input, mappedTextures]);
@@ -3233,18 +2238,32 @@ function useTexture(input, optionsOrOnLoad) {
3233
2238
  urlTextureMap.push([url, textureRecord[key]]);
3234
2239
  }
3235
2240
  }
3236
- set((state) => {
3237
- const newMap = new Map(state.textures);
3238
- let changed = false;
2241
+ store.setState((state) => {
2242
+ const refs = new Map(state._textureRefs);
2243
+ let textures = state.textures;
2244
+ let added = false;
3239
2245
  for (const [url, texture] of urlTextureMap) {
3240
- if (!newMap.has(url)) {
3241
- newMap.set(url, texture);
3242
- changed = true;
2246
+ if (!textures.has(url)) {
2247
+ if (!added) {
2248
+ textures = new Map(textures);
2249
+ added = true;
2250
+ }
2251
+ textures.set(url, texture);
3243
2252
  }
2253
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3244
2254
  }
3245
- return changed ? { textures: newMap } : state;
2255
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2256
+ });
2257
+ return () => store.setState((state) => {
2258
+ const refs = new Map(state._textureRefs);
2259
+ for (const [url] of urlTextureMap) {
2260
+ const next = (refs.get(url) ?? 0) - 1;
2261
+ if (next <= 0) refs.delete(url);
2262
+ else refs.set(url, next);
2263
+ }
2264
+ return { _textureRefs: refs };
3246
2265
  });
3247
- }, [cache, input, mappedTextures, store, cachedResult]);
2266
+ }, [cache, input, mappedTextures, store]);
3248
2267
  return mappedTextures;
3249
2268
  }
3250
2269
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3260,96 +2279,63 @@ const Texture = ({
3260
2279
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3261
2280
  };
3262
2281
 
3263
- function getTextureValue(entry) {
3264
- if (entry instanceof Texture$1) return entry;
3265
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3266
- return entry.value;
3267
- }
3268
- return null;
3269
- }
3270
- function useTextures() {
2282
+ function useTextures(selector) {
3271
2283
  const store = useStore();
3272
- return useMemo(() => {
3273
- const set = store.setState;
2284
+ const registry = useMemo(() => {
3274
2285
  const getState = store.getState;
3275
- const add = (key, value) => {
3276
- set((state) => {
3277
- const newMap = new Map(state.textures);
3278
- newMap.set(key, value);
3279
- return { textures: newMap };
3280
- });
3281
- };
3282
- const addMultiple = (items) => {
3283
- set((state) => {
3284
- const newMap = new Map(state.textures);
3285
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3286
- for (const [key, value] of entries) {
3287
- newMap.set(key, value);
3288
- }
3289
- return { textures: newMap };
3290
- });
3291
- };
3292
- const remove = (key) => {
3293
- set((state) => {
3294
- const newMap = new Map(state.textures);
3295
- newMap.delete(key);
3296
- return { textures: newMap };
3297
- });
3298
- };
3299
- const removeMultiple = (keys) => {
3300
- set((state) => {
3301
- const newMap = new Map(state.textures);
3302
- for (const key of keys) newMap.delete(key);
3303
- return { textures: newMap };
3304
- });
3305
- };
3306
- const dispose = (key) => {
3307
- const entry = getState().textures.get(key);
3308
- if (entry) {
3309
- const tex = getTextureValue(entry);
3310
- tex?.dispose();
3311
- }
3312
- remove(key);
3313
- };
3314
- const disposeMultiple = (keys) => {
3315
- const textures = getState().textures;
3316
- for (const key of keys) {
3317
- const entry = textures.get(key);
3318
- if (entry) {
3319
- const tex = getTextureValue(entry);
3320
- tex?.dispose();
3321
- }
3322
- }
3323
- removeMultiple(keys);
3324
- };
3325
- const disposeAll = () => {
3326
- const textures = getState().textures;
3327
- for (const entry of textures.values()) {
3328
- const tex = getTextureValue(entry);
3329
- tex?.dispose();
3330
- }
3331
- set({ textures: /* @__PURE__ */ new Map() });
3332
- };
2286
+ const setState = store.setState;
2287
+ const getOne = (key) => getState().textures.get(key);
3333
2288
  return {
3334
- // Getter for the textures Map (reactive via getState)
3335
- get textures() {
2289
+ get all() {
3336
2290
  return getState().textures;
3337
2291
  },
3338
- // Read
3339
- get: (key) => getState().textures.get(key),
2292
+ get(input) {
2293
+ if (typeof input === "string") return getOne(input);
2294
+ if (Array.isArray(input)) return input.map(getOne);
2295
+ const out = {};
2296
+ for (const name in input) out[name] = getOne(input[name]);
2297
+ return out;
2298
+ },
3340
2299
  has: (key) => getState().textures.has(key),
3341
- // Write
3342
- add,
3343
- addMultiple,
3344
- // Remove (cache only)
3345
- remove,
3346
- removeMultiple,
3347
- // Dispose (GPU + cache)
3348
- dispose,
3349
- disposeMultiple,
3350
- disposeAll
2300
+ add(keyOrRecord, texture) {
2301
+ setState((state) => {
2302
+ const textures = new Map(state.textures);
2303
+ if (typeof keyOrRecord === "string") {
2304
+ textures.set(keyOrRecord, texture);
2305
+ } else {
2306
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2307
+ }
2308
+ return { textures };
2309
+ });
2310
+ },
2311
+ dispose(key, options) {
2312
+ const state = getState();
2313
+ const refs = state._textureRefs.get(key) ?? 0;
2314
+ if (refs > 0 && !options?.force) {
2315
+ console.warn(
2316
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2317
+ );
2318
+ return false;
2319
+ }
2320
+ state.textures.get(key)?.dispose();
2321
+ setState((s) => {
2322
+ const textures = new Map(s.textures);
2323
+ textures.delete(key);
2324
+ const nextRefs = new Map(s._textureRefs);
2325
+ nextRefs.delete(key);
2326
+ return { textures, _textureRefs: nextRefs };
2327
+ });
2328
+ return true;
2329
+ },
2330
+ disposeAll() {
2331
+ for (const texture of getState().textures.values()) texture.dispose();
2332
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2333
+ }
3351
2334
  };
3352
2335
  }, [store]);
2336
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2337
+ const selected = useThree(subscribe);
2338
+ return selector ? selected : registry;
3353
2339
  }
3354
2340
 
3355
2341
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3432,7 +2418,7 @@ function advance(timestamp) {
3432
2418
  getScheduler().step(timestamp);
3433
2419
  }
3434
2420
 
3435
- const version = "10.0.0-alpha.2";
2421
+ const version = "10.0.0-alpha.3";
3436
2422
  const packageData = {
3437
2423
  version: version};
3438
2424
 
@@ -14688,7 +13674,7 @@ function n0() {
14688
13674
  var t0 = n0();
14689
13675
  const r0 = Xb(t0);
14690
13676
 
14691
- const t = 1, o = 8, r = 32, e = 2;
13677
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14692
13678
 
14693
13679
  function createReconciler(config) {
14694
13680
  const reconciler2 = r0(config);
@@ -14853,7 +13839,15 @@ function setFiberRef(fiber, publicInstance) {
14853
13839
  }
14854
13840
  }
14855
13841
  const reconstructed = [];
14856
- function swapInstances() {
13842
+ function flushReconstructedInstances() {
13843
+ if (reconstructed.length === 0) return;
13844
+ try {
13845
+ swapReconstructedInstances();
13846
+ } finally {
13847
+ reconstructed.length = 0;
13848
+ }
13849
+ }
13850
+ function swapReconstructedInstances() {
14857
13851
  for (const [instance] of reconstructed) {
14858
13852
  const parent = instance.parent;
14859
13853
  if (parent) {
@@ -14871,6 +13865,7 @@ function swapInstances() {
14871
13865
  }
14872
13866
  }
14873
13867
  if (instance.isHidden) unhideInstance(instance);
13868
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14874
13869
  if (instance.object.__r3f) delete instance.object.__r3f;
14875
13870
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14876
13871
  }
@@ -14883,6 +13878,8 @@ function swapInstances() {
14883
13878
  instance.object.__r3f = instance;
14884
13879
  setFiberRef(fiber, instance.object);
14885
13880
  delete instance.appliedOnce;
13881
+ instance.eventCount = 0;
13882
+ instance.handlers = {};
14886
13883
  applyProps(instance.object, instance.props);
14887
13884
  if (instance.props.attach) {
14888
13885
  attach(parent, instance);
@@ -14899,14 +13896,114 @@ function swapInstances() {
14899
13896
  invalidateInstance(instance);
14900
13897
  }
14901
13898
  }
14902
- reconstructed.length = 0;
14903
13899
  }
14904
13900
  const handleTextInstance = () => {
14905
13901
  };
14906
13902
  const NO_CONTEXT = {};
14907
13903
  let currentUpdatePriority = NoEventPriority;
14908
- const NoFlags = 0;
14909
- const Update = 4;
13904
+ function getEventPriority(type) {
13905
+ switch (type) {
13906
+ case "beforetoggle":
13907
+ case "cancel":
13908
+ case "click":
13909
+ case "close":
13910
+ case "contextmenu":
13911
+ case "copy":
13912
+ case "cut":
13913
+ case "auxclick":
13914
+ case "dblclick":
13915
+ case "dragend":
13916
+ case "dragstart":
13917
+ case "drop":
13918
+ case "focusin":
13919
+ case "focusout":
13920
+ case "input":
13921
+ case "invalid":
13922
+ case "keydown":
13923
+ case "keypress":
13924
+ case "keyup":
13925
+ case "mousedown":
13926
+ case "mouseup":
13927
+ case "paste":
13928
+ case "pause":
13929
+ case "play":
13930
+ case "pointercancel":
13931
+ case "pointerdown":
13932
+ case "pointerup":
13933
+ case "ratechange":
13934
+ case "reset":
13935
+ case "resize":
13936
+ case "seeked":
13937
+ case "submit":
13938
+ case "touchcancel":
13939
+ case "touchend":
13940
+ case "touchstart":
13941
+ case "volumechange":
13942
+ case "change":
13943
+ case "selectionchange":
13944
+ case "compositionstart":
13945
+ case "compositionend":
13946
+ case "compositionupdate":
13947
+ case "beforeinput":
13948
+ case "blur":
13949
+ case "fullscreenchange":
13950
+ case "focus":
13951
+ case "hashchange":
13952
+ case "popstate":
13953
+ case "select":
13954
+ case "selectstart":
13955
+ return e;
13956
+ case "drag":
13957
+ case "dragenter":
13958
+ case "dragexit":
13959
+ case "dragleave":
13960
+ case "dragover":
13961
+ case "mousemove":
13962
+ case "mouseout":
13963
+ case "mouseover":
13964
+ case "pointermove":
13965
+ case "pointerout":
13966
+ case "pointerover":
13967
+ case "scroll":
13968
+ case "touchmove":
13969
+ case "wheel":
13970
+ case "mouseenter":
13971
+ case "mouseleave":
13972
+ case "pointerenter":
13973
+ case "pointerleave":
13974
+ return o;
13975
+ case "message": {
13976
+ switch (unstable_getCurrentPriorityLevel()) {
13977
+ case unstable_ImmediatePriority:
13978
+ return e;
13979
+ case unstable_UserBlockingPriority:
13980
+ return o;
13981
+ case unstable_NormalPriority:
13982
+ case unstable_LowPriority:
13983
+ return r;
13984
+ case unstable_IdlePriority:
13985
+ return i$1;
13986
+ default:
13987
+ return r;
13988
+ }
13989
+ }
13990
+ default:
13991
+ return r;
13992
+ }
13993
+ }
13994
+ function scheduleMicrotask(callback) {
13995
+ if (typeof queueMicrotask === "function") {
13996
+ queueMicrotask(callback);
13997
+ } else if (typeof Promise !== "undefined") {
13998
+ Promise.resolve().then(callback).catch((error) => {
13999
+ setTimeout(() => {
14000
+ throw error;
14001
+ });
14002
+ });
14003
+ } else {
14004
+ setTimeout(callback);
14005
+ }
14006
+ }
14910
14007
  const reconciler = /* @__PURE__ */ createReconciler({
14911
14008
  isPrimaryRenderer: false,
14912
14009
  warnsIfNotActing: false,
@@ -14945,16 +14042,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14945
14042
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14946
14043
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14947
14044
  if (reconstruct) {
14948
- reconstructed.push([instance, { ...newProps }, fiber]);
14045
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14949
14046
  } else {
14950
14047
  const changedProps = diffProps(instance, newProps);
14951
- if (Object.keys(changedProps).length) {
14952
- Object.assign(instance.props, changedProps);
14953
- applyProps(instance.object, changedProps);
14954
- }
14048
+ const attach2 = instance.props.attach;
14049
+ instance.props = getInstanceProps(newProps);
14050
+ if (attach2 !== void 0) instance.props.attach = attach2;
14051
+ else delete instance.props.attach;
14052
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14955
14053
  }
14956
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14957
- if (isTailSibling) swapInstances();
14958
14054
  },
14959
14055
  finalizeInitialChildren: (instance) => {
14960
14056
  for (const prop in instance.props) {
@@ -14979,8 +14075,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14979
14075
  const target = container.getState().internal.container ?? container.getState().scene;
14980
14076
  return prepare(target, container, "", {});
14981
14077
  },
14982
- resetAfterCommit: () => {
14983
- },
14078
+ // Reconstructed instances are swapped once all mutations are committed,
14079
+ // before layout effects run so refs point to the new objects
14080
+ resetAfterCommit: flushReconstructedInstances,
14984
14081
  shouldSetTextContent: () => false,
14985
14082
  clearContainer: () => false,
14986
14083
  hideInstance,
@@ -14988,6 +14085,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14988
14085
  createTextInstance: handleTextInstance,
14989
14086
  hideTextInstance: handleTextInstance,
14990
14087
  unhideTextInstance: handleTextInstance,
14088
+ // Mirrors react-dom, which flushes discrete work in microtasks
14089
+ supportsMicrotasks: true,
14090
+ scheduleMicrotask,
14991
14091
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
14992
14092
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
14993
14093
  noTimeout: -1,
@@ -15028,28 +14128,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15028
14128
  },
15029
14129
  resolveUpdatePriority() {
15030
14130
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
15031
- switch (typeof window !== "undefined" && window.event?.type) {
15032
- case "click":
15033
- case "contextmenu":
15034
- case "dblclick":
15035
- case "dragenter":
15036
- case "dragleave":
15037
- case "drop":
15038
- case "pointercancel":
15039
- case "pointerdown":
15040
- case "pointerup":
15041
- return e;
15042
- case "dragover":
15043
- case "pointermove":
15044
- case "pointerout":
15045
- case "pointerover":
15046
- case "pointerenter":
15047
- case "pointerleave":
15048
- case "wheel":
15049
- return o;
15050
- default:
15051
- return r;
15052
- }
14131
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14132
+ if (eventType === void 0) return r;
14133
+ return getEventPriority(eventType);
15053
14134
  },
15054
14135
  resetFormInstance() {
15055
14136
  },
@@ -15098,11 +14179,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15098
14179
  cloneMutableTextInstance(textInstance) {
15099
14180
  return textInstance;
15100
14181
  },
14182
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14183
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14184
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14185
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14186
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14187
+ // Guarded by a test asserting a full render + unmount never reaches them.
15101
14188
  cloneRootViewTransitionContainer(_rootContainer) {
15102
- throw new Error("Not implemented.");
15103
14189
  },
15104
14190
  removeRootViewTransitionClone(_rootContainer, _clone) {
15105
- throw new Error("Not implemented.");
15106
14191
  },
15107
14192
  // https://github.com/facebook/react/pull/32465
15108
14193
  createFragmentInstance: (_fiber) => null,
@@ -15187,6 +14272,7 @@ function createRoot(canvas) {
15187
14272
  const lastConfiguredProps = {};
15188
14273
  let configured = false;
15189
14274
  let pending = null;
14275
+ let rendererSetup = null;
15190
14276
  return {
15191
14277
  async configure(props = {}) {
15192
14278
  let resolve;
@@ -15217,7 +14303,7 @@ function createRoot(canvas) {
15217
14303
  forceEven
15218
14304
  } = props;
15219
14305
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15220
- const state = store.getState();
14306
+ let state = store.getState();
15221
14307
  const defaultGLProps = {
15222
14308
  canvas,
15223
14309
  powerPreference: "high-performance",
@@ -15245,56 +14331,68 @@ function createRoot(canvas) {
15245
14331
  "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
15246
14332
  );
15247
14333
  }
15248
- if (wantsGL && !state.internal.actualRenderer) {
15249
- renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
15250
- state.internal.actualRenderer = renderer;
15251
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
15252
- } else if (!wantsGL && primaryCanvas && !state.internal.actualRenderer) {
15253
- const primary = await waitForPrimary(primaryCanvas);
15254
- renderer = primary.renderer;
15255
- state.internal.actualRenderer = renderer;
15256
- const canvasTarget = new CanvasTarget(canvas);
15257
- primary.store.setState((prev) => ({
15258
- internal: { ...prev.internal, isMultiCanvas: true }
15259
- }));
15260
- state.set((prev) => ({
15261
- webGPUSupported: primary.store.getState().webGPUSupported,
15262
- renderer,
15263
- primaryStore: primary.store,
15264
- internal: {
15265
- ...prev.internal,
15266
- canvasTarget,
15267
- isMultiCanvas: true,
15268
- isSecondary: true,
15269
- targetId: primaryCanvas
15270
- }
15271
- }));
15272
- } else if (!wantsGL && !state.internal.actualRenderer) {
15273
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15274
- if (!renderer.hasInitialized?.()) {
15275
- const size2 = computeInitialSize(canvas, propsSize);
15276
- if (size2.width > 0 && size2.height > 0) {
15277
- const pixelRatio = calculateDpr(dpr);
15278
- canvas.width = size2.width * pixelRatio;
15279
- canvas.height = size2.height * pixelRatio;
15280
- }
15281
- await renderer.init();
15282
- }
15283
- const backend = renderer.backend;
15284
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15285
- state.internal.actualRenderer = renderer;
15286
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15287
- if (canvasId && !state.internal.isSecondary) {
15288
- const canvasTarget = new CanvasTarget(canvas);
15289
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15290
- state.set((prev) => ({
15291
- internal: {
15292
- ...prev.internal,
15293
- canvasTarget,
15294
- unregisterPrimary
14334
+ if (!state.internal.actualRenderer) {
14335
+ if (!rendererSetup) {
14336
+ rendererSetup = (async () => {
14337
+ if (wantsGL) {
14338
+ renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
14339
+ state.internal.actualRenderer = renderer;
14340
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14341
+ } else if (!wantsGL && primaryCanvas) {
14342
+ const primary = await waitForPrimary(primaryCanvas);
14343
+ renderer = primary.renderer;
14344
+ state.internal.actualRenderer = renderer;
14345
+ const canvasTarget = new CanvasTarget(canvas);
14346
+ primary.store.setState((prev) => ({
14347
+ internal: { ...prev.internal, isMultiCanvas: true }
14348
+ }));
14349
+ state.set((prev) => ({
14350
+ webGPUSupported: primary.store.getState().webGPUSupported,
14351
+ renderer,
14352
+ primaryStore: primary.store,
14353
+ internal: {
14354
+ ...prev.internal,
14355
+ canvasTarget,
14356
+ isMultiCanvas: true,
14357
+ isSecondary: true,
14358
+ targetId: primaryCanvas
14359
+ }
14360
+ }));
14361
+ } else if (!wantsGL) {
14362
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14363
+ if (!renderer.hasInitialized?.()) {
14364
+ const size2 = computeInitialSize(canvas, propsSize);
14365
+ if (size2.width > 0 && size2.height > 0) {
14366
+ const pixelRatio = calculateDpr(dpr);
14367
+ canvas.width = size2.width * pixelRatio;
14368
+ canvas.height = size2.height * pixelRatio;
14369
+ }
14370
+ await renderer.init();
14371
+ }
14372
+ const backend = renderer.backend;
14373
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14374
+ state.internal.actualRenderer = renderer;
14375
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14376
+ if (canvasId && !state.internal.isSecondary) {
14377
+ const canvasTarget = new CanvasTarget(canvas);
14378
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14379
+ state.set((prev) => ({
14380
+ internal: {
14381
+ ...prev.internal,
14382
+ canvasTarget,
14383
+ unregisterPrimary
14384
+ }
14385
+ }));
14386
+ }
15295
14387
  }
15296
- }));
14388
+ })().catch((err) => {
14389
+ rendererSetup = null;
14390
+ throw err;
14391
+ });
15297
14392
  }
14393
+ await rendererSetup;
14394
+ state = store.getState();
14395
+ renderer = state.internal.actualRenderer;
15298
14396
  }
15299
14397
  let raycaster = state.raycaster;
15300
14398
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15519,7 +14617,7 @@ function createRoot(canvas) {
15519
14617
  {
15520
14618
  id: `${newRootId}_frustum`,
15521
14619
  rootId: newRootId,
15522
- phase: "preRender",
14620
+ before: "render",
15523
14621
  system: true
15524
14622
  }
15525
14623
  );
@@ -15531,7 +14629,7 @@ function createRoot(canvas) {
15531
14629
  {
15532
14630
  id: `${newRootId}_visibility`,
15533
14631
  rootId: newRootId,
15534
- phase: "preRender",
14632
+ before: "render",
15535
14633
  system: true,
15536
14634
  after: `${newRootId}_frustum`
15537
14635
  }
@@ -15644,7 +14742,8 @@ function unmountComponentAtNode(canvas, callback) {
15644
14742
  dispose(state.scene);
15645
14743
  _roots.delete(canvas);
15646
14744
  if (callback) callback(canvas);
15647
- } catch {
14745
+ } catch (error) {
14746
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15648
14747
  }
15649
14748
  }, 500);
15650
14749
  }
@@ -15707,6 +14806,7 @@ function PortalInner({ state = {}, children, container }) {
15707
14806
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15708
14807
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15709
14808
  }
14809
+ const set = injectState.set;
15710
14810
  return {
15711
14811
  // The intersect consists of the previous root state
15712
14812
  ...rootState,
@@ -15725,7 +14825,7 @@ function PortalInner({ state = {}, children, container }) {
15725
14825
  size: resolvedSize,
15726
14826
  viewport: { ...rootState.viewport, ...viewport },
15727
14827
  // Layers are allowed to override events
15728
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14828
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15729
14829
  // Container for child attachment - the portalScene (injected or container itself)
15730
14830
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15731
14831
  };
@@ -15754,6 +14854,81 @@ function flushSync(fn) {
15754
14854
  return reconciler.flushSyncFromReconciler(fn);
15755
14855
  }
15756
14856
 
14857
+ function parseBackground(background) {
14858
+ if (!background) return null;
14859
+ if (typeof background === "object" && !background.isColor) {
14860
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14861
+ return {
14862
+ ...rest,
14863
+ preset,
14864
+ files: envMap || files,
14865
+ backgroundFiles: backgroundMap,
14866
+ background: true
14867
+ };
14868
+ }
14869
+ if (typeof background === "number") {
14870
+ return { color: background, background: true };
14871
+ }
14872
+ if (typeof background === "string") {
14873
+ if (background in presetsObj) {
14874
+ return { preset: background, background: true };
14875
+ }
14876
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14877
+ return { files: background, background: true };
14878
+ }
14879
+ return { color: background, background: true };
14880
+ }
14881
+ if (background.isColor) {
14882
+ return { color: background, background: true };
14883
+ }
14884
+ return null;
14885
+ }
14886
+
14887
+ function parseRendererConfig(rendererProp) {
14888
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14889
+ if (isRendererConfig) {
14890
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14891
+ return {
14892
+ primaryCanvas: pc,
14893
+ scheduler: sc,
14894
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14895
+ };
14896
+ }
14897
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14898
+ }
14899
+
14900
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14901
+ const registries = /* @__PURE__ */ new WeakMap();
14902
+ function getKindRegistry(store, kind) {
14903
+ let registry = registries.get(store);
14904
+ if (!registry) {
14905
+ registry = {
14906
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14907
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14908
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14909
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14910
+ };
14911
+ registries.set(store, registry);
14912
+ }
14913
+ return registry[kind];
14914
+ }
14915
+ function invalidateResource(store, kind, scopeKey) {
14916
+ const registry = getKindRegistry(store, kind);
14917
+ {
14918
+ registry.valid.clear();
14919
+ registry.staged.clear();
14920
+ }
14921
+ }
14922
+ function invalidateAllResources(store) {
14923
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14924
+ }
14925
+
14926
+ function clearHmrCaches(store) {
14927
+ const primary = store.getState().primaryStore ?? store;
14928
+ invalidateAllResources(primary);
14929
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14930
+ }
14931
+
15757
14932
  function CanvasImpl({
15758
14933
  ref,
15759
14934
  children,
@@ -15774,6 +14949,8 @@ function CanvasImpl({
15774
14949
  raycaster,
15775
14950
  camera,
15776
14951
  scene,
14952
+ autoUpdateFrustum,
14953
+ occlusion,
15777
14954
  onPointerMissed,
15778
14955
  onDragOverMissed,
15779
14956
  onDropMissed,
@@ -15785,49 +14962,10 @@ function CanvasImpl({
15785
14962
  forceEven,
15786
14963
  ...props
15787
14964
  }) {
15788
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15789
- let primaryCanvas;
15790
- let scheduler;
15791
- let renderer;
15792
- if (isRendererConfig) {
15793
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15794
- primaryCanvas = pc;
15795
- scheduler = sc;
15796
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15797
- } else {
15798
- renderer = rendererProp;
15799
- }
14965
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15800
14966
  React.useMemo(() => extend(THREE), []);
15801
14967
  const Bridge = useBridge();
15802
- const backgroundProps = React.useMemo(() => {
15803
- if (!background) return null;
15804
- if (typeof background === "object" && !background.isColor) {
15805
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15806
- return {
15807
- ...rest,
15808
- preset,
15809
- files: envMap || files,
15810
- backgroundFiles: backgroundMap,
15811
- background: true
15812
- };
15813
- }
15814
- if (typeof background === "number") {
15815
- return { color: background, background: true };
15816
- }
15817
- if (typeof background === "string") {
15818
- if (background in presetsObj) {
15819
- return { preset: background, background: true };
15820
- }
15821
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15822
- return { files: background, background: true };
15823
- }
15824
- return { color: background, background: true };
15825
- }
15826
- if (background.isColor) {
15827
- return { color: background, background: true };
15828
- }
15829
- return null;
15830
- }, [background]);
14968
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15831
14969
  const hasInitialSizeRef = React.useRef(false);
15832
14970
  const measureConfig = React.useMemo(() => {
15833
14971
  if (!hasInitialSizeRef.current) {
@@ -15869,6 +15007,7 @@ function CanvasImpl({
15869
15007
  const handleDropMissed = useMutableCallback(onDropMissed);
15870
15008
  const [block, setBlock] = React.useState(false);
15871
15009
  const [error, setError] = React.useState(false);
15010
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15872
15011
  if (block) throw block;
15873
15012
  if (error) throw error;
15874
15013
  const root = React.useRef(null);
@@ -15876,6 +15015,7 @@ function CanvasImpl({
15876
15015
  const unsubscribeErrorRef = React.useRef(null);
15877
15016
  useIsomorphicLayoutEffect(() => {
15878
15017
  effectActiveRef.current = true;
15018
+ if (fallbackVisible) return;
15879
15019
  const canvas = canvasRef.current;
15880
15020
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15881
15021
  if (!root.current) {
@@ -15896,7 +15036,7 @@ function CanvasImpl({
15896
15036
  }
15897
15037
  async function run() {
15898
15038
  if (!effectActiveRef.current || !root.current) return;
15899
- await root.current.configure({
15039
+ const configured = await root.current.configure({
15900
15040
  id,
15901
15041
  primaryCanvas,
15902
15042
  scheduler,
@@ -15911,6 +15051,8 @@ function CanvasImpl({
15911
15051
  performance,
15912
15052
  raycaster,
15913
15053
  camera,
15054
+ autoUpdateFrustum,
15055
+ occlusion,
15914
15056
  size: effectiveSize,
15915
15057
  // Store size props for reset functionality
15916
15058
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15935,8 +15077,20 @@ function CanvasImpl({
15935
15077
  }
15936
15078
  onCreated?.(state);
15937
15079
  }
15938
- });
15939
- if (!effectActiveRef.current || !root.current) return;
15080
+ }).then(
15081
+ () => true,
15082
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15083
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15084
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15085
+ (setupError) => {
15086
+ if (effectActiveRef.current) {
15087
+ if (fallback != null) setFallbackVisible(true);
15088
+ else setError(setupError);
15089
+ }
15090
+ return false;
15091
+ }
15092
+ );
15093
+ if (!configured || !effectActiveRef.current || !root.current) return;
15940
15094
  root.current.render(
15941
15095
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15942
15096
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15970,14 +15124,7 @@ function CanvasImpl({
15970
15124
  const handleHMR = () => {
15971
15125
  queueMicrotask(() => {
15972
15126
  const rootEntry = _roots.get(canvas);
15973
- if (rootEntry?.store) {
15974
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15975
- rootEntry.store.setState((state) => ({
15976
- nodes: {},
15977
- uniforms: {},
15978
- _hmrVersion: state._hmrVersion + 1
15979
- }));
15980
- }
15127
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15981
15128
  });
15982
15129
  };
15983
15130
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -16006,7 +15153,11 @@ function CanvasImpl({
16006
15153
  ...style
16007
15154
  },
16008
15155
  ...props,
16009
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15156
+ children: fallbackVisible ? (
15157
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15158
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15159
+ fallback
15160
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
16010
15161
  "canvas",
16011
15162
  {
16012
15163
  ref: canvasRef,
@@ -16025,4 +15176,4 @@ function Canvas(props) {
16025
15176
 
16026
15177
  extend(THREE);
16027
15178
 
16028
- 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 };
15179
+ 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, 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 };