@react-three/fiber 9.4.1 → 9.5.0

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.
@@ -1,2510 +0,0 @@
1
- import * as React from 'react';
2
- import { DefaultEventPriority, ContinuousEventPriority, DiscreteEventPriority, ConcurrentRoot } from 'react-reconciler/constants';
3
- import * as THREE from 'three';
4
- import { createWithEqualityFn } from 'zustand/traditional';
5
- import { suspend, preload, clear } from 'suspend-react';
6
- import Reconciler from 'react-reconciler';
7
- import { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
8
- import { jsx, Fragment } from 'react/jsx-runtime';
9
- import { useFiber, useContextBridge, traverseFiber } from 'its-fine';
10
-
11
- var threeTypes = /*#__PURE__*/Object.freeze({
12
- __proto__: null
13
- });
14
-
15
- /**
16
- * Returns the instance's initial (outmost) root.
17
- */
18
- function findInitialRoot(instance) {
19
- let root = instance.root;
20
- while (root.getState().previousRoot) root = root.getState().previousRoot;
21
- return root;
22
- }
23
- /**
24
- * Safely flush async effects when testing, simulating a legacy root.
25
- * @deprecated Import from React instead. import { act } from 'react'
26
- */
27
- // Reference with computed key to break Webpack static analysis
28
- // https://github.com/webpack/webpack/issues/14814
29
- const act = React['act' + ''];
30
- const isOrthographicCamera = def => def && def.isOrthographicCamera;
31
- const isRef = obj => obj && obj.hasOwnProperty('current');
32
- const isColorRepresentation = value => value != null && (typeof value === 'string' || typeof value === 'number' || value.isColor);
33
-
34
- /**
35
- * An SSR-friendly useLayoutEffect.
36
- *
37
- * React currently throws a warning when using useLayoutEffect on the server.
38
- * To get around it, we can conditionally useEffect on the server (no-op) and
39
- * useLayoutEffect elsewhere.
40
- *
41
- * @see https://github.com/facebook/react/issues/14927
42
- */
43
- const useIsomorphicLayoutEffect = /* @__PURE__ */((_window$document, _window$navigator) => typeof window !== 'undefined' && (((_window$document = window.document) == null ? void 0 : _window$document.createElement) || ((_window$navigator = window.navigator) == null ? void 0 : _window$navigator.product) === 'ReactNative'))() ? React.useLayoutEffect : React.useEffect;
44
- function useMutableCallback(fn) {
45
- const ref = React.useRef(fn);
46
- useIsomorphicLayoutEffect(() => void (ref.current = fn), [fn]);
47
- return ref;
48
- }
49
- /**
50
- * Bridges renderer Context and StrictMode from a primary renderer.
51
- */
52
- function useBridge() {
53
- const fiber = useFiber();
54
- const ContextBridge = useContextBridge();
55
- return React.useMemo(() => ({
56
- children
57
- }) => {
58
- const strict = !!traverseFiber(fiber, true, node => node.type === React.StrictMode);
59
- const Root = strict ? React.StrictMode : React.Fragment;
60
- return /*#__PURE__*/jsx(Root, {
61
- children: /*#__PURE__*/jsx(ContextBridge, {
62
- children: children
63
- })
64
- });
65
- }, [fiber, ContextBridge]);
66
- }
67
- function Block({
68
- set
69
- }) {
70
- useIsomorphicLayoutEffect(() => {
71
- set(new Promise(() => null));
72
- return () => set(false);
73
- }, [set]);
74
- return null;
75
- }
76
-
77
- // NOTE: static members get down-level transpiled to mutations which break tree-shaking
78
- const ErrorBoundary = /* @__PURE__ */(_ErrorBoundary => (_ErrorBoundary = class ErrorBoundary extends React.Component {
79
- constructor(...args) {
80
- super(...args);
81
- this.state = {
82
- error: false
83
- };
84
- }
85
- componentDidCatch(err) {
86
- this.props.set(err);
87
- }
88
- render() {
89
- return this.state.error ? null : this.props.children;
90
- }
91
- }, _ErrorBoundary.getDerivedStateFromError = () => ({
92
- error: true
93
- }), _ErrorBoundary))();
94
- function calculateDpr(dpr) {
95
- var _window$devicePixelRa;
96
- // Err on the side of progress by assuming 2x dpr if we can't detect it
97
- // This will happen in workers where window is defined but dpr isn't.
98
- const target = typeof window !== 'undefined' ? (_window$devicePixelRa = window.devicePixelRatio) != null ? _window$devicePixelRa : 2 : 1;
99
- return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], target), dpr[1]) : dpr;
100
- }
101
-
102
- /**
103
- * Returns instance root state
104
- */
105
- function getRootState(obj) {
106
- var _r3f;
107
- return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState();
108
- }
109
- // A collection of compare functions
110
- const is = {
111
- obj: a => a === Object(a) && !is.arr(a) && typeof a !== 'function',
112
- fun: a => typeof a === 'function',
113
- str: a => typeof a === 'string',
114
- num: a => typeof a === 'number',
115
- boo: a => typeof a === 'boolean',
116
- und: a => a === void 0,
117
- nul: a => a === null,
118
- arr: a => Array.isArray(a),
119
- equ(a, b, {
120
- arrays = 'shallow',
121
- objects = 'reference',
122
- strict = true
123
- } = {}) {
124
- // Wrong type or one of the two undefined, doesn't match
125
- if (typeof a !== typeof b || !!a !== !!b) return false;
126
- // Atomic, just compare a against b
127
- if (is.str(a) || is.num(a) || is.boo(a)) return a === b;
128
- const isObj = is.obj(a);
129
- if (isObj && objects === 'reference') return a === b;
130
- const isArr = is.arr(a);
131
- if (isArr && arrays === 'reference') return a === b;
132
- // Array or Object, shallow compare first to see if it's a match
133
- if ((isArr || isObj) && a === b) return true;
134
- // Last resort, go through keys
135
- let i;
136
- // Check if a has all the keys of b
137
- for (i in a) if (!(i in b)) return false;
138
- // Check if values between keys match
139
- if (isObj && arrays === 'shallow' && objects === 'shallow') {
140
- for (i in strict ? b : a) if (!is.equ(a[i], b[i], {
141
- strict,
142
- objects: 'reference'
143
- })) return false;
144
- } else {
145
- for (i in strict ? b : a) if (a[i] !== b[i]) return false;
146
- }
147
- // If i is undefined
148
- if (is.und(i)) {
149
- // If both arrays are empty we consider them equal
150
- if (isArr && a.length === 0 && b.length === 0) return true;
151
- // If both objects are empty we consider them equal
152
- if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true;
153
- // Otherwise match them by value
154
- if (a !== b) return false;
155
- }
156
- return true;
157
- }
158
- };
159
-
160
- // Collects nodes and materials from a THREE.Object3D
161
- function buildGraph(object) {
162
- const data = {
163
- nodes: {},
164
- materials: {},
165
- meshes: {}
166
- };
167
- if (object) {
168
- object.traverse(obj => {
169
- if (obj.name) data.nodes[obj.name] = obj;
170
- if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material;
171
- if (obj.isMesh && !data.meshes[obj.name]) data.meshes[obj.name] = obj;
172
- });
173
- }
174
- return data;
175
- }
176
- // Disposes an object and all its properties
177
- function dispose(obj) {
178
- if (obj.type !== 'Scene') obj.dispose == null ? void 0 : obj.dispose();
179
- for (const p in obj) {
180
- const prop = obj[p];
181
- if ((prop == null ? void 0 : prop.type) !== 'Scene') prop == null ? void 0 : prop.dispose == null ? void 0 : prop.dispose();
182
- }
183
- }
184
- const REACT_INTERNAL_PROPS = ['children', 'key', 'ref'];
185
-
186
- // Gets only instance props from reconciler fibers
187
- function getInstanceProps(queue) {
188
- const props = {};
189
- for (const key in queue) {
190
- if (!REACT_INTERNAL_PROPS.includes(key)) props[key] = queue[key];
191
- }
192
- return props;
193
- }
194
-
195
- // Each object in the scene carries a small LocalState descriptor
196
- function prepare(target, root, type, props) {
197
- const object = target;
198
-
199
- // Create instance descriptor
200
- let instance = object == null ? void 0 : object.__r3f;
201
- if (!instance) {
202
- instance = {
203
- root,
204
- type,
205
- parent: null,
206
- children: [],
207
- props: getInstanceProps(props),
208
- object,
209
- eventCount: 0,
210
- handlers: {},
211
- isHidden: false
212
- };
213
- if (object) object.__r3f = instance;
214
- }
215
- return instance;
216
- }
217
- function resolve(root, key) {
218
- if (!key.includes('-')) return {
219
- root,
220
- key,
221
- target: root[key]
222
- };
223
-
224
- // First try the entire key as a single property (e.g., 'foo-bar')
225
- if (key in root) {
226
- return {
227
- root,
228
- key,
229
- target: root[key]
230
- };
231
- }
232
-
233
- // Try piercing (e.g., 'material-color' -> material.color)
234
- let target = root;
235
- const parts = key.split('-');
236
- for (const part of parts) {
237
- if (typeof target !== 'object' || target === null) {
238
- if (target !== undefined) {
239
- // Property exists but has unexpected shape
240
- const remaining = parts.slice(parts.indexOf(part)).join('-');
241
- return {
242
- root: target,
243
- key: remaining,
244
- target: undefined
245
- };
246
- }
247
- // Property doesn't exist - fallback to original key
248
- return {
249
- root,
250
- key,
251
- target: undefined
252
- };
253
- }
254
- key = part;
255
- root = target;
256
- target = target[key];
257
- }
258
- return {
259
- root,
260
- key,
261
- target
262
- };
263
- }
264
-
265
- // Checks if a dash-cased string ends with an integer
266
- const INDEX_REGEX = /-\d+$/;
267
- function attach(parent, child) {
268
- if (is.str(child.props.attach)) {
269
- // If attaching into an array (foo-0), create one
270
- if (INDEX_REGEX.test(child.props.attach)) {
271
- const index = child.props.attach.replace(INDEX_REGEX, '');
272
- const {
273
- root,
274
- key
275
- } = resolve(parent.object, index);
276
- if (!Array.isArray(root[key])) root[key] = [];
277
- }
278
- const {
279
- root,
280
- key
281
- } = resolve(parent.object, child.props.attach);
282
- child.previousAttach = root[key];
283
- root[key] = child.object;
284
- } else if (is.fun(child.props.attach)) {
285
- child.previousAttach = child.props.attach(parent.object, child.object);
286
- }
287
- }
288
- function detach(parent, child) {
289
- if (is.str(child.props.attach)) {
290
- const {
291
- root,
292
- key
293
- } = resolve(parent.object, child.props.attach);
294
- const previous = child.previousAttach;
295
- // When the previous value was undefined, it means the value was never set to begin with
296
- if (previous === undefined) delete root[key];
297
- // Otherwise set the previous value
298
- else root[key] = previous;
299
- } else {
300
- child.previousAttach == null ? void 0 : child.previousAttach(parent.object, child.object);
301
- }
302
- delete child.previousAttach;
303
- }
304
- const RESERVED_PROPS = [...REACT_INTERNAL_PROPS,
305
- // Instance props
306
- 'args', 'dispose', 'attach', 'object', 'onUpdate',
307
- // Behavior flags
308
- 'dispose'];
309
- const MEMOIZED_PROTOTYPES = new Map();
310
- function getMemoizedPrototype(root) {
311
- let ctor = MEMOIZED_PROTOTYPES.get(root.constructor);
312
- try {
313
- if (!ctor) {
314
- ctor = new root.constructor();
315
- MEMOIZED_PROTOTYPES.set(root.constructor, ctor);
316
- }
317
- } catch (e) {
318
- // ...
319
- }
320
- return ctor;
321
- }
322
-
323
- // This function prepares a set of changes to be applied to the instance
324
- function diffProps(instance, newProps) {
325
- const changedProps = {};
326
-
327
- // Sort through props
328
- for (const prop in newProps) {
329
- // Skip reserved keys
330
- if (RESERVED_PROPS.includes(prop)) continue;
331
- // Skip if props match
332
- if (is.equ(newProps[prop], instance.props[prop])) continue;
333
-
334
- // Props changed, add them
335
- changedProps[prop] = newProps[prop];
336
-
337
- // Reset pierced props
338
- for (const other in newProps) {
339
- if (other.startsWith(`${prop}-`)) changedProps[other] = newProps[other];
340
- }
341
- }
342
-
343
- // Reset removed props for HMR
344
- for (const prop in instance.props) {
345
- if (RESERVED_PROPS.includes(prop) || newProps.hasOwnProperty(prop)) continue;
346
- const {
347
- root,
348
- key
349
- } = resolve(instance.object, prop);
350
-
351
- // https://github.com/mrdoob/three.js/issues/21209
352
- // HMR/fast-refresh relies on the ability to cancel out props, but threejs
353
- // has no means to do this. Hence we curate a small collection of value-classes
354
- // with their respective constructor/set arguments
355
- // For removed props, try to set default values, if possible
356
- if (root.constructor && root.constructor.length === 0) {
357
- // create a blank slate of the instance and copy the particular parameter.
358
- const ctor = getMemoizedPrototype(root);
359
- if (!is.und(ctor)) changedProps[key] = ctor[key];
360
- } else {
361
- // instance does not have constructor, just set it to 0
362
- changedProps[key] = 0;
363
- }
364
- }
365
- return changedProps;
366
- }
367
-
368
- // https://github.com/mrdoob/three.js/pull/27042
369
- // https://github.com/mrdoob/three.js/pull/22748
370
- const colorMaps = ['map', 'emissiveMap', 'sheenColorMap', 'specularColorMap', 'envMap'];
371
- const EVENT_REGEX = /^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;
372
- // This function applies a set of changes to the instance
373
- function applyProps(object, props) {
374
- var _instance$object;
375
- const instance = object.__r3f;
376
- const rootState = instance && findInitialRoot(instance).getState();
377
- const prevHandlers = instance == null ? void 0 : instance.eventCount;
378
- for (const prop in props) {
379
- let value = props[prop];
380
-
381
- // Don't mutate reserved keys
382
- if (RESERVED_PROPS.includes(prop)) continue;
383
-
384
- // Deal with pointer events, including removing them if undefined
385
- if (instance && EVENT_REGEX.test(prop)) {
386
- if (typeof value === 'function') instance.handlers[prop] = value;else delete instance.handlers[prop];
387
- instance.eventCount = Object.keys(instance.handlers).length;
388
- continue;
389
- }
390
-
391
- // Ignore setting undefined props
392
- // https://github.com/pmndrs/react-three-fiber/issues/274
393
- if (value === undefined) continue;
394
- let {
395
- root,
396
- key,
397
- target
398
- } = resolve(object, prop);
399
-
400
- // Throw an error if we attempted to set a pierced prop to a non-object
401
- if (target === undefined && (typeof root !== 'object' || root === null)) {
402
- throw Error(`R3F: Cannot set "${prop}". Ensure it is an object before setting "${key}".`);
403
- }
404
-
405
- // Layers must be written to the mask property
406
- if (target instanceof THREE.Layers && value instanceof THREE.Layers) {
407
- target.mask = value.mask;
408
- }
409
- // Set colors if valid color representation for automatic conversion (copy)
410
- else if (target instanceof THREE.Color && isColorRepresentation(value)) {
411
- target.set(value);
412
- }
413
- // Copy if properties match signatures and implement math interface (likely read-only)
414
- else if (target !== null && typeof target === 'object' && typeof target.set === 'function' && typeof target.copy === 'function' && value != null && value.constructor && target.constructor === value.constructor) {
415
- target.copy(value);
416
- }
417
- // Set array types
418
- else if (target !== null && typeof target === 'object' && typeof target.set === 'function' && Array.isArray(value)) {
419
- if (typeof target.fromArray === 'function') target.fromArray(value);else target.set(...value);
420
- }
421
- // Set literal types
422
- else if (target !== null && typeof target === 'object' && typeof target.set === 'function' && typeof value === 'number') {
423
- // Allow setting array scalars
424
- if (typeof target.setScalar === 'function') target.setScalar(value);
425
- // Otherwise just set single value
426
- else target.set(value);
427
- }
428
- // Else, just overwrite the value
429
- else {
430
- var _root$key;
431
- root[key] = value;
432
-
433
- // Auto-convert sRGB texture parameters for built-in materials
434
- // https://github.com/pmndrs/react-three-fiber/issues/344
435
- // https://github.com/mrdoob/three.js/pull/25857
436
- if (rootState && !rootState.linear && colorMaps.includes(key) && (_root$key = root[key]) != null && _root$key.isTexture &&
437
- // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
438
- root[key].format === THREE.RGBAFormat && root[key].type === THREE.UnsignedByteType) {
439
- // NOTE: this cannot be set from the renderer (e.g. sRGB source textures rendered to P3)
440
- root[key].colorSpace = THREE.SRGBColorSpace;
441
- }
442
- }
443
- }
444
-
445
- // Register event handlers
446
- if (instance != null && instance.parent && rootState != null && rootState.internal && (_instance$object = instance.object) != null && _instance$object.isObject3D && prevHandlers !== instance.eventCount) {
447
- const object = instance.object;
448
- // Pre-emptively remove the instance from the interaction manager
449
- const index = rootState.internal.interaction.indexOf(object);
450
- if (index > -1) rootState.internal.interaction.splice(index, 1);
451
- // Add the instance to the interaction manager only when it has handlers
452
- if (instance.eventCount && object.raycast !== null) {
453
- rootState.internal.interaction.push(object);
454
- }
455
- }
456
-
457
- // Auto-attach geometries and materials
458
- if (instance && instance.props.attach === undefined) {
459
- if (instance.object.isBufferGeometry) instance.props.attach = 'geometry';else if (instance.object.isMaterial) instance.props.attach = 'material';
460
- }
461
-
462
- // Instance was updated, request a frame
463
- if (instance) invalidateInstance(instance);
464
- return object;
465
- }
466
- function invalidateInstance(instance) {
467
- var _instance$root;
468
- if (!instance.parent) return;
469
- instance.props.onUpdate == null ? void 0 : instance.props.onUpdate(instance.object);
470
- const state = (_instance$root = instance.root) == null ? void 0 : _instance$root.getState == null ? void 0 : _instance$root.getState();
471
- if (state && state.internal.frames === 0) state.invalidate();
472
- }
473
- function updateCamera(camera, size) {
474
- // Do not mess with the camera if it belongs to the user
475
- // https://github.com/pmndrs/react-three-fiber/issues/92
476
- if (camera.manual) return;
477
- if (isOrthographicCamera(camera)) {
478
- camera.left = size.width / -2;
479
- camera.right = size.width / 2;
480
- camera.top = size.height / 2;
481
- camera.bottom = size.height / -2;
482
- } else {
483
- camera.aspect = size.width / size.height;
484
- }
485
- camera.updateProjectionMatrix();
486
- }
487
- const isObject3D = object => object == null ? void 0 : object.isObject3D;
488
-
489
- function makeId(event) {
490
- return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
491
- }
492
-
493
- /**
494
- * Release pointer captures.
495
- * This is called by releasePointerCapture in the API, and when an object is removed.
496
- */
497
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
498
- const captureData = captures.get(obj);
499
- if (captureData) {
500
- captures.delete(obj);
501
- // If this was the last capturing object for this pointer
502
- if (captures.size === 0) {
503
- capturedMap.delete(pointerId);
504
- captureData.target.releasePointerCapture(pointerId);
505
- }
506
- }
507
- }
508
- function removeInteractivity(store, object) {
509
- const {
510
- internal
511
- } = store.getState();
512
- // Removes every trace of an object from the data store
513
- internal.interaction = internal.interaction.filter(o => o !== object);
514
- internal.initialHits = internal.initialHits.filter(o => o !== object);
515
- internal.hovered.forEach((value, key) => {
516
- if (value.eventObject === object || value.object === object) {
517
- // Clear out intersects, they are outdated by now
518
- internal.hovered.delete(key);
519
- }
520
- });
521
- internal.capturedMap.forEach((captures, pointerId) => {
522
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
523
- });
524
- }
525
- function createEvents(store) {
526
- /** Calculates delta */
527
- function calculateDistance(event) {
528
- const {
529
- internal
530
- } = store.getState();
531
- const dx = event.offsetX - internal.initialClick[0];
532
- const dy = event.offsetY - internal.initialClick[1];
533
- return Math.round(Math.sqrt(dx * dx + dy * dy));
534
- }
535
-
536
- /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
537
- function filterPointerEvents(objects) {
538
- return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => {
539
- var _r3f;
540
- return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name];
541
- }));
542
- }
543
- function intersect(event, filter) {
544
- const state = store.getState();
545
- const duplicates = new Set();
546
- const intersections = [];
547
- // Allow callers to eliminate event objects
548
- const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction;
549
- // Reset all raycaster cameras to undefined
550
- for (let i = 0; i < eventsObjects.length; i++) {
551
- const state = getRootState(eventsObjects[i]);
552
- if (state) {
553
- state.raycaster.camera = undefined;
554
- }
555
- }
556
- if (!state.previousRoot) {
557
- // Make sure root-level pointer and ray are set up
558
- state.events.compute == null ? void 0 : state.events.compute(event, state);
559
- }
560
- function handleRaycast(obj) {
561
- const state = getRootState(obj);
562
- // Skip event handling when noEvents is set, or when the raycasters camera is null
563
- if (!state || !state.events.enabled || state.raycaster.camera === null) return [];
564
-
565
- // When the camera is undefined we have to call the event layers update function
566
- if (state.raycaster.camera === undefined) {
567
- var _state$previousRoot;
568
- state.events.compute == null ? void 0 : state.events.compute(event, state, (_state$previousRoot = state.previousRoot) == null ? void 0 : _state$previousRoot.getState());
569
- // If the camera is still undefined we have to skip this layer entirely
570
- if (state.raycaster.camera === undefined) state.raycaster.camera = null;
571
- }
572
-
573
- // Intersect object by object
574
- return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : [];
575
- }
576
-
577
- // Collect events
578
- let hits = eventsObjects
579
- // Intersect objects
580
- .flatMap(handleRaycast)
581
- // Sort by event priority and distance
582
- .sort((a, b) => {
583
- const aState = getRootState(a.object);
584
- const bState = getRootState(b.object);
585
- if (!aState || !bState) return a.distance - b.distance;
586
- return bState.events.priority - aState.events.priority || a.distance - b.distance;
587
- })
588
- // Filter out duplicates
589
- .filter(item => {
590
- const id = makeId(item);
591
- if (duplicates.has(id)) return false;
592
- duplicates.add(id);
593
- return true;
594
- });
595
-
596
- // https://github.com/mrdoob/three.js/issues/16031
597
- // Allow custom userland intersect sort order, this likely only makes sense on the root filter
598
- if (state.events.filter) hits = state.events.filter(hits, state);
599
-
600
- // Bubble up the events, find the event source (eventObject)
601
- for (const hit of hits) {
602
- let eventObject = hit.object;
603
- // Bubble event up
604
- while (eventObject) {
605
- var _r3f2;
606
- if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({
607
- ...hit,
608
- eventObject
609
- });
610
- eventObject = eventObject.parent;
611
- }
612
- }
613
-
614
- // If the interaction is captured, make all capturing targets part of the intersect.
615
- if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) {
616
- for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) {
617
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
618
- }
619
- }
620
- return intersections;
621
- }
622
-
623
- /** Handles intersections by forwarding them to handlers */
624
- function handleIntersects(intersections, event, delta, callback) {
625
- // If anything has been found, forward it to the event listeners
626
- if (intersections.length) {
627
- const localState = {
628
- stopped: false
629
- };
630
- for (const hit of intersections) {
631
- let state = getRootState(hit.object);
632
-
633
- // If the object is not managed by R3F, it might be parented to an element which is.
634
- // Traverse upwards until we find a managed parent and use its state instead.
635
- if (!state) {
636
- hit.object.traverseAncestors(obj => {
637
- const parentState = getRootState(obj);
638
- if (parentState) {
639
- state = parentState;
640
- return false;
641
- }
642
- });
643
- }
644
- if (state) {
645
- const {
646
- raycaster,
647
- pointer,
648
- camera,
649
- internal
650
- } = state;
651
- const unprojectedPoint = new THREE.Vector3(pointer.x, pointer.y, 0).unproject(camera);
652
- const hasPointerCapture = id => {
653
- var _internal$capturedMap, _internal$capturedMap2;
654
- return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
655
- };
656
- const setPointerCapture = id => {
657
- const captureData = {
658
- intersection: hit,
659
- target: event.target
660
- };
661
- if (internal.capturedMap.has(id)) {
662
- // if the pointerId was previously captured, we add the hit to the
663
- // event capturedMap.
664
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
665
- } else {
666
- // if the pointerId was not previously captured, we create a map
667
- // containing the hitObject, and the hit. hitObject is used for
668
- // faster access.
669
- internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
670
- }
671
- event.target.setPointerCapture(id);
672
- };
673
- const releasePointerCapture = id => {
674
- const captures = internal.capturedMap.get(id);
675
- if (captures) {
676
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
677
- }
678
- };
679
-
680
- // Add native event props
681
- let extractEventProps = {};
682
- // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones.
683
- for (let prop in event) {
684
- let property = event[prop];
685
- // Only copy over atomics, leave functions alone as these should be
686
- // called as event.nativeEvent.fn()
687
- if (typeof property !== 'function') extractEventProps[prop] = property;
688
- }
689
- let raycastEvent = {
690
- ...hit,
691
- ...extractEventProps,
692
- pointer,
693
- intersections,
694
- stopped: localState.stopped,
695
- delta,
696
- unprojectedPoint,
697
- ray: raycaster.ray,
698
- camera: camera,
699
- // Hijack stopPropagation, which just sets a flag
700
- stopPropagation() {
701
- // https://github.com/pmndrs/react-three-fiber/issues/596
702
- // Events are not allowed to stop propagation if the pointer has been captured
703
- const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId);
704
-
705
- // We only authorize stopPropagation...
706
- if (
707
- // ...if this pointer hasn't been captured
708
- !capturesForPointer ||
709
- // ... or if the hit object is capturing the pointer
710
- capturesForPointer.has(hit.eventObject)) {
711
- raycastEvent.stopped = localState.stopped = true;
712
- // Propagation is stopped, remove all other hover records
713
- // An event handler is only allowed to flush other handlers if it is hovered itself
714
- if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) {
715
- // Objects cannot flush out higher up objects that have already caught the event
716
- const higher = intersections.slice(0, intersections.indexOf(hit));
717
- cancelPointer([...higher, hit]);
718
- }
719
- }
720
- },
721
- // there should be a distinction between target and currentTarget
722
- target: {
723
- hasPointerCapture,
724
- setPointerCapture,
725
- releasePointerCapture
726
- },
727
- currentTarget: {
728
- hasPointerCapture,
729
- setPointerCapture,
730
- releasePointerCapture
731
- },
732
- nativeEvent: event
733
- };
734
-
735
- // Call subscribers
736
- callback(raycastEvent);
737
- // Event bubbling may be interrupted by stopPropagation
738
- if (localState.stopped === true) break;
739
- }
740
- }
741
- }
742
- return intersections;
743
- }
744
- function cancelPointer(intersections) {
745
- const {
746
- internal
747
- } = store.getState();
748
- for (const hoveredObj of internal.hovered.values()) {
749
- // When no objects were hit or the the hovered object wasn't found underneath the cursor
750
- // we call onPointerOut and delete the object from the hovered-elements map
751
- if (!intersections.length || !intersections.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) {
752
- const eventObject = hoveredObj.eventObject;
753
- const instance = eventObject.__r3f;
754
- internal.hovered.delete(makeId(hoveredObj));
755
- if (instance != null && instance.eventCount) {
756
- const handlers = instance.handlers;
757
- // Clear out intersects, they are outdated by now
758
- const data = {
759
- ...hoveredObj,
760
- intersections
761
- };
762
- handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
763
- handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
764
- }
765
- }
766
- }
767
- }
768
- function pointerMissed(event, objects) {
769
- for (let i = 0; i < objects.length; i++) {
770
- const instance = objects[i].__r3f;
771
- instance == null ? void 0 : instance.handlers.onPointerMissed == null ? void 0 : instance.handlers.onPointerMissed(event);
772
- }
773
- }
774
- function handlePointer(name) {
775
- // Deal with cancelation
776
- switch (name) {
777
- case 'onPointerLeave':
778
- case 'onPointerCancel':
779
- return () => cancelPointer([]);
780
- case 'onLostPointerCapture':
781
- return event => {
782
- const {
783
- internal
784
- } = store.getState();
785
- if ('pointerId' in event && internal.capturedMap.has(event.pointerId)) {
786
- // If the object event interface had onLostPointerCapture, we'd call it here on every
787
- // object that's getting removed. We call it on the next frame because onLostPointerCapture
788
- // fires before onPointerUp. Otherwise pointerUp would never be called if the event didn't
789
- // happen in the object it originated from, leaving components in a in-between state.
790
- requestAnimationFrame(() => {
791
- // Only release if pointer-up didn't do it already
792
- if (internal.capturedMap.has(event.pointerId)) {
793
- internal.capturedMap.delete(event.pointerId);
794
- cancelPointer([]);
795
- }
796
- });
797
- }
798
- };
799
- }
800
-
801
- // Any other pointer goes here ...
802
- return function handleEvent(event) {
803
- const {
804
- onPointerMissed,
805
- internal
806
- } = store.getState();
807
-
808
- // prepareRay(event)
809
- internal.lastEvent.current = event;
810
-
811
- // Get fresh intersects
812
- const isPointerMove = name === 'onPointerMove';
813
- const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick';
814
- const filter = isPointerMove ? filterPointerEvents : undefined;
815
- const hits = intersect(event, filter);
816
- const delta = isClickEvent ? calculateDistance(event) : 0;
817
-
818
- // Save initial coordinates on pointer-down
819
- if (name === 'onPointerDown') {
820
- internal.initialClick = [event.offsetX, event.offsetY];
821
- internal.initialHits = hits.map(hit => hit.eventObject);
822
- }
823
-
824
- // If a click yields no results, pass it back to the user as a miss
825
- // Missed events have to come first in order to establish user-land side-effect clean up
826
- if (isClickEvent && !hits.length) {
827
- if (delta <= 2) {
828
- pointerMissed(event, internal.interaction);
829
- if (onPointerMissed) onPointerMissed(event);
830
- }
831
- }
832
- // Take care of unhover
833
- if (isPointerMove) cancelPointer(hits);
834
- function onIntersect(data) {
835
- const eventObject = data.eventObject;
836
- const instance = eventObject.__r3f;
837
-
838
- // Check presence of handlers
839
- if (!(instance != null && instance.eventCount)) return;
840
- const handlers = instance.handlers;
841
-
842
- /*
843
- MAYBE TODO, DELETE IF NOT:
844
- Check if the object is captured, captured events should not have intersects running in parallel
845
- But wouldn't it be better to just replace capturedMap with a single entry?
846
- Also, are we OK with straight up making picking up multiple objects impossible?
847
-
848
- const pointerId = (data as ThreeEvent<PointerEvent>).pointerId
849
- if (pointerId !== undefined) {
850
- const capturedMeshSet = internal.capturedMap.get(pointerId)
851
- if (capturedMeshSet) {
852
- const captured = capturedMeshSet.get(eventObject)
853
- if (captured && captured.localState.stopped) return
854
- }
855
- }*/
856
-
857
- if (isPointerMove) {
858
- // Move event ...
859
- if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
860
- // When enter or out is present take care of hover-state
861
- const id = makeId(data);
862
- const hoveredItem = internal.hovered.get(id);
863
- if (!hoveredItem) {
864
- // If the object wasn't previously hovered, book it and call its handler
865
- internal.hovered.set(id, data);
866
- handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
867
- handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
868
- } else if (hoveredItem.stopped) {
869
- // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
870
- data.stopPropagation();
871
- }
872
- }
873
- // Call mouse move
874
- handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
875
- } else {
876
- // All other events ...
877
- const handler = handlers[name];
878
- if (handler) {
879
- // Forward all events back to their respective handlers with the exception of click events,
880
- // which must use the initial target
881
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
882
- // Missed events have to come first
883
- pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object)));
884
- // Now call the handler
885
- handler(data);
886
- }
887
- } else {
888
- // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit
889
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
890
- pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object)));
891
- }
892
- }
893
- }
894
- }
895
- handleIntersects(hits, event, delta, onIntersect);
896
- };
897
- }
898
- return {
899
- handlePointer
900
- };
901
- }
902
-
903
- const isRenderer = def => !!(def != null && def.render);
904
- const context = /* @__PURE__ */React.createContext(null);
905
- const createStore = (invalidate, advance) => {
906
- const rootStore = createWithEqualityFn((set, get) => {
907
- const position = new THREE.Vector3();
908
- const defaultTarget = new THREE.Vector3();
909
- const tempTarget = new THREE.Vector3();
910
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
911
- const {
912
- width,
913
- height,
914
- top,
915
- left
916
- } = size;
917
- const aspect = width / height;
918
- if (target.isVector3) tempTarget.copy(target);else tempTarget.set(...target);
919
- const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
920
- if (isOrthographicCamera(camera)) {
921
- return {
922
- width: width / camera.zoom,
923
- height: height / camera.zoom,
924
- top,
925
- left,
926
- factor: 1,
927
- distance,
928
- aspect
929
- };
930
- } else {
931
- const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians
932
- const h = 2 * Math.tan(fov / 2) * distance; // visible height
933
- const w = h * (width / height);
934
- return {
935
- width: w,
936
- height: h,
937
- top,
938
- left,
939
- factor: width / w,
940
- distance,
941
- aspect
942
- };
943
- }
944
- }
945
- let performanceTimeout = undefined;
946
- const setPerformanceCurrent = current => set(state => ({
947
- performance: {
948
- ...state.performance,
949
- current
950
- }
951
- }));
952
- const pointer = new THREE.Vector2();
953
- const rootState = {
954
- set,
955
- get,
956
- // Mock objects that have to be configured
957
- gl: null,
958
- camera: null,
959
- raycaster: null,
960
- events: {
961
- priority: 1,
962
- enabled: true,
963
- connected: false
964
- },
965
- scene: null,
966
- xr: null,
967
- invalidate: (frames = 1) => invalidate(get(), frames),
968
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
969
- legacy: false,
970
- linear: false,
971
- flat: false,
972
- controls: null,
973
- clock: new THREE.Clock(),
974
- pointer,
975
- mouse: pointer,
976
- frameloop: 'always',
977
- onPointerMissed: undefined,
978
- performance: {
979
- current: 1,
980
- min: 0.5,
981
- max: 1,
982
- debounce: 200,
983
- regress: () => {
984
- const state = get();
985
- // Clear timeout
986
- if (performanceTimeout) clearTimeout(performanceTimeout);
987
- // Set lower bound performance
988
- if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min);
989
- // Go back to upper bound performance after a while unless something regresses meanwhile
990
- performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce);
991
- }
992
- },
993
- size: {
994
- width: 0,
995
- height: 0,
996
- top: 0,
997
- left: 0
998
- },
999
- viewport: {
1000
- initialDpr: 0,
1001
- dpr: 0,
1002
- width: 0,
1003
- height: 0,
1004
- top: 0,
1005
- left: 0,
1006
- aspect: 0,
1007
- distance: 0,
1008
- factor: 0,
1009
- getCurrentViewport
1010
- },
1011
- setEvents: events => set(state => ({
1012
- ...state,
1013
- events: {
1014
- ...state.events,
1015
- ...events
1016
- }
1017
- })),
1018
- setSize: (width, height, top = 0, left = 0) => {
1019
- const camera = get().camera;
1020
- const size = {
1021
- width,
1022
- height,
1023
- top,
1024
- left
1025
- };
1026
- set(state => ({
1027
- size,
1028
- viewport: {
1029
- ...state.viewport,
1030
- ...getCurrentViewport(camera, defaultTarget, size)
1031
- }
1032
- }));
1033
- },
1034
- setDpr: dpr => set(state => {
1035
- const resolved = calculateDpr(dpr);
1036
- return {
1037
- viewport: {
1038
- ...state.viewport,
1039
- dpr: resolved,
1040
- initialDpr: state.viewport.initialDpr || resolved
1041
- }
1042
- };
1043
- }),
1044
- setFrameloop: (frameloop = 'always') => {
1045
- const clock = get().clock;
1046
-
1047
- // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp)
1048
- clock.stop();
1049
- clock.elapsedTime = 0;
1050
- if (frameloop !== 'never') {
1051
- clock.start();
1052
- clock.elapsedTime = 0;
1053
- }
1054
- set(() => ({
1055
- frameloop
1056
- }));
1057
- },
1058
- previousRoot: undefined,
1059
- internal: {
1060
- // Events
1061
- interaction: [],
1062
- hovered: new Map(),
1063
- subscribers: [],
1064
- initialClick: [0, 0],
1065
- initialHits: [],
1066
- capturedMap: new Map(),
1067
- lastEvent: /*#__PURE__*/React.createRef(),
1068
- // Updates
1069
- active: false,
1070
- frames: 0,
1071
- priority: 0,
1072
- subscribe: (ref, priority, store) => {
1073
- const internal = get().internal;
1074
- // If this subscription was given a priority, it takes rendering into its own hands
1075
- // For that reason we switch off automatic rendering and increase the manual flag
1076
- // As long as this flag is positive there can be no internal rendering at all
1077
- // because there could be multiple render subscriptions
1078
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1079
- internal.subscribers.push({
1080
- ref,
1081
- priority,
1082
- store
1083
- });
1084
- // Register subscriber and sort layers from lowest to highest, meaning,
1085
- // highest priority renders last (on top of the other frames)
1086
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1087
- return () => {
1088
- const internal = get().internal;
1089
- if (internal != null && internal.subscribers) {
1090
- // Decrease manual flag if this subscription had a priority
1091
- internal.priority = internal.priority - (priority > 0 ? 1 : 0);
1092
- // Remove subscriber from list
1093
- internal.subscribers = internal.subscribers.filter(s => s.ref !== ref);
1094
- }
1095
- };
1096
- }
1097
- }
1098
- };
1099
- return rootState;
1100
- });
1101
- const state = rootStore.getState();
1102
- let oldSize = state.size;
1103
- let oldDpr = state.viewport.dpr;
1104
- let oldCamera = state.camera;
1105
- rootStore.subscribe(() => {
1106
- const {
1107
- camera,
1108
- size,
1109
- viewport,
1110
- gl,
1111
- set
1112
- } = rootStore.getState();
1113
-
1114
- // Resize camera and renderer on changes to size and pixelratio
1115
- if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
1116
- oldSize = size;
1117
- oldDpr = viewport.dpr;
1118
- // Update camera & renderer
1119
- updateCamera(camera, size);
1120
- if (viewport.dpr > 0) gl.setPixelRatio(viewport.dpr);
1121
- const updateStyle = typeof HTMLCanvasElement !== 'undefined' && gl.domElement instanceof HTMLCanvasElement;
1122
- gl.setSize(size.width, size.height, updateStyle);
1123
- }
1124
-
1125
- // Update viewport once the camera changes
1126
- if (camera !== oldCamera) {
1127
- oldCamera = camera;
1128
- // Update viewport
1129
- set(state => ({
1130
- viewport: {
1131
- ...state.viewport,
1132
- ...state.viewport.getCurrentViewport(camera)
1133
- }
1134
- }));
1135
- }
1136
- });
1137
-
1138
- // Invalidate on any change
1139
- rootStore.subscribe(state => invalidate(state));
1140
-
1141
- // Return root state
1142
- return rootStore;
1143
- };
1144
-
1145
- /**
1146
- * Exposes an object's {@link Instance}.
1147
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
1148
- *
1149
- * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
1150
- */
1151
- function useInstanceHandle(ref) {
1152
- const instance = React.useRef(null);
1153
- React.useImperativeHandle(instance, () => ref.current.__r3f, [ref]);
1154
- return instance;
1155
- }
1156
-
1157
- /**
1158
- * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
1159
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usestore
1160
- */
1161
- function useStore() {
1162
- const store = React.useContext(context);
1163
- if (!store) throw new Error('R3F: Hooks can only be used within the Canvas component!');
1164
- return store;
1165
- }
1166
-
1167
- /**
1168
- * Accesses R3F's internal state, containing renderer, canvas, scene, etc.
1169
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree
1170
- */
1171
- function useThree(selector = state => state, equalityFn) {
1172
- return useStore()(selector, equalityFn);
1173
- }
1174
-
1175
- /**
1176
- * Executes a callback before render in a shared frame loop.
1177
- * Can order effects with render priority or manually render with a positive priority.
1178
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe
1179
- */
1180
- function useFrame(callback, renderPriority = 0) {
1181
- const store = useStore();
1182
- const subscribe = store.getState().internal.subscribe;
1183
- // Memoize ref
1184
- const ref = useMutableCallback(callback);
1185
- // Subscribe on mount, unsubscribe on unmount
1186
- useIsomorphicLayoutEffect(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]);
1187
- return null;
1188
- }
1189
-
1190
- /**
1191
- * Returns a node graph of an object with named nodes & materials.
1192
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
1193
- */
1194
- function useGraph(object) {
1195
- return React.useMemo(() => buildGraph(object), [object]);
1196
- }
1197
- const memoizedLoaders = new WeakMap();
1198
- const isConstructor$1 = value => {
1199
- var _value$prototype;
1200
- return typeof value === 'function' && (value == null ? void 0 : (_value$prototype = value.prototype) == null ? void 0 : _value$prototype.constructor) === value;
1201
- };
1202
- function loadingFn(extensions, onProgress) {
1203
- return function (Proto, ...input) {
1204
- let loader;
1205
-
1206
- // Construct and cache loader if constructor was passed
1207
- if (isConstructor$1(Proto)) {
1208
- loader = memoizedLoaders.get(Proto);
1209
- if (!loader) {
1210
- loader = new Proto();
1211
- memoizedLoaders.set(Proto, loader);
1212
- }
1213
- } else {
1214
- loader = Proto;
1215
- }
1216
-
1217
- // Apply loader extensions
1218
- if (extensions) extensions(loader);
1219
-
1220
- // Go through the urls and load them
1221
- return Promise.all(input.map(input => new Promise((res, reject) => loader.load(input, data => {
1222
- if (isObject3D(data == null ? void 0 : data.scene)) Object.assign(data, buildGraph(data.scene));
1223
- res(data);
1224
- }, onProgress, error => reject(new Error(`Could not load ${input}: ${error == null ? void 0 : error.message}`))))));
1225
- };
1226
- }
1227
-
1228
- /**
1229
- * Synchronously loads and caches assets with a three loader.
1230
- *
1231
- * Note: this hook's caller must be wrapped with `React.Suspense`
1232
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1233
- */
1234
- function useLoader(loader, input, extensions, onProgress) {
1235
- // Use suspense to load async assets
1236
- const keys = Array.isArray(input) ? input : [input];
1237
- const results = suspend(loadingFn(extensions, onProgress), [loader, ...keys], {
1238
- equal: is.equ
1239
- });
1240
- // Return the object(s)
1241
- return Array.isArray(input) ? results : results[0];
1242
- }
1243
-
1244
- /**
1245
- * Preloads an asset into cache as a side-effect.
1246
- */
1247
- useLoader.preload = function (loader, input, extensions) {
1248
- const keys = Array.isArray(input) ? input : [input];
1249
- return preload(loadingFn(extensions), [loader, ...keys]);
1250
- };
1251
-
1252
- /**
1253
- * Removes a loaded asset from cache.
1254
- */
1255
- useLoader.clear = function (loader, input) {
1256
- const keys = Array.isArray(input) ? input : [input];
1257
- return clear([loader, ...keys]);
1258
- };
1259
-
1260
- var packageData = {
1261
- name: "@react-three/fiber",
1262
- version: "9.4.1",
1263
- description: "A React renderer for Threejs",
1264
- keywords: [
1265
- "react",
1266
- "renderer",
1267
- "fiber",
1268
- "three",
1269
- "threejs"
1270
- ],
1271
- author: "Paul Henschel (https://github.com/drcmda)",
1272
- license: "MIT",
1273
- maintainers: [
1274
- "Josh Ellis (https://github.com/joshuaellis)",
1275
- "Cody Bennett (https://github.com/codyjasonbennett)",
1276
- "Kris Baumgarter (https://github.com/krispya)"
1277
- ],
1278
- bugs: {
1279
- url: "https://github.com/pmndrs/react-three-fiber/issues"
1280
- },
1281
- homepage: "https://github.com/pmndrs/react-three-fiber#readme",
1282
- repository: {
1283
- type: "git",
1284
- url: "git+https://github.com/pmndrs/react-three-fiber.git"
1285
- },
1286
- collective: {
1287
- type: "opencollective",
1288
- url: "https://opencollective.com/react-three-fiber"
1289
- },
1290
- main: "dist/react-three-fiber.cjs.js",
1291
- module: "dist/react-three-fiber.esm.js",
1292
- types: "dist/react-three-fiber.cjs.d.ts",
1293
- "react-native": "native/dist/react-three-fiber-native.cjs.js",
1294
- sideEffects: false,
1295
- preconstruct: {
1296
- entrypoints: [
1297
- "index.tsx",
1298
- "native.tsx"
1299
- ]
1300
- },
1301
- scripts: {
1302
- prebuild: "cp ../../readme.md readme.md"
1303
- },
1304
- dependencies: {
1305
- "@babel/runtime": "^7.17.8",
1306
- "@types/react-reconciler": "^0.32.0",
1307
- "@types/webxr": "*",
1308
- "base64-js": "^1.5.1",
1309
- buffer: "^6.0.3",
1310
- "its-fine": "^2.0.0",
1311
- "react-reconciler": "^0.31.0",
1312
- "react-use-measure": "^2.1.7",
1313
- scheduler: "^0.25.0",
1314
- "suspend-react": "^0.1.3",
1315
- "use-sync-external-store": "^1.4.0",
1316
- zustand: "^5.0.3"
1317
- },
1318
- peerDependencies: {
1319
- expo: ">=43.0",
1320
- "expo-asset": ">=8.4",
1321
- "expo-file-system": ">=11.0",
1322
- "expo-gl": ">=11.0",
1323
- react: "^19.0.0",
1324
- "react-dom": "^19.0.0",
1325
- "react-native": ">=0.78",
1326
- three: ">=0.156"
1327
- },
1328
- peerDependenciesMeta: {
1329
- "react-dom": {
1330
- optional: true
1331
- },
1332
- "react-native": {
1333
- optional: true
1334
- },
1335
- expo: {
1336
- optional: true
1337
- },
1338
- "expo-asset": {
1339
- optional: true
1340
- },
1341
- "expo-file-system": {
1342
- optional: true
1343
- },
1344
- "expo-gl": {
1345
- optional: true
1346
- }
1347
- }
1348
- };
1349
-
1350
- function createReconciler(config) {
1351
- const reconciler = Reconciler(config);
1352
-
1353
- // @ts-ignore DefinitelyTyped is not up to date
1354
- reconciler.injectIntoDevTools();
1355
- return reconciler;
1356
- }
1357
- const NoEventPriority = 0;
1358
-
1359
- // TODO: handle constructor overloads
1360
- // https://github.com/pmndrs/react-three-fiber/pull/2931
1361
- // https://github.com/microsoft/TypeScript/issues/37079
1362
-
1363
- const catalogue = {};
1364
- const PREFIX_REGEX = /^three(?=[A-Z])/;
1365
- const toPascalCase = type => `${type[0].toUpperCase()}${type.slice(1)}`;
1366
- let i = 0;
1367
- const isConstructor = object => typeof object === 'function';
1368
- function extend(objects) {
1369
- if (isConstructor(objects)) {
1370
- const Component = `${i++}`;
1371
- catalogue[Component] = objects;
1372
- return Component;
1373
- } else {
1374
- Object.assign(catalogue, objects);
1375
- }
1376
- }
1377
- function validateInstance(type, props) {
1378
- // Get target from catalogue
1379
- const name = toPascalCase(type);
1380
- const target = catalogue[name];
1381
-
1382
- // Validate element target
1383
- if (type !== 'primitive' && !target) throw new Error(`R3F: ${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);
1384
-
1385
- // Validate primitives
1386
- if (type === 'primitive' && !props.object) throw new Error(`R3F: Primitives without 'object' are invalid!`);
1387
-
1388
- // Throw if an object or literal was passed for args
1389
- if (props.args !== undefined && !Array.isArray(props.args)) throw new Error('R3F: The args prop must be an array!');
1390
- }
1391
- function createInstance(type, props, root) {
1392
- var _props$object;
1393
- // Remove three* prefix from elements if native element not present
1394
- type = toPascalCase(type) in catalogue ? type : type.replace(PREFIX_REGEX, '');
1395
- validateInstance(type, props);
1396
-
1397
- // Regenerate the R3F instance for primitives to simulate a new object
1398
- if (type === 'primitive' && (_props$object = props.object) != null && _props$object.__r3f) delete props.object.__r3f;
1399
- return prepare(props.object, root, type, props);
1400
- }
1401
- function hideInstance(instance) {
1402
- if (!instance.isHidden) {
1403
- var _instance$parent;
1404
- if (instance.props.attach && (_instance$parent = instance.parent) != null && _instance$parent.object) {
1405
- detach(instance.parent, instance);
1406
- } else if (isObject3D(instance.object)) {
1407
- instance.object.visible = false;
1408
- }
1409
- instance.isHidden = true;
1410
- invalidateInstance(instance);
1411
- }
1412
- }
1413
- function unhideInstance(instance) {
1414
- if (instance.isHidden) {
1415
- var _instance$parent2;
1416
- if (instance.props.attach && (_instance$parent2 = instance.parent) != null && _instance$parent2.object) {
1417
- attach(instance.parent, instance);
1418
- } else if (isObject3D(instance.object) && instance.props.visible !== false) {
1419
- instance.object.visible = true;
1420
- }
1421
- instance.isHidden = false;
1422
- invalidateInstance(instance);
1423
- }
1424
- }
1425
-
1426
- // https://github.com/facebook/react/issues/20271
1427
- // This will make sure events and attach are only handled once when trees are complete
1428
- function handleContainerEffects(parent, child, beforeChild) {
1429
- // Bail if tree isn't mounted or parent is not a container.
1430
- // This ensures that the tree is finalized and React won't discard results to Suspense
1431
- const state = child.root.getState();
1432
- if (!parent.parent && parent.object !== state.scene) return;
1433
-
1434
- // Create & link object on first run
1435
- if (!child.object) {
1436
- var _child$props$object, _child$props$args;
1437
- // Get target from catalogue
1438
- const target = catalogue[toPascalCase(child.type)];
1439
-
1440
- // Create object
1441
- child.object = (_child$props$object = child.props.object) != null ? _child$props$object : new target(...((_child$props$args = child.props.args) != null ? _child$props$args : []));
1442
- child.object.__r3f = child;
1443
- }
1444
-
1445
- // Set initial props
1446
- applyProps(child.object, child.props);
1447
-
1448
- // Append instance
1449
- if (child.props.attach) {
1450
- attach(parent, child);
1451
- } else if (isObject3D(child.object) && isObject3D(parent.object)) {
1452
- const childIndex = parent.object.children.indexOf(beforeChild == null ? void 0 : beforeChild.object);
1453
- if (beforeChild && childIndex !== -1) {
1454
- // If the child is already in the parent's children array, move it to the new position
1455
- // Otherwise, just insert it at the target position
1456
- const existingIndex = parent.object.children.indexOf(child.object);
1457
- if (existingIndex !== -1) {
1458
- parent.object.children.splice(existingIndex, 1);
1459
- const adjustedIndex = existingIndex < childIndex ? childIndex - 1 : childIndex;
1460
- parent.object.children.splice(adjustedIndex, 0, child.object);
1461
- } else {
1462
- child.object.parent = parent.object;
1463
- parent.object.children.splice(childIndex, 0, child.object);
1464
- child.object.dispatchEvent({
1465
- type: 'added'
1466
- });
1467
- parent.object.dispatchEvent({
1468
- type: 'childadded',
1469
- child: child.object
1470
- });
1471
- }
1472
- } else {
1473
- parent.object.add(child.object);
1474
- }
1475
- }
1476
-
1477
- // Link subtree
1478
- for (const childInstance of child.children) handleContainerEffects(child, childInstance);
1479
-
1480
- // Tree was updated, request a frame
1481
- invalidateInstance(child);
1482
- }
1483
- function appendChild(parent, child) {
1484
- if (!child) return;
1485
-
1486
- // Link instances
1487
- child.parent = parent;
1488
- parent.children.push(child);
1489
-
1490
- // Attach tree once complete
1491
- handleContainerEffects(parent, child);
1492
- }
1493
- function insertBefore(parent, child, beforeChild) {
1494
- if (!child || !beforeChild) return;
1495
-
1496
- // Link instances
1497
- child.parent = parent;
1498
- const childIndex = parent.children.indexOf(beforeChild);
1499
- if (childIndex !== -1) parent.children.splice(childIndex, 0, child);else parent.children.push(child);
1500
-
1501
- // Attach tree once complete
1502
- handleContainerEffects(parent, child, beforeChild);
1503
- }
1504
- function disposeOnIdle(object) {
1505
- if (typeof object.dispose === 'function') {
1506
- const handleDispose = () => {
1507
- try {
1508
- object.dispose();
1509
- } catch {
1510
- // no-op
1511
- }
1512
- };
1513
-
1514
- // In a testing environment, cleanup immediately
1515
- if (typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined') handleDispose();
1516
- // Otherwise, using a real GPU so schedule cleanup to prevent stalls
1517
- else unstable_scheduleCallback(unstable_IdlePriority, handleDispose);
1518
- }
1519
- }
1520
- function removeChild(parent, child, dispose) {
1521
- if (!child) return;
1522
-
1523
- // Unlink instances
1524
- child.parent = null;
1525
- const childIndex = parent.children.indexOf(child);
1526
- if (childIndex !== -1) parent.children.splice(childIndex, 1);
1527
-
1528
- // Eagerly tear down tree
1529
- if (child.props.attach) {
1530
- detach(parent, child);
1531
- } else if (isObject3D(child.object) && isObject3D(parent.object)) {
1532
- parent.object.remove(child.object);
1533
- removeInteractivity(findInitialRoot(child), child.object);
1534
- }
1535
-
1536
- // Allow objects to bail out of unmount disposal with dispose={null}
1537
- const shouldDispose = child.props.dispose !== null && dispose !== false;
1538
-
1539
- // Recursively remove instance children
1540
- for (let i = child.children.length - 1; i >= 0; i--) {
1541
- const node = child.children[i];
1542
- removeChild(child, node, shouldDispose);
1543
- }
1544
- child.children.length = 0;
1545
-
1546
- // Unlink instance object
1547
- delete child.object.__r3f;
1548
-
1549
- // Dispose object whenever the reconciler feels like it.
1550
- // Never dispose of primitives because their state may be kept outside of React!
1551
- // In order for an object to be able to dispose it
1552
- // - has a dispose method
1553
- // - cannot be a <primitive object={...} />
1554
- // - cannot be a THREE.Scene, because three has broken its own API
1555
- if (shouldDispose && child.type !== 'primitive' && child.object.type !== 'Scene') {
1556
- disposeOnIdle(child.object);
1557
- }
1558
-
1559
- // Tree was updated, request a frame for top-level instance
1560
- if (dispose === undefined) invalidateInstance(child);
1561
- }
1562
- function setFiberRef(fiber, publicInstance) {
1563
- for (const _fiber of [fiber, fiber.alternate]) {
1564
- if (_fiber !== null) {
1565
- if (typeof _fiber.ref === 'function') {
1566
- _fiber.refCleanup == null ? void 0 : _fiber.refCleanup();
1567
- const cleanup = _fiber.ref(publicInstance);
1568
- if (typeof cleanup === 'function') _fiber.refCleanup = cleanup;
1569
- } else if (_fiber.ref) {
1570
- _fiber.ref.current = publicInstance;
1571
- }
1572
- }
1573
- }
1574
- }
1575
- const reconstructed = [];
1576
- function swapInstances() {
1577
- // Detach instance
1578
- for (const [instance] of reconstructed) {
1579
- const parent = instance.parent;
1580
- if (parent) {
1581
- if (instance.props.attach) {
1582
- detach(parent, instance);
1583
- } else if (isObject3D(instance.object) && isObject3D(parent.object)) {
1584
- parent.object.remove(instance.object);
1585
- }
1586
- for (const child of instance.children) {
1587
- if (child.props.attach) {
1588
- detach(instance, child);
1589
- } else if (isObject3D(child.object) && isObject3D(instance.object)) {
1590
- instance.object.remove(child.object);
1591
- }
1592
- }
1593
- }
1594
-
1595
- // If the old instance is hidden, we need to unhide it.
1596
- // React assumes it can discard instances since they're pure for DOM.
1597
- // This isn't true for us since our lifetimes are impure and longliving.
1598
- // So, we manually check if an instance was hidden and unhide it.
1599
- if (instance.isHidden) unhideInstance(instance);
1600
-
1601
- // Dispose of old object if able
1602
- if (instance.object.__r3f) delete instance.object.__r3f;
1603
- if (instance.type !== 'primitive') disposeOnIdle(instance.object);
1604
- }
1605
-
1606
- // Update instance
1607
- for (const [instance, props, fiber] of reconstructed) {
1608
- instance.props = props;
1609
- const parent = instance.parent;
1610
- if (parent) {
1611
- var _instance$props$objec, _instance$props$args;
1612
- // Get target from catalogue
1613
- const target = catalogue[toPascalCase(instance.type)];
1614
-
1615
- // Create object
1616
- instance.object = (_instance$props$objec = instance.props.object) != null ? _instance$props$objec : new target(...((_instance$props$args = instance.props.args) != null ? _instance$props$args : []));
1617
- instance.object.__r3f = instance;
1618
- setFiberRef(fiber, instance.object);
1619
-
1620
- // Set initial props
1621
- applyProps(instance.object, instance.props);
1622
- if (instance.props.attach) {
1623
- attach(parent, instance);
1624
- } else if (isObject3D(instance.object) && isObject3D(parent.object)) {
1625
- parent.object.add(instance.object);
1626
- }
1627
- for (const child of instance.children) {
1628
- if (child.props.attach) {
1629
- attach(instance, child);
1630
- } else if (isObject3D(child.object) && isObject3D(instance.object)) {
1631
- instance.object.add(child.object);
1632
- }
1633
- }
1634
-
1635
- // Tree was updated, request a frame
1636
- invalidateInstance(instance);
1637
- }
1638
- }
1639
- reconstructed.length = 0;
1640
- }
1641
-
1642
- // Don't handle text instances, make it no-op
1643
- const handleTextInstance = () => {};
1644
- const NO_CONTEXT = {};
1645
- let currentUpdatePriority = NoEventPriority;
1646
-
1647
- // https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberFlags.js
1648
- const NoFlags = 0;
1649
- const Update = 4;
1650
- const reconciler = /* @__PURE__ */createReconciler({
1651
- isPrimaryRenderer: false,
1652
- warnsIfNotActing: false,
1653
- supportsMutation: true,
1654
- supportsPersistence: false,
1655
- supportsHydration: false,
1656
- createInstance,
1657
- removeChild,
1658
- appendChild,
1659
- appendInitialChild: appendChild,
1660
- insertBefore,
1661
- appendChildToContainer(container, child) {
1662
- const scene = container.getState().scene.__r3f;
1663
- if (!child || !scene) return;
1664
- appendChild(scene, child);
1665
- },
1666
- removeChildFromContainer(container, child) {
1667
- const scene = container.getState().scene.__r3f;
1668
- if (!child || !scene) return;
1669
- removeChild(scene, child);
1670
- },
1671
- insertInContainerBefore(container, child, beforeChild) {
1672
- const scene = container.getState().scene.__r3f;
1673
- if (!child || !beforeChild || !scene) return;
1674
- insertBefore(scene, child, beforeChild);
1675
- },
1676
- getRootHostContext: () => NO_CONTEXT,
1677
- getChildHostContext: () => NO_CONTEXT,
1678
- commitUpdate(instance, type, oldProps, newProps, fiber) {
1679
- var _newProps$args, _oldProps$args, _newProps$args2;
1680
- validateInstance(type, newProps);
1681
- let reconstruct = false;
1682
-
1683
- // Reconstruct primitives if object prop changes
1684
- if (instance.type === 'primitive' && oldProps.object !== newProps.object) reconstruct = true;
1685
- // Reconstruct instance if args were added or removed
1686
- else if (((_newProps$args = newProps.args) == null ? void 0 : _newProps$args.length) !== ((_oldProps$args = oldProps.args) == null ? void 0 : _oldProps$args.length)) reconstruct = true;
1687
- // Reconstruct instance if args were changed
1688
- else if ((_newProps$args2 = newProps.args) != null && _newProps$args2.some((value, index) => {
1689
- var _oldProps$args2;
1690
- return value !== ((_oldProps$args2 = oldProps.args) == null ? void 0 : _oldProps$args2[index]);
1691
- })) reconstruct = true;
1692
-
1693
- // Reconstruct when args or <primitive object={...} have changes
1694
- if (reconstruct) {
1695
- reconstructed.push([instance, {
1696
- ...newProps
1697
- }, fiber]);
1698
- } else {
1699
- // Create a diff-set, flag if there are any changes
1700
- const changedProps = diffProps(instance, newProps);
1701
- if (Object.keys(changedProps).length) {
1702
- Object.assign(instance.props, changedProps);
1703
- applyProps(instance.object, changedProps);
1704
- }
1705
- }
1706
-
1707
- // Flush reconstructed siblings when we hit the last updated child in a sequence
1708
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
1709
- if (isTailSibling) swapInstances();
1710
- },
1711
- finalizeInitialChildren: () => false,
1712
- commitMount() {},
1713
- getPublicInstance: instance => instance == null ? void 0 : instance.object,
1714
- prepareForCommit: () => null,
1715
- preparePortalMount: container => prepare(container.getState().scene, container, '', {}),
1716
- resetAfterCommit: () => {},
1717
- shouldSetTextContent: () => false,
1718
- clearContainer: () => false,
1719
- hideInstance,
1720
- unhideInstance,
1721
- createTextInstance: handleTextInstance,
1722
- hideTextInstance: handleTextInstance,
1723
- unhideTextInstance: handleTextInstance,
1724
- scheduleTimeout: typeof setTimeout === 'function' ? setTimeout : undefined,
1725
- cancelTimeout: typeof clearTimeout === 'function' ? clearTimeout : undefined,
1726
- noTimeout: -1,
1727
- getInstanceFromNode: () => null,
1728
- beforeActiveInstanceBlur() {},
1729
- afterActiveInstanceBlur() {},
1730
- detachDeletedInstance() {},
1731
- prepareScopeUpdate() {},
1732
- getInstanceFromScope: () => null,
1733
- shouldAttemptEagerTransition: () => false,
1734
- trackSchedulerEvent: () => {},
1735
- resolveEventType: () => null,
1736
- resolveEventTimeStamp: () => -1.1,
1737
- requestPostPaintCallback() {},
1738
- maySuspendCommit: () => false,
1739
- preloadInstance: () => true,
1740
- // true indicates already loaded
1741
- startSuspendingCommit() {},
1742
- suspendInstance() {},
1743
- waitForCommitToBeReady: () => null,
1744
- NotPendingTransition: null,
1745
- // The reconciler types use the internal ReactContext with all the hidden properties
1746
- // so we have to cast from the public React.Context type
1747
- HostTransitionContext: /* @__PURE__ */React.createContext(null),
1748
- setCurrentUpdatePriority(newPriority) {
1749
- currentUpdatePriority = newPriority;
1750
- },
1751
- getCurrentUpdatePriority() {
1752
- return currentUpdatePriority;
1753
- },
1754
- resolveUpdatePriority() {
1755
- var _window$event;
1756
- if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
1757
- switch (typeof window !== 'undefined' && ((_window$event = window.event) == null ? void 0 : _window$event.type)) {
1758
- case 'click':
1759
- case 'contextmenu':
1760
- case 'dblclick':
1761
- case 'pointercancel':
1762
- case 'pointerdown':
1763
- case 'pointerup':
1764
- return DiscreteEventPriority;
1765
- case 'pointermove':
1766
- case 'pointerout':
1767
- case 'pointerover':
1768
- case 'pointerenter':
1769
- case 'pointerleave':
1770
- case 'wheel':
1771
- return ContinuousEventPriority;
1772
- default:
1773
- return DefaultEventPriority;
1774
- }
1775
- },
1776
- resetFormInstance() {},
1777
- // @ts-ignore DefinitelyTyped is not up to date
1778
- rendererPackageName: '@react-three/fiber',
1779
- rendererVersion: packageData.version
1780
- });
1781
-
1782
- const _roots = new Map();
1783
- const shallowLoose = {
1784
- objects: 'shallow',
1785
- strict: false
1786
- };
1787
- function computeInitialSize(canvas, size) {
1788
- if (!size && typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement && canvas.parentElement) {
1789
- const {
1790
- width,
1791
- height,
1792
- top,
1793
- left
1794
- } = canvas.parentElement.getBoundingClientRect();
1795
- return {
1796
- width,
1797
- height,
1798
- top,
1799
- left
1800
- };
1801
- } else if (!size && typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
1802
- return {
1803
- width: canvas.width,
1804
- height: canvas.height,
1805
- top: 0,
1806
- left: 0
1807
- };
1808
- }
1809
- return {
1810
- width: 0,
1811
- height: 0,
1812
- top: 0,
1813
- left: 0,
1814
- ...size
1815
- };
1816
- }
1817
- function createRoot(canvas) {
1818
- // Check against mistaken use of createRoot
1819
- const prevRoot = _roots.get(canvas);
1820
- const prevFiber = prevRoot == null ? void 0 : prevRoot.fiber;
1821
- const prevStore = prevRoot == null ? void 0 : prevRoot.store;
1822
- if (prevRoot) console.warn('R3F.createRoot should only be called once!');
1823
-
1824
- // Report when an error was detected in a previous render
1825
- // https://github.com/pmndrs/react-three-fiber/pull/2261
1826
- const logRecoverableError = typeof reportError === 'function' ?
1827
- // In modern browsers, reportError will dispatch an error event,
1828
- // emulating an uncaught JavaScript error.
1829
- reportError :
1830
- // In older browsers and test environments, fallback to console.error.
1831
- console.error;
1832
-
1833
- // Create store
1834
- const store = prevStore || createStore(invalidate, advance);
1835
- // Create renderer
1836
- const fiber = prevFiber || reconciler.createContainer(store,
1837
- // container
1838
- ConcurrentRoot,
1839
- // tag
1840
- null,
1841
- // hydration callbacks
1842
- false,
1843
- // isStrictMode
1844
- null,
1845
- // concurrentUpdatesByDefaultOverride
1846
- '',
1847
- // identifierPrefix
1848
- logRecoverableError,
1849
- // onUncaughtError
1850
- logRecoverableError,
1851
- // onCaughtError
1852
- logRecoverableError,
1853
- // onRecoverableError
1854
- null // transitionCallbacks
1855
- );
1856
- // Map it
1857
- if (!prevRoot) _roots.set(canvas, {
1858
- fiber,
1859
- store
1860
- });
1861
-
1862
- // Locals
1863
- let onCreated;
1864
- let lastCamera;
1865
- let configured = false;
1866
- let pending = null;
1867
- return {
1868
- async configure(props = {}) {
1869
- let resolve;
1870
- pending = new Promise(_resolve => resolve = _resolve);
1871
- let {
1872
- gl: glConfig,
1873
- size: propsSize,
1874
- scene: sceneOptions,
1875
- events,
1876
- onCreated: onCreatedCallback,
1877
- shadows = false,
1878
- linear = false,
1879
- flat = false,
1880
- legacy = false,
1881
- orthographic = false,
1882
- frameloop = 'always',
1883
- dpr = [1, 2],
1884
- performance,
1885
- raycaster: raycastOptions,
1886
- camera: cameraOptions,
1887
- onPointerMissed
1888
- } = props;
1889
- let state = store.getState();
1890
-
1891
- // Set up renderer (one time only!)
1892
- let gl = state.gl;
1893
- if (!state.gl) {
1894
- const defaultProps = {
1895
- canvas: canvas,
1896
- powerPreference: 'high-performance',
1897
- antialias: true,
1898
- alpha: true
1899
- };
1900
- const customRenderer = typeof glConfig === 'function' ? await glConfig(defaultProps) : glConfig;
1901
- if (isRenderer(customRenderer)) {
1902
- gl = customRenderer;
1903
- } else {
1904
- gl = new THREE.WebGLRenderer({
1905
- ...defaultProps,
1906
- ...glConfig
1907
- });
1908
- }
1909
- state.set({
1910
- gl
1911
- });
1912
- }
1913
-
1914
- // Set up raycaster (one time only!)
1915
- let raycaster = state.raycaster;
1916
- if (!raycaster) state.set({
1917
- raycaster: raycaster = new THREE.Raycaster()
1918
- });
1919
-
1920
- // Set raycaster options
1921
- const {
1922
- params,
1923
- ...options
1924
- } = raycastOptions || {};
1925
- if (!is.equ(options, raycaster, shallowLoose)) applyProps(raycaster, {
1926
- ...options
1927
- });
1928
- if (!is.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, {
1929
- params: {
1930
- ...raycaster.params,
1931
- ...params
1932
- }
1933
- });
1934
-
1935
- // Create default camera, don't overwrite any user-set state
1936
- if (!state.camera || state.camera === lastCamera && !is.equ(lastCamera, cameraOptions, shallowLoose)) {
1937
- lastCamera = cameraOptions;
1938
- const isCamera = cameraOptions == null ? void 0 : cameraOptions.isCamera;
1939
- const camera = isCamera ? cameraOptions : orthographic ? new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new THREE.PerspectiveCamera(75, 0, 0.1, 1000);
1940
- if (!isCamera) {
1941
- camera.position.z = 5;
1942
- if (cameraOptions) {
1943
- applyProps(camera, cameraOptions);
1944
- // Preserve user-defined frustum if possible
1945
- // https://github.com/pmndrs/react-three-fiber/issues/3160
1946
- if (!camera.manual) {
1947
- if ('aspect' in cameraOptions || 'left' in cameraOptions || 'right' in cameraOptions || 'bottom' in cameraOptions || 'top' in cameraOptions) {
1948
- camera.manual = true;
1949
- camera.updateProjectionMatrix();
1950
- }
1951
- }
1952
- }
1953
- // Always look at center by default
1954
- if (!state.camera && !(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0);
1955
- }
1956
- state.set({
1957
- camera
1958
- });
1959
-
1960
- // Configure raycaster
1961
- // https://github.com/pmndrs/react-xr/issues/300
1962
- raycaster.camera = camera;
1963
- }
1964
-
1965
- // Set up scene (one time only!)
1966
- if (!state.scene) {
1967
- let scene;
1968
- if (sceneOptions != null && sceneOptions.isScene) {
1969
- scene = sceneOptions;
1970
- prepare(scene, store, '', {});
1971
- } else {
1972
- scene = new THREE.Scene();
1973
- prepare(scene, store, '', {});
1974
- if (sceneOptions) applyProps(scene, sceneOptions);
1975
- }
1976
- state.set({
1977
- scene
1978
- });
1979
- }
1980
-
1981
- // Store events internally
1982
- if (events && !state.events.handlers) state.set({
1983
- events: events(store)
1984
- });
1985
- // Check size, allow it to take on container bounds initially
1986
- const size = computeInitialSize(canvas, propsSize);
1987
- if (!is.equ(size, state.size, shallowLoose)) {
1988
- state.setSize(size.width, size.height, size.top, size.left);
1989
- }
1990
- // Check pixelratio
1991
- if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr);
1992
- // Check frameloop
1993
- if (state.frameloop !== frameloop) state.setFrameloop(frameloop);
1994
- // Check pointer missed
1995
- if (!state.onPointerMissed) state.set({
1996
- onPointerMissed
1997
- });
1998
- // Check performance
1999
- if (performance && !is.equ(performance, state.performance, shallowLoose)) state.set(state => ({
2000
- performance: {
2001
- ...state.performance,
2002
- ...performance
2003
- }
2004
- }));
2005
-
2006
- // Set up XR (one time only!)
2007
- if (!state.xr) {
2008
- var _gl$xr;
2009
- // Handle frame behavior in WebXR
2010
- const handleXRFrame = (timestamp, frame) => {
2011
- const state = store.getState();
2012
- if (state.frameloop === 'never') return;
2013
- advance(timestamp, true, state, frame);
2014
- };
2015
-
2016
- // Toggle render switching on session
2017
- const handleSessionChange = () => {
2018
- const state = store.getState();
2019
- state.gl.xr.enabled = state.gl.xr.isPresenting;
2020
- state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null);
2021
- if (!state.gl.xr.isPresenting) invalidate(state);
2022
- };
2023
-
2024
- // WebXR session manager
2025
- const xr = {
2026
- connect() {
2027
- const gl = store.getState().gl;
2028
- gl.xr.addEventListener('sessionstart', handleSessionChange);
2029
- gl.xr.addEventListener('sessionend', handleSessionChange);
2030
- },
2031
- disconnect() {
2032
- const gl = store.getState().gl;
2033
- gl.xr.removeEventListener('sessionstart', handleSessionChange);
2034
- gl.xr.removeEventListener('sessionend', handleSessionChange);
2035
- }
2036
- };
2037
-
2038
- // Subscribe to WebXR session events
2039
- if (typeof ((_gl$xr = gl.xr) == null ? void 0 : _gl$xr.addEventListener) === 'function') xr.connect();
2040
- state.set({
2041
- xr
2042
- });
2043
- }
2044
-
2045
- // Set shadowmap
2046
- if (gl.shadowMap) {
2047
- const oldEnabled = gl.shadowMap.enabled;
2048
- const oldType = gl.shadowMap.type;
2049
- gl.shadowMap.enabled = !!shadows;
2050
- if (is.boo(shadows)) {
2051
- gl.shadowMap.type = THREE.PCFSoftShadowMap;
2052
- } else if (is.str(shadows)) {
2053
- var _types$shadows;
2054
- const types = {
2055
- basic: THREE.BasicShadowMap,
2056
- percentage: THREE.PCFShadowMap,
2057
- soft: THREE.PCFSoftShadowMap,
2058
- variance: THREE.VSMShadowMap
2059
- };
2060
- gl.shadowMap.type = (_types$shadows = types[shadows]) != null ? _types$shadows : THREE.PCFSoftShadowMap;
2061
- } else if (is.obj(shadows)) {
2062
- Object.assign(gl.shadowMap, shadows);
2063
- }
2064
- if (oldEnabled !== gl.shadowMap.enabled || oldType !== gl.shadowMap.type) gl.shadowMap.needsUpdate = true;
2065
- }
2066
- THREE.ColorManagement.enabled = !legacy;
2067
-
2068
- // Set color space and tonemapping preferences
2069
- if (!configured) {
2070
- gl.outputColorSpace = linear ? THREE.LinearSRGBColorSpace : THREE.SRGBColorSpace;
2071
- gl.toneMapping = flat ? THREE.NoToneMapping : THREE.ACESFilmicToneMapping;
2072
- }
2073
-
2074
- // Update color management state
2075
- if (state.legacy !== legacy) state.set(() => ({
2076
- legacy
2077
- }));
2078
- if (state.linear !== linear) state.set(() => ({
2079
- linear
2080
- }));
2081
- if (state.flat !== flat) state.set(() => ({
2082
- flat
2083
- }));
2084
-
2085
- // Set gl props
2086
- if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig);
2087
-
2088
- // Set locals
2089
- onCreated = onCreatedCallback;
2090
- configured = true;
2091
- resolve();
2092
- return this;
2093
- },
2094
- render(children) {
2095
- // The root has to be configured before it can be rendered
2096
- if (!configured && !pending) this.configure();
2097
- pending.then(() => {
2098
- reconciler.updateContainer( /*#__PURE__*/jsx(Provider, {
2099
- store: store,
2100
- children: children,
2101
- onCreated: onCreated,
2102
- rootElement: canvas
2103
- }), fiber, null, () => undefined);
2104
- });
2105
- return store;
2106
- },
2107
- unmount() {
2108
- unmountComponentAtNode(canvas);
2109
- }
2110
- };
2111
- }
2112
- function Provider({
2113
- store,
2114
- children,
2115
- onCreated,
2116
- rootElement
2117
- }) {
2118
- useIsomorphicLayoutEffect(() => {
2119
- const state = store.getState();
2120
- // Flag the canvas active, rendering will now begin
2121
- state.set(state => ({
2122
- internal: {
2123
- ...state.internal,
2124
- active: true
2125
- }
2126
- }));
2127
- // Notify that init is completed, the scene graph exists, but nothing has yet rendered
2128
- if (onCreated) onCreated(state);
2129
- // Connect events to the targets parent, this is done to ensure events are registered on
2130
- // a shared target, and not on the canvas itself
2131
- if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement);
2132
- // eslint-disable-next-line react-hooks/exhaustive-deps
2133
- }, []);
2134
- return /*#__PURE__*/jsx(context.Provider, {
2135
- value: store,
2136
- children: children
2137
- });
2138
- }
2139
- function unmountComponentAtNode(canvas, callback) {
2140
- const root = _roots.get(canvas);
2141
- const fiber = root == null ? void 0 : root.fiber;
2142
- if (fiber) {
2143
- const state = root == null ? void 0 : root.store.getState();
2144
- if (state) state.internal.active = false;
2145
- reconciler.updateContainer(null, fiber, null, () => {
2146
- if (state) {
2147
- setTimeout(() => {
2148
- try {
2149
- var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3;
2150
- state.events.disconnect == null ? void 0 : state.events.disconnect();
2151
- (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose();
2152
- (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss();
2153
- if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect();
2154
- dispose(state.scene);
2155
- _roots.delete(canvas);
2156
- if (callback) callback(canvas);
2157
- } catch (e) {
2158
- /* ... */
2159
- }
2160
- }, 500);
2161
- }
2162
- });
2163
- }
2164
- }
2165
- function createPortal(children, container, state) {
2166
- return /*#__PURE__*/jsx(Portal, {
2167
- children: children,
2168
- container: container,
2169
- state: state
2170
- });
2171
- }
2172
- function Portal({
2173
- state = {},
2174
- children,
2175
- container
2176
- }) {
2177
- /** This has to be a component because it would not be able to call useThree/useStore otherwise since
2178
- * if this is our environment, then we are not in r3f's renderer but in react-dom, it would trigger
2179
- * the "R3F hooks can only be used within the Canvas component!" warning:
2180
- * <Canvas>
2181
- * {createPortal(...)} */
2182
- const {
2183
- events,
2184
- size,
2185
- ...rest
2186
- } = state;
2187
- const previousRoot = useStore();
2188
- const [raycaster] = React.useState(() => new THREE.Raycaster());
2189
- const [pointer] = React.useState(() => new THREE.Vector2());
2190
- const inject = useMutableCallback((rootState, injectState) => {
2191
- let viewport = undefined;
2192
- if (injectState.camera && size) {
2193
- const camera = injectState.camera;
2194
- // Calculate the override viewport, if present
2195
- viewport = rootState.viewport.getCurrentViewport(camera, new THREE.Vector3(), size);
2196
- // Update the portal camera, if it differs from the previous layer
2197
- if (camera !== rootState.camera) updateCamera(camera, size);
2198
- }
2199
- return {
2200
- // The intersect consists of the previous root state
2201
- ...rootState,
2202
- ...injectState,
2203
- // Portals have their own scene, which forms the root, a raycaster and a pointer
2204
- scene: container,
2205
- raycaster,
2206
- pointer,
2207
- mouse: pointer,
2208
- // Their previous root is the layer before it
2209
- previousRoot,
2210
- // Events, size and viewport can be overridden by the inject layer
2211
- events: {
2212
- ...rootState.events,
2213
- ...injectState.events,
2214
- ...events
2215
- },
2216
- size: {
2217
- ...rootState.size,
2218
- ...size
2219
- },
2220
- viewport: {
2221
- ...rootState.viewport,
2222
- ...viewport
2223
- },
2224
- // Layers are allowed to override events
2225
- setEvents: events => injectState.set(state => ({
2226
- ...state,
2227
- events: {
2228
- ...state.events,
2229
- ...events
2230
- }
2231
- }))
2232
- };
2233
- });
2234
- const usePortalStore = React.useMemo(() => {
2235
- // Create a mirrored store, based on the previous root with a few overrides ...
2236
- const store = createWithEqualityFn((set, get) => ({
2237
- ...rest,
2238
- set,
2239
- get
2240
- }));
2241
-
2242
- // Subscribe to previous root-state and copy changes over to the mirrored portal-state
2243
- const onMutate = prev => store.setState(state => inject.current(prev, state));
2244
- onMutate(previousRoot.getState());
2245
- previousRoot.subscribe(onMutate);
2246
- return store;
2247
- // eslint-disable-next-line react-hooks/exhaustive-deps
2248
- }, [previousRoot, container]);
2249
- return (
2250
- /*#__PURE__*/
2251
- // @ts-ignore, reconciler types are not maintained
2252
- jsx(Fragment, {
2253
- children: reconciler.createPortal( /*#__PURE__*/jsx(context.Provider, {
2254
- value: usePortalStore,
2255
- children: children
2256
- }), usePortalStore, null)
2257
- })
2258
- );
2259
- }
2260
-
2261
- /**
2262
- * Force React to flush any updates inside the provided callback synchronously and immediately.
2263
- * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
2264
- * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
2265
- * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
2266
- */
2267
- function flushSync(fn) {
2268
- // @ts-ignore - reconciler types are not maintained
2269
- return reconciler.flushSyncFromReconciler(fn);
2270
- }
2271
-
2272
- function createSubs(callback, subs) {
2273
- const sub = {
2274
- callback
2275
- };
2276
- subs.add(sub);
2277
- return () => void subs.delete(sub);
2278
- }
2279
- const globalEffects = new Set();
2280
- const globalAfterEffects = new Set();
2281
- const globalTailEffects = new Set();
2282
-
2283
- /**
2284
- * Adds a global render callback which is called each frame.
2285
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
2286
- */
2287
- const addEffect = callback => createSubs(callback, globalEffects);
2288
-
2289
- /**
2290
- * Adds a global after-render callback which is called each frame.
2291
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
2292
- */
2293
- const addAfterEffect = callback => createSubs(callback, globalAfterEffects);
2294
-
2295
- /**
2296
- * Adds a global callback which is called when rendering stops.
2297
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
2298
- */
2299
- const addTail = callback => createSubs(callback, globalTailEffects);
2300
- function run(effects, timestamp) {
2301
- if (!effects.size) return;
2302
- for (const {
2303
- callback
2304
- } of effects.values()) {
2305
- callback(timestamp);
2306
- }
2307
- }
2308
- function flushGlobalEffects(type, timestamp) {
2309
- switch (type) {
2310
- case 'before':
2311
- return run(globalEffects, timestamp);
2312
- case 'after':
2313
- return run(globalAfterEffects, timestamp);
2314
- case 'tail':
2315
- return run(globalTailEffects, timestamp);
2316
- }
2317
- }
2318
- let subscribers;
2319
- let subscription;
2320
- function update(timestamp, state, frame) {
2321
- // Run local effects
2322
- let delta = state.clock.getDelta();
2323
-
2324
- // In frameloop='never' mode, clock times are updated using the provided timestamp
2325
- if (state.frameloop === 'never' && typeof timestamp === 'number') {
2326
- delta = timestamp - state.clock.elapsedTime;
2327
- state.clock.oldTime = state.clock.elapsedTime;
2328
- state.clock.elapsedTime = timestamp;
2329
- }
2330
-
2331
- // Call subscribers (useFrame)
2332
- subscribers = state.internal.subscribers;
2333
- for (let i = 0; i < subscribers.length; i++) {
2334
- subscription = subscribers[i];
2335
- subscription.ref.current(subscription.store.getState(), delta, frame);
2336
- }
2337
-
2338
- // Render content
2339
- if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera);
2340
-
2341
- // Decrease frame count
2342
- state.internal.frames = Math.max(0, state.internal.frames - 1);
2343
- return state.frameloop === 'always' ? 1 : state.internal.frames;
2344
- }
2345
- let running = false;
2346
- let useFrameInProgress = false;
2347
- let repeat;
2348
- let frame;
2349
- let state;
2350
- function loop(timestamp) {
2351
- frame = requestAnimationFrame(loop);
2352
- running = true;
2353
- repeat = 0;
2354
-
2355
- // Run effects
2356
- flushGlobalEffects('before', timestamp);
2357
-
2358
- // Render all roots
2359
- useFrameInProgress = true;
2360
- for (const root of _roots.values()) {
2361
- var _state$gl$xr;
2362
- state = root.store.getState();
2363
-
2364
- // If the frameloop is invalidated, do not run another frame
2365
- if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) {
2366
- repeat += update(timestamp, state);
2367
- }
2368
- }
2369
- useFrameInProgress = false;
2370
-
2371
- // Run after-effects
2372
- flushGlobalEffects('after', timestamp);
2373
-
2374
- // Stop the loop if nothing invalidates it
2375
- if (repeat === 0) {
2376
- // Tail call effects, they are called when rendering stops
2377
- flushGlobalEffects('tail', timestamp);
2378
-
2379
- // Flag end of operation
2380
- running = false;
2381
- return cancelAnimationFrame(frame);
2382
- }
2383
- }
2384
-
2385
- /**
2386
- * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state.
2387
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
2388
- */
2389
- function invalidate(state, frames = 1) {
2390
- var _state$gl$xr2;
2391
- if (!state) return _roots.forEach(root => invalidate(root.store.getState(), frames));
2392
- if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return;
2393
- if (frames > 1) {
2394
- // legacy support for people using frames parameters
2395
- // Increase frames, do not go higher than 60
2396
- state.internal.frames = Math.min(60, state.internal.frames + frames);
2397
- } else {
2398
- if (useFrameInProgress) {
2399
- //called from within a useFrame, it means the user wants an additional frame
2400
- state.internal.frames = 2;
2401
- } else {
2402
- //the user need a new frame, no need to increment further than 1
2403
- state.internal.frames = 1;
2404
- }
2405
- }
2406
-
2407
- // If the render-loop isn't active, start it
2408
- if (!running) {
2409
- running = true;
2410
- requestAnimationFrame(loop);
2411
- }
2412
- }
2413
-
2414
- /**
2415
- * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`.
2416
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2417
- */
2418
- function advance(timestamp, runGlobalEffects = true, state, frame) {
2419
- if (runGlobalEffects) flushGlobalEffects('before', timestamp);
2420
- if (!state) for (const root of _roots.values()) update(timestamp, root.store.getState());else update(timestamp, state, frame);
2421
- if (runGlobalEffects) flushGlobalEffects('after', timestamp);
2422
- }
2423
-
2424
- const DOM_EVENTS = {
2425
- onClick: ['click', false],
2426
- onContextMenu: ['contextmenu', false],
2427
- onDoubleClick: ['dblclick', false],
2428
- onWheel: ['wheel', true],
2429
- onPointerDown: ['pointerdown', true],
2430
- onPointerUp: ['pointerup', true],
2431
- onPointerLeave: ['pointerleave', true],
2432
- onPointerMove: ['pointermove', true],
2433
- onPointerCancel: ['pointercancel', true],
2434
- onLostPointerCapture: ['lostpointercapture', true]
2435
- };
2436
-
2437
- /** Default R3F event manager for web */
2438
- function createPointerEvents(store) {
2439
- const {
2440
- handlePointer
2441
- } = createEvents(store);
2442
- return {
2443
- priority: 1,
2444
- enabled: true,
2445
- compute(event, state, previous) {
2446
- // https://github.com/pmndrs/react-three-fiber/pull/782
2447
- // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides
2448
- state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
2449
- state.raycaster.setFromCamera(state.pointer, state.camera);
2450
- },
2451
- connected: undefined,
2452
- handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({
2453
- ...acc,
2454
- [key]: handlePointer(key)
2455
- }), {}),
2456
- update: () => {
2457
- var _internal$lastEvent;
2458
- const {
2459
- events,
2460
- internal
2461
- } = store.getState();
2462
- if ((_internal$lastEvent = internal.lastEvent) != null && _internal$lastEvent.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
2463
- },
2464
- connect: target => {
2465
- const {
2466
- set,
2467
- events
2468
- } = store.getState();
2469
- events.disconnect == null ? void 0 : events.disconnect();
2470
- set(state => ({
2471
- events: {
2472
- ...state.events,
2473
- connected: target
2474
- }
2475
- }));
2476
- if (events.handlers) {
2477
- for (const name in events.handlers) {
2478
- const event = events.handlers[name];
2479
- const [eventName, passive] = DOM_EVENTS[name];
2480
- target.addEventListener(eventName, event, {
2481
- passive
2482
- });
2483
- }
2484
- }
2485
- },
2486
- disconnect: () => {
2487
- const {
2488
- set,
2489
- events
2490
- } = store.getState();
2491
- if (events.connected) {
2492
- if (events.handlers) {
2493
- for (const name in events.handlers) {
2494
- const event = events.handlers[name];
2495
- const [eventName] = DOM_EVENTS[name];
2496
- events.connected.removeEventListener(eventName, event);
2497
- }
2498
- }
2499
- set(state => ({
2500
- events: {
2501
- ...state.events,
2502
- connected: undefined
2503
- }
2504
- }));
2505
- }
2506
- }
2507
- };
2508
- }
2509
-
2510
- export { useStore as A, Block as B, useThree as C, useFrame as D, ErrorBoundary as E, useGraph as F, useLoader as G, _roots as _, useMutableCallback as a, useIsomorphicLayoutEffect as b, createRoot as c, unmountComponentAtNode as d, extend as e, createPointerEvents as f, createEvents as g, flushGlobalEffects as h, isRef as i, addEffect as j, addAfterEffect as k, addTail as l, invalidate as m, advance as n, createPortal as o, flushSync as p, context as q, reconciler as r, applyProps as s, threeTypes as t, useBridge as u, getRootState as v, dispose as w, act as x, buildGraph as y, useInstanceHandle as z };