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