2D distance field playground

glint · Examples · Tutorials · Gallery

Shapes as distance functions, melted together with a smooth union, and the distance field itself drawn as contour lines (orange outside, blue inside). The circle follows the mouse.

2D distance field playground: a GLSL shader

An example in glint, a free live shader editor in the browser: the GLSL code floats over the running picture and recompiles as you type.

The code

One pass, in GLSL.

fragment shader

#version 300 es
precision highp float;

uniform float time;
uniform vec2 resolution;
uniform vec2 mouse;

in vec2 v_texcoord;
out vec4 fragColor;

float hash(float n) { return fract(sin(n * 127.1) * 43758.5453); }
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
vec2 hash2(float n) { return fract(sin(vec2(n * 127.1, n * 269.5)) * 43758.5453); }
mat2 rot(float a) { float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
vec3 pal(float t) { return 0.5 + 0.5 * cos(6.28318 * (t + vec3(0.0, 0.33, 0.67))); }

float sdCircle(vec2 p, float r) { return length(p) - r; }
float sdBox(vec2 p, vec2 b) { vec2 d = abs(p) - b; return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); }
float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); }
// Smooth union: like min(), but blended over distance k.
float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    vec2 m = (mouse - 0.5) * vec2(resolution.x / resolution.y, 1.0);
    float k = 0.05 + 0.1 * (0.5 + 0.5 * sin(time));
    float d = sdCircle(uv - m, 0.12);
    d = smin(d, sdBox(rot(time * 0.5) * (uv - vec2(0.3, 0.05)), vec2(0.12, 0.07)) - 0.02, k);
    d = smin(d, sdSegment(uv, vec2(-0.4, -0.2), vec2(-0.1, 0.25 * sin(time * 0.7))) - 0.04, k);
    // The classic distance-field picture: colour by sign, darker near the edge, contour lines every 0.02.
    vec3 col = d > 0.0 ? vec3(0.9, 0.6, 0.3) : vec3(0.65, 0.85, 1.0);
    col *= 1.0 - exp(-6.0 * abs(d));
    col *= 0.8 + 0.2 * cos(150.0 * d);
    col = mix(col, vec3(1.0), smoothstep(0.004, 0.0, abs(d)));
    fragColor = vec4(col, 1.0);
}

More More GLSL examples

Rain on the window · Gyroid cave · Julia set · Mandelbrot zoom · Lava lamp