@react-three/fiber 10.0.0-canary.2b511a5 → 10.0.0-canary.2c50459

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as webgpu from 'three/webgpu';
2
- import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFSoftShadowMap, VSMShadowMap, PCFShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
2
+ import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
3
3
  import { WebGLRenderTarget, WebGLRenderer } from 'three';
4
4
  import { Inspector } from 'three/addons/inspector/Inspector.js';
5
5
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
@@ -15,6 +15,8 @@ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
15
15
  import { GainMapLoader } from '@monogrid/gainmap-js';
16
16
  import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
17
17
  import { createWithEqualityFn } from 'zustand/traditional';
18
+ import { getScheduler } from '@pmndrs/scheduler';
19
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
18
20
  import { suspend, preload, clear } from 'suspend-react';
19
21
 
20
22
  function _mergeNamespaces(n, m) {
@@ -139,7 +141,7 @@ function useEnvironment({
139
141
  useLoader$1.clear(loader, multiFile ? [files] : files);
140
142
  }
141
143
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
142
- }, [files, renderer.domElement]);
144
+ }, [extension, files, loader, multiFile, renderer.domElement]);
143
145
  const loaderResult = useLoader$1(
144
146
  loader,
145
147
  multiFile ? [files] : files,
@@ -339,7 +341,22 @@ function EnvironmentPortal({
339
341
  environmentIntensity,
340
342
  environmentRotation
341
343
  });
342
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
344
+ }, [
345
+ children,
346
+ virtualScene,
347
+ fbo.texture,
348
+ scene,
349
+ defaultScene,
350
+ background,
351
+ frames,
352
+ gl,
353
+ blur,
354
+ backgroundBlurriness,
355
+ backgroundIntensity,
356
+ backgroundRotation,
357
+ environmentIntensity,
358
+ environmentRotation
359
+ ]);
343
360
  let count = 1;
344
361
  useFrame$1(() => {
345
362
  if (frames === Infinity || count < frames) {
@@ -410,9 +427,9 @@ function Environment(props) {
410
427
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
411
428
  }
412
429
 
413
- var __defProp$2 = Object.defineProperty;
414
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
415
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
430
+ var __defProp = Object.defineProperty;
431
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
432
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
416
433
  const act = React["act"];
417
434
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
418
435
  function useMutableCallback(fn) {
@@ -444,7 +461,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
444
461
  return _a = class extends React.Component {
445
462
  constructor() {
446
463
  super(...arguments);
447
- __publicField$2(this, "state", { error: false });
464
+ __publicField(this, "state", { error: false });
448
465
  }
449
466
  componentDidCatch(err) {
450
467
  this.props.set(err);
@@ -452,7 +469,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
452
469
  render() {
453
470
  return this.state.error ? null : this.props.children;
454
471
  }
455
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
472
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
456
473
  })();
457
474
 
458
475
  const is = {
@@ -975,6 +992,9 @@ function applyProps(object, props) {
975
992
  else target.set(value);
976
993
  } else {
977
994
  root[key] = value;
995
+ if (key.endsWith("Node") && root.isMaterial) {
996
+ root.needsUpdate = true;
997
+ }
978
998
  if (rootState && rootState.renderer?.outputColorSpace === SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
979
999
  root[key].format === RGBAFormat && root[key].type === UnsignedByteType) {
980
1000
  root[key].colorSpace = rootState.textureColorSpace;
@@ -1008,38 +1028,60 @@ function applyProps(object, props) {
1008
1028
  return object;
1009
1029
  }
1010
1030
 
1031
+ const DEFAULT_POINTER_ID = 0;
1032
+ const XR_POINTER_ID_START = 1e3;
1033
+ function getPointerState(internal, pointerId) {
1034
+ let state = internal.pointerMap.get(pointerId);
1035
+ if (!state) {
1036
+ state = {
1037
+ hovered: /* @__PURE__ */ new Map(),
1038
+ captured: /* @__PURE__ */ new Map(),
1039
+ initialClick: [0, 0],
1040
+ initialHits: []
1041
+ };
1042
+ internal.pointerMap.set(pointerId, state);
1043
+ }
1044
+ return state;
1045
+ }
1046
+ function getPointerId(event) {
1047
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1048
+ }
1011
1049
  function makeId(event) {
1012
1050
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
1013
1051
  }
1014
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
1015
- const captureData = captures.get(obj);
1052
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1053
+ const pointerState = internal.pointerMap.get(pointerId);
1054
+ if (!pointerState) return;
1055
+ const captureData = pointerState.captured.get(obj);
1016
1056
  if (captureData) {
1017
- captures.delete(obj);
1018
- if (captures.size === 0) {
1019
- capturedMap.delete(pointerId);
1020
- captureData.target.releasePointerCapture(pointerId);
1021
- }
1057
+ pointerState.captured.delete(obj);
1058
+ captureData.target.releasePointerCapture(pointerId);
1022
1059
  }
1023
1060
  }
1024
1061
  function removeInteractivity(store, object) {
1025
1062
  const { internal } = store.getState();
1026
1063
  internal.interaction = internal.interaction.filter((o) => o !== object);
1027
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
1028
- internal.hovered.forEach((value, key) => {
1029
- if (value.eventObject === object || value.object === object) {
1030
- internal.hovered.delete(key);
1064
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1065
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1066
+ pointerState.hovered.forEach((value, key) => {
1067
+ if (value.eventObject === object || value.object === object) {
1068
+ pointerState.hovered.delete(key);
1069
+ }
1070
+ });
1071
+ if (pointerState.captured.has(object)) {
1072
+ releaseInternalPointerCapture(internal, object, pointerId);
1031
1073
  }
1032
- });
1033
- internal.capturedMap.forEach((captures, pointerId) => {
1034
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
1035
- });
1074
+ }
1036
1075
  unregisterVisibility(store, object);
1037
1076
  }
1038
1077
  function createEvents(store) {
1039
- function calculateDistance(event) {
1078
+ function calculateDistance(event, pointerId) {
1040
1079
  const { internal } = store.getState();
1041
- const dx = event.offsetX - internal.initialClick[0];
1042
- const dy = event.offsetY - internal.initialClick[1];
1080
+ const pointerState = internal.pointerMap.get(pointerId);
1081
+ if (!pointerState) return 0;
1082
+ const [initialX, initialY] = pointerState.initialClick;
1083
+ const dx = event.offsetX - initialX;
1084
+ const dy = event.offsetY - initialY;
1043
1085
  return Math.round(Math.sqrt(dx * dx + dy * dy));
1044
1086
  }
1045
1087
  function filterPointerEvents(objects) {
@@ -1075,6 +1117,15 @@ function createEvents(store) {
1075
1117
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
1076
1118
  }
1077
1119
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1120
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1121
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1122
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1123
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1124
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1125
+ if (aInteractivePriority !== bInteractivePriority) {
1126
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1127
+ }
1128
+ }
1078
1129
  const aState = getRootState(a.object);
1079
1130
  const bState = getRootState(b.object);
1080
1131
  const aPriority = aState?.events?.priority ?? 1;
@@ -1096,9 +1147,13 @@ function createEvents(store) {
1096
1147
  eventObject = eventObject.parent;
1097
1148
  }
1098
1149
  }
1099
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
1100
- for (const captureData of state.internal.capturedMap.get(event.pointerId).values()) {
1101
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1150
+ if ("pointerId" in event) {
1151
+ const pointerId = event.pointerId;
1152
+ const pointerState = state.internal.pointerMap.get(pointerId);
1153
+ if (pointerState?.captured.size) {
1154
+ for (const captureData of pointerState.captured.values()) {
1155
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1156
+ }
1102
1157
  }
1103
1158
  }
1104
1159
  return intersections;
@@ -1111,27 +1166,25 @@ function createEvents(store) {
1111
1166
  if (state) {
1112
1167
  const { raycaster, pointer, camera, internal } = state;
1113
1168
  const unprojectedPoint = new Vector3(pointer.x, pointer.y, 0).unproject(camera);
1114
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1169
+ const hasPointerCapture = (id) => {
1170
+ const pointerState = internal.pointerMap.get(id);
1171
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1172
+ };
1115
1173
  const setPointerCapture = (id) => {
1116
1174
  const captureData = { intersection: hit, target: event.target };
1117
- if (internal.capturedMap.has(id)) {
1118
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
1119
- } else {
1120
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
1121
- }
1175
+ const pointerState = getPointerState(internal, id);
1176
+ pointerState.captured.set(hit.eventObject, captureData);
1122
1177
  event.target.setPointerCapture(id);
1123
1178
  };
1124
1179
  const releasePointerCapture = (id) => {
1125
- const captures = internal.capturedMap.get(id);
1126
- if (captures) {
1127
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
1128
- }
1180
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
1129
1181
  };
1130
1182
  const extractEventProps = {};
1131
1183
  for (const prop in event) {
1132
1184
  const property = event[prop];
1133
1185
  if (typeof property !== "function") extractEventProps[prop] = property;
1134
1186
  }
1187
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1135
1188
  const raycastEvent = {
1136
1189
  ...hit,
1137
1190
  ...extractEventProps,
@@ -1142,18 +1195,19 @@ function createEvents(store) {
1142
1195
  unprojectedPoint,
1143
1196
  ray: raycaster.ray,
1144
1197
  camera,
1198
+ pointerId: eventPointerId,
1145
1199
  // Hijack stopPropagation, which just sets a flag
1146
1200
  stopPropagation() {
1147
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1201
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
1148
1202
  if (
1149
1203
  // ...if this pointer hasn't been captured
1150
- !capturesForPointer || // ... or if the hit object is capturing the pointer
1151
- capturesForPointer.has(hit.eventObject)
1204
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1205
+ pointerState.captured.has(hit.eventObject)
1152
1206
  ) {
1153
1207
  raycastEvent.stopped = localState.stopped = true;
1154
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1208
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1155
1209
  const higher = intersections.slice(0, intersections.indexOf(hit));
1156
- cancelPointer([...higher, hit]);
1210
+ cancelPointer([...higher, hit], eventPointerId);
1157
1211
  }
1158
1212
  }
1159
1213
  },
@@ -1169,15 +1223,18 @@ function createEvents(store) {
1169
1223
  }
1170
1224
  return intersections;
1171
1225
  }
1172
- function cancelPointer(intersections) {
1226
+ function cancelPointer(intersections, pointerId) {
1173
1227
  const { internal } = store.getState();
1174
- for (const hoveredObj of internal.hovered.values()) {
1228
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1229
+ const pointerState = internal.pointerMap.get(pid);
1230
+ if (!pointerState) return;
1231
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
1175
1232
  if (!intersections.length || !intersections.find(
1176
1233
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
1177
1234
  )) {
1178
1235
  const eventObject = hoveredObj.eventObject;
1179
1236
  const instance = eventObject.__r3f;
1180
- internal.hovered.delete(makeId(hoveredObj));
1237
+ pointerState.hovered.delete(hoveredId);
1181
1238
  if (instance?.eventCount) {
1182
1239
  const handlers = instance.handlers;
1183
1240
  const data = { ...hoveredObj, intersections };
@@ -1206,41 +1263,118 @@ function createEvents(store) {
1206
1263
  instance?.handlers.onDropMissed?.(event);
1207
1264
  }
1208
1265
  }
1266
+ function cleanupPointer(pointerId) {
1267
+ const { internal } = store.getState();
1268
+ const pointerState = internal.pointerMap.get(pointerId);
1269
+ if (pointerState) {
1270
+ for (const [, hoveredObj] of pointerState.hovered) {
1271
+ const eventObject = hoveredObj.eventObject;
1272
+ const instance = eventObject.__r3f;
1273
+ if (instance?.eventCount) {
1274
+ const handlers = instance.handlers;
1275
+ const data = { ...hoveredObj, intersections: [] };
1276
+ handlers.onPointerOut?.(data);
1277
+ handlers.onPointerLeave?.(data);
1278
+ }
1279
+ }
1280
+ internal.pointerMap.delete(pointerId);
1281
+ }
1282
+ internal.pointerDirty.delete(pointerId);
1283
+ }
1284
+ function processDeferredPointer(event, pointerId) {
1285
+ const state = store.getState();
1286
+ const { internal } = state;
1287
+ if (!state.events.enabled) return;
1288
+ const filter = filterPointerEvents;
1289
+ const hits = intersect(event, filter);
1290
+ cancelPointer(hits, pointerId);
1291
+ function onIntersect(data) {
1292
+ const eventObject = data.eventObject;
1293
+ const instance = eventObject.__r3f;
1294
+ if (!instance?.eventCount) return;
1295
+ const handlers = instance.handlers;
1296
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1297
+ const id = makeId(data);
1298
+ const pointerState = getPointerState(internal, pointerId);
1299
+ const hoveredItem = pointerState.hovered.get(id);
1300
+ if (!hoveredItem) {
1301
+ pointerState.hovered.set(id, data);
1302
+ handlers.onPointerOver?.(data);
1303
+ handlers.onPointerEnter?.(data);
1304
+ } else if (hoveredItem.stopped) {
1305
+ data.stopPropagation();
1306
+ }
1307
+ }
1308
+ handlers.onPointerMove?.(data);
1309
+ }
1310
+ handleIntersects(hits, event, 0, onIntersect);
1311
+ }
1209
1312
  function handlePointer(name) {
1210
1313
  switch (name) {
1211
1314
  case "onPointerLeave":
1212
- case "onPointerCancel":
1213
1315
  case "onDragLeave":
1214
1316
  return () => cancelPointer([]);
1317
+ // Global cancel of these events
1318
+ case "onPointerCancel":
1319
+ return (event) => {
1320
+ const pointerId = getPointerId(event);
1321
+ cleanupPointer(pointerId);
1322
+ };
1215
1323
  case "onLostPointerCapture":
1216
1324
  return (event) => {
1217
1325
  const { internal } = store.getState();
1218
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1326
+ const pointerId = getPointerId(event);
1327
+ const pointerState = internal.pointerMap.get(pointerId);
1328
+ if (pointerState?.captured.size) {
1219
1329
  requestAnimationFrame(() => {
1220
- if (internal.capturedMap.has(event.pointerId)) {
1221
- internal.capturedMap.delete(event.pointerId);
1222
- cancelPointer([]);
1330
+ const pointerState2 = internal.pointerMap.get(pointerId);
1331
+ if (pointerState2?.captured.size) {
1332
+ pointerState2.captured.clear();
1223
1333
  }
1334
+ cancelPointer([], pointerId);
1224
1335
  });
1225
1336
  }
1226
1337
  };
1227
1338
  }
1228
1339
  return function handleEvent(event) {
1229
1340
  const state = store.getState();
1230
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1341
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1342
+ const pointerId = getPointerId(event);
1231
1343
  internal.lastEvent.current = event;
1232
- if (!state.events.enabled) return;
1344
+ if (!events.enabled) return;
1233
1345
  const isPointerMove = name === "onPointerMove";
1234
1346
  const isDragOver = name === "onDragOver";
1235
1347
  const isDrop = name === "onDrop";
1236
1348
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1349
+ const isPointerDown = name === "onPointerDown";
1350
+ const isPointerUp = name === "onPointerUp";
1351
+ const isWheel = name === "onWheel";
1352
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1353
+ if (isPointerMove && canDeferRaycasts) {
1354
+ events.compute?.(event, state);
1355
+ internal.pointerDirty.set(pointerId, event);
1356
+ return;
1357
+ }
1358
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1359
+ events.compute?.(event, state);
1360
+ internal.pointerDirty.set(pointerId, event);
1361
+ return;
1362
+ }
1363
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1364
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1365
+ internal.pointerDirty.delete(pointerId);
1366
+ processDeferredPointer(deferredEvent, pointerId);
1367
+ }
1237
1368
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
1238
1369
  const hits = intersect(event, filter);
1239
- const delta = isClickEvent ? calculateDistance(event) : 0;
1240
- if (name === "onPointerDown") {
1241
- internal.initialClick = [event.offsetX, event.offsetY];
1242
- internal.initialHits = hits.map((hit) => hit.eventObject);
1243
- }
1370
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1371
+ if (isPointerDown) {
1372
+ const pointerState2 = getPointerState(internal, pointerId);
1373
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1374
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1375
+ }
1376
+ const pointerState = internal.pointerMap.get(pointerId);
1377
+ const initialHits = pointerState?.initialHits ?? [];
1244
1378
  if (isClickEvent && !hits.length) {
1245
1379
  if (delta <= 2) {
1246
1380
  pointerMissed(event, internal.interaction);
@@ -1255,7 +1389,9 @@ function createEvents(store) {
1255
1389
  dropMissed(event, internal.interaction);
1256
1390
  if (onDropMissed) onDropMissed(event);
1257
1391
  }
1258
- if (isPointerMove || isDragOver) cancelPointer(hits);
1392
+ if (isPointerMove || isDragOver) {
1393
+ cancelPointer(hits, pointerId);
1394
+ }
1259
1395
  function onIntersect(data) {
1260
1396
  const eventObject = data.eventObject;
1261
1397
  const instance = eventObject.__r3f;
@@ -1264,9 +1400,10 @@ function createEvents(store) {
1264
1400
  if (isPointerMove) {
1265
1401
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1266
1402
  const id = makeId(data);
1267
- const hoveredItem = internal.hovered.get(id);
1403
+ const pointerState2 = getPointerState(internal, pointerId);
1404
+ const hoveredItem = pointerState2.hovered.get(id);
1268
1405
  if (!hoveredItem) {
1269
- internal.hovered.set(id, data);
1406
+ pointerState2.hovered.set(id, data);
1270
1407
  handlers.onPointerOver?.(data);
1271
1408
  handlers.onPointerEnter?.(data);
1272
1409
  } else if (hoveredItem.stopped) {
@@ -1276,9 +1413,10 @@ function createEvents(store) {
1276
1413
  handlers.onPointerMove?.(data);
1277
1414
  } else if (isDragOver) {
1278
1415
  const id = makeId(data);
1279
- const hoveredItem = internal.hovered.get(id);
1416
+ const pointerState2 = getPointerState(internal, pointerId);
1417
+ const hoveredItem = pointerState2.hovered.get(id);
1280
1418
  if (!hoveredItem) {
1281
- internal.hovered.set(id, data);
1419
+ pointerState2.hovered.set(id, data);
1282
1420
  handlers.onDragOverEnter?.(data);
1283
1421
  } else if (hoveredItem.stopped) {
1284
1422
  data.stopPropagation();
@@ -1289,18 +1427,18 @@ function createEvents(store) {
1289
1427
  } else {
1290
1428
  const handler = handlers[name];
1291
1429
  if (handler) {
1292
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1430
+ if (!isClickEvent || initialHits.includes(eventObject)) {
1293
1431
  pointerMissed(
1294
1432
  event,
1295
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1433
+ internal.interaction.filter((object) => !initialHits.includes(object))
1296
1434
  );
1297
1435
  handler(data);
1298
1436
  }
1299
1437
  } else {
1300
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1438
+ if (isClickEvent && initialHits.includes(eventObject)) {
1301
1439
  pointerMissed(
1302
1440
  event,
1303
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1441
+ internal.interaction.filter((object) => !initialHits.includes(object))
1304
1442
  );
1305
1443
  }
1306
1444
  }
@@ -1309,7 +1447,15 @@ function createEvents(store) {
1309
1447
  handleIntersects(hits, event, delta, onIntersect);
1310
1448
  };
1311
1449
  }
1312
- return { handlePointer };
1450
+ function flushDeferredPointers() {
1451
+ const { internal, events } = store.getState();
1452
+ if (!events.frameTimedRaycasts) return;
1453
+ for (const [pointerId, event] of internal.pointerDirty) {
1454
+ processDeferredPointer(event, pointerId);
1455
+ }
1456
+ internal.pointerDirty.clear();
1457
+ }
1458
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
1313
1459
  }
1314
1460
  const DOM_EVENTS = {
1315
1461
  onClick: ["click", false],
@@ -1328,10 +1474,15 @@ const DOM_EVENTS = {
1328
1474
  onLostPointerCapture: ["lostpointercapture", true]
1329
1475
  };
1330
1476
  function createPointerEvents(store) {
1331
- const { handlePointer } = createEvents(store);
1477
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1478
+ let nextXRPointerId = XR_POINTER_ID_START;
1479
+ const xrPointers = /* @__PURE__ */ new Map();
1332
1480
  return {
1333
1481
  priority: 1,
1334
1482
  enabled: true,
1483
+ frameTimedRaycasts: true,
1484
+ alwaysFireOnScroll: true,
1485
+ updateOnFrame: false,
1335
1486
  compute(event, state) {
1336
1487
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
1337
1488
  state.raycaster.setFromCamera(state.pointer, state.camera);
@@ -1341,11 +1492,33 @@ function createPointerEvents(store) {
1341
1492
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
1342
1493
  {}
1343
1494
  ),
1344
- update: () => {
1495
+ update: (pointerId) => {
1345
1496
  const { events, internal } = store.getState();
1346
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1497
+ if (!events.handlers) return;
1498
+ if (pointerId !== void 0) {
1499
+ const event = internal.pointerDirty.get(pointerId);
1500
+ if (event) {
1501
+ internal.pointerDirty.delete(pointerId);
1502
+ processDeferredPointer(event, pointerId);
1503
+ } else if (internal.lastEvent?.current) {
1504
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1505
+ }
1506
+ } else {
1507
+ flushDeferredPointers();
1508
+ if (internal.lastEvent?.current) {
1509
+ events.handlers.onPointerMove(internal.lastEvent.current);
1510
+ }
1511
+ }
1512
+ },
1513
+ flush: () => {
1514
+ const { events, internal } = store.getState();
1515
+ flushDeferredPointers();
1516
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1517
+ events.handlers.onPointerMove(internal.lastEvent.current);
1518
+ }
1347
1519
  },
1348
1520
  connect: (target) => {
1521
+ if (!target) return;
1349
1522
  const { set, events } = store.getState();
1350
1523
  events.disconnect?.();
1351
1524
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1369,6 +1542,32 @@ function createPointerEvents(store) {
1369
1542
  }
1370
1543
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1371
1544
  }
1545
+ },
1546
+ registerPointer: (config) => {
1547
+ const pointerId = nextXRPointerId++;
1548
+ xrPointers.set(pointerId, config);
1549
+ const { internal } = store.getState();
1550
+ getPointerState(internal, pointerId);
1551
+ return pointerId;
1552
+ },
1553
+ unregisterPointer: (pointerId) => {
1554
+ xrPointers.delete(pointerId);
1555
+ const { internal } = store.getState();
1556
+ const pointerState = internal.pointerMap.get(pointerId);
1557
+ if (pointerState) {
1558
+ for (const [, hoveredObj] of pointerState.hovered) {
1559
+ const eventObject = hoveredObj.eventObject;
1560
+ const instance = eventObject.__r3f;
1561
+ if (instance?.eventCount) {
1562
+ const handlers = instance.handlers;
1563
+ const data = { ...hoveredObj, intersections: [] };
1564
+ handlers.onPointerOut?.(data);
1565
+ handlers.onPointerLeave?.(data);
1566
+ }
1567
+ }
1568
+ internal.pointerMap.delete(pointerId);
1569
+ }
1570
+ internal.pointerDirty.delete(pointerId);
1372
1571
  }
1373
1572
  };
1374
1573
  }
@@ -1430,1038 +1629,6 @@ function notifyAlpha({ message, link }) {
1430
1629
  }
1431
1630
  }
1432
1631
 
1433
- var __defProp$1 = Object.defineProperty;
1434
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1435
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1436
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1437
- class PhaseGraph {
1438
- constructor() {
1439
- /** Ordered list of phase nodes */
1440
- __publicField$1(this, "phases", []);
1441
- /** Quick lookup by name */
1442
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1443
- /** Cached ordered names (invalidated on changes) */
1444
- __publicField$1(this, "orderedNamesCache", null);
1445
- this.initializeDefaultPhases();
1446
- }
1447
- //* Initialization --------------------------------
1448
- initializeDefaultPhases() {
1449
- for (const name of DEFAULT_PHASES) {
1450
- const node = { name, isAutoGenerated: false };
1451
- this.phases.push(node);
1452
- this.phaseMap.set(name, node);
1453
- }
1454
- this.invalidateCache();
1455
- }
1456
- //* Public API --------------------------------
1457
- /**
1458
- * Add a named phase to the graph
1459
- * @param name - Phase name (must be unique)
1460
- * @param options - Position options (before or after another phase)
1461
- */
1462
- addPhase(name, options = {}) {
1463
- if (this.phaseMap.has(name)) {
1464
- console.warn(`[useFrame] Phase "${name}" already exists`);
1465
- return;
1466
- }
1467
- const { before, after } = options;
1468
- const node = { name, isAutoGenerated: false };
1469
- let insertIndex = this.phases.length;
1470
- const targetIndex = this.getPhaseIndex(before ?? after);
1471
- if (targetIndex !== -1) {
1472
- insertIndex = before ? targetIndex : targetIndex + 1;
1473
- } else {
1474
- const constraintType = before ? "before" : "after";
1475
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1476
- }
1477
- this.phases.splice(insertIndex, 0, node);
1478
- this.phaseMap.set(name, node);
1479
- this.invalidateCache();
1480
- }
1481
- /**
1482
- * Get ordered list of phase names
1483
- */
1484
- getOrderedPhases() {
1485
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1486
- return this.orderedNamesCache;
1487
- }
1488
- /**
1489
- * Check if a phase exists
1490
- */
1491
- hasPhase(name) {
1492
- return this.phaseMap.has(name);
1493
- }
1494
- /**
1495
- * Get the index of a phase (-1 if not found)
1496
- */
1497
- getPhaseIndex(name) {
1498
- if (!name) return -1;
1499
- return this.phases.findIndex((p) => p.name === name);
1500
- }
1501
- /**
1502
- * Ensure a phase exists, creating an auto-generated one if needed.
1503
- * Used for resolving before/after constraints.
1504
- *
1505
- * @param name - The phase name to ensure exists
1506
- * @returns The phase name (may be auto-generated like 'before:render')
1507
- */
1508
- ensurePhase(name) {
1509
- if (this.phaseMap.has(name)) return name;
1510
- const node = { name, isAutoGenerated: true };
1511
- this.phases.push(node);
1512
- this.phaseMap.set(name, node);
1513
- this.invalidateCache();
1514
- return name;
1515
- }
1516
- /**
1517
- * Resolve where a job with before/after constraints should go.
1518
- * Creates auto-generated phases if needed.
1519
- *
1520
- * @param before - Phase(s) to run before
1521
- * @param after - Phase(s) to run after
1522
- * @returns The resolved phase name
1523
- */
1524
- resolveConstraintPhase(before, after) {
1525
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1526
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1527
- if (beforeArr.length > 0) {
1528
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1529
- }
1530
- if (afterArr.length > 0) {
1531
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1532
- }
1533
- return "update";
1534
- }
1535
- /**
1536
- * Ensure an auto-generated phase exists relative to a target phase.
1537
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1538
- *
1539
- * @param target - The target phase name to position relative to
1540
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1541
- * @param offset - Insertion offset (0 for before, 1 for after)
1542
- * @returns The auto-generated phase name
1543
- */
1544
- ensureAutoPhase(target, prefix, offset) {
1545
- const autoName = `${prefix}:${target}`;
1546
- if (this.phaseMap.has(autoName)) return autoName;
1547
- const node = { name: autoName, isAutoGenerated: true };
1548
- const targetIndex = this.getPhaseIndex(target);
1549
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1550
- else this.phases.push(node);
1551
- this.phaseMap.set(autoName, node);
1552
- this.invalidateCache();
1553
- return autoName;
1554
- }
1555
- // Internal --------------------------------
1556
- invalidateCache() {
1557
- this.orderedNamesCache = null;
1558
- }
1559
- }
1560
-
1561
- function rebuildSortedJobs(jobs, phaseGraph) {
1562
- const orderedPhases = phaseGraph.getOrderedPhases();
1563
- const buckets = /* @__PURE__ */ new Map();
1564
- for (const phase of orderedPhases) {
1565
- buckets.set(phase, []);
1566
- }
1567
- for (const job of jobs.values()) {
1568
- if (!job.enabled) continue;
1569
- let bucket = buckets.get(job.phase);
1570
- if (!bucket) {
1571
- bucket = [];
1572
- buckets.set(job.phase, bucket);
1573
- }
1574
- bucket.push(job);
1575
- }
1576
- const sortedBuckets = [];
1577
- for (const phase of orderedPhases) {
1578
- const bucket = buckets.get(phase);
1579
- if (!bucket || bucket.length === 0) continue;
1580
- bucket.sort((a, b) => {
1581
- if (a.priority !== b.priority) return b.priority - a.priority;
1582
- return a.index - b.index;
1583
- });
1584
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1585
- }
1586
- for (const [phase, bucket] of buckets) {
1587
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1588
- bucket.sort((a, b) => {
1589
- if (a.priority !== b.priority) return b.priority - a.priority;
1590
- return a.index - b.index;
1591
- });
1592
- sortedBuckets.push(bucket);
1593
- }
1594
- }
1595
- return sortedBuckets.flat();
1596
- }
1597
- function hasCrossJobConstraints(bucket) {
1598
- const jobIds = new Set(bucket.map((j) => j.id));
1599
- for (const job of bucket) {
1600
- for (const ref of job.before) {
1601
- if (jobIds.has(ref)) return true;
1602
- }
1603
- for (const ref of job.after) {
1604
- if (jobIds.has(ref)) return true;
1605
- }
1606
- }
1607
- return false;
1608
- }
1609
- function topologicalSort(jobs) {
1610
- const n = jobs.length;
1611
- if (n <= 1) return jobs;
1612
- const jobMap = /* @__PURE__ */ new Map();
1613
- const inDegree = /* @__PURE__ */ new Map();
1614
- const adjacency = /* @__PURE__ */ new Map();
1615
- for (const job of jobs) {
1616
- jobMap.set(job.id, job);
1617
- inDegree.set(job.id, 0);
1618
- adjacency.set(job.id, []);
1619
- }
1620
- for (const job of jobs) {
1621
- for (const ref of job.before) {
1622
- if (jobMap.has(ref)) {
1623
- adjacency.get(job.id).push(ref);
1624
- inDegree.set(ref, inDegree.get(ref) + 1);
1625
- }
1626
- }
1627
- for (const ref of job.after) {
1628
- if (jobMap.has(ref)) {
1629
- adjacency.get(ref).push(job.id);
1630
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1631
- }
1632
- }
1633
- }
1634
- const queue = [];
1635
- for (const job of jobs) {
1636
- if (inDegree.get(job.id) === 0) {
1637
- queue.push(job);
1638
- }
1639
- }
1640
- queue.sort((a, b) => {
1641
- if (a.priority !== b.priority) return b.priority - a.priority;
1642
- return a.index - b.index;
1643
- });
1644
- const result = [];
1645
- while (queue.length > 0) {
1646
- const job = queue.shift();
1647
- result.push(job);
1648
- const neighbors = adjacency.get(job.id) || [];
1649
- for (const neighborId of neighbors) {
1650
- const newDegree = inDegree.get(neighborId) - 1;
1651
- inDegree.set(neighborId, newDegree);
1652
- if (newDegree === 0) {
1653
- const neighbor = jobMap.get(neighborId);
1654
- insertSorted(queue, neighbor);
1655
- }
1656
- }
1657
- }
1658
- if (result.length !== n) {
1659
- console.warn("[useFrame] Circular dependency detected in job constraints");
1660
- const resultIds = new Set(result.map((j) => j.id));
1661
- for (const job of jobs) {
1662
- if (!resultIds.has(job.id)) result.push(job);
1663
- }
1664
- }
1665
- return result;
1666
- }
1667
- function insertSorted(arr, job) {
1668
- let i = 0;
1669
- while (i < arr.length) {
1670
- const cmp = arr[i];
1671
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1672
- break;
1673
- }
1674
- i++;
1675
- }
1676
- arr.splice(i, 0, job);
1677
- }
1678
-
1679
- function shouldRun(job, now) {
1680
- if (!job.enabled) return false;
1681
- if (!job.fps) return true;
1682
- const minInterval = 1e3 / job.fps;
1683
- const lastRun = job.lastRun ?? 0;
1684
- const elapsed = now - lastRun;
1685
- if (elapsed < minInterval) return false;
1686
- if (job.drop) {
1687
- job.lastRun = now;
1688
- } else {
1689
- const steps = Math.floor(elapsed / minInterval);
1690
- job.lastRun = lastRun + steps * minInterval;
1691
- if (job.lastRun < now - minInterval) {
1692
- job.lastRun = now;
1693
- }
1694
- }
1695
- return true;
1696
- }
1697
- function resetJobTiming(job) {
1698
- job.lastRun = void 0;
1699
- }
1700
-
1701
- var __defProp = Object.defineProperty;
1702
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1703
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1704
- const hmrData = (() => {
1705
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1706
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1707
- try {
1708
- return (0, eval)("import.meta.hot");
1709
- } catch {
1710
- return void 0;
1711
- }
1712
- })();
1713
- const _Scheduler = class _Scheduler {
1714
- //* Constructor ================================
1715
- constructor() {
1716
- //* Critical State ================================
1717
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1718
- __publicField(this, "phaseGraph");
1719
- __publicField(this, "loopState", {
1720
- running: false,
1721
- rafHandle: null,
1722
- lastTime: null,
1723
- // null = uninitialized, 0+ = valid timestamp
1724
- frameCount: 0,
1725
- elapsedTime: 0,
1726
- createdAt: performance.now()
1727
- });
1728
- __publicField(this, "stoppedTime", 0);
1729
- //* Private State ================================
1730
- __publicField(this, "nextRootIndex", 0);
1731
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1732
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1733
- __publicField(this, "nextGlobalIndex", 0);
1734
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1735
- __publicField(this, "nextJobIndex", 0);
1736
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1737
- __publicField(this, "pendingFrames", 0);
1738
- __publicField(this, "_frameloop", "always");
1739
- //* Independent Mode & Error Handling State ================================
1740
- __publicField(this, "_independent", false);
1741
- __publicField(this, "errorHandler", null);
1742
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1743
- //* Core Loop Execution Methods ================================
1744
- /**
1745
- * Main RAF loop callback.
1746
- * Executes frame, handles demand mode, and schedules next frame.
1747
- * @param {number} timestamp - RAF timestamp in milliseconds
1748
- * @returns {void}
1749
- * @private
1750
- */
1751
- __publicField(this, "loop", (timestamp) => {
1752
- if (!this.loopState.running) return;
1753
- this.executeFrame(timestamp);
1754
- if (this._frameloop === "demand") {
1755
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1756
- if (this.pendingFrames === 0) {
1757
- this.notifyIdle(timestamp);
1758
- return this.stop();
1759
- }
1760
- }
1761
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1762
- });
1763
- this.phaseGraph = new PhaseGraph();
1764
- }
1765
- static get instance() {
1766
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1767
- }
1768
- static set instance(value) {
1769
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1770
- }
1771
- /**
1772
- * Get the global scheduler instance (creates if doesn't exist).
1773
- * Uses HMR data to preserve instance across hot reloads.
1774
- * @returns {Scheduler} The singleton scheduler instance
1775
- */
1776
- static get() {
1777
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1778
- _Scheduler.instance = hmrData.data.scheduler;
1779
- }
1780
- if (!_Scheduler.instance) {
1781
- _Scheduler.instance = new _Scheduler();
1782
- if (hmrData?.data) {
1783
- hmrData.data.scheduler = _Scheduler.instance;
1784
- }
1785
- }
1786
- return _Scheduler.instance;
1787
- }
1788
- /**
1789
- * Reset the singleton instance. Stops the loop and clears all state.
1790
- * Primarily used for testing to ensure clean state between tests.
1791
- * @returns {void}
1792
- */
1793
- static reset() {
1794
- if (_Scheduler.instance) {
1795
- _Scheduler.instance.stop();
1796
- _Scheduler.instance = null;
1797
- }
1798
- if (hmrData?.data) {
1799
- hmrData.data.scheduler = null;
1800
- }
1801
- }
1802
- //* Getters & Setters ================================
1803
- get phases() {
1804
- return this.phaseGraph.getOrderedPhases();
1805
- }
1806
- get frameloop() {
1807
- return this._frameloop;
1808
- }
1809
- set frameloop(mode) {
1810
- if (this._frameloop === mode) return;
1811
- const wasAlways = this._frameloop === "always";
1812
- this._frameloop = mode;
1813
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1814
- else if (mode !== "always" && wasAlways) this.stop();
1815
- }
1816
- get isRunning() {
1817
- return this.loopState.running;
1818
- }
1819
- get isReady() {
1820
- return this.roots.size > 0;
1821
- }
1822
- get independent() {
1823
- return this._independent;
1824
- }
1825
- set independent(value) {
1826
- this._independent = value;
1827
- if (value) this.ensureDefaultRoot();
1828
- }
1829
- //* Root Management Methods ================================
1830
- /**
1831
- * Register a root (Canvas) with the scheduler.
1832
- * The first root to register starts the RAF loop (if frameloop='always').
1833
- * @param {string} id - Unique identifier for this root
1834
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1835
- * @returns {() => void} Unsubscribe function to remove this root
1836
- */
1837
- registerRoot(id, options = {}) {
1838
- if (this.roots.has(id)) {
1839
- console.warn(`[Scheduler] Root "${id}" already registered`);
1840
- return () => this.unregisterRoot(id);
1841
- }
1842
- const entry = {
1843
- id,
1844
- getState: options.getState ?? (() => ({})),
1845
- jobs: /* @__PURE__ */ new Map(),
1846
- sortedJobs: [],
1847
- needsRebuild: false
1848
- };
1849
- if (options.onError) {
1850
- this.errorHandler = options.onError;
1851
- }
1852
- this.roots.set(id, entry);
1853
- if (this.roots.size === 1) {
1854
- this.notifyRootReady();
1855
- if (this._frameloop === "always") this.start();
1856
- }
1857
- return () => this.unregisterRoot(id);
1858
- }
1859
- /**
1860
- * Unregister a root from the scheduler.
1861
- * Cleans up all job state listeners for this root's jobs.
1862
- * The last root to unregister stops the RAF loop.
1863
- * @param {string} id - The root ID to unregister
1864
- * @returns {void}
1865
- */
1866
- unregisterRoot(id) {
1867
- const root = this.roots.get(id);
1868
- if (!root) return;
1869
- for (const jobId of root.jobs.keys()) {
1870
- this.jobStateListeners.delete(jobId);
1871
- }
1872
- this.roots.delete(id);
1873
- if (this.roots.size === 0) {
1874
- this.stop();
1875
- this.errorHandler = null;
1876
- }
1877
- }
1878
- /**
1879
- * Subscribe to be notified when a root becomes available.
1880
- * Fires immediately if a root already exists.
1881
- * @param {() => void} callback - Function called when first root registers
1882
- * @returns {() => void} Unsubscribe function
1883
- */
1884
- onRootReady(callback) {
1885
- if (this.roots.size > 0) {
1886
- callback();
1887
- return () => {
1888
- };
1889
- }
1890
- this.rootReadyCallbacks.add(callback);
1891
- return () => this.rootReadyCallbacks.delete(callback);
1892
- }
1893
- /**
1894
- * Notify all registered root-ready callbacks.
1895
- * Called when the first root registers.
1896
- * @returns {void}
1897
- * @private
1898
- */
1899
- notifyRootReady() {
1900
- for (const cb of this.rootReadyCallbacks) {
1901
- try {
1902
- cb();
1903
- } catch (error) {
1904
- console.error("[Scheduler] Error in root-ready callback:", error);
1905
- }
1906
- }
1907
- this.rootReadyCallbacks.clear();
1908
- }
1909
- /**
1910
- * Ensure a default root exists for independent mode.
1911
- * Creates a minimal root with no state provider.
1912
- * @returns {void}
1913
- * @private
1914
- */
1915
- ensureDefaultRoot() {
1916
- if (!this.roots.has("__default__")) {
1917
- this.registerRoot("__default__");
1918
- }
1919
- }
1920
- /**
1921
- * Trigger error handling for job errors.
1922
- * Uses the bound error handler if available, otherwise logs to console.
1923
- * @param {Error} error - The error to handle
1924
- * @returns {void}
1925
- */
1926
- triggerError(error) {
1927
- if (this.errorHandler) this.errorHandler(error);
1928
- else console.error("[Scheduler]", error);
1929
- }
1930
- //* Phase Management Methods ================================
1931
- /**
1932
- * Add a named phase to the scheduler's execution order.
1933
- * Marks all roots for rebuild to incorporate the new phase.
1934
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1935
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1936
- * @returns {void}
1937
- * @example
1938
- * scheduler.addPhase('physics', { before: 'update' });
1939
- * scheduler.addPhase('postprocess', { after: 'render' });
1940
- */
1941
- addPhase(name, options) {
1942
- this.phaseGraph.addPhase(name, options);
1943
- for (const root of this.roots.values()) {
1944
- root.needsRebuild = true;
1945
- }
1946
- }
1947
- /**
1948
- * Check if a phase exists in the scheduler.
1949
- * @param {string} name - The phase name to check
1950
- * @returns {boolean} True if the phase exists
1951
- */
1952
- hasPhase(name) {
1953
- return this.phaseGraph.hasPhase(name);
1954
- }
1955
- //* Global Job Registration Methods (Deprecated APIs) ================================
1956
- /**
1957
- * Register a global job that runs once per frame (not per-root).
1958
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1959
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1960
- * @param {string} id - Unique identifier for this global job
1961
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1962
- * @returns {() => void} Unsubscribe function to remove this global job
1963
- * @deprecated Use useFrame with phases instead
1964
- */
1965
- registerGlobal(phase, id, callback) {
1966
- const job = { id, callback };
1967
- if (phase === "before") {
1968
- this.globalBeforeJobs.set(id, job);
1969
- } else {
1970
- this.globalAfterJobs.set(id, job);
1971
- }
1972
- return () => {
1973
- if (phase === "before") this.globalBeforeJobs.delete(id);
1974
- else this.globalAfterJobs.delete(id);
1975
- };
1976
- }
1977
- //* Idle Callback Methods (Deprecated API) ================================
1978
- /**
1979
- * Register an idle callback that fires when the loop stops.
1980
- * Used internally by deprecated addTail API.
1981
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
1982
- * @returns {() => void} Unsubscribe function to remove this idle callback
1983
- * @deprecated Use demand mode with invalidate() instead
1984
- */
1985
- onIdle(callback) {
1986
- this.idleCallbacks.add(callback);
1987
- return () => this.idleCallbacks.delete(callback);
1988
- }
1989
- /**
1990
- * Notify all registered idle callbacks.
1991
- * Called when the loop stops in demand mode.
1992
- * @param {number} timestamp - The RAF timestamp when idle occurred
1993
- * @returns {void}
1994
- * @private
1995
- */
1996
- notifyIdle(timestamp) {
1997
- for (const cb of this.idleCallbacks) {
1998
- try {
1999
- cb(timestamp);
2000
- } catch (error) {
2001
- console.error("[Scheduler] Error in idle callback:", error);
2002
- }
2003
- }
2004
- }
2005
- //* Job Registration & Management Methods ================================
2006
- /**
2007
- * Register a job (frame callback) with a specific root.
2008
- * This is the core registration method used by useFrame internally.
2009
- * @param {FrameNextCallback} callback - The function to call each frame
2010
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2011
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2012
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2013
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2014
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2015
- * @param {number} [options.fps] - FPS throttle limit
2016
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2017
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2018
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2019
- * @returns {() => void} Unsubscribe function to remove this job
2020
- */
2021
- register(callback, options = {}) {
2022
- const rootId = options.rootId;
2023
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2024
- if (!root) {
2025
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2026
- return () => {
2027
- };
2028
- }
2029
- const id = options.id ?? this.generateJobId();
2030
- let phase = options.phase ?? "update";
2031
- if (!options.phase && (options.before || options.after)) {
2032
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2033
- }
2034
- const before = this.normalizeConstraints(options.before);
2035
- const after = this.normalizeConstraints(options.after);
2036
- const job = {
2037
- id,
2038
- callback,
2039
- phase,
2040
- before,
2041
- after,
2042
- priority: options.priority ?? 0,
2043
- index: this.nextJobIndex++,
2044
- fps: options.fps,
2045
- drop: options.drop ?? true,
2046
- enabled: options.enabled ?? true,
2047
- system: options.system ?? false
2048
- };
2049
- if (root.jobs.has(id)) {
2050
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2051
- }
2052
- root.jobs.set(id, job);
2053
- root.needsRebuild = true;
2054
- return () => this.unregister(id, root.id);
2055
- }
2056
- /**
2057
- * Unregister a job by its ID.
2058
- * Searches all roots if rootId is not provided.
2059
- * @param {string} id - The job ID to unregister
2060
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2061
- * @returns {void}
2062
- */
2063
- unregister(id, rootId) {
2064
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2065
- if (root?.jobs.delete(id)) {
2066
- root.needsRebuild = true;
2067
- this.jobStateListeners.delete(id);
2068
- }
2069
- }
2070
- /**
2071
- * Update a job's options dynamically.
2072
- * Searches all roots to find the job by ID.
2073
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2074
- * @param {string} id - The job ID to update
2075
- * @param {Partial<JobOptions>} options - The options to update
2076
- * @returns {void}
2077
- */
2078
- updateJob(id, options) {
2079
- let job;
2080
- let root;
2081
- for (const r of this.roots.values()) {
2082
- job = r.jobs.get(id);
2083
- if (job) {
2084
- root = r;
2085
- break;
2086
- }
2087
- }
2088
- if (!job || !root) return;
2089
- if (options.priority !== void 0) job.priority = options.priority;
2090
- if (options.fps !== void 0) job.fps = options.fps;
2091
- if (options.drop !== void 0) job.drop = options.drop;
2092
- if (options.enabled !== void 0) {
2093
- const wasEnabled = job.enabled;
2094
- job.enabled = options.enabled;
2095
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2096
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2097
- }
2098
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2099
- if (options.phase) job.phase = options.phase;
2100
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2101
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2102
- root.needsRebuild = true;
2103
- }
2104
- }
2105
- //* Job State Management Methods ================================
2106
- /**
2107
- * Check if a job is currently paused (disabled).
2108
- * @param {string} id - The job ID to check
2109
- * @returns {boolean} True if the job exists and is paused
2110
- */
2111
- isJobPaused(id) {
2112
- for (const root of this.roots.values()) {
2113
- const job = root.jobs.get(id);
2114
- if (job) return !job.enabled;
2115
- }
2116
- return false;
2117
- }
2118
- /**
2119
- * Subscribe to state changes for a specific job.
2120
- * Listener is called when job is paused or resumed.
2121
- * @param {string} id - The job ID to subscribe to
2122
- * @param {() => void} listener - Callback invoked on state changes
2123
- * @returns {() => void} Unsubscribe function
2124
- */
2125
- subscribeJobState(id, listener) {
2126
- if (!this.jobStateListeners.has(id)) {
2127
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2128
- }
2129
- this.jobStateListeners.get(id).add(listener);
2130
- return () => {
2131
- this.jobStateListeners.get(id)?.delete(listener);
2132
- if (this.jobStateListeners.get(id)?.size === 0) {
2133
- this.jobStateListeners.delete(id);
2134
- }
2135
- };
2136
- }
2137
- /**
2138
- * Notify all listeners that a job's state has changed.
2139
- * @param {string} id - The job ID that changed
2140
- * @returns {void}
2141
- * @private
2142
- */
2143
- notifyJobStateChange(id) {
2144
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2145
- }
2146
- /**
2147
- * Pause a job by ID (sets enabled=false).
2148
- * Notifies any subscribed state listeners.
2149
- * @param {string} id - The job ID to pause
2150
- * @returns {void}
2151
- */
2152
- pauseJob(id) {
2153
- this.updateJob(id, { enabled: false });
2154
- this.notifyJobStateChange(id);
2155
- }
2156
- /**
2157
- * Resume a paused job by ID (sets enabled=true).
2158
- * Resets job timing to prevent frame accumulation.
2159
- * Notifies any subscribed state listeners.
2160
- * @param {string} id - The job ID to resume
2161
- * @returns {void}
2162
- */
2163
- resumeJob(id) {
2164
- this.updateJob(id, { enabled: true });
2165
- this.notifyJobStateChange(id);
2166
- }
2167
- //* Frame Loop Control Methods ================================
2168
- /**
2169
- * Start the requestAnimationFrame loop.
2170
- * Resets timing state (elapsedTime, frameCount) on start.
2171
- * No-op if already running.
2172
- * @returns {void}
2173
- */
2174
- start() {
2175
- if (this.loopState.running) return;
2176
- const { elapsedTime, createdAt } = this.loopState;
2177
- let adjustedCreated = 0;
2178
- if (this.stoppedTime > 0) {
2179
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2180
- this.stoppedTime = 0;
2181
- }
2182
- Object.assign(this.loopState, {
2183
- running: true,
2184
- elapsedTime: elapsedTime ?? 0,
2185
- lastTime: performance.now(),
2186
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2187
- frameCount: 0,
2188
- rafHandle: requestAnimationFrame(this.loop)
2189
- });
2190
- }
2191
- /**
2192
- * Stop the requestAnimationFrame loop.
2193
- * Cancels any pending RAF callback.
2194
- * No-op if not running.
2195
- * @returns {void}
2196
- */
2197
- stop() {
2198
- if (!this.loopState.running) return;
2199
- this.loopState.running = false;
2200
- if (this.loopState.rafHandle !== null) {
2201
- cancelAnimationFrame(this.loopState.rafHandle);
2202
- this.loopState.rafHandle = null;
2203
- }
2204
- this.stoppedTime = performance.now();
2205
- }
2206
- /**
2207
- * Request frames to be rendered in demand mode.
2208
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2209
- * No-op if frameloop is not 'demand'.
2210
- * @param {number} [frames=1] - Number of frames to request
2211
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2212
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2213
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2214
- * @returns {void}
2215
- * @example
2216
- * // Request a single frame render
2217
- * scheduler.invalidate();
2218
- *
2219
- * @example
2220
- * // Request 5 frames (e.g., for animations)
2221
- * scheduler.invalidate(5);
2222
- *
2223
- * @example
2224
- * // Set pending frames to exactly 3 (don't stack with existing)
2225
- * scheduler.invalidate(3, false);
2226
- *
2227
- * @example
2228
- * // Add 2 more frames to existing pending count
2229
- * scheduler.invalidate(2, true);
2230
- */
2231
- invalidate(frames = 1, stackFrames = false) {
2232
- if (this._frameloop !== "demand") return;
2233
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2234
- this.pendingFrames = Math.min(60, baseFrames + frames);
2235
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2236
- }
2237
- /**
2238
- * Reset timing state for deterministic testing.
2239
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2240
- * @returns {void}
2241
- */
2242
- resetTiming() {
2243
- this.loopState.lastTime = null;
2244
- this.loopState.frameCount = 0;
2245
- this.loopState.elapsedTime = 0;
2246
- this.loopState.createdAt = performance.now();
2247
- }
2248
- //* Manual Stepping Methods ================================
2249
- /**
2250
- * Manually execute a single frame for all roots.
2251
- * Useful for frameloop='never' mode or testing scenarios.
2252
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2253
- * @returns {void}
2254
- * @example
2255
- * // Manual control mode
2256
- * scheduler.frameloop = 'never';
2257
- * scheduler.step(); // Execute one frame
2258
- */
2259
- step(timestamp) {
2260
- const now = timestamp ?? performance.now();
2261
- this.executeFrame(now);
2262
- }
2263
- /**
2264
- * Manually execute a single job by its ID.
2265
- * Useful for testing individual job callbacks in isolation.
2266
- * @param {string} id - The job ID to step
2267
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2268
- * @returns {void}
2269
- */
2270
- stepJob(id, timestamp) {
2271
- let job;
2272
- let root;
2273
- for (const r of this.roots.values()) {
2274
- job = r.jobs.get(id);
2275
- if (job) {
2276
- root = r;
2277
- break;
2278
- }
2279
- }
2280
- if (!job || !root) {
2281
- console.warn(`[Scheduler] Job "${id}" not found`);
2282
- return;
2283
- }
2284
- const now = timestamp ?? performance.now();
2285
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2286
- const delta = deltaMs / 1e3;
2287
- const elapsed = now - this.loopState.createdAt;
2288
- const providedState = root.getState?.() ?? {};
2289
- const frameState = {
2290
- ...providedState,
2291
- time: now,
2292
- delta,
2293
- elapsed,
2294
- frame: this.loopState.frameCount
2295
- };
2296
- try {
2297
- job.callback(frameState, delta);
2298
- } catch (error) {
2299
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2300
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2301
- }
2302
- }
2303
- /**
2304
- * Execute a single frame across all roots.
2305
- * Order: globalBefore → each root's jobs → globalAfter
2306
- * @param {number} timestamp - RAF timestamp in milliseconds
2307
- * @returns {void}
2308
- * @private
2309
- */
2310
- executeFrame(timestamp) {
2311
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2312
- const delta = deltaMs / 1e3;
2313
- this.loopState.lastTime = timestamp;
2314
- this.loopState.frameCount++;
2315
- this.loopState.elapsedTime += deltaMs;
2316
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2317
- for (const root of this.roots.values()) {
2318
- this.tickRoot(root, timestamp, delta);
2319
- }
2320
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2321
- }
2322
- /**
2323
- * Run all global jobs from a job map.
2324
- * Catches and logs errors without stopping execution.
2325
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2326
- * @param {number} timestamp - RAF timestamp in milliseconds
2327
- * @returns {void}
2328
- * @private
2329
- */
2330
- runGlobalJobs(jobs, timestamp) {
2331
- for (const job of jobs.values()) {
2332
- try {
2333
- job.callback(timestamp);
2334
- } catch (error) {
2335
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2336
- }
2337
- }
2338
- }
2339
- /**
2340
- * Execute all jobs for a single root in sorted order.
2341
- * Rebuilds sorted job list if needed, then dispatches each job.
2342
- * Errors are caught and propagated via triggerError.
2343
- * @param {RootEntry} root - The root entry to tick
2344
- * @param {number} timestamp - RAF timestamp in milliseconds
2345
- * @param {number} delta - Time since last frame in seconds
2346
- * @returns {void}
2347
- * @private
2348
- */
2349
- tickRoot(root, timestamp, delta) {
2350
- if (root.needsRebuild) {
2351
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2352
- root.needsRebuild = false;
2353
- }
2354
- const providedState = root.getState?.() ?? {};
2355
- const frameState = {
2356
- ...providedState,
2357
- time: timestamp,
2358
- delta,
2359
- elapsed: this.loopState.elapsedTime / 1e3,
2360
- // Convert ms to seconds
2361
- frame: this.loopState.frameCount
2362
- };
2363
- for (const job of root.sortedJobs) {
2364
- if (!shouldRun(job, timestamp)) continue;
2365
- try {
2366
- job.callback(frameState, delta);
2367
- } catch (error) {
2368
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2369
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2370
- }
2371
- }
2372
- }
2373
- //* Debug & Inspection Methods ================================
2374
- /**
2375
- * Get the total number of registered jobs across all roots.
2376
- * Includes both per-root jobs and global before/after jobs.
2377
- * @returns {number} Total job count
2378
- */
2379
- getJobCount() {
2380
- let count = 0;
2381
- for (const root of this.roots.values()) {
2382
- count += root.jobs.size;
2383
- }
2384
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2385
- }
2386
- /**
2387
- * Get all registered job IDs across all roots.
2388
- * Includes both per-root jobs and global before/after jobs.
2389
- * @returns {string[]} Array of all job IDs
2390
- */
2391
- getJobIds() {
2392
- const ids = [];
2393
- for (const root of this.roots.values()) {
2394
- ids.push(...root.jobs.keys());
2395
- }
2396
- ids.push(...this.globalBeforeJobs.keys());
2397
- ids.push(...this.globalAfterJobs.keys());
2398
- return ids;
2399
- }
2400
- /**
2401
- * Get the number of registered roots (Canvas instances).
2402
- * @returns {number} Number of registered roots
2403
- */
2404
- getRootCount() {
2405
- return this.roots.size;
2406
- }
2407
- /**
2408
- * Check if any user (non-system) jobs are registered in a specific phase.
2409
- * Used by the default render job to know if a user has taken over rendering.
2410
- *
2411
- * @param phase The phase to check
2412
- * @param rootId Optional root ID to check (checks all roots if not provided)
2413
- * @returns true if any user jobs exist in the phase
2414
- */
2415
- hasUserJobsInPhase(phase, rootId) {
2416
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2417
- return rootsToCheck.some((root) => {
2418
- if (!root) return false;
2419
- for (const job of root.jobs.values()) {
2420
- if (job.phase === phase && !job.system && job.enabled) return true;
2421
- }
2422
- return false;
2423
- });
2424
- }
2425
- //* Utility Methods ================================
2426
- /**
2427
- * Generate a unique root ID for automatic root registration.
2428
- * @returns {string} A unique root ID in the format 'root_N'
2429
- */
2430
- generateRootId() {
2431
- return `root_${this.nextRootIndex++}`;
2432
- }
2433
- /**
2434
- * Generate a unique job ID.
2435
- * @returns {string} A unique job ID in the format 'job_N'
2436
- * @private
2437
- */
2438
- generateJobId() {
2439
- return `job_${this.nextJobIndex}`;
2440
- }
2441
- /**
2442
- * Normalize before/after constraints to a Set.
2443
- * Handles undefined, single string, or array inputs.
2444
- * @param {string | string[] | undefined} value - The constraint value(s)
2445
- * @returns {Set<string>} Normalized Set of constraint strings
2446
- * @private
2447
- */
2448
- normalizeConstraints(value) {
2449
- if (!value) return /* @__PURE__ */ new Set();
2450
- if (Array.isArray(value)) return new Set(value);
2451
- return /* @__PURE__ */ new Set([value]);
2452
- }
2453
- };
2454
- //* Static State & Methods (Singleton Usage) ================================
2455
- //* Cross-Bundle Singleton Key ==============================
2456
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2457
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2458
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2459
- let Scheduler = _Scheduler;
2460
- const getScheduler = () => Scheduler.get();
2461
- if (hmrData) {
2462
- hmrData.accept?.();
2463
- }
2464
-
2465
1632
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
2466
1633
  const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
2467
1634
  const createStore = (invalidate, advance) => {
@@ -2499,7 +1666,14 @@ const createStore = (invalidate, advance) => {
2499
1666
  frustum: new Frustum(),
2500
1667
  autoUpdateFrustum: true,
2501
1668
  raycaster: null,
2502
- events: { priority: 1, enabled: true, connected: false },
1669
+ events: {
1670
+ priority: 1,
1671
+ enabled: true,
1672
+ connected: false,
1673
+ frameTimedRaycasts: true,
1674
+ alwaysFireOnScroll: true,
1675
+ updateOnFrame: false
1676
+ },
2503
1677
  scene: null,
2504
1678
  rootScene: null,
2505
1679
  xr: null,
@@ -2590,11 +1764,14 @@ const createStore = (invalidate, advance) => {
2590
1764
  },
2591
1765
  setError: (error) => set(() => ({ error })),
2592
1766
  error: null,
2593
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1767
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2594
1768
  uniforms: {},
2595
1769
  nodes: {},
1770
+ buffers: {},
1771
+ gpuStorage: {},
2596
1772
  textures: /* @__PURE__ */ new Map(),
2597
- postProcessing: null,
1773
+ _textureRefs: /* @__PURE__ */ new Map(),
1774
+ renderPipeline: null,
2598
1775
  passes: {},
2599
1776
  _hmrVersion: 0,
2600
1777
  _sizeImperative: false,
@@ -2603,12 +1780,16 @@ const createStore = (invalidate, advance) => {
2603
1780
  internal: {
2604
1781
  // Events
2605
1782
  interaction: [],
2606
- hovered: /* @__PURE__ */ new Map(),
2607
1783
  subscribers: [],
1784
+ // Per-pointer state (new unified structure)
1785
+ pointerMap: /* @__PURE__ */ new Map(),
1786
+ pointerDirty: /* @__PURE__ */ new Map(),
1787
+ lastEvent: React.createRef(),
1788
+ // Deprecated but kept for backwards compatibility
1789
+ hovered: /* @__PURE__ */ new Map(),
2608
1790
  initialClick: [0, 0],
2609
1791
  initialHits: [],
2610
1792
  capturedMap: /* @__PURE__ */ new Map(),
2611
- lastEvent: React.createRef(),
2612
1793
  // Visibility tracking (onFramed, onOccluded, onVisible)
2613
1794
  visibilityRegistry: /* @__PURE__ */ new Map(),
2614
1795
  // Occlusion system (WebGPU only)
@@ -2696,14 +1877,16 @@ const createStore = (invalidate, advance) => {
2696
1877
  oldSize = size;
2697
1878
  oldDpr = viewport.dpr;
2698
1879
  updateCamera(camera, size);
2699
- if (canvasTarget) {
1880
+ if (internal.isSecondary && canvasTarget) {
2700
1881
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2701
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2702
- canvasTarget.setSize(size.width, size.height, updateStyle);
1882
+ canvasTarget.setSize(size.width, size.height, false);
2703
1883
  } else {
2704
1884
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2705
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2706
- actualRenderer.setSize(size.width, size.height, updateStyle);
1885
+ actualRenderer.setSize(size.width, size.height, false);
1886
+ if (canvasTarget) {
1887
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1888
+ canvasTarget.setSize(size.width, size.height, false);
1889
+ }
2707
1890
  }
2708
1891
  }
2709
1892
  if (camera !== oldCamera) {
@@ -2847,20 +2030,14 @@ function useFrame(callback, priorityOrOptions) {
2847
2030
  }
2848
2031
  };
2849
2032
  } else {
2850
- const registerOutside = () => {
2851
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2852
- };
2853
- if (scheduler.independent || scheduler.isReady) {
2854
- return registerOutside();
2855
- }
2856
- let unregisterJob = null;
2857
- const unsubReady = scheduler.onRootReady(() => {
2858
- unregisterJob = registerOutside();
2859
- });
2860
- return () => {
2861
- unsubReady();
2862
- unregisterJob?.();
2863
- };
2033
+ return scheduler.register(
2034
+ (state, delta) => {
2035
+ const frameState = state;
2036
+ if (!frameState.renderer) return;
2037
+ callbackRef.current?.(frameState, delta);
2038
+ },
2039
+ { id, ...options }
2040
+ );
2864
2041
  }
2865
2042
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2866
2043
  const isPaused = React.useSyncExternalStore(
@@ -2951,18 +2128,18 @@ function buildFromCache(input, textureCache) {
2951
2128
  function useTexture(input, optionsOrOnLoad) {
2952
2129
  const renderer = useThree((state) => state.internal.actualRenderer);
2953
2130
  const store = useStore();
2954
- const textureCache = useThree((state) => state.textures);
2955
2131
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2956
- const { onLoad, cache = false } = options;
2132
+ const { onLoad, cache = true } = options;
2957
2133
  const onLoadRef = useRef(onLoad);
2958
2134
  onLoadRef.current = onLoad;
2959
2135
  const onLoadCalledForRef = useRef(null);
2960
2136
  const urls = useMemo(() => getUrls(input), [input]);
2961
2137
  const cachedResult = useMemo(() => {
2962
2138
  if (!cache) return null;
2963
- if (!allUrlsCached(urls, textureCache)) return null;
2964
- return buildFromCache(input, textureCache);
2965
- }, [cache, urls, textureCache, input]);
2139
+ const textures = store.getState().textures;
2140
+ if (!allUrlsCached(urls, textures)) return null;
2141
+ return buildFromCache(input, textures);
2142
+ }, [cache, urls, input, store]);
2966
2143
  const loadedTextures = useLoader(
2967
2144
  TextureLoader,
2968
2145
  IsObject(input) ? Object.values(input) : input
@@ -3006,8 +2183,6 @@ function useTexture(input, optionsOrOnLoad) {
3006
2183
  }, [input, loadedTextures, cachedResult]);
3007
2184
  useEffect(() => {
3008
2185
  if (!cache) return;
3009
- if (cachedResult) return;
3010
- const set = store.setState;
3011
2186
  const urlTextureMap = [];
3012
2187
  if (typeof input === "string") {
3013
2188
  urlTextureMap.push([input, mappedTextures]);
@@ -3021,18 +2196,32 @@ function useTexture(input, optionsOrOnLoad) {
3021
2196
  urlTextureMap.push([url, textureRecord[key]]);
3022
2197
  }
3023
2198
  }
3024
- set((state) => {
3025
- const newMap = new Map(state.textures);
3026
- let changed = false;
2199
+ store.setState((state) => {
2200
+ const refs = new Map(state._textureRefs);
2201
+ let textures = state.textures;
2202
+ let added = false;
3027
2203
  for (const [url, texture] of urlTextureMap) {
3028
- if (!newMap.has(url)) {
3029
- newMap.set(url, texture);
3030
- changed = true;
2204
+ if (!textures.has(url)) {
2205
+ if (!added) {
2206
+ textures = new Map(textures);
2207
+ added = true;
2208
+ }
2209
+ textures.set(url, texture);
3031
2210
  }
2211
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3032
2212
  }
3033
- return changed ? { textures: newMap } : state;
2213
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3034
2214
  });
3035
- }, [cache, input, mappedTextures, store, cachedResult]);
2215
+ return () => store.setState((state) => {
2216
+ const refs = new Map(state._textureRefs);
2217
+ for (const [url] of urlTextureMap) {
2218
+ const next = (refs.get(url) ?? 0) - 1;
2219
+ if (next <= 0) refs.delete(url);
2220
+ else refs.set(url, next);
2221
+ }
2222
+ return { _textureRefs: refs };
2223
+ });
2224
+ }, [cache, input, mappedTextures, store]);
3036
2225
  return mappedTextures;
3037
2226
  }
3038
2227
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3048,96 +2237,63 @@ const Texture = ({
3048
2237
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3049
2238
  };
3050
2239
 
3051
- function getTextureValue(entry) {
3052
- if (entry instanceof Texture$1) return entry;
3053
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3054
- return entry.value;
3055
- }
3056
- return null;
3057
- }
3058
- function useTextures() {
2240
+ function useTextures(selector) {
3059
2241
  const store = useStore();
3060
- return useMemo(() => {
3061
- const set = store.setState;
2242
+ const registry = useMemo(() => {
3062
2243
  const getState = store.getState;
3063
- const add = (key, value) => {
3064
- set((state) => {
3065
- const newMap = new Map(state.textures);
3066
- newMap.set(key, value);
3067
- return { textures: newMap };
3068
- });
3069
- };
3070
- const addMultiple = (items) => {
3071
- set((state) => {
3072
- const newMap = new Map(state.textures);
3073
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3074
- for (const [key, value] of entries) {
3075
- newMap.set(key, value);
3076
- }
3077
- return { textures: newMap };
3078
- });
3079
- };
3080
- const remove = (key) => {
3081
- set((state) => {
3082
- const newMap = new Map(state.textures);
3083
- newMap.delete(key);
3084
- return { textures: newMap };
3085
- });
3086
- };
3087
- const removeMultiple = (keys) => {
3088
- set((state) => {
3089
- const newMap = new Map(state.textures);
3090
- for (const key of keys) newMap.delete(key);
3091
- return { textures: newMap };
3092
- });
3093
- };
3094
- const dispose = (key) => {
3095
- const entry = getState().textures.get(key);
3096
- if (entry) {
3097
- const tex = getTextureValue(entry);
3098
- tex?.dispose();
3099
- }
3100
- remove(key);
3101
- };
3102
- const disposeMultiple = (keys) => {
3103
- const textures = getState().textures;
3104
- for (const key of keys) {
3105
- const entry = textures.get(key);
3106
- if (entry) {
3107
- const tex = getTextureValue(entry);
3108
- tex?.dispose();
3109
- }
3110
- }
3111
- removeMultiple(keys);
3112
- };
3113
- const disposeAll = () => {
3114
- const textures = getState().textures;
3115
- for (const entry of textures.values()) {
3116
- const tex = getTextureValue(entry);
3117
- tex?.dispose();
3118
- }
3119
- set({ textures: /* @__PURE__ */ new Map() });
3120
- };
2244
+ const setState = store.setState;
2245
+ const getOne = (key) => getState().textures.get(key);
3121
2246
  return {
3122
- // Getter for the textures Map (reactive via getState)
3123
- get textures() {
2247
+ get all() {
3124
2248
  return getState().textures;
3125
2249
  },
3126
- // Read
3127
- get: (key) => getState().textures.get(key),
2250
+ get(input) {
2251
+ if (typeof input === "string") return getOne(input);
2252
+ if (Array.isArray(input)) return input.map(getOne);
2253
+ const out = {};
2254
+ for (const name in input) out[name] = getOne(input[name]);
2255
+ return out;
2256
+ },
3128
2257
  has: (key) => getState().textures.has(key),
3129
- // Write
3130
- add,
3131
- addMultiple,
3132
- // Remove (cache only)
3133
- remove,
3134
- removeMultiple,
3135
- // Dispose (GPU + cache)
3136
- dispose,
3137
- disposeMultiple,
3138
- disposeAll
2258
+ add(keyOrRecord, texture) {
2259
+ setState((state) => {
2260
+ const textures = new Map(state.textures);
2261
+ if (typeof keyOrRecord === "string") {
2262
+ textures.set(keyOrRecord, texture);
2263
+ } else {
2264
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2265
+ }
2266
+ return { textures };
2267
+ });
2268
+ },
2269
+ dispose(key, options) {
2270
+ const state = getState();
2271
+ const refs = state._textureRefs.get(key) ?? 0;
2272
+ if (refs > 0 && !options?.force) {
2273
+ console.warn(
2274
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2275
+ );
2276
+ return false;
2277
+ }
2278
+ state.textures.get(key)?.dispose();
2279
+ setState((s) => {
2280
+ const textures = new Map(s.textures);
2281
+ textures.delete(key);
2282
+ const nextRefs = new Map(s._textureRefs);
2283
+ nextRefs.delete(key);
2284
+ return { textures, _textureRefs: nextRefs };
2285
+ });
2286
+ return true;
2287
+ },
2288
+ disposeAll() {
2289
+ for (const texture of getState().textures.values()) texture.dispose();
2290
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2291
+ }
3139
2292
  };
3140
2293
  }, [store]);
2294
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2295
+ const selected = useThree(subscribe);
2296
+ return selector ? selected : registry;
3141
2297
  }
3142
2298
 
3143
2299
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -14990,7 +14146,6 @@ function createRoot(canvas) {
14990
14146
  events,
14991
14147
  onCreated: onCreatedCallback,
14992
14148
  shadows = false,
14993
- textureColorSpace = SRGBColorSpace,
14994
14149
  orthographic = false,
14995
14150
  frameloop = "always",
14996
14151
  dpr = [1, 2],
@@ -15005,6 +14160,7 @@ function createRoot(canvas) {
15005
14160
  _sizeProps,
15006
14161
  forceEven
15007
14162
  } = props;
14163
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15008
14164
  const state = store.getState();
15009
14165
  const defaultGLProps = {
15010
14166
  canvas,
@@ -15060,6 +14216,12 @@ function createRoot(canvas) {
15060
14216
  } else if (!wantsGL && !state.internal.actualRenderer) {
15061
14217
  renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15062
14218
  if (!renderer.hasInitialized?.()) {
14219
+ const size2 = computeInitialSize(canvas, propsSize);
14220
+ if (size2.width > 0 && size2.height > 0) {
14221
+ const pixelRatio = calculateDpr(dpr);
14222
+ canvas.width = size2.width * pixelRatio;
14223
+ canvas.height = size2.height * pixelRatio;
14224
+ }
15063
14225
  await renderer.init();
15064
14226
  }
15065
14227
  const backend = renderer.backend;
@@ -15169,7 +14331,7 @@ function createRoot(canvas) {
15169
14331
  lastConfiguredProps.performance = performance;
15170
14332
  }
15171
14333
  if (!state.xr) {
15172
- const handleXRFrame = (timestamp, frame) => {
14334
+ const handleXRFrame = (timestamp, _frame) => {
15173
14335
  const state2 = store.getState();
15174
14336
  if (state2.frameloop === "never") return;
15175
14337
  advance(timestamp);
@@ -15205,15 +14367,22 @@ function createRoot(canvas) {
15205
14367
  const oldType = renderer.shadowMap.type;
15206
14368
  renderer.shadowMap.enabled = !!shadows;
15207
14369
  if (is.boo(shadows)) {
15208
- renderer.shadowMap.type = PCFSoftShadowMap;
14370
+ renderer.shadowMap.type = PCFShadowMap;
15209
14371
  } else if (is.str(shadows)) {
14372
+ if (shadows === "soft") {
14373
+ notifyDepreciated({
14374
+ heading: 'shadows="soft" is deprecated',
14375
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14376
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14377
+ });
14378
+ }
15210
14379
  const types = {
15211
14380
  basic: BasicShadowMap,
15212
14381
  percentage: PCFShadowMap,
15213
- soft: PCFSoftShadowMap,
14382
+ soft: PCFShadowMap,
15214
14383
  variance: VSMShadowMap
15215
14384
  };
15216
- renderer.shadowMap.type = types[shadows] ?? PCFSoftShadowMap;
14385
+ renderer.shadowMap.type = types[shadows] ?? PCFShadowMap;
15217
14386
  } else if (is.obj(shadows)) {
15218
14387
  Object.assign(renderer.shadowMap, shadows);
15219
14388
  }
@@ -15229,13 +14398,24 @@ function createRoot(canvas) {
15229
14398
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15230
14399
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15231
14400
  }
14401
+ const r3fProps = ["textureColorSpace"];
14402
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14403
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15232
14404
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15233
- applyProps(renderer, glConfig);
14405
+ const glProps = {};
14406
+ for (const key in glConfig) {
14407
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14408
+ }
14409
+ applyProps(renderer, glProps);
15234
14410
  }
15235
14411
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15236
14412
  const currentRenderer = state.renderer;
15237
14413
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15238
- applyProps(currentRenderer, rendererConfig);
14414
+ const rendererProps = {};
14415
+ for (const key in rendererConfig) {
14416
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14417
+ }
14418
+ applyProps(currentRenderer, rendererProps);
15239
14419
  }
15240
14420
  }
15241
14421
  const scheduler = getScheduler();
@@ -15261,6 +14441,18 @@ function createRoot(canvas) {
15261
14441
  system: true
15262
14442
  }
15263
14443
  );
14444
+ const unregisterEventsFlush = scheduler.register(
14445
+ () => {
14446
+ const state2 = store.getState();
14447
+ state2.events.flush?.();
14448
+ },
14449
+ {
14450
+ id: `${newRootId}_events`,
14451
+ rootId: newRootId,
14452
+ phase: "input",
14453
+ system: true
14454
+ }
14455
+ );
15264
14456
  const unregisterFrustum = scheduler.register(
15265
14457
  () => {
15266
14458
  const state2 = store.getState();
@@ -15271,7 +14463,7 @@ function createRoot(canvas) {
15271
14463
  {
15272
14464
  id: `${newRootId}_frustum`,
15273
14465
  rootId: newRootId,
15274
- phase: "preRender",
14466
+ before: "render",
15275
14467
  system: true
15276
14468
  }
15277
14469
  );
@@ -15283,7 +14475,7 @@ function createRoot(canvas) {
15283
14475
  {
15284
14476
  id: `${newRootId}_visibility`,
15285
14477
  rootId: newRootId,
15286
- phase: "preRender",
14478
+ before: "render",
15287
14479
  system: true,
15288
14480
  after: `${newRootId}_frustum`
15289
14481
  }
@@ -15295,7 +14487,7 @@ function createRoot(canvas) {
15295
14487
  const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
15296
14488
  if (userHandlesRender || state2.internal.priority) return;
15297
14489
  try {
15298
- if (state2.postProcessing?.render) state2.postProcessing.render();
14490
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
15299
14491
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
15300
14492
  } catch (error) {
15301
14493
  state2.setError(error instanceof Error ? error : new Error(String(error)));
@@ -15320,6 +14512,7 @@ function createRoot(canvas) {
15320
14512
  unregisterRoot: () => {
15321
14513
  unregisterRoot();
15322
14514
  unregisterCanvasTarget();
14515
+ unregisterEventsFlush();
15323
14516
  unregisterFrustum();
15324
14517
  unregisterVisibility();
15325
14518
  unregisterRender();
@@ -15485,9 +14678,13 @@ function PortalInner({ state = {}, children, container }) {
15485
14678
  const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15486
14679
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15487
14680
  onMutate(previousRoot.getState());
15488
- previousRoot.subscribe(onMutate);
15489
14681
  return store;
15490
14682
  }, [previousRoot, container]);
14683
+ useIsomorphicLayoutEffect(() => {
14684
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14685
+ const unsubscribe = previousRoot.subscribe(onMutate);
14686
+ return unsubscribe;
14687
+ }, [previousRoot, usePortalStore]);
15491
14688
  return (
15492
14689
  // @ts-ignore, reconciler types are not maintained
15493
14690
  /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
@@ -15501,6 +14698,46 @@ function flushSync(fn) {
15501
14698
  return reconciler.flushSyncFromReconciler(fn);
15502
14699
  }
15503
14700
 
14701
+ function parseBackground(background) {
14702
+ if (!background) return null;
14703
+ if (typeof background === "object" && !background.isColor) {
14704
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14705
+ return {
14706
+ ...rest,
14707
+ preset,
14708
+ files: envMap || files,
14709
+ backgroundFiles: backgroundMap,
14710
+ background: true
14711
+ };
14712
+ }
14713
+ if (typeof background === "number") {
14714
+ return { color: background, background: true };
14715
+ }
14716
+ if (typeof background === "string") {
14717
+ if (background in presetsObj) {
14718
+ return { preset: background, background: true };
14719
+ }
14720
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14721
+ return { files: background, background: true };
14722
+ }
14723
+ return { color: background, background: true };
14724
+ }
14725
+ if (background.isColor) {
14726
+ return { color: background, background: true };
14727
+ }
14728
+ return null;
14729
+ }
14730
+
14731
+ function clearHmrCaches(store) {
14732
+ store.setState((state) => ({
14733
+ nodes: {},
14734
+ uniforms: {},
14735
+ buffers: {},
14736
+ gpuStorage: {},
14737
+ _hmrVersion: state._hmrVersion + 1
14738
+ }));
14739
+ }
14740
+
15504
14741
  function CanvasImpl({
15505
14742
  ref,
15506
14743
  children,
@@ -15521,6 +14758,8 @@ function CanvasImpl({
15521
14758
  raycaster,
15522
14759
  camera,
15523
14760
  scene,
14761
+ autoUpdateFrustum,
14762
+ occlusion,
15524
14763
  onPointerMissed,
15525
14764
  onDragOverMissed,
15526
14765
  onDropMissed,
@@ -15532,39 +14771,21 @@ function CanvasImpl({
15532
14771
  forceEven,
15533
14772
  ...props
15534
14773
  }) {
15535
- 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 };
15536
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14774
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14775
+ let primaryCanvas;
14776
+ let scheduler;
14777
+ let renderer;
14778
+ if (isRendererConfig) {
14779
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14780
+ primaryCanvas = pc;
14781
+ scheduler = sc;
14782
+ renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
14783
+ } else {
14784
+ renderer = rendererProp;
14785
+ }
15537
14786
  React.useMemo(() => extend(THREE), []);
15538
14787
  const Bridge = useBridge();
15539
- const backgroundProps = React.useMemo(() => {
15540
- if (!background) return null;
15541
- if (typeof background === "object" && !background.isColor) {
15542
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15543
- return {
15544
- ...rest,
15545
- preset,
15546
- files: envMap || files,
15547
- backgroundFiles: backgroundMap,
15548
- background: true
15549
- };
15550
- }
15551
- if (typeof background === "number") {
15552
- return { color: background, background: true };
15553
- }
15554
- if (typeof background === "string") {
15555
- if (background in presetsObj) {
15556
- return { preset: background, background: true };
15557
- }
15558
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15559
- return { files: background, background: true };
15560
- }
15561
- return { color: background, background: true };
15562
- }
15563
- if (background.isColor) {
15564
- return { color: background, background: true };
15565
- }
15566
- return null;
15567
- }, [background]);
14788
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15568
14789
  const hasInitialSizeRef = React.useRef(false);
15569
14790
  const measureConfig = React.useMemo(() => {
15570
14791
  if (!hasInitialSizeRef.current) {
@@ -15648,6 +14869,8 @@ function CanvasImpl({
15648
14869
  performance,
15649
14870
  raycaster,
15650
14871
  camera,
14872
+ autoUpdateFrustum,
14873
+ occlusion,
15651
14874
  size: effectiveSize,
15652
14875
  // Store size props for reset functionality
15653
14876
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15707,20 +14930,13 @@ function CanvasImpl({
15707
14930
  const handleHMR = () => {
15708
14931
  queueMicrotask(() => {
15709
14932
  const rootEntry = _roots.get(canvas);
15710
- if (rootEntry?.store) {
15711
- rootEntry.store.setState((state) => ({
15712
- nodes: {},
15713
- uniforms: {},
15714
- _hmrVersion: state._hmrVersion + 1
15715
- }));
15716
- }
14933
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15717
14934
  });
15718
14935
  };
15719
14936
  if (typeof import.meta !== "undefined" && import.meta.hot) {
15720
14937
  const hot = import.meta.hot;
15721
14938
  hot.on("vite:afterUpdate", handleHMR);
15722
- return () => hot.dispose?.(() => {
15723
- });
14939
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
15724
14940
  }
15725
14941
  if (typeof module !== "undefined" && module.hot) {
15726
14942
  const hot = module.hot;
@@ -15743,7 +14959,16 @@ function CanvasImpl({
15743
14959
  ...style
15744
14960
  },
15745
14961
  ...props,
15746
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx("canvas", { ref: canvasRef, id, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
14962
+ children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
14963
+ "canvas",
14964
+ {
14965
+ ref: canvasRef,
14966
+ id,
14967
+ className: "r3f-canvas",
14968
+ style: { display: "block", width: "100%", height: "100%" },
14969
+ children: fallback
14970
+ }
14971
+ ) })
15747
14972
  }
15748
14973
  );
15749
14974
  }
@@ -15753,4 +14978,4 @@ function Canvas(props) {
15753
14978
 
15754
14979
  extend(THREE);
15755
14980
 
15756
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
14981
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };