@react-three/fiber 10.0.0-canary.604355a → 10.0.0-canary.6d6e5ab

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,10 +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);
446
- const act = React__namespace["act"];
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);
447
466
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
448
467
  function useMutableCallback(fn) {
449
468
  const ref = React__namespace.useRef(fn);
@@ -474,7 +493,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
474
493
  return _a = class extends React__namespace.Component {
475
494
  constructor() {
476
495
  super(...arguments);
477
- __publicField$2(this, "state", { error: false });
496
+ __publicField(this, "state", { error: false });
478
497
  }
479
498
  componentDidCatch(err) {
480
499
  this.props.set(err);
@@ -482,7 +501,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
482
501
  render() {
483
502
  return this.state.error ? null : this.props.children;
484
503
  }
485
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
504
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
505
  })();
487
506
 
488
507
  const is = {
@@ -619,8 +638,7 @@ function prepare(target, root, type, props) {
619
638
  object,
620
639
  eventCount: 0,
621
640
  handlers: {},
622
- isHidden: false,
623
- deferredRefs: []
641
+ isHidden: false
624
642
  };
625
643
  if (object) object.__r3f = instance;
626
644
  }
@@ -777,6 +795,17 @@ function unregisterVisibility(store, object) {
777
795
  internal.visibilityRegistry.delete(object.uuid);
778
796
  internal.occlusionCache.delete(object);
779
797
  }
798
+ function updateVisibilityHandlers(store, object, handlers) {
799
+ const { internal } = store.getState();
800
+ const entry = internal.visibilityRegistry.get(object.uuid);
801
+ if (!entry) return false;
802
+ entry.handlers = handlers;
803
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
804
+ object.occlusionTest = true;
805
+ enableOcclusion(store);
806
+ }
807
+ return true;
808
+ }
780
809
  function checkVisibility(state) {
781
810
  const { internal, camera } = state;
782
811
  const registry = internal.visibilityRegistry;
@@ -937,9 +966,9 @@ function diffProps(instance, newProps) {
937
966
  const { root, key } = resolve(instance.object, prop);
938
967
  if (root.constructor && root.constructor.length === 0) {
939
968
  const ctor = getMemoizedPrototype(root);
940
- if (!is.und(ctor)) changedProps[key] = ctor[key];
969
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
941
970
  } else {
942
- changedProps[key] = 0;
971
+ changedProps[prop] = 0;
943
972
  }
944
973
  }
945
974
  return changedProps;
@@ -964,10 +993,7 @@ function applyProps(object, props) {
964
993
  continue;
965
994
  }
966
995
  if (value === void 0) continue;
967
- if (isFromRef(value)) {
968
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
969
- continue;
970
- }
996
+ if (isFromRef(value)) continue;
971
997
  if (isOnce(value)) {
972
998
  if (instance?.appliedOnce?.has(prop)) continue;
973
999
  if (instance) {
@@ -1003,8 +1029,24 @@ function applyProps(object, props) {
1003
1029
  } else if (isVectorLike(target) && is.num(value)) {
1004
1030
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1005
1031
  else target.set(value);
1032
+ } else if (root instanceof three.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1033
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1034
+ const uniforms = root.uniforms;
1035
+ const nextUniforms = value;
1036
+ for (const name in nextUniforms) {
1037
+ const uniform = nextUniforms[name];
1038
+ const targetUniform = uniforms[name];
1039
+ if (targetUniform) Object.assign(targetUniform, uniform);
1040
+ else {
1041
+ const nextUniform = uniform instanceof three.Uniform ? uniform.clone() : new three.Uniform(uniform.value);
1042
+ uniforms[name] = nextUniform;
1043
+ }
1044
+ }
1006
1045
  } else {
1007
1046
  root[key] = value;
1047
+ if (key.endsWith("Node") && root.isMaterial) {
1048
+ root.needsUpdate = true;
1049
+ }
1008
1050
  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
1051
  root[key].format === three.RGBAFormat && root[key].type === three.UnsignedByteType) {
1010
1052
  root[key].colorSpace = rootState.textureColorSpace;
@@ -1018,6 +1060,9 @@ function applyProps(object, props) {
1018
1060
  if (instance.eventCount && object2.raycast !== null) {
1019
1061
  rootState.internal.interaction.push(object2);
1020
1062
  }
1063
+ }
1064
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1065
+ const object2 = instance.object;
1021
1066
  const root = findInitialRoot(instance);
1022
1067
  const visibilityHandlers = {
1023
1068
  onFramed: instance.handlers.onFramed,
@@ -1025,7 +1070,9 @@ function applyProps(object, props) {
1025
1070
  onVisible: instance.handlers.onVisible
1026
1071
  };
1027
1072
  if (hasVisibilityHandlers(visibilityHandlers)) {
1028
- registerVisibility(root, object2, visibilityHandlers);
1073
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1074
+ registerVisibility(root, object2, visibilityHandlers);
1075
+ }
1029
1076
  } else {
1030
1077
  unregisterVisibility(root, object2);
1031
1078
  }
@@ -1038,38 +1085,60 @@ function applyProps(object, props) {
1038
1085
  return object;
1039
1086
  }
1040
1087
 
1088
+ const DEFAULT_POINTER_ID = 0;
1089
+ const XR_POINTER_ID_START = 1e3;
1090
+ function getPointerState(internal, pointerId) {
1091
+ let state = internal.pointerMap.get(pointerId);
1092
+ if (!state) {
1093
+ state = {
1094
+ hovered: /* @__PURE__ */ new Map(),
1095
+ captured: /* @__PURE__ */ new Map(),
1096
+ initialClick: [0, 0],
1097
+ initialHits: []
1098
+ };
1099
+ internal.pointerMap.set(pointerId, state);
1100
+ }
1101
+ return state;
1102
+ }
1103
+ function getPointerId(event) {
1104
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1105
+ }
1041
1106
  function makeId(event) {
1042
1107
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
1043
1108
  }
1044
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
1045
- const captureData = captures.get(obj);
1109
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1110
+ const pointerState = internal.pointerMap.get(pointerId);
1111
+ if (!pointerState) return;
1112
+ const captureData = pointerState.captured.get(obj);
1046
1113
  if (captureData) {
1047
- captures.delete(obj);
1048
- if (captures.size === 0) {
1049
- capturedMap.delete(pointerId);
1050
- captureData.target.releasePointerCapture(pointerId);
1051
- }
1114
+ pointerState.captured.delete(obj);
1115
+ captureData.target.releasePointerCapture(pointerId);
1052
1116
  }
1053
1117
  }
1054
1118
  function removeInteractivity(store, object) {
1055
1119
  const { internal } = store.getState();
1056
1120
  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);
1121
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1122
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1123
+ pointerState.hovered.forEach((value, key) => {
1124
+ if (value.eventObject === object || value.object === object) {
1125
+ pointerState.hovered.delete(key);
1126
+ }
1127
+ });
1128
+ if (pointerState.captured.has(object)) {
1129
+ releaseInternalPointerCapture(internal, object, pointerId);
1061
1130
  }
1062
- });
1063
- internal.capturedMap.forEach((captures, pointerId) => {
1064
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
1065
- });
1131
+ }
1066
1132
  unregisterVisibility(store, object);
1067
1133
  }
1068
1134
  function createEvents(store) {
1069
- function calculateDistance(event) {
1135
+ function calculateDistance(event, pointerId) {
1070
1136
  const { internal } = store.getState();
1071
- const dx = event.offsetX - internal.initialClick[0];
1072
- const dy = event.offsetY - internal.initialClick[1];
1137
+ const pointerState = internal.pointerMap.get(pointerId);
1138
+ if (!pointerState) return 0;
1139
+ const [initialX, initialY] = pointerState.initialClick;
1140
+ const dx = event.offsetX - initialX;
1141
+ const dy = event.offsetY - initialY;
1073
1142
  return Math.round(Math.sqrt(dx * dx + dy * dy));
1074
1143
  }
1075
1144
  function filterPointerEvents(objects) {
@@ -1105,6 +1174,15 @@ function createEvents(store) {
1105
1174
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
1106
1175
  }
1107
1176
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1177
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1178
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1179
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1180
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1181
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1182
+ if (aInteractivePriority !== bInteractivePriority) {
1183
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1184
+ }
1185
+ }
1108
1186
  const aState = getRootState(a.object);
1109
1187
  const bState = getRootState(b.object);
1110
1188
  const aPriority = aState?.events?.priority ?? 1;
@@ -1126,9 +1204,13 @@ function createEvents(store) {
1126
1204
  eventObject = eventObject.parent;
1127
1205
  }
1128
1206
  }
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);
1207
+ if ("pointerId" in event) {
1208
+ const pointerId = event.pointerId;
1209
+ const pointerState = state.internal.pointerMap.get(pointerId);
1210
+ if (pointerState?.captured.size) {
1211
+ for (const captureData of pointerState.captured.values()) {
1212
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1213
+ }
1132
1214
  }
1133
1215
  }
1134
1216
  return intersections;
@@ -1141,27 +1223,25 @@ function createEvents(store) {
1141
1223
  if (state) {
1142
1224
  const { raycaster, pointer, camera, internal } = state;
1143
1225
  const unprojectedPoint = new three.Vector3(pointer.x, pointer.y, 0).unproject(camera);
1144
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1226
+ const hasPointerCapture = (id) => {
1227
+ const pointerState = internal.pointerMap.get(id);
1228
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1229
+ };
1145
1230
  const setPointerCapture = (id) => {
1146
1231
  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
- }
1232
+ const pointerState = getPointerState(internal, id);
1233
+ pointerState.captured.set(hit.eventObject, captureData);
1152
1234
  event.target.setPointerCapture(id);
1153
1235
  };
1154
1236
  const releasePointerCapture = (id) => {
1155
- const captures = internal.capturedMap.get(id);
1156
- if (captures) {
1157
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
1158
- }
1237
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
1159
1238
  };
1160
1239
  const extractEventProps = {};
1161
1240
  for (const prop in event) {
1162
1241
  const property = event[prop];
1163
1242
  if (typeof property !== "function") extractEventProps[prop] = property;
1164
1243
  }
1244
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1165
1245
  const raycastEvent = {
1166
1246
  ...hit,
1167
1247
  ...extractEventProps,
@@ -1172,18 +1252,19 @@ function createEvents(store) {
1172
1252
  unprojectedPoint,
1173
1253
  ray: raycaster.ray,
1174
1254
  camera,
1255
+ pointerId: eventPointerId,
1175
1256
  // Hijack stopPropagation, which just sets a flag
1176
1257
  stopPropagation() {
1177
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1258
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
1178
1259
  if (
1179
1260
  // ...if this pointer hasn't been captured
1180
- !capturesForPointer || // ... or if the hit object is capturing the pointer
1181
- capturesForPointer.has(hit.eventObject)
1261
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1262
+ pointerState.captured.has(hit.eventObject)
1182
1263
  ) {
1183
1264
  raycastEvent.stopped = localState.stopped = true;
1184
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1265
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1185
1266
  const higher = intersections.slice(0, intersections.indexOf(hit));
1186
- cancelPointer([...higher, hit]);
1267
+ cancelPointer([...higher, hit], eventPointerId);
1187
1268
  }
1188
1269
  }
1189
1270
  },
@@ -1199,15 +1280,18 @@ function createEvents(store) {
1199
1280
  }
1200
1281
  return intersections;
1201
1282
  }
1202
- function cancelPointer(intersections) {
1283
+ function cancelPointer(intersections, pointerId) {
1203
1284
  const { internal } = store.getState();
1204
- for (const hoveredObj of internal.hovered.values()) {
1285
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1286
+ const pointerState = internal.pointerMap.get(pid);
1287
+ if (!pointerState) return;
1288
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
1205
1289
  if (!intersections.length || !intersections.find(
1206
1290
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
1207
1291
  )) {
1208
1292
  const eventObject = hoveredObj.eventObject;
1209
1293
  const instance = eventObject.__r3f;
1210
- internal.hovered.delete(makeId(hoveredObj));
1294
+ pointerState.hovered.delete(hoveredId);
1211
1295
  if (instance?.eventCount) {
1212
1296
  const handlers = instance.handlers;
1213
1297
  const data = { ...hoveredObj, intersections };
@@ -1236,41 +1320,118 @@ function createEvents(store) {
1236
1320
  instance?.handlers.onDropMissed?.(event);
1237
1321
  }
1238
1322
  }
1323
+ function cleanupPointer(pointerId) {
1324
+ const { internal } = store.getState();
1325
+ const pointerState = internal.pointerMap.get(pointerId);
1326
+ if (pointerState) {
1327
+ for (const [, hoveredObj] of pointerState.hovered) {
1328
+ const eventObject = hoveredObj.eventObject;
1329
+ const instance = eventObject.__r3f;
1330
+ if (instance?.eventCount) {
1331
+ const handlers = instance.handlers;
1332
+ const data = { ...hoveredObj, intersections: [] };
1333
+ handlers.onPointerOut?.(data);
1334
+ handlers.onPointerLeave?.(data);
1335
+ }
1336
+ }
1337
+ internal.pointerMap.delete(pointerId);
1338
+ }
1339
+ internal.pointerDirty.delete(pointerId);
1340
+ }
1341
+ function processDeferredPointer(event, pointerId) {
1342
+ const state = store.getState();
1343
+ const { internal } = state;
1344
+ if (!state.events.enabled) return;
1345
+ const filter = filterPointerEvents;
1346
+ const hits = intersect(event, filter);
1347
+ cancelPointer(hits, pointerId);
1348
+ function onIntersect(data) {
1349
+ const eventObject = data.eventObject;
1350
+ const instance = eventObject.__r3f;
1351
+ if (!instance?.eventCount) return;
1352
+ const handlers = instance.handlers;
1353
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1354
+ const id = makeId(data);
1355
+ const pointerState = getPointerState(internal, pointerId);
1356
+ const hoveredItem = pointerState.hovered.get(id);
1357
+ if (!hoveredItem) {
1358
+ pointerState.hovered.set(id, data);
1359
+ handlers.onPointerOver?.(data);
1360
+ handlers.onPointerEnter?.(data);
1361
+ } else if (hoveredItem.stopped) {
1362
+ data.stopPropagation();
1363
+ }
1364
+ }
1365
+ handlers.onPointerMove?.(data);
1366
+ }
1367
+ handleIntersects(hits, event, 0, onIntersect);
1368
+ }
1239
1369
  function handlePointer(name) {
1240
1370
  switch (name) {
1241
1371
  case "onPointerLeave":
1242
- case "onPointerCancel":
1243
1372
  case "onDragLeave":
1244
1373
  return () => cancelPointer([]);
1374
+ // Global cancel of these events
1375
+ case "onPointerCancel":
1376
+ return (event) => {
1377
+ const pointerId = getPointerId(event);
1378
+ cleanupPointer(pointerId);
1379
+ };
1245
1380
  case "onLostPointerCapture":
1246
1381
  return (event) => {
1247
1382
  const { internal } = store.getState();
1248
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1383
+ const pointerId = getPointerId(event);
1384
+ const pointerState = internal.pointerMap.get(pointerId);
1385
+ if (pointerState?.captured.size) {
1249
1386
  requestAnimationFrame(() => {
1250
- if (internal.capturedMap.has(event.pointerId)) {
1251
- internal.capturedMap.delete(event.pointerId);
1252
- cancelPointer([]);
1387
+ const pointerState2 = internal.pointerMap.get(pointerId);
1388
+ if (pointerState2?.captured.size) {
1389
+ pointerState2.captured.clear();
1253
1390
  }
1391
+ cancelPointer([], pointerId);
1254
1392
  });
1255
1393
  }
1256
1394
  };
1257
1395
  }
1258
1396
  return function handleEvent(event) {
1259
1397
  const state = store.getState();
1260
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1398
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1399
+ const pointerId = getPointerId(event);
1261
1400
  internal.lastEvent.current = event;
1262
- if (!state.events.enabled) return;
1401
+ if (!events.enabled) return;
1263
1402
  const isPointerMove = name === "onPointerMove";
1264
1403
  const isDragOver = name === "onDragOver";
1265
1404
  const isDrop = name === "onDrop";
1266
1405
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1406
+ const isPointerDown = name === "onPointerDown";
1407
+ const isPointerUp = name === "onPointerUp";
1408
+ const isWheel = name === "onWheel";
1409
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1410
+ if (isPointerMove && canDeferRaycasts) {
1411
+ events.compute?.(event, state);
1412
+ internal.pointerDirty.set(pointerId, event);
1413
+ return;
1414
+ }
1415
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1416
+ events.compute?.(event, state);
1417
+ internal.pointerDirty.set(pointerId, event);
1418
+ return;
1419
+ }
1420
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1421
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1422
+ internal.pointerDirty.delete(pointerId);
1423
+ processDeferredPointer(deferredEvent, pointerId);
1424
+ }
1267
1425
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
1268
1426
  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
- }
1427
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1428
+ if (isPointerDown) {
1429
+ const pointerState2 = getPointerState(internal, pointerId);
1430
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1431
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1432
+ }
1433
+ const pointerState = internal.pointerMap.get(pointerId);
1434
+ const initialHits = pointerState?.initialHits ?? [];
1274
1435
  if (isClickEvent && !hits.length) {
1275
1436
  if (delta <= 2) {
1276
1437
  pointerMissed(event, internal.interaction);
@@ -1285,7 +1446,9 @@ function createEvents(store) {
1285
1446
  dropMissed(event, internal.interaction);
1286
1447
  if (onDropMissed) onDropMissed(event);
1287
1448
  }
1288
- if (isPointerMove || isDragOver) cancelPointer(hits);
1449
+ if (isPointerMove || isDragOver) {
1450
+ cancelPointer(hits, pointerId);
1451
+ }
1289
1452
  function onIntersect(data) {
1290
1453
  const eventObject = data.eventObject;
1291
1454
  const instance = eventObject.__r3f;
@@ -1294,9 +1457,10 @@ function createEvents(store) {
1294
1457
  if (isPointerMove) {
1295
1458
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1296
1459
  const id = makeId(data);
1297
- const hoveredItem = internal.hovered.get(id);
1460
+ const pointerState2 = getPointerState(internal, pointerId);
1461
+ const hoveredItem = pointerState2.hovered.get(id);
1298
1462
  if (!hoveredItem) {
1299
- internal.hovered.set(id, data);
1463
+ pointerState2.hovered.set(id, data);
1300
1464
  handlers.onPointerOver?.(data);
1301
1465
  handlers.onPointerEnter?.(data);
1302
1466
  } else if (hoveredItem.stopped) {
@@ -1306,9 +1470,10 @@ function createEvents(store) {
1306
1470
  handlers.onPointerMove?.(data);
1307
1471
  } else if (isDragOver) {
1308
1472
  const id = makeId(data);
1309
- const hoveredItem = internal.hovered.get(id);
1473
+ const pointerState2 = getPointerState(internal, pointerId);
1474
+ const hoveredItem = pointerState2.hovered.get(id);
1310
1475
  if (!hoveredItem) {
1311
- internal.hovered.set(id, data);
1476
+ pointerState2.hovered.set(id, data);
1312
1477
  handlers.onDragOverEnter?.(data);
1313
1478
  } else if (hoveredItem.stopped) {
1314
1479
  data.stopPropagation();
@@ -1319,18 +1484,18 @@ function createEvents(store) {
1319
1484
  } else {
1320
1485
  const handler = handlers[name];
1321
1486
  if (handler) {
1322
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1487
+ if (!isClickEvent || initialHits.includes(eventObject)) {
1323
1488
  pointerMissed(
1324
1489
  event,
1325
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1490
+ internal.interaction.filter((object) => !initialHits.includes(object))
1326
1491
  );
1327
1492
  handler(data);
1328
1493
  }
1329
1494
  } else {
1330
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1495
+ if (isClickEvent && initialHits.includes(eventObject)) {
1331
1496
  pointerMissed(
1332
1497
  event,
1333
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1498
+ internal.interaction.filter((object) => !initialHits.includes(object))
1334
1499
  );
1335
1500
  }
1336
1501
  }
@@ -1339,7 +1504,15 @@ function createEvents(store) {
1339
1504
  handleIntersects(hits, event, delta, onIntersect);
1340
1505
  };
1341
1506
  }
1342
- return { handlePointer };
1507
+ function flushDeferredPointers() {
1508
+ const { internal, events } = store.getState();
1509
+ if (!events.frameTimedRaycasts) return;
1510
+ for (const [pointerId, event] of internal.pointerDirty) {
1511
+ processDeferredPointer(event, pointerId);
1512
+ }
1513
+ internal.pointerDirty.clear();
1514
+ }
1515
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
1343
1516
  }
1344
1517
  const DOM_EVENTS = {
1345
1518
  onClick: ["click", false],
@@ -1358,10 +1531,15 @@ const DOM_EVENTS = {
1358
1531
  onLostPointerCapture: ["lostpointercapture", true]
1359
1532
  };
1360
1533
  function createPointerEvents(store) {
1361
- const { handlePointer } = createEvents(store);
1534
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1535
+ let nextXRPointerId = XR_POINTER_ID_START;
1536
+ const xrPointers = /* @__PURE__ */ new Map();
1362
1537
  return {
1363
1538
  priority: 1,
1364
1539
  enabled: true,
1540
+ frameTimedRaycasts: true,
1541
+ alwaysFireOnScroll: true,
1542
+ updateOnFrame: false,
1365
1543
  compute(event, state) {
1366
1544
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
1367
1545
  state.raycaster.setFromCamera(state.pointer, state.camera);
@@ -1371,11 +1549,33 @@ function createPointerEvents(store) {
1371
1549
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
1372
1550
  {}
1373
1551
  ),
1374
- update: () => {
1552
+ update: (pointerId) => {
1553
+ const { events, internal } = store.getState();
1554
+ if (!events.handlers) return;
1555
+ if (pointerId !== void 0) {
1556
+ const event = internal.pointerDirty.get(pointerId);
1557
+ if (event) {
1558
+ internal.pointerDirty.delete(pointerId);
1559
+ processDeferredPointer(event, pointerId);
1560
+ } else if (internal.lastEvent?.current) {
1561
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1562
+ }
1563
+ } else {
1564
+ flushDeferredPointers();
1565
+ if (internal.lastEvent?.current) {
1566
+ events.handlers.onPointerMove(internal.lastEvent.current);
1567
+ }
1568
+ }
1569
+ },
1570
+ flush: () => {
1375
1571
  const { events, internal } = store.getState();
1376
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1572
+ flushDeferredPointers();
1573
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1574
+ events.handlers.onPointerMove(internal.lastEvent.current);
1575
+ }
1377
1576
  },
1378
1577
  connect: (target) => {
1578
+ if (!target) return;
1379
1579
  const { set, events } = store.getState();
1380
1580
  events.disconnect?.();
1381
1581
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1399,6 +1599,33 @@ function createPointerEvents(store) {
1399
1599
  }
1400
1600
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1401
1601
  }
1602
+ },
1603
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1604
+ registerPointer: (config) => {
1605
+ const pointerId = nextXRPointerId++;
1606
+ xrPointers.set(pointerId, config);
1607
+ const { internal } = store.getState();
1608
+ getPointerState(internal, pointerId);
1609
+ return pointerId;
1610
+ },
1611
+ unregisterPointer: (pointerId) => {
1612
+ xrPointers.delete(pointerId);
1613
+ const { internal } = store.getState();
1614
+ const pointerState = internal.pointerMap.get(pointerId);
1615
+ if (pointerState) {
1616
+ for (const [, hoveredObj] of pointerState.hovered) {
1617
+ const eventObject = hoveredObj.eventObject;
1618
+ const instance = eventObject.__r3f;
1619
+ if (instance?.eventCount) {
1620
+ const handlers = instance.handlers;
1621
+ const data = { ...hoveredObj, intersections: [] };
1622
+ handlers.onPointerOut?.(data);
1623
+ handlers.onPointerLeave?.(data);
1624
+ }
1625
+ }
1626
+ internal.pointerMap.delete(pointerId);
1627
+ }
1628
+ internal.pointerDirty.delete(pointerId);
1402
1629
  }
1403
1630
  };
1404
1631
  }
@@ -1460,1036 +1687,11 @@ function notifyAlpha({ message, link }) {
1460
1687
  }
1461
1688
  }
1462
1689
 
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?.();
1690
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1691
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1692
+ if (!stack) return false;
1693
+ const caller = stack.split("\n")[callerDepth] ?? "";
1694
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2493
1695
  }
2494
1696
 
2495
1697
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2529,7 +1731,14 @@ const createStore = (invalidate, advance) => {
2529
1731
  frustum: new three.Frustum(),
2530
1732
  autoUpdateFrustum: true,
2531
1733
  raycaster: null,
2532
- events: { priority: 1, enabled: true, connected: false },
1734
+ events: {
1735
+ priority: 1,
1736
+ enabled: true,
1737
+ connected: false,
1738
+ frameTimedRaycasts: true,
1739
+ alwaysFireOnScroll: true,
1740
+ updateOnFrame: false
1741
+ },
2533
1742
  scene: null,
2534
1743
  rootScene: null,
2535
1744
  xr: null,
@@ -2594,7 +1803,7 @@ const createStore = (invalidate, advance) => {
2594
1803
  size: newSize,
2595
1804
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2596
1805
  }));
2597
- getScheduler().invalidate();
1806
+ scheduler.getScheduler().invalidate();
2598
1807
  }
2599
1808
  }
2600
1809
  return;
@@ -2609,7 +1818,7 @@ const createStore = (invalidate, advance) => {
2609
1818
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2610
1819
  _sizeImperative: true
2611
1820
  }));
2612
- getScheduler().invalidate();
1821
+ scheduler.getScheduler().invalidate();
2613
1822
  },
2614
1823
  setDpr: (dpr) => set((state2) => {
2615
1824
  const resolved = calculateDpr(dpr);
@@ -2617,14 +1826,18 @@ const createStore = (invalidate, advance) => {
2617
1826
  }),
2618
1827
  setFrameloop: (frameloop = "always") => {
2619
1828
  set(() => ({ frameloop }));
1829
+ scheduler.getScheduler().frameloop = frameloop;
2620
1830
  },
2621
1831
  setError: (error) => set(() => ({ error })),
2622
1832
  error: null,
2623
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1833
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2624
1834
  uniforms: {},
2625
1835
  nodes: {},
1836
+ buffers: {},
1837
+ gpuStorage: {},
2626
1838
  textures: /* @__PURE__ */ new Map(),
2627
- postProcessing: null,
1839
+ _textureRefs: /* @__PURE__ */ new Map(),
1840
+ renderPipeline: null,
2628
1841
  passes: {},
2629
1842
  _hmrVersion: 0,
2630
1843
  _sizeImperative: false,
@@ -2633,12 +1846,16 @@ const createStore = (invalidate, advance) => {
2633
1846
  internal: {
2634
1847
  // Events
2635
1848
  interaction: [],
2636
- hovered: /* @__PURE__ */ new Map(),
2637
1849
  subscribers: [],
1850
+ // Per-pointer state (new unified structure)
1851
+ pointerMap: /* @__PURE__ */ new Map(),
1852
+ pointerDirty: /* @__PURE__ */ new Map(),
1853
+ lastEvent: React__namespace.createRef(),
1854
+ // Deprecated but kept for backwards compatibility
1855
+ hovered: /* @__PURE__ */ new Map(),
2638
1856
  initialClick: [0, 0],
2639
1857
  initialHits: [],
2640
1858
  capturedMap: /* @__PURE__ */ new Map(),
2641
- lastEvent: React__namespace.createRef(),
2642
1859
  // Visibility tracking (onFramed, onOccluded, onVisible)
2643
1860
  visibilityRegistry: /* @__PURE__ */ new Map(),
2644
1861
  // Occlusion system (WebGPU only)
@@ -2677,8 +1894,7 @@ const createStore = (invalidate, advance) => {
2677
1894
  const currentState = rootStore.getState();
2678
1895
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2679
1896
  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) {
1897
+ if (!isInternalRendererAccess(stack)) {
2682
1898
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2683
1899
  notifyDepreciated({
2684
1900
  heading: "Accessing state.gl in WebGPU mode",
@@ -2726,14 +1942,16 @@ const createStore = (invalidate, advance) => {
2726
1942
  oldSize = size;
2727
1943
  oldDpr = viewport.dpr;
2728
1944
  updateCamera(camera, size);
2729
- if (canvasTarget) {
1945
+ if (internal.isSecondary && canvasTarget) {
2730
1946
  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);
1947
+ canvasTarget.setSize(size.width, size.height, false);
2733
1948
  } else {
2734
1949
  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);
1950
+ actualRenderer.setSize(size.width, size.height, false);
1951
+ if (canvasTarget) {
1952
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1953
+ canvasTarget.setSize(size.width, size.height, false);
1954
+ }
2737
1955
  }
2738
1956
  }
2739
1957
  if (camera !== oldCamera) {
@@ -2789,26 +2007,32 @@ function loadingFn(extensions, onProgress) {
2789
2007
  );
2790
2008
  };
2791
2009
  }
2792
- function useLoader(loader, input, extensions, onProgress) {
2793
- const keys = Array.isArray(input) ? input : [input];
2010
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2011
+ const inputs = Array.isArray(input) ? input : [input];
2012
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2794
2013
  const fn = loadingFn(extensions, onProgress);
2795
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2014
+ const results = cacheKeys.map(
2015
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2016
+ );
2796
2017
  return Array.isArray(input) ? results : results[0];
2797
2018
  }
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]));
2019
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2020
+ const inputs = Array.isArray(input) ? input : [input];
2021
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2022
+ cacheKeys.forEach(
2023
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2024
+ );
2801
2025
  };
2802
- useLoader.clear = function(loader, input) {
2803
- const keys = Array.isArray(input) ? input : [input];
2804
- keys.forEach((key) => suspendReact.clear([loader, key]));
2026
+ useLoader.clear = function(loader, input, cacheKey) {
2027
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2028
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
2805
2029
  };
2806
2030
  useLoader.loader = getLoader;
2807
2031
 
2808
2032
  function useFrame(callback, priorityOrOptions) {
2809
2033
  const store = React__namespace.useContext(context);
2810
2034
  const isInsideCanvas = store !== null;
2811
- const scheduler = getScheduler();
2035
+ const scheduler$1 = scheduler.getScheduler();
2812
2036
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2813
2037
  id: priorityOrOptions.id,
2814
2038
  phase: priorityOrOptions.phase,
@@ -2856,7 +2080,7 @@ function useFrame(callback, priorityOrOptions) {
2856
2080
  };
2857
2081
  callbackRef.current?.(mergedState, delta);
2858
2082
  };
2859
- const unregister = scheduler.register(wrappedCallback, {
2083
+ const unregister = scheduler$1.register(wrappedCallback, {
2860
2084
  id,
2861
2085
  rootId,
2862
2086
  ...options
@@ -2877,37 +2101,31 @@ function useFrame(callback, priorityOrOptions) {
2877
2101
  }
2878
2102
  };
2879
2103
  } 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
- };
2104
+ return scheduler$1.register(
2105
+ (state, delta) => {
2106
+ const frameState = state;
2107
+ if (!frameState.renderer) return;
2108
+ callbackRef.current?.(frameState, delta);
2109
+ },
2110
+ { id, ...options }
2111
+ );
2894
2112
  }
2895
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2113
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2896
2114
  const isPaused = React__namespace.useSyncExternalStore(
2897
2115
  // Subscribe function
2898
2116
  React__namespace.useCallback(
2899
2117
  (onStoreChange) => {
2900
- return getScheduler().subscribeJobState(id, onStoreChange);
2118
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
2901
2119
  },
2902
2120
  [id]
2903
2121
  ),
2904
2122
  // getSnapshot function
2905
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2123
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
2906
2124
  // getServerSnapshot function (SSR)
2907
2125
  React__namespace.useCallback(() => false, [])
2908
2126
  );
2909
2127
  const controls = React__namespace.useMemo(() => {
2910
- const scheduler2 = getScheduler();
2128
+ const scheduler2 = scheduler.getScheduler();
2911
2129
  return {
2912
2130
  /** The job's unique ID */
2913
2131
  id,
@@ -2922,7 +2140,7 @@ function useFrame(callback, priorityOrOptions) {
2922
2140
  * @param timestamp Optional timestamp (defaults to performance.now())
2923
2141
  */
2924
2142
  step: (timestamp) => {
2925
- getScheduler().stepJob(id, timestamp);
2143
+ scheduler.getScheduler().stepJob(id, timestamp);
2926
2144
  },
2927
2145
  /**
2928
2146
  * Manually step ALL jobs in the scheduler.
@@ -2930,20 +2148,20 @@ function useFrame(callback, priorityOrOptions) {
2930
2148
  * @param timestamp Optional timestamp (defaults to performance.now())
2931
2149
  */
2932
2150
  stepAll: (timestamp) => {
2933
- getScheduler().step(timestamp);
2151
+ scheduler.getScheduler().step(timestamp);
2934
2152
  },
2935
2153
  /**
2936
2154
  * Pause this job (set enabled=false).
2937
2155
  * Job remains registered but won't run.
2938
2156
  */
2939
2157
  pause: () => {
2940
- getScheduler().pauseJob(id);
2158
+ scheduler.getScheduler().pauseJob(id);
2941
2159
  },
2942
2160
  /**
2943
2161
  * Resume this job (set enabled=true).
2944
2162
  */
2945
2163
  resume: () => {
2946
- getScheduler().resumeJob(id);
2164
+ scheduler.getScheduler().resumeJob(id);
2947
2165
  },
2948
2166
  /**
2949
2167
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2981,18 +2199,18 @@ function buildFromCache(input, textureCache) {
2981
2199
  function useTexture(input, optionsOrOnLoad) {
2982
2200
  const renderer = useThree((state) => state.internal.actualRenderer);
2983
2201
  const store = useStore();
2984
- const textureCache = useThree((state) => state.textures);
2985
2202
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2986
- const { onLoad, cache = false } = options;
2203
+ const { onLoad, cache = true } = options;
2987
2204
  const onLoadRef = React.useRef(onLoad);
2988
2205
  onLoadRef.current = onLoad;
2989
2206
  const onLoadCalledForRef = React.useRef(null);
2990
2207
  const urls = React.useMemo(() => getUrls(input), [input]);
2991
2208
  const cachedResult = React.useMemo(() => {
2992
2209
  if (!cache) return null;
2993
- if (!allUrlsCached(urls, textureCache)) return null;
2994
- return buildFromCache(input, textureCache);
2995
- }, [cache, urls, textureCache, input]);
2210
+ const textures = store.getState().textures;
2211
+ if (!allUrlsCached(urls, textures)) return null;
2212
+ return buildFromCache(input, textures);
2213
+ }, [cache, urls, input, store]);
2996
2214
  const loadedTextures = useLoader(
2997
2215
  three.TextureLoader,
2998
2216
  IsObject(input) ? Object.values(input) : input
@@ -3036,8 +2254,6 @@ function useTexture(input, optionsOrOnLoad) {
3036
2254
  }, [input, loadedTextures, cachedResult]);
3037
2255
  React.useEffect(() => {
3038
2256
  if (!cache) return;
3039
- if (cachedResult) return;
3040
- const set = store.setState;
3041
2257
  const urlTextureMap = [];
3042
2258
  if (typeof input === "string") {
3043
2259
  urlTextureMap.push([input, mappedTextures]);
@@ -3051,18 +2267,32 @@ function useTexture(input, optionsOrOnLoad) {
3051
2267
  urlTextureMap.push([url, textureRecord[key]]);
3052
2268
  }
3053
2269
  }
3054
- set((state) => {
3055
- const newMap = new Map(state.textures);
3056
- let changed = false;
2270
+ store.setState((state) => {
2271
+ const refs = new Map(state._textureRefs);
2272
+ let textures = state.textures;
2273
+ let added = false;
3057
2274
  for (const [url, texture] of urlTextureMap) {
3058
- if (!newMap.has(url)) {
3059
- newMap.set(url, texture);
3060
- changed = true;
2275
+ if (!textures.has(url)) {
2276
+ if (!added) {
2277
+ textures = new Map(textures);
2278
+ added = true;
2279
+ }
2280
+ textures.set(url, texture);
3061
2281
  }
2282
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3062
2283
  }
3063
- return changed ? { textures: newMap } : state;
2284
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2285
+ });
2286
+ return () => store.setState((state) => {
2287
+ const refs = new Map(state._textureRefs);
2288
+ for (const [url] of urlTextureMap) {
2289
+ const next = (refs.get(url) ?? 0) - 1;
2290
+ if (next <= 0) refs.delete(url);
2291
+ else refs.set(url, next);
2292
+ }
2293
+ return { _textureRefs: refs };
3064
2294
  });
3065
- }, [cache, input, mappedTextures, store, cachedResult]);
2295
+ }, [cache, input, mappedTextures, store]);
3066
2296
  return mappedTextures;
3067
2297
  }
3068
2298
  useTexture.preload = (url) => useLoader.preload(three.TextureLoader, url);
@@ -3078,96 +2308,63 @@ const Texture = ({
3078
2308
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3079
2309
  };
3080
2310
 
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() {
2311
+ function useTextures(selector) {
3089
2312
  const store = useStore();
3090
- return React.useMemo(() => {
3091
- const set = store.setState;
2313
+ const registry = React.useMemo(() => {
3092
2314
  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
- };
2315
+ const setState = store.setState;
2316
+ const getOne = (key) => getState().textures.get(key);
3151
2317
  return {
3152
- // Getter for the textures Map (reactive via getState)
3153
- get textures() {
2318
+ get all() {
3154
2319
  return getState().textures;
3155
2320
  },
3156
- // Read
3157
- get: (key) => getState().textures.get(key),
2321
+ get(input) {
2322
+ if (typeof input === "string") return getOne(input);
2323
+ if (Array.isArray(input)) return input.map(getOne);
2324
+ const out = {};
2325
+ for (const name in input) out[name] = getOne(input[name]);
2326
+ return out;
2327
+ },
3158
2328
  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
2329
+ add(keyOrRecord, texture) {
2330
+ setState((state) => {
2331
+ const textures = new Map(state.textures);
2332
+ if (typeof keyOrRecord === "string") {
2333
+ textures.set(keyOrRecord, texture);
2334
+ } else {
2335
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2336
+ }
2337
+ return { textures };
2338
+ });
2339
+ },
2340
+ dispose(key, options) {
2341
+ const state = getState();
2342
+ const refs = state._textureRefs.get(key) ?? 0;
2343
+ if (refs > 0 && !options?.force) {
2344
+ console.warn(
2345
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2346
+ );
2347
+ return false;
2348
+ }
2349
+ state.textures.get(key)?.dispose();
2350
+ setState((s) => {
2351
+ const textures = new Map(s.textures);
2352
+ textures.delete(key);
2353
+ const nextRefs = new Map(s._textureRefs);
2354
+ nextRefs.delete(key);
2355
+ return { textures, _textureRefs: nextRefs };
2356
+ });
2357
+ return true;
2358
+ },
2359
+ disposeAll() {
2360
+ for (const texture of getState().textures.values()) texture.dispose();
2361
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2362
+ }
3169
2363
  };
3170
2364
  }, [store]);
2365
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2366
+ const selected = useThree(subscribe);
2367
+ return selector ? selected : registry;
3171
2368
  }
3172
2369
 
3173
2370
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3222,7 +2419,7 @@ function addEffect(callback) {
3222
2419
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3223
2420
  });
3224
2421
  const id = `legacy_effect_${effectId++}`;
3225
- return getScheduler().registerGlobal("before", id, callback);
2422
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3226
2423
  }
3227
2424
  function addAfterEffect(callback) {
3228
2425
  notifyDepreciated({
@@ -3231,7 +2428,7 @@ function addAfterEffect(callback) {
3231
2428
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3232
2429
  });
3233
2430
  const id = `legacy_afterEffect_${effectId++}`;
3234
- return getScheduler().registerGlobal("after", id, callback);
2431
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3235
2432
  }
3236
2433
  function addTail(callback) {
3237
2434
  notifyDepreciated({
@@ -3239,16 +2436,16 @@ function addTail(callback) {
3239
2436
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3240
2437
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3241
2438
  });
3242
- return getScheduler().onIdle(callback);
2439
+ return scheduler.getScheduler().onIdle(callback);
3243
2440
  }
3244
2441
  function invalidate(state, frames = 1, stackFrames = false) {
3245
- getScheduler().invalidate(frames, stackFrames);
2442
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3246
2443
  }
3247
2444
  function advance(timestamp) {
3248
- getScheduler().step(timestamp);
2445
+ scheduler.getScheduler().step(timestamp);
3249
2446
  }
3250
2447
 
3251
- const version = "10.0.0-alpha.2";
2448
+ const version = "10.0.0-alpha.3";
3252
2449
  const packageData = {
3253
2450
  version: version};
3254
2451
 
@@ -14504,7 +13701,7 @@ function n0() {
14504
13701
  var t0 = n0();
14505
13702
  const r0 = Xb(t0);
14506
13703
 
14507
- const t = 1, o = 8, r = 32, e = 2;
13704
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14508
13705
 
14509
13706
  function createReconciler(config) {
14510
13707
  const reconciler2 = r0(config);
@@ -14669,7 +13866,15 @@ function setFiberRef(fiber, publicInstance) {
14669
13866
  }
14670
13867
  }
14671
13868
  const reconstructed = [];
14672
- function swapInstances() {
13869
+ function flushReconstructedInstances() {
13870
+ if (reconstructed.length === 0) return;
13871
+ try {
13872
+ swapReconstructedInstances();
13873
+ } finally {
13874
+ reconstructed.length = 0;
13875
+ }
13876
+ }
13877
+ function swapReconstructedInstances() {
14673
13878
  for (const [instance] of reconstructed) {
14674
13879
  const parent = instance.parent;
14675
13880
  if (parent) {
@@ -14687,6 +13892,7 @@ function swapInstances() {
14687
13892
  }
14688
13893
  }
14689
13894
  if (instance.isHidden) unhideInstance(instance);
13895
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14690
13896
  if (instance.object.__r3f) delete instance.object.__r3f;
14691
13897
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14692
13898
  }
@@ -14699,6 +13905,8 @@ function swapInstances() {
14699
13905
  instance.object.__r3f = instance;
14700
13906
  setFiberRef(fiber, instance.object);
14701
13907
  delete instance.appliedOnce;
13908
+ instance.eventCount = 0;
13909
+ instance.handlers = {};
14702
13910
  applyProps(instance.object, instance.props);
14703
13911
  if (instance.props.attach) {
14704
13912
  attach(parent, instance);
@@ -14715,14 +13923,114 @@ function swapInstances() {
14715
13923
  invalidateInstance(instance);
14716
13924
  }
14717
13925
  }
14718
- reconstructed.length = 0;
14719
13926
  }
14720
13927
  const handleTextInstance = () => {
14721
13928
  };
14722
13929
  const NO_CONTEXT = {};
14723
13930
  let currentUpdatePriority = NoEventPriority;
14724
- const NoFlags = 0;
14725
- const Update = 4;
13931
+ function getEventPriority(type) {
13932
+ switch (type) {
13933
+ case "beforetoggle":
13934
+ case "cancel":
13935
+ case "click":
13936
+ case "close":
13937
+ case "contextmenu":
13938
+ case "copy":
13939
+ case "cut":
13940
+ case "auxclick":
13941
+ case "dblclick":
13942
+ case "dragend":
13943
+ case "dragstart":
13944
+ case "drop":
13945
+ case "focusin":
13946
+ case "focusout":
13947
+ case "input":
13948
+ case "invalid":
13949
+ case "keydown":
13950
+ case "keypress":
13951
+ case "keyup":
13952
+ case "mousedown":
13953
+ case "mouseup":
13954
+ case "paste":
13955
+ case "pause":
13956
+ case "play":
13957
+ case "pointercancel":
13958
+ case "pointerdown":
13959
+ case "pointerup":
13960
+ case "ratechange":
13961
+ case "reset":
13962
+ case "resize":
13963
+ case "seeked":
13964
+ case "submit":
13965
+ case "touchcancel":
13966
+ case "touchend":
13967
+ case "touchstart":
13968
+ case "volumechange":
13969
+ case "change":
13970
+ case "selectionchange":
13971
+ case "compositionstart":
13972
+ case "compositionend":
13973
+ case "compositionupdate":
13974
+ case "beforeinput":
13975
+ case "blur":
13976
+ case "fullscreenchange":
13977
+ case "focus":
13978
+ case "hashchange":
13979
+ case "popstate":
13980
+ case "select":
13981
+ case "selectstart":
13982
+ return e;
13983
+ case "drag":
13984
+ case "dragenter":
13985
+ case "dragexit":
13986
+ case "dragleave":
13987
+ case "dragover":
13988
+ case "mousemove":
13989
+ case "mouseout":
13990
+ case "mouseover":
13991
+ case "pointermove":
13992
+ case "pointerout":
13993
+ case "pointerover":
13994
+ case "scroll":
13995
+ case "touchmove":
13996
+ case "wheel":
13997
+ case "mouseenter":
13998
+ case "mouseleave":
13999
+ case "pointerenter":
14000
+ case "pointerleave":
14001
+ return o;
14002
+ case "message": {
14003
+ switch (Tb.unstable_getCurrentPriorityLevel()) {
14004
+ case Tb.unstable_ImmediatePriority:
14005
+ return e;
14006
+ case Tb.unstable_UserBlockingPriority:
14007
+ return o;
14008
+ case Tb.unstable_NormalPriority:
14009
+ case Tb.unstable_LowPriority:
14010
+ return r;
14011
+ case Tb.unstable_IdlePriority:
14012
+ return i$1;
14013
+ default:
14014
+ return r;
14015
+ }
14016
+ }
14017
+ default:
14018
+ return r;
14019
+ }
14020
+ }
14021
+ function scheduleMicrotask(callback) {
14022
+ if (typeof queueMicrotask === "function") {
14023
+ queueMicrotask(callback);
14024
+ } else if (typeof Promise !== "undefined") {
14025
+ Promise.resolve().then(callback).catch((error) => {
14026
+ setTimeout(() => {
14027
+ throw error;
14028
+ });
14029
+ });
14030
+ } else {
14031
+ setTimeout(callback);
14032
+ }
14033
+ }
14726
14034
  const reconciler = /* @__PURE__ */ createReconciler({
14727
14035
  isPrimaryRenderer: false,
14728
14036
  warnsIfNotActing: false,
@@ -14761,16 +14069,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14761
14069
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14762
14070
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14763
14071
  if (reconstruct) {
14764
- reconstructed.push([instance, { ...newProps }, fiber]);
14072
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14765
14073
  } else {
14766
14074
  const changedProps = diffProps(instance, newProps);
14767
- if (Object.keys(changedProps).length) {
14768
- Object.assign(instance.props, changedProps);
14769
- applyProps(instance.object, changedProps);
14770
- }
14075
+ const attach2 = instance.props.attach;
14076
+ instance.props = getInstanceProps(newProps);
14077
+ if (attach2 !== void 0) instance.props.attach = attach2;
14078
+ else delete instance.props.attach;
14079
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14771
14080
  }
14772
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14773
- if (isTailSibling) swapInstances();
14774
14081
  },
14775
14082
  finalizeInitialChildren: (instance) => {
14776
14083
  for (const prop in instance.props) {
@@ -14795,8 +14102,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14795
14102
  const target = container.getState().internal.container ?? container.getState().scene;
14796
14103
  return prepare(target, container, "", {});
14797
14104
  },
14798
- resetAfterCommit: () => {
14799
- },
14105
+ // Reconstructed instances are swapped once all mutations are committed,
14106
+ // before layout effects run so refs point to the new objects
14107
+ resetAfterCommit: flushReconstructedInstances,
14800
14108
  shouldSetTextContent: () => false,
14801
14109
  clearContainer: () => false,
14802
14110
  hideInstance,
@@ -14804,6 +14112,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14804
14112
  createTextInstance: handleTextInstance,
14805
14113
  hideTextInstance: handleTextInstance,
14806
14114
  unhideTextInstance: handleTextInstance,
14115
+ // Mirrors react-dom, which flushes discrete work in microtasks
14116
+ supportsMicrotasks: true,
14117
+ scheduleMicrotask,
14807
14118
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
14808
14119
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
14809
14120
  noTimeout: -1,
@@ -14844,28 +14155,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14844
14155
  },
14845
14156
  resolveUpdatePriority() {
14846
14157
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
14847
- switch (typeof window !== "undefined" && window.event?.type) {
14848
- case "click":
14849
- case "contextmenu":
14850
- case "dblclick":
14851
- case "dragenter":
14852
- case "dragleave":
14853
- case "drop":
14854
- case "pointercancel":
14855
- case "pointerdown":
14856
- case "pointerup":
14857
- return e;
14858
- case "dragover":
14859
- case "pointermove":
14860
- case "pointerout":
14861
- case "pointerover":
14862
- case "pointerenter":
14863
- case "pointerleave":
14864
- case "wheel":
14865
- return o;
14866
- default:
14867
- return r;
14868
- }
14158
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14159
+ if (eventType === void 0) return r;
14160
+ return getEventPriority(eventType);
14869
14161
  },
14870
14162
  resetFormInstance() {
14871
14163
  },
@@ -14914,11 +14206,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14914
14206
  cloneMutableTextInstance(textInstance) {
14915
14207
  return textInstance;
14916
14208
  },
14209
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14210
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14211
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14212
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14213
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14214
+ // Guarded by a test asserting a full render + unmount never reaches them.
14917
14215
  cloneRootViewTransitionContainer(_rootContainer) {
14918
- throw new Error("Not implemented.");
14919
14216
  },
14920
14217
  removeRootViewTransitionClone(_rootContainer, _clone) {
14921
- throw new Error("Not implemented.");
14922
14218
  },
14923
14219
  // https://github.com/facebook/react/pull/32465
14924
14220
  createFragmentInstance: (_fiber) => null,
@@ -15003,6 +14299,7 @@ function createRoot(canvas) {
15003
14299
  const lastConfiguredProps = {};
15004
14300
  let configured = false;
15005
14301
  let pending = null;
14302
+ let rendererSetup = null;
15006
14303
  return {
15007
14304
  async configure(props = {}) {
15008
14305
  let resolve;
@@ -15018,7 +14315,6 @@ function createRoot(canvas) {
15018
14315
  events,
15019
14316
  onCreated: onCreatedCallback,
15020
14317
  shadows = false,
15021
- textureColorSpace = three.SRGBColorSpace,
15022
14318
  orthographic = false,
15023
14319
  frameloop = "always",
15024
14320
  dpr = [1, 2],
@@ -15033,7 +14329,8 @@ function createRoot(canvas) {
15033
14329
  _sizeProps,
15034
14330
  forceEven
15035
14331
  } = props;
15036
- const state = store.getState();
14332
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || three.SRGBColorSpace;
14333
+ let state = store.getState();
15037
14334
  const defaultGLProps = {
15038
14335
  canvas,
15039
14336
  powerPreference: "high-performance",
@@ -15061,9 +14358,21 @@ function createRoot(canvas) {
15061
14358
  );
15062
14359
  }
15063
14360
  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 });
14361
+ if (!rendererSetup) {
14362
+ rendererSetup = (async () => {
14363
+ {
14364
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14365
+ state.internal.actualRenderer = renderer;
14366
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14367
+ }
14368
+ })().catch((err) => {
14369
+ rendererSetup = null;
14370
+ throw err;
14371
+ });
14372
+ }
14373
+ await rendererSetup;
14374
+ state = store.getState();
14375
+ renderer = state.internal.actualRenderer;
15067
14376
  }
15068
14377
  let raycaster = state.raycaster;
15069
14378
  if (!raycaster) state.set({ raycaster: raycaster = new three.Raycaster() });
@@ -15156,7 +14465,7 @@ function createRoot(canvas) {
15156
14465
  lastConfiguredProps.performance = performance;
15157
14466
  }
15158
14467
  if (!state.xr) {
15159
- const handleXRFrame = (timestamp, frame) => {
14468
+ const handleXRFrame = (timestamp, _frame) => {
15160
14469
  const state2 = store.getState();
15161
14470
  if (state2.frameloop === "never") return;
15162
14471
  advance(timestamp);
@@ -15192,15 +14501,22 @@ function createRoot(canvas) {
15192
14501
  const oldType = renderer.shadowMap.type;
15193
14502
  renderer.shadowMap.enabled = !!shadows;
15194
14503
  if (is.boo(shadows)) {
15195
- renderer.shadowMap.type = three.PCFSoftShadowMap;
14504
+ renderer.shadowMap.type = three.PCFShadowMap;
15196
14505
  } else if (is.str(shadows)) {
14506
+ if (shadows === "soft") {
14507
+ notifyDepreciated({
14508
+ heading: 'shadows="soft" is deprecated',
14509
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14510
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14511
+ });
14512
+ }
15197
14513
  const types = {
15198
14514
  basic: three.BasicShadowMap,
15199
14515
  percentage: three.PCFShadowMap,
15200
- soft: three.PCFSoftShadowMap,
14516
+ soft: three.PCFShadowMap,
15201
14517
  variance: three.VSMShadowMap
15202
14518
  };
15203
- renderer.shadowMap.type = types[shadows] ?? three.PCFSoftShadowMap;
14519
+ renderer.shadowMap.type = types[shadows] ?? three.PCFShadowMap;
15204
14520
  } else if (is.obj(shadows)) {
15205
14521
  Object.assign(renderer.shadowMap, shadows);
15206
14522
  }
@@ -15216,24 +14532,35 @@ function createRoot(canvas) {
15216
14532
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15217
14533
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15218
14534
  }
14535
+ const r3fProps = ["textureColorSpace"];
14536
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14537
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15219
14538
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15220
- applyProps(renderer, glConfig);
14539
+ const glProps = {};
14540
+ for (const key in glConfig) {
14541
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14542
+ }
14543
+ applyProps(renderer, glProps);
15221
14544
  }
15222
14545
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15223
14546
  const currentRenderer = state.renderer;
15224
14547
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15225
- applyProps(currentRenderer, rendererConfig);
14548
+ const rendererProps = {};
14549
+ for (const key in rendererConfig) {
14550
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14551
+ }
14552
+ applyProps(currentRenderer, rendererProps);
15226
14553
  }
15227
14554
  }
15228
- const scheduler = getScheduler();
14555
+ const scheduler$1 = scheduler.getScheduler();
15229
14556
  const rootId = state.internal.rootId;
15230
14557
  if (!rootId) {
15231
- const newRootId = canvasId || scheduler.generateRootId();
15232
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14558
+ const newRootId = canvasId || scheduler$1.generateRootId();
14559
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15233
14560
  getState: () => store.getState(),
15234
14561
  onError: (err) => store.getState().setError(err)
15235
14562
  });
15236
- const unregisterCanvasTarget = scheduler.register(
14563
+ const unregisterCanvasTarget = scheduler$1.register(
15237
14564
  () => {
15238
14565
  const state2 = store.getState();
15239
14566
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15248,7 +14575,19 @@ function createRoot(canvas) {
15248
14575
  system: true
15249
14576
  }
15250
14577
  );
15251
- const unregisterFrustum = scheduler.register(
14578
+ const unregisterEventsFlush = scheduler$1.register(
14579
+ () => {
14580
+ const state2 = store.getState();
14581
+ state2.events.flush?.();
14582
+ },
14583
+ {
14584
+ id: `${newRootId}_events`,
14585
+ rootId: newRootId,
14586
+ phase: "input",
14587
+ system: true
14588
+ }
14589
+ );
14590
+ const unregisterFrustum = scheduler$1.register(
15252
14591
  () => {
15253
14592
  const state2 = store.getState();
15254
14593
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15258,11 +14597,11 @@ function createRoot(canvas) {
15258
14597
  {
15259
14598
  id: `${newRootId}_frustum`,
15260
14599
  rootId: newRootId,
15261
- phase: "preRender",
14600
+ before: "render",
15262
14601
  system: true
15263
14602
  }
15264
14603
  );
15265
- const unregisterVisibility = scheduler.register(
14604
+ const unregisterVisibility = scheduler$1.register(
15266
14605
  () => {
15267
14606
  const state2 = store.getState();
15268
14607
  checkVisibility(state2);
@@ -15270,19 +14609,19 @@ function createRoot(canvas) {
15270
14609
  {
15271
14610
  id: `${newRootId}_visibility`,
15272
14611
  rootId: newRootId,
15273
- phase: "preRender",
14612
+ before: "render",
15274
14613
  system: true,
15275
14614
  after: `${newRootId}_frustum`
15276
14615
  }
15277
14616
  );
15278
- const unregisterRender = scheduler.register(
14617
+ const unregisterRender = scheduler$1.register(
15279
14618
  () => {
15280
14619
  const state2 = store.getState();
15281
14620
  const renderer2 = state2.internal.actualRenderer;
15282
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14621
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15283
14622
  if (userHandlesRender || state2.internal.priority) return;
15284
14623
  try {
15285
- if (state2.postProcessing?.render) state2.postProcessing.render();
14624
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
15286
14625
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
15287
14626
  } catch (error) {
15288
14627
  state2.setError(error instanceof Error ? error : new Error(String(error)));
@@ -15307,15 +14646,16 @@ function createRoot(canvas) {
15307
14646
  unregisterRoot: () => {
15308
14647
  unregisterRoot();
15309
14648
  unregisterCanvasTarget();
14649
+ unregisterEventsFlush();
15310
14650
  unregisterFrustum();
15311
14651
  unregisterVisibility();
15312
14652
  unregisterRender();
15313
14653
  },
15314
- scheduler
14654
+ scheduler: scheduler$1
15315
14655
  }
15316
14656
  }));
15317
14657
  }
15318
- scheduler.frameloop = frameloop;
14658
+ scheduler$1.frameloop = frameloop;
15319
14659
  onCreated = onCreatedCallback;
15320
14660
  configured = true;
15321
14661
  resolve();
@@ -15382,7 +14722,8 @@ function unmountComponentAtNode(canvas, callback) {
15382
14722
  dispose(state.scene);
15383
14723
  _roots.delete(canvas);
15384
14724
  if (callback) callback(canvas);
15385
- } catch {
14725
+ } catch (error) {
14726
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15386
14727
  }
15387
14728
  }, 500);
15388
14729
  }
@@ -15445,6 +14786,7 @@ function PortalInner({ state = {}, children, container }) {
15445
14786
  viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), resolvedSize);
15446
14787
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15447
14788
  }
14789
+ const set = injectState.set;
15448
14790
  return {
15449
14791
  // The intersect consists of the previous root state
15450
14792
  ...rootState,
@@ -15463,7 +14805,7 @@ function PortalInner({ state = {}, children, container }) {
15463
14805
  size: resolvedSize,
15464
14806
  viewport: { ...rootState.viewport, ...viewport },
15465
14807
  // Layers are allowed to override events
15466
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14808
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15467
14809
  // Container for child attachment - the portalScene (injected or container itself)
15468
14810
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15469
14811
  };
@@ -15472,9 +14814,13 @@ function PortalInner({ state = {}, children, container }) {
15472
14814
  const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15473
14815
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15474
14816
  onMutate(previousRoot.getState());
15475
- previousRoot.subscribe(onMutate);
15476
14817
  return store;
15477
14818
  }, [previousRoot, container]);
14819
+ useIsomorphicLayoutEffect(() => {
14820
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14821
+ const unsubscribe = previousRoot.subscribe(onMutate);
14822
+ return unsubscribe;
14823
+ }, [previousRoot, usePortalStore]);
15478
14824
  return (
15479
14825
  // @ts-ignore, reconciler types are not maintained
15480
14826
  /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
@@ -15488,6 +14834,81 @@ function flushSync(fn) {
15488
14834
  return reconciler.flushSyncFromReconciler(fn);
15489
14835
  }
15490
14836
 
14837
+ function parseBackground(background) {
14838
+ if (!background) return null;
14839
+ if (typeof background === "object" && !background.isColor) {
14840
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14841
+ return {
14842
+ ...rest,
14843
+ preset,
14844
+ files: envMap || files,
14845
+ backgroundFiles: backgroundMap,
14846
+ background: true
14847
+ };
14848
+ }
14849
+ if (typeof background === "number") {
14850
+ return { color: background, background: true };
14851
+ }
14852
+ if (typeof background === "string") {
14853
+ if (background in presetsObj) {
14854
+ return { preset: background, background: true };
14855
+ }
14856
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14857
+ return { files: background, background: true };
14858
+ }
14859
+ return { color: background, background: true };
14860
+ }
14861
+ if (background.isColor) {
14862
+ return { color: background, background: true };
14863
+ }
14864
+ return null;
14865
+ }
14866
+
14867
+ function parseRendererConfig(rendererProp) {
14868
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14869
+ if (isRendererConfig) {
14870
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14871
+ return {
14872
+ primaryCanvas: pc,
14873
+ scheduler: sc,
14874
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14875
+ };
14876
+ }
14877
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14878
+ }
14879
+
14880
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14881
+ const registries = /* @__PURE__ */ new WeakMap();
14882
+ function getKindRegistry(store, kind) {
14883
+ let registry = registries.get(store);
14884
+ if (!registry) {
14885
+ registry = {
14886
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14887
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14888
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14889
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14890
+ };
14891
+ registries.set(store, registry);
14892
+ }
14893
+ return registry[kind];
14894
+ }
14895
+ function invalidateResource(store, kind, scopeKey) {
14896
+ const registry = getKindRegistry(store, kind);
14897
+ {
14898
+ registry.valid.clear();
14899
+ registry.staged.clear();
14900
+ }
14901
+ }
14902
+ function invalidateAllResources(store) {
14903
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14904
+ }
14905
+
14906
+ function clearHmrCaches(store) {
14907
+ const primary = store.getState().primaryStore ?? store;
14908
+ invalidateAllResources(primary);
14909
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14910
+ }
14911
+
15491
14912
  function CanvasImpl({
15492
14913
  ref,
15493
14914
  children,
@@ -15508,6 +14929,8 @@ function CanvasImpl({
15508
14929
  raycaster,
15509
14930
  camera,
15510
14931
  scene,
14932
+ autoUpdateFrustum,
14933
+ occlusion,
15511
14934
  onPointerMissed,
15512
14935
  onDragOverMissed,
15513
14936
  onDropMissed,
@@ -15519,39 +14942,10 @@ function CanvasImpl({
15519
14942
  forceEven,
15520
14943
  ...props
15521
14944
  }) {
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;
14945
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15524
14946
  React__namespace.useMemo(() => extend(THREE), []);
15525
14947
  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]);
14948
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15555
14949
  const hasInitialSizeRef = React__namespace.useRef(false);
15556
14950
  const measureConfig = React__namespace.useMemo(() => {
15557
14951
  if (!hasInitialSizeRef.current) {
@@ -15593,6 +14987,7 @@ function CanvasImpl({
15593
14987
  const handleDropMissed = useMutableCallback(onDropMissed);
15594
14988
  const [block, setBlock] = React__namespace.useState(false);
15595
14989
  const [error, setError] = React__namespace.useState(false);
14990
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15596
14991
  if (block) throw block;
15597
14992
  if (error) throw error;
15598
14993
  const root = React__namespace.useRef(null);
@@ -15600,6 +14995,7 @@ function CanvasImpl({
15600
14995
  const unsubscribeErrorRef = React__namespace.useRef(null);
15601
14996
  useIsomorphicLayoutEffect(() => {
15602
14997
  effectActiveRef.current = true;
14998
+ if (fallbackVisible) return;
15603
14999
  const canvas = canvasRef.current;
15604
15000
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15605
15001
  if (!root.current) {
@@ -15620,7 +15016,7 @@ function CanvasImpl({
15620
15016
  }
15621
15017
  async function run() {
15622
15018
  if (!effectActiveRef.current || !root.current) return;
15623
- await root.current.configure({
15019
+ const configured = await root.current.configure({
15624
15020
  id,
15625
15021
  primaryCanvas,
15626
15022
  scheduler,
@@ -15635,6 +15031,8 @@ function CanvasImpl({
15635
15031
  performance,
15636
15032
  raycaster,
15637
15033
  camera,
15034
+ autoUpdateFrustum,
15035
+ occlusion,
15638
15036
  size: effectiveSize,
15639
15037
  // Store size props for reset functionality
15640
15038
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15659,8 +15057,20 @@ function CanvasImpl({
15659
15057
  }
15660
15058
  onCreated?.(state);
15661
15059
  }
15662
- });
15663
- if (!effectActiveRef.current || !root.current) return;
15060
+ }).then(
15061
+ () => true,
15062
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15063
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15064
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15065
+ (setupError) => {
15066
+ if (effectActiveRef.current) {
15067
+ if (fallback != null) setFallbackVisible(true);
15068
+ else setError(setupError);
15069
+ }
15070
+ return false;
15071
+ }
15072
+ );
15073
+ if (!configured || !effectActiveRef.current || !root.current) return;
15664
15074
  root.current.render(
15665
15075
  /* @__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
15076
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15694,20 +15104,13 @@ function CanvasImpl({
15694
15104
  const handleHMR = () => {
15695
15105
  queueMicrotask(() => {
15696
15106
  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
- }
15107
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15704
15108
  });
15705
15109
  };
15706
15110
  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
15111
  const hot = undefined;
15708
15112
  hot.on("vite:afterUpdate", handleHMR);
15709
- return () => hot.dispose?.(() => {
15710
- });
15113
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
15711
15114
  }
15712
15115
  if (typeof module !== "undefined" && module.hot) {
15713
15116
  const hot = module.hot;
@@ -15730,7 +15133,20 @@ function CanvasImpl({
15730
15133
  ...style
15731
15134
  },
15732
15135
  ...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 }) })
15136
+ children: fallbackVisible ? (
15137
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15138
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15139
+ fallback
15140
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15141
+ "canvas",
15142
+ {
15143
+ ref: canvasRef,
15144
+ id,
15145
+ className: "r3f-canvas",
15146
+ style: { display: "block", width: "100%", height: "100%" },
15147
+ children: fallback
15148
+ }
15149
+ ) })
15734
15150
  }
15735
15151
  );
15736
15152
  }
@@ -15740,6 +15156,8 @@ function Canvas(props) {
15740
15156
 
15741
15157
  extend(THREE);
15742
15158
 
15159
+ exports.Scheduler = scheduler.Scheduler;
15160
+ exports.getScheduler = scheduler.getScheduler;
15743
15161
  exports.Block = Block;
15744
15162
  exports.Canvas = Canvas;
15745
15163
  exports.Environment = Environment;
@@ -15755,10 +15173,8 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15755
15173
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15756
15174
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15757
15175
  exports.RESERVED_PROPS = RESERVED_PROPS;
15758
- exports.Scheduler = Scheduler;
15759
15176
  exports.Texture = Texture;
15760
15177
  exports._roots = _roots;
15761
- exports.act = act;
15762
15178
  exports.addAfterEffect = addAfterEffect;
15763
15179
  exports.addEffect = addEffect;
15764
15180
  exports.addTail = addTail;
@@ -15785,7 +15201,6 @@ exports.getInstanceProps = getInstanceProps;
15785
15201
  exports.getPrimary = getPrimary;
15786
15202
  exports.getPrimaryIds = getPrimaryIds;
15787
15203
  exports.getRootState = getRootState;
15788
- exports.getScheduler = getScheduler;
15789
15204
  exports.getUuidPrefix = getUuidPrefix;
15790
15205
  exports.hasConstructor = hasConstructor;
15791
15206
  exports.hasPrimary = hasPrimary;