Surfaces: from vertex to fragment
glint · Examples · Tutorials · Gallery
A 3D point for every pixel of a mesh, handed over by the vertex shader: noise on surfaces, per pixel not per corner, object vs world space, a 3D noise texture, marble, wood, bumps, the same noise in both shaders, normals from derivatives, a planet with air, snow from above, terrain fog and contours, triplanar textures, dissolving, flowing lava.
A free interactive course of 21 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. A 3D point for every pixel
The question this course answers: the vertex shader knows where each corner is in 3D, but how does the fragment shader get a 3D point for each pixel (to read noise with, say)? No maths is needed to work it out backwards from the screen. The vertex shader hands it over.
Look at the Vertex tab: out vec3 v_pos; and v_pos = a_position.xyz; give every corner its own position. Anything a vertex shader writes to an out arrives in the fragment shader's in of the same name, blended between the triangle's three corners by how close the pixel is to each (exactly, even in perspective). Blending three points on a flat triangle gives the point on the triangle: so each pixel gets the 3D point it shows.
The Fragment tab has in vec3 v_pos; already, and paints everything orange. Show the position as a colour: x red, y green, z blue (the sphere runs -0.5 to 0.5, so add 0.5).
Your turn: Paint the position: vec3 col = v_pos + 0.5;
2. Per pixel, not per corner
With the point, noise is one call: noise(v_pos * 12.0), 3D value noise (a random number at every whole-number point in space, blended in between; the 12 is how fine).
This sphere is coarse on purpose (Pass panel › Geometry, 10 segments), and the noise is worked out in the vertex shader, once per corner, handed over as v_n. The fragment shader only gets the blend of three corners' values: faceted blotches, as coarse as the mesh.
Work it out in the fragment shader instead, from v_pos. Now every pixel asks the noise itself, and the detail has nothing to do with how many triangles there are. (The outline stays faceted: that's the mesh's shape.)
Your turn: Noise per pixel: float n = noise(v_pos * 12.0);
3. Why not the UVs?
Meshes come with 2D map coordinates too (a_texcoord, here v_uv): the sphere unrolled like a map of the Earth. 2D noise on them is the obvious first try, and it's what's on the sphere now.
Watch it turn: there's a seam down one side, where u jumps from 1 back to 0 and the noise doesn't match up, and at the poles the whole top row of the map is squeezed into one point, so the noise pinches into streaks.
3D noise on the 3D point has neither: space has no seams, and nothing is squeezed. Every mesh, whatever its UVs (or with none at all), gets the same even pattern.
Your turn: Use the 3D point: float n = noise(v_pos * 6.0);
4. Stuck on, or swimming through
Which 3D point? This vertex shader hands over (modelMatrix * a_position).xyz: the corner in the world, after the mesh has been turned (the model matrix is the Camera's tilt and spin). As the cube turns, its faces slide through a pattern that stays still: like a cube carved out of a block of marble, but moving through the block.
a_position itself is in the mesh's own space, before any turning. A pattern read there is painted on: it turns with the cube.
Both are useful. World space for things that belong to the world (fog, snow falling from above, light); object space for what the thing is made of.
Your turn: Stick the pattern on: in the Vertex tab, v_pos = a_position.xyz;
5. A noise map in 3D
Noise can come from a picture instead of a formula. glint has a stock 3D texture, grayNoise3D: a 32 × 32 × 32 block of random values. Declare it as uniform sampler3D grayNoise3D; and read it with a 3D point, texture(grayNoise3D, p).r, and the GPU blends between the eight nearest values for you (p is 0..1 across the block, and it repeats).
tnoise(p) reads it at one texel per unit, and tfbm adds five layers of it. That's five texture reads where the hashed noise does forty hashes: much cheaper, for a pattern that repeats every 32 units and is a little creased (the GPU blends in straight lines, not smooth curves).
Any 3D texture works this way with v_pos; a 2D one needs a trick (two steps on).
Your turn: Read the noise map: float n = tfbm(v_pos * 8.0);
6. Marble
Patterns from position, not only noise: sin(v_pos.x * 20.0) is straight stripes through space, and the torus is cut out of them. Each stripe's middle (where the sine crosses 0) is a dark vein.
Marble is those stripes pushed about by noise: add fbm to what the sine reads, and the straight layers fold and wander, as real marble's layers did under heat and pressure. The 6 is how far they're pushed.
Your turn: Fold the layers: float v = sin(v_pos.x * 20.0 + fbm(v_pos * 4.0) * 6.0);
7. Wood
Wood is rings round the trunk: the distance from the y axis, length(v_pos.xz), makes circles in every slice across it and straight lines down its length. The cube is a block cut from a log, so its top shows circles and its sides show grain.
Perfect circles look turned on a lathe. Real rings wobble: add noise to the distance, and they wander and vary in width.
Your turn: Make them wobble: float r = length(v_pos.xz) * 24.0 + fbm(v_pos * 3.0) * 4.0;
8. Lighting it
Positions aren't the only thing worth handing over. v_normal (the way the surface faces, from normalMatrix * a_normal, so it turns with the mesh) arrives blended between the corners too.
Blending three directions of length 1 gives something shorter than 1, so the fragment shader lengthens it again (normalize) before using it. Then the usual: how much the surface faces the light is dot(n, l), never below 0.
Lit per pixel, the light moves smoothly over the torus, however coarse its triangles.
Your turn: Light it: float dif = max(dot(n, l), 0.0);
9. Bumps without moving anything
The stone's colour comes from noise, but it's still a smooth ball: light falls on it as on glass. The surface needn't really move to look rough: tilt the normal the way the noise slopes, and the light does the rest (bump mapping).
slope(q) is how fast the noise changes along x, y and z (each from two samples a little either side). Only its part along the surface matters, g - dot(g, n) * n: the normal tips away from uphill. normalMatrix turns the slope with the mesh, as it does the normal.
The outline stays perfectly round: nothing moved. The next step moves it for real.
Your turn: Rough it up: const float BUMP = 0.2;
10. The same noise in both shaders
Now the vertex shader moves each corner out along its normal by h. Its fragment shader colours by height: dark rock low, pale high. It asks fbm(v_pos * 4.0) * 0.25, the very sum the vertex shader will use: the same function with the same point gives the same number, so the colours will land exactly on the bumps.
v_pos stays the corner's place before it moved (a_position), so both shaders read the noise at the same point. The fragment shader can also add detail far finer than the corners (fbm(v_pos * 30.0)): the mesh only has to hold the big shapes.
The light is still the smooth ball's (v_normal), so the bumps look flat-lit: the next step fixes that.
Your turn: Raise the ground: in the Vertex tab, float h = fbm(a_position.xyz * 4.0) * 0.25;
11. Normals from the pixels themselves
The bumps need their own normals, and the vertex shader doesn't know them (it would have to ask the noise around each corner). The fragment shader can measure them.
dFdx(v_world) is how much v_world changes from this pixel to the next one across, and dFdy to the next one up: two little steps along the surface, as it is now. Across them, cross gives the way the surface faces. It's flat per triangle (the triangles are flat), so with 128 segments it reads as finely carved rock.
This works for anything a vertex shader does to a mesh, with no extra maths in it.
Your turn: Measure the normal: vec3 n = normalize(cross(dFdx(v_world), dFdy(v_world)));
12. A planet
Everything so far at once: the vertex shader raises land where fbm(a_position.xyz * 3.0) is over 0.5 and leaves the sea round; the fragment shader asks the same noise, so it knows what's sea and what's land, how deep and how high, at every pixel. Land is lit with measured normals, the sea with the smooth ball's.
Ice caps: v_pos.y is how far north or south this pixel is on the planet itself (its own space, so the caps turn with it). Near the poles, and sooner where the land is high.
Your turn: Add ice caps: float snow = smoothstep(0.42, 0.46, abs(v_pos.y) + land * 0.5);
13. Snow falls from above
The planet's ice belonged to the planet. Snow on a rock belongs to the world: it settles wherever the surface faces up, whichever way the rock is turned.
This rock is tilted well over as it spins, so its own up keeps moving. The normal n here is measured from v_world, so it's in the world's space: n.y near 1 faces the sky. Snow there and it stays on top as the rock turns underneath it.
Your turn: Let it snow: float snow = smoothstep(0.55, 0.8, n.y);
14. Where the camera is
With the pixel's place in the world (v_world), the camera's place gives the way to the eye. Its place is in the view matrix: inverse(viewMatrix)[3].xyz (the view matrix moves the world in front of the camera; undone, it says where the camera stands).
v = normalize(eye - v_world) points from the surface to the eye. Where the surface faces you, dot(n, v) is 1; at the edges, where you see it side on, 0. An atmosphere is thickest seen side on: a glow round the rim, pow(1.0 - dot(n, v), 3.0).
Your turn: Give it air: float rim = pow(1.0 - max(dot(round, v), 0.0), 3.0);
15. Fog by distance
A plane (Pass panel › Geometry, 160 segments) laid flat and raised by noise: a landscape, coloured by height (v_pos.y) and lit with measured normals.
The distance from the camera, length(v_world - eye), is the real distance through the air to this bit of ground: fog by it fades far hills into the sky, as air does. 1.0 - exp(-dist * dist * k) is how much light the air in between scatters: almost none close by, more and more with distance, never quite all.
Your turn: Add air: float fog = 1.0 - exp(-dist * dist * 0.005);
16. Contour lines
A map's contours are lines of equal height: wherever v_pos.y * 10.0 is a whole number. d is how far this pixel is from the nearest one, in contours.
1.0 - step(0.03, d) draws them, but unevenly: thick on flat ground (the height changes slowly, so many pixels are near a line) and broken on steep slopes (it jumps past them between pixels).
fwidth(k) is how much k changes from one pixel to the next. Measured in that, every line is the same width on screen, whatever the slope.
Your turn: Even them out: float line = 1.0 - smoothstep(0.0, 1.5 * fwidth(k), d);
17. A 2D picture on a 3D shape
A 2D texture (the stock rockTiles) needs two coordinates. Taking two of the three, v_pos.xy, projects it from the front, like a slide projector: fine on the faces looking that way, smeared into streaks where the rock turns side on.
Triplanar: project it three times (from the side with p.zy, the top p.xz and the front p.xy) and weight each by how much the surface faces that way. on is the normal in the rock's own space (measured from v_pos), so the picture stays on as it turns.
Your turn: Project it three ways: vec3 albedo = triplanar(v_pos * 3.0, on);
18. Dissolving
A fragment shader can refuse to draw its pixel: discard. Throw away every pixel whose noise is under a level, and the sphere is eaten away in noisy holes, wherever the 3D noise is low.
cut rises and falls with time, so it dissolves and comes back. Pixels near the level burn orange (that's already there: it's where the holes will open), and through the holes you see the inside: gl_FrontFacing is false there, so it's turned round and darkened.
Your turn: Eat it away: if (n < cut) discard;
19. Flowing
Noise in 3D has a free trick: moving the point through it moves the pattern. Read fbm(q) at q = v_pos * 3.0 plus a drift with time, and the pattern slides over the surface as if it flowed.
Here it's noise of noise (the inner fbm pushes where the outer one reads), which makes swirls; low values glow, high ones are dark crust. Drifting downwards, the lava crawls over the ball as a slow river would.
Your turn: Set it flowing: vec3 q = v_pos * 3.0 + vec3(0.0, time * 0.3, 0.0);
20. Copies with their own pattern
Nine instances of the one sphere (Pass panel › Instances). Each is moved to its own place, but v_pos is the sphere's own point, the same for all nine, so they all wear the same pattern.
The vertex shader hands over v_seed too: a different point in space for each copy (gl_InstanceID times some odd numbers). Adding it to where the noise reads moves each copy to its own part of the noise.
Your turn: Give each its own: float n = fbm(v_pos * 5.0 + v_seed);
21. Pull it apart: slipping colours
A little world: the vertex shader raises hills with fbm(a_position.xyz * 4.0) * 0.25, and the fragment shader colours by height, grass low, rock above and snow on the peaks.
But the colours don't stay on the hills: as it turns, the snow slides down into the valleys and the grass climbs the peaks. Read which point each shader asks the noise at.
Your turn: Fix it so the colours stay on their hills.
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 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 · Blur and glow