Lightning

glint · Examples · Tutorials · Gallery

Storm: every few seconds bolts fork down from the clouds, their paths a sum of wiggles at halving sizes (1D fractal noise), flickering and lighting the clouds from inside.

Lightning: 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;

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 noise(vec2 p) {
    vec2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);
}
float fbm(vec2 p) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + 17.0; a *= 0.5; }
    return v;
}

float noise1(float x) { float i = floor(x), f = fract(x); return mix(hash(i), hash(i + 1.0), f * f * (3.0 - 2.0 * f)); }

// Horizontal distance to a bolt that starts at the top and reaches down to y = bottom.
float bolt(vec2 uv, float seed, float bottom) {
    float x = (hash(seed) - 0.5) * 1.2, amp = 0.2;
    for (int i = 0; i < 6; i++) {
        float fi = float(i);
        x += amp * (noise1(uv.y * 3.0 * pow(2.0, fi) + seed * 13.0 + fi * 7.0) - 0.5);
        amp *= 0.5;
    }
    return uv.y < bottom ? 1e3 : abs(uv.x - x);
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    float strike = floor(time * 0.7), phase = fract(time * 0.7);
    // On for the first ~0.3 of each cycle, flickering.
    float flash = exp(-phase * 6.0) * step(phase, 0.35) * (0.5 + 0.5 * step(0.4, hash(floor(time * 25.0))));
    float clouds = fbm(uv * 3.0 + vec2(time * 0.05, 0.0));
    vec3 col = vec3(0.03, 0.04, 0.07) + vec3(0.1, 0.1, 0.14) * clouds * smoothstep(-0.1, 0.5, uv.y);
    col += vec3(0.5, 0.55, 0.8) * flash * clouds * smoothstep(0.0, 0.5, uv.y);
    float d = min(bolt(uv, strike, -0.45), min(bolt(uv, strike + 0.3, -0.1) + 0.001, bolt(uv, strike + 0.6, 0.15) + 0.002));
    col += vec3(0.7, 0.8, 1.0) * flash * (0.003 / (d + 0.002) + smoothstep(0.004, 0.0, d) * 2.0);
    // Hills against the flash.
    float hills = -0.42 + 0.05 * sin(uv.x * 4.0) + 0.03 * noise(vec2(uv.x * 10.0, 0.0));
    if (uv.y < hills) col = vec3(0.01) + flash * 0.02;
    fragColor = vec4(col, 1.0);
}

More More GLSL examples

ASCII · Soap bubbles · Sierpinski tetrahedron · CRT television · Candle · Planet · Isometric city · Gyroscope