Shaders in three.js

Shader Material

Last class we looked at how to build and add meshes to a scene in three.js. Remember that a mesh is made up of a geometry and a material.

Just like in p5.js, three.js has many materials which have built-in shaders. We have been using MeshBasicMaterial, but there is also MeshNormalMaterial, MeshMatcapMaterial, MeshStandardMaterial, … each with its own parameters and requirements. We can change the material we use in our mesh to change its appearance.

We can also make our own material using our own custom shaders with a RawShaderMaterial. Much like in p5.js, this material takes two parameters, one for the vertex and the other for the fragment pass of the program.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* eslint-disable no-undef, no-unused-vars, import/first */

// Page styles are defined in index.html.

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

// Create renderer.
const canvas = document.querySelector("#canvas");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Create scene.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292f33);

// Create camera.
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = -2;
scene.add(camera);

// Add mouse controls for camera.
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;

// Create groups and objects.
const group = new THREE.Group();
scene.add(group);

import vertShader from "./shaders/uv.vert";
import fragShader from "./shaders/uv.frag";

const sphereGeo = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
});
const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
group.add(sphereMesh);

// Animation loop.
const tick = () => {
  group.rotation.x += 0.01;
  group.rotation.y += 0.02;

  controls.update();

  renderer.render(scene, camera);

  requestAnimationFrame(tick);
};
tick();

// Window resize listener.
window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});

Looking at the vertex shader, you will notice a few differences in the built-in variables compared to p5.js.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

attribute vec3 position;
attribute vec2 uv;

varying vec2 vUv;

void main()
{
    vec4 modelPos = vec4(position, 1.0);
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * modelPos;

    vUv = uv;
}
  • The uniforms for the model and view matrices are not combined.
  • The MVP (model view projection) matrices are named modelMatrix, viewMatrix, and projectionMatrix.
  • The position attribute is named position.
  • The texture coordinate attribute is named uv.

And that’s it! Otherwise, the shaders should look pretty familiar.

Textures

There are a few ways to load images, but the easiest is to use the TextureLoader. This ensures two things:

  • That the image is loaded asynchronously, without freezing the app.
  • That the texture object is ready to use even before the image is fully loaded.

Basically, no need for a preload() function or a progress callback. A single TextureLoader can be used to load many textures in the same app.

1
2
const textureLoader = new THREE.TextureLoader();
const earthTex = textureLoader.load("/textures/terrain.jpg");

We can then pass the texture to the shader as a uniform, by adding it to a uniforms object when creating the material.

1
2
3
4
5
6
7
const sphereMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
  uniforms: {
    uTerrainMap: { value: earthTex }
  }
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* eslint-disable no-undef, no-unused-vars, import/first */

// Page styles are defined in index.html.

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

// Create renderer.
const canvas = document.querySelector("#canvas");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Create scene.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292f33);

// Create camera.
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = -2;
scene.add(camera);

// Add mouse controls for camera.
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;

// Load textures.
const textureLoader = new THREE.TextureLoader();
const earthTex = textureLoader.load(sketchFile0);

// Create groups and objects.
const group = new THREE.Group();
scene.add(group);

import vertShader from "./shaders/earth.vert";
import fragShader from "./shaders/earth.frag";

const sphereGeo = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
  uniforms: {
    uTerrainMap: { value: earthTex }
  }
});
const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
group.add(sphereMesh);

// Animation loop.
const tick = () => {
  group.rotation.x += 0.01;
  group.rotation.y += 0.02;

  controls.update();

  renderer.render(scene, camera);

  requestAnimationFrame(tick);
};
tick();

// Window resize listener.
window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});

import sketchFile0 from "../textures/terrain.jpg";

Because the shaders are nearly identical, we can bring in some of the concepts we learned for p5.js into our three.js sketches. Let’s bring in the noise functions and map them to the sphere using the texture coordinate attributes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
precision mediump float;

varying vec2 vUv;

// Some useful functions
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }

//
// Description : GLSL 2D simplex noise function
//      Author : Ian McEwan, Ashima Arts
//  Maintainer : ijm
//     Lastmod : 20110822 (ijm)
//     License :
//  Copyright (C) 2011 Ashima Arts. All rights reserved.
//  Distributed under the MIT License. See LICENSE file.
//  https://github.com/ashima/webgl-noise
//
float snoise(vec2 v) {

    // Precompute values for skewed triangular grid
    const vec4 C = vec4(0.211324865405187,
                        // (3.0-sqrt(3.0))/6.0
                        0.366025403784439,
                        // 0.5*(sqrt(3.0)-1.0)
                        -0.577350269189626,
                        // -1.0 + 2.0 * C.x
                        0.024390243902439);
                        // 1.0 / 41.0

    // First corner (x0)
    vec2 i  = floor(v + dot(v, C.yy));
    vec2 x0 = v - i + dot(i, C.xx);

    // Other two corners (x1, x2)
    vec2 i1 = vec2(0.0);
    i1 = (x0.x > x0.y)? vec2(1.0, 0.0):vec2(0.0, 1.0);
    vec2 x1 = x0.xy + C.xx - i1;
    vec2 x2 = x0.xy + C.zz;

    // Do some permutations to avoid
    // truncation effects in permutation
    i = mod289(i);
    vec3 p = permute(
            permute( i.y + vec3(0.0, i1.y, 1.0))
                + i.x + vec3(0.0, i1.x, 1.0 ));

    vec3 m = max(0.5 - vec3(
                        dot(x0,x0),
                        dot(x1,x1),
                        dot(x2,x2)
                        ), 0.0);

    m = m*m ;
    m = m*m ;

    // Gradients:
    //  41 pts uniformly over a line, mapped onto a diamond
    //  The ring size 17*17 = 289 is close to a multiple
    //      of 41 (41*7 = 287)

    vec3 x = 2.0 * fract(p * C.www) - 1.0;
    vec3 h = abs(x) - 0.5;
    vec3 ox = floor(x + 0.5);
    vec3 a0 = x - ox;

    // Normalise gradients implicitly by scaling m
    // Approximation of: m *= inversesqrt(a0*a0 + h*h);
    m *= 1.79284291400159 - 0.85373472095314 * (a0*a0+h*h);

    // Compute final noise value at P
    vec3 g = vec3(0.0);
    g.x  = a0.x  * x0.x  + h.x  * x0.y;
    g.yz = a0.yz * vec2(x1.x,x2.x) + h.yz * vec2(x1.y,x2.y);
    return 130.0 * dot(m, g);
}

void main()
{
    gl_FragColor = vec4(vec3(snoise(vUv * 10.0)), 1.0);
}

Blob O’clock

Let’s animate a blob like movement on our sphere using vertex displacement.

We can use the three.js Clock to get a running time value. We will pass this in as the uniform variable uTime. Because this value needs to change every frame, we will also update it in our tick() function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* eslint-disable no-undef, no-unused-vars, import/first */

// Page styles are defined in index.html.

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

// Create renderer.
const canvas = document.querySelector("#canvas");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Create scene.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292f33);

// Create camera.
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = -2;
scene.add(camera);

// Add mouse controls for camera.
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;

// Load textures.
const textureLoader = new THREE.TextureLoader();
const earthTex = textureLoader.load(sketchFile0);

// Create groups and objects.
const group = new THREE.Group();
scene.add(group);

import vertShader from "./shaders/earth.vert";
import fragShader from "./shaders/earth.frag";

const sphereGeo = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
  uniforms: {
    uTerrainMap: { value: earthTex },
    uTime: { value: 0.0 },
  },
});
const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
group.add(sphereMesh);

// Animation loop.
const clock = new THREE.Clock();

const tick = () => {
  sphereMat.uniforms.uTime.value = clock.getElapsedTime();

  //group.rotation.x += 0.01;
  //group.rotation.y += 0.02;

  controls.update();

  renderer.render(scene, camera);

  requestAnimationFrame(tick);
};
tick();

// Window resize listener.
window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});

import sketchFile0 from "../textures/terrain.jpg";

Let’s move the noise functions to the vertex shaders, then calculate a position offset using the uv as input to the noise function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void main()
{
    vec4 modelPos = vec4(position, 1.0);

    float elevation = snoise(uv + uTime * 2.0) * 0.2;
    modelPos.xyz += elevation;

    gl_Position = projectionMatrix * viewMatrix * modelMatrix * modelPos;

    vUv = uv;
}

This is starting to look interesting but there are a couple of problems that stand out:

  • There is a seam in the sphere where the mesh is split and we can see inside of it.
  • The noisy movement is two-dimensional, which you notice more if you increase the offset scale.

Mesh Normals

These two issues can be resolved by using a different attribute as input to the noise function.

  • Noise requires continous input to give continuous output. The seam occurs because as we wrap around our sphere, we reach the end of our UVs values and jump from 1.0 back to 0.0.
  • The “2D” movement occurs because we are moving all our points in the same plane, even though they are spread across the surface of the sphere. We need a way to add a direction to the movement that corresponds to the vertex position on the sphere.

This is where using normals can come in handy. A normal is a 3D vector representing the direction a vertex is facing. It is perpendicular to the surface position of the vertex.

Normals are automatically added as vertex attributes when using built-in geometries in three.js. We can access them using the normal variable. Each vertex has a normal (along with a position and a uv).

A normal represents a direction, and this means by definition that it is a unit vector, i.e. that its length is 1.0. This is useful for many reasons but for our case, it means we can also use it as a color value. Any normal vector will have the values of its xyz components somewhere in the [-1, 1] range, so we just need to convert that to [0, 1] range to use as a color.

Like all other attributes, it is accessible in the vertex shader, and we can pass it to the fragment shader using a varying variable to color our sphere.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

attribute vec3 position;
attribute vec3 normal;

varying vec3 vNormal;

void main()
{
    vec4 modelPos = vec4(position, 1.0);
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * modelPos;

    vNormal = normal;
}

We can see that the normal value is a continuous gradient around the sphere. There are no hard cuts, so if we use this as input in our noise function, we should get a blob with no seams in it.

We will also multiply the noise displacement by our normal which will reorient the displacement so that it is aligned with the surface. This will resolve the 2D movement issue.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;

uniform float uTime;

varying vec2 vUv;

// Some useful functions
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }

//
// Description : GLSL 2D simplex noise function
//      Author : Ian McEwan, Ashima Arts
//  Maintainer : ijm
//     Lastmod : 20110822 (ijm)
//     License :
//  Copyright (C) 2011 Ashima Arts. All rights reserved.
//  Distributed under the MIT License. See LICENSE file.
//  https://github.com/ashima/webgl-noise
//
float snoise(vec2 v) {

    // Precompute values for skewed triangular grid
    const vec4 C = vec4(0.211324865405187,
                        // (3.0-sqrt(3.0))/6.0
                        0.366025403784439,
                        // 0.5*(sqrt(3.0)-1.0)
                        -0.577350269189626,
                        // -1.0 + 2.0 * C.x
                        0.024390243902439);
                        // 1.0 / 41.0

    // First corner (x0)
    vec2 i  = floor(v + dot(v, C.yy));
    vec2 x0 = v - i + dot(i, C.xx);

    // Other two corners (x1, x2)
    vec2 i1 = vec2(0.0);
    i1 = (x0.x > x0.y)? vec2(1.0, 0.0):vec2(0.0, 1.0);
    vec2 x1 = x0.xy + C.xx - i1;
    vec2 x2 = x0.xy + C.zz;

    // Do some permutations to avoid
    // truncation effects in permutation
    i = mod289(i);
    vec3 p = permute(
            permute( i.y + vec3(0.0, i1.y, 1.0))
                + i.x + vec3(0.0, i1.x, 1.0 ));

    vec3 m = max(0.5 - vec3(
                        dot(x0,x0),
                        dot(x1,x1),
                        dot(x2,x2)
                        ), 0.0);

    m = m*m ;
    m = m*m ;

    // Gradients:
    //  41 pts uniformly over a line, mapped onto a diamond
    //  The ring size 17*17 = 289 is close to a multiple
    //      of 41 (41*7 = 287)

    vec3 x = 2.0 * fract(p * C.www) - 1.0;
    vec3 h = abs(x) - 0.5;
    vec3 ox = floor(x + 0.5);
    vec3 a0 = x - ox;

    // Normalise gradients implicitly by scaling m
    // Approximation of: m *= inversesqrt(a0*a0 + h*h);
    m *= 1.79284291400159 - 0.85373472095314 * (a0*a0+h*h);

    // Compute final noise value at P
    vec3 g = vec3(0.0);
    g.x  = a0.x  * x0.x  + h.x  * x0.y;
    g.yz = a0.yz * vec2(x1.x,x2.x) + h.yz * vec2(x1.y,x2.y);
    return 130.0 * dot(m, g);
}

void main()
{
    vec4 modelPos = vec4(position, 1.0);

    float elevation = snoise(normal.xy + uTime * 2.0) * 0.1;
    modelPos.xyz += normal * elevation;

    gl_Position = projectionMatrix * viewMatrix * modelMatrix * modelPos;

    vUv = uv;
}

GUI

We can use the lil-gui package for drawing a GUI and adjusting parameters on the fly. It’s simple to add to a project and use, so let’s add it to our sketch to modify the noise and offset scales.

We first need to import the package at the top of the file:

1
import GUI from 'lil-gui'

Then we create a gui object. This is where we will add all the parameter sliders.

1
const gui = new GUI();

Finally, we add the parameters using the add() function. We can also set the range with min() and max(), the step with step(), and a custom name with name(). It’s all pretty self-explanatory; the only unintuitive command is in the add() function, where we need to pass the entire object hierarchy as an object until the last node (which is passed in as a string). For example, if we want to modify the value of sphereMat.uniforms.uNoiseScale.value, we would pass sphereMat.uniforms.uNoiseScale as the first parameter, and "value" as the second parameter.

1
2
3
4
5
6
gui
  .add(sphereMat.uniforms.uNoiseScale, "value")
  .min(0)
  .max(5)
  .step(0.01)
  .name("noise scale");
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* eslint-disable no-undef, no-unused-vars, import/first */

// Page styles are defined in index.html.

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import GUI from 'lil-gui'

// Create debug GUI.
const gui = new GUI();

// Create renderer.
const canvas = document.querySelector("#canvas");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Create scene.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292f33);

// Create camera.
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = -2;
scene.add(camera);

// Add mouse controls for camera.
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;

// Load textures.
const textureLoader = new THREE.TextureLoader();
const earthTex = textureLoader.load(sketchFile0);

// Create groups and objects.
const group = new THREE.Group();
scene.add(group);

import vertShader from "./shaders/earth.vert";
import fragShader from "./shaders/earth.frag";

const sphereGeo = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
  uniforms: {
    uTerrainMap: { value: earthTex },
    uTime: { value: 0.0 },
    uNoiseScale: { value: 2.0 },
    uOffsetScale: { value: 0.1 }
  }
});
const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
group.add(sphereMesh);

gui
  .add(sphereMat.uniforms.uNoiseScale, "value")
  .min(0)
  .max(5)
  .step(0.01)
  .name("noise scale");
gui
  .add(sphereMat.uniforms.uOffsetScale, "value")
  .min(0)
  .max(1)
  .step(0.01)
  .name("offset scale");

// Animation loop.
const clock = new THREE.Clock();

const tick = () => {
  sphereMat.uniforms.uTime.value = clock.getElapsedTime();

  group.rotation.x += 0.01;
  group.rotation.y += 0.02;

  controls.update();

  renderer.render(scene, camera);

  requestAnimationFrame(tick);
};
tick();

// Window resize listener.
window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});

import sketchFile0 from "../textures/terrain.jpg";

Vertex Manipulation

Let’s combine everything we’ve learned to build a scene where our planet will travel in and out of a portal, and as it gets near the center it will get gradually more warped.

We will create a mesh using a TorusGeometry and add it to our group. We will use a MeshNormalMaterial on the torus, and will not need a custom shader for it. This material essentially does what we did when we converted our normal to a color earlier on this page.

We will also move our planet back and forth using a sin wave. We will do this in the tick() function so that the position is updated every frame.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
/* eslint-disable no-undef, no-unused-vars, import/first */

// Page styles are defined in index.html.

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import GUI from "lil-gui";

// Create debug GUI.
const gui = new GUI();

// Create renderer.
const canvas = document.querySelector("#canvas");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Create scene.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292f33);

// Create camera.
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = -5;
scene.add(camera);

// Add mouse controls for camera.
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;

// Load textures.
const textureLoader = new THREE.TextureLoader();
const earthTex = textureLoader.load(sketchFile0);

// Create groups and objects.
const group = new THREE.Group();
scene.add(group);

const ringGeo = new THREE.TorusGeometry(1.0, 0.05, 16, 64);
const ringMat = new THREE.MeshNormalMaterial();
const ringMesh = new THREE.Mesh(ringGeo, ringMat);
group.add(ringMesh);

import vertShader from "./shaders/earth.vert";
import fragShader from "./shaders/earth.frag";

const sphereGeo = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
  uniforms: {
    uTerrainMap: { value: earthTex },
    uTime: { value: 0.0 },
    uNoiseScale: { value: 2.0 },
    uOffsetScale: { value: 0.1 },
  },
});
const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
group.add(sphereMesh);

gui
  .add(sphereMat.uniforms.uNoiseScale, "value")
  .min(0)
  .max(5)
  .step(0.01)
  .name("noise scale");
gui
  .add(sphereMat.uniforms.uOffsetScale, "value")
  .min(0)
  .max(1)
  .step(0.01)
  .name("offset scale");

// Animation loop.
const clock = new THREE.Clock();

const tick = () => {
  const elapsedTime = clock.getElapsedTime();

  sphereMat.uniforms.uTime.value = elapsedTime;

  sphereMesh.position.z = Math.sin(elapsedTime);
  sphereMesh.rotation.x += 0.03;

  // group.rotation.x += 0.01;
  // group.rotation.y += 0.02;

  controls.update();

  renderer.render(scene, camera);

  requestAnimationFrame(tick);
};
tick();

// Window resize listener.
window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});

import sketchFile0 from "../textures/terrain.jpg";

We know the ring is at the origin (0, 0, 0) so we can assume the planet goes through the ring when its position is near (0, 0, 0). We will update the vertex shader to calculate an offset amount for each vertex based on how far it is from the origin.

  • We will use the GLSL distance() function to get this distance from the origin.
  • We will write our own version of the p5.js map() in GLSL to remap this distance to a value in the range [0.0, uOffsetScale].
  • We can clamp the mapped value to the range using the GLSL clamp() function to make sure we don’t go out of bounds.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;

uniform float uTime;
uniform float uNoiseScale;
uniform float uOffsetScale;

varying vec2 vUv;

// Some useful functions
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }

//
// Description : GLSL 2D simplex noise function
//      Author : Ian McEwan, Ashima Arts
//  Maintainer : ijm
//     Lastmod : 20110822 (ijm)
//     License :
//  Copyright (C) 2011 Ashima Arts. All rights reserved.
//  Distributed under the MIT License. See LICENSE file.
//  https://github.com/ashima/webgl-noise
//
float snoise(vec2 v) {

    // Precompute values for skewed triangular grid
    const vec4 C = vec4(0.211324865405187,
                        // (3.0-sqrt(3.0))/6.0
                        0.366025403784439,
                        // 0.5*(sqrt(3.0)-1.0)
                        -0.577350269189626,
                        // -1.0 + 2.0 * C.x
                        0.024390243902439);
                        // 1.0 / 41.0

    // First corner (x0)
    vec2 i  = floor(v + dot(v, C.yy));
    vec2 x0 = v - i + dot(i, C.xx);

    // Other two corners (x1, x2)
    vec2 i1 = vec2(0.0);
    i1 = (x0.x > x0.y)? vec2(1.0, 0.0):vec2(0.0, 1.0);
    vec2 x1 = x0.xy + C.xx - i1;
    vec2 x2 = x0.xy + C.zz;

    // Do some permutations to avoid
    // truncation effects in permutation
    i = mod289(i);
    vec3 p = permute(
            permute( i.y + vec3(0.0, i1.y, 1.0))
                + i.x + vec3(0.0, i1.x, 1.0 ));

    vec3 m = max(0.5 - vec3(
                        dot(x0,x0),
                        dot(x1,x1),
                        dot(x2,x2)
                        ), 0.0);

    m = m*m ;
    m = m*m ;

    // Gradients:
    //  41 pts uniformly over a line, mapped onto a diamond
    //  The ring size 17*17 = 289 is close to a multiple
    //      of 41 (41*7 = 287)

    vec3 x = 2.0 * fract(p * C.www) - 1.0;
    vec3 h = abs(x) - 0.5;
    vec3 ox = floor(x + 0.5);
    vec3 a0 = x - ox;

    // Normalise gradients implicitly by scaling m
    // Approximation of: m *= inversesqrt(a0*a0 + h*h);
    m *= 1.79284291400159 - 0.85373472095314 * (a0*a0+h*h);

    // Compute final noise value at P
    vec3 g = vec3(0.0);
    g.x  = a0.x  * x0.x  + h.x  * x0.y;
    g.yz = a0.yz * vec2(x1.x,x2.x) + h.yz * vec2(x1.y,x2.y);
    return 130.0 * dot(m, g);
}

float map(float inVal, float inMin, float inMax, float outMin, float outMax)
{
    return ((inVal - inMin) / (inMax - inMin) * (outMax - outMin) + outMin);
}

void main()
{
    vec4 modelPos = vec4(position, 1.0);

    float centerDist = distance(modelPos.xyz, vec3(0.0));
    float offsetAmount = clamp(map(centerDist, 0.5, 2.0, uOffsetScale, 0.0), 0.0, uOffsetScale);

    float elevation = snoise(normal.xz + uTime * uNoiseScale) * offsetAmount;
    modelPos.xyz += normal * elevation;

    gl_Position = projectionMatrix * viewMatrix * modelMatrix * modelPos;

    vUv = uv;
}

World Position

The “blobbiness” of the planet does not seem to be changing. Let’s debug the value of the offset scale to figure out if it behaving as expected. We can’t print the value to the console, or step through our code, so we will need another way to preview our value.

Let’s pass the calculated offset scale as a varying variable to the fragment shader and use it to color our sphere. It should be black when it is at the origin and gradually get lighter as it moves away from it. We will remap the value before saving it to make sure it stays in the range [0.0, 1.0].

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;

uniform float uTime;
uniform float uNoiseScale;
uniform float uOffsetScale;

varying vec2 vUv;
varying float vOffset;

// Some useful functions
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }

//
// Description : GLSL 2D simplex noise function
//      Author : Ian McEwan, Ashima Arts
//  Maintainer : ijm
//     Lastmod : 20110822 (ijm)
//     License :
//  Copyright (C) 2011 Ashima Arts. All rights reserved.
//  Distributed under the MIT License. See LICENSE file.
//  https://github.com/ashima/webgl-noise
//
float snoise(vec2 v) {

    // Precompute values for skewed triangular grid
    const vec4 C = vec4(0.211324865405187,
                        // (3.0-sqrt(3.0))/6.0
                        0.366025403784439,
                        // 0.5*(sqrt(3.0)-1.0)
                        -0.577350269189626,
                        // -1.0 + 2.0 * C.x
                        0.024390243902439);
                        // 1.0 / 41.0

    // First corner (x0)
    vec2 i  = floor(v + dot(v, C.yy));
    vec2 x0 = v - i + dot(i, C.xx);

    // Other two corners (x1, x2)
    vec2 i1 = vec2(0.0);
    i1 = (x0.x > x0.y)? vec2(1.0, 0.0):vec2(0.0, 1.0);
    vec2 x1 = x0.xy + C.xx - i1;
    vec2 x2 = x0.xy + C.zz;

    // Do some permutations to avoid
    // truncation effects in permutation
    i = mod289(i);
    vec3 p = permute(
            permute( i.y + vec3(0.0, i1.y, 1.0))
                + i.x + vec3(0.0, i1.x, 1.0 ));

    vec3 m = max(0.5 - vec3(
                        dot(x0,x0),
                        dot(x1,x1),
                        dot(x2,x2)
                        ), 0.0);

    m = m*m ;
    m = m*m ;

    // Gradients:
    //  41 pts uniformly over a line, mapped onto a diamond
    //  The ring size 17*17 = 289 is close to a multiple
    //      of 41 (41*7 = 287)

    vec3 x = 2.0 * fract(p * C.www) - 1.0;
    vec3 h = abs(x) - 0.5;
    vec3 ox = floor(x + 0.5);
    vec3 a0 = x - ox;

    // Normalise gradients implicitly by scaling m
    // Approximation of: m *= inversesqrt(a0*a0 + h*h);
    m *= 1.79284291400159 - 0.85373472095314 * (a0*a0+h*h);

    // Compute final noise value at P
    vec3 g = vec3(0.0);
    g.x  = a0.x  * x0.x  + h.x  * x0.y;
    g.yz = a0.yz * vec2(x1.x,x2.x) + h.yz * vec2(x1.y,x2.y);
    return 130.0 * dot(m, g);
}

float map(float inVal, float inMin, float inMax, float outMin, float outMax)
{
    return ((inVal - inMin) / (inMax - inMin) * (outMax - outMin) + outMin);
}

void main()
{
    vec4 modelPos = vec4(position, 1.0);

    float centerDist = distance(modelPos.xyz, vec3(0.0));
    float offsetAmount = clamp(map(centerDist, 0.5, 2.0, uOffsetScale, 0.0), 0.0, uOffsetScale);

    float elevation = snoise(normal.xz + uTime * uNoiseScale) * offsetAmount;
    modelPos.xyz += normal * elevation;

    gl_Position = projectionMatrix * viewMatrix * modelMatrix * modelPos;

    vUv = uv;
    vOffset = map(offsetAmount, 0.0, uOffsetScale, 1.0, 0.0);
}

The color remains black throughout the entire cycle, so something is wrong…

The issue is that we are calculating the offset using the “local” model position. We are looking at the vertex position on the surface of the sphere and not taking the sin wave movement into consideration.

In order to get the correct position value, we need to use the “global” (aka world) space position. We can get this by multiplying the model position by the model matrix. Once we have this position, we can use that to calculate the distance from the origin.

Note that since we have already calculated our world position, we can use it directly instead of modelMatrix * modelPos in our gl_Position calculation.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;

uniform float uTime;
uniform float uNoiseScale;
uniform float uOffsetScale;

varying vec2 vUv;
varying float vOffset;

// Some useful functions
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }

//
// Description : GLSL 2D simplex noise function
//      Author : Ian McEwan, Ashima Arts
//  Maintainer : ijm
//     Lastmod : 20110822 (ijm)
//     License :
//  Copyright (C) 2011 Ashima Arts. All rights reserved.
//  Distributed under the MIT License. See LICENSE file.
//  https://github.com/ashima/webgl-noise
//
float snoise(vec2 v) {

    // Precompute values for skewed triangular grid
    const vec4 C = vec4(0.211324865405187,
                        // (3.0-sqrt(3.0))/6.0
                        0.366025403784439,
                        // 0.5*(sqrt(3.0)-1.0)
                        -0.577350269189626,
                        // -1.0 + 2.0 * C.x
                        0.024390243902439);
                        // 1.0 / 41.0

    // First corner (x0)
    vec2 i  = floor(v + dot(v, C.yy));
    vec2 x0 = v - i + dot(i, C.xx);

    // Other two corners (x1, x2)
    vec2 i1 = vec2(0.0);
    i1 = (x0.x > x0.y)? vec2(1.0, 0.0):vec2(0.0, 1.0);
    vec2 x1 = x0.xy + C.xx - i1;
    vec2 x2 = x0.xy + C.zz;

    // Do some permutations to avoid
    // truncation effects in permutation
    i = mod289(i);
    vec3 p = permute(
            permute( i.y + vec3(0.0, i1.y, 1.0))
                + i.x + vec3(0.0, i1.x, 1.0 ));

    vec3 m = max(0.5 - vec3(
                        dot(x0,x0),
                        dot(x1,x1),
                        dot(x2,x2)
                        ), 0.0);

    m = m*m ;
    m = m*m ;

    // Gradients:
    //  41 pts uniformly over a line, mapped onto a diamond
    //  The ring size 17*17 = 289 is close to a multiple
    //      of 41 (41*7 = 287)

    vec3 x = 2.0 * fract(p * C.www) - 1.0;
    vec3 h = abs(x) - 0.5;
    vec3 ox = floor(x + 0.5);
    vec3 a0 = x - ox;

    // Normalise gradients implicitly by scaling m
    // Approximation of: m *= inversesqrt(a0*a0 + h*h);
    m *= 1.79284291400159 - 0.85373472095314 * (a0*a0+h*h);

    // Compute final noise value at P
    vec3 g = vec3(0.0);
    g.x  = a0.x  * x0.x  + h.x  * x0.y;
    g.yz = a0.yz * vec2(x1.x,x2.x) + h.yz * vec2(x1.y,x2.y);
    return 130.0 * dot(m, g);
}

float map(float inVal, float inMin, float inMax, float outMin, float outMax)
{
    return ((inVal - inMin) / (inMax - inMin) * (outMax - outMin) + outMin);
}

void main()
{
    vec4 modelPos = vec4(position, 1.0);

    vec4 worldPos = modelMatrix * modelPos;

    float centerDist = distance(worldPos.xyz, vec3(0.0));
    float offsetAmount = clamp(map(centerDist, 0.5, 2.0, uOffsetScale, 0.0), 0.0, uOffsetScale);

    float elevation = snoise(normal.xz + uTime * uNoiseScale) * offsetAmount;
    worldPos.xyz += normal * elevation;

    gl_Position = projectionMatrix * viewMatrix * worldPos;

    vUv = uv;
    vOffset = map(offsetAmount, 0.0, uOffsetScale, 1.0, 0.0);
}

We now see the color changing as expected! Now that our code is working, we can go back to using the texture as our sphere color.

Since we already have our offset scale value available in the fragment shader, we can use it to affect the color as well. Let’s pass in the normal value as a new varying variable, and mix the color between the texture and the normal based on this offset scale.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
precision mediump float;

uniform sampler2D uTerrainMap;

varying vec2 vUv;
varying vec3 vNormal;
varying float vOffset;

void main()
{
    vec4 texCol = texture2D(uTerrainMap, vUv);
    vec3 normCol = vNormal * 0.5 + 0.5;
    gl_FragColor = vec4(mix(normCol, texCol.rgb, vOffset), 1.0);
    //gl_FragColor = vec4(vec3(vOffset), 1.0);
}

Exercise

Build an animation of a ball bouncing on a paddle.

  • The ball movement should be done in the vertex shader, not in the tick() function.
  • Make sure the ball always stays on top of the paddle.
  • Add some squash and stretch to be extra fancy.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* eslint-disable no-undef, no-unused-vars, import/first */

// Page styles are defined in index.html.

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import GUI from "lil-gui";

// Create debug GUI.
const gui = new GUI();

// Create renderer.
const canvas = document.querySelector("#canvas");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Create scene.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292f33);

// Create camera.
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = -8;
scene.add(camera);

// Add mouse controls for camera.
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;

// Create groups and objects.
const group = new THREE.Group();
scene.add(group);
group.position.y -= 3.0;
group.rotation.x = THREE.MathUtils.degToRad(-90);

const paddleGeo = new THREE.CircleGeometry(1.0, 32);
const paddleMat = new THREE.MeshBasicMaterial({
  color: 0xd4605a,
  side: THREE.DoubleSide,
});
const paddleMesh = new THREE.Mesh(paddleGeo, paddleMat);
group.add(paddleMesh);

import vertShader from "./shaders/bounce.vert";
import fragShader from "./shaders/bounce.frag";

const ballGeo = new THREE.SphereGeometry(0.5, 32, 32);
const ballMat = new THREE.RawShaderMaterial({
  vertexShader: vertShader,
  fragmentShader: fragShader,
  uniforms: {
    uTime: { value: 0.0 },
    uColor: { value: new THREE.Color(0xeae3ce) },
    uBounceSpeed: { value: 4.0 },
    uBounceHeight: { value: 6.0 },
    uSquashStretch: { value: new THREE.Vector2(0.5, 2.0) },
  },
});
const ballMesh = new THREE.Mesh(ballGeo, ballMat);
group.add(ballMesh);

gui
  .add(ballMat.uniforms.uBounceSpeed, "value")
  .min(0)
  .max(10)
  .step(0.1)
  .name("bounce speed");
gui
  .add(ballMat.uniforms.uBounceHeight, "value")
  .min(0)
  .max(10)
  .step(0.1)
  .name("bounce height");
gui
  .add(ballMat.uniforms.uSquashStretch.value, "x")
  .min(0)
  .max(2)
  .step(0.01)
  .name("squash");
gui
  .add(ballMat.uniforms.uSquashStretch.value, "y")
  .min(0)
  .max(4)
  .step(0.01)
  .name("stretch");

// Animation loop.
const clock = new THREE.Clock();

const tick = () => {
  const elapsedTime = clock.getElapsedTime();

  ballMat.uniforms.uTime.value = elapsedTime;

  controls.update();

  renderer.render(scene, camera);

  requestAnimationFrame(tick);
};
tick();

// Window resize listener.
window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});