@react-three/fiber 10.0.0-canary.dbbe704 → 10.0.0-canary.f046a54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -15,6 +15,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
15
15
  const gainmapJs = require('@monogrid/gainmap-js');
16
16
  const Tb = require('scheduler');
17
17
  const traditional = require('zustand/traditional');
18
+ const scheduler = require('@pmndrs/scheduler');
18
19
  const suspendReact = require('suspend-react');
19
20
 
20
21
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -160,7 +161,7 @@ function useEnvironment({
160
161
  fiber.useLoader.clear(loader, multiFile ? [files] : files);
161
162
  }
162
163
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
163
- }, [files, renderer.domElement]);
164
+ }, [extension, files, loader, multiFile, renderer.domElement]);
164
165
  const loaderResult = fiber.useLoader(
165
166
  loader,
166
167
  multiFile ? [files] : files,
@@ -360,7 +361,22 @@ function EnvironmentPortal({
360
361
  environmentIntensity,
361
362
  environmentRotation
362
363
  });
363
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
364
+ }, [
365
+ children,
366
+ virtualScene,
367
+ fbo.texture,
368
+ scene,
369
+ defaultScene,
370
+ background,
371
+ frames,
372
+ gl,
373
+ blur,
374
+ backgroundBlurriness,
375
+ backgroundIntensity,
376
+ backgroundRotation,
377
+ environmentIntensity,
378
+ environmentRotation
379
+ ]);
364
380
  let count = 1;
365
381
  fiber.useFrame(() => {
366
382
  if (frames === Infinity || count < frames) {
@@ -431,9 +447,9 @@ function Environment(props) {
431
447
  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 });
432
448
  }
433
449
 
434
- var __defProp$2 = Object.defineProperty;
435
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
436
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
450
+ var __defProp = Object.defineProperty;
451
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
452
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
437
453
  const act = React__namespace["act"];
438
454
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
439
455
  function useMutableCallback(fn) {
@@ -465,7 +481,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
465
481
  return _a = class extends React__namespace.Component {
466
482
  constructor() {
467
483
  super(...arguments);
468
- __publicField$2(this, "state", { error: false });
484
+ __publicField(this, "state", { error: false });
469
485
  }
470
486
  componentDidCatch(err) {
471
487
  this.props.set(err);
@@ -473,7 +489,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
473
489
  render() {
474
490
  return this.state.error ? null : this.props.children;
475
491
  }
476
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
492
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
477
493
  })();
478
494
 
479
495
  const is = {
@@ -994,8 +1010,24 @@ function applyProps(object, props) {
994
1010
  } else if (isVectorLike(target) && is.num(value)) {
995
1011
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
996
1012
  else target.set(value);
1013
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1014
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1015
+ const uniforms = root.uniforms;
1016
+ const nextUniforms = value;
1017
+ for (const name in nextUniforms) {
1018
+ const uniform = nextUniforms[name];
1019
+ const targetUniform = uniforms[name];
1020
+ if (targetUniform) Object.assign(targetUniform, uniform);
1021
+ else {
1022
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1023
+ uniforms[name] = nextUniform;
1024
+ }
1025
+ }
997
1026
  } else {
998
1027
  root[key] = value;
1028
+ if (key.endsWith("Node") && root.isMaterial) {
1029
+ root.needsUpdate = true;
1030
+ }
999
1031
  if (rootState && rootState.renderer?.outputColorSpace === webgpu.SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
1000
1032
  root[key].format === webgpu.RGBAFormat && root[key].type === webgpu.UnsignedByteType) {
1001
1033
  root[key].colorSpace = rootState.textureColorSpace;
@@ -1029,38 +1061,60 @@ function applyProps(object, props) {
1029
1061
  return object;
1030
1062
  }
1031
1063
 
1064
+ const DEFAULT_POINTER_ID = 0;
1065
+ const XR_POINTER_ID_START = 1e3;
1066
+ function getPointerState(internal, pointerId) {
1067
+ let state = internal.pointerMap.get(pointerId);
1068
+ if (!state) {
1069
+ state = {
1070
+ hovered: /* @__PURE__ */ new Map(),
1071
+ captured: /* @__PURE__ */ new Map(),
1072
+ initialClick: [0, 0],
1073
+ initialHits: []
1074
+ };
1075
+ internal.pointerMap.set(pointerId, state);
1076
+ }
1077
+ return state;
1078
+ }
1079
+ function getPointerId(event) {
1080
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1081
+ }
1032
1082
  function makeId(event) {
1033
1083
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
1034
1084
  }
1035
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
1036
- const captureData = captures.get(obj);
1085
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1086
+ const pointerState = internal.pointerMap.get(pointerId);
1087
+ if (!pointerState) return;
1088
+ const captureData = pointerState.captured.get(obj);
1037
1089
  if (captureData) {
1038
- captures.delete(obj);
1039
- if (captures.size === 0) {
1040
- capturedMap.delete(pointerId);
1041
- captureData.target.releasePointerCapture(pointerId);
1042
- }
1090
+ pointerState.captured.delete(obj);
1091
+ captureData.target.releasePointerCapture(pointerId);
1043
1092
  }
1044
1093
  }
1045
1094
  function removeInteractivity(store, object) {
1046
1095
  const { internal } = store.getState();
1047
1096
  internal.interaction = internal.interaction.filter((o) => o !== object);
1048
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
1049
- internal.hovered.forEach((value, key) => {
1050
- if (value.eventObject === object || value.object === object) {
1051
- internal.hovered.delete(key);
1097
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1098
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1099
+ pointerState.hovered.forEach((value, key) => {
1100
+ if (value.eventObject === object || value.object === object) {
1101
+ pointerState.hovered.delete(key);
1102
+ }
1103
+ });
1104
+ if (pointerState.captured.has(object)) {
1105
+ releaseInternalPointerCapture(internal, object, pointerId);
1052
1106
  }
1053
- });
1054
- internal.capturedMap.forEach((captures, pointerId) => {
1055
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
1056
- });
1107
+ }
1057
1108
  unregisterVisibility(store, object);
1058
1109
  }
1059
1110
  function createEvents(store) {
1060
- function calculateDistance(event) {
1111
+ function calculateDistance(event, pointerId) {
1061
1112
  const { internal } = store.getState();
1062
- const dx = event.offsetX - internal.initialClick[0];
1063
- const dy = event.offsetY - internal.initialClick[1];
1113
+ const pointerState = internal.pointerMap.get(pointerId);
1114
+ if (!pointerState) return 0;
1115
+ const [initialX, initialY] = pointerState.initialClick;
1116
+ const dx = event.offsetX - initialX;
1117
+ const dy = event.offsetY - initialY;
1064
1118
  return Math.round(Math.sqrt(dx * dx + dy * dy));
1065
1119
  }
1066
1120
  function filterPointerEvents(objects) {
@@ -1096,6 +1150,15 @@ function createEvents(store) {
1096
1150
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
1097
1151
  }
1098
1152
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1153
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1154
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1155
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1156
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1157
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1158
+ if (aInteractivePriority !== bInteractivePriority) {
1159
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1160
+ }
1161
+ }
1099
1162
  const aState = getRootState(a.object);
1100
1163
  const bState = getRootState(b.object);
1101
1164
  const aPriority = aState?.events?.priority ?? 1;
@@ -1117,9 +1180,13 @@ function createEvents(store) {
1117
1180
  eventObject = eventObject.parent;
1118
1181
  }
1119
1182
  }
1120
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
1121
- for (const captureData of state.internal.capturedMap.get(event.pointerId).values()) {
1122
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1183
+ if ("pointerId" in event) {
1184
+ const pointerId = event.pointerId;
1185
+ const pointerState = state.internal.pointerMap.get(pointerId);
1186
+ if (pointerState?.captured.size) {
1187
+ for (const captureData of pointerState.captured.values()) {
1188
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1189
+ }
1123
1190
  }
1124
1191
  }
1125
1192
  return intersections;
@@ -1132,27 +1199,25 @@ function createEvents(store) {
1132
1199
  if (state) {
1133
1200
  const { raycaster, pointer, camera, internal } = state;
1134
1201
  const unprojectedPoint = new webgpu.Vector3(pointer.x, pointer.y, 0).unproject(camera);
1135
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1202
+ const hasPointerCapture = (id) => {
1203
+ const pointerState = internal.pointerMap.get(id);
1204
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1205
+ };
1136
1206
  const setPointerCapture = (id) => {
1137
1207
  const captureData = { intersection: hit, target: event.target };
1138
- if (internal.capturedMap.has(id)) {
1139
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
1140
- } else {
1141
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
1142
- }
1208
+ const pointerState = getPointerState(internal, id);
1209
+ pointerState.captured.set(hit.eventObject, captureData);
1143
1210
  event.target.setPointerCapture(id);
1144
1211
  };
1145
1212
  const releasePointerCapture = (id) => {
1146
- const captures = internal.capturedMap.get(id);
1147
- if (captures) {
1148
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
1149
- }
1213
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
1150
1214
  };
1151
1215
  const extractEventProps = {};
1152
1216
  for (const prop in event) {
1153
1217
  const property = event[prop];
1154
1218
  if (typeof property !== "function") extractEventProps[prop] = property;
1155
1219
  }
1220
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1156
1221
  const raycastEvent = {
1157
1222
  ...hit,
1158
1223
  ...extractEventProps,
@@ -1163,18 +1228,19 @@ function createEvents(store) {
1163
1228
  unprojectedPoint,
1164
1229
  ray: raycaster.ray,
1165
1230
  camera,
1231
+ pointerId: eventPointerId,
1166
1232
  // Hijack stopPropagation, which just sets a flag
1167
1233
  stopPropagation() {
1168
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1234
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
1169
1235
  if (
1170
1236
  // ...if this pointer hasn't been captured
1171
- !capturesForPointer || // ... or if the hit object is capturing the pointer
1172
- capturesForPointer.has(hit.eventObject)
1237
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1238
+ pointerState.captured.has(hit.eventObject)
1173
1239
  ) {
1174
1240
  raycastEvent.stopped = localState.stopped = true;
1175
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1241
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1176
1242
  const higher = intersections.slice(0, intersections.indexOf(hit));
1177
- cancelPointer([...higher, hit]);
1243
+ cancelPointer([...higher, hit], eventPointerId);
1178
1244
  }
1179
1245
  }
1180
1246
  },
@@ -1190,15 +1256,18 @@ function createEvents(store) {
1190
1256
  }
1191
1257
  return intersections;
1192
1258
  }
1193
- function cancelPointer(intersections) {
1259
+ function cancelPointer(intersections, pointerId) {
1194
1260
  const { internal } = store.getState();
1195
- for (const hoveredObj of internal.hovered.values()) {
1261
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1262
+ const pointerState = internal.pointerMap.get(pid);
1263
+ if (!pointerState) return;
1264
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
1196
1265
  if (!intersections.length || !intersections.find(
1197
1266
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
1198
1267
  )) {
1199
1268
  const eventObject = hoveredObj.eventObject;
1200
1269
  const instance = eventObject.__r3f;
1201
- internal.hovered.delete(makeId(hoveredObj));
1270
+ pointerState.hovered.delete(hoveredId);
1202
1271
  if (instance?.eventCount) {
1203
1272
  const handlers = instance.handlers;
1204
1273
  const data = { ...hoveredObj, intersections };
@@ -1227,41 +1296,118 @@ function createEvents(store) {
1227
1296
  instance?.handlers.onDropMissed?.(event);
1228
1297
  }
1229
1298
  }
1299
+ function cleanupPointer(pointerId) {
1300
+ const { internal } = store.getState();
1301
+ const pointerState = internal.pointerMap.get(pointerId);
1302
+ if (pointerState) {
1303
+ for (const [, hoveredObj] of pointerState.hovered) {
1304
+ const eventObject = hoveredObj.eventObject;
1305
+ const instance = eventObject.__r3f;
1306
+ if (instance?.eventCount) {
1307
+ const handlers = instance.handlers;
1308
+ const data = { ...hoveredObj, intersections: [] };
1309
+ handlers.onPointerOut?.(data);
1310
+ handlers.onPointerLeave?.(data);
1311
+ }
1312
+ }
1313
+ internal.pointerMap.delete(pointerId);
1314
+ }
1315
+ internal.pointerDirty.delete(pointerId);
1316
+ }
1317
+ function processDeferredPointer(event, pointerId) {
1318
+ const state = store.getState();
1319
+ const { internal } = state;
1320
+ if (!state.events.enabled) return;
1321
+ const filter = filterPointerEvents;
1322
+ const hits = intersect(event, filter);
1323
+ cancelPointer(hits, pointerId);
1324
+ function onIntersect(data) {
1325
+ const eventObject = data.eventObject;
1326
+ const instance = eventObject.__r3f;
1327
+ if (!instance?.eventCount) return;
1328
+ const handlers = instance.handlers;
1329
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1330
+ const id = makeId(data);
1331
+ const pointerState = getPointerState(internal, pointerId);
1332
+ const hoveredItem = pointerState.hovered.get(id);
1333
+ if (!hoveredItem) {
1334
+ pointerState.hovered.set(id, data);
1335
+ handlers.onPointerOver?.(data);
1336
+ handlers.onPointerEnter?.(data);
1337
+ } else if (hoveredItem.stopped) {
1338
+ data.stopPropagation();
1339
+ }
1340
+ }
1341
+ handlers.onPointerMove?.(data);
1342
+ }
1343
+ handleIntersects(hits, event, 0, onIntersect);
1344
+ }
1230
1345
  function handlePointer(name) {
1231
1346
  switch (name) {
1232
1347
  case "onPointerLeave":
1233
- case "onPointerCancel":
1234
1348
  case "onDragLeave":
1235
1349
  return () => cancelPointer([]);
1350
+ // Global cancel of these events
1351
+ case "onPointerCancel":
1352
+ return (event) => {
1353
+ const pointerId = getPointerId(event);
1354
+ cleanupPointer(pointerId);
1355
+ };
1236
1356
  case "onLostPointerCapture":
1237
1357
  return (event) => {
1238
1358
  const { internal } = store.getState();
1239
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1359
+ const pointerId = getPointerId(event);
1360
+ const pointerState = internal.pointerMap.get(pointerId);
1361
+ if (pointerState?.captured.size) {
1240
1362
  requestAnimationFrame(() => {
1241
- if (internal.capturedMap.has(event.pointerId)) {
1242
- internal.capturedMap.delete(event.pointerId);
1243
- cancelPointer([]);
1363
+ const pointerState2 = internal.pointerMap.get(pointerId);
1364
+ if (pointerState2?.captured.size) {
1365
+ pointerState2.captured.clear();
1244
1366
  }
1367
+ cancelPointer([], pointerId);
1245
1368
  });
1246
1369
  }
1247
1370
  };
1248
1371
  }
1249
1372
  return function handleEvent(event) {
1250
1373
  const state = store.getState();
1251
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1374
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1375
+ const pointerId = getPointerId(event);
1252
1376
  internal.lastEvent.current = event;
1253
- if (!state.events.enabled) return;
1377
+ if (!events.enabled) return;
1254
1378
  const isPointerMove = name === "onPointerMove";
1255
1379
  const isDragOver = name === "onDragOver";
1256
1380
  const isDrop = name === "onDrop";
1257
1381
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1382
+ const isPointerDown = name === "onPointerDown";
1383
+ const isPointerUp = name === "onPointerUp";
1384
+ const isWheel = name === "onWheel";
1385
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1386
+ if (isPointerMove && canDeferRaycasts) {
1387
+ events.compute?.(event, state);
1388
+ internal.pointerDirty.set(pointerId, event);
1389
+ return;
1390
+ }
1391
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1392
+ events.compute?.(event, state);
1393
+ internal.pointerDirty.set(pointerId, event);
1394
+ return;
1395
+ }
1396
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1397
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1398
+ internal.pointerDirty.delete(pointerId);
1399
+ processDeferredPointer(deferredEvent, pointerId);
1400
+ }
1258
1401
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
1259
1402
  const hits = intersect(event, filter);
1260
- const delta = isClickEvent ? calculateDistance(event) : 0;
1261
- if (name === "onPointerDown") {
1262
- internal.initialClick = [event.offsetX, event.offsetY];
1263
- internal.initialHits = hits.map((hit) => hit.eventObject);
1264
- }
1403
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1404
+ if (isPointerDown) {
1405
+ const pointerState2 = getPointerState(internal, pointerId);
1406
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1407
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1408
+ }
1409
+ const pointerState = internal.pointerMap.get(pointerId);
1410
+ const initialHits = pointerState?.initialHits ?? [];
1265
1411
  if (isClickEvent && !hits.length) {
1266
1412
  if (delta <= 2) {
1267
1413
  pointerMissed(event, internal.interaction);
@@ -1276,7 +1422,9 @@ function createEvents(store) {
1276
1422
  dropMissed(event, internal.interaction);
1277
1423
  if (onDropMissed) onDropMissed(event);
1278
1424
  }
1279
- if (isPointerMove || isDragOver) cancelPointer(hits);
1425
+ if (isPointerMove || isDragOver) {
1426
+ cancelPointer(hits, pointerId);
1427
+ }
1280
1428
  function onIntersect(data) {
1281
1429
  const eventObject = data.eventObject;
1282
1430
  const instance = eventObject.__r3f;
@@ -1285,9 +1433,10 @@ function createEvents(store) {
1285
1433
  if (isPointerMove) {
1286
1434
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1287
1435
  const id = makeId(data);
1288
- const hoveredItem = internal.hovered.get(id);
1436
+ const pointerState2 = getPointerState(internal, pointerId);
1437
+ const hoveredItem = pointerState2.hovered.get(id);
1289
1438
  if (!hoveredItem) {
1290
- internal.hovered.set(id, data);
1439
+ pointerState2.hovered.set(id, data);
1291
1440
  handlers.onPointerOver?.(data);
1292
1441
  handlers.onPointerEnter?.(data);
1293
1442
  } else if (hoveredItem.stopped) {
@@ -1297,9 +1446,10 @@ function createEvents(store) {
1297
1446
  handlers.onPointerMove?.(data);
1298
1447
  } else if (isDragOver) {
1299
1448
  const id = makeId(data);
1300
- const hoveredItem = internal.hovered.get(id);
1449
+ const pointerState2 = getPointerState(internal, pointerId);
1450
+ const hoveredItem = pointerState2.hovered.get(id);
1301
1451
  if (!hoveredItem) {
1302
- internal.hovered.set(id, data);
1452
+ pointerState2.hovered.set(id, data);
1303
1453
  handlers.onDragOverEnter?.(data);
1304
1454
  } else if (hoveredItem.stopped) {
1305
1455
  data.stopPropagation();
@@ -1310,18 +1460,18 @@ function createEvents(store) {
1310
1460
  } else {
1311
1461
  const handler = handlers[name];
1312
1462
  if (handler) {
1313
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1463
+ if (!isClickEvent || initialHits.includes(eventObject)) {
1314
1464
  pointerMissed(
1315
1465
  event,
1316
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1466
+ internal.interaction.filter((object) => !initialHits.includes(object))
1317
1467
  );
1318
1468
  handler(data);
1319
1469
  }
1320
1470
  } else {
1321
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1471
+ if (isClickEvent && initialHits.includes(eventObject)) {
1322
1472
  pointerMissed(
1323
1473
  event,
1324
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1474
+ internal.interaction.filter((object) => !initialHits.includes(object))
1325
1475
  );
1326
1476
  }
1327
1477
  }
@@ -1330,7 +1480,15 @@ function createEvents(store) {
1330
1480
  handleIntersects(hits, event, delta, onIntersect);
1331
1481
  };
1332
1482
  }
1333
- return { handlePointer };
1483
+ function flushDeferredPointers() {
1484
+ const { internal, events } = store.getState();
1485
+ if (!events.frameTimedRaycasts) return;
1486
+ for (const [pointerId, event] of internal.pointerDirty) {
1487
+ processDeferredPointer(event, pointerId);
1488
+ }
1489
+ internal.pointerDirty.clear();
1490
+ }
1491
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
1334
1492
  }
1335
1493
  const DOM_EVENTS = {
1336
1494
  onClick: ["click", false],
@@ -1349,10 +1507,15 @@ const DOM_EVENTS = {
1349
1507
  onLostPointerCapture: ["lostpointercapture", true]
1350
1508
  };
1351
1509
  function createPointerEvents(store) {
1352
- const { handlePointer } = createEvents(store);
1510
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1511
+ let nextXRPointerId = XR_POINTER_ID_START;
1512
+ const xrPointers = /* @__PURE__ */ new Map();
1353
1513
  return {
1354
1514
  priority: 1,
1355
1515
  enabled: true,
1516
+ frameTimedRaycasts: true,
1517
+ alwaysFireOnScroll: true,
1518
+ updateOnFrame: false,
1356
1519
  compute(event, state) {
1357
1520
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
1358
1521
  state.raycaster.setFromCamera(state.pointer, state.camera);
@@ -1362,11 +1525,33 @@ function createPointerEvents(store) {
1362
1525
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
1363
1526
  {}
1364
1527
  ),
1365
- update: () => {
1528
+ update: (pointerId) => {
1366
1529
  const { events, internal } = store.getState();
1367
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1530
+ if (!events.handlers) return;
1531
+ if (pointerId !== void 0) {
1532
+ const event = internal.pointerDirty.get(pointerId);
1533
+ if (event) {
1534
+ internal.pointerDirty.delete(pointerId);
1535
+ processDeferredPointer(event, pointerId);
1536
+ } else if (internal.lastEvent?.current) {
1537
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1538
+ }
1539
+ } else {
1540
+ flushDeferredPointers();
1541
+ if (internal.lastEvent?.current) {
1542
+ events.handlers.onPointerMove(internal.lastEvent.current);
1543
+ }
1544
+ }
1545
+ },
1546
+ flush: () => {
1547
+ const { events, internal } = store.getState();
1548
+ flushDeferredPointers();
1549
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1550
+ events.handlers.onPointerMove(internal.lastEvent.current);
1551
+ }
1368
1552
  },
1369
1553
  connect: (target) => {
1554
+ if (!target) return;
1370
1555
  const { set, events } = store.getState();
1371
1556
  events.disconnect?.();
1372
1557
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1390,6 +1575,32 @@ function createPointerEvents(store) {
1390
1575
  }
1391
1576
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1392
1577
  }
1578
+ },
1579
+ registerPointer: (config) => {
1580
+ const pointerId = nextXRPointerId++;
1581
+ xrPointers.set(pointerId, config);
1582
+ const { internal } = store.getState();
1583
+ getPointerState(internal, pointerId);
1584
+ return pointerId;
1585
+ },
1586
+ unregisterPointer: (pointerId) => {
1587
+ xrPointers.delete(pointerId);
1588
+ const { internal } = store.getState();
1589
+ const pointerState = internal.pointerMap.get(pointerId);
1590
+ if (pointerState) {
1591
+ for (const [, hoveredObj] of pointerState.hovered) {
1592
+ const eventObject = hoveredObj.eventObject;
1593
+ const instance = eventObject.__r3f;
1594
+ if (instance?.eventCount) {
1595
+ const handlers = instance.handlers;
1596
+ const data = { ...hoveredObj, intersections: [] };
1597
+ handlers.onPointerOut?.(data);
1598
+ handlers.onPointerLeave?.(data);
1599
+ }
1600
+ }
1601
+ internal.pointerMap.delete(pointerId);
1602
+ }
1603
+ internal.pointerDirty.delete(pointerId);
1393
1604
  }
1394
1605
  };
1395
1606
  }
@@ -1451,1036 +1662,12 @@ function notifyAlpha({ message, link }) {
1451
1662
  }
1452
1663
  }
1453
1664
 
1454
- var __defProp$1 = Object.defineProperty;
1455
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1456
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1457
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1458
- class PhaseGraph {
1459
- constructor() {
1460
- /** Ordered list of phase nodes */
1461
- __publicField$1(this, "phases", []);
1462
- /** Quick lookup by name */
1463
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1464
- /** Cached ordered names (invalidated on changes) */
1465
- __publicField$1(this, "orderedNamesCache", null);
1466
- this.initializeDefaultPhases();
1467
- }
1468
- //* Initialization --------------------------------
1469
- initializeDefaultPhases() {
1470
- for (const name of DEFAULT_PHASES) {
1471
- const node = { name, isAutoGenerated: false };
1472
- this.phases.push(node);
1473
- this.phaseMap.set(name, node);
1474
- }
1475
- this.invalidateCache();
1476
- }
1477
- //* Public API --------------------------------
1478
- /**
1479
- * Add a named phase to the graph
1480
- * @param name - Phase name (must be unique)
1481
- * @param options - Position options (before or after another phase)
1482
- */
1483
- addPhase(name, options = {}) {
1484
- if (this.phaseMap.has(name)) {
1485
- console.warn(`[useFrame] Phase "${name}" already exists`);
1486
- return;
1487
- }
1488
- const { before, after } = options;
1489
- const node = { name, isAutoGenerated: false };
1490
- let insertIndex = this.phases.length;
1491
- const targetIndex = this.getPhaseIndex(before ?? after);
1492
- if (targetIndex !== -1) {
1493
- insertIndex = before ? targetIndex : targetIndex + 1;
1494
- } else {
1495
- const constraintType = before ? "before" : "after";
1496
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1497
- }
1498
- this.phases.splice(insertIndex, 0, node);
1499
- this.phaseMap.set(name, node);
1500
- this.invalidateCache();
1501
- }
1502
- /**
1503
- * Get ordered list of phase names
1504
- */
1505
- getOrderedPhases() {
1506
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1507
- return this.orderedNamesCache;
1508
- }
1509
- /**
1510
- * Check if a phase exists
1511
- */
1512
- hasPhase(name) {
1513
- return this.phaseMap.has(name);
1514
- }
1515
- /**
1516
- * Get the index of a phase (-1 if not found)
1517
- */
1518
- getPhaseIndex(name) {
1519
- if (!name) return -1;
1520
- return this.phases.findIndex((p) => p.name === name);
1521
- }
1522
- /**
1523
- * Ensure a phase exists, creating an auto-generated one if needed.
1524
- * Used for resolving before/after constraints.
1525
- *
1526
- * @param name - The phase name to ensure exists
1527
- * @returns The phase name (may be auto-generated like 'before:render')
1528
- */
1529
- ensurePhase(name) {
1530
- if (this.phaseMap.has(name)) return name;
1531
- const node = { name, isAutoGenerated: true };
1532
- this.phases.push(node);
1533
- this.phaseMap.set(name, node);
1534
- this.invalidateCache();
1535
- return name;
1536
- }
1537
- /**
1538
- * Resolve where a job with before/after constraints should go.
1539
- * Creates auto-generated phases if needed.
1540
- *
1541
- * @param before - Phase(s) to run before
1542
- * @param after - Phase(s) to run after
1543
- * @returns The resolved phase name
1544
- */
1545
- resolveConstraintPhase(before, after) {
1546
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1547
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1548
- if (beforeArr.length > 0) {
1549
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1550
- }
1551
- if (afterArr.length > 0) {
1552
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1553
- }
1554
- return "update";
1555
- }
1556
- /**
1557
- * Ensure an auto-generated phase exists relative to a target phase.
1558
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1559
- *
1560
- * @param target - The target phase name to position relative to
1561
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1562
- * @param offset - Insertion offset (0 for before, 1 for after)
1563
- * @returns The auto-generated phase name
1564
- */
1565
- ensureAutoPhase(target, prefix, offset) {
1566
- const autoName = `${prefix}:${target}`;
1567
- if (this.phaseMap.has(autoName)) return autoName;
1568
- const node = { name: autoName, isAutoGenerated: true };
1569
- const targetIndex = this.getPhaseIndex(target);
1570
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1571
- else this.phases.push(node);
1572
- this.phaseMap.set(autoName, node);
1573
- this.invalidateCache();
1574
- return autoName;
1575
- }
1576
- // Internal --------------------------------
1577
- invalidateCache() {
1578
- this.orderedNamesCache = null;
1579
- }
1580
- }
1581
-
1582
- function rebuildSortedJobs(jobs, phaseGraph) {
1583
- const orderedPhases = phaseGraph.getOrderedPhases();
1584
- const buckets = /* @__PURE__ */ new Map();
1585
- for (const phase of orderedPhases) {
1586
- buckets.set(phase, []);
1587
- }
1588
- for (const job of jobs.values()) {
1589
- if (!job.enabled) continue;
1590
- let bucket = buckets.get(job.phase);
1591
- if (!bucket) {
1592
- bucket = [];
1593
- buckets.set(job.phase, bucket);
1594
- }
1595
- bucket.push(job);
1596
- }
1597
- const sortedBuckets = [];
1598
- for (const phase of orderedPhases) {
1599
- const bucket = buckets.get(phase);
1600
- if (!bucket || bucket.length === 0) continue;
1601
- bucket.sort((a, b) => {
1602
- if (a.priority !== b.priority) return b.priority - a.priority;
1603
- return a.index - b.index;
1604
- });
1605
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1606
- }
1607
- for (const [phase, bucket] of buckets) {
1608
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1609
- bucket.sort((a, b) => {
1610
- if (a.priority !== b.priority) return b.priority - a.priority;
1611
- return a.index - b.index;
1612
- });
1613
- sortedBuckets.push(bucket);
1614
- }
1615
- }
1616
- return sortedBuckets.flat();
1617
- }
1618
- function hasCrossJobConstraints(bucket) {
1619
- const jobIds = new Set(bucket.map((j) => j.id));
1620
- for (const job of bucket) {
1621
- for (const ref of job.before) {
1622
- if (jobIds.has(ref)) return true;
1623
- }
1624
- for (const ref of job.after) {
1625
- if (jobIds.has(ref)) return true;
1626
- }
1627
- }
1628
- return false;
1629
- }
1630
- function topologicalSort(jobs) {
1631
- const n = jobs.length;
1632
- if (n <= 1) return jobs;
1633
- const jobMap = /* @__PURE__ */ new Map();
1634
- const inDegree = /* @__PURE__ */ new Map();
1635
- const adjacency = /* @__PURE__ */ new Map();
1636
- for (const job of jobs) {
1637
- jobMap.set(job.id, job);
1638
- inDegree.set(job.id, 0);
1639
- adjacency.set(job.id, []);
1640
- }
1641
- for (const job of jobs) {
1642
- for (const ref of job.before) {
1643
- if (jobMap.has(ref)) {
1644
- adjacency.get(job.id).push(ref);
1645
- inDegree.set(ref, inDegree.get(ref) + 1);
1646
- }
1647
- }
1648
- for (const ref of job.after) {
1649
- if (jobMap.has(ref)) {
1650
- adjacency.get(ref).push(job.id);
1651
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1652
- }
1653
- }
1654
- }
1655
- const queue = [];
1656
- for (const job of jobs) {
1657
- if (inDegree.get(job.id) === 0) {
1658
- queue.push(job);
1659
- }
1660
- }
1661
- queue.sort((a, b) => {
1662
- if (a.priority !== b.priority) return b.priority - a.priority;
1663
- return a.index - b.index;
1664
- });
1665
- const result = [];
1666
- while (queue.length > 0) {
1667
- const job = queue.shift();
1668
- result.push(job);
1669
- const neighbors = adjacency.get(job.id) || [];
1670
- for (const neighborId of neighbors) {
1671
- const newDegree = inDegree.get(neighborId) - 1;
1672
- inDegree.set(neighborId, newDegree);
1673
- if (newDegree === 0) {
1674
- const neighbor = jobMap.get(neighborId);
1675
- insertSorted(queue, neighbor);
1676
- }
1677
- }
1678
- }
1679
- if (result.length !== n) {
1680
- console.warn("[useFrame] Circular dependency detected in job constraints");
1681
- const resultIds = new Set(result.map((j) => j.id));
1682
- for (const job of jobs) {
1683
- if (!resultIds.has(job.id)) result.push(job);
1684
- }
1685
- }
1686
- return result;
1687
- }
1688
- function insertSorted(arr, job) {
1689
- let i = 0;
1690
- while (i < arr.length) {
1691
- const cmp = arr[i];
1692
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1693
- break;
1694
- }
1695
- i++;
1696
- }
1697
- arr.splice(i, 0, job);
1698
- }
1699
-
1700
- function shouldRun(job, now) {
1701
- if (!job.enabled) return false;
1702
- if (!job.fps) return true;
1703
- const minInterval = 1e3 / job.fps;
1704
- const lastRun = job.lastRun ?? 0;
1705
- const elapsed = now - lastRun;
1706
- if (elapsed < minInterval) return false;
1707
- if (job.drop) {
1708
- job.lastRun = now;
1709
- } else {
1710
- const steps = Math.floor(elapsed / minInterval);
1711
- job.lastRun = lastRun + steps * minInterval;
1712
- if (job.lastRun < now - minInterval) {
1713
- job.lastRun = now;
1714
- }
1715
- }
1716
- return true;
1717
- }
1718
- function resetJobTiming(job) {
1719
- job.lastRun = void 0;
1720
- }
1721
-
1722
- var __defProp = Object.defineProperty;
1723
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1724
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1725
- const hmrData = (() => {
1726
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1727
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1728
- try {
1729
- return (0, eval)("import.meta.hot");
1730
- } catch {
1731
- return void 0;
1732
- }
1733
- })();
1734
- const _Scheduler = class _Scheduler {
1735
- //* Constructor ================================
1736
- constructor() {
1737
- //* Critical State ================================
1738
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1739
- __publicField(this, "phaseGraph");
1740
- __publicField(this, "loopState", {
1741
- running: false,
1742
- rafHandle: null,
1743
- lastTime: null,
1744
- // null = uninitialized, 0+ = valid timestamp
1745
- frameCount: 0,
1746
- elapsedTime: 0,
1747
- createdAt: performance.now()
1748
- });
1749
- __publicField(this, "stoppedTime", 0);
1750
- //* Private State ================================
1751
- __publicField(this, "nextRootIndex", 0);
1752
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1753
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1754
- __publicField(this, "nextGlobalIndex", 0);
1755
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1756
- __publicField(this, "nextJobIndex", 0);
1757
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1758
- __publicField(this, "pendingFrames", 0);
1759
- __publicField(this, "_frameloop", "always");
1760
- //* Independent Mode & Error Handling State ================================
1761
- __publicField(this, "_independent", false);
1762
- __publicField(this, "errorHandler", null);
1763
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1764
- //* Core Loop Execution Methods ================================
1765
- /**
1766
- * Main RAF loop callback.
1767
- * Executes frame, handles demand mode, and schedules next frame.
1768
- * @param {number} timestamp - RAF timestamp in milliseconds
1769
- * @returns {void}
1770
- * @private
1771
- */
1772
- __publicField(this, "loop", (timestamp) => {
1773
- if (!this.loopState.running) return;
1774
- this.executeFrame(timestamp);
1775
- if (this._frameloop === "demand") {
1776
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1777
- if (this.pendingFrames === 0) {
1778
- this.notifyIdle(timestamp);
1779
- return this.stop();
1780
- }
1781
- }
1782
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1783
- });
1784
- this.phaseGraph = new PhaseGraph();
1785
- }
1786
- static get instance() {
1787
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1788
- }
1789
- static set instance(value) {
1790
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1791
- }
1792
- /**
1793
- * Get the global scheduler instance (creates if doesn't exist).
1794
- * Uses HMR data to preserve instance across hot reloads.
1795
- * @returns {Scheduler} The singleton scheduler instance
1796
- */
1797
- static get() {
1798
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1799
- _Scheduler.instance = hmrData.data.scheduler;
1800
- }
1801
- if (!_Scheduler.instance) {
1802
- _Scheduler.instance = new _Scheduler();
1803
- if (hmrData?.data) {
1804
- hmrData.data.scheduler = _Scheduler.instance;
1805
- }
1806
- }
1807
- return _Scheduler.instance;
1808
- }
1809
- /**
1810
- * Reset the singleton instance. Stops the loop and clears all state.
1811
- * Primarily used for testing to ensure clean state between tests.
1812
- * @returns {void}
1813
- */
1814
- static reset() {
1815
- if (_Scheduler.instance) {
1816
- _Scheduler.instance.stop();
1817
- _Scheduler.instance = null;
1818
- }
1819
- if (hmrData?.data) {
1820
- hmrData.data.scheduler = null;
1821
- }
1822
- }
1823
- //* Getters & Setters ================================
1824
- get phases() {
1825
- return this.phaseGraph.getOrderedPhases();
1826
- }
1827
- get frameloop() {
1828
- return this._frameloop;
1829
- }
1830
- set frameloop(mode) {
1831
- if (this._frameloop === mode) return;
1832
- const wasAlways = this._frameloop === "always";
1833
- this._frameloop = mode;
1834
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1835
- else if (mode !== "always" && wasAlways) this.stop();
1836
- }
1837
- get isRunning() {
1838
- return this.loopState.running;
1839
- }
1840
- get isReady() {
1841
- return this.roots.size > 0;
1842
- }
1843
- get independent() {
1844
- return this._independent;
1845
- }
1846
- set independent(value) {
1847
- this._independent = value;
1848
- if (value) this.ensureDefaultRoot();
1849
- }
1850
- //* Root Management Methods ================================
1851
- /**
1852
- * Register a root (Canvas) with the scheduler.
1853
- * The first root to register starts the RAF loop (if frameloop='always').
1854
- * @param {string} id - Unique identifier for this root
1855
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1856
- * @returns {() => void} Unsubscribe function to remove this root
1857
- */
1858
- registerRoot(id, options = {}) {
1859
- if (this.roots.has(id)) {
1860
- console.warn(`[Scheduler] Root "${id}" already registered`);
1861
- return () => this.unregisterRoot(id);
1862
- }
1863
- const entry = {
1864
- id,
1865
- getState: options.getState ?? (() => ({})),
1866
- jobs: /* @__PURE__ */ new Map(),
1867
- sortedJobs: [],
1868
- needsRebuild: false
1869
- };
1870
- if (options.onError) {
1871
- this.errorHandler = options.onError;
1872
- }
1873
- this.roots.set(id, entry);
1874
- if (this.roots.size === 1) {
1875
- this.notifyRootReady();
1876
- if (this._frameloop === "always") this.start();
1877
- }
1878
- return () => this.unregisterRoot(id);
1879
- }
1880
- /**
1881
- * Unregister a root from the scheduler.
1882
- * Cleans up all job state listeners for this root's jobs.
1883
- * The last root to unregister stops the RAF loop.
1884
- * @param {string} id - The root ID to unregister
1885
- * @returns {void}
1886
- */
1887
- unregisterRoot(id) {
1888
- const root = this.roots.get(id);
1889
- if (!root) return;
1890
- for (const jobId of root.jobs.keys()) {
1891
- this.jobStateListeners.delete(jobId);
1892
- }
1893
- this.roots.delete(id);
1894
- if (this.roots.size === 0) {
1895
- this.stop();
1896
- this.errorHandler = null;
1897
- }
1898
- }
1899
- /**
1900
- * Subscribe to be notified when a root becomes available.
1901
- * Fires immediately if a root already exists.
1902
- * @param {() => void} callback - Function called when first root registers
1903
- * @returns {() => void} Unsubscribe function
1904
- */
1905
- onRootReady(callback) {
1906
- if (this.roots.size > 0) {
1907
- callback();
1908
- return () => {
1909
- };
1910
- }
1911
- this.rootReadyCallbacks.add(callback);
1912
- return () => this.rootReadyCallbacks.delete(callback);
1913
- }
1914
- /**
1915
- * Notify all registered root-ready callbacks.
1916
- * Called when the first root registers.
1917
- * @returns {void}
1918
- * @private
1919
- */
1920
- notifyRootReady() {
1921
- for (const cb of this.rootReadyCallbacks) {
1922
- try {
1923
- cb();
1924
- } catch (error) {
1925
- console.error("[Scheduler] Error in root-ready callback:", error);
1926
- }
1927
- }
1928
- this.rootReadyCallbacks.clear();
1929
- }
1930
- /**
1931
- * Ensure a default root exists for independent mode.
1932
- * Creates a minimal root with no state provider.
1933
- * @returns {void}
1934
- * @private
1935
- */
1936
- ensureDefaultRoot() {
1937
- if (!this.roots.has("__default__")) {
1938
- this.registerRoot("__default__");
1939
- }
1940
- }
1941
- /**
1942
- * Trigger error handling for job errors.
1943
- * Uses the bound error handler if available, otherwise logs to console.
1944
- * @param {Error} error - The error to handle
1945
- * @returns {void}
1946
- */
1947
- triggerError(error) {
1948
- if (this.errorHandler) this.errorHandler(error);
1949
- else console.error("[Scheduler]", error);
1950
- }
1951
- //* Phase Management Methods ================================
1952
- /**
1953
- * Add a named phase to the scheduler's execution order.
1954
- * Marks all roots for rebuild to incorporate the new phase.
1955
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1956
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1957
- * @returns {void}
1958
- * @example
1959
- * scheduler.addPhase('physics', { before: 'update' });
1960
- * scheduler.addPhase('postprocess', { after: 'render' });
1961
- */
1962
- addPhase(name, options) {
1963
- this.phaseGraph.addPhase(name, options);
1964
- for (const root of this.roots.values()) {
1965
- root.needsRebuild = true;
1966
- }
1967
- }
1968
- /**
1969
- * Check if a phase exists in the scheduler.
1970
- * @param {string} name - The phase name to check
1971
- * @returns {boolean} True if the phase exists
1972
- */
1973
- hasPhase(name) {
1974
- return this.phaseGraph.hasPhase(name);
1975
- }
1976
- //* Global Job Registration Methods (Deprecated APIs) ================================
1977
- /**
1978
- * Register a global job that runs once per frame (not per-root).
1979
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1980
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1981
- * @param {string} id - Unique identifier for this global job
1982
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1983
- * @returns {() => void} Unsubscribe function to remove this global job
1984
- * @deprecated Use useFrame with phases instead
1985
- */
1986
- registerGlobal(phase, id, callback) {
1987
- const job = { id, callback };
1988
- if (phase === "before") {
1989
- this.globalBeforeJobs.set(id, job);
1990
- } else {
1991
- this.globalAfterJobs.set(id, job);
1992
- }
1993
- return () => {
1994
- if (phase === "before") this.globalBeforeJobs.delete(id);
1995
- else this.globalAfterJobs.delete(id);
1996
- };
1997
- }
1998
- //* Idle Callback Methods (Deprecated API) ================================
1999
- /**
2000
- * Register an idle callback that fires when the loop stops.
2001
- * Used internally by deprecated addTail API.
2002
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2003
- * @returns {() => void} Unsubscribe function to remove this idle callback
2004
- * @deprecated Use demand mode with invalidate() instead
2005
- */
2006
- onIdle(callback) {
2007
- this.idleCallbacks.add(callback);
2008
- return () => this.idleCallbacks.delete(callback);
2009
- }
2010
- /**
2011
- * Notify all registered idle callbacks.
2012
- * Called when the loop stops in demand mode.
2013
- * @param {number} timestamp - The RAF timestamp when idle occurred
2014
- * @returns {void}
2015
- * @private
2016
- */
2017
- notifyIdle(timestamp) {
2018
- for (const cb of this.idleCallbacks) {
2019
- try {
2020
- cb(timestamp);
2021
- } catch (error) {
2022
- console.error("[Scheduler] Error in idle callback:", error);
2023
- }
2024
- }
2025
- }
2026
- //* Job Registration & Management Methods ================================
2027
- /**
2028
- * Register a job (frame callback) with a specific root.
2029
- * This is the core registration method used by useFrame internally.
2030
- * @param {FrameNextCallback} callback - The function to call each frame
2031
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2032
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2033
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2034
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2035
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2036
- * @param {number} [options.fps] - FPS throttle limit
2037
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2038
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2039
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2040
- * @returns {() => void} Unsubscribe function to remove this job
2041
- */
2042
- register(callback, options = {}) {
2043
- const rootId = options.rootId;
2044
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2045
- if (!root) {
2046
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2047
- return () => {
2048
- };
2049
- }
2050
- const id = options.id ?? this.generateJobId();
2051
- let phase = options.phase ?? "update";
2052
- if (!options.phase && (options.before || options.after)) {
2053
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2054
- }
2055
- const before = this.normalizeConstraints(options.before);
2056
- const after = this.normalizeConstraints(options.after);
2057
- const job = {
2058
- id,
2059
- callback,
2060
- phase,
2061
- before,
2062
- after,
2063
- priority: options.priority ?? 0,
2064
- index: this.nextJobIndex++,
2065
- fps: options.fps,
2066
- drop: options.drop ?? true,
2067
- enabled: options.enabled ?? true,
2068
- system: options.system ?? false
2069
- };
2070
- if (root.jobs.has(id)) {
2071
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2072
- }
2073
- root.jobs.set(id, job);
2074
- root.needsRebuild = true;
2075
- return () => this.unregister(id, root.id);
2076
- }
2077
- /**
2078
- * Unregister a job by its ID.
2079
- * Searches all roots if rootId is not provided.
2080
- * @param {string} id - The job ID to unregister
2081
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2082
- * @returns {void}
2083
- */
2084
- unregister(id, rootId) {
2085
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2086
- if (root?.jobs.delete(id)) {
2087
- root.needsRebuild = true;
2088
- this.jobStateListeners.delete(id);
2089
- }
2090
- }
2091
- /**
2092
- * Update a job's options dynamically.
2093
- * Searches all roots to find the job by ID.
2094
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2095
- * @param {string} id - The job ID to update
2096
- * @param {Partial<JobOptions>} options - The options to update
2097
- * @returns {void}
2098
- */
2099
- updateJob(id, options) {
2100
- let job;
2101
- let root;
2102
- for (const r of this.roots.values()) {
2103
- job = r.jobs.get(id);
2104
- if (job) {
2105
- root = r;
2106
- break;
2107
- }
2108
- }
2109
- if (!job || !root) return;
2110
- if (options.priority !== void 0) job.priority = options.priority;
2111
- if (options.fps !== void 0) job.fps = options.fps;
2112
- if (options.drop !== void 0) job.drop = options.drop;
2113
- if (options.enabled !== void 0) {
2114
- const wasEnabled = job.enabled;
2115
- job.enabled = options.enabled;
2116
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2117
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2118
- }
2119
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2120
- if (options.phase) job.phase = options.phase;
2121
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2122
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2123
- root.needsRebuild = true;
2124
- }
2125
- }
2126
- //* Job State Management Methods ================================
2127
- /**
2128
- * Check if a job is currently paused (disabled).
2129
- * @param {string} id - The job ID to check
2130
- * @returns {boolean} True if the job exists and is paused
2131
- */
2132
- isJobPaused(id) {
2133
- for (const root of this.roots.values()) {
2134
- const job = root.jobs.get(id);
2135
- if (job) return !job.enabled;
2136
- }
2137
- return false;
2138
- }
2139
- /**
2140
- * Subscribe to state changes for a specific job.
2141
- * Listener is called when job is paused or resumed.
2142
- * @param {string} id - The job ID to subscribe to
2143
- * @param {() => void} listener - Callback invoked on state changes
2144
- * @returns {() => void} Unsubscribe function
2145
- */
2146
- subscribeJobState(id, listener) {
2147
- if (!this.jobStateListeners.has(id)) {
2148
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2149
- }
2150
- this.jobStateListeners.get(id).add(listener);
2151
- return () => {
2152
- this.jobStateListeners.get(id)?.delete(listener);
2153
- if (this.jobStateListeners.get(id)?.size === 0) {
2154
- this.jobStateListeners.delete(id);
2155
- }
2156
- };
2157
- }
2158
- /**
2159
- * Notify all listeners that a job's state has changed.
2160
- * @param {string} id - The job ID that changed
2161
- * @returns {void}
2162
- * @private
2163
- */
2164
- notifyJobStateChange(id) {
2165
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2166
- }
2167
- /**
2168
- * Pause a job by ID (sets enabled=false).
2169
- * Notifies any subscribed state listeners.
2170
- * @param {string} id - The job ID to pause
2171
- * @returns {void}
2172
- */
2173
- pauseJob(id) {
2174
- this.updateJob(id, { enabled: false });
2175
- this.notifyJobStateChange(id);
2176
- }
2177
- /**
2178
- * Resume a paused job by ID (sets enabled=true).
2179
- * Resets job timing to prevent frame accumulation.
2180
- * Notifies any subscribed state listeners.
2181
- * @param {string} id - The job ID to resume
2182
- * @returns {void}
2183
- */
2184
- resumeJob(id) {
2185
- this.updateJob(id, { enabled: true });
2186
- this.notifyJobStateChange(id);
2187
- }
2188
- //* Frame Loop Control Methods ================================
2189
- /**
2190
- * Start the requestAnimationFrame loop.
2191
- * Resets timing state (elapsedTime, frameCount) on start.
2192
- * No-op if already running.
2193
- * @returns {void}
2194
- */
2195
- start() {
2196
- if (this.loopState.running) return;
2197
- const { elapsedTime, createdAt } = this.loopState;
2198
- let adjustedCreated = 0;
2199
- if (this.stoppedTime > 0) {
2200
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2201
- this.stoppedTime = 0;
2202
- }
2203
- Object.assign(this.loopState, {
2204
- running: true,
2205
- elapsedTime: elapsedTime ?? 0,
2206
- lastTime: performance.now(),
2207
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2208
- frameCount: 0,
2209
- rafHandle: requestAnimationFrame(this.loop)
2210
- });
2211
- }
2212
- /**
2213
- * Stop the requestAnimationFrame loop.
2214
- * Cancels any pending RAF callback.
2215
- * No-op if not running.
2216
- * @returns {void}
2217
- */
2218
- stop() {
2219
- if (!this.loopState.running) return;
2220
- this.loopState.running = false;
2221
- if (this.loopState.rafHandle !== null) {
2222
- cancelAnimationFrame(this.loopState.rafHandle);
2223
- this.loopState.rafHandle = null;
2224
- }
2225
- this.stoppedTime = performance.now();
2226
- }
2227
- /**
2228
- * Request frames to be rendered in demand mode.
2229
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2230
- * No-op if frameloop is not 'demand'.
2231
- * @param {number} [frames=1] - Number of frames to request
2232
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2233
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2234
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2235
- * @returns {void}
2236
- * @example
2237
- * // Request a single frame render
2238
- * scheduler.invalidate();
2239
- *
2240
- * @example
2241
- * // Request 5 frames (e.g., for animations)
2242
- * scheduler.invalidate(5);
2243
- *
2244
- * @example
2245
- * // Set pending frames to exactly 3 (don't stack with existing)
2246
- * scheduler.invalidate(3, false);
2247
- *
2248
- * @example
2249
- * // Add 2 more frames to existing pending count
2250
- * scheduler.invalidate(2, true);
2251
- */
2252
- invalidate(frames = 1, stackFrames = false) {
2253
- if (this._frameloop !== "demand") return;
2254
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2255
- this.pendingFrames = Math.min(60, baseFrames + frames);
2256
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2257
- }
2258
- /**
2259
- * Reset timing state for deterministic testing.
2260
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2261
- * @returns {void}
2262
- */
2263
- resetTiming() {
2264
- this.loopState.lastTime = null;
2265
- this.loopState.frameCount = 0;
2266
- this.loopState.elapsedTime = 0;
2267
- this.loopState.createdAt = performance.now();
2268
- }
2269
- //* Manual Stepping Methods ================================
2270
- /**
2271
- * Manually execute a single frame for all roots.
2272
- * Useful for frameloop='never' mode or testing scenarios.
2273
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2274
- * @returns {void}
2275
- * @example
2276
- * // Manual control mode
2277
- * scheduler.frameloop = 'never';
2278
- * scheduler.step(); // Execute one frame
2279
- */
2280
- step(timestamp) {
2281
- const now = timestamp ?? performance.now();
2282
- this.executeFrame(now);
2283
- }
2284
- /**
2285
- * Manually execute a single job by its ID.
2286
- * Useful for testing individual job callbacks in isolation.
2287
- * @param {string} id - The job ID to step
2288
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2289
- * @returns {void}
2290
- */
2291
- stepJob(id, timestamp) {
2292
- let job;
2293
- let root;
2294
- for (const r of this.roots.values()) {
2295
- job = r.jobs.get(id);
2296
- if (job) {
2297
- root = r;
2298
- break;
2299
- }
2300
- }
2301
- if (!job || !root) {
2302
- console.warn(`[Scheduler] Job "${id}" not found`);
2303
- return;
2304
- }
2305
- const now = timestamp ?? performance.now();
2306
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2307
- const delta = deltaMs / 1e3;
2308
- const elapsed = now - this.loopState.createdAt;
2309
- const providedState = root.getState?.() ?? {};
2310
- const frameState = {
2311
- ...providedState,
2312
- time: now,
2313
- delta,
2314
- elapsed,
2315
- frame: this.loopState.frameCount
2316
- };
2317
- try {
2318
- job.callback(frameState, delta);
2319
- } catch (error) {
2320
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2321
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2322
- }
2323
- }
2324
- /**
2325
- * Execute a single frame across all roots.
2326
- * Order: globalBefore → each root's jobs → globalAfter
2327
- * @param {number} timestamp - RAF timestamp in milliseconds
2328
- * @returns {void}
2329
- * @private
2330
- */
2331
- executeFrame(timestamp) {
2332
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2333
- const delta = deltaMs / 1e3;
2334
- this.loopState.lastTime = timestamp;
2335
- this.loopState.frameCount++;
2336
- this.loopState.elapsedTime += deltaMs;
2337
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2338
- for (const root of this.roots.values()) {
2339
- this.tickRoot(root, timestamp, delta);
2340
- }
2341
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2342
- }
2343
- /**
2344
- * Run all global jobs from a job map.
2345
- * Catches and logs errors without stopping execution.
2346
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2347
- * @param {number} timestamp - RAF timestamp in milliseconds
2348
- * @returns {void}
2349
- * @private
2350
- */
2351
- runGlobalJobs(jobs, timestamp) {
2352
- for (const job of jobs.values()) {
2353
- try {
2354
- job.callback(timestamp);
2355
- } catch (error) {
2356
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2357
- }
2358
- }
2359
- }
2360
- /**
2361
- * Execute all jobs for a single root in sorted order.
2362
- * Rebuilds sorted job list if needed, then dispatches each job.
2363
- * Errors are caught and propagated via triggerError.
2364
- * @param {RootEntry} root - The root entry to tick
2365
- * @param {number} timestamp - RAF timestamp in milliseconds
2366
- * @param {number} delta - Time since last frame in seconds
2367
- * @returns {void}
2368
- * @private
2369
- */
2370
- tickRoot(root, timestamp, delta) {
2371
- if (root.needsRebuild) {
2372
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2373
- root.needsRebuild = false;
2374
- }
2375
- const providedState = root.getState?.() ?? {};
2376
- const frameState = {
2377
- ...providedState,
2378
- time: timestamp,
2379
- delta,
2380
- elapsed: this.loopState.elapsedTime / 1e3,
2381
- // Convert ms to seconds
2382
- frame: this.loopState.frameCount
2383
- };
2384
- for (const job of root.sortedJobs) {
2385
- if (!shouldRun(job, timestamp)) continue;
2386
- try {
2387
- job.callback(frameState, delta);
2388
- } catch (error) {
2389
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2390
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2391
- }
2392
- }
2393
- }
2394
- //* Debug & Inspection Methods ================================
2395
- /**
2396
- * Get the total number of registered jobs across all roots.
2397
- * Includes both per-root jobs and global before/after jobs.
2398
- * @returns {number} Total job count
2399
- */
2400
- getJobCount() {
2401
- let count = 0;
2402
- for (const root of this.roots.values()) {
2403
- count += root.jobs.size;
2404
- }
2405
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2406
- }
2407
- /**
2408
- * Get all registered job IDs across all roots.
2409
- * Includes both per-root jobs and global before/after jobs.
2410
- * @returns {string[]} Array of all job IDs
2411
- */
2412
- getJobIds() {
2413
- const ids = [];
2414
- for (const root of this.roots.values()) {
2415
- ids.push(...root.jobs.keys());
2416
- }
2417
- ids.push(...this.globalBeforeJobs.keys());
2418
- ids.push(...this.globalAfterJobs.keys());
2419
- return ids;
2420
- }
2421
- /**
2422
- * Get the number of registered roots (Canvas instances).
2423
- * @returns {number} Number of registered roots
2424
- */
2425
- getRootCount() {
2426
- return this.roots.size;
2427
- }
2428
- /**
2429
- * Check if any user (non-system) jobs are registered in a specific phase.
2430
- * Used by the default render job to know if a user has taken over rendering.
2431
- *
2432
- * @param phase The phase to check
2433
- * @param rootId Optional root ID to check (checks all roots if not provided)
2434
- * @returns true if any user jobs exist in the phase
2435
- */
2436
- hasUserJobsInPhase(phase, rootId) {
2437
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2438
- return rootsToCheck.some((root) => {
2439
- if (!root) return false;
2440
- for (const job of root.jobs.values()) {
2441
- if (job.phase === phase && !job.system && job.enabled) return true;
2442
- }
2443
- return false;
2444
- });
2445
- }
2446
- //* Utility Methods ================================
2447
- /**
2448
- * Generate a unique root ID for automatic root registration.
2449
- * @returns {string} A unique root ID in the format 'root_N'
2450
- */
2451
- generateRootId() {
2452
- return `root_${this.nextRootIndex++}`;
2453
- }
2454
- /**
2455
- * Generate a unique job ID.
2456
- * @returns {string} A unique job ID in the format 'job_N'
2457
- * @private
2458
- */
2459
- generateJobId() {
2460
- return `job_${this.nextJobIndex}`;
2461
- }
2462
- /**
2463
- * Normalize before/after constraints to a Set.
2464
- * Handles undefined, single string, or array inputs.
2465
- * @param {string | string[] | undefined} value - The constraint value(s)
2466
- * @returns {Set<string>} Normalized Set of constraint strings
2467
- * @private
2468
- */
2469
- normalizeConstraints(value) {
2470
- if (!value) return /* @__PURE__ */ new Set();
2471
- if (Array.isArray(value)) return new Set(value);
2472
- return /* @__PURE__ */ new Set([value]);
2473
- }
2474
- };
2475
- //* Static State & Methods (Singleton Usage) ================================
2476
- //* Cross-Bundle Singleton Key ==============================
2477
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2478
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2479
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2480
- let Scheduler = _Scheduler;
2481
- const getScheduler = () => Scheduler.get();
2482
- if (hmrData) {
2483
- hmrData.accept?.();
1665
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1666
+ const INTERNAL_FIBER_MARKERS = ["packages/fiber/src", "packages/fiber/dist", "@react-three/fiber", "@react-three_fiber"];
1667
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1668
+ if (!stack) return false;
1669
+ const caller = stack.split("\n")[callerDepth] ?? "";
1670
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m)) || INTERNAL_FIBER_MARKERS.some((m) => caller.includes(m));
2484
1671
  }
2485
1672
 
2486
1673
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2520,7 +1707,14 @@ const createStore = (invalidate, advance) => {
2520
1707
  frustum: new webgpu.Frustum(),
2521
1708
  autoUpdateFrustum: true,
2522
1709
  raycaster: null,
2523
- events: { priority: 1, enabled: true, connected: false },
1710
+ events: {
1711
+ priority: 1,
1712
+ enabled: true,
1713
+ connected: false,
1714
+ frameTimedRaycasts: true,
1715
+ alwaysFireOnScroll: true,
1716
+ updateOnFrame: false
1717
+ },
2524
1718
  scene: null,
2525
1719
  rootScene: null,
2526
1720
  xr: null,
@@ -2585,7 +1779,7 @@ const createStore = (invalidate, advance) => {
2585
1779
  size: newSize,
2586
1780
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2587
1781
  }));
2588
- getScheduler().invalidate();
1782
+ scheduler.getScheduler().invalidate();
2589
1783
  }
2590
1784
  }
2591
1785
  return;
@@ -2600,7 +1794,7 @@ const createStore = (invalidate, advance) => {
2600
1794
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2601
1795
  _sizeImperative: true
2602
1796
  }));
2603
- getScheduler().invalidate();
1797
+ scheduler.getScheduler().invalidate();
2604
1798
  },
2605
1799
  setDpr: (dpr) => set((state2) => {
2606
1800
  const resolved = calculateDpr(dpr);
@@ -2611,11 +1805,14 @@ const createStore = (invalidate, advance) => {
2611
1805
  },
2612
1806
  setError: (error) => set(() => ({ error })),
2613
1807
  error: null,
2614
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1808
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2615
1809
  uniforms: {},
2616
1810
  nodes: {},
1811
+ buffers: {},
1812
+ gpuStorage: {},
2617
1813
  textures: /* @__PURE__ */ new Map(),
2618
- postProcessing: null,
1814
+ _textureRefs: /* @__PURE__ */ new Map(),
1815
+ renderPipeline: null,
2619
1816
  passes: {},
2620
1817
  _hmrVersion: 0,
2621
1818
  _sizeImperative: false,
@@ -2624,12 +1821,16 @@ const createStore = (invalidate, advance) => {
2624
1821
  internal: {
2625
1822
  // Events
2626
1823
  interaction: [],
2627
- hovered: /* @__PURE__ */ new Map(),
2628
1824
  subscribers: [],
1825
+ // Per-pointer state (new unified structure)
1826
+ pointerMap: /* @__PURE__ */ new Map(),
1827
+ pointerDirty: /* @__PURE__ */ new Map(),
1828
+ lastEvent: React__namespace.createRef(),
1829
+ // Deprecated but kept for backwards compatibility
1830
+ hovered: /* @__PURE__ */ new Map(),
2629
1831
  initialClick: [0, 0],
2630
1832
  initialHits: [],
2631
1833
  capturedMap: /* @__PURE__ */ new Map(),
2632
- lastEvent: React__namespace.createRef(),
2633
1834
  // Visibility tracking (onFramed, onOccluded, onVisible)
2634
1835
  visibilityRegistry: /* @__PURE__ */ new Map(),
2635
1836
  // Occlusion system (WebGPU only)
@@ -2668,8 +1869,7 @@ const createStore = (invalidate, advance) => {
2668
1869
  const currentState = rootStore.getState();
2669
1870
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2670
1871
  const stack = new Error().stack || "";
2671
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2672
- if (!isInternalAccess) {
1872
+ if (!isInternalRendererAccess(stack)) {
2673
1873
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2674
1874
  notifyDepreciated({
2675
1875
  heading: "Accessing state.gl in WebGPU mode",
@@ -2717,14 +1917,16 @@ const createStore = (invalidate, advance) => {
2717
1917
  oldSize = size;
2718
1918
  oldDpr = viewport.dpr;
2719
1919
  updateCamera(camera, size);
2720
- if (canvasTarget) {
1920
+ if (internal.isSecondary && canvasTarget) {
2721
1921
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2722
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2723
- canvasTarget.setSize(size.width, size.height, updateStyle);
1922
+ canvasTarget.setSize(size.width, size.height, false);
2724
1923
  } else {
2725
1924
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2726
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2727
- actualRenderer.setSize(size.width, size.height, updateStyle);
1925
+ actualRenderer.setSize(size.width, size.height, false);
1926
+ if (canvasTarget) {
1927
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1928
+ canvasTarget.setSize(size.width, size.height, false);
1929
+ }
2728
1930
  }
2729
1931
  }
2730
1932
  if (camera !== oldCamera) {
@@ -2780,26 +1982,32 @@ function loadingFn(extensions, onProgress) {
2780
1982
  );
2781
1983
  };
2782
1984
  }
2783
- function useLoader(loader, input, extensions, onProgress) {
2784
- const keys = Array.isArray(input) ? input : [input];
1985
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1986
+ const inputs = Array.isArray(input) ? input : [input];
1987
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2785
1988
  const fn = loadingFn(extensions, onProgress);
2786
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
1989
+ const results = cacheKeys.map(
1990
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1991
+ );
2787
1992
  return Array.isArray(input) ? results : results[0];
2788
1993
  }
2789
- useLoader.preload = function(loader, input, extensions, onProgress) {
2790
- const keys = Array.isArray(input) ? input : [input];
2791
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
1994
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
1995
+ const inputs = Array.isArray(input) ? input : [input];
1996
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1997
+ cacheKeys.forEach(
1998
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
1999
+ );
2792
2000
  };
2793
- useLoader.clear = function(loader, input) {
2794
- const keys = Array.isArray(input) ? input : [input];
2795
- keys.forEach((key) => suspendReact.clear([loader, key]));
2001
+ useLoader.clear = function(loader, input, cacheKey) {
2002
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2003
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
2796
2004
  };
2797
2005
  useLoader.loader = getLoader;
2798
2006
 
2799
2007
  function useFrame(callback, priorityOrOptions) {
2800
2008
  const store = React__namespace.useContext(context);
2801
2009
  const isInsideCanvas = store !== null;
2802
- const scheduler = getScheduler();
2010
+ const scheduler$1 = scheduler.getScheduler();
2803
2011
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2804
2012
  id: priorityOrOptions.id,
2805
2013
  phase: priorityOrOptions.phase,
@@ -2847,7 +2055,7 @@ function useFrame(callback, priorityOrOptions) {
2847
2055
  };
2848
2056
  callbackRef.current?.(mergedState, delta);
2849
2057
  };
2850
- const unregister = scheduler.register(wrappedCallback, {
2058
+ const unregister = scheduler$1.register(wrappedCallback, {
2851
2059
  id,
2852
2060
  rootId,
2853
2061
  ...options
@@ -2868,37 +2076,31 @@ function useFrame(callback, priorityOrOptions) {
2868
2076
  }
2869
2077
  };
2870
2078
  } else {
2871
- const registerOutside = () => {
2872
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2873
- };
2874
- if (scheduler.independent || scheduler.isReady) {
2875
- return registerOutside();
2876
- }
2877
- let unregisterJob = null;
2878
- const unsubReady = scheduler.onRootReady(() => {
2879
- unregisterJob = registerOutside();
2880
- });
2881
- return () => {
2882
- unsubReady();
2883
- unregisterJob?.();
2884
- };
2079
+ return scheduler$1.register(
2080
+ (state, delta) => {
2081
+ const frameState = state;
2082
+ if (!frameState.renderer) return;
2083
+ callbackRef.current?.(frameState, delta);
2084
+ },
2085
+ { id, ...options }
2086
+ );
2885
2087
  }
2886
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2088
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2887
2089
  const isPaused = React__namespace.useSyncExternalStore(
2888
2090
  // Subscribe function
2889
2091
  React__namespace.useCallback(
2890
2092
  (onStoreChange) => {
2891
- return getScheduler().subscribeJobState(id, onStoreChange);
2093
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
2892
2094
  },
2893
2095
  [id]
2894
2096
  ),
2895
2097
  // getSnapshot function
2896
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2098
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
2897
2099
  // getServerSnapshot function (SSR)
2898
2100
  React__namespace.useCallback(() => false, [])
2899
2101
  );
2900
2102
  const controls = React__namespace.useMemo(() => {
2901
- const scheduler2 = getScheduler();
2103
+ const scheduler2 = scheduler.getScheduler();
2902
2104
  return {
2903
2105
  /** The job's unique ID */
2904
2106
  id,
@@ -2913,7 +2115,7 @@ function useFrame(callback, priorityOrOptions) {
2913
2115
  * @param timestamp Optional timestamp (defaults to performance.now())
2914
2116
  */
2915
2117
  step: (timestamp) => {
2916
- getScheduler().stepJob(id, timestamp);
2118
+ scheduler.getScheduler().stepJob(id, timestamp);
2917
2119
  },
2918
2120
  /**
2919
2121
  * Manually step ALL jobs in the scheduler.
@@ -2921,20 +2123,20 @@ function useFrame(callback, priorityOrOptions) {
2921
2123
  * @param timestamp Optional timestamp (defaults to performance.now())
2922
2124
  */
2923
2125
  stepAll: (timestamp) => {
2924
- getScheduler().step(timestamp);
2126
+ scheduler.getScheduler().step(timestamp);
2925
2127
  },
2926
2128
  /**
2927
2129
  * Pause this job (set enabled=false).
2928
2130
  * Job remains registered but won't run.
2929
2131
  */
2930
2132
  pause: () => {
2931
- getScheduler().pauseJob(id);
2133
+ scheduler.getScheduler().pauseJob(id);
2932
2134
  },
2933
2135
  /**
2934
2136
  * Resume this job (set enabled=true).
2935
2137
  */
2936
2138
  resume: () => {
2937
- getScheduler().resumeJob(id);
2139
+ scheduler.getScheduler().resumeJob(id);
2938
2140
  },
2939
2141
  /**
2940
2142
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2972,18 +2174,18 @@ function buildFromCache(input, textureCache) {
2972
2174
  function useTexture(input, optionsOrOnLoad) {
2973
2175
  const renderer = useThree((state) => state.internal.actualRenderer);
2974
2176
  const store = useStore();
2975
- const textureCache = useThree((state) => state.textures);
2976
2177
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2977
- const { onLoad, cache = false } = options;
2178
+ const { onLoad, cache = true } = options;
2978
2179
  const onLoadRef = React.useRef(onLoad);
2979
2180
  onLoadRef.current = onLoad;
2980
2181
  const onLoadCalledForRef = React.useRef(null);
2981
2182
  const urls = React.useMemo(() => getUrls(input), [input]);
2982
2183
  const cachedResult = React.useMemo(() => {
2983
2184
  if (!cache) return null;
2984
- if (!allUrlsCached(urls, textureCache)) return null;
2985
- return buildFromCache(input, textureCache);
2986
- }, [cache, urls, textureCache, input]);
2185
+ const textures = store.getState().textures;
2186
+ if (!allUrlsCached(urls, textures)) return null;
2187
+ return buildFromCache(input, textures);
2188
+ }, [cache, urls, input, store]);
2987
2189
  const loadedTextures = useLoader(
2988
2190
  webgpu.TextureLoader,
2989
2191
  IsObject(input) ? Object.values(input) : input
@@ -3027,8 +2229,6 @@ function useTexture(input, optionsOrOnLoad) {
3027
2229
  }, [input, loadedTextures, cachedResult]);
3028
2230
  React.useEffect(() => {
3029
2231
  if (!cache) return;
3030
- if (cachedResult) return;
3031
- const set = store.setState;
3032
2232
  const urlTextureMap = [];
3033
2233
  if (typeof input === "string") {
3034
2234
  urlTextureMap.push([input, mappedTextures]);
@@ -3042,18 +2242,32 @@ function useTexture(input, optionsOrOnLoad) {
3042
2242
  urlTextureMap.push([url, textureRecord[key]]);
3043
2243
  }
3044
2244
  }
3045
- set((state) => {
3046
- const newMap = new Map(state.textures);
3047
- let changed = false;
2245
+ store.setState((state) => {
2246
+ const refs = new Map(state._textureRefs);
2247
+ let textures = state.textures;
2248
+ let added = false;
3048
2249
  for (const [url, texture] of urlTextureMap) {
3049
- if (!newMap.has(url)) {
3050
- newMap.set(url, texture);
3051
- changed = true;
2250
+ if (!textures.has(url)) {
2251
+ if (!added) {
2252
+ textures = new Map(textures);
2253
+ added = true;
2254
+ }
2255
+ textures.set(url, texture);
3052
2256
  }
2257
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3053
2258
  }
3054
- return changed ? { textures: newMap } : state;
2259
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3055
2260
  });
3056
- }, [cache, input, mappedTextures, store, cachedResult]);
2261
+ return () => store.setState((state) => {
2262
+ const refs = new Map(state._textureRefs);
2263
+ for (const [url] of urlTextureMap) {
2264
+ const next = (refs.get(url) ?? 0) - 1;
2265
+ if (next <= 0) refs.delete(url);
2266
+ else refs.set(url, next);
2267
+ }
2268
+ return { _textureRefs: refs };
2269
+ });
2270
+ }, [cache, input, mappedTextures, store]);
3057
2271
  return mappedTextures;
3058
2272
  }
3059
2273
  useTexture.preload = (url) => useLoader.preload(webgpu.TextureLoader, url);
@@ -3069,96 +2283,63 @@ const Texture = ({
3069
2283
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3070
2284
  };
3071
2285
 
3072
- function getTextureValue(entry) {
3073
- if (entry instanceof webgpu.Texture) return entry;
3074
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof webgpu.Texture) {
3075
- return entry.value;
3076
- }
3077
- return null;
3078
- }
3079
- function useTextures() {
2286
+ function useTextures(selector) {
3080
2287
  const store = useStore();
3081
- return React.useMemo(() => {
3082
- const set = store.setState;
2288
+ const registry = React.useMemo(() => {
3083
2289
  const getState = store.getState;
3084
- const add = (key, value) => {
3085
- set((state) => {
3086
- const newMap = new Map(state.textures);
3087
- newMap.set(key, value);
3088
- return { textures: newMap };
3089
- });
3090
- };
3091
- const addMultiple = (items) => {
3092
- set((state) => {
3093
- const newMap = new Map(state.textures);
3094
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3095
- for (const [key, value] of entries) {
3096
- newMap.set(key, value);
3097
- }
3098
- return { textures: newMap };
3099
- });
3100
- };
3101
- const remove = (key) => {
3102
- set((state) => {
3103
- const newMap = new Map(state.textures);
3104
- newMap.delete(key);
3105
- return { textures: newMap };
3106
- });
3107
- };
3108
- const removeMultiple = (keys) => {
3109
- set((state) => {
3110
- const newMap = new Map(state.textures);
3111
- for (const key of keys) newMap.delete(key);
3112
- return { textures: newMap };
3113
- });
3114
- };
3115
- const dispose = (key) => {
3116
- const entry = getState().textures.get(key);
3117
- if (entry) {
3118
- const tex = getTextureValue(entry);
3119
- tex?.dispose();
3120
- }
3121
- remove(key);
3122
- };
3123
- const disposeMultiple = (keys) => {
3124
- const textures = getState().textures;
3125
- for (const key of keys) {
3126
- const entry = textures.get(key);
3127
- if (entry) {
3128
- const tex = getTextureValue(entry);
3129
- tex?.dispose();
3130
- }
3131
- }
3132
- removeMultiple(keys);
3133
- };
3134
- const disposeAll = () => {
3135
- const textures = getState().textures;
3136
- for (const entry of textures.values()) {
3137
- const tex = getTextureValue(entry);
3138
- tex?.dispose();
3139
- }
3140
- set({ textures: /* @__PURE__ */ new Map() });
3141
- };
2290
+ const setState = store.setState;
2291
+ const getOne = (key) => getState().textures.get(key);
3142
2292
  return {
3143
- // Getter for the textures Map (reactive via getState)
3144
- get textures() {
2293
+ get all() {
3145
2294
  return getState().textures;
3146
2295
  },
3147
- // Read
3148
- get: (key) => getState().textures.get(key),
2296
+ get(input) {
2297
+ if (typeof input === "string") return getOne(input);
2298
+ if (Array.isArray(input)) return input.map(getOne);
2299
+ const out = {};
2300
+ for (const name in input) out[name] = getOne(input[name]);
2301
+ return out;
2302
+ },
3149
2303
  has: (key) => getState().textures.has(key),
3150
- // Write
3151
- add,
3152
- addMultiple,
3153
- // Remove (cache only)
3154
- remove,
3155
- removeMultiple,
3156
- // Dispose (GPU + cache)
3157
- dispose,
3158
- disposeMultiple,
3159
- disposeAll
2304
+ add(keyOrRecord, texture) {
2305
+ setState((state) => {
2306
+ const textures = new Map(state.textures);
2307
+ if (typeof keyOrRecord === "string") {
2308
+ textures.set(keyOrRecord, texture);
2309
+ } else {
2310
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2311
+ }
2312
+ return { textures };
2313
+ });
2314
+ },
2315
+ dispose(key, options) {
2316
+ const state = getState();
2317
+ const refs = state._textureRefs.get(key) ?? 0;
2318
+ if (refs > 0 && !options?.force) {
2319
+ console.warn(
2320
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2321
+ );
2322
+ return false;
2323
+ }
2324
+ state.textures.get(key)?.dispose();
2325
+ setState((s) => {
2326
+ const textures = new Map(s.textures);
2327
+ textures.delete(key);
2328
+ const nextRefs = new Map(s._textureRefs);
2329
+ nextRefs.delete(key);
2330
+ return { textures, _textureRefs: nextRefs };
2331
+ });
2332
+ return true;
2333
+ },
2334
+ disposeAll() {
2335
+ for (const texture of getState().textures.values()) texture.dispose();
2336
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2337
+ }
3160
2338
  };
3161
2339
  }, [store]);
2340
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2341
+ const selected = useThree(subscribe);
2342
+ return selector ? selected : registry;
3162
2343
  }
3163
2344
 
3164
2345
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3215,7 +2396,7 @@ function addEffect(callback) {
3215
2396
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3216
2397
  });
3217
2398
  const id = `legacy_effect_${effectId++}`;
3218
- return getScheduler().registerGlobal("before", id, callback);
2399
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3219
2400
  }
3220
2401
  function addAfterEffect(callback) {
3221
2402
  notifyDepreciated({
@@ -3224,7 +2405,7 @@ function addAfterEffect(callback) {
3224
2405
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3225
2406
  });
3226
2407
  const id = `legacy_afterEffect_${effectId++}`;
3227
- return getScheduler().registerGlobal("after", id, callback);
2408
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3228
2409
  }
3229
2410
  function addTail(callback) {
3230
2411
  notifyDepreciated({
@@ -3232,13 +2413,13 @@ function addTail(callback) {
3232
2413
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3233
2414
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3234
2415
  });
3235
- return getScheduler().onIdle(callback);
2416
+ return scheduler.getScheduler().onIdle(callback);
3236
2417
  }
3237
2418
  function invalidate(state, frames = 1, stackFrames = false) {
3238
- getScheduler().invalidate(frames, stackFrames);
2419
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3239
2420
  }
3240
2421
  function advance(timestamp) {
3241
- getScheduler().step(timestamp);
2422
+ scheduler.getScheduler().step(timestamp);
3242
2423
  }
3243
2424
 
3244
2425
  const version = "10.0.0-alpha.2";
@@ -14680,6 +13861,7 @@ function swapInstances() {
14680
13861
  }
14681
13862
  }
14682
13863
  if (instance.isHidden) unhideInstance(instance);
13864
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14683
13865
  if (instance.object.__r3f) delete instance.object.__r3f;
14684
13866
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14685
13867
  }
@@ -14692,6 +13874,8 @@ function swapInstances() {
14692
13874
  instance.object.__r3f = instance;
14693
13875
  setFiberRef(fiber, instance.object);
14694
13876
  delete instance.appliedOnce;
13877
+ instance.eventCount = 0;
13878
+ instance.handlers = {};
14695
13879
  applyProps(instance.object, instance.props);
14696
13880
  if (instance.props.attach) {
14697
13881
  attach(parent, instance);
@@ -14996,6 +14180,7 @@ function createRoot(canvas) {
14996
14180
  const lastConfiguredProps = {};
14997
14181
  let configured = false;
14998
14182
  let pending = null;
14183
+ let rendererSetup = null;
14999
14184
  return {
15000
14185
  async configure(props = {}) {
15001
14186
  let resolve;
@@ -15011,7 +14196,6 @@ function createRoot(canvas) {
15011
14196
  events,
15012
14197
  onCreated: onCreatedCallback,
15013
14198
  shadows = false,
15014
- textureColorSpace = webgpu.SRGBColorSpace,
15015
14199
  orthographic = false,
15016
14200
  frameloop = "always",
15017
14201
  dpr = [1, 2],
@@ -15026,7 +14210,8 @@ function createRoot(canvas) {
15026
14210
  _sizeProps,
15027
14211
  forceEven
15028
14212
  } = props;
15029
- const state = store.getState();
14213
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
14214
+ let state = store.getState();
15030
14215
  const defaultGLProps = {
15031
14216
  canvas,
15032
14217
  powerPreference: "high-performance",
@@ -15054,50 +14239,68 @@ function createRoot(canvas) {
15054
14239
  "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
15055
14240
  );
15056
14241
  }
15057
- if (wantsGL && !state.internal.actualRenderer) {
15058
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
15059
- state.internal.actualRenderer = renderer;
15060
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
15061
- } else if (!wantsGL && primaryCanvas && !state.internal.actualRenderer) {
15062
- const primary = await waitForPrimary(primaryCanvas);
15063
- renderer = primary.renderer;
15064
- state.internal.actualRenderer = renderer;
15065
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15066
- primary.store.setState((prev) => ({
15067
- internal: { ...prev.internal, isMultiCanvas: true }
15068
- }));
15069
- state.set((prev) => ({
15070
- webGPUSupported: primary.store.getState().webGPUSupported,
15071
- renderer,
15072
- primaryStore: primary.store,
15073
- internal: {
15074
- ...prev.internal,
15075
- canvasTarget,
15076
- isMultiCanvas: true,
15077
- isSecondary: true,
15078
- targetId: primaryCanvas
15079
- }
15080
- }));
15081
- } else if (!wantsGL && !state.internal.actualRenderer) {
15082
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
15083
- if (!renderer.hasInitialized?.()) {
15084
- await renderer.init();
15085
- }
15086
- const backend = renderer.backend;
15087
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15088
- state.internal.actualRenderer = renderer;
15089
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15090
- if (canvasId && !state.internal.isSecondary) {
15091
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15092
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15093
- state.set((prev) => ({
15094
- internal: {
15095
- ...prev.internal,
15096
- canvasTarget,
15097
- unregisterPrimary
14242
+ if (!state.internal.actualRenderer) {
14243
+ if (!rendererSetup) {
14244
+ rendererSetup = (async () => {
14245
+ if (wantsGL) {
14246
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14247
+ state.internal.actualRenderer = renderer;
14248
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14249
+ } else if (!wantsGL && primaryCanvas) {
14250
+ const primary = await waitForPrimary(primaryCanvas);
14251
+ renderer = primary.renderer;
14252
+ state.internal.actualRenderer = renderer;
14253
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14254
+ primary.store.setState((prev) => ({
14255
+ internal: { ...prev.internal, isMultiCanvas: true }
14256
+ }));
14257
+ state.set((prev) => ({
14258
+ webGPUSupported: primary.store.getState().webGPUSupported,
14259
+ renderer,
14260
+ primaryStore: primary.store,
14261
+ internal: {
14262
+ ...prev.internal,
14263
+ canvasTarget,
14264
+ isMultiCanvas: true,
14265
+ isSecondary: true,
14266
+ targetId: primaryCanvas
14267
+ }
14268
+ }));
14269
+ } else if (!wantsGL) {
14270
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14271
+ if (!renderer.hasInitialized?.()) {
14272
+ const size2 = computeInitialSize(canvas, propsSize);
14273
+ if (size2.width > 0 && size2.height > 0) {
14274
+ const pixelRatio = calculateDpr(dpr);
14275
+ canvas.width = size2.width * pixelRatio;
14276
+ canvas.height = size2.height * pixelRatio;
14277
+ }
14278
+ await renderer.init();
14279
+ }
14280
+ const backend = renderer.backend;
14281
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14282
+ state.internal.actualRenderer = renderer;
14283
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14284
+ if (canvasId && !state.internal.isSecondary) {
14285
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14286
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14287
+ state.set((prev) => ({
14288
+ internal: {
14289
+ ...prev.internal,
14290
+ canvasTarget,
14291
+ unregisterPrimary
14292
+ }
14293
+ }));
14294
+ }
15098
14295
  }
15099
- }));
14296
+ })().catch((err) => {
14297
+ rendererSetup = null;
14298
+ throw err;
14299
+ });
15100
14300
  }
14301
+ await rendererSetup;
14302
+ state = store.getState();
14303
+ renderer = state.internal.actualRenderer;
15101
14304
  }
15102
14305
  let raycaster = state.raycaster;
15103
14306
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -15190,7 +14393,7 @@ function createRoot(canvas) {
15190
14393
  lastConfiguredProps.performance = performance;
15191
14394
  }
15192
14395
  if (!state.xr) {
15193
- const handleXRFrame = (timestamp, frame) => {
14396
+ const handleXRFrame = (timestamp, _frame) => {
15194
14397
  const state2 = store.getState();
15195
14398
  if (state2.frameloop === "never") return;
15196
14399
  advance(timestamp);
@@ -15226,15 +14429,22 @@ function createRoot(canvas) {
15226
14429
  const oldType = renderer.shadowMap.type;
15227
14430
  renderer.shadowMap.enabled = !!shadows;
15228
14431
  if (is.boo(shadows)) {
15229
- renderer.shadowMap.type = webgpu.PCFSoftShadowMap;
14432
+ renderer.shadowMap.type = webgpu.PCFShadowMap;
15230
14433
  } else if (is.str(shadows)) {
14434
+ if (shadows === "soft") {
14435
+ notifyDepreciated({
14436
+ heading: 'shadows="soft" is deprecated',
14437
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14438
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14439
+ });
14440
+ }
15231
14441
  const types = {
15232
14442
  basic: webgpu.BasicShadowMap,
15233
14443
  percentage: webgpu.PCFShadowMap,
15234
- soft: webgpu.PCFSoftShadowMap,
14444
+ soft: webgpu.PCFShadowMap,
15235
14445
  variance: webgpu.VSMShadowMap
15236
14446
  };
15237
- renderer.shadowMap.type = types[shadows] ?? webgpu.PCFSoftShadowMap;
14447
+ renderer.shadowMap.type = types[shadows] ?? webgpu.PCFShadowMap;
15238
14448
  } else if (is.obj(shadows)) {
15239
14449
  Object.assign(renderer.shadowMap, shadows);
15240
14450
  }
@@ -15250,24 +14460,35 @@ function createRoot(canvas) {
15250
14460
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15251
14461
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15252
14462
  }
14463
+ const r3fProps = ["textureColorSpace"];
14464
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14465
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15253
14466
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15254
- applyProps(renderer, glConfig);
14467
+ const glProps = {};
14468
+ for (const key in glConfig) {
14469
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14470
+ }
14471
+ applyProps(renderer, glProps);
15255
14472
  }
15256
14473
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15257
14474
  const currentRenderer = state.renderer;
15258
14475
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15259
- applyProps(currentRenderer, rendererConfig);
14476
+ const rendererProps = {};
14477
+ for (const key in rendererConfig) {
14478
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14479
+ }
14480
+ applyProps(currentRenderer, rendererProps);
15260
14481
  }
15261
14482
  }
15262
- const scheduler = getScheduler();
14483
+ const scheduler$1 = scheduler.getScheduler();
15263
14484
  const rootId = state.internal.rootId;
15264
14485
  if (!rootId) {
15265
- const newRootId = canvasId || scheduler.generateRootId();
15266
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14486
+ const newRootId = canvasId || scheduler$1.generateRootId();
14487
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15267
14488
  getState: () => store.getState(),
15268
14489
  onError: (err) => store.getState().setError(err)
15269
14490
  });
15270
- const unregisterCanvasTarget = scheduler.register(
14491
+ const unregisterCanvasTarget = scheduler$1.register(
15271
14492
  () => {
15272
14493
  const state2 = store.getState();
15273
14494
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15282,7 +14503,19 @@ function createRoot(canvas) {
15282
14503
  system: true
15283
14504
  }
15284
14505
  );
15285
- const unregisterFrustum = scheduler.register(
14506
+ const unregisterEventsFlush = scheduler$1.register(
14507
+ () => {
14508
+ const state2 = store.getState();
14509
+ state2.events.flush?.();
14510
+ },
14511
+ {
14512
+ id: `${newRootId}_events`,
14513
+ rootId: newRootId,
14514
+ phase: "input",
14515
+ system: true
14516
+ }
14517
+ );
14518
+ const unregisterFrustum = scheduler$1.register(
15286
14519
  () => {
15287
14520
  const state2 = store.getState();
15288
14521
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15292,11 +14525,11 @@ function createRoot(canvas) {
15292
14525
  {
15293
14526
  id: `${newRootId}_frustum`,
15294
14527
  rootId: newRootId,
15295
- phase: "preRender",
14528
+ before: "render",
15296
14529
  system: true
15297
14530
  }
15298
14531
  );
15299
- const unregisterVisibility = scheduler.register(
14532
+ const unregisterVisibility = scheduler$1.register(
15300
14533
  () => {
15301
14534
  const state2 = store.getState();
15302
14535
  checkVisibility(state2);
@@ -15304,19 +14537,19 @@ function createRoot(canvas) {
15304
14537
  {
15305
14538
  id: `${newRootId}_visibility`,
15306
14539
  rootId: newRootId,
15307
- phase: "preRender",
14540
+ before: "render",
15308
14541
  system: true,
15309
14542
  after: `${newRootId}_frustum`
15310
14543
  }
15311
14544
  );
15312
- const unregisterRender = scheduler.register(
14545
+ const unregisterRender = scheduler$1.register(
15313
14546
  () => {
15314
14547
  const state2 = store.getState();
15315
14548
  const renderer2 = state2.internal.actualRenderer;
15316
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14549
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15317
14550
  if (userHandlesRender || state2.internal.priority) return;
15318
14551
  try {
15319
- if (state2.postProcessing?.render) state2.postProcessing.render();
14552
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
15320
14553
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
15321
14554
  } catch (error) {
15322
14555
  state2.setError(error instanceof Error ? error : new Error(String(error)));
@@ -15341,15 +14574,16 @@ function createRoot(canvas) {
15341
14574
  unregisterRoot: () => {
15342
14575
  unregisterRoot();
15343
14576
  unregisterCanvasTarget();
14577
+ unregisterEventsFlush();
15344
14578
  unregisterFrustum();
15345
14579
  unregisterVisibility();
15346
14580
  unregisterRender();
15347
14581
  },
15348
- scheduler
14582
+ scheduler: scheduler$1
15349
14583
  }
15350
14584
  }));
15351
14585
  }
15352
- scheduler.frameloop = frameloop;
14586
+ scheduler$1.frameloop = frameloop;
15353
14587
  onCreated = onCreatedCallback;
15354
14588
  configured = true;
15355
14589
  resolve();
@@ -15479,6 +14713,7 @@ function PortalInner({ state = {}, children, container }) {
15479
14713
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
15480
14714
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15481
14715
  }
14716
+ const set = injectState.set;
15482
14717
  return {
15483
14718
  // The intersect consists of the previous root state
15484
14719
  ...rootState,
@@ -15497,7 +14732,7 @@ function PortalInner({ state = {}, children, container }) {
15497
14732
  size: resolvedSize,
15498
14733
  viewport: { ...rootState.viewport, ...viewport },
15499
14734
  // Layers are allowed to override events
15500
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14735
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15501
14736
  // Container for child attachment - the portalScene (injected or container itself)
15502
14737
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15503
14738
  };
@@ -15506,9 +14741,13 @@ function PortalInner({ state = {}, children, container }) {
15506
14741
  const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15507
14742
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15508
14743
  onMutate(previousRoot.getState());
15509
- previousRoot.subscribe(onMutate);
15510
14744
  return store;
15511
14745
  }, [previousRoot, container]);
14746
+ useIsomorphicLayoutEffect(() => {
14747
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14748
+ const unsubscribe = previousRoot.subscribe(onMutate);
14749
+ return unsubscribe;
14750
+ }, [previousRoot, usePortalStore]);
15512
14751
  return (
15513
14752
  // @ts-ignore, reconciler types are not maintained
15514
14753
  /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
@@ -15522,6 +14761,59 @@ function flushSync(fn) {
15522
14761
  return reconciler.flushSyncFromReconciler(fn);
15523
14762
  }
15524
14763
 
14764
+ function parseBackground(background) {
14765
+ if (!background) return null;
14766
+ if (typeof background === "object" && !background.isColor) {
14767
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14768
+ return {
14769
+ ...rest,
14770
+ preset,
14771
+ files: envMap || files,
14772
+ backgroundFiles: backgroundMap,
14773
+ background: true
14774
+ };
14775
+ }
14776
+ if (typeof background === "number") {
14777
+ return { color: background, background: true };
14778
+ }
14779
+ if (typeof background === "string") {
14780
+ if (background in presetsObj) {
14781
+ return { preset: background, background: true };
14782
+ }
14783
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14784
+ return { files: background, background: true };
14785
+ }
14786
+ return { color: background, background: true };
14787
+ }
14788
+ if (background.isColor) {
14789
+ return { color: background, background: true };
14790
+ }
14791
+ return null;
14792
+ }
14793
+
14794
+ function parseRendererConfig(rendererProp) {
14795
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14796
+ if (isRendererConfig) {
14797
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14798
+ return {
14799
+ primaryCanvas: pc,
14800
+ scheduler: sc,
14801
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14802
+ };
14803
+ }
14804
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14805
+ }
14806
+
14807
+ function clearHmrCaches(store) {
14808
+ store.setState((state) => ({
14809
+ nodes: {},
14810
+ uniforms: {},
14811
+ buffers: {},
14812
+ gpuStorage: {},
14813
+ _hmrVersion: state._hmrVersion + 1
14814
+ }));
14815
+ }
14816
+
15525
14817
  function CanvasImpl({
15526
14818
  ref,
15527
14819
  children,
@@ -15542,6 +14834,8 @@ function CanvasImpl({
15542
14834
  raycaster,
15543
14835
  camera,
15544
14836
  scene,
14837
+ autoUpdateFrustum,
14838
+ occlusion,
15545
14839
  onPointerMissed,
15546
14840
  onDragOverMissed,
15547
14841
  onDropMissed,
@@ -15553,39 +14847,10 @@ function CanvasImpl({
15553
14847
  forceEven,
15554
14848
  ...props
15555
14849
  }) {
15556
- 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 };
15557
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14850
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15558
14851
  React__namespace.useMemo(() => extend(THREE), []);
15559
14852
  const Bridge = useBridge();
15560
- const backgroundProps = React__namespace.useMemo(() => {
15561
- if (!background) return null;
15562
- if (typeof background === "object" && !background.isColor) {
15563
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15564
- return {
15565
- ...rest,
15566
- preset,
15567
- files: envMap || files,
15568
- backgroundFiles: backgroundMap,
15569
- background: true
15570
- };
15571
- }
15572
- if (typeof background === "number") {
15573
- return { color: background, background: true };
15574
- }
15575
- if (typeof background === "string") {
15576
- if (background in presetsObj) {
15577
- return { preset: background, background: true };
15578
- }
15579
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15580
- return { files: background, background: true };
15581
- }
15582
- return { color: background, background: true };
15583
- }
15584
- if (background.isColor) {
15585
- return { color: background, background: true };
15586
- }
15587
- return null;
15588
- }, [background]);
14853
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15589
14854
  const hasInitialSizeRef = React__namespace.useRef(false);
15590
14855
  const measureConfig = React__namespace.useMemo(() => {
15591
14856
  if (!hasInitialSizeRef.current) {
@@ -15627,6 +14892,7 @@ function CanvasImpl({
15627
14892
  const handleDropMissed = useMutableCallback(onDropMissed);
15628
14893
  const [block, setBlock] = React__namespace.useState(false);
15629
14894
  const [error, setError] = React__namespace.useState(false);
14895
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15630
14896
  if (block) throw block;
15631
14897
  if (error) throw error;
15632
14898
  const root = React__namespace.useRef(null);
@@ -15634,6 +14900,7 @@ function CanvasImpl({
15634
14900
  const unsubscribeErrorRef = React__namespace.useRef(null);
15635
14901
  useIsomorphicLayoutEffect(() => {
15636
14902
  effectActiveRef.current = true;
14903
+ if (fallbackVisible) return;
15637
14904
  const canvas = canvasRef.current;
15638
14905
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15639
14906
  if (!root.current) {
@@ -15654,7 +14921,7 @@ function CanvasImpl({
15654
14921
  }
15655
14922
  async function run() {
15656
14923
  if (!effectActiveRef.current || !root.current) return;
15657
- await root.current.configure({
14924
+ const configured = await root.current.configure({
15658
14925
  id,
15659
14926
  primaryCanvas,
15660
14927
  scheduler,
@@ -15669,6 +14936,8 @@ function CanvasImpl({
15669
14936
  performance,
15670
14937
  raycaster,
15671
14938
  camera,
14939
+ autoUpdateFrustum,
14940
+ occlusion,
15672
14941
  size: effectiveSize,
15673
14942
  // Store size props for reset functionality
15674
14943
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15693,8 +14962,20 @@ function CanvasImpl({
15693
14962
  }
15694
14963
  onCreated?.(state);
15695
14964
  }
15696
- });
15697
- if (!effectActiveRef.current || !root.current) return;
14965
+ }).then(
14966
+ () => true,
14967
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14968
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14969
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14970
+ (setupError) => {
14971
+ if (effectActiveRef.current) {
14972
+ if (fallback != null) setFallbackVisible(true);
14973
+ else setError(setupError);
14974
+ }
14975
+ return false;
14976
+ }
14977
+ );
14978
+ if (!configured || !effectActiveRef.current || !root.current) return;
15698
14979
  root.current.render(
15699
14980
  /* @__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: [
15700
14981
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15728,20 +15009,13 @@ function CanvasImpl({
15728
15009
  const handleHMR = () => {
15729
15010
  queueMicrotask(() => {
15730
15011
  const rootEntry = _roots.get(canvas);
15731
- if (rootEntry?.store) {
15732
- rootEntry.store.setState((state) => ({
15733
- nodes: {},
15734
- uniforms: {},
15735
- _hmrVersion: state._hmrVersion + 1
15736
- }));
15737
- }
15012
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15738
15013
  });
15739
15014
  };
15740
15015
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
15741
15016
  const hot = undefined;
15742
15017
  hot.on("vite:afterUpdate", handleHMR);
15743
- return () => hot.dispose?.(() => {
15744
- });
15018
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
15745
15019
  }
15746
15020
  if (typeof module !== "undefined" && module.hot) {
15747
15021
  const hot = module.hot;
@@ -15764,7 +15038,20 @@ function CanvasImpl({
15764
15038
  ...style
15765
15039
  },
15766
15040
  ...props,
15767
- 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 }) })
15041
+ children: fallbackVisible ? (
15042
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15043
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15044
+ fallback
15045
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15046
+ "canvas",
15047
+ {
15048
+ ref: canvasRef,
15049
+ id,
15050
+ className: "r3f-canvas",
15051
+ style: { display: "block", width: "100%", height: "100%" },
15052
+ children: fallback
15053
+ }
15054
+ ) })
15768
15055
  }
15769
15056
  );
15770
15057
  }
@@ -15774,6 +15061,8 @@ function Canvas(props) {
15774
15061
 
15775
15062
  extend(THREE);
15776
15063
 
15064
+ exports.Scheduler = scheduler.Scheduler;
15065
+ exports.getScheduler = scheduler.getScheduler;
15777
15066
  exports.Block = Block;
15778
15067
  exports.Canvas = Canvas;
15779
15068
  exports.Environment = Environment;
@@ -15789,7 +15078,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15789
15078
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15790
15079
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15791
15080
  exports.RESERVED_PROPS = RESERVED_PROPS;
15792
- exports.Scheduler = Scheduler;
15793
15081
  exports.Texture = Texture;
15794
15082
  exports._roots = _roots;
15795
15083
  exports.act = act;
@@ -15819,7 +15107,6 @@ exports.getInstanceProps = getInstanceProps;
15819
15107
  exports.getPrimary = getPrimary;
15820
15108
  exports.getPrimaryIds = getPrimaryIds;
15821
15109
  exports.getRootState = getRootState;
15822
- exports.getScheduler = getScheduler;
15823
15110
  exports.getUuidPrefix = getUuidPrefix;
15824
15111
  exports.hasConstructor = hasConstructor;
15825
15112
  exports.hasPrimary = hasPrimary;