Bokeh

glint · Examples · Tutorials · Gallery

Out-of-focus lights: each is the lens aperture's shape (a polygon, one side per blade), brighter at the rim, added up. Try the blades and size parameters.

Bokeh: 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 float size;
uniform float blades;

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))); }

// Distance to a regular polygon with n sides and inner radius r.
float polygon(vec2 p, float r, float n) {
    float s = 6.28318 / n;
    float a = atan(p.y, p.x) + 0.3;
    return cos(floor(0.5 + a / s) * s - a) * length(p) - r;
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    vec3 col = mix(vec3(0.02, 0.01, 0.04), vec3(0.08, 0.03, 0.06), gl_FragCoord.y / resolution.y);
    float n = floor(blades);
    for (int i = 0; i < 60; i++) {
        float fi = float(i);
        vec2 h = hash2(fi + 1.0);
        float depth = 0.4 + 0.6 * hash(fi * 3.7);   // further lights are smaller and dimmer
        vec2 p = (h - 0.5) * vec2(2.0, 1.2);
        p.x = mod(p.x + time * 0.03 * depth + 1.0, 2.0) - 1.0;
        p.y += 0.02 * sin(time * 0.5 + fi);
        float r = size * depth;
        float d = polygon(uv - p, r, n);
        float disc = smoothstep(0.004, -0.004, d);
        float rim = 0.5 + 0.5 * smoothstep(-r * 0.6, 0.0, d);     // brighter towards the edge
        vec3 c = mix(vec3(1.0, 0.55, 0.2), vec3(0.3, 0.6, 1.0), step(0.7, hash(fi * 9.1)));
        col += c * disc * rim * 0.35 * depth * (0.8 + 0.2 * sin(time * 2.0 + fi));
    }
    fragColor = vec4(1.0 - exp(-col * 1.5), 1.0);
}

More More GLSL examples

Clock · Desert dunes · Apollonian · Digital rain · ASCII · Soap bubbles · Sierpinski tetrahedron · CRT television