@react-three/fiber 10.0.0-canary.b0fafc8 → 10.0.0-canary.b6c54f2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +714 -1383
- package/dist/index.d.cts +291 -806
- package/dist/index.d.mts +291 -806
- package/dist/index.d.ts +291 -806
- package/dist/index.mjs +689 -1357
- package/dist/legacy.cjs +669 -1344
- package/dist/legacy.d.cts +292 -806
- package/dist/legacy.d.mts +292 -806
- package/dist/legacy.d.ts +292 -806
- package/dist/legacy.mjs +643 -1317
- package/dist/webgpu/index.cjs +1170 -1698
- package/dist/webgpu/index.d.cts +407 -820
- package/dist/webgpu/index.d.mts +407 -820
- package/dist/webgpu/index.d.ts +407 -820
- package/dist/webgpu/index.mjs +1139 -1670
- package/package.json +4 -3
- package/readme.md +2 -3
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as webgpu from 'three/webgpu';
|
|
2
|
-
import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene,
|
|
3
|
-
import { WebGLRenderTarget, WebGLRenderer } from 'three';
|
|
2
|
+
import { CubeRenderTarget, RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
|
|
3
|
+
import { WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer } from 'three';
|
|
4
4
|
import { Inspector } from 'three/addons/inspector/Inspector.js';
|
|
5
5
|
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
|
|
6
6
|
import * as React from 'react';
|
|
@@ -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) {
|
|
@@ -34,10 +36,13 @@ const R3F_BUILD_WEBGPU = true;
|
|
|
34
36
|
|
|
35
37
|
const THREE = /*#__PURE__*/_mergeNamespaces({
|
|
36
38
|
__proto__: null,
|
|
39
|
+
CubeRenderTarget: CubeRenderTarget,
|
|
40
|
+
CubeRenderTargetCompat: CubeRenderTarget,
|
|
37
41
|
Inspector: Inspector,
|
|
38
42
|
R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
|
|
39
43
|
R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
|
|
40
44
|
RenderTargetCompat: RenderTarget,
|
|
45
|
+
WebGLCubeRenderTarget: WebGLCubeRenderTarget,
|
|
41
46
|
WebGLRenderTarget: WebGLRenderTarget,
|
|
42
47
|
WebGLRenderer: WebGLRenderer
|
|
43
48
|
}, [webgpu]);
|
|
@@ -139,7 +144,7 @@ function useEnvironment({
|
|
|
139
144
|
useLoader$1.clear(loader, multiFile ? [files] : files);
|
|
140
145
|
}
|
|
141
146
|
renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
|
|
142
|
-
}, [files, renderer.domElement]);
|
|
147
|
+
}, [extension, files, loader, multiFile, renderer.domElement]);
|
|
143
148
|
const loaderResult = useLoader$1(
|
|
144
149
|
loader,
|
|
145
150
|
multiFile ? [files] : files,
|
|
@@ -311,15 +316,16 @@ function EnvironmentPortal({
|
|
|
311
316
|
preset = void 0,
|
|
312
317
|
extensions
|
|
313
318
|
}) {
|
|
314
|
-
const
|
|
319
|
+
const renderer = useThree$1((state) => state.renderer);
|
|
320
|
+
const isLegacy = useThree$1((state) => state.isLegacy);
|
|
315
321
|
const defaultScene = useThree$1((state) => state.scene);
|
|
316
322
|
const camera = React.useRef(null);
|
|
317
323
|
const [virtualScene] = React.useState(() => new Scene());
|
|
318
324
|
const fbo = React.useMemo(() => {
|
|
319
|
-
const fbo2 = new WebGLCubeRenderTarget(resolution);
|
|
325
|
+
const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
|
|
320
326
|
fbo2.texture.type = HalfFloatType;
|
|
321
327
|
return fbo2;
|
|
322
|
-
}, [resolution]);
|
|
328
|
+
}, [resolution, isLegacy]);
|
|
323
329
|
React.useEffect(() => {
|
|
324
330
|
return () => {
|
|
325
331
|
fbo.dispose();
|
|
@@ -327,10 +333,10 @@ function EnvironmentPortal({
|
|
|
327
333
|
}, [fbo]);
|
|
328
334
|
React.useLayoutEffect(() => {
|
|
329
335
|
if (frames === 1) {
|
|
330
|
-
const autoClear =
|
|
331
|
-
|
|
332
|
-
camera.current.update(
|
|
333
|
-
|
|
336
|
+
const autoClear = renderer.autoClear;
|
|
337
|
+
renderer.autoClear = true;
|
|
338
|
+
camera.current.update(renderer, virtualScene);
|
|
339
|
+
renderer.autoClear = autoClear;
|
|
334
340
|
}
|
|
335
341
|
return setEnvProps(background, scene, defaultScene, fbo.texture, {
|
|
336
342
|
backgroundBlurriness: blur ?? backgroundBlurriness,
|
|
@@ -339,14 +345,29 @@ function EnvironmentPortal({
|
|
|
339
345
|
environmentIntensity,
|
|
340
346
|
environmentRotation
|
|
341
347
|
});
|
|
342
|
-
}, [
|
|
348
|
+
}, [
|
|
349
|
+
children,
|
|
350
|
+
virtualScene,
|
|
351
|
+
fbo.texture,
|
|
352
|
+
scene,
|
|
353
|
+
defaultScene,
|
|
354
|
+
background,
|
|
355
|
+
frames,
|
|
356
|
+
renderer,
|
|
357
|
+
blur,
|
|
358
|
+
backgroundBlurriness,
|
|
359
|
+
backgroundIntensity,
|
|
360
|
+
backgroundRotation,
|
|
361
|
+
environmentIntensity,
|
|
362
|
+
environmentRotation
|
|
363
|
+
]);
|
|
343
364
|
let count = 1;
|
|
344
365
|
useFrame$1(() => {
|
|
345
366
|
if (frames === Infinity || count < frames) {
|
|
346
|
-
const autoClear =
|
|
347
|
-
|
|
348
|
-
camera.current.update(
|
|
349
|
-
|
|
367
|
+
const autoClear = renderer.autoClear;
|
|
368
|
+
renderer.autoClear = true;
|
|
369
|
+
camera.current.update(renderer, virtualScene);
|
|
370
|
+
renderer.autoClear = autoClear;
|
|
350
371
|
count++;
|
|
351
372
|
}
|
|
352
373
|
});
|
|
@@ -410,9 +431,9 @@ function Environment(props) {
|
|
|
410
431
|
return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
|
|
411
432
|
}
|
|
412
433
|
|
|
413
|
-
var __defProp
|
|
414
|
-
var __defNormalProp
|
|
415
|
-
var __publicField
|
|
434
|
+
var __defProp = Object.defineProperty;
|
|
435
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
436
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
416
437
|
const act = React["act"];
|
|
417
438
|
const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
|
|
418
439
|
function useMutableCallback(fn) {
|
|
@@ -444,7 +465,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
|
|
|
444
465
|
return _a = class extends React.Component {
|
|
445
466
|
constructor() {
|
|
446
467
|
super(...arguments);
|
|
447
|
-
__publicField
|
|
468
|
+
__publicField(this, "state", { error: false });
|
|
448
469
|
}
|
|
449
470
|
componentDidCatch(err) {
|
|
450
471
|
this.props.set(err);
|
|
@@ -452,7 +473,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
|
|
|
452
473
|
render() {
|
|
453
474
|
return this.state.error ? null : this.props.children;
|
|
454
475
|
}
|
|
455
|
-
}, __publicField
|
|
476
|
+
}, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
|
|
456
477
|
})();
|
|
457
478
|
|
|
458
479
|
const is = {
|
|
@@ -589,8 +610,7 @@ function prepare(target, root, type, props) {
|
|
|
589
610
|
object,
|
|
590
611
|
eventCount: 0,
|
|
591
612
|
handlers: {},
|
|
592
|
-
isHidden: false
|
|
593
|
-
deferredRefs: []
|
|
613
|
+
isHidden: false
|
|
594
614
|
};
|
|
595
615
|
if (object) object.__r3f = instance;
|
|
596
616
|
}
|
|
@@ -747,6 +767,17 @@ function unregisterVisibility(store, object) {
|
|
|
747
767
|
internal.visibilityRegistry.delete(object.uuid);
|
|
748
768
|
internal.occlusionCache.delete(object);
|
|
749
769
|
}
|
|
770
|
+
function updateVisibilityHandlers(store, object, handlers) {
|
|
771
|
+
const { internal } = store.getState();
|
|
772
|
+
const entry = internal.visibilityRegistry.get(object.uuid);
|
|
773
|
+
if (!entry) return false;
|
|
774
|
+
entry.handlers = handlers;
|
|
775
|
+
if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
|
|
776
|
+
object.occlusionTest = true;
|
|
777
|
+
enableOcclusion(store);
|
|
778
|
+
}
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
750
781
|
function checkVisibility(state) {
|
|
751
782
|
const { internal, camera } = state;
|
|
752
783
|
const registry = internal.visibilityRegistry;
|
|
@@ -934,10 +965,7 @@ function applyProps(object, props) {
|
|
|
934
965
|
continue;
|
|
935
966
|
}
|
|
936
967
|
if (value === void 0) continue;
|
|
937
|
-
if (isFromRef(value))
|
|
938
|
-
instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
|
|
939
|
-
continue;
|
|
940
|
-
}
|
|
968
|
+
if (isFromRef(value)) continue;
|
|
941
969
|
if (isOnce(value)) {
|
|
942
970
|
if (instance?.appliedOnce?.has(prop)) continue;
|
|
943
971
|
if (instance) {
|
|
@@ -973,8 +1001,24 @@ function applyProps(object, props) {
|
|
|
973
1001
|
} else if (isVectorLike(target) && is.num(value)) {
|
|
974
1002
|
if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
|
|
975
1003
|
else target.set(value);
|
|
1004
|
+
} else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
|
|
1005
|
+
if (!is.obj(root.uniforms)) root.uniforms = {};
|
|
1006
|
+
const uniforms = root.uniforms;
|
|
1007
|
+
const nextUniforms = value;
|
|
1008
|
+
for (const name in nextUniforms) {
|
|
1009
|
+
const uniform = nextUniforms[name];
|
|
1010
|
+
const targetUniform = uniforms[name];
|
|
1011
|
+
if (targetUniform) Object.assign(targetUniform, uniform);
|
|
1012
|
+
else {
|
|
1013
|
+
const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
|
|
1014
|
+
uniforms[name] = nextUniform;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
976
1017
|
} else {
|
|
977
1018
|
root[key] = value;
|
|
1019
|
+
if (key.endsWith("Node") && root.isMaterial) {
|
|
1020
|
+
root.needsUpdate = true;
|
|
1021
|
+
}
|
|
978
1022
|
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
1023
|
root[key].format === RGBAFormat && root[key].type === UnsignedByteType) {
|
|
980
1024
|
root[key].colorSpace = rootState.textureColorSpace;
|
|
@@ -988,6 +1032,9 @@ function applyProps(object, props) {
|
|
|
988
1032
|
if (instance.eventCount && object2.raycast !== null) {
|
|
989
1033
|
rootState.internal.interaction.push(object2);
|
|
990
1034
|
}
|
|
1035
|
+
}
|
|
1036
|
+
if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
|
|
1037
|
+
const object2 = instance.object;
|
|
991
1038
|
const root = findInitialRoot(instance);
|
|
992
1039
|
const visibilityHandlers = {
|
|
993
1040
|
onFramed: instance.handlers.onFramed,
|
|
@@ -995,7 +1042,9 @@ function applyProps(object, props) {
|
|
|
995
1042
|
onVisible: instance.handlers.onVisible
|
|
996
1043
|
};
|
|
997
1044
|
if (hasVisibilityHandlers(visibilityHandlers)) {
|
|
998
|
-
|
|
1045
|
+
if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
|
|
1046
|
+
registerVisibility(root, object2, visibilityHandlers);
|
|
1047
|
+
}
|
|
999
1048
|
} else {
|
|
1000
1049
|
unregisterVisibility(root, object2);
|
|
1001
1050
|
}
|
|
@@ -1008,38 +1057,60 @@ function applyProps(object, props) {
|
|
|
1008
1057
|
return object;
|
|
1009
1058
|
}
|
|
1010
1059
|
|
|
1060
|
+
const DEFAULT_POINTER_ID = 0;
|
|
1061
|
+
const XR_POINTER_ID_START = 1e3;
|
|
1062
|
+
function getPointerState(internal, pointerId) {
|
|
1063
|
+
let state = internal.pointerMap.get(pointerId);
|
|
1064
|
+
if (!state) {
|
|
1065
|
+
state = {
|
|
1066
|
+
hovered: /* @__PURE__ */ new Map(),
|
|
1067
|
+
captured: /* @__PURE__ */ new Map(),
|
|
1068
|
+
initialClick: [0, 0],
|
|
1069
|
+
initialHits: []
|
|
1070
|
+
};
|
|
1071
|
+
internal.pointerMap.set(pointerId, state);
|
|
1072
|
+
}
|
|
1073
|
+
return state;
|
|
1074
|
+
}
|
|
1075
|
+
function getPointerId(event) {
|
|
1076
|
+
return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
|
|
1077
|
+
}
|
|
1011
1078
|
function makeId(event) {
|
|
1012
1079
|
return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
|
|
1013
1080
|
}
|
|
1014
|
-
function releaseInternalPointerCapture(
|
|
1015
|
-
const
|
|
1081
|
+
function releaseInternalPointerCapture(internal, obj, pointerId) {
|
|
1082
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1083
|
+
if (!pointerState) return;
|
|
1084
|
+
const captureData = pointerState.captured.get(obj);
|
|
1016
1085
|
if (captureData) {
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
capturedMap.delete(pointerId);
|
|
1020
|
-
captureData.target.releasePointerCapture(pointerId);
|
|
1021
|
-
}
|
|
1086
|
+
pointerState.captured.delete(obj);
|
|
1087
|
+
captureData.target.releasePointerCapture(pointerId);
|
|
1022
1088
|
}
|
|
1023
1089
|
}
|
|
1024
1090
|
function removeInteractivity(store, object) {
|
|
1025
1091
|
const { internal } = store.getState();
|
|
1026
1092
|
internal.interaction = internal.interaction.filter((o) => o !== object);
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1093
|
+
for (const [pointerId, pointerState] of internal.pointerMap) {
|
|
1094
|
+
pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
|
|
1095
|
+
pointerState.hovered.forEach((value, key) => {
|
|
1096
|
+
if (value.eventObject === object || value.object === object) {
|
|
1097
|
+
pointerState.hovered.delete(key);
|
|
1098
|
+
}
|
|
1099
|
+
});
|
|
1100
|
+
if (pointerState.captured.has(object)) {
|
|
1101
|
+
releaseInternalPointerCapture(internal, object, pointerId);
|
|
1031
1102
|
}
|
|
1032
|
-
}
|
|
1033
|
-
internal.capturedMap.forEach((captures, pointerId) => {
|
|
1034
|
-
releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
|
|
1035
|
-
});
|
|
1103
|
+
}
|
|
1036
1104
|
unregisterVisibility(store, object);
|
|
1037
1105
|
}
|
|
1038
1106
|
function createEvents(store) {
|
|
1039
|
-
function calculateDistance(event) {
|
|
1107
|
+
function calculateDistance(event, pointerId) {
|
|
1040
1108
|
const { internal } = store.getState();
|
|
1041
|
-
const
|
|
1042
|
-
|
|
1109
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1110
|
+
if (!pointerState) return 0;
|
|
1111
|
+
const [initialX, initialY] = pointerState.initialClick;
|
|
1112
|
+
const dx = event.offsetX - initialX;
|
|
1113
|
+
const dy = event.offsetY - initialY;
|
|
1043
1114
|
return Math.round(Math.sqrt(dx * dx + dy * dy));
|
|
1044
1115
|
}
|
|
1045
1116
|
function filterPointerEvents(objects) {
|
|
@@ -1075,6 +1146,15 @@ function createEvents(store) {
|
|
|
1075
1146
|
return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
|
|
1076
1147
|
}
|
|
1077
1148
|
let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
|
|
1149
|
+
const aInteractivePriority = a.object.userData?.interactivePriority;
|
|
1150
|
+
const bInteractivePriority = b.object.userData?.interactivePriority;
|
|
1151
|
+
if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
|
|
1152
|
+
if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
|
|
1153
|
+
if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
|
|
1154
|
+
if (aInteractivePriority !== bInteractivePriority) {
|
|
1155
|
+
return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1078
1158
|
const aState = getRootState(a.object);
|
|
1079
1159
|
const bState = getRootState(b.object);
|
|
1080
1160
|
const aPriority = aState?.events?.priority ?? 1;
|
|
@@ -1096,9 +1176,13 @@ function createEvents(store) {
|
|
|
1096
1176
|
eventObject = eventObject.parent;
|
|
1097
1177
|
}
|
|
1098
1178
|
}
|
|
1099
|
-
if ("pointerId" in event
|
|
1100
|
-
|
|
1101
|
-
|
|
1179
|
+
if ("pointerId" in event) {
|
|
1180
|
+
const pointerId = event.pointerId;
|
|
1181
|
+
const pointerState = state.internal.pointerMap.get(pointerId);
|
|
1182
|
+
if (pointerState?.captured.size) {
|
|
1183
|
+
for (const captureData of pointerState.captured.values()) {
|
|
1184
|
+
if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
|
|
1185
|
+
}
|
|
1102
1186
|
}
|
|
1103
1187
|
}
|
|
1104
1188
|
return intersections;
|
|
@@ -1111,27 +1195,25 @@ function createEvents(store) {
|
|
|
1111
1195
|
if (state) {
|
|
1112
1196
|
const { raycaster, pointer, camera, internal } = state;
|
|
1113
1197
|
const unprojectedPoint = new Vector3(pointer.x, pointer.y, 0).unproject(camera);
|
|
1114
|
-
const hasPointerCapture = (id) =>
|
|
1198
|
+
const hasPointerCapture = (id) => {
|
|
1199
|
+
const pointerState = internal.pointerMap.get(id);
|
|
1200
|
+
return pointerState?.captured.has(hit.eventObject) ?? false;
|
|
1201
|
+
};
|
|
1115
1202
|
const setPointerCapture = (id) => {
|
|
1116
1203
|
const captureData = { intersection: hit, target: event.target };
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
} else {
|
|
1120
|
-
internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
|
|
1121
|
-
}
|
|
1204
|
+
const pointerState = getPointerState(internal, id);
|
|
1205
|
+
pointerState.captured.set(hit.eventObject, captureData);
|
|
1122
1206
|
event.target.setPointerCapture(id);
|
|
1123
1207
|
};
|
|
1124
1208
|
const releasePointerCapture = (id) => {
|
|
1125
|
-
|
|
1126
|
-
if (captures) {
|
|
1127
|
-
releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
|
|
1128
|
-
}
|
|
1209
|
+
releaseInternalPointerCapture(internal, hit.eventObject, id);
|
|
1129
1210
|
};
|
|
1130
1211
|
const extractEventProps = {};
|
|
1131
1212
|
for (const prop in event) {
|
|
1132
1213
|
const property = event[prop];
|
|
1133
1214
|
if (typeof property !== "function") extractEventProps[prop] = property;
|
|
1134
1215
|
}
|
|
1216
|
+
const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
|
|
1135
1217
|
const raycastEvent = {
|
|
1136
1218
|
...hit,
|
|
1137
1219
|
...extractEventProps,
|
|
@@ -1142,18 +1224,19 @@ function createEvents(store) {
|
|
|
1142
1224
|
unprojectedPoint,
|
|
1143
1225
|
ray: raycaster.ray,
|
|
1144
1226
|
camera,
|
|
1227
|
+
pointerId: eventPointerId,
|
|
1145
1228
|
// Hijack stopPropagation, which just sets a flag
|
|
1146
1229
|
stopPropagation() {
|
|
1147
|
-
const
|
|
1230
|
+
const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
|
|
1148
1231
|
if (
|
|
1149
1232
|
// ...if this pointer hasn't been captured
|
|
1150
|
-
!
|
|
1151
|
-
|
|
1233
|
+
!pointerState?.captured.size || // ... or if the hit object is capturing the pointer
|
|
1234
|
+
pointerState.captured.has(hit.eventObject)
|
|
1152
1235
|
) {
|
|
1153
1236
|
raycastEvent.stopped = localState.stopped = true;
|
|
1154
|
-
if (
|
|
1237
|
+
if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
|
|
1155
1238
|
const higher = intersections.slice(0, intersections.indexOf(hit));
|
|
1156
|
-
cancelPointer([...higher, hit]);
|
|
1239
|
+
cancelPointer([...higher, hit], eventPointerId);
|
|
1157
1240
|
}
|
|
1158
1241
|
}
|
|
1159
1242
|
},
|
|
@@ -1169,15 +1252,18 @@ function createEvents(store) {
|
|
|
1169
1252
|
}
|
|
1170
1253
|
return intersections;
|
|
1171
1254
|
}
|
|
1172
|
-
function cancelPointer(intersections) {
|
|
1255
|
+
function cancelPointer(intersections, pointerId) {
|
|
1173
1256
|
const { internal } = store.getState();
|
|
1174
|
-
|
|
1257
|
+
const pid = pointerId ?? DEFAULT_POINTER_ID;
|
|
1258
|
+
const pointerState = internal.pointerMap.get(pid);
|
|
1259
|
+
if (!pointerState) return;
|
|
1260
|
+
for (const [hoveredId, hoveredObj] of pointerState.hovered) {
|
|
1175
1261
|
if (!intersections.length || !intersections.find(
|
|
1176
1262
|
(hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
|
|
1177
1263
|
)) {
|
|
1178
1264
|
const eventObject = hoveredObj.eventObject;
|
|
1179
1265
|
const instance = eventObject.__r3f;
|
|
1180
|
-
|
|
1266
|
+
pointerState.hovered.delete(hoveredId);
|
|
1181
1267
|
if (instance?.eventCount) {
|
|
1182
1268
|
const handlers = instance.handlers;
|
|
1183
1269
|
const data = { ...hoveredObj, intersections };
|
|
@@ -1206,41 +1292,118 @@ function createEvents(store) {
|
|
|
1206
1292
|
instance?.handlers.onDropMissed?.(event);
|
|
1207
1293
|
}
|
|
1208
1294
|
}
|
|
1295
|
+
function cleanupPointer(pointerId) {
|
|
1296
|
+
const { internal } = store.getState();
|
|
1297
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1298
|
+
if (pointerState) {
|
|
1299
|
+
for (const [, hoveredObj] of pointerState.hovered) {
|
|
1300
|
+
const eventObject = hoveredObj.eventObject;
|
|
1301
|
+
const instance = eventObject.__r3f;
|
|
1302
|
+
if (instance?.eventCount) {
|
|
1303
|
+
const handlers = instance.handlers;
|
|
1304
|
+
const data = { ...hoveredObj, intersections: [] };
|
|
1305
|
+
handlers.onPointerOut?.(data);
|
|
1306
|
+
handlers.onPointerLeave?.(data);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
internal.pointerMap.delete(pointerId);
|
|
1310
|
+
}
|
|
1311
|
+
internal.pointerDirty.delete(pointerId);
|
|
1312
|
+
}
|
|
1313
|
+
function processDeferredPointer(event, pointerId) {
|
|
1314
|
+
const state = store.getState();
|
|
1315
|
+
const { internal } = state;
|
|
1316
|
+
if (!state.events.enabled) return;
|
|
1317
|
+
const filter = filterPointerEvents;
|
|
1318
|
+
const hits = intersect(event, filter);
|
|
1319
|
+
cancelPointer(hits, pointerId);
|
|
1320
|
+
function onIntersect(data) {
|
|
1321
|
+
const eventObject = data.eventObject;
|
|
1322
|
+
const instance = eventObject.__r3f;
|
|
1323
|
+
if (!instance?.eventCount) return;
|
|
1324
|
+
const handlers = instance.handlers;
|
|
1325
|
+
if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
|
|
1326
|
+
const id = makeId(data);
|
|
1327
|
+
const pointerState = getPointerState(internal, pointerId);
|
|
1328
|
+
const hoveredItem = pointerState.hovered.get(id);
|
|
1329
|
+
if (!hoveredItem) {
|
|
1330
|
+
pointerState.hovered.set(id, data);
|
|
1331
|
+
handlers.onPointerOver?.(data);
|
|
1332
|
+
handlers.onPointerEnter?.(data);
|
|
1333
|
+
} else if (hoveredItem.stopped) {
|
|
1334
|
+
data.stopPropagation();
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
handlers.onPointerMove?.(data);
|
|
1338
|
+
}
|
|
1339
|
+
handleIntersects(hits, event, 0, onIntersect);
|
|
1340
|
+
}
|
|
1209
1341
|
function handlePointer(name) {
|
|
1210
1342
|
switch (name) {
|
|
1211
1343
|
case "onPointerLeave":
|
|
1212
|
-
case "onPointerCancel":
|
|
1213
1344
|
case "onDragLeave":
|
|
1214
1345
|
return () => cancelPointer([]);
|
|
1346
|
+
// Global cancel of these events
|
|
1347
|
+
case "onPointerCancel":
|
|
1348
|
+
return (event) => {
|
|
1349
|
+
const pointerId = getPointerId(event);
|
|
1350
|
+
cleanupPointer(pointerId);
|
|
1351
|
+
};
|
|
1215
1352
|
case "onLostPointerCapture":
|
|
1216
1353
|
return (event) => {
|
|
1217
1354
|
const { internal } = store.getState();
|
|
1218
|
-
|
|
1355
|
+
const pointerId = getPointerId(event);
|
|
1356
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1357
|
+
if (pointerState?.captured.size) {
|
|
1219
1358
|
requestAnimationFrame(() => {
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1359
|
+
const pointerState2 = internal.pointerMap.get(pointerId);
|
|
1360
|
+
if (pointerState2?.captured.size) {
|
|
1361
|
+
pointerState2.captured.clear();
|
|
1223
1362
|
}
|
|
1363
|
+
cancelPointer([], pointerId);
|
|
1224
1364
|
});
|
|
1225
1365
|
}
|
|
1226
1366
|
};
|
|
1227
1367
|
}
|
|
1228
1368
|
return function handleEvent(event) {
|
|
1229
1369
|
const state = store.getState();
|
|
1230
|
-
const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
|
|
1370
|
+
const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
|
|
1371
|
+
const pointerId = getPointerId(event);
|
|
1231
1372
|
internal.lastEvent.current = event;
|
|
1232
|
-
if (!
|
|
1373
|
+
if (!events.enabled) return;
|
|
1233
1374
|
const isPointerMove = name === "onPointerMove";
|
|
1234
1375
|
const isDragOver = name === "onDragOver";
|
|
1235
1376
|
const isDrop = name === "onDrop";
|
|
1236
1377
|
const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
|
|
1378
|
+
const isPointerDown = name === "onPointerDown";
|
|
1379
|
+
const isPointerUp = name === "onPointerUp";
|
|
1380
|
+
const isWheel = name === "onWheel";
|
|
1381
|
+
const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
|
|
1382
|
+
if (isPointerMove && canDeferRaycasts) {
|
|
1383
|
+
events.compute?.(event, state);
|
|
1384
|
+
internal.pointerDirty.set(pointerId, event);
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
|
|
1388
|
+
events.compute?.(event, state);
|
|
1389
|
+
internal.pointerDirty.set(pointerId, event);
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
|
|
1393
|
+
const deferredEvent = internal.pointerDirty.get(pointerId);
|
|
1394
|
+
internal.pointerDirty.delete(pointerId);
|
|
1395
|
+
processDeferredPointer(deferredEvent, pointerId);
|
|
1396
|
+
}
|
|
1237
1397
|
const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
|
|
1238
1398
|
const hits = intersect(event, filter);
|
|
1239
|
-
const delta = isClickEvent ? calculateDistance(event) : 0;
|
|
1240
|
-
if (
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1399
|
+
const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
|
|
1400
|
+
if (isPointerDown) {
|
|
1401
|
+
const pointerState2 = getPointerState(internal, pointerId);
|
|
1402
|
+
pointerState2.initialClick = [event.offsetX, event.offsetY];
|
|
1403
|
+
pointerState2.initialHits = hits.map((hit) => hit.eventObject);
|
|
1404
|
+
}
|
|
1405
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1406
|
+
const initialHits = pointerState?.initialHits ?? [];
|
|
1244
1407
|
if (isClickEvent && !hits.length) {
|
|
1245
1408
|
if (delta <= 2) {
|
|
1246
1409
|
pointerMissed(event, internal.interaction);
|
|
@@ -1255,7 +1418,9 @@ function createEvents(store) {
|
|
|
1255
1418
|
dropMissed(event, internal.interaction);
|
|
1256
1419
|
if (onDropMissed) onDropMissed(event);
|
|
1257
1420
|
}
|
|
1258
|
-
if (isPointerMove || isDragOver)
|
|
1421
|
+
if (isPointerMove || isDragOver) {
|
|
1422
|
+
cancelPointer(hits, pointerId);
|
|
1423
|
+
}
|
|
1259
1424
|
function onIntersect(data) {
|
|
1260
1425
|
const eventObject = data.eventObject;
|
|
1261
1426
|
const instance = eventObject.__r3f;
|
|
@@ -1264,9 +1429,10 @@ function createEvents(store) {
|
|
|
1264
1429
|
if (isPointerMove) {
|
|
1265
1430
|
if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
|
|
1266
1431
|
const id = makeId(data);
|
|
1267
|
-
const
|
|
1432
|
+
const pointerState2 = getPointerState(internal, pointerId);
|
|
1433
|
+
const hoveredItem = pointerState2.hovered.get(id);
|
|
1268
1434
|
if (!hoveredItem) {
|
|
1269
|
-
|
|
1435
|
+
pointerState2.hovered.set(id, data);
|
|
1270
1436
|
handlers.onPointerOver?.(data);
|
|
1271
1437
|
handlers.onPointerEnter?.(data);
|
|
1272
1438
|
} else if (hoveredItem.stopped) {
|
|
@@ -1276,9 +1442,10 @@ function createEvents(store) {
|
|
|
1276
1442
|
handlers.onPointerMove?.(data);
|
|
1277
1443
|
} else if (isDragOver) {
|
|
1278
1444
|
const id = makeId(data);
|
|
1279
|
-
const
|
|
1445
|
+
const pointerState2 = getPointerState(internal, pointerId);
|
|
1446
|
+
const hoveredItem = pointerState2.hovered.get(id);
|
|
1280
1447
|
if (!hoveredItem) {
|
|
1281
|
-
|
|
1448
|
+
pointerState2.hovered.set(id, data);
|
|
1282
1449
|
handlers.onDragOverEnter?.(data);
|
|
1283
1450
|
} else if (hoveredItem.stopped) {
|
|
1284
1451
|
data.stopPropagation();
|
|
@@ -1289,18 +1456,18 @@ function createEvents(store) {
|
|
|
1289
1456
|
} else {
|
|
1290
1457
|
const handler = handlers[name];
|
|
1291
1458
|
if (handler) {
|
|
1292
|
-
if (!isClickEvent ||
|
|
1459
|
+
if (!isClickEvent || initialHits.includes(eventObject)) {
|
|
1293
1460
|
pointerMissed(
|
|
1294
1461
|
event,
|
|
1295
|
-
internal.interaction.filter((object) => !
|
|
1462
|
+
internal.interaction.filter((object) => !initialHits.includes(object))
|
|
1296
1463
|
);
|
|
1297
1464
|
handler(data);
|
|
1298
1465
|
}
|
|
1299
1466
|
} else {
|
|
1300
|
-
if (isClickEvent &&
|
|
1467
|
+
if (isClickEvent && initialHits.includes(eventObject)) {
|
|
1301
1468
|
pointerMissed(
|
|
1302
1469
|
event,
|
|
1303
|
-
internal.interaction.filter((object) => !
|
|
1470
|
+
internal.interaction.filter((object) => !initialHits.includes(object))
|
|
1304
1471
|
);
|
|
1305
1472
|
}
|
|
1306
1473
|
}
|
|
@@ -1309,7 +1476,15 @@ function createEvents(store) {
|
|
|
1309
1476
|
handleIntersects(hits, event, delta, onIntersect);
|
|
1310
1477
|
};
|
|
1311
1478
|
}
|
|
1312
|
-
|
|
1479
|
+
function flushDeferredPointers() {
|
|
1480
|
+
const { internal, events } = store.getState();
|
|
1481
|
+
if (!events.frameTimedRaycasts) return;
|
|
1482
|
+
for (const [pointerId, event] of internal.pointerDirty) {
|
|
1483
|
+
processDeferredPointer(event, pointerId);
|
|
1484
|
+
}
|
|
1485
|
+
internal.pointerDirty.clear();
|
|
1486
|
+
}
|
|
1487
|
+
return { handlePointer, flushDeferredPointers, processDeferredPointer };
|
|
1313
1488
|
}
|
|
1314
1489
|
const DOM_EVENTS = {
|
|
1315
1490
|
onClick: ["click", false],
|
|
@@ -1328,10 +1503,15 @@ const DOM_EVENTS = {
|
|
|
1328
1503
|
onLostPointerCapture: ["lostpointercapture", true]
|
|
1329
1504
|
};
|
|
1330
1505
|
function createPointerEvents(store) {
|
|
1331
|
-
const { handlePointer } = createEvents(store);
|
|
1506
|
+
const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
|
|
1507
|
+
let nextXRPointerId = XR_POINTER_ID_START;
|
|
1508
|
+
const xrPointers = /* @__PURE__ */ new Map();
|
|
1332
1509
|
return {
|
|
1333
1510
|
priority: 1,
|
|
1334
1511
|
enabled: true,
|
|
1512
|
+
frameTimedRaycasts: true,
|
|
1513
|
+
alwaysFireOnScroll: true,
|
|
1514
|
+
updateOnFrame: false,
|
|
1335
1515
|
compute(event, state) {
|
|
1336
1516
|
state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
|
|
1337
1517
|
state.raycaster.setFromCamera(state.pointer, state.camera);
|
|
@@ -1341,11 +1521,33 @@ function createPointerEvents(store) {
|
|
|
1341
1521
|
(acc, key) => ({ ...acc, [key]: handlePointer(key) }),
|
|
1342
1522
|
{}
|
|
1343
1523
|
),
|
|
1344
|
-
update: () => {
|
|
1524
|
+
update: (pointerId) => {
|
|
1345
1525
|
const { events, internal } = store.getState();
|
|
1346
|
-
if (
|
|
1526
|
+
if (!events.handlers) return;
|
|
1527
|
+
if (pointerId !== void 0) {
|
|
1528
|
+
const event = internal.pointerDirty.get(pointerId);
|
|
1529
|
+
if (event) {
|
|
1530
|
+
internal.pointerDirty.delete(pointerId);
|
|
1531
|
+
processDeferredPointer(event, pointerId);
|
|
1532
|
+
} else if (internal.lastEvent?.current) {
|
|
1533
|
+
processDeferredPointer(internal.lastEvent.current, pointerId);
|
|
1534
|
+
}
|
|
1535
|
+
} else {
|
|
1536
|
+
flushDeferredPointers();
|
|
1537
|
+
if (internal.lastEvent?.current) {
|
|
1538
|
+
events.handlers.onPointerMove(internal.lastEvent.current);
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
},
|
|
1542
|
+
flush: () => {
|
|
1543
|
+
const { events, internal } = store.getState();
|
|
1544
|
+
flushDeferredPointers();
|
|
1545
|
+
if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
|
|
1546
|
+
events.handlers.onPointerMove(internal.lastEvent.current);
|
|
1547
|
+
}
|
|
1347
1548
|
},
|
|
1348
1549
|
connect: (target) => {
|
|
1550
|
+
if (!target) return;
|
|
1349
1551
|
const { set, events } = store.getState();
|
|
1350
1552
|
events.disconnect?.();
|
|
1351
1553
|
set((state) => ({ events: { ...state.events, connected: target } }));
|
|
@@ -1369,6 +1571,33 @@ function createPointerEvents(store) {
|
|
|
1369
1571
|
}
|
|
1370
1572
|
set((state) => ({ events: { ...state.events, connected: void 0 } }));
|
|
1371
1573
|
}
|
|
1574
|
+
},
|
|
1575
|
+
// PREVIEW (A8): the XR pointer registration API may change before stable.
|
|
1576
|
+
registerPointer: (config) => {
|
|
1577
|
+
const pointerId = nextXRPointerId++;
|
|
1578
|
+
xrPointers.set(pointerId, config);
|
|
1579
|
+
const { internal } = store.getState();
|
|
1580
|
+
getPointerState(internal, pointerId);
|
|
1581
|
+
return pointerId;
|
|
1582
|
+
},
|
|
1583
|
+
unregisterPointer: (pointerId) => {
|
|
1584
|
+
xrPointers.delete(pointerId);
|
|
1585
|
+
const { internal } = store.getState();
|
|
1586
|
+
const pointerState = internal.pointerMap.get(pointerId);
|
|
1587
|
+
if (pointerState) {
|
|
1588
|
+
for (const [, hoveredObj] of pointerState.hovered) {
|
|
1589
|
+
const eventObject = hoveredObj.eventObject;
|
|
1590
|
+
const instance = eventObject.__r3f;
|
|
1591
|
+
if (instance?.eventCount) {
|
|
1592
|
+
const handlers = instance.handlers;
|
|
1593
|
+
const data = { ...hoveredObj, intersections: [] };
|
|
1594
|
+
handlers.onPointerOut?.(data);
|
|
1595
|
+
handlers.onPointerLeave?.(data);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
internal.pointerMap.delete(pointerId);
|
|
1599
|
+
}
|
|
1600
|
+
internal.pointerDirty.delete(pointerId);
|
|
1372
1601
|
}
|
|
1373
1602
|
};
|
|
1374
1603
|
}
|
|
@@ -1430,1036 +1659,11 @@ function notifyAlpha({ message, link }) {
|
|
|
1430
1659
|
}
|
|
1431
1660
|
}
|
|
1432
1661
|
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
const
|
|
1437
|
-
|
|
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?.();
|
|
1662
|
+
const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
|
|
1663
|
+
function isInternalRendererAccess(stack, callerDepth = 2) {
|
|
1664
|
+
if (!stack) return false;
|
|
1665
|
+
const caller = stack.split("\n")[callerDepth] ?? "";
|
|
1666
|
+
return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
|
|
2463
1667
|
}
|
|
2464
1668
|
|
|
2465
1669
|
const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
|
|
@@ -2499,7 +1703,14 @@ const createStore = (invalidate, advance) => {
|
|
|
2499
1703
|
frustum: new Frustum(),
|
|
2500
1704
|
autoUpdateFrustum: true,
|
|
2501
1705
|
raycaster: null,
|
|
2502
|
-
events: {
|
|
1706
|
+
events: {
|
|
1707
|
+
priority: 1,
|
|
1708
|
+
enabled: true,
|
|
1709
|
+
connected: false,
|
|
1710
|
+
frameTimedRaycasts: true,
|
|
1711
|
+
alwaysFireOnScroll: true,
|
|
1712
|
+
updateOnFrame: false
|
|
1713
|
+
},
|
|
2503
1714
|
scene: null,
|
|
2504
1715
|
rootScene: null,
|
|
2505
1716
|
xr: null,
|
|
@@ -2587,14 +1798,18 @@ const createStore = (invalidate, advance) => {
|
|
|
2587
1798
|
}),
|
|
2588
1799
|
setFrameloop: (frameloop = "always") => {
|
|
2589
1800
|
set(() => ({ frameloop }));
|
|
1801
|
+
getScheduler().frameloop = frameloop;
|
|
2590
1802
|
},
|
|
2591
1803
|
setError: (error) => set(() => ({ error })),
|
|
2592
1804
|
error: null,
|
|
2593
|
-
//* TSL State (managed via hooks: useUniforms, useNodes, useTextures,
|
|
1805
|
+
//* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
|
|
2594
1806
|
uniforms: {},
|
|
2595
1807
|
nodes: {},
|
|
1808
|
+
buffers: {},
|
|
1809
|
+
gpuStorage: {},
|
|
2596
1810
|
textures: /* @__PURE__ */ new Map(),
|
|
2597
|
-
|
|
1811
|
+
_textureRefs: /* @__PURE__ */ new Map(),
|
|
1812
|
+
renderPipeline: null,
|
|
2598
1813
|
passes: {},
|
|
2599
1814
|
_hmrVersion: 0,
|
|
2600
1815
|
_sizeImperative: false,
|
|
@@ -2603,12 +1818,16 @@ const createStore = (invalidate, advance) => {
|
|
|
2603
1818
|
internal: {
|
|
2604
1819
|
// Events
|
|
2605
1820
|
interaction: [],
|
|
2606
|
-
hovered: /* @__PURE__ */ new Map(),
|
|
2607
1821
|
subscribers: [],
|
|
1822
|
+
// Per-pointer state (new unified structure)
|
|
1823
|
+
pointerMap: /* @__PURE__ */ new Map(),
|
|
1824
|
+
pointerDirty: /* @__PURE__ */ new Map(),
|
|
1825
|
+
lastEvent: React.createRef(),
|
|
1826
|
+
// Deprecated but kept for backwards compatibility
|
|
1827
|
+
hovered: /* @__PURE__ */ new Map(),
|
|
2608
1828
|
initialClick: [0, 0],
|
|
2609
1829
|
initialHits: [],
|
|
2610
1830
|
capturedMap: /* @__PURE__ */ new Map(),
|
|
2611
|
-
lastEvent: React.createRef(),
|
|
2612
1831
|
// Visibility tracking (onFramed, onOccluded, onVisible)
|
|
2613
1832
|
visibilityRegistry: /* @__PURE__ */ new Map(),
|
|
2614
1833
|
// Occlusion system (WebGPU only)
|
|
@@ -2647,8 +1866,7 @@ const createStore = (invalidate, advance) => {
|
|
|
2647
1866
|
const currentState = rootStore.getState();
|
|
2648
1867
|
if (!currentState.isLegacy && currentState.internal.actualRenderer) {
|
|
2649
1868
|
const stack = new Error().stack || "";
|
|
2650
|
-
|
|
2651
|
-
if (!isInternalAccess) {
|
|
1869
|
+
if (!isInternalRendererAccess(stack)) {
|
|
2652
1870
|
const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
|
|
2653
1871
|
notifyDepreciated({
|
|
2654
1872
|
heading: "Accessing state.gl in WebGPU mode",
|
|
@@ -2696,14 +1914,16 @@ const createStore = (invalidate, advance) => {
|
|
|
2696
1914
|
oldSize = size;
|
|
2697
1915
|
oldDpr = viewport.dpr;
|
|
2698
1916
|
updateCamera(camera, size);
|
|
2699
|
-
if (canvasTarget) {
|
|
1917
|
+
if (internal.isSecondary && canvasTarget) {
|
|
2700
1918
|
if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
|
|
2701
|
-
|
|
2702
|
-
canvasTarget.setSize(size.width, size.height, updateStyle);
|
|
1919
|
+
canvasTarget.setSize(size.width, size.height, false);
|
|
2703
1920
|
} else {
|
|
2704
1921
|
if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
|
|
2705
|
-
|
|
2706
|
-
|
|
1922
|
+
actualRenderer.setSize(size.width, size.height, false);
|
|
1923
|
+
if (canvasTarget) {
|
|
1924
|
+
if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
|
|
1925
|
+
canvasTarget.setSize(size.width, size.height, false);
|
|
1926
|
+
}
|
|
2707
1927
|
}
|
|
2708
1928
|
}
|
|
2709
1929
|
if (camera !== oldCamera) {
|
|
@@ -2759,19 +1979,25 @@ function loadingFn(extensions, onProgress) {
|
|
|
2759
1979
|
);
|
|
2760
1980
|
};
|
|
2761
1981
|
}
|
|
2762
|
-
function useLoader(loader, input, extensions, onProgress) {
|
|
2763
|
-
const
|
|
1982
|
+
function useLoader(loader, input, extensions, onProgress, cacheKey) {
|
|
1983
|
+
const inputs = Array.isArray(input) ? input : [input];
|
|
1984
|
+
const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
|
|
2764
1985
|
const fn = loadingFn(extensions, onProgress);
|
|
2765
|
-
const results =
|
|
1986
|
+
const results = cacheKeys.map(
|
|
1987
|
+
(key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
|
|
1988
|
+
);
|
|
2766
1989
|
return Array.isArray(input) ? results : results[0];
|
|
2767
1990
|
}
|
|
2768
|
-
useLoader.preload = function(loader, input, extensions, onProgress) {
|
|
2769
|
-
const
|
|
2770
|
-
|
|
1991
|
+
useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
|
|
1992
|
+
const inputs = Array.isArray(input) ? input : [input];
|
|
1993
|
+
const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
|
|
1994
|
+
cacheKeys.forEach(
|
|
1995
|
+
(key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
|
|
1996
|
+
);
|
|
2771
1997
|
};
|
|
2772
|
-
useLoader.clear = function(loader, input) {
|
|
2773
|
-
const
|
|
2774
|
-
|
|
1998
|
+
useLoader.clear = function(loader, input, cacheKey) {
|
|
1999
|
+
const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
|
|
2000
|
+
cacheKeys.forEach((key) => clear([loader, key]));
|
|
2775
2001
|
};
|
|
2776
2002
|
useLoader.loader = getLoader;
|
|
2777
2003
|
|
|
@@ -2847,20 +2073,14 @@ function useFrame(callback, priorityOrOptions) {
|
|
|
2847
2073
|
}
|
|
2848
2074
|
};
|
|
2849
2075
|
} else {
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
unregisterJob = registerOutside();
|
|
2859
|
-
});
|
|
2860
|
-
return () => {
|
|
2861
|
-
unsubReady();
|
|
2862
|
-
unregisterJob?.();
|
|
2863
|
-
};
|
|
2076
|
+
return scheduler.register(
|
|
2077
|
+
(state, delta) => {
|
|
2078
|
+
const frameState = state;
|
|
2079
|
+
if (!frameState.renderer) return;
|
|
2080
|
+
callbackRef.current?.(frameState, delta);
|
|
2081
|
+
},
|
|
2082
|
+
{ id, ...options }
|
|
2083
|
+
);
|
|
2864
2084
|
}
|
|
2865
2085
|
}, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
|
|
2866
2086
|
const isPaused = React.useSyncExternalStore(
|
|
@@ -2951,18 +2171,18 @@ function buildFromCache(input, textureCache) {
|
|
|
2951
2171
|
function useTexture(input, optionsOrOnLoad) {
|
|
2952
2172
|
const renderer = useThree((state) => state.internal.actualRenderer);
|
|
2953
2173
|
const store = useStore();
|
|
2954
|
-
const textureCache = useThree((state) => state.textures);
|
|
2955
2174
|
const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
|
|
2956
|
-
const { onLoad, cache =
|
|
2175
|
+
const { onLoad, cache = true } = options;
|
|
2957
2176
|
const onLoadRef = useRef(onLoad);
|
|
2958
2177
|
onLoadRef.current = onLoad;
|
|
2959
2178
|
const onLoadCalledForRef = useRef(null);
|
|
2960
2179
|
const urls = useMemo(() => getUrls(input), [input]);
|
|
2961
2180
|
const cachedResult = useMemo(() => {
|
|
2962
2181
|
if (!cache) return null;
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2182
|
+
const textures = store.getState().textures;
|
|
2183
|
+
if (!allUrlsCached(urls, textures)) return null;
|
|
2184
|
+
return buildFromCache(input, textures);
|
|
2185
|
+
}, [cache, urls, input, store]);
|
|
2966
2186
|
const loadedTextures = useLoader(
|
|
2967
2187
|
TextureLoader,
|
|
2968
2188
|
IsObject(input) ? Object.values(input) : input
|
|
@@ -3006,8 +2226,6 @@ function useTexture(input, optionsOrOnLoad) {
|
|
|
3006
2226
|
}, [input, loadedTextures, cachedResult]);
|
|
3007
2227
|
useEffect(() => {
|
|
3008
2228
|
if (!cache) return;
|
|
3009
|
-
if (cachedResult) return;
|
|
3010
|
-
const set = store.setState;
|
|
3011
2229
|
const urlTextureMap = [];
|
|
3012
2230
|
if (typeof input === "string") {
|
|
3013
2231
|
urlTextureMap.push([input, mappedTextures]);
|
|
@@ -3021,18 +2239,32 @@ function useTexture(input, optionsOrOnLoad) {
|
|
|
3021
2239
|
urlTextureMap.push([url, textureRecord[key]]);
|
|
3022
2240
|
}
|
|
3023
2241
|
}
|
|
3024
|
-
|
|
3025
|
-
const
|
|
3026
|
-
let
|
|
2242
|
+
store.setState((state) => {
|
|
2243
|
+
const refs = new Map(state._textureRefs);
|
|
2244
|
+
let textures = state.textures;
|
|
2245
|
+
let added = false;
|
|
3027
2246
|
for (const [url, texture] of urlTextureMap) {
|
|
3028
|
-
if (!
|
|
3029
|
-
|
|
3030
|
-
|
|
2247
|
+
if (!textures.has(url)) {
|
|
2248
|
+
if (!added) {
|
|
2249
|
+
textures = new Map(textures);
|
|
2250
|
+
added = true;
|
|
2251
|
+
}
|
|
2252
|
+
textures.set(url, texture);
|
|
3031
2253
|
}
|
|
2254
|
+
refs.set(url, (refs.get(url) ?? 0) + 1);
|
|
3032
2255
|
}
|
|
3033
|
-
return
|
|
2256
|
+
return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
|
|
3034
2257
|
});
|
|
3035
|
-
|
|
2258
|
+
return () => store.setState((state) => {
|
|
2259
|
+
const refs = new Map(state._textureRefs);
|
|
2260
|
+
for (const [url] of urlTextureMap) {
|
|
2261
|
+
const next = (refs.get(url) ?? 0) - 1;
|
|
2262
|
+
if (next <= 0) refs.delete(url);
|
|
2263
|
+
else refs.set(url, next);
|
|
2264
|
+
}
|
|
2265
|
+
return { _textureRefs: refs };
|
|
2266
|
+
});
|
|
2267
|
+
}, [cache, input, mappedTextures, store]);
|
|
3036
2268
|
return mappedTextures;
|
|
3037
2269
|
}
|
|
3038
2270
|
useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
|
|
@@ -3048,96 +2280,63 @@ const Texture = ({
|
|
|
3048
2280
|
return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
|
|
3049
2281
|
};
|
|
3050
2282
|
|
|
3051
|
-
function
|
|
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() {
|
|
2283
|
+
function useTextures(selector) {
|
|
3059
2284
|
const store = useStore();
|
|
3060
|
-
|
|
3061
|
-
const set = store.setState;
|
|
2285
|
+
const registry = useMemo(() => {
|
|
3062
2286
|
const getState = store.getState;
|
|
3063
|
-
const
|
|
3064
|
-
|
|
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
|
-
};
|
|
2287
|
+
const setState = store.setState;
|
|
2288
|
+
const getOne = (key) => getState().textures.get(key);
|
|
3121
2289
|
return {
|
|
3122
|
-
|
|
3123
|
-
get textures() {
|
|
2290
|
+
get all() {
|
|
3124
2291
|
return getState().textures;
|
|
3125
2292
|
},
|
|
3126
|
-
|
|
3127
|
-
|
|
2293
|
+
get(input) {
|
|
2294
|
+
if (typeof input === "string") return getOne(input);
|
|
2295
|
+
if (Array.isArray(input)) return input.map(getOne);
|
|
2296
|
+
const out = {};
|
|
2297
|
+
for (const name in input) out[name] = getOne(input[name]);
|
|
2298
|
+
return out;
|
|
2299
|
+
},
|
|
3128
2300
|
has: (key) => getState().textures.has(key),
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
2301
|
+
add(keyOrRecord, texture) {
|
|
2302
|
+
setState((state) => {
|
|
2303
|
+
const textures = new Map(state.textures);
|
|
2304
|
+
if (typeof keyOrRecord === "string") {
|
|
2305
|
+
textures.set(keyOrRecord, texture);
|
|
2306
|
+
} else {
|
|
2307
|
+
for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
|
|
2308
|
+
}
|
|
2309
|
+
return { textures };
|
|
2310
|
+
});
|
|
2311
|
+
},
|
|
2312
|
+
dispose(key, options) {
|
|
2313
|
+
const state = getState();
|
|
2314
|
+
const refs = state._textureRefs.get(key) ?? 0;
|
|
2315
|
+
if (refs > 0 && !options?.force) {
|
|
2316
|
+
console.warn(
|
|
2317
|
+
`[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
|
|
2318
|
+
);
|
|
2319
|
+
return false;
|
|
2320
|
+
}
|
|
2321
|
+
state.textures.get(key)?.dispose();
|
|
2322
|
+
setState((s) => {
|
|
2323
|
+
const textures = new Map(s.textures);
|
|
2324
|
+
textures.delete(key);
|
|
2325
|
+
const nextRefs = new Map(s._textureRefs);
|
|
2326
|
+
nextRefs.delete(key);
|
|
2327
|
+
return { textures, _textureRefs: nextRefs };
|
|
2328
|
+
});
|
|
2329
|
+
return true;
|
|
2330
|
+
},
|
|
2331
|
+
disposeAll() {
|
|
2332
|
+
for (const texture of getState().textures.values()) texture.dispose();
|
|
2333
|
+
setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
|
|
2334
|
+
}
|
|
3139
2335
|
};
|
|
3140
2336
|
}, [store]);
|
|
2337
|
+
const subscribe = selector ? () => selector(registry) : (state) => state.textures;
|
|
2338
|
+
const selected = useThree(subscribe);
|
|
2339
|
+
return selector ? selected : registry;
|
|
3141
2340
|
}
|
|
3142
2341
|
|
|
3143
2342
|
function useRenderTarget(widthOrOptions, heightOrOptions, options) {
|
|
@@ -3220,7 +2419,7 @@ function advance(timestamp) {
|
|
|
3220
2419
|
getScheduler().step(timestamp);
|
|
3221
2420
|
}
|
|
3222
2421
|
|
|
3223
|
-
const version = "10.0.0-alpha.
|
|
2422
|
+
const version = "10.0.0-alpha.3";
|
|
3224
2423
|
const packageData = {
|
|
3225
2424
|
version: version};
|
|
3226
2425
|
|
|
@@ -14659,6 +13858,7 @@ function swapInstances() {
|
|
|
14659
13858
|
}
|
|
14660
13859
|
}
|
|
14661
13860
|
if (instance.isHidden) unhideInstance(instance);
|
|
13861
|
+
if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
|
|
14662
13862
|
if (instance.object.__r3f) delete instance.object.__r3f;
|
|
14663
13863
|
if (instance.type !== "primitive") disposeOnIdle(instance.object);
|
|
14664
13864
|
}
|
|
@@ -14671,6 +13871,8 @@ function swapInstances() {
|
|
|
14671
13871
|
instance.object.__r3f = instance;
|
|
14672
13872
|
setFiberRef(fiber, instance.object);
|
|
14673
13873
|
delete instance.appliedOnce;
|
|
13874
|
+
instance.eventCount = 0;
|
|
13875
|
+
instance.handlers = {};
|
|
14674
13876
|
applyProps(instance.object, instance.props);
|
|
14675
13877
|
if (instance.props.attach) {
|
|
14676
13878
|
attach(parent, instance);
|
|
@@ -14886,11 +14088,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
|
|
|
14886
14088
|
cloneMutableTextInstance(textInstance) {
|
|
14887
14089
|
return textInstance;
|
|
14888
14090
|
},
|
|
14091
|
+
// React 19.2 added these for root-level view transitions. They only run for hosts that opt into
|
|
14092
|
+
// view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
|
|
14093
|
+
// into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
|
|
14094
|
+
// React never calls them. They stay as no-ops rather than throws: the host config is shared by
|
|
14095
|
+
// every root, and a throw here would turn a React-internal probe into a hard crash for users.
|
|
14096
|
+
// Guarded by a test asserting a full render + unmount never reaches them.
|
|
14889
14097
|
cloneRootViewTransitionContainer(_rootContainer) {
|
|
14890
|
-
throw new Error("Not implemented.");
|
|
14891
14098
|
},
|
|
14892
14099
|
removeRootViewTransitionClone(_rootContainer, _clone) {
|
|
14893
|
-
throw new Error("Not implemented.");
|
|
14894
14100
|
},
|
|
14895
14101
|
// https://github.com/facebook/react/pull/32465
|
|
14896
14102
|
createFragmentInstance: (_fiber) => null,
|
|
@@ -14975,6 +14181,7 @@ function createRoot(canvas) {
|
|
|
14975
14181
|
const lastConfiguredProps = {};
|
|
14976
14182
|
let configured = false;
|
|
14977
14183
|
let pending = null;
|
|
14184
|
+
let rendererSetup = null;
|
|
14978
14185
|
return {
|
|
14979
14186
|
async configure(props = {}) {
|
|
14980
14187
|
let resolve;
|
|
@@ -14990,7 +14197,6 @@ function createRoot(canvas) {
|
|
|
14990
14197
|
events,
|
|
14991
14198
|
onCreated: onCreatedCallback,
|
|
14992
14199
|
shadows = false,
|
|
14993
|
-
textureColorSpace = SRGBColorSpace,
|
|
14994
14200
|
orthographic = false,
|
|
14995
14201
|
frameloop = "always",
|
|
14996
14202
|
dpr = [1, 2],
|
|
@@ -15005,7 +14211,8 @@ function createRoot(canvas) {
|
|
|
15005
14211
|
_sizeProps,
|
|
15006
14212
|
forceEven
|
|
15007
14213
|
} = props;
|
|
15008
|
-
const
|
|
14214
|
+
const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
|
|
14215
|
+
let state = store.getState();
|
|
15009
14216
|
const defaultGLProps = {
|
|
15010
14217
|
canvas,
|
|
15011
14218
|
powerPreference: "high-performance",
|
|
@@ -15033,50 +14240,68 @@ function createRoot(canvas) {
|
|
|
15033
14240
|
"The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
|
|
15034
14241
|
);
|
|
15035
14242
|
}
|
|
15036
|
-
if (
|
|
15037
|
-
|
|
15038
|
-
|
|
15039
|
-
|
|
15040
|
-
|
|
15041
|
-
|
|
15042
|
-
|
|
15043
|
-
|
|
15044
|
-
|
|
15045
|
-
|
|
15046
|
-
|
|
15047
|
-
|
|
15048
|
-
|
|
15049
|
-
|
|
15050
|
-
|
|
15051
|
-
|
|
15052
|
-
|
|
15053
|
-
|
|
15054
|
-
|
|
15055
|
-
|
|
15056
|
-
|
|
15057
|
-
|
|
15058
|
-
|
|
15059
|
-
|
|
15060
|
-
|
|
15061
|
-
|
|
15062
|
-
|
|
15063
|
-
|
|
15064
|
-
|
|
15065
|
-
|
|
15066
|
-
|
|
15067
|
-
|
|
15068
|
-
|
|
15069
|
-
|
|
15070
|
-
|
|
15071
|
-
|
|
15072
|
-
|
|
15073
|
-
|
|
15074
|
-
|
|
15075
|
-
|
|
15076
|
-
|
|
14243
|
+
if (!state.internal.actualRenderer) {
|
|
14244
|
+
if (!rendererSetup) {
|
|
14245
|
+
rendererSetup = (async () => {
|
|
14246
|
+
if (wantsGL) {
|
|
14247
|
+
renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
|
|
14248
|
+
state.internal.actualRenderer = renderer;
|
|
14249
|
+
state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
|
|
14250
|
+
} else if (!wantsGL && primaryCanvas) {
|
|
14251
|
+
const primary = await waitForPrimary(primaryCanvas);
|
|
14252
|
+
renderer = primary.renderer;
|
|
14253
|
+
state.internal.actualRenderer = renderer;
|
|
14254
|
+
const canvasTarget = new CanvasTarget(canvas);
|
|
14255
|
+
primary.store.setState((prev) => ({
|
|
14256
|
+
internal: { ...prev.internal, isMultiCanvas: true }
|
|
14257
|
+
}));
|
|
14258
|
+
state.set((prev) => ({
|
|
14259
|
+
webGPUSupported: primary.store.getState().webGPUSupported,
|
|
14260
|
+
renderer,
|
|
14261
|
+
primaryStore: primary.store,
|
|
14262
|
+
internal: {
|
|
14263
|
+
...prev.internal,
|
|
14264
|
+
canvasTarget,
|
|
14265
|
+
isMultiCanvas: true,
|
|
14266
|
+
isSecondary: true,
|
|
14267
|
+
targetId: primaryCanvas
|
|
14268
|
+
}
|
|
14269
|
+
}));
|
|
14270
|
+
} else if (!wantsGL) {
|
|
14271
|
+
renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
|
|
14272
|
+
if (!renderer.hasInitialized?.()) {
|
|
14273
|
+
const size2 = computeInitialSize(canvas, propsSize);
|
|
14274
|
+
if (size2.width > 0 && size2.height > 0) {
|
|
14275
|
+
const pixelRatio = calculateDpr(dpr);
|
|
14276
|
+
canvas.width = size2.width * pixelRatio;
|
|
14277
|
+
canvas.height = size2.height * pixelRatio;
|
|
14278
|
+
}
|
|
14279
|
+
await renderer.init();
|
|
14280
|
+
}
|
|
14281
|
+
const backend = renderer.backend;
|
|
14282
|
+
const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
|
|
14283
|
+
state.internal.actualRenderer = renderer;
|
|
14284
|
+
state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
|
|
14285
|
+
if (canvasId && !state.internal.isSecondary) {
|
|
14286
|
+
const canvasTarget = new CanvasTarget(canvas);
|
|
14287
|
+
const unregisterPrimary = registerPrimary(canvasId, renderer, store);
|
|
14288
|
+
state.set((prev) => ({
|
|
14289
|
+
internal: {
|
|
14290
|
+
...prev.internal,
|
|
14291
|
+
canvasTarget,
|
|
14292
|
+
unregisterPrimary
|
|
14293
|
+
}
|
|
14294
|
+
}));
|
|
14295
|
+
}
|
|
15077
14296
|
}
|
|
15078
|
-
}))
|
|
14297
|
+
})().catch((err) => {
|
|
14298
|
+
rendererSetup = null;
|
|
14299
|
+
throw err;
|
|
14300
|
+
});
|
|
15079
14301
|
}
|
|
14302
|
+
await rendererSetup;
|
|
14303
|
+
state = store.getState();
|
|
14304
|
+
renderer = state.internal.actualRenderer;
|
|
15080
14305
|
}
|
|
15081
14306
|
let raycaster = state.raycaster;
|
|
15082
14307
|
if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
|
|
@@ -15169,7 +14394,7 @@ function createRoot(canvas) {
|
|
|
15169
14394
|
lastConfiguredProps.performance = performance;
|
|
15170
14395
|
}
|
|
15171
14396
|
if (!state.xr) {
|
|
15172
|
-
const handleXRFrame = (timestamp,
|
|
14397
|
+
const handleXRFrame = (timestamp, _frame) => {
|
|
15173
14398
|
const state2 = store.getState();
|
|
15174
14399
|
if (state2.frameloop === "never") return;
|
|
15175
14400
|
advance(timestamp);
|
|
@@ -15205,15 +14430,22 @@ function createRoot(canvas) {
|
|
|
15205
14430
|
const oldType = renderer.shadowMap.type;
|
|
15206
14431
|
renderer.shadowMap.enabled = !!shadows;
|
|
15207
14432
|
if (is.boo(shadows)) {
|
|
15208
|
-
renderer.shadowMap.type =
|
|
14433
|
+
renderer.shadowMap.type = PCFShadowMap;
|
|
15209
14434
|
} else if (is.str(shadows)) {
|
|
14435
|
+
if (shadows === "soft") {
|
|
14436
|
+
notifyDepreciated({
|
|
14437
|
+
heading: 'shadows="soft" is deprecated',
|
|
14438
|
+
body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
|
|
14439
|
+
link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
|
|
14440
|
+
});
|
|
14441
|
+
}
|
|
15210
14442
|
const types = {
|
|
15211
14443
|
basic: BasicShadowMap,
|
|
15212
14444
|
percentage: PCFShadowMap,
|
|
15213
|
-
soft:
|
|
14445
|
+
soft: PCFShadowMap,
|
|
15214
14446
|
variance: VSMShadowMap
|
|
15215
14447
|
};
|
|
15216
|
-
renderer.shadowMap.type = types[shadows] ??
|
|
14448
|
+
renderer.shadowMap.type = types[shadows] ?? PCFShadowMap;
|
|
15217
14449
|
} else if (is.obj(shadows)) {
|
|
15218
14450
|
Object.assign(renderer.shadowMap, shadows);
|
|
15219
14451
|
}
|
|
@@ -15229,13 +14461,24 @@ function createRoot(canvas) {
|
|
|
15229
14461
|
if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
|
|
15230
14462
|
lastConfiguredProps.textureColorSpace = textureColorSpace;
|
|
15231
14463
|
}
|
|
14464
|
+
const r3fProps = ["textureColorSpace"];
|
|
14465
|
+
const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
|
|
14466
|
+
const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
|
|
15232
14467
|
if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
|
|
15233
|
-
|
|
14468
|
+
const glProps = {};
|
|
14469
|
+
for (const key in glConfig) {
|
|
14470
|
+
if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
|
|
14471
|
+
}
|
|
14472
|
+
applyProps(renderer, glProps);
|
|
15234
14473
|
}
|
|
15235
14474
|
if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
|
|
15236
14475
|
const currentRenderer = state.renderer;
|
|
15237
14476
|
if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
|
|
15238
|
-
|
|
14477
|
+
const rendererProps = {};
|
|
14478
|
+
for (const key in rendererConfig) {
|
|
14479
|
+
if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
|
|
14480
|
+
}
|
|
14481
|
+
applyProps(currentRenderer, rendererProps);
|
|
15239
14482
|
}
|
|
15240
14483
|
}
|
|
15241
14484
|
const scheduler = getScheduler();
|
|
@@ -15261,6 +14504,18 @@ function createRoot(canvas) {
|
|
|
15261
14504
|
system: true
|
|
15262
14505
|
}
|
|
15263
14506
|
);
|
|
14507
|
+
const unregisterEventsFlush = scheduler.register(
|
|
14508
|
+
() => {
|
|
14509
|
+
const state2 = store.getState();
|
|
14510
|
+
state2.events.flush?.();
|
|
14511
|
+
},
|
|
14512
|
+
{
|
|
14513
|
+
id: `${newRootId}_events`,
|
|
14514
|
+
rootId: newRootId,
|
|
14515
|
+
phase: "input",
|
|
14516
|
+
system: true
|
|
14517
|
+
}
|
|
14518
|
+
);
|
|
15264
14519
|
const unregisterFrustum = scheduler.register(
|
|
15265
14520
|
() => {
|
|
15266
14521
|
const state2 = store.getState();
|
|
@@ -15271,7 +14526,7 @@ function createRoot(canvas) {
|
|
|
15271
14526
|
{
|
|
15272
14527
|
id: `${newRootId}_frustum`,
|
|
15273
14528
|
rootId: newRootId,
|
|
15274
|
-
|
|
14529
|
+
before: "render",
|
|
15275
14530
|
system: true
|
|
15276
14531
|
}
|
|
15277
14532
|
);
|
|
@@ -15283,7 +14538,7 @@ function createRoot(canvas) {
|
|
|
15283
14538
|
{
|
|
15284
14539
|
id: `${newRootId}_visibility`,
|
|
15285
14540
|
rootId: newRootId,
|
|
15286
|
-
|
|
14541
|
+
before: "render",
|
|
15287
14542
|
system: true,
|
|
15288
14543
|
after: `${newRootId}_frustum`
|
|
15289
14544
|
}
|
|
@@ -15295,7 +14550,7 @@ function createRoot(canvas) {
|
|
|
15295
14550
|
const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
|
|
15296
14551
|
if (userHandlesRender || state2.internal.priority) return;
|
|
15297
14552
|
try {
|
|
15298
|
-
if (state2.
|
|
14553
|
+
if (state2.renderPipeline?.render) state2.renderPipeline.render();
|
|
15299
14554
|
else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
|
|
15300
14555
|
} catch (error) {
|
|
15301
14556
|
state2.setError(error instanceof Error ? error : new Error(String(error)));
|
|
@@ -15320,6 +14575,7 @@ function createRoot(canvas) {
|
|
|
15320
14575
|
unregisterRoot: () => {
|
|
15321
14576
|
unregisterRoot();
|
|
15322
14577
|
unregisterCanvasTarget();
|
|
14578
|
+
unregisterEventsFlush();
|
|
15323
14579
|
unregisterFrustum();
|
|
15324
14580
|
unregisterVisibility();
|
|
15325
14581
|
unregisterRender();
|
|
@@ -15395,7 +14651,8 @@ function unmountComponentAtNode(canvas, callback) {
|
|
|
15395
14651
|
dispose(state.scene);
|
|
15396
14652
|
_roots.delete(canvas);
|
|
15397
14653
|
if (callback) callback(canvas);
|
|
15398
|
-
} catch {
|
|
14654
|
+
} catch (error) {
|
|
14655
|
+
console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
|
|
15399
14656
|
}
|
|
15400
14657
|
}, 500);
|
|
15401
14658
|
}
|
|
@@ -15458,6 +14715,7 @@ function PortalInner({ state = {}, children, container }) {
|
|
|
15458
14715
|
viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
|
|
15459
14716
|
if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
|
|
15460
14717
|
}
|
|
14718
|
+
const set = injectState.set;
|
|
15461
14719
|
return {
|
|
15462
14720
|
// The intersect consists of the previous root state
|
|
15463
14721
|
...rootState,
|
|
@@ -15476,7 +14734,7 @@ function PortalInner({ state = {}, children, container }) {
|
|
|
15476
14734
|
size: resolvedSize,
|
|
15477
14735
|
viewport: { ...rootState.viewport, ...viewport },
|
|
15478
14736
|
// Layers are allowed to override events
|
|
15479
|
-
setEvents: (events2) =>
|
|
14737
|
+
setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
|
|
15480
14738
|
// Container for child attachment - the portalScene (injected or container itself)
|
|
15481
14739
|
internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
|
|
15482
14740
|
};
|
|
@@ -15485,9 +14743,13 @@ function PortalInner({ state = {}, children, container }) {
|
|
|
15485
14743
|
const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
|
|
15486
14744
|
const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
|
|
15487
14745
|
onMutate(previousRoot.getState());
|
|
15488
|
-
previousRoot.subscribe(onMutate);
|
|
15489
14746
|
return store;
|
|
15490
14747
|
}, [previousRoot, container]);
|
|
14748
|
+
useIsomorphicLayoutEffect(() => {
|
|
14749
|
+
const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
|
|
14750
|
+
const unsubscribe = previousRoot.subscribe(onMutate);
|
|
14751
|
+
return unsubscribe;
|
|
14752
|
+
}, [previousRoot, usePortalStore]);
|
|
15491
14753
|
return (
|
|
15492
14754
|
// @ts-ignore, reconciler types are not maintained
|
|
15493
14755
|
/* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
|
|
@@ -15501,6 +14763,81 @@ function flushSync(fn) {
|
|
|
15501
14763
|
return reconciler.flushSyncFromReconciler(fn);
|
|
15502
14764
|
}
|
|
15503
14765
|
|
|
14766
|
+
function parseBackground(background) {
|
|
14767
|
+
if (!background) return null;
|
|
14768
|
+
if (typeof background === "object" && !background.isColor) {
|
|
14769
|
+
const { backgroundMap, envMap, files, preset, ...rest } = background;
|
|
14770
|
+
return {
|
|
14771
|
+
...rest,
|
|
14772
|
+
preset,
|
|
14773
|
+
files: envMap || files,
|
|
14774
|
+
backgroundFiles: backgroundMap,
|
|
14775
|
+
background: true
|
|
14776
|
+
};
|
|
14777
|
+
}
|
|
14778
|
+
if (typeof background === "number") {
|
|
14779
|
+
return { color: background, background: true };
|
|
14780
|
+
}
|
|
14781
|
+
if (typeof background === "string") {
|
|
14782
|
+
if (background in presetsObj) {
|
|
14783
|
+
return { preset: background, background: true };
|
|
14784
|
+
}
|
|
14785
|
+
if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
|
|
14786
|
+
return { files: background, background: true };
|
|
14787
|
+
}
|
|
14788
|
+
return { color: background, background: true };
|
|
14789
|
+
}
|
|
14790
|
+
if (background.isColor) {
|
|
14791
|
+
return { color: background, background: true };
|
|
14792
|
+
}
|
|
14793
|
+
return null;
|
|
14794
|
+
}
|
|
14795
|
+
|
|
14796
|
+
function parseRendererConfig(rendererProp) {
|
|
14797
|
+
const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
|
|
14798
|
+
if (isRendererConfig) {
|
|
14799
|
+
const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
|
|
14800
|
+
return {
|
|
14801
|
+
primaryCanvas: pc,
|
|
14802
|
+
scheduler: sc,
|
|
14803
|
+
renderer: Object.keys(rest).length > 0 ? rest : rendererProp
|
|
14804
|
+
};
|
|
14805
|
+
}
|
|
14806
|
+
return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
|
|
14807
|
+
}
|
|
14808
|
+
|
|
14809
|
+
const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
|
|
14810
|
+
const registries = /* @__PURE__ */ new WeakMap();
|
|
14811
|
+
function getKindRegistry(store, kind) {
|
|
14812
|
+
let registry = registries.get(store);
|
|
14813
|
+
if (!registry) {
|
|
14814
|
+
registry = {
|
|
14815
|
+
nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
|
|
14816
|
+
uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
|
|
14817
|
+
buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
|
|
14818
|
+
gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
|
|
14819
|
+
};
|
|
14820
|
+
registries.set(store, registry);
|
|
14821
|
+
}
|
|
14822
|
+
return registry[kind];
|
|
14823
|
+
}
|
|
14824
|
+
function invalidateResource(store, kind, scopeKey) {
|
|
14825
|
+
const registry = getKindRegistry(store, kind);
|
|
14826
|
+
{
|
|
14827
|
+
registry.valid.clear();
|
|
14828
|
+
registry.staged.clear();
|
|
14829
|
+
}
|
|
14830
|
+
}
|
|
14831
|
+
function invalidateAllResources(store) {
|
|
14832
|
+
for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
|
|
14833
|
+
}
|
|
14834
|
+
|
|
14835
|
+
function clearHmrCaches(store) {
|
|
14836
|
+
const primary = store.getState().primaryStore ?? store;
|
|
14837
|
+
invalidateAllResources(primary);
|
|
14838
|
+
primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
|
|
14839
|
+
}
|
|
14840
|
+
|
|
15504
14841
|
function CanvasImpl({
|
|
15505
14842
|
ref,
|
|
15506
14843
|
children,
|
|
@@ -15521,6 +14858,8 @@ function CanvasImpl({
|
|
|
15521
14858
|
raycaster,
|
|
15522
14859
|
camera,
|
|
15523
14860
|
scene,
|
|
14861
|
+
autoUpdateFrustum,
|
|
14862
|
+
occlusion,
|
|
15524
14863
|
onPointerMissed,
|
|
15525
14864
|
onDragOverMissed,
|
|
15526
14865
|
onDropMissed,
|
|
@@ -15532,39 +14871,10 @@ function CanvasImpl({
|
|
|
15532
14871
|
forceEven,
|
|
15533
14872
|
...props
|
|
15534
14873
|
}) {
|
|
15535
|
-
const { primaryCanvas, scheduler,
|
|
15536
|
-
const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
|
|
14874
|
+
const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
|
|
15537
14875
|
React.useMemo(() => extend(THREE), []);
|
|
15538
14876
|
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]);
|
|
14877
|
+
const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
|
|
15568
14878
|
const hasInitialSizeRef = React.useRef(false);
|
|
15569
14879
|
const measureConfig = React.useMemo(() => {
|
|
15570
14880
|
if (!hasInitialSizeRef.current) {
|
|
@@ -15606,6 +14916,7 @@ function CanvasImpl({
|
|
|
15606
14916
|
const handleDropMissed = useMutableCallback(onDropMissed);
|
|
15607
14917
|
const [block, setBlock] = React.useState(false);
|
|
15608
14918
|
const [error, setError] = React.useState(false);
|
|
14919
|
+
const [fallbackVisible, setFallbackVisible] = React.useState(false);
|
|
15609
14920
|
if (block) throw block;
|
|
15610
14921
|
if (error) throw error;
|
|
15611
14922
|
const root = React.useRef(null);
|
|
@@ -15613,6 +14924,7 @@ function CanvasImpl({
|
|
|
15613
14924
|
const unsubscribeErrorRef = React.useRef(null);
|
|
15614
14925
|
useIsomorphicLayoutEffect(() => {
|
|
15615
14926
|
effectActiveRef.current = true;
|
|
14927
|
+
if (fallbackVisible) return;
|
|
15616
14928
|
const canvas = canvasRef.current;
|
|
15617
14929
|
if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
|
|
15618
14930
|
if (!root.current) {
|
|
@@ -15633,7 +14945,7 @@ function CanvasImpl({
|
|
|
15633
14945
|
}
|
|
15634
14946
|
async function run() {
|
|
15635
14947
|
if (!effectActiveRef.current || !root.current) return;
|
|
15636
|
-
await root.current.configure({
|
|
14948
|
+
const configured = await root.current.configure({
|
|
15637
14949
|
id,
|
|
15638
14950
|
primaryCanvas,
|
|
15639
14951
|
scheduler,
|
|
@@ -15648,6 +14960,8 @@ function CanvasImpl({
|
|
|
15648
14960
|
performance,
|
|
15649
14961
|
raycaster,
|
|
15650
14962
|
camera,
|
|
14963
|
+
autoUpdateFrustum,
|
|
14964
|
+
occlusion,
|
|
15651
14965
|
size: effectiveSize,
|
|
15652
14966
|
// Store size props for reset functionality
|
|
15653
14967
|
_sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
|
|
@@ -15672,8 +14986,20 @@ function CanvasImpl({
|
|
|
15672
14986
|
}
|
|
15673
14987
|
onCreated?.(state);
|
|
15674
14988
|
}
|
|
15675
|
-
})
|
|
15676
|
-
|
|
14989
|
+
}).then(
|
|
14990
|
+
() => true,
|
|
14991
|
+
// Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
|
|
14992
|
+
// inside <canvas>, which browsers don't display, so surface it as visible DOM
|
|
14993
|
+
// instead; with no fallback, rethrow to an external error boundary. (#3757)
|
|
14994
|
+
(setupError) => {
|
|
14995
|
+
if (effectActiveRef.current) {
|
|
14996
|
+
if (fallback != null) setFallbackVisible(true);
|
|
14997
|
+
else setError(setupError);
|
|
14998
|
+
}
|
|
14999
|
+
return false;
|
|
15000
|
+
}
|
|
15001
|
+
);
|
|
15002
|
+
if (!configured || !effectActiveRef.current || !root.current) return;
|
|
15677
15003
|
root.current.render(
|
|
15678
15004
|
/* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
|
|
15679
15005
|
backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
|
|
@@ -15707,20 +15033,13 @@ function CanvasImpl({
|
|
|
15707
15033
|
const handleHMR = () => {
|
|
15708
15034
|
queueMicrotask(() => {
|
|
15709
15035
|
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
|
-
}
|
|
15036
|
+
if (rootEntry?.store) clearHmrCaches(rootEntry.store);
|
|
15717
15037
|
});
|
|
15718
15038
|
};
|
|
15719
15039
|
if (typeof import.meta !== "undefined" && import.meta.hot) {
|
|
15720
15040
|
const hot = import.meta.hot;
|
|
15721
15041
|
hot.on("vite:afterUpdate", handleHMR);
|
|
15722
|
-
return () => hot.
|
|
15723
|
-
});
|
|
15042
|
+
return () => hot.off?.("vite:afterUpdate", handleHMR);
|
|
15724
15043
|
}
|
|
15725
15044
|
if (typeof module !== "undefined" && module.hot) {
|
|
15726
15045
|
const hot = module.hot;
|
|
@@ -15743,7 +15062,20 @@ function CanvasImpl({
|
|
|
15743
15062
|
...style
|
|
15744
15063
|
},
|
|
15745
15064
|
...props,
|
|
15746
|
-
children:
|
|
15065
|
+
children: fallbackVisible ? (
|
|
15066
|
+
// Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
|
|
15067
|
+
// it exists in the tree but browsers never paint it, which is the whole bug (#3757).
|
|
15068
|
+
fallback
|
|
15069
|
+
) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
|
|
15070
|
+
"canvas",
|
|
15071
|
+
{
|
|
15072
|
+
ref: canvasRef,
|
|
15073
|
+
id,
|
|
15074
|
+
className: "r3f-canvas",
|
|
15075
|
+
style: { display: "block", width: "100%", height: "100%" },
|
|
15076
|
+
children: fallback
|
|
15077
|
+
}
|
|
15078
|
+
) })
|
|
15747
15079
|
}
|
|
15748
15080
|
);
|
|
15749
15081
|
}
|
|
@@ -15753,4 +15085,4 @@ function Canvas(props) {
|
|
|
15753
15085
|
|
|
15754
15086
|
extend(THREE);
|
|
15755
15087
|
|
|
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,
|
|
15088
|
+
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 };
|