LearnInto 3D
Lesson 20 of 30 · 55 min
Raymarching
Step along distance functions to draw 3D shapes
In this lesson you will
- Explain why shapes with no hit formula can still be drawn: knowing the distance lets you step safely
- Write the 3D distance functions
sdSphereand the floorp.y + h, and gather a scene into amapfunction - Write the 64-step raymarching loop, with its hit test and far cutoff
- Visualize the step count as color to find slow spots and trouble spots
- Recognize the causes of common failures: flat screens, stray bands of color, backgrounds that end too soon
01Shapes with no formula
In Rays and cameras we drew a floor and a sphere. Both worked because we could solve "how far does the ray go before it hits?" with algebra: one division for the floor, a quadratic equation for the sphere.
As soon as shapes get a little more complex, though, the algebra gets out of hand. A doughnut (a torus) needs a fourth-degree equation, and two spheres blended with the smin from Drawing with distance have no solvable formula at all. Solving an equation per shape quickly leads to a dead end.
So we change our thinking. Even when "where does it hit?" can't be solved, "how far is the nearest surface from where I am now?" is usually easy to compute. That is the distance function (SDF) you wrote many times in the 2D lessons. In this lesson we build raymarching: drawing shapes by stepping a ray forward bit by bit, guided only by a distance function. Every 3D lesson from here on is built on it.
02Distance functions in 3D
The 2D circle's distance function, sdCircle, was length(p) - r. The 3D sphere has exactly the same form; p just becomes a vec3. length works on a vec3 too, returning the square root of the sum of the three squares: the distance from the origin in 3D.
1
2
3
4
float sdSphere(vec3 p, float r) { return length(p) - r; }
// distance to a floor (a flat plane) at height -h
float ground = p.y + h;
sdSphere(p, 1.0)gives 3 - 1 = 2 atp = (0, 3, 0)(2 units outside), 0 atp = (0.6, 0, 0.8)since its length is exactly 1 (on the surface), and -0.5 atp = (0, 0.5, 0)(inside)- On a flat floor, the nearest point is always straight down, so the distance is simply the height difference
p.y + h. With the floor at height -1 (h = 1), a point aty = 2is 3 away, a point on the floor is 0, and points below it are negative - To move a shape, shift the coordinates, just as in 2D.
sdSphere(p - vec3(1.0, 0.0, 0.0), 0.5)is a sphere of radius 0.5 centered at(1, 0, 0)
A 3D distance function assigns one number to every point in space: the distance to the nearest surface. The screen is flat, so we can't see the whole volume at once, but we can look at a slice at some depth z, using the same contour-line picture as in the 2D lessons. Below, the slice position z slides back and forth over time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
cos(time * 0.8) * 1.2 with 0.6, and the circle's radius is √(1 - 0.36) = 0.8. What if the sphere's radius 1.0 becomes 0.5?When the slice passes through the sphere's middle (z = 0), you see a circle of radius 1. Toward the ends the circle shrinks, and once z passes 1 the slice misses the sphere and everything is outside (blue). The white line is the surface, where the distance is exactly 0. The stripes show that points far from the white line have distance values too. Those distances away from the surface are exactly what will guide raymarching.
03Stepping with spheres
Say we measure the distance function at some point on the ray and get back d. That is a promise: inside a ball of radius d around this point, there is no surface at all, since even the nearest one is d away. So whichever way the ray points, moving forward by d can never punch through anything.
So we move forward by d. At the new point we measure again, and move again. Repeat, and the ray takes big strides through empty space and smaller ones near a surface, homing in on it. When d gets very small (say, under 0.001), we call it a hit. A ray that hits nothing finds d growing at each step and races away, so we give up once it is far enough (say, t over 20). This method is called sphere tracing.
The preview below shows a side-on slice of a scene (a ball and a floor) with one ray's journey drawn in. The yellow dots are where the ray stopped, and the light-blue circles are the "safe spheres" measured there. Notice that each circle just touches a surface somewhere.
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
sin(time * 0.5) with 1.0 and the ray grazes just over the ball, leaving a crowd of tiny circles. With -1.0 it heads straight for the floorLet's follow one ray in numbers. The eye is at (0, 0, -3), a sphere of radius 1 sits at the origin, and the ray heads slightly to the right, rd ≈ (0.29, 0, 0.96).
- At
t = 0, we measured = 2.0and move 2.0 - At
t = 2.0,d ≈ 0.23. We are near the sphere and the step suddenly shrinks - At
t ≈ 2.23,d ≈ 0.08; att ≈ 2.31,d ≈ 0.03; att ≈ 2.34,d ≈ 0.015… each less than half the last - On the ninth measurement
ddrops below 0.001, and we call it a hit att ≈ 2.37
A ray aimed straight at the center lands exactly on the surface after its first step of d = 2, so it finishes after two measurements. A ray that just grazes the rim and misses, on the other hand, keeps taking tiny steps along the surface and needs nearly 40 measurements to get clear. The step count varies a lot from ray to ray.
04Writing the loop
Now let's turn this into a shader. We put the whole scene's distance function in a function called map and advance the ray in a for loop. This site caps loops at 64 iterations, so we stop after 64 steps.
1
2
3
4
5
6
7
float t = 0.0; // distance traveled
for (int i = 0; i < 64; i++) {
float d = map(ro + rd * t); // measure the distance here
if (d < 0.001 || t > 20.0) break; // a hit, or too far
t += d; // step forward by that much
}
// after the loop, t < 20.0 means a hit, at ro + rd * t
d < 0.001is the hit test. Waiting for exactly 0 would take forever, so close enough countst > 20.0is the far cutoff. We assume nothing lies beyond and use the sky colorbreakexits the loop early. Walking on after a hit is wasted work- A ray that uses up all 64 steps without hitting or passing the cutoff still has
t < 20.0, so it counts as a hit. It is usually right next to a surface, so that is nearly correct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
map to sdSphere(p - vec3(sin(time), 0.0, 0.0), 1.0) and the ball moves. Change 64 to 3 and the background turns black while the ball swells into a blur. Why? (The answer is in "Common failures".)It is the same picture as the sphere we drew last time by solving a quadratic. But this code contains no sphere equation anywhere. Swap out the body of map, and the same loop draws any shape.
05Gathering the scene in map
Let's add more objects. Combining several distance functions with min gives the distance to the nearest surface of any of them. It is exactly how you made unions with min in 2D. Here we min two balls and a floor inside map. As we saw in Drawing with distance, values combined by union, intersection and subtraction are never more than the true distance. Never overshooting the truth matters a great deal for raymarching; you will see why in "Common failures" below.
After a hit, we want a different color depending on what we hit. The floor is at height -1, so if the hit point pos has a pos.y of about -1 it is the floor; otherwise it is a ball. The floor gets last lesson's checkerboard, and the balls get a color based on height. Lighting comes next lesson, so the colors are still flat for now.
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
sdSphere(p - vec3(-1.6, -0.3, 0.5), 0.7), to map. Wrap one more min around itTip
The fog is a bit thicker than last time (0.12) because the floor is cut off at t = 20. If the fog is almost pure sky color by then, you can't see where the floor ends. Always think of the cutoff distance and the fog density as a pair.
You can use time inside map, too. Move a shape's position over time, and objects move in the scene. Let's also orbit the camera as in the last lesson. The loop and the coloring code don't change by a single character; only map and the camera do.
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
abs(sin(time * 3.0)) to abs(sin(time * 3.0)) * 2.0 for higher bounces. Make the big ball's radius 0.8 + 0.2 * sin(time * 2.0) and it pulses06Step counts as a heat map
We saw that the number of steps varies wildly between rays. Turning the count straight into a color shows at a glance where the steps are going. Count inside the loop, divide by 64 to get 0–1, and map it to a "heat" ramp of black → red → yellow → white. Using s * 3.0 as red, s * 3.0 - 1.0 as green and s * 3.0 - 2.0 as blue, each clamped to 0–1, gives red at s = 1/3, yellow at 2/3 and white at 1.
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
0.001 to 0.01 and everything darkens (fewer steps). Change 20.0 to 60.0: which parts of the sky get heavier?The fronts of the balls are dark: they are hit in a few steps. The bright areas are the balls' rims (rays grazing the surface) and the floor near the horizon. A ray looking at the distant floor travels almost parallel to it, so each step only shaves a little off its height, and it takes ages to arrive. White areas are rays that used up all 64 steps and may not truly have hit anything yet.
This heat map helps both when chasing performance and when something won't render right. If most of the screen is red or yellow, the scene is heavy, and it is time to rethink the step budget or how the scene is built. If the shape you care about shows up white, it may be getting holes from running out of steps.
Tip
Works on this site must render a frame within 8 ms. Raymarching costs roughly pixels × steps × the cost of map. Keeping the steps at 64 or fewer and map light is partly for that reason. Fast and small covers this in depth.
07Common failures
When a render goes wrong, the cause is usually one of a few familiar ones. Let's start with the one you will meet most: running out of steps. Below is the same scene as the heat map, with only the loop limit cut from 64 to 12.
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
12 back to 64 and it heals. How much of it is fixed at 24, or 40?A band of ball color appears near the horizon, and the balls grow a halo-like outline. Both sit where the heat map was bright: where steps pile up. Rays cut off after 12 steps are still hanging in mid-air, short of any surface. Their t is under 20, though, so they count as hits, and since their height isn't -1 they get the ball color instead of the floor's.
Here are the other symptoms you are likely to meet, with their usual causes. When stuck, the quickest route is to show the heat map, or t as a color, and see what is happening where.
- The screen is one flat color: the eye
rois inside a shape. The very firstdis negative, so the loop stops at once with a "hit". Flipping the floor's sign, as in-p.y - 1.0, does the same, because the space the eye is in becomes inside - Odd colors around shapes or at the horizon: not enough steps (as above). Raise the limit, or keep the scene compact and close
- Holes or a grainy surface:
mapreturns more than the true distance. It happens when you forget the rule from Moving space, "after shrinking withp / s, multiply the distance bys", or forgetnormalizesordis longer than 1. On a plain sphere it may barely show, but thin or deformed shapes get holes - The far floor ends abruptly: the cutoff (
t > 20.0) is too short for the scene. Hide it with thicker fog, or extend the distance - Shapes look swollen with blurry corners: the hit threshold (
0.001) is too large. At 0.1, rays stop 0.1 short of the surface
Watch out
If map returns values larger than the true distance, the ray can step outside its safe sphere and leap over a surface. Values that are smaller are safe: steps just get shorter and you need more of them. That is why a map built from unions, intersections and subtractions can be trusted. When twisting or bending a shape makes its distance inaccurate, a common fix is to deliberately multiply the distance by something like 0.5 to shorten the steps. Infinite space and deformation covers this in detail.
08Exercises
Rewrite map to build some scenes. You should barely need to touch the loop or the coloring.
Three orbiting balls
Make three balls (radius 0.4) circle the center on a ring of radius 1.5 above the floor, staying evenly spaced as they go.
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
3D metaballs
The smin from Drawing with distance works unchanged in 3D. Have two small balls wander around a big one and melt into it like droplets when they come close.
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
Fix the broken scene
This should be two balls sitting on a floor, but the screen is one flat color. There are three causes, and fixing one reveals the next symptom. Use the "Common failures" list and the heat map as clues, and fix them all.
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
09Recap
- A distance value
dpromises nothing lies within radiusd, so stepping forward bydcan't punch through anything - A 3D sphere is
length(p) - r; a floor at height -h isp.y + h. Gather the scene inmapwithmin - Loop for up to 64 steps;
d < 0.001is a hit,t > 20.0is the cutoff. Changemap, and the same loop draws any shape - Coloring by step count shows the heavy spots (rims, the horizon) and where the steps run out
- Distances that are too large cause holes; too small only costs speed
We can draw shapes now, but they still look flat because nothing lights them. Next, in Normals and lighting, we will find the surface direction (the normal) from the distance function and shade our shapes into solid, lit objects.
Finished lessons get a mark in the course contents