@react-three/fiber 8.0.0-alpha.0 → 8.0.0-beta-01

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