LearnInto 3D

Lesson 22 of 30 · 55 min

Building 3D shapes

Combine boxes, tori and cylinders, and blend them smoothly into objects

In this lesson you will

  • Place 3D boxes (sdBox), tori (sdTorus), cylinders (sdCylinder) and capsules, and change their size and orientation
  • Rotate objects in 3D by rotating one plane at a time, as in q.xz = rot(-a) * q.xz
  • Combine shapes with union (min), intersection (max) and subtraction (max(a, -b)), and blend them with smin
  • Assemble parts into everyday objects like a snowman or a table, and color each part differently

01A workbench for 3D

Across Rays and cameras, Raymarching and Normals and lighting, we have collected every tool needed to draw a 3D scene. This lesson is about building things with those tools. Our scenes have had only balls and a floor; now we add boxes, doughnuts, cylinders and rods, and combine them into objects.

Every playground in this lesson shares the same base code. The final lighting from last lesson is wrapped up in a function called shade, so map is almost the only thing you will change.

  • map(p) … the shapes in the scene; the star of this lesson
  • calcNormal(p) and camera(ro, ta) … the same as in the last two lessons
  • shade(n, rd, albedo) … returns the surface color albedo lit by sun diffuse, sky ambient and a highlight
  • render … the 64-step raymarch, color choice, fog and gamma correction

02Boxes

The 3D box's distance function is the 2D sdBox from Drawing with distance with one more axis, z. It even keeps the name sdBox: GLSL picks the right version by the argument types (vec2 or vec3) on its own.

1

2

3

4

float sdBox(vec3 p, vec3 b) {

vec3 d = abs(p) - b;

return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);

}

  • b is half the box's size. vec3(0.8, 0.5, 0.5) makes a box 1.6 wide, 1.0 tall and 1.0 deep
  • abs(p) folds every point into the one corner at +x, +y, +z, since the box is symmetric in all three directions
  • Each component of d says how far outside the face in that direction you are. At p = (1.0, 0, 0), d = (0.2, -0.5, -0.5): 0.2 outside the x face, so the distance is 0.2
  • At p = (1.0, 0.7, 0), d = (0.2, 0.2, -0.5): near an edge. The distance is the length of the two outside components, √(0.04 + 0.04) ≈ 0.28
  • At the center, p = (0, 0, 0), d = (-0.8, -0.5, -0.5) is all negative (inside). The max part returns -0.5, the distance to the nearest face

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 ↗
▸Make the size vec3(0.3, 0.5, 1.2) for a box that runs away from you. Try sdBox(…, vec3(0.7, 0.4, 0.4)) - 0.1 to round the corners, just like in 2D

Rounding works just as in 2D: shrink the box by r, then subtract r from the distance. The surface swells out to distance r, so the edges round off with radius r. Real objects usually have slightly rounded edges, so a tiny rounding of about 0.02 makes things look much more real, because highlights catch on the rounded edges.

03Rotating in 3D

In 2D, Moving space turned a shape by a with p = rot(-a) * p. 3D uses the very same rot, in the same form: pick two of the three coordinates and rotate within that plane. The axis you didn't pick stays put and becomes the axis of rotation.

  • q.xz = rot(-a) * q.xz; … y is untouched: a turn of a around the vertical axis, like a top
  • q.yz = rot(-a) * q.yz; … x is untouched: a tip of a forward or back around the side-to-side axis, like a nod
  • q.xy = rot(-a) * q.xy; … z is untouched: a turn of a around the depth axis, like a steering wheel

Two cautions carry over from 2D. First, shift, then rotate. Use q = p - center to bring the object's center to the origin before rotating, or the object will swing in a wide arc around the origin. Second, rotating the coordinates turns the shape the opposite way, so to turn a shape by a, rotate the coordinates by rot(-a). The list above and this playground are both written that way. If you are just spinning things over time, the direction hardly matters.

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 ↗
▸Delete the q.xy line and it just spins like a top. What happens to the motion if you swap the q.xz and q.xy lines?

Tip

Rotation doesn't change a shape's size, so the distance stays exact. Unlike scaling in Moving space, there is no distance to correct.

04Tori, cylinders and capsules

The doughnut-shaped torus and the cylinder are both a 2D shape swept all the way around the vertical axis: a circle for the torus, a rectangle for the cylinder. So their distance functions first turn the 3D point into a point on a 2D cross-section, then use a 2D distance function.

1

2

3

4

5

6

7

8

float sdTorus(vec3 p, vec2 t) {

vec2 q = vec2(length(p.xz) - t.x, p.y); // the point on the cross-section

return length(q) - t.y; // distance to the cross-section circle

}

float sdCylinder(vec3 p, float r, float h) {

vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h); // the cross-section rectangle (2D sdBox)

return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));

}

  • length(p.xz) is the horizontal distance from the vertical (y) axis. It is the same in every direction around the axis, which is what makes the shape a sweep
  • For the torus, t.x is the ring radius and t.y the tube radius. With t = (1.0, 0.25), the point (1, 0, 0) is in the middle of the tube: q = (0, 0), distance -0.25. At the ring's center, (0, 0, 0), q = (-1, 0) and the distance is 1 - 0.25 = 0.75
  • For the cylinder, r is the radius and h is half the height. r = 0.5, h = 1.0 gives a cylinder 1 wide and 2 tall
  • Both are built around the y axis. To reorient one, swap axes with a swizzle, as in sdTorus(q.xzy, …). q.xzy swaps y and z, so a doughnut lying flat stands up on its edge

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

Starts when it scrolls into view
Open in /edit ↗
▸Change sdTorus(q.xzy, …) to sdTorus(q, …) and the torus lies down. Change the cylinder's 0.45, 0.6 to 0.8, 0.05 for a thin disk

One more very handy shape is the capsule. It is the segment distance function sdSegment from Combining shapes, written for vec3, with a thickness r subtracted. The result is a rod with rounded ends joining two points a and b. It suits any shape you'd describe as going from here to there: arms, legs, branches, the strokes of letters.

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

Starts when it scrolls into view
Open in /edit ↗
▸Set the elbow b to vec3(-0.5, 0.1, 0.5 * sin(time)) and the arm sways back and forth too. Make 0.14 and 0.1 equal for an even, wire-like thickness

05Union, intersection, subtraction

The three ways of combining shapes from Combining shapes in 2D work unchanged in 3D. Union is min(a, b) (inside either), intersection is max(a, b) (inside both), and subtraction is max(a, -b) (inside a and outside b). -b is b with inside and outside swapped, so it stands for "outside b".

Below is a classic example of combining 3D shapes. The intersection of a box and a sphere trims the box's corners into curves, then three cylinders along x, y and z are subtracted to bore holes through it. Notice how swizzles lay the y-axis cylinder on its side to make the other two directions.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change max(body, -holes) to max(box, -holes) or max(ball, -holes) to see what the intersection does. min(body, holes) makes the holes stick out instead

Watch out

Shapes made with intersection or subtraction report distances that are smaller than the truth in places. As we saw in Raymarching, too small is safe; it just costs a few more steps. Thin areas carved by subtraction are prone to holes if steps run short, though. If something looks off, check the heat map.

06Smooth blending

The smin from Drawing with distance works exactly the same in 3D. Use smin(a, b, k) instead of min, and the seam between two shapes smooths out as if you'd pressed clay together with your thumb. k is the width of the blend: shapes begin to merge once they come within k of each other.

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

Starts when it scrolls into view
Open in /edit ↗
▸At 0.05 they barely stick; at 0.6 they reach out and melt together from far apart. What if you also join the floor with smin?

Intersection and subtraction have smooth versions too. max(a, b) equals -min(-a, -b), so swapping in smin gives a smooth max. With it you can round the rims of carved holes, or soften the cut where two shapes overlap.

1

2

3

4

float smax(float a, float b, float k) { return -smin(-a, -b, k); }

 

float d1 = smax(box, ball, 0.1); // smooth intersection

float d2 = smax(box, -hole, 0.1); // smooth subtraction (rounded hole rims)

07Assembling an object

Let's put the parts together into an object: a snowman. The body is three spheres blended slightly with smin, the hat two cylinders, the nose and arms capsules, and the eyes and buttons small spheres. Writing a separate distance function per part keeps map readable: it just lines the parts up with min.

To color each part differently, measure each part's distance again at the hit point pos. The hit point lies on the surface of the part that was hit, so only that part's distance is close to 0. For example, if hat(pos) < 0.01, we hit the hat. A tidier method, returning a part number from map itself, comes in Materials and atmosphere.

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

Starts when it scrolls into view
Open in /edit ↗
▸Split hat(pos) < 0.01 into its own branch and give the snowman a red hat. Change the body's smin from 0.1 to 0.3 and the snowman starts to melt

More parts make map heavier, since it runs up to 64 times per pixel in the loop plus 6 more for the normal. A snowman like this is fine, but once you have dozens of parts, cut down the work with repetition (Infinite space and deformation) or with the symmetry trick in the next section.

08Symmetry with abs

A table has four legs, all the same shape, arranged symmetrically left-right and front-back. Rather than writing four legs, fold the coordinates with abs. After q.xz = abs(q.xz), a point with negative x gets the same coordinates as its positive twin, and the same goes for z. So one leg placed at +x, +z shows up in all four spots, as if reflected in mirrors. It is the same idea as the mirrored repetition in Repetition and tiles.

Concretely, abs(q.xz) - vec2(0.95, 0.55) folds the space and then shifts the leg position (0.95, 0.55) to the origin, where we place a cylinder. On the table sits a cup: a cylinder with a slightly smaller cylinder subtracted. The inner cylinder is shifted up a little, which leaves a bottom and an open top.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change vec2(0.95, 0.55) to vec2(0.5, 0.3) to pull the legs inward. Replace abs(q.xz) with vec2(abs(q.x), q.z) to fold only x: how many legs are left?

Tip

Folding with abs means only one leg is ever computed. It is lighter than combining four with min, and the code is shorter. Whenever you spot symmetry, like a left-right symmetric face or a machine with matching parts on every side, think of abs first.

09Exercises

Pick parts, combine them, color them: use this lesson's workflow to build some objects of your own.

Exercise 1

A jeweled ring

Stand a thin gold ring on its edge, spin it slowly around the vertical axis, and set a red gem (a sphere) on top. The gem turns together with the ring.

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

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

A mushroom

Build a mushroom: a red half-dome cap on a cream-colored stalk. Smooth the joint between stalk and cap with smin, and tilt the whole thing a little.

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 ↗
Exercise 3

A die

Turn a white rounded box into a real die. On the three visible faces, carve round, dark dimples by subtraction: one on top, two on the front, three on the right. The die rocks gently.

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

Starts when it scrolls into view
Open in /edit ↗

10Recap

  • The 3D sdBox is the 2D box plus z; b is half the size. Round it with sdBox(p, b - r) - r
  • Tori and cylinders are a 2D circle and rectangle swept around the y axis; length(p.xz) turns the point into a cross-section point. Reorient them with swizzles like q.xzy
  • A capsule is the distance to a 3D segment minus a thickness: a rod between two points
  • Rotate in 3D by picking two coordinates, as in q.xz = rot(-a) * q.xz (the shape turns by a). Shift first, then rotate
  • Union min, intersection max, subtraction max(a, -b), smooth union smin. Fold symmetric objects with abs
  • To color by part, re-measure each part's distance at the hit point and pick the one that is nearly 0

You can build a single object now. Next, in Infinite space and deformation, we repeat space itself to line objects up forever, and twist and bend it, turning one distance function into a whole landscape.

Finished lessons get a mark in the course contents