@react-three/fiber 10.0.0-canary.979dc2d → 10.0.0-canary.9b237a7

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.
@@ -1,4148 +1,89 @@
1
- import * as three_examples_jsm_inspector_Inspector_js from 'three/examples/jsm/inspector/Inspector.js';
2
- import * as three_webgpu from 'three/webgpu';
3
- import { CubeRenderTarget, RenderTarget, WebGPURenderer, Node, StorageTexture, Data3DTexture, CanvasTarget, ShaderNodeObject, Euler as Euler$2, Color as Color$2, ColorRepresentation as ColorRepresentation$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, Loader as Loader$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera, WebGPURendererParameters } from 'three/webgpu';
4
- import { Inspector } from 'three/addons/inspector/Inspector.js';
5
- import * as THREE$1 from 'three';
6
- import { Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1 } from 'three';
7
- import * as React$1 from 'react';
8
- import { ReactNode, Component, RefObject, JSX } from 'react';
1
+ import * as ThreeWebGPU from 'three/webgpu';
2
+ import { WebGPURenderer, WebGPURendererParameters, RenderTarget } from 'three/webgpu';
3
+ import { M as MutableOrReadonlyParameters$1, a as MathRepresentation$1, V as VectorRepresentation$1, b as MathTypes$1, c as MathType$1, d as MathProps$1, e as Vector2$1, f as Vector3$1, g as Vector4$1, C as Color$1, L as Layers$1, Q as Quaternion$1, E as Euler$1, h as Matrix3$1, i as Matrix4$1, R as RaycastableRepresentation$1, j as EventProps$1, G as GeometryTransformProps$1, k as GeometryProps$1, T as TSLNodeInput$1, N as NodeProps$1, l as ReactProps$1, m as ConstructorRepresentation, n as ElementProps$1, o as ThreeElement$1, p as ThreeToJSXElements$1, O as Object3DMethod$1, q as ThreeElementsOf$1, r as ElementOf$1, J as RendererFactory, I as BaseRendererProps, s as CanvasProps, u as ReconcilerRoot, v as RenderTargetOptions } from '../shared/fiber.DAg-9ieU.js';
4
+ export { a7 as Args, a8 as ArgsProp, a4 as AttachFnType, a5 as AttachType, ae as BackgroundConfig, af as BackgroundProp, b8 as Block, $ as CameraProps, Y as CanvasSchedulerConfig, a6 as Catalogue, P as ColorManagementConfig, S as DefaultGLProps, X as DefaultRendererProps, aO as DisposeOptions, ay as Environment, aw as EnvironmentCube, aR as EnvironmentLoaderProps, av as EnvironmentMap, ax as EnvironmentPortal, au as EnvironmentProps, b9 as ErrorBoundary, am as Extensions, bD as FROM_REF, a2 as FiberRoot, bE as FromRefMarker, U as GLProps, ai as GLTFLike, ad as GlobalEffectType, ac as GlobalRenderCallback, ab as HostConfig, ak as InferLoadResult, a1 as InjectState, ag as InputLike, aa as Instance, a9 as InstanceProps, aH as IsObject, x as LegacyInternalState, y as LegacyRenderer, t as LegacyRootState, aj as LoaderInstance, ah as LoaderLike, al as LoaderResult, aI as MappedTextureType, bH as ONCE, H as OffscreenCanvas, bJ as OnceValue, b2 as Portal, aA as PresetsType, an as PrimaryCanvasEntry, ba as REACT_INTERNAL_PROPS, bi as RESERVED_PROPS, a0 as RenderProps, K as Renderer, Z as RendererConfigExtended, _ as RendererProps, a3 as Root, aL as Texture, aM as TextureInput, aN as TextureResult, aJ as UseTextureOptions, aP as UseTexturesReturn, z as WebGLDefaultProps, W as WebGLProps, A as WebGLShadowConfig, a$ as _roots, aU as addAfterEffect, aT as addEffect, aV as addTail, aX as advance, bn as applyProps, bk as attach, bd as buildGraph, bo as calculateDpr, aD as createEvents, w as createPointerEvents, b1 as createPortal, b4 as createStore, bl as detach, bm as diffProps, be as dispose, w as events, aY as extend, bb as findInitialRoot, b3 as flushSync, bF as fromRef, bf as getInstanceProps, ap as getPrimary, at as getPrimaryIds, bc as getRootState, B as getThree, bp as getUuidPrefix, bC as hasConstructor, ar as hasPrimary, D as hasThree, aW as invalidate, bh as invalidateInstance, bs as is, bv as isColorRepresentation, bB as isCopyable, bG as isFromRef, by as isLayers, bw as isObject3D, bK as isOnce, bt as isOrthographicCamera, bu as isRef, a_ as isRenderer, bx as isTexture, bz as isUniform, bA as isVectorLike, bI as once, bg as prepare, az as presetsObj, aZ as reconciler, ao as registerPrimary, aC as removeInteractivity, bj as resolve, aB as swapInteractivity, b0 as unmountComponentAtNode, as as unregisterPrimary, bq as updateCamera, br as updateFrustum, b7 as useBridge, aS as useEnvironment, aF as useGraph, aE as useInstanceHandle, b5 as useIsomorphicLayoutEffect, aG as useLoader, b6 as useMutableCallback, aK as useTexture, aQ as useTextures, aq as waitForPrimary, F as whenThree } from '../shared/fiber.DAg-9ieU.js';
5
+ import { a6 as RootState, a5 as InternalState, n as Properties } from '../shared/fiber.Bw8YnGg5.js';
6
+ export { A as Act, B as Bridge, C as Camera, i as ComputeFunction, w as Disposable, f as DomEvent, D as Dpr, v as EquConfig, g as EventHandlers, k as EventManager, E as Events, h as FilterFunction, $ as ForRegisteredRenderer, G as FrameCallback, z as FrameNextCallback, x as FrameNextState, y as FrameState, F as Frameloop, I as Intersection, e as IntersectionEvent, p as IsAllOptional, o as IsOptional, M as Mutable, N as NonFunctionKeys, u as ObjectMap, K as OcclusionSupport, O as Overwrite, c as Performance, l as PointerCaptureTarget, P as PointerState, a0 as R3FRenderTarget, a1 as R3FRendererSupport, Z as Register, _ as RegisteredRenderer, b as RenderCallback, Y as RendererProvider, Q as RendererSupport, R as RootExtension, d as RootStore, t as SetBlock, a as Size, S as Subscription, q as ThreeCamera, J as ThreeCore, T as ThreeEvent, H as ThreeNamespace, U as UnblockProps, V as Viewport, m as VisibilityEntry, W as WebGLSupport, L as WebGPUSupport, X as XRManager, j as XRPointerConfig, a3 as context, r as registerRootExtension, s as setRenderOverride, a2 as useStore } from '../shared/fiber.Bw8YnGg5.js';
7
+ import { Texture } from 'three';
9
8
  import { StoreApi } from 'zustand';
10
- import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
11
- import { FrameTimingState, FrameCallback as FrameCallback$1, SchedulerApi, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
9
+ import { FrameCallback, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
12
10
  export { AddPhaseOptions, FrameControls, FrameNextControls, FrameTimingState, RootOptions, Scheduler, SchedulerApi, UseFrameNextOptions, UseFrameOptions, getScheduler } from '@pmndrs/scheduler';
13
- import { Options } from 'react-use-measure';
14
- import * as react_jsx_runtime from 'react/jsx-runtime';
15
- import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
16
-
17
- function _mergeNamespaces(n, m) {
18
- m.forEach(function (e) {
19
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
20
- if (k !== 'default' && !(k in n)) {
21
- var d = Object.getOwnPropertyDescriptor(e, k);
22
- Object.defineProperty(n, k, d.get ? d : {
23
- enumerable: true,
24
- get: function () { return e[k]; }
25
- });
26
- }
27
- });
28
- });
29
- return Object.freeze(n);
30
- }
31
-
32
- /**
33
- * @fileoverview Internal Three.js re-exports - WEBGPU ONLY ENTRY
34
- *
35
- * Pure WebGPU path - no WebGL legacy.
36
- * Use this for the explicit webgpu import path: @react-three/fiber/webgpu
37
- *
38
- * This is for apps that want ONLY WebGPU with no legacy fallback.
39
- * Attempting to use WebGLRenderer will cause type/runtime errors (intentional).
40
- */
41
- declare const R3F_BUILD_LEGACY = false;
42
- declare const R3F_BUILD_WEBGPU = true;
43
-
44
- /** Lazily load the three Inspector. Keeps it out of the eager module graph — see note above. */
45
- declare function loadInspector(): Promise<typeof three_examples_jsm_inspector_Inspector_js.Inspector>;
46
- declare const WebGLRenderer: {
47
- new (): {};
48
- };
49
- type WebGLRendererParameters = never;
50
- type WebGLShadowMap = never;
51
-
52
- declare const WebGLRenderTarget: any;
53
-
54
- declare const WebGLCubeRenderTarget: any;
55
-
56
- var THREE = /*#__PURE__*/_mergeNamespaces({
57
- __proto__: null,
58
- CubeRenderTargetCompat: CubeRenderTarget,
59
- Inspector: Inspector,
60
- R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
61
- R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
62
- RenderTargetCompat: RenderTarget,
63
- WebGLCubeRenderTarget: WebGLCubeRenderTarget,
64
- WebGLRenderTarget: WebGLRenderTarget,
65
- WebGLRenderer: WebGLRenderer,
66
- WebGLRendererParameters: WebGLRendererParameters,
67
- WebGLShadowMap: WebGLShadowMap,
68
- loadInspector: loadInspector
69
- }, [three_webgpu]);
70
-
71
- //* Utility Types ==============================
72
-
73
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
74
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
75
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
76
- type Mutable<P> = { -readonly [K in keyof P]: P[K] }
77
- type IsOptional<T> = undefined extends T ? true : false
78
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
79
- ? IsOptional<First> extends true
80
- ? IsAllOptional<Rest>
81
- : false
82
- : true
83
-
84
- //* Camera Types ==============================
85
-
86
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
87
-
88
- //* Act Type ==============================
89
-
90
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
91
-
92
- //* Bridge & Block Types ==============================
93
-
94
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
95
-
96
- type SetBlock = false | Promise<null> | null
97
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
98
-
99
- //* Object Map Type ==============================
100
-
101
- /* Original version
102
- export interface ObjectMap {
103
- nodes: { [name: string]: THREE.Object3D }
104
- materials: { [name: string]: THREE.Material }
105
- meshes: { [name: string]: THREE.Mesh }
106
- }
107
- */
108
- /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
109
- It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
110
- I will keep the use here)
111
- https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
112
- His description is:
113
- The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
114
- */
115
- interface ObjectMap<
116
- T extends { nodes?: string; materials?: string; meshes?: string } = {
117
- nodes: string
118
- materials: string
119
- meshes: string
120
- },
121
- > {
122
- nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
123
- materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
124
- meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
125
- }
126
-
127
- //* Equality Config ==============================
128
-
129
- interface EquConfig {
130
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
131
- arrays?: 'reference' | 'shallow'
132
- /** Compare objects by reference equality a === b (default), or by shallow equality */
133
- objects?: 'reference' | 'shallow'
134
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
135
- strict?: boolean
136
- }
137
-
138
- //* Disposable Type ==============================
139
-
140
- interface Disposable {
141
- type?: string
142
- dispose?: () => void
143
- }
144
-
145
- //* Event-related Types =====================================
146
-
147
- interface Intersection extends THREE$1.Intersection {
148
- /** The event source (the object which registered the handler) */
149
- eventObject: THREE$1.Object3D
150
- }
151
-
152
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
153
-
154
- interface IntersectionEvent<TSourceEvent> extends Intersection {
155
- /** The event source (the object which registered the handler) */
156
- eventObject: THREE$1.Object3D
157
- /** An array of intersections */
158
- intersections: Intersection[]
159
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
160
- unprojectedPoint: THREE$1.Vector3
161
- /** Normalized event coordinates */
162
- pointer: THREE$1.Vector2
163
- /** pointerId of the original event for multiple pointer events */
164
- pointerId: number
165
- /** Delta between first click and this event */
166
- delta: number
167
- /** The ray that pierced it */
168
- ray: THREE$1.Ray
169
- /** The camera that was used by the raycaster */
170
- camera: Camera
171
- /** stopPropagation will stop underlying handlers from firing */
172
- stopPropagation: () => void
173
- /** The original host event */
174
- nativeEvent: TSourceEvent
175
- /** If the event was stopped by calling stopPropagation */
176
- stopped: boolean
177
- }
178
-
179
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
180
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
181
-
182
- /** DOM event handlers registered on the canvas element */
183
- interface Events {
184
- onClick: EventListener
185
- onContextMenu: EventListener
186
- onDoubleClick: EventListener
187
- onWheel: EventListener
188
- onPointerDown: EventListener
189
- onPointerUp: EventListener
190
- onPointerLeave: EventListener
191
- onPointerMove: EventListener
192
- onPointerCancel: EventListener
193
- onLostPointerCapture: EventListener
194
- onDragEnter: EventListener
195
- onDragLeave: EventListener
196
- onDragOver: EventListener
197
- onDrop: EventListener
198
- }
199
-
200
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
201
- interface EventHandlers {
202
- onClick?: (event: ThreeEvent<MouseEvent>) => void
203
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
204
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
205
- /** Fires continuously while dragging over the object */
206
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
207
- /** Fires once when drag enters the object */
208
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
209
- /** Fires once when drag leaves the object */
210
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
211
- /** Fires when drag misses this object (for objects that have drag handlers) */
212
- onDragOverMissed?: (event: DragEvent) => void
213
- /** Fires when a drop occurs on this object */
214
- onDrop?: (event: ThreeEvent<DragEvent>) => void
215
- /** Fires when a drop misses this object (for objects that have drop handlers) */
216
- onDropMissed?: (event: DragEvent) => void
217
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
218
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
219
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
220
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
221
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
222
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
223
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
224
- onPointerMissed?: (event: MouseEvent) => void
225
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
226
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
227
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
228
-
229
- //* Visibility Events --------------------------------
230
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
231
- onFramed?: (inView: boolean) => void
232
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
233
- onOccluded?: (occluded: boolean) => void
234
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
235
- onVisible?: (visible: boolean) => void
236
- }
237
-
238
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
239
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
240
-
241
- /** Configuration for XR pointer registration (controllers/hands) */
242
- interface XRPointerConfig {
243
- /** Ray origin (updated each frame by XR system) */
244
- ray: THREE$1.Ray
245
- /** Optional: custom compute function for this pointer */
246
- compute?: (state: RootState) => void
247
- /** Pointer type identifier */
248
- type: 'controller' | 'hand' | 'gaze'
249
- /** Which hand (for controller/hand types) */
250
- handedness?: 'left' | 'right'
251
- }
252
-
253
- interface EventManager<TTarget> {
254
- /** Determines if the event layer is active */
255
- enabled: boolean
256
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
257
- priority: number
258
- /** The compute function needs to set up the raycaster and an xy- pointer */
259
- compute?: ComputeFunction
260
- /** The filter can re-order or re-structure the intersections */
261
- filter?: FilterFunction
262
- /** The target node the event layer is tied to */
263
- connected?: TTarget
264
- /** All the pointer event handlers through which the host forwards native events */
265
- handlers?: Events
266
- /** Allows re-connecting to another target */
267
- connect?: (target: TTarget) => void
268
- /** Removes all existing events handlers from the target */
269
- disconnect?: () => void
270
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
271
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
272
- * @param pointerId - Optional pointer ID to update specific pointer only
273
- */
274
- update?: (pointerId?: number) => void
275
- /** Defer pointer move raycasting to frame start (default: true) */
276
- frameTimedRaycasts?: boolean
277
- /** Always fire raycaster immediately on scroll events (default: true) */
278
- alwaysFireOnScroll?: boolean
279
- /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
280
- updateOnFrame?: boolean
281
- /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
282
- flush?: () => void
283
- /** Register an XR pointer (controller/hand). Returns assigned pointerId */
284
- registerPointer?: (config: XRPointerConfig) => number
285
- /** Unregister an XR pointer */
286
- unregisterPointer?: (pointerId: number) => void
287
- }
288
-
289
- interface PointerCaptureTarget {
290
- intersection: Intersection
291
- target: Element
292
- }
293
-
294
- //* Visibility System Types =====================================
295
-
296
- /** Entry in the visibility registry for tracking object visibility state */
297
- interface VisibilityEntry {
298
- object: THREE$1.Object3D
299
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
300
- lastFramedState: boolean | null
301
- lastOccludedState: boolean | null
302
- lastVisibleState: boolean | null
303
- }
304
-
305
- //* Scheduler Types (useFrame) ==============================
306
- //
307
- // The generic, framework-agnostic scheduler types now live in @pmndrs/scheduler.
308
- // This file re-exports them and layers r3f's RootState-aware frame state on top,
309
- // so existing `#types` imports across the codebase keep resolving unchanged.
310
-
311
-
312
-
313
- // Frame State (r3f-specific) --------------------------------
314
-
315
- /**
316
- * State passed to useFrame callbacks (extends RootState with timing).
317
- */
318
- interface FrameNextState extends RootState, FrameTimingState {}
319
-
320
- /** Alias for FrameNextState */
321
- type FrameState = FrameNextState
322
-
323
- // Callback Types (r3f-specific) --------------------------------
324
-
325
- /**
326
- * Callback function for useFrame. Receives the full r3f RootState plus timing.
327
- */
328
- type FrameNextCallback = FrameCallback$1<RootState>
329
-
330
- /** Alias for FrameNextCallback */
331
- type FrameCallback = FrameNextCallback
332
-
333
- //* Buffer Types (useBuffers) ========================================
334
-
335
- /**
336
- * Buffer-like types for GPU compute and storage operations.
337
- * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
338
- *
339
- * @example
340
- * ```tsx
341
- * const { positions, velocities } = useBuffers(() => ({
342
- * positions: instancedArray(count, 'vec3'), // StorageBufferNode
343
- * velocities: new Float32Array(count * 3), // TypedArray
344
- * }), 'particles')
345
- * ```
346
- */
347
- type BufferLike =
348
- | Float32Array
349
- | Uint32Array
350
- | Int32Array
351
- | Float64Array
352
- | Uint8Array
353
- | Int8Array
354
- | Uint16Array
355
- | Int16Array
356
- | THREE$1.BufferAttribute // Base class for all buffer attributes
357
- | Node // TSL buffer nodes (instancedArray, storage)
358
-
359
- /** Flat record of buffer-like values (no nested scopes) */
360
- type BufferRecord = Record<string, BufferLike>
361
-
362
- /**
363
- * Buffer store that can contain both root-level buffers and scoped buffer objects.
364
- * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
365
- */
366
- type BufferStore = Record<string, BufferLike | BufferRecord>
367
-
368
- //* Node Types (useNodes) ========================================
369
-
370
- /**
371
- * Structural shape of a TSL node as stored on `state.nodes`.
372
- *
373
- * Deliberately minimal rather than three's nominal `Node`: in @types/three several node classes
374
- * TSL hands back (OperatorNode, ConstNode, ...) do not extend `Node` cleanly, so a `Node` bound
375
- * would reject values `useNodes` creators legitimately return. This is the same shape
376
- * `useNodes` already constrains creators to (`TSLNodeLike`).
377
- */
378
- interface NodeLike {
379
- uuid?: string
380
- nodeType?: string | null
381
- /** label method for chaining - sets the node's label and returns self */
382
- label?: ((label: string) => NodeLike) | string
383
- setName?: (name: string) => this
384
- }
385
-
386
- /** Flat record of TSL nodes (no nested scopes) */
387
- type NodeRecord = Record<string, NodeLike>
388
-
389
- /**
390
- * Node store that can contain both root-level nodes and scoped node objects.
391
- * Structure: { wobble: OperatorNode, fx: { blur: ShaderCallable } }
392
- */
393
- type NodeStore = Record<string, NodeLike | NodeRecord>
394
-
395
- //* Storage Types (useGPUStorage) ========================================
396
-
397
- /**
398
- * GPU storage types for texture-based storage operations.
399
- * Includes Three.js storage textures and TSL storage texture nodes.
400
- *
401
- * @example
402
- * ```tsx
403
- * const { heightMap } = useGPUStorage(() => ({
404
- * heightMap: new StorageTexture(512, 512),
405
- * }), 'terrain')
406
- * ```
407
- */
408
- type StorageLike =
409
- | StorageTexture // GPU storage texture
410
- | Data3DTexture // 3D texture (can be used as storage)
411
- | Node // TSL storage texture nodes (storageTexture)
412
-
413
- /** Flat record of storage-like values (no nested scopes) */
414
- type StorageRecord = Record<string, StorageLike>
415
-
416
- /**
417
- * Storage store that can contain both root-level storage and scoped storage objects.
418
- * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
419
- */
420
- type StorageStore = Record<string, StorageLike | StorageRecord>
421
-
422
- //* Renderer Types ========================================
423
-
424
- /** Default renderer type - union of WebGL and WebGPU renderers */
425
- type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer
426
-
427
- //* Core Store Types ========================================
428
-
429
- type Subscription = {
430
- ref: React$1.RefObject<RenderCallback>
431
- priority: number
432
- store: RootStore
433
- }
434
-
435
- /** Per-pointer state for multi-touch and XR support */
436
- type PointerState = {
437
- /** Objects currently hovered by this pointer */
438
- hovered: Map<string, ThreeEvent<DomEvent>>
439
- /** Objects capturing this pointer */
440
- captured: Map<THREE$1.Object3D, PointerCaptureTarget>
441
- /** Initial click position [x, y] */
442
- initialClick: [x: number, y: number]
443
- /** Objects hit on initial click */
444
- initialHits: THREE$1.Object3D[]
445
- }
446
-
447
- type Dpr = number | [min: number, max: number]
448
-
449
- interface Size {
450
- width: number
451
- height: number
452
- top: number
453
- left: number
454
- }
455
-
456
- type Frameloop = 'always' | 'demand' | 'never'
457
-
458
- interface Viewport extends Size {
459
- /** The initial pixel ratio */
460
- initialDpr: number
461
- /** Current pixel ratio */
462
- dpr: number
463
- /** size.width / viewport.width */
464
- factor: number
465
- /** Camera distance */
466
- distance: number
467
- /** Camera aspect ratio: width / height */
468
- aspect: number
469
- }
470
-
471
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
472
-
473
- interface Performance {
474
- /** Current performance normal, between min and max */
475
- current: number
476
- /** How low the performance can go, between 0 and max */
477
- min: number
478
- /** How high the performance can go, between min and max */
479
- max: number
480
- /** Time until current returns to max in ms */
481
- debounce: number
482
- /** Sets current to min, puts the system in regression */
483
- regress: () => void
484
- }
485
-
486
- interface InternalState {
487
- interaction: THREE$1.Object3D[]
488
- subscribers: Subscription[]
489
- /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
490
- pointerMap: Map<number, PointerState>
491
- /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
492
- pointerDirty: Map<number, DomEvent>
493
- /** Last event received (for events.update() compatibility) */
494
- lastEvent: React$1.RefObject<DomEvent | null>
495
- /** @deprecated Use pointerMap.get(pointerId).hovered instead */
496
- hovered: Map<string, ThreeEvent<DomEvent>>
497
- /** @deprecated Use pointerMap.get(pointerId).captured instead */
498
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
499
- /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
500
- initialClick: [x: number, y: number]
501
- /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
502
- initialHits: THREE$1.Object3D[]
503
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
504
- visibilityRegistry: Map<string, VisibilityEntry>
505
- /** Whether occlusion queries are enabled (WebGPU only) */
506
- occlusionEnabled: boolean
507
- /** Reference to the invisible occlusion observer mesh */
508
- occlusionObserver: THREE$1.Mesh | null
509
- /** Cached occlusion results from render pass - keyed by Object3D */
510
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
511
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
512
- helperGroup: THREE$1.Group | null
513
- active: boolean
514
- priority: number
515
- frames: number
516
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
517
- /** Internal renderer storage - use state.renderer or state.gl to access */
518
- actualRenderer: R3FRenderer
519
- /** Global scheduler reference (for useFrame hook) */
520
- scheduler: SchedulerApi | null
521
- /** This root's unique ID in the global scheduler */
522
- rootId?: string
523
- /** Function to unregister this root from the global scheduler */
524
- unregisterRoot?: () => void
525
- /** Container for child attachment (scene for root, original container for portals) */
526
- container?: THREE$1.Object3D
527
- /**
528
- * The CanvasTarget this root sizes and renders through.
529
- *
530
- * A primary (`<Canvas id>`) owns the renderer's default target -- the one three itself built
531
- * around the canvas element -- so sizing it is sizing the renderer. A secondary owns a target
532
- * R3F created for its own element. Either way there is exactly one target per canvas element,
533
- * and the canvas-target job makes it the renderer's active one before this root renders.
534
- * Absent on WebGL and on an id-less WebGPU canvas, where the renderer is sized directly.
535
- * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
536
- */
537
- canvasTarget?: CanvasTarget
538
- /**
539
- * Set when this root's canvas target has been resized and the backend's cached render pass
540
- * descriptor (which holds a depth-stencil view built once per canvas) is therefore stale.
541
- *
542
- * Flushed by the canvas-target job in the `start` phase, which is the only place this root's
543
- * target is guaranteed to be the renderer's active one — `backend.updateSize()` operates on
544
- * whatever `getCanvasTarget()` returns, so calling it from the resize subscription would
545
- * invalidate some other canvas's descriptor instead.
546
- *
547
- * @see https://github.com/pmndrs/react-three-fiber/issues/3847
548
- */
549
- canvasTargetSizeDirty?: boolean
550
- /**
551
- * Whether multi-canvas rendering is active.
552
- * True when any canvas uses `renderer={{ primaryCanvas: 'id' }}` to share a renderer.
553
- * When true, setCanvasTarget is called before each render.
554
- */
555
- isMultiCanvas?: boolean
556
- /**
557
- * Whether this canvas is a secondary canvas sharing another's renderer.
558
- * True when `target` prop is used.
559
- */
560
- isSecondary?: boolean
561
- /**
562
- * The id of the primary canvas this secondary canvas targets.
563
- * Only set when isSecondary is true.
564
- */
565
- targetId?: string
566
- /**
567
- * Function to unregister this primary canvas from the registry.
568
- * Only set when this canvas has an `id` prop.
569
- */
570
- unregisterPrimary?: () => void
571
- /** Whether canvas dimensions are forced to even numbers */
572
- forceEven?: boolean
573
- }
574
-
575
- interface XRManager {
576
- connect: () => void
577
- disconnect: () => void
578
- }
579
-
580
- //* Root State Interface ====================================
581
-
582
- interface RootState {
583
- /** Set current state */
584
- set: StoreApi<RootState>['setState']
585
- /** Get current state */
586
- get: StoreApi<RootState>['getState']
587
- /**
588
- * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
589
- * - For primary/independent canvases: points to its own store (self-reference)
590
- * - For secondary canvases: points to the primary canvas's store
591
- *
592
- * Hooks like useNodes/useUniforms should read from primaryStore to ensure
593
- * consistent shared state across all canvases sharing a renderer.
594
- */
595
- primaryStore: RootStore
596
- /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
597
- gl: THREE$1.WebGLRenderer
598
- /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
599
- renderer: R3FRenderer
600
- /** Inspector of the webGPU Renderer. Init in the canvas */
601
- inspector: any // Inspector type from three/webgpu
602
-
603
- /** Default camera */
604
- camera: ThreeCamera
605
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
606
- frustum: THREE$1.Frustum
607
- /** Whether to automatically update the frustum each frame (default: true) */
608
- autoUpdateFrustum: boolean
609
- /** Default scene (may be overridden in portals to point to the portal container) */
610
- scene: THREE$1.Scene
611
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
612
- rootScene: THREE$1.Scene
613
- /** Default raycaster */
614
- raycaster: THREE$1.Raycaster
615
- /** Event layer interface, contains the event handler and the node they're connected to */
616
- events: EventManager<any>
617
- /** XR interface */
618
- xr: XRManager
619
- /** Currently used controls */
620
- controls: THREE$1.EventDispatcher | null
621
- /** Normalized event coordinates */
622
- pointer: THREE$1.Vector2
623
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
624
- mouse: THREE$1.Vector2
625
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
626
- textureColorSpace: THREE$1.ColorSpace
627
- /** Render loop flags */
628
- frameloop: Frameloop
629
- performance: Performance
630
- /** Reactive pixel-size of the canvas */
631
- size: Size
632
- /** Reactive size of the viewport in threejs units */
633
- viewport: Viewport & {
634
- getCurrentViewport: (
635
- camera?: ThreeCamera,
636
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
637
- size?: Size,
638
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
639
- }
640
- /** Flags the canvas for render, but doesn't render in itself */
641
- invalidate: (frames?: number, stackFrames?: boolean) => void
642
- /** Advance (render) one step */
643
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
644
- /** Shortcut to setting the event layer */
645
- setEvents: (events: Partial<EventManager<any>>) => void
646
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
647
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
648
- /** Shortcut to manual setting the pixel ratio */
649
- setDpr: (dpr: Dpr) => void
650
- /** Shortcut to setting frameloop flags. No args resets to 'always'. */
651
- setFrameloop: (frameloop?: Frameloop) => void
652
- /** Set error state to propagate to error boundary */
653
- setError: (error: Error | null) => void
654
- /** Current error state (null when no error) */
655
- error: Error | null
656
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
657
- uniforms: UniformStore
658
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
659
- nodes: NodeStore
660
- /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
661
- buffers: BufferStore
662
- /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
663
- gpuStorage: StorageStore
664
- /** Global Texture registry (key → Texture, usually keyed by URL) - use useTextures() hook for access + lifecycle */
665
- textures: Map<string, THREE$1.Texture>
666
- /** Internal: refcount per texture key, driven by mounted useTexture consumers (registry enrollment is on by default) */
667
- _textureRefs: Map<string, number>
668
- /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
669
- renderPipeline: ThreeRenderPipeline | null
670
- /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
671
- passes: PassRecord
672
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
673
- _hmrVersion: number
674
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
675
- _sizeImperative: boolean
676
- /** Internal: stored size props from Canvas for reset functionality */
677
- _sizeProps: { width?: number; height?: number } | null
678
- /** When the canvas was clicked but nothing was hit */
679
- onPointerMissed?: (event: MouseEvent) => void
680
- /** When a dragover event has missed any target */
681
- onDragOverMissed?: (event: DragEvent) => void
682
- /** When a drop event has missed any target */
683
- onDropMissed?: (event: DragEvent) => void
684
- /** If this state model is layered (via createPortal) then this contains the previous layer */
685
- previousRoot?: RootStore
686
- /** Internals */
687
- internal: InternalState
688
- // flags for triggers
689
- // if we are using the webGl renderer, this will be true
690
- isLegacy: boolean
691
- // regardless of renderer, if the system supports webGpu, this will be true
692
- webGPUSupported: boolean
693
- //if we are on native
694
- isNative: boolean
695
- }
696
-
697
- type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
698
-
699
- //* Base Renderer Types =====================================
700
-
701
- // Shim for OffscreenCanvas since it was removed from DOM types
702
- interface OffscreenCanvas$1 extends EventTarget {}
703
-
704
- interface BaseRendererProps {
705
- canvas: HTMLCanvasElement | OffscreenCanvas$1
706
- powerPreference?: 'high-performance' | 'low-power' | 'default'
707
- antialias?: boolean
708
- alpha?: boolean
709
- }
710
-
711
- type RendererFactory<TRenderer, TParams> =
712
- | TRenderer
713
- | ((defaultProps: TParams) => TRenderer)
714
- | ((defaultProps: TParams) => Promise<TRenderer>)
715
-
716
- interface Renderer {
717
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
718
- }
719
-
720
- //* Color Management Config ==============================
721
-
722
- /**
723
- * Color management configuration shared by both WebGL and WebGPU renderers.
724
- */
725
- interface ColorManagementConfig {
726
- /**
727
- * Color space assigned to 8-bit input textures (color maps).
728
- * Defaults to sRGB. Most textures are authored in sRGB.
729
- * @default THREE.SRGBColorSpace
730
- */
731
- textureColorSpace?: THREE$1.ColorSpace
732
- }
733
-
734
- //* WebGL Renderer Props ==============================
735
-
736
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
737
- canvas: HTMLCanvasElement | OffscreenCanvas$1
738
- }
739
-
740
- type GLProps =
741
- | Renderer
742
- | ((defaultProps: DefaultGLProps) => Renderer)
743
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
744
- | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
745
-
746
- //* WebGPU Renderer Props ==============================
747
-
748
- type DefaultRendererProps = {
749
- canvas: HTMLCanvasElement | OffscreenCanvas$1
750
- [key: string]: any
751
- }
752
-
753
- /**
754
- * Canvas-level scheduler configuration.
755
- * Controls render timing relative to other canvases.
756
- */
757
- interface CanvasSchedulerConfig {
758
- /**
759
- * Run this Canvas root before the referenced Canvas root id(s).
760
- */
761
- before?: string | string[]
762
- /**
763
- * Run this Canvas root after the referenced Canvas root id(s).
764
- */
765
- after?: string | string[]
766
- /**
767
- * Numeric root order. Lower values run first.
768
- */
769
- order?: number
770
- /**
771
- * Limit this Canvas's default render job (frames per second).
772
- */
773
- fps?: number
774
- }
775
-
776
- /**
777
- * Extended renderer configuration for multi-canvas support and color management.
778
- */
779
- interface RendererConfigExtended extends ColorManagementConfig {
780
- /** Share renderer from another canvas (WebGPU only) */
781
- primaryCanvas?: string
782
- /** Canvas-level scheduler options */
783
- scheduler?: CanvasSchedulerConfig
784
- }
785
-
786
- type RendererProps =
787
- | any // WebGPURenderer
788
- | ((defaultProps: DefaultRendererProps) => any)
789
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
790
- | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
791
-
792
- //* Camera Props ==============================
793
-
794
- type CameraProps = (
795
- | THREE$1.Camera
796
- | Partial<
797
- ThreeElement<typeof THREE$1.Camera> &
798
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
799
- ThreeElement<typeof THREE$1.OrthographicCamera>
800
- >
801
- ) & {
802
- /** Flags the camera as manual, putting projection into your own hands */
803
- manual?: boolean
804
- }
805
-
806
- //* Render Props ==============================
807
-
808
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
809
- /**
810
- * Unique identifier for multi-canvas renderer sharing.
811
- * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
812
- * Also sets the HTML `id` attribute on the canvas element.
813
- * @example <Canvas id="main-viewer">...</Canvas>
814
- */
815
- id?: string
816
- /**
817
- * Share the renderer from another canvas instead of creating a new one.
818
- * Pass the `id` of the primary canvas to share its WebGPURenderer.
819
- * Only available with WebGPU (not legacy WebGL).
820
- *
821
- * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
822
- * @internal
823
- */
824
- primaryCanvas?: string
825
- /**
826
- * Canvas-level scheduler options. Controls render timing relative to other canvases.
827
- *
828
- * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
829
- * @internal
830
- */
831
- scheduler?: CanvasSchedulerConfig
832
- /** A threejs renderer instance or props that go into the default renderer */
833
- gl?: GLProps
834
- /** A WebGPU renderer instance or props that go into the default renderer */
835
- renderer?: RendererProps
836
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
837
- size?: Size
838
- /**
839
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
840
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
841
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
842
- */
843
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
844
- /** Creates an orthographic camera */
845
- orthographic?: boolean
846
- /**
847
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
848
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
849
- */
850
- frameloop?: Frameloop
851
- /**
852
- * R3F performance options for adaptive performance.
853
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
854
- */
855
- performance?: Partial<Omit<Performance, 'regress'>>
856
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
857
- dpr?: Dpr
858
- /** Props that go into the default raycaster */
859
- raycaster?: Partial<THREE$1.Raycaster>
860
- /** A `THREE.Scene` instance or props that go into the default scene */
861
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
862
- /** A `THREE.Camera` instance or props that go into the default camera */
863
- camera?: CameraProps
864
- /** An R3F event manager to manage elements' pointer events */
865
- events?: (store: RootStore) => EventManager<HTMLElement>
866
- /** Callback after the canvas has rendered (but not yet committed) */
867
- onCreated?: (state: RootState) => void
868
- /** Response for pointer clicks that have missed any target */
869
- onPointerMissed?: (event: MouseEvent) => void
870
- /** Response for dragover events that have missed any target */
871
- onDragOverMissed?: (event: DragEvent) => void
872
- /** Response for drop events that have missed any target */
873
- onDropMissed?: (event: DragEvent) => void
874
- /** Whether to automatically update the frustum each frame (default: true) */
875
- autoUpdateFrustum?: boolean
876
- /**
877
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
878
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
879
- * Only works with WebGPU renderer - WebGL will log a warning.
880
- */
881
- occlusion?: boolean
882
- /** Internal: stored size props from Canvas for reset functionality */
883
- _sizeProps?: { width?: number; height?: number } | null
884
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
885
- forceEven?: boolean
886
- }
887
-
888
- //* Reconciler Root ==============================
889
-
890
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
891
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
892
- render: (element: ReactNode) => RootStore
893
- unmount: () => void
894
- }
895
-
896
- //* Inject State ==============================
897
-
898
- type InjectState = Partial<
899
- Omit<RootState, 'events'> & {
900
- events?: {
901
- enabled?: boolean
902
- priority?: number
903
- compute?: ComputeFunction
904
- connected?: any
905
- }
906
- /**
907
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
908
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
909
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
910
- */
911
- injectScene?: boolean
912
- }
913
- >
914
-
915
- //* Reconciler Types ==============================
916
-
917
- // FiberRoot is an opaque internal React type - we define it locally
918
- // to avoid bundling @types/react-reconciler which causes absolute path issues
919
- type FiberRoot = any
920
-
921
- interface Root {
922
- fiber: FiberRoot
923
- store: RootStore
924
- }
925
-
926
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
927
- type AttachType<O = any> = string | AttachFnType<O>
928
-
929
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
930
-
931
- interface Catalogue {
932
- [name: string]: ConstructorRepresentation
933
- }
934
-
935
- // TODO: handle constructor overloads
936
- // https://github.com/pmndrs/react-three-fiber/pull/2931
937
- // https://github.com/microsoft/TypeScript/issues/37079
938
- type Args<T> = T extends ConstructorRepresentation
939
- ? T extends typeof Color$1
940
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
941
- : ConstructorParameters<T>
942
- : any[]
943
-
944
- type ArgsProp<P> = P extends ConstructorRepresentation
945
- ? IsAllOptional<ConstructorParameters<P>> extends true
946
- ? { args?: Args<P> }
947
- : { args: Args<P> }
948
- : { args: unknown[] }
949
-
950
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
951
- object?: T
952
- dispose?: null
953
- attach?: AttachType<T>
954
- onUpdate?: (self: T) => void
955
- }
956
-
957
- interface Instance<O = any> {
958
- root: RootStore
959
- type: string
960
- parent: Instance | null
961
- children: Instance[]
962
- props: InstanceProps<O> & Record<string, unknown>
963
- object: O & { __r3f?: Instance<O> }
964
- eventCount: number
965
- handlers: Partial<EventHandlers>
966
- attach?: AttachType<O>
967
- previousAttach?: any
968
- isHidden: boolean
969
- /** Set of props that have been applied via once() */
970
- appliedOnce?: Set<string>
971
- }
972
-
973
- interface HostConfig {
974
- type: string
975
- props: Instance['props']
976
- container: RootStore
977
- instance: Instance
978
- textInstance: void
979
- suspenseInstance: Instance
980
- hydratableInstance: never
981
- formInstance: never
982
- publicInstance: Instance['object']
983
- hostContext: {}
984
- childSet: never
985
- timeoutHandle: number | undefined
986
- noTimeout: -1
987
- TransitionStatus: null
988
- }
989
- declare global {
990
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
991
- }
992
-
993
- //* Loop Types ==============================
994
-
995
- type GlobalRenderCallback = (timestamp: number) => void
996
-
997
- type GlobalEffectType = 'before' | 'after' | 'tail'
998
-
999
- declare const presetsObj: {
1000
- apartment: string;
1001
- city: string;
1002
- dawn: string;
1003
- forest: string;
1004
- lobby: string;
1005
- night: string;
1006
- park: string;
1007
- studio: string;
1008
- sunset: string;
1009
- warehouse: string;
1010
- };
1011
- type PresetsType = keyof typeof presetsObj;
1012
-
1013
- //* Background Types ==============================
1014
-
1015
- /**
1016
- * Expanded object form for background configuration.
1017
- * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
1018
- */
1019
- interface BackgroundConfig {
1020
- /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
1021
- preset?: PresetsType
1022
- /** Files for cube texture (6 faces) or single HDR/EXR */
1023
- files?: string | string[]
1024
- /** Separate files for scene.background (visual backdrop) */
1025
- backgroundMap?: string | string[]
1026
- backgroundRotation?: Euler$1 | [number, number, number]
1027
- backgroundBlurriness?: number
1028
- backgroundIntensity?: number
1029
- /** Separate files for scene.environment (PBR lighting/reflections) */
1030
- envMap?: string | string[]
1031
- environmentRotation?: Euler$1 | [number, number, number]
1032
- environmentIntensity?: number
1033
- path?: string
1034
- extensions?: (loader: Loader) => void
1035
- }
1036
-
1037
- /**
1038
- * Background prop type for Canvas.
1039
- *
1040
- * String detection priority:
1041
- * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1042
- * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1043
- * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1044
- *
1045
- * @example Color
1046
- * ```tsx
1047
- * <Canvas background="red" />
1048
- * <Canvas background="#ff0000" />
1049
- * <Canvas background={0xff0000} />
1050
- * ```
1051
- *
1052
- * @example Preset
1053
- * ```tsx
1054
- * <Canvas background="city" />
1055
- * ```
1056
- *
1057
- * @example URL
1058
- * ```tsx
1059
- * <Canvas background="/path/to/env.hdr" />
1060
- * <Canvas background="./sky.jpg" />
1061
- * ```
1062
- *
1063
- * @example Object form
1064
- * ```tsx
1065
- * <Canvas background={{
1066
- * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1067
- * backgroundMap: 'path/to/sky.jpg',
1068
- * envMap: 'path/to/lighting.hdr',
1069
- * backgroundBlurriness: 0.5,
1070
- * }} />
1071
- * ```
1072
- */
1073
- type BackgroundProp =
1074
- | ColorRepresentation // "red", "#ff0000", 0xff0000
1075
- | string // URL or preset
1076
- | BackgroundConfig // Expanded object form
1077
-
1078
- //* Canvas Types ==============================
1079
-
1080
- interface CanvasProps
1081
- extends
1082
- Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1083
- React$1.HTMLAttributes<HTMLDivElement> {
1084
- children?: React$1.ReactNode
1085
- ref?: React$1.Ref<HTMLCanvasElement>
1086
- /** Canvas fallback content, similar to img's alt prop */
1087
- fallback?: React$1.ReactNode
1088
- /**
1089
- * Options to pass to useMeasure.
1090
- * @see https://github.com/pmndrs/react-use-measure#api
1091
- */
1092
- resize?: Options
1093
- /** The target where events are being subscribed to, default: the div that wraps canvas */
1094
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1095
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1096
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1097
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1098
- hmr?: boolean
1099
- /** Canvas resolution width in pixels. If omitted, uses container width. */
1100
- width?: number
1101
- /** Canvas resolution height in pixels. If omitted, uses container height. */
1102
- height?: number
1103
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1104
- forceEven?: boolean
1105
- /**
1106
- * Scene background configuration.
1107
- * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1108
- * @see BackgroundProp for full documentation and examples
1109
- */
1110
- background?: BackgroundProp
1111
- }
1112
-
1113
- //* Loader Types ==============================
1114
-
1115
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1116
-
1117
- // Define a loader-like interface that matches THREE.Loader's load signature
1118
- // This works for both generic and non-generic THREE.Loader instances
1119
- interface LoaderLike {
1120
- load(
1121
- url: InputLike,
1122
- onLoad?: (result: any) => void,
1123
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
1124
- onError?: (error: unknown) => void,
1125
- ): any
1126
- }
1127
-
1128
- type GLTFLike = { scene: THREE$1.Object3D }
1129
-
1130
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1131
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1132
-
1133
- // Infer result type from the load method's callback parameter
1134
- type InferLoadResult<T> = T extends {
1135
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1136
- }
1137
- ? R
1138
- : T extends ConstructorRepresentation<any>
1139
- ? InstanceType<T> extends {
1140
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1141
- }
1142
- ? R
1143
- : any
1144
- : any
1145
-
1146
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1147
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1148
-
1149
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1150
- loader: LoaderInstance<T>,
1151
- ) => void
1152
-
1153
- //* Renderer Props ========================================
1154
-
1155
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1156
-
1157
- type WebGLProps =
1158
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1159
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1160
-
1161
- interface WebGLShadowConfig {
1162
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1163
- }
1164
-
1165
- //* Legacy-specific Types ========================================
1166
-
1167
- /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1168
- type LegacyRenderer = THREE$1.WebGLRenderer
1169
-
1170
- /** Legacy internal state with narrowed renderer type */
1171
- interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1172
- actualRenderer: THREE$1.WebGLRenderer
1173
- }
1174
-
1175
- /**
1176
- * Legacy-specific RootState with narrowed renderer type.
1177
- * Automatically used when importing from `@react-three/fiber/legacy`.
1178
- *
1179
- * @example
1180
- * ```tsx
1181
- * import { useThree } from '@react-three/fiber/legacy'
1182
- *
1183
- * function MyComponent() {
1184
- * const { renderer } = useThree()
1185
- * // renderer is typed as THREE.WebGLRenderer
1186
- * renderer.shadowMap.enabled = true
1187
- * }
1188
- * ```
1189
- */
1190
- interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1191
- /** The WebGL renderer instance */
1192
- renderer: THREE$1.WebGLRenderer
1193
- /** Internals with WebGL renderer */
1194
- internal: LegacyInternalState
1195
- }
1196
-
1197
- //* RenderTarget Types ==============================
1198
-
1199
-
1200
- type RenderTargetOptions = RenderTargetOptions$1
1201
-
1202
- //* Global Types ==============================
1203
-
1204
- declare global {
1205
- /**
1206
- * Uniform node type.
1207
- *
1208
- * This is three's own `UniformNode`, not a re-declaration of it. It previously was a
1209
- * hand-rolled `interface UniformNode<T> extends Node { value: T }`, which shadowed the real
1210
- * exported type globally — so R3F's ~58 references resolved to an approximation that was
1211
- * missing members three actually ships (`setName` among them) and had drifted to the wrong
1212
- * arity when three made `UniformNode` two-parameter.
1213
- *
1214
- * three's signature is `UniformNode<TNodeType, TValue>`. R3F only ever varies the value type,
1215
- * so the node type is fixed to `unknown` and the single parameter is kept for call-site
1216
- * ergonomics. The result is three's structural type, so members stay in sync with the
1217
- * installed three instead of needing to be mirrored by hand.
1218
- */
1219
- type UniformNode<T = unknown> = three_webgpu.UniformNode<UniformNodeTypeFor<T>, T>
1220
-
1221
- /**
1222
- * three's node type name for a uniform value type, mirroring the `uniform()` overloads.
1223
- * A `UniformNode<number>` is a `Node<'float'>`, so TSL math (`.mul`, `.add`, ...) accepts it.
1224
- * Unknown or unlisted value types resolve to `unknown`, which TSL math rejects: narrow with
1225
- * `as UniformNode<number>` (or the matching value type) at the call site.
1226
- */
1227
- type UniformNodeTypeFor<T> = T extends number
1228
- ? 'float'
1229
- : T extends boolean
1230
- ? 'bool'
1231
- : T extends three_webgpu.Color
1232
- ? 'color'
1233
- : T extends three_webgpu.Vector2
1234
- ? 'vec2'
1235
- : T extends three_webgpu.Vector3
1236
- ? 'vec3'
1237
- : T extends three_webgpu.Vector4
1238
- ? 'vec4'
1239
- : T extends three_webgpu.Matrix2
1240
- ? 'mat2'
1241
- : T extends three_webgpu.Matrix3
1242
- ? 'mat3'
1243
- : T extends three_webgpu.Matrix4
1244
- ? 'mat4'
1245
- : unknown
1246
-
1247
- /**
1248
- * ShaderCallable - the return type of Fn()
1249
- * A callable shader function node that can be invoked with parameters.
1250
- * The function returns a ShaderNodeObject when called.
1251
- *
1252
- * @example
1253
- * ```tsx
1254
- * // Define a shader function
1255
- * const blendColorFn = Fn(([color1, color2, factor]) => {
1256
- * return mix(color1, color2, factor)
1257
- * })
1258
- *
1259
- * // Type when retrieving from nodes store
1260
- * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1261
- *
1262
- * // Or with specific return type
1263
- * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1264
- * ```
1265
- */
1266
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1267
-
1268
- /**
1269
- * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1270
- * This is the common return type for TSL operations (add, mul, sin, etc.)
1271
- *
1272
- * @example
1273
- * ```tsx
1274
- * const { wobble } = nodes as { wobble: ShaderNodeRef }
1275
- * ```
1276
- */
1277
- type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1278
-
1279
- /**
1280
- * TSLNodeType - Union of all common TSL node types
1281
- * Used by ScopedStore to properly type node access from the store.
1282
- *
1283
- * Includes:
1284
- * - Node: base Three.js node type
1285
- * - ShaderCallable: function nodes created with Fn()
1286
- * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1287
- *
1288
- * @example
1289
- * ```tsx
1290
- * // In useLocalNodes, nodes are typed as TSLNodeType
1291
- * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1292
- * positionNode: nodes.myPosition, // Works - Node is in union
1293
- * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1294
- * }))
1295
- *
1296
- * // Can narrow with type guard or assertion when needed
1297
- * if (typeof blendColorFn === 'function') {
1298
- * blendColorFn(someColor, 0.5)
1299
- * }
1300
- * ```
1301
- */
1302
- type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1303
-
1304
- /** Flat record of uniform nodes (no nested scopes) */
1305
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1306
-
1307
- /**
1308
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
1309
- * Used by state.uniforms which has structure like:
1310
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1311
- */
1312
- type UniformStore = Record<string, UniformNode | UniformRecord>
1313
-
1314
- /**
1315
- * Helper to safely access a uniform node from the store.
1316
- * Use this when accessing state.uniforms to get proper typing.
1317
- * @example
1318
- * const uTime = uniforms.uTime as UniformNode<number>
1319
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1320
- */
1321
- type GetUniform<T = unknown> = UniformNode<T>
1322
-
1323
- /**
1324
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1325
- * Supports:
1326
- * - Primitives: number, string (color), boolean
1327
- * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1328
- * - Plain objects: { x, y, z, w } converted to vectors
1329
- * - TSL nodes: color(), vec3(), float() for type casting
1330
- * - UniformNode: existing uniforms (reused as-is)
1331
- */
1332
- type UniformValue =
1333
- | number
1334
- | string
1335
- | boolean
1336
- | three_webgpu.Color
1337
- | three_webgpu.Vector2
1338
- | three_webgpu.Vector3
1339
- | three_webgpu.Vector4
1340
- | three_webgpu.Matrix3
1341
- | three_webgpu.Matrix4
1342
- | three_webgpu.Euler
1343
- | three_webgpu.Quaternion
1344
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1345
- | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1346
- | Node // TSL nodes like color(), vec3(), float() for type casting
1347
- | UniformNode
1348
-
1349
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1350
- type UniformInputRecord = Record<string, UniformValue>
1351
- }
1352
-
1353
- //* Module Augmentation ==============================
1354
-
1355
- declare module 'three/tsl' {
1356
- /**
1357
- * Fn with array parameter destructuring
1358
- * @example Fn(([uv, skew]) => { ... })
1359
- */
1360
- export function Fn<R extends Node = Node>(
1361
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1362
- ): ShaderCallable<R>
1363
-
1364
- /**
1365
- * Fn with object parameter destructuring
1366
- * @example Fn(({ color, intensity }) => { ... })
1367
- */
1368
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1369
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1370
- ): ShaderCallable<R>
1371
-
1372
- /**
1373
- * Fn with array params + layout
1374
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1375
- */
1376
- export function Fn<R extends Node = Node>(
1377
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1378
- layout: { layout?: unknown },
1379
- ): ShaderCallable<R>
1380
-
1381
- /**
1382
- * Fn with object params + layout
1383
- */
1384
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1385
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1386
- layout: { layout?: unknown },
1387
- ): ShaderCallable<R>
1388
- }
1389
-
1390
- declare global {
1391
- /**
1392
- * three's own render pipeline type. Named here so the rest of R3F refers to three's shape
1393
- * rather than `any`. three r183 renamed `PostProcessing` to `RenderPipeline`; our peer floor
1394
- * is r185, so the new name is the only one.
1395
- */
1396
- type ThreeRenderPipeline = three_webgpu.RenderPipeline
1397
-
1398
- /**
1399
- * The pass `useRenderPipeline` creates for you: three's own `PassNode`, as returned by
1400
- * `pass(scene, camera)` from `three/tsl`. Referenced from three so members like
1401
- * `getTextureNode`, `setMRT` and `dispose` track the installed version.
1402
- */
1403
- type ScenePassNode = three_webgpu.PassNode
1404
-
1405
- /**
1406
- * Pass record - stores TSL pass nodes for render pipeline.
1407
- *
1408
- * `scenePass` is the only key the library owns. It is optional here because this is also the
1409
- * shape of `state.passes`, which is `{}` before the pipeline exists and again after `reset()`
1410
- * or `clearPasses()`. Inside the callbacks it is always present; see
1411
- * {@link RenderPipelineCallbackState}.
1412
- *
1413
- * Every other key is user-registered, via a callback's return value. Those are TSL nodes of
1414
- * any kind, not only passes: texture reads of an MRT attachment, effect nodes, extra
1415
- * `pass()` instances. `Node` is the common base, so that is the bound. Narrow at the call
1416
- * site when you need a member, e.g. `passes.velocity as TextureNode`.
1417
- */
1418
- interface PassRecord {
1419
- scenePass?: ScenePassNode
1420
- [key: string]: three_webgpu.Node
1421
- }
1422
-
1423
- /**
1424
- * State passed to pipeline callbacks after the active pipeline has been created.
1425
- *
1426
- * `passes.scenePass` is required here: the hook installs the default scene pass before either
1427
- * callback runs, so callbacks can use it without a guard or a cast.
1428
- *
1429
- * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
1430
- * the legacy renderer before either callback can run, so a callback never sees WebGL.
1431
- */
1432
- type RenderPipelineCallbackState = RootState & {
1433
- renderPipeline: ThreeRenderPipeline
1434
- passes: PassRecord & { scenePass: ScenePassNode }
1435
- renderer: three_webgpu.WebGPURenderer
1436
- isLegacy: false
1437
- }
1438
-
1439
- /**
1440
- * What a callback may return to register entries into `state.passes`.
1441
- *
1442
- * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
1443
- * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
1444
- * store entry would leave the store pointing at a node the hook never disposes, and the hook
1445
- * disposing a pass nothing references. So returning it is a type error.
1446
- */
1447
- type RegisteredPasses = Record<string, three_webgpu.Node> & { scenePass?: never }
1448
-
1449
- /** Setup callback - runs first to configure MRT, create additional passes */
1450
- type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1451
-
1452
- /** Main callback - runs second to configure outputNode, create effect passes */
1453
- type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1454
-
1455
- /** The imperative half of useRenderPipeline's return value, present in every state */
1456
- interface UseRenderPipelineActions {
1457
- /** Current passes from state */
1458
- passes: PassRecord
1459
- /** Clear all passes from state */
1460
- clearPasses: () => void
1461
- /** Reset RenderPipeline entirely (clears PP + passes) */
1462
- reset: () => void
1463
- /** Re-run setup/main callbacks with current closure values */
1464
- rebuild: () => void
1465
- }
1466
-
1467
- /**
1468
- * Return type for useRenderPipeline hook, discriminated on `isReady`.
1469
- *
1470
- * `if (isReady)` narrows `renderPipeline` to non-null, which is what the docs already tell
1471
- * callers to check. `passes.scenePass` deliberately stays optional in the ready branch:
1472
- * `clearPasses()` empties the record while leaving the pipeline in place.
1473
- */
1474
- type UseRenderPipelineReturn = UseRenderPipelineActions &
1475
- (
1476
- | {
1477
- /** True when RenderPipeline is configured and ready */
1478
- isReady: true
1479
- /** RenderPipeline instance */
1480
- renderPipeline: ThreeRenderPipeline
1481
- }
1482
- | {
1483
- /** False until the pipeline has been created */
1484
- isReady: false
1485
- /** Not initialized yet, or torn down by reset() */
1486
- renderPipeline: null
1487
- }
1488
- )
1489
- }
1490
-
1491
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1492
-
1493
- interface MathRepresentation {
1494
- set(...args: number[]): any
1495
- }
1496
- interface VectorRepresentation extends MathRepresentation {
1497
- setScalar(value: number): any
1498
- }
1499
- type MathTypes = MathRepresentation | Euler$2 | Color$2
1500
-
1501
- type MathType<T extends MathTypes> = T extends Color$2
1502
- ? Args<typeof Color$2> | ColorRepresentation$1
1503
- : T extends VectorRepresentation | Layers$1 | Euler$2
1504
- ? T | MutableOrReadonlyParameters<T['set']> | number
1505
- : T | MutableOrReadonlyParameters<T['set']>
1506
-
1507
- type MathProps<P> = {
1508
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1509
- }
1510
-
1511
- type Vector2 = MathType<Vector2$1>
1512
- type Vector3 = MathType<Vector3$1>
1513
- type Vector4 = MathType<Vector4$1>
1514
- type Color = MathType<Color$2>
1515
- type Layers = MathType<Layers$1>
1516
- type Quaternion = MathType<Quaternion$1>
1517
- type Euler = MathType<Euler$2>
1518
- type Matrix3 = MathType<Matrix3$1>
1519
- type Matrix4 = MathType<Matrix4$1>
1520
-
1521
- interface RaycastableRepresentation {
1522
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1523
- }
1524
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1525
-
1526
- /**
1527
- * Props for geometry transform methods that can be called with `once()`.
1528
- * These methods modify the geometry in-place and only make sense to call once on mount.
1529
- *
1530
- * @example
1531
- * import { once } from '@react-three/fiber'
1532
- *
1533
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1534
- * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1535
- * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1536
- */
1537
- interface GeometryTransformProps {
1538
- /** Rotate the geometry about the X axis (radians). Use with once(). */
1539
- rotateX?: number
1540
- /** Rotate the geometry about the Y axis (radians). Use with once(). */
1541
- rotateY?: number
1542
- /** Rotate the geometry about the Z axis (radians). Use with once(). */
1543
- rotateZ?: number
1544
- /** Translate the geometry (x, y, z). Use with once(). */
1545
- translate?: [x: number, y: number, z: number]
1546
- /** Scale the geometry (x, y, z). Use with once(). */
1547
- scale?: [x: number, y: number, z: number]
1548
- /** Center the geometry based on bounding box. Use with once(). */
1549
- center?: true
1550
- /** Apply a Matrix4 transformation. Use with once(). */
1551
- applyMatrix4?: Matrix4$1
1552
- /** Apply a Quaternion rotation. Use with once(). */
1553
- applyQuaternion?: Quaternion$1
1554
- }
1555
-
1556
- type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1557
-
1558
- /**
1559
- * Workaround for @types/three TSL node type issues.
1560
- * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1561
- * This transforms `Node | null` properties to accept any object with node-like shape.
1562
- */
1563
- type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1564
-
1565
- /**
1566
- * For node material properties (colorNode, positionNode, etc.), accept broader types
1567
- * since @types/three has broken inheritance for TSL node subclasses.
1568
- */
1569
- type NodeProps<P> = {
1570
- [K in keyof P as P[K] extends Node | null ? K : never]?: TSLNodeInput
1571
- }
1572
-
1573
- interface ReactProps<P> {
1574
- children?: React.ReactNode
1575
- ref?: React.Ref<P>
1576
- key?: React.Key
1577
- }
1578
-
1579
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1580
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1581
- >
1582
-
1583
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1584
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1585
- >
1586
-
1587
- type ThreeToJSXElements<T extends Record<string, any>> = {
1588
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1589
- }
1590
-
1591
- type ThreeExports = typeof import('three/webgpu')
1592
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1593
-
1594
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1595
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1596
- // Conflicts with DOM types can be accessed through a three* prefix
1597
- threeAudio: ThreeElementsImpl['audio']
1598
- threeSource: ThreeElementsImpl['source']
1599
- threeLine: ThreeElementsImpl['line']
1600
- threePath: ThreeElementsImpl['path']
1601
- }
1602
-
1603
- declare module 'react' {
1604
- namespace JSX {
1605
- interface IntrinsicElements extends ThreeElements {}
1606
- }
1607
- }
1608
-
1609
- declare module 'react/jsx-runtime' {
1610
- namespace JSX {
1611
- interface IntrinsicElements extends ThreeElements {}
1612
- }
1613
- }
1614
-
1615
- declare module 'react/jsx-dev-runtime' {
1616
- namespace JSX {
1617
- interface IntrinsicElements extends ThreeElements {}
1618
- }
1619
- }
1620
-
1621
- type three_d_Color = Color;
1622
- type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1623
- type three_d_Euler = Euler;
1624
- type three_d_EventProps<P> = EventProps<P>;
1625
- type three_d_GeometryProps<P> = GeometryProps<P>;
1626
- type three_d_GeometryTransformProps = GeometryTransformProps;
1627
- type three_d_Layers = Layers;
1628
- type three_d_MathProps<P> = MathProps<P>;
1629
- type three_d_MathRepresentation = MathRepresentation;
1630
- type three_d_MathType<T extends MathTypes> = MathType<T>;
1631
- type three_d_MathTypes = MathTypes;
1632
- type three_d_Matrix3 = Matrix3;
1633
- type three_d_Matrix4 = Matrix4;
1634
- type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1635
- type three_d_NodeProps<P> = NodeProps<P>;
1636
- type three_d_Quaternion = Quaternion;
1637
- type three_d_RaycastableRepresentation = RaycastableRepresentation;
1638
- type three_d_ReactProps<P> = ReactProps<P>;
1639
- type three_d_TSLNodeInput = TSLNodeInput;
1640
- type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1641
- type three_d_ThreeElements = ThreeElements;
1642
- type three_d_ThreeElementsImpl = ThreeElementsImpl;
1643
- type three_d_ThreeExports = ThreeExports;
1644
- type three_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
1645
- type three_d_Vector2 = Vector2;
1646
- type three_d_Vector3 = Vector3;
1647
- type three_d_Vector4 = Vector4;
1648
- type three_d_VectorRepresentation = VectorRepresentation;
1649
- declare namespace three_d {
1650
- export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_GeometryProps as GeometryProps, three_d_GeometryTransformProps as GeometryTransformProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_NodeProps as NodeProps, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_TSLNodeInput as TSLNodeInput, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1651
- }
1652
-
1653
- /**
1654
- * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1655
- *
1656
- * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1657
- * a single WebGPURenderer using Three.js CanvasTarget API.
1658
- *
1659
- * Primary canvas: Has `id` prop, creates its own renderer, registers here
1660
- * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
1661
- */
1662
-
1663
- interface PrimaryCanvasEntry {
1664
- /** The WebGPURenderer instance owned by this primary canvas */
1665
- renderer: WebGPURenderer;
1666
- /** The zustand store for this canvas */
1667
- store: RootStore;
1668
- }
1669
- /**
1670
- * Register a primary canvas that can be targeted by secondary canvases.
1671
- *
1672
- * @param id - Unique identifier for this primary canvas
1673
- * @param renderer - The WebGPURenderer owned by this canvas
1674
- * @param store - The zustand store for this canvas
1675
- * @returns Cleanup function to unregister on unmount
1676
- */
1677
- declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1678
- /**
1679
- * Get a registered primary canvas by id.
1680
- *
1681
- * @param id - The id of the primary canvas to look up
1682
- * @returns The primary canvas entry or undefined if not found
1683
- */
1684
- declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1685
- /**
1686
- * Wait for a primary canvas to be registered.
1687
- * Returns immediately if already registered, otherwise waits.
1688
- *
1689
- * @param id - The id of the primary canvas to wait for
1690
- * @param timeout - Optional timeout in ms (default: 5000)
1691
- * @returns Promise that resolves with the primary canvas entry
1692
- */
1693
- declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1694
- /**
1695
- * Check if a primary canvas with the given id exists.
1696
- *
1697
- * @param id - The id to check
1698
- * @returns True if a primary canvas with this id is registered
1699
- */
1700
- declare function hasPrimary(id: string): boolean;
1701
- /**
1702
- * Unregister a primary canvas. Called on unmount.
1703
- *
1704
- * @param id - The id of the primary canvas to unregister
1705
- */
1706
- declare function unregisterPrimary(id: string): void;
1707
- /**
1708
- * Get all registered primary canvas ids. Useful for debugging.
1709
- */
1710
- declare function getPrimaryIds(): string[];
1711
-
1712
- type EnvironmentLoaderProps = {
1713
- files?: string | string[];
1714
- path?: string;
1715
- preset?: PresetsType;
1716
- extensions?: (loader: Loader$1) => void;
1717
- colorSpace?: ColorSpace;
1718
- };
1719
- /**
1720
- * Loads environment textures for reflections and lighting.
1721
- * Supports HDR files, presets, and cubemaps.
1722
- *
1723
- * @example Basic usage
1724
- * ```jsx
1725
- * const texture = useEnvironment({ preset: 'sunset' })
1726
- * ```
1727
- */
1728
- declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1729
- declare namespace useEnvironment {
1730
- var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1731
- var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1732
- }
1733
- /**
1734
- * Options accepted by `useEnvironment.preload`.
1735
- *
1736
- * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
1737
- * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
1738
- * advertise an option this function silently ignores.
1739
- *
1740
- * This previously read `Omit<…, 'encoding'>` — omitting a key that does not exist on
1741
- * `EnvironmentLoaderProps`, a leftover from three's pre-`colorSpace` `encoding` API. That made the
1742
- * type equivalent to the full props, so `colorSpace` was accepted and then dropped on the floor.
1743
- */
1744
- type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
1745
- type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1746
-
1747
- /**
1748
- * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1749
- *
1750
- * @property children - React children to render into custom environment portal
1751
- * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1752
- * @property near - Near clipping plane for cube camera (default: 0.1)
1753
- * @property far - Far clipping plane for cube camera (default: 1000)
1754
- * @property resolution - Resolution of the cube render target (default: 256)
1755
- * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1756
- *
1757
- * @property blur - @deprecated Use backgroundBlurriness instead
1758
- * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1759
- * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1760
- * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1761
- * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1762
- * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1763
- *
1764
- * @property map - Pre-existing texture to use as environment map
1765
- * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1766
- * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1767
- * @property ground - Ground projection settings. Use true for defaults or object with:
1768
- * - height: Height of camera used to create env map (default: 15)
1769
- * - radius: Radius of the world (default: 60)
1770
- * - scale: Scale of backside projected sphere (default: 1000)
1771
- *
1772
- * Additional loader props:
1773
- * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1774
- * @property path - Base path for file loading
1775
- * @property extensions - Texture extensions override
1776
- */
1777
- type EnvironmentProps = {
1778
- children?: React$1.ReactNode;
1779
- frames?: number;
1780
- near?: number;
1781
- far?: number;
1782
- resolution?: number;
1783
- background?: boolean | 'only';
1784
- /** deprecated, use backgroundBlurriness */
1785
- blur?: number;
1786
- backgroundBlurriness?: number;
1787
- backgroundIntensity?: number;
1788
- backgroundRotation?: Euler;
1789
- environmentIntensity?: number;
1790
- environmentRotation?: Euler;
1791
- map?: Texture$1;
1792
- preset?: PresetsType;
1793
- scene?: Scene | React$1.RefObject<Scene>;
1794
- ground?: boolean | {
1795
- radius?: number;
1796
- height?: number;
1797
- scale?: number;
1798
- };
1799
- /** Solid color for background (alternative to files/preset) */
1800
- color?: ColorRepresentation$1;
1801
- /** Separate files for background (when different from environment files) */
1802
- backgroundFiles?: string | string[];
1803
- } & EnvironmentLoaderProps;
1804
- /**
1805
- * Internal component that applies a pre-existing texture as environment map.
1806
- * Sets scene.environment and optionally scene.background.
1807
- *
1808
- * @example
1809
- * ```jsx
1810
- * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1811
- * ```
1812
- */
1813
- declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1814
- /**
1815
- * Internal component that loads environment textures from files or presets.
1816
- * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1817
- * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1818
- *
1819
- * @example With preset
1820
- * ```jsx
1821
- * <EnvironmentCube preset="sunset" />
1822
- * ```
1823
- *
1824
- * @example From HDR file
1825
- * ```jsx
1826
- * <EnvironmentCube files="environment.hdr" />
1827
- * ```
1828
- *
1829
- * @example From gainmap (smallest footprint)
1830
- * ```jsx
1831
- * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1832
- * ```
1833
- *
1834
- * @example From cube faces
1835
- * ```jsx
1836
- * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1837
- * ```
1838
- */
1839
- declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1840
- /**
1841
- * Internal component that renders custom environment using a portal and cube camera.
1842
- * Renders children into an off-buffer and films with a cube camera to create environment map.
1843
- * Can be static (frames=1) or animated (frames=Infinity).
1844
- *
1845
- * @example Custom environment with sphere
1846
- * ```jsx
1847
- * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1848
- * <mesh scale={100}>
1849
- * <sphereGeometry args={[1, 64, 64]} />
1850
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1851
- * </mesh>
1852
- * </EnvironmentPortal>
1853
- * ```
1854
- *
1855
- * @example Animated environment
1856
- * ```jsx
1857
- * <EnvironmentPortal frames={Infinity} resolution={256}>
1858
- * <Float>
1859
- * <mesh />
1860
- * </Float>
1861
- * </EnvironmentPortal>
1862
- * ```
1863
- *
1864
- * @example Mixed with preset
1865
- * ```jsx
1866
- * <EnvironmentPortal preset="warehouse">
1867
- * <mesh />
1868
- * </EnvironmentPortal>
1869
- * ```
1870
- */
1871
- declare function EnvironmentPortal({ children, near, far, resolution, frames, map, background, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, scene, files, path, preset, extensions, }: EnvironmentProps): react_jsx_runtime.JSX.Element;
1872
- declare module '@react-three/fiber' {
1873
- interface ThreeElements {
1874
- groundProjectedEnvImpl: ThreeElement<typeof GroundedSkybox>;
1875
- }
1876
- }
1877
- /**
1878
- * Sets up a global environment map for PBR materials and backgrounds.
1879
- * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1880
- *
1881
- * Supports multiple input methods:
1882
- * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1883
- * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1884
- * - **Texture**: Pre-existing cube texture via `map` prop
1885
- * - **Custom Scene**: Render children into environment using portal and cube camera
1886
- * - **Ground Projection**: Project environment onto ground plane
1887
- *
1888
- * @remarks
1889
- * - Preset property is NOT meant for production and may fail (relies on CDNs)
1890
- * - Gainmap format has the smallest file footprint
1891
- * - Use `frames={Infinity}` for animated environments with low resolution for performance
1892
- * - Ground projection places models on the "ground" within the environment map
1893
- * - Supports self-hosting with @pmndrs/assets using dynamic imports
1894
- *
1895
- * @example Basic preset usage
1896
- * ```jsx
1897
- * <Environment preset="sunset" />
1898
- * ```
1899
- *
1900
- * @example From HDR file
1901
- * ```jsx
1902
- * <Environment files="/hdr/environment.hdr" />
1903
- * ```
1904
- *
1905
- * @example From gainmap (smallest footprint)
1906
- * ```jsx
1907
- * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1908
- * ```
1909
- *
1910
- * @example With self-hosted assets
1911
- * ```jsx
1912
- * import { suspend } from 'suspend-react'
1913
- * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1914
- *
1915
- * <Environment files={suspend(city)} />
1916
- * ```
1917
- *
1918
- * @example From existing texture
1919
- * ```jsx
1920
- * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1921
- * ```
1922
- *
1923
- * @example Custom environment scene
1924
- * ```jsx
1925
- * <Environment background near={1} far={1000} resolution={256}>
1926
- * <mesh scale={100}>
1927
- * <sphereGeometry args={[1, 64, 64]} />
1928
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1929
- * </mesh>
1930
- * </Environment>
1931
- * ```
1932
- *
1933
- * @example Animated environment
1934
- * ```jsx
1935
- * <Environment frames={Infinity} resolution={256}>
1936
- * <Float>
1937
- * <mesh />
1938
- * </Float>
1939
- * </Environment>
1940
- * ```
1941
- *
1942
- * @example Mixed custom scene with preset
1943
- * ```jsx
1944
- * <Environment background preset="warehouse">
1945
- * <mesh />
1946
- * </Environment>
1947
- * ```
1948
- *
1949
- * @example With ground projection
1950
- * ```jsx
1951
- * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1952
- * ```
1953
- *
1954
- * @example As background only
1955
- * ```jsx
1956
- * <Environment background="only" preset="sunset" />
1957
- * ```
1958
- *
1959
- * @example With rotation and intensity
1960
- * ```jsx
1961
- * <Environment
1962
- * background
1963
- * backgroundBlurriness={0.5}
1964
- * backgroundIntensity={0.8}
1965
- * backgroundRotation={[0, Math.PI / 2, 0]}
1966
- * environmentIntensity={1.2}
1967
- * environmentRotation={[0, Math.PI / 4, 0]}
1968
- * preset="studio"
1969
- * />
1970
- * ```
1971
- */
1972
- declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1973
-
1974
- /**
1975
- * Moves every trace of interactivity from one object to its replacement, for reconstruction.
1976
- *
1977
- * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
1978
- * instance. Removing the old object from the interaction state and registering the new one from
1979
- * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
1980
- * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
1981
- * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
1982
- * swap the user never asked to see (#3744).
1983
- *
1984
- * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
1985
- * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
1986
- *
1987
- * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
1988
- * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
1989
- * cannot outlive the object it described.
1990
- */
1991
- declare function swapInteractivity(store: RootStore, object: Object3D, newObject: Object3D): void;
1992
- declare function removeInteractivity(store: RootStore, object: Object3D): void;
1993
- declare function createEvents(store: RootStore): {
1994
- handlePointer: (name: string) => (event: DomEvent) => void;
1995
- flushDeferredPointers: () => void;
1996
- processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1997
- };
1998
- /** Default R3F event manager for web */
1999
- declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
2000
-
2001
- /**
2002
- * Gets or creates a memoized loader instance from a loader constructor or returns the loader if it's already an instance.
2003
- * This allows external code to access loader methods like abort().
2004
- */
2005
- declare function getLoader<L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(Proto: L): L extends ConstructorRepresentation<infer T> ? T : L;
2006
- /**
2007
- * Synchronously loads and caches assets with a three loader.
2008
- *
2009
- * Note: this hook's caller must be wrapped with `React.Suspense`
2010
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
2011
- */
2012
- declare function useLoader<I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike): I extends any[] ? LoaderResult<L>[] : LoaderResult<L>;
2013
- declare namespace useLoader {
2014
- var preload: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike) => void;
2015
- var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
2016
- var loader: typeof getLoader;
2017
- }
2018
-
2019
- declare const IsObject: (url: unknown) => url is Record<string, string>;
2020
- type TextureArray<T> = T extends string[] ? Texture$1[] : never;
2021
- type TextureRecord<T> = T extends Record<string, string> ? {
2022
- [key in keyof T]: Texture$1;
2023
- } : never;
2024
- type SingleTexture<T> = T extends string ? Texture$1 : never;
2025
- type MappedTextureType<T extends string[] | string | Record<string, string>> = TextureArray<T> | TextureRecord<T> | SingleTexture<T>;
2026
- /** Options for useTexture hook */
2027
- type UseTextureOptions<Url extends string[] | string | Record<string, string>> = {
2028
- /** Callback when texture(s) finish loading */
2029
- onLoad?: (texture: MappedTextureType<Url>) => void;
2030
- /**
2031
- * Register the texture(s) in R3F's global texture registry for access via useTextures().
2032
- * When true (the default):
2033
- * - Textures persist until explicitly disposed
2034
- * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
2035
- *
2036
- * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
2037
- * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
2038
- *
2039
- * Pass `false` to opt out of registry enrollment entirely.
2040
- * @default true
2041
- */
2042
- cache?: boolean;
2043
- };
2044
- /**
2045
- * Load texture(s) using Three's TextureLoader with Suspense support.
2046
- *
2047
- * @param input - URL string, array of URLs, or object mapping keys to URLs
2048
- * @param optionsOrOnLoad - Options object or legacy onLoad callback
2049
- *
2050
- * @example
2051
- * ```tsx
2052
- * // Single texture
2053
- * const diffuse = useTexture('/textures/diffuse.png')
2054
- *
2055
- * // Multiple textures (array)
2056
- * const [diffuse, normal] = useTexture(['/diffuse.png', '/normal.png'])
2057
- *
2058
- * // Named textures (object)
2059
- * const { diffuse, normal } = useTexture({
2060
- * diffuse: '/diffuse.png',
2061
- * normal: '/normal.png'
2062
- * })
2063
- *
2064
- * // Textures are registered in the global registry by default — the same texture
2065
- * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
2066
- * const diffuse = useTexture('/diffuse.png')
2067
- * diffuse.colorSpace = THREE.SRGBColorSpace
2068
- *
2069
- * // Another component gets the SAME texture with colorSpace already set
2070
- * const sameDiffuse = useTexture('/diffuse.png')
2071
- *
2072
- * // Opt out of registry enrollment for a one-off texture
2073
- * const scratch = useTexture('/scratch.png', { cache: false })
2074
- *
2075
- * // Access the registry directly
2076
- * const { get } = useTextures()
2077
- * const cached = get('/diffuse.png')
2078
- * ```
2079
- */
2080
- declare function useTexture<Url extends string[] | string | Record<string, string>>(input: Url, optionsOrOnLoad?: UseTextureOptions<Url> | ((texture: MappedTextureType<Url>) => void)): MappedTextureType<Url>;
2081
- declare namespace useTexture {
2082
- var preload: (url: string | string[]) => void;
2083
- var clear: (input: string | string[]) => void;
2084
- }
2085
- declare const Texture: ({ children, input, onLoad, cache, }: {
2086
- children?: (texture: ReturnType<typeof useTexture>) => ReactNode;
2087
- input: Parameters<typeof useTexture>[0];
2088
- onLoad?: Parameters<typeof useTexture>[1];
2089
- cache?: boolean;
2090
- }) => react_jsx_runtime.JSX.Element;
2091
-
2092
- /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
2093
- type TextureInput = string | string[] | Record<string, string>;
2094
- /** Result of a `get()` read, mirroring the input shape. */
2095
- type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
2096
- [K in keyof Input]: Texture$1 | undefined;
2097
- };
2098
- /** Options for `dispose()`. */
2099
- interface DisposeOptions {
2100
- /** Dispose even if the texture still has active references (default false). */
2101
- force?: boolean;
2102
- }
2103
- interface UseTexturesReturn {
2104
- /** The live registry Map (key → Texture). Treat as read-only. */
2105
- readonly all: Map<string, Texture$1>;
2106
- /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2107
- get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2108
- /** Check whether a key exists in the registry. */
2109
- has(key: string): boolean;
2110
- /**
2111
- * Register a texture (or a record of textures) that has no URL — e.g. a render
2112
- * target or procedural texture. URL-loaded textures are registered automatically
2113
- * by `useTexture` (registry enrollment is on by default).
2114
- */
2115
- add(key: string, texture: Texture$1): void;
2116
- add(record: Record<string, Texture$1>): void;
2117
- /**
2118
- * Dispose a texture's GPU resources and remove it from the registry.
2119
- * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2120
- * skipped (with a warning) unless `{ force: true }` is passed.
2121
- * @returns true if disposed, false if skipped.
2122
- */
2123
- dispose(key: string, options?: DisposeOptions): boolean;
2124
- /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2125
- disposeAll(): void;
2126
- }
2127
- /**
2128
- * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
2129
- *
2130
- * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2131
- * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2132
- * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2133
- *
2134
- * The returned handle is **reactive**: the calling component re-renders when the registry
2135
- * changes. Pass a selector to scope the subscription to a single read.
2136
- *
2137
- * @example
2138
- * ```tsx
2139
- * // Load + register once (anywhere in the tree) — registered by default
2140
- * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2141
- *
2142
- * // Reach them from another component — record form lands straight into a material
2143
- * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2144
- * return <meshStandardMaterial map={map} normalMap={normalMap} />
2145
- *
2146
- * // A set of heightmaps at once
2147
- * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
2148
- *
2149
- * // Register a non-URL texture (render target / procedural)
2150
- * useTextures().add('rt-main', renderTarget.texture)
2151
- *
2152
- * // Deliberate GPU cleanup (refcount-aware; force to override)
2153
- * useTextures().dispose('/diffuse.jpg')
2154
- * useTextures().disposeAll() // scene teardown
2155
- * ```
2156
- *
2157
- * @remarks
2158
- * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2159
- * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2160
- * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2161
- * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2162
- * `useTexture`.
2163
- */
2164
- declare function useTextures(): UseTexturesReturn;
2165
- declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
2166
-
2167
- /**
2168
- * Creates a render target compatible with the current renderer.
2169
- *
2170
- * - Legacy build: Returns WebGLRenderTarget
2171
- * - WebGPU build: Returns RenderTarget
2172
- * - Default build: Returns whichever matches the active renderer
2173
- *
2174
- * @example
2175
- * ```tsx
2176
- * // Use canvas size
2177
- * const fbo = useRenderTarget()
2178
- *
2179
- * // Use canvas size with options
2180
- * const fbo = useRenderTarget({ samples: 4 })
2181
- *
2182
- * // Square render target
2183
- * const fbo = useRenderTarget(512)
2184
- *
2185
- * // Square render target with options
2186
- * const fbo = useRenderTarget(512, { depthBuffer: true })
2187
- *
2188
- * // Explicit dimensions
2189
- * const fbo = useRenderTarget(512, 256)
2190
- *
2191
- * // Explicit dimensions with options
2192
- * const fbo = useRenderTarget(512, 256, { samples: 4 })
2193
- * ```
2194
- */
2195
- declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget;
2196
- declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget;
2197
- declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget;
2198
-
2199
- /**
2200
- * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
2201
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usestore
2202
- */
2203
- declare function useStore(): RootStore;
2204
- /**
2205
- * Exposes an object's {@link Instance}.
2206
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
2207
- *
2208
- * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
2209
- */
2210
- declare function useInstanceHandle<T>(ref: React.RefObject<T>): React.RefObject<Instance<T>>;
2211
- /**
2212
- * Returns a node graph of an object with named nodes & materials.
2213
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
2214
- */
2215
- declare function useGraph(object: Object3D): ObjectMap;
2216
-
2217
- /**
2218
- * Adds a global render callback which is called each frame BEFORE rendering.
2219
- *
2220
- * @deprecated Use `useFrame(callback, { phase: 'start' })` instead.
2221
- * This function will be removed in a future version.
2222
- *
2223
- * @param callback - Function called each frame with timestamp
2224
- * @returns Unsubscribe function
2225
- *
2226
- * @example
2227
- * // OLD (deprecated)
2228
- * const unsub = addEffect((timestamp) => { ... })
2229
- *
2230
- * // NEW
2231
- * useFrame((state, delta) => { ... }, { phase: 'start' })
2232
- *
2233
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
2234
- */
2235
- declare function addEffect(callback: GlobalRenderCallback): () => void;
2236
- /**
2237
- * Adds a global after-render callback which is called each frame AFTER rendering.
2238
- *
2239
- * @deprecated Use `useFrame(callback, { phase: 'finish' })` instead.
2240
- * This function will be removed in a future version.
2241
- *
2242
- * @param callback - Function called each frame with timestamp
2243
- * @returns Unsubscribe function
2244
- *
2245
- * @example
2246
- * // OLD (deprecated)
2247
- * const unsub = addAfterEffect((timestamp) => { ... })
2248
- *
2249
- * // NEW
2250
- * useFrame((state, delta) => { ... }, { phase: 'finish' })
2251
- *
2252
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
2253
- */
2254
- declare function addAfterEffect(callback: GlobalRenderCallback): () => void;
2255
- /**
2256
- * Adds a global callback which is called when rendering stops.
2257
- *
2258
- * @deprecated Use `scheduler.onIdle(callback)` instead.
2259
- * This function will be removed in a future version.
2260
- *
2261
- * @param callback - Function called when rendering stops
2262
- * @returns Unsubscribe function
2263
- *
2264
- * @example
2265
- * // OLD (deprecated)
2266
- * const unsub = addTail((timestamp) => { ... })
2267
- *
2268
- * // NEW
2269
- * const { scheduler } = useFrame()
2270
- * const unsub = scheduler.onIdle((timestamp) => { ... })
2271
- *
2272
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
2273
- */
2274
- declare function addTail(callback: GlobalRenderCallback): () => void;
2275
- /**
2276
- * Invalidates the view, requesting a frame to be rendered.
2277
- * In demand mode, this triggers the scheduler to run frames.
2278
- *
2279
- * With a state argument, only that root's jobs run on the requested frames; other
2280
- * roots on 'demand' stay idle. Without one, every registered root is invalidated.
2281
- *
2282
- * @param state - Optional root state; targets the invalidation at that root
2283
- * @param frames - Number of frames to request (default: 1)
2284
- * @param stackFrames - If false, sets pendingFrames to frames. If true, adds to existing pendingFrames (default: false)
2285
- *
2286
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
2287
- */
2288
- declare function invalidate(state?: RootState, frames?: number, stackFrames?: boolean): void;
2289
- /**
2290
- * Advances the frameloop and runs render effects.
2291
- * Useful for when manually rendering via `frameloop="never"`.
2292
- *
2293
- * With a state argument, only that root is stepped. Without one, every
2294
- * registered root is stepped for backwards compatibility.
2295
- *
2296
- * @param timestamp - The timestamp to use for this frame
2297
- * @param runGlobalEffects - Ignored (kept for backwards compat, global effects always run)
2298
- * @param state - Optional root state; targets the manual step at that root
2299
- *
2300
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2301
- */
2302
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState): void;
2303
-
2304
- /* eslint-disable @definitelytyped/no-unnecessary-generics */
2305
- declare function ReactReconciler<
2306
- Type,
2307
- Props,
2308
- Container,
2309
- Instance,
2310
- TextInstance,
2311
- SuspenseInstance,
2312
- HydratableInstance,
2313
- FormInstance,
2314
- PublicInstance,
2315
- HostContext,
2316
- ChildSet,
2317
- TimeoutHandle,
2318
- NoTimeout,
2319
- TransitionStatus,
2320
- >(
2321
- /* eslint-enable @definitelytyped/no-unnecessary-generics */
2322
- config: ReactReconciler.HostConfig<
2323
- Type,
2324
- Props,
2325
- Container,
2326
- Instance,
2327
- TextInstance,
2328
- SuspenseInstance,
2329
- HydratableInstance,
2330
- FormInstance,
2331
- PublicInstance,
2332
- HostContext,
2333
- ChildSet,
2334
- TimeoutHandle,
2335
- NoTimeout,
2336
- TransitionStatus
2337
- >,
2338
- ): ReactReconciler.Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance>;
2339
-
2340
- declare namespace ReactReconciler {
2341
- interface HostConfig<
2342
- Type,
2343
- Props,
2344
- Container,
2345
- Instance,
2346
- TextInstance,
2347
- SuspenseInstance,
2348
- HydratableInstance,
2349
- FormInstance,
2350
- PublicInstance,
2351
- HostContext,
2352
- ChildSet,
2353
- TimeoutHandle,
2354
- NoTimeout,
2355
- TransitionStatus,
2356
- > {
2357
- // -------------------
2358
- // Modes
2359
- // -------------------
2360
- /**
2361
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2362
- *
2363
- * If your target platform is similar to the DOM and has methods similar to `appendChild`, `removeChild`, and so on, you'll want to use the **mutation mode**. This is the same mode used by React DOM, React ART, and the classic React Native renderer.
2364
- *
2365
- * ```js
2366
- * const HostConfig = {
2367
- * // ...
2368
- * supportsMutation: true,
2369
- * // ...
2370
- * }
2371
- * ```
2372
- *
2373
- * Depending on the mode, the reconciler will call different methods on your host config.
2374
- *
2375
- * If you're not sure which one you want, you likely need the mutation mode.
2376
- */
2377
- supportsMutation: boolean;
2378
-
2379
- /**
2380
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2381
- *
2382
- * If your target platform has immutable trees, you'll want the **persistent mode** instead. In that mode, existing nodes are never mutated, and instead every change clones the parent tree and then replaces the whole parent tree at the root. This is the node used by the new React Native renderer, codenamed "Fabric".
2383
- *
2384
- * ```js
2385
- * const HostConfig = {
2386
- * // ...
2387
- * supportsPersistence: true,
2388
- * // ...
2389
- * }
2390
- * ```
2391
- *
2392
- * Depending on the mode, the reconciler will call different methods on your host config.
2393
- *
2394
- * If you're not sure which one you want, you likely need the mutation mode.
2395
- */
2396
- supportsPersistence: boolean;
2397
-
2398
- // -------------------
2399
- // Core Methods
2400
- // -------------------
2401
-
2402
- /**
2403
- * This method should return a newly created node. For example, the DOM renderer would call `document.createElement(type)` here and then set the properties from `props`.
2404
- *
2405
- * You can use `rootContainer` to access the root container associated with that tree. For example, in the DOM renderer, this is useful to get the correct `document` reference that the root belongs to.
2406
- *
2407
- * The `hostContext` parameter lets you keep track of some information about your current place in the tree. To learn more about it, see `getChildHostContext` below.
2408
- *
2409
- * The `internalHandle` data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2410
- *
2411
- * This method happens **in the render phase**. It can (and usually should) mutate the node it has just created before returning it, but it must not modify any other nodes. It must not register any event handlers on the parent tree. This is because an instance being created doesn't guarantee it would be placed in the tree — it could be left unused and later collected by GC. If you need to do something when an instance is definitely in the tree, look at `commitMount` instead.
2412
- */
2413
- createInstance(
2414
- type: Type,
2415
- props: Props,
2416
- rootContainer: Container,
2417
- hostContext: HostContext,
2418
- internalHandle: OpaqueHandle,
2419
- ): Instance;
2420
-
2421
- /**
2422
- * Same as `createInstance`, but for text nodes. If your renderer doesn't support text nodes, you can throw here.
2423
- */
2424
- createTextInstance(
2425
- text: string,
2426
- rootContainer: Container,
2427
- hostContext: HostContext,
2428
- internalHandle: OpaqueHandle,
2429
- ): TextInstance;
2430
-
2431
- /**
2432
- * This method should mutate the `parentInstance` and add the child to its list of children. For example, in the DOM this would translate to a `parentInstance.appendChild(child)` call.
2433
- *
2434
- * This method happens **in the render phase**. It can mutate `parentInstance` and `child`, but it must not modify any other nodes. It's called while the tree is still being built up and not connected to the actual tree on the screen.
2435
- */
2436
- appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void;
2437
-
2438
- /**
2439
- * In this method, you can perform some final mutations on the `instance`. Unlike with `createInstance`, by the time `finalizeInitialChildren` is called, all the initial children have already been added to the `instance`, but the instance itself has not yet been connected to the tree on the screen.
2440
- *
2441
- * This method happens **in the render phase**. It can mutate `instance`, but it must not modify any other nodes. It's called while the tree is still being built up and not connected to the actual tree on the screen.
2442
- *
2443
- * There is a second purpose to this method. It lets you specify whether there is some work that needs to happen when the node is connected to the tree on the screen. If you return `true`, the instance will receive a `commitMount` call later. See its documentation below.
2444
- *
2445
- * If you don't want to do anything here, you should return `false`.
2446
- */
2447
- finalizeInitialChildren(
2448
- instance: Instance,
2449
- type: Type,
2450
- props: Props,
2451
- rootContainer: Container,
2452
- hostContext: HostContext,
2453
- ): boolean;
2454
-
2455
- /**
2456
- * Some target platforms support setting an instance's text content without manually creating a text node. For example, in the DOM, you can set `node.textContent` instead of creating a text node and appending it.
2457
- *
2458
- * If you return `true` from this method, React will assume that this node's children are text, and will not create nodes for them. It will instead rely on you to have filled that text during `createInstance`. This is a performance optimization. For example, the DOM renderer returns `true` only if `type` is a known text-only parent (like `'textarea'`) or if `props.children` has a `'string'` type. If you return `true`, you will need to implement `resetTextContent` too.
2459
- *
2460
- * If you don't want to do anything here, you should return `false`.
2461
- *
2462
- * This method happens **in the render phase**. Do not mutate the tree from it.
2463
- */
2464
- shouldSetTextContent(type: Type, props: Props): boolean;
2465
-
2466
- /**
2467
- * This method lets you return the initial host context from the root of the tree. See `getChildHostContext` for the explanation of host context.
2468
- *
2469
- * If you don't intend to use host context, you can return `null`.
2470
- *
2471
- * This method happens **in the render phase**. Do not mutate the tree from it.
2472
- */
2473
- getRootHostContext(rootContainer: Container): HostContext | null;
2474
-
2475
- /**
2476
- * Host context lets you track some information about where you are in the tree so that it's available inside `createInstance` as the `hostContext` parameter. For example, the DOM renderer uses it to track whether it's inside an HTML or an SVG tree, because `createInstance` implementation needs to be different for them.
2477
- *
2478
- * If the node of this `type` does not influence the context you want to pass down, you can return `parentHostContext`. Alternatively, you can return any custom object representing the information you want to pass down.
2479
- *
2480
- * If you don't want to do anything here, return `parentHostContext`.
2481
- *
2482
- * This method happens **in the render phase**. Do not mutate the tree from it.
2483
- */
2484
- getChildHostContext(parentHostContext: HostContext, type: Type, rootContainer: Container): HostContext;
2485
-
2486
- /**
2487
- * Determines what object gets exposed as a ref. You'll likely want to return the `instance` itself. But in some cases it might make sense to only expose some part of it.
2488
- *
2489
- * If you don't want to do anything here, return `instance`.
2490
- */
2491
- getPublicInstance(instance: Instance | TextInstance): PublicInstance;
2492
-
2493
- /**
2494
- * This method lets you store some information before React starts making changes to the tree on the screen. For example, the DOM renderer stores the current text selection so that it can later restore it. This method is mirrored by `resetAfterCommit`.
2495
- *
2496
- * Even if you don't want to do anything here, you need to return `null` from it.
2497
- */
2498
- prepareForCommit(containerInfo: Container): Record<string, any> | null;
2499
-
2500
- /**
2501
- * This method is called right after React has performed the tree mutations. You can use it to restore something you've stored in `prepareForCommit` — for example, text selection.
2502
- *
2503
- * You can leave it empty.
2504
- */
2505
- resetAfterCommit(containerInfo: Container): void;
2506
-
2507
- /**
2508
- * This method is called for a container that's used as a portal target. Usually you can leave it empty.
2509
- */
2510
- preparePortalMount(containerInfo: Container): void;
2511
-
2512
- /**
2513
- * You can proxy this to `setTimeout` or its equivalent in your environment.
2514
- */
2515
- scheduleTimeout(fn: (...args: unknown[]) => unknown, delay?: number): TimeoutHandle;
2516
-
2517
- /**
2518
- * You can proxy this to `clearTimeout` or its equivalent in your environment.
2519
- */
2520
- cancelTimeout(id: TimeoutHandle): void;
2521
-
2522
- /**
2523
- * This is a property (not a function) that should be set to something that can never be a valid timeout ID. For example, you can set it to `-1`.
2524
- */
2525
- noTimeout: NoTimeout;
2526
-
2527
- /**
2528
- * Set this to true to indicate that your renderer supports `scheduleMicrotask`. We use microtasks as part of our discrete event implementation in React DOM. If you're not sure if your renderer should support this, you probably should. The option to not implement `scheduleMicrotask` exists so that platforms with more control over user events, like React Native, can choose to use a different mechanism.
2529
- */
2530
- supportsMicrotasks?: boolean;
2531
-
2532
- /**
2533
- * Optional. You can proxy this to `queueMicrotask` or its equivalent in your environment.
2534
- */
2535
- scheduleMicrotask?(fn: () => unknown): void;
2536
-
2537
- /**
2538
- * This is a property (not a function) that should be set to `true` if your renderer is the main one on the page. For example, if you're writing a renderer for the Terminal, it makes sense to set it to `true`, but if your renderer is used *on top of* React DOM or some other existing renderer, set it to `false`.
2539
- */
2540
- isPrimaryRenderer: boolean;
2541
-
2542
- /**
2543
- * Whether the renderer shouldn't trigger missing `act()` warnings
2544
- */
2545
- warnsIfNotActing?: boolean;
2546
-
2547
- getInstanceFromNode(node: any): Fiber | null | undefined;
2548
-
2549
- beforeActiveInstanceBlur(): void;
2550
-
2551
- afterActiveInstanceBlur(): void;
2552
-
2553
- prepareScopeUpdate(scopeInstance: any, instance: any): void;
2554
-
2555
- getInstanceFromScope(scopeInstance: any): null | Instance;
2556
-
2557
- detachDeletedInstance(node: Instance): void;
2558
-
2559
- // -------------------
2560
- // Mutation Methods
2561
- // (optional)
2562
- // If you're using React in mutation mode (you probably do), you'll need to implement a few more methods.
2563
- // -------------------
2564
-
2565
- /**
2566
- * This method should mutate the `parentInstance` and add the child to its list of children. For example, in the DOM this would translate to a `parentInstance.appendChild(child)` call.
2567
- *
2568
- * Although this method currently runs in the commit phase, you still should not mutate any other nodes in it. If you need to do some additional work when a node is definitely connected to the visible tree, look at `commitMount`.
2569
- */
2570
- appendChild?(parentInstance: Instance, child: Instance | TextInstance): void;
2571
-
2572
- /**
2573
- * Same as `appendChild`, but for when a node is attached to the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2574
- */
2575
- appendChildToContainer?(container: Container, child: Instance | TextInstance): void;
2576
-
2577
- /**
2578
- * This method should mutate the `parentInstance` and place the `child` before `beforeChild` in the list of its children. For example, in the DOM this would translate to a `parentInstance.insertBefore(child, beforeChild)` call.
2579
- *
2580
- * Note that React uses this method both for insertions and for reordering nodes. Similar to DOM, it is expected that you can call `insertBefore` to reposition an existing child. Do not mutate any other parts of the tree from it.
2581
- */
2582
- insertBefore?(
2583
- parentInstance: Instance,
2584
- child: Instance | TextInstance,
2585
- beforeChild: Instance | TextInstance | SuspenseInstance,
2586
- ): void;
2587
-
2588
- /**
2589
- * Same as `insertBefore`, but for when a node is attached to the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2590
- */
2591
- insertInContainerBefore?(
2592
- container: Container,
2593
- child: Instance | TextInstance,
2594
- beforeChild: Instance | TextInstance | SuspenseInstance,
2595
- ): void;
2596
-
2597
- /**
2598
- * This method should mutate the `parentInstance` to remove the `child` from the list of its children.
2599
- *
2600
- * React will only call it for the top-level node that is being removed. It is expected that garbage collection would take care of the whole subtree. You are not expected to traverse the child tree in it.
2601
- */
2602
- removeChild?(parentInstance: Instance, child: Instance | TextInstance | SuspenseInstance): void;
2603
-
2604
- /**
2605
- * Same as `removeChild`, but for when a node is detached from the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2606
- */
2607
- removeChildFromContainer?(container: Container, child: Instance | TextInstance | SuspenseInstance): void;
2608
-
2609
- /**
2610
- * If you returned `true` from `shouldSetTextContent` for the previous props, but returned `false` from `shouldSetTextContent` for the next props, React will call this method so that you can clear the text content you were managing manually. For example, in the DOM you could set `node.textContent = ''`.
2611
- *
2612
- * If you never return `true` from `shouldSetTextContent`, you can leave it empty.
2613
- */
2614
- resetTextContent?(instance: Instance): void;
2615
-
2616
- /**
2617
- * This method should mutate the `textInstance` and update its text content to `nextText`.
2618
- *
2619
- * Here, `textInstance` is a node created by `createTextInstance`.
2620
- */
2621
- commitTextUpdate?(textInstance: TextInstance, oldText: string, newText: string): void;
2622
-
2623
- /**
2624
- * This method is only called if you returned `true` from `finalizeInitialChildren` for this instance.
2625
- *
2626
- * It lets you do some additional work after the node is actually attached to the tree on the screen for the first time. For example, the DOM renderer uses it to trigger focus on nodes with the `autoFocus` attribute.
2627
- *
2628
- * Note that `commitMount` does not mirror `removeChild` one to one because `removeChild` is only called for the top-level removed node. This is why ideally `commitMount` should not mutate any nodes other than the `instance` itself. For example, if it registers some events on some node above, it will be your responsibility to traverse the tree in `removeChild` and clean them up, which is not ideal.
2629
- *
2630
- * The `internalHandle` data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2631
- *
2632
- * If you never return `true` from `finalizeInitialChildren`, you can leave it empty.
2633
- */
2634
- commitMount?(instance: Instance, type: Type, props: Props, internalInstanceHandle: OpaqueHandle): void;
2635
-
2636
- /**
2637
- * This method should mutate the instance to match nextProps.
2638
- *
2639
- * The internalHandle data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2640
- */
2641
- commitUpdate?(
2642
- instance: Instance,
2643
- type: Type,
2644
- prevProps: Props,
2645
- nextProps: Props,
2646
- internalHandle: OpaqueHandle,
2647
- ): void;
2648
-
2649
- /**
2650
- * This method should make the `instance` invisible without removing it from the tree. For example, it can apply visual styling to hide it. It is used by Suspense to hide the tree while the fallback is visible.
2651
- */
2652
- hideInstance?(instance: Instance): void;
2653
-
2654
- /**
2655
- * Same as `hideInstance`, but for nodes created by `createTextInstance`.
2656
- */
2657
- hideTextInstance?(textInstance: TextInstance): void;
2658
-
2659
- /**
2660
- * This method should make the `instance` visible, undoing what `hideInstance` did.
2661
- */
2662
- unhideInstance?(instance: Instance, props: Props): void;
2663
-
2664
- /**
2665
- * Same as `unhideInstance`, but for nodes created by `createTextInstance`.
2666
- */
2667
- unhideTextInstance?(textInstance: TextInstance, text: string): void;
2668
-
2669
- /**
2670
- * This method should mutate the `container` root node and remove all children from it.
2671
- */
2672
- clearContainer?(container: Container): void;
2673
-
2674
- // -------------------
2675
- // Persistence Methods
2676
- // (optional)
2677
- // If you use the persistent mode instead of the mutation mode, you would still need the "Core Methods". However, instead of the Mutation Methods above you will implement a different set of methods that performs cloning nodes and replacing them at the root level. You can find a list of them in the "Persistence" section [listed in this file](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberConfig.custom.js). File an issue if you need help.
2678
- // -------------------
2679
- cloneInstance?(
2680
- instance: Instance,
2681
- type: Type,
2682
- oldProps: Props,
2683
- newProps: Props,
2684
- keepChildren: boolean,
2685
- recyclableInstance: null | Instance,
2686
- ): Instance;
2687
- createContainerChildSet?(container: Container): ChildSet;
2688
- appendChildToContainerChildSet?(childSet: ChildSet, child: Instance | TextInstance): void;
2689
- finalizeContainerChildren?(container: Container, newChildren: ChildSet): void;
2690
- replaceContainerChildren?(container: Container, newChildren: ChildSet): void;
2691
- cloneHiddenInstance?(
2692
- instance: Instance,
2693
- type: Type,
2694
- props: Props,
2695
- internalInstanceHandle: OpaqueHandle,
2696
- ): Instance;
2697
- cloneHiddenTextInstance?(instance: Instance, text: Type, internalInstanceHandle: OpaqueHandle): TextInstance;
2698
-
2699
- // -------------------
2700
- // Hydration Methods
2701
- // (optional)
2702
- // You can optionally implement hydration to "attach" to the existing tree during the initial render instead of creating it from scratch. For example, the DOM renderer uses this to attach to an HTML markup.
2703
- //
2704
- // To support hydration, you need to declare `supportsHydration: true` and then implement the methods in the "Hydration" section [listed in this file](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberConfig.custom.js). File an issue if you need help.
2705
- // -------------------
2706
- supportsHydration: boolean;
2707
-
2708
- canHydrateInstance?(instance: HydratableInstance, type: Type, props: Props): null | Instance;
2709
-
2710
- canHydrateTextInstance?(instance: HydratableInstance, text: string): null | TextInstance;
2711
-
2712
- canHydrateSuspenseInstance?(instance: HydratableInstance): null | SuspenseInstance;
2713
-
2714
- isSuspenseInstancePending?(instance: SuspenseInstance): boolean;
2715
-
2716
- isSuspenseInstanceFallback?(instance: SuspenseInstance): boolean;
2717
-
2718
- registerSuspenseInstanceRetry?(instance: SuspenseInstance, callback: () => void): void;
2719
-
2720
- getNextHydratableSibling?(instance: HydratableInstance): null | HydratableInstance;
2721
-
2722
- getFirstHydratableChild?(parentInstance: Container | Instance): null | HydratableInstance;
2723
-
2724
- hydrateInstance?(
2725
- instance: Instance,
2726
- type: Type,
2727
- props: Props,
2728
- rootContainerInstance: Container,
2729
- hostContext: HostContext,
2730
- internalInstanceHandle: any,
2731
- ): null | any[];
2732
-
2733
- hydrateTextInstance?(textInstance: TextInstance, text: string, internalInstanceHandle: any): boolean;
2734
-
2735
- hydrateSuspenseInstance?(suspenseInstance: SuspenseInstance, internalInstanceHandle: any): void;
2736
-
2737
- getNextHydratableInstanceAfterSuspenseInstance?(suspenseInstance: SuspenseInstance): null | HydratableInstance;
2738
-
2739
- // Returns the SuspenseInstance if this node is a direct child of a
2740
- // SuspenseInstance. I.e. if its previous sibling is a Comment with
2741
- // SUSPENSE_x_START_DATA. Otherwise, null.
2742
- getParentSuspenseInstance?(targetInstance: any): null | SuspenseInstance;
2743
-
2744
- commitHydratedContainer?(container: Container): void;
2745
-
2746
- commitHydratedSuspenseInstance?(suspenseInstance: SuspenseInstance): void;
2747
-
2748
- didNotMatchHydratedContainerTextInstance?(
2749
- parentContainer: Container,
2750
- textInstance: TextInstance,
2751
- text: string,
2752
- ): void;
2753
-
2754
- didNotMatchHydratedTextInstance?(
2755
- parentType: Type,
2756
- parentProps: Props,
2757
- parentInstance: Instance,
2758
- textInstance: TextInstance,
2759
- text: string,
2760
- ): void;
2761
-
2762
- didNotHydrateContainerInstance?(parentContainer: Container, instance: HydratableInstance): void;
2763
-
2764
- didNotHydrateInstance?(
2765
- parentType: Type,
2766
- parentProps: Props,
2767
- parentInstance: Instance,
2768
- instance: HydratableInstance,
2769
- ): void;
2770
-
2771
- didNotFindHydratableContainerInstance?(parentContainer: Container, type: Type, props: Props): void;
2772
-
2773
- didNotFindHydratableContainerTextInstance?(parentContainer: Container, text: string): void;
2774
-
2775
- didNotFindHydratableContainerSuspenseInstance?(parentContainer: Container): void;
2776
-
2777
- didNotFindHydratableInstance?(
2778
- parentType: Type,
2779
- parentProps: Props,
2780
- parentInstance: Instance,
2781
- type: Type,
2782
- props: Props,
2783
- ): void;
2784
-
2785
- didNotFindHydratableTextInstance?(
2786
- parentType: Type,
2787
- parentProps: Props,
2788
- parentInstance: Instance,
2789
- text: string,
2790
- ): void;
2791
-
2792
- didNotFindHydratableSuspenseInstance?(parentType: Type, parentProps: Props, parentInstance: Instance): void;
2793
-
2794
- errorHydratingContainer?(parentContainer: Container): void;
2795
-
2796
- // Undocumented
2797
- // https://github.com/facebook/react/pull/26722
2798
- NotPendingTransition: TransitionStatus | null;
2799
- HostTransitionContext: ReactContext<TransitionStatus>;
2800
-
2801
- // https://github.com/facebook/react/pull/28751
2802
- setCurrentUpdatePriority(newPriority: EventPriority): void;
2803
- getCurrentUpdatePriority(): EventPriority;
2804
- resolveUpdatePriority(): EventPriority;
2805
-
2806
- // https://github.com/facebook/react/pull/28804
2807
- resetFormInstance(form: FormInstance): void;
2808
-
2809
- // https://github.com/facebook/react/pull/25105
2810
- requestPostPaintCallback(callback: (time: number) => void): void;
2811
-
2812
- // https://github.com/facebook/react/pull/26025
2813
- shouldAttemptEagerTransition(): boolean;
2814
-
2815
- // https://github.com/facebook/react/pull/31528
2816
- trackSchedulerEvent(): void;
2817
-
2818
- // https://github.com/facebook/react/pull/31008
2819
- resolveEventType(): null | string;
2820
- resolveEventTimeStamp(): number;
2821
-
2822
- /**
2823
- * This method is called during render to determine if the Host Component type and props require some kind of loading process to complete before committing an update.
2824
- */
2825
- maySuspendCommit(type: Type, props: Props): boolean;
2826
-
2827
- /**
2828
- * This method may be called during render if the Host Component type and props might suspend a commit. It can be used to initiate any work that might shorten the duration of a suspended commit.
2829
- */
2830
- preloadInstance(type: Type, props: Props): boolean;
2831
-
2832
- /**
2833
- * This method is called just before the commit phase. Use it to set up any necessary state while any Host Components that might suspend this commit are evaluated to determine if the commit must be suspended.
2834
- */
2835
- startSuspendingCommit(): void;
2836
-
2837
- /**
2838
- * This method is called after `startSuspendingCommit` for each Host Component that indicated it might suspend a commit.
2839
- */
2840
- suspendInstance(type: Type, props: Props): void;
2841
-
2842
- /**
2843
- * This method is called after all `suspendInstance` calls are complete.
2844
- *
2845
- * Return `null` if the commit can happen immediately.
2846
- *
2847
- * Return `(initiateCommit: Function) => Function` if the commit must be suspended. The argument to this callback will initiate the commit when called. The return value is a cancellation function that the Reconciler can use to abort the commit.
2848
- */
2849
- waitForCommitToBeReady():
2850
- | ((initiateCommit: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown)
2851
- | null;
2852
- }
2853
-
2854
- interface Thenable<T> {
2855
- then(resolve: () => T, reject?: () => T): T;
2856
- }
2857
-
2858
- type RootTag = 0 | 1 | 2;
2859
-
2860
- type WorkTag =
2861
- | 0
2862
- | 1
2863
- | 2
2864
- | 3
2865
- | 4
2866
- | 5
2867
- | 6
2868
- | 7
2869
- | 8
2870
- | 9
2871
- | 10
2872
- | 11
2873
- | 12
2874
- | 13
2875
- | 14
2876
- | 15
2877
- | 16
2878
- | 17
2879
- | 18
2880
- | 19
2881
- | 20
2882
- | 21
2883
- | 22
2884
- | 23
2885
- | 24;
2886
-
2887
- type HookType =
2888
- | "useState"
2889
- | "useReducer"
2890
- | "useContext"
2891
- | "useRef"
2892
- | "useEffect"
2893
- | "useLayoutEffect"
2894
- | "useCallback"
2895
- | "useMemo"
2896
- | "useImperativeHandle"
2897
- | "useDebugValue"
2898
- | "useDeferredValue"
2899
- | "useTransition"
2900
- | "useMutableSource"
2901
- | "useOpaqueIdentifier"
2902
- | "useCacheRefresh";
2903
-
2904
- interface Source {
2905
- fileName: string;
2906
- lineNumber: number;
2907
- }
2908
-
2909
- // TODO: Ideally these types would be opaque but that doesn't work well with
2910
- // our reconciler fork infra, since these leak into non-reconciler packages.
2911
- type LanePriority = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
2912
-
2913
- type Lanes = number;
2914
- type Lane = number;
2915
-
2916
- type Flags = number;
2917
-
2918
- type TypeOfMode = number;
2919
-
2920
- type EventPriority = number;
2921
-
2922
- interface ReactProvider<T> {
2923
- $$typeof: symbol | number;
2924
- type: ReactProviderType<T>;
2925
- key: null | string;
2926
- ref: null;
2927
- props: {
2928
- value: T;
2929
- children?: ReactNode;
2930
- };
2931
- }
2932
-
2933
- interface ReactProviderType<T> {
2934
- $$typeof: symbol | number;
2935
- _context: ReactContext<T>;
2936
- }
2937
-
2938
- interface ReactConsumer<T> {
2939
- $$typeof: symbol | number;
2940
- type: ReactContext<T>;
2941
- key: null | string;
2942
- ref: null;
2943
- props: {
2944
- children: (value: T) => ReactNode;
2945
- unstable_observedBits?: number;
2946
- };
2947
- }
2948
-
2949
- interface ReactContext<T> {
2950
- $$typeof: symbol | number;
2951
- Consumer: ReactContext<T>;
2952
- Provider: ReactProviderType<T>;
2953
- _currentValue: T;
2954
- _currentValue2: T;
2955
- _threadCount: number;
2956
- // DEV only
2957
- _currentRenderer?: {
2958
- [key: string]: any;
2959
- } | null;
2960
- _currentRenderer2?: {
2961
- [key: string]: any;
2962
- } | null;
2963
- // This value may be added by application code
2964
- // to improve DEV tooling display names
2965
- displayName?: string;
2966
- }
2967
-
2968
- interface ReactPortal {
2969
- $$typeof: symbol | number;
2970
- key: null | string;
2971
- containerInfo: any;
2972
- children: ReactNode;
2973
- // TODO: figure out the API for cross-renderer implementation.
2974
- implementation: any;
2975
- }
2976
-
2977
- interface RefObject {
2978
- current: any;
2979
- }
2980
-
2981
- interface ContextDependency<T> {
2982
- context: ReactContext<T>;
2983
- observedBits: number;
2984
- next: ContextDependency<unknown> | null;
2985
- }
2986
-
2987
- interface Dependencies {
2988
- lanes: Lanes;
2989
- firstContext: ContextDependency<unknown> | null;
2990
- }
2991
-
2992
- interface Fiber {
2993
- // These first fields are conceptually members of an Instance. This used to
2994
- // be split into a separate type and intersected with the other Fiber fields,
2995
- // but until Flow fixes its intersection bugs, we've merged them into a
2996
- // single type.
2997
-
2998
- // An Instance is shared between all versions of a component. We can easily
2999
- // break this out into a separate object to avoid copying so much to the
3000
- // alternate versions of the tree. We put this on a single object for now to
3001
- // minimize the number of objects created during the initial render.
3002
-
3003
- // Tag identifying the type of fiber.
3004
- tag: WorkTag;
3005
-
3006
- // Unique identifier of this child.
3007
- key: null | string;
3008
-
3009
- // The value of element.type which is used to preserve the identity during
3010
- // reconciliation of this child.
3011
- elementType: any;
3012
-
3013
- // The resolved function/class/ associated with this fiber.
3014
- type: any;
3015
-
3016
- // The local state associated with this fiber.
3017
- stateNode: any;
3018
-
3019
- // Conceptual aliases
3020
- // parent : Instance -> return The parent happens to be the same as the
3021
- // return fiber since we've merged the fiber and instance.
3022
-
3023
- // Remaining fields belong to Fiber
3024
-
3025
- // The Fiber to return to after finishing processing this one.
3026
- // This is effectively the parent, but there can be multiple parents (two)
3027
- // so this is only the parent of the thing we're currently processing.
3028
- // It is conceptually the same as the return address of a stack frame.
3029
- return: Fiber | null;
3030
-
3031
- // Singly Linked List Tree Structure.
3032
- child: Fiber | null;
3033
- sibling: Fiber | null;
3034
- index: number;
3035
-
3036
- // The ref last used to attach this node.
3037
- // I'll avoid adding an owner field for prod and model that as functions.
3038
- ref:
3039
- | null
3040
- | (((handle: unknown) => void) & {
3041
- _stringRef?: string | null;
3042
- })
3043
- | RefObject;
3044
-
3045
- // Input is the data coming into process this fiber. Arguments. Props.
3046
- pendingProps: any; // This type will be more specific once we overload the tag.
3047
- memoizedProps: any; // The props used to create the output.
3048
-
3049
- // A queue of state updates and callbacks.
3050
- updateQueue: unknown;
3051
-
3052
- // The state used to create the output
3053
- memoizedState: any;
3054
-
3055
- // Dependencies (contexts, events) for this fiber, if it has any
3056
- dependencies: Dependencies | null;
3057
-
3058
- // Bitfield that describes properties about the fiber and its subtree. E.g.
3059
- // the ConcurrentMode flag indicates whether the subtree should be async-by-
3060
- // default. When a fiber is created, it inherits the mode of its
3061
- // parent. Additional flags can be set at creation time, but after that the
3062
- // value should remain unchanged throughout the fiber's lifetime, particularly
3063
- // before its child fibers are created.
3064
- mode: TypeOfMode;
3065
-
3066
- // Effect
3067
- flags: Flags;
3068
- subtreeFlags: Flags;
3069
- deletions: Fiber[] | null;
3070
-
3071
- // Singly linked list fast path to the next fiber with side-effects.
3072
- nextEffect: Fiber | null;
3073
-
3074
- // The first and last fiber with side-effect within this subtree. This allows
3075
- // us to reuse a slice of the linked list when we reuse the work done within
3076
- // this fiber.
3077
- firstEffect: Fiber | null;
3078
- lastEffect: Fiber | null;
3079
-
3080
- lanes: Lanes;
3081
- childLanes: Lanes;
3082
-
3083
- // This is a pooled version of a Fiber. Every fiber that gets updated will
3084
- // eventually have a pair. There are cases when we can clean up pairs to save
3085
- // memory if we need to.
3086
- alternate: Fiber | null;
3087
-
3088
- // Time spent rendering this Fiber and its descendants for the current update.
3089
- // This tells us how well the tree makes use of sCU for memoization.
3090
- // It is reset to 0 each time we render and only updated when we don't bailout.
3091
- // This field is only set when the enableProfilerTimer flag is enabled.
3092
- actualDuration?: number;
3093
-
3094
- // If the Fiber is currently active in the "render" phase,
3095
- // This marks the time at which the work began.
3096
- // This field is only set when the enableProfilerTimer flag is enabled.
3097
- actualStartTime?: number;
3098
-
3099
- // Duration of the most recent render time for this Fiber.
3100
- // This value is not updated when we bailout for memoization purposes.
3101
- // This field is only set when the enableProfilerTimer flag is enabled.
3102
- selfBaseDuration?: number;
3103
-
3104
- // Sum of base times for all descendants of this Fiber.
3105
- // This value bubbles up during the "complete" phase.
3106
- // This field is only set when the enableProfilerTimer flag is enabled.
3107
- treeBaseDuration?: number;
3108
-
3109
- // Conceptual aliases
3110
- // workInProgress : Fiber -> alternate The alternate used for reuse happens
3111
- // to be the same as work in progress.
3112
- // __DEV__ only
3113
- _debugID?: number;
3114
- _debugSource?: Source | null;
3115
- _debugOwner?: Fiber | null;
3116
- _debugIsCurrentlyTiming?: boolean;
3117
- _debugNeedsRemount?: boolean;
3118
-
3119
- // Used to verify that the order of hooks does not change between renders.
3120
- _debugHookTypes?: HookType[] | null;
3121
- }
3122
-
3123
- type FiberRoot = any;
3124
-
3125
- // Concurrent related struct
3126
- type MutableSource = any;
3127
-
3128
- type OpaqueHandle = any;
3129
- type OpaqueRoot = any;
3130
-
3131
- // 0 is PROD, 1 is DEV.
3132
- // Might add PROFILE later.
3133
- type BundleType = 0 | 1;
3134
-
3135
- interface DevToolsConfig<Instance, TextInstance, RendererInspectionConfig> {
3136
- bundleType: BundleType;
3137
- version: string;
3138
- rendererPackageName: string;
3139
- // Note: this actually *does* depend on Fiber internal fields.
3140
- // Used by "inspect clicked DOM element" in React DevTools.
3141
- findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null;
3142
- rendererConfig?: RendererInspectionConfig;
3143
- }
3144
-
3145
- interface SuspenseHydrationCallbacks<SuspenseInstance> {
3146
- onHydrated?: (suspenseInstance: SuspenseInstance) => void;
3147
- onDeleted?: (suspenseInstance: SuspenseInstance) => void;
3148
- }
3149
-
3150
- interface TransitionTracingCallbacks {
3151
- onTransitionStart?: (transitionName: string, startTime: number) => void;
3152
- onTransitionProgress?: (
3153
- transitionName: string,
3154
- startTime: number,
3155
- currentTime: number,
3156
- pending: Array<{ name: null | string }>,
3157
- ) => void;
3158
- onTransitionIncomplete?: (
3159
- transitionName: string,
3160
- startTime: number,
3161
- deletions: Array<{
3162
- type: string;
3163
- name?: string;
3164
- newName?: string;
3165
- endTime: number;
3166
- }>,
3167
- ) => void;
3168
- onTransitionComplete?: (transitionName: string, startTime: number, endTime: number) => void;
3169
- onMarkerProgress?: (
3170
- transitionName: string,
3171
- marker: string,
3172
- startTime: number,
3173
- currentTime: number,
3174
- pending: Array<{ name: null | string }>,
3175
- ) => void;
3176
- onMarkerIncomplete?: (
3177
- transitionName: string,
3178
- marker: string,
3179
- startTime: number,
3180
- deletions: Array<{
3181
- type: string;
3182
- name?: string;
3183
- newName?: string;
3184
- endTime: number;
3185
- }>,
3186
- ) => void;
3187
- onMarkerComplete?: (transitionName: string, marker: string, startTime: number, endTime: number) => void;
3188
- }
3189
-
3190
- interface ComponentSelector {
3191
- $$typeof: symbol | number;
3192
- value: React$AbstractComponent<never, unknown>;
3193
- }
3194
-
3195
- interface HasPseudoClassSelector {
3196
- $$typeof: symbol | number;
3197
- value: Selector[];
3198
- }
3199
-
3200
- interface RoleSelector {
3201
- $$typeof: symbol | number;
3202
- value: string;
3203
- }
3204
-
3205
- interface TextSelector {
3206
- $$typeof: symbol | number;
3207
- value: string;
3208
- }
3209
-
3210
- interface TestNameSelector {
3211
- $$typeof: symbol | number;
3212
- value: string;
3213
- }
3214
-
3215
- type Selector = ComponentSelector | HasPseudoClassSelector | RoleSelector | TextSelector | TestNameSelector;
3216
-
3217
- // TODO can not find React$AbstractComponent def
3218
- type React$AbstractComponent<Config, Instance = any> = any;
3219
-
3220
- interface BoundingRect {
3221
- x: number;
3222
- y: number;
3223
- width: number;
3224
- height: number;
3225
- }
3226
-
3227
- type IntersectionObserverOptions = any;
3228
-
3229
- interface BaseErrorInfo {
3230
- componentStack?: string;
3231
- }
3232
-
3233
- interface Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance> {
3234
- createContainer(
3235
- containerInfo: Container,
3236
- tag: RootTag,
3237
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3238
- isStrictMode: boolean,
3239
- concurrentUpdatesByDefaultOverride: null | boolean,
3240
- identifierPrefix: string,
3241
- onUncaughtError: (error: Error, info: BaseErrorInfo & { errorBoundary?: Component }) => void,
3242
- onCaughtError: (error: Error, info: BaseErrorInfo) => void,
3243
- onRecoverableError: (error: Error, info: BaseErrorInfo) => void,
3244
- onDefaultTransitionIndicator: () => void,
3245
- transitionCallbacks: null | TransitionTracingCallbacks,
3246
- ): OpaqueRoot;
3247
-
3248
- createPortal(
3249
- children: ReactNode,
3250
- containerInfo: any, // TODO: figure out the API for cross-renderer implementation.
3251
- implementation: any,
3252
- key?: string | null,
3253
- ): ReactPortal;
3254
-
3255
- registerMutableSourceForHydration(root: FiberRoot, mutableSource: MutableSource): void;
3256
-
3257
- createComponentSelector(component: React$AbstractComponent<never, unknown>): ComponentSelector;
3258
-
3259
- createHasPseudoClassSelector(selectors: Selector[]): HasPseudoClassSelector;
3260
-
3261
- createRoleSelector(role: string): RoleSelector;
3262
-
3263
- createTextSelector(text: string): TextSelector;
3264
-
3265
- createTestNameSelector(id: string): TestNameSelector;
3266
-
3267
- getFindAllNodesFailureDescription(hostRoot: Instance, selectors: Selector[]): string | null;
3268
-
3269
- findAllNodes(hostRoot: Instance, selectors: Selector[]): Instance[];
3270
-
3271
- findBoundingRects(hostRoot: Instance, selectors: Selector[]): BoundingRect[];
3272
-
3273
- focusWithin(hostRoot: Instance, selectors: Selector[]): boolean;
3274
-
3275
- observeVisibleRects(
3276
- hostRoot: Instance,
3277
- selectors: Selector[],
3278
- callback: (intersections: Array<{ ratio: number; rect: BoundingRect }>) => void,
3279
- options?: IntersectionObserverOptions,
3280
- ): { disconnect: () => void };
3281
-
3282
- createHydrationContainer(
3283
- initialChildren: ReactNode,
3284
- callback: (() => void) | null | undefined,
3285
- containerInfo: Container,
3286
- tag: RootTag,
3287
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3288
- isStrictMode: boolean,
3289
- concurrentUpdatesByDefaultOverride: null | boolean,
3290
- identifierPrefix: string,
3291
- onRecoverableError: (error: Error) => void,
3292
- transitionCallbacks: null | TransitionTracingCallbacks,
3293
- ): OpaqueRoot;
3294
-
3295
- updateContainer(
3296
- element: ReactNode,
3297
- container: OpaqueRoot,
3298
- parentComponent?: Component<any, any> | null,
3299
- callback?: (() => void) | null,
3300
- ): Lane;
3301
-
3302
- batchedUpdates<A, R>(fn: (a: A) => R, a: A): R;
3303
-
3304
- deferredUpdates<A>(fn: () => A): A;
3305
-
3306
- discreteUpdates<A, B, C, D, R>(fn: (arg0: A, arg1: B, arg2: C, arg3: D) => R, a: A, b: B, c: C, d: D): R;
3307
-
3308
- flushControlled(fn: () => any): void;
3309
-
3310
- flushSync(): void;
3311
- flushSync<R>(fn: () => R): R;
3312
-
3313
- isAlreadyRendering(): boolean;
3314
-
3315
- flushPassiveEffects(): boolean;
3316
-
3317
- getPublicRootInstance(container: OpaqueRoot): Component<any, any> | PublicInstance | null;
3318
-
3319
- attemptSynchronousHydration(fiber: Fiber): void;
3320
-
3321
- attemptDiscreteHydration(fiber: Fiber): void;
3322
-
3323
- attemptContinuousHydration(fiber: Fiber): void;
3324
-
3325
- attemptHydrationAtCurrentPriority(fiber: Fiber): void;
3326
-
3327
- getCurrentUpdatePriority(): LanePriority;
3328
-
3329
- runWithPriority<T>(priority: LanePriority, fn: () => T): T;
3330
-
3331
- findHostInstance(component: any): PublicInstance | null;
3332
-
3333
- findHostInstanceWithWarning(component: any, methodName: string): PublicInstance | null;
3334
-
3335
- findHostInstanceWithNoPortals(fiber: Fiber): PublicInstance | null;
3336
-
3337
- shouldError(fiber: Fiber): boolean | undefined;
3338
-
3339
- shouldSuspend(fiber: Fiber): boolean;
3340
-
3341
- injectIntoDevTools(devToolsConfig: DevToolsConfig<Instance, TextInstance, any>): boolean;
3342
- }
3343
- }
3344
-
3345
- declare function extend<T extends ConstructorRepresentation>(objects: T): React$1.ExoticComponent<ThreeElement<T>>;
3346
- declare function extend<T extends Catalogue>(objects: T): void;
3347
- declare const reconciler: ReactReconciler.Reconciler<RootStore, Instance<any>, void, Instance<any>, never, any>;
3348
-
3349
- declare const isRenderer: (def: any) => boolean;
3350
- interface OffscreenCanvas extends EventTarget {
3351
- }
3352
- declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3353
- declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3354
- declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3355
- declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3356
- interface PortalProps {
3357
- children: ReactNode;
3358
- state?: InjectState;
3359
- container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
11
+ import { JSX } from 'react';
12
+ import 'react-use-measure';
13
+ import 'react/jsx-runtime';
14
+ import 'zustand/traditional';
15
+ import 'three/tsl';
16
+
17
+ /**
18
+ * The `ReactThreeFiber` namespace of the WebGPU entry: the shared element types plus this entry's JSX map.
19
+ *
20
+ * Explicit aliases, not `export type *`: rollup-dts otherwise re-exports the types as namespace values
21
+ * and the built declaration fails to compile for consumers.
22
+ */
23
+
24
+
25
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters$1<T>
26
+ type MathRepresentation = MathRepresentation$1
27
+ type VectorRepresentation = VectorRepresentation$1
28
+ type MathTypes = MathTypes$1
29
+ type MathType<T extends MathTypes$1> = MathType$1<T>
30
+ type MathProps<P> = MathProps$1<P>
31
+ type Vector2 = Vector2$1
32
+ type Vector3 = Vector3$1
33
+ type Vector4 = Vector4$1
34
+ type Color = Color$1
35
+ type Layers = Layers$1
36
+ type Quaternion = Quaternion$1
37
+ type Euler = Euler$1
38
+ type Matrix3 = Matrix3$1
39
+ type Matrix4 = Matrix4$1
40
+ type RaycastableRepresentation = RaycastableRepresentation$1
41
+ type EventProps<P> = EventProps$1<P>
42
+ type GeometryTransformProps = GeometryTransformProps$1
43
+ type GeometryProps<P> = GeometryProps$1<P>
44
+ type TSLNodeInput = TSLNodeInput$1
45
+ type NodeProps<P> = NodeProps$1<P>
46
+ type ReactProps<P> = ReactProps$1<P>
47
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps$1<T, P>
48
+ type ThreeElement<T extends ConstructorRepresentation> = ThreeElement$1<T>
49
+ type ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements$1<T>
50
+ type Object3DMethod = Object3DMethod$1
51
+ type ThreeElementsOf<T extends Record<string, any>> = ThreeElementsOf$1<T>
52
+ type ElementOf<E, K extends string> = ElementOf$1<E, K>
53
+
54
+ type webgpu_d_Color = Color;
55
+ type webgpu_d_ElementOf<E, K extends string> = ElementOf<E, K>;
56
+ type webgpu_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
57
+ type webgpu_d_Euler = Euler;
58
+ type webgpu_d_EventProps<P> = EventProps<P>;
59
+ type webgpu_d_GeometryProps<P> = GeometryProps<P>;
60
+ type webgpu_d_GeometryTransformProps = GeometryTransformProps;
61
+ type webgpu_d_Layers = Layers;
62
+ type webgpu_d_MathProps<P> = MathProps<P>;
63
+ type webgpu_d_MathRepresentation = MathRepresentation;
64
+ type webgpu_d_MathType<T extends MathTypes$1> = MathType<T>;
65
+ type webgpu_d_MathTypes = MathTypes;
66
+ type webgpu_d_Matrix3 = Matrix3;
67
+ type webgpu_d_Matrix4 = Matrix4;
68
+ type webgpu_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
69
+ type webgpu_d_NodeProps<P> = NodeProps<P>;
70
+ type webgpu_d_Object3DMethod = Object3DMethod;
71
+ type webgpu_d_Quaternion = Quaternion;
72
+ type webgpu_d_RaycastableRepresentation = RaycastableRepresentation;
73
+ type webgpu_d_ReactProps<P> = ReactProps<P>;
74
+ type webgpu_d_TSLNodeInput = TSLNodeInput;
75
+ type webgpu_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
76
+ type webgpu_d_ThreeElements = ThreeElements;
77
+ type webgpu_d_ThreeElementsOf<T extends Record<string, any>> = ThreeElementsOf<T>;
78
+ type webgpu_d_ThreeExports = ThreeExports;
79
+ type webgpu_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
80
+ type webgpu_d_Vector2 = Vector2;
81
+ type webgpu_d_Vector3 = Vector3;
82
+ type webgpu_d_Vector4 = Vector4;
83
+ type webgpu_d_VectorRepresentation = VectorRepresentation;
84
+ declare namespace webgpu_d {
85
+ export type { webgpu_d_Color as Color, webgpu_d_ElementOf as ElementOf, webgpu_d_ElementProps as ElementProps, webgpu_d_Euler as Euler, webgpu_d_EventProps as EventProps, webgpu_d_GeometryProps as GeometryProps, webgpu_d_GeometryTransformProps as GeometryTransformProps, webgpu_d_Layers as Layers, webgpu_d_MathProps as MathProps, webgpu_d_MathRepresentation as MathRepresentation, webgpu_d_MathType as MathType, webgpu_d_MathTypes as MathTypes, webgpu_d_Matrix3 as Matrix3, webgpu_d_Matrix4 as Matrix4, webgpu_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, webgpu_d_NodeProps as NodeProps, webgpu_d_Object3DMethod as Object3DMethod, webgpu_d_Quaternion as Quaternion, webgpu_d_RaycastableRepresentation as RaycastableRepresentation, webgpu_d_ReactProps as ReactProps, webgpu_d_TSLNodeInput as TSLNodeInput, webgpu_d_ThreeElement as ThreeElement, webgpu_d_ThreeElements as ThreeElements, webgpu_d_ThreeElementsOf as ThreeElementsOf, webgpu_d_ThreeExports as ThreeExports, webgpu_d_ThreeToJSXElements as ThreeToJSXElements, webgpu_d_Vector2 as Vector2, webgpu_d_Vector3 as Vector3, webgpu_d_Vector4 as Vector4, webgpu_d_VectorRepresentation as VectorRepresentation };
3360
86
  }
3361
- declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3362
- /**
3363
- * Force React to flush any updates inside the provided callback synchronously and immediately.
3364
- * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
3365
- * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
3366
- * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
3367
- */
3368
- declare function flushSync<R>(fn: () => R): R;
3369
-
3370
- declare const context: React$1.Context<RootStore>;
3371
- declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
3372
-
3373
- /**
3374
- * An SSR-friendly useLayoutEffect.
3375
- *
3376
- * React currently throws a warning when using useLayoutEffect on the server.
3377
- * To get around it, we can conditionally useEffect on the server (no-op) and
3378
- * useLayoutEffect elsewhere.
3379
- *
3380
- * @see https://github.com/facebook/react/issues/14927
3381
- */
3382
- declare const useIsomorphicLayoutEffect: typeof React$1.useLayoutEffect;
3383
- /**
3384
- * Creates a stable ref that always contains the latest callback.
3385
- * Useful for avoiding dependency arrays while ensuring the latest closure is called.
3386
- *
3387
- * @param fn - The callback function to wrap
3388
- * @returns A ref containing the current callback
3389
- */
3390
- declare function useMutableCallback<T>(fn: T): React$1.RefObject<T>;
3391
- /**
3392
- * Bridges renderer Context and StrictMode from a primary renderer.
3393
- * Used to maintain React context when rendering into portals or secondary canvases.
3394
- *
3395
- * @returns A Bridge component that wraps children with the parent renderer's context
3396
- */
3397
- declare function useBridge(): Bridge;
3398
- /**
3399
- * Internal component that blocks rendering until a promise resolves.
3400
- * Used for suspense-like blocking behavior.
3401
- *
3402
- * @param set - Function to set the blocking promise
3403
- */
3404
- declare function Block({ set }: Omit<UnblockProps, 'children'>): null;
3405
- /**
3406
- * Error boundary component for catching and handling errors in the React tree.
3407
- * Forwards errors to a state setter for external handling.
3408
- *
3409
- * NOTE: static members get down-level transpiled to mutations which break tree-shaking
3410
- */
3411
- declare const ErrorBoundary: {
3412
- new (props: {
3413
- set: React$1.Dispatch<Error | undefined>;
3414
- children: React$1.ReactNode;
3415
- }): {
3416
- state: {
3417
- error: boolean;
3418
- };
3419
- componentDidCatch(err: Error): void;
3420
- render(): React$1.ReactNode;
3421
- context: unknown;
3422
- setState<K extends "error">(state: {
3423
- error: boolean;
3424
- } | ((prevState: Readonly<{
3425
- error: boolean;
3426
- }>, props: Readonly<{
3427
- set: React$1.Dispatch<Error | undefined>;
3428
- children: React$1.ReactNode;
3429
- }>) => {
3430
- error: boolean;
3431
- } | Pick<{
3432
- error: boolean;
3433
- }, K> | null) | Pick<{
3434
- error: boolean;
3435
- }, K> | null, callback?: (() => void) | undefined): void;
3436
- forceUpdate(callback?: (() => void) | undefined): void;
3437
- readonly props: Readonly<{
3438
- set: React$1.Dispatch<Error | undefined>;
3439
- children: React$1.ReactNode;
3440
- }>;
3441
- componentDidMount?(): void;
3442
- shouldComponentUpdate?(nextProps: Readonly<{
3443
- set: React$1.Dispatch<Error | undefined>;
3444
- children: React$1.ReactNode;
3445
- }>, nextState: Readonly<{
3446
- error: boolean;
3447
- }>, nextContext: any): boolean;
3448
- componentWillUnmount?(): void;
3449
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3450
- set: React$1.Dispatch<Error | undefined>;
3451
- children: React$1.ReactNode;
3452
- }>, prevState: Readonly<{
3453
- error: boolean;
3454
- }>): any;
3455
- componentDidUpdate?(prevProps: Readonly<{
3456
- set: React$1.Dispatch<Error | undefined>;
3457
- children: React$1.ReactNode;
3458
- }>, prevState: Readonly<{
3459
- error: boolean;
3460
- }>, snapshot?: any): void;
3461
- componentWillMount?(): void;
3462
- UNSAFE_componentWillMount?(): void;
3463
- componentWillReceiveProps?(nextProps: Readonly<{
3464
- set: React$1.Dispatch<Error | undefined>;
3465
- children: React$1.ReactNode;
3466
- }>, nextContext: any): void;
3467
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3468
- set: React$1.Dispatch<Error | undefined>;
3469
- children: React$1.ReactNode;
3470
- }>, nextContext: any): void;
3471
- componentWillUpdate?(nextProps: Readonly<{
3472
- set: React$1.Dispatch<Error | undefined>;
3473
- children: React$1.ReactNode;
3474
- }>, nextState: Readonly<{
3475
- error: boolean;
3476
- }>, nextContext: any): void;
3477
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3478
- set: React$1.Dispatch<Error | undefined>;
3479
- children: React$1.ReactNode;
3480
- }>, nextState: Readonly<{
3481
- error: boolean;
3482
- }>, nextContext: any): void;
3483
- };
3484
- new (props: {
3485
- set: React$1.Dispatch<Error | undefined>;
3486
- children: React$1.ReactNode;
3487
- }, context: any): {
3488
- state: {
3489
- error: boolean;
3490
- };
3491
- componentDidCatch(err: Error): void;
3492
- render(): React$1.ReactNode;
3493
- context: unknown;
3494
- setState<K extends "error">(state: {
3495
- error: boolean;
3496
- } | ((prevState: Readonly<{
3497
- error: boolean;
3498
- }>, props: Readonly<{
3499
- set: React$1.Dispatch<Error | undefined>;
3500
- children: React$1.ReactNode;
3501
- }>) => {
3502
- error: boolean;
3503
- } | Pick<{
3504
- error: boolean;
3505
- }, K> | null) | Pick<{
3506
- error: boolean;
3507
- }, K> | null, callback?: (() => void) | undefined): void;
3508
- forceUpdate(callback?: (() => void) | undefined): void;
3509
- readonly props: Readonly<{
3510
- set: React$1.Dispatch<Error | undefined>;
3511
- children: React$1.ReactNode;
3512
- }>;
3513
- componentDidMount?(): void;
3514
- shouldComponentUpdate?(nextProps: Readonly<{
3515
- set: React$1.Dispatch<Error | undefined>;
3516
- children: React$1.ReactNode;
3517
- }>, nextState: Readonly<{
3518
- error: boolean;
3519
- }>, nextContext: any): boolean;
3520
- componentWillUnmount?(): void;
3521
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3522
- set: React$1.Dispatch<Error | undefined>;
3523
- children: React$1.ReactNode;
3524
- }>, prevState: Readonly<{
3525
- error: boolean;
3526
- }>): any;
3527
- componentDidUpdate?(prevProps: Readonly<{
3528
- set: React$1.Dispatch<Error | undefined>;
3529
- children: React$1.ReactNode;
3530
- }>, prevState: Readonly<{
3531
- error: boolean;
3532
- }>, snapshot?: any): void;
3533
- componentWillMount?(): void;
3534
- UNSAFE_componentWillMount?(): void;
3535
- componentWillReceiveProps?(nextProps: Readonly<{
3536
- set: React$1.Dispatch<Error | undefined>;
3537
- children: React$1.ReactNode;
3538
- }>, nextContext: any): void;
3539
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3540
- set: React$1.Dispatch<Error | undefined>;
3541
- children: React$1.ReactNode;
3542
- }>, nextContext: any): void;
3543
- componentWillUpdate?(nextProps: Readonly<{
3544
- set: React$1.Dispatch<Error | undefined>;
3545
- children: React$1.ReactNode;
3546
- }>, nextState: Readonly<{
3547
- error: boolean;
3548
- }>, nextContext: any): void;
3549
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3550
- set: React$1.Dispatch<Error | undefined>;
3551
- children: React$1.ReactNode;
3552
- }>, nextState: Readonly<{
3553
- error: boolean;
3554
- }>, nextContext: any): void;
3555
- };
3556
- getDerivedStateFromError: () => {
3557
- error: boolean;
3558
- };
3559
- contextType?: React$1.Context<any> | undefined;
3560
- propTypes?: any;
3561
- };
3562
-
3563
- /**
3564
- * React internal props that should not be passed to Three.js objects.
3565
- */
3566
- declare const REACT_INTERNAL_PROPS: string[];
3567
- /**
3568
- * Returns the instance's initial (outermost) root.
3569
- * Traverses through previousRoot links to find the original root store.
3570
- *
3571
- * @param instance - R3F instance to find root for
3572
- * @returns The outermost root store
3573
- */
3574
- declare function findInitialRoot<T>(instance: Instance<T>): RootStore;
3575
- /**
3576
- * Returns instance root state.
3577
- * If the object doesn't have __r3f (e.g., child meshes in primitives/GLTFs),
3578
- * traverses ancestors to find the nearest managed parent.
3579
- *
3580
- * @param obj - Three.js object to get root state for
3581
- * @returns Root state if found, undefined otherwise
3582
- */
3583
- declare function getRootState<T extends Object3D = Object3D>(obj: T): RootState | undefined;
3584
- /**
3585
- * Collects nodes, materials, and meshes from a Three.js Object3D hierarchy.
3586
- * Handles duplicate material names by appending UUID prefixes.
3587
- *
3588
- * @param object - Root object to traverse
3589
- * @returns ObjectMap containing named nodes, materials, and meshes
3590
- *
3591
- * @example
3592
- * const { nodes, materials, meshes } = buildGraph(gltf.scene)
3593
- * // Access by name: nodes.Head, materials.Metal, meshes.Body
3594
- */
3595
- declare function buildGraph(object: Object3D): ObjectMap;
3596
- /**
3597
- * Disposes an object and all its disposable properties.
3598
- * Skips Scene objects as they should not be disposed automatically.
3599
- *
3600
- * @param obj - Object to dispose
3601
- */
3602
- declare function dispose<T extends Disposable>(obj: T): void;
3603
- /**
3604
- * Extracts instance props from React reconciler fiber props.
3605
- * Filters out React-internal props (children, key, ref).
3606
- *
3607
- * @param queue - Pending props from reconciler fiber
3608
- * @returns Props object without React-internal keys
3609
- */
3610
- declare function getInstanceProps<T = any>(pendingProps: Record<string, unknown>): Instance<T>['props'];
3611
- /**
3612
- * Creates or retrieves an R3F instance descriptor for a Three.js object.
3613
- * Each object in the scene carries a LocalState descriptor (__r3f).
3614
- *
3615
- * @param target - Target object to prepare
3616
- * @param root - Root store for this instance
3617
- * @param type - String identifier for the object type
3618
- * @param props - Initial props for the instance
3619
- * @returns Instance descriptor
3620
- */
3621
- declare function prepare<T = any>(target: T, root: RootStore, type: string, props: Instance<T>['props']): Instance<T>;
3622
- /**
3623
- * Triggers an update for an instance.
3624
- * Calls onUpdate callback and invalidates the frame if necessary.
3625
- *
3626
- * @param instance - Instance to invalidate
3627
- */
3628
- declare function invalidateInstance(instance: Instance): void;
3629
-
3630
- /**
3631
- * Reserved prop names that should not be applied to Three.js objects.
3632
- */
3633
- declare const RESERVED_PROPS: string[];
3634
- /**
3635
- * Resolves a potentially pierced property key (e.g., 'material-color' → material.color).
3636
- * First tries the entire key as a single property, then attempts piercing.
3637
- *
3638
- * @param root - Root object to resolve from
3639
- * @param key - Property key (may contain dashes for piercing)
3640
- * @returns Object containing root, key, and target value
3641
- *
3642
- * @example
3643
- * resolve(mesh, 'material-color')
3644
- * // => { root: mesh.material, key: 'color', target: mesh.material.color }
3645
- */
3646
- declare function resolve(root: any, key: string): {
3647
- root: any;
3648
- key: string;
3649
- target: any;
3650
- };
3651
- /**
3652
- * Attaches a child instance to a parent instance.
3653
- * Handles both string-based attachment (e.g., 'geometry', 'material-map')
3654
- * and function-based attachment for custom logic.
3655
- *
3656
- * @param parent - Parent instance
3657
- * @param child - Child instance to attach
3658
- *
3659
- * @example
3660
- * // String attachment
3661
- * <bufferGeometry attach="geometry" />
3662
- * // Array attachment
3663
- * <light attach="lights-0" />
3664
- * // Function attachment
3665
- * <thing attach={(parent, self) => { parent.customProp = self }} />
3666
- */
3667
- declare function attach(parent: Instance, child: Instance): void;
3668
- /**
3669
- * Detaches a child instance from a parent instance.
3670
- * Restores the previous value or deletes the property if it was never set.
3671
- *
3672
- * @param parent - Parent instance
3673
- * @param child - Child instance to detach
3674
- */
3675
- declare function detach(parent: Instance, child: Instance): void;
3676
- /**
3677
- * Compares old and new props to determine which properties have changed.
3678
- * Also handles resetting removed props for HMR/fast-refresh.
3679
- *
3680
- * @param instance - Instance to diff props for
3681
- * @param newProps - New props to compare against
3682
- * @returns Object containing only changed props
3683
- *
3684
- * @example
3685
- * const changes = diffProps(instance, { position: [1, 2, 3], color: 'red' })
3686
- * // => { position: [1, 2, 3] } (only if position changed)
3687
- */
3688
- declare function diffProps<T = any>(instance: Instance<T>, newProps: Instance<T>['props']): Instance<T>['props'];
3689
- /**
3690
- * Applies a set of props to a Three.js object.
3691
- * Handles special cases like colors, vectors, textures, events, and pierced props.
3692
- *
3693
- * @param object - Three.js object to apply props to
3694
- * @param props - Props to apply
3695
- * @returns The object with props applied
3696
- *
3697
- * @example
3698
- * applyProps(mesh, { position: [0, 1, 0], 'material-color': 'red' })
3699
- */
3700
- declare function applyProps<T = any>(object: Instance<T>['object'], props: Instance<T>['props']): Instance<T>['object'];
3701
-
3702
- /**
3703
- * Calculates the device pixel ratio for rendering.
3704
- * Handles array DPR ranges [min, max] to clamp devicePixelRatio.
3705
- *
3706
- * @param dpr - Target DPR value or [min, max] range
3707
- * @returns Calculated DPR value
3708
- *
3709
- * @example
3710
- * calculateDpr(2) // => 2
3711
- * calculateDpr([1, 2]) // => clamps window.devicePixelRatio between 1 and 2
3712
- */
3713
- declare function calculateDpr(dpr: Dpr): number;
3714
- /**
3715
- * Extracts the first segment of a UUID string (before the first hyphen).
3716
- * Used for creating unique material names when duplicates exist.
3717
- *
3718
- * @param uuid - UUID string to extract prefix from
3719
- * @returns First segment of the UUID
3720
- *
3721
- * @example
3722
- * getUuidPrefix('a1b2c3d4-e5f6-g7h8-i9j0') // => 'a1b2c3d4'
3723
- */
3724
- declare function getUuidPrefix(uuid: string): string;
3725
- /**
3726
- * Updates camera projection based on viewport size.
3727
- * Adjusts aspect ratio for perspective cameras or bounds for orthographic cameras.
3728
- * Respects camera.manual flag - manual cameras are not modified.
3729
- *
3730
- * @param camera - Camera to update
3731
- * @param size - Current viewport size
3732
- */
3733
- declare function updateCamera(camera: ThreeCamera, size: Size): void;
3734
- /**
3735
- * Updates a frustum from a camera's projection and world matrices.
3736
- * If no target frustum is provided, creates and returns a new one.
3737
- *
3738
- * @param camera - Camera to extract frustum from
3739
- * @param frustum - Optional existing frustum to update (creates new if not provided)
3740
- * @returns The updated or newly created frustum
3741
- *
3742
- * @example
3743
- * // Create new frustum
3744
- * const frustum = updateFrustum(camera)
3745
- *
3746
- * // Update existing frustum (no allocation)
3747
- * updateFrustum(camera, existingFrustum)
3748
- *
3749
- * // Use for visibility checks
3750
- * if (frustum.containsPoint(point)) { ... }
3751
- * if (frustum.intersectsObject(mesh)) { ... }
3752
- */
3753
- declare function updateFrustum(camera: ThreeCamera, frustum?: Frustum): Frustum;
3754
-
3755
- declare const is: {
3756
- obj: (a: any) => boolean;
3757
- fun: (a: any) => a is Function;
3758
- str: (a: any) => a is string;
3759
- num: (a: any) => a is number;
3760
- boo: (a: any) => a is boolean;
3761
- und: (a: any) => boolean;
3762
- nul: (a: any) => boolean;
3763
- arr: (a: any) => a is any[];
3764
- equ(a: any, b: any, { arrays, objects, strict }?: EquConfig): boolean;
3765
- };
3766
- declare const isOrthographicCamera: (def: ThreeCamera) => def is OrthographicCamera;
3767
- declare const isRef: (obj: unknown) => obj is React.RefObject<unknown>;
3768
- declare const isColorRepresentation: (value: unknown) => value is ColorRepresentation$1;
3769
- declare const isObject3D: (object: any) => object is Object3D;
3770
- declare const isTexture: (value: unknown) => value is Texture$1;
3771
- type VectorLike = {
3772
- set: (...args: any[]) => void;
3773
- constructor?: Function;
3774
- };
3775
- declare const isVectorLike: (object: unknown) => object is VectorLike;
3776
- type Copyable = {
3777
- copy: (...args: any[]) => void;
3778
- constructor?: Function;
3779
- };
3780
- declare const isCopyable: (object: unknown) => object is Copyable;
3781
- declare const hasConstructor: (object: unknown) => object is {
3782
- constructor?: Function;
3783
- };
3784
-
3785
- /**
3786
- * Symbol marker for deferred ref resolution.
3787
- * Used to identify values that should be resolved from refs after mount.
3788
- */
3789
- declare const FROM_REF: unique symbol;
3790
- /**
3791
- * Defers prop application until the referenced object is available.
3792
- * Useful for props like `target` that need sibling refs to be populated.
3793
- *
3794
- * @param ref - React ref object to resolve at mount time
3795
- * @returns A marker value that applyProps will resolve after mount
3796
- *
3797
- * @example
3798
- * const targetRef = useRef<THREE.Object3D>(null)
3799
- *
3800
- * <group ref={targetRef} position={[-3, -2, -15]} />
3801
- * <spotLight target={fromRef(targetRef)} intensity={100} />
3802
- */
3803
- declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
3804
- /**
3805
- * Type guard to check if a value is a fromRef marker.
3806
- *
3807
- * @param value - Value to check
3808
- * @returns True if value is a fromRef marker
3809
- */
3810
- declare function isFromRef(value: unknown): value is {
3811
- [FROM_REF]: React$1.RefObject<any>;
3812
- };
3813
-
3814
- /**
3815
- * Symbol marker for mount-only method calls.
3816
- * Used to identify methods that should only be called once on initial mount.
3817
- */
3818
- declare const ONCE: unique symbol;
3819
- /**
3820
- * Marks a method call to be executed only on initial mount.
3821
- * Useful for geometry transforms that should not be reapplied on every render.
3822
- *
3823
- * When `args` prop changes (triggering reconstruction), the method will be
3824
- * called again on the new instance since appliedOnce is not carried over.
3825
- *
3826
- * @param args - Arguments to pass to the method
3827
- * @returns A marker value that applyProps will execute once
3828
- *
3829
- * @example
3830
- * // Rotate geometry on mount
3831
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
3832
- *
3833
- * // Multiple arguments
3834
- * <bufferGeometry applyMatrix4={once(matrix)} />
3835
- *
3836
- * // No arguments
3837
- * <geometry center={once()} />
3838
- */
3839
- declare function once<T>(...args: T[]): T;
3840
- /**
3841
- * Type guard to check if a value is a once marker.
3842
- *
3843
- * @param value - Value to check
3844
- * @returns True if value is a once marker
3845
- */
3846
- declare function isOnce(value: unknown): value is {
3847
- [ONCE]: any[] | true;
3848
- };
3849
-
3850
- /**
3851
- * A DOM canvas which accepts threejs elements as children.
3852
- * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3853
- */
3854
- declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3855
-
3856
- /**
3857
- * ScopedStore - Type-safe wrapper for nested stores (uniforms, nodes)
3858
- *
3859
- * Provides TypeScript-friendly access to uniform/node stores where the runtime
3860
- * structure is `Record<string, T | Record<string, T>>` (leaf nodes or nested scopes).
3861
- *
3862
- * The wrapper uses a Proxy to:
3863
- * 1. Return `T` for property access (type assumption: assumes leaf node)
3864
- * 2. Provide `.scope(key)` method for explicit nested access
3865
- * 3. Support iteration methods: has(), keys(), Object.keys(), for...in
3866
- *
3867
- * @example
3868
- * ```tsx
3869
- * useLocalNodes(({ uniforms }) => ({
3870
- * wobble: sin(uniforms.uTime.mul(2)), // No cast needed!
3871
- * playerHealth: uniforms.scope('player').uHealth // Explicit scope access
3872
- * }))
3873
- * ```
3874
- */
3875
-
3876
- /** Keys reserved for methods (excluded from index signature) */
3877
- type MethodKeys = 'scope' | 'has' | 'keys';
3878
- /**
3879
- * Type-safe wrapper interface for accessing nested store data.
3880
- * Property access returns `T` (assumes leaf node).
3881
- * Use `.scope(key)` for nested object access.
3882
- *
3883
- * Uses mapped type with key filtering to exclude method names from index signature,
3884
- * allowing methods to have their correct return types.
3885
- */
3886
- type ScopedStoreType<T> = {
3887
- /** Direct property access returns the leaf type T (method keys excluded) */
3888
- readonly [K in string as K extends MethodKeys ? never : K]: T;
3889
- } & {
3890
- /** Access a nested scope by key. Returns empty wrapper if scope doesn't exist. */
3891
- scope(key: string): ScopedStoreType<T>;
3892
- /** Check if a key exists in the store */
3893
- has(key: string): boolean;
3894
- /** Get all keys in the store */
3895
- keys(): string[];
3896
- };
3897
- /**
3898
- * Create a type-safe ScopedStore wrapper around store data.
3899
- * @param data - The raw store data (uniforms or nodes from RootState)
3900
- * @returns A ScopedStoreType wrapper with type-safe access
3901
- */
3902
- declare function createScopedStore<T>(data: Record<string, any>): ScopedStoreType<T>;
3903
- /**
3904
- * State type passed to creator functions with ScopedStore wrappers.
3905
- * Provides type-safe access to uniforms, nodes, buffers, and gpuStorage without manual casting.
3906
- */
3907
- type CreatorState = Omit<RootState, 'uniforms' | 'nodes' | 'buffers' | 'gpuStorage'> & {
3908
- /** Type-safe uniform access - property access returns UniformNode */
3909
- uniforms: ScopedStoreType<UniformNode>;
3910
- /** Type-safe node access - property access returns TSLNodeType (Node | ShaderCallable | ShaderNodeObject) */
3911
- nodes: ScopedStoreType<TSLNodeType>;
3912
- /** Type-safe buffer access - property access returns BufferLike (TypedArrays, BufferAttributes, TSL nodes) */
3913
- buffers: ScopedStoreType<BufferLike>;
3914
- /** Type-safe GPU storage access - property access returns StorageLike (StorageTexture, TSL nodes) */
3915
- gpuStorage: ScopedStoreType<StorageLike>;
3916
- };
3917
-
3918
- /** Creator function that returns uniform inputs (can be raw values or UniformNodes) */
3919
- type UniformCreator<T extends UniformInputRecord = UniformInputRecord> = (state: CreatorState) => T;
3920
- /** Function signature for removeUniforms util */
3921
- type RemoveUniformsFn = (names: string | string[], scope?: string) => void;
3922
- /** Function signature for clearUniforms util */
3923
- type ClearUniformsFn = (scope?: string) => void;
3924
- /** Function signature for rebuildUniforms util */
3925
- type RebuildUniformsFn = (scope?: string) => void;
3926
- /** Return type with utils included */
3927
- type UniformsWithUtils<T extends UniformRecord = UniformRecord> = T & {
3928
- removeUniforms: RemoveUniformsFn;
3929
- clearUniforms: ClearUniformsFn;
3930
- rebuildUniforms: RebuildUniformsFn;
3931
- };
3932
- declare function useUniforms(): UniformsWithUtils<UniformRecord & Record<string, UniformRecord>>;
3933
- declare function useUniforms(scope: string): UniformsWithUtils;
3934
- declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>): UniformsWithUtils<UniformRecord<UniformNode>>;
3935
- declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>, scope: string): UniformsWithUtils<UniformRecord<UniformNode>>;
3936
- declare function useUniforms<T extends UniformInputRecord>(uniforms: T): UniformsWithUtils<UniformRecord<UniformNode>>;
3937
- declare function useUniforms<T extends UniformInputRecord>(uniforms: T, scope: string): UniformsWithUtils<UniformRecord<UniformNode>>;
3938
- /**
3939
- * Global rebuildUniforms function for HMR integration.
3940
- * Invalidates cached uniforms and increments _hmrVersion to trigger re-creation.
3941
- * Call this when HMR is detected to refresh all uniform creators.
3942
- *
3943
- * Resolves to the primary store so shared TSL resources rebuild on the
3944
- * authoritative store.
3945
- *
3946
- * @param store - The R3F store (from useStore or context)
3947
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
3948
- */
3949
- declare function rebuildAllUniforms(store: ReturnType<typeof useStore>, scope?: string): void;
3950
- /**
3951
- * Remove uniforms by name from root level or a scope
3952
- * @deprecated Use `const { removeUniforms } = useUniforms()` instead
3953
- */
3954
- declare function removeUniforms(set: ReturnType<typeof useStore>['setState'], names: string[], scope?: string): void;
3955
- /**
3956
- * Clear all uniforms from a scope (removes the entire scope object)
3957
- * @deprecated Use `const { clearUniforms } = useUniforms()` instead
3958
- */
3959
- declare function clearScope(set: ReturnType<typeof useStore>['setState'], scope: string): void;
3960
- /**
3961
- * Clear all root-level uniforms (preserves scopes)
3962
- * @deprecated Use `const { clearUniforms } = useUniforms()` with `clearUniforms('root')` instead
3963
- */
3964
- declare function clearRootUniforms(set: ReturnType<typeof useStore>['setState']): void;
3965
-
3966
- /**
3967
- * Supported uniform value types:
3968
- * - Raw values: number, boolean, Vector2, Vector3, Vector4, Color, Matrix3, Matrix4
3969
- * - String colors: '#ff0000', 'red', 'rgb(255,0,0)' (auto-converted to Color)
3970
- * - TSL nodes: color(), vec3(), float(), etc. (for type casting)
3971
- * - UniformNode: existing uniforms (reused as-is)
3972
- */
3973
- type UniformValue = number | boolean | string | Vector2$1 | Vector3$1 | Vector4$1 | Color$2 | Matrix3$1 | Matrix4$1 | Node | UniformNode;
3974
- /**
3975
- * Widen literal types to their base types:
3976
- * - 0 → number
3977
- * - true → boolean
3978
- * - '#ff0000' → Color (string colors are converted to Color objects)
3979
- * - Node → Node (TSL nodes passed through for uniform type casting)
3980
- */
3981
- type Widen<T> = T extends number ? number : T extends boolean ? boolean : T extends string ? Color$2 : T;
3982
- declare function useUniform<T extends UniformValue>(name: string): UniformNode<T>;
3983
- declare function useUniform<T extends UniformValue>(name: string, value: T): UniformNode<Widen<T>>;
3984
-
3985
- /**
3986
- * Minimal interface for TSL nodes. The definition lives with the store types as `NodeLike`, so
3987
- * the shape creators may return and the shape `state.nodes` holds are the same type by
3988
- * construction. See `NodeLike` for why this is structural rather than three's `Node`.
3989
- */
3990
- type TSLNodeLike = NodeLike;
3991
- /** TSL node type - alias for compatibility */
3992
- type TSLNode = TSLNodeLike;
3993
- /**
3994
- * Creator function that returns a record of nodes.
3995
- * Uses TSLNodeLike constraint to allow mixed node types
3996
- * (e.g., { n: OperatorNode; color: ConstNode<Color> }) to pass type checking.
3997
- */
3998
- type NodeCreator<T extends Record<string, TSLNodeLike>> = (state: CreatorState) => T;
3999
- /** Function signature for removeNodes util */
4000
- type RemoveNodesFn = (names: string | string[], scope?: string) => void;
4001
- /** Function signature for clearNodes util */
4002
- type ClearNodesFn = (scope?: string) => void;
4003
- /** Function signature for rebuildNodes util */
4004
- type RebuildNodesFn = (scope?: string) => void;
4005
- /** Return type with utils included */
4006
- type NodesWithUtils<T extends Record<string, TSLNodeLike> = Record<string, TSLNodeLike>> = T & {
4007
- removeNodes: RemoveNodesFn;
4008
- clearNodes: ClearNodesFn;
4009
- rebuildNodes: RebuildNodesFn;
4010
- };
4011
- declare function useNodes(): NodesWithUtils<Record<string, TSLNodeLike> & Record<string, Record<string, TSLNodeLike>>>;
4012
- declare function useNodes(scope: string): NodesWithUtils<Record<string, TSLNodeLike>>;
4013
- declare function useNodes<T extends Record<string, TSLNodeLike>>(creator: NodeCreator<T>): NodesWithUtils<T>;
4014
- declare function useNodes<T extends Record<string, TSLNodeLike>>(creator: NodeCreator<T>, scope: string): NodesWithUtils<T>;
4015
- /**
4016
- * Global rebuildNodes function for HMR integration.
4017
- * Invalidates cached nodes and increments _hmrVersion to trigger re-creation.
4018
- * Call this when HMR is detected to refresh all node creators.
4019
- *
4020
- * Resolves to the primary store so shared TSL resources rebuild on the
4021
- * authoritative store.
4022
- *
4023
- * @param store - The R3F store (from useStore or context)
4024
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4025
- */
4026
- declare function rebuildAllNodes(store: ReturnType<typeof useStore>, scope?: string): void;
4027
- /**
4028
- * Remove nodes by name from root level or a scope
4029
- * @deprecated Use `const { removeNodes } = useNodes()` instead
4030
- */
4031
- declare function removeNodes(set: ReturnType<typeof useStore>['setState'], names: string[], scope?: string): void;
4032
- /**
4033
- * Clear all nodes from a scope (removes the entire scope object)
4034
- * @deprecated Use `const { clearNodes } = useNodes()` instead
4035
- */
4036
- declare function clearNodeScope(set: ReturnType<typeof useStore>['setState'], scope: string): void;
4037
- /**
4038
- * Clear all root-level nodes (preserves scopes)
4039
- * @deprecated Use `const { clearNodes } = useNodes()` with `clearNodes('root')` instead
4040
- */
4041
- declare function clearRootNodes(set: ReturnType<typeof useStore>['setState']): void;
4042
-
4043
- /** Creator receives CreatorState with ScopedStore wrappers for type-safe access. Returns any record. */
4044
- type LocalNodeCreator<T extends Record<string, unknown>> = (state: CreatorState) => T;
4045
- /**
4046
- * Creates local values that rebuild when uniforms, nodes, or textures change.
4047
- *
4048
- * Unlike `useNodes`, this does NOT register to the global store.
4049
- * Use for component-specific nodes/values that depend on shared resources.
4050
- *
4051
- * @example
4052
- * ```tsx
4053
- * // Destructure what you need from state
4054
- * const { wobble, uTime } = useLocalNodes(({ uniforms, nodes }) => ({
4055
- * wobble: sin(uniforms.uTime.mul(2)),
4056
- * uTime: uniforms.uTime, // can return uniforms too
4057
- * }))
4058
- *
4059
- * // Or access anything else from RootState
4060
- * const { scaled } = useLocalNodes(({ camera, nodes }) => ({
4061
- * scaled: nodes.basePos.mul(camera.zoom),
4062
- * }))
4063
- *
4064
- * // Type-safe uniform access
4065
- * const { colorNode } = useLocalNodes(({ uniforms }) => {
4066
- * const uValue = uniforms.myUniform as UniformNode<number>
4067
- * return { colorNode: mix(colorA, colorB, uValue) }
4068
- * })
4069
- * ```
4070
- */
4071
- declare function useLocalNodes<T extends Record<string, unknown>>(creator: LocalNodeCreator<T>): T;
4072
-
4073
- /**
4074
- * Creator function that returns a record of buffers.
4075
- * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4076
- */
4077
- type BufferCreator<T extends Record<string, BufferLike>> = (state: CreatorState) => T;
4078
- /** Function signature for removeBuffers util */
4079
- type RemoveBuffersFn = (names: string | string[], scope?: string) => void;
4080
- /** Function signature for clearBuffers util */
4081
- type ClearBuffersFn = (scope?: string) => void;
4082
- /** Function signature for rebuildBuffers util */
4083
- type RebuildBuffersFn = (scope?: string) => void;
4084
- /** Function signature for disposeBuffers util - releases GPU resources */
4085
- type DisposeBuffersFn = (names: string | string[], scope?: string) => void;
4086
- /** Return type with utils included */
4087
- type BuffersWithUtils<T extends Record<string, BufferLike> = Record<string, BufferLike>> = T & {
4088
- removeBuffers: RemoveBuffersFn;
4089
- clearBuffers: ClearBuffersFn;
4090
- rebuildBuffers: RebuildBuffersFn;
4091
- disposeBuffers: DisposeBuffersFn;
4092
- };
4093
- declare function useBuffers(): BuffersWithUtils<Record<string, BufferLike> & Record<string, Record<string, BufferLike>>>;
4094
- declare function useBuffers(scope: string): BuffersWithUtils<Record<string, BufferLike>>;
4095
- declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>): BuffersWithUtils<T>;
4096
- declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>, scope: string): BuffersWithUtils<T>;
4097
- /**
4098
- * Global rebuildBuffers function for HMR integration.
4099
- * Invalidates cached buffers and increments _hmrVersion to trigger re-creation.
4100
- * Call this when HMR is detected to refresh all buffer creators.
4101
- *
4102
- * Resolves to the primary store so shared TSL resources rebuild on the
4103
- * authoritative store.
4104
- *
4105
- * @param store - The R3F store (from useStore or context)
4106
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4107
- */
4108
- declare function rebuildAllBuffers(store: ReturnType<typeof useStore>, scope?: string): void;
4109
-
4110
- /**
4111
- * Creator function that returns a record of GPU storage objects.
4112
- * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4113
- */
4114
- type StorageCreator<T extends Record<string, StorageLike>> = (state: CreatorState) => T;
4115
- /** Function signature for removeStorage util */
4116
- type RemoveStorageFn = (names: string | string[], scope?: string) => void;
4117
- /** Function signature for clearStorage util */
4118
- type ClearStorageFn = (scope?: string) => void;
4119
- /** Function signature for rebuildStorage util */
4120
- type RebuildStorageFn = (scope?: string) => void;
4121
- /** Function signature for disposeStorage util - releases GPU resources */
4122
- type DisposeStorageFn = (names: string | string[], scope?: string) => void;
4123
- /** Return type with utils included */
4124
- type StorageWithUtils<T extends Record<string, StorageLike> = Record<string, StorageLike>> = T & {
4125
- removeStorage: RemoveStorageFn;
4126
- clearStorage: ClearStorageFn;
4127
- rebuildStorage: RebuildStorageFn;
4128
- disposeStorage: DisposeStorageFn;
4129
- };
4130
- declare function useGPUStorage(): StorageWithUtils<Record<string, StorageLike> & Record<string, Record<string, StorageLike>>>;
4131
- declare function useGPUStorage(scope: string): StorageWithUtils<Record<string, StorageLike>>;
4132
- declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>): StorageWithUtils<T>;
4133
- declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>, scope: string): StorageWithUtils<T>;
4134
- /**
4135
- * Global rebuildStorage function for HMR integration.
4136
- * Invalidates cached storage and increments _hmrVersion to trigger re-creation.
4137
- * Call this when HMR is detected to refresh all storage creators.
4138
- *
4139
- * Resolves to the primary store so shared TSL resources rebuild on the
4140
- * authoritative store.
4141
- *
4142
- * @param store - The R3F store (from useStore or context)
4143
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4144
- */
4145
- declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: string): void;
4146
87
 
4147
88
  /**
4148
89
  * Re-export from core - useTextures is now a core R3F hook (a reactive Texture registry).
@@ -4154,12 +95,12 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
4154
95
  * @deprecated The registry now stores plain `Texture` objects, not TSL nodes. Use `Texture` directly.
4155
96
  * Kept as an alias for backwards compatibility.
4156
97
  */
4157
- type TextureEntry = Texture$1;
98
+ type TextureEntry = Texture;
4158
99
  /**
4159
100
  * @deprecated The registry now stores plain `Texture` objects, not TSL nodes. Use `Texture` directly.
4160
101
  * Kept as an alias for backwards compatibility.
4161
102
  */
4162
- type TextureNode = Texture$1;
103
+ type TextureNode = Texture;
4163
104
 
4164
105
  interface TextureOperations {
4165
106
  add: (key: string, value: any) => void;
@@ -4169,49 +110,6 @@ interface TextureOperations {
4169
110
  }
4170
111
  declare function createTextureOperations(set: StoreApi<RootState>['setState']): TextureOperations;
4171
112
 
4172
- /**
4173
- * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
4174
- *
4175
- * Features:
4176
- * - Creates RenderPipeline instance if not exists
4177
- * - Creates default scenePass (no MRT) automatically
4178
- * - Callbacks receive full RootState for flexibility
4179
- * - No auto-cleanup on unmount - use reset() for explicit cleanup
4180
- * - Scene/camera changes trigger scenePass recreation
4181
- * - A replaced scenePass is disposed once the new graph is installed, so rebuild() does not
4182
- * strand its render target (and MRT attachments) on the GPU
4183
- * - Any run that changes the output node sets RenderPipeline.needsUpdate, so rebuild() actually
4184
- * recompiles instead of silently keeping the first compiled graph
4185
- *
4186
- * @param mainCB - Main callback to configure outputNode and create effect passes
4187
- * @param setupCB - Optional setup callback to configure MRT on scenePass
4188
- * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
4189
- *
4190
- * @example
4191
- * ```tsx
4192
- * // Simple effect
4193
- * useRenderPipeline(({ renderPipeline, passes }) => {
4194
- * renderPipeline.outputNode = bloom(passes.scenePass.getTextureNode())
4195
- * })
4196
- *
4197
- * // With MRT setup
4198
- * useRenderPipeline(
4199
- * ({ renderPipeline, passes }) => {
4200
- * const beauty = passes.scenePass.getTextureNode().toInspector('Color')
4201
- * const vel = passes.scenePass.getTextureNode('velocity')
4202
- * renderPipeline.outputNode = motionBlur(beauty, vel)
4203
- * },
4204
- * ({ passes }) => {
4205
- * passes.scenePass.setMRT(mrt({ output, velocity }))
4206
- * }
4207
- * )
4208
- *
4209
- * // Read-only access
4210
- * const { renderPipeline, passes } = useRenderPipeline()
4211
- * ```
4212
- */
4213
- declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
4214
-
4215
113
  //* Renderer Props ========================================
4216
114
 
4217
115
  type WebGPUDefaultProps = Omit<WebGPURendererParameters, 'canvas'> & BaseRendererProps
@@ -4259,23 +157,46 @@ interface WebGPURootState extends Omit<RootState, 'renderer' | 'gl' | 'internal'
4259
157
  internal: WebGPUInternalState
4260
158
  }
4261
159
 
4262
- /**
4263
- * @fileoverview WebGPU entry point - WebGPU only, no legacy WebGL
4264
- *
4265
- * This entry point is for apps that want to use ONLY WebGPURenderer.
4266
- * Includes WebGPU-specific hooks (useUniforms, useNodes, useTextures).
4267
- * Auto-extends THREE with WebGPU node materials (MeshBasicNodeMaterial, etc.)
4268
- *
4269
- * Usage:
4270
- * import { Canvas, useFrame, useUniforms } from '@react-three/fiber/webgpu'
4271
- */
160
+ declare const R3F_BUILD_LEGACY = false;
161
+ declare const R3F_BUILD_WEBGPU = true;
162
+ /** Create a root that always constructs a WebGPURenderer. */
163
+ declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
4272
164
 
4273
165
  /** `useThree` narrowed to WebGPU state — `state.renderer` is a `WebGPURenderer`. */
4274
166
  type UseThreeWebGPU = <T = WebGPURootState>(selector?: (state: WebGPURootState) => T, equalityFn?: <U>(state: U, newState: U) => boolean) => T;
4275
167
  /** `useFrame` narrowed to WebGPU state — the callback's `state.renderer` is a `WebGPURenderer`. */
4276
- type UseFrameWebGPU = (callback?: FrameCallback$1<WebGPURootState>, priorityOrOptions?: number | UseFrameNextOptions) => FrameNextControls;
168
+ type UseFrameWebGPU = (callback?: FrameCallback<WebGPURootState>, priorityOrOptions?: number | UseFrameNextOptions) => FrameNextControls;
4277
169
  declare const useThree: UseThreeWebGPU;
4278
170
  declare const useFrame: UseFrameWebGPU;
171
+ /** `useRenderTarget` narrowed to the target this entry's renderer produces. */
172
+ declare const useRenderTarget: {
173
+ (options?: RenderTargetOptions): RenderTarget;
174
+ (size: number, options?: RenderTargetOptions): RenderTarget;
175
+ (width: number, height: number, options?: RenderTargetOptions): RenderTarget;
176
+ };
177
+
178
+ /** Canvas props on the WebGPU entry: `onCreated` receives `WebGPURootState`. */
179
+ type WebGPUCanvasProps = Omit<CanvasProps, 'onCreated'> & {
180
+ /** Callback after the canvas has rendered (but not yet committed); `state.renderer` is a `WebGPURenderer` */
181
+ onCreated?: (state: WebGPURootState) => void;
182
+ };
183
+
184
+ /**
185
+ * A DOM canvas which accepts threejs elements as children, rendered with WebGPU. `onCreated` is
186
+ * typed against `WebGPURootState`.
187
+ * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
188
+ */
189
+ declare const Canvas: (props: WebGPUCanvasProps) => JSX.Element;
190
+ /** Three.js constructors available as JSX elements on this entry. */
191
+ type ThreeExports = typeof ThreeWebGPU;
192
+ interface ThreeElements extends ThreeElementsOf$1<ThreeExports> {
193
+ }
194
+ declare module 'react' {
195
+ namespace JSX {
196
+ interface IntrinsicElements extends ThreeElements {
197
+ }
198
+ }
199
+ }
4279
200
 
4280
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Texture, _roots, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, swapInteractivity, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
4281
- export type { Act, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferCreator, BufferLike, BufferRecord, BufferStore, BuffersWithUtils, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, ClearBuffersFn, ClearNodesFn, ClearStorageFn, ClearUniformsFn, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, CreatorState, DefaultGLProps, DefaultRendererProps, Disposable, DisposeBuffersFn, DisposeOptions, DisposeStorageFn, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameNextCallback, FrameNextState, FrameState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, WebGPUInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, LocalNodeCreator, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeCreator, NodeLike, NodeProps, NodeStore, NodesWithUtils, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, WebGPUR3FRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, RebuildBuffersFn, RebuildNodesFn, RebuildStorageFn, RebuildUniformsFn, ReconcilerRoot, RemoveBuffersFn, RemoveNodesFn, RemoveStorageFn, RemoveUniformsFn, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, WebGPURootState as RootState, RootStore, ScopedStoreType, SetBlock, Size, StorageCreator, StorageLike, StorageRecord, StorageStore, StorageWithUtils, Subscription, TSLNode, TSLNodeInput, TextureEntry, TextureInput, TextureNode, TextureOperations, TextureResult, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UniformCreator, UniformValue, UniformsWithUtils, UseFrameWebGPU, UseTextureOptions, UseTexturesReturn, UseThreeWebGPU, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig, XRManager, XRPointerConfig };
201
+ export { BaseRendererProps, RootState as BaseRootState, Canvas, Color$1 as Color, ConstructorRepresentation, ElementOf$1 as ElementOf, ElementProps$1 as ElementProps, Euler$1 as Euler, EventProps$1 as EventProps, GeometryProps$1 as GeometryProps, GeometryTransformProps$1 as GeometryTransformProps, Layers$1 as Layers, MathProps$1 as MathProps, MathRepresentation$1 as MathRepresentation, MathType$1 as MathType, MathTypes$1 as MathTypes, Matrix3$1 as Matrix3, Matrix4$1 as Matrix4, MutableOrReadonlyParameters$1 as MutableOrReadonlyParameters, NodeProps$1 as NodeProps, Object3DMethod$1 as Object3DMethod, Properties, Quaternion$1 as Quaternion, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, RaycastableRepresentation$1 as RaycastableRepresentation, ReactProps$1 as ReactProps, webgpu_d as ReactThreeFiber, ReconcilerRoot, RenderTargetOptions, RendererFactory, TSLNodeInput$1 as TSLNodeInput, ThreeElement$1 as ThreeElement, ThreeElementsOf$1 as ThreeElementsOf, ThreeToJSXElements$1 as ThreeToJSXElements, Vector2$1 as Vector2, Vector3$1 as Vector3, Vector4$1 as Vector4, VectorRepresentation$1 as VectorRepresentation, createRoot, createTextureOperations, useFrame, useRenderTarget, useThree };
202
+ export type { WebGPUCanvasProps as CanvasProps, WebGPUInternalState as InternalState, WebGPUR3FRenderer as R3FRenderer, WebGPURootState as RootState, TextureEntry, TextureNode, TextureOperations, ThreeElements, ThreeExports, UseFrameWebGPU, UseThreeWebGPU, WebGPUCanvasProps, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig };