Medium
glint · Examples · Tutorials · Gallery
2D design with distance fields: shapes and booleans, smooth blends, transforms, noise, kaleidoscopes, feedback, passes.
A free interactive course of 10 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. Write your own functions
GLSL functions look like C: a return type, a name, and typed parameters. float sdCircle(vec2 p, float r) takes a point and a radius and gives back one float. A function has to be written above the code that calls it, which is why the helpers sit above main.
What sdCircle gives back is a signed distance: how far the point p is from the circle's edge. length(p) is the distance from the centre, so length(p) - r is negative inside the circle, exactly zero on its edge, and positive outside. A function like this, describing a whole shape as a distance, is called a signed distance function (SDF), or a distance field.
p is this pixel's position, centred on the screen: (0, 0) is the middle and y runs from -0.5 at the bottom to 0.5 at the top (x goes further on a wide screen). So a radius of 0.25 fills half the height.
Drawing turns the distance into colour. smoothstep(0.005, -0.005, d) is 1 inside, 0 outside and blends across a tiny soft edge; mix uses it to fade the dark background to orange. The faint rings come from cos(d * 120.0): each ring is a line of equal distance, so you can see the whole field, not only the shape.
To put a circle somewhere else, measure from another centre: sdCircle(p - c, r) is a circle centred at c. min(d1, d2) keeps whichever shape is nearer, which draws both (the next step is all about that).
Try: a third circle, or make one move with vec2(0.4 * sin(time), 0.0) as its centre.
Your turn: Draw a second circle with the same function: d = min(d, sdCircle(p - vec2(0.4, 0.0), 0.15)); joins them.
2. Shapes and boolean operations
Each shape is just a number per pixel (how far away it is), so combining shapes is arithmetic on those numbers:
min(a, b) union: in either shape
max(a, b) intersection: in both
max(a, -b) subtraction: a minus bWhy subtraction works: negating b turns it inside out (inside becomes positive, outside negative). Intersecting a with that keeps only the parts of a that are outside b.
sdBox(p, b) is the distance to a box with half-size b, so vec2(0.3, 0.2) is 0.6 wide and 0.4 tall. You don't need to follow its formula: distance functions for dozens of shapes are written up (search for Inigo Quilez's 2D distance functions) and they all plug in the same way.
Watch the contour rings as you edit: they bend around the new shape. The result is still (close enough to) a distance field, so everything else in this course keeps working on it.
Try: max(box, circle) for just the overlap, or abs(d) - 0.01 to turn any shape into a thin outline.
Your turn: Cut the circle out of the box instead: float d = max(box, -circle);
3. Smooth blending
min joins shapes with a sharp crease where they meet. smin(a, b, k), a smooth minimum, gives the same answer as min away from the join, but within a distance k of it the surface is rounded off, so the shapes melt together like wax. It's how blobby, organic forms are made.
How it works: h says which shape is nearer, from 0 (b is much nearer) to 1 (a is much nearer), and it's only in between where the two distances are within k of each other. mix(b, a, h) blends the distances, and - k * h * (1.0 - h) pushes the surface outward most where they're equal (h = 0.5), filling the crease.
k is a distance in the same units as the shapes: 0.05 is a small fillet, 0.3 a big gooey bridge. The small circle orbits the big one (0.35 * vec2(cos(time), sin(time)) moves its centre round a circle), so you can watch them stretch and let go.
Try: animate the gooeyness with 0.1 + 0.1 * sin(time) as k, or blend a box and a circle.
Your turn: Make the blend much gooier: raise k (the last number in smin) to 0.2 or more.
4. Move, rotate, scale
There's no “move the shape” command: a distance function always describes its shape at the origin. To move, turn or resize a shape, you move, turn or resize the point you measure from, the opposite way.
move q = p - offset
rotate q = rot(angle) * q
scale sdBox(q / s, b) * sAngles are in radians (6.28 is a full turn). Move: p - vec2(0.2, 0.0) measures from 0.2 to the right, so the box appears 0.2 to the right (adding would move it left: it's reversed). Scale: dividing q by s makes the shape s times bigger, and multiplying the distance by s afterwards keeps it in screen units.
Order matters. Move, then rotate (as here) and the box spins around its own centre. Rotate first, then move, and it would swing around the middle of the screen instead, like a clock hand.
rot(a) builds a 2×2 rotation matrix from cos and sin of the angle. The Maths for shaders course explains matrices from scratch, if you'd like to see why.
Try: rot(time * 3.0) spins faster; rot(sin(time)) rocks back and forth.
Your turn: Spin the box: rotate q before measuring, q = rot(time) * q;.
5. Every cell is different
Multiplying p by 6.0 makes the coordinates run across several whole numbers. floor(p) rounds down, so every pixel in the same grid square gets the same pair of whole numbers, like (2, -1): the cell's id. fract(p) is what's left over, 0 to 1 across each cell; subtracting 0.5 centres it, so q is the position inside the cell with (0, 0) at its middle.
Drawing one circle at q draws it in every cell at once, because every cell has the same local coordinates. That's repetition. To make the cells differ, each one needs a number of its own, worked out from its id.
hash(id) does that: it scrambles the id into a random-looking number from 0 to 1. It isn't truly random (the same cell always gets the same value), which is what we want: nothing flickers. The formula (sine of a dot product, times a big number, keep the fraction) is a common quick hash; its numbers are arbitrary.
Here the hash r sets each circle's size and when it pulses. It can drive anything: colour, speed, rotation, or whether a cell is drawn at all (if (r < 0.3)).
The task's colour is a cosine palette: 0.5 + 0.5 * cos(6.28 * (r + offsets)) goes all the way round the colour wheel as r goes from 0 to 1, and the three offsets put red, green and blue a third of a turn apart.
Your turn: Colour the cells by their random value too: e.g. vec3 ink = 0.5 + 0.5 * cos(6.28 * (r + vec3(0.0, 0.33, 0.67))); and use ink in the mix.
6. Noise and fractal noise
A hash gives every grid point an unrelated random number: jumpy, like TV static. Value noise smooths it out. noise() finds the cell the point is in (i) and where it is inside it (f), takes the hashes at the cell's four corners, and blends them: across with the inner mix calls, then up with the outer one. So the value changes gradually from place to place.
u = f * f * (3.0 - 2.0 * f) eases the blend so it starts and stops gently (it's the smoothstep curve). With plain f you'd see creases along the grid lines.
One layer of noise is soft blobs, all about the same size. Real textures (clouds, rock, terrain) have detail at every scale. fbm (fractional Brownian motion) stacks layers called octaves. Each time round its loop it adds noise at the current size, then doubles the frequency (p *= 2.0: features half as big) and halves the strength (a *= 0.5). The first octave makes the big shapes, later ones the fine detail.
With 2 octaves there's hardly any detail. Each extra one adds finer grain; beyond about 8 the new detail is smaller than a pixel and only costs time.
The colour maps the noise (roughly 0 to 1) from deep blue to white; smoothstep(0.3, 0.8, n) picks where the change happens. Adding time * 0.3 to x scrolls it, like drifting cloud.
Try: p *= 2.5 in the loop for rougher detail, or smoothstep(0.48, 0.52, n) for crisp islands.
Your turn: Change the number of octaves (the 2 in the loop) to 5 or more, and watch detail appear.
7. Kaleidoscopes
A kaleidoscope works in polar coordinates. Instead of x and y, describe each pixel by its angle around the centre, a = atan(p.y, p.x) (from -3.14 to 3.14), and its distance from the centre, r = length(p).
Split the full turn (6.2831 radians) into segments slices, each seg wide. mod(a, seg) maps every angle into the first slice, so every slice now shows the same thing. Subtracting half a slice and taking abs mirrors it down the slice's middle: that's what makes it look like mirrors, with no seams between slices.
Then q = r * vec2(cos(a), sin(a)) turns the folded angle and distance back into x and y. Anything drawn using q appears once in the slice, and so in every slice. Here that's a circle and the outline of a small box (abs(d) - 0.005 makes a thin outline from any shape).
Adding time * 0.2 to the angle turns the whole pattern. The colours depend on r, so they ripple outward in rings.
Try: draw something else at q, or move the circle with sin(time) in its position: every copy moves.
Your turn: Change the number of segments (the 6.0) to something else.
8. Feedback: remembering the last frame
Normally each frame starts from nothing. With uniform sampler2D feedback; a pass can read what it drew last frame, as a texture. So each frame can be: take the last frame, change it a little, add something new. That's how trails, smears and echoes are made.
texture(feedback, uv) reads last frame's colour at uv (0 to 1 across the screen; v_texcoord is this pixel's). Multiplying by decay darkens it a little every frame: after n frames a bright pixel is decayⁿ as bright. At 60 fps, 0.9 fades to almost nothing in half a second, 0.97 takes about two seconds, and 1.0 never fades.
(uv - 0.5) * 0.99 + 0.5 reads from slightly nearer the centre than this pixel, which enlarges the old picture by 1% a frame, so trails drift outward. 1.01 shrinks it and pulls them inward; adding a small vec2 pushes them sideways.
now is this frame's new drawing: a dot moving along a looping path. max(prev, now) keeps whichever is brighter, so the dot paints over its own fading trail.
Try: 1.01 instead of 0.99, or rotate the lookup a little each frame for spirals.
Your turn: Make the trails last longer: raise decay closer to 1.0 (e.g. 0.97).
9. Several passes
A project can have several passes, run in order every frame. Each draws into its own image (a buffer) rather than the screen, and only the last pass is shown. Later passes can read earlier ones as textures.
Pass 0, Scene, draws six outlined circles. Pass 1, Post, draws no shapes at all: it reads Scene's image with texture(prevPass, uv) (prevPass is always the pass just before) and changes it. So far it only darkens the corners, a vignette.
That split is how post-processing works: blur, glow, colour grading, glitches. Because the post pass can read the scene anywhere, not only at this pixel, it can do things one pass can't, like shifting colours sideways.
Chromatic aberration imitates a cheap lens, which bends red, green and blue by different amounts. Reading red from a little to the right (uv + vec2(0.005, 0.0)), while green and blue still come from uv, splits the colours at every edge. 0.005 is half a percent of the screen width.
Switch passes with the tabs above the code; you're on pass 1, Post. Pass settings (the layers icon) shows each pass's options.
Try: shift blue the other way too, col.b = texture(prevPass, uv - vec2(0.005, 0.0)).b;, or make the offset grow towards the edges, as in a real lens.
Your turn: Add chromatic aberration in pass 1: sample the red channel slightly offset, e.g. col.r = texture(prevPass, uv + vec2(0.005, 0.0)).r;.
10. Designing for music
Once an audio input is on (the Inputs panel, the waveform icon: microphone, system audio or a music file), glint fills in audio uniforms. Each is good at a different job.
spectrum is how loud it is right now in three bands: x is bass, y mids, z treble, each roughly 0 to 1. It's smoothed, so it suits sizes and brightness that breathe with the music. The ring's radius is 0.25 + 0.15 * spectrum.x: it swells with the bass.
beat jumps to 1 on each kick drum and fades back to 0: made for flashes, cuts and jumps. (How it fades is set in Inputs › Audio.)
spectrumIntegrated keeps adding up the loudness, so it only grows, and grows faster when the music is loud. Use it instead of time for movement: spectrumIntegrated.x * 2.0 turns the ring faster in loud parts and slower in quiet ones, without the jitter you'd get from driving rotation with spectrum directly.
Without audio they all stay at 0, so the ring sits still. That's expected: turn on an input to see it move.
Try: kick the size as well, float r = 0.25 + 0.15 * spectrum.x + 0.05 * beat;.
Your turn: Make it flash on the kick: add beat somewhere, e.g. col += beat * 0.4;.
Other courses: Basics · 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 · Surfaces: from vertex to fragment · Blur and glow