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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
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, PCFSoftShadowMap, VSMShadowMap, PCFShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, PostProcessing } from 'three/webgpu';
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, Vector4, RenderPipeline } from 'three/webgpu';
3
3
  import { Inspector } from 'three/addons/inspector/Inspector.js';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
  import * as React from 'react';
@@ -14,6 +14,8 @@ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
14
14
  import { GainMapLoader } from '@monogrid/gainmap-js';
15
15
  import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
16
16
  import { createWithEqualityFn } from 'zustand/traditional';
17
+ import { getScheduler } from '@pmndrs/scheduler';
18
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
17
19
  import { suspend, preload, clear } from 'suspend-react';
18
20
  import { dequal } from 'dequal/lite';
19
21
  import 'zustand/shallow';
@@ -41,13 +43,16 @@ const WebGLRenderer = class WebGLRenderer2 {
41
43
  }
42
44
  };
43
45
  const WebGLRenderTarget = null;
46
+ const WebGLCubeRenderTarget = null;
44
47
 
45
48
  const THREE = /*#__PURE__*/_mergeNamespaces({
46
49
  __proto__: null,
50
+ CubeRenderTargetCompat: CubeRenderTarget,
47
51
  Inspector: Inspector,
48
52
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
49
53
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
50
54
  RenderTargetCompat: RenderTarget,
55
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
51
56
  WebGLRenderTarget: WebGLRenderTarget,
52
57
  WebGLRenderer: WebGLRenderer
53
58
  }, [webgpu]);
@@ -149,7 +154,7 @@ function useEnvironment({
149
154
  useLoader$1.clear(loader, multiFile ? [files] : files);
150
155
  }
151
156
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
152
- }, [files, renderer.domElement]);
157
+ }, [extension, files, loader, multiFile, renderer.domElement]);
153
158
  const loaderResult = useLoader$1(
154
159
  loader,
155
160
  multiFile ? [files] : files,
@@ -321,15 +326,16 @@ function EnvironmentPortal({
321
326
  preset = void 0,
322
327
  extensions
323
328
  }) {
324
- const gl = useThree$1((state) => state.gl);
329
+ const renderer = useThree$1((state) => state.renderer);
330
+ const isLegacy = useThree$1((state) => state.isLegacy);
325
331
  const defaultScene = useThree$1((state) => state.scene);
326
332
  const camera = React.useRef(null);
327
333
  const [virtualScene] = React.useState(() => new Scene());
328
334
  const fbo = React.useMemo(() => {
329
- const fbo2 = new WebGLCubeRenderTarget(resolution);
335
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
330
336
  fbo2.texture.type = HalfFloatType;
331
337
  return fbo2;
332
- }, [resolution]);
338
+ }, [resolution, isLegacy]);
333
339
  React.useEffect(() => {
334
340
  return () => {
335
341
  fbo.dispose();
@@ -337,10 +343,10 @@ function EnvironmentPortal({
337
343
  }, [fbo]);
338
344
  React.useLayoutEffect(() => {
339
345
  if (frames === 1) {
340
- const autoClear = gl.autoClear;
341
- gl.autoClear = true;
342
- camera.current.update(gl, virtualScene);
343
- gl.autoClear = autoClear;
346
+ const autoClear = renderer.autoClear;
347
+ renderer.autoClear = true;
348
+ camera.current.update(renderer, virtualScene);
349
+ renderer.autoClear = autoClear;
344
350
  }
345
351
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
346
352
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -349,14 +355,29 @@ function EnvironmentPortal({
349
355
  environmentIntensity,
350
356
  environmentRotation
351
357
  });
352
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
358
+ }, [
359
+ children,
360
+ virtualScene,
361
+ fbo.texture,
362
+ scene,
363
+ defaultScene,
364
+ background,
365
+ frames,
366
+ renderer,
367
+ blur,
368
+ backgroundBlurriness,
369
+ backgroundIntensity,
370
+ backgroundRotation,
371
+ environmentIntensity,
372
+ environmentRotation
373
+ ]);
353
374
  let count = 1;
354
375
  useFrame$1(() => {
355
376
  if (frames === Infinity || count < frames) {
356
- const autoClear = gl.autoClear;
357
- gl.autoClear = true;
358
- camera.current.update(gl, virtualScene);
359
- gl.autoClear = autoClear;
377
+ const autoClear = renderer.autoClear;
378
+ renderer.autoClear = true;
379
+ camera.current.update(renderer, virtualScene);
380
+ renderer.autoClear = autoClear;
360
381
  count++;
361
382
  }
362
383
  });
@@ -420,9 +441,9 @@ function Environment(props) {
420
441
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
421
442
  }
422
443
 
423
- var __defProp$3 = Object.defineProperty;
424
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
425
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
444
+ var __defProp$1 = Object.defineProperty;
445
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
446
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
426
447
  const act = React["act"];
427
448
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
428
449
  function useMutableCallback(fn) {
@@ -454,7 +475,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
454
475
  return _a = class extends React.Component {
455
476
  constructor() {
456
477
  super(...arguments);
457
- __publicField$3(this, "state", { error: false });
478
+ __publicField$1(this, "state", { error: false });
458
479
  }
459
480
  componentDidCatch(err) {
460
481
  this.props.set(err);
@@ -462,7 +483,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
462
483
  render() {
463
484
  return this.state.error ? null : this.props.children;
464
485
  }
465
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
466
487
  })();
467
488
 
468
489
  const is = {
@@ -599,8 +620,7 @@ function prepare(target, root, type, props) {
599
620
  object,
600
621
  eventCount: 0,
601
622
  handlers: {},
602
- isHidden: false,
603
- deferredRefs: []
623
+ isHidden: false
604
624
  };
605
625
  if (object) object.__r3f = instance;
606
626
  }
@@ -757,6 +777,17 @@ function unregisterVisibility(store, object) {
757
777
  internal.visibilityRegistry.delete(object.uuid);
758
778
  internal.occlusionCache.delete(object);
759
779
  }
780
+ function updateVisibilityHandlers(store, object, handlers) {
781
+ const { internal } = store.getState();
782
+ const entry = internal.visibilityRegistry.get(object.uuid);
783
+ if (!entry) return false;
784
+ entry.handlers = handlers;
785
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
786
+ object.occlusionTest = true;
787
+ enableOcclusion(store);
788
+ }
789
+ return true;
790
+ }
760
791
  function checkVisibility(state) {
761
792
  const { internal, camera } = state;
762
793
  const registry = internal.visibilityRegistry;
@@ -944,10 +975,7 @@ function applyProps(object, props) {
944
975
  continue;
945
976
  }
946
977
  if (value === void 0) continue;
947
- if (isFromRef(value)) {
948
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
949
- continue;
950
- }
978
+ if (isFromRef(value)) continue;
951
979
  if (isOnce(value)) {
952
980
  if (instance?.appliedOnce?.has(prop)) continue;
953
981
  if (instance) {
@@ -983,6 +1011,19 @@ function applyProps(object, props) {
983
1011
  } else if (isVectorLike(target) && is.num(value)) {
984
1012
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
985
1013
  else target.set(value);
1014
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1015
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1016
+ const uniforms = root.uniforms;
1017
+ const nextUniforms = value;
1018
+ for (const name in nextUniforms) {
1019
+ const uniform = nextUniforms[name];
1020
+ const targetUniform = uniforms[name];
1021
+ if (targetUniform) Object.assign(targetUniform, uniform);
1022
+ else {
1023
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1024
+ uniforms[name] = nextUniform;
1025
+ }
1026
+ }
986
1027
  } else {
987
1028
  root[key] = value;
988
1029
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1001,6 +1042,9 @@ function applyProps(object, props) {
1001
1042
  if (instance.eventCount && object2.raycast !== null) {
1002
1043
  rootState.internal.interaction.push(object2);
1003
1044
  }
1045
+ }
1046
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1047
+ const object2 = instance.object;
1004
1048
  const root = findInitialRoot(instance);
1005
1049
  const visibilityHandlers = {
1006
1050
  onFramed: instance.handlers.onFramed,
@@ -1008,7 +1052,9 @@ function applyProps(object, props) {
1008
1052
  onVisible: instance.handlers.onVisible
1009
1053
  };
1010
1054
  if (hasVisibilityHandlers(visibilityHandlers)) {
1011
- registerVisibility(root, object2, visibilityHandlers);
1055
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1056
+ registerVisibility(root, object2, visibilityHandlers);
1057
+ }
1012
1058
  } else {
1013
1059
  unregisterVisibility(root, object2);
1014
1060
  }
@@ -1276,7 +1322,7 @@ function createEvents(store) {
1276
1322
  }
1277
1323
  function processDeferredPointer(event, pointerId) {
1278
1324
  const state = store.getState();
1279
- const { onPointerMissed, onDragOverMissed, internal } = state;
1325
+ const { internal } = state;
1280
1326
  if (!state.events.enabled) return;
1281
1327
  const filter = filterPointerEvents;
1282
1328
  const hits = intersect(event, filter);
@@ -1511,6 +1557,7 @@ function createPointerEvents(store) {
1511
1557
  }
1512
1558
  },
1513
1559
  connect: (target) => {
1560
+ if (!target) return;
1514
1561
  const { set, events } = store.getState();
1515
1562
  events.disconnect?.();
1516
1563
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1535,6 +1582,7 @@ function createPointerEvents(store) {
1535
1582
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1536
1583
  }
1537
1584
  },
1585
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1538
1586
  registerPointer: (config) => {
1539
1587
  const pointerId = nextXRPointerId++;
1540
1588
  xrPointers.set(pointerId, config);
@@ -1621,1229 +1669,206 @@ function notifyAlpha({ message, link }) {
1621
1669
  }
1622
1670
  }
1623
1671
 
1624
- var __defProp$2 = Object.defineProperty;
1625
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1626
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1627
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1628
- class PhaseGraph {
1629
- constructor() {
1630
- /** Ordered list of phase nodes */
1631
- __publicField$2(this, "phases", []);
1632
- /** Quick lookup by name */
1633
- __publicField$2(this, "phaseMap", /* @__PURE__ */ new Map());
1634
- /** Cached ordered names (invalidated on changes) */
1635
- __publicField$2(this, "orderedNamesCache", null);
1636
- this.initializeDefaultPhases();
1637
- }
1638
- //* Initialization --------------------------------
1639
- initializeDefaultPhases() {
1640
- for (const name of DEFAULT_PHASES) {
1641
- const node = { name, isAutoGenerated: false };
1642
- this.phases.push(node);
1643
- this.phaseMap.set(name, node);
1644
- }
1645
- this.invalidateCache();
1646
- }
1647
- //* Public API --------------------------------
1648
- /**
1649
- * Add a named phase to the graph
1650
- * @param name - Phase name (must be unique)
1651
- * @param options - Position options (before or after another phase)
1652
- */
1653
- addPhase(name, options = {}) {
1654
- if (this.phaseMap.has(name)) {
1655
- console.warn(`[useFrame] Phase "${name}" already exists`);
1656
- return;
1657
- }
1658
- const { before, after } = options;
1659
- const node = { name, isAutoGenerated: false };
1660
- let insertIndex = this.phases.length;
1661
- const targetIndex = this.getPhaseIndex(before ?? after);
1662
- if (targetIndex !== -1) {
1663
- insertIndex = before ? targetIndex : targetIndex + 1;
1664
- } else {
1665
- const constraintType = before ? "before" : "after";
1666
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1667
- }
1668
- this.phases.splice(insertIndex, 0, node);
1669
- this.phaseMap.set(name, node);
1670
- this.invalidateCache();
1671
- }
1672
- /**
1673
- * Get ordered list of phase names
1674
- */
1675
- getOrderedPhases() {
1676
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1677
- return this.orderedNamesCache;
1678
- }
1679
- /**
1680
- * Check if a phase exists
1681
- */
1682
- hasPhase(name) {
1683
- return this.phaseMap.has(name);
1684
- }
1685
- /**
1686
- * Get the index of a phase (-1 if not found)
1687
- */
1688
- getPhaseIndex(name) {
1689
- if (!name) return -1;
1690
- return this.phases.findIndex((p) => p.name === name);
1691
- }
1692
- /**
1693
- * Ensure a phase exists, creating an auto-generated one if needed.
1694
- * Used for resolving before/after constraints.
1695
- *
1696
- * @param name - The phase name to ensure exists
1697
- * @returns The phase name (may be auto-generated like 'before:render')
1698
- */
1699
- ensurePhase(name) {
1700
- if (this.phaseMap.has(name)) return name;
1701
- const node = { name, isAutoGenerated: true };
1702
- this.phases.push(node);
1703
- this.phaseMap.set(name, node);
1704
- this.invalidateCache();
1705
- return name;
1706
- }
1707
- /**
1708
- * Resolve where a job with before/after constraints should go.
1709
- * Creates auto-generated phases if needed.
1710
- *
1711
- * @param before - Phase(s) to run before
1712
- * @param after - Phase(s) to run after
1713
- * @returns The resolved phase name
1714
- */
1715
- resolveConstraintPhase(before, after) {
1716
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1717
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1718
- if (beforeArr.length > 0) {
1719
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1720
- }
1721
- if (afterArr.length > 0) {
1722
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1723
- }
1724
- return "update";
1725
- }
1726
- /**
1727
- * Ensure an auto-generated phase exists relative to a target phase.
1728
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1729
- *
1730
- * @param target - The target phase name to position relative to
1731
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1732
- * @param offset - Insertion offset (0 for before, 1 for after)
1733
- * @returns The auto-generated phase name
1734
- */
1735
- ensureAutoPhase(target, prefix, offset) {
1736
- const autoName = `${prefix}:${target}`;
1737
- if (this.phaseMap.has(autoName)) return autoName;
1738
- const node = { name: autoName, isAutoGenerated: true };
1739
- const targetIndex = this.getPhaseIndex(target);
1740
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1741
- else this.phases.push(node);
1742
- this.phaseMap.set(autoName, node);
1743
- this.invalidateCache();
1744
- return autoName;
1745
- }
1746
- // Internal --------------------------------
1747
- invalidateCache() {
1748
- this.orderedNamesCache = null;
1749
- }
1672
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1673
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1674
+ if (!stack) return false;
1675
+ const caller = stack.split("\n")[callerDepth] ?? "";
1676
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1750
1677
  }
1751
1678
 
1752
- function rebuildSortedJobs(jobs, phaseGraph) {
1753
- const orderedPhases = phaseGraph.getOrderedPhases();
1754
- const buckets = /* @__PURE__ */ new Map();
1755
- for (const phase of orderedPhases) {
1756
- buckets.set(phase, []);
1757
- }
1758
- for (const job of jobs.values()) {
1759
- if (!job.enabled) continue;
1760
- let bucket = buckets.get(job.phase);
1761
- if (!bucket) {
1762
- bucket = [];
1763
- buckets.set(job.phase, bucket);
1764
- }
1765
- bucket.push(job);
1766
- }
1767
- const sortedBuckets = [];
1768
- for (const phase of orderedPhases) {
1769
- const bucket = buckets.get(phase);
1770
- if (!bucket || bucket.length === 0) continue;
1771
- bucket.sort((a, b) => {
1772
- if (a.priority !== b.priority) return b.priority - a.priority;
1773
- return a.index - b.index;
1774
- });
1775
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1776
- }
1777
- for (const [phase, bucket] of buckets) {
1778
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1779
- bucket.sort((a, b) => {
1780
- if (a.priority !== b.priority) return b.priority - a.priority;
1781
- return a.index - b.index;
1782
- });
1783
- sortedBuckets.push(bucket);
1784
- }
1785
- }
1786
- return sortedBuckets.flat();
1787
- }
1788
- function hasCrossJobConstraints(bucket) {
1789
- const jobIds = new Set(bucket.map((j) => j.id));
1790
- for (const job of bucket) {
1791
- for (const ref of job.before) {
1792
- if (jobIds.has(ref)) return true;
1793
- }
1794
- for (const ref of job.after) {
1795
- if (jobIds.has(ref)) return true;
1796
- }
1797
- }
1798
- return false;
1799
- }
1800
- function topologicalSort(jobs) {
1801
- const n = jobs.length;
1802
- if (n <= 1) return jobs;
1803
- const jobMap = /* @__PURE__ */ new Map();
1804
- const inDegree = /* @__PURE__ */ new Map();
1805
- const adjacency = /* @__PURE__ */ new Map();
1806
- for (const job of jobs) {
1807
- jobMap.set(job.id, job);
1808
- inDegree.set(job.id, 0);
1809
- adjacency.set(job.id, []);
1810
- }
1811
- for (const job of jobs) {
1812
- for (const ref of job.before) {
1813
- if (jobMap.has(ref)) {
1814
- adjacency.get(job.id).push(ref);
1815
- inDegree.set(ref, inDegree.get(ref) + 1);
1679
+ const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1680
+ const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
1681
+ const createStore = (invalidate, advance) => {
1682
+ const rootStore = createWithEqualityFn((set, get) => {
1683
+ const position = new Vector3();
1684
+ const defaultTarget = new Vector3();
1685
+ const tempTarget = new Vector3();
1686
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1687
+ const { width, height, top, left } = size;
1688
+ const aspect = width / height;
1689
+ if (target.isVector3) tempTarget.copy(target);
1690
+ else tempTarget.set(...target);
1691
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1692
+ if (isOrthographicCamera(camera)) {
1693
+ return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
1694
+ } else {
1695
+ const fov = camera.fov * Math.PI / 180;
1696
+ const h = 2 * Math.tan(fov / 2) * distance;
1697
+ const w = h * (width / height);
1698
+ return { width: w, height: h, top, left, factor: width / w, distance, aspect };
1816
1699
  }
1817
1700
  }
1818
- for (const ref of job.after) {
1819
- if (jobMap.has(ref)) {
1820
- adjacency.get(ref).push(job.id);
1821
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1701
+ let performanceTimeout = void 0;
1702
+ const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
1703
+ const pointer = new Vector2();
1704
+ const rootState = {
1705
+ set,
1706
+ get,
1707
+ // Mock objects that have to be configured
1708
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1709
+ primaryStore: null,
1710
+ gl: null,
1711
+ renderer: null,
1712
+ camera: null,
1713
+ frustum: new Frustum(),
1714
+ autoUpdateFrustum: true,
1715
+ raycaster: null,
1716
+ events: {
1717
+ priority: 1,
1718
+ enabled: true,
1719
+ connected: false,
1720
+ frameTimedRaycasts: true,
1721
+ alwaysFireOnScroll: true,
1722
+ updateOnFrame: false
1723
+ },
1724
+ scene: null,
1725
+ rootScene: null,
1726
+ xr: null,
1727
+ inspector: null,
1728
+ invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1729
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1730
+ textureColorSpace: SRGBColorSpace,
1731
+ isLegacy: false,
1732
+ webGPUSupported: false,
1733
+ isNative: false,
1734
+ controls: null,
1735
+ pointer,
1736
+ mouse: pointer,
1737
+ frameloop: "always",
1738
+ onPointerMissed: void 0,
1739
+ onDragOverMissed: void 0,
1740
+ onDropMissed: void 0,
1741
+ performance: {
1742
+ current: 1,
1743
+ min: 0.5,
1744
+ max: 1,
1745
+ debounce: 200,
1746
+ regress: () => {
1747
+ const state2 = get();
1748
+ if (performanceTimeout) clearTimeout(performanceTimeout);
1749
+ if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
1750
+ performanceTimeout = setTimeout(
1751
+ () => setPerformanceCurrent(get().performance.max),
1752
+ state2.performance.debounce
1753
+ );
1754
+ }
1755
+ },
1756
+ size: { width: 0, height: 0, top: 0, left: 0 },
1757
+ viewport: {
1758
+ initialDpr: 0,
1759
+ dpr: 0,
1760
+ width: 0,
1761
+ height: 0,
1762
+ top: 0,
1763
+ left: 0,
1764
+ aspect: 0,
1765
+ distance: 0,
1766
+ factor: 0,
1767
+ getCurrentViewport
1768
+ },
1769
+ setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1770
+ setSize: (width, height, top, left) => {
1771
+ const state2 = get();
1772
+ if (width === void 0) {
1773
+ set({ _sizeImperative: false });
1774
+ if (state2._sizeProps) {
1775
+ const { width: propW, height: propH } = state2._sizeProps;
1776
+ if (propW !== void 0 || propH !== void 0) {
1777
+ const currentSize = state2.size;
1778
+ const newSize = {
1779
+ width: propW ?? currentSize.width,
1780
+ height: propH ?? currentSize.height,
1781
+ top: currentSize.top,
1782
+ left: currentSize.left
1783
+ };
1784
+ set((s) => ({
1785
+ size: newSize,
1786
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1787
+ }));
1788
+ getScheduler().invalidate();
1789
+ }
1790
+ }
1791
+ return;
1792
+ }
1793
+ const w = width;
1794
+ const h = height ?? width;
1795
+ const t = top ?? state2.size.top;
1796
+ const l = left ?? state2.size.left;
1797
+ const size = { width: w, height: h, top: t, left: l };
1798
+ set((s) => ({
1799
+ size,
1800
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1801
+ _sizeImperative: true
1802
+ }));
1803
+ getScheduler().invalidate();
1804
+ },
1805
+ setDpr: (dpr) => set((state2) => {
1806
+ const resolved = calculateDpr(dpr);
1807
+ return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
1808
+ }),
1809
+ setFrameloop: (frameloop = "always") => {
1810
+ set(() => ({ frameloop }));
1811
+ getScheduler().frameloop = frameloop;
1812
+ },
1813
+ setError: (error) => set(() => ({ error })),
1814
+ error: null,
1815
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1816
+ uniforms: {},
1817
+ nodes: {},
1818
+ buffers: {},
1819
+ gpuStorage: {},
1820
+ textures: /* @__PURE__ */ new Map(),
1821
+ _textureRefs: /* @__PURE__ */ new Map(),
1822
+ renderPipeline: null,
1823
+ passes: {},
1824
+ _hmrVersion: 0,
1825
+ _sizeImperative: false,
1826
+ _sizeProps: null,
1827
+ previousRoot: void 0,
1828
+ internal: {
1829
+ // Events
1830
+ interaction: [],
1831
+ subscribers: [],
1832
+ // Per-pointer state (new unified structure)
1833
+ pointerMap: /* @__PURE__ */ new Map(),
1834
+ pointerDirty: /* @__PURE__ */ new Map(),
1835
+ lastEvent: React.createRef(),
1836
+ // Deprecated but kept for backwards compatibility
1837
+ hovered: /* @__PURE__ */ new Map(),
1838
+ initialClick: [0, 0],
1839
+ initialHits: [],
1840
+ capturedMap: /* @__PURE__ */ new Map(),
1841
+ // Visibility tracking (onFramed, onOccluded, onVisible)
1842
+ visibilityRegistry: /* @__PURE__ */ new Map(),
1843
+ // Occlusion system (WebGPU only)
1844
+ occlusionEnabled: false,
1845
+ occlusionObserver: null,
1846
+ occlusionCache: /* @__PURE__ */ new Map(),
1847
+ helperGroup: null,
1848
+ // Updates
1849
+ active: false,
1850
+ frames: 0,
1851
+ priority: 0,
1852
+ subscribe: (ref, priority, store) => {
1853
+ const internal = get().internal;
1854
+ internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1855
+ internal.subscribers.push({ ref, priority, store });
1856
+ internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1857
+ return () => {
1858
+ const internal2 = get().internal;
1859
+ if (internal2?.subscribers) {
1860
+ internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
1861
+ internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
1862
+ }
1863
+ };
1864
+ },
1865
+ // Renderer Storage (single source of truth)
1866
+ actualRenderer: null,
1867
+ // Scheduler for useFrameNext (initialized in renderer.tsx)
1868
+ scheduler: null
1822
1869
  }
1823
- }
1824
- }
1825
- const queue = [];
1826
- for (const job of jobs) {
1827
- if (inDegree.get(job.id) === 0) {
1828
- queue.push(job);
1829
- }
1830
- }
1831
- queue.sort((a, b) => {
1832
- if (a.priority !== b.priority) return b.priority - a.priority;
1833
- return a.index - b.index;
1834
- });
1835
- const result = [];
1836
- while (queue.length > 0) {
1837
- const job = queue.shift();
1838
- result.push(job);
1839
- const neighbors = adjacency.get(job.id) || [];
1840
- for (const neighborId of neighbors) {
1841
- const newDegree = inDegree.get(neighborId) - 1;
1842
- inDegree.set(neighborId, newDegree);
1843
- if (newDegree === 0) {
1844
- const neighbor = jobMap.get(neighborId);
1845
- insertSorted(queue, neighbor);
1846
- }
1847
- }
1848
- }
1849
- if (result.length !== n) {
1850
- console.warn("[useFrame] Circular dependency detected in job constraints");
1851
- const resultIds = new Set(result.map((j) => j.id));
1852
- for (const job of jobs) {
1853
- if (!resultIds.has(job.id)) result.push(job);
1854
- }
1855
- }
1856
- return result;
1857
- }
1858
- function insertSorted(arr, job) {
1859
- let i = 0;
1860
- while (i < arr.length) {
1861
- const cmp = arr[i];
1862
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1863
- break;
1864
- }
1865
- i++;
1866
- }
1867
- arr.splice(i, 0, job);
1868
- }
1869
-
1870
- function shouldRun(job, now) {
1871
- if (!job.enabled) return false;
1872
- if (!job.fps) return true;
1873
- const minInterval = 1e3 / job.fps;
1874
- const lastRun = job.lastRun ?? 0;
1875
- const elapsed = now - lastRun;
1876
- if (elapsed < minInterval) return false;
1877
- if (job.drop) {
1878
- job.lastRun = now;
1879
- } else {
1880
- const steps = Math.floor(elapsed / minInterval);
1881
- job.lastRun = lastRun + steps * minInterval;
1882
- if (job.lastRun < now - minInterval) {
1883
- job.lastRun = now;
1884
- }
1885
- }
1886
- return true;
1887
- }
1888
- function resetJobTiming(job) {
1889
- job.lastRun = void 0;
1890
- }
1891
-
1892
- var __defProp$1 = Object.defineProperty;
1893
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1894
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1895
- const hmrData = (() => {
1896
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1897
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1898
- try {
1899
- return (0, eval)("import.meta.hot");
1900
- } catch {
1901
- return void 0;
1902
- }
1903
- })();
1904
- const _Scheduler = class _Scheduler {
1905
- //* Constructor ================================
1906
- constructor() {
1907
- //* Critical State ================================
1908
- __publicField$1(this, "roots", /* @__PURE__ */ new Map());
1909
- __publicField$1(this, "phaseGraph");
1910
- __publicField$1(this, "loopState", {
1911
- running: false,
1912
- rafHandle: null,
1913
- lastTime: null,
1914
- // null = uninitialized, 0+ = valid timestamp
1915
- frameCount: 0,
1916
- elapsedTime: 0,
1917
- createdAt: performance.now()
1918
- });
1919
- __publicField$1(this, "stoppedTime", 0);
1920
- //* Private State ================================
1921
- __publicField$1(this, "nextRootIndex", 0);
1922
- __publicField$1(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1923
- __publicField$1(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1924
- __publicField$1(this, "nextGlobalIndex", 0);
1925
- __publicField$1(this, "idleCallbacks", /* @__PURE__ */ new Set());
1926
- __publicField$1(this, "nextJobIndex", 0);
1927
- __publicField$1(this, "jobStateListeners", /* @__PURE__ */ new Map());
1928
- __publicField$1(this, "pendingFrames", 0);
1929
- __publicField$1(this, "_frameloop", "always");
1930
- //* Independent Mode & Error Handling State ================================
1931
- __publicField$1(this, "_independent", false);
1932
- __publicField$1(this, "errorHandler", null);
1933
- __publicField$1(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1934
- //* Core Loop Execution Methods ================================
1935
- /**
1936
- * Main RAF loop callback.
1937
- * Executes frame, handles demand mode, and schedules next frame.
1938
- * @param {number} timestamp - RAF timestamp in milliseconds
1939
- * @returns {void}
1940
- * @private
1941
- */
1942
- __publicField$1(this, "loop", (timestamp) => {
1943
- if (!this.loopState.running) return;
1944
- this.executeFrame(timestamp);
1945
- if (this._frameloop === "demand") {
1946
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1947
- if (this.pendingFrames === 0) {
1948
- this.notifyIdle(timestamp);
1949
- return this.stop();
1950
- }
1951
- }
1952
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1953
- });
1954
- this.phaseGraph = new PhaseGraph();
1955
- }
1956
- static get instance() {
1957
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1958
- }
1959
- static set instance(value) {
1960
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1961
- }
1962
- /**
1963
- * Get the global scheduler instance (creates if doesn't exist).
1964
- * Uses HMR data to preserve instance across hot reloads.
1965
- * @returns {Scheduler} The singleton scheduler instance
1966
- */
1967
- static get() {
1968
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1969
- _Scheduler.instance = hmrData.data.scheduler;
1970
- }
1971
- if (!_Scheduler.instance) {
1972
- _Scheduler.instance = new _Scheduler();
1973
- if (hmrData?.data) {
1974
- hmrData.data.scheduler = _Scheduler.instance;
1975
- }
1976
- }
1977
- return _Scheduler.instance;
1978
- }
1979
- /**
1980
- * Reset the singleton instance. Stops the loop and clears all state.
1981
- * Primarily used for testing to ensure clean state between tests.
1982
- * @returns {void}
1983
- */
1984
- static reset() {
1985
- if (_Scheduler.instance) {
1986
- _Scheduler.instance.stop();
1987
- _Scheduler.instance = null;
1988
- }
1989
- if (hmrData?.data) {
1990
- hmrData.data.scheduler = null;
1991
- }
1992
- }
1993
- //* Getters & Setters ================================
1994
- get phases() {
1995
- return this.phaseGraph.getOrderedPhases();
1996
- }
1997
- get frameloop() {
1998
- return this._frameloop;
1999
- }
2000
- set frameloop(mode) {
2001
- if (this._frameloop === mode) return;
2002
- const wasAlways = this._frameloop === "always";
2003
- this._frameloop = mode;
2004
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2005
- else if (mode !== "always" && wasAlways) this.stop();
2006
- }
2007
- get isRunning() {
2008
- return this.loopState.running;
2009
- }
2010
- get isReady() {
2011
- return this.roots.size > 0;
2012
- }
2013
- get independent() {
2014
- return this._independent;
2015
- }
2016
- set independent(value) {
2017
- this._independent = value;
2018
- if (value) this.ensureDefaultRoot();
2019
- }
2020
- //* Root Management Methods ================================
2021
- /**
2022
- * Register a root (Canvas) with the scheduler.
2023
- * The first root to register starts the RAF loop (if frameloop='always').
2024
- * @param {string} id - Unique identifier for this root
2025
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2026
- * @returns {() => void} Unsubscribe function to remove this root
2027
- */
2028
- registerRoot(id, options = {}) {
2029
- if (this.roots.has(id)) {
2030
- console.warn(`[Scheduler] Root "${id}" already registered`);
2031
- return () => this.unregisterRoot(id);
2032
- }
2033
- const entry = {
2034
- id,
2035
- getState: options.getState ?? (() => ({})),
2036
- jobs: /* @__PURE__ */ new Map(),
2037
- sortedJobs: [],
2038
- needsRebuild: false
2039
- };
2040
- if (options.onError) {
2041
- this.errorHandler = options.onError;
2042
- }
2043
- this.roots.set(id, entry);
2044
- if (this.roots.size === 1) {
2045
- this.notifyRootReady();
2046
- if (this._frameloop === "always") this.start();
2047
- }
2048
- return () => this.unregisterRoot(id);
2049
- }
2050
- /**
2051
- * Unregister a root from the scheduler.
2052
- * Cleans up all job state listeners for this root's jobs.
2053
- * The last root to unregister stops the RAF loop.
2054
- * @param {string} id - The root ID to unregister
2055
- * @returns {void}
2056
- */
2057
- unregisterRoot(id) {
2058
- const root = this.roots.get(id);
2059
- if (!root) return;
2060
- for (const jobId of root.jobs.keys()) {
2061
- this.jobStateListeners.delete(jobId);
2062
- }
2063
- this.roots.delete(id);
2064
- if (this.roots.size === 0) {
2065
- this.stop();
2066
- this.errorHandler = null;
2067
- }
2068
- }
2069
- /**
2070
- * Subscribe to be notified when a root becomes available.
2071
- * Fires immediately if a root already exists.
2072
- * @param {() => void} callback - Function called when first root registers
2073
- * @returns {() => void} Unsubscribe function
2074
- */
2075
- onRootReady(callback) {
2076
- if (this.roots.size > 0) {
2077
- callback();
2078
- return () => {
2079
- };
2080
- }
2081
- this.rootReadyCallbacks.add(callback);
2082
- return () => this.rootReadyCallbacks.delete(callback);
2083
- }
2084
- /**
2085
- * Notify all registered root-ready callbacks.
2086
- * Called when the first root registers.
2087
- * @returns {void}
2088
- * @private
2089
- */
2090
- notifyRootReady() {
2091
- for (const cb of this.rootReadyCallbacks) {
2092
- try {
2093
- cb();
2094
- } catch (error) {
2095
- console.error("[Scheduler] Error in root-ready callback:", error);
2096
- }
2097
- }
2098
- this.rootReadyCallbacks.clear();
2099
- }
2100
- /**
2101
- * Ensure a default root exists for independent mode.
2102
- * Creates a minimal root with no state provider.
2103
- * @returns {void}
2104
- * @private
2105
- */
2106
- ensureDefaultRoot() {
2107
- if (!this.roots.has("__default__")) {
2108
- this.registerRoot("__default__");
2109
- }
2110
- }
2111
- /**
2112
- * Trigger error handling for job errors.
2113
- * Uses the bound error handler if available, otherwise logs to console.
2114
- * @param {Error} error - The error to handle
2115
- * @returns {void}
2116
- */
2117
- triggerError(error) {
2118
- if (this.errorHandler) this.errorHandler(error);
2119
- else console.error("[Scheduler]", error);
2120
- }
2121
- //* Phase Management Methods ================================
2122
- /**
2123
- * Add a named phase to the scheduler's execution order.
2124
- * Marks all roots for rebuild to incorporate the new phase.
2125
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2126
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2127
- * @returns {void}
2128
- * @example
2129
- * scheduler.addPhase('physics', { before: 'update' });
2130
- * scheduler.addPhase('postprocess', { after: 'render' });
2131
- */
2132
- addPhase(name, options) {
2133
- this.phaseGraph.addPhase(name, options);
2134
- for (const root of this.roots.values()) {
2135
- root.needsRebuild = true;
2136
- }
2137
- }
2138
- /**
2139
- * Check if a phase exists in the scheduler.
2140
- * @param {string} name - The phase name to check
2141
- * @returns {boolean} True if the phase exists
2142
- */
2143
- hasPhase(name) {
2144
- return this.phaseGraph.hasPhase(name);
2145
- }
2146
- //* Global Job Registration Methods (Deprecated APIs) ================================
2147
- /**
2148
- * Register a global job that runs once per frame (not per-root).
2149
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2150
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2151
- * @param {string} id - Unique identifier for this global job
2152
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2153
- * @returns {() => void} Unsubscribe function to remove this global job
2154
- * @deprecated Use useFrame with phases instead
2155
- */
2156
- registerGlobal(phase, id, callback) {
2157
- const job = { id, callback };
2158
- if (phase === "before") {
2159
- this.globalBeforeJobs.set(id, job);
2160
- } else {
2161
- this.globalAfterJobs.set(id, job);
2162
- }
2163
- return () => {
2164
- if (phase === "before") this.globalBeforeJobs.delete(id);
2165
- else this.globalAfterJobs.delete(id);
2166
- };
2167
- }
2168
- //* Idle Callback Methods (Deprecated API) ================================
2169
- /**
2170
- * Register an idle callback that fires when the loop stops.
2171
- * Used internally by deprecated addTail API.
2172
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2173
- * @returns {() => void} Unsubscribe function to remove this idle callback
2174
- * @deprecated Use demand mode with invalidate() instead
2175
- */
2176
- onIdle(callback) {
2177
- this.idleCallbacks.add(callback);
2178
- return () => this.idleCallbacks.delete(callback);
2179
- }
2180
- /**
2181
- * Notify all registered idle callbacks.
2182
- * Called when the loop stops in demand mode.
2183
- * @param {number} timestamp - The RAF timestamp when idle occurred
2184
- * @returns {void}
2185
- * @private
2186
- */
2187
- notifyIdle(timestamp) {
2188
- for (const cb of this.idleCallbacks) {
2189
- try {
2190
- cb(timestamp);
2191
- } catch (error) {
2192
- console.error("[Scheduler] Error in idle callback:", error);
2193
- }
2194
- }
2195
- }
2196
- //* Job Registration & Management Methods ================================
2197
- /**
2198
- * Register a job (frame callback) with a specific root.
2199
- * This is the core registration method used by useFrame internally.
2200
- * @param {FrameNextCallback} callback - The function to call each frame
2201
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2202
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2203
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2204
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2205
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2206
- * @param {number} [options.fps] - FPS throttle limit
2207
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2208
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2209
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2210
- * @returns {() => void} Unsubscribe function to remove this job
2211
- */
2212
- register(callback, options = {}) {
2213
- const rootId = options.rootId;
2214
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2215
- if (!root) {
2216
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2217
- return () => {
2218
- };
2219
- }
2220
- const id = options.id ?? this.generateJobId();
2221
- let phase = options.phase ?? "update";
2222
- if (!options.phase && (options.before || options.after)) {
2223
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2224
- }
2225
- const before = this.normalizeConstraints(options.before);
2226
- const after = this.normalizeConstraints(options.after);
2227
- const job = {
2228
- id,
2229
- callback,
2230
- phase,
2231
- before,
2232
- after,
2233
- priority: options.priority ?? 0,
2234
- index: this.nextJobIndex++,
2235
- fps: options.fps,
2236
- drop: options.drop ?? true,
2237
- enabled: options.enabled ?? true,
2238
- system: options.system ?? false
2239
- };
2240
- if (root.jobs.has(id)) {
2241
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2242
- }
2243
- root.jobs.set(id, job);
2244
- root.needsRebuild = true;
2245
- return () => this.unregister(id, root.id);
2246
- }
2247
- /**
2248
- * Unregister a job by its ID.
2249
- * Searches all roots if rootId is not provided.
2250
- * @param {string} id - The job ID to unregister
2251
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2252
- * @returns {void}
2253
- */
2254
- unregister(id, rootId) {
2255
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2256
- if (root?.jobs.delete(id)) {
2257
- root.needsRebuild = true;
2258
- this.jobStateListeners.delete(id);
2259
- }
2260
- }
2261
- /**
2262
- * Update a job's options dynamically.
2263
- * Searches all roots to find the job by ID.
2264
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2265
- * @param {string} id - The job ID to update
2266
- * @param {Partial<JobOptions>} options - The options to update
2267
- * @returns {void}
2268
- */
2269
- updateJob(id, options) {
2270
- let job;
2271
- let root;
2272
- for (const r of this.roots.values()) {
2273
- job = r.jobs.get(id);
2274
- if (job) {
2275
- root = r;
2276
- break;
2277
- }
2278
- }
2279
- if (!job || !root) return;
2280
- if (options.priority !== void 0) job.priority = options.priority;
2281
- if (options.fps !== void 0) job.fps = options.fps;
2282
- if (options.drop !== void 0) job.drop = options.drop;
2283
- if (options.enabled !== void 0) {
2284
- const wasEnabled = job.enabled;
2285
- job.enabled = options.enabled;
2286
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2287
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2288
- }
2289
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2290
- if (options.phase) job.phase = options.phase;
2291
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2292
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2293
- root.needsRebuild = true;
2294
- }
2295
- }
2296
- //* Job State Management Methods ================================
2297
- /**
2298
- * Check if a job is currently paused (disabled).
2299
- * @param {string} id - The job ID to check
2300
- * @returns {boolean} True if the job exists and is paused
2301
- */
2302
- isJobPaused(id) {
2303
- for (const root of this.roots.values()) {
2304
- const job = root.jobs.get(id);
2305
- if (job) return !job.enabled;
2306
- }
2307
- return false;
2308
- }
2309
- /**
2310
- * Subscribe to state changes for a specific job.
2311
- * Listener is called when job is paused or resumed.
2312
- * @param {string} id - The job ID to subscribe to
2313
- * @param {() => void} listener - Callback invoked on state changes
2314
- * @returns {() => void} Unsubscribe function
2315
- */
2316
- subscribeJobState(id, listener) {
2317
- if (!this.jobStateListeners.has(id)) {
2318
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2319
- }
2320
- this.jobStateListeners.get(id).add(listener);
2321
- return () => {
2322
- this.jobStateListeners.get(id)?.delete(listener);
2323
- if (this.jobStateListeners.get(id)?.size === 0) {
2324
- this.jobStateListeners.delete(id);
2325
- }
2326
- };
2327
- }
2328
- /**
2329
- * Notify all listeners that a job's state has changed.
2330
- * @param {string} id - The job ID that changed
2331
- * @returns {void}
2332
- * @private
2333
- */
2334
- notifyJobStateChange(id) {
2335
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2336
- }
2337
- /**
2338
- * Pause a job by ID (sets enabled=false).
2339
- * Notifies any subscribed state listeners.
2340
- * @param {string} id - The job ID to pause
2341
- * @returns {void}
2342
- */
2343
- pauseJob(id) {
2344
- this.updateJob(id, { enabled: false });
2345
- this.notifyJobStateChange(id);
2346
- }
2347
- /**
2348
- * Resume a paused job by ID (sets enabled=true).
2349
- * Resets job timing to prevent frame accumulation.
2350
- * Notifies any subscribed state listeners.
2351
- * @param {string} id - The job ID to resume
2352
- * @returns {void}
2353
- */
2354
- resumeJob(id) {
2355
- this.updateJob(id, { enabled: true });
2356
- this.notifyJobStateChange(id);
2357
- }
2358
- //* Frame Loop Control Methods ================================
2359
- /**
2360
- * Start the requestAnimationFrame loop.
2361
- * Resets timing state (elapsedTime, frameCount) on start.
2362
- * No-op if already running.
2363
- * @returns {void}
2364
- */
2365
- start() {
2366
- if (this.loopState.running) return;
2367
- const { elapsedTime, createdAt } = this.loopState;
2368
- let adjustedCreated = 0;
2369
- if (this.stoppedTime > 0) {
2370
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2371
- this.stoppedTime = 0;
2372
- }
2373
- Object.assign(this.loopState, {
2374
- running: true,
2375
- elapsedTime: elapsedTime ?? 0,
2376
- lastTime: performance.now(),
2377
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2378
- frameCount: 0,
2379
- rafHandle: requestAnimationFrame(this.loop)
2380
- });
2381
- }
2382
- /**
2383
- * Stop the requestAnimationFrame loop.
2384
- * Cancels any pending RAF callback.
2385
- * No-op if not running.
2386
- * @returns {void}
2387
- */
2388
- stop() {
2389
- if (!this.loopState.running) return;
2390
- this.loopState.running = false;
2391
- if (this.loopState.rafHandle !== null) {
2392
- cancelAnimationFrame(this.loopState.rafHandle);
2393
- this.loopState.rafHandle = null;
2394
- }
2395
- this.stoppedTime = performance.now();
2396
- }
2397
- /**
2398
- * Request frames to be rendered in demand mode.
2399
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2400
- * No-op if frameloop is not 'demand'.
2401
- * @param {number} [frames=1] - Number of frames to request
2402
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2403
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2404
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2405
- * @returns {void}
2406
- * @example
2407
- * // Request a single frame render
2408
- * scheduler.invalidate();
2409
- *
2410
- * @example
2411
- * // Request 5 frames (e.g., for animations)
2412
- * scheduler.invalidate(5);
2413
- *
2414
- * @example
2415
- * // Set pending frames to exactly 3 (don't stack with existing)
2416
- * scheduler.invalidate(3, false);
2417
- *
2418
- * @example
2419
- * // Add 2 more frames to existing pending count
2420
- * scheduler.invalidate(2, true);
2421
- */
2422
- invalidate(frames = 1, stackFrames = false) {
2423
- if (this._frameloop !== "demand") return;
2424
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2425
- this.pendingFrames = Math.min(60, baseFrames + frames);
2426
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2427
- }
2428
- /**
2429
- * Reset timing state for deterministic testing.
2430
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2431
- * @returns {void}
2432
- */
2433
- resetTiming() {
2434
- this.loopState.lastTime = null;
2435
- this.loopState.frameCount = 0;
2436
- this.loopState.elapsedTime = 0;
2437
- this.loopState.createdAt = performance.now();
2438
- }
2439
- //* Manual Stepping Methods ================================
2440
- /**
2441
- * Manually execute a single frame for all roots.
2442
- * Useful for frameloop='never' mode or testing scenarios.
2443
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2444
- * @returns {void}
2445
- * @example
2446
- * // Manual control mode
2447
- * scheduler.frameloop = 'never';
2448
- * scheduler.step(); // Execute one frame
2449
- */
2450
- step(timestamp) {
2451
- const now = timestamp ?? performance.now();
2452
- this.executeFrame(now);
2453
- }
2454
- /**
2455
- * Manually execute a single job by its ID.
2456
- * Useful for testing individual job callbacks in isolation.
2457
- * @param {string} id - The job ID to step
2458
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2459
- * @returns {void}
2460
- */
2461
- stepJob(id, timestamp) {
2462
- let job;
2463
- let root;
2464
- for (const r of this.roots.values()) {
2465
- job = r.jobs.get(id);
2466
- if (job) {
2467
- root = r;
2468
- break;
2469
- }
2470
- }
2471
- if (!job || !root) {
2472
- console.warn(`[Scheduler] Job "${id}" not found`);
2473
- return;
2474
- }
2475
- const now = timestamp ?? performance.now();
2476
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2477
- const delta = deltaMs / 1e3;
2478
- const elapsed = now - this.loopState.createdAt;
2479
- const providedState = root.getState?.() ?? {};
2480
- const frameState = {
2481
- ...providedState,
2482
- time: now,
2483
- delta,
2484
- elapsed,
2485
- frame: this.loopState.frameCount
2486
- };
2487
- try {
2488
- job.callback(frameState, delta);
2489
- } catch (error) {
2490
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2491
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2492
- }
2493
- }
2494
- /**
2495
- * Execute a single frame across all roots.
2496
- * Order: globalBefore → each root's jobs → globalAfter
2497
- * @param {number} timestamp - RAF timestamp in milliseconds
2498
- * @returns {void}
2499
- * @private
2500
- */
2501
- executeFrame(timestamp) {
2502
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2503
- const delta = deltaMs / 1e3;
2504
- this.loopState.lastTime = timestamp;
2505
- this.loopState.frameCount++;
2506
- this.loopState.elapsedTime += deltaMs;
2507
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2508
- for (const root of this.roots.values()) {
2509
- this.tickRoot(root, timestamp, delta);
2510
- }
2511
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2512
- }
2513
- /**
2514
- * Run all global jobs from a job map.
2515
- * Catches and logs errors without stopping execution.
2516
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2517
- * @param {number} timestamp - RAF timestamp in milliseconds
2518
- * @returns {void}
2519
- * @private
2520
- */
2521
- runGlobalJobs(jobs, timestamp) {
2522
- for (const job of jobs.values()) {
2523
- try {
2524
- job.callback(timestamp);
2525
- } catch (error) {
2526
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2527
- }
2528
- }
2529
- }
2530
- /**
2531
- * Execute all jobs for a single root in sorted order.
2532
- * Rebuilds sorted job list if needed, then dispatches each job.
2533
- * Errors are caught and propagated via triggerError.
2534
- * @param {RootEntry} root - The root entry to tick
2535
- * @param {number} timestamp - RAF timestamp in milliseconds
2536
- * @param {number} delta - Time since last frame in seconds
2537
- * @returns {void}
2538
- * @private
2539
- */
2540
- tickRoot(root, timestamp, delta) {
2541
- if (root.needsRebuild) {
2542
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2543
- root.needsRebuild = false;
2544
- }
2545
- const providedState = root.getState?.() ?? {};
2546
- const frameState = {
2547
- ...providedState,
2548
- time: timestamp,
2549
- delta,
2550
- elapsed: this.loopState.elapsedTime / 1e3,
2551
- // Convert ms to seconds
2552
- frame: this.loopState.frameCount
2553
- };
2554
- for (const job of root.sortedJobs) {
2555
- if (!shouldRun(job, timestamp)) continue;
2556
- try {
2557
- job.callback(frameState, delta);
2558
- } catch (error) {
2559
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2560
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2561
- }
2562
- }
2563
- }
2564
- //* Debug & Inspection Methods ================================
2565
- /**
2566
- * Get the total number of registered jobs across all roots.
2567
- * Includes both per-root jobs and global before/after jobs.
2568
- * @returns {number} Total job count
2569
- */
2570
- getJobCount() {
2571
- let count = 0;
2572
- for (const root of this.roots.values()) {
2573
- count += root.jobs.size;
2574
- }
2575
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2576
- }
2577
- /**
2578
- * Get all registered job IDs across all roots.
2579
- * Includes both per-root jobs and global before/after jobs.
2580
- * @returns {string[]} Array of all job IDs
2581
- */
2582
- getJobIds() {
2583
- const ids = [];
2584
- for (const root of this.roots.values()) {
2585
- ids.push(...root.jobs.keys());
2586
- }
2587
- ids.push(...this.globalBeforeJobs.keys());
2588
- ids.push(...this.globalAfterJobs.keys());
2589
- return ids;
2590
- }
2591
- /**
2592
- * Get the number of registered roots (Canvas instances).
2593
- * @returns {number} Number of registered roots
2594
- */
2595
- getRootCount() {
2596
- return this.roots.size;
2597
- }
2598
- /**
2599
- * Check if any user (non-system) jobs are registered in a specific phase.
2600
- * Used by the default render job to know if a user has taken over rendering.
2601
- *
2602
- * @param phase The phase to check
2603
- * @param rootId Optional root ID to check (checks all roots if not provided)
2604
- * @returns true if any user jobs exist in the phase
2605
- */
2606
- hasUserJobsInPhase(phase, rootId) {
2607
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2608
- return rootsToCheck.some((root) => {
2609
- if (!root) return false;
2610
- for (const job of root.jobs.values()) {
2611
- if (job.phase === phase && !job.system && job.enabled) return true;
2612
- }
2613
- return false;
2614
- });
2615
- }
2616
- //* Utility Methods ================================
2617
- /**
2618
- * Generate a unique root ID for automatic root registration.
2619
- * @returns {string} A unique root ID in the format 'root_N'
2620
- */
2621
- generateRootId() {
2622
- return `root_${this.nextRootIndex++}`;
2623
- }
2624
- /**
2625
- * Generate a unique job ID.
2626
- * @returns {string} A unique job ID in the format 'job_N'
2627
- * @private
2628
- */
2629
- generateJobId() {
2630
- return `job_${this.nextJobIndex}`;
2631
- }
2632
- /**
2633
- * Normalize before/after constraints to a Set.
2634
- * Handles undefined, single string, or array inputs.
2635
- * @param {string | string[] | undefined} value - The constraint value(s)
2636
- * @returns {Set<string>} Normalized Set of constraint strings
2637
- * @private
2638
- */
2639
- normalizeConstraints(value) {
2640
- if (!value) return /* @__PURE__ */ new Set();
2641
- if (Array.isArray(value)) return new Set(value);
2642
- return /* @__PURE__ */ new Set([value]);
2643
- }
2644
- };
2645
- //* Static State & Methods (Singleton Usage) ================================
2646
- //* Cross-Bundle Singleton Key ==============================
2647
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2648
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2649
- __publicField$1(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2650
- let Scheduler = _Scheduler;
2651
- const getScheduler = () => Scheduler.get();
2652
- if (hmrData) {
2653
- hmrData.accept?.();
2654
- }
2655
-
2656
- const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
2657
- const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
2658
- const createStore = (invalidate, advance) => {
2659
- const rootStore = createWithEqualityFn((set, get) => {
2660
- const position = new Vector3();
2661
- const defaultTarget = new Vector3();
2662
- const tempTarget = new Vector3();
2663
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
2664
- const { width, height, top, left } = size;
2665
- const aspect = width / height;
2666
- if (target.isVector3) tempTarget.copy(target);
2667
- else tempTarget.set(...target);
2668
- const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
2669
- if (isOrthographicCamera(camera)) {
2670
- return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
2671
- } else {
2672
- const fov = camera.fov * Math.PI / 180;
2673
- const h = 2 * Math.tan(fov / 2) * distance;
2674
- const w = h * (width / height);
2675
- return { width: w, height: h, top, left, factor: width / w, distance, aspect };
2676
- }
2677
- }
2678
- let performanceTimeout = void 0;
2679
- const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
2680
- const pointer = new Vector2();
2681
- const rootState = {
2682
- set,
2683
- get,
2684
- // Mock objects that have to be configured
2685
- // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
2686
- primaryStore: null,
2687
- gl: null,
2688
- renderer: null,
2689
- camera: null,
2690
- frustum: new Frustum(),
2691
- autoUpdateFrustum: true,
2692
- raycaster: null,
2693
- events: {
2694
- priority: 1,
2695
- enabled: true,
2696
- connected: false,
2697
- frameTimedRaycasts: true,
2698
- alwaysFireOnScroll: true,
2699
- updateOnFrame: false
2700
- },
2701
- scene: null,
2702
- rootScene: null,
2703
- xr: null,
2704
- inspector: null,
2705
- invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
2706
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
2707
- textureColorSpace: SRGBColorSpace,
2708
- isLegacy: false,
2709
- webGPUSupported: false,
2710
- isNative: false,
2711
- controls: null,
2712
- pointer,
2713
- mouse: pointer,
2714
- frameloop: "always",
2715
- onPointerMissed: void 0,
2716
- onDragOverMissed: void 0,
2717
- onDropMissed: void 0,
2718
- performance: {
2719
- current: 1,
2720
- min: 0.5,
2721
- max: 1,
2722
- debounce: 200,
2723
- regress: () => {
2724
- const state2 = get();
2725
- if (performanceTimeout) clearTimeout(performanceTimeout);
2726
- if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
2727
- performanceTimeout = setTimeout(
2728
- () => setPerformanceCurrent(get().performance.max),
2729
- state2.performance.debounce
2730
- );
2731
- }
2732
- },
2733
- size: { width: 0, height: 0, top: 0, left: 0 },
2734
- viewport: {
2735
- initialDpr: 0,
2736
- dpr: 0,
2737
- width: 0,
2738
- height: 0,
2739
- top: 0,
2740
- left: 0,
2741
- aspect: 0,
2742
- distance: 0,
2743
- factor: 0,
2744
- getCurrentViewport
2745
- },
2746
- setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
2747
- setSize: (width, height, top, left) => {
2748
- const state2 = get();
2749
- if (width === void 0) {
2750
- set({ _sizeImperative: false });
2751
- if (state2._sizeProps) {
2752
- const { width: propW, height: propH } = state2._sizeProps;
2753
- if (propW !== void 0 || propH !== void 0) {
2754
- const currentSize = state2.size;
2755
- const newSize = {
2756
- width: propW ?? currentSize.width,
2757
- height: propH ?? currentSize.height,
2758
- top: currentSize.top,
2759
- left: currentSize.left
2760
- };
2761
- set((s) => ({
2762
- size: newSize,
2763
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2764
- }));
2765
- getScheduler().invalidate();
2766
- }
2767
- }
2768
- return;
2769
- }
2770
- const w = width;
2771
- const h = height ?? width;
2772
- const t = top ?? state2.size.top;
2773
- const l = left ?? state2.size.left;
2774
- const size = { width: w, height: h, top: t, left: l };
2775
- set((s) => ({
2776
- size,
2777
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2778
- _sizeImperative: true
2779
- }));
2780
- getScheduler().invalidate();
2781
- },
2782
- setDpr: (dpr) => set((state2) => {
2783
- const resolved = calculateDpr(dpr);
2784
- return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
2785
- }),
2786
- setFrameloop: (frameloop = "always") => {
2787
- set(() => ({ frameloop }));
2788
- },
2789
- setError: (error) => set(() => ({ error })),
2790
- error: null,
2791
- //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2792
- uniforms: {},
2793
- nodes: {},
2794
- buffers: {},
2795
- gpuStorage: {},
2796
- textures: /* @__PURE__ */ new Map(),
2797
- renderPipeline: null,
2798
- passes: {},
2799
- _hmrVersion: 0,
2800
- _sizeImperative: false,
2801
- _sizeProps: null,
2802
- previousRoot: void 0,
2803
- internal: {
2804
- // Events
2805
- interaction: [],
2806
- subscribers: [],
2807
- // Per-pointer state (new unified structure)
2808
- pointerMap: /* @__PURE__ */ new Map(),
2809
- pointerDirty: /* @__PURE__ */ new Map(),
2810
- lastEvent: React.createRef(),
2811
- // Deprecated but kept for backwards compatibility
2812
- hovered: /* @__PURE__ */ new Map(),
2813
- initialClick: [0, 0],
2814
- initialHits: [],
2815
- capturedMap: /* @__PURE__ */ new Map(),
2816
- // Visibility tracking (onFramed, onOccluded, onVisible)
2817
- visibilityRegistry: /* @__PURE__ */ new Map(),
2818
- // Occlusion system (WebGPU only)
2819
- occlusionEnabled: false,
2820
- occlusionObserver: null,
2821
- occlusionCache: /* @__PURE__ */ new Map(),
2822
- helperGroup: null,
2823
- // Updates
2824
- active: false,
2825
- frames: 0,
2826
- priority: 0,
2827
- subscribe: (ref, priority, store) => {
2828
- const internal = get().internal;
2829
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
2830
- internal.subscribers.push({ ref, priority, store });
2831
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
2832
- return () => {
2833
- const internal2 = get().internal;
2834
- if (internal2?.subscribers) {
2835
- internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
2836
- internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
2837
- }
2838
- };
2839
- },
2840
- // Renderer Storage (single source of truth)
2841
- actualRenderer: null,
2842
- // Scheduler for useFrameNext (initialized in renderer.tsx)
2843
- scheduler: null
2844
- }
2845
- };
2846
- return rootState;
1870
+ };
1871
+ return rootState;
2847
1872
  });
2848
1873
  const state = rootStore.getState();
2849
1874
  Object.defineProperty(state, "gl", {
@@ -2851,8 +1876,7 @@ const createStore = (invalidate, advance) => {
2851
1876
  const currentState = rootStore.getState();
2852
1877
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2853
1878
  const stack = new Error().stack || "";
2854
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2855
- if (!isInternalAccess) {
1879
+ if (!isInternalRendererAccess(stack)) {
2856
1880
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2857
1881
  notifyDepreciated({
2858
1882
  heading: "Accessing state.gl in WebGPU mode",
@@ -2900,14 +1924,16 @@ const createStore = (invalidate, advance) => {
2900
1924
  oldSize = size;
2901
1925
  oldDpr = viewport.dpr;
2902
1926
  updateCamera(camera, size);
2903
- if (canvasTarget) {
1927
+ if (internal.isSecondary && canvasTarget) {
2904
1928
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2905
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2906
- canvasTarget.setSize(size.width, size.height, updateStyle);
1929
+ canvasTarget.setSize(size.width, size.height, false);
2907
1930
  } else {
2908
1931
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2909
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2910
- actualRenderer.setSize(size.width, size.height, updateStyle);
1932
+ actualRenderer.setSize(size.width, size.height, false);
1933
+ if (canvasTarget) {
1934
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1935
+ canvasTarget.setSize(size.width, size.height, false);
1936
+ }
2911
1937
  }
2912
1938
  }
2913
1939
  if (camera !== oldCamera) {
@@ -2963,19 +1989,25 @@ function loadingFn(extensions, onProgress) {
2963
1989
  );
2964
1990
  };
2965
1991
  }
2966
- function useLoader(loader, input, extensions, onProgress) {
2967
- const keys = Array.isArray(input) ? input : [input];
1992
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1993
+ const inputs = Array.isArray(input) ? input : [input];
1994
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2968
1995
  const fn = loadingFn(extensions, onProgress);
2969
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1996
+ const results = cacheKeys.map(
1997
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1998
+ );
2970
1999
  return Array.isArray(input) ? results : results[0];
2971
2000
  }
2972
- useLoader.preload = function(loader, input, extensions, onProgress) {
2973
- const keys = Array.isArray(input) ? input : [input];
2974
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
2001
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2002
+ const inputs = Array.isArray(input) ? input : [input];
2003
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2004
+ cacheKeys.forEach(
2005
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2006
+ );
2975
2007
  };
2976
- useLoader.clear = function(loader, input) {
2977
- const keys = Array.isArray(input) ? input : [input];
2978
- keys.forEach((key) => clear([loader, key]));
2008
+ useLoader.clear = function(loader, input, cacheKey) {
2009
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2010
+ cacheKeys.forEach((key) => clear([loader, key]));
2979
2011
  };
2980
2012
  useLoader.loader = getLoader;
2981
2013
 
@@ -3051,20 +2083,14 @@ function useFrame(callback, priorityOrOptions) {
3051
2083
  }
3052
2084
  };
3053
2085
  } else {
3054
- const registerOutside = () => {
3055
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3056
- };
3057
- if (scheduler.independent || scheduler.isReady) {
3058
- return registerOutside();
3059
- }
3060
- let unregisterJob = null;
3061
- const unsubReady = scheduler.onRootReady(() => {
3062
- unregisterJob = registerOutside();
3063
- });
3064
- return () => {
3065
- unsubReady();
3066
- unregisterJob?.();
3067
- };
2086
+ return scheduler.register(
2087
+ (state, delta) => {
2088
+ const frameState = state;
2089
+ if (!frameState.renderer) return;
2090
+ callbackRef.current?.(frameState, delta);
2091
+ },
2092
+ { id, ...options }
2093
+ );
3068
2094
  }
3069
2095
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3070
2096
  const isPaused = React.useSyncExternalStore(
@@ -3155,18 +2181,18 @@ function buildFromCache(input, textureCache) {
3155
2181
  function useTexture(input, optionsOrOnLoad) {
3156
2182
  const renderer = useThree((state) => state.internal.actualRenderer);
3157
2183
  const store = useStore();
3158
- const textureCache = useThree((state) => state.textures);
3159
2184
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3160
- const { onLoad, cache = false } = options;
2185
+ const { onLoad, cache = true } = options;
3161
2186
  const onLoadRef = useRef(onLoad);
3162
2187
  onLoadRef.current = onLoad;
3163
2188
  const onLoadCalledForRef = useRef(null);
3164
2189
  const urls = useMemo(() => getUrls(input), [input]);
3165
2190
  const cachedResult = useMemo(() => {
3166
2191
  if (!cache) return null;
3167
- if (!allUrlsCached(urls, textureCache)) return null;
3168
- return buildFromCache(input, textureCache);
3169
- }, [cache, urls, textureCache, input]);
2192
+ const textures = store.getState().textures;
2193
+ if (!allUrlsCached(urls, textures)) return null;
2194
+ return buildFromCache(input, textures);
2195
+ }, [cache, urls, input, store]);
3170
2196
  const loadedTextures = useLoader(
3171
2197
  TextureLoader,
3172
2198
  IsObject(input) ? Object.values(input) : input
@@ -3210,8 +2236,6 @@ function useTexture(input, optionsOrOnLoad) {
3210
2236
  }, [input, loadedTextures, cachedResult]);
3211
2237
  useEffect(() => {
3212
2238
  if (!cache) return;
3213
- if (cachedResult) return;
3214
- const set = store.setState;
3215
2239
  const urlTextureMap = [];
3216
2240
  if (typeof input === "string") {
3217
2241
  urlTextureMap.push([input, mappedTextures]);
@@ -3225,18 +2249,32 @@ function useTexture(input, optionsOrOnLoad) {
3225
2249
  urlTextureMap.push([url, textureRecord[key]]);
3226
2250
  }
3227
2251
  }
3228
- set((state) => {
3229
- const newMap = new Map(state.textures);
3230
- let changed = false;
2252
+ store.setState((state) => {
2253
+ const refs = new Map(state._textureRefs);
2254
+ let textures = state.textures;
2255
+ let added = false;
3231
2256
  for (const [url, texture] of urlTextureMap) {
3232
- if (!newMap.has(url)) {
3233
- newMap.set(url, texture);
3234
- changed = true;
2257
+ if (!textures.has(url)) {
2258
+ if (!added) {
2259
+ textures = new Map(textures);
2260
+ added = true;
2261
+ }
2262
+ textures.set(url, texture);
3235
2263
  }
2264
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3236
2265
  }
3237
- return changed ? { textures: newMap } : state;
2266
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2267
+ });
2268
+ return () => store.setState((state) => {
2269
+ const refs = new Map(state._textureRefs);
2270
+ for (const [url] of urlTextureMap) {
2271
+ const next = (refs.get(url) ?? 0) - 1;
2272
+ if (next <= 0) refs.delete(url);
2273
+ else refs.set(url, next);
2274
+ }
2275
+ return { _textureRefs: refs };
3238
2276
  });
3239
- }, [cache, input, mappedTextures, store, cachedResult]);
2277
+ }, [cache, input, mappedTextures, store]);
3240
2278
  return mappedTextures;
3241
2279
  }
3242
2280
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3252,96 +2290,63 @@ const Texture = ({
3252
2290
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3253
2291
  };
3254
2292
 
3255
- function getTextureValue(entry) {
3256
- if (entry instanceof Texture$1) return entry;
3257
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3258
- return entry.value;
3259
- }
3260
- return null;
3261
- }
3262
- function useTextures() {
2293
+ function useTextures(selector) {
3263
2294
  const store = useStore();
3264
- return useMemo(() => {
3265
- const set = store.setState;
2295
+ const registry = useMemo(() => {
3266
2296
  const getState = store.getState;
3267
- const add = (key, value) => {
3268
- set((state) => {
3269
- const newMap = new Map(state.textures);
3270
- newMap.set(key, value);
3271
- return { textures: newMap };
3272
- });
3273
- };
3274
- const addMultiple = (items) => {
3275
- set((state) => {
3276
- const newMap = new Map(state.textures);
3277
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3278
- for (const [key, value] of entries) {
3279
- newMap.set(key, value);
3280
- }
3281
- return { textures: newMap };
3282
- });
3283
- };
3284
- const remove = (key) => {
3285
- set((state) => {
3286
- const newMap = new Map(state.textures);
3287
- newMap.delete(key);
3288
- return { textures: newMap };
3289
- });
3290
- };
3291
- const removeMultiple = (keys) => {
3292
- set((state) => {
3293
- const newMap = new Map(state.textures);
3294
- for (const key of keys) newMap.delete(key);
3295
- return { textures: newMap };
3296
- });
3297
- };
3298
- const dispose = (key) => {
3299
- const entry = getState().textures.get(key);
3300
- if (entry) {
3301
- const tex = getTextureValue(entry);
3302
- tex?.dispose();
3303
- }
3304
- remove(key);
3305
- };
3306
- const disposeMultiple = (keys) => {
3307
- const textures = getState().textures;
3308
- for (const key of keys) {
3309
- const entry = textures.get(key);
3310
- if (entry) {
3311
- const tex = getTextureValue(entry);
3312
- tex?.dispose();
3313
- }
3314
- }
3315
- removeMultiple(keys);
3316
- };
3317
- const disposeAll = () => {
3318
- const textures = getState().textures;
3319
- for (const entry of textures.values()) {
3320
- const tex = getTextureValue(entry);
3321
- tex?.dispose();
3322
- }
3323
- set({ textures: /* @__PURE__ */ new Map() });
3324
- };
2297
+ const setState = store.setState;
2298
+ const getOne = (key) => getState().textures.get(key);
3325
2299
  return {
3326
- // Getter for the textures Map (reactive via getState)
3327
- get textures() {
2300
+ get all() {
3328
2301
  return getState().textures;
3329
2302
  },
3330
- // Read
3331
- get: (key) => getState().textures.get(key),
2303
+ get(input) {
2304
+ if (typeof input === "string") return getOne(input);
2305
+ if (Array.isArray(input)) return input.map(getOne);
2306
+ const out = {};
2307
+ for (const name in input) out[name] = getOne(input[name]);
2308
+ return out;
2309
+ },
3332
2310
  has: (key) => getState().textures.has(key),
3333
- // Write
3334
- add,
3335
- addMultiple,
3336
- // Remove (cache only)
3337
- remove,
3338
- removeMultiple,
3339
- // Dispose (GPU + cache)
3340
- dispose,
3341
- disposeMultiple,
3342
- disposeAll
2311
+ add(keyOrRecord, texture) {
2312
+ setState((state) => {
2313
+ const textures = new Map(state.textures);
2314
+ if (typeof keyOrRecord === "string") {
2315
+ textures.set(keyOrRecord, texture);
2316
+ } else {
2317
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2318
+ }
2319
+ return { textures };
2320
+ });
2321
+ },
2322
+ dispose(key, options) {
2323
+ const state = getState();
2324
+ const refs = state._textureRefs.get(key) ?? 0;
2325
+ if (refs > 0 && !options?.force) {
2326
+ console.warn(
2327
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2328
+ );
2329
+ return false;
2330
+ }
2331
+ state.textures.get(key)?.dispose();
2332
+ setState((s) => {
2333
+ const textures = new Map(s.textures);
2334
+ textures.delete(key);
2335
+ const nextRefs = new Map(s._textureRefs);
2336
+ nextRefs.delete(key);
2337
+ return { textures, _textureRefs: nextRefs };
2338
+ });
2339
+ return true;
2340
+ },
2341
+ disposeAll() {
2342
+ for (const texture of getState().textures.values()) texture.dispose();
2343
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2344
+ }
3343
2345
  };
3344
2346
  }, [store]);
2347
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2348
+ const selected = useThree(subscribe);
2349
+ return selector ? selected : registry;
3345
2350
  }
3346
2351
 
3347
2352
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3422,7 +2427,7 @@ function advance(timestamp) {
3422
2427
  getScheduler().step(timestamp);
3423
2428
  }
3424
2429
 
3425
- const version = "10.0.0-alpha.2";
2430
+ const version = "10.0.0-alpha.3";
3426
2431
  const packageData = {
3427
2432
  version: version};
3428
2433
 
@@ -14861,6 +13866,7 @@ function swapInstances() {
14861
13866
  }
14862
13867
  }
14863
13868
  if (instance.isHidden) unhideInstance(instance);
13869
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14864
13870
  if (instance.object.__r3f) delete instance.object.__r3f;
14865
13871
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14866
13872
  }
@@ -14873,6 +13879,8 @@ function swapInstances() {
14873
13879
  instance.object.__r3f = instance;
14874
13880
  setFiberRef(fiber, instance.object);
14875
13881
  delete instance.appliedOnce;
13882
+ instance.eventCount = 0;
13883
+ instance.handlers = {};
14876
13884
  applyProps(instance.object, instance.props);
14877
13885
  if (instance.props.attach) {
14878
13886
  attach(parent, instance);
@@ -15088,11 +14096,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15088
14096
  cloneMutableTextInstance(textInstance) {
15089
14097
  return textInstance;
15090
14098
  },
14099
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14100
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14101
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14102
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14103
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14104
+ // Guarded by a test asserting a full render + unmount never reaches them.
15091
14105
  cloneRootViewTransitionContainer(_rootContainer) {
15092
- throw new Error("Not implemented.");
15093
14106
  },
15094
14107
  removeRootViewTransitionClone(_rootContainer, _clone) {
15095
- throw new Error("Not implemented.");
15096
14108
  },
15097
14109
  // https://github.com/facebook/react/pull/32465
15098
14110
  createFragmentInstance: (_fiber) => null,
@@ -15177,6 +14189,7 @@ function createRoot(canvas) {
15177
14189
  const lastConfiguredProps = {};
15178
14190
  let configured = false;
15179
14191
  let pending = null;
14192
+ let rendererSetup = null;
15180
14193
  return {
15181
14194
  async configure(props = {}) {
15182
14195
  let resolve;
@@ -15192,7 +14205,6 @@ function createRoot(canvas) {
15192
14205
  events,
15193
14206
  onCreated: onCreatedCallback,
15194
14207
  shadows = false,
15195
- textureColorSpace = SRGBColorSpace,
15196
14208
  orthographic = false,
15197
14209
  frameloop = "always",
15198
14210
  dpr = [1, 2],
@@ -15207,7 +14219,8 @@ function createRoot(canvas) {
15207
14219
  _sizeProps,
15208
14220
  forceEven
15209
14221
  } = props;
15210
- const state = store.getState();
14222
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
14223
+ let state = store.getState();
15211
14224
  const defaultGPUProps = {
15212
14225
  canvas,
15213
14226
  antialias: true
@@ -15221,52 +14234,64 @@ function createRoot(canvas) {
15221
14234
  throw new Error("Cannot use both gl and renderer props at the same time");
15222
14235
  }
15223
14236
  let renderer = state.internal.actualRenderer;
15224
- if (primaryCanvas && !state.internal.actualRenderer) {
15225
- const primary = await waitForPrimary(primaryCanvas);
15226
- renderer = primary.renderer;
15227
- state.internal.actualRenderer = renderer;
15228
- const canvasTarget = new CanvasTarget(canvas);
15229
- primary.store.setState((prev) => ({
15230
- internal: { ...prev.internal, isMultiCanvas: true }
15231
- }));
15232
- state.set((prev) => ({
15233
- webGPUSupported: primary.store.getState().webGPUSupported,
15234
- renderer,
15235
- primaryStore: primary.store,
15236
- internal: {
15237
- ...prev.internal,
15238
- canvasTarget,
15239
- isMultiCanvas: true,
15240
- isSecondary: true,
15241
- targetId: primaryCanvas
15242
- }
15243
- }));
15244
- } else if (!state.internal.actualRenderer) {
15245
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15246
- if (!renderer.hasInitialized?.()) {
15247
- const size2 = computeInitialSize(canvas, propsSize);
15248
- if (size2.width > 0 && size2.height > 0) {
15249
- const pixelRatio = calculateDpr(dpr);
15250
- canvas.width = size2.width * pixelRatio;
15251
- canvas.height = size2.height * pixelRatio;
15252
- }
15253
- await renderer.init();
15254
- }
15255
- const backend = renderer.backend;
15256
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15257
- state.internal.actualRenderer = renderer;
15258
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15259
- if (canvasId && !state.internal.isSecondary) {
15260
- const canvasTarget = new CanvasTarget(canvas);
15261
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15262
- state.set((prev) => ({
15263
- internal: {
15264
- ...prev.internal,
15265
- canvasTarget,
15266
- unregisterPrimary
14237
+ if (!state.internal.actualRenderer) {
14238
+ if (!rendererSetup) {
14239
+ rendererSetup = (async () => {
14240
+ if (primaryCanvas) {
14241
+ const primary = await waitForPrimary(primaryCanvas);
14242
+ renderer = primary.renderer;
14243
+ state.internal.actualRenderer = renderer;
14244
+ const canvasTarget = new CanvasTarget(canvas);
14245
+ primary.store.setState((prev) => ({
14246
+ internal: { ...prev.internal, isMultiCanvas: true }
14247
+ }));
14248
+ state.set((prev) => ({
14249
+ webGPUSupported: primary.store.getState().webGPUSupported,
14250
+ renderer,
14251
+ primaryStore: primary.store,
14252
+ internal: {
14253
+ ...prev.internal,
14254
+ canvasTarget,
14255
+ isMultiCanvas: true,
14256
+ isSecondary: true,
14257
+ targetId: primaryCanvas
14258
+ }
14259
+ }));
14260
+ } else {
14261
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14262
+ if (!renderer.hasInitialized?.()) {
14263
+ const size2 = computeInitialSize(canvas, propsSize);
14264
+ if (size2.width > 0 && size2.height > 0) {
14265
+ const pixelRatio = calculateDpr(dpr);
14266
+ canvas.width = size2.width * pixelRatio;
14267
+ canvas.height = size2.height * pixelRatio;
14268
+ }
14269
+ await renderer.init();
14270
+ }
14271
+ const backend = renderer.backend;
14272
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14273
+ state.internal.actualRenderer = renderer;
14274
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14275
+ if (canvasId && !state.internal.isSecondary) {
14276
+ const canvasTarget = new CanvasTarget(canvas);
14277
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14278
+ state.set((prev) => ({
14279
+ internal: {
14280
+ ...prev.internal,
14281
+ canvasTarget,
14282
+ unregisterPrimary
14283
+ }
14284
+ }));
14285
+ }
15267
14286
  }
15268
- }));
14287
+ })().catch((err) => {
14288
+ rendererSetup = null;
14289
+ throw err;
14290
+ });
15269
14291
  }
14292
+ await rendererSetup;
14293
+ state = store.getState();
14294
+ renderer = state.internal.actualRenderer;
15270
14295
  }
15271
14296
  let raycaster = state.raycaster;
15272
14297
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15359,7 +14384,7 @@ function createRoot(canvas) {
15359
14384
  lastConfiguredProps.performance = performance;
15360
14385
  }
15361
14386
  if (!state.xr) {
15362
- const handleXRFrame = (timestamp, frame) => {
14387
+ const handleXRFrame = (timestamp, _frame) => {
15363
14388
  const state2 = store.getState();
15364
14389
  if (state2.frameloop === "never") return;
15365
14390
  advance(timestamp);
@@ -15395,15 +14420,22 @@ function createRoot(canvas) {
15395
14420
  const oldType = renderer.shadowMap.type;
15396
14421
  renderer.shadowMap.enabled = !!shadows;
15397
14422
  if (is.boo(shadows)) {
15398
- renderer.shadowMap.type = PCFSoftShadowMap;
14423
+ renderer.shadowMap.type = PCFShadowMap;
15399
14424
  } else if (is.str(shadows)) {
14425
+ if (shadows === "soft") {
14426
+ notifyDepreciated({
14427
+ heading: 'shadows="soft" is deprecated',
14428
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14429
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14430
+ });
14431
+ }
15400
14432
  const types = {
15401
14433
  basic: BasicShadowMap,
15402
14434
  percentage: PCFShadowMap,
15403
- soft: PCFSoftShadowMap,
14435
+ soft: PCFShadowMap,
15404
14436
  variance: VSMShadowMap
15405
14437
  };
15406
- renderer.shadowMap.type = types[shadows] ?? PCFSoftShadowMap;
14438
+ renderer.shadowMap.type = types[shadows] ?? PCFShadowMap;
15407
14439
  } else if (is.obj(shadows)) {
15408
14440
  Object.assign(renderer.shadowMap, shadows);
15409
14441
  }
@@ -15419,13 +14451,24 @@ function createRoot(canvas) {
15419
14451
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15420
14452
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15421
14453
  }
14454
+ const r3fProps = ["textureColorSpace"];
14455
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14456
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15422
14457
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15423
- applyProps(renderer, glConfig);
14458
+ const glProps = {};
14459
+ for (const key in glConfig) {
14460
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14461
+ }
14462
+ applyProps(renderer, glProps);
15424
14463
  }
15425
14464
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15426
14465
  const currentRenderer = state.renderer;
15427
14466
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15428
- applyProps(currentRenderer, rendererConfig);
14467
+ const rendererProps = {};
14468
+ for (const key in rendererConfig) {
14469
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14470
+ }
14471
+ applyProps(currentRenderer, rendererProps);
15429
14472
  }
15430
14473
  }
15431
14474
  const scheduler = getScheduler();
@@ -15473,7 +14516,7 @@ function createRoot(canvas) {
15473
14516
  {
15474
14517
  id: `${newRootId}_frustum`,
15475
14518
  rootId: newRootId,
15476
- phase: "preRender",
14519
+ before: "render",
15477
14520
  system: true
15478
14521
  }
15479
14522
  );
@@ -15485,7 +14528,7 @@ function createRoot(canvas) {
15485
14528
  {
15486
14529
  id: `${newRootId}_visibility`,
15487
14530
  rootId: newRootId,
15488
- phase: "preRender",
14531
+ before: "render",
15489
14532
  system: true,
15490
14533
  after: `${newRootId}_frustum`
15491
14534
  }
@@ -15598,7 +14641,8 @@ function unmountComponentAtNode(canvas, callback) {
15598
14641
  dispose(state.scene);
15599
14642
  _roots.delete(canvas);
15600
14643
  if (callback) callback(canvas);
15601
- } catch {
14644
+ } catch (error) {
14645
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15602
14646
  }
15603
14647
  }, 500);
15604
14648
  }
@@ -15661,6 +14705,7 @@ function PortalInner({ state = {}, children, container }) {
15661
14705
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15662
14706
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15663
14707
  }
14708
+ const set = injectState.set;
15664
14709
  return {
15665
14710
  // The intersect consists of the previous root state
15666
14711
  ...rootState,
@@ -15679,33 +14724,205 @@ function PortalInner({ state = {}, children, container }) {
15679
14724
  size: resolvedSize,
15680
14725
  viewport: { ...rootState.viewport, ...viewport },
15681
14726
  // Layers are allowed to override events
15682
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14727
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15683
14728
  // Container for child attachment - the portalScene (injected or container itself)
15684
14729
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15685
14730
  };
15686
14731
  });
15687
- const usePortalStore = useMemo(() => {
15688
- const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15689
- const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15690
- onMutate(previousRoot.getState());
15691
- return store;
15692
- }, [previousRoot, container]);
15693
- useIsomorphicLayoutEffect(() => {
15694
- const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
15695
- const unsubscribe = previousRoot.subscribe(onMutate);
15696
- return unsubscribe;
15697
- }, [previousRoot, usePortalStore]);
15698
- return (
15699
- // @ts-ignore, reconciler types are not maintained
15700
- /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
15701
- /* @__PURE__ */ jsx(context.Provider, { value: usePortalStore, children }),
15702
- usePortalStore,
15703
- null
15704
- ) })
15705
- );
14732
+ const usePortalStore = useMemo(() => {
14733
+ const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14734
+ const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14735
+ onMutate(previousRoot.getState());
14736
+ return store;
14737
+ }, [previousRoot, container]);
14738
+ useIsomorphicLayoutEffect(() => {
14739
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14740
+ const unsubscribe = previousRoot.subscribe(onMutate);
14741
+ return unsubscribe;
14742
+ }, [previousRoot, usePortalStore]);
14743
+ return (
14744
+ // @ts-ignore, reconciler types are not maintained
14745
+ /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
14746
+ /* @__PURE__ */ jsx(context.Provider, { value: usePortalStore, children }),
14747
+ usePortalStore,
14748
+ null
14749
+ ) })
14750
+ );
14751
+ }
14752
+ function flushSync(fn) {
14753
+ return reconciler.flushSyncFromReconciler(fn);
14754
+ }
14755
+
14756
+ function parseBackground(background) {
14757
+ if (!background) return null;
14758
+ if (typeof background === "object" && !background.isColor) {
14759
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14760
+ return {
14761
+ ...rest,
14762
+ preset,
14763
+ files: envMap || files,
14764
+ backgroundFiles: backgroundMap,
14765
+ background: true
14766
+ };
14767
+ }
14768
+ if (typeof background === "number") {
14769
+ return { color: background, background: true };
14770
+ }
14771
+ if (typeof background === "string") {
14772
+ if (background in presetsObj) {
14773
+ return { preset: background, background: true };
14774
+ }
14775
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14776
+ return { files: background, background: true };
14777
+ }
14778
+ return { color: background, background: true };
14779
+ }
14780
+ if (background.isColor) {
14781
+ return { color: background, background: true };
14782
+ }
14783
+ return null;
14784
+ }
14785
+
14786
+ function parseRendererConfig(rendererProp) {
14787
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14788
+ if (isRendererConfig) {
14789
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14790
+ return {
14791
+ primaryCanvas: pc,
14792
+ scheduler: sc,
14793
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14794
+ };
14795
+ }
14796
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14797
+ }
14798
+
14799
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14800
+ const ROOT_SCOPE = "";
14801
+ const registries = /* @__PURE__ */ new WeakMap();
14802
+ function getKindRegistry(store, kind) {
14803
+ let registry = registries.get(store);
14804
+ if (!registry) {
14805
+ registry = {
14806
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14807
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14808
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14809
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14810
+ };
14811
+ registries.set(store, registry);
14812
+ }
14813
+ return registry[kind];
14814
+ }
14815
+ function resolvePrimary$1(store) {
14816
+ return store.getState().primaryStore ?? store;
14817
+ }
14818
+ function isScopeValid(store, kind, scopeKey) {
14819
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14820
+ }
14821
+ function peekStaged(store, kind, scopeKey) {
14822
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14823
+ }
14824
+ function stageEntries(store, kind, scopeKey, entries) {
14825
+ const { staged } = getKindRegistry(store, kind);
14826
+ const current = staged.get(scopeKey);
14827
+ if (current) Object.assign(current, entries);
14828
+ else staged.set(scopeKey, { ...entries });
14829
+ }
14830
+ function readCommittedScope(map, scopeKey, isLeaf) {
14831
+ if (scopeKey === ROOT_SCOPE) {
14832
+ const leaves = {};
14833
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14834
+ return leaves;
14835
+ }
14836
+ const scopeData = map[scopeKey];
14837
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14838
+ return {};
14839
+ }
14840
+ function withStagedOverlay(store, kind, committed) {
14841
+ const { staged } = getKindRegistry(store, kind);
14842
+ if (staged.size === 0) return committed;
14843
+ const view = { ...committed };
14844
+ for (const [scopeKey, entries] of staged) {
14845
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14846
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14847
+ }
14848
+ return view;
14849
+ }
14850
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14851
+ const registry = getKindRegistry(store, kind);
14852
+ const staged = registry.staged.get(scopeKey);
14853
+ if (!staged) return;
14854
+ registry.staged.delete(scopeKey);
14855
+ const replace = !registry.valid.has(scopeKey);
14856
+ store.setState((state) => {
14857
+ const map = state[kind];
14858
+ if (scopeKey === ROOT_SCOPE) {
14859
+ if (!replace) return { [kind]: { ...map, ...staged } };
14860
+ const next = {};
14861
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14862
+ return { [kind]: { ...next, ...staged } };
14863
+ }
14864
+ const current = replace ? {} : map[scopeKey] ?? {};
14865
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14866
+ });
14867
+ registry.valid.add(scopeKey);
14868
+ }
14869
+ function invalidateResource(store, kind, scopeKey) {
14870
+ const registry = getKindRegistry(store, kind);
14871
+ if (scopeKey === void 0) {
14872
+ registry.valid.clear();
14873
+ registry.staged.clear();
14874
+ } else {
14875
+ registry.valid.delete(scopeKey);
14876
+ registry.staged.delete(scopeKey);
14877
+ }
14878
+ }
14879
+ function rebuildResource(store, kind, userScope) {
14880
+ const primary = resolvePrimary$1(store);
14881
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14882
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14883
+ }
14884
+ function invalidateAllResources(store) {
14885
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14886
+ }
14887
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14888
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
14889
+ if (staged) for (const name of names) delete staged[name];
14890
+ store.setState((state) => {
14891
+ const map = state[kind];
14892
+ if (scope) {
14893
+ const currentScope = { ...map[scope] };
14894
+ for (const name of names) delete currentScope[name];
14895
+ return { [kind]: { ...map, [scope]: currentScope } };
14896
+ }
14897
+ const next = { ...map };
14898
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
14899
+ return { [kind]: next };
14900
+ });
15706
14901
  }
15707
- function flushSync(fn) {
15708
- return reconciler.flushSyncFromReconciler(fn);
14902
+ function clearResourceEntries(store, kind, scope, isLeaf) {
14903
+ const registry = getKindRegistry(store, kind);
14904
+ if (scope && scope !== "root") registry.staged.delete(scope);
14905
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
14906
+ else registry.staged.clear();
14907
+ store.setState((state) => {
14908
+ const map = state[kind];
14909
+ if (scope && scope !== "root") {
14910
+ const { [scope]: _, ...rest } = map;
14911
+ return { [kind]: rest };
14912
+ }
14913
+ if (scope === "root") {
14914
+ const next = {};
14915
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14916
+ return { [kind]: next };
14917
+ }
14918
+ return { [kind]: {} };
14919
+ });
14920
+ }
14921
+
14922
+ function clearHmrCaches(store) {
14923
+ const primary = store.getState().primaryStore ?? store;
14924
+ invalidateAllResources(primary);
14925
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
15709
14926
  }
15710
14927
 
15711
14928
  function CanvasImpl({
@@ -15728,6 +14945,8 @@ function CanvasImpl({
15728
14945
  raycaster,
15729
14946
  camera,
15730
14947
  scene,
14948
+ autoUpdateFrustum,
14949
+ occlusion,
15731
14950
  onPointerMissed,
15732
14951
  onDragOverMissed,
15733
14952
  onDropMissed,
@@ -15739,39 +14958,10 @@ function CanvasImpl({
15739
14958
  forceEven,
15740
14959
  ...props
15741
14960
  }) {
15742
- const { primaryCanvas, scheduler, ...rendererConfig } = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp) ? rendererProp : { primaryCanvas: void 0, scheduler: void 0 };
15743
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14961
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15744
14962
  React.useMemo(() => extend(THREE), []);
15745
14963
  const Bridge = useBridge();
15746
- const backgroundProps = React.useMemo(() => {
15747
- if (!background) return null;
15748
- if (typeof background === "object" && !background.isColor) {
15749
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15750
- return {
15751
- ...rest,
15752
- preset,
15753
- files: envMap || files,
15754
- backgroundFiles: backgroundMap,
15755
- background: true
15756
- };
15757
- }
15758
- if (typeof background === "number") {
15759
- return { color: background, background: true };
15760
- }
15761
- if (typeof background === "string") {
15762
- if (background in presetsObj) {
15763
- return { preset: background, background: true };
15764
- }
15765
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15766
- return { files: background, background: true };
15767
- }
15768
- return { color: background, background: true };
15769
- }
15770
- if (background.isColor) {
15771
- return { color: background, background: true };
15772
- }
15773
- return null;
15774
- }, [background]);
14964
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15775
14965
  const hasInitialSizeRef = React.useRef(false);
15776
14966
  const measureConfig = React.useMemo(() => {
15777
14967
  if (!hasInitialSizeRef.current) {
@@ -15813,6 +15003,7 @@ function CanvasImpl({
15813
15003
  const handleDropMissed = useMutableCallback(onDropMissed);
15814
15004
  const [block, setBlock] = React.useState(false);
15815
15005
  const [error, setError] = React.useState(false);
15006
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15816
15007
  if (block) throw block;
15817
15008
  if (error) throw error;
15818
15009
  const root = React.useRef(null);
@@ -15820,6 +15011,7 @@ function CanvasImpl({
15820
15011
  const unsubscribeErrorRef = React.useRef(null);
15821
15012
  useIsomorphicLayoutEffect(() => {
15822
15013
  effectActiveRef.current = true;
15014
+ if (fallbackVisible) return;
15823
15015
  const canvas = canvasRef.current;
15824
15016
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15825
15017
  if (!root.current) {
@@ -15840,7 +15032,7 @@ function CanvasImpl({
15840
15032
  }
15841
15033
  async function run() {
15842
15034
  if (!effectActiveRef.current || !root.current) return;
15843
- await root.current.configure({
15035
+ const configured = await root.current.configure({
15844
15036
  id,
15845
15037
  primaryCanvas,
15846
15038
  scheduler,
@@ -15855,6 +15047,8 @@ function CanvasImpl({
15855
15047
  performance,
15856
15048
  raycaster,
15857
15049
  camera,
15050
+ autoUpdateFrustum,
15051
+ occlusion,
15858
15052
  size: effectiveSize,
15859
15053
  // Store size props for reset functionality
15860
15054
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15879,8 +15073,20 @@ function CanvasImpl({
15879
15073
  }
15880
15074
  onCreated?.(state);
15881
15075
  }
15882
- });
15883
- if (!effectActiveRef.current || !root.current) return;
15076
+ }).then(
15077
+ () => true,
15078
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15079
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15080
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15081
+ (setupError) => {
15082
+ if (effectActiveRef.current) {
15083
+ if (fallback != null) setFallbackVisible(true);
15084
+ else setError(setupError);
15085
+ }
15086
+ return false;
15087
+ }
15088
+ );
15089
+ if (!configured || !effectActiveRef.current || !root.current) return;
15884
15090
  root.current.render(
15885
15091
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15886
15092
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15914,14 +15120,7 @@ function CanvasImpl({
15914
15120
  const handleHMR = () => {
15915
15121
  queueMicrotask(() => {
15916
15122
  const rootEntry = _roots.get(canvas);
15917
- if (rootEntry?.store) {
15918
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15919
- rootEntry.store.setState((state) => ({
15920
- nodes: {},
15921
- uniforms: {},
15922
- _hmrVersion: state._hmrVersion + 1
15923
- }));
15924
- }
15123
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15925
15124
  });
15926
15125
  };
15927
15126
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -15950,7 +15149,20 @@ function CanvasImpl({
15950
15149
  ...style
15951
15150
  },
15952
15151
  ...props,
15953
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx("canvas", { ref: canvasRef, id, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
15152
+ children: fallbackVisible ? (
15153
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15154
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15155
+ fallback
15156
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15157
+ "canvas",
15158
+ {
15159
+ ref: canvasRef,
15160
+ id,
15161
+ className: "r3f-canvas",
15162
+ style: { display: "block", width: "100%", height: "100%" },
15163
+ children: fallback
15164
+ }
15165
+ ) })
15954
15166
  }
15955
15167
  );
15956
15168
  }
@@ -16023,35 +15235,50 @@ let ScopedStore = _ScopedStore;
16023
15235
  function createScopedStore(data) {
16024
15236
  return new ScopedStore(data);
16025
15237
  }
16026
- function createLazyCreatorState(state) {
15238
+ function createLazyCreatorState(state, store) {
16027
15239
  let _uniforms = null;
16028
15240
  let _nodes = null;
16029
15241
  let _buffers = null;
16030
15242
  let _gpuStorage = null;
15243
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
16031
15244
  return Object.create(state, {
16032
15245
  uniforms: {
16033
15246
  get() {
16034
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15247
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
16035
15248
  }
16036
15249
  },
16037
15250
  nodes: {
16038
15251
  get() {
16039
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15252
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
16040
15253
  }
16041
15254
  },
16042
15255
  buffers: {
16043
15256
  get() {
16044
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15257
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
16045
15258
  }
16046
15259
  },
16047
15260
  gpuStorage: {
16048
15261
  get() {
16049
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15262
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
16050
15263
  }
16051
15264
  }
16052
15265
  });
16053
15266
  }
16054
15267
 
15268
+ function resolvePrimary(local) {
15269
+ return local.getState().primaryStore ?? local;
15270
+ }
15271
+ function usePrimaryStore() {
15272
+ const local = useStore();
15273
+ const primary = local.getState().primaryStore;
15274
+ return useMemo(() => primary ?? local, [primary, local]);
15275
+ }
15276
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15277
+ const local = useStore();
15278
+ const primary = resolvePrimary(local);
15279
+ return primary(selector, equalityFn);
15280
+ }
15281
+
16055
15282
  function addTexture(set, key, value) {
16056
15283
  set((state) => {
16057
15284
  const newMap = new Map(state.textures);
@@ -16155,65 +15382,56 @@ function useCompareMemoize(value, deep) {
16155
15382
  return ref.current;
16156
15383
  }
16157
15384
 
15385
+ function useScopedResource(options) {
15386
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15387
+ const scopeKey = scope ?? ROOT_SCOPE;
15388
+ const version = store((s) => s._hmrVersion);
15389
+ const entries = useMemo(() => {
15390
+ const staged = peekStaged(store, kind, scopeKey);
15391
+ const reusable = isScopeValid(store, kind, scopeKey);
15392
+ const map = store.getState()[kind];
15393
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15394
+ const result = {};
15395
+ let fresh = null;
15396
+ for (const [name, candidate] of Object.entries(create())) {
15397
+ const existing = staged?.[name] ?? committed?.[name];
15398
+ if (existing !== void 0) {
15399
+ result[name] = existing;
15400
+ reconcile?.(existing, candidate);
15401
+ } else {
15402
+ const value = prepare ? prepare(name, candidate) : candidate;
15403
+ result[name] = value;
15404
+ (fresh ?? (fresh = {}))[name] = value;
15405
+ }
15406
+ }
15407
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15408
+ return result;
15409
+ }, [store, kind, scopeKey, version, input]);
15410
+ useIsomorphicLayoutEffect(() => {
15411
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15412
+ });
15413
+ return entries;
15414
+ }
15415
+
16158
15416
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16159
15417
  function useUniforms(creatorOrScope, scope) {
16160
- const store = useStore();
15418
+ const store = usePrimaryStore();
16161
15419
  const removeUniforms2 = useCallback(
16162
- (names, targetScope) => {
16163
- const nameArray = Array.isArray(names) ? names : [names];
16164
- store.setState((state) => {
16165
- if (targetScope) {
16166
- const currentScope = { ...state.uniforms[targetScope] };
16167
- for (const name of nameArray) delete currentScope[name];
16168
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
16169
- }
16170
- const uniforms2 = { ...state.uniforms };
16171
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
16172
- return { uniforms: uniforms2 };
16173
- });
16174
- },
15420
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
16175
15421
  [store]
16176
15422
  );
16177
15423
  const clearUniforms = useCallback(
16178
- (targetScope) => {
16179
- store.setState((state) => {
16180
- if (targetScope && targetScope !== "root") {
16181
- const { [targetScope]: _, ...rest } = state.uniforms;
16182
- return { uniforms: rest };
16183
- }
16184
- if (targetScope === "root") {
16185
- const uniforms2 = {};
16186
- for (const [key, value] of Object.entries(state.uniforms)) {
16187
- if (!isUniformNode$1(value)) uniforms2[key] = value;
16188
- }
16189
- return { uniforms: uniforms2 };
16190
- }
16191
- return { uniforms: {} };
16192
- });
16193
- },
15424
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
16194
15425
  [store]
16195
15426
  );
16196
15427
  const rebuildUniforms = useCallback(
16197
- (targetScope) => {
16198
- store.setState((state) => {
16199
- let newUniforms = {};
16200
- if (targetScope && targetScope !== "root") {
16201
- const { [targetScope]: _, ...rest } = state.uniforms;
16202
- newUniforms = rest;
16203
- } else if (targetScope === "root") {
16204
- for (const [key, value] of Object.entries(state.uniforms)) {
16205
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16206
- }
16207
- }
16208
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16209
- });
16210
- },
15428
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
16211
15429
  [store]
16212
15430
  );
16213
15431
  const inputForMemoization = useMemo(() => {
16214
15432
  let raw = creatorOrScope;
16215
15433
  if (is.fun(creatorOrScope)) {
16216
- const wrappedState = createLazyCreatorState(store.getState());
15434
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16217
15435
  raw = creatorOrScope(wrappedState);
16218
15436
  }
16219
15437
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -16227,80 +15445,44 @@ function useUniforms(creatorOrScope, scope) {
16227
15445
  }, [creatorOrScope, store]);
16228
15446
  const memoizedInput = useCompareMemoize(inputForMemoization);
16229
15447
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16230
- const storeUniforms = useThree((s) => s.uniforms);
16231
- const hmrVersion = useThree((s) => s._hmrVersion);
16232
- const readerDep = isReader ? storeUniforms : null;
16233
- const creatorDep = isReader ? null : hmrVersion;
16234
- const uniforms = useMemo(() => {
16235
- if (memoizedInput === void 0) {
16236
- return storeUniforms;
16237
- }
16238
- if (typeof memoizedInput === "string") {
16239
- const scopeData = storeUniforms[memoizedInput];
16240
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
16241
- return {};
16242
- }
16243
- const state = store.getState();
16244
- const set = store.setState;
16245
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
16246
- throw new Error("Invalid uniform input");
16247
- }
16248
- const created = memoizedInput;
16249
- const result = {};
16250
- let hasNewUniforms = false;
16251
- let targetRecord = state.uniforms;
16252
- if (scope) {
16253
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
16254
- targetRecord = state.uniforms[scope];
16255
- }
16256
- for (const [name, node] of Object.entries(created)) {
16257
- if (targetRecord[name]) {
16258
- result[name] = targetRecord[name];
16259
- const existingVal = result[name].value;
16260
- const newVal = vectorize(node);
16261
- let equals = newVal === existingVal;
16262
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
16263
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
16264
- equals = vectorEquals(existingVal, newVal);
16265
- } else if (isSameThreeType(existingVal, newVal)) {
16266
- equals = existingVal.equals(newVal);
16267
- }
15448
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15449
+ const created = useScopedResource({
15450
+ store,
15451
+ kind: "uniforms",
15452
+ scope: isReader ? void 0 : scope,
15453
+ isLeaf: isUniformNode$1,
15454
+ input: memoizedInput,
15455
+ create: () => {
15456
+ if (isReader) return {};
15457
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15458
+ return memoizedInput;
15459
+ },
15460
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15461
+ reconcile: (existing, candidate) => {
15462
+ const existingVal = existing.value;
15463
+ const newVal = vectorize(candidate);
15464
+ let equals = newVal === existingVal;
15465
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15466
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15467
+ equals = vectorEquals(existingVal, newVal);
15468
+ } else if (isSameThreeType(existingVal, newVal)) {
15469
+ equals = existingVal.equals(newVal);
16268
15470
  }
16269
- if (!equals) result[name].value = newVal;
16270
- } else {
16271
- result[name] = createUniform(name, node, scope);
16272
- hasNewUniforms = true;
16273
- }
16274
- }
16275
- if (hasNewUniforms) {
16276
- if (scope) {
16277
- set((s) => ({
16278
- uniforms: {
16279
- ...s.uniforms,
16280
- [scope]: { ...s.uniforms[scope], ...result }
16281
- }
16282
- }));
16283
- } else {
16284
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
16285
15471
  }
15472
+ if (!equals) existing.value = newVal;
16286
15473
  }
16287
- return result;
16288
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15474
+ });
15475
+ let uniforms = created;
15476
+ if (memoizedInput === void 0) {
15477
+ uniforms = storeUniforms;
15478
+ } else if (typeof memoizedInput === "string") {
15479
+ const scopeData = storeUniforms[memoizedInput];
15480
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15481
+ }
16289
15482
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16290
15483
  }
16291
15484
  function rebuildAllUniforms(store, scope) {
16292
- store.setState((state) => {
16293
- let newUniforms = {};
16294
- if (scope && scope !== "root") {
16295
- const { [scope]: _, ...rest } = state.uniforms;
16296
- newUniforms = rest;
16297
- } else if (scope === "root") {
16298
- for (const [key, value] of Object.entries(state.uniforms)) {
16299
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16300
- }
16301
- }
16302
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16303
- });
15485
+ rebuildResource(store, "uniforms", scope);
16304
15486
  }
16305
15487
  function removeUniforms(set, names, scope) {
16306
15488
  set((state) => {
@@ -16364,191 +15546,91 @@ function isSameThreeType(a, b) {
16364
15546
  return obj_a.isColor && obj_b.isColor || obj_a.isMatrix3 && obj_b.isMatrix3 || obj_a.isMatrix4 && obj_b.isMatrix4 || obj_a.isEuler && obj_b.isEuler || obj_a.isQuaternion && obj_b.isQuaternion;
16365
15547
  }
16366
15548
 
15549
+ const uniformOf = uniform;
16367
15550
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16368
15551
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16369
15552
  function useUniform(name, value) {
16370
15553
  const store = useStore();
16371
- const hmrVersion = useThree((s) => s._hmrVersion);
16372
- return useMemo(() => {
16373
- const state = store.getState();
16374
- const set = store.setState;
16375
- const existing = state.uniforms[name];
16376
- if (existing && isUniformNode(existing)) {
15554
+ const registered = useScopedResource({
15555
+ store,
15556
+ kind: "uniforms",
15557
+ scope: void 0,
15558
+ isLeaf: isUniformNode,
15559
+ input: name,
15560
+ create: () => value === void 0 ? {} : { [name]: value },
15561
+ prepare: createNamedUniform,
15562
+ reconcile: (existing2) => {
16377
15563
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
16378
- existing.value = typeof value === "string" ? new Color(value) : value;
15564
+ existing2.value = typeof value === "string" ? new Color(value) : value;
16379
15565
  }
16380
- return existing;
16381
- }
16382
- if (value === void 0) {
16383
- throw new Error(
16384
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
16385
- );
16386
- }
16387
- if (isUniformNode(value)) {
16388
- const node2 = value;
16389
- if (typeof node2.setName === "function") {
16390
- node2.setName(name);
16391
- }
16392
- set((s) => ({
16393
- uniforms: { ...s.uniforms, [name]: node2 }
16394
- }));
16395
- return node2;
16396
- }
16397
- let node;
16398
- if (isTSLNode$1(value)) {
16399
- node = uniform(value);
16400
- } else if (typeof value === "string") {
16401
- node = uniform(new Color(value));
16402
- } else {
16403
- node = uniform(value);
16404
- }
16405
- if (typeof node.setName === "function") {
16406
- node.setName(name);
16407
15566
  }
16408
- set((s) => ({
16409
- uniforms: {
16410
- ...s.uniforms,
16411
- [name]: node
16412
- }
16413
- }));
16414
- return node;
16415
- }, [store, name, hmrVersion]);
15567
+ });
15568
+ if (registered[name]) return registered[name];
15569
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15570
+ if (existing && isUniformNode(existing)) return existing;
15571
+ throw new Error(
15572
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15573
+ );
15574
+ }
15575
+ function createNamedUniform(name, value) {
15576
+ let node;
15577
+ if (isUniformNode(value)) {
15578
+ node = value;
15579
+ } else if (isTSLNode$1(value)) {
15580
+ node = uniformOf(value);
15581
+ } else if (typeof value === "string") {
15582
+ node = uniform(new Color(value));
15583
+ } else {
15584
+ node = uniformOf(value);
15585
+ }
15586
+ if (typeof node.setName === "function") {
15587
+ node.setName(name);
15588
+ }
15589
+ return node;
16416
15590
  }
16417
15591
 
16418
15592
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16419
15593
  function useNodes(creatorOrScope, scope) {
16420
- const store = useStore();
15594
+ const store = usePrimaryStore();
16421
15595
  const removeNodes2 = useCallback(
16422
- (names, targetScope) => {
16423
- const nameArray = Array.isArray(names) ? names : [names];
16424
- store.setState((state) => {
16425
- if (targetScope) {
16426
- const currentScope = { ...state.nodes[targetScope] };
16427
- for (const name of nameArray) delete currentScope[name];
16428
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
16429
- }
16430
- const nodes2 = { ...state.nodes };
16431
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
16432
- return { nodes: nodes2 };
16433
- });
16434
- },
15596
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
16435
15597
  [store]
16436
15598
  );
16437
15599
  const clearNodes = useCallback(
16438
- (targetScope) => {
16439
- store.setState((state) => {
16440
- if (targetScope && targetScope !== "root") {
16441
- const { [targetScope]: _, ...rest } = state.nodes;
16442
- return { nodes: rest };
16443
- }
16444
- if (targetScope === "root") {
16445
- const nodes2 = {};
16446
- for (const [key, value] of Object.entries(state.nodes)) {
16447
- if (!isTSLNode(value)) nodes2[key] = value;
16448
- }
16449
- return { nodes: nodes2 };
16450
- }
16451
- return { nodes: {} };
16452
- });
16453
- },
15600
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
16454
15601
  [store]
16455
15602
  );
16456
15603
  const rebuildNodes = useCallback(
16457
- (targetScope) => {
16458
- store.setState((state) => {
16459
- let newNodes = state.nodes;
16460
- if (targetScope && targetScope !== "root") {
16461
- const { [targetScope]: _, ...rest } = state.nodes;
16462
- newNodes = rest;
16463
- } else if (targetScope === "root") {
16464
- newNodes = {};
16465
- for (const [key, value] of Object.entries(state.nodes)) {
16466
- if (!isTSLNode(value)) newNodes[key] = value;
16467
- }
16468
- } else {
16469
- newNodes = {};
16470
- }
16471
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16472
- });
16473
- },
15604
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
16474
15605
  [store]
16475
15606
  );
16476
15607
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16477
- const storeNodes = useThree((s) => s.nodes);
16478
- const hmrVersion = useThree((s) => s._hmrVersion);
16479
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16480
- const readerDep = isReader ? storeNodes : null;
16481
- const creatorDep = isReader ? null : hmrVersion;
16482
- const nodes = useMemo(() => {
16483
- if (creatorOrScope === void 0) {
16484
- return storeNodes;
16485
- }
16486
- if (typeof creatorOrScope === "string") {
16487
- const scopeData = storeNodes[creatorOrScope];
16488
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
16489
- return {};
16490
- }
16491
- const state = store.getState();
16492
- const set = store.setState;
16493
- const creator = creatorOrScope;
16494
- const wrappedState = createLazyCreatorState(state);
16495
- const created = creator(wrappedState);
16496
- const result = {};
16497
- let hasNewNodes = false;
16498
- if (scope) {
16499
- const currentScope = state.nodes[scope] ?? {};
16500
- for (const [name, node] of Object.entries(created)) {
16501
- if (currentScope[name]) {
16502
- result[name] = currentScope[name];
16503
- } else {
16504
- node.setName?.(`${scope}.${name}`);
16505
- result[name] = node;
16506
- hasNewNodes = true;
16507
- }
16508
- }
16509
- if (hasNewNodes) {
16510
- set((s) => ({
16511
- nodes: {
16512
- ...s.nodes,
16513
- [scope]: { ...s.nodes[scope], ...result }
16514
- }
16515
- }));
16516
- }
16517
- return result;
16518
- }
16519
- for (const [name, node] of Object.entries(created)) {
16520
- const existing = state.nodes[name];
16521
- if (existing && isTSLNode(existing)) {
16522
- result[name] = existing;
16523
- } else {
16524
- node.setName?.(name);
16525
- result[name] = node;
16526
- hasNewNodes = true;
16527
- }
16528
- }
16529
- if (hasNewNodes) {
16530
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15608
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15609
+ const created = useScopedResource({
15610
+ store,
15611
+ kind: "nodes",
15612
+ scope: isReader ? void 0 : scope,
15613
+ isLeaf: isTSLNode,
15614
+ create: () => {
15615
+ if (isReader) return {};
15616
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15617
+ },
15618
+ prepare: (name, node) => {
15619
+ node.setName?.(scope ? `${scope}.${name}` : name);
15620
+ return node;
16531
15621
  }
16532
- return result;
16533
- }, [store, scopeDep, readerDep, creatorDep]);
15622
+ });
15623
+ let nodes = created;
15624
+ if (creatorOrScope === void 0) {
15625
+ nodes = storeNodes;
15626
+ } else if (typeof creatorOrScope === "string") {
15627
+ const scopeData = storeNodes[creatorOrScope];
15628
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15629
+ }
16534
15630
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16535
15631
  }
16536
15632
  function rebuildAllNodes(store, scope) {
16537
- store.setState((state) => {
16538
- let newNodes = state.nodes;
16539
- if (scope && scope !== "root") {
16540
- const { [scope]: _, ...rest } = state.nodes;
16541
- newNodes = rest;
16542
- } else if (scope === "root") {
16543
- newNodes = {};
16544
- for (const [key, value] of Object.entries(state.nodes)) {
16545
- if (!isTSLNode(value)) newNodes[key] = value;
16546
- }
16547
- } else {
16548
- newNodes = {};
16549
- }
16550
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16551
- });
15633
+ rebuildResource(store, "nodes", scope);
16552
15634
  }
16553
15635
  function removeNodes(set, names, scope) {
16554
15636
  set((state) => {
@@ -16578,13 +15660,13 @@ function clearRootNodes(set) {
16578
15660
  });
16579
15661
  }
16580
15662
  function useLocalNodes(creator) {
16581
- const store = useStore();
16582
- const uniforms = useThree((s) => s.uniforms);
16583
- const nodes = useThree((s) => s.nodes);
16584
- const textures = useThree((s) => s.textures);
16585
- const hmrVersion = useThree((s) => s._hmrVersion);
15663
+ const store = usePrimaryStore();
15664
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15665
+ const nodes = usePrimaryThree((s) => s.nodes);
15666
+ const textures = usePrimaryThree((s) => s.textures);
15667
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16586
15668
  return useMemo(() => {
16587
- const wrappedState = createLazyCreatorState(store.getState());
15669
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16588
15670
  return creator(wrappedState);
16589
15671
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
16590
15672
  }
@@ -16603,60 +15685,17 @@ const disposeBuffer = (buffer) => {
16603
15685
  }
16604
15686
  };
16605
15687
  function useBuffers(creatorOrScope, scope) {
16606
- const store = useStore();
15688
+ const store = usePrimaryStore();
16607
15689
  const removeBuffers = useCallback(
16608
- (names, targetScope) => {
16609
- const nameArray = Array.isArray(names) ? names : [names];
16610
- store.setState((state) => {
16611
- if (targetScope) {
16612
- const currentScope = { ...state.buffers[targetScope] };
16613
- for (const name of nameArray) delete currentScope[name];
16614
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
16615
- }
16616
- const buffers2 = { ...state.buffers };
16617
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
16618
- return { buffers: buffers2 };
16619
- });
16620
- },
15690
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
16621
15691
  [store]
16622
15692
  );
16623
15693
  const clearBuffers = useCallback(
16624
- (targetScope) => {
16625
- store.setState((state) => {
16626
- if (targetScope && targetScope !== "root") {
16627
- const { [targetScope]: _, ...rest } = state.buffers;
16628
- return { buffers: rest };
16629
- }
16630
- if (targetScope === "root") {
16631
- const buffers2 = {};
16632
- for (const [key, value] of Object.entries(state.buffers)) {
16633
- if (!isBufferLike(value)) buffers2[key] = value;
16634
- }
16635
- return { buffers: buffers2 };
16636
- }
16637
- return { buffers: {} };
16638
- });
16639
- },
15694
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
16640
15695
  [store]
16641
15696
  );
16642
15697
  const rebuildBuffers = useCallback(
16643
- (targetScope) => {
16644
- store.setState((state) => {
16645
- let newBuffers = state.buffers;
16646
- if (targetScope && targetScope !== "root") {
16647
- const { [targetScope]: _, ...rest } = state.buffers;
16648
- newBuffers = rest;
16649
- } else if (targetScope === "root") {
16650
- newBuffers = {};
16651
- for (const [key, value] of Object.entries(state.buffers)) {
16652
- if (!isBufferLike(value)) newBuffers[key] = value;
16653
- }
16654
- } else {
16655
- newBuffers = {};
16656
- }
16657
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16658
- });
16659
- },
15698
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
16660
15699
  [store]
16661
15700
  );
16662
15701
  const disposeBuffers = useCallback(
@@ -16674,85 +15713,34 @@ function useBuffers(creatorOrScope, scope) {
16674
15713
  [store, removeBuffers]
16675
15714
  );
16676
15715
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16677
- const storeBuffers = useThree((s) => s.buffers);
16678
- const hmrVersion = useThree((s) => s._hmrVersion);
16679
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16680
- const readerDep = isReader ? storeBuffers : null;
16681
- const creatorDep = isReader ? null : hmrVersion;
16682
- const buffers = useMemo(() => {
16683
- if (creatorOrScope === void 0) {
16684
- return storeBuffers;
16685
- }
16686
- if (typeof creatorOrScope === "string") {
16687
- const scopeData = storeBuffers[creatorOrScope];
16688
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
16689
- return {};
16690
- }
16691
- const state = store.getState();
16692
- const set = store.setState;
16693
- const creator = creatorOrScope;
16694
- const wrappedState = createLazyCreatorState(state);
16695
- const created = creator(wrappedState);
16696
- const result = {};
16697
- let hasNewBuffers = false;
16698
- if (scope) {
16699
- const currentScope = state.buffers[scope] ?? {};
16700
- for (const [name, buffer] of Object.entries(created)) {
16701
- if (currentScope[name]) {
16702
- result[name] = currentScope[name];
16703
- } else {
16704
- if ("setName" in buffer && typeof buffer.setName === "function") {
16705
- buffer.setName(`${scope}.${name}`);
16706
- }
16707
- result[name] = buffer;
16708
- hasNewBuffers = true;
16709
- }
16710
- }
16711
- if (hasNewBuffers) {
16712
- set((s) => ({
16713
- buffers: {
16714
- ...s.buffers,
16715
- [scope]: { ...s.buffers[scope], ...result }
16716
- }
16717
- }));
16718
- }
16719
- return result;
16720
- }
16721
- for (const [name, buffer] of Object.entries(created)) {
16722
- const existing = state.buffers[name];
16723
- if (existing && isBufferLike(existing)) {
16724
- result[name] = existing;
16725
- } else {
16726
- if ("setName" in buffer && typeof buffer.setName === "function") {
16727
- buffer.setName(name);
16728
- }
16729
- result[name] = buffer;
16730
- hasNewBuffers = true;
15716
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15717
+ const created = useScopedResource({
15718
+ store,
15719
+ kind: "buffers",
15720
+ scope: isReader ? void 0 : scope,
15721
+ isLeaf: isBufferLike,
15722
+ create: () => {
15723
+ if (isReader) return {};
15724
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15725
+ },
15726
+ prepare: (name, buffer) => {
15727
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15728
+ buffer.setName(scope ? `${scope}.${name}` : name);
16731
15729
  }
15730
+ return buffer;
16732
15731
  }
16733
- if (hasNewBuffers) {
16734
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
16735
- }
16736
- return result;
16737
- }, [store, scopeDep, readerDep, creatorDep]);
15732
+ });
15733
+ let buffers = created;
15734
+ if (creatorOrScope === void 0) {
15735
+ buffers = storeBuffers;
15736
+ } else if (typeof creatorOrScope === "string") {
15737
+ const scopeData = storeBuffers[creatorOrScope];
15738
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15739
+ }
16738
15740
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16739
15741
  }
16740
15742
  function rebuildAllBuffers(store, scope) {
16741
- store.setState((state) => {
16742
- let newBuffers = state.buffers;
16743
- if (scope && scope !== "root") {
16744
- const { [scope]: _, ...rest } = state.buffers;
16745
- newBuffers = rest;
16746
- } else if (scope === "root") {
16747
- newBuffers = {};
16748
- for (const [key, value] of Object.entries(state.buffers)) {
16749
- if (!isBufferLike(value)) newBuffers[key] = value;
16750
- }
16751
- } else {
16752
- newBuffers = {};
16753
- }
16754
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16755
- });
15743
+ rebuildResource(store, "buffers", scope);
16756
15744
  }
16757
15745
 
16758
15746
  const isStorageLike = (value) => {
@@ -16769,60 +15757,17 @@ const disposeStorage = (storage) => {
16769
15757
  }
16770
15758
  };
16771
15759
  function useGPUStorage(creatorOrScope, scope) {
16772
- const store = useStore();
15760
+ const store = usePrimaryStore();
16773
15761
  const removeStorage = useCallback(
16774
- (names, targetScope) => {
16775
- const nameArray = Array.isArray(names) ? names : [names];
16776
- store.setState((state) => {
16777
- if (targetScope) {
16778
- const currentScope = { ...state.gpuStorage[targetScope] };
16779
- for (const name of nameArray) delete currentScope[name];
16780
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
16781
- }
16782
- const gpuStorage2 = { ...state.gpuStorage };
16783
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
16784
- return { gpuStorage: gpuStorage2 };
16785
- });
16786
- },
15762
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
16787
15763
  [store]
16788
15764
  );
16789
15765
  const clearStorage = useCallback(
16790
- (targetScope) => {
16791
- store.setState((state) => {
16792
- if (targetScope && targetScope !== "root") {
16793
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16794
- return { gpuStorage: rest };
16795
- }
16796
- if (targetScope === "root") {
16797
- const gpuStorage2 = {};
16798
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16799
- if (!isStorageLike(value)) gpuStorage2[key] = value;
16800
- }
16801
- return { gpuStorage: gpuStorage2 };
16802
- }
16803
- return { gpuStorage: {} };
16804
- });
16805
- },
15766
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
16806
15767
  [store]
16807
15768
  );
16808
15769
  const rebuildStorage = useCallback(
16809
- (targetScope) => {
16810
- store.setState((state) => {
16811
- let newStorage = state.gpuStorage;
16812
- if (targetScope && targetScope !== "root") {
16813
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16814
- newStorage = rest;
16815
- } else if (targetScope === "root") {
16816
- newStorage = {};
16817
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16818
- if (!isStorageLike(value)) newStorage[key] = value;
16819
- }
16820
- } else {
16821
- newStorage = {};
16822
- }
16823
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16824
- });
16825
- },
15770
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
16826
15771
  [store]
16827
15772
  );
16828
15773
  const disposeStorageFn = useCallback(
@@ -16840,73 +15785,34 @@ function useGPUStorage(creatorOrScope, scope) {
16840
15785
  [store, removeStorage]
16841
15786
  );
16842
15787
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16843
- const storeStorage = useThree((s) => s.gpuStorage);
16844
- const hmrVersion = useThree((s) => s._hmrVersion);
16845
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16846
- const readerDep = isReader ? storeStorage : null;
16847
- const creatorDep = isReader ? null : hmrVersion;
16848
- const gpuStorage = useMemo(() => {
16849
- if (creatorOrScope === void 0) {
16850
- return storeStorage;
16851
- }
16852
- if (typeof creatorOrScope === "string") {
16853
- const scopeData = storeStorage[creatorOrScope];
16854
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
16855
- return {};
16856
- }
16857
- const state = store.getState();
16858
- const set = store.setState;
16859
- const creator = creatorOrScope;
16860
- const wrappedState = createLazyCreatorState(state);
16861
- const created = creator(wrappedState);
16862
- const result = {};
16863
- let hasNewStorage = false;
16864
- if (scope) {
16865
- const currentScope = state.gpuStorage[scope] ?? {};
16866
- for (const [name, storage] of Object.entries(created)) {
16867
- if (currentScope[name]) {
16868
- result[name] = currentScope[name];
16869
- } else {
16870
- if ("setName" in storage && typeof storage.setName === "function") {
16871
- storage.setName(`${scope}.${name}`);
16872
- }
16873
- if ("name" in storage && typeof storage.name === "string") {
16874
- storage.name = `${scope}.${name}`;
16875
- }
16876
- result[name] = storage;
16877
- hasNewStorage = true;
16878
- }
16879
- }
16880
- if (hasNewStorage) {
16881
- set((s) => ({
16882
- gpuStorage: {
16883
- ...s.gpuStorage,
16884
- [scope]: { ...s.gpuStorage[scope], ...result }
16885
- }
16886
- }));
15788
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15789
+ const created = useScopedResource({
15790
+ store,
15791
+ kind: "gpuStorage",
15792
+ scope: isReader ? void 0 : scope,
15793
+ isLeaf: isStorageLike,
15794
+ create: () => {
15795
+ if (isReader) return {};
15796
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15797
+ },
15798
+ prepare: (name, storage) => {
15799
+ const label = scope ? `${scope}.${name}` : name;
15800
+ if ("setName" in storage && typeof storage.setName === "function") {
15801
+ storage.setName(label);
16887
15802
  }
16888
- return result;
16889
- }
16890
- for (const [name, storage] of Object.entries(created)) {
16891
- const existing = state.gpuStorage[name];
16892
- if (existing && isStorageLike(existing)) {
16893
- result[name] = existing;
16894
- } else {
16895
- if ("setName" in storage && typeof storage.setName === "function") {
16896
- storage.setName(name);
16897
- }
16898
- if ("name" in storage && typeof storage.name === "string") {
16899
- storage.name = name;
16900
- }
16901
- result[name] = storage;
16902
- hasNewStorage = true;
15803
+ if ("name" in storage && typeof storage.name === "string") {
15804
+ storage.name = label;
16903
15805
  }
15806
+ return storage;
16904
15807
  }
16905
- if (hasNewStorage) {
16906
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
16907
- }
16908
- return result;
16909
- }, [store, scopeDep, readerDep, creatorDep]);
15808
+ });
15809
+ let gpuStorage = created;
15810
+ if (creatorOrScope === void 0) {
15811
+ gpuStorage = storeStorage;
15812
+ } else if (typeof creatorOrScope === "string") {
15813
+ const scopeData = storeStorage[creatorOrScope];
15814
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15815
+ }
16910
15816
  return {
16911
15817
  ...gpuStorage,
16912
15818
  removeStorage,
@@ -16916,21 +15822,7 @@ function useGPUStorage(creatorOrScope, scope) {
16916
15822
  };
16917
15823
  }
16918
15824
  function rebuildAllStorage(store, scope) {
16919
- store.setState((state) => {
16920
- let newStorage = state.gpuStorage;
16921
- if (scope && scope !== "root") {
16922
- const { [scope]: _, ...rest } = state.gpuStorage;
16923
- newStorage = rest;
16924
- } else if (scope === "root") {
16925
- newStorage = {};
16926
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16927
- if (!isStorageLike(value)) newStorage[key] = value;
16928
- }
16929
- } else {
16930
- newStorage = {};
16931
- }
16932
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16933
- });
15825
+ rebuildResource(store, "gpuStorage", scope);
16934
15826
  }
16935
15827
 
16936
15828
  function useRenderPipeline(mainCB, setupCB) {
@@ -16971,12 +15863,12 @@ function useRenderPipeline(mainCB, setupCB) {
16971
15863
  const state = store.getState();
16972
15864
  const set = store.setState;
16973
15865
  try {
16974
- let pp = state.renderPipeline;
15866
+ let pipeline = state.renderPipeline;
16975
15867
  let currentPasses = { ...state.passes };
16976
- let justCreatedPP = false;
16977
- if (!pp) {
16978
- pp = new PostProcessing(renderer);
16979
- justCreatedPP = true;
15868
+ let justCreatedPipeline = false;
15869
+ if (!pipeline) {
15870
+ pipeline = new RenderPipeline(renderer);
15871
+ justCreatedPipeline = true;
16980
15872
  }
16981
15873
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
16982
15874
  let scenePass;
@@ -16987,9 +15879,9 @@ function useRenderPipeline(mainCB, setupCB) {
16987
15879
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
16988
15880
  }
16989
15881
  currentPasses.scenePass = scenePass;
16990
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
16991
- set({ renderPipeline: pp, passes: currentPasses });
16992
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15882
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15883
+ set({ renderPipeline: pipeline, passes: currentPasses });
15884
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
16993
15885
  if (shouldRunCallbacks) {
16994
15886
  if (setupCBRef.current) {
16995
15887
  const freshState = store.getState();
@@ -17010,7 +15902,7 @@ function useRenderPipeline(mainCB, setupCB) {
17010
15902
  callbacksRanRef.current = true;
17011
15903
  }
17012
15904
  } catch (error) {
17013
- console.error("[useRenderPipeline] Setup error:", error);
15905
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17014
15906
  }
17015
15907
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17016
15908
  const passes = useThree((s) => s.passes);
@@ -17028,4 +15920,4 @@ function useRenderPipeline(mainCB, setupCB) {
17028
15920
 
17029
15921
  extend(THREE);
17030
15922
 
17031
- 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, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, 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, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
15923
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, 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, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };