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