@react-three/fiber 10.0.0-alpha.2 → 10.0.0-canary.0f8db17

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.
package/dist/legacy.d.mts CHANGED
@@ -1,13 +1,16 @@
1
1
  import * as THREE$1 from 'three';
2
- import { WebGLRenderTarget, Color as Color$1, ColorRepresentation, RenderTargetOptions as RenderTargetOptions$1, Euler as Euler$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Quaternion as Quaternion$1, Matrix3 as Matrix3$1, Matrix4 as Matrix4$1, Object3D, Texture as Texture$1, Frustum, OrthographicCamera } from 'three';
2
+ import { WebGLCubeRenderTarget, WebGLRenderTarget, Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Node as Node$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera } from 'three';
3
3
  import * as React$1 from 'react';
4
4
  import { ReactNode, Component, RefObject, JSX } from 'react';
5
+ import * as three_webgpu from 'three/webgpu';
6
+ import { WebGPURenderer as WebGPURenderer$1, Node, StorageTexture, Data3DTexture, CanvasTarget, ShaderNodeObject } from 'three/webgpu';
5
7
  import { StoreApi } from 'zustand';
6
8
  import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
7
- import * as three_webgpu from 'three/webgpu';
8
- import { Node, ShaderNodeObject } from 'three/webgpu';
9
+ import { FrameTimingState, FrameCallback as FrameCallback$1, SchedulerApi, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
10
+ export { AddPhaseOptions, FrameControls, FrameNextControls, FrameTimingState, RootOptions, Scheduler, SchedulerApi, UseFrameNextOptions, UseFrameOptions, getScheduler } from '@pmndrs/scheduler';
9
11
  import { Options } from 'react-use-measure';
10
12
  import * as react_jsx_runtime from 'react/jsx-runtime';
13
+ import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
11
14
 
12
15
  function _mergeNamespaces(n, m) {
13
16
  m.forEach(function (e) {
@@ -44,8 +47,12 @@ declare const WebGPURenderer: {
44
47
 
45
48
  declare const RenderTarget: any;
46
49
 
50
+ declare const CubeRenderTarget: any;
51
+
47
52
  var THREE = /*#__PURE__*/_mergeNamespaces({
48
53
  __proto__: null,
54
+ CubeRenderTarget: CubeRenderTarget,
55
+ CubeRenderTargetCompat: WebGLCubeRenderTarget,
49
56
  Inspector: Inspector,
50
57
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
51
58
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
@@ -54,1282 +61,1418 @@ var THREE = /*#__PURE__*/_mergeNamespaces({
54
61
  WebGPURenderer: WebGPURenderer
55
62
  }, [THREE$1]);
56
63
 
57
- //* Utility Types ==============================
58
-
59
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
60
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
61
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
62
- type Mutable<P> = { [K in keyof P]: P[K] | Readonly<P[K]> }
63
- type IsOptional<T> = undefined extends T ? true : false
64
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
65
- ? IsOptional<First> extends true
66
- ? IsAllOptional<Rest>
67
- : false
68
- : true
69
-
70
- //* Camera Types ==============================
71
-
72
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
73
-
74
- //* Act Type ==============================
75
-
76
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
77
-
78
- //* Bridge & Block Types ==============================
79
-
80
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
81
-
82
- type SetBlock = false | Promise<null> | null
83
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
84
-
85
- //* Object Map Type ==============================
86
-
87
- interface ObjectMap {
88
- nodes: { [name: string]: THREE$1.Object3D }
89
- materials: { [name: string]: THREE$1.Material }
90
- meshes: { [name: string]: THREE$1.Mesh }
91
- }
92
-
93
- //* Equality Config ==============================
94
-
95
- interface EquConfig {
96
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
97
- arrays?: 'reference' | 'shallow'
98
- /** Compare objects by reference equality a === b (default), or by shallow equality */
99
- objects?: 'reference' | 'shallow'
100
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
101
- strict?: boolean
102
- }
103
-
104
- //* Disposable Type ==============================
105
-
106
- interface Disposable {
107
- type?: string
108
- dispose?: () => void
109
- }
110
-
111
- //* Event-related Types =====================================
112
-
113
- interface Intersection extends THREE$1.Intersection {
114
- /** The event source (the object which registered the handler) */
115
- eventObject: THREE$1.Object3D
116
- }
117
-
118
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
119
-
120
- interface IntersectionEvent<TSourceEvent> extends Intersection {
121
- /** The event source (the object which registered the handler) */
122
- eventObject: THREE$1.Object3D
123
- /** An array of intersections */
124
- intersections: Intersection[]
125
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
126
- unprojectedPoint: THREE$1.Vector3
127
- /** Normalized event coordinates */
128
- pointer: THREE$1.Vector2
129
- /** Delta between first click and this event */
130
- delta: number
131
- /** The ray that pierced it */
132
- ray: THREE$1.Ray
133
- /** The camera that was used by the raycaster */
134
- camera: Camera
135
- /** stopPropagation will stop underlying handlers from firing */
136
- stopPropagation: () => void
137
- /** The original host event */
138
- nativeEvent: TSourceEvent
139
- /** If the event was stopped by calling stopPropagation */
140
- stopped: boolean
141
- }
142
-
143
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
144
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
145
-
146
- /** DOM event handlers registered on the canvas element */
147
- interface Events {
148
- onClick: EventListener
149
- onContextMenu: EventListener
150
- onDoubleClick: EventListener
151
- onWheel: EventListener
152
- onPointerDown: EventListener
153
- onPointerUp: EventListener
154
- onPointerLeave: EventListener
155
- onPointerMove: EventListener
156
- onPointerCancel: EventListener
157
- onLostPointerCapture: EventListener
158
- onDragEnter: EventListener
159
- onDragLeave: EventListener
160
- onDragOver: EventListener
161
- onDrop: EventListener
162
- }
163
-
164
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
165
- interface EventHandlers {
166
- onClick?: (event: ThreeEvent<MouseEvent>) => void
167
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
168
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
169
- /** Fires continuously while dragging over the object */
170
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
171
- /** Fires once when drag enters the object */
172
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
173
- /** Fires once when drag leaves the object */
174
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
175
- /** Fires when drag misses this object (for objects that have drag handlers) */
176
- onDragOverMissed?: (event: DragEvent) => void
177
- /** Fires when a drop occurs on this object */
178
- onDrop?: (event: ThreeEvent<DragEvent>) => void
179
- /** Fires when a drop misses this object (for objects that have drop handlers) */
180
- onDropMissed?: (event: DragEvent) => void
181
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
182
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
183
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
184
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
185
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
186
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
187
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
188
- onPointerMissed?: (event: MouseEvent) => void
189
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
190
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
191
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
192
-
193
- //* Visibility Events --------------------------------
194
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
195
- onFramed?: (inView: boolean) => void
196
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
197
- onOccluded?: (occluded: boolean) => void
198
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
199
- onVisible?: (visible: boolean) => void
200
- }
201
-
202
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
203
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
204
-
205
- interface EventManager<TTarget> {
206
- /** Determines if the event layer is active */
207
- enabled: boolean
208
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
209
- priority: number
210
- /** The compute function needs to set up the raycaster and an xy- pointer */
211
- compute?: ComputeFunction
212
- /** The filter can re-order or re-structure the intersections */
213
- filter?: FilterFunction
214
- /** The target node the event layer is tied to */
215
- connected?: TTarget
216
- /** All the pointer event handlers through which the host forwards native events */
217
- handlers?: Events
218
- /** Allows re-connecting to another target */
219
- connect?: (target: TTarget) => void
220
- /** Removes all existing events handlers from the target */
221
- disconnect?: () => void
222
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
223
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
224
- */
225
- update?: () => void
226
- }
227
-
228
- interface PointerCaptureTarget {
229
- intersection: Intersection
230
- target: Element
231
- }
232
-
233
- //* Visibility System Types =====================================
234
-
235
- /** Entry in the visibility registry for tracking object visibility state */
236
- interface VisibilityEntry {
237
- object: THREE$1.Object3D
238
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
239
- lastFramedState: boolean | null
240
- lastOccludedState: boolean | null
241
- lastVisibleState: boolean | null
242
- }
243
-
244
- //* Scheduler Types (useFrame) ==============================
245
-
246
-
247
-
248
- // Public Options --------------------------------
249
-
250
- /**
251
- * Options for useFrame hook
252
- */
253
- interface UseFrameNextOptions {
254
- /** Optional stable id for the job. Auto-generated if not provided */
255
- id?: string
256
- /** Named phase to run in. Default: 'update' */
257
- phase?: string
258
- /** Run before this phase or job id */
259
- before?: string | string[]
260
- /** Run after this phase or job id */
261
- after?: string | string[]
262
- /** Priority within phase. Higher runs first. Default: 0 */
263
- priority?: number
264
- /** Max frames per second for this job */
265
- fps?: number
266
- /** If true, skip frames when behind. If false, try to catch up. Default: true */
267
- drop?: boolean
268
- /** Enable/disable without unregistering. Default: true */
269
- enabled?: boolean
270
- }
271
-
272
- /** Alias for UseFrameNextOptions */
273
- type UseFrameOptions = UseFrameNextOptions
274
-
275
- /**
276
- * Options for addPhase
277
- */
278
- interface AddPhaseOptions {
279
- /** Insert this phase before the specified phase */
280
- before?: string
281
- /** Insert this phase after the specified phase */
282
- after?: string
283
- }
284
-
285
- // Frame State --------------------------------
286
-
287
- /**
288
- * Timing-only state for independent/outside mode (no RootState)
289
- */
290
- interface FrameTimingState {
291
- /** High-resolution timestamp from RAF (ms) */
292
- time: number
293
- /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
294
- delta: number
295
- /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
296
- elapsed: number
297
- /** Incrementing frame counter */
298
- frame: number
299
- }
300
-
301
- /**
302
- * State passed to useFrame callbacks (extends RootState with timing)
303
- */
304
- interface FrameNextState extends RootState, FrameTimingState {}
305
-
306
- /** Alias for FrameNextState */
307
- type FrameState = FrameNextState
308
-
309
- // Root Options --------------------------------
310
-
311
- /**
312
- * Options for registerRoot
313
- */
314
- interface RootOptions {
315
- /** State provider for callbacks. Optional in independent mode. */
316
- getState?: () => any
317
- /** Error handler for job errors. Falls back to console.error if not provided. */
318
- onError?: (error: Error) => void
319
- }
320
-
321
- // Callback Types --------------------------------
322
-
323
- /**
324
- * Callback function for useFrame
325
- */
326
- type FrameNextCallback = (state: FrameNextState, delta: number) => void
327
-
328
- /** Alias for FrameNextCallback */
329
- type FrameCallback = FrameNextCallback
330
-
331
- // Controls returned from useFrame --------------------------------
332
-
333
- /**
334
- * Controls object returned from useFrame hook
335
- */
336
- interface FrameNextControls {
337
- /** The job's unique ID */
338
- id: string
339
- /** Access to the global scheduler for frame loop control */
340
- scheduler: SchedulerApi
341
- /** Manually step this job only (bypasses FPS limiting) */
342
- step(timestamp?: number): void
343
- /** Manually step ALL jobs in the scheduler */
344
- stepAll(timestamp?: number): void
345
- /** Pause this job (set enabled=false) */
346
- pause(): void
347
- /** Resume this job (set enabled=true) */
348
- resume(): void
349
- /** Reactive paused state - automatically triggers re-render when changed */
350
- isPaused: boolean
351
- }
352
-
353
- /** Alias for FrameNextControls */
354
- type FrameControls = FrameNextControls
355
-
356
- // Scheduler Interface --------------------------------
357
-
358
- /**
359
- * Public interface for the global Scheduler
360
- */
361
- interface SchedulerApi {
362
- //* Phase Management --------------------------------
363
-
364
- /** Add a named phase to the scheduler */
365
- addPhase(name: string, options?: AddPhaseOptions): void
366
- /** Get the ordered list of phase names */
367
- readonly phases: string[]
368
- /** Check if a phase exists */
369
- hasPhase(name: string): boolean
370
-
371
- //* Root Management --------------------------------
372
-
373
- /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
374
- registerRoot(id: string, options?: RootOptions): () => void
375
- /** Unregister a root */
376
- unregisterRoot(id: string): void
377
- /** Generate a unique root ID */
378
- generateRootId(): string
379
- /** Get the number of registered roots */
380
- getRootCount(): number
381
- /** Check if any root is registered and ready */
382
- readonly isReady: boolean
383
- /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
384
- onRootReady(callback: () => void): () => void
385
-
386
- //* Job Registration --------------------------------
387
-
388
- /** Register a job with the scheduler (returns unsubscribe function) */
389
- register(
390
- callback: FrameNextCallback,
391
- options?: {
392
- id?: string
393
- rootId?: string
394
- phase?: string
395
- before?: string | string[]
396
- after?: string | string[]
397
- priority?: number
398
- fps?: number
399
- drop?: boolean
400
- enabled?: boolean
401
- },
402
- ): () => void
403
- /** Update a job's options */
404
- updateJob(
405
- id: string,
406
- options: {
407
- priority?: number
408
- fps?: number
409
- drop?: boolean
410
- enabled?: boolean
411
- phase?: string
412
- before?: string | string[]
413
- after?: string | string[]
414
- },
415
- ): void
416
- /** Unregister a job by ID */
417
- unregister(id: string, rootId?: string): void
418
- /** Get the number of registered jobs */
419
- getJobCount(): number
420
- /** Get all job IDs */
421
- getJobIds(): string[]
422
-
423
- //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
424
-
425
- /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
426
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
427
-
428
- //* Idle Callbacks (for legacy addTail) --------------------------------
429
-
430
- /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
431
- onIdle(callback: (timestamp: number) => void): () => void
432
-
433
- //* Frame Loop Control --------------------------------
434
-
435
- /** Start the scheduler loop */
436
- start(): void
437
- /** Stop the scheduler loop */
438
- stop(): void
439
- /** Check if the scheduler is running */
440
- readonly isRunning: boolean
441
- /** Get/set the frameloop mode ('always', 'demand', 'never') */
442
- frameloop: Frameloop
443
- /** Independent mode - runs without Canvas, callbacks receive timing-only state */
444
- independent: boolean
445
-
446
- //* Manual Stepping --------------------------------
447
-
448
- /** Manually step all jobs once (for frameloop='never' or testing) */
449
- step(timestamp?: number): void
450
- /** Manually step a single job by ID */
451
- stepJob(id: string, timestamp?: number): void
452
- /** Request frame(s) to be rendered (for frameloop='demand') */
453
- invalidate(frames?: number): void
454
-
455
- //* Per-Job Control --------------------------------
456
-
457
- /** Check if a job is paused */
458
- isJobPaused(id: string): boolean
459
- /** Pause a job */
460
- pauseJob(id: string): void
461
- /** Resume a job */
462
- resumeJob(id: string): void
463
- /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
464
- subscribeJobState(id: string, listener: () => void): () => void
465
- }
466
-
467
- //* Core Store Types ========================================
468
-
469
- type Subscription = {
470
- ref: React$1.RefObject<RenderCallback>
471
- priority: number
472
- store: RootStore
473
- }
474
-
475
- type Dpr = number | [min: number, max: number]
476
-
477
- interface Size {
478
- width: number
479
- height: number
480
- top: number
481
- left: number
482
- }
483
-
484
- type Frameloop = 'always' | 'demand' | 'never'
485
-
486
- interface Viewport extends Size {
487
- /** The initial pixel ratio */
488
- initialDpr: number
489
- /** Current pixel ratio */
490
- dpr: number
491
- /** size.width / viewport.width */
492
- factor: number
493
- /** Camera distance */
494
- distance: number
495
- /** Camera aspect ratio: width / height */
496
- aspect: number
497
- }
498
-
499
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
500
-
501
- interface Performance {
502
- /** Current performance normal, between min and max */
503
- current: number
504
- /** How low the performance can go, between 0 and max */
505
- min: number
506
- /** How high the performance can go, between min and max */
507
- max: number
508
- /** Time until current returns to max in ms */
509
- debounce: number
510
- /** Sets current to min, puts the system in regression */
511
- regress: () => void
512
- }
513
-
514
- interface InternalState {
515
- interaction: THREE$1.Object3D[]
516
- hovered: Map<string, ThreeEvent<DomEvent>>
517
- subscribers: Subscription[]
518
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
519
- initialClick: [x: number, y: number]
520
- initialHits: THREE$1.Object3D[]
521
- lastEvent: React$1.RefObject<DomEvent | null>
522
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
523
- visibilityRegistry: Map<string, VisibilityEntry>
524
- /** Whether occlusion queries are enabled (WebGPU only) */
525
- occlusionEnabled: boolean
526
- /** Reference to the invisible occlusion observer mesh */
527
- occlusionObserver: THREE$1.Mesh | null
528
- /** Cached occlusion results from render pass - keyed by Object3D */
529
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
530
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
531
- helperGroup: THREE$1.Group | null
532
- active: boolean
533
- priority: number
534
- frames: number
535
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
536
- /** Internal renderer storage - use state.renderer or state.gl to access */
537
- actualRenderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
538
- /** Global scheduler reference (for useFrame hook) */
539
- scheduler: SchedulerApi | null
540
- /** This root's unique ID in the global scheduler */
541
- rootId?: string
542
- /** Function to unregister this root from the global scheduler */
543
- unregisterRoot?: () => void
544
- /** Container for child attachment (scene for root, original container for portals) */
545
- container?: THREE$1.Object3D
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
- /** (deprecated) The instance of the WebGLrenderer */
561
- gl: THREE$1.WebGLRenderer
562
- /** The instance of the WebGPU renderer, the fallback, OR the default renderer as a mask of gl */
563
- renderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
564
- /** Inspector of the webGPU Renderer. Init in the canvas */
565
- inspector: any // Inspector type from three/webgpu
566
-
567
- /** Default camera */
568
- camera: ThreeCamera
569
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
570
- frustum: THREE$1.Frustum
571
- /** Whether to automatically update the frustum each frame (default: true) */
572
- autoUpdateFrustum: boolean
573
- /** Default scene (may be overridden in portals to point to the portal container) */
574
- scene: THREE$1.Scene
575
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
576
- rootScene: THREE$1.Scene
577
- /** Default raycaster */
578
- raycaster: THREE$1.Raycaster
579
- /** Event layer interface, contains the event handler and the node they're connected to */
580
- events: EventManager<any>
581
- /** XR interface */
582
- xr: XRManager
583
- /** Currently used controls */
584
- controls: THREE$1.EventDispatcher | null
585
- /** Normalized event coordinates */
586
- pointer: THREE$1.Vector2
587
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
588
- mouse: THREE$1.Vector2
589
- /* Whether to enable r139's THREE.ColorManagement */
590
- legacy: boolean
591
- /** Shortcut to gl.outputColorSpace = THREE.LinearSRGBColorSpace */
592
- linear: boolean
593
- /** Shortcut to gl.toneMapping = NoTonemapping */
594
- flat: boolean
595
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
596
- textureColorSpace: THREE$1.ColorSpace
597
- /** Render loop flags */
598
- frameloop: Frameloop
599
- performance: Performance
600
- /** Reactive pixel-size of the canvas */
601
- size: Size
602
- /** Reactive size of the viewport in threejs units */
603
- viewport: Viewport & {
604
- getCurrentViewport: (
605
- camera?: ThreeCamera,
606
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
607
- size?: Size,
608
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
609
- }
610
- /** Flags the canvas for render, but doesn't render in itself */
611
- invalidate: (frames?: number, stackFrames?: boolean) => void
612
- /** Advance (render) one step */
613
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
614
- /** Shortcut to setting the event layer */
615
- setEvents: (events: Partial<EventManager<any>>) => void
616
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
617
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
618
- /** Shortcut to manual setting the pixel ratio */
619
- setDpr: (dpr: Dpr) => void
620
- /** Shortcut to setting frameloop flags */
621
- setFrameloop: (frameloop: Frameloop) => void
622
- /** Set error state to propagate to error boundary */
623
- setError: (error: Error | null) => void
624
- /** Current error state (null when no error) */
625
- error: Error | null
626
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
627
- uniforms: UniformStore
628
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
629
- nodes: Record<string, any>
630
- /** Global TSL texture nodes - use useTextures() hook for operations */
631
- textures: Map<string, any>
632
- /** WebGPU PostProcessing instance - use usePostProcessing() hook */
633
- postProcessing: any | null // THREE.PostProcessing when available
634
- /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
635
- passes: Record<string, any>
636
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
637
- _hmrVersion: number
638
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
639
- _sizeImperative: boolean
640
- /** Internal: stored size props from Canvas for reset functionality */
641
- _sizeProps: { width?: number; height?: number } | null
642
- /** When the canvas was clicked but nothing was hit */
643
- onPointerMissed?: (event: MouseEvent) => void
644
- /** When a dragover event has missed any target */
645
- onDragOverMissed?: (event: DragEvent) => void
646
- /** When a drop event has missed any target */
647
- onDropMissed?: (event: DragEvent) => void
648
- /** If this state model is layered (via createPortal) then this contains the previous layer */
649
- previousRoot?: RootStore
650
- /** Internals */
651
- internal: InternalState
652
- // flags for triggers
653
- // if we are using the webGl renderer, this will be true
654
- isLegacy: boolean
655
- // regardless of renderer, if the system supports webGpu, this will be true
656
- webGPUSupported: boolean
657
- //if we are on native
658
- isNative: boolean
659
- }
660
-
64
+ //* Utility Types ==============================
65
+
66
+ type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
67
+ type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
68
+ type Properties<T> = Pick<T, NonFunctionKeys<T>>
69
+ type Mutable<P> = { -readonly [K in keyof P]: P[K] }
70
+ type IsOptional<T> = undefined extends T ? true : false
71
+ type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
72
+ ? IsOptional<First> extends true
73
+ ? IsAllOptional<Rest>
74
+ : false
75
+ : true
76
+
77
+ //* Camera Types ==============================
78
+
79
+ type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
80
+
81
+ //* Act Type ==============================
82
+
83
+ type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
84
+
85
+ //* Bridge & Block Types ==============================
86
+
87
+ type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
88
+
89
+ type SetBlock = false | Promise<null> | null
90
+ type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
91
+
92
+ //* Object Map Type ==============================
93
+
94
+ /* Original version
95
+ export interface ObjectMap {
96
+ nodes: { [name: string]: THREE.Object3D }
97
+ materials: { [name: string]: THREE.Material }
98
+ meshes: { [name: string]: THREE.Mesh }
99
+ }
100
+ */
101
+ /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
102
+ It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
103
+ I will keep the use here)
104
+ https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
105
+ His description is:
106
+ The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
107
+ */
108
+ interface ObjectMap<
109
+ T extends { nodes?: string; materials?: string; meshes?: string } = {
110
+ nodes: string
111
+ materials: string
112
+ meshes: string
113
+ },
114
+ > {
115
+ nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
116
+ materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
117
+ meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
118
+ }
119
+
120
+ //* Equality Config ==============================
121
+
122
+ interface EquConfig {
123
+ /** Compare arrays by reference equality a === b (default), or by shallow equality */
124
+ arrays?: 'reference' | 'shallow'
125
+ /** Compare objects by reference equality a === b (default), or by shallow equality */
126
+ objects?: 'reference' | 'shallow'
127
+ /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
128
+ strict?: boolean
129
+ }
130
+
131
+ //* Disposable Type ==============================
132
+
133
+ interface Disposable {
134
+ type?: string
135
+ dispose?: () => void
136
+ }
137
+
138
+ //* Event-related Types =====================================
139
+
140
+ interface Intersection extends THREE$1.Intersection {
141
+ /** The event source (the object which registered the handler) */
142
+ eventObject: THREE$1.Object3D
143
+ }
144
+
145
+ type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
146
+
147
+ interface IntersectionEvent<TSourceEvent> extends Intersection {
148
+ /** The event source (the object which registered the handler) */
149
+ eventObject: THREE$1.Object3D
150
+ /** An array of intersections */
151
+ intersections: Intersection[]
152
+ /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
153
+ unprojectedPoint: THREE$1.Vector3
154
+ /** Normalized event coordinates */
155
+ pointer: THREE$1.Vector2
156
+ /** pointerId of the original event for multiple pointer events */
157
+ pointerId: number
158
+ /** Delta between first click and this event */
159
+ delta: number
160
+ /** The ray that pierced it */
161
+ ray: THREE$1.Ray
162
+ /** The camera that was used by the raycaster */
163
+ camera: Camera
164
+ /** stopPropagation will stop underlying handlers from firing */
165
+ stopPropagation: () => void
166
+ /** The original host event */
167
+ nativeEvent: TSourceEvent
168
+ /** If the event was stopped by calling stopPropagation */
169
+ stopped: boolean
170
+ }
171
+
172
+ type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
173
+ type DomEvent = PointerEvent | MouseEvent | WheelEvent
174
+
175
+ /** DOM event handlers registered on the canvas element */
176
+ interface Events {
177
+ onClick: EventListener
178
+ onContextMenu: EventListener
179
+ onDoubleClick: EventListener
180
+ onWheel: EventListener
181
+ onPointerDown: EventListener
182
+ onPointerUp: EventListener
183
+ onPointerLeave: EventListener
184
+ onPointerMove: EventListener
185
+ onPointerCancel: EventListener
186
+ onLostPointerCapture: EventListener
187
+ onDragEnter: EventListener
188
+ onDragLeave: EventListener
189
+ onDragOver: EventListener
190
+ onDrop: EventListener
191
+ }
192
+
193
+ /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
194
+ interface EventHandlers {
195
+ onClick?: (event: ThreeEvent<MouseEvent>) => void
196
+ onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
197
+ onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
198
+ /** Fires continuously while dragging over the object */
199
+ onDragOver?: (event: ThreeEvent<DragEvent>) => void
200
+ /** Fires once when drag enters the object */
201
+ onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
202
+ /** Fires once when drag leaves the object */
203
+ onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
204
+ /** Fires when drag misses this object (for objects that have drag handlers) */
205
+ onDragOverMissed?: (event: DragEvent) => void
206
+ /** Fires when a drop occurs on this object */
207
+ onDrop?: (event: ThreeEvent<DragEvent>) => void
208
+ /** Fires when a drop misses this object (for objects that have drop handlers) */
209
+ onDropMissed?: (event: DragEvent) => void
210
+ onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
211
+ onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
212
+ onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
213
+ onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
214
+ onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
215
+ onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
216
+ onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
217
+ onPointerMissed?: (event: MouseEvent) => void
218
+ onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
219
+ onWheel?: (event: ThreeEvent<WheelEvent>) => void
220
+ onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
221
+
222
+ //* Visibility Events --------------------------------
223
+ /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
224
+ onFramed?: (inView: boolean) => void
225
+ /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
226
+ onOccluded?: (occluded: boolean) => void
227
+ /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
228
+ onVisible?: (visible: boolean) => void
229
+ }
230
+
231
+ type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
232
+ type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
233
+
234
+ /** Configuration for XR pointer registration (controllers/hands) */
235
+ interface XRPointerConfig {
236
+ /** Ray origin (updated each frame by XR system) */
237
+ ray: THREE$1.Ray
238
+ /** Optional: custom compute function for this pointer */
239
+ compute?: (state: RootState) => void
240
+ /** Pointer type identifier */
241
+ type: 'controller' | 'hand' | 'gaze'
242
+ /** Which hand (for controller/hand types) */
243
+ handedness?: 'left' | 'right'
244
+ }
245
+
246
+ interface EventManager<TTarget> {
247
+ /** Determines if the event layer is active */
248
+ enabled: boolean
249
+ /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
250
+ priority: number
251
+ /** The compute function needs to set up the raycaster and an xy- pointer */
252
+ compute?: ComputeFunction
253
+ /** The filter can re-order or re-structure the intersections */
254
+ filter?: FilterFunction
255
+ /** The target node the event layer is tied to */
256
+ connected?: TTarget
257
+ /** All the pointer event handlers through which the host forwards native events */
258
+ handlers?: Events
259
+ /** Allows re-connecting to another target */
260
+ connect?: (target: TTarget) => void
261
+ /** Removes all existing events handlers from the target */
262
+ disconnect?: () => void
263
+ /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
264
+ * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
265
+ * @param pointerId - Optional pointer ID to update specific pointer only
266
+ */
267
+ update?: (pointerId?: number) => void
268
+ /** Defer pointer move raycasting to frame start (default: true) */
269
+ frameTimedRaycasts?: boolean
270
+ /** Always fire raycaster immediately on scroll events (default: true) */
271
+ alwaysFireOnScroll?: boolean
272
+ /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
273
+ updateOnFrame?: boolean
274
+ /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
275
+ flush?: () => void
276
+ /** Register an XR pointer (controller/hand). Returns assigned pointerId */
277
+ registerPointer?: (config: XRPointerConfig) => number
278
+ /** Unregister an XR pointer */
279
+ unregisterPointer?: (pointerId: number) => void
280
+ }
281
+
282
+ interface PointerCaptureTarget {
283
+ intersection: Intersection
284
+ target: Element
285
+ }
286
+
287
+ //* Visibility System Types =====================================
288
+
289
+ /** Entry in the visibility registry for tracking object visibility state */
290
+ interface VisibilityEntry {
291
+ object: THREE$1.Object3D
292
+ handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
293
+ lastFramedState: boolean | null
294
+ lastOccludedState: boolean | null
295
+ lastVisibleState: boolean | null
296
+ }
297
+
298
+ //* Scheduler Types (useFrame) ==============================
299
+ //
300
+ // The generic, framework-agnostic scheduler types now live in @pmndrs/scheduler.
301
+ // This file re-exports them and layers r3f's RootState-aware frame state on top,
302
+ // so existing `#types` imports across the codebase keep resolving unchanged.
303
+
304
+
305
+
306
+ // Frame State (r3f-specific) --------------------------------
307
+
308
+ /**
309
+ * State passed to useFrame callbacks (extends RootState with timing).
310
+ */
311
+ interface FrameNextState extends RootState, FrameTimingState {}
312
+
313
+ /** Alias for FrameNextState */
314
+ type FrameState = FrameNextState
315
+
316
+ // Callback Types (r3f-specific) --------------------------------
317
+
318
+ /**
319
+ * Callback function for useFrame. Receives the full r3f RootState plus timing.
320
+ */
321
+ type FrameNextCallback = FrameCallback$1<RootState>
322
+
323
+ /** Alias for FrameNextCallback */
324
+ type FrameCallback = FrameNextCallback
325
+
326
+ //* Buffer Types (useBuffers) ========================================
327
+
328
+ /**
329
+ * Buffer-like types for GPU compute and storage operations.
330
+ * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
331
+ *
332
+ * @example
333
+ * ```tsx
334
+ * const { positions, velocities } = useBuffers(() => ({
335
+ * positions: instancedArray(count, 'vec3'), // StorageBufferNode
336
+ * velocities: new Float32Array(count * 3), // TypedArray
337
+ * }), 'particles')
338
+ * ```
339
+ */
340
+ type BufferLike =
341
+ | Float32Array
342
+ | Uint32Array
343
+ | Int32Array
344
+ | Float64Array
345
+ | Uint8Array
346
+ | Int8Array
347
+ | Uint16Array
348
+ | Int16Array
349
+ | THREE$1.BufferAttribute // Base class for all buffer attributes
350
+ | Node // TSL buffer nodes (instancedArray, storage)
351
+
352
+ /** Flat record of buffer-like values (no nested scopes) */
353
+ type BufferRecord = Record<string, BufferLike>
354
+
355
+ /**
356
+ * Buffer store that can contain both root-level buffers and scoped buffer objects.
357
+ * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
358
+ */
359
+ type BufferStore = Record<string, BufferLike | BufferRecord>
360
+
361
+ //* Storage Types (useGPUStorage) ========================================
362
+
363
+ /**
364
+ * GPU storage types for texture-based storage operations.
365
+ * Includes Three.js storage textures and TSL storage texture nodes.
366
+ *
367
+ * @example
368
+ * ```tsx
369
+ * const { heightMap } = useGPUStorage(() => ({
370
+ * heightMap: new StorageTexture(512, 512),
371
+ * }), 'terrain')
372
+ * ```
373
+ */
374
+ type StorageLike =
375
+ | StorageTexture // GPU storage texture
376
+ | Data3DTexture // 3D texture (can be used as storage)
377
+ | Node // TSL storage texture nodes (storageTexture)
378
+
379
+ /** Flat record of storage-like values (no nested scopes) */
380
+ type StorageRecord = Record<string, StorageLike>
381
+
382
+ /**
383
+ * Storage store that can contain both root-level storage and scoped storage objects.
384
+ * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
385
+ */
386
+ type StorageStore = Record<string, StorageLike | StorageRecord>
387
+
388
+ //* Renderer Types ========================================
389
+
390
+ /** Default renderer type - union of WebGL and WebGPU renderers */
391
+ type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer$1
392
+
393
+ //* Core Store Types ========================================
394
+
395
+ type Subscription = {
396
+ ref: React$1.RefObject<RenderCallback>
397
+ priority: number
398
+ store: RootStore
399
+ }
400
+
401
+ /** Per-pointer state for multi-touch and XR support */
402
+ type PointerState = {
403
+ /** Objects currently hovered by this pointer */
404
+ hovered: Map<string, ThreeEvent<DomEvent>>
405
+ /** Objects capturing this pointer */
406
+ captured: Map<THREE$1.Object3D, PointerCaptureTarget>
407
+ /** Initial click position [x, y] */
408
+ initialClick: [x: number, y: number]
409
+ /** Objects hit on initial click */
410
+ initialHits: THREE$1.Object3D[]
411
+ }
412
+
413
+ type Dpr = number | [min: number, max: number]
414
+
415
+ interface Size {
416
+ width: number
417
+ height: number
418
+ top: number
419
+ left: number
420
+ }
421
+
422
+ type Frameloop = 'always' | 'demand' | 'never'
423
+
424
+ interface Viewport extends Size {
425
+ /** The initial pixel ratio */
426
+ initialDpr: number
427
+ /** Current pixel ratio */
428
+ dpr: number
429
+ /** size.width / viewport.width */
430
+ factor: number
431
+ /** Camera distance */
432
+ distance: number
433
+ /** Camera aspect ratio: width / height */
434
+ aspect: number
435
+ }
436
+
437
+ type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
438
+
439
+ interface Performance {
440
+ /** Current performance normal, between min and max */
441
+ current: number
442
+ /** How low the performance can go, between 0 and max */
443
+ min: number
444
+ /** How high the performance can go, between min and max */
445
+ max: number
446
+ /** Time until current returns to max in ms */
447
+ debounce: number
448
+ /** Sets current to min, puts the system in regression */
449
+ regress: () => void
450
+ }
451
+
452
+ interface InternalState {
453
+ interaction: THREE$1.Object3D[]
454
+ subscribers: Subscription[]
455
+ /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
456
+ pointerMap: Map<number, PointerState>
457
+ /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
458
+ pointerDirty: Map<number, DomEvent>
459
+ /** Last event received (for events.update() compatibility) */
460
+ lastEvent: React$1.RefObject<DomEvent | null>
461
+ /** @deprecated Use pointerMap.get(pointerId).hovered instead */
462
+ hovered: Map<string, ThreeEvent<DomEvent>>
463
+ /** @deprecated Use pointerMap.get(pointerId).captured instead */
464
+ capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
465
+ /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
466
+ initialClick: [x: number, y: number]
467
+ /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
468
+ initialHits: THREE$1.Object3D[]
469
+ /** Visibility event registry (onFramed, onOccluded, onVisible) */
470
+ visibilityRegistry: Map<string, VisibilityEntry>
471
+ /** Whether occlusion queries are enabled (WebGPU only) */
472
+ occlusionEnabled: boolean
473
+ /** Reference to the invisible occlusion observer mesh */
474
+ occlusionObserver: THREE$1.Mesh | null
475
+ /** Cached occlusion results from render pass - keyed by Object3D */
476
+ occlusionCache: Map<THREE$1.Object3D, boolean | null>
477
+ /** Internal helper group for R3F system objects (occlusion observer, etc.) */
478
+ helperGroup: THREE$1.Group | null
479
+ active: boolean
480
+ priority: number
481
+ frames: number
482
+ subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
483
+ /** Internal renderer storage - use state.renderer or state.gl to access */
484
+ actualRenderer: R3FRenderer
485
+ /** Global scheduler reference (for useFrame hook) */
486
+ scheduler: SchedulerApi | null
487
+ /** This root's unique ID in the global scheduler */
488
+ rootId?: string
489
+ /** Function to unregister this root from the global scheduler */
490
+ unregisterRoot?: () => void
491
+ /** Container for child attachment (scene for root, original container for portals) */
492
+ container?: THREE$1.Object3D
493
+ /**
494
+ * CanvasTarget for multi-canvas WebGPU rendering.
495
+ * Created for all WebGPU canvases to support renderer sharing.
496
+ * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
497
+ */
498
+ canvasTarget?: CanvasTarget
499
+ /**
500
+ * Whether multi-canvas rendering is active.
501
+ * True when any canvas uses `renderer={{ primaryCanvas: 'id' }}` to share a renderer.
502
+ * When true, setCanvasTarget is called before each render.
503
+ */
504
+ isMultiCanvas?: boolean
505
+ /**
506
+ * Whether this canvas is a secondary canvas sharing another's renderer.
507
+ * True when `target` prop is used.
508
+ */
509
+ isSecondary?: boolean
510
+ /**
511
+ * The id of the primary canvas this secondary canvas targets.
512
+ * Only set when isSecondary is true.
513
+ */
514
+ targetId?: string
515
+ /**
516
+ * Function to unregister this primary canvas from the registry.
517
+ * Only set when this canvas has an `id` prop.
518
+ */
519
+ unregisterPrimary?: () => void
520
+ /** Whether canvas dimensions are forced to even numbers */
521
+ forceEven?: boolean
522
+ }
523
+
524
+ interface XRManager {
525
+ connect: () => void
526
+ disconnect: () => void
527
+ }
528
+
529
+ //* Root State Interface ====================================
530
+
531
+ interface RootState {
532
+ /** Set current state */
533
+ set: StoreApi<RootState>['setState']
534
+ /** Get current state */
535
+ get: StoreApi<RootState>['getState']
536
+ /**
537
+ * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
538
+ * - For primary/independent canvases: points to its own store (self-reference)
539
+ * - For secondary canvases: points to the primary canvas's store
540
+ *
541
+ * Hooks like useNodes/useUniforms should read from primaryStore to ensure
542
+ * consistent shared state across all canvases sharing a renderer.
543
+ */
544
+ primaryStore: RootStore
545
+ /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
546
+ gl: THREE$1.WebGLRenderer
547
+ /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
548
+ renderer: R3FRenderer
549
+ /** Inspector of the webGPU Renderer. Init in the canvas */
550
+ inspector: any // Inspector type from three/webgpu
551
+
552
+ /** Default camera */
553
+ camera: ThreeCamera
554
+ /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
555
+ frustum: THREE$1.Frustum
556
+ /** Whether to automatically update the frustum each frame (default: true) */
557
+ autoUpdateFrustum: boolean
558
+ /** Default scene (may be overridden in portals to point to the portal container) */
559
+ scene: THREE$1.Scene
560
+ /** The actual root THREE.Scene - always points to the true scene, even inside portals */
561
+ rootScene: THREE$1.Scene
562
+ /** Default raycaster */
563
+ raycaster: THREE$1.Raycaster
564
+ /** Event layer interface, contains the event handler and the node they're connected to */
565
+ events: EventManager<any>
566
+ /** XR interface */
567
+ xr: XRManager
568
+ /** Currently used controls */
569
+ controls: THREE$1.EventDispatcher | null
570
+ /** Normalized event coordinates */
571
+ pointer: THREE$1.Vector2
572
+ /** @deprecated Normalized event coordinates, use "pointer" instead! */
573
+ mouse: THREE$1.Vector2
574
+ /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
575
+ textureColorSpace: THREE$1.ColorSpace
576
+ /** Render loop flags */
577
+ frameloop: Frameloop
578
+ performance: Performance
579
+ /** Reactive pixel-size of the canvas */
580
+ size: Size
581
+ /** Reactive size of the viewport in threejs units */
582
+ viewport: Viewport & {
583
+ getCurrentViewport: (
584
+ camera?: ThreeCamera,
585
+ target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
586
+ size?: Size,
587
+ ) => Omit<Viewport, 'dpr' | 'initialDpr'>
588
+ }
589
+ /** Flags the canvas for render, but doesn't render in itself */
590
+ invalidate: (frames?: number, stackFrames?: boolean) => void
591
+ /** Advance (render) one step */
592
+ advance: (timestamp: number, runGlobalEffects?: boolean) => void
593
+ /** Shortcut to setting the event layer */
594
+ setEvents: (events: Partial<EventManager<any>>) => void
595
+ /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
596
+ setSize: (width?: number, height?: number, top?: number, left?: number) => void
597
+ /** Shortcut to manual setting the pixel ratio */
598
+ setDpr: (dpr: Dpr) => void
599
+ /** Shortcut to setting frameloop flags. No args resets to 'always'. */
600
+ setFrameloop: (frameloop?: Frameloop) => void
601
+ /** Set error state to propagate to error boundary */
602
+ setError: (error: Error | null) => void
603
+ /** Current error state (null when no error) */
604
+ error: Error | null
605
+ /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
606
+ uniforms: UniformStore
607
+ /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
608
+ nodes: Record<string, any>
609
+ /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
610
+ buffers: BufferStore
611
+ /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
612
+ gpuStorage: StorageStore
613
+ /** Global Texture registry (key → Texture, usually keyed by URL) - use useTextures() hook for access + lifecycle */
614
+ textures: Map<string, THREE$1.Texture>
615
+ /** Internal: refcount per texture key, driven by mounted useTexture consumers (registry enrollment is on by default) */
616
+ _textureRefs: Map<string, number>
617
+ /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
618
+ renderPipeline: ThreeRenderPipeline | null
619
+ /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
620
+ passes: Record<string, any>
621
+ /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
622
+ _hmrVersion: number
623
+ /** Internal: whether setSize() has taken ownership of canvas dimensions */
624
+ _sizeImperative: boolean
625
+ /** Internal: stored size props from Canvas for reset functionality */
626
+ _sizeProps: { width?: number; height?: number } | null
627
+ /** When the canvas was clicked but nothing was hit */
628
+ onPointerMissed?: (event: MouseEvent) => void
629
+ /** When a dragover event has missed any target */
630
+ onDragOverMissed?: (event: DragEvent) => void
631
+ /** When a drop event has missed any target */
632
+ onDropMissed?: (event: DragEvent) => void
633
+ /** If this state model is layered (via createPortal) then this contains the previous layer */
634
+ previousRoot?: RootStore
635
+ /** Internals */
636
+ internal: InternalState
637
+ // flags for triggers
638
+ // if we are using the webGl renderer, this will be true
639
+ isLegacy: boolean
640
+ // regardless of renderer, if the system supports webGpu, this will be true
641
+ webGPUSupported: boolean
642
+ //if we are on native
643
+ isNative: boolean
644
+ }
645
+
661
646
  type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
662
647
 
663
- //* Base Renderer Types =====================================
664
-
665
- // Shim for OffscreenCanvas since it was removed from DOM types
666
- interface OffscreenCanvas$1 extends EventTarget {}
667
-
668
- interface BaseRendererProps {
669
- canvas: HTMLCanvasElement | OffscreenCanvas$1
670
- powerPreference?: 'high-performance' | 'low-power' | 'default'
671
- antialias?: boolean
672
- alpha?: boolean
673
- }
674
-
675
- type RendererFactory<TRenderer, TParams> =
676
- | TRenderer
677
- | ((defaultProps: TParams) => TRenderer)
678
- | ((defaultProps: TParams) => Promise<TRenderer>)
679
-
680
- interface Renderer {
681
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
682
- }
683
-
684
- //* WebGL Renderer Props ==============================
685
-
686
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
687
- canvas: HTMLCanvasElement | OffscreenCanvas$1
688
- }
689
-
690
- type GLProps =
691
- | Renderer
692
- | ((defaultProps: DefaultGLProps) => Renderer)
693
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
694
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
695
-
696
- //* WebGPU Renderer Props ==============================
697
-
698
- type DefaultRendererProps = {
699
- canvas: HTMLCanvasElement | OffscreenCanvas$1
700
- [key: string]: any
701
- }
702
-
703
- type RendererProps =
704
- | any // WebGPURenderer
705
- | ((defaultProps: DefaultRendererProps) => any)
706
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
707
- | Partial<Properties<any> | Record<string, any>>
708
-
709
- //* Camera Props ==============================
710
-
711
- type CameraProps = (
712
- | THREE$1.Camera
713
- | Partial<
714
- ThreeElement<typeof THREE$1.Camera> &
715
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
716
- ThreeElement<typeof THREE$1.OrthographicCamera>
717
- >
718
- ) & {
719
- /** Flags the camera as manual, putting projection into your own hands */
720
- manual?: boolean
721
- }
722
-
723
- //* Render Props ==============================
724
-
725
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
726
- /** A threejs renderer instance or props that go into the default renderer */
727
- gl?: GLProps
728
- /** A WebGPU renderer instance or props that go into the default renderer */
729
- renderer?: RendererProps
730
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
731
- size?: Size
732
- /**
733
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
734
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
735
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
736
- */
737
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
738
- /**
739
- * Disables three r139 color management.
740
- * @see https://threejs.org/docs/#manual/en/introduction/Color-management
741
- */
742
- legacy?: boolean
743
- /** Switch off automatic sRGB encoding and gamma correction */
744
- linear?: boolean
745
- /** Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` */
746
- flat?: boolean
747
- /** Working color space for automatic texture colorspace assignment. Defaults to THREE.SRGBColorSpace */
748
- /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
749
- textureColorSpace?: THREE$1.ColorSpace
750
- /** Creates an orthographic camera */
751
- orthographic?: boolean
752
- /**
753
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
754
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
755
- */
756
- frameloop?: Frameloop
757
- /**
758
- * R3F performance options for adaptive performance.
759
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
760
- */
761
- performance?: Partial<Omit<Performance, 'regress'>>
762
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
763
- dpr?: Dpr
764
- /** Props that go into the default raycaster */
765
- raycaster?: Partial<THREE$1.Raycaster>
766
- /** A `THREE.Scene` instance or props that go into the default scene */
767
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
768
- /** A `THREE.Camera` instance or props that go into the default camera */
769
- camera?: CameraProps
770
- /** An R3F event manager to manage elements' pointer events */
771
- events?: (store: RootStore) => EventManager<HTMLElement>
772
- /** Callback after the canvas has rendered (but not yet committed) */
773
- onCreated?: (state: RootState) => void
774
- /** Response for pointer clicks that have missed any target */
775
- onPointerMissed?: (event: MouseEvent) => void
776
- /** Response for dragover events that have missed any target */
777
- onDragOverMissed?: (event: DragEvent) => void
778
- /** Response for drop events that have missed any target */
779
- onDropMissed?: (event: DragEvent) => void
780
- /** Whether to automatically update the frustum each frame (default: true) */
781
- autoUpdateFrustum?: boolean
782
- /**
783
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
784
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
785
- * Only works with WebGPU renderer - WebGL will log a warning.
786
- */
787
- occlusion?: boolean
788
- /** Internal: stored size props from Canvas for reset functionality */
789
- _sizeProps?: { width?: number; height?: number } | null
790
- }
791
-
792
- //* Reconciler Root ==============================
793
-
794
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
795
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
796
- render: (element: ReactNode) => RootStore
797
- unmount: () => void
798
- }
799
-
800
- //* Inject State ==============================
801
-
802
- type InjectState = Partial<
803
- Omit<RootState, 'events'> & {
804
- events?: {
805
- enabled?: boolean
806
- priority?: number
807
- compute?: ComputeFunction
808
- connected?: any
809
- }
810
- /**
811
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
812
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
813
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
814
- */
815
- injectScene?: boolean
816
- }
648
+ //* Base Renderer Types =====================================
649
+
650
+ // Shim for OffscreenCanvas since it was removed from DOM types
651
+ interface OffscreenCanvas$1 extends EventTarget {}
652
+
653
+ interface BaseRendererProps {
654
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
655
+ powerPreference?: 'high-performance' | 'low-power' | 'default'
656
+ antialias?: boolean
657
+ alpha?: boolean
658
+ }
659
+
660
+ type RendererFactory<TRenderer, TParams> =
661
+ | TRenderer
662
+ | ((defaultProps: TParams) => TRenderer)
663
+ | ((defaultProps: TParams) => Promise<TRenderer>)
664
+
665
+ interface Renderer {
666
+ render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
667
+ }
668
+
669
+ //* Color Management Config ==============================
670
+
671
+ /**
672
+ * Color management configuration shared by both WebGL and WebGPU renderers.
673
+ */
674
+ interface ColorManagementConfig {
675
+ /**
676
+ * Color space assigned to 8-bit input textures (color maps).
677
+ * Defaults to sRGB. Most textures are authored in sRGB.
678
+ * @default THREE.SRGBColorSpace
679
+ */
680
+ textureColorSpace?: THREE$1.ColorSpace
681
+ }
682
+
683
+ //* WebGL Renderer Props ==============================
684
+
685
+ type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
686
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
687
+ }
688
+
689
+ type GLProps =
690
+ | Renderer
691
+ | ((defaultProps: DefaultGLProps) => Renderer)
692
+ | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
693
+ | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
694
+
695
+ //* WebGPU Renderer Props ==============================
696
+
697
+ type DefaultRendererProps = {
698
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
699
+ [key: string]: any
700
+ }
701
+
702
+ /**
703
+ * Canvas-level scheduler configuration.
704
+ * Controls render timing relative to other canvases.
705
+ */
706
+ interface CanvasSchedulerConfig {
707
+ /**
708
+ * Render this canvas after another canvas completes.
709
+ * Pass the `id` of another canvas.
710
+ */
711
+ after?: string
712
+ /**
713
+ * Limit this canvas's render rate (frames per second).
714
+ */
715
+ fps?: number
716
+ }
717
+
718
+ /**
719
+ * Extended renderer configuration for multi-canvas support and color management.
720
+ */
721
+ interface RendererConfigExtended extends ColorManagementConfig {
722
+ /** Share renderer from another canvas (WebGPU only) */
723
+ primaryCanvas?: string
724
+ /** Canvas-level scheduler options */
725
+ scheduler?: CanvasSchedulerConfig
726
+ }
727
+
728
+ type RendererProps =
729
+ | any // WebGPURenderer
730
+ | ((defaultProps: DefaultRendererProps) => any)
731
+ | ((defaultProps: DefaultRendererProps) => Promise<any>)
732
+ | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
733
+
734
+ //* Camera Props ==============================
735
+
736
+ type CameraProps = (
737
+ | THREE$1.Camera
738
+ | Partial<
739
+ ThreeElement<typeof THREE$1.Camera> &
740
+ ThreeElement<typeof THREE$1.PerspectiveCamera> &
741
+ ThreeElement<typeof THREE$1.OrthographicCamera>
742
+ >
743
+ ) & {
744
+ /** Flags the camera as manual, putting projection into your own hands */
745
+ manual?: boolean
746
+ }
747
+
748
+ //* Render Props ==============================
749
+
750
+ interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
751
+ /**
752
+ * Unique identifier for multi-canvas renderer sharing.
753
+ * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
754
+ * Also sets the HTML `id` attribute on the canvas element.
755
+ * @example <Canvas id="main-viewer">...</Canvas>
756
+ */
757
+ id?: string
758
+ /**
759
+ * Share the renderer from another canvas instead of creating a new one.
760
+ * Pass the `id` of the primary canvas to share its WebGPURenderer.
761
+ * Only available with WebGPU (not legacy WebGL).
762
+ *
763
+ * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
764
+ * @internal
765
+ */
766
+ primaryCanvas?: string
767
+ /**
768
+ * Canvas-level scheduler options. Controls render timing relative to other canvases.
769
+ *
770
+ * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
771
+ * @internal
772
+ */
773
+ scheduler?: CanvasSchedulerConfig
774
+ /** A threejs renderer instance or props that go into the default renderer */
775
+ gl?: GLProps
776
+ /** A WebGPU renderer instance or props that go into the default renderer */
777
+ renderer?: RendererProps
778
+ /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
779
+ size?: Size
780
+ /**
781
+ * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
782
+ * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
783
+ * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
784
+ */
785
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
786
+ /** Creates an orthographic camera */
787
+ orthographic?: boolean
788
+ /**
789
+ * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
790
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
791
+ */
792
+ frameloop?: Frameloop
793
+ /**
794
+ * R3F performance options for adaptive performance.
795
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
796
+ */
797
+ performance?: Partial<Omit<Performance, 'regress'>>
798
+ /** Target pixel ratio. Can clamp between a range: `[min, max]` */
799
+ dpr?: Dpr
800
+ /** Props that go into the default raycaster */
801
+ raycaster?: Partial<THREE$1.Raycaster>
802
+ /** A `THREE.Scene` instance or props that go into the default scene */
803
+ scene?: THREE$1.Scene | Partial<THREE$1.Scene>
804
+ /** A `THREE.Camera` instance or props that go into the default camera */
805
+ camera?: CameraProps
806
+ /** An R3F event manager to manage elements' pointer events */
807
+ events?: (store: RootStore) => EventManager<HTMLElement>
808
+ /** Callback after the canvas has rendered (but not yet committed) */
809
+ onCreated?: (state: RootState) => void
810
+ /** Response for pointer clicks that have missed any target */
811
+ onPointerMissed?: (event: MouseEvent) => void
812
+ /** Response for dragover events that have missed any target */
813
+ onDragOverMissed?: (event: DragEvent) => void
814
+ /** Response for drop events that have missed any target */
815
+ onDropMissed?: (event: DragEvent) => void
816
+ /** Whether to automatically update the frustum each frame (default: true) */
817
+ autoUpdateFrustum?: boolean
818
+ /**
819
+ * Enable WebGPU occlusion queries for onOccluded/onVisible events.
820
+ * Auto-enabled when any object uses onOccluded or onVisible handlers.
821
+ * Only works with WebGPU renderer - WebGL will log a warning.
822
+ */
823
+ occlusion?: boolean
824
+ /** Internal: stored size props from Canvas for reset functionality */
825
+ _sizeProps?: { width?: number; height?: number } | null
826
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
827
+ forceEven?: boolean
828
+ }
829
+
830
+ //* Reconciler Root ==============================
831
+
832
+ interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
833
+ configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
834
+ render: (element: ReactNode) => RootStore
835
+ unmount: () => void
836
+ }
837
+
838
+ //* Inject State ==============================
839
+
840
+ type InjectState = Partial<
841
+ Omit<RootState, 'events'> & {
842
+ events?: {
843
+ enabled?: boolean
844
+ priority?: number
845
+ compute?: ComputeFunction
846
+ connected?: any
847
+ }
848
+ /**
849
+ * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
850
+ * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
851
+ * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
852
+ */
853
+ injectScene?: boolean
854
+ }
817
855
  >
818
856
 
819
- //* Reconciler Types ==============================
820
-
821
- // FiberRoot is an opaque internal React type - we define it locally
822
- // to avoid bundling @types/react-reconciler which causes absolute path issues
823
- type FiberRoot = any
824
-
825
- interface Root {
826
- fiber: FiberRoot
827
- store: RootStore
828
- }
829
-
830
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
831
- type AttachType<O = any> = string | AttachFnType<O>
832
-
833
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
834
-
835
- interface Catalogue {
836
- [name: string]: ConstructorRepresentation
837
- }
838
-
839
- // TODO: handle constructor overloads
840
- // https://github.com/pmndrs/react-three-fiber/pull/2931
841
- // https://github.com/microsoft/TypeScript/issues/37079
842
- type Args<T> = T extends ConstructorRepresentation
843
- ? T extends typeof Color$1
844
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
845
- : ConstructorParameters<T>
846
- : any[]
847
-
848
- type ArgsProp<P> = P extends ConstructorRepresentation
849
- ? IsAllOptional<ConstructorParameters<P>> extends true
850
- ? { args?: Args<P> }
851
- : { args: Args<P> }
852
- : { args: unknown[] }
853
-
854
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
855
- object?: T
856
- dispose?: null
857
- attach?: AttachType<T>
858
- onUpdate?: (self: T) => void
859
- }
860
-
861
- interface Instance<O = any> {
862
- root: RootStore
863
- type: string
864
- parent: Instance | null
865
- children: Instance[]
866
- props: InstanceProps<O> & Record<string, unknown>
867
- object: O & { __r3f?: Instance<O> }
868
- eventCount: number
869
- handlers: Partial<EventHandlers>
870
- attach?: AttachType<O>
871
- previousAttach?: any
872
- isHidden: boolean
873
- }
874
-
875
- interface HostConfig {
876
- type: string
877
- props: Instance['props']
878
- container: RootStore
879
- instance: Instance
880
- textInstance: void
881
- suspenseInstance: Instance
882
- hydratableInstance: never
883
- formInstance: never
884
- publicInstance: Instance['object']
885
- hostContext: {}
886
- childSet: never
887
- timeoutHandle: number | undefined
888
- noTimeout: -1
889
- TransitionStatus: null
890
- }
891
- declare global {
892
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
893
- }
894
-
895
- //* Loop Types ==============================
896
-
897
- type GlobalRenderCallback = (timestamp: number) => void
898
-
857
+ //* Reconciler Types ==============================
858
+
859
+ // FiberRoot is an opaque internal React type - we define it locally
860
+ // to avoid bundling @types/react-reconciler which causes absolute path issues
861
+ type FiberRoot = any
862
+
863
+ interface Root {
864
+ fiber: FiberRoot
865
+ store: RootStore
866
+ }
867
+
868
+ type AttachFnType<O = any> = (parent: any, self: O) => () => void
869
+ type AttachType<O = any> = string | AttachFnType<O>
870
+
871
+ type ConstructorRepresentation<T = any> = new (...args: any[]) => T
872
+
873
+ interface Catalogue {
874
+ [name: string]: ConstructorRepresentation
875
+ }
876
+
877
+ // TODO: handle constructor overloads
878
+ // https://github.com/pmndrs/react-three-fiber/pull/2931
879
+ // https://github.com/microsoft/TypeScript/issues/37079
880
+ type Args<T> = T extends ConstructorRepresentation
881
+ ? T extends typeof Color$1
882
+ ? [r: number, g: number, b: number] | [color: ColorRepresentation]
883
+ : ConstructorParameters<T>
884
+ : any[]
885
+
886
+ type ArgsProp<P> = P extends ConstructorRepresentation
887
+ ? IsAllOptional<ConstructorParameters<P>> extends true
888
+ ? { args?: Args<P> }
889
+ : { args: Args<P> }
890
+ : { args: unknown[] }
891
+
892
+ type InstanceProps<T = any, P = any> = ArgsProp<P> & {
893
+ object?: T
894
+ dispose?: null
895
+ attach?: AttachType<T>
896
+ onUpdate?: (self: T) => void
897
+ }
898
+
899
+ interface Instance<O = any> {
900
+ root: RootStore
901
+ type: string
902
+ parent: Instance | null
903
+ children: Instance[]
904
+ props: InstanceProps<O> & Record<string, unknown>
905
+ object: O & { __r3f?: Instance<O> }
906
+ eventCount: number
907
+ handlers: Partial<EventHandlers>
908
+ attach?: AttachType<O>
909
+ previousAttach?: any
910
+ isHidden: boolean
911
+ /** Set of props that have been applied via once() */
912
+ appliedOnce?: Set<string>
913
+ }
914
+
915
+ interface HostConfig {
916
+ type: string
917
+ props: Instance['props']
918
+ container: RootStore
919
+ instance: Instance
920
+ textInstance: void
921
+ suspenseInstance: Instance
922
+ hydratableInstance: never
923
+ formInstance: never
924
+ publicInstance: Instance['object']
925
+ hostContext: {}
926
+ childSet: never
927
+ timeoutHandle: number | undefined
928
+ noTimeout: -1
929
+ TransitionStatus: null
930
+ }
931
+ declare global {
932
+ var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
933
+ }
934
+
935
+ //* Loop Types ==============================
936
+
937
+ type GlobalRenderCallback = (timestamp: number) => void
938
+
899
939
  type GlobalEffectType = 'before' | 'after' | 'tail'
900
940
 
901
- //* Canvas Types ==============================
902
-
903
- interface CanvasProps
904
- extends Omit<RenderProps<HTMLCanvasElement>, 'size'>, React$1.HTMLAttributes<HTMLDivElement> {
905
- children?: React$1.ReactNode
906
- ref?: React$1.Ref<HTMLCanvasElement>
907
- /** Canvas fallback content, similar to img's alt prop */
908
- fallback?: React$1.ReactNode
909
- /**
910
- * Options to pass to useMeasure.
911
- * @see https://github.com/pmndrs/react-use-measure#api
912
- */
913
- resize?: Options
914
- /** The target where events are being subscribed to, default: the div that wraps canvas */
915
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
916
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
917
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
918
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
919
- hmr?: boolean
920
- /** Canvas resolution width in pixels. If omitted, uses container width. */
921
- width?: number
922
- /** Canvas resolution height in pixels. If omitted, uses container height. */
923
- height?: number
924
- }
925
-
926
- //* Loader Types ==============================
927
-
928
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
929
-
930
- // Define a loader-like interface that matches THREE.Loader's load signature
931
- // This works for both generic and non-generic THREE.Loader instances
932
- interface LoaderLike {
933
- load(
934
- url: InputLike,
935
- onLoad?: (result: any) => void,
936
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
937
- onError?: (error: unknown) => void,
938
- ): any
939
- }
940
-
941
- type GLTFLike = { scene: THREE$1.Object3D }
942
-
943
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
944
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
945
-
946
- // Infer result type from the load method's callback parameter
947
- type InferLoadResult<T> = T extends {
948
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
949
- }
950
- ? R
951
- : T extends ConstructorRepresentation<any>
952
- ? InstanceType<T> extends {
953
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
954
- }
955
- ? R
956
- : any
957
- : any
958
-
959
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
960
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
961
-
962
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
963
- loader: LoaderInstance<T>,
941
+ declare const presetsObj: {
942
+ apartment: string;
943
+ city: string;
944
+ dawn: string;
945
+ forest: string;
946
+ lobby: string;
947
+ night: string;
948
+ park: string;
949
+ studio: string;
950
+ sunset: string;
951
+ warehouse: string;
952
+ };
953
+ type PresetsType = keyof typeof presetsObj;
954
+
955
+ //* Background Types ==============================
956
+
957
+ /**
958
+ * Expanded object form for background configuration.
959
+ * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
960
+ */
961
+ interface BackgroundConfig {
962
+ /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
963
+ preset?: PresetsType
964
+ /** Files for cube texture (6 faces) or single HDR/EXR */
965
+ files?: string | string[]
966
+ /** Separate files for scene.background (visual backdrop) */
967
+ backgroundMap?: string | string[]
968
+ backgroundRotation?: Euler$1 | [number, number, number]
969
+ backgroundBlurriness?: number
970
+ backgroundIntensity?: number
971
+ /** Separate files for scene.environment (PBR lighting/reflections) */
972
+ envMap?: string | string[]
973
+ environmentRotation?: Euler$1 | [number, number, number]
974
+ environmentIntensity?: number
975
+ path?: string
976
+ extensions?: (loader: Loader) => void
977
+ }
978
+
979
+ /**
980
+ * Background prop type for Canvas.
981
+ *
982
+ * String detection priority:
983
+ * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
984
+ * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
985
+ * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
986
+ *
987
+ * @example Color
988
+ * ```tsx
989
+ * <Canvas background="red" />
990
+ * <Canvas background="#ff0000" />
991
+ * <Canvas background={0xff0000} />
992
+ * ```
993
+ *
994
+ * @example Preset
995
+ * ```tsx
996
+ * <Canvas background="city" />
997
+ * ```
998
+ *
999
+ * @example URL
1000
+ * ```tsx
1001
+ * <Canvas background="/path/to/env.hdr" />
1002
+ * <Canvas background="./sky.jpg" />
1003
+ * ```
1004
+ *
1005
+ * @example Object form
1006
+ * ```tsx
1007
+ * <Canvas background={{
1008
+ * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1009
+ * backgroundMap: 'path/to/sky.jpg',
1010
+ * envMap: 'path/to/lighting.hdr',
1011
+ * backgroundBlurriness: 0.5,
1012
+ * }} />
1013
+ * ```
1014
+ */
1015
+ type BackgroundProp =
1016
+ | ColorRepresentation // "red", "#ff0000", 0xff0000
1017
+ | string // URL or preset
1018
+ | BackgroundConfig // Expanded object form
1019
+
1020
+ //* Canvas Types ==============================
1021
+
1022
+ interface CanvasProps
1023
+ extends
1024
+ Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1025
+ React$1.HTMLAttributes<HTMLDivElement> {
1026
+ children?: React$1.ReactNode
1027
+ ref?: React$1.Ref<HTMLCanvasElement>
1028
+ /** Canvas fallback content, similar to img's alt prop */
1029
+ fallback?: React$1.ReactNode
1030
+ /**
1031
+ * Options to pass to useMeasure.
1032
+ * @see https://github.com/pmndrs/react-use-measure#api
1033
+ */
1034
+ resize?: Options
1035
+ /** The target where events are being subscribed to, default: the div that wraps canvas */
1036
+ eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1037
+ /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1038
+ eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1039
+ /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1040
+ hmr?: boolean
1041
+ /** Canvas resolution width in pixels. If omitted, uses container width. */
1042
+ width?: number
1043
+ /** Canvas resolution height in pixels. If omitted, uses container height. */
1044
+ height?: number
1045
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1046
+ forceEven?: boolean
1047
+ /**
1048
+ * Scene background configuration.
1049
+ * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1050
+ * @see BackgroundProp for full documentation and examples
1051
+ */
1052
+ background?: BackgroundProp
1053
+ }
1054
+
1055
+ //* Loader Types ==============================
1056
+
1057
+ type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1058
+
1059
+ // Define a loader-like interface that matches THREE.Loader's load signature
1060
+ // This works for both generic and non-generic THREE.Loader instances
1061
+ interface LoaderLike {
1062
+ load(
1063
+ url: InputLike,
1064
+ onLoad?: (result: any) => void,
1065
+ onProgress?: (event: ProgressEvent<EventTarget>) => void,
1066
+ onError?: (error: unknown) => void,
1067
+ ): any
1068
+ }
1069
+
1070
+ type GLTFLike = { scene: THREE$1.Object3D }
1071
+
1072
+ type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1073
+ T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1074
+
1075
+ // Infer result type from the load method's callback parameter
1076
+ type InferLoadResult<T> = T extends {
1077
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1078
+ }
1079
+ ? R
1080
+ : T extends ConstructorRepresentation<any>
1081
+ ? InstanceType<T> extends {
1082
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1083
+ }
1084
+ ? R
1085
+ : any
1086
+ : any
1087
+
1088
+ type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1089
+ InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1090
+
1091
+ type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1092
+ loader: LoaderInstance<T>,
964
1093
  ) => void
965
1094
 
966
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
967
-
968
- type WebGLProps =
969
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
970
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
971
-
972
- interface WebGLShadowConfig {
973
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1095
+ //* Renderer Props ========================================
1096
+
1097
+ type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1098
+
1099
+ type WebGLProps =
1100
+ | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1101
+ | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1102
+
1103
+ interface WebGLShadowConfig {
1104
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1105
+ }
1106
+
1107
+ //* Legacy-specific Types ========================================
1108
+
1109
+ /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1110
+ type LegacyRenderer = THREE$1.WebGLRenderer
1111
+
1112
+ /** Legacy internal state with narrowed renderer type */
1113
+ interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1114
+ actualRenderer: THREE$1.WebGLRenderer
1115
+ }
1116
+
1117
+ /**
1118
+ * Legacy-specific RootState with narrowed renderer type.
1119
+ * Automatically used when importing from `@react-three/fiber/legacy`.
1120
+ *
1121
+ * @example
1122
+ * ```tsx
1123
+ * import { useThree } from '@react-three/fiber/legacy'
1124
+ *
1125
+ * function MyComponent() {
1126
+ * const { renderer } = useThree()
1127
+ * // renderer is typed as THREE.WebGLRenderer
1128
+ * renderer.shadowMap.enabled = true
1129
+ * }
1130
+ * ```
1131
+ */
1132
+ interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1133
+ /** The WebGL renderer instance */
1134
+ renderer: THREE$1.WebGLRenderer
1135
+ /** Internals with WebGL renderer */
1136
+ internal: LegacyInternalState
974
1137
  }
975
1138
 
976
- //* RenderTarget Types ==============================
977
-
978
-
1139
+ //* RenderTarget Types ==============================
1140
+
1141
+
979
1142
  type RenderTargetOptions = RenderTargetOptions$1
980
1143
 
981
- //* Global Types ==============================
982
-
983
- declare global {
984
- /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
985
- interface UniformNode<T = unknown> extends Node {
986
- value: T
987
- }
988
-
989
- /** Flat record of uniform nodes (no nested scopes) */
990
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
991
-
992
- /**
993
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
994
- * Used by state.uniforms which has structure like:
995
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
996
- */
997
- type UniformStore = Record<string, UniformNode | UniformRecord>
998
-
999
- /**
1000
- * Helper to safely access a uniform node from the store.
1001
- * Use this when accessing state.uniforms to get proper typing.
1002
- * @example
1003
- * const uTime = uniforms.uTime as UniformNode<number>
1004
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1005
- */
1006
- type GetUniform<T = unknown> = UniformNode<T>
1007
-
1008
- /**
1009
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1010
- * Supports: primitives, Three.js types, plain objects (converted to vectors), and UniformNodes
1011
- */
1012
- type UniformValue =
1013
- | number
1014
- | string
1015
- | boolean
1016
- | three_webgpu.Color
1017
- | three_webgpu.Vector2
1018
- | three_webgpu.Vector3
1019
- | three_webgpu.Vector4
1020
- | three_webgpu.Matrix3
1021
- | three_webgpu.Matrix4
1022
- | three_webgpu.Euler
1023
- | three_webgpu.Quaternion
1024
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1025
- | UniformNode
1026
-
1027
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1028
- type UniformInputRecord = Record<string, UniformValue>
1029
- }
1030
-
1031
- //* Fn Return Type ==============================
1032
-
1033
- /** The return type of Fn() - a callable shader function node */
1034
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1035
-
1036
- //* Module Augmentation ==============================
1037
-
1038
- declare module 'three/tsl' {
1039
- /**
1040
- * Fn with array parameter destructuring
1041
- * @example Fn(([uv, skew]) => { ... })
1042
- */
1043
- export function Fn<R extends Node = Node>(
1044
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1045
- ): ShaderCallable<R>
1046
-
1047
- /**
1048
- * Fn with object parameter destructuring
1049
- * @example Fn(({ color, intensity }) => { ... })
1050
- */
1051
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1052
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1053
- ): ShaderCallable<R>
1054
-
1055
- /**
1056
- * Fn with array params + layout
1057
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1058
- */
1059
- export function Fn<R extends Node = Node>(
1060
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1061
- layout: { layout?: unknown },
1062
- ): ShaderCallable<R>
1063
-
1064
- /**
1065
- * Fn with object params + layout
1066
- */
1067
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1068
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1069
- layout: { layout?: unknown },
1070
- ): ShaderCallable<R>
1071
- }
1072
-
1073
- /**
1074
- * PostProcessing Types for usePostProcessing hook (WebGPU only)
1075
- */
1076
-
1077
-
1078
-
1079
- declare global {
1080
- /** Pass record - stores TSL pass nodes for post-processing */
1081
- type PassRecord = Record<string, any>
1082
-
1083
- /** Setup callback - runs first to configure MRT, create additional passes */
1084
- type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1085
-
1086
- /** Main callback - runs second to configure outputNode, create effect passes */
1087
- type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1088
-
1089
- /** Return type for usePostProcessing hook */
1090
- interface UsePostProcessingReturn {
1091
- /** Current passes from state */
1092
- passes: PassRecord
1093
- /** PostProcessing instance (null if not initialized) */
1094
- postProcessing: any | null // THREE.PostProcessing
1095
- /** Clear all passes from state */
1096
- clearPasses: () => void
1097
- /** Reset PostProcessing entirely (clears PP + passes) */
1098
- reset: () => void
1099
- /** Re-run setup/main callbacks with current closure values */
1100
- rebuild: () => void
1101
- /** True when PostProcessing is configured and ready */
1102
- isReady: boolean
1103
- }
1104
- }
1105
-
1106
- //* useFrameNext Types ==============================
1107
-
1108
-
1109
-
1110
- //* Global Type Declarations ==============================
1111
-
1112
- declare global {
1113
- // Job --------------------------------
1114
-
1115
- /**
1116
- * Internal job representation in the scheduler
1117
- */
1118
- interface Job {
1119
- /** Unique identifier */
1120
- id: string
1121
- /** The callback to execute */
1122
- callback: FrameNextCallback
1123
- /** Phase this job belongs to */
1124
- phase: string
1125
- /** Run before these phases/job ids */
1126
- before: Set<string>
1127
- /** Run after these phases/job ids */
1128
- after: Set<string>
1129
- /** Priority within phase (higher first) */
1130
- priority: number
1131
- /** Insertion order for deterministic tie-breaking */
1132
- index: number
1133
- /** Max FPS for this job (undefined = no limit) */
1134
- fps?: number
1135
- /** Drop frames when behind (true) or catch up (false) */
1136
- drop: boolean
1137
- /** Last run timestamp (ms) */
1138
- lastRun?: number
1139
- /** Whether job is enabled */
1140
- enabled: boolean
1141
- /** Internal flag: system jobs (like default render) don't block user render takeover */
1142
- system?: boolean
1143
- }
1144
-
1145
- // Phase Graph --------------------------------
1146
-
1147
- /**
1148
- * A node in the phase graph
1149
- */
1150
- interface PhaseNode {
1151
- /** Phase name */
1152
- name: string
1153
- /** Whether this was auto-generated from a before/after constraint */
1154
- isAutoGenerated: boolean
1155
- }
1156
-
1157
- /**
1158
- * Options for creating a job from hook options
1159
- */
1160
- interface JobOptions {
1161
- id?: string
1162
- phase?: string
1163
- before?: string | string[]
1164
- after?: string | string[]
1165
- priority?: number
1166
- fps?: number
1167
- drop?: boolean
1168
- enabled?: boolean
1169
- }
1170
-
1171
- // Frame Loop State --------------------------------
1172
-
1173
- /**
1174
- * Internal frame loop state
1175
- */
1176
- interface FrameLoopState {
1177
- /** Whether the loop is running */
1178
- running: boolean
1179
- /** Current RAF handle */
1180
- rafHandle: number | null
1181
- /** Last frame timestamp in ms (null = uninitialized) */
1182
- lastTime: number | null
1183
- /** Frame counter */
1184
- frameCount: number
1185
- /** Elapsed time since first frame in ms */
1186
- elapsedTime: number
1187
- /** createdAt timestamp in ms */
1188
- createdAt: number
1189
- }
1190
-
1191
- // Root Entry --------------------------------
1192
-
1193
- /**
1194
- * Internal representation of a registered root (Canvas).
1195
- * Tracks jobs and manages rebuild state for this root.
1196
- * @internal
1197
- */
1198
- interface RootEntry {
1199
- /** Unique identifier for this root */
1200
- id: string
1201
- /** Function to get the root's current state. Returns any to support independent mode. */
1202
- getState: () => any
1203
- /** Map of job IDs to Job objects */
1204
- jobs: Map<string, Job>
1205
- /** Cached sorted job list for execution order */
1206
- sortedJobs: Job[]
1207
- /** Whether sortedJobs needs rebuilding */
1208
- needsRebuild: boolean
1209
- }
1210
-
1211
- /**
1212
- * Internal representation of a global job (deprecated API).
1213
- * Global jobs run once per frame, not per-root.
1214
- * Used by legacy addEffect/addAfterEffect APIs.
1215
- * @internal
1216
- * @deprecated Use useFrame with phases instead
1217
- */
1218
- interface GlobalJob {
1219
- /** Unique identifier for this global job */
1220
- id: string
1221
- /** Callback invoked with RAF timestamp in ms */
1222
- callback: (timestamp: number) => void
1223
- }
1224
-
1225
- // HMR Support --------------------------------
1226
-
1227
- /**
1228
- * Hot Module Replacement data structure for preserving scheduler state
1229
- * @internal
1230
- */
1231
- interface HMRData {
1232
- /** Shared data object for storing values across reloads */
1233
- data: Record<string, any>
1234
- /** Optional function to accept HMR updates */
1235
- accept?: () => void
1236
- }
1237
-
1238
- // Default Phases --------------------------------
1239
-
1240
- /**
1241
- * Default phase names for the scheduler
1242
- */
1243
- type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1244
- }
1245
-
1246
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1247
-
1248
- interface MathRepresentation {
1249
- set(...args: number[]): any
1250
- }
1251
- interface VectorRepresentation extends MathRepresentation {
1252
- setScalar(value: number): any
1253
- }
1254
- type MathTypes = MathRepresentation | Euler$1 | Color$1
1255
-
1256
- type MathType<T extends MathTypes> = T extends Color$1
1257
- ? Args<typeof Color$1> | ColorRepresentation
1258
- : T extends VectorRepresentation | Layers$1 | Euler$1
1259
- ? T | MutableOrReadonlyParameters<T['set']> | number
1260
- : T | MutableOrReadonlyParameters<T['set']>
1261
-
1262
- type MathProps<P> = {
1263
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1264
- }
1265
-
1266
- type Vector2 = MathType<Vector2$1>
1267
- type Vector3 = MathType<Vector3$1>
1268
- type Vector4 = MathType<Vector4$1>
1269
- type Color = MathType<Color$1>
1270
- type Layers = MathType<Layers$1>
1271
- type Quaternion = MathType<Quaternion$1>
1272
- type Euler = MathType<Euler$1>
1273
- type Matrix3 = MathType<Matrix3$1>
1274
- type Matrix4 = MathType<Matrix4$1>
1275
-
1276
- interface RaycastableRepresentation {
1277
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1278
- }
1279
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1280
-
1281
- interface ReactProps<P> {
1282
- children?: React.ReactNode
1283
- ref?: React.Ref<P>
1284
- key?: React.Key
1285
- }
1286
-
1287
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1288
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P>>
1289
- >
1290
-
1291
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1292
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1293
- >
1294
-
1295
- type ThreeToJSXElements<T extends Record<string, any>> = {
1296
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1297
- }
1298
-
1299
- type ThreeExports = typeof THREE
1300
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1301
-
1302
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1303
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1304
- // Conflicts with DOM types can be accessed through a three* prefix
1305
- threeAudio: ThreeElementsImpl['audio']
1306
- threeSource: ThreeElementsImpl['source']
1307
- threeLine: ThreeElementsImpl['line']
1308
- threePath: ThreeElementsImpl['path']
1309
- }
1310
-
1311
- declare module 'react' {
1312
- namespace JSX {
1313
- interface IntrinsicElements extends ThreeElements {}
1314
- }
1315
- }
1316
-
1317
- declare module 'react/jsx-runtime' {
1318
- namespace JSX {
1319
- interface IntrinsicElements extends ThreeElements {}
1320
- }
1321
- }
1322
-
1323
- declare module 'react/jsx-dev-runtime' {
1324
- namespace JSX {
1325
- interface IntrinsicElements extends ThreeElements {}
1326
- }
1144
+ //* Global Types ==============================
1145
+
1146
+ declare global {
1147
+ /**
1148
+ * Uniform node type.
1149
+ *
1150
+ * This is three's own `UniformNode`, not a re-declaration of it. It previously was a
1151
+ * hand-rolled `interface UniformNode<T> extends Node { value: T }`, which shadowed the real
1152
+ * exported type globally — so R3F's ~58 references resolved to an approximation that was
1153
+ * missing members three actually ships (`setName` among them) and had drifted to the wrong
1154
+ * arity when three made `UniformNode` two-parameter.
1155
+ *
1156
+ * three's signature is `UniformNode<TNodeType, TValue>`. R3F only ever varies the value type,
1157
+ * so the node type is fixed to `unknown` and the single parameter is kept for call-site
1158
+ * ergonomics. The result is three's structural type, so members stay in sync with the
1159
+ * installed three instead of needing to be mirrored by hand.
1160
+ */
1161
+ type UniformNode<T = unknown> = three_webgpu.UniformNode<unknown, T>
1162
+
1163
+ /**
1164
+ * ShaderCallable - the return type of Fn()
1165
+ * A callable shader function node that can be invoked with parameters.
1166
+ * The function returns a ShaderNodeObject when called.
1167
+ *
1168
+ * @example
1169
+ * ```tsx
1170
+ * // Define a shader function
1171
+ * const blendColorFn = Fn(([color1, color2, factor]) => {
1172
+ * return mix(color1, color2, factor)
1173
+ * })
1174
+ *
1175
+ * // Type when retrieving from nodes store
1176
+ * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1177
+ *
1178
+ * // Or with specific return type
1179
+ * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1180
+ * ```
1181
+ */
1182
+ type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1183
+
1184
+ /**
1185
+ * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1186
+ * This is the common return type for TSL operations (add, mul, sin, etc.)
1187
+ *
1188
+ * @example
1189
+ * ```tsx
1190
+ * const { wobble } = nodes as { wobble: ShaderNodeRef }
1191
+ * ```
1192
+ */
1193
+ type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1194
+
1195
+ /**
1196
+ * TSLNodeType - Union of all common TSL node types
1197
+ * Used by ScopedStore to properly type node access from the store.
1198
+ *
1199
+ * Includes:
1200
+ * - Node: base Three.js node type
1201
+ * - ShaderCallable: function nodes created with Fn()
1202
+ * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1203
+ *
1204
+ * @example
1205
+ * ```tsx
1206
+ * // In useLocalNodes, nodes are typed as TSLNodeType
1207
+ * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1208
+ * positionNode: nodes.myPosition, // Works - Node is in union
1209
+ * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1210
+ * }))
1211
+ *
1212
+ * // Can narrow with type guard or assertion when needed
1213
+ * if (typeof blendColorFn === 'function') {
1214
+ * blendColorFn(someColor, 0.5)
1215
+ * }
1216
+ * ```
1217
+ */
1218
+ type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1219
+
1220
+ /** Flat record of uniform nodes (no nested scopes) */
1221
+ type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1222
+
1223
+ /**
1224
+ * Uniform store that can contain both root-level uniforms and scoped uniform objects
1225
+ * Used by state.uniforms which has structure like:
1226
+ * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1227
+ */
1228
+ type UniformStore = Record<string, UniformNode | UniformRecord>
1229
+
1230
+ /**
1231
+ * Helper to safely access a uniform node from the store.
1232
+ * Use this when accessing state.uniforms to get proper typing.
1233
+ * @example
1234
+ * const uTime = uniforms.uTime as UniformNode<number>
1235
+ * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1236
+ */
1237
+ type GetUniform<T = unknown> = UniformNode<T>
1238
+
1239
+ /**
1240
+ * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1241
+ * Supports:
1242
+ * - Primitives: number, string (color), boolean
1243
+ * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1244
+ * - Plain objects: { x, y, z, w } converted to vectors
1245
+ * - TSL nodes: color(), vec3(), float() for type casting
1246
+ * - UniformNode: existing uniforms (reused as-is)
1247
+ */
1248
+ type UniformValue =
1249
+ | number
1250
+ | string
1251
+ | boolean
1252
+ | three_webgpu.Color
1253
+ | three_webgpu.Vector2
1254
+ | three_webgpu.Vector3
1255
+ | three_webgpu.Vector4
1256
+ | three_webgpu.Matrix3
1257
+ | three_webgpu.Matrix4
1258
+ | three_webgpu.Euler
1259
+ | three_webgpu.Quaternion
1260
+ | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1261
+ | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1262
+ | Node // TSL nodes like color(), vec3(), float() for type casting
1263
+ | UniformNode
1264
+
1265
+ /** Input record for useUniforms - accepts raw values or UniformNodes */
1266
+ type UniformInputRecord = Record<string, UniformValue>
1267
+ }
1268
+
1269
+ //* Module Augmentation ==============================
1270
+
1271
+ declare module 'three/tsl' {
1272
+ /**
1273
+ * Fn with array parameter destructuring
1274
+ * @example Fn(([uv, skew]) => { ... })
1275
+ */
1276
+ export function Fn<R extends Node = Node>(
1277
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1278
+ ): ShaderCallable<R>
1279
+
1280
+ /**
1281
+ * Fn with object parameter destructuring
1282
+ * @example Fn(({ color, intensity }) => { ... })
1283
+ */
1284
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1285
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1286
+ ): ShaderCallable<R>
1287
+
1288
+ /**
1289
+ * Fn with array params + layout
1290
+ * @example Fn(([a, b]) => { ... }, { layout: [...] })
1291
+ */
1292
+ export function Fn<R extends Node = Node>(
1293
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1294
+ layout: { layout?: unknown },
1295
+ ): ShaderCallable<R>
1296
+
1297
+ /**
1298
+ * Fn with object params + layout
1299
+ */
1300
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1301
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1302
+ layout: { layout?: unknown },
1303
+ ): ShaderCallable<R>
1304
+ }
1305
+
1306
+ declare global {
1307
+ /**
1308
+ * three's own render pipeline type. Named here so the rest of R3F refers to three's shape
1309
+ * rather than `any`. three r183 renamed `PostProcessing` to `RenderPipeline`; our peer floor
1310
+ * is r185, so the new name is the only one.
1311
+ */
1312
+ type ThreeRenderPipeline = three_webgpu.RenderPipeline
1313
+
1314
+ /** Pass record - stores TSL pass nodes for render pipeline */
1315
+ type PassRecord = Record<string, any>
1316
+
1317
+ /** Setup callback - runs first to configure MRT, create additional passes */
1318
+ type RenderPipelineSetupCallback = (state: RootState) => PassRecord | void
1319
+
1320
+ /** Main callback - runs second to configure outputNode, create effect passes */
1321
+ type RenderPipelineMainCallback = (state: RootState) => PassRecord | void
1322
+
1323
+ /** Return type for useRenderPipeline hook */
1324
+ interface UseRenderPipelineReturn {
1325
+ /** Current passes from state */
1326
+ passes: PassRecord
1327
+ /** RenderPipeline instance (null if not initialized) */
1328
+ renderPipeline: ThreeRenderPipeline | null
1329
+ /** Clear all passes from state */
1330
+ clearPasses: () => void
1331
+ /** Reset RenderPipeline entirely (clears PP + passes) */
1332
+ reset: () => void
1333
+ /** Re-run setup/main callbacks with current closure values */
1334
+ rebuild: () => void
1335
+ /** True when RenderPipeline is configured and ready */
1336
+ isReady: boolean
1337
+ }
1338
+ }
1339
+
1340
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1341
+
1342
+ interface MathRepresentation {
1343
+ set(...args: number[]): any
1344
+ }
1345
+ interface VectorRepresentation extends MathRepresentation {
1346
+ setScalar(value: number): any
1347
+ }
1348
+ type MathTypes = MathRepresentation | Euler$1 | Color$1
1349
+
1350
+ type MathType<T extends MathTypes> = T extends Color$1
1351
+ ? Args<typeof Color$1> | ColorRepresentation
1352
+ : T extends VectorRepresentation | Layers$1 | Euler$1
1353
+ ? T | MutableOrReadonlyParameters<T['set']> | number
1354
+ : T | MutableOrReadonlyParameters<T['set']>
1355
+
1356
+ type MathProps<P> = {
1357
+ [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1358
+ }
1359
+
1360
+ type Vector2 = MathType<Vector2$1>
1361
+ type Vector3 = MathType<Vector3$1>
1362
+ type Vector4 = MathType<Vector4$1>
1363
+ type Color = MathType<Color$1>
1364
+ type Layers = MathType<Layers$1>
1365
+ type Quaternion = MathType<Quaternion$1>
1366
+ type Euler = MathType<Euler$1>
1367
+ type Matrix3 = MathType<Matrix3$1>
1368
+ type Matrix4 = MathType<Matrix4$1>
1369
+
1370
+ interface RaycastableRepresentation {
1371
+ raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1372
+ }
1373
+ type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1374
+
1375
+ /**
1376
+ * Props for geometry transform methods that can be called with `once()`.
1377
+ * These methods modify the geometry in-place and only make sense to call once on mount.
1378
+ *
1379
+ * @example
1380
+ * import { once } from '@react-three/fiber'
1381
+ *
1382
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1383
+ * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1384
+ * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1385
+ */
1386
+ interface GeometryTransformProps {
1387
+ /** Rotate the geometry about the X axis (radians). Use with once(). */
1388
+ rotateX?: number
1389
+ /** Rotate the geometry about the Y axis (radians). Use with once(). */
1390
+ rotateY?: number
1391
+ /** Rotate the geometry about the Z axis (radians). Use with once(). */
1392
+ rotateZ?: number
1393
+ /** Translate the geometry (x, y, z). Use with once(). */
1394
+ translate?: [x: number, y: number, z: number]
1395
+ /** Scale the geometry (x, y, z). Use with once(). */
1396
+ scale?: [x: number, y: number, z: number]
1397
+ /** Center the geometry based on bounding box. Use with once(). */
1398
+ center?: true
1399
+ /** Apply a Matrix4 transformation. Use with once(). */
1400
+ applyMatrix4?: Matrix4$1
1401
+ /** Apply a Quaternion rotation. Use with once(). */
1402
+ applyQuaternion?: Quaternion$1
1403
+ }
1404
+
1405
+ type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1406
+
1407
+ /**
1408
+ * Workaround for @types/three TSL node type issues.
1409
+ * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1410
+ * This transforms `Node | null` properties to accept any object with node-like shape.
1411
+ */
1412
+ type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1413
+
1414
+ /**
1415
+ * For node material properties (colorNode, positionNode, etc.), accept broader types
1416
+ * since @types/three has broken inheritance for TSL node subclasses.
1417
+ */
1418
+ type NodeProps<P> = {
1419
+ [K in keyof P as P[K] extends Node$1 | null ? K : never]?: TSLNodeInput
1420
+ }
1421
+
1422
+ interface ReactProps<P> {
1423
+ children?: React.ReactNode
1424
+ ref?: React.Ref<P>
1425
+ key?: React.Key
1426
+ }
1427
+
1428
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1429
+ Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1430
+ >
1431
+
1432
+ type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1433
+ Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1434
+ >
1435
+
1436
+ type ThreeToJSXElements<T extends Record<string, any>> = {
1437
+ [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1438
+ }
1439
+
1440
+ type ThreeExports = typeof THREE
1441
+ type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1442
+
1443
+ interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1444
+ primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1445
+ // Conflicts with DOM types can be accessed through a three* prefix
1446
+ threeAudio: ThreeElementsImpl['audio']
1447
+ threeSource: ThreeElementsImpl['source']
1448
+ threeLine: ThreeElementsImpl['line']
1449
+ threePath: ThreeElementsImpl['path']
1450
+ }
1451
+
1452
+ declare module 'react' {
1453
+ namespace JSX {
1454
+ interface IntrinsicElements extends ThreeElements {}
1455
+ }
1456
+ }
1457
+
1458
+ declare module 'react/jsx-runtime' {
1459
+ namespace JSX {
1460
+ interface IntrinsicElements extends ThreeElements {}
1461
+ }
1462
+ }
1463
+
1464
+ declare module 'react/jsx-dev-runtime' {
1465
+ namespace JSX {
1466
+ interface IntrinsicElements extends ThreeElements {}
1467
+ }
1327
1468
  }
1328
1469
 
1329
1470
  type three_d_Color = Color;
1330
1471
  type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1331
1472
  type three_d_Euler = Euler;
1332
1473
  type three_d_EventProps<P> = EventProps<P>;
1474
+ type three_d_GeometryProps<P> = GeometryProps<P>;
1475
+ type three_d_GeometryTransformProps = GeometryTransformProps;
1333
1476
  type three_d_Layers = Layers;
1334
1477
  type three_d_MathProps<P> = MathProps<P>;
1335
1478
  type three_d_MathRepresentation = MathRepresentation;
@@ -1338,9 +1481,11 @@ type three_d_MathTypes = MathTypes;
1338
1481
  type three_d_Matrix3 = Matrix3;
1339
1482
  type three_d_Matrix4 = Matrix4;
1340
1483
  type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1484
+ type three_d_NodeProps<P> = NodeProps<P>;
1341
1485
  type three_d_Quaternion = Quaternion;
1342
1486
  type three_d_RaycastableRepresentation = RaycastableRepresentation;
1343
1487
  type three_d_ReactProps<P> = ReactProps<P>;
1488
+ type three_d_TSLNodeInput = TSLNodeInput;
1344
1489
  type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1345
1490
  type three_d_ThreeElements = ThreeElements;
1346
1491
  type three_d_ThreeElementsImpl = ThreeElementsImpl;
@@ -1351,12 +1496,353 @@ type three_d_Vector3 = Vector3;
1351
1496
  type three_d_Vector4 = Vector4;
1352
1497
  type three_d_VectorRepresentation = VectorRepresentation;
1353
1498
  declare namespace three_d {
1354
- export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, 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_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, 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 };
1499
+ export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_GeometryProps as GeometryProps, three_d_GeometryTransformProps as GeometryTransformProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_NodeProps as NodeProps, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_TSLNodeInput as TSLNodeInput, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1500
+ }
1501
+
1502
+ /**
1503
+ * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1504
+ *
1505
+ * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1506
+ * a single WebGPURenderer using Three.js CanvasTarget API.
1507
+ *
1508
+ * Primary canvas: Has `id` prop, creates its own renderer, registers here
1509
+ * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
1510
+ */
1511
+
1512
+ interface PrimaryCanvasEntry {
1513
+ /** The WebGPURenderer instance owned by this primary canvas */
1514
+ renderer: WebGPURenderer;
1515
+ /** The zustand store for this canvas */
1516
+ store: RootStore;
1517
+ }
1518
+ /**
1519
+ * Register a primary canvas that can be targeted by secondary canvases.
1520
+ *
1521
+ * @param id - Unique identifier for this primary canvas
1522
+ * @param renderer - The WebGPURenderer owned by this canvas
1523
+ * @param store - The zustand store for this canvas
1524
+ * @returns Cleanup function to unregister on unmount
1525
+ */
1526
+ declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1527
+ /**
1528
+ * Get a registered primary canvas by id.
1529
+ *
1530
+ * @param id - The id of the primary canvas to look up
1531
+ * @returns The primary canvas entry or undefined if not found
1532
+ */
1533
+ declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1534
+ /**
1535
+ * Wait for a primary canvas to be registered.
1536
+ * Returns immediately if already registered, otherwise waits.
1537
+ *
1538
+ * @param id - The id of the primary canvas to wait for
1539
+ * @param timeout - Optional timeout in ms (default: 5000)
1540
+ * @returns Promise that resolves with the primary canvas entry
1541
+ */
1542
+ declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1543
+ /**
1544
+ * Check if a primary canvas with the given id exists.
1545
+ *
1546
+ * @param id - The id to check
1547
+ * @returns True if a primary canvas with this id is registered
1548
+ */
1549
+ declare function hasPrimary(id: string): boolean;
1550
+ /**
1551
+ * Unregister a primary canvas. Called on unmount.
1552
+ *
1553
+ * @param id - The id of the primary canvas to unregister
1554
+ */
1555
+ declare function unregisterPrimary(id: string): void;
1556
+ /**
1557
+ * Get all registered primary canvas ids. Useful for debugging.
1558
+ */
1559
+ declare function getPrimaryIds(): string[];
1560
+
1561
+ type EnvironmentLoaderProps = {
1562
+ files?: string | string[];
1563
+ path?: string;
1564
+ preset?: PresetsType;
1565
+ extensions?: (loader: Loader) => void;
1566
+ colorSpace?: ColorSpace;
1567
+ };
1568
+ /**
1569
+ * Loads environment textures for reflections and lighting.
1570
+ * Supports HDR files, presets, and cubemaps.
1571
+ *
1572
+ * @example Basic usage
1573
+ * ```jsx
1574
+ * const texture = useEnvironment({ preset: 'sunset' })
1575
+ * ```
1576
+ */
1577
+ declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1578
+ declare namespace useEnvironment {
1579
+ var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1580
+ var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1581
+ }
1582
+ /**
1583
+ * Options accepted by `useEnvironment.preload`.
1584
+ *
1585
+ * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
1586
+ * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
1587
+ * advertise an option this function silently ignores.
1588
+ *
1589
+ * This previously read `Omit<…, 'encoding'>` — omitting a key that does not exist on
1590
+ * `EnvironmentLoaderProps`, a leftover from three's pre-`colorSpace` `encoding` API. That made the
1591
+ * type equivalent to the full props, so `colorSpace` was accepted and then dropped on the floor.
1592
+ */
1593
+ type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
1594
+ type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1595
+
1596
+ /**
1597
+ * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1598
+ *
1599
+ * @property children - React children to render into custom environment portal
1600
+ * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1601
+ * @property near - Near clipping plane for cube camera (default: 0.1)
1602
+ * @property far - Far clipping plane for cube camera (default: 1000)
1603
+ * @property resolution - Resolution of the cube render target (default: 256)
1604
+ * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1605
+ *
1606
+ * @property blur - @deprecated Use backgroundBlurriness instead
1607
+ * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1608
+ * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1609
+ * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1610
+ * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1611
+ * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1612
+ *
1613
+ * @property map - Pre-existing texture to use as environment map
1614
+ * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1615
+ * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1616
+ * @property ground - Ground projection settings. Use true for defaults or object with:
1617
+ * - height: Height of camera used to create env map (default: 15)
1618
+ * - radius: Radius of the world (default: 60)
1619
+ * - scale: Scale of backside projected sphere (default: 1000)
1620
+ *
1621
+ * Additional loader props:
1622
+ * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1623
+ * @property path - Base path for file loading
1624
+ * @property extensions - Texture extensions override
1625
+ */
1626
+ type EnvironmentProps = {
1627
+ children?: React$1.ReactNode;
1628
+ frames?: number;
1629
+ near?: number;
1630
+ far?: number;
1631
+ resolution?: number;
1632
+ background?: boolean | 'only';
1633
+ /** deprecated, use backgroundBlurriness */
1634
+ blur?: number;
1635
+ backgroundBlurriness?: number;
1636
+ backgroundIntensity?: number;
1637
+ backgroundRotation?: Euler;
1638
+ environmentIntensity?: number;
1639
+ environmentRotation?: Euler;
1640
+ map?: Texture$1;
1641
+ preset?: PresetsType;
1642
+ scene?: Scene | React$1.RefObject<Scene>;
1643
+ ground?: boolean | {
1644
+ radius?: number;
1645
+ height?: number;
1646
+ scale?: number;
1647
+ };
1648
+ /** Solid color for background (alternative to files/preset) */
1649
+ color?: ColorRepresentation;
1650
+ /** Separate files for background (when different from environment files) */
1651
+ backgroundFiles?: string | string[];
1652
+ } & EnvironmentLoaderProps;
1653
+ /**
1654
+ * Internal component that applies a pre-existing texture as environment map.
1655
+ * Sets scene.environment and optionally scene.background.
1656
+ *
1657
+ * @example
1658
+ * ```jsx
1659
+ * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1660
+ * ```
1661
+ */
1662
+ declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1663
+ /**
1664
+ * Internal component that loads environment textures from files or presets.
1665
+ * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1666
+ * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1667
+ *
1668
+ * @example With preset
1669
+ * ```jsx
1670
+ * <EnvironmentCube preset="sunset" />
1671
+ * ```
1672
+ *
1673
+ * @example From HDR file
1674
+ * ```jsx
1675
+ * <EnvironmentCube files="environment.hdr" />
1676
+ * ```
1677
+ *
1678
+ * @example From gainmap (smallest footprint)
1679
+ * ```jsx
1680
+ * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1681
+ * ```
1682
+ *
1683
+ * @example From cube faces
1684
+ * ```jsx
1685
+ * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1686
+ * ```
1687
+ */
1688
+ declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1689
+ /**
1690
+ * Internal component that renders custom environment using a portal and cube camera.
1691
+ * Renders children into an off-buffer and films with a cube camera to create environment map.
1692
+ * Can be static (frames=1) or animated (frames=Infinity).
1693
+ *
1694
+ * @example Custom environment with sphere
1695
+ * ```jsx
1696
+ * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1697
+ * <mesh scale={100}>
1698
+ * <sphereGeometry args={[1, 64, 64]} />
1699
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1700
+ * </mesh>
1701
+ * </EnvironmentPortal>
1702
+ * ```
1703
+ *
1704
+ * @example Animated environment
1705
+ * ```jsx
1706
+ * <EnvironmentPortal frames={Infinity} resolution={256}>
1707
+ * <Float>
1708
+ * <mesh />
1709
+ * </Float>
1710
+ * </EnvironmentPortal>
1711
+ * ```
1712
+ *
1713
+ * @example Mixed with preset
1714
+ * ```jsx
1715
+ * <EnvironmentPortal preset="warehouse">
1716
+ * <mesh />
1717
+ * </EnvironmentPortal>
1718
+ * ```
1719
+ */
1720
+ 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;
1721
+ declare module '@react-three/fiber' {
1722
+ interface ThreeElements {
1723
+ groundProjectedEnvImpl: ThreeElement<typeof GroundedSkybox>;
1724
+ }
1355
1725
  }
1726
+ /**
1727
+ * Sets up a global environment map for PBR materials and backgrounds.
1728
+ * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1729
+ *
1730
+ * Supports multiple input methods:
1731
+ * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1732
+ * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1733
+ * - **Texture**: Pre-existing cube texture via `map` prop
1734
+ * - **Custom Scene**: Render children into environment using portal and cube camera
1735
+ * - **Ground Projection**: Project environment onto ground plane
1736
+ *
1737
+ * @remarks
1738
+ * - Preset property is NOT meant for production and may fail (relies on CDNs)
1739
+ * - Gainmap format has the smallest file footprint
1740
+ * - Use `frames={Infinity}` for animated environments with low resolution for performance
1741
+ * - Ground projection places models on the "ground" within the environment map
1742
+ * - Supports self-hosting with @pmndrs/assets using dynamic imports
1743
+ *
1744
+ * @example Basic preset usage
1745
+ * ```jsx
1746
+ * <Environment preset="sunset" />
1747
+ * ```
1748
+ *
1749
+ * @example From HDR file
1750
+ * ```jsx
1751
+ * <Environment files="/hdr/environment.hdr" />
1752
+ * ```
1753
+ *
1754
+ * @example From gainmap (smallest footprint)
1755
+ * ```jsx
1756
+ * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1757
+ * ```
1758
+ *
1759
+ * @example With self-hosted assets
1760
+ * ```jsx
1761
+ * import { suspend } from 'suspend-react'
1762
+ * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1763
+ *
1764
+ * <Environment files={suspend(city)} />
1765
+ * ```
1766
+ *
1767
+ * @example From existing texture
1768
+ * ```jsx
1769
+ * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1770
+ * ```
1771
+ *
1772
+ * @example Custom environment scene
1773
+ * ```jsx
1774
+ * <Environment background near={1} far={1000} resolution={256}>
1775
+ * <mesh scale={100}>
1776
+ * <sphereGeometry args={[1, 64, 64]} />
1777
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1778
+ * </mesh>
1779
+ * </Environment>
1780
+ * ```
1781
+ *
1782
+ * @example Animated environment
1783
+ * ```jsx
1784
+ * <Environment frames={Infinity} resolution={256}>
1785
+ * <Float>
1786
+ * <mesh />
1787
+ * </Float>
1788
+ * </Environment>
1789
+ * ```
1790
+ *
1791
+ * @example Mixed custom scene with preset
1792
+ * ```jsx
1793
+ * <Environment background preset="warehouse">
1794
+ * <mesh />
1795
+ * </Environment>
1796
+ * ```
1797
+ *
1798
+ * @example With ground projection
1799
+ * ```jsx
1800
+ * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1801
+ * ```
1802
+ *
1803
+ * @example As background only
1804
+ * ```jsx
1805
+ * <Environment background="only" preset="sunset" />
1806
+ * ```
1807
+ *
1808
+ * @example With rotation and intensity
1809
+ * ```jsx
1810
+ * <Environment
1811
+ * background
1812
+ * backgroundBlurriness={0.5}
1813
+ * backgroundIntensity={0.8}
1814
+ * backgroundRotation={[0, Math.PI / 2, 0]}
1815
+ * environmentIntensity={1.2}
1816
+ * environmentRotation={[0, Math.PI / 4, 0]}
1817
+ * preset="studio"
1818
+ * />
1819
+ * ```
1820
+ */
1821
+ declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1356
1822
 
1823
+ /**
1824
+ * Moves every trace of interactivity from one object to its replacement, for reconstruction.
1825
+ *
1826
+ * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
1827
+ * instance. Removing the old object from the interaction state and registering the new one from
1828
+ * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
1829
+ * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
1830
+ * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
1831
+ * swap the user never asked to see (#3744).
1832
+ *
1833
+ * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
1834
+ * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
1835
+ *
1836
+ * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
1837
+ * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
1838
+ * cannot outlive the object it described.
1839
+ */
1840
+ declare function swapInteractivity(store: RootStore, object: Object3D, newObject: Object3D): void;
1357
1841
  declare function removeInteractivity(store: RootStore, object: Object3D): void;
1358
1842
  declare function createEvents(store: RootStore): {
1359
1843
  handlePointer: (name: string) => (event: DomEvent) => void;
1844
+ flushDeferredPointers: () => void;
1845
+ processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1360
1846
  };
1361
1847
  /** Default R3F event manager for web */
1362
1848
  declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
@@ -1372,383 +1858,21 @@ declare function getLoader<L extends LoaderLike | ConstructorRepresentation<Load
1372
1858
  * Note: this hook's caller must be wrapped with `React.Suspense`
1373
1859
  * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1374
1860
  */
1375
- declare function useLoader<I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void): I extends any[] ? LoaderResult<L>[] : LoaderResult<L>;
1861
+ 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>;
1376
1862
  declare namespace useLoader {
1377
- var preload: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void) => void;
1378
- var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I) => void;
1863
+ 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;
1864
+ var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
1379
1865
  var loader: typeof getLoader;
1380
1866
  }
1381
1867
 
1382
- /**
1383
- * Global Singleton Scheduler - manages the frame loop and job execution for ALL R3F roots.
1384
- *
1385
- * Features:
1386
- * - Single RAF loop for entire application
1387
- * - Root registration (multiple Canvas support)
1388
- * - Global phases for addEffect/addAfterEffect (deprecated)
1389
- * - Per-root job management with phases, priorities, FPS throttling
1390
- * - onIdle callbacks for addTail (deprecated)
1391
- * - Demand mode support via invalidate()
1392
- */
1393
- declare class Scheduler {
1394
- private static readonly INSTANCE_KEY;
1395
- private static get instance();
1396
- private static set instance(value);
1397
- /**
1398
- * Get the global scheduler instance (creates if doesn't exist).
1399
- * Uses HMR data to preserve instance across hot reloads.
1400
- * @returns {Scheduler} The singleton scheduler instance
1401
- */
1402
- static get(): Scheduler;
1403
- /**
1404
- * Reset the singleton instance. Stops the loop and clears all state.
1405
- * Primarily used for testing to ensure clean state between tests.
1406
- * @returns {void}
1407
- */
1408
- static reset(): void;
1409
- private roots;
1410
- private phaseGraph;
1411
- private loopState;
1412
- private stoppedTime;
1413
- private nextRootIndex;
1414
- private globalBeforeJobs;
1415
- private globalAfterJobs;
1416
- private nextGlobalIndex;
1417
- private idleCallbacks;
1418
- private nextJobIndex;
1419
- private jobStateListeners;
1420
- private pendingFrames;
1421
- private _frameloop;
1422
- private _independent;
1423
- private errorHandler;
1424
- private rootReadyCallbacks;
1425
- get phases(): string[];
1426
- get frameloop(): Frameloop;
1427
- set frameloop(mode: Frameloop);
1428
- get isRunning(): boolean;
1429
- get isReady(): boolean;
1430
- get independent(): boolean;
1431
- set independent(value: boolean);
1432
- constructor();
1433
- /**
1434
- * Register a root (Canvas) with the scheduler.
1435
- * The first root to register starts the RAF loop (if frameloop='always').
1436
- * @param {string} id - Unique identifier for this root
1437
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1438
- * @returns {() => void} Unsubscribe function to remove this root
1439
- */
1440
- registerRoot(id: string, options?: RootOptions): () => void;
1441
- /**
1442
- * Unregister a root from the scheduler.
1443
- * Cleans up all job state listeners for this root's jobs.
1444
- * The last root to unregister stops the RAF loop.
1445
- * @param {string} id - The root ID to unregister
1446
- * @returns {void}
1447
- */
1448
- unregisterRoot(id: string): void;
1449
- /**
1450
- * Subscribe to be notified when a root becomes available.
1451
- * Fires immediately if a root already exists.
1452
- * @param {() => void} callback - Function called when first root registers
1453
- * @returns {() => void} Unsubscribe function
1454
- */
1455
- onRootReady(callback: () => void): () => void;
1456
- /**
1457
- * Notify all registered root-ready callbacks.
1458
- * Called when the first root registers.
1459
- * @returns {void}
1460
- * @private
1461
- */
1462
- private notifyRootReady;
1463
- /**
1464
- * Ensure a default root exists for independent mode.
1465
- * Creates a minimal root with no state provider.
1466
- * @returns {void}
1467
- * @private
1468
- */
1469
- private ensureDefaultRoot;
1470
- /**
1471
- * Trigger error handling for job errors.
1472
- * Uses the bound error handler if available, otherwise logs to console.
1473
- * @param {Error} error - The error to handle
1474
- * @returns {void}
1475
- */
1476
- triggerError(error: Error): void;
1477
- /**
1478
- * Add a named phase to the scheduler's execution order.
1479
- * Marks all roots for rebuild to incorporate the new phase.
1480
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1481
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1482
- * @returns {void}
1483
- * @example
1484
- * scheduler.addPhase('physics', { before: 'update' });
1485
- * scheduler.addPhase('postprocess', { after: 'render' });
1486
- */
1487
- addPhase(name: string, options?: AddPhaseOptions): void;
1488
- /**
1489
- * Check if a phase exists in the scheduler.
1490
- * @param {string} name - The phase name to check
1491
- * @returns {boolean} True if the phase exists
1492
- */
1493
- hasPhase(name: string): boolean;
1494
- /**
1495
- * Register a global job that runs once per frame (not per-root).
1496
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1497
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1498
- * @param {string} id - Unique identifier for this global job
1499
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1500
- * @returns {() => void} Unsubscribe function to remove this global job
1501
- * @deprecated Use useFrame with phases instead
1502
- */
1503
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void;
1504
- /**
1505
- * Register an idle callback that fires when the loop stops.
1506
- * Used internally by deprecated addTail API.
1507
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
1508
- * @returns {() => void} Unsubscribe function to remove this idle callback
1509
- * @deprecated Use demand mode with invalidate() instead
1510
- */
1511
- onIdle(callback: (timestamp: number) => void): () => void;
1512
- /**
1513
- * Notify all registered idle callbacks.
1514
- * Called when the loop stops in demand mode.
1515
- * @param {number} timestamp - The RAF timestamp when idle occurred
1516
- * @returns {void}
1517
- * @private
1518
- */
1519
- private notifyIdle;
1520
- /**
1521
- * Register a job (frame callback) with a specific root.
1522
- * This is the core registration method used by useFrame internally.
1523
- * @param {FrameNextCallback} callback - The function to call each frame
1524
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
1525
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
1526
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
1527
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
1528
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
1529
- * @param {number} [options.fps] - FPS throttle limit
1530
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
1531
- * @param {boolean} [options.enabled] - Whether job is active (default true)
1532
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
1533
- * @returns {() => void} Unsubscribe function to remove this job
1534
- */
1535
- register(callback: FrameNextCallback, options?: JobOptions & {
1536
- rootId?: string;
1537
- system?: boolean;
1538
- }): () => void;
1539
- /**
1540
- * Unregister a job by its ID.
1541
- * Searches all roots if rootId is not provided.
1542
- * @param {string} id - The job ID to unregister
1543
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
1544
- * @returns {void}
1545
- */
1546
- unregister(id: string, rootId?: string): void;
1547
- /**
1548
- * Update a job's options dynamically.
1549
- * Searches all roots to find the job by ID.
1550
- * Phase/constraint changes trigger a rebuild of the sorted job list.
1551
- * @param {string} id - The job ID to update
1552
- * @param {Partial<JobOptions>} options - The options to update
1553
- * @returns {void}
1554
- */
1555
- updateJob(id: string, options: Partial<JobOptions>): void;
1556
- /**
1557
- * Check if a job is currently paused (disabled).
1558
- * @param {string} id - The job ID to check
1559
- * @returns {boolean} True if the job exists and is paused
1560
- */
1561
- isJobPaused(id: string): boolean;
1562
- /**
1563
- * Subscribe to state changes for a specific job.
1564
- * Listener is called when job is paused or resumed.
1565
- * @param {string} id - The job ID to subscribe to
1566
- * @param {() => void} listener - Callback invoked on state changes
1567
- * @returns {() => void} Unsubscribe function
1568
- */
1569
- subscribeJobState(id: string, listener: () => void): () => void;
1570
- /**
1571
- * Notify all listeners that a job's state has changed.
1572
- * @param {string} id - The job ID that changed
1573
- * @returns {void}
1574
- * @private
1575
- */
1576
- private notifyJobStateChange;
1577
- /**
1578
- * Pause a job by ID (sets enabled=false).
1579
- * Notifies any subscribed state listeners.
1580
- * @param {string} id - The job ID to pause
1581
- * @returns {void}
1582
- */
1583
- pauseJob(id: string): void;
1584
- /**
1585
- * Resume a paused job by ID (sets enabled=true).
1586
- * Resets job timing to prevent frame accumulation.
1587
- * Notifies any subscribed state listeners.
1588
- * @param {string} id - The job ID to resume
1589
- * @returns {void}
1590
- */
1591
- resumeJob(id: string): void;
1592
- /**
1593
- * Start the requestAnimationFrame loop.
1594
- * Resets timing state (elapsedTime, frameCount) on start.
1595
- * No-op if already running.
1596
- * @returns {void}
1597
- */
1598
- start(): void;
1599
- /**
1600
- * Stop the requestAnimationFrame loop.
1601
- * Cancels any pending RAF callback.
1602
- * No-op if not running.
1603
- * @returns {void}
1604
- */
1605
- stop(): void;
1606
- /**
1607
- * Request frames to be rendered in demand mode.
1608
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
1609
- * No-op if frameloop is not 'demand'.
1610
- * @param {number} [frames=1] - Number of frames to request
1611
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
1612
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
1613
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
1614
- * @returns {void}
1615
- * @example
1616
- * // Request a single frame render
1617
- * scheduler.invalidate();
1618
- *
1619
- * @example
1620
- * // Request 5 frames (e.g., for animations)
1621
- * scheduler.invalidate(5);
1622
- *
1623
- * @example
1624
- * // Set pending frames to exactly 3 (don't stack with existing)
1625
- * scheduler.invalidate(3, false);
1626
- *
1627
- * @example
1628
- * // Add 2 more frames to existing pending count
1629
- * scheduler.invalidate(2, true);
1630
- */
1631
- invalidate(frames?: number, stackFrames?: boolean): void;
1632
- /**
1633
- * Reset timing state for deterministic testing.
1634
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
1635
- * @returns {void}
1636
- */
1637
- resetTiming(): void;
1638
- /**
1639
- * Manually execute a single frame for all roots.
1640
- * Useful for frameloop='never' mode or testing scenarios.
1641
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
1642
- * @returns {void}
1643
- * @example
1644
- * // Manual control mode
1645
- * scheduler.frameloop = 'never';
1646
- * scheduler.step(); // Execute one frame
1647
- */
1648
- step(timestamp?: number): void;
1649
- /**
1650
- * Manually execute a single job by its ID.
1651
- * Useful for testing individual job callbacks in isolation.
1652
- * @param {string} id - The job ID to step
1653
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
1654
- * @returns {void}
1655
- */
1656
- stepJob(id: string, timestamp?: number): void;
1657
- /**
1658
- * Main RAF loop callback.
1659
- * Executes frame, handles demand mode, and schedules next frame.
1660
- * @param {number} timestamp - RAF timestamp in milliseconds
1661
- * @returns {void}
1662
- * @private
1663
- */
1664
- private loop;
1665
- /**
1666
- * Execute a single frame across all roots.
1667
- * Order: globalBefore → each root's jobs → globalAfter
1668
- * @param {number} timestamp - RAF timestamp in milliseconds
1669
- * @returns {void}
1670
- * @private
1671
- */
1672
- private executeFrame;
1673
- /**
1674
- * Run all global jobs from a job map.
1675
- * Catches and logs errors without stopping execution.
1676
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
1677
- * @param {number} timestamp - RAF timestamp in milliseconds
1678
- * @returns {void}
1679
- * @private
1680
- */
1681
- private runGlobalJobs;
1682
- /**
1683
- * Execute all jobs for a single root in sorted order.
1684
- * Rebuilds sorted job list if needed, then dispatches each job.
1685
- * Errors are caught and propagated via triggerError.
1686
- * @param {RootEntry} root - The root entry to tick
1687
- * @param {number} timestamp - RAF timestamp in milliseconds
1688
- * @param {number} delta - Time since last frame in seconds
1689
- * @returns {void}
1690
- * @private
1691
- */
1692
- private tickRoot;
1693
- /**
1694
- * Get the total number of registered jobs across all roots.
1695
- * Includes both per-root jobs and global before/after jobs.
1696
- * @returns {number} Total job count
1697
- */
1698
- getJobCount(): number;
1699
- /**
1700
- * Get all registered job IDs across all roots.
1701
- * Includes both per-root jobs and global before/after jobs.
1702
- * @returns {string[]} Array of all job IDs
1703
- */
1704
- getJobIds(): string[];
1705
- /**
1706
- * Get the number of registered roots (Canvas instances).
1707
- * @returns {number} Number of registered roots
1708
- */
1709
- getRootCount(): number;
1710
- /**
1711
- * Check if any user (non-system) jobs are registered in a specific phase.
1712
- * Used by the default render job to know if a user has taken over rendering.
1713
- *
1714
- * @param phase The phase to check
1715
- * @param rootId Optional root ID to check (checks all roots if not provided)
1716
- * @returns true if any user jobs exist in the phase
1717
- */
1718
- hasUserJobsInPhase(phase: string, rootId?: string): boolean;
1719
- /**
1720
- * Generate a unique root ID for automatic root registration.
1721
- * @returns {string} A unique root ID in the format 'root_N'
1722
- */
1723
- generateRootId(): string;
1724
- /**
1725
- * Generate a unique job ID.
1726
- * @returns {string} A unique job ID in the format 'job_N'
1727
- * @private
1728
- */
1729
- private generateJobId;
1730
- /**
1731
- * Normalize before/after constraints to a Set.
1732
- * Handles undefined, single string, or array inputs.
1733
- * @param {string | string[] | undefined} value - The constraint value(s)
1734
- * @returns {Set<string>} Normalized Set of constraint strings
1735
- * @private
1736
- */
1737
- private normalizeConstraints;
1738
- }
1739
- /**
1740
- * Get the global scheduler instance.
1741
- * Creates one if it doesn't exist.
1742
- */
1743
- declare const getScheduler: () => Scheduler;
1744
-
1745
1868
  /**
1746
1869
  * Frame hook with phase-based ordering, priority, and FPS throttling.
1747
1870
  *
1748
- * Works both inside and outside Canvas context:
1749
- * - Inside Canvas: Full RootState (gl, scene, camera, etc.)
1750
- * - Outside Canvas (waiting mode): Waits for Canvas to mount, then gets full state
1751
- * - Outside Canvas (independent mode): Fires immediately with timing-only state
1871
+ * Always delivers full RootState — works both inside and outside Canvas context:
1872
+ * - Inside Canvas: Full RootState (renderer, scene, camera, etc.)
1873
+ * - Outside Canvas: The job registers immediately but the callback is held until a
1874
+ * Canvas adopts it, then runs with full RootState. For hostless / standalone
1875
+ * frame loops with no Canvas, use `@pmndrs/scheduler` directly.
1752
1876
  *
1753
1877
  * Returns a controls object for manual stepping, pausing, and resuming.
1754
1878
  *
@@ -1765,16 +1889,16 @@ declare const getScheduler: () => Scheduler;
1765
1889
  * useFrame((state, delta) => { ... }, { phase: 'physics' })
1766
1890
  *
1767
1891
  * @example
1768
- * // Outside Canvas - waits for Canvas to mount
1892
+ * // Outside Canvas - callback waits for a Canvas, then always has full state
1769
1893
  * function UI() {
1770
1894
  * useFrame((state, delta) => { syncUI(state.camera) });
1771
1895
  * return <button>...</button>;
1772
1896
  * }
1773
1897
  *
1774
1898
  * @example
1775
- * // Independent mode - no Canvas needed
1776
- * getScheduler().independent = true;
1777
- * useFrame((state, delta) => { updateGame(delta) });
1899
+ * // Hostless / standalone loop (no Canvas) - use @pmndrs/scheduler directly
1900
+ * import { getScheduler } from '@pmndrs/scheduler'
1901
+ * getScheduler().register((state, delta) => { updateGame(delta) })
1778
1902
  *
1779
1903
  * @example
1780
1904
  * // Scheduler-only access (no callback)
@@ -1797,11 +1921,16 @@ type UseTextureOptions<Url extends string[] | string | Record<string, string>> =
1797
1921
  /** Callback when texture(s) finish loading */
1798
1922
  onLoad?: (texture: MappedTextureType<Url>) => void;
1799
1923
  /**
1800
- * Cache the texture in R3F's global state for access via useTextures().
1801
- * When true:
1924
+ * Register the texture(s) in R3F's global texture registry for access via useTextures().
1925
+ * When true (the default):
1802
1926
  * - Textures persist until explicitly disposed
1803
- * - Returns existing cached textures if available (preserving modifications like colorSpace)
1804
- * @default false
1927
+ * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
1928
+ *
1929
+ * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
1930
+ * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
1931
+ *
1932
+ * Pass `false` to opt out of registry enrollment entirely.
1933
+ * @default true
1805
1934
  */
1806
1935
  cache?: boolean;
1807
1936
  };
@@ -1825,15 +1954,18 @@ type UseTextureOptions<Url extends string[] | string | Record<string, string>> =
1825
1954
  * normal: '/normal.png'
1826
1955
  * })
1827
1956
  *
1828
- * // With caching - returns same texture object across components
1829
- * // Modifications (colorSpace, wrapS, etc.) are preserved
1830
- * const diffuse = useTexture('/diffuse.png', { cache: true })
1957
+ * // Textures are registered in the global registry by default — the same texture
1958
+ * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
1959
+ * const diffuse = useTexture('/diffuse.png')
1831
1960
  * diffuse.colorSpace = THREE.SRGBColorSpace
1832
1961
  *
1833
1962
  * // Another component gets the SAME texture with colorSpace already set
1834
- * const sameDiffuse = useTexture('/diffuse.png', { cache: true })
1963
+ * const sameDiffuse = useTexture('/diffuse.png')
1964
+ *
1965
+ * // Opt out of registry enrollment for a one-off texture
1966
+ * const scratch = useTexture('/scratch.png', { cache: false })
1835
1967
  *
1836
- * // Access cache directly
1968
+ * // Access the registry directly
1837
1969
  * const { get } = useTextures()
1838
1970
  * const cached = get('/diffuse.png')
1839
1971
  * ```
@@ -1850,63 +1982,80 @@ declare const Texture: ({ children, input, onLoad, cache, }: {
1850
1982
  cache?: boolean;
1851
1983
  }) => react_jsx_runtime.JSX.Element;
1852
1984
 
1853
- type TextureEntry = Texture$1 | {
1854
- value: Texture$1;
1855
- [key: string]: any;
1985
+ /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
1986
+ type TextureInput = string | string[] | Record<string, string>;
1987
+ /** Result of a `get()` read, mirroring the input shape. */
1988
+ type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
1989
+ [K in keyof Input]: Texture$1 | undefined;
1856
1990
  };
1991
+ /** Options for `dispose()`. */
1992
+ interface DisposeOptions {
1993
+ /** Dispose even if the texture still has active references (default false). */
1994
+ force?: boolean;
1995
+ }
1857
1996
  interface UseTexturesReturn {
1858
- /** Map of all textures currently in cache */
1859
- textures: Map<string, TextureEntry>;
1860
- /** Get a specific texture by key (usually URL) */
1861
- get: (key: string) => TextureEntry | undefined;
1862
- /** Check if a texture exists in cache */
1863
- has: (key: string) => boolean;
1864
- /** Add a texture to the cache */
1865
- add: (key: string, value: TextureEntry) => void;
1866
- /** Add multiple textures to the cache */
1867
- addMultiple: (items: Map<string, TextureEntry> | Record<string, TextureEntry>) => void;
1868
- /** Remove a texture from cache (does NOT dispose GPU resources) */
1869
- remove: (key: string) => void;
1870
- /** Remove multiple textures from cache */
1871
- removeMultiple: (keys: string[]) => void;
1872
- /** Dispose a texture's GPU resources and remove from cache */
1873
- dispose: (key: string) => void;
1874
- /** Dispose multiple textures */
1875
- disposeMultiple: (keys: string[]) => void;
1876
- /** Dispose ALL cached textures - use with caution */
1877
- disposeAll: () => void;
1878
- }
1879
- /**
1880
- * Hook for managing the global texture cache in R3F state.
1881
- *
1882
- * Textures are stored in a Map with URL/path keys for efficient lookup.
1883
- * Useful for sharing texture references across materials and components.
1997
+ /** The live registry Map (key → Texture). Treat as read-only. */
1998
+ readonly all: Map<string, Texture$1>;
1999
+ /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2000
+ get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2001
+ /** Check whether a key exists in the registry. */
2002
+ has(key: string): boolean;
2003
+ /**
2004
+ * Register a texture (or a record of textures) that has no URL — e.g. a render
2005
+ * target or procedural texture. URL-loaded textures are registered automatically
2006
+ * by `useTexture` (registry enrollment is on by default).
2007
+ */
2008
+ add(key: string, texture: Texture$1): void;
2009
+ add(record: Record<string, Texture$1>): void;
2010
+ /**
2011
+ * Dispose a texture's GPU resources and remove it from the registry.
2012
+ * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2013
+ * skipped (with a warning) unless `{ force: true }` is passed.
2014
+ * @returns true if disposed, false if skipped.
2015
+ */
2016
+ dispose(key: string, options?: DisposeOptions): boolean;
2017
+ /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2018
+ disposeAll(): void;
2019
+ }
2020
+ /**
2021
+ * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
2022
+ *
2023
+ * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2024
+ * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2025
+ * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2026
+ *
2027
+ * The returned handle is **reactive**: the calling component re-renders when the registry
2028
+ * changes. Pass a selector to scope the subscription to a single read.
1884
2029
  *
1885
2030
  * @example
1886
2031
  * ```tsx
1887
- * const { textures, add, get, remove, has, dispose } = useTextures()
2032
+ * // Load + register once (anywhere in the tree) — registered by default
2033
+ * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
1888
2034
  *
1889
- * // Check if texture is already cached
1890
- * if (!has('/textures/diffuse.png')) {
1891
- * // Load with useTexture and cache: true, or manually add
1892
- * const tex = useTexture('/textures/diffuse.png', { cache: true })
1893
- * }
1894
- *
1895
- * // Access cached texture from anywhere
1896
- * const diffuse = get('/textures/diffuse.png')
1897
- * if (diffuse) material.map = diffuse
2035
+ * // Reach them from another component — record form lands straight into a material
2036
+ * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2037
+ * return <meshStandardMaterial map={map} normalMap={normalMap} />
1898
2038
  *
1899
- * // Remove from cache only (texture still in GPU memory)
1900
- * remove('/textures/old.png')
2039
+ * // A set of heightmaps at once
2040
+ * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
1901
2041
  *
1902
- * // Fully dispose (frees GPU memory + removes from cache)
1903
- * dispose('/textures/unused.png')
2042
+ * // Register a non-URL texture (render target / procedural)
2043
+ * useTextures().add('rt-main', renderTarget.texture)
1904
2044
  *
1905
- * // Nuclear option - dispose everything
1906
- * disposeAll()
2045
+ * // Deliberate GPU cleanup (refcount-aware; force to override)
2046
+ * useTextures().dispose('/diffuse.jpg')
2047
+ * useTextures().disposeAll() // scene teardown
1907
2048
  * ```
2049
+ *
2050
+ * @remarks
2051
+ * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2052
+ * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2053
+ * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2054
+ * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2055
+ * `useTexture`.
1908
2056
  */
1909
2057
  declare function useTextures(): UseTexturesReturn;
2058
+ declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
1910
2059
 
1911
2060
  /**
1912
2061
  * Creates a render target compatible with the current renderer.
@@ -1915,31 +2064,30 @@ declare function useTextures(): UseTexturesReturn;
1915
2064
  * - WebGPU build: Returns RenderTarget
1916
2065
  * - Default build: Returns whichever matches the active renderer
1917
2066
  *
1918
- * @param width - Target width (defaults to canvas width)
1919
- * @param height - Target height (defaults to canvas height)
1920
- * @param options - Three.js RenderTarget options
1921
- *
1922
2067
  * @example
1923
2068
  * ```tsx
1924
- * function PortalScene() {
1925
- * const fbo = useRenderTarget(512, 512, { depthBuffer: true })
1926
- *
1927
- * useFrame(({ renderer, scene, camera }) => {
1928
- * renderer.setRenderTarget(fbo)
1929
- * renderer.render(scene, camera)
1930
- * renderer.setRenderTarget(null)
1931
- * })
1932
- *
1933
- * return (
1934
- * <mesh>
1935
- * <planeGeometry />
1936
- * <meshBasicMaterial map={fbo.texture} />
1937
- * </mesh>
1938
- * )
1939
- * }
2069
+ * // Use canvas size
2070
+ * const fbo = useRenderTarget()
2071
+ *
2072
+ * // Use canvas size with options
2073
+ * const fbo = useRenderTarget({ samples: 4 })
2074
+ *
2075
+ * // Square render target
2076
+ * const fbo = useRenderTarget(512)
2077
+ *
2078
+ * // Square render target with options
2079
+ * const fbo = useRenderTarget(512, { depthBuffer: true })
2080
+ *
2081
+ * // Explicit dimensions
2082
+ * const fbo = useRenderTarget(512, 256)
2083
+ *
2084
+ * // Explicit dimensions with options
2085
+ * const fbo = useRenderTarget(512, 256, { samples: 4 })
1940
2086
  * ```
1941
2087
  */
1942
- declare function useRenderTarget(width?: number, height?: number, options?: RenderTargetOptions): RenderTarget<THREE$1.Texture<unknown>>;
2088
+ declare function useRenderTarget(options?: RenderTargetOptions): WebGLRenderTarget;
2089
+ declare function useRenderTarget(size: number, options?: RenderTargetOptions): WebGLRenderTarget;
2090
+ declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): WebGLRenderTarget;
1943
2091
 
1944
2092
  /**
1945
2093
  * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
@@ -2044,7 +2192,7 @@ declare function invalidate(state?: RootState, frames?: number, stackFrames?: bo
2044
2192
  *
2045
2193
  * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2046
2194
  */
2047
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame): void;
2195
+ declare function advance(timestamp: number): void;
2048
2196
 
2049
2197
  /* eslint-disable @definitelytyped/no-unnecessary-generics */
2050
2198
  declare function ReactReconciler<
@@ -3098,6 +3246,12 @@ declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3098
3246
  declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3099
3247
  declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3100
3248
  declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3249
+ interface PortalProps {
3250
+ children: ReactNode;
3251
+ state?: InjectState;
3252
+ container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3253
+ }
3254
+ declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3101
3255
  /**
3102
3256
  * Force React to flush any updates inside the provided callback synchronously and immediately.
3103
3257
  * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
@@ -3109,11 +3263,6 @@ declare function flushSync<R>(fn: () => R): R;
3109
3263
  declare const context: React$1.Context<RootStore>;
3110
3264
  declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
3111
3265
 
3112
- /**
3113
- * Safely flush async effects when testing, simulating a legacy root.
3114
- * @deprecated Import from React instead. import { act } from 'react'
3115
- */
3116
- declare const act: typeof React$1.act;
3117
3266
  /**
3118
3267
  * An SSR-friendly useLayoutEffect.
3119
3268
  *
@@ -3526,11 +3675,76 @@ declare const hasConstructor: (object: unknown) => object is {
3526
3675
  constructor?: Function;
3527
3676
  };
3528
3677
 
3678
+ /**
3679
+ * Symbol marker for deferred ref resolution.
3680
+ * Used to identify values that should be resolved from refs after mount.
3681
+ */
3682
+ declare const FROM_REF: unique symbol;
3683
+ /**
3684
+ * Defers prop application until the referenced object is available.
3685
+ * Useful for props like `target` that need sibling refs to be populated.
3686
+ *
3687
+ * @param ref - React ref object to resolve at mount time
3688
+ * @returns A marker value that applyProps will resolve after mount
3689
+ *
3690
+ * @example
3691
+ * const targetRef = useRef<THREE.Object3D>(null)
3692
+ *
3693
+ * <group ref={targetRef} position={[-3, -2, -15]} />
3694
+ * <spotLight target={fromRef(targetRef)} intensity={100} />
3695
+ */
3696
+ declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
3697
+ /**
3698
+ * Type guard to check if a value is a fromRef marker.
3699
+ *
3700
+ * @param value - Value to check
3701
+ * @returns True if value is a fromRef marker
3702
+ */
3703
+ declare function isFromRef(value: unknown): value is {
3704
+ [FROM_REF]: React$1.RefObject<any>;
3705
+ };
3706
+
3707
+ /**
3708
+ * Symbol marker for mount-only method calls.
3709
+ * Used to identify methods that should only be called once on initial mount.
3710
+ */
3711
+ declare const ONCE: unique symbol;
3712
+ /**
3713
+ * Marks a method call to be executed only on initial mount.
3714
+ * Useful for geometry transforms that should not be reapplied on every render.
3715
+ *
3716
+ * When `args` prop changes (triggering reconstruction), the method will be
3717
+ * called again on the new instance since appliedOnce is not carried over.
3718
+ *
3719
+ * @param args - Arguments to pass to the method
3720
+ * @returns A marker value that applyProps will execute once
3721
+ *
3722
+ * @example
3723
+ * // Rotate geometry on mount
3724
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
3725
+ *
3726
+ * // Multiple arguments
3727
+ * <bufferGeometry applyMatrix4={once(matrix)} />
3728
+ *
3729
+ * // No arguments
3730
+ * <geometry center={once()} />
3731
+ */
3732
+ declare function once<T>(...args: T[]): T;
3733
+ /**
3734
+ * Type guard to check if a value is a once marker.
3735
+ *
3736
+ * @param value - Value to check
3737
+ * @returns True if value is a once marker
3738
+ */
3739
+ declare function isOnce(value: unknown): value is {
3740
+ [ONCE]: any[] | true;
3741
+ };
3742
+
3529
3743
  /**
3530
3744
  * A DOM canvas which accepts threejs elements as children.
3531
3745
  * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3532
3746
  */
3533
3747
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3534
3748
 
3535
- export { Block, Canvas, ErrorBoundary, IsObject, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, getInstanceProps, getRootState, getScheduler, getUuidPrefix, hasConstructor, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isObject3D, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, prepare, reconciler, removeInteractivity, resolve, unmountComponentAtNode, updateCamera, updateFrustum, useBridge, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree };
3536
- export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BaseRendererProps, Bridge, Camera, CameraProps, CanvasProps, Catalogue, Color, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DomEvent, Dpr, ElementProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameControls, FrameNextCallback, FrameNextControls, FrameNextState, FrameState, FrameTimingState, Frameloop, GLProps, GLTFLike, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, Properties, Quaternion, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererFactory, RendererProps, Root, RootOptions, RootState, RootStore, SchedulerApi, SetBlock, Size, Subscription, TextureEntry, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager };
3749
+ 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, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, 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, reconciler, registerPrimary, removeInteractivity, resolve, swapInteractivity, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
3750
+ export type { Act, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferLike, BufferRecord, BufferStore, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DisposeOptions, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameNextCallback, FrameNextState, FrameState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, LegacyInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeProps, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, LegacyRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, LegacyRootState as RootState, RootStore, SetBlock, Size, StorageLike, StorageRecord, StorageStore, Subscription, TSLNodeInput, TextureInput, TextureResult, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager, XRPointerConfig };