Lava lamp

glint · Examples · Tutorials · Gallery

Metaballs in 2D: blobs of wax rising and sinking, merging and splitting, because they're drawn where the sum of their fields crosses a threshold.

Lava lamp: 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))); }

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    // The lamp: a tapered glass shape.
    float lamp = abs(uv.x) - (0.2 - uv.y * 0.07);
    float field = 0.0;
    for (int i = 0; i < 9; i++) {
        float fi = float(i);
        float speed = 0.08 + 0.1 * hash(fi);
        // Each blob rises and falls through the lamp at its own pace.
        float y = sin(time * speed * 3.0 + fi * 1.7) * 0.36;
        float x = sin(time * speed * 2.0 + fi * 2.3) * 0.09;
        float r = 0.045 + 0.04 * hash(fi + 11.0);
        vec2 d = uv - vec2(x, y);
        field += r * r / dot(d, d);
    }
    // Wax pooled at the bottom and top.
    field += 0.02 / max(uv.y + 0.44, 0.001) + 0.01 / max(0.45 - uv.y, 0.001);
    vec3 liquid = mix(vec3(0.35, 0.02, 0.2), vec3(0.6, 0.1, 0.3), uv.y + 0.5);
    vec3 wax = mix(vec3(1.0, 0.25, 0.05), vec3(1.0, 0.75, 0.2), clamp(field - 1.0, 0.0, 1.0));
    vec3 col = mix(liquid, wax, smoothstep(0.95, 1.05, field));
    col *= smoothstep(0.01, -0.01, lamp) * step(abs(uv.y), 0.45);
    // The room glows from the lamp.
    col += vec3(0.5, 0.1, 0.1) * 0.15 * exp(-abs(lamp) * 6.0);
    fragColor = vec4(col, 1.0);
}

More More GLSL examples

2D distance field playground · Gyroid cave · Julia set · Mandelbrot zoom · Circuit board · Snowfall · Ink in water · Infinite spheres