@react-three/fiber 10.0.0-canary.dc0ec15 → 10.0.0-canary.e53bd54

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