LearnInto 3D

Lesson 21 of 30 · 55 min

Normals and lighting

Find surface normals and shade with diffuse, specular and ambient light

In this lesson you will

  • Understand how calcNormal finds the surface direction (the normal) from the slope of the distance function, and check normals as colors
  • Give shapes depth with diffuse light from dot(n, l) and hemisphere ambient light from the sky
  • Add Blinn-Phong specular highlights (shine) and a rim light (edge glow)
  • Layer several colored lights and finish with gamma correction for natural brightness

01Which way does the surface face?

With Raymarching we could draw shapes, but coloring them by height or distance left them looking somewhat flat. Real objects look solid because light falls differently on each part. Surfaces facing the light are bright; surfaces turned away are dark.

For that, we need to know which way the surface faces at the hit point. An arrow of length 1, standing straight out from the surface, is called the normal, usually written n. For a floor it points straight up, (0, 1, 0); for a sphere it points from the center toward the hit point.

There is a way to find the normal for any shape. A distance function grows fastest when you move straight away from the surface, and barely changes when you move along it. So if we nudge the hit point a little along x, y and z and measure how much the distance grows each way, we learn the direction of fastest growth. That is the normal. Mathematicians call this direction of growth the gradient.

1

2

3

4

5

6

7

vec3 calcNormal(vec3 p) {

vec2 e = vec2(0.001, 0.0);

return normalize(vec3(

map(p + e.xyy) - map(p - e.xyy), // growth along x

map(p + e.yxy) - map(p - e.yxy), // growth along y

map(p + e.yyx) - map(p - e.yyx))); // growth along z

}

Place it after map, since it calls map
  • e.xyy is a swizzle, as in Knowing where you are: it means (0.001, 0, 0). e.yxy is (0, 0.001, 0) and e.yyx is (0, 0, 0.001)
  • Measuring on both the plus and minus sides and taking the difference is more accurate than one side alone (this is called a central difference)
  • The three differences are tiny numbers, but normalize scales the result to length 1, leaving only the direction
  • It calls map six times, but only once per pixel after the hit, which is cheap next to the 64-step loop

Let's check with numbers. On a radius-1 sphere at the origin, at the surface point (0.6, 0, 0.8), the x difference is about 0.0012, the y difference is 0 (by symmetry), and the z difference is about 0.0016. Normalizing (0.0012, 0, 0.0016) gives (0.6, 0, 0.8): exactly the direction from the center to the hit point.

02Normals as color

Before adding light, we check the normals with color. Just as we colored rd in Rays and cameras, n * 0.5 + 0.5 maps -1..1 to 0..1 for red, green and blue. The scene is a big ball and a small ball joined smoothly with smin, plus a floor.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change col = n * 0.5 + 0.5; to col = vec3(n.y * 0.5 + 0.5); to see just how much each part faces up, in grayscale. Change the 0.35 in smin to 0.01: how does the color change at the seam?
  • The whole floor faces up, (0, 1, 0), so it is the light green (0.5, 1.0, 0.5)
  • The right side of a ball faces +x and turns reddish; the left side faces -x, loses its red and turns teal
  • The front, facing us, points along -z, so its blue drops out and it nears the olive (0.5, 0.5, 0.0)
  • At the smin seam the color shifts smoothly instead of jumping: proof that the surface direction blends smoothly too

Tip

The normal-color view is the most trustworthy debugging tool in 3D. Whenever the lighting looks wrong, come back to it first. A grainy pattern means either map is inaccurate or the rays aren't reaching the surface.

03Diffuse light

With normals in hand, we can add light. Start with light arriving in parallel from far away, like the sun, and call the length-1 arrow pointing toward the light l. A surface that faces the light head-on is brightest, and one that catches it at a slant is darker. Shine a flashlight straight down at a desk and you get a small bright circle; tilt it and the same light spreads into a long, dimmer oval.

How far off head-on the light is: that is exactly the dot from Rays and cameras. dot(n, l) is 1 when the light hits straight on, 0.5 when tilted 60 degrees, and 0 from the side. For example, a floor with n = (0, 1, 0) lit from 45 degrees, l ≈ (0.71, 0.71, 0), has brightness about 0.71. On surfaces facing away from the light the value is negative, so max(…, 0.0) clamps it to 0. This is called diffuse light: the look of matte surfaces like paper or clay.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change the 0.8 in the light direction to 0.1 for low, sideways light like a setting sun. Set both cos(a) and -sin(a) to 0.0 for light from straight overhead

albedo is the surface's own color: the fraction of white light it sends back. The final color is the surface color times the light that reaches it. The floor's albedo is a gray checkerboard. As in the last lesson, we tell the floor apart by the hit point's height, store 0 or 1 in obj, and switch with mix.

The side facing away from the light is pitch black. In the real world, though, shade is almost never pure black, because the sky itself softly lights everything with blue light. That is what we add next.

04Hemisphere ambient light

The sky spreads overhead like a dome. So the more a surface faces up, the more sky it sees, and the more sky light it gets. A surface facing sideways sees half the sky; one facing down sees only the ground. A simple way to express this is 0.5 + 0.5 * n.y: 1 facing straight up, 0.5 facing sideways, 0 facing straight down. This is called hemisphere ambient light.

Lights get colors too: the sun a slightly warm white, the sky blue. Multiply each brightness by its light color, add them up, and finally multiply by the surface color. The unlit side picks up a faint blue tint, like a photo taken on a sunny day.

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

Starts when it scrolls into view
Open in /edit ↗
▸Set skyCol to vec3(0.5, 0.2, 0.4) and the shadows turn purple. Remove sunCol * dif to keep only sky light, and it looks like an overcast day

Tip

The underside of a ball has negative n.y, gets almost no sky light, and stays dark. In reality, light bouncing off the ground lights it a little from below. Adding a bit of clamp(-n.y, 0.0, 1.0) times the ground color imitates this bounce light. We use it in the final polish at the end of this lesson.

05Specular highlights

Look at a plastic or ceramic ball and you will see a small white reflection of the light source: a highlight. It appears where the surface bounces light like a mirror straight into your eye. If the surface faces exactly halfway between the direction to the light, l, and the direction to the eye, -rd, the incoming light bounces right into the eye.

We write this halfway direction as h = normalize(l - rd), the half vector: l plus -rd, scaled to length 1. The closer the normal n is to h, the stronger the highlight. Raising dot(n, h) to a high power with pow keeps only the values near 1, leaving a small spot of light. Where dot(n, h) is 0.95, the 8th power is about 0.66, the 32nd about 0.19, and the 128th almost 0. The bigger the exponent, the smaller and sharper the highlight, and the harder and more polished the surface looks. This is Blinn-Phong specular reflection.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change 32.0 to 4.0 for a soft, rubbery sheen, or 200.0 for the sharp glint of a polished marble

The highlight uses the light's color, not the surface color. On materials like plastic, light bounces off the very top of the surface, so the highlight takes the light source's color (nearly white here). Multiplying by dif keeps highlights off the unlit side, and multiplying by obj keeps the floor matte.

06Rim light

Films and photos often light a subject's outline thinly from behind to lift it off the background. This is called a rim light. In a shader you can fake it with a simple rule: the less a surface faces the viewer, the more it glows.

dot(n, -rd) tells how much a surface faces you: 1 at the center of a ball, which faces you squarely, and 0 at the outline, which faces sideways. 1.0 - dot(n, -rd) flips that: 0 at the center, 1 at the outline. Cubing it keeps only the area right by the outline: where dot(n, -rd) is 0.5 you get 0.125, and where it is 0.1, about 0.73.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change 3.0 to 1.0 to widen the glow, or 8.0 for a thin line. Remove * obj, and the distant floor lights up too. Why?

A rim light is less physically accurate light than staging for the viewer. It keeps an outline crisp even when a dark object sits in front of a dark background. It also looks natural, because real surfaces reflect more light when you view them at a shallow angle (the Fresnel effect), so edges often do look brighter.

07Layering colored lights

You can add as many lights as you like. As we saw in Your first shader, light gets brighter the more you add, and the colors mix. Each light needs the same math (diffuse plus highlight), so it is handy to wrap it in a function, light. Let's shine an orange light and a blue light from opposite sides.

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

Starts when it scrolls into view
Open in /edit ↗
▸Add a third light, col += light(n, rd, normalize(vec3(0.0, 1.0, 0.0)), vec3(0.6, 0.2, 0.5), albedo, obj);, for pink light from straight above

Making the objects nearly white lets the light colors show through as they are. Where both lights land, orange and blue add up toward white. Notice how, as with stage lighting, light color and direction alone transform the mood. Photographers call the strong light on the subject the key light and the weaker one softening shadows from the other side the fill light. Add a rim light to those two and you have "three-point lighting", a setup used constantly in 3D scenes too.

08Finishing with gamma correction

All our math so far has dealt directly in amounts of light: a dif of 0.5 means half the light. The screen, however, doesn't emit values as amounts of light. As we saw in Light and finishing, send 0.5 to the screen and the light it actually emits is 0.5 to the power 2.2, only about 0.22. So after the lighting math, we finish with gamma correction, pow(col, vec3(1.0 / 2.2)), to cancel out the screen's quirk. 0.5 rises to about 0.73, and 0.2 to about 0.48.

The preview below applies gamma correction to the right half of the screen only. On the left, brightness drops off abruptly from the lit side into shadow, and detail in the shade is crushed. On the right, light fades smoothly into dark and looks much more real.

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

Starts when it scrolls into view
Open in /edit ↗
▸Delete if (p.x > 0.0) to apply gamma correction to the whole screen

Gamma correction brightens everything, so colors and light strengths need choosing again. Before gamma, values are amounts of light, so the trick is to pick surface colors darker and more saturated than you'd expect, and keep the sky light weak. Finally, let's put everything together: the sun as key light, sky ambient, bounce light from the ground, highlights, rim light, fog, and gamma correction.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change the ball color vec3(0.75, 0.15, 0.06) to vec3(0.05, 0.3, 0.7) for a blue ball. Change the 0.6 in the light direction to 0.15 for long evening light
  • Do all lighting as amounts of light and add them up, then apply gamma once, at the very end. Applying it midway makes the sums come out wrong
  • Sunlight above 1 (1.3) is fine; bright light can have bright values. If blown-out whites bother you, apply tone mapping before gamma. The finishing order is the same as in Light and finishing: scene, exposure, tone mapping, vignette, gamma correction, grain
  • Mix in the fog (the sky color) in the same amount-of-light world, then gamma-correct
  • Basing the fog on t * t, as in 1.0 - exp(-t * t * 0.006), keeps nearby things clear and hazes only the distance: about 0.09 at t = 4 and about 0.91 at 20

Tip

The balls look as if they float a little above the floor because there are no shadows yet. Shadows, where something blocks the light, and ambient occlusion, where gaps and corners darken, are added in Shadows and depth.

09Exercises

Choose the direction, color and strength of the lights yourself and light up some scenes. Every exercise builds on the final code from this lesson.

Exercise 1

Light from the mouse

Make the light come from wherever the cursor is: from the right when the cursor is on the right, from above when it is near the top. When the cursor isn't over the preview (mouse is (0, 0)), light the scene from the front, slightly above.

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

Starts when it scrolls into view
Open in /edit ↗
Exercise 2

Three materials

Line up three balls and make them look, from left to right, like clay (no shine), plastic (a sharp white highlight) and gold (a gold-tinted highlight, weak diffuse). Tell which ball was hit by the hit point's pos.x.

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

Starts when it scrolls into view
Open in /edit ↗
Exercise 3

Lantern light (a point light)

Instead of a distant light like the sun, light the scene with a small lamp flying around inside it: a point light. The light direction differs at every point (from the hit point toward the lamp), and things get darker the farther they are from it. Make the lamp itself visible as a small glowing ball.

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

Starts when it scrolls into view
Open in /edit ↗

10Recap

  • The normal is the direction in which map grows, measured by nudging along x, y and z (calcNormal). Check it as a color with n * 0.5 + 0.5
  • Diffuse light is max(dot(n, l), 0.0). Hemisphere ambient is 0.5 + 0.5 * n.y times the sky color
  • Highlights use h = normalize(l - rd) and pow(max(dot(n, h), 0.0), exponent); a bigger exponent means a sharper highlight
  • Rim light is pow(1.0 - max(dot(n, -rd), 0.0), 3.0), a staging trick that lifts outlines
  • Color is surface color times the sum of the lights. Add as many lights as you like, and gamma-correct once at the end

You can now draw solid, lit objects. So far our scenes have been only balls and a floor. Next, in Building 3D shapes, we add boxes, tori, cylinders and more, and combine them into everyday objects.

Finished lessons get a mark in the course contents