npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@unrealisticguy/r3drei

v9.56.6

Published

useful add-ons for react-three-fiber

Downloads

1

Readme

logo

Version Downloads Discord Shield

A growing collection of useful helpers and fully functional, ready-made abstractions for @react-three/fiber. If you make a component that is generic enough to be useful to others, think about making it available here through a PR!

npm install @react-three/drei

:point_right: this package is using the stand-alone three-stdlib instead of three/examples/jsm. :point_left:

Basic usage:

import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei'

React-native:

import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei/native'

The native route of the library does not export Html or Loader. The default export of the library is web which does export Html and Loader.

Index

Cameras

PerspectiveCamera

type Props = Omit<JSX.IntrinsicElements['perspectiveCamera'], 'children'> & {
  /** Registers the camera as the system default, fiber will start rendering with it */
  makeDefault?: boolean
  /** Making it manual will stop responsiveness and you have to calculate aspect ratio yourself. */
  manual?: boolean
  /** The contents will either follow the camera, or be hidden when filming if you pass a function */
  children?: React.ReactNode | ((texture: THREE.Texture) => React.ReactNode)
  /** Number of frames to render, 0 */
  frames?: number
  /** Resolution of the FBO, 256 */
  resolution?: number
  /** Optional environment map for functional use */
  envMap?: THREE.Texture
}

A responsive THREE.PerspectiveCamera that can set itself as the default.

<PerspectiveCamera makeDefault {...props} />
<mesh />

You can also give it children, which will now occupy the same position as the camera and follow along as it moves.

<PerspectiveCamera makeDefault {...props}>
  <mesh />
</PerspectiveCamera>

You can also drive it manually, it won't be responsive and you have to calculate aspect ratio yourself.

<PerspectiveCamera manual aspect={...} onUpdate={(c) => c.updateProjectionMatrix()}>

You can use the PerspectiveCamera to film contents into a RenderTarget, similar to CubeCamera. As a child you must provide a render-function which receives the texture as its first argument. The result of that function will not follow the camera, instead it will be set invisible while the the FBO renders so as to avoid issues where the meshes that receive the texture are interrering.

<PerspectiveCamera position={[0, 0, 10]}>
  {(texture) => (
    <mesh geometry={plane}>
      <meshBasicMaterial map={texture} />
    </mesh>
  )}
</PerspectiveCamera>

OrthographicCamera

A responsive THREE.OrthographicCamera that can set itself as the default.

<OrthographicCamera makeDefault {...props}>
  <mesh />
</OrthographicCamera>

You can use the OrthographicCamera to film contents into a RenderTarget, it has the same API as OrthographicCamera.

<OrthographicCamera position={[0, 0, 10]}>
  {(texture) => (
    <mesh geometry={plane}>
      <meshBasicMaterial map={texture} />
    </mesh>
  )}
</OrthographicCamera>

CubeCamera

A THREE.CubeCamera that returns its texture as a render-prop. It makes children invisible while rendering to the internal buffer so that they are not included in the reflection.

type Props = JSX.IntrinsicElements['group'] & {
  /** Number of frames to render, Infinity */
  frames?: number
  /** Resolution of the FBO, 256 */
  resolution?: number
  /** Camera near, 0.1 */
  near?: number
  /** Camera far, 1000 */
  far?: number
  /** Custom environment map that is temporarily set as the scenes background */
  envMap?: THREE.Texture
  /** Custom fog that is temporarily set as the scenes fog */
  fog?: Fog | FogExp2
  /** The contents of CubeCamera will be hidden when filming the cube */
  children: (tex: Texture) => React.ReactNode
}

Using the frames prop you can control if this camera renders indefinitively or statically (a given number of times). If you have two static objects in the scene, make it frames={2} for instance, so that both objects get to "see" one another in the reflections, which takes multiple renders. If you have moving objects, unset the prop and use a smaller resolution instead.

<CubeCamera>
  {(texture) => (
    <mesh>
      <sphereGeometry />
      <meshStandardMaterial envMap={texture} />
    </mesh>
  )}
</CubeCamera>

Controls

If available controls have damping enabled by default, they manage their own updates, remove themselves on unmount, are compatible with the frameloop="demand" canvas-flag. They inherit all props from their underlying THREE controls. They are the first effects to run before all other useFrames, to ensure that other components may mutate the camera on top of them.

Some controls allow you to set makeDefault, similar to, for instance, PerspectiveCamera. This will set @react-three/fiber's controls field in the root store. This can make it easier in situations where you want controls to be known and other parts of the app could respond to it. Some drei controls already take it into account, like CameraShake, Gizmo and TransformControls.

Drei currently exports OrbitControls , MapControls , TrackballControls, ArcballControls, FlyControls, DeviceOrientationControls, PointerLockControls , FirstPersonControls and CameraControls

All controls react to the default camera. If you have a <PerspectiveCamera makeDefault /> in your scene, they will control it. If you need to inject an imperative camera or one that isn't the default, use the camera prop: <OrbitControls camera={MyCamera} />.

PointerLockControls additionally supports a selector prop, which enables the binding of click event handlers for control activation to other elements than document (e.g. a 'Click here to play' button). All elements matching the selector prop will activate the controls. It will also center raycast events by default, so regular onPointerOver/etc events on meshes will continue to work.

CameraControls

This is an implementation of the camera-controls library.

<CameraControls />
type CameraControlsProps = {
  /** The camera to control, default to the state's `camera` */
  camera?: PerspectiveCamera | OrthographicCamera
  /** DOM element to connect to, default to the state's `gl` renderer */
  domElement?: HTMLElement
}

ScrollControls

type ScrollControlsProps = {
  /** Precision, default 0.00001 */
  eps?: number
  /** Horontal scroll, default false (vertical) */
  horizontal?: boolean
  /** Infinite scroll, default false (experimental!) */
  infinite?: boolean
  /** Defines the lenght of the scroll area, each page is height:100%, default 1 */
  pages?: number
  /** A factor that increases scroll bar travel, default 1 */
  distance?: number
  /** Friction in seconds, default: 0.2 (1/5 second) */
  damping?: number
  /** maxSpeed optionally allows you to clamp the maximum speed. If damping is 0.2s and looks OK
   *  going between, say, page 1 and 2, but not for pages far apart as it'll move very rapid,
   *  then a maxSpeed of e.g. 0.1 which will clamp the speed to 0.1 units per second, it may now
   *  take much longer than damping to reach the target if it is far away. Default: Infinity */
  maxSpeed?: number
  enabled?: boolean
  style?: React.CSSProperties
  children: React.ReactNode
}

Scroll controls create a HTML scroll container in front of the canvas. Everything you drop into the <Scroll> component will be affected.

You can listen and react to scroll with the useScroll hook which gives you useful data like the current scroll offset, delta and functions for range finding: range, curve and visible. The latter functions are especially useful if you want to react to the scroll offset, for instance if you wanted to fade things in and out if they are in or out of view.

;<ScrollControls pages={3} damping={0.1}>
  {/* Canvas contents in here will *not* scroll, but receive useScroll! */}
  <SomeModel />
  <Scroll>
    {/* Canvas contents in here will scroll along */}
    <Foo position={[0, 0, 0]} />
    <Foo position={[0, viewport.height, 0]} />
    <Foo position={[0, viewport.height * 1, 0]} />
  </Scroll>
  <Scroll html>
    {/* DOM contents in here will scroll along */}
    <h1>html in here (optional)</h1>
    <h1 style={{ top: '100vh' }}>second page</h1>
    <h1 style={{ top: '200vh' }}>third page</h1>
  </Scroll>
</ScrollControls>

function Foo(props) {
  const ref = useRef()
  const data = useScroll()
  useFrame(() => {
    // data.offset = current scroll position, between 0 and 1, dampened
    // data.delta = current delta, between 0 and 1, dampened

    // Will be 0 when the scrollbar is at the starting position,
    // then increase to 1 until 1 / 3 of the scroll distance is reached
    const a = data.range(0, 1 / 3)
    // Will start increasing when 1 / 3 of the scroll distance is reached,
    // and reach 1 when it reaches 2 / 3rds.
    const b = data.range(1 / 3, 1 / 3)
    // Same as above but with a margin of 0.1 on both ends
    const c = data.range(1 / 3, 1 / 3, 0.1)
    // Will move between 0-1-0 for the selected range
    const d = data.curve(1 / 3, 1 / 3)
    // Same as above, but with a margin of 0.1 on both ends
    const e = data.curve(1 / 3, 1 / 3, 0.1)
    // Returns true if the offset is in range and false if it isn't
    const f = data.visible(2 / 3, 1 / 3)
    // The visible function can also receive a margin
    const g = data.visible(2 / 3, 1 / 3, 0.1)
  })
  return <mesh ref={ref} {...props} />
}

PresentationControls

Semi-OrbitControls with spring-physics, polar zoom and snap-back, for presentational purposes. These controls do not turn the camera but will spin their contents. They will not suddenly come to rest when they reach limits like OrbitControls do, but rather smoothly anticipate stopping position.

<PresentationControls
  enabled={true} // the controls can be disabled by setting this to false
  global={false} // Spin globally or by dragging the model
  cursor={true} // Whether to toggle cursor style on drag
  snap={false} // Snap-back to center (can also be a spring config)
  speed={1} // Speed factor
  zoom={1} // Zoom factor when half the polar-max is reached
  rotation={[0, 0, 0]} // Default rotation
  polar={[0, Math.PI / 2]} // Vertical limits
  azimuth={[-Infinity, Infinity]} // Horizontal limits
  config={{ mass: 1, tension: 170, friction: 26 }} // Spring config
>
  <mesh />
</PresentationControls>

KeyboardControls

A rudimentary keyboard controller which distributes your defined data-model to the useKeyboard hook. It's a rather simple way to get started with keyboard input.

type KeyboardControlsState<T extends string = string> = { [K in T]: boolean }

type KeyboardControlsEntry<T extends string = string> = {
  /** Name of the action */
  name: T
  /** The keys that define it, you can use either event.key, or event.code */
  keys: string[]
  /** If the event receives the keyup event, true by default */
  up?: boolean
}

type KeyboardControlsProps = {
  /** A map of named keys */
  map: KeyboardControlsEntry[]
  /** All children will be able to useKeyboardControls */
  children: React.ReactNode
  /** Optional onchange event */
  onChange: (name: string, pressed: boolean, state: KeyboardControlsState) => void
  /** Optional event source */
  domElement?: HTMLElement
}

You start by wrapping your app, or scene, into <KeyboardControls>.

enum Controls {
  forward = 'forward',
  back = 'back',
  left = 'left',
  right = 'right',
  jump = 'jump',
}
function App() {
  const map = useMemo<KeyboardControlsEntry<Controls>[]>(()=>[
    { name: Controls.forward, keys: ['ArrowUp', 'w', 'W'] },
    { name: Controls.back, keys: ['ArrowDown', 's', 'S'] },
    { name: Controls.left, keys: ['ArrowLeft', 'a', 'A'] },
    { name: Controls.right, keys: ['ArrowRight', 'd', 'D'] },
    { name: Controls.jump, keys: ['Space'] },
  ], [])
  return (
    <KeyboardControls map={map}>
      <App />
    </KeyboardControls>

You can either respond to input reactively, it uses zustand (with the subscribeWithSelector middleware) so all the rules apply:

function Foo() {
  const forwardPressed = useKeyboardControls<Controls>(state => state.forward)

Or transiently, either by subscribe, which is a function which returns a function to unsubscribe, so you can pair it with useEffect for cleanup, or get, which fetches fresh state non-reactively.

function Foo() {
  const [sub, get] = useKeyboardControls<Controls>()

  useEffect(() => {
    return sub(
      (state) => state.forward,
      (pressed) => {
        console.log('forward', pressed)
      }
    )
  }, [])

  useFrame(() => {
    // Fetch fresh data from store
    const pressed = get().back
  })
}

Gizmos

GizmoHelper

Used by widgets that visualize and control camera position.

Two example gizmos are included: GizmoViewport and GizmoViewcube, and useGizmoContext makes it easy to create your own.

Make sure to set the makeDefault prop on your controls, in that case you do not have to define the onTarget and onUpdate props.

<GizmoHelper
  alignment="bottom-right" // widget alignment within scene
  margin={[80, 80]} // widget margins (X, Y)
  onUpdate={/* called during camera animation  */}
  onTarget={/* return current camera target (e.g. from orbit controls) to center animation */}
  renderPriority={/* use renderPriority to prevent the helper from disappearing if there is another useFrame(..., 1)*/}
>
  <GizmoViewport axisColors={['red', 'green', 'blue']} labelColor="black" />
  {/* alternative: <GizmoViewcube /> */}
</GizmoHelper>

PivotControls

Controls for rotating and translating objects. These controls will stick to the object the transform and by offsetting or anchoring it forms a pivot. This control has HTML annotations for some transforms and supports [tab] for rounded values while dragging.

type PivotControlsProps = {
  /** Scale of the gizmo, 1 */
  scale?: number
  /** Width of the gizmo lines, this is a THREE.Line2 prop, 2.5 */
  lineWidth?: number
  /** If fixed is true is remains constant in size, scale is now in pixels, false */
  fixed?: boolean
  /** Pivot does not act as a group, it won't shift contents but can offset in position */
  offset?: [number, number, number]
  /** Starting rotation */
  rotation?: [number, number, number]
  /** Starting matrix */
  matrix?: THREE.Matrix4
  /** Anchor point, like BBAnchor, each axis can be between -1/0/+1 */
  anchor?: [number, number, number]
  /** If autoTransform is true, automatically apply the local transform on drag, true */
  autoTransform?: boolean
  /** Allows you to switch individual axes off */
  activeAxes?: [boolean, boolean, boolean]
  /** RGB colors */
  axisColors?: [string | number, string | number, string | number]
  /** Color of the hovered item */
  hoveredColor?: string | number
  /** HTML value annotations, default: false */
  annotations?: boolean
  /** CSS Classname applied to the HTML annotations */
  annotationsClass?: string
  /** Drag start event */
  onDragStart?: () => void
  /** Drag event */
  onDrag?: (l: THREE.Matrix4, deltaL: THREE.Matrix4, w: THREE.Matrix4, deltaW: THREE.Matrix4) => void
  /** Drag end event */
  onDragEnd?: () => void
  /** Set this to false if you want the gizmo to be visible through faces */
  depthTest?: boolean
  opacity?: number
  visible?: boolean
  userData?: { [key: string]: any }
  children?: React.ReactNode
}
<PivotControls>
  <mesh />
</PivotControls>

You can use Pivot as a controlled component, switch autoTransform off in that case and now you are responsible for applying the matrix transform yourself. You can also leave autoTransform on and apply the matrix to foreign objects, in that case Pivot will be able to control objects that are not parented within.

const matrix = new THREE.Matrix4()
return (
  <PivotControls
    ref={ref}
    matrix={matrix}
    autoTransform={false}
    onDrag={({ matrix: matrix_ }) => matrix.copy(matrix_)}

TransformControls

An abstraction around THREE.TransformControls.

You can wrap objects which then receive a transform gizmo.

<TransformControls mode="translate">
  <mesh />
</TransformControls>

You could also reference the object which might make it easier to exchange the target. Now the object does not have to be part of the same sub-graph. References can be plain objects or React.MutableRefObjects.

<TransformControls object={mesh} mode="translate" />
<mesh ref={mesh} />

If you are using other controls (Orbit, Trackball, etc), you will notice how they interfere, dragging one will affect the other. Default-controls will temporarily be disabled automatically when the user is pulling on the transform gizmo.

<TransformControls mode="translate" />
<OrbitControls makeDefault />

Grid

A y-up oriented, shader-based grid implementation.

export type GridMaterialType = {
  /** Cell size, default: 0.5 */
  cellSize?: number
  /** Cell thickness, default: 0.5 */
  cellThickness?: number
  /** Cell color, default: black */
  cellColor?: THREE.ColorRepresentation
  /** Section size, default: 1 */
  sectionSize?: number
  /** Section thickness, default: 1 */
  sectionThickness?: number
  /** Section color, default: #2080ff */
  sectionColor?: THREE.ColorRepresentation
  /** Follow camera, default: false */
  followCamera?: boolean
  /** Display the grid infinitely, default: false */
  infiniteGrid?: boolean
  /** Fade distance, default: 100 */
  fadeDistance?: number
  /** Fade strength, default: 1 */
  fadeStrength?: number
}

export type GridProps = GridMaterialType & {
  /** Default plane-geometry arguments */
  args?: ConstructorParameters<typeof THREE.PlaneGeometry>
}
<Grid />

useHelper

A hook for a quick way to add helpers to existing nodes in the scene. It handles removal of the helper on unmount and auto-updates it by default.

const mesh = useRef()
useHelper(mesh, BoxHelper, 'cyan')
useHelper(condition && mesh, BoxHelper, 'red') // you can passe false instead of the object ref to hide the helper

<mesh ref={mesh} ... />

Shapes

Plane, Box, Sphere, Circle, Cone, Cylinder, Tube, Torus, TorusKnot, Ring, Tetrahedron, Polyhedron, Icosahedron, Octahedron, Dodecahedron, Extrude, Lathe

Short-cuts for a mesh with a buffer geometry.

<Box
  args={[1, 1, 1]}                // Args for the buffer geometry
  {...meshProps}                  // All THREE.Mesh props are valid
/>

// Plane with buffer geometry args
<Plane args={[2, 2]} />

// Box with color set on the default MeshBasicMaterial
<Box material-color="hotpink" />

// Sphere with a MeshStandardMaterial
<Sphere>
  <meshStandardMaterial color="hotpink" />
</Sphere>

RoundedBox

A box buffer geometry with rounded corners, done with extrusion.

<RoundedBox
  args={[1, 1, 1]} // Width, height, depth. Default is [1, 1, 1]
  radius={0.05} // Radius of the rounded corners. Default is 0.05
  smoothness={4} // The number of curve segments. Default is 4
  {...meshProps} // All THREE.Mesh props are valid
>
  <meshPhongMaterial color="#f3f3f3" wireframe />
</RoundedBox>

ScreenQuad

<ScreenQuad>
  <myMaterial />
</ScreenQuad>

A triangle that fills the screen, ideal for full-screen fragment shader work (raymarching, postprocessing). 👉 Why a triangle? 👉 Use as a post processing mesh

Line

Renders a THREE.Line2 or THREE.LineSegments2 (depending on the value of segments).

<Line
  points={[[0, 0, 0], ...]}       // Array of points, Array<Vector3 | Vector2 | [number, number, number] | [number, number] | number>
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  segments                        // If true, renders a THREE.LineSegments2. Otherwise, renders a THREE.Line2
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

QuadraticBezierLine

Renders a THREE.Line2 using THREE.QuadraticBezierCurve3 for interpolation.

<QuadraticBezierLine
  start={[0, 0, 0]}               // Starting point, can be an array or a vec3
  end={[10, 0, 10]}               // Ending point, can be an array or a vec3
  mid={[5, 0, 5]}                 // Optional control point, can be an array or a vec3
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

You can also update the line runtime.

const ref = useRef()
useFrame((state) => {
  ref.current.setPoints(
    [0, 0, 0],
    [10, 0, 0],
    // [5, 0, 0] // Optional: mid-point
  )
}, [])
return <QuadraticBezierLine ref={ref} />
}

CubicBezierLine

Renders a THREE.Line2 using THREE.CubicBezierCurve3 for interpolation.

<CubicBezierLine
  start={[0, 0, 0]}               // Starting point
  end={[10, 0, 10]}               // Ending point
  midA={[5, 0, 0]}                // First control point
  midB={[0, 0, 5]}                // Second control point
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

CatmullRomLine

Renders a THREE.Line2 using THREE.CatmullRomCurve3 for interpolation.

<CatmullRomLine
  points={[[0, 0, 0], ...]}       // Array of Points
  closed={false}                  // Default
  curveType="centripetal"         // One of "centripetal" (default), "chordal", or "catmullrom"
  tension={0.5}                   // Default (only applies to "catmullrom" curveType)
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

Abstractions

Image

A shader-based image component with auto-cover (similar to css/background: cover).

function Foo() {
  const ref = useRef()
  useFrame(() => {
    ref.current.material.zoom = ... // 1 and higher
    ref.current.material.grayscale = ... // between 0 and 1
    ref.current.material.color.set(...) // mix-in color
  })
  return <Image ref={ref} url="/file.jpg" />
}

To make the material transparent:

<Image url="/file.jpg" transparent opacity={0.5} />

Text

Hi-quality text rendering w/ signed distance fields (SDF) and antialiasing, using troika-3d-text. All of troikas props are valid! Text is suspense-based!

<Text color="black" anchorX="center" anchorY="middle">
  hello world!
</Text>

Text will suspend while loading the font data, but in order to completely avoid FOUC you can pass the characters it needs to render.

<Text font={fontUrl} characters="abcdefghijklmnopqrstuvwxyz0123456789!">
  hello world!
</Text>

Text3D

Render 3D text using ThreeJS's TextGeometry.

Text3D will suspend while loading the font data. Text3D requires fonts in JSON format generated through (typeface.json)[http://gero3.github.io/facetype.js], either as a path to a JSON file or a JSON object. If you face display issues try checking "Reverse font direction" in the typeface tool.

<Text3D font={fontUrl} {...textOptions}>
  Hello world!
  <meshNormalMaterial />
</Text3D>

You can use any material. textOptions are options you'd pass to the TextGeometry constructor. Find more information about available options here.

You can align the text using the <Center> component.

<Center top left>
  <Text3D>hello</Text3D>
</Center>

It adds two properties that do not exist in the original TextGeometry, lineHeight and letterSpacing. The former a factor that is 1 by default, the latter is in threejs units and 0 by default.

<Text3D lineHeight={0.5} letterSpacing={-0.025}>{`hello\nworld`}</Text3D>

Effects

Abstraction around threes own EffectComposer. By default it will prepend a render-pass and a gammacorrection-pass. Children are cloned, attach is given to them automatically. You can only use passes or effects in there.

By default it creates a render target with HalfFloatType, RGBAFormat and gl.outputEncoding. You can change all of this to your liking, inspect the types.

import { SSAOPass } from "three-stdlib"

extend({ SSAOPass })

<Effects multisamping={8} renderIndex={1} disableGamma={false} disableRenderPass={false} disableRender={false}>
  <sSAOPass args={[scene, camera, 100, 100]} kernelRadius={1.2} kernelSize={0} />
</Effects>

PositionalAudio

A wrapper around THREE.PositionalAudio. Add this to groups or meshes to tie them to a sound that plays when the camera comes near.

<PositionalAudio
  url="/sound.mp3"
  distance={1}
  loop
  {...props} // All THREE.PositionalAudio props are valid
/>

Billboard

Adds a <group /> that always faces the camera.

<Billboard
  follow={true}
  lockX={false}
  lockY={false}
  lockZ={false} // Lock the rotation on the z axis (default=false)
>
  <Text fontSize={1}>I'm a billboard</Text>
</Billboard>

ScreenSpace

Adds a <group /> that aligns objects to screen space.

<ScreenSpace
  depth={1} // Distance from camera
>
  <Box>I'm in screen space</Box>
</ScreenSpace>

GradientTexture

A declarative THREE.Texture which attaches to "map" by default. You can use this to create gradient backgrounds.

<mesh>
  <planeGeometry />
  <meshBasicMaterial>
    <GradientTexture
      stops={[0, 1]} // As many stops as you want
      colors={['aquamarine', 'hotpink']} // Colors need to match the number of stops
      size={1024} // Size is optional, default = 1024
    />
  </meshBasicMaterial>
</mesh>

Edges

Abstracts THREE.EdgesGeometry. It pulls the geometry automatically from its parent, optionally you can ungroup it and give it a geometry prop. You can give it children, for instance a custom material.

<mesh>
  <boxGeometry />
  <meshBasicMaterial />
  <Edges
    scale={1.1}
    threshold={15} // Display edges only when the angle between two faces exceeds this value (default=15 degrees)
    color="white"
  />
</mesh>

Trail

A declarative, three.MeshLine based Trails implementation. You can attach it to any mesh and it will give it a beautiful trail.

Props defined below with their default values.

<Trail
  width={0.2} // Width of the line
  color={'hotpink'} // Color of the line
  length={1} // Length of the line
  decay={1} // How fast the line fades away
  local={false} // Wether to use the target's world or local positions
  stride={0} // Min distance between previous and current point
  interval={1} // Number of frames to wait before next calculation
  target={undefined} // Optional target. This object will produce the trail.
  attenuation={(width) => width} // A function to define the width in each point along it.
>
  {/* If `target` is not defined, Trail will use the first `Object3D` child as the target. */}
  <mesh>
    <sphereGeometry />
    <meshBasicMaterial />
  </mesh>

  {/* You can optionally define a custom meshLineMaterial to use. */}
  {/* <meshLineMaterial color={"red"} /> */}
</Trail>

👉 Inspired by TheSpite's Codevember 2021 #9

Sampler

Declarative abstraction around MeshSurfaceSampler & InstancedMesh. It samples points from the passed mesh and transforms an InstancedMesh's matrix to distribute instances on the points.

Check the demos & code for more.

You can either pass a Mesh and InstancedMesh as children:

// This simple example scatters 1000 spheres on the surface of the sphere mesh.
<Sampler
  weight={'normal'} // the name of the attribute to be used as sampling weight
  transform={transformPoint} // a function that transforms each instance given a sample. See the examples for more.
  count={16} // Number of samples
>
  <mesh>
    <sphereGeometry args={[2]} />
  </mesh>

  <instancedMesh args={[null, null, 1_000]}>
    <sphereGeometry args={[0.1]} />
  </instancedMesh>
</Sampler>

or use refs when you can't compose declaratively:

const { nodes } = useGLTF('my/mesh/url')
const mesh = useRef(nodes)
const instances = useRef()

return <>
  <instancedMesh args={[null, null, 1_000]}>
    <sphereGeometry args={[0.1]}>
  </instancedMesh>

  <Sampler mesh={mesh} instances={instances}>
</>

ComputedAttribute

Create and attach an attribute declaratively.

<sphereGeometry>
  <ComputedAttribute
    // attribute will be added to the geometry with this name
    name="my-attribute-name"
    compute={(geometry) => {
      // ...someLogic;
      return new THREE.BufferAttribute([1, 2, 3], 1)
    }}
    // you can pass any BufferAttribute prop to this component, eg.
    usage={THREE.StaticReadUsage}
  />
</sphereGeometry>

Clone

Declarative abstraction around THREE.Object3D.clone. This is useful when you want to create a shallow copy of an existing fragment (and Object3D, Groups, etc) into your scene, for instance a group from a loaded GLTF. This clone is now re-usable, but it will still refer to the original geometries and materials.

<Clone
  /** Any pre-existing THREE.Object3D (groups, meshes, ...), or an array of objects */
  object: THREE.Object3D | THREE.Object3D[]
  /** Children will be placed within the object, or within the group that holds arrayed objects */
  children?: React.ReactNode
  /** Can clone materials and/or geometries deeply (default: false) */
  deep?: boolean | 'materialsOnly' | 'geometriesOnly'
  /** The property keys it will shallow-clone (material, geometry, visible, ...) */
  keys?: string[]
  /** Can either spread over props or fill in JSX children, applies to every mesh within */
  inject?: MeshProps | React.ReactNode | ((object: THREE.Object3D) => React.ReactNode)
  /** Short access castShadow, applied to every mesh within */
  castShadow?: boolean
  /** Short access receiveShadow, applied to every mesh within */
  receiveShadow?: boolean
/>

You create a shallow clone by passing a pre-existing object to the object prop.

const { nodes } = useGLTF(url)
return (
  <Clone object={nodes.table} />

Or, multiple objects:

<Clone object={[nodes.foo, nodes.bar]} />

You can dynamically insert objects, these will apply to anything that isn't a group or a plain object3d (meshes, lines, etc):

<Clone object={nodes.table} inject={<meshStandardMaterial color="green" />} />

Or make inserts conditional:

<Clone object={nodes.table} inject={
  {(object) => (object.name === 'table' ? <meshStandardMaterial color="green" /> : null)}
} />

useAnimations

A hook that abstracts AnimationMixer.

const { nodes, materials, animations } = useGLTF(url)
const { ref, mixer, names, actions, clips } = useAnimations(animations)
useEffect(() => {
  actions?.jump.play()
})
return (
  <mesh ref={ref} />

The hook can also take a pre-existing root (which can be a plain object3d or a reference to one):

const { scene, animations } = useGLTF(url)
const { actions } = useAnimations(animations, scene)
return <primitive object={scene} />

MarchingCubes

An abstraction for threes MarchingCubes

<MarchingCubes resolution={50} maxPolyCount={20000} enableUvs={false} enableColors={true}>
  <MarchingCube strength={0.5} subtract={12} color={new Color('#f0f')} position={[0.5, 0.5, 0.5]} />

  <MarchingPlane planeType="y" strength={0.5} subtract={12} />
</MarchingCubes>

Decal

Abstraction around Three's DecalGeometry. It will use the its parent mesh as the decal surface by default.

The decal box has to intersect the surface, otherwise it will not be visible. if you do not specifiy a rotation it will look at the parents center point. You can also pass a single number as the rotation which allows you to spin it.

<mesh>
  <sphereGeometry />
  <meshBasicMaterial />
  <Decal
    debug // Makes "bounding box" of the decal visible
    position={[0, 0, 0]} // Position of the decal
    rotation={[0, 0, 0]} // Rotation of the decal (can be a vector or a degree in radians)
    scale={1} // Scale of the decal
  >
    <meshBasicMaterial map={texture} />
  </Decal>
</mesh>

If you do not specifiy a material it will create a transparent meshStandardMaterial with a polygonOffsetFactor of -10 and all rest-props will be spread over it.

<mesh>
  <sphereGeometry />
  <meshBasicMaterial />
  <Decal map={texture} roughness={0.5} />
</mesh>

If declarative composition is not possible, use the mesh prop to define the surface the decal must attach to.

<Decal mesh={ref}>
  <meshBasicMaterial map={texture} />
</Decal>

Svg

Wrapper around the three svg loader demo.

Accepts an SVG url or svg raw data.

<Svg src={urlOrRawSvgString} />

Gltf

This is a convenience component that will load a gltf file and clone the scene using drei/Clone. That means you can re-use and mount the same gltf file multiple times. It accepts all props that Clone does, including shortcuts (castShadow, receiveShadow) and material overrides.

<Gltf src="/model.glb" receiveShadow castShadow />

AsciiRenderer

Abstraction of three's AsciiEffect. It creates a DOM layer on top of the canvas and renders the scene as ascii characters.

type AsciiRendererProps = {
  /** Render index, default: 1 */
  renderIndex?: number
  /** CSS background color (can be "transparent"), default: black */
  bgColor?: string
  /** CSS character color, default: white */
  fgColor?: string
  /** Characters, default: ' .:-+*=%@#' */
  characters?: string
  /** Invert character, default: true */
  invert?: boolean
  /** Colorize output (very expensive!), default: false */
  color?: boolean
  /** Level of detail, default: 0.15 */
  resolution?: number
}
<Canvas>
  <AsciiRenderer />

Shaders

MeshReflectorMaterial

Easily add reflections and/or blur to any mesh. It takes surface roughness into account for a more realistic effect. This material extends from THREE.MeshStandardMaterial and accepts all its props.

<mesh>
  <planeGeometry />
  <MeshReflectorMaterial
    blur={[0, 0]} // Blur ground reflections (width, heigt), 0 skips blur
    mixBlur={0} // How much blur mixes with surface roughness (default = 1)
    mixStrength={1} // Strength of the reflections
    mixContrast={1} // Contrast of the reflections
    resolution={256} // Off-buffer resolution, lower=faster, higher=better quality, slower
    mirror={0} // Mirror environment, 0 = texture colors, 1 = pick up env colors
    depthScale={0} // Scale the depth factor (0 = no depth, default = 0)
    minDepthThreshold={0.9} // Lower edge for the depthTexture interpolation (default = 0)
    maxDepthThreshold={1} // Upper edge for the depthTexture interpolation (default = 0)
    depthToBlurRatioBias={0.25} // Adds a bias factor to the depthTexture before calculating the blur amount [blurFactor = blurTexture * (depthTexture + bias)]. It accepts values between 0 and 1, default is 0.25. An amount > 0 of bias makes sure that the blurTexture is not too sharp because of the multiplication with the depthTexture
    distortion={1} // Amount of distortion based on the distortionMap texture
    distortionMap={distortionTexture} // The red channel of this texture is used as the distortion map. Default is null
    debug={0} /* Depending on the assigned value, one of the following channels is shown:
      0 = no debug
      1 = depth channel
      2 = base channel
      3 = distortion channel
      4 = lod channel (based on the roughness)
    */
   reflectorOffset={0.2} // Offsets the virtual camera that projects the reflection. Useful when the reflective surface is some distance from the object's origin (default = 0)
  >
</mesh>

MeshWobbleMaterial

This material makes your geometry wobble and wave around. It was taken from the threejs-examples and adapted into a self-contained material.

<mesh>
  <boxGeometry />
  <MeshWobbleMaterial factor={1} speed={10} />
</mesh>

MeshDistortMaterial

This material makes your geometry distort following simplex noise.

<mesh>
  <boxGeometry />
  <MeshDistortMaterial distort={1} speed={10} />
</mesh>

MeshRefractionMaterial

A convincing Glass/Diamond refraction material.

type MeshRefractionMaterialProps = JSX.IntrinsicElements['shaderMaterial'] & {
  /** Environment map */
  envMap: THREE.CubeTexture | THREE.Texture
  /** Number of ray-cast bounces, it can be expensive to have too many, 2 */
  bounces?: number
  /** Refraction index, 2.4 */
  ior?: number
  /** Fresnel (strip light), 0 */
  fresnel?: number
  /** RGB shift intensity, can be expensive, 0 */
  aberrationStrength?: number
  /** Color, white */
  color?: ReactThreeFiber.Color
  /** If this is on it uses fewer ray casts for the RGB shift sacrificing physical accuracy, true */
  fastChroma?: boolean
}

If you want it to reflect other objects in the scene you best pair it with a cube-camera.

<CubeCamera>
  {(texture) => (
    <mesh geometry={diamondGeometry} {...props}>
      <MeshRefractionMaterial envMap={texture} />
    </mesh>
  )}
</CubeCamera>

Otherwise just pass it an environment map.

const texture = useLoader(RGBELoader, "/textures/royal_esplanade_1k.hdr")
return (
  <mesh geometry={diamondGeometry} {...props}>
    <MeshRefractionMaterial envMap={texture} />

MeshTransmissionMaterial

An improved THREE.MeshPhysicalMaterial. It acts like a normal PhysicalMaterial in terms of transmission support, thickness, ior, roughness, etc., but has chromatic aberration, noise-based roughness blur, (primitive) anisotropy support, and unlike the original it can "see" other transmissive or transparent objects which leads to improved visuals.

Although it should be faster than MPM keep in mind that it can still be expensive as it causes an additional render pass of the scene. Low samples and low resolution will make it faster. If you use roughness consider using a tiny resolution, for instance 32x32 pixels, it will still look good but perform much faster.

For performance and visual reasons the host mesh gets removed from the render-stack temporarily. If you have other objects that you don't want to see reflected in the material just add them to the parent mesh as children.

type MeshTransmissionMaterialProps = JSX.IntrinsicElements['meshPhysicalMaterial'] & {
  /* Transmission, default: 1 */
  transmission?: number
  /* Thickness (refraction), default: 0 */
  thickness?: number
  /** Backside thickness (when backside is true), default: 0 */
  backsideThickness?: number
  /* Roughness (blur), default: 0 */
  roughness?: number
  /* Chromatic aberration, default: 0.03 */
  chromaticAberration?: number
  /* Anisotropy, default: 0.1 */
  anisotropy?: number
  /* Distortion, default: 0 */
  distortion?: number
  /* Distortion scale, default: 0.5 */
  distortionScale: number
  /* Temporal distortion (speed of movement), default: 0.0 */
  temporalDistortion: number
  /** The scene rendered into a texture (use it to share a texture between materials), default: null  */
  buffer?: THREE.Texture
  /** transmissionSampler, you can use the threejs transmission sampler texture that is
   *  generated once for all transmissive materials. The upside is that it can be faster if you
   *  use multiple MeshPhysical and Transmission materials, the downside is that transmissive materials
   *  using this can't see other transparent or transmissive objects nor do you have control over the
   *  buffer and its resolution, default: false */
  transmissionSampler?: boolean
  /** Render the backside of the material (more cost, better results), default: false */
  backside?: boolean
  /** Resolution of the local buffer, default: undefined (fullscreen) */
  resolution?: number
  /** Resolution of the local buffer for backfaces, default: undefined (fullscreen) */
  backsideResolution?: number
  /** Refraction samples, default: 6 */
  samples?: number
  /** Buffer scene background (can be a texture, a cubetexture or a color), default: null */
  background?: THREE.Texture
}
return (
  <mesh geometry={geometry} {...props}>
    <MeshTransmissionMaterial />

If each material rendering the scene on its own is too much expensense you can share a buffer texture. Either by enabling transmissionSampler which would use the threejs-internal buffer that MeshPhysicalMaterials use. This might be faster, the downside is that no transmissive material can "see" other transparent or transmissive objects.

<mesh geometry={torus}>
  <MeshTransmissionMaterial transmissionSampler />
</mesh>
<mesh geometry={sphere}>
  <MeshTransmissionMaterial transmissionSampler />
</mesh>

Or, by passing a texture to buffer manually, for instance using useFBO.

const buffer = useFBO()
useFrame((state) => {
  state.gl.setRenderTarget(buffer)
  state.gl.render(state.scene, state.camera)
  state.gl.setRenderTarget(null)
})
return (
  <>
    <mesh geometry={torus}>
      <MeshTransmissionMaterial buffer={buffer.texture} />
    </mesh>
    <mesh geometry={sphere}>
      <MeshTransmissionMaterial buffer={buffer.texture} />
    </mesh>

Or a PerspectiveCamera.

<PerspectiveCamera makeDefault fov={75} position={[10, 0, 15]} resolution={1024}>
  {(texture) => (
    <>
      <mesh geometry={torus}>
        <MeshTransmissionMaterial buffer={texture} />
      </mesh>
      <mesh geometry={sphere}>
        <MeshTransmissionMaterial buffer={texture} />
      </mesh>
    </>
  )}

This would mimic the default MeshPhysicalMaterial behaviour, these materials won't "see" one another, but at least they would pick up on everything else, including transmissive or transparent objects.

PointMaterial

Antialiased round dots. It takes the same props as regular THREE.PointsMaterial on which it is based.

<points>
  <PointMaterial transparent vertexColors size={15} sizeAttenuation={false} depthWrite={false} />
</points>

SoftShadows

Injects percent closer soft shadows (pcss) into threes shader chunk. Mounting and unmounting this component will lead to all shaders being be re-compiled, although it will only cause overhead if SoftShadows is mounted after the scene has already rendered, if it mounts with everything else in your scene shaders will compile naturally.

<SoftShadows frustum={3.75} size={0.005} near={9.5} samples={17} rings={11} />

shaderMaterial

Creates a THREE.ShaderMaterial for you with easier handling of uniforms, which are automatically declared as setter/getters on the object and allowed as constructor arguments.

import { extend } from '@react-three/fiber'

const ColorShiftMaterial = shaderMaterial(
  { time: 0, color: new THREE.Color(0.2, 0.0, 0.1) },
  // vertex shader
  /*glsl*/`
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  // fragment shader
  /*glsl*/`
    uniform float time;
    uniform vec3 color;
    varying vec2 vUv;
    void main() {
      gl_FragColor.rgba = vec4(0.5 + 0.3 * sin(vUv.yxx +