<p>There’s a slew of artists and creative coders on social media who regularly post satisfying, hypnotic looping animations. One example is Dave Whyte, also known as @beesandbombs on Twitter. In this tutorial I’ll explain how to recreate one of his more popular recent animations, which I’ve dubbed “Breathing Dots”. Here’s the original animation: </p> <p> pic.twitter.com/YZbXrUyi4C— dave (@beesandbombs) November 20, 2020 </p> <p>The Tools </p> <p>Dave says he uses Processing for his animations, but I’ll be using react-three-fiber (R3F) which is a React renderer for Three.js. Why am I using a 3D library for a 2D animation? Well, R3F provides a powerful declarative syntax for WebGL graphics and grants you access to useful Three.js features such as post-processing effects. It lets you do a lot with few lines of code, all while being highly modular and re-usable. You can use whatever tool you like, but I find the combined ecosystems of React and Three.js make R3F a robust tool for general purpose graphics. </p> <p>View the template </p> <p>I use an adapted Codesandbox template running Create React App to bootstrap my R3F projects; You can fork it by clicking the button above to get a project running in a few seconds. I will assume some familiarity with React, Three.js and R3F for the rest of the tutorial. If you’re totally new, you might want to start here. </p> <p>Step 1: Observations </p> <p>First things first, we need to take a close look at what’s going on in the source material. When I look at the GIF, I see a field of little white dots. They’re spread out evenly, but the pattern looks more random than a grid. The dots are moving in a rhythmic pulse, getting pulled towards the center and then flung outwards in a gentle shockwave. The shockwave has the shape of an octagon. The dots aren’t in constant motion, rather they seem to pause at each end of the cycle. The dots in motion look really smooth, almost like they’re melting. We need to zoom in to really understand what’s going on here. Here’s a close up of the corners during the contraction phase: </p> <p>Top leftBottom right </p> <p>Interesting! The moving dots are split into red, green, and blue parts. The red part points in the direction of motion, while the blue part points away from the motion. The faster the dot is moving, the farther these three parts are spread out. As the colored parts overlap, they combine into a solid white color. Now that we understand what exactly we want to produce, lets start coding. </p> <p>Step 2: Making Some Dots </p> <p>If you’re using the Codesandbox template I provided, you can strip down the main App.js to just an empty scene with a black background: </p> <p>import React from &#8216;react&#8217;<br /> import { Canvas } from &#8216;react-three-fiber&#8217; </p> <p>export default function App() {<br /> return ( </p> <p> )<br /> } </p> <p>Our First Dot </p> <p>Let’s create a component for our dots, starting with just a single white circle mesh composed of a CircleBufferGeometry and MeshBasicMaterial </p> <p>function Dots() {<br /> return ( </p> <p> )<br /> } </p> <p>Add the component inside the canvas, and you should see a white octagon appear onscreen. Our first dot! Since it’ll be tiny, it doesn’t matter that it’s not very round. </p> <p>But wait a second… Using a color picker, you’ll notice that it’s not pure white! This is because R3F sets up color management by default which is great if you’re working with glTF models, but not if you need raw colors. We can disable the default behavior by setting colorManagement={false} on our canvas. </p> <p>More Dots </p> <p>We need approximately 10,000 dots to fully fill the screen throughout the animation. A naive approach at creating a field of dots would be to simply render our dot mesh a few thousand times. However, you’ll quickly notice that this destroys performance. Rendering 10,000 of these chunky dots brings my gaming rig down to a measly 5 FPS. The problem is that each dot mesh incurs its own draw call, which means the CPU needs to send 10,000 (largely redundant) instructions to the GPU every frame. </p> <p>The solution is to use instanced rendering, which means the CPU can tell the GPU about the dot shape, material, and the locations of all 10,000 instances in a single draw call. Three.js offers a helpful InstancedMesh class to facilitate instanced rendering of a mesh. According to the docs it accepts a geometry, material, and integer count as constructor arguments. Let’s convert our regular old mesh into an , starting with just one instance. We can leave the geometry and material slots as null since the child elements will fill them, so we only need to specify the count. </p> <p>function Dots() {<br /> return ( </p> <p> )<br /> } </p> <p>Hey, where did it go? The dot disappeared because of how InstancedMesh is initialized. Internally, the .instanceMatrix stores the transformation matrix of each instance, but it’s initialized with all zeros which squashes our mesh into the abyss. Instead, we should start with an identity matrix to get a neutral transformation. Let’s get a reference to our InstancedMesh and apply the identity matrix to the first instance inside of useLayoutEffect so that it’s properly positioned before anything is painted to the screen. </p> <p>function Dots() {<br /> const ref = useRef()<br /> useLayoutEffect(() = > {<br /> // THREE.Matrix4 defaults to an identity matrix<br /> const transform = new THREE.Matrix4() </p> <p> // Apply the transform to the instance at index 0<br /> ref.current.setMatrixAt(0, transform)<br /> }, [])<br /> return ( </p> <p> )<br /> } </p> <p>Great, now we have our dot back. Time to crank it up to 10,000. We’ll increase the instance count and set the transform of each instance along a centered 100 x 100 grid. </p> <p>for (let i = 0; i < 10000; ++i) { const x = (i % 100) - 50 const y = Math.floor(i / 100) - 50 transform.setPosition(x, y, 0) ref.current.setMatrixAt(i, transform) } We should also decrease the circle radius to 0.15 to better fit the grid proportions. We don’t want any perspective distortion on our grid, so we should set the orthographic prop on the canvas. Lastly, we’ll lower the default camera’s zoom to 20 to fit more dots on screen. The result should look like this: Although you can’t notice yet, it’s now running at a silky smooth 60 FPS Adding Some Noise There’s a variety of ways to distribute points on a surface beyond a simple grid. “Poisson disc sampling” and “centroidal Voronoi tessellation” are some mathematical approaches that generate slightly more natural distributions. That’s a little too involved for this demo, so let’s just approximate a natural distribution by turning our square grid into hexagons and adding in small random offsets to each point. The positioning logic now looks like this: // Place in a grid let x = (i % 100) - 50 let y = Math.floor(i / 100) - 50 // Offset every other column (hexagonal pattern) y += (i % 2) * 0.5 // Add some noise x += Math.random() * 0.3 y += Math.random() * 0.3 Step 3: Creating Motion Sine waves are the heart of cyclical motion. By feeding the clock time into a sine function, we get a value that oscillates between -1 and 1. To get the effect of expansion and contraction, we want to oscillate each point’s distance from the center. Another way of thinking about this is that we want to dynamically scale each point’s intial position vector. Since we should avoid unnecessary computations in the render loop, let’s cache our initial position vectors in useMemo for re-use. We’re also going to need that Matrix4 in the loop, so let’s cache that as well. Finally, we don’t want to overwrite our initial dot positions, so let’s cache a spare Vector3 for use during calculations. const { vec, transform, positions } = useMemo(() = > {<br /> const vec = new THREE.Vector3()<br /> const transform = new THREE.Matrix4()<br /> const positions = [&#8230;Array(10000)].map((_, i) = > {<br /> const position = new THREE.Vector3()<br /> position.x = (i % 100) &#8211; 50<br /> position.y = Math.floor(i / 100) &#8211; 50<br /> position.y += (i % 2) * 0.5<br /> position.x += Math.random() * 0.3<br /> position.y += Math.random() * 0.3<br /> return position<br /> })<br /> return { vec, transform, positions }<br /> }, []) </p> <p>For simplicity let’s scrap the useLayoutEffect call and configure all the matrix updates in a useFrame loop. Remember that in R3F, the useFrame callback receives the same arguments as useThree including the Three.js clock, so we can access a dynamic time through clock.elapsedTime. We’ll add some simple motion by copying each instance position into our scratch vector, scaling it by some factor of the sine wave, and then copying that to the matrix. As mentioned in the docs, we need to set .needsUpdate to true on the instanced mesh’s .instanceMatrix in the loop so that Three.js knows to keep updating the positions. </p> <p>useFrame(({ clock }) = > {<br /> const scale = 1 + Math.sin(clock.elapsedTime) * 0.3<br /> for (let i = 0; i < 10000; ++i) { vec.copy(positions[i]).multiplyScalar(scale) transform.setPosition(vec) ref.current.setMatrixAt(i, transform) } ref.current.instanceMatrix.needsUpdate = true }) Rounded square waves The raw sine wave follows a perfectly round, circular motion. However, as we observed earlier: The dots aren’t in constant motion, rather they seem to pause at each end of the cycle. This calls for a different, more boxy looking wave with longer plateaus and shorter transitions. A search through the digital signal processing StackExchange produces this post with the equation for a rounded square wave. I’ve visualized the equation here and animated the delta parameter, watch how it goes from smooth to boxy: The equation translates to this Javascript function: const roundedSquareWave = (t, delta, a, f) = > {<br /> return ((2 * a) / Math.PI) * Math.atan(Math.sin(2 * Math.PI * t * f) / delta)<br /> } </p> <p>Swapping out our Math.sin call for the new wave function with a delta of 0.1 makes the motion more snappy, with time to rest in between: </p> <p>Ripples </p> <p>How do we use this wave to make the dots move at different speeds and create ripples? If we change the input to the wave based on the dot’s distance from the center, then each ring of dots will be at a different phase causing the surface to stretch and squeeze like an actual wave. We’ll use the initial distances on every frame, so let’s cache and return the array of distances in our useMemo callback: </p> <p>const distances = positions.map(pos = > pos.length()) </p> <p>Then, in the useFrame callback we subtract a factor of the distance from the t (time) variable that gets plugged into the wave. That looks like this: </p> <p>That already looks pretty cool! </p> <p>The Octagon </p> <p>Our ripple is perfectly circular, how can we make it look more octagonal like the original? One way to approximate this effect is by combining a sine or cosine wave with our distance function at an appropriate frequency (8 times per revolution). Watch how changing the strength of this wave changes the shape of the region: </p> <p>A strength of 0.5 is a pretty good balance between looking like an octagon and not looking too wavy. That change can happen in our initial distance calculations: </p> <p>const right = new THREE.Vector3(1, 0, 0)<br /> const distances = positions.map((pos) = > (<br /> pos.length() + Math.cos(pos.angleTo(right) * 8) * 0.5<br /> )) </p> <p>It’ll take some additional tweaks to really see the effect of this. There’s a few places that we can focus our adjustments on: </p> <p>Influence of point distance on wave phaseInfluence of point distance on wave roundnessFrequency of the waveAmplitude of the wave </p> <p>It’s a bit of educated trial and error to make it match the original GIF, but after fiddling with the wave parameters and multipliers eventually you can get something like this: </p> <p>When previewing in full screen, the octagonal shape is now pretty clear. </p> <p>Step 4: Post-processing </p> <p>We have something that mimics the overall motion of the GIF, but the dots in motion don’t have the same color shifting effect that we observed earlier. As a reminder: </p> <p>The moving dots are split into red, green, and blue parts. The red part points in the direction of motion, while the blue part points away from the motion. The faster the dot is moving, the farther these three parts are spread out. As the colored parts overlap, they combine into a solid white color. </p> <p>We can achieve this effect using the post-processing EffectComposer built into Three.js, which we can conveniently tack onto the scene without any changes to the code we’ve already written. If you’re new to post-processing like me, I highly recommend reading this intro guide from threejsfundamentals. In short, the composer lets you toss image data back and forth between two “render targets” (glorified image textures), applying shaders and other operations in between. Each step of the pipeline is called a “pass”. Typically the first pass performs the initial scene render, then there are some passes to add effects, and by default the final pass writes the resulting image to the screen. </p> <p>An example: motion blur </p> <p>Here’s a JSFiddle from Maxime R that demonstrates a naive motion blur effect with the EffectComposer. This effect makes use of a third render target in order to preserve a blend of previous frames. I’ve drawn out a diagram to track how image data moves through the pipeline (read from the top down): </p> <p>First, the scene is rendered as usual and written to rt1 with a RenderPass. Most passes will automatically switch the read and write buffers (render targets), so our next pass will read what we just rendered in rt1 and write to rt2. In this case we use a ShaderPass configured with a BlendShader to blend the contents of rt1 with whatever is stored in our third render target (empty at first, but it eventually accumulates a blend of previous frames). This blend is written to rt2 and another swap automatically occurs. Next, we use a SavePass to save the blend we just created in rt2 back to our third render target. The SavePass is a little unique in that it doesn’t swap the read and write buffers, which makes sense since it doesn’t actually change the image data. Finally, that same blend in rt2 (which is still the read buffer) gets read into another ShaderPass set to a CopyShader, which simply copies its input into the output. Since it’s the last pass on the stack, it automatically gets renderToScreen=true which means that its output is what you’ll see on screen. </p> <p>Working with post-processing requires some mental gymnastics, but hopefully this makes some sense of how different components like ShaderPass, SavePass, and CopyPass work together to apply effects and preserve data between frames. </p> <p>RGB Delay Effect </p> <p>A simple RGB color shifting effect involves turning our single white dot into three colored dots that get farther apart the faster they move. Rather than trying to compute velocities for all the dots and passing them to the post-processing stack, we can cheat by overlaying previous frames: </p> <p>This turns out to be a very similar problem as the motion blur, since it requires us to use additional render targets to store data from previous frames. We actually need two extra render targets this time, one to store the image from frame n-1 and another for frame n-2. I’ll call these render targets delay1 and delay2. </p> <p>Here’s a diagram of the RGB delay effect: </p> <p>A circle containing a value X represents the individual frame for delay X. </p> <p>The trick is to manually disable needsSwap on the ShaderPass that blends the colors together, so that the proceeding SavePass re-reads the buffer that holds the current frame rather than the colored composite. Similarly, by manually enabling needsSwap on the SavePass we ensure that we read from the colored composite on the final ShaderPass for the end result. The other tricky part is that since we’re placing the current frame’s contents in the delay2 buffer (as to not lose the contents of delay1 for the next frame), we need to swap these buffers each frame. It’s easiest to do this outside of the EffectComposer by swapping the references to these render targets on the ShaderPass and SavePass within the render loop. </p> <p>Implementation </p> <p>This is all very abstract, so let’s see what this means in practice. In a new file (Effects.js), start by importing the necessary passes and shaders, then extending the classes so that R3F can access them declaratively. </p> <p>import { useThree, useFrame, extend } from &#8216;react-three-fiber&#8217;<br /> import { EffectComposer } from &#8216;three/examples/jsm/postprocessing/EffectComposer&#8217;<br /> import { ShaderPass } from &#8216;three/examples/jsm/postprocessing/ShaderPass&#8217;<br /> import { SavePass } from &#8216;three/examples/jsm/postprocessing/SavePass&#8217;<br /> import { CopyShader } from &#8216;three/examples/jsm/shaders/CopyShader&#8217;<br /> import { RenderPass } from &#8216;three/examples/jsm/postprocessing/RenderPass&#8217; </p> <p>extend({ EffectComposer, ShaderPass, SavePass, RenderPass }) </p> <p>We’ll put our effects inside a new component. Here is what a basic effect looks like in R3F: </p> <p>function Effects() {<br /> const composer = useRef()<br /> const { scene, gl, size, camera } = useThree()<br /> useEffect(() = > void composer.current.setSize(size.width, size.height), [size])<br /> useFrame(() = > {<br /> composer.current.render()<br /> }, 1)<br /> return ( </p> <p> )<br /> } </p> <p>All that this does is render the scene to the canvas. Let’s start adding in the pieces from our diagram. We’ll need a shader that takes in 3 textures and respectively blends the red, green, and blue channels of them. The vertexShader of a post-processing shader always looks the same, so we only really need to focus on the fragmentShader. Here’s what the complete shader looks like: </p> <p>const triColorMix = {<br /> uniforms: {<br /> tDiffuse1: { value: null },<br /> tDiffuse2: { value: null },<br /> tDiffuse3: { value: null }<br /> },<br /> vertexShader: `<br /> varying vec2 vUv;<br /> void main() {<br /> vUv = uv;<br /> gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1);<br /> }<br /> `,<br /> fragmentShader: `<br /> varying vec2 vUv;<br /> uniform sampler2D tDiffuse1;<br /> uniform sampler2D tDiffuse2;<br /> uniform sampler2D tDiffuse3; </p> <p> void main() {<br /> vec4 del0 = texture2D(tDiffuse1, vUv);<br /> vec4 del1 = texture2D(tDiffuse2, vUv);<br /> vec4 del2 = texture2D(tDiffuse3, vUv);<br /> float alpha = min(min(del0.a, del1.a), del2.a);<br /> gl_FragColor = vec4(del0.r, del1.g, del2.b, alpha);<br /> }<br /> `<br /> } </p> <p>With the shader ready to roll, we’ll then memo-ize our helper render targets and set up some additional refs to hold constants and references to our other passes. </p> <p>const savePass = useRef()<br /> const blendPass = useRef()<br /> const swap = useRef(false) // Whether to swap the delay buffers<br /> const { rtA, rtB } = useMemo(() = > {<br /> const rtA = new THREE.WebGLRenderTarget(size.width, size.height)<br /> const rtB = new THREE.WebGLRenderTarget(size.width, size.height)<br /> return { rtA, rtB }<br /> }, [size]) </p> <p>Next, we’ll flesh out the effect stack with the other passes specified in the diagram above and attach our refs: </p> <p>return ( </p> <p>) </p> <p>By stating args={[triColorMix, &#8216;tDiffuse1&#8217;]} on the blend pass, we indicate that the composer’s read buffer should be passed as the tDiffuse1 uniform in our custom shader. The behavior of these passes is unfortunately not documented, so you sometimes need to poke through the source files to figure this stuff out. </p> <p>Finally, we’ll need to modify the render loop to swap between our spare render targets and plug them in as the remaining 2 uniforms: </p> <p>useFrame(() = > {<br /> // Swap render targets and update dependencies<br /> let delay1 = swap.current ? rtB : rtA<br /> let delay2 = swap.current ? rtA : rtB<br /> savePass.current.renderTarget = delay2<br /> blendPass.current.uniforms[&#8216;tDiffuse2&#8217;].value = delay1.texture<br /> blendPass.current.uniforms[&#8216;tDiffuse3&#8217;].value = delay2.texture<br /> swap.current = !swap.current<br /> composer.current.render()<br /> }, 1) </p> <p>All the pieces for our RGB delay effect are in place. Here’s a demo of the end result on a simpler scene with one white dot moving back and forth: </p> <p>Putting it all together </p> <p>As you’ll notice in the previous sandbox, we can make the effect take hold by simply plopping the component inside the canvas. After doing this, we can make it look even better by adding an anti-aliasing pass to the effect composer. </p> <p>import { FXAAShader } from &#8216;three/examples/jsm/shaders/FXAAShader&#8217; </p> <p>&#8230;<br /> const pixelRatio = gl.getPixelRatio()<br /> return ( </p> <p> )<br /> } </p> <p>And here’s our finished demo! </p> <p>(Bonus) Interactivity </p> <p>While outside the scope of this tutorial, I’ve added an interactive demo variant which responds to mouse clicks and cursor position. This variant uses react-spring v9 to smoothly reposition the focus point of the dots. Check it out in the “Demo 2” page of the demo linked at the top of this page, and play around with the source code to see if you can add other forms of interactivity. </p> <p>Step 5: Sharing Your Work </p> <p>I highly recommend publicly sharing the things you create. It’s a great way to track your progress, share your learning with others, and get feedback. I wouldn’t be writing this tutorial if I hadn’t shared my work! For perfect loops you can use the use-capture hook to automate your recording. If you’re sharing to Twitter, consider converting to a GIF to avoid compression artifacts. Here’s a thread from @arc4g explaining how they create smooth 50 FPS GIFs for Twitter. </p> <p>I hope you learned something about Three.js or react-three-fiber from this tutorial. Many of the animations I see online follow a similar formula of repeated shapes moving in some mathematical rhythm, so the principles here extend beyond just rippling dots. If this inspired you to create something cool, tag me in it so I can see!<br /> The post Recreating a Dave Whyte Animation in React-Three-Fiber appeared first on Codrops.</p>

Breakdown

There’s a slew of artists and creative coders on social media who regularly post satisfying, hypnotic looping animations. One example is Dave Whyte, also known as @beesandbombs on Twitter. In this tutorial I’ll explain how to recreate one of his

...