@react-three/fiber 10.0.0-canary.b0fafc8 → 10.0.0-canary.bc9af3b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/legacy.cjs CHANGED
@@ -13,6 +13,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
13
13
  const gainmapJs = require('@monogrid/gainmap-js');
14
14
  const Tb = require('scheduler');
15
15
  const traditional = require('zustand/traditional');
16
+ const scheduler = require('@pmndrs/scheduler');
16
17
  const suspendReact = require('suspend-react');
17
18
 
18
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -61,9 +62,12 @@ const WebGPURenderer = class WebGPURenderer2 {
61
62
  }
62
63
  };
63
64
  const RenderTarget = null;
65
+ const CubeRenderTarget = null;
64
66
 
65
67
  const THREE = /*#__PURE__*/_mergeNamespaces({
66
68
  __proto__: null,
69
+ CubeRenderTarget: CubeRenderTarget,
70
+ CubeRenderTargetCompat: three.WebGLCubeRenderTarget,
67
71
  Inspector: Inspector,
68
72
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
69
73
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
@@ -169,7 +173,7 @@ function useEnvironment({
169
173
  fiber.useLoader.clear(loader, multiFile ? [files] : files);
170
174
  }
171
175
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
172
- }, [files, renderer.domElement]);
176
+ }, [extension, files, loader, multiFile, renderer.domElement]);
173
177
  const loaderResult = fiber.useLoader(
174
178
  loader,
175
179
  multiFile ? [files] : files,
@@ -341,15 +345,16 @@ function EnvironmentPortal({
341
345
  preset = void 0,
342
346
  extensions
343
347
  }) {
344
- const gl = fiber.useThree((state) => state.gl);
348
+ const renderer = fiber.useThree((state) => state.renderer);
349
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
345
350
  const defaultScene = fiber.useThree((state) => state.scene);
346
351
  const camera = React__namespace.useRef(null);
347
352
  const [virtualScene] = React__namespace.useState(() => new three.Scene());
348
353
  const fbo = React__namespace.useMemo(() => {
349
- const fbo2 = new three.WebGLCubeRenderTarget(resolution);
354
+ const fbo2 = isLegacy ? new three.WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
350
355
  fbo2.texture.type = three.HalfFloatType;
351
356
  return fbo2;
352
- }, [resolution]);
357
+ }, [resolution, isLegacy]);
353
358
  React__namespace.useEffect(() => {
354
359
  return () => {
355
360
  fbo.dispose();
@@ -357,10 +362,10 @@ function EnvironmentPortal({
357
362
  }, [fbo]);
358
363
  React__namespace.useLayoutEffect(() => {
359
364
  if (frames === 1) {
360
- const autoClear = gl.autoClear;
361
- gl.autoClear = true;
362
- camera.current.update(gl, virtualScene);
363
- gl.autoClear = autoClear;
365
+ const autoClear = renderer.autoClear;
366
+ renderer.autoClear = true;
367
+ camera.current.update(renderer, virtualScene);
368
+ renderer.autoClear = autoClear;
364
369
  }
365
370
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
366
371
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -369,14 +374,29 @@ function EnvironmentPortal({
369
374
  environmentIntensity,
370
375
  environmentRotation
371
376
  });
372
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
377
+ }, [
378
+ children,
379
+ virtualScene,
380
+ fbo.texture,
381
+ scene,
382
+ defaultScene,
383
+ background,
384
+ frames,
385
+ renderer,
386
+ blur,
387
+ backgroundBlurriness,
388
+ backgroundIntensity,
389
+ backgroundRotation,
390
+ environmentIntensity,
391
+ environmentRotation
392
+ ]);
373
393
  let count = 1;
374
394
  fiber.useFrame(() => {
375
395
  if (frames === Infinity || count < frames) {
376
- const autoClear = gl.autoClear;
377
- gl.autoClear = true;
378
- camera.current.update(gl, virtualScene);
379
- gl.autoClear = autoClear;
396
+ const autoClear = renderer.autoClear;
397
+ renderer.autoClear = true;
398
+ camera.current.update(renderer, virtualScene);
399
+ renderer.autoClear = autoClear;
380
400
  count++;
381
401
  }
382
402
  });
@@ -440,9 +460,9 @@ function Environment(props) {
440
460
  return props.ground ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props });
441
461
  }
442
462
 
443
- var __defProp$2 = Object.defineProperty;
444
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
445
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
463
+ var __defProp = Object.defineProperty;
464
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
465
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
446
466
  const act = React__namespace["act"];
447
467
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
448
468
  function useMutableCallback(fn) {
@@ -474,7 +494,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
474
494
  return _a = class extends React__namespace.Component {
475
495
  constructor() {
476
496
  super(...arguments);
477
- __publicField$2(this, "state", { error: false });
497
+ __publicField(this, "state", { error: false });
478
498
  }
479
499
  componentDidCatch(err) {
480
500
  this.props.set(err);
@@ -482,7 +502,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
482
502
  render() {
483
503
  return this.state.error ? null : this.props.children;
484
504
  }
485
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
505
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
506
  })();
487
507
 
488
508
  const is = {
@@ -619,8 +639,7 @@ function prepare(target, root, type, props) {
619
639
  object,
620
640
  eventCount: 0,
621
641
  handlers: {},
622
- isHidden: false,
623
- deferredRefs: []
642
+ isHidden: false
624
643
  };
625
644
  if (object) object.__r3f = instance;
626
645
  }
@@ -777,6 +796,17 @@ function unregisterVisibility(store, object) {
777
796
  internal.visibilityRegistry.delete(object.uuid);
778
797
  internal.occlusionCache.delete(object);
779
798
  }
799
+ function updateVisibilityHandlers(store, object, handlers) {
800
+ const { internal } = store.getState();
801
+ const entry = internal.visibilityRegistry.get(object.uuid);
802
+ if (!entry) return false;
803
+ entry.handlers = handlers;
804
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
805
+ object.occlusionTest = true;
806
+ enableOcclusion(store);
807
+ }
808
+ return true;
809
+ }
780
810
  function checkVisibility(state) {
781
811
  const { internal, camera } = state;
782
812
  const registry = internal.visibilityRegistry;
@@ -964,10 +994,7 @@ function applyProps(object, props) {
964
994
  continue;
965
995
  }
966
996
  if (value === void 0) continue;
967
- if (isFromRef(value)) {
968
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
969
- continue;
970
- }
997
+ if (isFromRef(value)) continue;
971
998
  if (isOnce(value)) {
972
999
  if (instance?.appliedOnce?.has(prop)) continue;
973
1000
  if (instance) {
@@ -1003,8 +1030,24 @@ function applyProps(object, props) {
1003
1030
  } else if (isVectorLike(target) && is.num(value)) {
1004
1031
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1005
1032
  else target.set(value);
1033
+ } else if (root instanceof three.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1034
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1035
+ const uniforms = root.uniforms;
1036
+ const nextUniforms = value;
1037
+ for (const name in nextUniforms) {
1038
+ const uniform = nextUniforms[name];
1039
+ const targetUniform = uniforms[name];
1040
+ if (targetUniform) Object.assign(targetUniform, uniform);
1041
+ else {
1042
+ const nextUniform = uniform instanceof three.Uniform ? uniform.clone() : new three.Uniform(uniform.value);
1043
+ uniforms[name] = nextUniform;
1044
+ }
1045
+ }
1006
1046
  } else {
1007
1047
  root[key] = value;
1048
+ if (key.endsWith("Node") && root.isMaterial) {
1049
+ root.needsUpdate = true;
1050
+ }
1008
1051
  if (rootState && rootState.renderer?.outputColorSpace === three.SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
1009
1052
  root[key].format === three.RGBAFormat && root[key].type === three.UnsignedByteType) {
1010
1053
  root[key].colorSpace = rootState.textureColorSpace;
@@ -1018,6 +1061,9 @@ function applyProps(object, props) {
1018
1061
  if (instance.eventCount && object2.raycast !== null) {
1019
1062
  rootState.internal.interaction.push(object2);
1020
1063
  }
1064
+ }
1065
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1066
+ const object2 = instance.object;
1021
1067
  const root = findInitialRoot(instance);
1022
1068
  const visibilityHandlers = {
1023
1069
  onFramed: instance.handlers.onFramed,
@@ -1025,7 +1071,9 @@ function applyProps(object, props) {
1025
1071
  onVisible: instance.handlers.onVisible
1026
1072
  };
1027
1073
  if (hasVisibilityHandlers(visibilityHandlers)) {
1028
- registerVisibility(root, object2, visibilityHandlers);
1074
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1075
+ registerVisibility(root, object2, visibilityHandlers);
1076
+ }
1029
1077
  } else {
1030
1078
  unregisterVisibility(root, object2);
1031
1079
  }
@@ -1038,38 +1086,60 @@ function applyProps(object, props) {
1038
1086
  return object;
1039
1087
  }
1040
1088
 
1089
+ const DEFAULT_POINTER_ID = 0;
1090
+ const XR_POINTER_ID_START = 1e3;
1091
+ function getPointerState(internal, pointerId) {
1092
+ let state = internal.pointerMap.get(pointerId);
1093
+ if (!state) {
1094
+ state = {
1095
+ hovered: /* @__PURE__ */ new Map(),
1096
+ captured: /* @__PURE__ */ new Map(),
1097
+ initialClick: [0, 0],
1098
+ initialHits: []
1099
+ };
1100
+ internal.pointerMap.set(pointerId, state);
1101
+ }
1102
+ return state;
1103
+ }
1104
+ function getPointerId(event) {
1105
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1106
+ }
1041
1107
  function makeId(event) {
1042
1108
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
1043
1109
  }
1044
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
1045
- const captureData = captures.get(obj);
1110
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1111
+ const pointerState = internal.pointerMap.get(pointerId);
1112
+ if (!pointerState) return;
1113
+ const captureData = pointerState.captured.get(obj);
1046
1114
  if (captureData) {
1047
- captures.delete(obj);
1048
- if (captures.size === 0) {
1049
- capturedMap.delete(pointerId);
1050
- captureData.target.releasePointerCapture(pointerId);
1051
- }
1115
+ pointerState.captured.delete(obj);
1116
+ captureData.target.releasePointerCapture(pointerId);
1052
1117
  }
1053
1118
  }
1054
1119
  function removeInteractivity(store, object) {
1055
1120
  const { internal } = store.getState();
1056
1121
  internal.interaction = internal.interaction.filter((o) => o !== object);
1057
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
1058
- internal.hovered.forEach((value, key) => {
1059
- if (value.eventObject === object || value.object === object) {
1060
- internal.hovered.delete(key);
1122
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1123
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1124
+ pointerState.hovered.forEach((value, key) => {
1125
+ if (value.eventObject === object || value.object === object) {
1126
+ pointerState.hovered.delete(key);
1127
+ }
1128
+ });
1129
+ if (pointerState.captured.has(object)) {
1130
+ releaseInternalPointerCapture(internal, object, pointerId);
1061
1131
  }
1062
- });
1063
- internal.capturedMap.forEach((captures, pointerId) => {
1064
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
1065
- });
1132
+ }
1066
1133
  unregisterVisibility(store, object);
1067
1134
  }
1068
1135
  function createEvents(store) {
1069
- function calculateDistance(event) {
1136
+ function calculateDistance(event, pointerId) {
1070
1137
  const { internal } = store.getState();
1071
- const dx = event.offsetX - internal.initialClick[0];
1072
- const dy = event.offsetY - internal.initialClick[1];
1138
+ const pointerState = internal.pointerMap.get(pointerId);
1139
+ if (!pointerState) return 0;
1140
+ const [initialX, initialY] = pointerState.initialClick;
1141
+ const dx = event.offsetX - initialX;
1142
+ const dy = event.offsetY - initialY;
1073
1143
  return Math.round(Math.sqrt(dx * dx + dy * dy));
1074
1144
  }
1075
1145
  function filterPointerEvents(objects) {
@@ -1105,6 +1175,15 @@ function createEvents(store) {
1105
1175
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
1106
1176
  }
1107
1177
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1178
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1179
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1180
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1181
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1182
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1183
+ if (aInteractivePriority !== bInteractivePriority) {
1184
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1185
+ }
1186
+ }
1108
1187
  const aState = getRootState(a.object);
1109
1188
  const bState = getRootState(b.object);
1110
1189
  const aPriority = aState?.events?.priority ?? 1;
@@ -1126,9 +1205,13 @@ function createEvents(store) {
1126
1205
  eventObject = eventObject.parent;
1127
1206
  }
1128
1207
  }
1129
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
1130
- for (const captureData of state.internal.capturedMap.get(event.pointerId).values()) {
1131
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1208
+ if ("pointerId" in event) {
1209
+ const pointerId = event.pointerId;
1210
+ const pointerState = state.internal.pointerMap.get(pointerId);
1211
+ if (pointerState?.captured.size) {
1212
+ for (const captureData of pointerState.captured.values()) {
1213
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1214
+ }
1132
1215
  }
1133
1216
  }
1134
1217
  return intersections;
@@ -1141,27 +1224,25 @@ function createEvents(store) {
1141
1224
  if (state) {
1142
1225
  const { raycaster, pointer, camera, internal } = state;
1143
1226
  const unprojectedPoint = new three.Vector3(pointer.x, pointer.y, 0).unproject(camera);
1144
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1227
+ const hasPointerCapture = (id) => {
1228
+ const pointerState = internal.pointerMap.get(id);
1229
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1230
+ };
1145
1231
  const setPointerCapture = (id) => {
1146
1232
  const captureData = { intersection: hit, target: event.target };
1147
- if (internal.capturedMap.has(id)) {
1148
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
1149
- } else {
1150
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
1151
- }
1233
+ const pointerState = getPointerState(internal, id);
1234
+ pointerState.captured.set(hit.eventObject, captureData);
1152
1235
  event.target.setPointerCapture(id);
1153
1236
  };
1154
1237
  const releasePointerCapture = (id) => {
1155
- const captures = internal.capturedMap.get(id);
1156
- if (captures) {
1157
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
1158
- }
1238
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
1159
1239
  };
1160
1240
  const extractEventProps = {};
1161
1241
  for (const prop in event) {
1162
1242
  const property = event[prop];
1163
1243
  if (typeof property !== "function") extractEventProps[prop] = property;
1164
1244
  }
1245
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1165
1246
  const raycastEvent = {
1166
1247
  ...hit,
1167
1248
  ...extractEventProps,
@@ -1172,18 +1253,19 @@ function createEvents(store) {
1172
1253
  unprojectedPoint,
1173
1254
  ray: raycaster.ray,
1174
1255
  camera,
1256
+ pointerId: eventPointerId,
1175
1257
  // Hijack stopPropagation, which just sets a flag
1176
1258
  stopPropagation() {
1177
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1259
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
1178
1260
  if (
1179
1261
  // ...if this pointer hasn't been captured
1180
- !capturesForPointer || // ... or if the hit object is capturing the pointer
1181
- capturesForPointer.has(hit.eventObject)
1262
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1263
+ pointerState.captured.has(hit.eventObject)
1182
1264
  ) {
1183
1265
  raycastEvent.stopped = localState.stopped = true;
1184
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1266
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1185
1267
  const higher = intersections.slice(0, intersections.indexOf(hit));
1186
- cancelPointer([...higher, hit]);
1268
+ cancelPointer([...higher, hit], eventPointerId);
1187
1269
  }
1188
1270
  }
1189
1271
  },
@@ -1199,15 +1281,18 @@ function createEvents(store) {
1199
1281
  }
1200
1282
  return intersections;
1201
1283
  }
1202
- function cancelPointer(intersections) {
1284
+ function cancelPointer(intersections, pointerId) {
1203
1285
  const { internal } = store.getState();
1204
- for (const hoveredObj of internal.hovered.values()) {
1286
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1287
+ const pointerState = internal.pointerMap.get(pid);
1288
+ if (!pointerState) return;
1289
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
1205
1290
  if (!intersections.length || !intersections.find(
1206
1291
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
1207
1292
  )) {
1208
1293
  const eventObject = hoveredObj.eventObject;
1209
1294
  const instance = eventObject.__r3f;
1210
- internal.hovered.delete(makeId(hoveredObj));
1295
+ pointerState.hovered.delete(hoveredId);
1211
1296
  if (instance?.eventCount) {
1212
1297
  const handlers = instance.handlers;
1213
1298
  const data = { ...hoveredObj, intersections };
@@ -1236,41 +1321,118 @@ function createEvents(store) {
1236
1321
  instance?.handlers.onDropMissed?.(event);
1237
1322
  }
1238
1323
  }
1324
+ function cleanupPointer(pointerId) {
1325
+ const { internal } = store.getState();
1326
+ const pointerState = internal.pointerMap.get(pointerId);
1327
+ if (pointerState) {
1328
+ for (const [, hoveredObj] of pointerState.hovered) {
1329
+ const eventObject = hoveredObj.eventObject;
1330
+ const instance = eventObject.__r3f;
1331
+ if (instance?.eventCount) {
1332
+ const handlers = instance.handlers;
1333
+ const data = { ...hoveredObj, intersections: [] };
1334
+ handlers.onPointerOut?.(data);
1335
+ handlers.onPointerLeave?.(data);
1336
+ }
1337
+ }
1338
+ internal.pointerMap.delete(pointerId);
1339
+ }
1340
+ internal.pointerDirty.delete(pointerId);
1341
+ }
1342
+ function processDeferredPointer(event, pointerId) {
1343
+ const state = store.getState();
1344
+ const { internal } = state;
1345
+ if (!state.events.enabled) return;
1346
+ const filter = filterPointerEvents;
1347
+ const hits = intersect(event, filter);
1348
+ cancelPointer(hits, pointerId);
1349
+ function onIntersect(data) {
1350
+ const eventObject = data.eventObject;
1351
+ const instance = eventObject.__r3f;
1352
+ if (!instance?.eventCount) return;
1353
+ const handlers = instance.handlers;
1354
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1355
+ const id = makeId(data);
1356
+ const pointerState = getPointerState(internal, pointerId);
1357
+ const hoveredItem = pointerState.hovered.get(id);
1358
+ if (!hoveredItem) {
1359
+ pointerState.hovered.set(id, data);
1360
+ handlers.onPointerOver?.(data);
1361
+ handlers.onPointerEnter?.(data);
1362
+ } else if (hoveredItem.stopped) {
1363
+ data.stopPropagation();
1364
+ }
1365
+ }
1366
+ handlers.onPointerMove?.(data);
1367
+ }
1368
+ handleIntersects(hits, event, 0, onIntersect);
1369
+ }
1239
1370
  function handlePointer(name) {
1240
1371
  switch (name) {
1241
1372
  case "onPointerLeave":
1242
- case "onPointerCancel":
1243
1373
  case "onDragLeave":
1244
1374
  return () => cancelPointer([]);
1375
+ // Global cancel of these events
1376
+ case "onPointerCancel":
1377
+ return (event) => {
1378
+ const pointerId = getPointerId(event);
1379
+ cleanupPointer(pointerId);
1380
+ };
1245
1381
  case "onLostPointerCapture":
1246
1382
  return (event) => {
1247
1383
  const { internal } = store.getState();
1248
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1384
+ const pointerId = getPointerId(event);
1385
+ const pointerState = internal.pointerMap.get(pointerId);
1386
+ if (pointerState?.captured.size) {
1249
1387
  requestAnimationFrame(() => {
1250
- if (internal.capturedMap.has(event.pointerId)) {
1251
- internal.capturedMap.delete(event.pointerId);
1252
- cancelPointer([]);
1388
+ const pointerState2 = internal.pointerMap.get(pointerId);
1389
+ if (pointerState2?.captured.size) {
1390
+ pointerState2.captured.clear();
1253
1391
  }
1392
+ cancelPointer([], pointerId);
1254
1393
  });
1255
1394
  }
1256
1395
  };
1257
1396
  }
1258
1397
  return function handleEvent(event) {
1259
1398
  const state = store.getState();
1260
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1399
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1400
+ const pointerId = getPointerId(event);
1261
1401
  internal.lastEvent.current = event;
1262
- if (!state.events.enabled) return;
1402
+ if (!events.enabled) return;
1263
1403
  const isPointerMove = name === "onPointerMove";
1264
1404
  const isDragOver = name === "onDragOver";
1265
1405
  const isDrop = name === "onDrop";
1266
1406
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1407
+ const isPointerDown = name === "onPointerDown";
1408
+ const isPointerUp = name === "onPointerUp";
1409
+ const isWheel = name === "onWheel";
1410
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1411
+ if (isPointerMove && canDeferRaycasts) {
1412
+ events.compute?.(event, state);
1413
+ internal.pointerDirty.set(pointerId, event);
1414
+ return;
1415
+ }
1416
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1417
+ events.compute?.(event, state);
1418
+ internal.pointerDirty.set(pointerId, event);
1419
+ return;
1420
+ }
1421
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1422
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1423
+ internal.pointerDirty.delete(pointerId);
1424
+ processDeferredPointer(deferredEvent, pointerId);
1425
+ }
1267
1426
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
1268
1427
  const hits = intersect(event, filter);
1269
- const delta = isClickEvent ? calculateDistance(event) : 0;
1270
- if (name === "onPointerDown") {
1271
- internal.initialClick = [event.offsetX, event.offsetY];
1272
- internal.initialHits = hits.map((hit) => hit.eventObject);
1273
- }
1428
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1429
+ if (isPointerDown) {
1430
+ const pointerState2 = getPointerState(internal, pointerId);
1431
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1432
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1433
+ }
1434
+ const pointerState = internal.pointerMap.get(pointerId);
1435
+ const initialHits = pointerState?.initialHits ?? [];
1274
1436
  if (isClickEvent && !hits.length) {
1275
1437
  if (delta <= 2) {
1276
1438
  pointerMissed(event, internal.interaction);
@@ -1285,7 +1447,9 @@ function createEvents(store) {
1285
1447
  dropMissed(event, internal.interaction);
1286
1448
  if (onDropMissed) onDropMissed(event);
1287
1449
  }
1288
- if (isPointerMove || isDragOver) cancelPointer(hits);
1450
+ if (isPointerMove || isDragOver) {
1451
+ cancelPointer(hits, pointerId);
1452
+ }
1289
1453
  function onIntersect(data) {
1290
1454
  const eventObject = data.eventObject;
1291
1455
  const instance = eventObject.__r3f;
@@ -1294,9 +1458,10 @@ function createEvents(store) {
1294
1458
  if (isPointerMove) {
1295
1459
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1296
1460
  const id = makeId(data);
1297
- const hoveredItem = internal.hovered.get(id);
1461
+ const pointerState2 = getPointerState(internal, pointerId);
1462
+ const hoveredItem = pointerState2.hovered.get(id);
1298
1463
  if (!hoveredItem) {
1299
- internal.hovered.set(id, data);
1464
+ pointerState2.hovered.set(id, data);
1300
1465
  handlers.onPointerOver?.(data);
1301
1466
  handlers.onPointerEnter?.(data);
1302
1467
  } else if (hoveredItem.stopped) {
@@ -1306,9 +1471,10 @@ function createEvents(store) {
1306
1471
  handlers.onPointerMove?.(data);
1307
1472
  } else if (isDragOver) {
1308
1473
  const id = makeId(data);
1309
- const hoveredItem = internal.hovered.get(id);
1474
+ const pointerState2 = getPointerState(internal, pointerId);
1475
+ const hoveredItem = pointerState2.hovered.get(id);
1310
1476
  if (!hoveredItem) {
1311
- internal.hovered.set(id, data);
1477
+ pointerState2.hovered.set(id, data);
1312
1478
  handlers.onDragOverEnter?.(data);
1313
1479
  } else if (hoveredItem.stopped) {
1314
1480
  data.stopPropagation();
@@ -1319,18 +1485,18 @@ function createEvents(store) {
1319
1485
  } else {
1320
1486
  const handler = handlers[name];
1321
1487
  if (handler) {
1322
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1488
+ if (!isClickEvent || initialHits.includes(eventObject)) {
1323
1489
  pointerMissed(
1324
1490
  event,
1325
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1491
+ internal.interaction.filter((object) => !initialHits.includes(object))
1326
1492
  );
1327
1493
  handler(data);
1328
1494
  }
1329
1495
  } else {
1330
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1496
+ if (isClickEvent && initialHits.includes(eventObject)) {
1331
1497
  pointerMissed(
1332
1498
  event,
1333
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1499
+ internal.interaction.filter((object) => !initialHits.includes(object))
1334
1500
  );
1335
1501
  }
1336
1502
  }
@@ -1339,7 +1505,15 @@ function createEvents(store) {
1339
1505
  handleIntersects(hits, event, delta, onIntersect);
1340
1506
  };
1341
1507
  }
1342
- return { handlePointer };
1508
+ function flushDeferredPointers() {
1509
+ const { internal, events } = store.getState();
1510
+ if (!events.frameTimedRaycasts) return;
1511
+ for (const [pointerId, event] of internal.pointerDirty) {
1512
+ processDeferredPointer(event, pointerId);
1513
+ }
1514
+ internal.pointerDirty.clear();
1515
+ }
1516
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
1343
1517
  }
1344
1518
  const DOM_EVENTS = {
1345
1519
  onClick: ["click", false],
@@ -1358,10 +1532,15 @@ const DOM_EVENTS = {
1358
1532
  onLostPointerCapture: ["lostpointercapture", true]
1359
1533
  };
1360
1534
  function createPointerEvents(store) {
1361
- const { handlePointer } = createEvents(store);
1535
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1536
+ let nextXRPointerId = XR_POINTER_ID_START;
1537
+ const xrPointers = /* @__PURE__ */ new Map();
1362
1538
  return {
1363
1539
  priority: 1,
1364
1540
  enabled: true,
1541
+ frameTimedRaycasts: true,
1542
+ alwaysFireOnScroll: true,
1543
+ updateOnFrame: false,
1365
1544
  compute(event, state) {
1366
1545
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
1367
1546
  state.raycaster.setFromCamera(state.pointer, state.camera);
@@ -1371,11 +1550,33 @@ function createPointerEvents(store) {
1371
1550
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
1372
1551
  {}
1373
1552
  ),
1374
- update: () => {
1553
+ update: (pointerId) => {
1375
1554
  const { events, internal } = store.getState();
1376
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1555
+ if (!events.handlers) return;
1556
+ if (pointerId !== void 0) {
1557
+ const event = internal.pointerDirty.get(pointerId);
1558
+ if (event) {
1559
+ internal.pointerDirty.delete(pointerId);
1560
+ processDeferredPointer(event, pointerId);
1561
+ } else if (internal.lastEvent?.current) {
1562
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1563
+ }
1564
+ } else {
1565
+ flushDeferredPointers();
1566
+ if (internal.lastEvent?.current) {
1567
+ events.handlers.onPointerMove(internal.lastEvent.current);
1568
+ }
1569
+ }
1570
+ },
1571
+ flush: () => {
1572
+ const { events, internal } = store.getState();
1573
+ flushDeferredPointers();
1574
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1575
+ events.handlers.onPointerMove(internal.lastEvent.current);
1576
+ }
1377
1577
  },
1378
1578
  connect: (target) => {
1579
+ if (!target) return;
1379
1580
  const { set, events } = store.getState();
1380
1581
  events.disconnect?.();
1381
1582
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1399,6 +1600,33 @@ function createPointerEvents(store) {
1399
1600
  }
1400
1601
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1401
1602
  }
1603
+ },
1604
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1605
+ registerPointer: (config) => {
1606
+ const pointerId = nextXRPointerId++;
1607
+ xrPointers.set(pointerId, config);
1608
+ const { internal } = store.getState();
1609
+ getPointerState(internal, pointerId);
1610
+ return pointerId;
1611
+ },
1612
+ unregisterPointer: (pointerId) => {
1613
+ xrPointers.delete(pointerId);
1614
+ const { internal } = store.getState();
1615
+ const pointerState = internal.pointerMap.get(pointerId);
1616
+ if (pointerState) {
1617
+ for (const [, hoveredObj] of pointerState.hovered) {
1618
+ const eventObject = hoveredObj.eventObject;
1619
+ const instance = eventObject.__r3f;
1620
+ if (instance?.eventCount) {
1621
+ const handlers = instance.handlers;
1622
+ const data = { ...hoveredObj, intersections: [] };
1623
+ handlers.onPointerOut?.(data);
1624
+ handlers.onPointerLeave?.(data);
1625
+ }
1626
+ }
1627
+ internal.pointerMap.delete(pointerId);
1628
+ }
1629
+ internal.pointerDirty.delete(pointerId);
1402
1630
  }
1403
1631
  };
1404
1632
  }
@@ -1460,1036 +1688,11 @@ function notifyAlpha({ message, link }) {
1460
1688
  }
1461
1689
  }
1462
1690
 
1463
- var __defProp$1 = Object.defineProperty;
1464
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1465
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1466
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1467
- class PhaseGraph {
1468
- constructor() {
1469
- /** Ordered list of phase nodes */
1470
- __publicField$1(this, "phases", []);
1471
- /** Quick lookup by name */
1472
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1473
- /** Cached ordered names (invalidated on changes) */
1474
- __publicField$1(this, "orderedNamesCache", null);
1475
- this.initializeDefaultPhases();
1476
- }
1477
- //* Initialization --------------------------------
1478
- initializeDefaultPhases() {
1479
- for (const name of DEFAULT_PHASES) {
1480
- const node = { name, isAutoGenerated: false };
1481
- this.phases.push(node);
1482
- this.phaseMap.set(name, node);
1483
- }
1484
- this.invalidateCache();
1485
- }
1486
- //* Public API --------------------------------
1487
- /**
1488
- * Add a named phase to the graph
1489
- * @param name - Phase name (must be unique)
1490
- * @param options - Position options (before or after another phase)
1491
- */
1492
- addPhase(name, options = {}) {
1493
- if (this.phaseMap.has(name)) {
1494
- console.warn(`[useFrame] Phase "${name}" already exists`);
1495
- return;
1496
- }
1497
- const { before, after } = options;
1498
- const node = { name, isAutoGenerated: false };
1499
- let insertIndex = this.phases.length;
1500
- const targetIndex = this.getPhaseIndex(before ?? after);
1501
- if (targetIndex !== -1) {
1502
- insertIndex = before ? targetIndex : targetIndex + 1;
1503
- } else {
1504
- const constraintType = before ? "before" : "after";
1505
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1506
- }
1507
- this.phases.splice(insertIndex, 0, node);
1508
- this.phaseMap.set(name, node);
1509
- this.invalidateCache();
1510
- }
1511
- /**
1512
- * Get ordered list of phase names
1513
- */
1514
- getOrderedPhases() {
1515
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1516
- return this.orderedNamesCache;
1517
- }
1518
- /**
1519
- * Check if a phase exists
1520
- */
1521
- hasPhase(name) {
1522
- return this.phaseMap.has(name);
1523
- }
1524
- /**
1525
- * Get the index of a phase (-1 if not found)
1526
- */
1527
- getPhaseIndex(name) {
1528
- if (!name) return -1;
1529
- return this.phases.findIndex((p) => p.name === name);
1530
- }
1531
- /**
1532
- * Ensure a phase exists, creating an auto-generated one if needed.
1533
- * Used for resolving before/after constraints.
1534
- *
1535
- * @param name - The phase name to ensure exists
1536
- * @returns The phase name (may be auto-generated like 'before:render')
1537
- */
1538
- ensurePhase(name) {
1539
- if (this.phaseMap.has(name)) return name;
1540
- const node = { name, isAutoGenerated: true };
1541
- this.phases.push(node);
1542
- this.phaseMap.set(name, node);
1543
- this.invalidateCache();
1544
- return name;
1545
- }
1546
- /**
1547
- * Resolve where a job with before/after constraints should go.
1548
- * Creates auto-generated phases if needed.
1549
- *
1550
- * @param before - Phase(s) to run before
1551
- * @param after - Phase(s) to run after
1552
- * @returns The resolved phase name
1553
- */
1554
- resolveConstraintPhase(before, after) {
1555
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1556
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1557
- if (beforeArr.length > 0) {
1558
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1559
- }
1560
- if (afterArr.length > 0) {
1561
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1562
- }
1563
- return "update";
1564
- }
1565
- /**
1566
- * Ensure an auto-generated phase exists relative to a target phase.
1567
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1568
- *
1569
- * @param target - The target phase name to position relative to
1570
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1571
- * @param offset - Insertion offset (0 for before, 1 for after)
1572
- * @returns The auto-generated phase name
1573
- */
1574
- ensureAutoPhase(target, prefix, offset) {
1575
- const autoName = `${prefix}:${target}`;
1576
- if (this.phaseMap.has(autoName)) return autoName;
1577
- const node = { name: autoName, isAutoGenerated: true };
1578
- const targetIndex = this.getPhaseIndex(target);
1579
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1580
- else this.phases.push(node);
1581
- this.phaseMap.set(autoName, node);
1582
- this.invalidateCache();
1583
- return autoName;
1584
- }
1585
- // Internal --------------------------------
1586
- invalidateCache() {
1587
- this.orderedNamesCache = null;
1588
- }
1589
- }
1590
-
1591
- function rebuildSortedJobs(jobs, phaseGraph) {
1592
- const orderedPhases = phaseGraph.getOrderedPhases();
1593
- const buckets = /* @__PURE__ */ new Map();
1594
- for (const phase of orderedPhases) {
1595
- buckets.set(phase, []);
1596
- }
1597
- for (const job of jobs.values()) {
1598
- if (!job.enabled) continue;
1599
- let bucket = buckets.get(job.phase);
1600
- if (!bucket) {
1601
- bucket = [];
1602
- buckets.set(job.phase, bucket);
1603
- }
1604
- bucket.push(job);
1605
- }
1606
- const sortedBuckets = [];
1607
- for (const phase of orderedPhases) {
1608
- const bucket = buckets.get(phase);
1609
- if (!bucket || bucket.length === 0) continue;
1610
- bucket.sort((a, b) => {
1611
- if (a.priority !== b.priority) return b.priority - a.priority;
1612
- return a.index - b.index;
1613
- });
1614
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1615
- }
1616
- for (const [phase, bucket] of buckets) {
1617
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1618
- bucket.sort((a, b) => {
1619
- if (a.priority !== b.priority) return b.priority - a.priority;
1620
- return a.index - b.index;
1621
- });
1622
- sortedBuckets.push(bucket);
1623
- }
1624
- }
1625
- return sortedBuckets.flat();
1626
- }
1627
- function hasCrossJobConstraints(bucket) {
1628
- const jobIds = new Set(bucket.map((j) => j.id));
1629
- for (const job of bucket) {
1630
- for (const ref of job.before) {
1631
- if (jobIds.has(ref)) return true;
1632
- }
1633
- for (const ref of job.after) {
1634
- if (jobIds.has(ref)) return true;
1635
- }
1636
- }
1637
- return false;
1638
- }
1639
- function topologicalSort(jobs) {
1640
- const n = jobs.length;
1641
- if (n <= 1) return jobs;
1642
- const jobMap = /* @__PURE__ */ new Map();
1643
- const inDegree = /* @__PURE__ */ new Map();
1644
- const adjacency = /* @__PURE__ */ new Map();
1645
- for (const job of jobs) {
1646
- jobMap.set(job.id, job);
1647
- inDegree.set(job.id, 0);
1648
- adjacency.set(job.id, []);
1649
- }
1650
- for (const job of jobs) {
1651
- for (const ref of job.before) {
1652
- if (jobMap.has(ref)) {
1653
- adjacency.get(job.id).push(ref);
1654
- inDegree.set(ref, inDegree.get(ref) + 1);
1655
- }
1656
- }
1657
- for (const ref of job.after) {
1658
- if (jobMap.has(ref)) {
1659
- adjacency.get(ref).push(job.id);
1660
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1661
- }
1662
- }
1663
- }
1664
- const queue = [];
1665
- for (const job of jobs) {
1666
- if (inDegree.get(job.id) === 0) {
1667
- queue.push(job);
1668
- }
1669
- }
1670
- queue.sort((a, b) => {
1671
- if (a.priority !== b.priority) return b.priority - a.priority;
1672
- return a.index - b.index;
1673
- });
1674
- const result = [];
1675
- while (queue.length > 0) {
1676
- const job = queue.shift();
1677
- result.push(job);
1678
- const neighbors = adjacency.get(job.id) || [];
1679
- for (const neighborId of neighbors) {
1680
- const newDegree = inDegree.get(neighborId) - 1;
1681
- inDegree.set(neighborId, newDegree);
1682
- if (newDegree === 0) {
1683
- const neighbor = jobMap.get(neighborId);
1684
- insertSorted(queue, neighbor);
1685
- }
1686
- }
1687
- }
1688
- if (result.length !== n) {
1689
- console.warn("[useFrame] Circular dependency detected in job constraints");
1690
- const resultIds = new Set(result.map((j) => j.id));
1691
- for (const job of jobs) {
1692
- if (!resultIds.has(job.id)) result.push(job);
1693
- }
1694
- }
1695
- return result;
1696
- }
1697
- function insertSorted(arr, job) {
1698
- let i = 0;
1699
- while (i < arr.length) {
1700
- const cmp = arr[i];
1701
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1702
- break;
1703
- }
1704
- i++;
1705
- }
1706
- arr.splice(i, 0, job);
1707
- }
1708
-
1709
- function shouldRun(job, now) {
1710
- if (!job.enabled) return false;
1711
- if (!job.fps) return true;
1712
- const minInterval = 1e3 / job.fps;
1713
- const lastRun = job.lastRun ?? 0;
1714
- const elapsed = now - lastRun;
1715
- if (elapsed < minInterval) return false;
1716
- if (job.drop) {
1717
- job.lastRun = now;
1718
- } else {
1719
- const steps = Math.floor(elapsed / minInterval);
1720
- job.lastRun = lastRun + steps * minInterval;
1721
- if (job.lastRun < now - minInterval) {
1722
- job.lastRun = now;
1723
- }
1724
- }
1725
- return true;
1726
- }
1727
- function resetJobTiming(job) {
1728
- job.lastRun = void 0;
1729
- }
1730
-
1731
- var __defProp = Object.defineProperty;
1732
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1733
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1734
- const hmrData = (() => {
1735
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1736
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1737
- try {
1738
- return (0, eval)("import.meta.hot");
1739
- } catch {
1740
- return void 0;
1741
- }
1742
- })();
1743
- const _Scheduler = class _Scheduler {
1744
- //* Constructor ================================
1745
- constructor() {
1746
- //* Critical State ================================
1747
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1748
- __publicField(this, "phaseGraph");
1749
- __publicField(this, "loopState", {
1750
- running: false,
1751
- rafHandle: null,
1752
- lastTime: null,
1753
- // null = uninitialized, 0+ = valid timestamp
1754
- frameCount: 0,
1755
- elapsedTime: 0,
1756
- createdAt: performance.now()
1757
- });
1758
- __publicField(this, "stoppedTime", 0);
1759
- //* Private State ================================
1760
- __publicField(this, "nextRootIndex", 0);
1761
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1762
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1763
- __publicField(this, "nextGlobalIndex", 0);
1764
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1765
- __publicField(this, "nextJobIndex", 0);
1766
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1767
- __publicField(this, "pendingFrames", 0);
1768
- __publicField(this, "_frameloop", "always");
1769
- //* Independent Mode & Error Handling State ================================
1770
- __publicField(this, "_independent", false);
1771
- __publicField(this, "errorHandler", null);
1772
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1773
- //* Core Loop Execution Methods ================================
1774
- /**
1775
- * Main RAF loop callback.
1776
- * Executes frame, handles demand mode, and schedules next frame.
1777
- * @param {number} timestamp - RAF timestamp in milliseconds
1778
- * @returns {void}
1779
- * @private
1780
- */
1781
- __publicField(this, "loop", (timestamp) => {
1782
- if (!this.loopState.running) return;
1783
- this.executeFrame(timestamp);
1784
- if (this._frameloop === "demand") {
1785
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1786
- if (this.pendingFrames === 0) {
1787
- this.notifyIdle(timestamp);
1788
- return this.stop();
1789
- }
1790
- }
1791
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1792
- });
1793
- this.phaseGraph = new PhaseGraph();
1794
- }
1795
- static get instance() {
1796
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1797
- }
1798
- static set instance(value) {
1799
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1800
- }
1801
- /**
1802
- * Get the global scheduler instance (creates if doesn't exist).
1803
- * Uses HMR data to preserve instance across hot reloads.
1804
- * @returns {Scheduler} The singleton scheduler instance
1805
- */
1806
- static get() {
1807
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1808
- _Scheduler.instance = hmrData.data.scheduler;
1809
- }
1810
- if (!_Scheduler.instance) {
1811
- _Scheduler.instance = new _Scheduler();
1812
- if (hmrData?.data) {
1813
- hmrData.data.scheduler = _Scheduler.instance;
1814
- }
1815
- }
1816
- return _Scheduler.instance;
1817
- }
1818
- /**
1819
- * Reset the singleton instance. Stops the loop and clears all state.
1820
- * Primarily used for testing to ensure clean state between tests.
1821
- * @returns {void}
1822
- */
1823
- static reset() {
1824
- if (_Scheduler.instance) {
1825
- _Scheduler.instance.stop();
1826
- _Scheduler.instance = null;
1827
- }
1828
- if (hmrData?.data) {
1829
- hmrData.data.scheduler = null;
1830
- }
1831
- }
1832
- //* Getters & Setters ================================
1833
- get phases() {
1834
- return this.phaseGraph.getOrderedPhases();
1835
- }
1836
- get frameloop() {
1837
- return this._frameloop;
1838
- }
1839
- set frameloop(mode) {
1840
- if (this._frameloop === mode) return;
1841
- const wasAlways = this._frameloop === "always";
1842
- this._frameloop = mode;
1843
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1844
- else if (mode !== "always" && wasAlways) this.stop();
1845
- }
1846
- get isRunning() {
1847
- return this.loopState.running;
1848
- }
1849
- get isReady() {
1850
- return this.roots.size > 0;
1851
- }
1852
- get independent() {
1853
- return this._independent;
1854
- }
1855
- set independent(value) {
1856
- this._independent = value;
1857
- if (value) this.ensureDefaultRoot();
1858
- }
1859
- //* Root Management Methods ================================
1860
- /**
1861
- * Register a root (Canvas) with the scheduler.
1862
- * The first root to register starts the RAF loop (if frameloop='always').
1863
- * @param {string} id - Unique identifier for this root
1864
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1865
- * @returns {() => void} Unsubscribe function to remove this root
1866
- */
1867
- registerRoot(id, options = {}) {
1868
- if (this.roots.has(id)) {
1869
- console.warn(`[Scheduler] Root "${id}" already registered`);
1870
- return () => this.unregisterRoot(id);
1871
- }
1872
- const entry = {
1873
- id,
1874
- getState: options.getState ?? (() => ({})),
1875
- jobs: /* @__PURE__ */ new Map(),
1876
- sortedJobs: [],
1877
- needsRebuild: false
1878
- };
1879
- if (options.onError) {
1880
- this.errorHandler = options.onError;
1881
- }
1882
- this.roots.set(id, entry);
1883
- if (this.roots.size === 1) {
1884
- this.notifyRootReady();
1885
- if (this._frameloop === "always") this.start();
1886
- }
1887
- return () => this.unregisterRoot(id);
1888
- }
1889
- /**
1890
- * Unregister a root from the scheduler.
1891
- * Cleans up all job state listeners for this root's jobs.
1892
- * The last root to unregister stops the RAF loop.
1893
- * @param {string} id - The root ID to unregister
1894
- * @returns {void}
1895
- */
1896
- unregisterRoot(id) {
1897
- const root = this.roots.get(id);
1898
- if (!root) return;
1899
- for (const jobId of root.jobs.keys()) {
1900
- this.jobStateListeners.delete(jobId);
1901
- }
1902
- this.roots.delete(id);
1903
- if (this.roots.size === 0) {
1904
- this.stop();
1905
- this.errorHandler = null;
1906
- }
1907
- }
1908
- /**
1909
- * Subscribe to be notified when a root becomes available.
1910
- * Fires immediately if a root already exists.
1911
- * @param {() => void} callback - Function called when first root registers
1912
- * @returns {() => void} Unsubscribe function
1913
- */
1914
- onRootReady(callback) {
1915
- if (this.roots.size > 0) {
1916
- callback();
1917
- return () => {
1918
- };
1919
- }
1920
- this.rootReadyCallbacks.add(callback);
1921
- return () => this.rootReadyCallbacks.delete(callback);
1922
- }
1923
- /**
1924
- * Notify all registered root-ready callbacks.
1925
- * Called when the first root registers.
1926
- * @returns {void}
1927
- * @private
1928
- */
1929
- notifyRootReady() {
1930
- for (const cb of this.rootReadyCallbacks) {
1931
- try {
1932
- cb();
1933
- } catch (error) {
1934
- console.error("[Scheduler] Error in root-ready callback:", error);
1935
- }
1936
- }
1937
- this.rootReadyCallbacks.clear();
1938
- }
1939
- /**
1940
- * Ensure a default root exists for independent mode.
1941
- * Creates a minimal root with no state provider.
1942
- * @returns {void}
1943
- * @private
1944
- */
1945
- ensureDefaultRoot() {
1946
- if (!this.roots.has("__default__")) {
1947
- this.registerRoot("__default__");
1948
- }
1949
- }
1950
- /**
1951
- * Trigger error handling for job errors.
1952
- * Uses the bound error handler if available, otherwise logs to console.
1953
- * @param {Error} error - The error to handle
1954
- * @returns {void}
1955
- */
1956
- triggerError(error) {
1957
- if (this.errorHandler) this.errorHandler(error);
1958
- else console.error("[Scheduler]", error);
1959
- }
1960
- //* Phase Management Methods ================================
1961
- /**
1962
- * Add a named phase to the scheduler's execution order.
1963
- * Marks all roots for rebuild to incorporate the new phase.
1964
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1965
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1966
- * @returns {void}
1967
- * @example
1968
- * scheduler.addPhase('physics', { before: 'update' });
1969
- * scheduler.addPhase('postprocess', { after: 'render' });
1970
- */
1971
- addPhase(name, options) {
1972
- this.phaseGraph.addPhase(name, options);
1973
- for (const root of this.roots.values()) {
1974
- root.needsRebuild = true;
1975
- }
1976
- }
1977
- /**
1978
- * Check if a phase exists in the scheduler.
1979
- * @param {string} name - The phase name to check
1980
- * @returns {boolean} True if the phase exists
1981
- */
1982
- hasPhase(name) {
1983
- return this.phaseGraph.hasPhase(name);
1984
- }
1985
- //* Global Job Registration Methods (Deprecated APIs) ================================
1986
- /**
1987
- * Register a global job that runs once per frame (not per-root).
1988
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1989
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1990
- * @param {string} id - Unique identifier for this global job
1991
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1992
- * @returns {() => void} Unsubscribe function to remove this global job
1993
- * @deprecated Use useFrame with phases instead
1994
- */
1995
- registerGlobal(phase, id, callback) {
1996
- const job = { id, callback };
1997
- if (phase === "before") {
1998
- this.globalBeforeJobs.set(id, job);
1999
- } else {
2000
- this.globalAfterJobs.set(id, job);
2001
- }
2002
- return () => {
2003
- if (phase === "before") this.globalBeforeJobs.delete(id);
2004
- else this.globalAfterJobs.delete(id);
2005
- };
2006
- }
2007
- //* Idle Callback Methods (Deprecated API) ================================
2008
- /**
2009
- * Register an idle callback that fires when the loop stops.
2010
- * Used internally by deprecated addTail API.
2011
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2012
- * @returns {() => void} Unsubscribe function to remove this idle callback
2013
- * @deprecated Use demand mode with invalidate() instead
2014
- */
2015
- onIdle(callback) {
2016
- this.idleCallbacks.add(callback);
2017
- return () => this.idleCallbacks.delete(callback);
2018
- }
2019
- /**
2020
- * Notify all registered idle callbacks.
2021
- * Called when the loop stops in demand mode.
2022
- * @param {number} timestamp - The RAF timestamp when idle occurred
2023
- * @returns {void}
2024
- * @private
2025
- */
2026
- notifyIdle(timestamp) {
2027
- for (const cb of this.idleCallbacks) {
2028
- try {
2029
- cb(timestamp);
2030
- } catch (error) {
2031
- console.error("[Scheduler] Error in idle callback:", error);
2032
- }
2033
- }
2034
- }
2035
- //* Job Registration & Management Methods ================================
2036
- /**
2037
- * Register a job (frame callback) with a specific root.
2038
- * This is the core registration method used by useFrame internally.
2039
- * @param {FrameNextCallback} callback - The function to call each frame
2040
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2041
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2042
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2043
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2044
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2045
- * @param {number} [options.fps] - FPS throttle limit
2046
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2047
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2048
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2049
- * @returns {() => void} Unsubscribe function to remove this job
2050
- */
2051
- register(callback, options = {}) {
2052
- const rootId = options.rootId;
2053
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2054
- if (!root) {
2055
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2056
- return () => {
2057
- };
2058
- }
2059
- const id = options.id ?? this.generateJobId();
2060
- let phase = options.phase ?? "update";
2061
- if (!options.phase && (options.before || options.after)) {
2062
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2063
- }
2064
- const before = this.normalizeConstraints(options.before);
2065
- const after = this.normalizeConstraints(options.after);
2066
- const job = {
2067
- id,
2068
- callback,
2069
- phase,
2070
- before,
2071
- after,
2072
- priority: options.priority ?? 0,
2073
- index: this.nextJobIndex++,
2074
- fps: options.fps,
2075
- drop: options.drop ?? true,
2076
- enabled: options.enabled ?? true,
2077
- system: options.system ?? false
2078
- };
2079
- if (root.jobs.has(id)) {
2080
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2081
- }
2082
- root.jobs.set(id, job);
2083
- root.needsRebuild = true;
2084
- return () => this.unregister(id, root.id);
2085
- }
2086
- /**
2087
- * Unregister a job by its ID.
2088
- * Searches all roots if rootId is not provided.
2089
- * @param {string} id - The job ID to unregister
2090
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2091
- * @returns {void}
2092
- */
2093
- unregister(id, rootId) {
2094
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2095
- if (root?.jobs.delete(id)) {
2096
- root.needsRebuild = true;
2097
- this.jobStateListeners.delete(id);
2098
- }
2099
- }
2100
- /**
2101
- * Update a job's options dynamically.
2102
- * Searches all roots to find the job by ID.
2103
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2104
- * @param {string} id - The job ID to update
2105
- * @param {Partial<JobOptions>} options - The options to update
2106
- * @returns {void}
2107
- */
2108
- updateJob(id, options) {
2109
- let job;
2110
- let root;
2111
- for (const r of this.roots.values()) {
2112
- job = r.jobs.get(id);
2113
- if (job) {
2114
- root = r;
2115
- break;
2116
- }
2117
- }
2118
- if (!job || !root) return;
2119
- if (options.priority !== void 0) job.priority = options.priority;
2120
- if (options.fps !== void 0) job.fps = options.fps;
2121
- if (options.drop !== void 0) job.drop = options.drop;
2122
- if (options.enabled !== void 0) {
2123
- const wasEnabled = job.enabled;
2124
- job.enabled = options.enabled;
2125
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2126
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2127
- }
2128
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2129
- if (options.phase) job.phase = options.phase;
2130
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2131
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2132
- root.needsRebuild = true;
2133
- }
2134
- }
2135
- //* Job State Management Methods ================================
2136
- /**
2137
- * Check if a job is currently paused (disabled).
2138
- * @param {string} id - The job ID to check
2139
- * @returns {boolean} True if the job exists and is paused
2140
- */
2141
- isJobPaused(id) {
2142
- for (const root of this.roots.values()) {
2143
- const job = root.jobs.get(id);
2144
- if (job) return !job.enabled;
2145
- }
2146
- return false;
2147
- }
2148
- /**
2149
- * Subscribe to state changes for a specific job.
2150
- * Listener is called when job is paused or resumed.
2151
- * @param {string} id - The job ID to subscribe to
2152
- * @param {() => void} listener - Callback invoked on state changes
2153
- * @returns {() => void} Unsubscribe function
2154
- */
2155
- subscribeJobState(id, listener) {
2156
- if (!this.jobStateListeners.has(id)) {
2157
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2158
- }
2159
- this.jobStateListeners.get(id).add(listener);
2160
- return () => {
2161
- this.jobStateListeners.get(id)?.delete(listener);
2162
- if (this.jobStateListeners.get(id)?.size === 0) {
2163
- this.jobStateListeners.delete(id);
2164
- }
2165
- };
2166
- }
2167
- /**
2168
- * Notify all listeners that a job's state has changed.
2169
- * @param {string} id - The job ID that changed
2170
- * @returns {void}
2171
- * @private
2172
- */
2173
- notifyJobStateChange(id) {
2174
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2175
- }
2176
- /**
2177
- * Pause a job by ID (sets enabled=false).
2178
- * Notifies any subscribed state listeners.
2179
- * @param {string} id - The job ID to pause
2180
- * @returns {void}
2181
- */
2182
- pauseJob(id) {
2183
- this.updateJob(id, { enabled: false });
2184
- this.notifyJobStateChange(id);
2185
- }
2186
- /**
2187
- * Resume a paused job by ID (sets enabled=true).
2188
- * Resets job timing to prevent frame accumulation.
2189
- * Notifies any subscribed state listeners.
2190
- * @param {string} id - The job ID to resume
2191
- * @returns {void}
2192
- */
2193
- resumeJob(id) {
2194
- this.updateJob(id, { enabled: true });
2195
- this.notifyJobStateChange(id);
2196
- }
2197
- //* Frame Loop Control Methods ================================
2198
- /**
2199
- * Start the requestAnimationFrame loop.
2200
- * Resets timing state (elapsedTime, frameCount) on start.
2201
- * No-op if already running.
2202
- * @returns {void}
2203
- */
2204
- start() {
2205
- if (this.loopState.running) return;
2206
- const { elapsedTime, createdAt } = this.loopState;
2207
- let adjustedCreated = 0;
2208
- if (this.stoppedTime > 0) {
2209
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2210
- this.stoppedTime = 0;
2211
- }
2212
- Object.assign(this.loopState, {
2213
- running: true,
2214
- elapsedTime: elapsedTime ?? 0,
2215
- lastTime: performance.now(),
2216
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2217
- frameCount: 0,
2218
- rafHandle: requestAnimationFrame(this.loop)
2219
- });
2220
- }
2221
- /**
2222
- * Stop the requestAnimationFrame loop.
2223
- * Cancels any pending RAF callback.
2224
- * No-op if not running.
2225
- * @returns {void}
2226
- */
2227
- stop() {
2228
- if (!this.loopState.running) return;
2229
- this.loopState.running = false;
2230
- if (this.loopState.rafHandle !== null) {
2231
- cancelAnimationFrame(this.loopState.rafHandle);
2232
- this.loopState.rafHandle = null;
2233
- }
2234
- this.stoppedTime = performance.now();
2235
- }
2236
- /**
2237
- * Request frames to be rendered in demand mode.
2238
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2239
- * No-op if frameloop is not 'demand'.
2240
- * @param {number} [frames=1] - Number of frames to request
2241
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2242
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2243
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2244
- * @returns {void}
2245
- * @example
2246
- * // Request a single frame render
2247
- * scheduler.invalidate();
2248
- *
2249
- * @example
2250
- * // Request 5 frames (e.g., for animations)
2251
- * scheduler.invalidate(5);
2252
- *
2253
- * @example
2254
- * // Set pending frames to exactly 3 (don't stack with existing)
2255
- * scheduler.invalidate(3, false);
2256
- *
2257
- * @example
2258
- * // Add 2 more frames to existing pending count
2259
- * scheduler.invalidate(2, true);
2260
- */
2261
- invalidate(frames = 1, stackFrames = false) {
2262
- if (this._frameloop !== "demand") return;
2263
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2264
- this.pendingFrames = Math.min(60, baseFrames + frames);
2265
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2266
- }
2267
- /**
2268
- * Reset timing state for deterministic testing.
2269
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2270
- * @returns {void}
2271
- */
2272
- resetTiming() {
2273
- this.loopState.lastTime = null;
2274
- this.loopState.frameCount = 0;
2275
- this.loopState.elapsedTime = 0;
2276
- this.loopState.createdAt = performance.now();
2277
- }
2278
- //* Manual Stepping Methods ================================
2279
- /**
2280
- * Manually execute a single frame for all roots.
2281
- * Useful for frameloop='never' mode or testing scenarios.
2282
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2283
- * @returns {void}
2284
- * @example
2285
- * // Manual control mode
2286
- * scheduler.frameloop = 'never';
2287
- * scheduler.step(); // Execute one frame
2288
- */
2289
- step(timestamp) {
2290
- const now = timestamp ?? performance.now();
2291
- this.executeFrame(now);
2292
- }
2293
- /**
2294
- * Manually execute a single job by its ID.
2295
- * Useful for testing individual job callbacks in isolation.
2296
- * @param {string} id - The job ID to step
2297
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2298
- * @returns {void}
2299
- */
2300
- stepJob(id, timestamp) {
2301
- let job;
2302
- let root;
2303
- for (const r of this.roots.values()) {
2304
- job = r.jobs.get(id);
2305
- if (job) {
2306
- root = r;
2307
- break;
2308
- }
2309
- }
2310
- if (!job || !root) {
2311
- console.warn(`[Scheduler] Job "${id}" not found`);
2312
- return;
2313
- }
2314
- const now = timestamp ?? performance.now();
2315
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2316
- const delta = deltaMs / 1e3;
2317
- const elapsed = now - this.loopState.createdAt;
2318
- const providedState = root.getState?.() ?? {};
2319
- const frameState = {
2320
- ...providedState,
2321
- time: now,
2322
- delta,
2323
- elapsed,
2324
- frame: this.loopState.frameCount
2325
- };
2326
- try {
2327
- job.callback(frameState, delta);
2328
- } catch (error) {
2329
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2330
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2331
- }
2332
- }
2333
- /**
2334
- * Execute a single frame across all roots.
2335
- * Order: globalBefore → each root's jobs → globalAfter
2336
- * @param {number} timestamp - RAF timestamp in milliseconds
2337
- * @returns {void}
2338
- * @private
2339
- */
2340
- executeFrame(timestamp) {
2341
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2342
- const delta = deltaMs / 1e3;
2343
- this.loopState.lastTime = timestamp;
2344
- this.loopState.frameCount++;
2345
- this.loopState.elapsedTime += deltaMs;
2346
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2347
- for (const root of this.roots.values()) {
2348
- this.tickRoot(root, timestamp, delta);
2349
- }
2350
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2351
- }
2352
- /**
2353
- * Run all global jobs from a job map.
2354
- * Catches and logs errors without stopping execution.
2355
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2356
- * @param {number} timestamp - RAF timestamp in milliseconds
2357
- * @returns {void}
2358
- * @private
2359
- */
2360
- runGlobalJobs(jobs, timestamp) {
2361
- for (const job of jobs.values()) {
2362
- try {
2363
- job.callback(timestamp);
2364
- } catch (error) {
2365
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2366
- }
2367
- }
2368
- }
2369
- /**
2370
- * Execute all jobs for a single root in sorted order.
2371
- * Rebuilds sorted job list if needed, then dispatches each job.
2372
- * Errors are caught and propagated via triggerError.
2373
- * @param {RootEntry} root - The root entry to tick
2374
- * @param {number} timestamp - RAF timestamp in milliseconds
2375
- * @param {number} delta - Time since last frame in seconds
2376
- * @returns {void}
2377
- * @private
2378
- */
2379
- tickRoot(root, timestamp, delta) {
2380
- if (root.needsRebuild) {
2381
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2382
- root.needsRebuild = false;
2383
- }
2384
- const providedState = root.getState?.() ?? {};
2385
- const frameState = {
2386
- ...providedState,
2387
- time: timestamp,
2388
- delta,
2389
- elapsed: this.loopState.elapsedTime / 1e3,
2390
- // Convert ms to seconds
2391
- frame: this.loopState.frameCount
2392
- };
2393
- for (const job of root.sortedJobs) {
2394
- if (!shouldRun(job, timestamp)) continue;
2395
- try {
2396
- job.callback(frameState, delta);
2397
- } catch (error) {
2398
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2399
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2400
- }
2401
- }
2402
- }
2403
- //* Debug & Inspection Methods ================================
2404
- /**
2405
- * Get the total number of registered jobs across all roots.
2406
- * Includes both per-root jobs and global before/after jobs.
2407
- * @returns {number} Total job count
2408
- */
2409
- getJobCount() {
2410
- let count = 0;
2411
- for (const root of this.roots.values()) {
2412
- count += root.jobs.size;
2413
- }
2414
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2415
- }
2416
- /**
2417
- * Get all registered job IDs across all roots.
2418
- * Includes both per-root jobs and global before/after jobs.
2419
- * @returns {string[]} Array of all job IDs
2420
- */
2421
- getJobIds() {
2422
- const ids = [];
2423
- for (const root of this.roots.values()) {
2424
- ids.push(...root.jobs.keys());
2425
- }
2426
- ids.push(...this.globalBeforeJobs.keys());
2427
- ids.push(...this.globalAfterJobs.keys());
2428
- return ids;
2429
- }
2430
- /**
2431
- * Get the number of registered roots (Canvas instances).
2432
- * @returns {number} Number of registered roots
2433
- */
2434
- getRootCount() {
2435
- return this.roots.size;
2436
- }
2437
- /**
2438
- * Check if any user (non-system) jobs are registered in a specific phase.
2439
- * Used by the default render job to know if a user has taken over rendering.
2440
- *
2441
- * @param phase The phase to check
2442
- * @param rootId Optional root ID to check (checks all roots if not provided)
2443
- * @returns true if any user jobs exist in the phase
2444
- */
2445
- hasUserJobsInPhase(phase, rootId) {
2446
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2447
- return rootsToCheck.some((root) => {
2448
- if (!root) return false;
2449
- for (const job of root.jobs.values()) {
2450
- if (job.phase === phase && !job.system && job.enabled) return true;
2451
- }
2452
- return false;
2453
- });
2454
- }
2455
- //* Utility Methods ================================
2456
- /**
2457
- * Generate a unique root ID for automatic root registration.
2458
- * @returns {string} A unique root ID in the format 'root_N'
2459
- */
2460
- generateRootId() {
2461
- return `root_${this.nextRootIndex++}`;
2462
- }
2463
- /**
2464
- * Generate a unique job ID.
2465
- * @returns {string} A unique job ID in the format 'job_N'
2466
- * @private
2467
- */
2468
- generateJobId() {
2469
- return `job_${this.nextJobIndex}`;
2470
- }
2471
- /**
2472
- * Normalize before/after constraints to a Set.
2473
- * Handles undefined, single string, or array inputs.
2474
- * @param {string | string[] | undefined} value - The constraint value(s)
2475
- * @returns {Set<string>} Normalized Set of constraint strings
2476
- * @private
2477
- */
2478
- normalizeConstraints(value) {
2479
- if (!value) return /* @__PURE__ */ new Set();
2480
- if (Array.isArray(value)) return new Set(value);
2481
- return /* @__PURE__ */ new Set([value]);
2482
- }
2483
- };
2484
- //* Static State & Methods (Singleton Usage) ================================
2485
- //* Cross-Bundle Singleton Key ==============================
2486
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2487
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2488
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2489
- let Scheduler = _Scheduler;
2490
- const getScheduler = () => Scheduler.get();
2491
- if (hmrData) {
2492
- hmrData.accept?.();
1691
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1692
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1693
+ if (!stack) return false;
1694
+ const caller = stack.split("\n")[callerDepth] ?? "";
1695
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2493
1696
  }
2494
1697
 
2495
1698
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2529,7 +1732,14 @@ const createStore = (invalidate, advance) => {
2529
1732
  frustum: new three.Frustum(),
2530
1733
  autoUpdateFrustum: true,
2531
1734
  raycaster: null,
2532
- events: { priority: 1, enabled: true, connected: false },
1735
+ events: {
1736
+ priority: 1,
1737
+ enabled: true,
1738
+ connected: false,
1739
+ frameTimedRaycasts: true,
1740
+ alwaysFireOnScroll: true,
1741
+ updateOnFrame: false
1742
+ },
2533
1743
  scene: null,
2534
1744
  rootScene: null,
2535
1745
  xr: null,
@@ -2594,7 +1804,7 @@ const createStore = (invalidate, advance) => {
2594
1804
  size: newSize,
2595
1805
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2596
1806
  }));
2597
- getScheduler().invalidate();
1807
+ scheduler.getScheduler().invalidate();
2598
1808
  }
2599
1809
  }
2600
1810
  return;
@@ -2609,7 +1819,7 @@ const createStore = (invalidate, advance) => {
2609
1819
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2610
1820
  _sizeImperative: true
2611
1821
  }));
2612
- getScheduler().invalidate();
1822
+ scheduler.getScheduler().invalidate();
2613
1823
  },
2614
1824
  setDpr: (dpr) => set((state2) => {
2615
1825
  const resolved = calculateDpr(dpr);
@@ -2617,14 +1827,18 @@ const createStore = (invalidate, advance) => {
2617
1827
  }),
2618
1828
  setFrameloop: (frameloop = "always") => {
2619
1829
  set(() => ({ frameloop }));
1830
+ scheduler.getScheduler().frameloop = frameloop;
2620
1831
  },
2621
1832
  setError: (error) => set(() => ({ error })),
2622
1833
  error: null,
2623
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1834
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2624
1835
  uniforms: {},
2625
1836
  nodes: {},
1837
+ buffers: {},
1838
+ gpuStorage: {},
2626
1839
  textures: /* @__PURE__ */ new Map(),
2627
- postProcessing: null,
1840
+ _textureRefs: /* @__PURE__ */ new Map(),
1841
+ renderPipeline: null,
2628
1842
  passes: {},
2629
1843
  _hmrVersion: 0,
2630
1844
  _sizeImperative: false,
@@ -2633,12 +1847,16 @@ const createStore = (invalidate, advance) => {
2633
1847
  internal: {
2634
1848
  // Events
2635
1849
  interaction: [],
2636
- hovered: /* @__PURE__ */ new Map(),
2637
1850
  subscribers: [],
1851
+ // Per-pointer state (new unified structure)
1852
+ pointerMap: /* @__PURE__ */ new Map(),
1853
+ pointerDirty: /* @__PURE__ */ new Map(),
1854
+ lastEvent: React__namespace.createRef(),
1855
+ // Deprecated but kept for backwards compatibility
1856
+ hovered: /* @__PURE__ */ new Map(),
2638
1857
  initialClick: [0, 0],
2639
1858
  initialHits: [],
2640
1859
  capturedMap: /* @__PURE__ */ new Map(),
2641
- lastEvent: React__namespace.createRef(),
2642
1860
  // Visibility tracking (onFramed, onOccluded, onVisible)
2643
1861
  visibilityRegistry: /* @__PURE__ */ new Map(),
2644
1862
  // Occlusion system (WebGPU only)
@@ -2677,8 +1895,7 @@ const createStore = (invalidate, advance) => {
2677
1895
  const currentState = rootStore.getState();
2678
1896
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2679
1897
  const stack = new Error().stack || "";
2680
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2681
- if (!isInternalAccess) {
1898
+ if (!isInternalRendererAccess(stack)) {
2682
1899
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2683
1900
  notifyDepreciated({
2684
1901
  heading: "Accessing state.gl in WebGPU mode",
@@ -2726,14 +1943,16 @@ const createStore = (invalidate, advance) => {
2726
1943
  oldSize = size;
2727
1944
  oldDpr = viewport.dpr;
2728
1945
  updateCamera(camera, size);
2729
- if (canvasTarget) {
1946
+ if (internal.isSecondary && canvasTarget) {
2730
1947
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2731
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2732
- canvasTarget.setSize(size.width, size.height, updateStyle);
1948
+ canvasTarget.setSize(size.width, size.height, false);
2733
1949
  } else {
2734
1950
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2735
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2736
- actualRenderer.setSize(size.width, size.height, updateStyle);
1951
+ actualRenderer.setSize(size.width, size.height, false);
1952
+ if (canvasTarget) {
1953
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1954
+ canvasTarget.setSize(size.width, size.height, false);
1955
+ }
2737
1956
  }
2738
1957
  }
2739
1958
  if (camera !== oldCamera) {
@@ -2789,26 +2008,32 @@ function loadingFn(extensions, onProgress) {
2789
2008
  );
2790
2009
  };
2791
2010
  }
2792
- function useLoader(loader, input, extensions, onProgress) {
2793
- const keys = Array.isArray(input) ? input : [input];
2011
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2012
+ const inputs = Array.isArray(input) ? input : [input];
2013
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2794
2014
  const fn = loadingFn(extensions, onProgress);
2795
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2015
+ const results = cacheKeys.map(
2016
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2017
+ );
2796
2018
  return Array.isArray(input) ? results : results[0];
2797
2019
  }
2798
- useLoader.preload = function(loader, input, extensions, onProgress) {
2799
- const keys = Array.isArray(input) ? input : [input];
2800
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2020
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2021
+ const inputs = Array.isArray(input) ? input : [input];
2022
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2023
+ cacheKeys.forEach(
2024
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2025
+ );
2801
2026
  };
2802
- useLoader.clear = function(loader, input) {
2803
- const keys = Array.isArray(input) ? input : [input];
2804
- keys.forEach((key) => suspendReact.clear([loader, key]));
2027
+ useLoader.clear = function(loader, input, cacheKey) {
2028
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2029
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
2805
2030
  };
2806
2031
  useLoader.loader = getLoader;
2807
2032
 
2808
2033
  function useFrame(callback, priorityOrOptions) {
2809
2034
  const store = React__namespace.useContext(context);
2810
2035
  const isInsideCanvas = store !== null;
2811
- const scheduler = getScheduler();
2036
+ const scheduler$1 = scheduler.getScheduler();
2812
2037
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2813
2038
  id: priorityOrOptions.id,
2814
2039
  phase: priorityOrOptions.phase,
@@ -2856,7 +2081,7 @@ function useFrame(callback, priorityOrOptions) {
2856
2081
  };
2857
2082
  callbackRef.current?.(mergedState, delta);
2858
2083
  };
2859
- const unregister = scheduler.register(wrappedCallback, {
2084
+ const unregister = scheduler$1.register(wrappedCallback, {
2860
2085
  id,
2861
2086
  rootId,
2862
2087
  ...options
@@ -2877,37 +2102,31 @@ function useFrame(callback, priorityOrOptions) {
2877
2102
  }
2878
2103
  };
2879
2104
  } else {
2880
- const registerOutside = () => {
2881
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2882
- };
2883
- if (scheduler.independent || scheduler.isReady) {
2884
- return registerOutside();
2885
- }
2886
- let unregisterJob = null;
2887
- const unsubReady = scheduler.onRootReady(() => {
2888
- unregisterJob = registerOutside();
2889
- });
2890
- return () => {
2891
- unsubReady();
2892
- unregisterJob?.();
2893
- };
2105
+ return scheduler$1.register(
2106
+ (state, delta) => {
2107
+ const frameState = state;
2108
+ if (!frameState.renderer) return;
2109
+ callbackRef.current?.(frameState, delta);
2110
+ },
2111
+ { id, ...options }
2112
+ );
2894
2113
  }
2895
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2114
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2896
2115
  const isPaused = React__namespace.useSyncExternalStore(
2897
2116
  // Subscribe function
2898
2117
  React__namespace.useCallback(
2899
2118
  (onStoreChange) => {
2900
- return getScheduler().subscribeJobState(id, onStoreChange);
2119
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
2901
2120
  },
2902
2121
  [id]
2903
2122
  ),
2904
2123
  // getSnapshot function
2905
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2124
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
2906
2125
  // getServerSnapshot function (SSR)
2907
2126
  React__namespace.useCallback(() => false, [])
2908
2127
  );
2909
2128
  const controls = React__namespace.useMemo(() => {
2910
- const scheduler2 = getScheduler();
2129
+ const scheduler2 = scheduler.getScheduler();
2911
2130
  return {
2912
2131
  /** The job's unique ID */
2913
2132
  id,
@@ -2922,7 +2141,7 @@ function useFrame(callback, priorityOrOptions) {
2922
2141
  * @param timestamp Optional timestamp (defaults to performance.now())
2923
2142
  */
2924
2143
  step: (timestamp) => {
2925
- getScheduler().stepJob(id, timestamp);
2144
+ scheduler.getScheduler().stepJob(id, timestamp);
2926
2145
  },
2927
2146
  /**
2928
2147
  * Manually step ALL jobs in the scheduler.
@@ -2930,20 +2149,20 @@ function useFrame(callback, priorityOrOptions) {
2930
2149
  * @param timestamp Optional timestamp (defaults to performance.now())
2931
2150
  */
2932
2151
  stepAll: (timestamp) => {
2933
- getScheduler().step(timestamp);
2152
+ scheduler.getScheduler().step(timestamp);
2934
2153
  },
2935
2154
  /**
2936
2155
  * Pause this job (set enabled=false).
2937
2156
  * Job remains registered but won't run.
2938
2157
  */
2939
2158
  pause: () => {
2940
- getScheduler().pauseJob(id);
2159
+ scheduler.getScheduler().pauseJob(id);
2941
2160
  },
2942
2161
  /**
2943
2162
  * Resume this job (set enabled=true).
2944
2163
  */
2945
2164
  resume: () => {
2946
- getScheduler().resumeJob(id);
2165
+ scheduler.getScheduler().resumeJob(id);
2947
2166
  },
2948
2167
  /**
2949
2168
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2981,18 +2200,18 @@ function buildFromCache(input, textureCache) {
2981
2200
  function useTexture(input, optionsOrOnLoad) {
2982
2201
  const renderer = useThree((state) => state.internal.actualRenderer);
2983
2202
  const store = useStore();
2984
- const textureCache = useThree((state) => state.textures);
2985
2203
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2986
- const { onLoad, cache = false } = options;
2204
+ const { onLoad, cache = true } = options;
2987
2205
  const onLoadRef = React.useRef(onLoad);
2988
2206
  onLoadRef.current = onLoad;
2989
2207
  const onLoadCalledForRef = React.useRef(null);
2990
2208
  const urls = React.useMemo(() => getUrls(input), [input]);
2991
2209
  const cachedResult = React.useMemo(() => {
2992
2210
  if (!cache) return null;
2993
- if (!allUrlsCached(urls, textureCache)) return null;
2994
- return buildFromCache(input, textureCache);
2995
- }, [cache, urls, textureCache, input]);
2211
+ const textures = store.getState().textures;
2212
+ if (!allUrlsCached(urls, textures)) return null;
2213
+ return buildFromCache(input, textures);
2214
+ }, [cache, urls, input, store]);
2996
2215
  const loadedTextures = useLoader(
2997
2216
  three.TextureLoader,
2998
2217
  IsObject(input) ? Object.values(input) : input
@@ -3036,8 +2255,6 @@ function useTexture(input, optionsOrOnLoad) {
3036
2255
  }, [input, loadedTextures, cachedResult]);
3037
2256
  React.useEffect(() => {
3038
2257
  if (!cache) return;
3039
- if (cachedResult) return;
3040
- const set = store.setState;
3041
2258
  const urlTextureMap = [];
3042
2259
  if (typeof input === "string") {
3043
2260
  urlTextureMap.push([input, mappedTextures]);
@@ -3051,18 +2268,32 @@ function useTexture(input, optionsOrOnLoad) {
3051
2268
  urlTextureMap.push([url, textureRecord[key]]);
3052
2269
  }
3053
2270
  }
3054
- set((state) => {
3055
- const newMap = new Map(state.textures);
3056
- let changed = false;
2271
+ store.setState((state) => {
2272
+ const refs = new Map(state._textureRefs);
2273
+ let textures = state.textures;
2274
+ let added = false;
3057
2275
  for (const [url, texture] of urlTextureMap) {
3058
- if (!newMap.has(url)) {
3059
- newMap.set(url, texture);
3060
- changed = true;
2276
+ if (!textures.has(url)) {
2277
+ if (!added) {
2278
+ textures = new Map(textures);
2279
+ added = true;
2280
+ }
2281
+ textures.set(url, texture);
3061
2282
  }
2283
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3062
2284
  }
3063
- return changed ? { textures: newMap } : state;
2285
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2286
+ });
2287
+ return () => store.setState((state) => {
2288
+ const refs = new Map(state._textureRefs);
2289
+ for (const [url] of urlTextureMap) {
2290
+ const next = (refs.get(url) ?? 0) - 1;
2291
+ if (next <= 0) refs.delete(url);
2292
+ else refs.set(url, next);
2293
+ }
2294
+ return { _textureRefs: refs };
3064
2295
  });
3065
- }, [cache, input, mappedTextures, store, cachedResult]);
2296
+ }, [cache, input, mappedTextures, store]);
3066
2297
  return mappedTextures;
3067
2298
  }
3068
2299
  useTexture.preload = (url) => useLoader.preload(three.TextureLoader, url);
@@ -3078,96 +2309,63 @@ const Texture = ({
3078
2309
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3079
2310
  };
3080
2311
 
3081
- function getTextureValue(entry) {
3082
- if (entry instanceof three.Texture) return entry;
3083
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof three.Texture) {
3084
- return entry.value;
3085
- }
3086
- return null;
3087
- }
3088
- function useTextures() {
2312
+ function useTextures(selector) {
3089
2313
  const store = useStore();
3090
- return React.useMemo(() => {
3091
- const set = store.setState;
2314
+ const registry = React.useMemo(() => {
3092
2315
  const getState = store.getState;
3093
- const add = (key, value) => {
3094
- set((state) => {
3095
- const newMap = new Map(state.textures);
3096
- newMap.set(key, value);
3097
- return { textures: newMap };
3098
- });
3099
- };
3100
- const addMultiple = (items) => {
3101
- set((state) => {
3102
- const newMap = new Map(state.textures);
3103
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3104
- for (const [key, value] of entries) {
3105
- newMap.set(key, value);
3106
- }
3107
- return { textures: newMap };
3108
- });
3109
- };
3110
- const remove = (key) => {
3111
- set((state) => {
3112
- const newMap = new Map(state.textures);
3113
- newMap.delete(key);
3114
- return { textures: newMap };
3115
- });
3116
- };
3117
- const removeMultiple = (keys) => {
3118
- set((state) => {
3119
- const newMap = new Map(state.textures);
3120
- for (const key of keys) newMap.delete(key);
3121
- return { textures: newMap };
3122
- });
3123
- };
3124
- const dispose = (key) => {
3125
- const entry = getState().textures.get(key);
3126
- if (entry) {
3127
- const tex = getTextureValue(entry);
3128
- tex?.dispose();
3129
- }
3130
- remove(key);
3131
- };
3132
- const disposeMultiple = (keys) => {
3133
- const textures = getState().textures;
3134
- for (const key of keys) {
3135
- const entry = textures.get(key);
3136
- if (entry) {
3137
- const tex = getTextureValue(entry);
3138
- tex?.dispose();
3139
- }
3140
- }
3141
- removeMultiple(keys);
3142
- };
3143
- const disposeAll = () => {
3144
- const textures = getState().textures;
3145
- for (const entry of textures.values()) {
3146
- const tex = getTextureValue(entry);
3147
- tex?.dispose();
3148
- }
3149
- set({ textures: /* @__PURE__ */ new Map() });
3150
- };
2316
+ const setState = store.setState;
2317
+ const getOne = (key) => getState().textures.get(key);
3151
2318
  return {
3152
- // Getter for the textures Map (reactive via getState)
3153
- get textures() {
2319
+ get all() {
3154
2320
  return getState().textures;
3155
2321
  },
3156
- // Read
3157
- get: (key) => getState().textures.get(key),
2322
+ get(input) {
2323
+ if (typeof input === "string") return getOne(input);
2324
+ if (Array.isArray(input)) return input.map(getOne);
2325
+ const out = {};
2326
+ for (const name in input) out[name] = getOne(input[name]);
2327
+ return out;
2328
+ },
3158
2329
  has: (key) => getState().textures.has(key),
3159
- // Write
3160
- add,
3161
- addMultiple,
3162
- // Remove (cache only)
3163
- remove,
3164
- removeMultiple,
3165
- // Dispose (GPU + cache)
3166
- dispose,
3167
- disposeMultiple,
3168
- disposeAll
2330
+ add(keyOrRecord, texture) {
2331
+ setState((state) => {
2332
+ const textures = new Map(state.textures);
2333
+ if (typeof keyOrRecord === "string") {
2334
+ textures.set(keyOrRecord, texture);
2335
+ } else {
2336
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2337
+ }
2338
+ return { textures };
2339
+ });
2340
+ },
2341
+ dispose(key, options) {
2342
+ const state = getState();
2343
+ const refs = state._textureRefs.get(key) ?? 0;
2344
+ if (refs > 0 && !options?.force) {
2345
+ console.warn(
2346
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2347
+ );
2348
+ return false;
2349
+ }
2350
+ state.textures.get(key)?.dispose();
2351
+ setState((s) => {
2352
+ const textures = new Map(s.textures);
2353
+ textures.delete(key);
2354
+ const nextRefs = new Map(s._textureRefs);
2355
+ nextRefs.delete(key);
2356
+ return { textures, _textureRefs: nextRefs };
2357
+ });
2358
+ return true;
2359
+ },
2360
+ disposeAll() {
2361
+ for (const texture of getState().textures.values()) texture.dispose();
2362
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2363
+ }
3169
2364
  };
3170
2365
  }, [store]);
2366
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2367
+ const selected = useThree(subscribe);
2368
+ return selector ? selected : registry;
3171
2369
  }
3172
2370
 
3173
2371
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3222,7 +2420,7 @@ function addEffect(callback) {
3222
2420
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3223
2421
  });
3224
2422
  const id = `legacy_effect_${effectId++}`;
3225
- return getScheduler().registerGlobal("before", id, callback);
2423
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3226
2424
  }
3227
2425
  function addAfterEffect(callback) {
3228
2426
  notifyDepreciated({
@@ -3231,7 +2429,7 @@ function addAfterEffect(callback) {
3231
2429
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3232
2430
  });
3233
2431
  const id = `legacy_afterEffect_${effectId++}`;
3234
- return getScheduler().registerGlobal("after", id, callback);
2432
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3235
2433
  }
3236
2434
  function addTail(callback) {
3237
2435
  notifyDepreciated({
@@ -3239,16 +2437,16 @@ function addTail(callback) {
3239
2437
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3240
2438
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3241
2439
  });
3242
- return getScheduler().onIdle(callback);
2440
+ return scheduler.getScheduler().onIdle(callback);
3243
2441
  }
3244
2442
  function invalidate(state, frames = 1, stackFrames = false) {
3245
- getScheduler().invalidate(frames, stackFrames);
2443
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3246
2444
  }
3247
2445
  function advance(timestamp) {
3248
- getScheduler().step(timestamp);
2446
+ scheduler.getScheduler().step(timestamp);
3249
2447
  }
3250
2448
 
3251
- const version = "10.0.0-alpha.2";
2449
+ const version = "10.0.0-alpha.3";
3252
2450
  const packageData = {
3253
2451
  version: version};
3254
2452
 
@@ -14687,6 +13885,7 @@ function swapInstances() {
14687
13885
  }
14688
13886
  }
14689
13887
  if (instance.isHidden) unhideInstance(instance);
13888
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14690
13889
  if (instance.object.__r3f) delete instance.object.__r3f;
14691
13890
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14692
13891
  }
@@ -14699,6 +13898,8 @@ function swapInstances() {
14699
13898
  instance.object.__r3f = instance;
14700
13899
  setFiberRef(fiber, instance.object);
14701
13900
  delete instance.appliedOnce;
13901
+ instance.eventCount = 0;
13902
+ instance.handlers = {};
14702
13903
  applyProps(instance.object, instance.props);
14703
13904
  if (instance.props.attach) {
14704
13905
  attach(parent, instance);
@@ -14914,11 +14115,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14914
14115
  cloneMutableTextInstance(textInstance) {
14915
14116
  return textInstance;
14916
14117
  },
14118
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14119
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14120
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14121
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14122
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14123
+ // Guarded by a test asserting a full render + unmount never reaches them.
14917
14124
  cloneRootViewTransitionContainer(_rootContainer) {
14918
- throw new Error("Not implemented.");
14919
14125
  },
14920
14126
  removeRootViewTransitionClone(_rootContainer, _clone) {
14921
- throw new Error("Not implemented.");
14922
14127
  },
14923
14128
  // https://github.com/facebook/react/pull/32465
14924
14129
  createFragmentInstance: (_fiber) => null,
@@ -15003,6 +14208,7 @@ function createRoot(canvas) {
15003
14208
  const lastConfiguredProps = {};
15004
14209
  let configured = false;
15005
14210
  let pending = null;
14211
+ let rendererSetup = null;
15006
14212
  return {
15007
14213
  async configure(props = {}) {
15008
14214
  let resolve;
@@ -15018,7 +14224,6 @@ function createRoot(canvas) {
15018
14224
  events,
15019
14225
  onCreated: onCreatedCallback,
15020
14226
  shadows = false,
15021
- textureColorSpace = three.SRGBColorSpace,
15022
14227
  orthographic = false,
15023
14228
  frameloop = "always",
15024
14229
  dpr = [1, 2],
@@ -15033,7 +14238,8 @@ function createRoot(canvas) {
15033
14238
  _sizeProps,
15034
14239
  forceEven
15035
14240
  } = props;
15036
- const state = store.getState();
14241
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || three.SRGBColorSpace;
14242
+ let state = store.getState();
15037
14243
  const defaultGLProps = {
15038
14244
  canvas,
15039
14245
  powerPreference: "high-performance",
@@ -15061,9 +14267,21 @@ function createRoot(canvas) {
15061
14267
  );
15062
14268
  }
15063
14269
  if (!state.internal.actualRenderer) {
15064
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
15065
- state.internal.actualRenderer = renderer;
15066
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14270
+ if (!rendererSetup) {
14271
+ rendererSetup = (async () => {
14272
+ {
14273
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14274
+ state.internal.actualRenderer = renderer;
14275
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14276
+ }
14277
+ })().catch((err) => {
14278
+ rendererSetup = null;
14279
+ throw err;
14280
+ });
14281
+ }
14282
+ await rendererSetup;
14283
+ state = store.getState();
14284
+ renderer = state.internal.actualRenderer;
15067
14285
  }
15068
14286
  let raycaster = state.raycaster;
15069
14287
  if (!raycaster) state.set({ raycaster: raycaster = new three.Raycaster() });
@@ -15156,7 +14374,7 @@ function createRoot(canvas) {
15156
14374
  lastConfiguredProps.performance = performance;
15157
14375
  }
15158
14376
  if (!state.xr) {
15159
- const handleXRFrame = (timestamp, frame) => {
14377
+ const handleXRFrame = (timestamp, _frame) => {
15160
14378
  const state2 = store.getState();
15161
14379
  if (state2.frameloop === "never") return;
15162
14380
  advance(timestamp);
@@ -15192,15 +14410,22 @@ function createRoot(canvas) {
15192
14410
  const oldType = renderer.shadowMap.type;
15193
14411
  renderer.shadowMap.enabled = !!shadows;
15194
14412
  if (is.boo(shadows)) {
15195
- renderer.shadowMap.type = three.PCFSoftShadowMap;
14413
+ renderer.shadowMap.type = three.PCFShadowMap;
15196
14414
  } else if (is.str(shadows)) {
14415
+ if (shadows === "soft") {
14416
+ notifyDepreciated({
14417
+ heading: 'shadows="soft" is deprecated',
14418
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14419
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14420
+ });
14421
+ }
15197
14422
  const types = {
15198
14423
  basic: three.BasicShadowMap,
15199
14424
  percentage: three.PCFShadowMap,
15200
- soft: three.PCFSoftShadowMap,
14425
+ soft: three.PCFShadowMap,
15201
14426
  variance: three.VSMShadowMap
15202
14427
  };
15203
- renderer.shadowMap.type = types[shadows] ?? three.PCFSoftShadowMap;
14428
+ renderer.shadowMap.type = types[shadows] ?? three.PCFShadowMap;
15204
14429
  } else if (is.obj(shadows)) {
15205
14430
  Object.assign(renderer.shadowMap, shadows);
15206
14431
  }
@@ -15216,24 +14441,35 @@ function createRoot(canvas) {
15216
14441
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15217
14442
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15218
14443
  }
14444
+ const r3fProps = ["textureColorSpace"];
14445
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14446
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15219
14447
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15220
- applyProps(renderer, glConfig);
14448
+ const glProps = {};
14449
+ for (const key in glConfig) {
14450
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14451
+ }
14452
+ applyProps(renderer, glProps);
15221
14453
  }
15222
14454
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15223
14455
  const currentRenderer = state.renderer;
15224
14456
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15225
- applyProps(currentRenderer, rendererConfig);
14457
+ const rendererProps = {};
14458
+ for (const key in rendererConfig) {
14459
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14460
+ }
14461
+ applyProps(currentRenderer, rendererProps);
15226
14462
  }
15227
14463
  }
15228
- const scheduler = getScheduler();
14464
+ const scheduler$1 = scheduler.getScheduler();
15229
14465
  const rootId = state.internal.rootId;
15230
14466
  if (!rootId) {
15231
- const newRootId = canvasId || scheduler.generateRootId();
15232
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14467
+ const newRootId = canvasId || scheduler$1.generateRootId();
14468
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15233
14469
  getState: () => store.getState(),
15234
14470
  onError: (err) => store.getState().setError(err)
15235
14471
  });
15236
- const unregisterCanvasTarget = scheduler.register(
14472
+ const unregisterCanvasTarget = scheduler$1.register(
15237
14473
  () => {
15238
14474
  const state2 = store.getState();
15239
14475
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15248,7 +14484,19 @@ function createRoot(canvas) {
15248
14484
  system: true
15249
14485
  }
15250
14486
  );
15251
- const unregisterFrustum = scheduler.register(
14487
+ const unregisterEventsFlush = scheduler$1.register(
14488
+ () => {
14489
+ const state2 = store.getState();
14490
+ state2.events.flush?.();
14491
+ },
14492
+ {
14493
+ id: `${newRootId}_events`,
14494
+ rootId: newRootId,
14495
+ phase: "input",
14496
+ system: true
14497
+ }
14498
+ );
14499
+ const unregisterFrustum = scheduler$1.register(
15252
14500
  () => {
15253
14501
  const state2 = store.getState();
15254
14502
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15258,11 +14506,11 @@ function createRoot(canvas) {
15258
14506
  {
15259
14507
  id: `${newRootId}_frustum`,
15260
14508
  rootId: newRootId,
15261
- phase: "preRender",
14509
+ before: "render",
15262
14510
  system: true
15263
14511
  }
15264
14512
  );
15265
- const unregisterVisibility = scheduler.register(
14513
+ const unregisterVisibility = scheduler$1.register(
15266
14514
  () => {
15267
14515
  const state2 = store.getState();
15268
14516
  checkVisibility(state2);
@@ -15270,19 +14518,19 @@ function createRoot(canvas) {
15270
14518
  {
15271
14519
  id: `${newRootId}_visibility`,
15272
14520
  rootId: newRootId,
15273
- phase: "preRender",
14521
+ before: "render",
15274
14522
  system: true,
15275
14523
  after: `${newRootId}_frustum`
15276
14524
  }
15277
14525
  );
15278
- const unregisterRender = scheduler.register(
14526
+ const unregisterRender = scheduler$1.register(
15279
14527
  () => {
15280
14528
  const state2 = store.getState();
15281
14529
  const renderer2 = state2.internal.actualRenderer;
15282
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14530
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15283
14531
  if (userHandlesRender || state2.internal.priority) return;
15284
14532
  try {
15285
- if (state2.postProcessing?.render) state2.postProcessing.render();
14533
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
15286
14534
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
15287
14535
  } catch (error) {
15288
14536
  state2.setError(error instanceof Error ? error : new Error(String(error)));
@@ -15307,15 +14555,16 @@ function createRoot(canvas) {
15307
14555
  unregisterRoot: () => {
15308
14556
  unregisterRoot();
15309
14557
  unregisterCanvasTarget();
14558
+ unregisterEventsFlush();
15310
14559
  unregisterFrustum();
15311
14560
  unregisterVisibility();
15312
14561
  unregisterRender();
15313
14562
  },
15314
- scheduler
14563
+ scheduler: scheduler$1
15315
14564
  }
15316
14565
  }));
15317
14566
  }
15318
- scheduler.frameloop = frameloop;
14567
+ scheduler$1.frameloop = frameloop;
15319
14568
  onCreated = onCreatedCallback;
15320
14569
  configured = true;
15321
14570
  resolve();
@@ -15382,7 +14631,8 @@ function unmountComponentAtNode(canvas, callback) {
15382
14631
  dispose(state.scene);
15383
14632
  _roots.delete(canvas);
15384
14633
  if (callback) callback(canvas);
15385
- } catch {
14634
+ } catch (error) {
14635
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15386
14636
  }
15387
14637
  }, 500);
15388
14638
  }
@@ -15445,6 +14695,7 @@ function PortalInner({ state = {}, children, container }) {
15445
14695
  viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), resolvedSize);
15446
14696
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15447
14697
  }
14698
+ const set = injectState.set;
15448
14699
  return {
15449
14700
  // The intersect consists of the previous root state
15450
14701
  ...rootState,
@@ -15463,7 +14714,7 @@ function PortalInner({ state = {}, children, container }) {
15463
14714
  size: resolvedSize,
15464
14715
  viewport: { ...rootState.viewport, ...viewport },
15465
14716
  // Layers are allowed to override events
15466
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14717
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15467
14718
  // Container for child attachment - the portalScene (injected or container itself)
15468
14719
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15469
14720
  };
@@ -15472,9 +14723,13 @@ function PortalInner({ state = {}, children, container }) {
15472
14723
  const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15473
14724
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15474
14725
  onMutate(previousRoot.getState());
15475
- previousRoot.subscribe(onMutate);
15476
14726
  return store;
15477
14727
  }, [previousRoot, container]);
14728
+ useIsomorphicLayoutEffect(() => {
14729
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14730
+ const unsubscribe = previousRoot.subscribe(onMutate);
14731
+ return unsubscribe;
14732
+ }, [previousRoot, usePortalStore]);
15478
14733
  return (
15479
14734
  // @ts-ignore, reconciler types are not maintained
15480
14735
  /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
@@ -15488,6 +14743,81 @@ function flushSync(fn) {
15488
14743
  return reconciler.flushSyncFromReconciler(fn);
15489
14744
  }
15490
14745
 
14746
+ function parseBackground(background) {
14747
+ if (!background) return null;
14748
+ if (typeof background === "object" && !background.isColor) {
14749
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14750
+ return {
14751
+ ...rest,
14752
+ preset,
14753
+ files: envMap || files,
14754
+ backgroundFiles: backgroundMap,
14755
+ background: true
14756
+ };
14757
+ }
14758
+ if (typeof background === "number") {
14759
+ return { color: background, background: true };
14760
+ }
14761
+ if (typeof background === "string") {
14762
+ if (background in presetsObj) {
14763
+ return { preset: background, background: true };
14764
+ }
14765
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14766
+ return { files: background, background: true };
14767
+ }
14768
+ return { color: background, background: true };
14769
+ }
14770
+ if (background.isColor) {
14771
+ return { color: background, background: true };
14772
+ }
14773
+ return null;
14774
+ }
14775
+
14776
+ function parseRendererConfig(rendererProp) {
14777
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14778
+ if (isRendererConfig) {
14779
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14780
+ return {
14781
+ primaryCanvas: pc,
14782
+ scheduler: sc,
14783
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14784
+ };
14785
+ }
14786
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14787
+ }
14788
+
14789
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14790
+ const registries = /* @__PURE__ */ new WeakMap();
14791
+ function getKindRegistry(store, kind) {
14792
+ let registry = registries.get(store);
14793
+ if (!registry) {
14794
+ registry = {
14795
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14796
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14797
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14798
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14799
+ };
14800
+ registries.set(store, registry);
14801
+ }
14802
+ return registry[kind];
14803
+ }
14804
+ function invalidateResource(store, kind, scopeKey) {
14805
+ const registry = getKindRegistry(store, kind);
14806
+ {
14807
+ registry.valid.clear();
14808
+ registry.staged.clear();
14809
+ }
14810
+ }
14811
+ function invalidateAllResources(store) {
14812
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14813
+ }
14814
+
14815
+ function clearHmrCaches(store) {
14816
+ const primary = store.getState().primaryStore ?? store;
14817
+ invalidateAllResources(primary);
14818
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14819
+ }
14820
+
15491
14821
  function CanvasImpl({
15492
14822
  ref,
15493
14823
  children,
@@ -15508,6 +14838,8 @@ function CanvasImpl({
15508
14838
  raycaster,
15509
14839
  camera,
15510
14840
  scene,
14841
+ autoUpdateFrustum,
14842
+ occlusion,
15511
14843
  onPointerMissed,
15512
14844
  onDragOverMissed,
15513
14845
  onDropMissed,
@@ -15519,39 +14851,10 @@ function CanvasImpl({
15519
14851
  forceEven,
15520
14852
  ...props
15521
14853
  }) {
15522
- 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 };
15523
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14854
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15524
14855
  React__namespace.useMemo(() => extend(THREE), []);
15525
14856
  const Bridge = useBridge();
15526
- const backgroundProps = React__namespace.useMemo(() => {
15527
- if (!background) return null;
15528
- if (typeof background === "object" && !background.isColor) {
15529
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15530
- return {
15531
- ...rest,
15532
- preset,
15533
- files: envMap || files,
15534
- backgroundFiles: backgroundMap,
15535
- background: true
15536
- };
15537
- }
15538
- if (typeof background === "number") {
15539
- return { color: background, background: true };
15540
- }
15541
- if (typeof background === "string") {
15542
- if (background in presetsObj) {
15543
- return { preset: background, background: true };
15544
- }
15545
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15546
- return { files: background, background: true };
15547
- }
15548
- return { color: background, background: true };
15549
- }
15550
- if (background.isColor) {
15551
- return { color: background, background: true };
15552
- }
15553
- return null;
15554
- }, [background]);
14857
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15555
14858
  const hasInitialSizeRef = React__namespace.useRef(false);
15556
14859
  const measureConfig = React__namespace.useMemo(() => {
15557
14860
  if (!hasInitialSizeRef.current) {
@@ -15593,6 +14896,7 @@ function CanvasImpl({
15593
14896
  const handleDropMissed = useMutableCallback(onDropMissed);
15594
14897
  const [block, setBlock] = React__namespace.useState(false);
15595
14898
  const [error, setError] = React__namespace.useState(false);
14899
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15596
14900
  if (block) throw block;
15597
14901
  if (error) throw error;
15598
14902
  const root = React__namespace.useRef(null);
@@ -15600,6 +14904,7 @@ function CanvasImpl({
15600
14904
  const unsubscribeErrorRef = React__namespace.useRef(null);
15601
14905
  useIsomorphicLayoutEffect(() => {
15602
14906
  effectActiveRef.current = true;
14907
+ if (fallbackVisible) return;
15603
14908
  const canvas = canvasRef.current;
15604
14909
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15605
14910
  if (!root.current) {
@@ -15620,7 +14925,7 @@ function CanvasImpl({
15620
14925
  }
15621
14926
  async function run() {
15622
14927
  if (!effectActiveRef.current || !root.current) return;
15623
- await root.current.configure({
14928
+ const configured = await root.current.configure({
15624
14929
  id,
15625
14930
  primaryCanvas,
15626
14931
  scheduler,
@@ -15635,6 +14940,8 @@ function CanvasImpl({
15635
14940
  performance,
15636
14941
  raycaster,
15637
14942
  camera,
14943
+ autoUpdateFrustum,
14944
+ occlusion,
15638
14945
  size: effectiveSize,
15639
14946
  // Store size props for reset functionality
15640
14947
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15659,8 +14966,20 @@ function CanvasImpl({
15659
14966
  }
15660
14967
  onCreated?.(state);
15661
14968
  }
15662
- });
15663
- if (!effectActiveRef.current || !root.current) return;
14969
+ }).then(
14970
+ () => true,
14971
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14972
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14973
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14974
+ (setupError) => {
14975
+ if (effectActiveRef.current) {
14976
+ if (fallback != null) setFallbackVisible(true);
14977
+ else setError(setupError);
14978
+ }
14979
+ return false;
14980
+ }
14981
+ );
14982
+ if (!configured || !effectActiveRef.current || !root.current) return;
15664
14983
  root.current.render(
15665
14984
  /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: [
15666
14985
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15694,20 +15013,13 @@ function CanvasImpl({
15694
15013
  const handleHMR = () => {
15695
15014
  queueMicrotask(() => {
15696
15015
  const rootEntry = _roots.get(canvas);
15697
- if (rootEntry?.store) {
15698
- rootEntry.store.setState((state) => ({
15699
- nodes: {},
15700
- uniforms: {},
15701
- _hmrVersion: state._hmrVersion + 1
15702
- }));
15703
- }
15016
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15704
15017
  });
15705
15018
  };
15706
15019
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('legacy.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
15707
15020
  const hot = undefined;
15708
15021
  hot.on("vite:afterUpdate", handleHMR);
15709
- return () => hot.dispose?.(() => {
15710
- });
15022
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
15711
15023
  }
15712
15024
  if (typeof module !== "undefined" && module.hot) {
15713
15025
  const hot = module.hot;
@@ -15730,7 +15042,20 @@ function CanvasImpl({
15730
15042
  ...style
15731
15043
  },
15732
15044
  ...props,
15733
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx("canvas", { ref: canvasRef, id, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
15045
+ children: fallbackVisible ? (
15046
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15047
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15048
+ fallback
15049
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15050
+ "canvas",
15051
+ {
15052
+ ref: canvasRef,
15053
+ id,
15054
+ className: "r3f-canvas",
15055
+ style: { display: "block", width: "100%", height: "100%" },
15056
+ children: fallback
15057
+ }
15058
+ ) })
15734
15059
  }
15735
15060
  );
15736
15061
  }
@@ -15740,6 +15065,8 @@ function Canvas(props) {
15740
15065
 
15741
15066
  extend(THREE);
15742
15067
 
15068
+ exports.Scheduler = scheduler.Scheduler;
15069
+ exports.getScheduler = scheduler.getScheduler;
15743
15070
  exports.Block = Block;
15744
15071
  exports.Canvas = Canvas;
15745
15072
  exports.Environment = Environment;
@@ -15755,7 +15082,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15755
15082
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15756
15083
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15757
15084
  exports.RESERVED_PROPS = RESERVED_PROPS;
15758
- exports.Scheduler = Scheduler;
15759
15085
  exports.Texture = Texture;
15760
15086
  exports._roots = _roots;
15761
15087
  exports.act = act;
@@ -15785,7 +15111,6 @@ exports.getInstanceProps = getInstanceProps;
15785
15111
  exports.getPrimary = getPrimary;
15786
15112
  exports.getPrimaryIds = getPrimaryIds;
15787
15113
  exports.getRootState = getRootState;
15788
- exports.getScheduler = getScheduler;
15789
15114
  exports.getUuidPrefix = getUuidPrefix;
15790
15115
  exports.hasConstructor = hasConstructor;
15791
15116
  exports.hasPrimary = hasPrimary;