Skip to content
ImagineWorld

Render Postprocessing

node_idnode-book_learn-three-js_chapter-11-render-postprocessing
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleRender Postprocessing
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’ll look at one of the main features of Three.js that we haven’t touched upon yet: render postprocessing. With render postprocessing, you can add additional effects to your scene after it is rendered. For instance, you could add an effect that makes the scene look like it is shown on an old TV, or you could add blur and bloom effects.

The main points we’ll discuss in this chapter are as follows:

  • Setting up Three.js for postprocessing
  • Some basic postprocessing passes provided by Three.js, such as BloomPass and FilmPass
  • Applying effects to part of a scene using masks
  • Using ShaderPass to add even more basic postprocessing effects, such as sepia filters, mirror effects, and color adjustments
  • Using ShaderPass for various blurring effects and more advanced filters
  • Creating a custom postprocessing effect by writing a simple shader

In Chapter 1, Creating Your First 3D Scene with Three.js, in the Introducing requestAnimationFrame section, we set up a rendering loop that we’ve used throughout the book, in order to render and animate our scenes. For postprocessing, we need to make a couple of changes to this setup to allow Three.js to postprocess the final rendering. In the first section, we’ll look at how to do this.

To set up Three.js for postprocessing, we have to make a couple of changes to our current setup, as follows:

  1. Create EffectComposer, which can be used to add postprocessing passes.
  2. Configure EffectComposer so that it can render our scene and apply any additional postprocessing steps.
  3. In the render loop, use EffectComposer to render the scene, apply the configured postprocessing steps, and show the output.

As always, we will show an example that you can use to experiment with and adapt for your own purposes. The first example in this chapter can be accessed from basic-setup.html. You can use the menu in the top-right corner to modify the properties of the postprocessing step used in this example. In this example, we will render the mushroom man from Chapter 9, Animation and Moving the Camera, and add an RGB shift effect to it, as follows:

Figure 11.1 – Rendered using a postprocessing pass

This effect is added after the scene is rendered by using ShaderPass, together with EffectComposer. In the menu on the right side of the screen, you can configure this effect and also enable the DotScreenShader effect.

In the following sections, we’ll explain the individual steps from the previous list.

To get EffectComposer to work, we first need effects that we can use with it. Three.js comes with a large number of effects and shaders you can use. In this chapter, we’ll show most of them, but for a complete overview, check out the following two directories on GitHub:

To use these effects in your scene, you need to import them:

import { EffectComposer } from
'three/examples/jsm/postprocessing/EffectComposer'
import { RenderPass } from
'three/examples/jsm/postprocessing/RenderPass.js'
import { ShaderPass } from
'three/examples/jsm/postprocessing/ShaderPass.js'
import { BloomPass } from
'three/examples/jsm/postprocessing/BloomPass.js'
import { GlitchPass } from
'three/examples/jsm/postprocessing/GlitchPass.js'
import { RGBShiftShader } from
'three/examples/jsm/shaders/RGBShiftShader.js'
import { DotScreenShader } from
'three/examples/jsm/shaders/DotScreenShader.js'
import { CopyShader } from
'three/examples/jsm/shaders/CopyShader.js'

In the imports in the preceding code block, we import the main EffectComposer and a different number of postprocessing passes and shaders that we can use together with this EffectComposer. Once we’ve got these, setting up EffectComposer is done like this:

const composer = new EffectComposer(renderer)

As you can see, the only argument an effect composer takes is renderer. Next, we will add various passes to this composer.

Configuring THREE.EffectComposer for postprocessing

Section titled “Configuring THREE.EffectComposer for postprocessing”

Each pass is executed in the sequence it is added to THREE.EffectComposer. The first pass that we add is RenderPass. This pass renders our scene using the camera provided but doesn’t output it to the screen yet:

const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);

With the addPass function, we add RenderPass to EffectComposer. The next step is to add another pass that will take the results from RenderPass as its input, apply its transformation, and output its result to the screen. Not all the available passes allow for this, but the passes we’ve used in this example do:

const effect1 = new ShaderPass(DotScreenShader)
effect1.uniforms['scale'].value = 10
effect1.enabled = false
const effect2 = new ShaderPass(RGBShiftShader)
effect2.uniforms['amount'].value = 0.015
effect2.enabled = false
const composer = new EffectComposer(renderer)
composer.addPass(new RenderPass(scene, camera))
composer.addPass(effect1)
composer.addPass(effect2)

In this example, we’ve added two effects to composer. First, the scene is rendered using RenderPass, then DotScreenShader is applied, and finally, we apply RGBShiftShader.

All we need to do now is update the render loop so that we render using EffectComposer instead of through the normal WebGLRenderer.

We just need to make a small modification to our render loop to use the composer instead of THREE.WebGLRenderer:

const render = () => {
requestAnimationFrame(render);
composer.render();
}

The only modification that we made is removing renderer.render(scene, camera) and replacing it with composer.render(). This will call the render function on EffectComposer, which, in turn, uses the passed-in THREE.WebGLRenderer, and the result is that we see the output on the screen:

Figure 11.2 – Rendered using multiple postprocessing passes

Using controls after applying a render pass

You can still use the normal controls to move around a scene. All of the effects that you will see in this chapter are applied after the scene is rendered. With this basic setup, we’ll look at the available postprocessing passes in the next couple of sections.

Three.js comes with a number of postprocessing passes that you can use directly with THREE.EffectComposer.

Use a simple GUI to experiment

Most of the shaders and passes shown in this chapter can be configured. When you want to apply one yourself, it is usually easiest to just add a simple UI that allows you to play around with the properties. That way, you can see what a good setting for your specific scenario is.

The following list shows all the postprocessing passes available in Three.js:

  • AdaptiveToneMappingPass: This render pass adapts the luminosity of a scene, based on the amount of light available in it.
  • BloomPass: This is an effect that makes lighter areas bleed into darker areas. This simulates an effect wherein the camera is overwhelmed by extremely bright light.
  • BokehPass: This adds a bokeh effect to the scene. With a bokeh effect, the foreground of the scene is in focus, while the rest is out of focus.
  • ClearPass: This spill pass clears the current texture buffer.
  • CubeTexturePass: This can be used to render a skybox in the scene.
  • DotScreenPass: This applies a layer of black dots, representing the original image across the screen.
  • FilmPass: This simulates a TV screen by applying scanlines and distortions.
  • GlitchPass: This shows an electronic glitch on the screen at a random time interval.
  • HalfTonePass: This adds a halftone effect to the scene. With a halftone effect, the scene is rendered as a set of colored glyphs (circles, squares, and so on) of various sizes.
  • LUTPass: With LUTPass, you can apply a color correction step to the scene after it is rendered (not shown in this chapter).
  • MaskPass: This allows you to apply a mask to the current image. Subsequent passes are only applied to the masked area.
  • OutlinePass: This renders the outline of the objects in the scene.
  • RenderPass: This renders a scene based on the scene and camera supplied.
  • SAOPass: This provides runtime ambient occlusion.
  • SMAAPass: This adds an anti-aliasing effect to the scene.
  • SSAARenderPass: This adds anti-aliasing to the scene.
  • SSAOPass: This provides an alternative way to perform runtime ambient occlusion.
  • SSRPass: This pass allows you to create reflective objects.
  • SavePass: When this pass is executed, it makes a copy of the current rendering step that you can use later. This pass isn’t that useful in practice, and we won’t use it in any of our examples.
  • ShaderPass: This allows you to pass in custom shaders for advanced or custom postprocessing passes.
  • TAARenderPass: This adds an anti-aliasing effect to the scene.
  • TexturePass: This stores the current state of the composer in a texture that you can use as input for other EffectComposer instances.
  • UnrealBloomPass: This is the same as THREE.BloomPass but with an effect similar to the effect used in the Unreal 3D engine.

Let’s start with a number of simple passes.

For simple passes, we’ll look at what we can do with FilmPass, BloomPass, and DotScreenPass. For these passes, an example is available (multi-passes.html) that will allow you to experiment with these passes and see how they affect the original output differently. The following screenshot shows the example:

Figure 11.3 – Three simple passes applied to a scene

In this example, you can see four scenes at the same time, and in each scene, a different postprocessing pass is added. The one in the top-left corner shows BloomPass, the one in the bottom-right corner shows DotScreenPass, and the one in the bottom-left corner shows FilmPass. The scene in the top-right corner shows the original render.

In this example, we also use THREE.ShaderPass and THREE.TexturePass to reuse the output from the original rendering as input for the other three scenes. That way, we only need to render the scene once. So, before we look at the individual passes, let’s look at these two passes, as follows:

const effectCopy = new ShaderPass(CopyShader)
const renderedSceneComposer = new EffectComposer(renderer)
renderedSceneComposer.addPass(new RenderPass(scene,
camera))
renderedSceneComposer.addPass(new ShaderPass
(GammaCorrectionShader))
renderedSceneComposer.addPass(effectCopy)
renderedSceneComposer.renderToScreen = false
const texturePass = new TexturePass
(renderedSceneComposer.renderTarget2.texture)

In this piece of code, we set up EffectComposer, which will output the default scene (the one in the top-right corner). This composer has three passes:

  • RenderPass: This pass renders the scene.
  • ShaderPass with GammaCorrectionShader: Makes sure that the colors of the output are correct. If, after applying effects, the color of the scene looks incorrect, this shader will correct it.
  • ShaderPass with CopyShader: Renders the output (without any further postprocessing to the screen, if we set the renderToScreen property to true).

If you look at the example, you can see that we show the same scene four times but with a different effect applied each time. We could also render the scene from scratch by using RenderPass four times, but that would be a bit of a waste, since we can just reuse the output from the first composer. To do this, we create TexturePass and pass in the composer.renderTarget2.texture value. This property contains the rendered scene as a texture, which we can pass into TexturePass. We can now use the texturePass variable as input for our other composers, without having to render the scene from scratch. Let’s look at FilmPass first and how we can use the results from TexturePass as input.

Using THREE.FilmPass to create a TV-like effect

Section titled “Using THREE.FilmPass to create a TV-like effect”

To create FilmPass, we use the following piece of code:

const filmpass = new FilmPass()
const filmpassComposer = new EffectComposer(renderer)
filmpassComposer.addPass(texturePass)
filmpassComposer.addPass(filmpass)

The only step that we need to take to use TexturePass is to add it as the first pass in our composer. Next, we can just add FilmPass, and the effect will be applied. FilmPass can take four additional parameters, as shown in the following list:

  • noiseIntensity: This property allows you to control how grainy the scene looks.
  • scanlinesIntensity: FilmPass adds a number of scanlines (see scanLinesCount) to the scene. With this property, you can define how prominently these scanlines are shown.
  • scanLinesCount: The number of scanlines that are shown can be controlled with this property.
  • grayscale: If this is set to true, the output will be converted to grayscale.

There are actually two ways that you can pass in these parameters. In this example, we passed them in as arguments to the constructor, but you can also set them directly, as follows:

effectFilm.uniforms.grayscale.value = controls.grayscale;
effectFilm.uniforms.nIntensity.value = controls.
noiseIntensity;
effectFilm.uniforms.sIntensity.value = controls.
scanlinesIntensity;
effectFilm.uniforms.sCount.value = controls.scanlinesCount;

In this approach, we use the uniforms property, which communicates directly with WebGL. In the Using THREE.ShaderPass for custom effects section, where we talk about creating a custom shader, we’ll get a bit deeper into uniforms; for now, all you need to know is that this way, you can update the configuration of postprocessing passes and shaders and see the results directly.

The result of this pass is shown in the following figure:

Figure 11.4 – A film effect provided by FilmPass

The next effect is the bloom effect, which you can see in the top-left part of the screen in Figure 11*.3*.

Adding a bloom effect to the scene with THREE.BloomPass

Section titled “Adding a bloom effect to the scene with THREE.BloomPass”

The effect that you see in the top-left corner is called the bloom effect. When you apply the bloom effect, the bright areas of a scene will be made more prominent and bleed into the darker areas. The code to create BloomPass is as follows:

const bloomPass = new BloomPass()
const effectCopy = new ShaderPass(CopyShader)
bloomPassComposer = new EffectComposer(renderer)
bloomPassComposer.addPass(texturePass)
bloomPassComposer.addPass(bloomPass)
bloomPassComposer.addPass(effectCopy)

If you compare this with EffectComposer, which we used with FilmPass, you’ll notice that we add an additional pass, effectCopy. This step doesn’t add any special effects but just copies the output from the last pass to the screen. We need to add this step, since BloomPass doesn’t render directly to the screen.

The following table lists the properties that you can set on BloomPass:

  • strength: This is the strength of the bloom effect. The higher this is, the more bright the brighter areas are, and the more they will bleed into the darker areas.
  • kernelSize: This is the size of the kernel. This is the size of the area that is blurred in a single step. If you set this higher, more pixels will be included to determine the effect at a specific point.
  • sigma: With the sigma property, you can control the sharpness of the bloom effect. The higher the value, the more blurred the bloom effect will look.
  • resolution: The resolution property defines how precisely the bloom effect is created. If you make this too low, the result will look blocky.

A better way to understand these properties is to just experiment with them by using the aforementioned example, multi-passes.html. The following screenshot shows the bloom effect with a high sigma size and high strength:

Figure 11.5 – The bloom effect using BloomPass

The next simple effects that we’ll look at are the DotScreenPass effects.

Using DotScreenPass is very similar to using BloomPass. We just saw BloomPass in action. Let’s now look at the code for DotScreenPass:

const dotScreenPass = new DotScreenPass()
const dotScreenPassComposer = new EffectComposer(renderer)
dotScreenPassComposer.addPass(texturePass)
dotScreenPassComposer.addPass(dotScreenPass)

With this effect, we don’t need effectCopy to output the result to the screen.

DotScreenPass can also be configured with a number of properties, as follows:

  • center: With the center property, you can fine-tune the way the dots are offset.
  • angle: The dots are aligned in a certain manner. With the angle properties, you can change this alignment.
  • scale: With this, we can set the sizes of the dots to use. The lower the scale, the larger the dots.

What applies to the other shaders also applies to this shader. It’s much easier to get the right settings with experimentation, as seen in the following figure:

Figure 11.6 – A dot-screen effect using DotScreenPass

Before we move on to the next set of simple shaders, we’ll first look at how we’ve rendered multiple scenes on the same screen.

Showing the output of multiple renderers on the same screen

Section titled “Showing the output of multiple renderers on the same screen”

This section won’t go into detail on how to use postprocessing effects but will explain how to get the output of all four EffectComposer instances on the same screen. First, let’s look at the render loop used for this example:

const width = window.innerWidth || 2
const height = window.innerHeight || 2
const halfWidth = width / 2
const halfHeight = height / 2
const render = () => {
renderer.autoClear = false
renderer.clear()
renderedSceneComposer.render()
renderer.setViewport(0, 0, halfWidth, halfHeight)
filmpassComposer.render()
renderer.setViewport(halfWidth, 0, halfWidth, halfHeight)
dotScreenPassComposer.render()
renderer.setViewport(0, halfHeight, halfWidth,
halfHeight)
bloomPassComposer.render()
renderer.setViewport(halfWidth, halfHeight, halfWidth,
halfHeight)
copyComposer.render()
requestAnimationFrame(() => render())
}

The first thing to notice is that we set the renderer.autoClear property to false and then explicitly call the clear() function in the render loop. If we don’t do this each time we call the render() function on a composer, the previously rendered parts of the screen will be cleared. With this approach, we only clear everything at the beginning of our render loop.

To avoid having all of our composers render in the same space, we set the viewport function of the renderer, which is used by our composers, to a different part of the screen. This function takes four arguments: x, y, width, and height. As you can see in the code sample, we use this function to divide the screen into four areas and make the composers render to their individual areas. Note that you can also use this approach with multiple scene, camera, and WebGLRenderer instances, if you want. With this setup, the render loop will render each of the four EffectComposer objects to their own parts of the screen. Let’s quickly look at another couple of passes.

If you open the multi-passes-2.html example in your browser, you will see a number of additional passes in action:

Figure 11.7 – Another set of four passes

We won’t go into too much detail here, since these passes are configured in the same way as those in the previous sections. In this example, you can see the following:

  • In the bottom-left corner, you can see OutlinePass. The outline pass can be used to draw an outline for a THREE.Mesh object.
  • In the bottom-right corner, GlitchPass is shown. As the name implies, this pass provides a technical rendering glitch effect.
  • In the top-left corner, the UnrealBloom effect is shown.
  • In the top-right corner, HalftonePass is used to convert the rendering to a set of dots.

As is the case for all of the examples in this chapter, you can configure the individual properties of these passes by using the menu on the right.

To see OutlinePass correctly, you can set the scene background to black and zoom out a bit:

Figure 11.8 – The outline pass showing the outline of the scene

So far we’ve seen simple effects, in the next section, we’ll look at how you can use masks to apply effects to parts of the screen.

In the previous examples, we applied the postprocessing pass to a complete screen. However, Three.js also has the ability to apply passes only to a specific area. In this section, we will perform the following steps:

  1. Create a scene to serve as a background image.
  2. Create a scene containing a sphere that looks like Earth.
  3. Create a scene containing a sphere that looks like Mars.
  4. Create EffectComposer, which renders these three scenes into a single image.
  5. Apply a colorify effect to the sphere rendered as Mars.
  6. Apply a sepia effect to the sphere rendered as Earth.

This might sound complex, but it is actually surprisingly easy to accomplish. First, let’s look at the result that we’re aiming for in the masks.html example. The following screenshot shows the results of these steps:

Figure 11.9 – Use a mask to apply an effect to part of the screen

The first thing that we need to do is set up the various scenes that we’ll be rendering:

const sceneEarth = new THREE.Scene()
const sceneMars = new THREE.Scene()
const sceneBG = new THREE.Scene()

To create the Earth and Mars spheres, we just create the spheres with the correct material and textures and add them to their specific scenes. For the background scene, we load a texture and set it to as the background for sceneBG. This is shown in the following code (addEarth and addMars are just helper functions to keep the code clear; they create a simple THREE.Mesh from THREE.SphereGeometry, create some lights, and add them all to THREE.Scene):

sceneBG.background = new THREE.TextureLoader().load
('/assets/textures/bg/starry-deep-outer-space-galaxy.jpg')
const earthAndLight = addEarth(sceneEarth)
sceneEarth.translateX(-16)
sceneEarth.scale.set(1.2, 1.2, 1.2)
const marsAndLight = addMars(sceneMars)
sceneMars.translateX(12)
sceneMars.translateY(6)
sceneMars.scale.set(0.2, 0.2, 0.2)

In this example, we use the background property of a scene to add the starry background. There is an alternative way to create a background. We can use THREE.OrhoGraphicCamera. With THREE.OrthographicCamera, the size of the rendered object doesn’t change when it is closer or further away from the camera, so, by positioning a THREE.PlaneGeometry object directly in front of THREE.rhoGraphicCamera, we can create a background as well.

We now have got our three scenes, and we can start to set up our passes and EffectComposer. Let’s start by looking at the complete chain of passes, after which we’ll look at the individual passes:

var composer = new EffectComposer(renderer)
composer.renderTarget1.stencilBuffer = true
composer.renderTarget2.stencilBuffer = true
composer.addPass(bgRenderPass)
composer.addPass(earthRenderPass)
composer.addPass(marsRenderPass)
composer.addPass(marsMask)
composer.addPass(effectColorify)
composer.addPass(clearMask)
composer.addPass(earthMask)
composer.addPass(effectSepia)
composer.addPass(clearMask)
composer.addPass(effectCopy)

To work with masks, we need to create EffectComposer in a slightly different manner. We need to set the stencilBuffer property of the internally used render targets to true. A stencil buffer, a special type of buffer, is used to limit the area of rendering. So, by enabling the stencil buffer, we can use our masks. Let’s look at the first three passes that are added. These three passes render the background, the Earth scene, and the Mars scene, as follows:

const bgRenderPass = new RenderPass(sceneBG, camera)
const earthRenderPass = new RenderPass(sceneEarth, camera)
earthRenderPass.clear = false
const marsRenderPass = new RenderPass(sceneMars, camera)
marsRenderPass.clear = false

There’s nothing new here, except that we set the clear property of two of these passes to false. If we don’t do this, we’ll only see the output from the marsRenderPass render, since it will clear everything before it starts rendering.

If you look back at the code for EffectComposer, the next three passes are marsMask, effectColorify, and clearMask. First, we’ll look at how these three passes are defined:

const marsMask = new MaskPass(sceneMars, camera)
const effectColorify = new ShaderPass(ColorifyShader)
effectColorify.uniforms['color'].value.setRGB(0.5, 0.5, 1)
const clearMask = new ClearMaskPass()

The first of these three passes is MaskPass. When creating a MaskPass object, you pass in a scene and a camera, just as you did for RenderPass. A MaskPass object will render this scene internally, but instead of showing this on screen, it will use the rendered internal scene to create a mask. When a MaskPass object is added to EffectComposer, all of the subsequent passes will be applied only to the mask defined by MaskPass, until a ClearMaskPass step is encountered. In this example, this means that the effectColorify pass, which adds a blue glow, is only applied to the objects rendered in sceneMars.

We use the same approach to apply a sepia filter to the Earth object. We first create a mask based on the Earth scene and use this mask in EffectComposer. After using MaskPass, we add the effect that we want to apply (effectSepia in this case), and, once we’re done with that, we add ClearMaskPass to remove the mask again.

The last step for this specific EffectComposer is one that we’ve already seen. We need to copy the final result to the screen, and we once again use the effectCopy pass for that. With this setup, we can apply the effects that we want to be a part of the total screen. Be aware, though, that these effects are applied to a part of the rendered image if the Mars scene and the Earth scene overlap.

The effects of both will be applied to that part of the screen:

Figure 11.10 – When masks overlap, both effects are applied

There is one additional property that’s interesting when working with MaskPass, and that’s the inverse property. If this property is set to true, the mask is inverted. In other words, the effect is applied to everything but the scene passed into MaskPass. This is shown in the following screenshot, where we set the inverse property of earthMask to true:

Figure 11.11 – When masks overlap, both effects are applied

Before we move on to a discussion of ShaderPass, we’re going to look at two passes that provide a more advanced effect: BokehPass and SSAOPass.

With the BokehPass, you can add a bokeh effect to your scene. In a bokeh effect, only part of the scene is in focus, and the rest of the scene looks blurry. To see this effect in action, you can open the bokeh.html example:

Figure 11.12 – An unfocussed bokeh effect

When you open it, initially, the whole scene will look blurry. With the Bokeh controls on the right, you can set the focus value to the part of the scene that you want to have in focus, and play around with the aperture property to determine the size of the area that should be in focus. By sliding the focus, you can have the set of cubes in the foreground in focus, as follows:

Figure 11.13 – Bokeh focussed on the first set of cubes

Alternatively, if we slide the focus further, we can focus on the red cubes:

Figure 11.14 – Bokeh focussed on the second set of cubes

And, if we slide the focus even further, we can focus on the set of green cubes at the far end of the scene:

Figure 11.15 – Bokeh focussed on the third set of cubes

BokehPass can be used just like the other passes we’ve seen so far:

const params = {
focus: 10,
aspect: camera.aspect,
aperture: 0.0002,
maxblur: 1
};
const renderPass = new RenderPass(scene, camera);
const bokehPass = new BokehPass(scene, camera, params)
bokehPass.renderToScreen = true;
const composer = new EffectComposer(renderer);
composer.addPass(renderPass);
composer.addPass(bokehPass);

Achieving the desired result might require some fine-tuning of the properties.

In Chapter 10, Loading and Working with Textures, we discussed using a pre-baked ambient occlusion map (aoMap) to directly apply shadows, based on ambient lighting. Ambient occlusion involves the shadows and light intensity variations that you see on objects, since not all parts of an object receive the same amount of ambient light. Besides using aoMap on the material, it is also possible to use a pass on EffectComposer to get the same effect. If you open the ambient-occlusion.html example, you will see the result of using SSAOPass:

Figure 11.16 – An AO pass applied

A similar scene, without the application of an ambient occlusion filter, appears to be really flat, as follows:

Figure 11.17 – The same scene without the AO pass

Note though that if you use this, you have to keep an eye on the overall performance of your application, since this is a very GPU-intensive pass.

Until now, we’ve used the standard passes provided by Three.js for our effects. Three.js also provides THREE.ShaderPass, which can be used for custom effects and comes with a large number of shaders that you can use and experiment with.

With THREE.ShaderPass, we can apply a large number of additional effects to our scene by passing in a custom shader. Three.js comes with a set of shaders that can be used together with this THREE.ShaderPass. They will be listed in this section. We’ve divided this section into three parts.

The first set involves simple shaders. All of these shaders can be viewed and configured by opening up the shaderpass-simple.html example:

  • BleachBypassShader: This creates a bleach bypass effect. With this effect, a silver-like overlay will be applied to the image.
  • BlendShader: This isn’t a shader that you apply as a single postprocessing step, but it allows you to blend two textures together. You can, for instance, use this shader to smoothly blend the rendering of one scene into another (not shown in shaderpass-simple.html).
  • BrightnessContrastShader: This allows you to change the brightness and contrast of an image.
  • ColorifyShader: This applies a color overlay to the screen. We’ve seen this one already, in the mask example.
  • ColorCorrectionShader: With this shader, you can change the color distribution.
  • GammaCorrectionShader: This applies a gamma correction to the rendered scene. This uses a fixed gamma factor of 2. Note that you can also set the gamma correction directly on THREE.WebGLRenderer by using the gammaFactor, gammaInput, and gammaOutput properties.
  • HueSaturationShader: This allows you to change the hue and saturation of the colors.
  • KaleidoShader: This adds a kaleidoscope effect to the scene that provides radial reflection around the center of the scene.
  • LuminosityShader and LuminostyHighPassShader: This provides a luminosity effect, where the luminosity of the scene is shown.
  • MirrorShader: This creates a mirror effect for part of the screen.
  • PixelShader: This creates a pixelated effect.
  • RGBShiftShader: This shader separates the red, green, and blue components of a color.
  • SepiaShader: This creates a sepia-like effect on the screen.
  • SobelOperatorShader: This provides edge detection.
  • VignetteShader: This applies a vignette effect. This effect shows dark borders around the center of the image.

Next, we’ll look at the shaders that provide a couple of blur-related effects. These effects can be experimented with through the shaderpass-blurs.html example:

  • HorizontalBlurShader and VerticalBlurShader: These apply a blur effect to the complete scene.
  • HorizontalTiltShiftShader and VerticalTiltShiftShader: These recreate a tilt-shift effect. With the tilt-shift effect, it is possible to create scenes that look miniature by making sure that only part of the image is sharp.
  • FocusShader: This is a simple shader that results in a sharply rendered center area with blurring along its borders.

Finally, there are a number of shaders that we won’t look at in detail; we are listing them simply for the sake of completeness. These shaders are mostly used internally, by either another shader or the shader passes that we discussed at the beginning of this chapter:

  • THREE.FXAAShader: This shader applies an anti-aliasing effect during the postprocessing phase. Use this if applying anti-aliasing during rendering is too expensive.
  • THREE.ConvolutionShader: This shader is used internally by the BloomPass render pass.
  • THREE.DepthLimitedBlurShader: This is used internally by SAOPass for ambient occlusion.
  • THREE.HalftoneShader: This is used internally by HalftonePass.
  • THREE.SAOShader: This provides ambient occlusion in shader form.
  • THREE.SSAOShader: This provides an alternative approach to ambient occlusion in shader form.
  • THREE.SMAAShader: This provides anti-aliasing to the rendered scene.
  • THREE.ToneMapShader: This is used internally by AdaptiveToneMappingPass.
  • UnpackDepthRGBAShader: This can be used to visualize encoded depth values from an RGBA texture as a visual color.

If you look through the Shaders directory of the Three.js distribution, you might notice a couple of other shaders that we haven’t listed in this chapter. These shaders – FresnelShader, OceanShader, ParallaxShader, and WaterRefractionShader – aren’t shaders that can be used for postprocessing, but they should be used with the THREE.ShaderMaterial object that we discussed in Chapter 4, Working with Three.js Materials.

We will start with a couple of simple shaders.

To experiment with the basic shaders, we’ve created an example where you can play around with most of the shaders and see the effects directly in the scene. You can find this example at shaders.html. The following screenshots show some of the effects.

The BrightnessContrastShader effect is as follows:

Figure 11.18 – The BrightnessContractShader effect

The SobelOperatorShader effect detects outlines:

Figure 11.19 – The SobelOperatorShader effect

You can create a kaleidoscope effect using KaleidoShader:

Figure 11.20 – The KaleidoShader effect

You can mirror parts of the scene with MirrorShader:

Figure 11.21 – The MirrorShader effect

The RGBShiftShader effect looks like this:

Figure 11.22 – The RGBShiftShader effect

You can play around with the luminosity in the scene with LuminosityHighPassShader:

Figure 11.23 – The LuminosityHighPassShader effect

To see the other effects, use the menu on the right to see what they do and how they can be configured. Three.js also provides a couple of shaders that are specifically used to add blurring effects. Those are shown in the next section.

Again in this section, we won’t dive into the code; we’ll just show you the results of the various blur shaders. You can experiment with these by using the shaders-blur.html example. The first two shaders shown are HorizontalBlurShader and VerticalBlurShader:

Figure 11.24 – HorizontalBlurShader and VerticalBlurShader

Another blur-like effect is provided by HorizontalTiltShiftShader and VerticalTiltShiftShader. This shader doesn’t blur the complete scene, only a small area. This provides an effect called tilt-shift. This is often used to create miniature-like scenes from normal photographs. The following screenshot shows this effect:

Figure 11.25 – HorizontalTiltShiftShader and VerticalTiltShiftShader

And the last of the blur-like effects is provided by FocusShader:

Figure 11.26 – FocusShader

So far, we’ve used the shaders provided by Three.js. However, it is also possible to write your own shaders for use with THREE.EffectComposer.

In this section, you’ll learn how to create a custom shader that you can use in postprocessing. We’ll create two different shaders. The first one will convert the current image to a grayscale image, and the second one will convert the image to an 8-bit image by reducing the number of colors that are available.

Vertex and fragment shaders

Creating vertex and fragment shaders is a very broad subject. In this section, we will only touch the surface of what can be done by these shaders and how they work. For more in-depth information, you can find the WebGL specification at http://www.khronos.org/webgl/. An additional resource, full of examples, is Shadertoy, available at https://www.shadertoy.com, or The Book of Shaders: https://thebookofshaders.com/.

To create a custom shader for Three.js (and also for other WebGL libraries), you have to create two components: a vertex shader and a fragment shader. The vertex shader can be used to change the position of individual vertices, and the fragment shader can be used to determine the colors of individual pixels. For a postprocessing shader, we only need to implement a fragment shader, and we can keep the default vertex shader provided by Three.js.

An important point to make before looking at the code is that GPUs support multiple shader pipelines. This means that the vertex shaders run in parallel on multiple vertices at the same time, and the same goes for the fragment shaders.

Let’s start by looking at the complete source code for the shader that applies a grayscale effect to our image (custom-shader.js):

export const CustomGrayScaleShader = {
uniforms: {
tDiffuse: { type: 't', value: null },
rPower: { type: 'f', value: 0.2126 },
gPower: { type: 'f', value: 0.7152 },
bPower: { type: 'f', value: 0.0722 }
},
// 0.2126 R + 0.7152 G + 0.0722 B
// vertexshader is always the same for postprocessing
steps
vertexShader: [
'varying vec2 vUv;',
'void main() {',
'vUv = uv;',
'gl_Position = projectionMatrix * modelViewMatrix *
vec4( position, 1.0 );',
'}'
].join('\n'),
fragmentShader: [
// pass in our custom uniforms
'uniform float rPower;',
'uniform float gPower;',
'uniform float bPower;',
// pass in the image/texture we'll be modifying
'uniform sampler2D tDiffuse;',
// used to determine the correct texel we're working on
'varying vec2 vUv;',
// executed, in parallel, for each pixel
'void main() {',
// get the pixel from the texture we're working with
(called a texel)
'vec4 texel = texture2D( tDiffuse, vUv );',
// calculate the new color
'float gray = texel.r*rPower + texel.g*gPower +
texel.b*bPower;',
// return this new color
'gl_FragColor = vec4( vec3(gray), texel.w );',
'}'
].join('\n')
}

An alternative way of defining shaders

In Chapter 4, we showed how to define the shaders in separate standalone files. In Three.js, most shaders follow the structure seen in the previous code fragment. Both methods can be used to define the code of the shaders.

As you can see in the preceding code block, this isn’t JavaScript. When you write shaders, you write them in the OpenGL Shading Language (GLSL), which looks a lot like the C programming language. More information on GLSL can be found at http://www.khronos.org/opengles/sdk/docs/manglsl/.

First, let’s look at the vertex shader:

vertexShader: [
'varying vec2 vUv;',
'void main() {',
'vUv = uv;',
'gl_Position = projectionMatrix * modelViewMatrix *
vec4( position, 1.0 );',
'}'
].join('\n'),

For postprocessing, this shader doesn’t really need to do anything. The preceding code is the standard way that Three.js implements a vertex shader. It uses projectionMatrix, which is the projection from the camera, together with modelViewMatrix, which maps an object’s position into the world position, in order to determine where to render a vertex on screen. For postprocessing, the only interesting thing in this piece of code is that the uv value, which indicates which texel to read from a texture, is passed on to the fragment shader using the varying vec2 vUv variable.

This can be used to get the pixel to modify in the fragment shader. Now, let’s look at the fragment shader and see what the code is doing. We will start with the following variable declaration:

'uniform float rPower;',
'uniform float gPower;',
'uniform float bPower;',
'uniform sampler2D tDiffuse;',
'varying vec2 vUv;',

Here, we can see four instances of the uniform property. The instances of the uniform property have values that are passed in from JavaScript to the shader, which are the same for each fragment that is processed. In this case, we pass in three floats, identified by type float (which are used to determine the ratio of a color to include in the final grayscale image), and a texture (tDiffuse) is also passed in, identified by type tDiffuse. This texture contains the image from the previous pass from the EffectComposer instance. Three.js makes sure this texture gets passed to this shader when tDiffuse is used as its name. We can also set the other instances of the uniform property from JavaScript by ourselves. Before we can use these uniforms from JavaScript, we have to define which uniform properties we want to expose to JavaScript. This is done as follows, at the top of the shader file:

uniforms: {
"tDiffuse": { type: "t", value: null },
"rPower": { type: "f", value: 0.2126 },
"gPower": { type: "f", value: 0.7152 },
"bPower": { type: "f", value: 0.0722 }
},

At this point, we can receive configuration parameters from Three.js, which will provide the output of the current rendering. Let’s look at the code that will convert each pixel to a gray pixel:

"void main() {",
"vec4 texel = texture2D( tDiffuse, vUv );",
"float gray = texel.r*rPower + texel.g*gPower +
texel.b*bPower;", "gl_FragColor = vec4( vec3(gray),
texel.w );"

What happens here is that we get the correct pixel from the passed-in texture. We do this by using the texture2D function, where we pass in our current image (tDiffuse) and the location of the pixel (vUv) that we want to analyze. The result is a texel (a pixel from a texture) that contains a color and an opacity (texel.w). Next, we use the r, g, and b properties of this texel to calculate a gray value. This gray value is set to the gl_FragColor variable, which is eventually shown on the screen. And, with that, we have our own custom shader. This shader is used in the same way that we’ve already seen a couple of times in this chapter. First, we just need to set up EffectComposer, as follows:

const effectCopy = new ShaderPass(CopyShader)
effectCopy.renderToScreen = true
const grayScaleShader = new ShaderPass
(CustomGrayScaleShader)
const gammaCorrectionShader = new ShaderPass
(GammaCorrectionShader)
const composer = new EffectComposer(renderer)
composer.addPass(new RenderPass(scene, camera))
composer.addPass(grayScaleShader)
composer.addPass(gammaCorrectionShader)
composer.addPass(effectCopy)

We call composer.render() in the render loop. If we want to change the properties of this shader at runtime, we can just update the uniforms property that we’ve defined, as follows:

shaderPass.uniforms.rPower.value = ...;
shaderPass.uniforms.gPower.value = ...;
shaderPass.uniforms.bPower.value = ...;

The result can be seen in custom-shaders-scene.html. The following screenshot shows this example:

Figure 11.27 – A custom grayscale filter

Let’s create another custom shader. This time, we’ll reduce the 24-bit output to a lower bit count.

Normally, colors are represented as a 24-bit value, which gives us about 16 million different colors. In the early days of computing, this wasn’t possible, and the colors were often represented as 8- or 16-bit colors. With this shader, we’ll automatically transform our 24-bit output to a color depth of 4 bits (or anything that you want).

Since the vertex shader is the same as in our previous example, we’ll skip the vertex shader and directly list the definition of the uniforms property:

uniforms: {
"tDiffuse": { type: "t", value: null },
"bitSize": { type: "i", value: 4 }
}

The fragmentShader code is as follows:

fragmentShader: [
'uniform int bitSize;',
'uniform sampler2D tDiffuse;',
'varying vec2 vUv;',
'void main() {',
'vec4 texel = texture2D( tDiffuse, vUv );',
'float n = pow(float(bitSize),2.0);',
'float newR = floor(texel.r*n)/n;',
'float newG = floor(texel.g*n)/n;',
'float newB = floor(texel.b*n)/n;',
'gl_FragColor = vec4( vec3(newR,newG,newB), 1.0);',
'}'
].join('\n')

We define two instances of the uniform property, which can be used to configure this shader. The first one is what Three.js uses to pass in the current screen, and the second one is defined by us as an integer (type:"i") and serves as the color depth that we want to render the result in. The code itself is very straightforward:

  1. First, we get texel from the tDiffuse texture, based on the passed-in vUv location of the pixel.
  2. We calculate the number of colors that we can have, based on the bitSize property, by calculating 2 to the power of bitSize (pow(float(bitSize),2.0))).
  3. Next, we calculate the new value of the color of texel by multiplying this value by n, rounding it off (floor(texel.r*n)), and dividing it again by n.
  4. The result is set to gl_FragColor (red, green, and blue values and the opacity) and shown on the screen.

You can view the result for this custom shader in the same example as our previous custom shader, custom-shaders-scene.html. The following screenshot shows this example, where we set the bit size to 4. This means the model is rendered in only 16 colors:

Figure 11.28 – A custom bit filter

That’s it for this chapter on postprocessing.

We discussed many different postprocessing options in this chapter. As you saw, creating EffectComposer and chaining passes together is actually very easy. You just have to keep a few things in mind. Not all passes will have an output on the screen. If you want to output to the screen, you can always use ShaderPass with CopyShader. The sequence in which you add passes to a composer is important. The effects are applied in that sequence. If you want to reuse the result from a specific EffectComposer instance, you can do so by using TexturePass. When you have more than one RenderPass in your EffectComposer, make sure to set the clear property to false. If not, you’ll only see the output from the last RenderPass step. If you want to only apply an effect to a specific object, you can use MaskPass. When you’re done with the mask, clear the mask with ClearMaskPass. Besides the standard passes provided by Three.js, there are also many standard shaders available. You can use these together with ShaderPass. Creating custom shaders for postprocessing is very easy, using the standard approach from Three.js. You only have to create a fragment shader.

We have now covered pretty much everything there is to know about the core of Three.js. In Chapter 12, Adding Physics and Sounds to Your Scene, we’ll look at a library called Rapier.js, which you can use to extend Three.js with physics, in order to apply collisions, gravity, and constraints.