@react-three/fiber 10.0.0-canary.aecbafb → 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 +433 -1319
- package/dist/index.d.cts +169 -801
- package/dist/index.d.mts +169 -801
- package/dist/index.d.ts +169 -801
- package/dist/index.mjs +407 -1292
- package/dist/legacy.cjs +388 -1274
- package/dist/legacy.d.cts +169 -800
- package/dist/legacy.d.mts +169 -800
- package/dist/legacy.d.ts +169 -800
- package/dist/legacy.mjs +361 -1246
- package/dist/webgpu/index.cjs +953 -2062
- package/dist/webgpu/index.d.cts +202 -804
- package/dist/webgpu/index.d.mts +202 -804
- package/dist/webgpu/index.d.ts +202 -804
- package/dist/webgpu/index.mjs +928 -2036
- package/package.json +4 -3
- package/readme.md +2 -3
package/dist/legacy.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as three from 'three';
|
|
2
|
-
import { WebGLRenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene,
|
|
2
|
+
import { WebGLCubeRenderTarget, WebGLRenderTarget, 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, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGLRenderer } from 'three';
|
|
3
3
|
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
|
|
4
4
|
import * as React from 'react';
|
|
5
5
|
import React__default, { useLayoutEffect, useRef, useMemo, useEffect, useContext, useImperativeHandle, useCallback, useState } from 'react';
|
|
@@ -13,6 +13,8 @@ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
|
|
|
13
13
|
import { GainMapLoader } from '@monogrid/gainmap-js';
|
|
14
14
|
import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
|
|
15
15
|
import { createWithEqualityFn } from 'zustand/traditional';
|
|
16
|
+
import { getScheduler } from '@pmndrs/scheduler';
|
|
17
|
+
export { Scheduler, getScheduler } from '@pmndrs/scheduler';
|
|
16
18
|
import { suspend, preload, clear } from 'suspend-react';
|
|
17
19
|
|
|
18
20
|
function _mergeNamespaces(n, m) {
|
|
@@ -40,9 +42,12 @@ const WebGPURenderer = class WebGPURenderer2 {
|
|
|
40
42
|
}
|
|
41
43
|
};
|
|
42
44
|
const RenderTarget = null;
|
|
45
|
+
const CubeRenderTarget = null;
|
|
43
46
|
|
|
44
47
|
const THREE = /*#__PURE__*/_mergeNamespaces({
|
|
45
48
|
__proto__: null,
|
|
49
|
+
CubeRenderTarget: CubeRenderTarget,
|
|
50
|
+
CubeRenderTargetCompat: WebGLCubeRenderTarget,
|
|
46
51
|
Inspector: Inspector,
|
|
47
52
|
R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
|
|
48
53
|
R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
|
|
@@ -148,7 +153,7 @@ function useEnvironment({
|
|
|
148
153
|
useLoader$1.clear(loader, multiFile ? [files] : files);
|
|
149
154
|
}
|
|
150
155
|
renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
|
|
151
|
-
}, [files, renderer.domElement]);
|
|
156
|
+
}, [extension, files, loader, multiFile, renderer.domElement]);
|
|
152
157
|
const loaderResult = useLoader$1(
|
|
153
158
|
loader,
|
|
154
159
|
multiFile ? [files] : files,
|
|
@@ -320,15 +325,16 @@ function EnvironmentPortal({
|
|
|
320
325
|
preset = void 0,
|
|
321
326
|
extensions
|
|
322
327
|
}) {
|
|
323
|
-
const
|
|
328
|
+
const renderer = useThree$1((state) => state.renderer);
|
|
329
|
+
const isLegacy = useThree$1((state) => state.isLegacy);
|
|
324
330
|
const defaultScene = useThree$1((state) => state.scene);
|
|
325
331
|
const camera = React.useRef(null);
|
|
326
332
|
const [virtualScene] = React.useState(() => new Scene());
|
|
327
333
|
const fbo = React.useMemo(() => {
|
|
328
|
-
const fbo2 = new WebGLCubeRenderTarget(resolution);
|
|
334
|
+
const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
|
|
329
335
|
fbo2.texture.type = HalfFloatType;
|
|
330
336
|
return fbo2;
|
|
331
|
-
}, [resolution]);
|
|
337
|
+
}, [resolution, isLegacy]);
|
|
332
338
|
React.useEffect(() => {
|
|
333
339
|
return () => {
|
|
334
340
|
fbo.dispose();
|
|
@@ -336,10 +342,10 @@ function EnvironmentPortal({
|
|
|
336
342
|
}, [fbo]);
|
|
337
343
|
React.useLayoutEffect(() => {
|
|
338
344
|
if (frames === 1) {
|
|
339
|
-
const autoClear =
|
|
340
|
-
|
|
341
|
-
camera.current.update(
|
|
342
|
-
|
|
345
|
+
const autoClear = renderer.autoClear;
|
|
346
|
+
renderer.autoClear = true;
|
|
347
|
+
camera.current.update(renderer, virtualScene);
|
|
348
|
+
renderer.autoClear = autoClear;
|
|
343
349
|
}
|
|
344
350
|
return setEnvProps(background, scene, defaultScene, fbo.texture, {
|
|
345
351
|
backgroundBlurriness: blur ?? backgroundBlurriness,
|
|
@@ -348,14 +354,29 @@ function EnvironmentPortal({
|
|
|
348
354
|
environmentIntensity,
|
|
349
355
|
environmentRotation
|
|
350
356
|
});
|
|
351
|
-
}, [
|
|
357
|
+
}, [
|
|
358
|
+
children,
|
|
359
|
+
virtualScene,
|
|
360
|
+
fbo.texture,
|
|
361
|
+
scene,
|
|
362
|
+
defaultScene,
|
|
363
|
+
background,
|
|
364
|
+
frames,
|
|
365
|
+
renderer,
|
|
366
|
+
blur,
|
|
367
|
+
backgroundBlurriness,
|
|
368
|
+
backgroundIntensity,
|
|
369
|
+
backgroundRotation,
|
|
370
|
+
environmentIntensity,
|
|
371
|
+
environmentRotation
|
|
372
|
+
]);
|
|
352
373
|
let count = 1;
|
|
353
374
|
useFrame$1(() => {
|
|
354
375
|
if (frames === Infinity || count < frames) {
|
|
355
|
-
const autoClear =
|
|
356
|
-
|
|
357
|
-
camera.current.update(
|
|
358
|
-
|
|
376
|
+
const autoClear = renderer.autoClear;
|
|
377
|
+
renderer.autoClear = true;
|
|
378
|
+
camera.current.update(renderer, virtualScene);
|
|
379
|
+
renderer.autoClear = autoClear;
|
|
359
380
|
count++;
|
|
360
381
|
}
|
|
361
382
|
});
|
|
@@ -419,9 +440,9 @@ function Environment(props) {
|
|
|
419
440
|
return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
|
|
420
441
|
}
|
|
421
442
|
|
|
422
|
-
var __defProp
|
|
423
|
-
var __defNormalProp
|
|
424
|
-
var __publicField
|
|
443
|
+
var __defProp = Object.defineProperty;
|
|
444
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
445
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
425
446
|
const act = React["act"];
|
|
426
447
|
const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
|
|
427
448
|
function useMutableCallback(fn) {
|
|
@@ -453,7 +474,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
|
|
|
453
474
|
return _a = class extends React.Component {
|
|
454
475
|
constructor() {
|
|
455
476
|
super(...arguments);
|
|
456
|
-
__publicField
|
|
477
|
+
__publicField(this, "state", { error: false });
|
|
457
478
|
}
|
|
458
479
|
componentDidCatch(err) {
|
|
459
480
|
this.props.set(err);
|
|
@@ -461,7 +482,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
|
|
|
461
482
|
render() {
|
|
462
483
|
return this.state.error ? null : this.props.children;
|
|
463
484
|
}
|
|
464
|
-
}, __publicField
|
|
485
|
+
}, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
|
|
465
486
|
})();
|
|
466
487
|
|
|
467
488
|
const is = {
|
|
@@ -598,8 +619,7 @@ function prepare(target, root, type, props) {
|
|
|
598
619
|
object,
|
|
599
620
|
eventCount: 0,
|
|
600
621
|
handlers: {},
|
|
601
|
-
isHidden: false
|
|
602
|
-
deferredRefs: []
|
|
622
|
+
isHidden: false
|
|
603
623
|
};
|
|
604
624
|
if (object) object.__r3f = instance;
|
|
605
625
|
}
|
|
@@ -756,6 +776,17 @@ function unregisterVisibility(store, object) {
|
|
|
756
776
|
internal.visibilityRegistry.delete(object.uuid);
|
|
757
777
|
internal.occlusionCache.delete(object);
|
|
758
778
|
}
|
|
779
|
+
function updateVisibilityHandlers(store, object, handlers) {
|
|
780
|
+
const { internal } = store.getState();
|
|
781
|
+
const entry = internal.visibilityRegistry.get(object.uuid);
|
|
782
|
+
if (!entry) return false;
|
|
783
|
+
entry.handlers = handlers;
|
|
784
|
+
if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
|
|
785
|
+
object.occlusionTest = true;
|
|
786
|
+
enableOcclusion(store);
|
|
787
|
+
}
|
|
788
|
+
return true;
|
|
789
|
+
}
|
|
759
790
|
function checkVisibility(state) {
|
|
760
791
|
const { internal, camera } = state;
|
|
761
792
|
const registry = internal.visibilityRegistry;
|
|
@@ -943,10 +974,7 @@ function applyProps(object, props) {
|
|
|
943
974
|
continue;
|
|
944
975
|
}
|
|
945
976
|
if (value === void 0) continue;
|
|
946
|
-
if (isFromRef(value))
|
|
947
|
-
instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
|
|
948
|
-
continue;
|
|
949
|
-
}
|
|
977
|
+
if (isFromRef(value)) continue;
|
|
950
978
|
if (isOnce(value)) {
|
|
951
979
|
if (instance?.appliedOnce?.has(prop)) continue;
|
|
952
980
|
if (instance) {
|
|
@@ -982,6 +1010,19 @@ function applyProps(object, props) {
|
|
|
982
1010
|
} else if (isVectorLike(target) && is.num(value)) {
|
|
983
1011
|
if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
|
|
984
1012
|
else target.set(value);
|
|
1013
|
+
} else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
|
|
1014
|
+
if (!is.obj(root.uniforms)) root.uniforms = {};
|
|
1015
|
+
const uniforms = root.uniforms;
|
|
1016
|
+
const nextUniforms = value;
|
|
1017
|
+
for (const name in nextUniforms) {
|
|
1018
|
+
const uniform = nextUniforms[name];
|
|
1019
|
+
const targetUniform = uniforms[name];
|
|
1020
|
+
if (targetUniform) Object.assign(targetUniform, uniform);
|
|
1021
|
+
else {
|
|
1022
|
+
const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
|
|
1023
|
+
uniforms[name] = nextUniform;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
985
1026
|
} else {
|
|
986
1027
|
root[key] = value;
|
|
987
1028
|
if (key.endsWith("Node") && root.isMaterial) {
|
|
@@ -1000,6 +1041,9 @@ function applyProps(object, props) {
|
|
|
1000
1041
|
if (instance.eventCount && object2.raycast !== null) {
|
|
1001
1042
|
rootState.internal.interaction.push(object2);
|
|
1002
1043
|
}
|
|
1044
|
+
}
|
|
1045
|
+
if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
|
|
1046
|
+
const object2 = instance.object;
|
|
1003
1047
|
const root = findInitialRoot(instance);
|
|
1004
1048
|
const visibilityHandlers = {
|
|
1005
1049
|
onFramed: instance.handlers.onFramed,
|
|
@@ -1007,7 +1051,9 @@ function applyProps(object, props) {
|
|
|
1007
1051
|
onVisible: instance.handlers.onVisible
|
|
1008
1052
|
};
|
|
1009
1053
|
if (hasVisibilityHandlers(visibilityHandlers)) {
|
|
1010
|
-
|
|
1054
|
+
if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
|
|
1055
|
+
registerVisibility(root, object2, visibilityHandlers);
|
|
1056
|
+
}
|
|
1011
1057
|
} else {
|
|
1012
1058
|
unregisterVisibility(root, object2);
|
|
1013
1059
|
}
|
|
@@ -1275,7 +1321,7 @@ function createEvents(store) {
|
|
|
1275
1321
|
}
|
|
1276
1322
|
function processDeferredPointer(event, pointerId) {
|
|
1277
1323
|
const state = store.getState();
|
|
1278
|
-
const {
|
|
1324
|
+
const { internal } = state;
|
|
1279
1325
|
if (!state.events.enabled) return;
|
|
1280
1326
|
const filter = filterPointerEvents;
|
|
1281
1327
|
const hits = intersect(event, filter);
|
|
@@ -1510,6 +1556,7 @@ function createPointerEvents(store) {
|
|
|
1510
1556
|
}
|
|
1511
1557
|
},
|
|
1512
1558
|
connect: (target) => {
|
|
1559
|
+
if (!target) return;
|
|
1513
1560
|
const { set, events } = store.getState();
|
|
1514
1561
|
events.disconnect?.();
|
|
1515
1562
|
set((state) => ({ events: { ...state.events, connected: target } }));
|
|
@@ -1534,6 +1581,7 @@ function createPointerEvents(store) {
|
|
|
1534
1581
|
set((state) => ({ events: { ...state.events, connected: void 0 } }));
|
|
1535
1582
|
}
|
|
1536
1583
|
},
|
|
1584
|
+
// PREVIEW (A8): the XR pointer registration API may change before stable.
|
|
1537
1585
|
registerPointer: (config) => {
|
|
1538
1586
|
const pointerId = nextXRPointerId++;
|
|
1539
1587
|
xrPointers.set(pointerId, config);
|
|
@@ -1620,1036 +1668,11 @@ function notifyAlpha({ message, link }) {
|
|
|
1620
1668
|
}
|
|
1621
1669
|
}
|
|
1622
1670
|
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
const
|
|
1627
|
-
|
|
1628
|
-
constructor() {
|
|
1629
|
-
/** Ordered list of phase nodes */
|
|
1630
|
-
__publicField$1(this, "phases", []);
|
|
1631
|
-
/** Quick lookup by name */
|
|
1632
|
-
__publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
|
|
1633
|
-
/** Cached ordered names (invalidated on changes) */
|
|
1634
|
-
__publicField$1(this, "orderedNamesCache", null);
|
|
1635
|
-
this.initializeDefaultPhases();
|
|
1636
|
-
}
|
|
1637
|
-
//* Initialization --------------------------------
|
|
1638
|
-
initializeDefaultPhases() {
|
|
1639
|
-
for (const name of DEFAULT_PHASES) {
|
|
1640
|
-
const node = { name, isAutoGenerated: false };
|
|
1641
|
-
this.phases.push(node);
|
|
1642
|
-
this.phaseMap.set(name, node);
|
|
1643
|
-
}
|
|
1644
|
-
this.invalidateCache();
|
|
1645
|
-
}
|
|
1646
|
-
//* Public API --------------------------------
|
|
1647
|
-
/**
|
|
1648
|
-
* Add a named phase to the graph
|
|
1649
|
-
* @param name - Phase name (must be unique)
|
|
1650
|
-
* @param options - Position options (before or after another phase)
|
|
1651
|
-
*/
|
|
1652
|
-
addPhase(name, options = {}) {
|
|
1653
|
-
if (this.phaseMap.has(name)) {
|
|
1654
|
-
console.warn(`[useFrame] Phase "${name}" already exists`);
|
|
1655
|
-
return;
|
|
1656
|
-
}
|
|
1657
|
-
const { before, after } = options;
|
|
1658
|
-
const node = { name, isAutoGenerated: false };
|
|
1659
|
-
let insertIndex = this.phases.length;
|
|
1660
|
-
const targetIndex = this.getPhaseIndex(before ?? after);
|
|
1661
|
-
if (targetIndex !== -1) {
|
|
1662
|
-
insertIndex = before ? targetIndex : targetIndex + 1;
|
|
1663
|
-
} else {
|
|
1664
|
-
const constraintType = before ? "before" : "after";
|
|
1665
|
-
console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
|
|
1666
|
-
}
|
|
1667
|
-
this.phases.splice(insertIndex, 0, node);
|
|
1668
|
-
this.phaseMap.set(name, node);
|
|
1669
|
-
this.invalidateCache();
|
|
1670
|
-
}
|
|
1671
|
-
/**
|
|
1672
|
-
* Get ordered list of phase names
|
|
1673
|
-
*/
|
|
1674
|
-
getOrderedPhases() {
|
|
1675
|
-
if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
|
|
1676
|
-
return this.orderedNamesCache;
|
|
1677
|
-
}
|
|
1678
|
-
/**
|
|
1679
|
-
* Check if a phase exists
|
|
1680
|
-
*/
|
|
1681
|
-
hasPhase(name) {
|
|
1682
|
-
return this.phaseMap.has(name);
|
|
1683
|
-
}
|
|
1684
|
-
/**
|
|
1685
|
-
* Get the index of a phase (-1 if not found)
|
|
1686
|
-
*/
|
|
1687
|
-
getPhaseIndex(name) {
|
|
1688
|
-
if (!name) return -1;
|
|
1689
|
-
return this.phases.findIndex((p) => p.name === name);
|
|
1690
|
-
}
|
|
1691
|
-
/**
|
|
1692
|
-
* Ensure a phase exists, creating an auto-generated one if needed.
|
|
1693
|
-
* Used for resolving before/after constraints.
|
|
1694
|
-
*
|
|
1695
|
-
* @param name - The phase name to ensure exists
|
|
1696
|
-
* @returns The phase name (may be auto-generated like 'before:render')
|
|
1697
|
-
*/
|
|
1698
|
-
ensurePhase(name) {
|
|
1699
|
-
if (this.phaseMap.has(name)) return name;
|
|
1700
|
-
const node = { name, isAutoGenerated: true };
|
|
1701
|
-
this.phases.push(node);
|
|
1702
|
-
this.phaseMap.set(name, node);
|
|
1703
|
-
this.invalidateCache();
|
|
1704
|
-
return name;
|
|
1705
|
-
}
|
|
1706
|
-
/**
|
|
1707
|
-
* Resolve where a job with before/after constraints should go.
|
|
1708
|
-
* Creates auto-generated phases if needed.
|
|
1709
|
-
*
|
|
1710
|
-
* @param before - Phase(s) to run before
|
|
1711
|
-
* @param after - Phase(s) to run after
|
|
1712
|
-
* @returns The resolved phase name
|
|
1713
|
-
*/
|
|
1714
|
-
resolveConstraintPhase(before, after) {
|
|
1715
|
-
const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
|
|
1716
|
-
const afterArr = after ? Array.isArray(after) ? after : [after] : [];
|
|
1717
|
-
if (beforeArr.length > 0) {
|
|
1718
|
-
return this.ensureAutoPhase(beforeArr[0], "before", 0);
|
|
1719
|
-
}
|
|
1720
|
-
if (afterArr.length > 0) {
|
|
1721
|
-
return this.ensureAutoPhase(afterArr[0], "after", 1);
|
|
1722
|
-
}
|
|
1723
|
-
return "update";
|
|
1724
|
-
}
|
|
1725
|
-
/**
|
|
1726
|
-
* Ensure an auto-generated phase exists relative to a target phase.
|
|
1727
|
-
* Creates the phase if it doesn't exist, inserting it at the correct position.
|
|
1728
|
-
*
|
|
1729
|
-
* @param target - The target phase name to position relative to
|
|
1730
|
-
* @param prefix - Prefix for auto-generated phase name ('before' or 'after')
|
|
1731
|
-
* @param offset - Insertion offset (0 for before, 1 for after)
|
|
1732
|
-
* @returns The auto-generated phase name
|
|
1733
|
-
*/
|
|
1734
|
-
ensureAutoPhase(target, prefix, offset) {
|
|
1735
|
-
const autoName = `${prefix}:${target}`;
|
|
1736
|
-
if (this.phaseMap.has(autoName)) return autoName;
|
|
1737
|
-
const node = { name: autoName, isAutoGenerated: true };
|
|
1738
|
-
const targetIndex = this.getPhaseIndex(target);
|
|
1739
|
-
if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
|
|
1740
|
-
else this.phases.push(node);
|
|
1741
|
-
this.phaseMap.set(autoName, node);
|
|
1742
|
-
this.invalidateCache();
|
|
1743
|
-
return autoName;
|
|
1744
|
-
}
|
|
1745
|
-
// Internal --------------------------------
|
|
1746
|
-
invalidateCache() {
|
|
1747
|
-
this.orderedNamesCache = null;
|
|
1748
|
-
}
|
|
1749
|
-
}
|
|
1750
|
-
|
|
1751
|
-
function rebuildSortedJobs(jobs, phaseGraph) {
|
|
1752
|
-
const orderedPhases = phaseGraph.getOrderedPhases();
|
|
1753
|
-
const buckets = /* @__PURE__ */ new Map();
|
|
1754
|
-
for (const phase of orderedPhases) {
|
|
1755
|
-
buckets.set(phase, []);
|
|
1756
|
-
}
|
|
1757
|
-
for (const job of jobs.values()) {
|
|
1758
|
-
if (!job.enabled) continue;
|
|
1759
|
-
let bucket = buckets.get(job.phase);
|
|
1760
|
-
if (!bucket) {
|
|
1761
|
-
bucket = [];
|
|
1762
|
-
buckets.set(job.phase, bucket);
|
|
1763
|
-
}
|
|
1764
|
-
bucket.push(job);
|
|
1765
|
-
}
|
|
1766
|
-
const sortedBuckets = [];
|
|
1767
|
-
for (const phase of orderedPhases) {
|
|
1768
|
-
const bucket = buckets.get(phase);
|
|
1769
|
-
if (!bucket || bucket.length === 0) continue;
|
|
1770
|
-
bucket.sort((a, b) => {
|
|
1771
|
-
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1772
|
-
return a.index - b.index;
|
|
1773
|
-
});
|
|
1774
|
-
sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
|
|
1775
|
-
}
|
|
1776
|
-
for (const [phase, bucket] of buckets) {
|
|
1777
|
-
if (!orderedPhases.includes(phase) && bucket.length > 0) {
|
|
1778
|
-
bucket.sort((a, b) => {
|
|
1779
|
-
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1780
|
-
return a.index - b.index;
|
|
1781
|
-
});
|
|
1782
|
-
sortedBuckets.push(bucket);
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1785
|
-
return sortedBuckets.flat();
|
|
1786
|
-
}
|
|
1787
|
-
function hasCrossJobConstraints(bucket) {
|
|
1788
|
-
const jobIds = new Set(bucket.map((j) => j.id));
|
|
1789
|
-
for (const job of bucket) {
|
|
1790
|
-
for (const ref of job.before) {
|
|
1791
|
-
if (jobIds.has(ref)) return true;
|
|
1792
|
-
}
|
|
1793
|
-
for (const ref of job.after) {
|
|
1794
|
-
if (jobIds.has(ref)) return true;
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
return false;
|
|
1798
|
-
}
|
|
1799
|
-
function topologicalSort(jobs) {
|
|
1800
|
-
const n = jobs.length;
|
|
1801
|
-
if (n <= 1) return jobs;
|
|
1802
|
-
const jobMap = /* @__PURE__ */ new Map();
|
|
1803
|
-
const inDegree = /* @__PURE__ */ new Map();
|
|
1804
|
-
const adjacency = /* @__PURE__ */ new Map();
|
|
1805
|
-
for (const job of jobs) {
|
|
1806
|
-
jobMap.set(job.id, job);
|
|
1807
|
-
inDegree.set(job.id, 0);
|
|
1808
|
-
adjacency.set(job.id, []);
|
|
1809
|
-
}
|
|
1810
|
-
for (const job of jobs) {
|
|
1811
|
-
for (const ref of job.before) {
|
|
1812
|
-
if (jobMap.has(ref)) {
|
|
1813
|
-
adjacency.get(job.id).push(ref);
|
|
1814
|
-
inDegree.set(ref, inDegree.get(ref) + 1);
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
for (const ref of job.after) {
|
|
1818
|
-
if (jobMap.has(ref)) {
|
|
1819
|
-
adjacency.get(ref).push(job.id);
|
|
1820
|
-
inDegree.set(job.id, inDegree.get(job.id) + 1);
|
|
1821
|
-
}
|
|
1822
|
-
}
|
|
1823
|
-
}
|
|
1824
|
-
const queue = [];
|
|
1825
|
-
for (const job of jobs) {
|
|
1826
|
-
if (inDegree.get(job.id) === 0) {
|
|
1827
|
-
queue.push(job);
|
|
1828
|
-
}
|
|
1829
|
-
}
|
|
1830
|
-
queue.sort((a, b) => {
|
|
1831
|
-
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1832
|
-
return a.index - b.index;
|
|
1833
|
-
});
|
|
1834
|
-
const result = [];
|
|
1835
|
-
while (queue.length > 0) {
|
|
1836
|
-
const job = queue.shift();
|
|
1837
|
-
result.push(job);
|
|
1838
|
-
const neighbors = adjacency.get(job.id) || [];
|
|
1839
|
-
for (const neighborId of neighbors) {
|
|
1840
|
-
const newDegree = inDegree.get(neighborId) - 1;
|
|
1841
|
-
inDegree.set(neighborId, newDegree);
|
|
1842
|
-
if (newDegree === 0) {
|
|
1843
|
-
const neighbor = jobMap.get(neighborId);
|
|
1844
|
-
insertSorted(queue, neighbor);
|
|
1845
|
-
}
|
|
1846
|
-
}
|
|
1847
|
-
}
|
|
1848
|
-
if (result.length !== n) {
|
|
1849
|
-
console.warn("[useFrame] Circular dependency detected in job constraints");
|
|
1850
|
-
const resultIds = new Set(result.map((j) => j.id));
|
|
1851
|
-
for (const job of jobs) {
|
|
1852
|
-
if (!resultIds.has(job.id)) result.push(job);
|
|
1853
|
-
}
|
|
1854
|
-
}
|
|
1855
|
-
return result;
|
|
1856
|
-
}
|
|
1857
|
-
function insertSorted(arr, job) {
|
|
1858
|
-
let i = 0;
|
|
1859
|
-
while (i < arr.length) {
|
|
1860
|
-
const cmp = arr[i];
|
|
1861
|
-
if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
|
|
1862
|
-
break;
|
|
1863
|
-
}
|
|
1864
|
-
i++;
|
|
1865
|
-
}
|
|
1866
|
-
arr.splice(i, 0, job);
|
|
1867
|
-
}
|
|
1868
|
-
|
|
1869
|
-
function shouldRun(job, now) {
|
|
1870
|
-
if (!job.enabled) return false;
|
|
1871
|
-
if (!job.fps) return true;
|
|
1872
|
-
const minInterval = 1e3 / job.fps;
|
|
1873
|
-
const lastRun = job.lastRun ?? 0;
|
|
1874
|
-
const elapsed = now - lastRun;
|
|
1875
|
-
if (elapsed < minInterval) return false;
|
|
1876
|
-
if (job.drop) {
|
|
1877
|
-
job.lastRun = now;
|
|
1878
|
-
} else {
|
|
1879
|
-
const steps = Math.floor(elapsed / minInterval);
|
|
1880
|
-
job.lastRun = lastRun + steps * minInterval;
|
|
1881
|
-
if (job.lastRun < now - minInterval) {
|
|
1882
|
-
job.lastRun = now;
|
|
1883
|
-
}
|
|
1884
|
-
}
|
|
1885
|
-
return true;
|
|
1886
|
-
}
|
|
1887
|
-
function resetJobTiming(job) {
|
|
1888
|
-
job.lastRun = void 0;
|
|
1889
|
-
}
|
|
1890
|
-
|
|
1891
|
-
var __defProp = Object.defineProperty;
|
|
1892
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
1893
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1894
|
-
const hmrData = (() => {
|
|
1895
|
-
if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
|
|
1896
|
-
if (typeof import_meta_hot !== "undefined") return import_meta_hot;
|
|
1897
|
-
try {
|
|
1898
|
-
return (0, eval)("import.meta.hot");
|
|
1899
|
-
} catch {
|
|
1900
|
-
return void 0;
|
|
1901
|
-
}
|
|
1902
|
-
})();
|
|
1903
|
-
const _Scheduler = class _Scheduler {
|
|
1904
|
-
//* Constructor ================================
|
|
1905
|
-
constructor() {
|
|
1906
|
-
//* Critical State ================================
|
|
1907
|
-
__publicField(this, "roots", /* @__PURE__ */ new Map());
|
|
1908
|
-
__publicField(this, "phaseGraph");
|
|
1909
|
-
__publicField(this, "loopState", {
|
|
1910
|
-
running: false,
|
|
1911
|
-
rafHandle: null,
|
|
1912
|
-
lastTime: null,
|
|
1913
|
-
// null = uninitialized, 0+ = valid timestamp
|
|
1914
|
-
frameCount: 0,
|
|
1915
|
-
elapsedTime: 0,
|
|
1916
|
-
createdAt: performance.now()
|
|
1917
|
-
});
|
|
1918
|
-
__publicField(this, "stoppedTime", 0);
|
|
1919
|
-
//* Private State ================================
|
|
1920
|
-
__publicField(this, "nextRootIndex", 0);
|
|
1921
|
-
__publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
|
|
1922
|
-
__publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
|
|
1923
|
-
__publicField(this, "nextGlobalIndex", 0);
|
|
1924
|
-
__publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
|
|
1925
|
-
__publicField(this, "nextJobIndex", 0);
|
|
1926
|
-
__publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
|
|
1927
|
-
__publicField(this, "pendingFrames", 0);
|
|
1928
|
-
__publicField(this, "_frameloop", "always");
|
|
1929
|
-
//* Independent Mode & Error Handling State ================================
|
|
1930
|
-
__publicField(this, "_independent", false);
|
|
1931
|
-
__publicField(this, "errorHandler", null);
|
|
1932
|
-
__publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
|
|
1933
|
-
//* Core Loop Execution Methods ================================
|
|
1934
|
-
/**
|
|
1935
|
-
* Main RAF loop callback.
|
|
1936
|
-
* Executes frame, handles demand mode, and schedules next frame.
|
|
1937
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
1938
|
-
* @returns {void}
|
|
1939
|
-
* @private
|
|
1940
|
-
*/
|
|
1941
|
-
__publicField(this, "loop", (timestamp) => {
|
|
1942
|
-
if (!this.loopState.running) return;
|
|
1943
|
-
this.executeFrame(timestamp);
|
|
1944
|
-
if (this._frameloop === "demand") {
|
|
1945
|
-
this.pendingFrames = Math.max(0, this.pendingFrames - 1);
|
|
1946
|
-
if (this.pendingFrames === 0) {
|
|
1947
|
-
this.notifyIdle(timestamp);
|
|
1948
|
-
return this.stop();
|
|
1949
|
-
}
|
|
1950
|
-
}
|
|
1951
|
-
this.loopState.rafHandle = requestAnimationFrame(this.loop);
|
|
1952
|
-
});
|
|
1953
|
-
this.phaseGraph = new PhaseGraph();
|
|
1954
|
-
}
|
|
1955
|
-
static get instance() {
|
|
1956
|
-
return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
|
|
1957
|
-
}
|
|
1958
|
-
static set instance(value) {
|
|
1959
|
-
globalThis[_Scheduler.INSTANCE_KEY] = value;
|
|
1960
|
-
}
|
|
1961
|
-
/**
|
|
1962
|
-
* Get the global scheduler instance (creates if doesn't exist).
|
|
1963
|
-
* Uses HMR data to preserve instance across hot reloads.
|
|
1964
|
-
* @returns {Scheduler} The singleton scheduler instance
|
|
1965
|
-
*/
|
|
1966
|
-
static get() {
|
|
1967
|
-
if (!_Scheduler.instance && hmrData?.data?.scheduler) {
|
|
1968
|
-
_Scheduler.instance = hmrData.data.scheduler;
|
|
1969
|
-
}
|
|
1970
|
-
if (!_Scheduler.instance) {
|
|
1971
|
-
_Scheduler.instance = new _Scheduler();
|
|
1972
|
-
if (hmrData?.data) {
|
|
1973
|
-
hmrData.data.scheduler = _Scheduler.instance;
|
|
1974
|
-
}
|
|
1975
|
-
}
|
|
1976
|
-
return _Scheduler.instance;
|
|
1977
|
-
}
|
|
1978
|
-
/**
|
|
1979
|
-
* Reset the singleton instance. Stops the loop and clears all state.
|
|
1980
|
-
* Primarily used for testing to ensure clean state between tests.
|
|
1981
|
-
* @returns {void}
|
|
1982
|
-
*/
|
|
1983
|
-
static reset() {
|
|
1984
|
-
if (_Scheduler.instance) {
|
|
1985
|
-
_Scheduler.instance.stop();
|
|
1986
|
-
_Scheduler.instance = null;
|
|
1987
|
-
}
|
|
1988
|
-
if (hmrData?.data) {
|
|
1989
|
-
hmrData.data.scheduler = null;
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
//* Getters & Setters ================================
|
|
1993
|
-
get phases() {
|
|
1994
|
-
return this.phaseGraph.getOrderedPhases();
|
|
1995
|
-
}
|
|
1996
|
-
get frameloop() {
|
|
1997
|
-
return this._frameloop;
|
|
1998
|
-
}
|
|
1999
|
-
set frameloop(mode) {
|
|
2000
|
-
if (this._frameloop === mode) return;
|
|
2001
|
-
const wasAlways = this._frameloop === "always";
|
|
2002
|
-
this._frameloop = mode;
|
|
2003
|
-
if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
|
|
2004
|
-
else if (mode !== "always" && wasAlways) this.stop();
|
|
2005
|
-
}
|
|
2006
|
-
get isRunning() {
|
|
2007
|
-
return this.loopState.running;
|
|
2008
|
-
}
|
|
2009
|
-
get isReady() {
|
|
2010
|
-
return this.roots.size > 0;
|
|
2011
|
-
}
|
|
2012
|
-
get independent() {
|
|
2013
|
-
return this._independent;
|
|
2014
|
-
}
|
|
2015
|
-
set independent(value) {
|
|
2016
|
-
this._independent = value;
|
|
2017
|
-
if (value) this.ensureDefaultRoot();
|
|
2018
|
-
}
|
|
2019
|
-
//* Root Management Methods ================================
|
|
2020
|
-
/**
|
|
2021
|
-
* Register a root (Canvas) with the scheduler.
|
|
2022
|
-
* The first root to register starts the RAF loop (if frameloop='always').
|
|
2023
|
-
* @param {string} id - Unique identifier for this root
|
|
2024
|
-
* @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
|
|
2025
|
-
* @returns {() => void} Unsubscribe function to remove this root
|
|
2026
|
-
*/
|
|
2027
|
-
registerRoot(id, options = {}) {
|
|
2028
|
-
if (this.roots.has(id)) {
|
|
2029
|
-
console.warn(`[Scheduler] Root "${id}" already registered`);
|
|
2030
|
-
return () => this.unregisterRoot(id);
|
|
2031
|
-
}
|
|
2032
|
-
const entry = {
|
|
2033
|
-
id,
|
|
2034
|
-
getState: options.getState ?? (() => ({})),
|
|
2035
|
-
jobs: /* @__PURE__ */ new Map(),
|
|
2036
|
-
sortedJobs: [],
|
|
2037
|
-
needsRebuild: false
|
|
2038
|
-
};
|
|
2039
|
-
if (options.onError) {
|
|
2040
|
-
this.errorHandler = options.onError;
|
|
2041
|
-
}
|
|
2042
|
-
this.roots.set(id, entry);
|
|
2043
|
-
if (this.roots.size === 1) {
|
|
2044
|
-
this.notifyRootReady();
|
|
2045
|
-
if (this._frameloop === "always") this.start();
|
|
2046
|
-
}
|
|
2047
|
-
return () => this.unregisterRoot(id);
|
|
2048
|
-
}
|
|
2049
|
-
/**
|
|
2050
|
-
* Unregister a root from the scheduler.
|
|
2051
|
-
* Cleans up all job state listeners for this root's jobs.
|
|
2052
|
-
* The last root to unregister stops the RAF loop.
|
|
2053
|
-
* @param {string} id - The root ID to unregister
|
|
2054
|
-
* @returns {void}
|
|
2055
|
-
*/
|
|
2056
|
-
unregisterRoot(id) {
|
|
2057
|
-
const root = this.roots.get(id);
|
|
2058
|
-
if (!root) return;
|
|
2059
|
-
for (const jobId of root.jobs.keys()) {
|
|
2060
|
-
this.jobStateListeners.delete(jobId);
|
|
2061
|
-
}
|
|
2062
|
-
this.roots.delete(id);
|
|
2063
|
-
if (this.roots.size === 0) {
|
|
2064
|
-
this.stop();
|
|
2065
|
-
this.errorHandler = null;
|
|
2066
|
-
}
|
|
2067
|
-
}
|
|
2068
|
-
/**
|
|
2069
|
-
* Subscribe to be notified when a root becomes available.
|
|
2070
|
-
* Fires immediately if a root already exists.
|
|
2071
|
-
* @param {() => void} callback - Function called when first root registers
|
|
2072
|
-
* @returns {() => void} Unsubscribe function
|
|
2073
|
-
*/
|
|
2074
|
-
onRootReady(callback) {
|
|
2075
|
-
if (this.roots.size > 0) {
|
|
2076
|
-
callback();
|
|
2077
|
-
return () => {
|
|
2078
|
-
};
|
|
2079
|
-
}
|
|
2080
|
-
this.rootReadyCallbacks.add(callback);
|
|
2081
|
-
return () => this.rootReadyCallbacks.delete(callback);
|
|
2082
|
-
}
|
|
2083
|
-
/**
|
|
2084
|
-
* Notify all registered root-ready callbacks.
|
|
2085
|
-
* Called when the first root registers.
|
|
2086
|
-
* @returns {void}
|
|
2087
|
-
* @private
|
|
2088
|
-
*/
|
|
2089
|
-
notifyRootReady() {
|
|
2090
|
-
for (const cb of this.rootReadyCallbacks) {
|
|
2091
|
-
try {
|
|
2092
|
-
cb();
|
|
2093
|
-
} catch (error) {
|
|
2094
|
-
console.error("[Scheduler] Error in root-ready callback:", error);
|
|
2095
|
-
}
|
|
2096
|
-
}
|
|
2097
|
-
this.rootReadyCallbacks.clear();
|
|
2098
|
-
}
|
|
2099
|
-
/**
|
|
2100
|
-
* Ensure a default root exists for independent mode.
|
|
2101
|
-
* Creates a minimal root with no state provider.
|
|
2102
|
-
* @returns {void}
|
|
2103
|
-
* @private
|
|
2104
|
-
*/
|
|
2105
|
-
ensureDefaultRoot() {
|
|
2106
|
-
if (!this.roots.has("__default__")) {
|
|
2107
|
-
this.registerRoot("__default__");
|
|
2108
|
-
}
|
|
2109
|
-
}
|
|
2110
|
-
/**
|
|
2111
|
-
* Trigger error handling for job errors.
|
|
2112
|
-
* Uses the bound error handler if available, otherwise logs to console.
|
|
2113
|
-
* @param {Error} error - The error to handle
|
|
2114
|
-
* @returns {void}
|
|
2115
|
-
*/
|
|
2116
|
-
triggerError(error) {
|
|
2117
|
-
if (this.errorHandler) this.errorHandler(error);
|
|
2118
|
-
else console.error("[Scheduler]", error);
|
|
2119
|
-
}
|
|
2120
|
-
//* Phase Management Methods ================================
|
|
2121
|
-
/**
|
|
2122
|
-
* Add a named phase to the scheduler's execution order.
|
|
2123
|
-
* Marks all roots for rebuild to incorporate the new phase.
|
|
2124
|
-
* @param {string} name - The phase name (e.g., 'physics', 'postprocess')
|
|
2125
|
-
* @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
|
|
2126
|
-
* @returns {void}
|
|
2127
|
-
* @example
|
|
2128
|
-
* scheduler.addPhase('physics', { before: 'update' });
|
|
2129
|
-
* scheduler.addPhase('postprocess', { after: 'render' });
|
|
2130
|
-
*/
|
|
2131
|
-
addPhase(name, options) {
|
|
2132
|
-
this.phaseGraph.addPhase(name, options);
|
|
2133
|
-
for (const root of this.roots.values()) {
|
|
2134
|
-
root.needsRebuild = true;
|
|
2135
|
-
}
|
|
2136
|
-
}
|
|
2137
|
-
/**
|
|
2138
|
-
* Check if a phase exists in the scheduler.
|
|
2139
|
-
* @param {string} name - The phase name to check
|
|
2140
|
-
* @returns {boolean} True if the phase exists
|
|
2141
|
-
*/
|
|
2142
|
-
hasPhase(name) {
|
|
2143
|
-
return this.phaseGraph.hasPhase(name);
|
|
2144
|
-
}
|
|
2145
|
-
//* Global Job Registration Methods (Deprecated APIs) ================================
|
|
2146
|
-
/**
|
|
2147
|
-
* Register a global job that runs once per frame (not per-root).
|
|
2148
|
-
* Used internally by deprecated addEffect/addAfterEffect APIs.
|
|
2149
|
-
* @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
|
|
2150
|
-
* @param {string} id - Unique identifier for this global job
|
|
2151
|
-
* @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
|
|
2152
|
-
* @returns {() => void} Unsubscribe function to remove this global job
|
|
2153
|
-
* @deprecated Use useFrame with phases instead
|
|
2154
|
-
*/
|
|
2155
|
-
registerGlobal(phase, id, callback) {
|
|
2156
|
-
const job = { id, callback };
|
|
2157
|
-
if (phase === "before") {
|
|
2158
|
-
this.globalBeforeJobs.set(id, job);
|
|
2159
|
-
} else {
|
|
2160
|
-
this.globalAfterJobs.set(id, job);
|
|
2161
|
-
}
|
|
2162
|
-
return () => {
|
|
2163
|
-
if (phase === "before") this.globalBeforeJobs.delete(id);
|
|
2164
|
-
else this.globalAfterJobs.delete(id);
|
|
2165
|
-
};
|
|
2166
|
-
}
|
|
2167
|
-
//* Idle Callback Methods (Deprecated API) ================================
|
|
2168
|
-
/**
|
|
2169
|
-
* Register an idle callback that fires when the loop stops.
|
|
2170
|
-
* Used internally by deprecated addTail API.
|
|
2171
|
-
* @param {(timestamp: number) => void} callback - Function called when loop becomes idle
|
|
2172
|
-
* @returns {() => void} Unsubscribe function to remove this idle callback
|
|
2173
|
-
* @deprecated Use demand mode with invalidate() instead
|
|
2174
|
-
*/
|
|
2175
|
-
onIdle(callback) {
|
|
2176
|
-
this.idleCallbacks.add(callback);
|
|
2177
|
-
return () => this.idleCallbacks.delete(callback);
|
|
2178
|
-
}
|
|
2179
|
-
/**
|
|
2180
|
-
* Notify all registered idle callbacks.
|
|
2181
|
-
* Called when the loop stops in demand mode.
|
|
2182
|
-
* @param {number} timestamp - The RAF timestamp when idle occurred
|
|
2183
|
-
* @returns {void}
|
|
2184
|
-
* @private
|
|
2185
|
-
*/
|
|
2186
|
-
notifyIdle(timestamp) {
|
|
2187
|
-
for (const cb of this.idleCallbacks) {
|
|
2188
|
-
try {
|
|
2189
|
-
cb(timestamp);
|
|
2190
|
-
} catch (error) {
|
|
2191
|
-
console.error("[Scheduler] Error in idle callback:", error);
|
|
2192
|
-
}
|
|
2193
|
-
}
|
|
2194
|
-
}
|
|
2195
|
-
//* Job Registration & Management Methods ================================
|
|
2196
|
-
/**
|
|
2197
|
-
* Register a job (frame callback) with a specific root.
|
|
2198
|
-
* This is the core registration method used by useFrame internally.
|
|
2199
|
-
* @param {FrameNextCallback} callback - The function to call each frame
|
|
2200
|
-
* @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
|
|
2201
|
-
* @param {string} [options.rootId] - Target root ID (defaults to first registered root)
|
|
2202
|
-
* @param {string} [options.id] - Unique job ID (auto-generated if not provided)
|
|
2203
|
-
* @param {string} [options.phase] - Execution phase (defaults to 'update')
|
|
2204
|
-
* @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
|
|
2205
|
-
* @param {number} [options.fps] - FPS throttle limit
|
|
2206
|
-
* @param {boolean} [options.drop] - Drop frames when behind (default true)
|
|
2207
|
-
* @param {boolean} [options.enabled] - Whether job is active (default true)
|
|
2208
|
-
* @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
|
|
2209
|
-
* @returns {() => void} Unsubscribe function to remove this job
|
|
2210
|
-
*/
|
|
2211
|
-
register(callback, options = {}) {
|
|
2212
|
-
const rootId = options.rootId;
|
|
2213
|
-
const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
|
|
2214
|
-
if (!root) {
|
|
2215
|
-
console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
|
|
2216
|
-
return () => {
|
|
2217
|
-
};
|
|
2218
|
-
}
|
|
2219
|
-
const id = options.id ?? this.generateJobId();
|
|
2220
|
-
let phase = options.phase ?? "update";
|
|
2221
|
-
if (!options.phase && (options.before || options.after)) {
|
|
2222
|
-
phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
|
|
2223
|
-
}
|
|
2224
|
-
const before = this.normalizeConstraints(options.before);
|
|
2225
|
-
const after = this.normalizeConstraints(options.after);
|
|
2226
|
-
const job = {
|
|
2227
|
-
id,
|
|
2228
|
-
callback,
|
|
2229
|
-
phase,
|
|
2230
|
-
before,
|
|
2231
|
-
after,
|
|
2232
|
-
priority: options.priority ?? 0,
|
|
2233
|
-
index: this.nextJobIndex++,
|
|
2234
|
-
fps: options.fps,
|
|
2235
|
-
drop: options.drop ?? true,
|
|
2236
|
-
enabled: options.enabled ?? true,
|
|
2237
|
-
system: options.system ?? false
|
|
2238
|
-
};
|
|
2239
|
-
if (root.jobs.has(id)) {
|
|
2240
|
-
console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
|
|
2241
|
-
}
|
|
2242
|
-
root.jobs.set(id, job);
|
|
2243
|
-
root.needsRebuild = true;
|
|
2244
|
-
return () => this.unregister(id, root.id);
|
|
2245
|
-
}
|
|
2246
|
-
/**
|
|
2247
|
-
* Unregister a job by its ID.
|
|
2248
|
-
* Searches all roots if rootId is not provided.
|
|
2249
|
-
* @param {string} id - The job ID to unregister
|
|
2250
|
-
* @param {string} [rootId] - Optional root ID to search (searches all if not provided)
|
|
2251
|
-
* @returns {void}
|
|
2252
|
-
*/
|
|
2253
|
-
unregister(id, rootId) {
|
|
2254
|
-
const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
|
|
2255
|
-
if (root?.jobs.delete(id)) {
|
|
2256
|
-
root.needsRebuild = true;
|
|
2257
|
-
this.jobStateListeners.delete(id);
|
|
2258
|
-
}
|
|
2259
|
-
}
|
|
2260
|
-
/**
|
|
2261
|
-
* Update a job's options dynamically.
|
|
2262
|
-
* Searches all roots to find the job by ID.
|
|
2263
|
-
* Phase/constraint changes trigger a rebuild of the sorted job list.
|
|
2264
|
-
* @param {string} id - The job ID to update
|
|
2265
|
-
* @param {Partial<JobOptions>} options - The options to update
|
|
2266
|
-
* @returns {void}
|
|
2267
|
-
*/
|
|
2268
|
-
updateJob(id, options) {
|
|
2269
|
-
let job;
|
|
2270
|
-
let root;
|
|
2271
|
-
for (const r of this.roots.values()) {
|
|
2272
|
-
job = r.jobs.get(id);
|
|
2273
|
-
if (job) {
|
|
2274
|
-
root = r;
|
|
2275
|
-
break;
|
|
2276
|
-
}
|
|
2277
|
-
}
|
|
2278
|
-
if (!job || !root) return;
|
|
2279
|
-
if (options.priority !== void 0) job.priority = options.priority;
|
|
2280
|
-
if (options.fps !== void 0) job.fps = options.fps;
|
|
2281
|
-
if (options.drop !== void 0) job.drop = options.drop;
|
|
2282
|
-
if (options.enabled !== void 0) {
|
|
2283
|
-
const wasEnabled = job.enabled;
|
|
2284
|
-
job.enabled = options.enabled;
|
|
2285
|
-
if (!wasEnabled && job.enabled) resetJobTiming(job);
|
|
2286
|
-
if (wasEnabled !== job.enabled) root.needsRebuild = true;
|
|
2287
|
-
}
|
|
2288
|
-
if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
|
|
2289
|
-
if (options.phase) job.phase = options.phase;
|
|
2290
|
-
if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
|
|
2291
|
-
if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
|
|
2292
|
-
root.needsRebuild = true;
|
|
2293
|
-
}
|
|
2294
|
-
}
|
|
2295
|
-
//* Job State Management Methods ================================
|
|
2296
|
-
/**
|
|
2297
|
-
* Check if a job is currently paused (disabled).
|
|
2298
|
-
* @param {string} id - The job ID to check
|
|
2299
|
-
* @returns {boolean} True if the job exists and is paused
|
|
2300
|
-
*/
|
|
2301
|
-
isJobPaused(id) {
|
|
2302
|
-
for (const root of this.roots.values()) {
|
|
2303
|
-
const job = root.jobs.get(id);
|
|
2304
|
-
if (job) return !job.enabled;
|
|
2305
|
-
}
|
|
2306
|
-
return false;
|
|
2307
|
-
}
|
|
2308
|
-
/**
|
|
2309
|
-
* Subscribe to state changes for a specific job.
|
|
2310
|
-
* Listener is called when job is paused or resumed.
|
|
2311
|
-
* @param {string} id - The job ID to subscribe to
|
|
2312
|
-
* @param {() => void} listener - Callback invoked on state changes
|
|
2313
|
-
* @returns {() => void} Unsubscribe function
|
|
2314
|
-
*/
|
|
2315
|
-
subscribeJobState(id, listener) {
|
|
2316
|
-
if (!this.jobStateListeners.has(id)) {
|
|
2317
|
-
this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
|
|
2318
|
-
}
|
|
2319
|
-
this.jobStateListeners.get(id).add(listener);
|
|
2320
|
-
return () => {
|
|
2321
|
-
this.jobStateListeners.get(id)?.delete(listener);
|
|
2322
|
-
if (this.jobStateListeners.get(id)?.size === 0) {
|
|
2323
|
-
this.jobStateListeners.delete(id);
|
|
2324
|
-
}
|
|
2325
|
-
};
|
|
2326
|
-
}
|
|
2327
|
-
/**
|
|
2328
|
-
* Notify all listeners that a job's state has changed.
|
|
2329
|
-
* @param {string} id - The job ID that changed
|
|
2330
|
-
* @returns {void}
|
|
2331
|
-
* @private
|
|
2332
|
-
*/
|
|
2333
|
-
notifyJobStateChange(id) {
|
|
2334
|
-
this.jobStateListeners.get(id)?.forEach((listener) => listener());
|
|
2335
|
-
}
|
|
2336
|
-
/**
|
|
2337
|
-
* Pause a job by ID (sets enabled=false).
|
|
2338
|
-
* Notifies any subscribed state listeners.
|
|
2339
|
-
* @param {string} id - The job ID to pause
|
|
2340
|
-
* @returns {void}
|
|
2341
|
-
*/
|
|
2342
|
-
pauseJob(id) {
|
|
2343
|
-
this.updateJob(id, { enabled: false });
|
|
2344
|
-
this.notifyJobStateChange(id);
|
|
2345
|
-
}
|
|
2346
|
-
/**
|
|
2347
|
-
* Resume a paused job by ID (sets enabled=true).
|
|
2348
|
-
* Resets job timing to prevent frame accumulation.
|
|
2349
|
-
* Notifies any subscribed state listeners.
|
|
2350
|
-
* @param {string} id - The job ID to resume
|
|
2351
|
-
* @returns {void}
|
|
2352
|
-
*/
|
|
2353
|
-
resumeJob(id) {
|
|
2354
|
-
this.updateJob(id, { enabled: true });
|
|
2355
|
-
this.notifyJobStateChange(id);
|
|
2356
|
-
}
|
|
2357
|
-
//* Frame Loop Control Methods ================================
|
|
2358
|
-
/**
|
|
2359
|
-
* Start the requestAnimationFrame loop.
|
|
2360
|
-
* Resets timing state (elapsedTime, frameCount) on start.
|
|
2361
|
-
* No-op if already running.
|
|
2362
|
-
* @returns {void}
|
|
2363
|
-
*/
|
|
2364
|
-
start() {
|
|
2365
|
-
if (this.loopState.running) return;
|
|
2366
|
-
const { elapsedTime, createdAt } = this.loopState;
|
|
2367
|
-
let adjustedCreated = 0;
|
|
2368
|
-
if (this.stoppedTime > 0) {
|
|
2369
|
-
adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
|
|
2370
|
-
this.stoppedTime = 0;
|
|
2371
|
-
}
|
|
2372
|
-
Object.assign(this.loopState, {
|
|
2373
|
-
running: true,
|
|
2374
|
-
elapsedTime: elapsedTime ?? 0,
|
|
2375
|
-
lastTime: performance.now(),
|
|
2376
|
-
createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
|
|
2377
|
-
frameCount: 0,
|
|
2378
|
-
rafHandle: requestAnimationFrame(this.loop)
|
|
2379
|
-
});
|
|
2380
|
-
}
|
|
2381
|
-
/**
|
|
2382
|
-
* Stop the requestAnimationFrame loop.
|
|
2383
|
-
* Cancels any pending RAF callback.
|
|
2384
|
-
* No-op if not running.
|
|
2385
|
-
* @returns {void}
|
|
2386
|
-
*/
|
|
2387
|
-
stop() {
|
|
2388
|
-
if (!this.loopState.running) return;
|
|
2389
|
-
this.loopState.running = false;
|
|
2390
|
-
if (this.loopState.rafHandle !== null) {
|
|
2391
|
-
cancelAnimationFrame(this.loopState.rafHandle);
|
|
2392
|
-
this.loopState.rafHandle = null;
|
|
2393
|
-
}
|
|
2394
|
-
this.stoppedTime = performance.now();
|
|
2395
|
-
}
|
|
2396
|
-
/**
|
|
2397
|
-
* Request frames to be rendered in demand mode.
|
|
2398
|
-
* Accumulates pending frames (capped at 60) and starts the loop if not running.
|
|
2399
|
-
* No-op if frameloop is not 'demand'.
|
|
2400
|
-
* @param {number} [frames=1] - Number of frames to request
|
|
2401
|
-
* @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
|
|
2402
|
-
* - `false` (default): Sets pending frames to the specified value (replaces existing count)
|
|
2403
|
-
* - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
|
|
2404
|
-
* @returns {void}
|
|
2405
|
-
* @example
|
|
2406
|
-
* // Request a single frame render
|
|
2407
|
-
* scheduler.invalidate();
|
|
2408
|
-
*
|
|
2409
|
-
* @example
|
|
2410
|
-
* // Request 5 frames (e.g., for animations)
|
|
2411
|
-
* scheduler.invalidate(5);
|
|
2412
|
-
*
|
|
2413
|
-
* @example
|
|
2414
|
-
* // Set pending frames to exactly 3 (don't stack with existing)
|
|
2415
|
-
* scheduler.invalidate(3, false);
|
|
2416
|
-
*
|
|
2417
|
-
* @example
|
|
2418
|
-
* // Add 2 more frames to existing pending count
|
|
2419
|
-
* scheduler.invalidate(2, true);
|
|
2420
|
-
*/
|
|
2421
|
-
invalidate(frames = 1, stackFrames = false) {
|
|
2422
|
-
if (this._frameloop !== "demand") return;
|
|
2423
|
-
const baseFrames = stackFrames ? this.pendingFrames : 0;
|
|
2424
|
-
this.pendingFrames = Math.min(60, baseFrames + frames);
|
|
2425
|
-
if (!this.loopState.running && this.pendingFrames > 0) this.start();
|
|
2426
|
-
}
|
|
2427
|
-
/**
|
|
2428
|
-
* Reset timing state for deterministic testing.
|
|
2429
|
-
* Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
|
|
2430
|
-
* @returns {void}
|
|
2431
|
-
*/
|
|
2432
|
-
resetTiming() {
|
|
2433
|
-
this.loopState.lastTime = null;
|
|
2434
|
-
this.loopState.frameCount = 0;
|
|
2435
|
-
this.loopState.elapsedTime = 0;
|
|
2436
|
-
this.loopState.createdAt = performance.now();
|
|
2437
|
-
}
|
|
2438
|
-
//* Manual Stepping Methods ================================
|
|
2439
|
-
/**
|
|
2440
|
-
* Manually execute a single frame for all roots.
|
|
2441
|
-
* Useful for frameloop='never' mode or testing scenarios.
|
|
2442
|
-
* @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
|
|
2443
|
-
* @returns {void}
|
|
2444
|
-
* @example
|
|
2445
|
-
* // Manual control mode
|
|
2446
|
-
* scheduler.frameloop = 'never';
|
|
2447
|
-
* scheduler.step(); // Execute one frame
|
|
2448
|
-
*/
|
|
2449
|
-
step(timestamp) {
|
|
2450
|
-
const now = timestamp ?? performance.now();
|
|
2451
|
-
this.executeFrame(now);
|
|
2452
|
-
}
|
|
2453
|
-
/**
|
|
2454
|
-
* Manually execute a single job by its ID.
|
|
2455
|
-
* Useful for testing individual job callbacks in isolation.
|
|
2456
|
-
* @param {string} id - The job ID to step
|
|
2457
|
-
* @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
|
|
2458
|
-
* @returns {void}
|
|
2459
|
-
*/
|
|
2460
|
-
stepJob(id, timestamp) {
|
|
2461
|
-
let job;
|
|
2462
|
-
let root;
|
|
2463
|
-
for (const r of this.roots.values()) {
|
|
2464
|
-
job = r.jobs.get(id);
|
|
2465
|
-
if (job) {
|
|
2466
|
-
root = r;
|
|
2467
|
-
break;
|
|
2468
|
-
}
|
|
2469
|
-
}
|
|
2470
|
-
if (!job || !root) {
|
|
2471
|
-
console.warn(`[Scheduler] Job "${id}" not found`);
|
|
2472
|
-
return;
|
|
2473
|
-
}
|
|
2474
|
-
const now = timestamp ?? performance.now();
|
|
2475
|
-
const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
|
|
2476
|
-
const delta = deltaMs / 1e3;
|
|
2477
|
-
const elapsed = now - this.loopState.createdAt;
|
|
2478
|
-
const providedState = root.getState?.() ?? {};
|
|
2479
|
-
const frameState = {
|
|
2480
|
-
...providedState,
|
|
2481
|
-
time: now,
|
|
2482
|
-
delta,
|
|
2483
|
-
elapsed,
|
|
2484
|
-
frame: this.loopState.frameCount
|
|
2485
|
-
};
|
|
2486
|
-
try {
|
|
2487
|
-
job.callback(frameState, delta);
|
|
2488
|
-
} catch (error) {
|
|
2489
|
-
console.error(`[Scheduler] Error in job "${job.id}":`, error);
|
|
2490
|
-
this.triggerError(error instanceof Error ? error : new Error(String(error)));
|
|
2491
|
-
}
|
|
2492
|
-
}
|
|
2493
|
-
/**
|
|
2494
|
-
* Execute a single frame across all roots.
|
|
2495
|
-
* Order: globalBefore → each root's jobs → globalAfter
|
|
2496
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
2497
|
-
* @returns {void}
|
|
2498
|
-
* @private
|
|
2499
|
-
*/
|
|
2500
|
-
executeFrame(timestamp) {
|
|
2501
|
-
const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
|
|
2502
|
-
const delta = deltaMs / 1e3;
|
|
2503
|
-
this.loopState.lastTime = timestamp;
|
|
2504
|
-
this.loopState.frameCount++;
|
|
2505
|
-
this.loopState.elapsedTime += deltaMs;
|
|
2506
|
-
this.runGlobalJobs(this.globalBeforeJobs, timestamp);
|
|
2507
|
-
for (const root of this.roots.values()) {
|
|
2508
|
-
this.tickRoot(root, timestamp, delta);
|
|
2509
|
-
}
|
|
2510
|
-
this.runGlobalJobs(this.globalAfterJobs, timestamp);
|
|
2511
|
-
}
|
|
2512
|
-
/**
|
|
2513
|
-
* Run all global jobs from a job map.
|
|
2514
|
-
* Catches and logs errors without stopping execution.
|
|
2515
|
-
* @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
|
|
2516
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
2517
|
-
* @returns {void}
|
|
2518
|
-
* @private
|
|
2519
|
-
*/
|
|
2520
|
-
runGlobalJobs(jobs, timestamp) {
|
|
2521
|
-
for (const job of jobs.values()) {
|
|
2522
|
-
try {
|
|
2523
|
-
job.callback(timestamp);
|
|
2524
|
-
} catch (error) {
|
|
2525
|
-
console.error(`[Scheduler] Error in global job "${job.id}":`, error);
|
|
2526
|
-
}
|
|
2527
|
-
}
|
|
2528
|
-
}
|
|
2529
|
-
/**
|
|
2530
|
-
* Execute all jobs for a single root in sorted order.
|
|
2531
|
-
* Rebuilds sorted job list if needed, then dispatches each job.
|
|
2532
|
-
* Errors are caught and propagated via triggerError.
|
|
2533
|
-
* @param {RootEntry} root - The root entry to tick
|
|
2534
|
-
* @param {number} timestamp - RAF timestamp in milliseconds
|
|
2535
|
-
* @param {number} delta - Time since last frame in seconds
|
|
2536
|
-
* @returns {void}
|
|
2537
|
-
* @private
|
|
2538
|
-
*/
|
|
2539
|
-
tickRoot(root, timestamp, delta) {
|
|
2540
|
-
if (root.needsRebuild) {
|
|
2541
|
-
root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
|
|
2542
|
-
root.needsRebuild = false;
|
|
2543
|
-
}
|
|
2544
|
-
const providedState = root.getState?.() ?? {};
|
|
2545
|
-
const frameState = {
|
|
2546
|
-
...providedState,
|
|
2547
|
-
time: timestamp,
|
|
2548
|
-
delta,
|
|
2549
|
-
elapsed: this.loopState.elapsedTime / 1e3,
|
|
2550
|
-
// Convert ms to seconds
|
|
2551
|
-
frame: this.loopState.frameCount
|
|
2552
|
-
};
|
|
2553
|
-
for (const job of root.sortedJobs) {
|
|
2554
|
-
if (!shouldRun(job, timestamp)) continue;
|
|
2555
|
-
try {
|
|
2556
|
-
job.callback(frameState, delta);
|
|
2557
|
-
} catch (error) {
|
|
2558
|
-
console.error(`[Scheduler] Error in job "${job.id}":`, error);
|
|
2559
|
-
this.triggerError(error instanceof Error ? error : new Error(String(error)));
|
|
2560
|
-
}
|
|
2561
|
-
}
|
|
2562
|
-
}
|
|
2563
|
-
//* Debug & Inspection Methods ================================
|
|
2564
|
-
/**
|
|
2565
|
-
* Get the total number of registered jobs across all roots.
|
|
2566
|
-
* Includes both per-root jobs and global before/after jobs.
|
|
2567
|
-
* @returns {number} Total job count
|
|
2568
|
-
*/
|
|
2569
|
-
getJobCount() {
|
|
2570
|
-
let count = 0;
|
|
2571
|
-
for (const root of this.roots.values()) {
|
|
2572
|
-
count += root.jobs.size;
|
|
2573
|
-
}
|
|
2574
|
-
return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
|
|
2575
|
-
}
|
|
2576
|
-
/**
|
|
2577
|
-
* Get all registered job IDs across all roots.
|
|
2578
|
-
* Includes both per-root jobs and global before/after jobs.
|
|
2579
|
-
* @returns {string[]} Array of all job IDs
|
|
2580
|
-
*/
|
|
2581
|
-
getJobIds() {
|
|
2582
|
-
const ids = [];
|
|
2583
|
-
for (const root of this.roots.values()) {
|
|
2584
|
-
ids.push(...root.jobs.keys());
|
|
2585
|
-
}
|
|
2586
|
-
ids.push(...this.globalBeforeJobs.keys());
|
|
2587
|
-
ids.push(...this.globalAfterJobs.keys());
|
|
2588
|
-
return ids;
|
|
2589
|
-
}
|
|
2590
|
-
/**
|
|
2591
|
-
* Get the number of registered roots (Canvas instances).
|
|
2592
|
-
* @returns {number} Number of registered roots
|
|
2593
|
-
*/
|
|
2594
|
-
getRootCount() {
|
|
2595
|
-
return this.roots.size;
|
|
2596
|
-
}
|
|
2597
|
-
/**
|
|
2598
|
-
* Check if any user (non-system) jobs are registered in a specific phase.
|
|
2599
|
-
* Used by the default render job to know if a user has taken over rendering.
|
|
2600
|
-
*
|
|
2601
|
-
* @param phase The phase to check
|
|
2602
|
-
* @param rootId Optional root ID to check (checks all roots if not provided)
|
|
2603
|
-
* @returns true if any user jobs exist in the phase
|
|
2604
|
-
*/
|
|
2605
|
-
hasUserJobsInPhase(phase, rootId) {
|
|
2606
|
-
const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
|
|
2607
|
-
return rootsToCheck.some((root) => {
|
|
2608
|
-
if (!root) return false;
|
|
2609
|
-
for (const job of root.jobs.values()) {
|
|
2610
|
-
if (job.phase === phase && !job.system && job.enabled) return true;
|
|
2611
|
-
}
|
|
2612
|
-
return false;
|
|
2613
|
-
});
|
|
2614
|
-
}
|
|
2615
|
-
//* Utility Methods ================================
|
|
2616
|
-
/**
|
|
2617
|
-
* Generate a unique root ID for automatic root registration.
|
|
2618
|
-
* @returns {string} A unique root ID in the format 'root_N'
|
|
2619
|
-
*/
|
|
2620
|
-
generateRootId() {
|
|
2621
|
-
return `root_${this.nextRootIndex++}`;
|
|
2622
|
-
}
|
|
2623
|
-
/**
|
|
2624
|
-
* Generate a unique job ID.
|
|
2625
|
-
* @returns {string} A unique job ID in the format 'job_N'
|
|
2626
|
-
* @private
|
|
2627
|
-
*/
|
|
2628
|
-
generateJobId() {
|
|
2629
|
-
return `job_${this.nextJobIndex}`;
|
|
2630
|
-
}
|
|
2631
|
-
/**
|
|
2632
|
-
* Normalize before/after constraints to a Set.
|
|
2633
|
-
* Handles undefined, single string, or array inputs.
|
|
2634
|
-
* @param {string | string[] | undefined} value - The constraint value(s)
|
|
2635
|
-
* @returns {Set<string>} Normalized Set of constraint strings
|
|
2636
|
-
* @private
|
|
2637
|
-
*/
|
|
2638
|
-
normalizeConstraints(value) {
|
|
2639
|
-
if (!value) return /* @__PURE__ */ new Set();
|
|
2640
|
-
if (Array.isArray(value)) return new Set(value);
|
|
2641
|
-
return /* @__PURE__ */ new Set([value]);
|
|
2642
|
-
}
|
|
2643
|
-
};
|
|
2644
|
-
//* Static State & Methods (Singleton Usage) ================================
|
|
2645
|
-
//* Cross-Bundle Singleton Key ==============================
|
|
2646
|
-
// Use Symbol.for() to ensure scheduler is shared across bundle boundaries
|
|
2647
|
-
// This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
|
|
2648
|
-
__publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
|
|
2649
|
-
let Scheduler = _Scheduler;
|
|
2650
|
-
const getScheduler = () => Scheduler.get();
|
|
2651
|
-
if (hmrData) {
|
|
2652
|
-
hmrData.accept?.();
|
|
1671
|
+
const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
|
|
1672
|
+
function isInternalRendererAccess(stack, callerDepth = 2) {
|
|
1673
|
+
if (!stack) return false;
|
|
1674
|
+
const caller = stack.split("\n")[callerDepth] ?? "";
|
|
1675
|
+
return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
|
|
2653
1676
|
}
|
|
2654
1677
|
|
|
2655
1678
|
const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
|
|
@@ -2784,6 +1807,7 @@ const createStore = (invalidate, advance) => {
|
|
|
2784
1807
|
}),
|
|
2785
1808
|
setFrameloop: (frameloop = "always") => {
|
|
2786
1809
|
set(() => ({ frameloop }));
|
|
1810
|
+
getScheduler().frameloop = frameloop;
|
|
2787
1811
|
},
|
|
2788
1812
|
setError: (error) => set(() => ({ error })),
|
|
2789
1813
|
error: null,
|
|
@@ -2793,6 +1817,7 @@ const createStore = (invalidate, advance) => {
|
|
|
2793
1817
|
buffers: {},
|
|
2794
1818
|
gpuStorage: {},
|
|
2795
1819
|
textures: /* @__PURE__ */ new Map(),
|
|
1820
|
+
_textureRefs: /* @__PURE__ */ new Map(),
|
|
2796
1821
|
renderPipeline: null,
|
|
2797
1822
|
passes: {},
|
|
2798
1823
|
_hmrVersion: 0,
|
|
@@ -2850,8 +1875,7 @@ const createStore = (invalidate, advance) => {
|
|
|
2850
1875
|
const currentState = rootStore.getState();
|
|
2851
1876
|
if (!currentState.isLegacy && currentState.internal.actualRenderer) {
|
|
2852
1877
|
const stack = new Error().stack || "";
|
|
2853
|
-
|
|
2854
|
-
if (!isInternalAccess) {
|
|
1878
|
+
if (!isInternalRendererAccess(stack)) {
|
|
2855
1879
|
const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
|
|
2856
1880
|
notifyDepreciated({
|
|
2857
1881
|
heading: "Accessing state.gl in WebGPU mode",
|
|
@@ -2899,14 +1923,16 @@ const createStore = (invalidate, advance) => {
|
|
|
2899
1923
|
oldSize = size;
|
|
2900
1924
|
oldDpr = viewport.dpr;
|
|
2901
1925
|
updateCamera(camera, size);
|
|
2902
|
-
if (canvasTarget) {
|
|
1926
|
+
if (internal.isSecondary && canvasTarget) {
|
|
2903
1927
|
if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
|
|
2904
|
-
|
|
2905
|
-
canvasTarget.setSize(size.width, size.height, updateStyle);
|
|
1928
|
+
canvasTarget.setSize(size.width, size.height, false);
|
|
2906
1929
|
} else {
|
|
2907
1930
|
if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
|
|
2908
|
-
|
|
2909
|
-
|
|
1931
|
+
actualRenderer.setSize(size.width, size.height, false);
|
|
1932
|
+
if (canvasTarget) {
|
|
1933
|
+
if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
|
|
1934
|
+
canvasTarget.setSize(size.width, size.height, false);
|
|
1935
|
+
}
|
|
2910
1936
|
}
|
|
2911
1937
|
}
|
|
2912
1938
|
if (camera !== oldCamera) {
|
|
@@ -2962,19 +1988,25 @@ function loadingFn(extensions, onProgress) {
|
|
|
2962
1988
|
);
|
|
2963
1989
|
};
|
|
2964
1990
|
}
|
|
2965
|
-
function useLoader(loader, input, extensions, onProgress) {
|
|
2966
|
-
const
|
|
1991
|
+
function useLoader(loader, input, extensions, onProgress, cacheKey) {
|
|
1992
|
+
const inputs = Array.isArray(input) ? input : [input];
|
|
1993
|
+
const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
|
|
2967
1994
|
const fn = loadingFn(extensions, onProgress);
|
|
2968
|
-
const results =
|
|
1995
|
+
const results = cacheKeys.map(
|
|
1996
|
+
(key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
|
|
1997
|
+
);
|
|
2969
1998
|
return Array.isArray(input) ? results : results[0];
|
|
2970
1999
|
}
|
|
2971
|
-
useLoader.preload = function(loader, input, extensions, onProgress) {
|
|
2972
|
-
const
|
|
2973
|
-
|
|
2000
|
+
useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
|
|
2001
|
+
const inputs = Array.isArray(input) ? input : [input];
|
|
2002
|
+
const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
|
|
2003
|
+
cacheKeys.forEach(
|
|
2004
|
+
(key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
|
|
2005
|
+
);
|
|
2974
2006
|
};
|
|
2975
|
-
useLoader.clear = function(loader, input) {
|
|
2976
|
-
const
|
|
2977
|
-
|
|
2007
|
+
useLoader.clear = function(loader, input, cacheKey) {
|
|
2008
|
+
const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
|
|
2009
|
+
cacheKeys.forEach((key) => clear([loader, key]));
|
|
2978
2010
|
};
|
|
2979
2011
|
useLoader.loader = getLoader;
|
|
2980
2012
|
|
|
@@ -3050,20 +2082,14 @@ function useFrame(callback, priorityOrOptions) {
|
|
|
3050
2082
|
}
|
|
3051
2083
|
};
|
|
3052
2084
|
} else {
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
unregisterJob = registerOutside();
|
|
3062
|
-
});
|
|
3063
|
-
return () => {
|
|
3064
|
-
unsubReady();
|
|
3065
|
-
unregisterJob?.();
|
|
3066
|
-
};
|
|
2085
|
+
return scheduler.register(
|
|
2086
|
+
(state, delta) => {
|
|
2087
|
+
const frameState = state;
|
|
2088
|
+
if (!frameState.renderer) return;
|
|
2089
|
+
callbackRef.current?.(frameState, delta);
|
|
2090
|
+
},
|
|
2091
|
+
{ id, ...options }
|
|
2092
|
+
);
|
|
3067
2093
|
}
|
|
3068
2094
|
}, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
|
|
3069
2095
|
const isPaused = React.useSyncExternalStore(
|
|
@@ -3154,18 +2180,18 @@ function buildFromCache(input, textureCache) {
|
|
|
3154
2180
|
function useTexture(input, optionsOrOnLoad) {
|
|
3155
2181
|
const renderer = useThree((state) => state.internal.actualRenderer);
|
|
3156
2182
|
const store = useStore();
|
|
3157
|
-
const textureCache = useThree((state) => state.textures);
|
|
3158
2183
|
const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
|
|
3159
|
-
const { onLoad, cache =
|
|
2184
|
+
const { onLoad, cache = true } = options;
|
|
3160
2185
|
const onLoadRef = useRef(onLoad);
|
|
3161
2186
|
onLoadRef.current = onLoad;
|
|
3162
2187
|
const onLoadCalledForRef = useRef(null);
|
|
3163
2188
|
const urls = useMemo(() => getUrls(input), [input]);
|
|
3164
2189
|
const cachedResult = useMemo(() => {
|
|
3165
2190
|
if (!cache) return null;
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
2191
|
+
const textures = store.getState().textures;
|
|
2192
|
+
if (!allUrlsCached(urls, textures)) return null;
|
|
2193
|
+
return buildFromCache(input, textures);
|
|
2194
|
+
}, [cache, urls, input, store]);
|
|
3169
2195
|
const loadedTextures = useLoader(
|
|
3170
2196
|
TextureLoader,
|
|
3171
2197
|
IsObject(input) ? Object.values(input) : input
|
|
@@ -3209,8 +2235,6 @@ function useTexture(input, optionsOrOnLoad) {
|
|
|
3209
2235
|
}, [input, loadedTextures, cachedResult]);
|
|
3210
2236
|
useEffect(() => {
|
|
3211
2237
|
if (!cache) return;
|
|
3212
|
-
if (cachedResult) return;
|
|
3213
|
-
const set = store.setState;
|
|
3214
2238
|
const urlTextureMap = [];
|
|
3215
2239
|
if (typeof input === "string") {
|
|
3216
2240
|
urlTextureMap.push([input, mappedTextures]);
|
|
@@ -3224,18 +2248,32 @@ function useTexture(input, optionsOrOnLoad) {
|
|
|
3224
2248
|
urlTextureMap.push([url, textureRecord[key]]);
|
|
3225
2249
|
}
|
|
3226
2250
|
}
|
|
3227
|
-
|
|
3228
|
-
const
|
|
3229
|
-
let
|
|
2251
|
+
store.setState((state) => {
|
|
2252
|
+
const refs = new Map(state._textureRefs);
|
|
2253
|
+
let textures = state.textures;
|
|
2254
|
+
let added = false;
|
|
3230
2255
|
for (const [url, texture] of urlTextureMap) {
|
|
3231
|
-
if (!
|
|
3232
|
-
|
|
3233
|
-
|
|
2256
|
+
if (!textures.has(url)) {
|
|
2257
|
+
if (!added) {
|
|
2258
|
+
textures = new Map(textures);
|
|
2259
|
+
added = true;
|
|
2260
|
+
}
|
|
2261
|
+
textures.set(url, texture);
|
|
3234
2262
|
}
|
|
2263
|
+
refs.set(url, (refs.get(url) ?? 0) + 1);
|
|
3235
2264
|
}
|
|
3236
|
-
return
|
|
2265
|
+
return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
|
|
3237
2266
|
});
|
|
3238
|
-
|
|
2267
|
+
return () => store.setState((state) => {
|
|
2268
|
+
const refs = new Map(state._textureRefs);
|
|
2269
|
+
for (const [url] of urlTextureMap) {
|
|
2270
|
+
const next = (refs.get(url) ?? 0) - 1;
|
|
2271
|
+
if (next <= 0) refs.delete(url);
|
|
2272
|
+
else refs.set(url, next);
|
|
2273
|
+
}
|
|
2274
|
+
return { _textureRefs: refs };
|
|
2275
|
+
});
|
|
2276
|
+
}, [cache, input, mappedTextures, store]);
|
|
3239
2277
|
return mappedTextures;
|
|
3240
2278
|
}
|
|
3241
2279
|
useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
|
|
@@ -3251,96 +2289,63 @@ const Texture = ({
|
|
|
3251
2289
|
return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
|
|
3252
2290
|
};
|
|
3253
2291
|
|
|
3254
|
-
function
|
|
3255
|
-
if (entry instanceof Texture$1) return entry;
|
|
3256
|
-
if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
|
|
3257
|
-
return entry.value;
|
|
3258
|
-
}
|
|
3259
|
-
return null;
|
|
3260
|
-
}
|
|
3261
|
-
function useTextures() {
|
|
2292
|
+
function useTextures(selector) {
|
|
3262
2293
|
const store = useStore();
|
|
3263
|
-
|
|
3264
|
-
const set = store.setState;
|
|
2294
|
+
const registry = useMemo(() => {
|
|
3265
2295
|
const getState = store.getState;
|
|
3266
|
-
const
|
|
3267
|
-
|
|
3268
|
-
const newMap = new Map(state.textures);
|
|
3269
|
-
newMap.set(key, value);
|
|
3270
|
-
return { textures: newMap };
|
|
3271
|
-
});
|
|
3272
|
-
};
|
|
3273
|
-
const addMultiple = (items) => {
|
|
3274
|
-
set((state) => {
|
|
3275
|
-
const newMap = new Map(state.textures);
|
|
3276
|
-
const entries = items instanceof Map ? items.entries() : Object.entries(items);
|
|
3277
|
-
for (const [key, value] of entries) {
|
|
3278
|
-
newMap.set(key, value);
|
|
3279
|
-
}
|
|
3280
|
-
return { textures: newMap };
|
|
3281
|
-
});
|
|
3282
|
-
};
|
|
3283
|
-
const remove = (key) => {
|
|
3284
|
-
set((state) => {
|
|
3285
|
-
const newMap = new Map(state.textures);
|
|
3286
|
-
newMap.delete(key);
|
|
3287
|
-
return { textures: newMap };
|
|
3288
|
-
});
|
|
3289
|
-
};
|
|
3290
|
-
const removeMultiple = (keys) => {
|
|
3291
|
-
set((state) => {
|
|
3292
|
-
const newMap = new Map(state.textures);
|
|
3293
|
-
for (const key of keys) newMap.delete(key);
|
|
3294
|
-
return { textures: newMap };
|
|
3295
|
-
});
|
|
3296
|
-
};
|
|
3297
|
-
const dispose = (key) => {
|
|
3298
|
-
const entry = getState().textures.get(key);
|
|
3299
|
-
if (entry) {
|
|
3300
|
-
const tex = getTextureValue(entry);
|
|
3301
|
-
tex?.dispose();
|
|
3302
|
-
}
|
|
3303
|
-
remove(key);
|
|
3304
|
-
};
|
|
3305
|
-
const disposeMultiple = (keys) => {
|
|
3306
|
-
const textures = getState().textures;
|
|
3307
|
-
for (const key of keys) {
|
|
3308
|
-
const entry = textures.get(key);
|
|
3309
|
-
if (entry) {
|
|
3310
|
-
const tex = getTextureValue(entry);
|
|
3311
|
-
tex?.dispose();
|
|
3312
|
-
}
|
|
3313
|
-
}
|
|
3314
|
-
removeMultiple(keys);
|
|
3315
|
-
};
|
|
3316
|
-
const disposeAll = () => {
|
|
3317
|
-
const textures = getState().textures;
|
|
3318
|
-
for (const entry of textures.values()) {
|
|
3319
|
-
const tex = getTextureValue(entry);
|
|
3320
|
-
tex?.dispose();
|
|
3321
|
-
}
|
|
3322
|
-
set({ textures: /* @__PURE__ */ new Map() });
|
|
3323
|
-
};
|
|
2296
|
+
const setState = store.setState;
|
|
2297
|
+
const getOne = (key) => getState().textures.get(key);
|
|
3324
2298
|
return {
|
|
3325
|
-
|
|
3326
|
-
get textures() {
|
|
2299
|
+
get all() {
|
|
3327
2300
|
return getState().textures;
|
|
3328
2301
|
},
|
|
3329
|
-
|
|
3330
|
-
|
|
2302
|
+
get(input) {
|
|
2303
|
+
if (typeof input === "string") return getOne(input);
|
|
2304
|
+
if (Array.isArray(input)) return input.map(getOne);
|
|
2305
|
+
const out = {};
|
|
2306
|
+
for (const name in input) out[name] = getOne(input[name]);
|
|
2307
|
+
return out;
|
|
2308
|
+
},
|
|
3331
2309
|
has: (key) => getState().textures.has(key),
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
2310
|
+
add(keyOrRecord, texture) {
|
|
2311
|
+
setState((state) => {
|
|
2312
|
+
const textures = new Map(state.textures);
|
|
2313
|
+
if (typeof keyOrRecord === "string") {
|
|
2314
|
+
textures.set(keyOrRecord, texture);
|
|
2315
|
+
} else {
|
|
2316
|
+
for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
|
|
2317
|
+
}
|
|
2318
|
+
return { textures };
|
|
2319
|
+
});
|
|
2320
|
+
},
|
|
2321
|
+
dispose(key, options) {
|
|
2322
|
+
const state = getState();
|
|
2323
|
+
const refs = state._textureRefs.get(key) ?? 0;
|
|
2324
|
+
if (refs > 0 && !options?.force) {
|
|
2325
|
+
console.warn(
|
|
2326
|
+
`[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
|
|
2327
|
+
);
|
|
2328
|
+
return false;
|
|
2329
|
+
}
|
|
2330
|
+
state.textures.get(key)?.dispose();
|
|
2331
|
+
setState((s) => {
|
|
2332
|
+
const textures = new Map(s.textures);
|
|
2333
|
+
textures.delete(key);
|
|
2334
|
+
const nextRefs = new Map(s._textureRefs);
|
|
2335
|
+
nextRefs.delete(key);
|
|
2336
|
+
return { textures, _textureRefs: nextRefs };
|
|
2337
|
+
});
|
|
2338
|
+
return true;
|
|
2339
|
+
},
|
|
2340
|
+
disposeAll() {
|
|
2341
|
+
for (const texture of getState().textures.values()) texture.dispose();
|
|
2342
|
+
setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
|
|
2343
|
+
}
|
|
3342
2344
|
};
|
|
3343
2345
|
}, [store]);
|
|
2346
|
+
const subscribe = selector ? () => selector(registry) : (state) => state.textures;
|
|
2347
|
+
const selected = useThree(subscribe);
|
|
2348
|
+
return selector ? selected : registry;
|
|
3344
2349
|
}
|
|
3345
2350
|
|
|
3346
2351
|
function useRenderTarget(widthOrOptions, heightOrOptions, options) {
|
|
@@ -3421,7 +2426,7 @@ function advance(timestamp) {
|
|
|
3421
2426
|
getScheduler().step(timestamp);
|
|
3422
2427
|
}
|
|
3423
2428
|
|
|
3424
|
-
const version = "10.0.0-alpha.
|
|
2429
|
+
const version = "10.0.0-alpha.3";
|
|
3425
2430
|
const packageData = {
|
|
3426
2431
|
version: version};
|
|
3427
2432
|
|
|
@@ -14860,6 +13865,7 @@ function swapInstances() {
|
|
|
14860
13865
|
}
|
|
14861
13866
|
}
|
|
14862
13867
|
if (instance.isHidden) unhideInstance(instance);
|
|
13868
|
+
if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
|
|
14863
13869
|
if (instance.object.__r3f) delete instance.object.__r3f;
|
|
14864
13870
|
if (instance.type !== "primitive") disposeOnIdle(instance.object);
|
|
14865
13871
|
}
|
|
@@ -14872,6 +13878,8 @@ function swapInstances() {
|
|
|
14872
13878
|
instance.object.__r3f = instance;
|
|
14873
13879
|
setFiberRef(fiber, instance.object);
|
|
14874
13880
|
delete instance.appliedOnce;
|
|
13881
|
+
instance.eventCount = 0;
|
|
13882
|
+
instance.handlers = {};
|
|
14875
13883
|
applyProps(instance.object, instance.props);
|
|
14876
13884
|
if (instance.props.attach) {
|
|
14877
13885
|
attach(parent, instance);
|
|
@@ -15087,11 +14095,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
|
|
|
15087
14095
|
cloneMutableTextInstance(textInstance) {
|
|
15088
14096
|
return textInstance;
|
|
15089
14097
|
},
|
|
14098
|
+
// React 19.2 added these for root-level view transitions. They only run for hosts that opt into
|
|
14099
|
+
// view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
|
|
14100
|
+
// into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
|
|
14101
|
+
// React never calls them. They stay as no-ops rather than throws: the host config is shared by
|
|
14102
|
+
// every root, and a throw here would turn a React-internal probe into a hard crash for users.
|
|
14103
|
+
// Guarded by a test asserting a full render + unmount never reaches them.
|
|
15090
14104
|
cloneRootViewTransitionContainer(_rootContainer) {
|
|
15091
|
-
throw new Error("Not implemented.");
|
|
15092
14105
|
},
|
|
15093
14106
|
removeRootViewTransitionClone(_rootContainer, _clone) {
|
|
15094
|
-
throw new Error("Not implemented.");
|
|
15095
14107
|
},
|
|
15096
14108
|
// https://github.com/facebook/react/pull/32465
|
|
15097
14109
|
createFragmentInstance: (_fiber) => null,
|
|
@@ -15176,6 +14188,7 @@ function createRoot(canvas) {
|
|
|
15176
14188
|
const lastConfiguredProps = {};
|
|
15177
14189
|
let configured = false;
|
|
15178
14190
|
let pending = null;
|
|
14191
|
+
let rendererSetup = null;
|
|
15179
14192
|
return {
|
|
15180
14193
|
async configure(props = {}) {
|
|
15181
14194
|
let resolve;
|
|
@@ -15191,7 +14204,6 @@ function createRoot(canvas) {
|
|
|
15191
14204
|
events,
|
|
15192
14205
|
onCreated: onCreatedCallback,
|
|
15193
14206
|
shadows = false,
|
|
15194
|
-
textureColorSpace = SRGBColorSpace,
|
|
15195
14207
|
orthographic = false,
|
|
15196
14208
|
frameloop = "always",
|
|
15197
14209
|
dpr = [1, 2],
|
|
@@ -15206,7 +14218,8 @@ function createRoot(canvas) {
|
|
|
15206
14218
|
_sizeProps,
|
|
15207
14219
|
forceEven
|
|
15208
14220
|
} = props;
|
|
15209
|
-
const
|
|
14221
|
+
const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
|
|
14222
|
+
let state = store.getState();
|
|
15210
14223
|
const defaultGLProps = {
|
|
15211
14224
|
canvas,
|
|
15212
14225
|
powerPreference: "high-performance",
|
|
@@ -15234,9 +14247,21 @@ function createRoot(canvas) {
|
|
|
15234
14247
|
);
|
|
15235
14248
|
}
|
|
15236
14249
|
if (!state.internal.actualRenderer) {
|
|
15237
|
-
|
|
15238
|
-
|
|
15239
|
-
|
|
14250
|
+
if (!rendererSetup) {
|
|
14251
|
+
rendererSetup = (async () => {
|
|
14252
|
+
{
|
|
14253
|
+
renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
|
|
14254
|
+
state.internal.actualRenderer = renderer;
|
|
14255
|
+
state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
|
|
14256
|
+
}
|
|
14257
|
+
})().catch((err) => {
|
|
14258
|
+
rendererSetup = null;
|
|
14259
|
+
throw err;
|
|
14260
|
+
});
|
|
14261
|
+
}
|
|
14262
|
+
await rendererSetup;
|
|
14263
|
+
state = store.getState();
|
|
14264
|
+
renderer = state.internal.actualRenderer;
|
|
15240
14265
|
}
|
|
15241
14266
|
let raycaster = state.raycaster;
|
|
15242
14267
|
if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
|
|
@@ -15329,7 +14354,7 @@ function createRoot(canvas) {
|
|
|
15329
14354
|
lastConfiguredProps.performance = performance;
|
|
15330
14355
|
}
|
|
15331
14356
|
if (!state.xr) {
|
|
15332
|
-
const handleXRFrame = (timestamp,
|
|
14357
|
+
const handleXRFrame = (timestamp, _frame) => {
|
|
15333
14358
|
const state2 = store.getState();
|
|
15334
14359
|
if (state2.frameloop === "never") return;
|
|
15335
14360
|
advance(timestamp);
|
|
@@ -15365,15 +14390,22 @@ function createRoot(canvas) {
|
|
|
15365
14390
|
const oldType = renderer.shadowMap.type;
|
|
15366
14391
|
renderer.shadowMap.enabled = !!shadows;
|
|
15367
14392
|
if (is.boo(shadows)) {
|
|
15368
|
-
renderer.shadowMap.type =
|
|
14393
|
+
renderer.shadowMap.type = PCFShadowMap;
|
|
15369
14394
|
} else if (is.str(shadows)) {
|
|
14395
|
+
if (shadows === "soft") {
|
|
14396
|
+
notifyDepreciated({
|
|
14397
|
+
heading: 'shadows="soft" is deprecated',
|
|
14398
|
+
body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
|
|
14399
|
+
link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
|
|
14400
|
+
});
|
|
14401
|
+
}
|
|
15370
14402
|
const types = {
|
|
15371
14403
|
basic: BasicShadowMap,
|
|
15372
14404
|
percentage: PCFShadowMap,
|
|
15373
|
-
soft:
|
|
14405
|
+
soft: PCFShadowMap,
|
|
15374
14406
|
variance: VSMShadowMap
|
|
15375
14407
|
};
|
|
15376
|
-
renderer.shadowMap.type = types[shadows] ??
|
|
14408
|
+
renderer.shadowMap.type = types[shadows] ?? PCFShadowMap;
|
|
15377
14409
|
} else if (is.obj(shadows)) {
|
|
15378
14410
|
Object.assign(renderer.shadowMap, shadows);
|
|
15379
14411
|
}
|
|
@@ -15389,13 +14421,24 @@ function createRoot(canvas) {
|
|
|
15389
14421
|
if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
|
|
15390
14422
|
lastConfiguredProps.textureColorSpace = textureColorSpace;
|
|
15391
14423
|
}
|
|
14424
|
+
const r3fProps = ["textureColorSpace"];
|
|
14425
|
+
const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
|
|
14426
|
+
const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
|
|
15392
14427
|
if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
|
|
15393
|
-
|
|
14428
|
+
const glProps = {};
|
|
14429
|
+
for (const key in glConfig) {
|
|
14430
|
+
if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
|
|
14431
|
+
}
|
|
14432
|
+
applyProps(renderer, glProps);
|
|
15394
14433
|
}
|
|
15395
14434
|
if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
|
|
15396
14435
|
const currentRenderer = state.renderer;
|
|
15397
14436
|
if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
|
|
15398
|
-
|
|
14437
|
+
const rendererProps = {};
|
|
14438
|
+
for (const key in rendererConfig) {
|
|
14439
|
+
if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
|
|
14440
|
+
}
|
|
14441
|
+
applyProps(currentRenderer, rendererProps);
|
|
15399
14442
|
}
|
|
15400
14443
|
}
|
|
15401
14444
|
const scheduler = getScheduler();
|
|
@@ -15443,7 +14486,7 @@ function createRoot(canvas) {
|
|
|
15443
14486
|
{
|
|
15444
14487
|
id: `${newRootId}_frustum`,
|
|
15445
14488
|
rootId: newRootId,
|
|
15446
|
-
|
|
14489
|
+
before: "render",
|
|
15447
14490
|
system: true
|
|
15448
14491
|
}
|
|
15449
14492
|
);
|
|
@@ -15455,7 +14498,7 @@ function createRoot(canvas) {
|
|
|
15455
14498
|
{
|
|
15456
14499
|
id: `${newRootId}_visibility`,
|
|
15457
14500
|
rootId: newRootId,
|
|
15458
|
-
|
|
14501
|
+
before: "render",
|
|
15459
14502
|
system: true,
|
|
15460
14503
|
after: `${newRootId}_frustum`
|
|
15461
14504
|
}
|
|
@@ -15568,7 +14611,8 @@ function unmountComponentAtNode(canvas, callback) {
|
|
|
15568
14611
|
dispose(state.scene);
|
|
15569
14612
|
_roots.delete(canvas);
|
|
15570
14613
|
if (callback) callback(canvas);
|
|
15571
|
-
} catch {
|
|
14614
|
+
} catch (error) {
|
|
14615
|
+
console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
|
|
15572
14616
|
}
|
|
15573
14617
|
}, 500);
|
|
15574
14618
|
}
|
|
@@ -15631,6 +14675,7 @@ function PortalInner({ state = {}, children, container }) {
|
|
|
15631
14675
|
viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
|
|
15632
14676
|
if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
|
|
15633
14677
|
}
|
|
14678
|
+
const set = injectState.set;
|
|
15634
14679
|
return {
|
|
15635
14680
|
// The intersect consists of the previous root state
|
|
15636
14681
|
...rootState,
|
|
@@ -15649,7 +14694,7 @@ function PortalInner({ state = {}, children, container }) {
|
|
|
15649
14694
|
size: resolvedSize,
|
|
15650
14695
|
viewport: { ...rootState.viewport, ...viewport },
|
|
15651
14696
|
// Layers are allowed to override events
|
|
15652
|
-
setEvents: (events2) =>
|
|
14697
|
+
setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
|
|
15653
14698
|
// Container for child attachment - the portalScene (injected or container itself)
|
|
15654
14699
|
internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
|
|
15655
14700
|
};
|
|
@@ -15678,6 +14723,81 @@ function flushSync(fn) {
|
|
|
15678
14723
|
return reconciler.flushSyncFromReconciler(fn);
|
|
15679
14724
|
}
|
|
15680
14725
|
|
|
14726
|
+
function parseBackground(background) {
|
|
14727
|
+
if (!background) return null;
|
|
14728
|
+
if (typeof background === "object" && !background.isColor) {
|
|
14729
|
+
const { backgroundMap, envMap, files, preset, ...rest } = background;
|
|
14730
|
+
return {
|
|
14731
|
+
...rest,
|
|
14732
|
+
preset,
|
|
14733
|
+
files: envMap || files,
|
|
14734
|
+
backgroundFiles: backgroundMap,
|
|
14735
|
+
background: true
|
|
14736
|
+
};
|
|
14737
|
+
}
|
|
14738
|
+
if (typeof background === "number") {
|
|
14739
|
+
return { color: background, background: true };
|
|
14740
|
+
}
|
|
14741
|
+
if (typeof background === "string") {
|
|
14742
|
+
if (background in presetsObj) {
|
|
14743
|
+
return { preset: background, background: true };
|
|
14744
|
+
}
|
|
14745
|
+
if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
|
|
14746
|
+
return { files: background, background: true };
|
|
14747
|
+
}
|
|
14748
|
+
return { color: background, background: true };
|
|
14749
|
+
}
|
|
14750
|
+
if (background.isColor) {
|
|
14751
|
+
return { color: background, background: true };
|
|
14752
|
+
}
|
|
14753
|
+
return null;
|
|
14754
|
+
}
|
|
14755
|
+
|
|
14756
|
+
function parseRendererConfig(rendererProp) {
|
|
14757
|
+
const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
|
|
14758
|
+
if (isRendererConfig) {
|
|
14759
|
+
const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
|
|
14760
|
+
return {
|
|
14761
|
+
primaryCanvas: pc,
|
|
14762
|
+
scheduler: sc,
|
|
14763
|
+
renderer: Object.keys(rest).length > 0 ? rest : rendererProp
|
|
14764
|
+
};
|
|
14765
|
+
}
|
|
14766
|
+
return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
|
|
14767
|
+
}
|
|
14768
|
+
|
|
14769
|
+
const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
|
|
14770
|
+
const registries = /* @__PURE__ */ new WeakMap();
|
|
14771
|
+
function getKindRegistry(store, kind) {
|
|
14772
|
+
let registry = registries.get(store);
|
|
14773
|
+
if (!registry) {
|
|
14774
|
+
registry = {
|
|
14775
|
+
nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
|
|
14776
|
+
uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
|
|
14777
|
+
buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
|
|
14778
|
+
gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
|
|
14779
|
+
};
|
|
14780
|
+
registries.set(store, registry);
|
|
14781
|
+
}
|
|
14782
|
+
return registry[kind];
|
|
14783
|
+
}
|
|
14784
|
+
function invalidateResource(store, kind, scopeKey) {
|
|
14785
|
+
const registry = getKindRegistry(store, kind);
|
|
14786
|
+
{
|
|
14787
|
+
registry.valid.clear();
|
|
14788
|
+
registry.staged.clear();
|
|
14789
|
+
}
|
|
14790
|
+
}
|
|
14791
|
+
function invalidateAllResources(store) {
|
|
14792
|
+
for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
|
|
14793
|
+
}
|
|
14794
|
+
|
|
14795
|
+
function clearHmrCaches(store) {
|
|
14796
|
+
const primary = store.getState().primaryStore ?? store;
|
|
14797
|
+
invalidateAllResources(primary);
|
|
14798
|
+
primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
|
|
14799
|
+
}
|
|
14800
|
+
|
|
15681
14801
|
function CanvasImpl({
|
|
15682
14802
|
ref,
|
|
15683
14803
|
children,
|
|
@@ -15698,6 +14818,8 @@ function CanvasImpl({
|
|
|
15698
14818
|
raycaster,
|
|
15699
14819
|
camera,
|
|
15700
14820
|
scene,
|
|
14821
|
+
autoUpdateFrustum,
|
|
14822
|
+
occlusion,
|
|
15701
14823
|
onPointerMissed,
|
|
15702
14824
|
onDragOverMissed,
|
|
15703
14825
|
onDropMissed,
|
|
@@ -15709,39 +14831,10 @@ function CanvasImpl({
|
|
|
15709
14831
|
forceEven,
|
|
15710
14832
|
...props
|
|
15711
14833
|
}) {
|
|
15712
|
-
const { primaryCanvas, scheduler,
|
|
15713
|
-
const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
|
|
14834
|
+
const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
|
|
15714
14835
|
React.useMemo(() => extend(THREE), []);
|
|
15715
14836
|
const Bridge = useBridge();
|
|
15716
|
-
const backgroundProps = React.useMemo(() =>
|
|
15717
|
-
if (!background) return null;
|
|
15718
|
-
if (typeof background === "object" && !background.isColor) {
|
|
15719
|
-
const { backgroundMap, envMap, files, preset, ...rest } = background;
|
|
15720
|
-
return {
|
|
15721
|
-
...rest,
|
|
15722
|
-
preset,
|
|
15723
|
-
files: envMap || files,
|
|
15724
|
-
backgroundFiles: backgroundMap,
|
|
15725
|
-
background: true
|
|
15726
|
-
};
|
|
15727
|
-
}
|
|
15728
|
-
if (typeof background === "number") {
|
|
15729
|
-
return { color: background, background: true };
|
|
15730
|
-
}
|
|
15731
|
-
if (typeof background === "string") {
|
|
15732
|
-
if (background in presetsObj) {
|
|
15733
|
-
return { preset: background, background: true };
|
|
15734
|
-
}
|
|
15735
|
-
if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
|
|
15736
|
-
return { files: background, background: true };
|
|
15737
|
-
}
|
|
15738
|
-
return { color: background, background: true };
|
|
15739
|
-
}
|
|
15740
|
-
if (background.isColor) {
|
|
15741
|
-
return { color: background, background: true };
|
|
15742
|
-
}
|
|
15743
|
-
return null;
|
|
15744
|
-
}, [background]);
|
|
14837
|
+
const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
|
|
15745
14838
|
const hasInitialSizeRef = React.useRef(false);
|
|
15746
14839
|
const measureConfig = React.useMemo(() => {
|
|
15747
14840
|
if (!hasInitialSizeRef.current) {
|
|
@@ -15783,6 +14876,7 @@ function CanvasImpl({
|
|
|
15783
14876
|
const handleDropMissed = useMutableCallback(onDropMissed);
|
|
15784
14877
|
const [block, setBlock] = React.useState(false);
|
|
15785
14878
|
const [error, setError] = React.useState(false);
|
|
14879
|
+
const [fallbackVisible, setFallbackVisible] = React.useState(false);
|
|
15786
14880
|
if (block) throw block;
|
|
15787
14881
|
if (error) throw error;
|
|
15788
14882
|
const root = React.useRef(null);
|
|
@@ -15790,6 +14884,7 @@ function CanvasImpl({
|
|
|
15790
14884
|
const unsubscribeErrorRef = React.useRef(null);
|
|
15791
14885
|
useIsomorphicLayoutEffect(() => {
|
|
15792
14886
|
effectActiveRef.current = true;
|
|
14887
|
+
if (fallbackVisible) return;
|
|
15793
14888
|
const canvas = canvasRef.current;
|
|
15794
14889
|
if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
|
|
15795
14890
|
if (!root.current) {
|
|
@@ -15810,7 +14905,7 @@ function CanvasImpl({
|
|
|
15810
14905
|
}
|
|
15811
14906
|
async function run() {
|
|
15812
14907
|
if (!effectActiveRef.current || !root.current) return;
|
|
15813
|
-
await root.current.configure({
|
|
14908
|
+
const configured = await root.current.configure({
|
|
15814
14909
|
id,
|
|
15815
14910
|
primaryCanvas,
|
|
15816
14911
|
scheduler,
|
|
@@ -15825,6 +14920,8 @@ function CanvasImpl({
|
|
|
15825
14920
|
performance,
|
|
15826
14921
|
raycaster,
|
|
15827
14922
|
camera,
|
|
14923
|
+
autoUpdateFrustum,
|
|
14924
|
+
occlusion,
|
|
15828
14925
|
size: effectiveSize,
|
|
15829
14926
|
// Store size props for reset functionality
|
|
15830
14927
|
_sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
|
|
@@ -15849,8 +14946,20 @@ function CanvasImpl({
|
|
|
15849
14946
|
}
|
|
15850
14947
|
onCreated?.(state);
|
|
15851
14948
|
}
|
|
15852
|
-
})
|
|
15853
|
-
|
|
14949
|
+
}).then(
|
|
14950
|
+
() => true,
|
|
14951
|
+
// Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
|
|
14952
|
+
// inside <canvas>, which browsers don't display, so surface it as visible DOM
|
|
14953
|
+
// instead; with no fallback, rethrow to an external error boundary. (#3757)
|
|
14954
|
+
(setupError) => {
|
|
14955
|
+
if (effectActiveRef.current) {
|
|
14956
|
+
if (fallback != null) setFallbackVisible(true);
|
|
14957
|
+
else setError(setupError);
|
|
14958
|
+
}
|
|
14959
|
+
return false;
|
|
14960
|
+
}
|
|
14961
|
+
);
|
|
14962
|
+
if (!configured || !effectActiveRef.current || !root.current) return;
|
|
15854
14963
|
root.current.render(
|
|
15855
14964
|
/* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
|
|
15856
14965
|
backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
|
|
@@ -15884,14 +14993,7 @@ function CanvasImpl({
|
|
|
15884
14993
|
const handleHMR = () => {
|
|
15885
14994
|
queueMicrotask(() => {
|
|
15886
14995
|
const rootEntry = _roots.get(canvas);
|
|
15887
|
-
if (rootEntry?.store)
|
|
15888
|
-
console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
|
|
15889
|
-
rootEntry.store.setState((state) => ({
|
|
15890
|
-
nodes: {},
|
|
15891
|
-
uniforms: {},
|
|
15892
|
-
_hmrVersion: state._hmrVersion + 1
|
|
15893
|
-
}));
|
|
15894
|
-
}
|
|
14996
|
+
if (rootEntry?.store) clearHmrCaches(rootEntry.store);
|
|
15895
14997
|
});
|
|
15896
14998
|
};
|
|
15897
14999
|
if (typeof import.meta !== "undefined" && import.meta.hot) {
|
|
@@ -15920,7 +15022,20 @@ function CanvasImpl({
|
|
|
15920
15022
|
...style
|
|
15921
15023
|
},
|
|
15922
15024
|
...props,
|
|
15923
|
-
children:
|
|
15025
|
+
children: fallbackVisible ? (
|
|
15026
|
+
// Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
|
|
15027
|
+
// it exists in the tree but browsers never paint it, which is the whole bug (#3757).
|
|
15028
|
+
fallback
|
|
15029
|
+
) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
|
|
15030
|
+
"canvas",
|
|
15031
|
+
{
|
|
15032
|
+
ref: canvasRef,
|
|
15033
|
+
id,
|
|
15034
|
+
className: "r3f-canvas",
|
|
15035
|
+
style: { display: "block", width: "100%", height: "100%" },
|
|
15036
|
+
children: fallback
|
|
15037
|
+
}
|
|
15038
|
+
) })
|
|
15924
15039
|
}
|
|
15925
15040
|
);
|
|
15926
15041
|
}
|
|
@@ -15930,4 +15045,4 @@ function Canvas(props) {
|
|
|
15930
15045
|
|
|
15931
15046
|
extend(THREE);
|
|
15932
15047
|
|
|
15933
|
-
export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS,
|
|
15048
|
+
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 };
|