Real-time 2D fluid velocity simulation for React Three Fiber.
npm install r3f-fluid-simReal-time 2D fluid velocity simulation for React Three Fiber (R3F) and Three.js.
Use it to drive particles, flow fields, or any shader that samples a velocity texture.
```
npm install r3f-fluid-sim
Peer dependencies:
- reactreact-dom
- three
- @react-three/fiber
- @react-three/drei
-
- WebGL2 + float render targets (EXT_color_buffer_float on most hardware)
`tsx
import { Canvas } from '@react-three/fiber'
import { FluidSimulation } from 'r3f-fluid-sim'
export function Scene() {
return (
)
}
`
`tsx
import { useFrame } from '@react-three/fiber'
import { FluidSimulation, useFluid } from 'r3f-fluid-sim'
import * as THREE from 'three'
import { useMemo, useRef } from 'react'
const vertexShader =
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix modelViewMatrix vec4(position, 1.0);
}
const fragmentShader =
uniform sampler2D uVelocity;
varying vec2 vUv;
void main() {
vec2 vel = texture2D(uVelocity, vUv).xy;
float mag = length(vel);
gl_FragColor = vec4(vec3(mag), 1.0);
}
function VelocityFieldPlane() {
const { velocityFBO } = useFluid()
const materialRef = useRef
const uniforms = useMemo(
() => ({ uVelocity: { value: null as THREE.Texture | null } }),
[]
)
useFrame(() => {
if (velocityFBO && materialRef.current) {
materialRef.current.uniforms.uVelocity.value = velocityFBO.read.texture
}
})
return (
uniforms={uniforms}
vertexShader={vertexShader}
fragmentShader={fragmentShader}
/>
)
}
export function Scene() {
return (
)
}
`
FluidSimulation props (defaults):
- size (128)viscosity
- (0.05)viscousIterations
- (20)pressureIterations
- (20)dt
- (0.01)advectionDecay
- (0.98)forceRadius
- (0.0025)forceStrength
- (1.0)forceClamp
- (3.0)bfecc
- (true)interaction
- (true)pointer
- (THREE.Vector2 in NDC, optional)
useFluid() returns:
- velocityFBO (double FBO)fboSize` (number)
-
MIT