@react-three/fiber 8.0.0-alpha-09 → 8.0.0-beta-03

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 (32) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/declarations/src/core/events.d.ts +63 -59
  3. package/dist/declarations/src/core/hooks.d.ts +21 -29
  4. package/dist/declarations/src/core/loop.d.ts +12 -12
  5. package/dist/declarations/src/core/renderer.d.ts +50 -51
  6. package/dist/declarations/src/core/store.d.ts +117 -106
  7. package/dist/declarations/src/core/utils.d.ts +50 -27
  8. package/dist/declarations/src/index.d.ts +8 -7
  9. package/dist/declarations/src/native/Canvas.d.ts +16 -0
  10. package/dist/declarations/src/native/events.d.ts +6 -0
  11. package/dist/declarations/src/native/hooks.d.ts +9 -0
  12. package/dist/declarations/src/native/index.d.ts +36 -0
  13. package/dist/declarations/src/native.d.ts +8 -0
  14. package/dist/declarations/src/three-types.d.ts +309 -319
  15. package/dist/declarations/src/web/Canvas.d.ts +13 -13
  16. package/dist/declarations/src/web/events.d.ts +5 -5
  17. package/dist/declarations/src/web/index.d.ts +33 -30
  18. package/dist/hooks-15c12e3e.esm.js +1539 -0
  19. package/dist/hooks-6526f63c.cjs.dev.js +1589 -0
  20. package/dist/hooks-7b7e01e6.cjs.prod.js +1589 -0
  21. package/dist/react-three-fiber.cjs.dev.js +261 -1596
  22. package/dist/react-three-fiber.cjs.prod.js +261 -1596
  23. package/dist/react-three-fiber.esm.js +222 -1554
  24. package/native/dist/react-three-fiber-native.cjs.d.ts +1 -0
  25. package/native/dist/react-three-fiber-native.cjs.dev.js +589 -0
  26. package/native/dist/react-three-fiber-native.cjs.js +7 -0
  27. package/native/dist/react-three-fiber-native.cjs.prod.js +589 -0
  28. package/native/dist/react-three-fiber-native.esm.js +537 -0
  29. package/native/package.json +5 -0
  30. package/package.json +18 -8
  31. package/readme.md +10 -10
  32. package/__mocks__/react-use-measure/index.ts +0 -22
@@ -0,0 +1,1539 @@
1
+ import Reconciler from 'react-reconciler';
2
+ import { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
3
+ import { DefaultEventPriority } from 'react-reconciler/constants';
4
+ import * as THREE from 'three';
5
+ import * as React from 'react';
6
+ import { suspend, preload, clear } from 'suspend-react';
7
+ import create from 'zustand';
8
+
9
+ var threeTypes = /*#__PURE__*/Object.freeze({
10
+ __proto__: null
11
+ });
12
+
13
+ const DEFAULT = '__default';
14
+ const isDiffSet = def => def && !!def.memoized && !!def.changes;
15
+ function calculateDpr(dpr) {
16
+ return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr;
17
+ }
18
+ /**
19
+ * Picks or omits keys from an object
20
+ * `omit` will filter out keys, and otherwise cherry-pick them.
21
+ */
22
+
23
+ function filterKeys(obj, omit, ...keys) {
24
+ const keysToSelect = new Set(keys);
25
+ return Object.entries(obj).reduce((acc, [key, value]) => {
26
+ const shouldInclude = !omit;
27
+
28
+ if (keysToSelect.has(key) === shouldInclude) {
29
+ acc[key] = value;
30
+ }
31
+
32
+ return acc;
33
+ }, {});
34
+ }
35
+ /**
36
+ * Clones an object and cherry-picks keys.
37
+ */
38
+
39
+ const pick = (obj, keys) => filterKeys(obj, false, ...keys);
40
+ /**
41
+ * Clones an object and prunes or omits keys.
42
+ */
43
+
44
+ const omit = (obj, keys) => filterKeys(obj, true, ...keys); // A collection of compare functions
45
+
46
+ const is = {
47
+ obj: a => a === Object(a) && !is.arr(a) && typeof a !== 'function',
48
+ fun: a => typeof a === 'function',
49
+ str: a => typeof a === 'string',
50
+ num: a => typeof a === 'number',
51
+ und: a => a === void 0,
52
+ arr: a => Array.isArray(a),
53
+
54
+ equ(a, b) {
55
+ // Wrong type or one of the two undefined, doesn't match
56
+ if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b
57
+
58
+ if (is.str(a) || is.num(a) || is.obj(a)) return a === b; // Array, shallow compare first to see if it's a match
59
+
60
+ if (is.arr(a) && a == b) return true; // Last resort, go through keys
61
+
62
+ let i;
63
+
64
+ for (i in a) if (!(i in b)) return false;
65
+
66
+ for (i in b) if (a[i] !== b[i]) return false;
67
+
68
+ return is.und(i) ? a === b : true;
69
+ }
70
+
71
+ }; // Collects nodes and materials from a THREE.Object3D
72
+
73
+ function buildGraph(object) {
74
+ const data = {
75
+ nodes: {},
76
+ materials: {}
77
+ };
78
+
79
+ if (object) {
80
+ object.traverse(obj => {
81
+ if (obj.name) data.nodes[obj.name] = obj;
82
+ if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material;
83
+ });
84
+ }
85
+
86
+ return data;
87
+ } // Disposes an object and all its properties
88
+
89
+ function dispose(obj) {
90
+ if (obj.dispose && obj.type !== 'Scene') obj.dispose();
91
+
92
+ for (const p in obj) {
93
+ p.dispose == null ? void 0 : p.dispose();
94
+ delete obj[p];
95
+ }
96
+ } // Each object in the scene carries a small LocalState descriptor
97
+
98
+ function prepare(object, state) {
99
+ const instance = object;
100
+
101
+ if (state != null && state.primitive || !instance.__r3f) {
102
+ instance.__r3f = {
103
+ root: null,
104
+ memoizedProps: {},
105
+ eventCount: 0,
106
+ handlers: {},
107
+ objects: [],
108
+ parent: null,
109
+ ...state
110
+ };
111
+ }
112
+
113
+ return object;
114
+ }
115
+
116
+ function resolve(instance, key) {
117
+ let target = instance;
118
+
119
+ if (key.includes('-')) {
120
+ const entries = key.split('-');
121
+ const last = entries.pop();
122
+ target = entries.reduce((acc, key) => acc[key], instance);
123
+ return {
124
+ target,
125
+ key: last
126
+ };
127
+ } else return {
128
+ target,
129
+ key
130
+ };
131
+ }
132
+
133
+ function attach(parent, child, type) {
134
+ if (is.str(type)) {
135
+ const {
136
+ target,
137
+ key
138
+ } = resolve(parent, type);
139
+ parent.__r3f.previousAttach = target[key];
140
+ target[key] = child;
141
+ } else if (is.arr(type)) {
142
+ const [attach] = type;
143
+ if (is.str(attach)) parent[attach](child);else if (is.fun(attach)) attach(parent, child);
144
+ }
145
+ }
146
+ function detach(parent, child, type) {
147
+ if (is.str(type)) {
148
+ const {
149
+ target,
150
+ key
151
+ } = resolve(parent, type);
152
+ target[key] = parent.__r3f.previousAttach;
153
+ } else if (is.arr(type)) {
154
+ const [, detach] = type;
155
+ if (is.str(detach)) parent[detach](child);else if (is.fun(detach)) detach(parent, child);
156
+ }
157
+ } // Shallow check arrays, but check objects atomically
158
+
159
+ function checkShallow(a, b) {
160
+ if (is.arr(a) && is.equ(a, b)) return true;
161
+ if (a === b) return true;
162
+ return false;
163
+ } // This function prepares a set of changes to be applied to the instance
164
+
165
+
166
+ function diffProps(instance, {
167
+ children: cN,
168
+ key: kN,
169
+ ref: rN,
170
+ ...props
171
+ }, {
172
+ children: cP,
173
+ key: kP,
174
+ ref: rP,
175
+ ...previous
176
+ } = {}, remove = false) {
177
+ var _instance$__r3f;
178
+
179
+ const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {};
180
+ const entries = Object.entries(props);
181
+ const changes = []; // Catch removed props, prepend them so they can be reset or removed
182
+
183
+ if (remove) {
184
+ const previousKeys = Object.keys(previous);
185
+
186
+ for (let i = 0; i < previousKeys.length; i++) {
187
+ if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']);
188
+ }
189
+ }
190
+
191
+ entries.forEach(([key, value]) => {
192
+ var _instance$__r3f2;
193
+
194
+ // Bail out on primitive object
195
+ if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out
196
+
197
+ if (checkShallow(value, previous[key])) return; // Collect handlers and bail out
198
+
199
+ if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props
200
+
201
+ let entries = [];
202
+ if (key.includes('-')) entries = key.split('-');
203
+ changes.push([key, value, false, entries]);
204
+ });
205
+ const memoized = { ...props
206
+ };
207
+ if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args;
208
+ if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach;
209
+ return {
210
+ memoized,
211
+ changes
212
+ };
213
+ } // This function applies a set of changes to the instance
214
+
215
+ function applyProps(instance, data) {
216
+ var _instance$__r3f3, _root$getState;
217
+
218
+ // Filter equals, events and reserved props
219
+ const localState = (_instance$__r3f3 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f3 : {};
220
+ const root = localState.root;
221
+ const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {};
222
+ const {
223
+ memoized,
224
+ changes
225
+ } = isDiffSet(data) ? data : diffProps(instance, data);
226
+ const prevHandlers = localState.eventCount; // Prepare memoized props
227
+
228
+ if (instance.__r3f) instance.__r3f.memoizedProps = memoized;
229
+ changes.forEach(([key, value, isEvent, keys]) => {
230
+ let currentInstance = instance;
231
+ let targetProp = currentInstance[key]; // Revolve dashed props
232
+
233
+ if (keys.length) {
234
+ targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root
235
+
236
+ if (!(targetProp && targetProp.set)) {
237
+ const [name, ...reverseEntries] = keys.reverse();
238
+ currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance);
239
+ key = name;
240
+ }
241
+ } // https://github.com/mrdoob/three.js/issues/21209
242
+ // HMR/fast-refresh relies on the ability to cancel out props, but threejs
243
+ // has no means to do this. Hence we curate a small collection of value-classes
244
+ // with their respective constructor/set arguments
245
+ // For removed props, try to set default values, if possible
246
+
247
+
248
+ if (value === DEFAULT + 'remove') {
249
+ if (targetProp && targetProp.constructor) {
250
+ // use the prop constructor to find the default it should be
251
+ value = new targetProp.constructor(memoized.args);
252
+ } else if (currentInstance.constructor) {
253
+ // create a blank slate of the instance and copy the particular parameter.
254
+ // @ts-ignore
255
+ const defaultClassCall = new currentInstance.constructor(currentInstance.__r3f.memoizedProps.args);
256
+ value = defaultClassCall[targetProp]; // destory the instance
257
+
258
+ if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0
259
+ } else {
260
+ value = 0;
261
+ }
262
+ } // Deal with pointer events ...
263
+
264
+
265
+ if (isEvent) {
266
+ if (value) localState.handlers[key] = value;else delete localState.handlers[key];
267
+ localState.eventCount = Object.keys(localState.handlers).length;
268
+ } // Special treatment for objects with support for set/copy, and layers
269
+ else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof THREE.Layers)) {
270
+ // If value is an array
271
+ if (Array.isArray(value)) {
272
+ if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value);
273
+ } // Test again target.copy(class) next ...
274
+ else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) {
275
+ targetProp.copy(value);
276
+ } // If nothing else fits, just set the single value, ignore undefined
277
+ // https://github.com/pmndrs/react-three-fiber/issues/274
278
+ else if (value !== undefined) {
279
+ const isColor = targetProp instanceof THREE.Color; // Allow setting array scalars
280
+
281
+ if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property
282
+ else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers) targetProp.mask = value.mask; // Otherwise just set ...
283
+ else targetProp.set(value); // Auto-convert sRGB colors, for now ...
284
+ // https://github.com/pmndrs/react-three-fiber/issues/344
285
+
286
+ if (!rootState.linear && isColor) targetProp.convertSRGBToLinear();
287
+ } // Else, just overwrite the value
288
+
289
+ } else {
290
+ currentInstance[key] = value; // Auto-convert sRGB textures, for now ...
291
+ // https://github.com/pmndrs/react-three-fiber/issues/344
292
+
293
+ if (!rootState.linear && currentInstance[key] instanceof THREE.Texture) {
294
+ currentInstance[key].encoding = THREE.sRGBEncoding;
295
+ }
296
+ }
297
+
298
+ invalidateInstance(instance);
299
+ return instance;
300
+ });
301
+
302
+ if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) {
303
+ // Pre-emptively remove the instance from the interaction manager
304
+ const index = rootState.internal.interaction.indexOf(instance);
305
+ if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers
306
+
307
+ if (localState.eventCount) rootState.internal.interaction.push(instance);
308
+ } // Call the update lifecycle when it is being updated, but only when it is part of the scene
309
+
310
+
311
+ if (changes.length && instance.parent) updateInstance(instance);
312
+ }
313
+ function invalidateInstance(instance) {
314
+ var _instance$__r3f4, _instance$__r3f4$root;
315
+
316
+ 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();
317
+ if (state && state.internal.frames === 0) state.invalidate();
318
+ }
319
+ function updateInstance(instance) {
320
+ instance.onUpdate == null ? void 0 : instance.onUpdate(instance);
321
+ }
322
+
323
+ function makeId(event) {
324
+ return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
325
+ }
326
+ /**
327
+ * Release pointer captures.
328
+ * This is called by releasePointerCapture in the API, and when an object is removed.
329
+ */
330
+
331
+
332
+ function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
333
+ const captureData = captures.get(obj);
334
+
335
+ if (captureData) {
336
+ captures.delete(obj); // If this was the last capturing object for this pointer
337
+
338
+ if (captures.size === 0) {
339
+ capturedMap.delete(pointerId);
340
+ captureData.target.releasePointerCapture(pointerId);
341
+ }
342
+ }
343
+ }
344
+
345
+ function removeInteractivity(store, object) {
346
+ const {
347
+ internal
348
+ } = store.getState(); // Removes every trace of an object from the data store
349
+
350
+ internal.interaction = internal.interaction.filter(o => o !== object);
351
+ internal.initialHits = internal.initialHits.filter(o => o !== object);
352
+ internal.hovered.forEach((value, key) => {
353
+ if (value.eventObject === object || value.object === object) {
354
+ internal.hovered.delete(key);
355
+ }
356
+ });
357
+ internal.capturedMap.forEach((captures, pointerId) => {
358
+ releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
359
+ });
360
+ }
361
+ function createEvents(store) {
362
+ const temp = new THREE.Vector3();
363
+ /** Sets up defaultRaycaster */
364
+
365
+ function prepareRay(event) {
366
+ var _raycaster$computeOff;
367
+
368
+ const state = store.getState();
369
+ const {
370
+ raycaster,
371
+ mouse,
372
+ camera,
373
+ size
374
+ } = state; // https://github.com/pmndrs/react-three-fiber/pull/782
375
+ // Events trigger outside of canvas when moved
376
+
377
+ const {
378
+ offsetX,
379
+ offsetY
380
+ } = (_raycaster$computeOff = raycaster.computeOffsets == null ? void 0 : raycaster.computeOffsets(event, state)) != null ? _raycaster$computeOff : event;
381
+ const {
382
+ width,
383
+ height
384
+ } = size;
385
+ mouse.set(offsetX / width * 2 - 1, -(offsetY / height) * 2 + 1);
386
+ raycaster.setFromCamera(mouse, camera);
387
+ }
388
+ /** Calculates delta */
389
+
390
+
391
+ function calculateDistance(event) {
392
+ const {
393
+ internal
394
+ } = store.getState();
395
+ const dx = event.offsetX - internal.initialClick[0];
396
+ const dy = event.offsetY - internal.initialClick[1];
397
+ return Math.round(Math.sqrt(dx * dx + dy * dy));
398
+ }
399
+ /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
400
+
401
+
402
+ function filterPointerEvents(objects) {
403
+ return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => {
404
+ var _r3f;
405
+
406
+ return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name];
407
+ }));
408
+ }
409
+
410
+ function intersect(filter) {
411
+ const state = store.getState();
412
+ const {
413
+ raycaster,
414
+ internal
415
+ } = state; // Skip event handling when noEvents is set
416
+
417
+ if (!raycaster.enabled) return [];
418
+ const seen = new Set();
419
+ const intersections = []; // Allow callers to eliminate event objects
420
+
421
+ const eventsObjects = filter ? filter(internal.interaction) : internal.interaction; // Intersect known handler objects and filter against duplicates
422
+
423
+ let intersects = raycaster.intersectObjects(eventsObjects, true).filter(item => {
424
+ const id = makeId(item);
425
+ if (seen.has(id)) return false;
426
+ seen.add(id);
427
+ return true;
428
+ }); // https://github.com/mrdoob/three.js/issues/16031
429
+ // Allow custom userland intersect sort order
430
+
431
+ if (raycaster.filter) intersects = raycaster.filter(intersects, state);
432
+
433
+ for (const intersect of intersects) {
434
+ let eventObject = intersect.object; // Bubble event up
435
+
436
+ while (eventObject) {
437
+ var _r3f2;
438
+
439
+ if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...intersect,
440
+ eventObject
441
+ });
442
+ eventObject = eventObject.parent;
443
+ }
444
+ }
445
+
446
+ return intersections;
447
+ }
448
+ /** Creates filtered intersects and returns an array of positive hits */
449
+
450
+
451
+ function patchIntersects(intersections, event) {
452
+ const {
453
+ internal
454
+ } = store.getState(); // If the interaction is captured, make all capturing targets part of the
455
+ // intersect.
456
+
457
+ if ('pointerId' in event && internal.capturedMap.has(event.pointerId)) {
458
+ for (let captureData of internal.capturedMap.get(event.pointerId).values()) {
459
+ intersections.push(captureData.intersection);
460
+ }
461
+ }
462
+
463
+ return intersections;
464
+ }
465
+ /** Handles intersections by forwarding them to handlers */
466
+
467
+
468
+ function handleIntersects(intersections, event, delta, callback) {
469
+ const {
470
+ raycaster,
471
+ mouse,
472
+ camera,
473
+ internal
474
+ } = store.getState(); // If anything has been found, forward it to the event listeners
475
+
476
+ if (intersections.length) {
477
+ const unprojectedPoint = temp.set(mouse.x, mouse.y, 0).unproject(camera);
478
+ const localState = {
479
+ stopped: false
480
+ };
481
+
482
+ for (const hit of intersections) {
483
+ const hasPointerCapture = id => {
484
+ var _internal$capturedMap, _internal$capturedMap2;
485
+
486
+ return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
487
+ };
488
+
489
+ const setPointerCapture = id => {
490
+ const captureData = {
491
+ intersection: hit,
492
+ target: event.target
493
+ };
494
+
495
+ if (internal.capturedMap.has(id)) {
496
+ // if the pointerId was previously captured, we add the hit to the
497
+ // event capturedMap.
498
+ internal.capturedMap.get(id).set(hit.eventObject, captureData);
499
+ } else {
500
+ // if the pointerId was not previously captured, we create a map
501
+ // containing the hitObject, and the hit. hitObject is used for
502
+ // faster access.
503
+ internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
504
+ } // Call the original event now
505
+ event.target.setPointerCapture(id);
506
+ };
507
+
508
+ const releasePointerCapture = id => {
509
+ const captures = internal.capturedMap.get(id);
510
+
511
+ if (captures) {
512
+ releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
513
+ }
514
+ }; // Add native event props
515
+
516
+
517
+ 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.
518
+
519
+ for (let prop in event) {
520
+ let property = event[prop]; // Only copy over atomics, leave functions alone as these should be
521
+ // called as event.nativeEvent.fn()
522
+
523
+ if (typeof property !== 'function') extractEventProps[prop] = property;
524
+ }
525
+
526
+ let raycastEvent = { ...hit,
527
+ ...extractEventProps,
528
+ spaceX: mouse.x,
529
+ spaceY: mouse.y,
530
+ intersections,
531
+ stopped: localState.stopped,
532
+ delta,
533
+ unprojectedPoint,
534
+ ray: raycaster.ray,
535
+ camera: camera,
536
+ // Hijack stopPropagation, which just sets a flag
537
+ stopPropagation: () => {
538
+ // https://github.com/pmndrs/react-three-fiber/issues/596
539
+ // Events are not allowed to stop propagation if the pointer has been captured
540
+ const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation...
541
+
542
+ if ( // ...if this pointer hasn't been captured
543
+ !capturesForPointer || // ... or if the hit object is capturing the pointer
544
+ capturesForPointer.has(hit.eventObject)) {
545
+ raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records
546
+ // An event handler is only allowed to flush other handlers if it is hovered itself
547
+
548
+ if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) {
549
+ // Objects cannot flush out higher up objects that have already caught the event
550
+ const higher = intersections.slice(0, intersections.indexOf(hit));
551
+ cancelPointer([...higher, hit]);
552
+ }
553
+ }
554
+ },
555
+ // there should be a distinction between target and currentTarget
556
+ target: {
557
+ hasPointerCapture,
558
+ setPointerCapture,
559
+ releasePointerCapture
560
+ },
561
+ currentTarget: {
562
+ hasPointerCapture,
563
+ setPointerCapture,
564
+ releasePointerCapture
565
+ },
566
+ sourceEvent: event,
567
+ // deprecated
568
+ nativeEvent: event
569
+ }; // Call subscribers
570
+
571
+ callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation
572
+
573
+ if (localState.stopped === true) break;
574
+ }
575
+ }
576
+
577
+ return intersections;
578
+ }
579
+
580
+ function cancelPointer(hits) {
581
+ const {
582
+ internal
583
+ } = store.getState();
584
+ Array.from(internal.hovered.values()).forEach(hoveredObj => {
585
+ // When no objects were hit or the the hovered object wasn't found underneath the cursor
586
+ // we call onPointerOut and delete the object from the hovered-elements map
587
+ if (!hits.length || !hits.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) {
588
+ const eventObject = hoveredObj.eventObject;
589
+ const instance = eventObject.__r3f;
590
+ const handlers = instance == null ? void 0 : instance.handlers;
591
+ internal.hovered.delete(makeId(hoveredObj));
592
+
593
+ if (instance != null && instance.eventCount) {
594
+ // Clear out intersects, they are outdated by now
595
+ const data = { ...hoveredObj,
596
+ intersections: hits || []
597
+ };
598
+ handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
599
+ handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
600
+ }
601
+ }
602
+ });
603
+ }
604
+
605
+ const handlePointer = name => {
606
+ // Deal with cancelation
607
+ switch (name) {
608
+ case 'onPointerLeave':
609
+ case 'onPointerCancel':
610
+ return () => cancelPointer([]);
611
+
612
+ case 'onLostPointerCapture':
613
+ return event => {
614
+ const {
615
+ internal
616
+ } = store.getState();
617
+
618
+ if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) {
619
+ // If the object event interface had onLostPointerCapture, we'd call it here on every
620
+ // object that's getting removed.
621
+ internal.capturedMap.delete(event.pointerId);
622
+ cancelPointer([]);
623
+ }
624
+ };
625
+ } // Any other pointer goes here ...
626
+
627
+
628
+ return event => {
629
+ const {
630
+ onPointerMissed,
631
+ internal
632
+ } = store.getState();
633
+ prepareRay(event);
634
+ internal.lastEvent.current = event; // Get fresh intersects
635
+
636
+ const isPointerMove = name === 'onPointerMove';
637
+ const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick';
638
+ const filter = isPointerMove ? filterPointerEvents : undefined;
639
+ const hits = patchIntersects(intersect(filter), event);
640
+ const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down
641
+
642
+ if (name === 'onPointerDown') {
643
+ internal.initialClick = [event.offsetX, event.offsetY];
644
+ internal.initialHits = hits.map(hit => hit.eventObject);
645
+ } // If a click yields no results, pass it back to the user as a miss
646
+ // Missed events have to come first in order to establish user-land side-effect clean up
647
+
648
+
649
+ if (isClickEvent && !hits.length) {
650
+ if (delta <= 2) {
651
+ pointerMissed(event, internal.interaction);
652
+ if (onPointerMissed) onPointerMissed(event);
653
+ }
654
+ } // Take care of unhover
655
+
656
+
657
+ if (isPointerMove) cancelPointer(hits);
658
+ handleIntersects(hits, event, delta, data => {
659
+ const eventObject = data.eventObject;
660
+ const instance = eventObject.__r3f;
661
+ const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers
662
+
663
+ if (!(instance != null && instance.eventCount)) return;
664
+
665
+ if (isPointerMove) {
666
+ // Move event ...
667
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
668
+ // When enter or out is present take care of hover-state
669
+ const id = makeId(data);
670
+ const hoveredItem = internal.hovered.get(id);
671
+
672
+ if (!hoveredItem) {
673
+ // If the object wasn't previously hovered, book it and call its handler
674
+ internal.hovered.set(id, data);
675
+ handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
676
+ handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
677
+ } else if (hoveredItem.stopped) {
678
+ // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
679
+ data.stopPropagation();
680
+ }
681
+ } // Call mouse move
682
+
683
+
684
+ handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
685
+ } else {
686
+ // All other events ...
687
+ const handler = handlers[name];
688
+
689
+ if (handler) {
690
+ // Forward all events back to their respective handlers with the exception of click events,
691
+ // which must use the initial target
692
+ if (!isClickEvent || internal.initialHits.includes(eventObject)) {
693
+ // Missed events have to come first
694
+ pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler
695
+
696
+ handler(data);
697
+ }
698
+ } else {
699
+ // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit
700
+ if (isClickEvent && internal.initialHits.includes(eventObject)) {
701
+ pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object)));
702
+ }
703
+ }
704
+ }
705
+ });
706
+ };
707
+ };
708
+
709
+ function pointerMissed(event, objects) {
710
+ objects.forEach(object => {
711
+ var _r3f3;
712
+
713
+ return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event);
714
+ });
715
+ }
716
+
717
+ return {
718
+ handlePointer
719
+ };
720
+ }
721
+
722
+ // Type guard to tell a store from a portal
723
+ const isStore = def => def && !!def.getState;
724
+
725
+ const getContainer = (container, child) => {
726
+ var _container$__r3f$root, _container$__r3f;
727
+
728
+ return {
729
+ // If the container is not a root-store then it must be a THREE.Object3D into which part of the
730
+ // scene is portalled into. Now there can be two variants of this, either that object is part of
731
+ // the regular jsx tree, in which case it already has __r3f with a valid root attached, or it lies
732
+ // outside react, in which case we must take the root of the child that is about to be attached to it.
733
+ root: isStore(container) ? container : (_container$__r3f$root = (_container$__r3f = container.__r3f) == null ? void 0 : _container$__r3f.root) != null ? _container$__r3f$root : child.__r3f.root,
734
+ // The container is the eventual target into which objects are mounted, it has to be a THREE.Object3D
735
+ container: isStore(container) ? container.getState().scene : container
736
+ };
737
+ };
738
+
739
+ let catalogue = {};
740
+
741
+ let extend = objects => void (catalogue = { ...catalogue,
742
+ ...objects
743
+ });
744
+
745
+ function createRenderer(roots, getEventPriority) {
746
+ function createInstance(type, {
747
+ args = [],
748
+ attach,
749
+ ...props
750
+ }, root, hostContext, internalInstanceHandle) {
751
+ let name = `${type[0].toUpperCase()}${type.slice(1)}`;
752
+ let instance; // https://github.com/facebook/react/issues/17147
753
+ // Portals do not give us a root, they are themselves treated as a root by the reconciler
754
+ // In order to figure out the actual root we have to climb through fiber internals :(
755
+
756
+ if (!isStore(root) && internalInstanceHandle) {
757
+ const fn = node => {
758
+ if (!node.return) return node.stateNode && node.stateNode.containerInfo;else return fn(node.return);
759
+ };
760
+
761
+ root = fn(internalInstanceHandle);
762
+ } // Assert that by now we have a valid root
763
+
764
+
765
+ if (!root || !isStore(root)) throw `No valid root for ${name}!`; // Auto-attach geometries and materials
766
+
767
+ if (attach === undefined) {
768
+ if (name.endsWith('Geometry')) attach = 'geometry';else if (name.endsWith('Material')) attach = 'material';
769
+ }
770
+
771
+ if (type === 'primitive') {
772
+ if (props.object === undefined) throw `Primitives without 'object' are invalid!`;
773
+ const object = props.object;
774
+ instance = prepare(object, {
775
+ root,
776
+ attach,
777
+ primitive: true
778
+ });
779
+ } else {
780
+ const target = catalogue[name];
781
+
782
+ if (!target) {
783
+ throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://github.com/pmndrs/react-three-fiber/blob/master/markdown/api.md#using-3rd-party-objects-declaratively`;
784
+ } // Throw if an object or literal was passed for args
785
+
786
+
787
+ if (!Array.isArray(args)) throw 'The args prop must be an array!'; // Instanciate new object, link it to the root
788
+ // Append memoized props with args so it's not forgotten
789
+
790
+ instance = prepare(new target(...args), {
791
+ root,
792
+ attach,
793
+ // TODO: Figure out what this is for
794
+ memoizedProps: {
795
+ args: args.length === 0 ? null : args
796
+ }
797
+ });
798
+ } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the
799
+ // view yet. If the callback relies on references for instance, they won't be ready yet, this is
800
+ // why it passes "true" here
801
+
802
+
803
+ applyProps(instance, props);
804
+ return instance;
805
+ }
806
+
807
+ function appendChild(parentInstance, child) {
808
+ let added = false;
809
+
810
+ if (child) {
811
+ // The attach attribute implies that the object attaches itself on the parent
812
+ if (child.__r3f.attach) {
813
+ attach(parentInstance, child, child.__r3f.attach);
814
+ } else if (child.isObject3D && parentInstance.isObject3D) {
815
+ // add in the usual parent-child way
816
+ parentInstance.add(child);
817
+ added = true;
818
+ } // This is for anything that used attach, and for non-Object3Ds that don't get attached to props;
819
+ // that is, anything that's a child in React but not a child in the scenegraph.
820
+
821
+
822
+ if (!added) parentInstance.__r3f.objects.push(child);
823
+ if (!child.__r3f) prepare(child, {});
824
+ child.__r3f.parent = parentInstance;
825
+ updateInstance(child);
826
+ invalidateInstance(child);
827
+ }
828
+ }
829
+
830
+ function insertBefore(parentInstance, child, beforeChild) {
831
+ let added = false;
832
+
833
+ if (child) {
834
+ if (child.__r3f.attach) {
835
+ attach(parentInstance, child, child.__r3f.attach);
836
+ } else if (child.isObject3D && parentInstance.isObject3D) {
837
+ child.parent = parentInstance;
838
+ child.dispatchEvent({
839
+ type: 'added'
840
+ });
841
+ const restSiblings = parentInstance.children.filter(sibling => sibling !== child);
842
+ const index = restSiblings.indexOf(beforeChild);
843
+ parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)];
844
+ added = true;
845
+ }
846
+
847
+ if (!added) parentInstance.__r3f.objects.push(child);
848
+ if (!child.__r3f) prepare(child, {});
849
+ child.__r3f.parent = parentInstance;
850
+ updateInstance(child);
851
+ invalidateInstance(child);
852
+ }
853
+ }
854
+
855
+ function removeRecursive(array, parent, dispose = false) {
856
+ if (array) [...array].forEach(child => removeChild(parent, child, dispose));
857
+ }
858
+
859
+ function removeChild(parentInstance, child, dispose) {
860
+ if (child) {
861
+ var _parentInstance$__r3f, _child$__r3f2;
862
+
863
+ // Clear the parent reference
864
+ if (child.__r3f) child.__r3f.parent = null; // Remove child from the parents objects
865
+
866
+ if ((_parentInstance$__r3f = parentInstance.__r3f) != null && _parentInstance$__r3f.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child); // Remove attachment
867
+
868
+ if (child.__r3f.attach) {
869
+ detach(parentInstance, child, child.__r3f.attach);
870
+ } else if (child.isObject3D && parentInstance.isObject3D) {
871
+ var _child$__r3f;
872
+
873
+ parentInstance.remove(child); // Remove interactivity
874
+
875
+ if ((_child$__r3f = child.__r3f) != null && _child$__r3f.root) {
876
+ removeInteractivity(child.__r3f.root, child);
877
+ }
878
+ } // Allow objects to bail out of recursive dispose alltogether by passing dispose={null}
879
+ // Never dispose of primitives because their state may be kept outside of React!
880
+ // In order for an object to be able to dispose it has to have
881
+ // - a dispose method,
882
+ // - it cannot be a <primitive object={...} />
883
+ // - it cannot be a THREE.Scene, because three has broken it's own api
884
+ //
885
+ // Since disposal is recursive, we can check the optional dispose arg, which will be undefined
886
+ // when the reconciler calls it, but then carry our own check recursively
887
+
888
+
889
+ const isPrimitive = (_child$__r3f2 = child.__r3f) == null ? void 0 : _child$__r3f2.primitive;
890
+ const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are
891
+ // attached to them declaratively ...
892
+
893
+ if (!isPrimitive) {
894
+ var _child$__r3f3;
895
+
896
+ removeRecursive((_child$__r3f3 = child.__r3f) == null ? void 0 : _child$__r3f3.objects, child, shouldDispose);
897
+ removeRecursive(child.children, child, shouldDispose);
898
+ } // Remove references
899
+
900
+
901
+ if (child.__r3f) {
902
+ delete child.__r3f.root;
903
+ delete child.__r3f.objects;
904
+ delete child.__r3f.handlers;
905
+ delete child.__r3f.memoizedProps;
906
+ if (!isPrimitive) delete child.__r3f;
907
+ } // Dispose item whenever the reconciler feels like it
908
+
909
+
910
+ if (shouldDispose && child.dispose && child.type !== 'Scene') {
911
+ unstable_scheduleCallback(unstable_IdlePriority, () => {
912
+ try {
913
+ child.dispose();
914
+ } catch (e) {
915
+ /* ... */
916
+ }
917
+ });
918
+ }
919
+
920
+ invalidateInstance(parentInstance);
921
+ }
922
+ }
923
+
924
+ function switchInstance(instance, type, newProps, fiber) {
925
+ var _instance$__r3f;
926
+
927
+ const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent;
928
+ if (!parent) return;
929
+ const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348
930
+ // When args change the instance has to be re-constructed, which then
931
+ // forces r3f to re-parent the children and non-scene objects
932
+ // This can not include primitives, which should not have declarative children
933
+
934
+ if (type !== 'primitive' && instance.children) {
935
+ instance.children.forEach(child => appendChild(newInstance, child));
936
+ instance.children = [];
937
+ }
938
+
939
+ instance.__r3f.objects.forEach(child => appendChild(newInstance, child));
940
+
941
+ instance.__r3f.objects = [];
942
+ removeChild(parent, instance);
943
+ appendChild(parent, newInstance) // This evil hack switches the react-internal fiber node
944
+ // https://github.com/facebook/react/issues/14983
945
+ // https://github.com/facebook/react/pull/15021
946
+ ;
947
+ [fiber, fiber.alternate].forEach(fiber => {
948
+ if (fiber !== null) {
949
+ fiber.stateNode = newInstance;
950
+
951
+ if (fiber.ref) {
952
+ if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance;
953
+ }
954
+ }
955
+ });
956
+ }
957
+
958
+ const reconciler = Reconciler({
959
+ appendChildToContainer: (parentInstance, child) => {
960
+ const {
961
+ container,
962
+ root
963
+ } = getContainer(parentInstance, child); // Link current root to the default scene
964
+
965
+ container.__r3f.root = root;
966
+ appendChild(container, child);
967
+ },
968
+ removeChildFromContainer: (parentInstance, child) => removeChild(getContainer(parentInstance, child).container, child),
969
+ insertInContainerBefore: (parentInstance, child, beforeChild) => insertBefore(getContainer(parentInstance, child).container, child, beforeChild),
970
+
971
+ prepareUpdate(instance, type, oldProps, newProps) {
972
+ if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) {
973
+ return [true];
974
+ } else {
975
+ // This is a data object, let's extract critical information about it
976
+ const {
977
+ args: argsNew = [],
978
+ children: cN,
979
+ ...restNew
980
+ } = newProps;
981
+ const {
982
+ args: argsOld = [],
983
+ children: cO,
984
+ ...restOld
985
+ } = oldProps; // Throw if an object or literal was passed for args
986
+
987
+ if (!Array.isArray(argsNew)) throw 'The args prop must be an array!'; // If it has new props or arguments, then it needs to be re-instanciated
988
+
989
+ if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes
990
+
991
+ const diff = diffProps(instance, restNew, restOld, true);
992
+ if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance
993
+
994
+ return null;
995
+ }
996
+ },
997
+
998
+ commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) {
999
+ // Reconstruct when args or <primitive object={...} have changes
1000
+ if (reconstruct) switchInstance(instance, type, newProps, fiber); // Otherwise just overwrite props
1001
+ else applyProps(instance, diff);
1002
+ },
1003
+
1004
+ hideInstance(instance) {
1005
+ var _instance$__r3f2;
1006
+
1007
+ // Deatch while the instance is hidden
1008
+ const {
1009
+ attach: type,
1010
+ parent
1011
+ } = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {};
1012
+ if (type && parent) detach(parent, instance, type);
1013
+ if (instance.isObject3D) instance.visible = false;
1014
+ invalidateInstance(instance);
1015
+ },
1016
+
1017
+ unhideInstance(instance, props) {
1018
+ var _instance$__r3f3;
1019
+
1020
+ // Re-attach when the instance is unhidden
1021
+ const {
1022
+ attach: type,
1023
+ parent
1024
+ } = (_instance$__r3f3 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f3 : {};
1025
+ if (type && parent) attach(parent, instance, type);
1026
+ if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true;
1027
+ invalidateInstance(instance);
1028
+ },
1029
+
1030
+ createInstance,
1031
+ removeChild,
1032
+ appendChild,
1033
+ appendInitialChild: appendChild,
1034
+ insertBefore,
1035
+ warnsIfNotActing: true,
1036
+ supportsMutation: true,
1037
+ isPrimaryRenderer: false,
1038
+ getCurrentEventPriority: () => getEventPriority ? getEventPriority() : DefaultEventPriority,
1039
+ // @ts-ignore
1040
+ now: is.fun(performance.now) ? performance.now : is.fun(Date.now) ? Date.now : undefined,
1041
+ // @ts-ignore
1042
+ scheduleTimeout: is.fun(setTimeout) ? setTimeout : undefined,
1043
+ // @ts-ignore
1044
+ cancelTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
1045
+ setTimeout: is.fun(setTimeout) ? setTimeout : undefined,
1046
+ clearTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
1047
+ noTimeout: -1,
1048
+ hideTextInstance: () => {
1049
+ throw new Error('Text is not allowed in the R3F tree.');
1050
+ },
1051
+ // prettier-ignore
1052
+ getPublicInstance: instance => instance,
1053
+ getRootHostContext: () => null,
1054
+ getChildHostContext: parentHostContext => parentHostContext,
1055
+ createTextInstance: () => {},
1056
+
1057
+ finalizeInitialChildren(instance) {
1058
+ var _instance$__r3f4;
1059
+
1060
+ // https://github.com/facebook/react/issues/20271
1061
+ // Returning true will trigger commitMount
1062
+ const localState = (_instance$__r3f4 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f4 : {};
1063
+ return !!localState.handlers;
1064
+ },
1065
+
1066
+ commitMount(instance)
1067
+ /*, type, props*/
1068
+ {
1069
+ var _instance$__r3f5;
1070
+
1071
+ // https://github.com/facebook/react/issues/20271
1072
+ // This will make sure events are only added once to the central container
1073
+ const localState = (_instance$__r3f5 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f5 : {};
1074
+
1075
+ if (instance.raycast && localState.handlers && localState.eventCount) {
1076
+ instance.__r3f.root.getState().internal.interaction.push(instance);
1077
+ }
1078
+ },
1079
+
1080
+ shouldDeprioritizeSubtree: () => false,
1081
+ prepareForCommit: () => null,
1082
+ preparePortalMount: containerInfo => prepare(containerInfo),
1083
+ resetAfterCommit: () => {},
1084
+ shouldSetTextContent: () => false,
1085
+ clearContainer: () => false,
1086
+ detachDeletedInstance: () => {}
1087
+ });
1088
+ return {
1089
+ reconciler,
1090
+ applyProps
1091
+ };
1092
+ }
1093
+
1094
+ const isRenderer = def => !!(def != null && def.render);
1095
+ const isOrthographicCamera = def => def && def.isOrthographicCamera;
1096
+ const context = /*#__PURE__*/React.createContext(null);
1097
+
1098
+ const createStore = (applyProps, invalidate, advance, props) => {
1099
+ const {
1100
+ gl,
1101
+ size,
1102
+ shadows = false,
1103
+ linear = false,
1104
+ flat = false,
1105
+ orthographic = false,
1106
+ frameloop = 'always',
1107
+ dpr = [1, 2],
1108
+ performance,
1109
+ clock = new THREE.Clock(),
1110
+ raycaster: raycastOptions,
1111
+ camera: cameraOptions,
1112
+ onPointerMissed
1113
+ } = props; // Set shadowmap
1114
+
1115
+ if (shadows) {
1116
+ gl.shadowMap.enabled = true;
1117
+ if (typeof shadows === 'object') Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = THREE.PCFSoftShadowMap;
1118
+ } // Set color preferences
1119
+
1120
+
1121
+ if (linear) gl.outputEncoding = THREE.LinearEncoding;
1122
+ if (flat) gl.toneMapping = THREE.NoToneMapping; // clock.elapsedTime is updated using advance(timestamp)
1123
+
1124
+ if (frameloop === 'never') {
1125
+ clock.stop();
1126
+ clock.elapsedTime = 0;
1127
+ }
1128
+
1129
+ const rootState = create((set, get) => {
1130
+ // Create custom raycaster
1131
+ const raycaster = new THREE.Raycaster();
1132
+ const {
1133
+ params,
1134
+ ...options
1135
+ } = raycastOptions || {};
1136
+ applyProps(raycaster, {
1137
+ enabled: true,
1138
+ ...options,
1139
+ params: { ...raycaster.params,
1140
+ ...params
1141
+ }
1142
+ }); // Create default camera
1143
+
1144
+ const isCamera = cameraOptions instanceof THREE.Camera;
1145
+ const camera = isCamera ? cameraOptions : orthographic ? new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new THREE.PerspectiveCamera(75, 0, 0.1, 1000);
1146
+
1147
+ if (!isCamera) {
1148
+ camera.position.z = 5;
1149
+ if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default
1150
+
1151
+ if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0);
1152
+ }
1153
+
1154
+ const initialDpr = calculateDpr(dpr);
1155
+ const position = new THREE.Vector3();
1156
+ const defaultTarget = new THREE.Vector3();
1157
+ const tempTarget = new THREE.Vector3();
1158
+
1159
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1160
+ const {
1161
+ width,
1162
+ height
1163
+ } = size;
1164
+ const aspect = width / height;
1165
+ if (target instanceof THREE.Vector3) tempTarget.copy(target);else tempTarget.set(...target);
1166
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1167
+
1168
+ if (isOrthographicCamera(camera)) {
1169
+ return {
1170
+ width: width / camera.zoom,
1171
+ height: height / camera.zoom,
1172
+ factor: 1,
1173
+ distance,
1174
+ aspect
1175
+ };
1176
+ } else {
1177
+ const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians
1178
+
1179
+ const h = 2 * Math.tan(fov / 2) * distance; // visible height
1180
+
1181
+ const w = h * (width / height);
1182
+ return {
1183
+ width: w,
1184
+ height: h,
1185
+ factor: width / w,
1186
+ distance,
1187
+ aspect
1188
+ };
1189
+ }
1190
+ }
1191
+
1192
+ let performanceTimeout = undefined;
1193
+
1194
+ const setPerformanceCurrent = current => set(state => ({
1195
+ performance: { ...state.performance,
1196
+ current
1197
+ }
1198
+ })); // Handle frame behavior in WebXR
1199
+
1200
+
1201
+ const handleXRFrame = timestamp => {
1202
+ const state = get();
1203
+ if (state.frameloop === 'never') return;
1204
+ advance(timestamp, true);
1205
+ }; // Toggle render switching on session
1206
+
1207
+
1208
+ const handleSessionChange = () => {
1209
+ gl.xr.enabled = gl.xr.isPresenting;
1210
+ gl.setAnimationLoop(gl.xr.isPresenting ? handleXRFrame : null); // If exiting session, request frame
1211
+
1212
+ if (!gl.xr.isPresenting) invalidate(get());
1213
+ }; // WebXR session manager
1214
+
1215
+
1216
+ const xr = {
1217
+ connect() {
1218
+ gl.xr.addEventListener('sessionstart', handleSessionChange);
1219
+ gl.xr.addEventListener('sessionend', handleSessionChange);
1220
+ },
1221
+
1222
+ disconnect() {
1223
+ gl.xr.removeEventListener('sessionstart', handleSessionChange);
1224
+ gl.xr.removeEventListener('sessionend', handleSessionChange);
1225
+ }
1226
+
1227
+ }; // Subscribe to WebXR session events
1228
+
1229
+ if (gl.xr) xr.connect();
1230
+ return {
1231
+ gl,
1232
+ set,
1233
+ get,
1234
+ invalidate: () => invalidate(get()),
1235
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1236
+ linear,
1237
+ flat,
1238
+ scene: prepare(new THREE.Scene()),
1239
+ camera,
1240
+ controls: null,
1241
+ raycaster,
1242
+ clock,
1243
+ mouse: new THREE.Vector2(),
1244
+ frameloop,
1245
+ onPointerMissed,
1246
+ performance: {
1247
+ current: 1,
1248
+ min: 0.5,
1249
+ max: 1,
1250
+ debounce: 200,
1251
+ ...performance,
1252
+ regress: () => {
1253
+ const state = get(); // Clear timeout
1254
+
1255
+ if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance
1256
+
1257
+ if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile
1258
+
1259
+ performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce);
1260
+ }
1261
+ },
1262
+ size: {
1263
+ width: 0,
1264
+ height: 0
1265
+ },
1266
+ viewport: {
1267
+ initialDpr,
1268
+ dpr: initialDpr,
1269
+ width: 0,
1270
+ height: 0,
1271
+ aspect: 0,
1272
+ distance: 0,
1273
+ factor: 0,
1274
+ getCurrentViewport
1275
+ },
1276
+ setSize: (width, height) => {
1277
+ const size = {
1278
+ width,
1279
+ height
1280
+ };
1281
+ set(state => ({
1282
+ size,
1283
+ viewport: { ...state.viewport,
1284
+ ...getCurrentViewport(camera, defaultTarget, size)
1285
+ }
1286
+ }));
1287
+ },
1288
+ setDpr: dpr => set(state => ({
1289
+ viewport: { ...state.viewport,
1290
+ dpr: calculateDpr(dpr)
1291
+ }
1292
+ })),
1293
+ setFrameloop: (frameloop = 'always') => set(() => ({
1294
+ frameloop
1295
+ })),
1296
+ events: {
1297
+ connected: false
1298
+ },
1299
+ internal: {
1300
+ active: false,
1301
+ priority: 0,
1302
+ frames: 0,
1303
+ lastProps: props,
1304
+ lastEvent: /*#__PURE__*/React.createRef(),
1305
+ interaction: [],
1306
+ hovered: new Map(),
1307
+ subscribers: [],
1308
+ initialClick: [0, 0],
1309
+ initialHits: [],
1310
+ capturedMap: new Map(),
1311
+ xr,
1312
+ subscribe: (ref, priority = 0) => {
1313
+ set(({
1314
+ internal
1315
+ }) => ({
1316
+ internal: { ...internal,
1317
+ // If this subscription was given a priority, it takes rendering into its own hands
1318
+ // For that reason we switch off automatic rendering and increase the manual flag
1319
+ // As long as this flag is positive there can be no internal rendering at all
1320
+ // because there could be multiple render subscriptions
1321
+ priority: internal.priority + (priority > 0 ? 1 : 0),
1322
+ // Register subscriber and sort layers from lowest to highest, meaning,
1323
+ // highest priority renders last (on top of the other frames)
1324
+ subscribers: [...internal.subscribers, {
1325
+ ref,
1326
+ priority
1327
+ }].sort((a, b) => a.priority - b.priority)
1328
+ }
1329
+ }));
1330
+ return () => {
1331
+ set(({
1332
+ internal
1333
+ }) => ({
1334
+ internal: { ...internal,
1335
+ // Decrease manual flag if this subscription had a priority
1336
+ priority: internal.priority - (priority > 0 ? 1 : 0),
1337
+ // Remove subscriber from list
1338
+ subscribers: internal.subscribers.filter(s => s.ref !== ref)
1339
+ }
1340
+ }));
1341
+ };
1342
+ }
1343
+ }
1344
+ };
1345
+ });
1346
+ const state = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio
1347
+
1348
+ let oldSize = state.size;
1349
+ let oldDpr = state.viewport.dpr;
1350
+ rootState.subscribe(() => {
1351
+ const {
1352
+ camera,
1353
+ size,
1354
+ viewport,
1355
+ internal
1356
+ } = rootState.getState();
1357
+
1358
+ if (size !== oldSize || viewport.dpr !== oldDpr) {
1359
+ // https://github.com/pmndrs/react-three-fiber/issues/92
1360
+ // Do not mess with the camera if it belongs to the user
1361
+ if (!camera.manual && !(internal.lastProps.camera instanceof THREE.Camera)) {
1362
+ if (isOrthographicCamera(camera)) {
1363
+ camera.left = size.width / -2;
1364
+ camera.right = size.width / 2;
1365
+ camera.top = size.height / 2;
1366
+ camera.bottom = size.height / -2;
1367
+ } else {
1368
+ camera.aspect = size.width / size.height;
1369
+ }
1370
+
1371
+ camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178
1372
+ // Update matrix world since the renderer is a frame late
1373
+
1374
+ camera.updateMatrixWorld();
1375
+ } // Update renderer
1376
+
1377
+
1378
+ gl.setPixelRatio(viewport.dpr);
1379
+ gl.setSize(size.width, size.height);
1380
+ oldSize = size;
1381
+ oldDpr = viewport.dpr;
1382
+ }
1383
+ }); // Update size
1384
+
1385
+ if (size) state.setSize(size.width, size.height); // Invalidate on any change
1386
+
1387
+ rootState.subscribe(state => invalidate(state)); // Return root state
1388
+
1389
+ return rootState;
1390
+ };
1391
+
1392
+ function createSubs(callback, subs) {
1393
+ const index = subs.length;
1394
+ subs.push(callback);
1395
+ return () => void subs.splice(index, 1);
1396
+ }
1397
+
1398
+ let i;
1399
+ let globalEffects = [];
1400
+ let globalAfterEffects = [];
1401
+ let globalTailEffects = [];
1402
+ const addEffect = callback => createSubs(callback, globalEffects);
1403
+ const addAfterEffect = callback => createSubs(callback, globalAfterEffects);
1404
+ const addTail = callback => createSubs(callback, globalTailEffects);
1405
+
1406
+ function run(effects, timestamp) {
1407
+ for (i = 0; i < effects.length; i++) effects[i](timestamp);
1408
+ }
1409
+
1410
+ function render(timestamp, state) {
1411
+ // Run local effects
1412
+ let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp
1413
+
1414
+ if (state.frameloop === 'never' && typeof timestamp === 'number') {
1415
+ delta = timestamp - state.clock.elapsedTime;
1416
+ state.clock.oldTime = state.clock.elapsedTime;
1417
+ state.clock.elapsedTime = timestamp;
1418
+ } // Call subscribers (useFrame)
1419
+
1420
+
1421
+ for (i = 0; i < state.internal.subscribers.length; i++) state.internal.subscribers[i].ref.current(state, delta); // Render content
1422
+
1423
+
1424
+ if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count
1425
+
1426
+ state.internal.frames = Math.max(0, state.internal.frames - 1);
1427
+ return state.frameloop === 'always' ? 1 : state.internal.frames;
1428
+ }
1429
+
1430
+ function createLoop(roots) {
1431
+ let running = false;
1432
+ let repeat;
1433
+
1434
+ function loop(timestamp) {
1435
+ running = true;
1436
+ repeat = 0; // Run effects
1437
+
1438
+ run(globalEffects, timestamp); // Render all roots
1439
+
1440
+ roots.forEach(root => {
1441
+ var _state$gl$xr;
1442
+
1443
+ const state = root.store.getState(); // If the frameloop is invalidated, do not run another frame
1444
+
1445
+ if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) {
1446
+ repeat += render(timestamp, state);
1447
+ }
1448
+ }); // Run after-effects
1449
+
1450
+ run(globalAfterEffects, timestamp); // Keep on looping if anything invalidates the frameloop
1451
+
1452
+ if (repeat > 0) return requestAnimationFrame(loop); // Tail call effects, they are called when rendering stops
1453
+ else run(globalTailEffects, timestamp); // Flag end of operation
1454
+
1455
+ running = false;
1456
+ }
1457
+
1458
+ function invalidate(state) {
1459
+ var _state$gl$xr2;
1460
+
1461
+ if (!state) return roots.forEach(root => invalidate(root.store.getState()));
1462
+ 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
1463
+
1464
+ state.internal.frames = Math.min(60, state.internal.frames + 1); // If the render-loop isn't active, start it
1465
+
1466
+ if (!running) {
1467
+ running = true;
1468
+ requestAnimationFrame(loop);
1469
+ }
1470
+ }
1471
+
1472
+ function advance(timestamp, runGlobalEffects = true, state) {
1473
+ if (runGlobalEffects) run(globalEffects, timestamp);
1474
+ if (!state) roots.forEach(root => render(timestamp, root.store.getState()));else render(timestamp, state);
1475
+ if (runGlobalEffects) run(globalAfterEffects, timestamp);
1476
+ }
1477
+
1478
+ return {
1479
+ loop,
1480
+ invalidate,
1481
+ advance
1482
+ };
1483
+ }
1484
+
1485
+ function useStore() {
1486
+ const store = React.useContext(context);
1487
+ if (!store) throw `R3F hooks can only be used within the Canvas component!`;
1488
+ return store;
1489
+ }
1490
+ function useThree(selector = state => state, equalityFn) {
1491
+ return useStore()(selector, equalityFn);
1492
+ }
1493
+ function useFrame(callback, renderPriority = 0) {
1494
+ const subscribe = useStore().getState().internal.subscribe; // Update ref
1495
+
1496
+ const ref = React.useRef(callback);
1497
+ React.useLayoutEffect(() => void (ref.current = callback), [callback]); // Subscribe on mount, unsubscribe on unmount
1498
+
1499
+ React.useLayoutEffect(() => subscribe(ref, renderPriority), [renderPriority, subscribe]);
1500
+ return null;
1501
+ }
1502
+ function useGraph(object) {
1503
+ return React.useMemo(() => buildGraph(object), [object]);
1504
+ }
1505
+
1506
+ function loadingFn(extensions, onProgress) {
1507
+ return function (Proto, ...input) {
1508
+ // Construct new loader and run extensions
1509
+ const loader = new Proto();
1510
+ if (extensions) extensions(loader); // Go through the urls and load them
1511
+
1512
+ return Promise.all(input.map(input => new Promise((res, reject) => loader.load(input, data => {
1513
+ if (data.scene) Object.assign(data, buildGraph(data.scene));
1514
+ res(data);
1515
+ }, onProgress, error => reject(`Could not load ${input}: ${error.message}`)))));
1516
+ };
1517
+ }
1518
+
1519
+ function useLoader(Proto, input, extensions, onProgress) {
1520
+ // Use suspense to load async assets
1521
+ const keys = Array.isArray(input) ? input : [input];
1522
+ const results = suspend(loadingFn(extensions, onProgress), [Proto, ...keys], {
1523
+ equal: is.equ
1524
+ }); // Return the object/s
1525
+
1526
+ return Array.isArray(input) ? results : results[0];
1527
+ }
1528
+
1529
+ useLoader.preload = function (Proto, input, extensions) {
1530
+ const keys = Array.isArray(input) ? input : [input];
1531
+ return preload(loadingFn(extensions), [Proto, ...keys]);
1532
+ };
1533
+
1534
+ useLoader.clear = function (Proto, input) {
1535
+ const keys = Array.isArray(input) ? input : [input];
1536
+ return clear([Proto, ...keys]);
1537
+ };
1538
+
1539
+ export { createLoop as a, createRenderer as b, createEvents as c, calculateDpr as d, createStore as e, context as f, dispose as g, extend as h, isRenderer as i, addEffect as j, addAfterEffect as k, addTail as l, useThree as m, useFrame as n, omit as o, pick as p, useGraph as q, useLoader as r, buildGraph as s, threeTypes as t, useStore as u, is as v };