Raymarching 3: worlds
glint · Examples · Tutorials · Gallery
Whole places: terrain from a height, sky light, rock, grass and snow, haze towards the sun, water you see into and that reflects, less detail far away, clouds, glass, soap bubbles, light through thin parts, triplanar textures, rough rock, a different copy in every cell, limited repetition, a cave by lantern light, the Mandelbulb, a camera on a path and depth of field.
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. Terrain: a height is not a distance
The first two raymarching courses built scenes from shapes with exact distances. A landscape is easier to describe another way: a height for every (x, z) on the ground, here fractal noise (the Noise course builds it). A point is q.y - terrain(q.xz) above the ground: positive above, negative below.
Marching with that as if it were a distance mostly works. But on a slope, the ground ahead can be much closer than straight down: a point 1 above the ground can be 0.3 from a hillside in front. Step 1 and the ray goes straight through the hill. Look at the ridges: chunks missing, peaks sliced off.
The fix is to step less than the height says. Half is a common choice: twice the steps, but the steeper the slopes, the smaller the share needs to be.
Your turn: Take half steps: change t += d; to t += 0.5 * d;
2. Light from the whole sky
The landscape is now lit by the sun with soft shadows (the same kind as in Raymarching, step by step). But everything the sun can't reach is pitch black, which never happens outdoors: the whole blue sky lights the ground too, softly, from above.
A cheap stand-in for all that light: 0.5 + 0.5 * n.y, 1 for ground facing straight up, 0.5 for a wall, 0 facing down. Tinted sky-blue, it fills shadows with cool light and leaves the sunlit parts warm: the warm/cool split that makes outdoor light look right.
Your turn: In shade, before return col;, add the sky: col += albedo * vec3(0.35, 0.45, 0.65) * (0.5 + 0.5 * n.y) * 0.8;
3. Rock, grass and snow
Materials can come from where a point is and which way it faces, no textures needed. n.y is how flat the ground is (1 flat, 0 a cliff): grass only holds on flat ground, so smoothstep(0.78, 0.92, n.y) mixes from rock to grass as it flattens.
Snow lies high up, and more on flat ground than on steep: smoothstep(0.8, 1.2, pos.y + 0.6 * n.y) turns from 0 to 1 between heights 0.8 and 1.2, with flatter ground counting as higher. Right now snow is 0.
Your turn: Add the snow line: float snow = smoothstep(0.8, 1.2, pos.y + 0.6 * n.y);
4. Haze that knows where the sun is
Far away, air hides things in its own colour: the fog in the last line of main. But real haze isn't one colour: looking towards the sun it glows warm (light scattered towards you), and away from it it's blue.
So make the fog's colour depend on the ray's direction: dot(rd, SUN) is 1 looking straight at the sun. pow(…, 6.0) keeps the warm part to the sun's side of the sky. One line, and the landscape gets depth and a time of day.
Your turn: Make the fog warm towards the sun: vec3 fogCol = mix(vec3(0.5, 0.6, 0.75), vec3(1.0, 0.75, 0.5), pow(max(dot(rd, SUN), 0.0), 6.0));
5. Water that reflects
Where the land dips below 0, there's now water: a flat plane, found without marching (-ro.y / rd.y is where the ray reaches height 0). Its normal is tipped a little by moving noise, for ripples, and the ray bounces off it and is marched again over the land: refl is what the water reflects.
But it's mixed half-and-half with the dark deep colour everywhere, so the lake looks like grey plastic. Real water reflects almost nothing looking straight down and almost everything at a glancing angle: that's Fresnel. fresnel (Schlick's formula) is worked out already: 0.02 straight down, 1 skimming.
Your turn: Mix by it: col = mix(deep, refl, fresnel);
6. Seeing into the water
Near the shore you should see the bottom; out in the middle, only dark water. The light you see in water has come up from the bottom, and on the way it's absorbed: red first, then green, so deep water looks blue-green and then black.
The water block now also bends the ray into the water (refract, 1.33 for water), marches it down to the bottom (tb is how far it went through water), shades the ground it lands on and dims it by exp(-tb * vec3(2.2, 0.8, 0.5)): much more for red than for blue. That's under. But deep still ignores it.
Fresnel already does the rest: looking down you see deep, at a glancing angle the reflection.
Your turn: Use what's under the water: vec3 deep = under;
7. Less detail far away
Every height asks fractal noise for 10 octaves, finer and finer detail. Far away, the finest octaves are much smaller than a pixel: the work is spent on detail nobody can see (and it shimmers). And far-off pixels are the costly ones: those rays take the most steps.
So ask for fewer octaves the further away. Each octave's bumps are half the size of the last, and each time the distance doubles a pixel covers twice as much ground: so drop one octave per doubling. log2(1.0 + t) grows by 1 each time t doubles, so 11.0 - log2(1.0 + t), kept between 3 and 10, does it. Near the camera nothing changes.
Set SHOW_COST to true to see the noise lookups per pixel, before and after. The Profiler (Alt G) shows the time.
Your turn: In octavesFor: return int(clamp(11.0 - log2(1.0 + t), 3.0, 10.0));
8. Clouds: marching density
Clouds have no surface to hit, so there's nothing to march to. Instead the ray walks through the cloud layer in 40 even steps and, at each, asks how much cloud is there (density: 3D noise with a threshold so there are gaps).
Two things add up along the way. T is how much light from behind still gets through: each bit of cloud dims it (Beer's law, exp(-d * dt)), so thick cloud hides the sky. light is the cloud's own colour, added where there's cloud, dimmed by the cloud in front of it.
Now every bit of cloud is equally lit: flat, like cotton wool. A cloud's sunny side is bright and its far side grey because sunlight has to get through the cloud first. One look towards the sun tells you: the density a little way towards it. A lot there, little light arrives.
This pass draws at half resolution: clouds are soft and marching them is expensive.
Your turn: Shade them: float lit = exp(-density(q + SUN * 0.4) * 1.5);
9. Glass that bends light
Glass is see-through, but things behind it look moved and bent: light changes direction as it goes in and again coming out. refract(direction, normal, ratio) gives the new direction, the ratio being the two materials' indices of refraction (IOR).
So: march to the glass, bend the ray in, march through the inside (there the distance is negative, so step by -map), bend it out, and see what the world shows in that direction. Mix in the reflection by Fresnel, as with the water.
With IOR 1.0 nothing bends: the box is invisible, apart from faint reflections. When refract returns zero, the ray hit the inside too shallowly to get out (total internal reflection): it bounces instead, which is what makes cut glass and diamonds sparkle.
Your turn: Make it glass: const float IOR = 1.5;
10. Soap bubbles: colour from a thin film
A soap bubble has no colour of its own. Its skin is so thin (about a light wavelength) that light reflecting off its front and back surfaces interferes: some colours cancel, others add. Which ones depends on the thickness, and on the angle, since light crossing at a slant goes further through the film.
th is that: the film's thickness swirling with noise, plus more towards the edges. A cosine palette of it is a fair stand-in for the real interference colours, and they come in bands as the thickness changes, as on a real bubble.
The bubble itself is mostly see-through; the colours tint what it reflects (here, a dark room with three soft lights).
Your turn: Give the film its colours: vec3 film = 0.5 + 0.5 * cos(6.2832 * (th + vec3(0.0, 0.33, 0.67)));
11. Light through thin parts
Wax, skin, jade, leaves, ears against the light: light goes into them, scatters about and comes out somewhere else, more where they're thin. With the lamp behind these blobs they should glow at the thin edges and where they join, and stay dark in the thick middle.
Working that out properly is far too slow, but the distance field makes a guess cheap: step a little way into the surface (along -n) six times and add up how deep inside each point is. Thin parts give a small thick, thick parts a big one, and exp(-thick * 1.2) turns it into how much light gets through.
Scaling it by how directly we look towards the lamp makes it glow most against the light, as it does in life.
Your turn: Let the light through: float through = exp(-thick * 1.2) * (0.3 + 0.7 * max(dot(rd, LIGHT), 0.0));
12. Textures without UVs: triplanar
A raymarched shape has no texture coordinates (UVs): nobody unwrapped it. The easy way out is to use two of the position's coordinates: tex(pos.xz) projects the bricks straight down from above. Fine on top; on the walls, which face sideways, each brick is smeared into stripes.
Triplanar mapping projects three times, from the side (zy), the top (xz) and the front (xy), and blends them by how much the surface faces each way (abs(n), raised to a power so the blend is narrow). Every surface gets the projection that fits it.
It costs three texture reads instead of one, and works on any shape, which is why it's everywhere in raymarching and in games for terrain.
Your turn: Use it: vec3 albedo = triplanar(pos, n);
13. Rough surfaces: adding noise
Smooth shapes look made; nature is bumpy. The quickest way to make a shape rough is to add noise to its distance: where the noise is high the surface moves out, where it's low it moves in. Several octaves give lumps with bumps on them.
The distance is now only roughly right (the noise can lean a surface towards the ray faster than the distance says), which is why this march already takes 0.6 of each step. More noise, smaller steps.
Your turn: Roughen the ball: after the d line, add d += 0.25 * noise3(p * 2.0) + 0.08 * noise3(p * 6.0);
14. A different copy in every cell
mod repeats one tower forever (the Raymarching course's repetition step) and costs the same as one. id = floor(p.xz / 2.0) says which cell a point is in, and a hash of it gives each cell its own random number: height, colour, anything. The colours already use it; the heights don't.
One catch: the distance to this cell's tower isn't the distance to the nearest tower any more, because a taller neighbour can be closer. As long as each tower stays inside its cell with a gap round it, the error is small, and stepping a bit less (0.8 * d) covers it.
Your turn: Give each tower its own height: float h = 0.5 + 2.5 * hash(id);
15. Repeating only so many times
p - 2.0 * round(p / 2.0) repeats space every 2 units forever, so the columns carry on far beyond the temple's floor and roof. A building wants exactly so many.
round(p / 2.0) is which copy a point is nearest (…, −1, 0, 1, …). Clamping it between −3 and 3 across and −1 and 1 deep keeps 7 × 3 copies: points beyond the last column all measure from the last one, so there's nothing out there.
This limited repetition is how rows of windows, fences and colonnades are done: one column's cost, any number of them.
Your turn: Stop at the temple's edge: q.xz = p.xz - 2.0 * clamp(round(p.xz / 2.0), vec2(-3.0, -1.0), vec2(3.0, 1.0));
16. Inside a cave, by lantern
So far the camera has always been outside the shapes. A cave turns it round: the tunnel is the empty space, so the distance to the wall is the radius minus how far a point is from the tunnel's centre line. Noise on the radius makes the rock.
It's lit as if by the sun: the same light everywhere, from one direction, which makes no sense underground. The light is the lantern beside the camera: brightest facing it (dot with the direction to it, as with any light) and fading with the square of the distance (/ dot(toLamp, toLamp)), so the tunnel goes dark ahead.
Your turn: Light it by the lantern: float light = 3.0 * max(dot(n, normalize(toLamp)), 0.0) / dot(toLamp, toLamp);
17. A fractal, and its colours
The Mandelbulb: the Mandelbrot set's rule (square and add, over and over) done in 3D with spherical coordinates, raised to the 8th power. Each point is followed for a few rounds; points whose orbit stays small are inside. dr tracks how fast the orbit stretches, which turns the escape into a safe distance to march with.
Its colours come free: trap keeps how close a point's orbit came to the centre. Nearby points have similar orbits, so it changes smoothly over the surface and picks out the fractal's structure. Fed into a cosine palette, it paints the bulb.
The shading also uses the step count: rays that took many steps went deep into crevices, a cheap ambient occlusion. Try POWER 4 to 10 after.
Your turn: Colour it by the orbit trap: vec3 albedo = 0.5 + 0.5 * cos(6.2832 * (trap * 0.5 + vec3(0.0, 0.15, 0.3)));
18. A camera on a path
Flying through a world needs a path: pathX(z) says where across the camera is at each distance along, and the ground is carved into a valley along it, so it never flies into a hill.
But the camera looks straight ahead along z, so on every bend it stares into the valley wall. Point it where it's going instead: a target a little further along the same path, and the look-at camera (forward, right, up from the target) turns into each bend before it gets there.
Your turn: Look ahead along the path: vec3 ta = vec3(pathX(z + 3.0), 0.7, z + 3.0);
19. Depth of field
A camera lens is only sharp at one distance; nearer and further things blur, more the further from it they are. It draws the eye, and it makes a scene look like it was filmed.
The City pass is the towers from earlier, but it keeps each pixel's distance in alpha. Pass 1, Lens (open), reads that distance, works out how far it is from FOCUS, and picks that much blur: a mipmap level, read at six points round a circle (as in the glow passes), so the blur grows smoothly with distance.
APERTURE is how quickly things blur away from the focus, like a lens's f-stop: 0 is a pinhole, everything sharp.
Your turn: Open the lens: const float APERTURE = 0.25;
20. Pull it apart: a valley at sunset
Everything from this course in one place: the landscape with half steps, rock, grass and snow, sky light, a low sunset sun, water with reflections and haze that glows towards the sun. Read through it.
But the lakes are wrong. Every one is a perfect mirror, even right below the camera where you should see into the water and down to the stones on the bottom. Something in the water's maths is off.
Hint: Fresnel should be small looking straight down at the water and big at a glancing angle. Which way does rd point, and which way does the water's normal n?
Your turn: Fix the water so you can see into it again.
Other courses: Basics · Medium · Advanced · Maths for shaders · Raymarching, step by step · 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 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