Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
@react-three/drei
Advanced tools
@react-three/drei is a collection of useful helpers and abstractions for react-three-fiber, which is a React renderer for three.js. It provides a wide range of components and utilities to simplify the creation of 3D scenes in React applications.
Camera Controls
The OrbitControls component allows you to easily add camera controls to your 3D scene, enabling users to rotate, zoom, and pan the camera.
import { OrbitControls } from '@react-three/drei';
function Scene() {
return (
<Canvas>
<OrbitControls />
{/* other components */}
</Canvas>
);
}
Environment
The Environment component allows you to quickly set up a realistic lighting environment using HDRI images. You can choose from various presets like 'sunset', 'dawn', 'night', etc.
import { Environment } from '@react-three/drei';
function Scene() {
return (
<Canvas>
<Environment preset="sunset" />
{/* other components */}
</Canvas>
);
}
Loading Models
The useGLTF hook allows you to easily load and display GLTF models in your scene. It returns the loaded scene, which you can then use as a primitive object.
import { useGLTF } from '@react-three/drei';
function Model() {
const { scene } = useGLTF('/path/to/model.glb');
return <primitive object={scene} />;
}
function Scene() {
return (
<Canvas>
<Model />
{/* other components */}
</Canvas>
);
}
Text
The Text component allows you to easily add 3D text to your scene. You can customize the font, size, color, alignment, and other properties.
import { Text } from '@react-three/drei';
function Scene() {
return (
<Canvas>
<Text
color="black"
fontSize={1}
maxWidth={200}
lineHeight={1}
letterSpacing={0.02}
textAlign={'left'}
font="/path/to/font.woff"
anchorX="center"
anchorY="middle"
>
Hello World
</Text>
{/* other components */}
</Canvas>
);
}
Three.js is the core library for creating 3D graphics in the browser. While it provides a comprehensive set of features for 3D rendering, it requires more boilerplate code compared to @react-three/drei, which offers higher-level abstractions and components.
React-three-fiber is a React renderer for three.js. It allows you to build and manage 3D scenes using React components. @react-three/drei is built on top of react-three-fiber and provides additional helpers and components to simplify common tasks.
A-Frame is a web framework for building virtual reality experiences. It is built on top of three.js and provides a declarative, HTML-like syntax for creating 3D scenes. While it is not React-based, it offers similar functionalities for building 3D environments.
A growing collection of useful helpers and abstractions for react-three-fiber.
npm install @react-three/drei@latest
import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei'
react-native
usage:import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei/native'
The native
route of the library does not export Html
or Loader
. There default export of the library is web
which does export Html
and Loader
.
A responsive THREE.PerspectiveCamera that can set itself as the default.
<PerspectiveCamera
makeDefault // Registers it as the default camera system-wide (default=false)
{...props} // All THREE.PerspectiveCamera props are valid
>
<mesh />
</PerspectiveCamera>
A responsive THREE.OrthographicCamera that can set itself as the default.
If available controls have damping enabled by default, they manage their own updates, remove themselves on unmount, are compatible with the invalidateFrameloop
canvas-flag. They inherit all props from their underlying THREE controls.
Buffer-geometry short-cuts:
<Plane args={[2, 2]} />
<Sphere>
<meshBasicMaterial attach="material" color="hotpink" />
</Sphere>
A box buffer geometry with rounded corners, done with extrusion.
<RoundedBox
args={[1, 1, 1]} // Width, Height and Depth of the box
radius={0.05} // Border-Radius of the box
smoothness={4} // Optional, number of subdivisions
{...meshProps} // All THREE.Mesh props are valid
>
<meshPhongMaterial attach="material" color="#f3f3f3" wireframe />
</RoundedBox>
<ScreenQuad>
<myMaterial />
</ScreenQuad>
A triangle that fills the screen, ideal for full-screen fragment shader work (raymarching, postprocessing). š Why a triangle? https://www.cginternals.com/en/blog/2018-01-10-screen-aligned-quads-and-triangles.html š Use as a post processing mesh: https://medium.com/@luruke/simple-postprocessing-in-three-js-91936ecadfb7
Hi-quality text rendering w/ signed distance fields (SDF) and antialiasing, using troika-3d-text. All of troikas props are valid!
<Text
color="black" // default
anchorX="center" // default
anchorY="middle" // default
>
hello world!
</Text>
Renders a THREE.Line2.
<Line
points={[[0, 0, 0], ...]} // Array of points
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
/>
A wrapper around THREE.LOD (Level of detail).
<Detailed
distances={[0, 10, 20]} // Camera distances, correspends to the # of the children
{...props} // All THREE.LOD props are valid
>
<mesh geometry={highDetail} />
<mesh geometry={mediumDetail} />
<mesh geometry={lowDetail} />
</Detailed>
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" // Url of the sound file
distance={1} // Camera distance (default=1)
loop // Repat play (default=true)
{...props} // All THREE.PositionalAudio props are valid
/>
Adds a <Plane />
that always faces the camera.
<Billboard
follow={true} // Follow the camera (default=true)
lockX={false} // Lock the rotation on the x axis (default=false)
lockY={false} // Lock the rotation on the y axis (default=false)
lockZ={false} // Lock the rotation on the z axis (default=false)
/>
Sets up a global cubemap, which affects scene.environment
, and optionally scene.background
. A selection of presets from HDRI Haven are available for convenience.
<Environment
background={false} // Whether to affect scene.background
files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} // Array of cubemap files OR single equirectangular file
path={'/'} // Path to the above file(s)
preset={null} // Preset string (overrides files and path)
/>
Abstraction around threes own EffectComposer.
<Effects
multisamping={8} // Default, uses WebGL2 multisamping if available
renderIndex={1} // Default
disableGamma={false} // Default, would switch off the gamma-correction-pass
disableRenderPass={false} // Default, would remove the first scene-render-pass
>
{/* Generic passes go here ... */}
<lUTPass attachArray="passes" lut={texture3D} />
</Effects>
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} />
This material makes your geometry wobble and wave around. It was taken from the threejs-examples and adapted into a self-contained material.
<mesh>
<boxBufferGeometry attach="geometry" />
<MeshWobbleMaterial
attach="material"
factor={1} // Strength, 0 disables the effect (default=1)
speed={10} // Speed (default=1)
/>
</mesh>
This material makes your geometry distort following simplex noise.
<mesh>
<boxBufferGeometry attach="geometry" />
<MeshDistortMaterial
attach="material"
distort={1} // Strength, 0 disables the effect (default=1)
speed={10} // Speed (default=1)
/>
</mesh>
Adds a sky to your scene.
<Sky
distance={450000} // Camera distance (default=450000)
sunPosition={[0, 1, 0]} // Sun position normal (defaults to inclination and azimuth if not set)
inclination={0} // Sun elevation angle from 0 to 1 (default=0)
azimuth={0.25} // Sun rotation around the Y axis from 0 to 1 (default=0.25)
{...props} // All three/examples/jsm/objects/Sky props are valid
/>
Adds a blinking shader-based starfield to your scene.
<Stars
radius={100} // Radius of the inner sphere (default=100)
depth={50} // Depth of area where stars should fit (default=50)
count={5000} // Amount of stars (default=5000)
factor={4} // Size factor (default=4)
saturation={0} // Saturation 0-1 (default=0)
fade // Faded dots (default=false)
/>
A contact shadow implementation.
<ContactShadows
opacity={1}
width={1}
height={1}
blur={1} // Amount of blue (default=1)
far={10} // Focal distance (default=10)
resolution={256} // Rendertarget resolution (default=256)
/>
Injects percent closer soft shadows (pcss) into threes shader chunk.
softShadows({
frustrum: 3.75, // Frustrum width (default: 3.75)
size: 0.005, // World size (default: 0.005)
near: 9.5, // Near plane (default: 9.5)
samples: 17, // Samples (default: 17)
rings: 11, // Rings (default: 11)
})
Creates a THREE.ShaderMaterial for you with easier handling of uniforms, which are also automatically declared as setter/getters on the object.
import { extend } from 'react-three-fiber'
import glsl from 'babel-plugin-glsl/macro'
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 + time) + color, 1.0);
}
`
)
extend({ ColorShiftMaterial })
// in your component
<mesh>
<colorShiftMaterial attach="material" color="hotpink" time={1} />
</mesh>
Allows you to forward contexts provided above the <Canvas />
to be consumed from within the <Canvas />
normally
function SceneWrapper() {
// bridge any number of contexts
const ContextBridge = useContextBridge(ThemeContext, GreetingContext)
return (
<Canvas>
<ContextBridge>
<Scene />
</ContextBridge>
</Canvas>
)
}
function Scene() {
// we can now consume a context within the Canvas
const theme = React.useContext(ThemeContext)
const greeting = React.useContext(GreetingContext)
return (
//...
)
}
Creates a THREE.WebGLRenderTarget
or THREE.WebGLMultisampleRenderTarget
.
const target = useFBO(
// width: 500, height: 500,
// width and height are optional and defaulted to the viewport size
// multiplied by the renderer pixel ratio, and recalculated whenever the
// viewport size changes.
{
multisample: true, // if the renderer supports webGL2, it will return a WebGLMultisampleRenderTarget
stencilBuffer: false, // you can pass any options supported by THREE.WebGLRenderTarget
}
)
The rendertarget is automatically disposed when unmounted.
:no_entry_sign: Web usage only.
Allows you to tie HTML content to any object of your scene. It will be projected to the objects whereabouts automatically.
<Html
prepend // Project content behind the canvas (default: false)
center // Adds a -50%/-50% css transform (default: false)
fullscreen // Aligns to the upper-left corner, fills the screen (default:false)
scaleFactor={10} // If set (default: undefined), children will be scaled by this factor, and also by distance to a PerspectiveCamera.
zIndexRange={[100, 0]} // Z-order range (default=[16777271, 0])
portal={domnodeRef} // Reference to target container (default=undefined)
{...groupProps} // All THREE.Group props are valid
{...divProps} // All HTMLDivElement props are valid
>
<h1>hello</h1>
<p>world</p>
</Html>
Easily add reflection to any object
<Reflector>
<planeBufferGeometry args={[2, 5]} attach="geometry" />
</Reflector>
A cheap canvas-texture-based circular gradient.
<Shadow
color="black" // Color (default:black)
colorStop={0} // First gradient-stop (default:0)
opacity={0.5} // Alpha (default:0.5)
fog={false} // Reacts to fog (default=false)
/>
Adds stats to document.body. It takes over the render-loop!
<Stats
showPanel={0} // Start-up panel (default=0)
className="stats" // Optional className to add to the stats container dom element
{...props} // All stats.js props are valid
/>
You can choose to mount Stats to a different DOM Element - for example, for custom styling:
const node = useRef(document.createElement('div'))
useEffect(() => {
node.current.id = 'test'
document.body.appendChild(node.current)
return () => document.body.removeChild(node.current)
}, [])
return <Stats parent={parent} />
A very fast, but often good-enough bounds-only raycast for meshes. You can use this if performance has precidence over pointer precision.
<mesh raycast={meshBounds} />
A hook for the rare case when you are using non-default cameras for heads-up-displays or portals, and you need events/raytracing to function properly (raycasting uses the default camera otherwise).
<mesh raycast={useCamera(customCamera)} />
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')
This hook uses DetectGPU by @TimvanScherpenzeel to determine what tier should be assigned to the user's GPU.
š This hook CAN be used outside the react-three-fiber Canvas
.
const GPUTier = useDetectGPU()
// show a fallback for mobile or lowest tier GPUs
return (
{(GPUTier.tier === "0" || GPUTier.isMobile) ? <Fallback /> : <Canvas>...</Canvas>
This hook calculates aspect ratios (for now only what in css would be image-size: cover
is supported). You can use it to make an image fill the screen. It is responsive and adapts to viewport resize. Just give the hook the image bounds in pixels. It returns an array: [width, height, 1]
.
const scale = useAspect(
"cover", // Aspect ratio: cover | ... more to come, PR's welcome ;)
1024, // Pixel-width
512, // Pixel-height
1 // Optional scaling factor
)
return (
<mesh scale={scale}>
<planeBufferGeometry />
<meshBasicMaterial map={imageTexture} />
Given a curve will replace the children of this component with a mesh that move along said curve calling the property moveAlongCurve
on the passed ref. Uses three's Curve Modifier
const curveRef = useRef()
const curve = React.useMemo(() => new THREE.CatmullRomCurve3([...handlePos], true, 'centripetal'), [handlePos])
return (
<CurveModifier ref={curveRef} curve={curve}>
<mesh>
<boxBufferGeometry args={[10, 10]} />
</mesh>
</CurveModifier>
)
This hook mutates a mesh geometry using three's Edge Split modifier.
const meshRef = useEdgeSplit(Math.PI / 2)
return (
<mesh ref={meshRef}>
<boxBufferGeometry args={[10, 10]} />
</mesh>
)
This hook mutates a mesh geometry using three's Subdivision modifier.
š Vertex count is quadrupled for each subdivision.
const meshRef = useSubdivision(4)
return (
<mesh ref={meshRef}>
<boxBufferGeometry args={[10, 10]} />
</mesh>
)
This hook mutates a mesh geometry using three's Simplification modifier.
š The simplification code is based on this algorithm.
const meshRef = useSimplification(0.5) // the vertices will be halved
return (
<mesh ref={meshRef}>
<octahedronBufferGeometry args={[2, 5]} />
</mesh>
)
This hook mutates a mesh geometry using three's Tessellation modifier. It will break-up faces withe edge longer than the maxEdgeLength parameter.
const meshRef = useTessellation(
2, // passes - number of times the geometry will be subdivided
8 // maxEdgeLength - faces with edges longer than this number will be broken up
)
return (
<mesh ref={meshRef}>
<octahedronBufferGeometry args={[2, 2]} />
</mesh>
)
A convenience hook that uses useLoader
and GLTFLoader
, it defaults to CDN loaded draco binaries (https://www.gstatic.com/draco/v1/decoders/
) which are only loaded for compressed models.
// Loads model, uses CDN draco when needed
useGLTF(url)
// Use local draco binaries from a custom path
useGLTF(url, '/draco-gltf')
// Preload asset (you would do this in global space, not inside a component!)
useGLTF.preload(url)
A convenience hook that uses useLoader
and FBXLoader
:
useFBX(url)
function SuzanneFBX() {
let fbx = useFBX('suzanne/suzanne.fbx')
// wrap fbx in primitive.
return <primitive object={fbx} dispose={null} />
}
A convenience hook that uses useLoader
and TextureLoader
const texture = useTexture(url)
const [texture1, texture2] = useTexture([texture1, texture2])
A convenience hook that uses useLoader
and CubeTextureLoader
const envMap = useCubeTexture(['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'], { path: 'cube/' })
A convenience hook that wraps THREE.DefaultLoadingManager
's progress status.
function Loader() {
const { active, progress, errors, item, loaded, total } = useProgress()
return <Html center>{progress} % loaded</Html>
}
return (
<Suspense fallback={<Loader />}>
<AsyncModels />
</Suspense>
)
If you don't want your progress component to re-render on all changes you can be specific as to what you need, for instance if the component is supposed to collect errors only. Look into zustand for more info about selectors.
const errors = useProgress((state) => state.errors)
š Note that your loading component does not have to be a suspense fallback. You can use it anywhere, even in your dom tree, for instance for overlays.
:no_entry_sign: Web usage only.
A quick and easy loading overlay component that you can drop on top of your canvas. It will show an animated loadingbar and a percentage.
<Canvas>
<Suspense fallback={null}>
<AsyncModels />
</Suspense>
</Canvas>
<Loader />
You can override styles, too.
<Loader
containerStyles={...container} // Flex layout styles
innerStyles={...inner} // Inner container styles
barStyles={...bar} // Loading-bar styles
dataStyles={...data} // Text styles
dataInterpolation={(p) => `Loading ${p.toFixed(2)}%`} // Text
initialState={(active) => active} // Initial black out state
>
Loads matcap textures from this repository: https://github.com/emmelleppi/matcaps
(It is a fork of this repository: https://github.com/nidorx/matcaps)
const [matcap, url] = useMatcapTexture(
0, // index of the matcap texture https://github.com/emmelleppi/matcaps/blob/master/matcap-list.json
1024 // size of the texture ( 64, 128, 256, 512, 1024 )
)
return (
...
<meshMatcapMaterial matcap={matcap} />
...
)
š You can also use the exact name of the matcap texture, like so:
const [matcap] = useMatcapTexture('3E2335_D36A1B_8E4A2E_2842A5')
š Use the url
to download the texture when you are ready for production!
Loads normal textures from this repository: https://github.com/emmelleppi/normal-maps
const [normalMap, url] = useNormalTexture(
1, // index of the normal texture - https://github.com/emmelleppi/normal-maps/blob/master/normals.json
// second argument is texture attributes
{
offset: [0, 0],
repeat: [normRepeat, normRepeat],
anisotropy: 8
}
)
return (
...
<meshStandardMaterial normalMap={normalMap} />
...
)
FAQs
useful add-ons for react-three-fiber
The npm package @react-three/drei receives a total of 223,975 weekly downloads. As such, @react-three/drei popularity was classified as popular.
We found that @react-three/drei demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.