Raymarching, step by step
glint · Examples · Tutorials · Gallery
How a raymarcher works, one piece at a time: rays, distance functions, marching, normals, lighting, shadows, camera, repetition, fog; then boxes and tori, smooth blends, transforms, materials, ambient occlusion, reflections, bending space, speed and anti-aliasing.
A free interactive course of 20 steps in glint, a live shader editor in the browser: each step changes a running shader, and ticks itself when you've done its task.
1. The idea: ever-smaller spheres
Raymarching draws a 3D scene without any triangles. For each pixel, a ray goes out from the camera, and the question is simply: where does it first hit something?
The scene is described by a distance function: give it any point and it says how far away the nearest surface is. Not which way, just how far. So around the point there's a sphere of that radius with nothing inside it, and the ray can safely jump to the sphere's edge. Then ask again, jump again.
Far from everything the spheres are big and the ray covers ground fast. As it closes in on a surface, the spheres get smaller and smaller, until the distance is tiny: that's a hit. (That's why it's also called sphere tracing.) A ray that misses just takes bigger and bigger steps and leaves.
The picture is a side view, in 2D: the grey shapes are the scene, the orange dots are where the ray stops to ask, the blue circles are the empty spheres, and the white dot is the hit. The rest of the course builds exactly this in 3D.
Why not just walk along the ray in tiny equal steps and test each point? It works, but a step small enough not to skip thin objects (say 0.01) needs thousands of tests per pixel. Sphere tracing jumps whole units where it's safe, and most rays arrive in 20 to 80 steps.
Your turn: The ray only gets 3 tries: set STEPS to 30 and watch the circles shrink onto the surface.
2. One ray per pixel
Raymarching draws 3D scenes without triangles. For every pixel, shoot a ray from the camera through that pixel into the scene and find what it hits.
A ray is an origin ro (the camera) and a unit direction rd. Put the screen 1.5 units in front of the camera: the direction to this pixel's spot on it is vec3(p, 1.5), normalized. Points along the ray are ro + rd * t, where t is the distance travelled.
Nothing to hit yet, so the pixel shows its ray direction as a colour: it points left or right (red), up or down (green), and mostly forward (blue).
Worked example: the pixel in the middle of the screen has p = (0, 0), so its ray points along (0, 0, 1.5), which normalized is (0, 0, 1): straight ahead. A pixel at the top edge has p.y = 0.5: (0, 0.5, 1.5) normalized is about (0, 0.32, 0.95), tilted up by about 18°. So the screen spans roughly 37° from bottom to top. That's the field of view, and moving the screen closer (a smaller number) widens it.
Why normalize? Then t is a real distance along the ray in scene units, the same units the distance function answers in. Marching depends on that.
Your turn: Widen the field of view: move the screen closer, changing 1.5 to 0.8.
3. The scene is a distance function
The scene is described by one function, map(p): the distance from point p to the nearest surface. For a sphere of radius 1 at c that's length(p - c) - 1.0 (a signed distance: negative inside).
Here we look straight down at a slice through the scene (the plane y = 0) and colour it by map: blue outside with a ring every 0.25 units, orange inside. Rays will use these distances to know how far they can safely step.
Worked example: from the point (3, 0, 0), the sphere at the origin is length((3, 0, 0)) − 1 = 3 − 1 = 2 away. From (0.5, 0, 0) it's 0.5 − 1 = −0.5: half a unit inside.
The function has to be exact or an underestimate. If it ever said more than the real distance, a ray could jump straight through a surface. Every shape here keeps that promise; a later step shows what happens when bending space breaks it.
Your turn: Move the sphere to x = 1: length(p - vec3(1.0, 0.0, 0.0)) - 1.0.
4. Marching: step by the distance
Now the trick that gives raymarching (sphere tracing) its name. Standing at a point on the ray, map says nothing is closer than d, so we can move d along the ray without passing through anything. Repeat: at each new point ask again and step again.
Near a surface d gets tiny; once it's below 0.001 we call it a hit. If t gets very big, the ray missed. Each loop is one step: too few steps and rays give up before they arrive.
White is a hit, black a miss. With only 4 steps, only rays aimed straight at the sphere make it.
Worked example, a ray from (0, 0, −3) aimed straight at the sphere: the distance is 3 − 1 = 2, so jump 2 to z = −1, which is on the surface. A hit in one step. A ray that only just grazes the edge gets distances like 0.4, 0.2, 0.1, 0.05…, roughly halving each time: those rays need many steps.
The two limits matter: the step count is the worst-case cost per pixel, and the far distance (20 here) decides when a ray counts as sky.
Your turn: Give the rays more steps: change i < 4 to i < 64.
5. Seeing the cost, and adding shapes
Colour each pixel by how many steps its ray took. Rays that pass close to a surface without hitting it (along the edges) crawl with tiny steps: that's where the time goes, and why edges are where too few steps show first.
Combining shapes is just combining distances: min(a, b) is the union (the nearest of the two), max(a, b) the intersection, max(a, -b) cuts b out of a.
Reading the heat map: dark is cheap, bright is expensive. The sphere's edges glow because rays skim along the surface. With a floor, rays that miss the sphere hit the floor in a few steps instead of flying off.
max(a, -b) deserves a closer look: inside b, -b is positive, so max picks it and those points count as 'outside'. b is carved away. That's how you drill holes.
Your turn: Add a ground plane: the distance to the floor y = -1 is p.y + 1.0, so return min(sphere, p.y + 1.0).
6. Normals from the distance function
To light a surface we need its normal. The distance field gives it for free: the normal points the way map grows fastest (its gradient). Measure map a tiny step either side in x, y and z; the differences make a vector, and normalizing it gives the normal.
The picture shows normals as colours (n * 0.5 + 0.5): the floor faces up (green), the sphere's sides face left, right, up and towards us.
Why does this work? For a sphere of radius 1, length(p) - 1.0 grows fastest straight outwards: its gradient is p / length(p), which is exactly the sphere's normal. The six samples estimate that gradient numerically for any shape, no calculus needed.
The tiny step matters: too big (0.1) blurs small details, too small (0.000001) and floating-point rounding turns the normal into noise. 0.001 suits scenes a few units across.
Your turn: Squash the sphere into an ellipsoid-ish blob: divide by a scale, length(p / vec3(1.5, 0.7, 1.0)) - 1.0, and watch the normals follow.
7. Lighting
With a hit point and a normal, lighting is the dot product from the Maths course. Diffuse: max(dot(n, l), 0.0) with l the direction to the light. Specular (the shiny highlight): reflect the ray off the surface, reflect(rd, n), and see how close it points to the light, raised to a power for a small, sharp spot.
A little ambient light (0.1) keeps the shadowed side from being pure black.
Worked example: a floor facing straight up, n = (0, 1, 0), under a light straight above, l = (0, 1, 0): the dot is 1, fully lit. Move the light 60° away and the dot is cos 60° = 0.5, half as bright, because the same light now spreads over twice the area. Facing away gives a negative dot, clamped to 0: dark.
The 32 in the specular sets how glossy it looks: 8 is a broad, soft sheen, 128 a tight sparkle.
Your turn: Move the light round with time: vec3 l = normalize(vec3(sin(time), 1.0, cos(time)));
8. Shadows: march towards the light
Is a point in shadow? March a second ray from it towards the light: if it hits something on the way, the light is blocked. Start a little way off the surface (n * 0.01), or the ray hits the very surface it starts on and everything looks speckled (shadow acne).
Soft shadows come almost free: keep track of how close the shadow ray came to hitting something relative to how far it's gone (k * d / t). Near misses give partial shadow: a soft edge.
The soft-shadow score in numbers: a shadow ray that passes 0.1 from the sphere after travelling 2 units scores 8 × 0.1 / 2 = 0.4, so the point gets 40 % of the light. Further from the edge the score climbs past 1 (fully lit); closer, it falls to 0. The 8 sets the softness: bigger is sharper.
It's an approximation (real soft shadows come from lights that have a size), but it's cheap and looks right.
Your turn: Apply the shadow to the diffuse light: dif *= shadow(pos + n * 0.01, l);
9. A camera you can move
So far the camera sits at (0, 0, -3) looking along +z. To put it anywhere and look at anything, build its axes with cross products (Maths course, last step): forward to the target, right from forward and world-up, up from right and forward. mat3(r, u, f) * normalize(vec3(p, 1.5)) then aims each pixel's ray.
Orbiting is just moving ro round a circle with sin and cos while always looking at the middle.
Choosing the numbers: ro is where the camera stands and target is what it looks at. A camera a little higher than its target gives the classic 'looking down at a table' view.
The 1.5 is still the lens: smaller zooms out (wide angle), larger zooms in.
Your turn: Orbit the scene: vec3 ro = vec3(4.0 * sin(time * 0.5), 1.0, -4.0 * cos(time * 0.5));
10. Infinite repetition
Space can be folded before it's measured. mod(p + 1.0, 2.0) - 1.0 maps every point into a single 2×2×2 cell centred on the origin, so a sphere drawn once appears in every cell: infinitely many, for the price of one.
Fold only some axes to repeat in rows or planes. Folding breaks the distance a little at cell borders, which is why the step size is scaled by 0.8 here to stay safe.
In numbers: x = 2.6 becomes mod(2.6 + 1.5, 3.0) − 1.5 = 1.1 − 1.5 = −0.4, so the point is 0.4 left of the centre of its own cell, and gets measured against the one sphere in the middle of that cell.
floor((p.xz + 1.5) / 3.0) is the cell's number. It's handy for giving each copy its own colour, height or speed.
Your turn: Repeat the sphere in x and z: add vec3 q = p; q.xz = mod(q.xz + 1.5, 3.0) - 1.5; and measure the sphere with q instead of p.
11. Fog and gamma: the finishing touches
Far-off things fade into the air. Blend the surface colour towards the sky by distance: mix(col, sky, 1.0 - exp(-k * t * t)). The endless rows now melt into the horizon instead of ending in hard, flickering edges.
Last, gamma: screens darken mid-tones, and lighting maths assumes they don't. pow(col, vec3(1.0 / 2.2)) (or roughly sqrt(col)) at the very end corrects for it, and lighting looks natural instead of harsh. You now have every part of a real raymarcher.
Why exp(-k * t * t)? It's 1 close by and falls smoothly to 0 far away, slowly at first and then faster, like real haze. With k = 0.002, at 10 units a surface keeps exp(−0.2) ≈ 82 % of its colour; at 30 units, exp(−1.8) ≈ 17 %.
Gamma in numbers: a lit value of 0.5 is shown as 0.5^(1/2.2) ≈ 0.73. Without it, everything half-lit looks far too dark.
Your turn: Add fog before the gamma line: col = mix(col, sky, 1.0 - exp(-0.002 * t * t));
12. More shapes: boxes and tori
A sphere is easy: distance to the centre, minus the radius. A box needs a little thought. Fold space with abs(p) so only one corner of the box matters, then q = abs(p) - b measures how far past each face the point is (b is half the box's size).
Outside the box, the parts of q that are positive say how far beyond each face we are: length(max(q, 0.0)). Inside, all of q is negative and the nearest face is the largest of them: min(max(q.x, max(q.y, q.z)), 0.0). Add the two and you have sdBox.
Worked example, a box with b = (0.7, 0.7, 0.7) and the point (2, 0, 0): q = (1.3, −0.7, −0.7), so the outside part is length((1.3, 0, 0)) = 1.3: right, the face is at x = 0.7.
A torus (a doughnut) is a circle swept round another circle: in the flat plane its distance is length(p.xz) - R (how far from the big ring), and then it's a 2D circle of radius r around that: length(vec2(that, p.y)) - r.
Your turn: Put all the shapes in the scene: return min(ground, min(sphere, min(box, torus)));
13. Smooth blending
min(a, b) joins two shapes with a hard crease where they meet. smin (smooth minimum) melts them together instead, like wax or metaballs.
Away from the join, where a and b differ by more than k, smin is just min. Close to it, where they're nearly equal, it dips a little below both: k * h * (1 - h) with h = 0.5 at the middle, so the most it dips is k / 4. That dip is the fillet that fills the crease.
Worked example with k = 0.4: where both shapes are 0.1 away, min gives 0.1, but smin gives 0.1 − 0.4 × 0.25 = 0. The surface bulges out to meet that point.
The two spheres slide apart and together. k is the blend radius: 0.1 is a small fillet, 1.0 a big gooey merge.
Your turn: Melt the spheres together: return min(ground, smin(a, b, 0.4));
14. Moving and turning shapes
Distance functions describe shapes sitting at the origin. To move or turn one, don't move the shape: move the point the other way before measuring. p - c already does this for moving: measuring at p - c puts the shape at c.
Turning is the same idea with a rotation (see the Matrices course): q.xz = rot(time) * q.xz turns the point about the y axis, so the box appears to turn the opposite way. Rotations keep distances, so the box's distance stays exact.
Scaling is the one to watch: to make a shape s times bigger, measure at p / s and multiply the answer by s: sdBox(p / s, b) * s. Without the * s the distances are in the wrong units and rays overshoot or crawl.
Your turn: Turn the box: add q.xz = rot(time) * q.xz; before the box is measured.
15. Which object did we hit? Materials
So far the colour was chosen by position (below y = −0.99 means floor). That stops working with more objects. Instead, let map return two numbers: the distance, and which object it is: vec2(distance, id).
Combining becomes 'keep the pair with the smaller distance': a.x < b.x ? a : b. When the march hits, the id says which material to use. Here 0 is the floor, 1 the sphere and 2 the torus.
Everything that only needs distances (normals, shadows) just uses .x.
Your turn: Give the torus its own colour: add if (id > 1.5) albedo = vec3(0.2, 0.55, 1.0); after the sphere's line.
16. Ambient occlusion
Corners and creases get less light from the sky than open surfaces: the nearby geometry blocks it. That darkening is ambient occlusion, and distance fields make a cheap version easy.
From the hit point, take a few small steps out along the normal and ask map each time. On an open surface the distance grows exactly as fast as you step (at 0.1 out, map says 0.1). In a crease, something else is close, so map says less than you stepped. Add up the shortfalls: the bigger the total, the darker.
Worked example: 0.12 out from a corner, map says 0.05: a shortfall of 0.07. Weight the near samples more (they matter most), and subtract from 1.
Look at where the sphere meets the floor and inside the box's corner when it's on.
Your turn: Darken the ambient light in creases: amb *= ao(pos, n);
17. Reflections
A mirror shows what a ray would see after bouncing. We already have everything: from the hit point, reflect(rd, n) is the bounced direction, and march can trace it like any other ray.
How much of the reflection to show depends on the angle (the Fresnel effect): surfaces seen edge-on reflect much more than ones facing you. Look at a table top from above, then from low down, and you'll see it. pow(1 + dot(rd, n), 5) is a cheap version: 0 facing you, 1 edge-on.
The shade function lights one ray, so reflecting is just calling it again from the hit point. Each extra bounce costs another march.
Your turn: Show the reflection, more at grazing angles: col = mix(col, refl, 0.1 + 0.6 * fre);
18. Bending space, and what it costs
You can bend space before measuring, like the repetition step: twisting turns each height slice by a different angle, q.xz = rot(q.y * k) * q.xz. A tall box becomes a twisted column.
There's a price. Twisting stretches space, so map can now say a surface is further away than it really is, which breaks the promise from the start of the course. Rays overshoot, jump inside the shape, and you get holes and torn edges. Look closely at the column.
The fix: trust each distance a bit less. Stepping only 60 % of what map says (STEP = 0.6) keeps rays from overshooting, at the cost of more steps. The stronger the bend, the smaller the factor needs to be.
Your turn: Stop the overshooting: set const float STEP = 0.6;
19. Precision and speed
Far away, one pixel covers a lot of the scene: at 20 units, a pixel is about 0.02 units across. Insisting on getting within 0.001 of a surface out there is wasted effort: the ray crawls along in tiny steps for detail nobody can see.
So let the 'close enough' distance grow with how far the ray has gone: d < 0.0005 * t. At 2 units that's 0.001, as before; at 20 units it's 0.01. Distant rays stop much sooner, with no visible difference.
The picture is a heat map of steps again (bright = expensive), over an endless field of spheres. Watch the far rows go dark when you change it. The far limit (t > 60.0) and the step count are the other two speed controls.
Your turn: Let 'close enough' grow with distance: change d < 0.001 to d < 0.0005 * t.
20. Smooth edges: more rays per pixel
One ray per pixel decides each pixel all or nothing: the edge of a shape against the sky comes out as jagged steps. Real cameras average all the light landing on a pixel, so let's do the same: send several rays through slightly different spots inside each pixel and average their colours.
With AA = 2, each pixel gets a 2 × 2 grid of rays, each shifted by a fraction of a pixel. An edge pixel that's half shape, half sky comes out half and half: smooth.
It costs exactly AA × AA times as much (2 is 4×, 3 is 9×), so it's usually kept for final renders. glint's Save image and Render video can use it while the live view stays fast.
Your turn: Use 2 × 2 rays per pixel: const int AA = 2;
Other courses: Basics · Medium · Advanced · Maths for shaders · Matrices, from scratch · Sound you can see · Noise from scratch · Colour and light · Passes and feedback · Skies and reflections · Vertex shaders, step by step · Raymarching 2: glow, fog and light · Raymarching 3: worlds · Raymarching 4: modelling, materials and motion · Fractals, step by step · Vertex shaders 2: lines, particles and moving meshes · Fractals 2: further in · Vertex shaders 3: living geometry · Post-processing · Surfaces: from vertex to fragment · Blur and glow