@react-three/fiber 10.0.0-canary.07c4f9d → 10.0.0-canary.0ea97c0

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/index.d.ts CHANGED
@@ -363,6 +363,33 @@ type BufferRecord = Record<string, BufferLike>
363
363
  */
364
364
  type BufferStore = Record<string, BufferLike | BufferRecord>
365
365
 
366
+ //* Node Types (useNodes) ========================================
367
+
368
+ /**
369
+ * Structural shape of a TSL node as stored on `state.nodes`.
370
+ *
371
+ * Deliberately minimal rather than three's nominal `Node`: in @types/three several node classes
372
+ * TSL hands back (OperatorNode, ConstNode, ...) do not extend `Node` cleanly, so a `Node` bound
373
+ * would reject values `useNodes` creators legitimately return. This is the same shape
374
+ * `useNodes` already constrains creators to (`TSLNodeLike`).
375
+ */
376
+ interface NodeLike {
377
+ uuid?: string
378
+ nodeType?: string | null
379
+ /** label method for chaining - sets the node's label and returns self */
380
+ label?: ((label: string) => NodeLike) | string
381
+ setName?: (name: string) => this
382
+ }
383
+
384
+ /** Flat record of TSL nodes (no nested scopes) */
385
+ type NodeRecord = Record<string, NodeLike>
386
+
387
+ /**
388
+ * Node store that can contain both root-level nodes and scoped node objects.
389
+ * Structure: { wobble: OperatorNode, fx: { blur: ShaderCallable } }
390
+ */
391
+ type NodeStore = Record<string, NodeLike | NodeRecord>
392
+
366
393
  //* Storage Types (useGPUStorage) ========================================
367
394
 
368
395
  /**
@@ -496,8 +523,13 @@ interface InternalState {
496
523
  /** Container for child attachment (scene for root, original container for portals) */
497
524
  container?: THREE$1.Object3D
498
525
  /**
499
- * CanvasTarget for multi-canvas WebGPU rendering.
500
- * Created for all WebGPU canvases to support renderer sharing.
526
+ * The CanvasTarget this root sizes and renders through.
527
+ *
528
+ * A primary (`<Canvas id>`) owns the renderer's default target -- the one three itself built
529
+ * around the canvas element -- so sizing it is sizing the renderer. A secondary owns a target
530
+ * R3F created for its own element. Either way there is exactly one target per canvas element,
531
+ * and the canvas-target job makes it the renderer's active one before this root renders.
532
+ * Absent on WebGL and on an id-less WebGPU canvas, where the renderer is sized directly.
501
533
  * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
502
534
  */
503
535
  canvasTarget?: CanvasTarget
@@ -622,7 +654,7 @@ interface RootState {
622
654
  /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
623
655
  uniforms: UniformStore
624
656
  /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
625
- nodes: Record<string, any>
657
+ nodes: NodeStore
626
658
  /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
627
659
  buffers: BufferStore
628
660
  /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
@@ -634,7 +666,7 @@ interface RootState {
634
666
  /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
635
667
  renderPipeline: ThreeRenderPipeline | null
636
668
  /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
637
- passes: Record<string, any>
669
+ passes: PassRecord
638
670
  /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
639
671
  _hmrVersion: number
640
672
  /** Internal: whether setSize() has taken ownership of canvas dimensions */
@@ -1182,7 +1214,33 @@ declare global {
1182
1214
  * ergonomics. The result is three's structural type, so members stay in sync with the
1183
1215
  * installed three instead of needing to be mirrored by hand.
1184
1216
  */
1185
- type UniformNode<T = unknown> = three_webgpu.UniformNode<unknown, T>
1217
+ type UniformNode<T = unknown> = three_webgpu.UniformNode<UniformNodeTypeFor<T>, T>
1218
+
1219
+ /**
1220
+ * three's node type name for a uniform value type, mirroring the `uniform()` overloads.
1221
+ * A `UniformNode<number>` is a `Node<'float'>`, so TSL math (`.mul`, `.add`, ...) accepts it.
1222
+ * Unknown or unlisted value types resolve to `unknown`, which TSL math rejects: narrow with
1223
+ * `as UniformNode<number>` (or the matching value type) at the call site.
1224
+ */
1225
+ type UniformNodeTypeFor<T> = T extends number
1226
+ ? 'float'
1227
+ : T extends boolean
1228
+ ? 'bool'
1229
+ : T extends three_webgpu.Color
1230
+ ? 'color'
1231
+ : T extends three_webgpu.Vector2
1232
+ ? 'vec2'
1233
+ : T extends three_webgpu.Vector3
1234
+ ? 'vec3'
1235
+ : T extends three_webgpu.Vector4
1236
+ ? 'vec4'
1237
+ : T extends three_webgpu.Matrix2
1238
+ ? 'mat2'
1239
+ : T extends three_webgpu.Matrix3
1240
+ ? 'mat3'
1241
+ : T extends three_webgpu.Matrix4
1242
+ ? 'mat4'
1243
+ : unknown
1186
1244
 
1187
1245
  /**
1188
1246
  * ShaderCallable - the return type of Fn()
@@ -1335,35 +1393,97 @@ declare global {
1335
1393
  */
1336
1394
  type ThreeRenderPipeline = three_webgpu.RenderPipeline
1337
1395
 
1338
- /** Pass record - stores TSL pass nodes for render pipeline */
1339
- type PassRecord = Record<string, any>
1396
+ /**
1397
+ * The pass `useRenderPipeline` creates for you: three's own `PassNode`, as returned by
1398
+ * `pass(scene, camera)` from `three/tsl`. Referenced from three so members like
1399
+ * `getTextureNode`, `setMRT` and `dispose` track the installed version.
1400
+ */
1401
+ type ScenePassNode = three_webgpu.PassNode
1402
+
1403
+ /**
1404
+ * Pass record - stores TSL pass nodes for render pipeline.
1405
+ *
1406
+ * `scenePass` is the only key the library owns. It is optional here because this is also the
1407
+ * shape of `state.passes`, which is `{}` before the pipeline exists and again after `reset()`
1408
+ * or `clearPasses()`. Inside the callbacks it is always present; see
1409
+ * {@link RenderPipelineCallbackState}.
1410
+ *
1411
+ * Every other key is user-registered, via a callback's return value. Those are TSL nodes of
1412
+ * any kind, not only passes: texture reads of an MRT attachment, effect nodes, extra
1413
+ * `pass()` instances. `Node` is the common base, so that is the bound. Narrow at the call
1414
+ * site when you need a member, e.g. `passes.velocity as TextureNode`.
1415
+ */
1416
+ interface PassRecord {
1417
+ scenePass?: ScenePassNode
1418
+ [key: string]: three_webgpu.Node
1419
+ }
1340
1420
 
1341
- /** State passed to pipeline callbacks after the active pipeline has been created */
1421
+ /**
1422
+ * State passed to pipeline callbacks after the active pipeline has been created.
1423
+ *
1424
+ * `passes.scenePass` is required here: the hook installs the default scene pass before either
1425
+ * callback runs, so callbacks can use it without a guard or a cast.
1426
+ *
1427
+ * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
1428
+ * the legacy renderer before either callback can run, so a callback never sees WebGL.
1429
+ */
1342
1430
  type RenderPipelineCallbackState = RootState & {
1343
1431
  renderPipeline: ThreeRenderPipeline
1432
+ passes: PassRecord & { scenePass: ScenePassNode }
1433
+ renderer: three_webgpu.WebGPURenderer
1434
+ isLegacy: false
1344
1435
  }
1345
1436
 
1437
+ /**
1438
+ * What a callback may return to register entries into `state.passes`.
1439
+ *
1440
+ * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
1441
+ * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
1442
+ * store entry would leave the store pointing at a node the hook never disposes, and the hook
1443
+ * disposing a pass nothing references. So returning it is a type error.
1444
+ */
1445
+ type RegisteredPasses = Record<string, three_webgpu.Node> & { scenePass?: never }
1446
+
1346
1447
  /** Setup callback - runs first to configure MRT, create additional passes */
1347
- type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => PassRecord | void
1448
+ type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1348
1449
 
1349
1450
  /** Main callback - runs second to configure outputNode, create effect passes */
1350
- type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => PassRecord | void
1451
+ type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1351
1452
 
1352
- /** Return type for useRenderPipeline hook */
1353
- interface UseRenderPipelineReturn {
1453
+ /** The imperative half of useRenderPipeline's return value, present in every state */
1454
+ interface UseRenderPipelineActions {
1354
1455
  /** Current passes from state */
1355
1456
  passes: PassRecord
1356
- /** RenderPipeline instance (null if not initialized) */
1357
- renderPipeline: ThreeRenderPipeline | null
1358
1457
  /** Clear all passes from state */
1359
1458
  clearPasses: () => void
1360
1459
  /** Reset RenderPipeline entirely (clears PP + passes) */
1361
1460
  reset: () => void
1362
1461
  /** Re-run setup/main callbacks with current closure values */
1363
1462
  rebuild: () => void
1364
- /** True when RenderPipeline is configured and ready */
1365
- isReady: boolean
1366
1463
  }
1464
+
1465
+ /**
1466
+ * Return type for useRenderPipeline hook, discriminated on `isReady`.
1467
+ *
1468
+ * `if (isReady)` narrows `renderPipeline` to non-null, which is what the docs already tell
1469
+ * callers to check. `passes.scenePass` deliberately stays optional in the ready branch:
1470
+ * `clearPasses()` empties the record while leaving the pipeline in place.
1471
+ */
1472
+ type UseRenderPipelineReturn = UseRenderPipelineActions &
1473
+ (
1474
+ | {
1475
+ /** True when RenderPipeline is configured and ready */
1476
+ isReady: true
1477
+ /** RenderPipeline instance */
1478
+ renderPipeline: ThreeRenderPipeline
1479
+ }
1480
+ | {
1481
+ /** False until the pipeline has been created */
1482
+ isReady: false
1483
+ /** Not initialized yet, or torn down by reset() */
1484
+ renderPipeline: null
1485
+ }
1486
+ )
1367
1487
  }
1368
1488
 
1369
1489
  type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
@@ -3781,4 +3901,4 @@ declare function isOnce(value: unknown): value is {
3781
3901
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3782
3902
 
3783
3903
  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 };
3784
- 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, 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, R3FRenderer, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, 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 };
3904
+ 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, InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeLike, NodeProps, NodeRecord, NodeStore, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, R3FRenderer, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, 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 };
package/dist/index.mjs CHANGED
@@ -602,7 +602,12 @@ function diffProps(instance, newProps) {
602
602
  const changedProps = {};
603
603
  for (const prop in newProps) {
604
604
  if (RESERVED_PROPS.includes(prop)) continue;
605
- if (is.equ(newProps[prop], instance.props[prop])) continue;
605
+ if (is.equ(newProps[prop], instance.props[prop])) {
606
+ const value = newProps[prop];
607
+ if (!isCopyable(value)) continue;
608
+ const { target } = resolve(instance.object, prop);
609
+ if (!isCopyable(target) || target.constructor !== value.constructor) continue;
610
+ }
606
611
  changedProps[prop] = newProps[prop];
607
612
  for (const other in newProps) {
608
613
  if (other.startsWith(`${prop}-`)) changedProps[other] = newProps[other];
@@ -1048,7 +1053,8 @@ const createStore = (invalidate, advance) => {
1048
1053
  const resizeTarget = canvasTarget ?? actualRenderer;
1049
1054
  if (viewport.dpr > 0) resizeTarget.setPixelRatio(viewport.dpr);
1050
1055
  resizeTarget.setSize(size.width, size.height, false);
1051
- internal.canvasTargetSizeDirty = true;
1056
+ const activeTarget = actualRenderer.getCanvasTarget?.();
1057
+ if (!canvasTarget || activeTarget !== canvasTarget) internal.canvasTargetSizeDirty = true;
1052
1058
  }
1053
1059
  if (camera !== oldCamera) {
1054
1060
  oldCamera = camera;
@@ -14230,9 +14236,8 @@ function createRoot(canvas) {
14230
14236
  if (!renderer.hasInitialized?.()) {
14231
14237
  const size2 = computeInitialSize(canvas, propsSize);
14232
14238
  if (size2.width > 0 && size2.height > 0) {
14233
- const pixelRatio = calculateDpr(dpr);
14234
- canvas.width = size2.width * pixelRatio;
14235
- canvas.height = size2.height * pixelRatio;
14239
+ renderer.setPixelRatio(calculateDpr(dpr));
14240
+ renderer.setSize(size2.width, size2.height, false);
14236
14241
  }
14237
14242
  await renderer.init();
14238
14243
  }
@@ -14241,7 +14246,7 @@ function createRoot(canvas) {
14241
14246
  state.internal.actualRenderer = renderer;
14242
14247
  state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14243
14248
  if (canvasId && !state.internal.isSecondary) {
14244
- const canvasTarget = new CanvasTarget(canvas);
14249
+ const canvasTarget = renderer.getCanvasTarget?.();
14245
14250
  const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14246
14251
  state.set((prev) => ({
14247
14252
  internal: {
@@ -14454,9 +14459,10 @@ function createRoot(canvas) {
14454
14459
  const unregisterCanvasTarget = scheduler.register(
14455
14460
  () => {
14456
14461
  const state2 = store.getState();
14457
- if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
14462
+ const canvasTarget = state2.internal.canvasTarget;
14463
+ if (canvasTarget) {
14458
14464
  const renderer2 = state2.internal.actualRenderer;
14459
- renderer2.setCanvasTarget(state2.internal.canvasTarget);
14465
+ if (renderer2.getCanvasTarget() !== canvasTarget) renderer2.setCanvasTarget(canvasTarget);
14460
14466
  if (state2.internal.canvasTargetSizeDirty) {
14461
14467
  state2.internal.canvasTargetSizeDirty = false;
14462
14468
  renderer2.backend?.updateSize?.();
@@ -14620,7 +14626,7 @@ function unmountComponentAtNode(canvas, callback) {
14620
14626
  const unregisterPrimary = state.internal.unregisterPrimary;
14621
14627
  if (unregisterPrimary) unregisterPrimary();
14622
14628
  const canvasTarget = state.internal.canvasTarget;
14623
- if (canvasTarget?.dispose) canvasTarget.dispose();
14629
+ if (state.internal.isSecondary && canvasTarget?.dispose) canvasTarget.dispose();
14624
14630
  state.events.disconnect?.();
14625
14631
  cleanupHelperGroup(root.store);
14626
14632
  if (state.isLegacy && renderer) {
@@ -15064,9 +15070,9 @@ function CanvasImpl({
15064
15070
  React.useMemo(() => extend(THREE), []);
15065
15071
  const Bridge = useBridge();
15066
15072
  const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15067
- const hasInitialSizeRef = React.useRef(false);
15073
+ const [hasInitialSize, setHasInitialSize] = React.useState(false);
15068
15074
  const measureConfig = React.useMemo(() => {
15069
- if (!hasInitialSizeRef.current) {
15075
+ if (!hasInitialSize) {
15070
15076
  return {
15071
15077
  ...resize,
15072
15078
  scroll: resize?.scroll ?? true,
@@ -15078,7 +15084,7 @@ function CanvasImpl({
15078
15084
  debounce: { scroll: 50, resize: 0 },
15079
15085
  ...resize
15080
15086
  };
15081
- }, [resize, hasInitialSizeRef.current]);
15087
+ }, [hasInitialSize, resize]);
15082
15088
  const [containerRef, containerRect] = useMeasure(measureConfig);
15083
15089
  const effectiveSize = React.useMemo(() => {
15084
15090
  let w = width ?? containerRect.width;
@@ -15094,9 +15100,7 @@ function CanvasImpl({
15094
15100
  left: containerRect.left
15095
15101
  };
15096
15102
  }, [width, height, containerRect, forceEven]);
15097
- if (!hasInitialSizeRef.current && effectiveSize.width > 0 && effectiveSize.height > 0) {
15098
- hasInitialSizeRef.current = true;
15099
- }
15103
+ if (!hasInitialSize && effectiveSize.width > 0 && effectiveSize.height > 0) setHasInitialSize(true);
15100
15104
  const canvasRef = React.useRef(null);
15101
15105
  const divRef = React.useRef(null);
15102
15106
  React.useImperativeHandle(ref, () => canvasRef.current);
package/dist/legacy.cjs CHANGED
@@ -626,7 +626,12 @@ function diffProps(instance, newProps) {
626
626
  const changedProps = {};
627
627
  for (const prop in newProps) {
628
628
  if (RESERVED_PROPS.includes(prop)) continue;
629
- if (is.equ(newProps[prop], instance.props[prop])) continue;
629
+ if (is.equ(newProps[prop], instance.props[prop])) {
630
+ const value = newProps[prop];
631
+ if (!isCopyable(value)) continue;
632
+ const { target } = resolve(instance.object, prop);
633
+ if (!isCopyable(target) || target.constructor !== value.constructor) continue;
634
+ }
630
635
  changedProps[prop] = newProps[prop];
631
636
  for (const other in newProps) {
632
637
  if (other.startsWith(`${prop}-`)) changedProps[other] = newProps[other];
@@ -1072,7 +1077,8 @@ const createStore = (invalidate, advance) => {
1072
1077
  const resizeTarget = canvasTarget ?? actualRenderer;
1073
1078
  if (viewport.dpr > 0) resizeTarget.setPixelRatio(viewport.dpr);
1074
1079
  resizeTarget.setSize(size.width, size.height, false);
1075
- internal.canvasTargetSizeDirty = true;
1080
+ const activeTarget = actualRenderer.getCanvasTarget?.();
1081
+ if (!canvasTarget || activeTarget !== canvasTarget) internal.canvasTargetSizeDirty = true;
1076
1082
  }
1077
1083
  if (camera !== oldCamera) {
1078
1084
  oldCamera = camera;
@@ -14429,9 +14435,10 @@ function createRoot(canvas) {
14429
14435
  const unregisterCanvasTarget = scheduler$1.register(
14430
14436
  () => {
14431
14437
  const state2 = store.getState();
14432
- if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
14438
+ const canvasTarget = state2.internal.canvasTarget;
14439
+ if (canvasTarget) {
14433
14440
  const renderer2 = state2.internal.actualRenderer;
14434
- renderer2.setCanvasTarget(state2.internal.canvasTarget);
14441
+ if (renderer2.getCanvasTarget() !== canvasTarget) renderer2.setCanvasTarget(canvasTarget);
14435
14442
  if (state2.internal.canvasTargetSizeDirty) {
14436
14443
  state2.internal.canvasTargetSizeDirty = false;
14437
14444
  renderer2.backend?.updateSize?.();
@@ -14595,7 +14602,7 @@ function unmountComponentAtNode(canvas, callback) {
14595
14602
  const unregisterPrimary = state.internal.unregisterPrimary;
14596
14603
  if (unregisterPrimary) unregisterPrimary();
14597
14604
  const canvasTarget = state.internal.canvasTarget;
14598
- if (canvasTarget?.dispose) canvasTarget.dispose();
14605
+ if (state.internal.isSecondary && canvasTarget?.dispose) canvasTarget.dispose();
14599
14606
  state.events.disconnect?.();
14600
14607
  cleanupHelperGroup(root.store);
14601
14608
  if (state.isLegacy && renderer) {
@@ -15039,9 +15046,9 @@ function CanvasImpl({
15039
15046
  React__namespace.useMemo(() => extend(THREE), []);
15040
15047
  const Bridge = useBridge();
15041
15048
  const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15042
- const hasInitialSizeRef = React__namespace.useRef(false);
15049
+ const [hasInitialSize, setHasInitialSize] = React__namespace.useState(false);
15043
15050
  const measureConfig = React__namespace.useMemo(() => {
15044
- if (!hasInitialSizeRef.current) {
15051
+ if (!hasInitialSize) {
15045
15052
  return {
15046
15053
  ...resize,
15047
15054
  scroll: resize?.scroll ?? true,
@@ -15053,7 +15060,7 @@ function CanvasImpl({
15053
15060
  debounce: { scroll: 50, resize: 0 },
15054
15061
  ...resize
15055
15062
  };
15056
- }, [resize, hasInitialSizeRef.current]);
15063
+ }, [hasInitialSize, resize]);
15057
15064
  const [containerRef, containerRect] = useMeasure__default(measureConfig);
15058
15065
  const effectiveSize = React__namespace.useMemo(() => {
15059
15066
  let w = width ?? containerRect.width;
@@ -15069,9 +15076,7 @@ function CanvasImpl({
15069
15076
  left: containerRect.left
15070
15077
  };
15071
15078
  }, [width, height, containerRect, forceEven]);
15072
- if (!hasInitialSizeRef.current && effectiveSize.width > 0 && effectiveSize.height > 0) {
15073
- hasInitialSizeRef.current = true;
15074
- }
15079
+ if (!hasInitialSize && effectiveSize.width > 0 && effectiveSize.height > 0) setHasInitialSize(true);
15075
15080
  const canvasRef = React__namespace.useRef(null);
15076
15081
  const divRef = React__namespace.useRef(null);
15077
15082
  React__namespace.useImperativeHandle(ref, () => canvasRef.current);
package/dist/legacy.d.cts CHANGED
@@ -359,6 +359,33 @@ type BufferRecord = Record<string, BufferLike>
359
359
  */
360
360
  type BufferStore = Record<string, BufferLike | BufferRecord>
361
361
 
362
+ //* Node Types (useNodes) ========================================
363
+
364
+ /**
365
+ * Structural shape of a TSL node as stored on `state.nodes`.
366
+ *
367
+ * Deliberately minimal rather than three's nominal `Node`: in @types/three several node classes
368
+ * TSL hands back (OperatorNode, ConstNode, ...) do not extend `Node` cleanly, so a `Node` bound
369
+ * would reject values `useNodes` creators legitimately return. This is the same shape
370
+ * `useNodes` already constrains creators to (`TSLNodeLike`).
371
+ */
372
+ interface NodeLike {
373
+ uuid?: string
374
+ nodeType?: string | null
375
+ /** label method for chaining - sets the node's label and returns self */
376
+ label?: ((label: string) => NodeLike) | string
377
+ setName?: (name: string) => this
378
+ }
379
+
380
+ /** Flat record of TSL nodes (no nested scopes) */
381
+ type NodeRecord = Record<string, NodeLike>
382
+
383
+ /**
384
+ * Node store that can contain both root-level nodes and scoped node objects.
385
+ * Structure: { wobble: OperatorNode, fx: { blur: ShaderCallable } }
386
+ */
387
+ type NodeStore = Record<string, NodeLike | NodeRecord>
388
+
362
389
  //* Storage Types (useGPUStorage) ========================================
363
390
 
364
391
  /**
@@ -492,8 +519,13 @@ interface InternalState {
492
519
  /** Container for child attachment (scene for root, original container for portals) */
493
520
  container?: THREE$1.Object3D
494
521
  /**
495
- * CanvasTarget for multi-canvas WebGPU rendering.
496
- * Created for all WebGPU canvases to support renderer sharing.
522
+ * The CanvasTarget this root sizes and renders through.
523
+ *
524
+ * A primary (`<Canvas id>`) owns the renderer's default target -- the one three itself built
525
+ * around the canvas element -- so sizing it is sizing the renderer. A secondary owns a target
526
+ * R3F created for its own element. Either way there is exactly one target per canvas element,
527
+ * and the canvas-target job makes it the renderer's active one before this root renders.
528
+ * Absent on WebGL and on an id-less WebGPU canvas, where the renderer is sized directly.
497
529
  * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
498
530
  */
499
531
  canvasTarget?: CanvasTarget
@@ -618,7 +650,7 @@ interface RootState {
618
650
  /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
619
651
  uniforms: UniformStore
620
652
  /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
621
- nodes: Record<string, any>
653
+ nodes: NodeStore
622
654
  /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
623
655
  buffers: BufferStore
624
656
  /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
@@ -630,7 +662,7 @@ interface RootState {
630
662
  /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
631
663
  renderPipeline: ThreeRenderPipeline | null
632
664
  /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
633
- passes: Record<string, any>
665
+ passes: PassRecord
634
666
  /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
635
667
  _hmrVersion: number
636
668
  /** Internal: whether setSize() has taken ownership of canvas dimensions */
@@ -1178,7 +1210,33 @@ declare global {
1178
1210
  * ergonomics. The result is three's structural type, so members stay in sync with the
1179
1211
  * installed three instead of needing to be mirrored by hand.
1180
1212
  */
1181
- type UniformNode<T = unknown> = three_webgpu.UniformNode<unknown, T>
1213
+ type UniformNode<T = unknown> = three_webgpu.UniformNode<UniformNodeTypeFor<T>, T>
1214
+
1215
+ /**
1216
+ * three's node type name for a uniform value type, mirroring the `uniform()` overloads.
1217
+ * A `UniformNode<number>` is a `Node<'float'>`, so TSL math (`.mul`, `.add`, ...) accepts it.
1218
+ * Unknown or unlisted value types resolve to `unknown`, which TSL math rejects: narrow with
1219
+ * `as UniformNode<number>` (or the matching value type) at the call site.
1220
+ */
1221
+ type UniformNodeTypeFor<T> = T extends number
1222
+ ? 'float'
1223
+ : T extends boolean
1224
+ ? 'bool'
1225
+ : T extends three_webgpu.Color
1226
+ ? 'color'
1227
+ : T extends three_webgpu.Vector2
1228
+ ? 'vec2'
1229
+ : T extends three_webgpu.Vector3
1230
+ ? 'vec3'
1231
+ : T extends three_webgpu.Vector4
1232
+ ? 'vec4'
1233
+ : T extends three_webgpu.Matrix2
1234
+ ? 'mat2'
1235
+ : T extends three_webgpu.Matrix3
1236
+ ? 'mat3'
1237
+ : T extends three_webgpu.Matrix4
1238
+ ? 'mat4'
1239
+ : unknown
1182
1240
 
1183
1241
  /**
1184
1242
  * ShaderCallable - the return type of Fn()
@@ -1331,35 +1389,97 @@ declare global {
1331
1389
  */
1332
1390
  type ThreeRenderPipeline = three_webgpu.RenderPipeline
1333
1391
 
1334
- /** Pass record - stores TSL pass nodes for render pipeline */
1335
- type PassRecord = Record<string, any>
1392
+ /**
1393
+ * The pass `useRenderPipeline` creates for you: three's own `PassNode`, as returned by
1394
+ * `pass(scene, camera)` from `three/tsl`. Referenced from three so members like
1395
+ * `getTextureNode`, `setMRT` and `dispose` track the installed version.
1396
+ */
1397
+ type ScenePassNode = three_webgpu.PassNode
1398
+
1399
+ /**
1400
+ * Pass record - stores TSL pass nodes for render pipeline.
1401
+ *
1402
+ * `scenePass` is the only key the library owns. It is optional here because this is also the
1403
+ * shape of `state.passes`, which is `{}` before the pipeline exists and again after `reset()`
1404
+ * or `clearPasses()`. Inside the callbacks it is always present; see
1405
+ * {@link RenderPipelineCallbackState}.
1406
+ *
1407
+ * Every other key is user-registered, via a callback's return value. Those are TSL nodes of
1408
+ * any kind, not only passes: texture reads of an MRT attachment, effect nodes, extra
1409
+ * `pass()` instances. `Node` is the common base, so that is the bound. Narrow at the call
1410
+ * site when you need a member, e.g. `passes.velocity as TextureNode`.
1411
+ */
1412
+ interface PassRecord {
1413
+ scenePass?: ScenePassNode
1414
+ [key: string]: three_webgpu.Node
1415
+ }
1336
1416
 
1337
- /** State passed to pipeline callbacks after the active pipeline has been created */
1417
+ /**
1418
+ * State passed to pipeline callbacks after the active pipeline has been created.
1419
+ *
1420
+ * `passes.scenePass` is required here: the hook installs the default scene pass before either
1421
+ * callback runs, so callbacks can use it without a guard or a cast.
1422
+ *
1423
+ * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
1424
+ * the legacy renderer before either callback can run, so a callback never sees WebGL.
1425
+ */
1338
1426
  type RenderPipelineCallbackState = RootState & {
1339
1427
  renderPipeline: ThreeRenderPipeline
1428
+ passes: PassRecord & { scenePass: ScenePassNode }
1429
+ renderer: three_webgpu.WebGPURenderer
1430
+ isLegacy: false
1340
1431
  }
1341
1432
 
1433
+ /**
1434
+ * What a callback may return to register entries into `state.passes`.
1435
+ *
1436
+ * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
1437
+ * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
1438
+ * store entry would leave the store pointing at a node the hook never disposes, and the hook
1439
+ * disposing a pass nothing references. So returning it is a type error.
1440
+ */
1441
+ type RegisteredPasses = Record<string, three_webgpu.Node> & { scenePass?: never }
1442
+
1342
1443
  /** Setup callback - runs first to configure MRT, create additional passes */
1343
- type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => PassRecord | void
1444
+ type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1344
1445
 
1345
1446
  /** Main callback - runs second to configure outputNode, create effect passes */
1346
- type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => PassRecord | void
1447
+ type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1347
1448
 
1348
- /** Return type for useRenderPipeline hook */
1349
- interface UseRenderPipelineReturn {
1449
+ /** The imperative half of useRenderPipeline's return value, present in every state */
1450
+ interface UseRenderPipelineActions {
1350
1451
  /** Current passes from state */
1351
1452
  passes: PassRecord
1352
- /** RenderPipeline instance (null if not initialized) */
1353
- renderPipeline: ThreeRenderPipeline | null
1354
1453
  /** Clear all passes from state */
1355
1454
  clearPasses: () => void
1356
1455
  /** Reset RenderPipeline entirely (clears PP + passes) */
1357
1456
  reset: () => void
1358
1457
  /** Re-run setup/main callbacks with current closure values */
1359
1458
  rebuild: () => void
1360
- /** True when RenderPipeline is configured and ready */
1361
- isReady: boolean
1362
1459
  }
1460
+
1461
+ /**
1462
+ * Return type for useRenderPipeline hook, discriminated on `isReady`.
1463
+ *
1464
+ * `if (isReady)` narrows `renderPipeline` to non-null, which is what the docs already tell
1465
+ * callers to check. `passes.scenePass` deliberately stays optional in the ready branch:
1466
+ * `clearPasses()` empties the record while leaving the pipeline in place.
1467
+ */
1468
+ type UseRenderPipelineReturn = UseRenderPipelineActions &
1469
+ (
1470
+ | {
1471
+ /** True when RenderPipeline is configured and ready */
1472
+ isReady: true
1473
+ /** RenderPipeline instance */
1474
+ renderPipeline: ThreeRenderPipeline
1475
+ }
1476
+ | {
1477
+ /** False until the pipeline has been created */
1478
+ isReady: false
1479
+ /** Not initialized yet, or torn down by reset() */
1480
+ renderPipeline: null
1481
+ }
1482
+ )
1363
1483
  }
1364
1484
 
1365
1485
  type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
@@ -3777,4 +3897,4 @@ declare function isOnce(value: unknown): value is {
3777
3897
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3778
3898
 
3779
3899
  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 };
3780
- 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 };
3900
+ 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, NodeLike, NodeProps, NodeRecord, NodeStore, 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 };