@react-three/fiber 9.0.0-alpha.1 → 9.0.0-alpha.3

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