@react-three/fiber 10.0.0-canary.b0fafc8 → 10.0.0-canary.d6fdf72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import * as three_webgpu from 'three/webgpu';
2
- import { RenderTarget, WebGPURenderer, CanvasTarget, Node, ShaderNodeObject, Euler as Euler$2, Color as Color$2, ColorRepresentation as ColorRepresentation$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, Loader as Loader$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera, WebGPURendererParameters } from 'three/webgpu';
2
+ import { RenderTarget, WebGPURenderer, Node, StorageTexture, Data3DTexture, CanvasTarget, ShaderNodeObject, Euler as Euler$2, Color as Color$2, ColorRepresentation as ColorRepresentation$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, Loader as Loader$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera, WebGPURendererParameters } from 'three/webgpu';
3
3
  import { Inspector } from 'three/addons/inspector/Inspector.js';
4
4
  import * as THREE$1 from 'three';
5
5
  import { Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1 } from 'three';
@@ -151,6 +151,8 @@ interface IntersectionEvent<TSourceEvent> extends Intersection {
151
151
  unprojectedPoint: THREE$1.Vector3
152
152
  /** Normalized event coordinates */
153
153
  pointer: THREE$1.Vector2
154
+ /** pointerId of the original event for multiple pointer events */
155
+ pointerId: number
154
156
  /** Delta between first click and this event */
155
157
  delta: number
156
158
  /** The ray that pierced it */
@@ -227,6 +229,18 @@ interface EventHandlers {
227
229
  type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
228
230
  type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
229
231
 
232
+ /** Configuration for XR pointer registration (controllers/hands) */
233
+ interface XRPointerConfig {
234
+ /** Ray origin (updated each frame by XR system) */
235
+ ray: THREE$1.Ray
236
+ /** Optional: custom compute function for this pointer */
237
+ compute?: (state: RootState) => void
238
+ /** Pointer type identifier */
239
+ type: 'controller' | 'hand' | 'gaze'
240
+ /** Which hand (for controller/hand types) */
241
+ handedness?: 'left' | 'right'
242
+ }
243
+
230
244
  interface EventManager<TTarget> {
231
245
  /** Determines if the event layer is active */
232
246
  enabled: boolean
@@ -246,8 +260,21 @@ interface EventManager<TTarget> {
246
260
  disconnect?: () => void
247
261
  /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
248
262
  * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
263
+ * @param pointerId - Optional pointer ID to update specific pointer only
249
264
  */
250
- update?: () => void
265
+ update?: (pointerId?: number) => void
266
+ /** Defer pointer move raycasting to frame start (default: true) */
267
+ frameTimedRaycasts?: boolean
268
+ /** Always fire raycaster immediately on scroll events (default: true) */
269
+ alwaysFireOnScroll?: boolean
270
+ /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
271
+ updateOnFrame?: boolean
272
+ /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
273
+ flush?: () => void
274
+ /** Register an XR pointer (controller/hand). Returns assigned pointerId */
275
+ registerPointer?: (config: XRPointerConfig) => number
276
+ /** Unregister an XR pointer */
277
+ unregisterPointer?: (pointerId: number) => void
251
278
  }
252
279
 
253
280
  interface PointerCaptureTarget {
@@ -489,6 +516,68 @@ interface SchedulerApi {
489
516
  subscribeJobState(id: string, listener: () => void): () => void
490
517
  }
491
518
 
519
+ //* Buffer Types (useBuffers) ========================================
520
+
521
+ /**
522
+ * Buffer-like types for GPU compute and storage operations.
523
+ * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
524
+ *
525
+ * @example
526
+ * ```tsx
527
+ * const { positions, velocities } = useBuffers(() => ({
528
+ * positions: instancedArray(count, 'vec3'), // StorageBufferNode
529
+ * velocities: new Float32Array(count * 3), // TypedArray
530
+ * }), 'particles')
531
+ * ```
532
+ */
533
+ type BufferLike =
534
+ | Float32Array
535
+ | Uint32Array
536
+ | Int32Array
537
+ | Float64Array
538
+ | Uint8Array
539
+ | Int8Array
540
+ | Uint16Array
541
+ | Int16Array
542
+ | THREE$1.BufferAttribute // Base class for all buffer attributes
543
+ | Node // TSL buffer nodes (instancedArray, storage)
544
+
545
+ /** Flat record of buffer-like values (no nested scopes) */
546
+ type BufferRecord = Record<string, BufferLike>
547
+
548
+ /**
549
+ * Buffer store that can contain both root-level buffers and scoped buffer objects.
550
+ * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
551
+ */
552
+ type BufferStore = Record<string, BufferLike | BufferRecord>
553
+
554
+ //* Storage Types (useGPUStorage) ========================================
555
+
556
+ /**
557
+ * GPU storage types for texture-based storage operations.
558
+ * Includes Three.js storage textures and TSL storage texture nodes.
559
+ *
560
+ * @example
561
+ * ```tsx
562
+ * const { heightMap } = useGPUStorage(() => ({
563
+ * heightMap: new StorageTexture(512, 512),
564
+ * }), 'terrain')
565
+ * ```
566
+ */
567
+ type StorageLike =
568
+ | StorageTexture // GPU storage texture
569
+ | Data3DTexture // 3D texture (can be used as storage)
570
+ | Node // TSL storage texture nodes (storageTexture)
571
+
572
+ /** Flat record of storage-like values (no nested scopes) */
573
+ type StorageRecord = Record<string, StorageLike>
574
+
575
+ /**
576
+ * Storage store that can contain both root-level storage and scoped storage objects.
577
+ * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
578
+ */
579
+ type StorageStore = Record<string, StorageLike | StorageRecord>
580
+
492
581
  //* Renderer Types ========================================
493
582
 
494
583
  /** Default renderer type - union of WebGL and WebGPU renderers */
@@ -502,6 +591,18 @@ type Subscription = {
502
591
  store: RootStore
503
592
  }
504
593
 
594
+ /** Per-pointer state for multi-touch and XR support */
595
+ type PointerState = {
596
+ /** Objects currently hovered by this pointer */
597
+ hovered: Map<string, ThreeEvent<DomEvent>>
598
+ /** Objects capturing this pointer */
599
+ captured: Map<THREE$1.Object3D, PointerCaptureTarget>
600
+ /** Initial click position [x, y] */
601
+ initialClick: [x: number, y: number]
602
+ /** Objects hit on initial click */
603
+ initialHits: THREE$1.Object3D[]
604
+ }
605
+
505
606
  type Dpr = number | [min: number, max: number]
506
607
 
507
608
  interface Size {
@@ -543,12 +644,21 @@ interface Performance {
543
644
 
544
645
  interface InternalState {
545
646
  interaction: THREE$1.Object3D[]
546
- hovered: Map<string, ThreeEvent<DomEvent>>
547
647
  subscribers: Subscription[]
648
+ /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
649
+ pointerMap: Map<number, PointerState>
650
+ /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
651
+ pointerDirty: Map<number, DomEvent>
652
+ /** Last event received (for events.update() compatibility) */
653
+ lastEvent: React$1.RefObject<DomEvent | null>
654
+ /** @deprecated Use pointerMap.get(pointerId).hovered instead */
655
+ hovered: Map<string, ThreeEvent<DomEvent>>
656
+ /** @deprecated Use pointerMap.get(pointerId).captured instead */
548
657
  capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
658
+ /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
549
659
  initialClick: [x: number, y: number]
660
+ /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
550
661
  initialHits: THREE$1.Object3D[]
551
- lastEvent: React$1.RefObject<DomEvent | null>
552
662
  /** Visibility event registry (onFramed, onOccluded, onVisible) */
553
663
  visibilityRegistry: Map<string, VisibilityEntry>
554
664
  /** Whether occlusion queries are enabled (WebGPU only) */
@@ -689,11 +799,17 @@ interface RootState {
689
799
  uniforms: UniformStore
690
800
  /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
691
801
  nodes: Record<string, any>
692
- /** Global TSL texture nodes - use useTextures() hook for operations */
693
- textures: Map<string, any>
694
- /** WebGPU PostProcessing instance - use usePostProcessing() hook */
695
- postProcessing: any | null // THREE.PostProcessing when available
696
- /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
802
+ /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
803
+ buffers: BufferStore
804
+ /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
805
+ gpuStorage: StorageStore
806
+ /** Global Texture registry (key Texture, usually keyed by URL) - use useTextures() hook for access + lifecycle */
807
+ textures: Map<string, THREE$1.Texture>
808
+ /** Internal: refcount per texture key, driven by mounted useTexture consumers (registry enrollment is on by default) */
809
+ _textureRefs: Map<string, number>
810
+ /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
811
+ renderPipeline: any | null // THREE.PostProcessing (will be THREE.RenderPipeline in future Three.js release)
812
+ /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
697
813
  passes: Record<string, any>
698
814
  /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
699
815
  _hmrVersion: number
@@ -743,6 +859,20 @@ interface Renderer {
743
859
  render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
744
860
  }
745
861
 
862
+ //* Color Management Config ==============================
863
+
864
+ /**
865
+ * Color management configuration shared by both WebGL and WebGPU renderers.
866
+ */
867
+ interface ColorManagementConfig {
868
+ /**
869
+ * Color space assigned to 8-bit input textures (color maps).
870
+ * Defaults to sRGB. Most textures are authored in sRGB.
871
+ * @default THREE.SRGBColorSpace
872
+ */
873
+ textureColorSpace?: THREE$1.ColorSpace
874
+ }
875
+
746
876
  //* WebGL Renderer Props ==============================
747
877
 
748
878
  type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
@@ -753,7 +883,7 @@ type GLProps =
753
883
  | Renderer
754
884
  | ((defaultProps: DefaultGLProps) => Renderer)
755
885
  | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
756
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
886
+ | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
757
887
 
758
888
  //* WebGPU Renderer Props ==============================
759
889
 
@@ -779,9 +909,9 @@ interface CanvasSchedulerConfig {
779
909
  }
780
910
 
781
911
  /**
782
- * Extended renderer configuration for multi-canvas support.
912
+ * Extended renderer configuration for multi-canvas support and color management.
783
913
  */
784
- interface RendererConfigExtended {
914
+ interface RendererConfigExtended extends ColorManagementConfig {
785
915
  /** Share renderer from another canvas (WebGPU only) */
786
916
  primaryCanvas?: string
787
917
  /** Canvas-level scheduler options */
@@ -846,8 +976,6 @@ interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
846
976
  * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
847
977
  */
848
978
  shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
849
- /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
850
- textureColorSpace?: THREE$1.ColorSpace
851
979
  /** Creates an orthographic camera */
852
980
  orthographic?: boolean
853
981
  /**
@@ -1100,7 +1228,7 @@ interface CanvasProps
1100
1228
  */
1101
1229
  resize?: Options
1102
1230
  /** The target where events are being subscribed to, default: the div that wraps canvas */
1103
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
1231
+ eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1104
1232
  /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1105
1233
  eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1106
1234
  /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
@@ -1314,6 +1442,7 @@ declare global {
1314
1442
  | three_webgpu.Euler
1315
1443
  | three_webgpu.Quaternion
1316
1444
  | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1445
+ | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1317
1446
  | Node // TSL nodes like color(), vec3(), float() for type casting
1318
1447
  | UniformNode
1319
1448
 
@@ -1359,34 +1488,34 @@ declare module 'three/tsl' {
1359
1488
  }
1360
1489
 
1361
1490
  /**
1362
- * PostProcessing Types for usePostProcessing hook (WebGPU only)
1491
+ * RenderPipeline Types for useRenderPipeline hook (WebGPU only)
1363
1492
  */
1364
1493
 
1365
1494
 
1366
1495
 
1367
1496
  declare global {
1368
- /** Pass record - stores TSL pass nodes for post-processing */
1497
+ /** Pass record - stores TSL pass nodes for render pipeline */
1369
1498
  type PassRecord = Record<string, any>
1370
1499
 
1371
1500
  /** Setup callback - runs first to configure MRT, create additional passes */
1372
- type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1501
+ type RenderPipelineSetupCallback = (state: RootState) => PassRecord | void
1373
1502
 
1374
1503
  /** Main callback - runs second to configure outputNode, create effect passes */
1375
- type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1504
+ type RenderPipelineMainCallback = (state: RootState) => PassRecord | void
1376
1505
 
1377
- /** Return type for usePostProcessing hook */
1378
- interface UsePostProcessingReturn {
1506
+ /** Return type for useRenderPipeline hook */
1507
+ interface UseRenderPipelineReturn {
1379
1508
  /** Current passes from state */
1380
1509
  passes: PassRecord
1381
- /** PostProcessing instance (null if not initialized) */
1382
- postProcessing: any | null // THREE.PostProcessing
1510
+ /** RenderPipeline instance (null if not initialized) */
1511
+ renderPipeline: any | null // THREE.PostProcessing (will be THREE.RenderPipeline in future Three.js release)
1383
1512
  /** Clear all passes from state */
1384
1513
  clearPasses: () => void
1385
- /** Reset PostProcessing entirely (clears PP + passes) */
1514
+ /** Reset RenderPipeline entirely (clears PP + passes) */
1386
1515
  reset: () => void
1387
1516
  /** Re-run setup/main callbacks with current closure values */
1388
1517
  rebuild: () => void
1389
- /** True when PostProcessing is configured and ready */
1518
+ /** True when RenderPipeline is configured and ready */
1390
1519
  isReady: boolean
1391
1520
  }
1392
1521
  }
@@ -2006,6 +2135,8 @@ declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Ele
2006
2135
  declare function removeInteractivity(store: RootStore, object: Object3D): void;
2007
2136
  declare function createEvents(store: RootStore): {
2008
2137
  handlePointer: (name: string) => (event: DomEvent) => void;
2138
+ flushDeferredPointers: () => void;
2139
+ processDeferredPointer: (event: DomEvent, pointerId: number) => void;
2009
2140
  };
2010
2141
  /** Default R3F event manager for web */
2011
2142
  declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
@@ -2446,11 +2577,16 @@ type UseTextureOptions<Url extends string[] | string | Record<string, string>> =
2446
2577
  /** Callback when texture(s) finish loading */
2447
2578
  onLoad?: (texture: MappedTextureType<Url>) => void;
2448
2579
  /**
2449
- * Cache the texture in R3F's global state for access via useTextures().
2450
- * When true:
2580
+ * Register the texture(s) in R3F's global texture registry for access via useTextures().
2581
+ * When true (the default):
2451
2582
  * - Textures persist until explicitly disposed
2452
- * - Returns existing cached textures if available (preserving modifications like colorSpace)
2453
- * @default false
2583
+ * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
2584
+ *
2585
+ * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
2586
+ * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
2587
+ *
2588
+ * Pass `false` to opt out of registry enrollment entirely.
2589
+ * @default true
2454
2590
  */
2455
2591
  cache?: boolean;
2456
2592
  };
@@ -2474,15 +2610,18 @@ type UseTextureOptions<Url extends string[] | string | Record<string, string>> =
2474
2610
  * normal: '/normal.png'
2475
2611
  * })
2476
2612
  *
2477
- * // With caching - returns same texture object across components
2478
- * // Modifications (colorSpace, wrapS, etc.) are preserved
2479
- * const diffuse = useTexture('/diffuse.png', { cache: true })
2613
+ * // Textures are registered in the global registry by default — the same texture
2614
+ * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
2615
+ * const diffuse = useTexture('/diffuse.png')
2480
2616
  * diffuse.colorSpace = THREE.SRGBColorSpace
2481
2617
  *
2482
2618
  * // Another component gets the SAME texture with colorSpace already set
2483
- * const sameDiffuse = useTexture('/diffuse.png', { cache: true })
2619
+ * const sameDiffuse = useTexture('/diffuse.png')
2620
+ *
2621
+ * // Opt out of registry enrollment for a one-off texture
2622
+ * const scratch = useTexture('/scratch.png', { cache: false })
2484
2623
  *
2485
- * // Access cache directly
2624
+ * // Access the registry directly
2486
2625
  * const { get } = useTextures()
2487
2626
  * const cached = get('/diffuse.png')
2488
2627
  * ```
@@ -2499,63 +2638,80 @@ declare const Texture: ({ children, input, onLoad, cache, }: {
2499
2638
  cache?: boolean;
2500
2639
  }) => react_jsx_runtime.JSX.Element;
2501
2640
 
2502
- type TextureEntry = Texture$1 | {
2503
- value: Texture$1;
2504
- [key: string]: any;
2641
+ /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
2642
+ type TextureInput = string | string[] | Record<string, string>;
2643
+ /** Result of a `get()` read, mirroring the input shape. */
2644
+ type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
2645
+ [K in keyof Input]: Texture$1 | undefined;
2505
2646
  };
2647
+ /** Options for `dispose()`. */
2648
+ interface DisposeOptions {
2649
+ /** Dispose even if the texture still has active references (default false). */
2650
+ force?: boolean;
2651
+ }
2506
2652
  interface UseTexturesReturn {
2507
- /** Map of all textures currently in cache */
2508
- textures: Map<string, TextureEntry>;
2509
- /** Get a specific texture by key (usually URL) */
2510
- get: (key: string) => TextureEntry | undefined;
2511
- /** Check if a texture exists in cache */
2512
- has: (key: string) => boolean;
2513
- /** Add a texture to the cache */
2514
- add: (key: string, value: TextureEntry) => void;
2515
- /** Add multiple textures to the cache */
2516
- addMultiple: (items: Map<string, TextureEntry> | Record<string, TextureEntry>) => void;
2517
- /** Remove a texture from cache (does NOT dispose GPU resources) */
2518
- remove: (key: string) => void;
2519
- /** Remove multiple textures from cache */
2520
- removeMultiple: (keys: string[]) => void;
2521
- /** Dispose a texture's GPU resources and remove from cache */
2522
- dispose: (key: string) => void;
2523
- /** Dispose multiple textures */
2524
- disposeMultiple: (keys: string[]) => void;
2525
- /** Dispose ALL cached textures - use with caution */
2526
- disposeAll: () => void;
2653
+ /** The live registry Map (key Texture). Treat as read-only. */
2654
+ readonly all: Map<string, Texture$1>;
2655
+ /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2656
+ get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2657
+ /** Check whether a key exists in the registry. */
2658
+ has(key: string): boolean;
2659
+ /**
2660
+ * Register a texture (or a record of textures) that has no URL — e.g. a render
2661
+ * target or procedural texture. URL-loaded textures are registered automatically
2662
+ * by `useTexture` (registry enrollment is on by default).
2663
+ */
2664
+ add(key: string, texture: Texture$1): void;
2665
+ add(record: Record<string, Texture$1>): void;
2666
+ /**
2667
+ * Dispose a texture's GPU resources and remove it from the registry.
2668
+ * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2669
+ * skipped (with a warning) unless `{ force: true }` is passed.
2670
+ * @returns true if disposed, false if skipped.
2671
+ */
2672
+ dispose(key: string, options?: DisposeOptions): boolean;
2673
+ /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2674
+ disposeAll(): void;
2527
2675
  }
2528
2676
  /**
2529
- * Hook for managing the global texture cache in R3F state.
2677
+ * Reactive Texture registry load once with `useTexture`, reach the textures from anywhere.
2530
2678
  *
2531
- * Textures are stored in a Map with URL/path keys for efficient lookup.
2532
- * Useful for sharing texture references across materials and components.
2679
+ * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2680
+ * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2681
+ * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2682
+ *
2683
+ * The returned handle is **reactive**: the calling component re-renders when the registry
2684
+ * changes. Pass a selector to scope the subscription to a single read.
2533
2685
  *
2534
2686
  * @example
2535
2687
  * ```tsx
2536
- * const { textures, add, get, remove, has, dispose } = useTextures()
2537
- *
2538
- * // Check if texture is already cached
2539
- * if (!has('/textures/diffuse.png')) {
2540
- * // Load with useTexture and cache: true, or manually add
2541
- * const tex = useTexture('/textures/diffuse.png', { cache: true })
2542
- * }
2688
+ * // Load + register once (anywhere in the tree) registered by default
2689
+ * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2543
2690
  *
2544
- * // Access cached texture from anywhere
2545
- * const diffuse = get('/textures/diffuse.png')
2546
- * if (diffuse) material.map = diffuse
2691
+ * // Reach them from another component — record form lands straight into a material
2692
+ * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2693
+ * return <meshStandardMaterial map={map} normalMap={normalMap} />
2547
2694
  *
2548
- * // Remove from cache only (texture still in GPU memory)
2549
- * remove('/textures/old.png')
2695
+ * // A set of heightmaps at once
2696
+ * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
2550
2697
  *
2551
- * // Fully dispose (frees GPU memory + removes from cache)
2552
- * dispose('/textures/unused.png')
2698
+ * // Register a non-URL texture (render target / procedural)
2699
+ * useTextures().add('rt-main', renderTarget.texture)
2553
2700
  *
2554
- * // Nuclear option - dispose everything
2555
- * disposeAll()
2701
+ * // Deliberate GPU cleanup (refcount-aware; force to override)
2702
+ * useTextures().dispose('/diffuse.jpg')
2703
+ * useTextures().disposeAll() // scene teardown
2556
2704
  * ```
2705
+ *
2706
+ * @remarks
2707
+ * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2708
+ * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2709
+ * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2710
+ * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2711
+ * `useTexture`.
2557
2712
  */
2558
2713
  declare function useTextures(): UseTexturesReturn;
2714
+ declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
2559
2715
 
2560
2716
  /**
2561
2717
  * Creates a render target compatible with the current renderer.
@@ -2585,9 +2741,9 @@ declare function useTextures(): UseTexturesReturn;
2585
2741
  * const fbo = useRenderTarget(512, 256, { samples: 4 })
2586
2742
  * ```
2587
2743
  */
2588
- declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget | WebGLRenderTarget;
2589
- declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget | WebGLRenderTarget;
2590
- declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget | WebGLRenderTarget;
2744
+ declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget;
2745
+ declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget;
2746
+ declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget;
2591
2747
 
2592
2748
  /**
2593
2749
  * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
@@ -4300,13 +4456,17 @@ type ScopedStoreType<T> = {
4300
4456
  declare function createScopedStore<T>(data: Record<string, any>): ScopedStoreType<T>;
4301
4457
  /**
4302
4458
  * State type passed to creator functions with ScopedStore wrappers.
4303
- * Provides type-safe access to uniforms and nodes without manual casting.
4459
+ * Provides type-safe access to uniforms, nodes, buffers, and gpuStorage without manual casting.
4304
4460
  */
4305
- type CreatorState = Omit<RootState, 'uniforms' | 'nodes'> & {
4461
+ type CreatorState = Omit<RootState, 'uniforms' | 'nodes' | 'buffers' | 'gpuStorage'> & {
4306
4462
  /** Type-safe uniform access - property access returns UniformNode */
4307
4463
  uniforms: ScopedStoreType<UniformNode>;
4308
4464
  /** Type-safe node access - property access returns TSLNodeType (Node | ShaderCallable | ShaderNodeObject) */
4309
4465
  nodes: ScopedStoreType<TSLNodeType>;
4466
+ /** Type-safe buffer access - property access returns BufferLike (TypedArrays, BufferAttributes, TSL nodes) */
4467
+ buffers: ScopedStoreType<BufferLike>;
4468
+ /** Type-safe GPU storage access - property access returns StorageLike (StorageTexture, TSL nodes) */
4469
+ gpuStorage: ScopedStoreType<StorageLike>;
4310
4470
  };
4311
4471
 
4312
4472
  /** Creator function that returns uniform inputs (can be raw values or UniformNodes) */
@@ -4470,6 +4630,74 @@ type LocalNodeCreator<T extends Record<string, unknown>> = (state: CreatorState)
4470
4630
  */
4471
4631
  declare function useLocalNodes<T extends Record<string, unknown>>(creator: LocalNodeCreator<T>): T;
4472
4632
 
4633
+ /**
4634
+ * Creator function that returns a record of buffers.
4635
+ * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4636
+ */
4637
+ type BufferCreator<T extends Record<string, BufferLike>> = (state: CreatorState) => T;
4638
+ /** Function signature for removeBuffers util */
4639
+ type RemoveBuffersFn = (names: string | string[], scope?: string) => void;
4640
+ /** Function signature for clearBuffers util */
4641
+ type ClearBuffersFn = (scope?: string) => void;
4642
+ /** Function signature for rebuildBuffers util */
4643
+ type RebuildBuffersFn = (scope?: string) => void;
4644
+ /** Function signature for disposeBuffers util - releases GPU resources */
4645
+ type DisposeBuffersFn = (names: string | string[], scope?: string) => void;
4646
+ /** Return type with utils included */
4647
+ type BuffersWithUtils<T extends Record<string, BufferLike> = Record<string, BufferLike>> = T & {
4648
+ removeBuffers: RemoveBuffersFn;
4649
+ clearBuffers: ClearBuffersFn;
4650
+ rebuildBuffers: RebuildBuffersFn;
4651
+ disposeBuffers: DisposeBuffersFn;
4652
+ };
4653
+ declare function useBuffers(): BuffersWithUtils<Record<string, BufferLike> & Record<string, Record<string, BufferLike>>>;
4654
+ declare function useBuffers(scope: string): BuffersWithUtils<Record<string, BufferLike>>;
4655
+ declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>): BuffersWithUtils<T>;
4656
+ declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>, scope: string): BuffersWithUtils<T>;
4657
+ /**
4658
+ * Global rebuildBuffers function for HMR integration.
4659
+ * Clears cached buffers and increments _hmrVersion to trigger re-creation.
4660
+ * Call this when HMR is detected to refresh all buffer creators.
4661
+ *
4662
+ * @param store - The R3F store (from useStore or context)
4663
+ * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4664
+ */
4665
+ declare function rebuildAllBuffers(store: ReturnType<typeof useStore>, scope?: string): void;
4666
+
4667
+ /**
4668
+ * Creator function that returns a record of GPU storage objects.
4669
+ * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4670
+ */
4671
+ type StorageCreator<T extends Record<string, StorageLike>> = (state: CreatorState) => T;
4672
+ /** Function signature for removeStorage util */
4673
+ type RemoveStorageFn = (names: string | string[], scope?: string) => void;
4674
+ /** Function signature for clearStorage util */
4675
+ type ClearStorageFn = (scope?: string) => void;
4676
+ /** Function signature for rebuildStorage util */
4677
+ type RebuildStorageFn = (scope?: string) => void;
4678
+ /** Function signature for disposeStorage util - releases GPU resources */
4679
+ type DisposeStorageFn = (names: string | string[], scope?: string) => void;
4680
+ /** Return type with utils included */
4681
+ type StorageWithUtils<T extends Record<string, StorageLike> = Record<string, StorageLike>> = T & {
4682
+ removeStorage: RemoveStorageFn;
4683
+ clearStorage: ClearStorageFn;
4684
+ rebuildStorage: RebuildStorageFn;
4685
+ disposeStorage: DisposeStorageFn;
4686
+ };
4687
+ declare function useGPUStorage(): StorageWithUtils<Record<string, StorageLike> & Record<string, Record<string, StorageLike>>>;
4688
+ declare function useGPUStorage(scope: string): StorageWithUtils<Record<string, StorageLike>>;
4689
+ declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>): StorageWithUtils<T>;
4690
+ declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>, scope: string): StorageWithUtils<T>;
4691
+ /**
4692
+ * Global rebuildStorage function for HMR integration.
4693
+ * Clears cached storage and increments _hmrVersion to trigger re-creation.
4694
+ * Call this when HMR is detected to refresh all storage creators.
4695
+ *
4696
+ * @param store - The R3F store (from useStore or context)
4697
+ * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4698
+ */
4699
+ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: string): void;
4700
+
4473
4701
  interface TextureOperations {
4474
4702
  add: (key: string, value: any) => void;
4475
4703
  addMultiple: (items: Map<string, any> | Record<string, any>) => void;
@@ -4479,10 +4707,10 @@ interface TextureOperations {
4479
4707
  declare function createTextureOperations(set: StoreApi<RootState>['setState']): TextureOperations;
4480
4708
 
4481
4709
  /**
4482
- * Hook for managing WebGPU PostProcessing with automatic scenePass setup.
4710
+ * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
4483
4711
  *
4484
4712
  * Features:
4485
- * - Creates PostProcessing instance if not exists
4713
+ * - Creates RenderPipeline instance if not exists
4486
4714
  * - Creates default scenePass (no MRT) automatically
4487
4715
  * - Callbacks receive full RootState for flexibility
4488
4716
  * - No auto-cleanup on unmount - use reset() for explicit cleanup
@@ -4490,21 +4718,21 @@ declare function createTextureOperations(set: StoreApi<RootState>['setState']):
4490
4718
  *
4491
4719
  * @param mainCB - Main callback to configure outputNode and create effect passes
4492
4720
  * @param setupCB - Optional setup callback to configure MRT on scenePass
4493
- * @returns { passes, postProcessing, clearPasses, reset, rebuild }
4721
+ * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
4494
4722
  *
4495
4723
  * @example
4496
4724
  * ```tsx
4497
4725
  * // Simple effect
4498
- * usePostProcessing(({ postProcessing, passes }) => {
4499
- * postProcessing.outputNode = bloom(passes.scenePass.getTextureNode())
4726
+ * useRenderPipeline(({ renderPipeline, passes }) => {
4727
+ * renderPipeline.outputNode = bloom(passes.scenePass.getTextureNode())
4500
4728
  * })
4501
4729
  *
4502
4730
  * // With MRT setup
4503
- * usePostProcessing(
4504
- * ({ postProcessing, passes }) => {
4731
+ * useRenderPipeline(
4732
+ * ({ renderPipeline, passes }) => {
4505
4733
  * const beauty = passes.scenePass.getTextureNode().toInspector('Color')
4506
4734
  * const vel = passes.scenePass.getTextureNode('velocity')
4507
- * postProcessing.outputNode = motionBlur(beauty, vel)
4735
+ * renderPipeline.outputNode = motionBlur(beauty, vel)
4508
4736
  * },
4509
4737
  * ({ passes }) => {
4510
4738
  * passes.scenePass.setMRT(mrt({ output, velocity }))
@@ -4512,10 +4740,10 @@ declare function createTextureOperations(set: StoreApi<RootState>['setState']):
4512
4740
  * )
4513
4741
  *
4514
4742
  * // Read-only access
4515
- * const { postProcessing, passes } = usePostProcessing()
4743
+ * const { renderPipeline, passes } = useRenderPipeline()
4516
4744
  * ```
4517
4745
  */
4518
- declare function usePostProcessing(mainCB?: PostProcessingMainCallback, setupCB?: PostProcessingSetupCallback): UsePostProcessingReturn;
4746
+ declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
4519
4747
 
4520
4748
  //* Renderer Props ========================================
4521
4749
 
@@ -4564,5 +4792,5 @@ interface WebGPURootState extends Omit<RootState, 'renderer' | 'gl' | 'internal'
4564
4792
  internal: WebGPUInternalState
4565
4793
  }
4566
4794
 
4567
- 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, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllNodes, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, usePostProcessing, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
4568
- export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, ClearNodesFn, ClearUniformsFn, Color, ComputeFunction, ConstructorRepresentation, CreatorState, DefaultGLProps, DefaultRendererProps, Disposable, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameControls, FrameNextCallback, FrameNextControls, FrameNextState, FrameState, FrameTimingState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, WebGPUInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, LocalNodeCreator, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeCreator, NodeProps, NodeRecord, NodesWithUtils, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, WebGPUR3FRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, RebuildNodesFn, RebuildUniformsFn, ReconcilerRoot, RemoveNodesFn, RemoveUniformsFn, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, RootOptions, WebGPURootState as RootState, RootStore, SchedulerApi, ScopedStoreType, SetBlock, Size, Subscription, TSLNode, TSLNodeInput, TextureEntry, TextureOperations, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UniformCreator, UniformValue, UniformsWithUtils, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig, XRManager };
4795
+ 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, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
4796
+ export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferCreator, BufferLike, BufferRecord, BufferStore, BuffersWithUtils, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, ClearBuffersFn, ClearNodesFn, ClearStorageFn, ClearUniformsFn, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, CreatorState, DefaultGLProps, DefaultRendererProps, Disposable, DisposeBuffersFn, DisposeOptions, DisposeStorageFn, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameControls, FrameNextCallback, FrameNextControls, FrameNextState, FrameState, FrameTimingState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, WebGPUInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, LocalNodeCreator, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeCreator, NodeProps, NodeRecord, NodesWithUtils, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, WebGPUR3FRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, RebuildBuffersFn, RebuildNodesFn, RebuildStorageFn, RebuildUniformsFn, ReconcilerRoot, RemoveBuffersFn, RemoveNodesFn, RemoveStorageFn, RemoveUniformsFn, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, RootOptions, WebGPURootState as RootState, RootStore, SchedulerApi, ScopedStoreType, SetBlock, Size, StorageCreator, StorageLike, StorageRecord, StorageStore, StorageWithUtils, Subscription, TSLNode, TSLNodeInput, TextureInput, TextureOperations, TextureResult, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UniformCreator, UniformValue, UniformsWithUtils, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig, XRManager, XRPointerConfig };