Infinite spheres

glint · Examples · Tutorials · Gallery

Endless repeated mirror spheres (one sphere, repeated with mod), each reflecting its neighbours once, fading into fog.

Infinite spheres: 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 map(vec3 p) {
    vec3 q = mod(p, 2.0) - 1.0;
    return length(q) - 0.4;
}

vec3 normal(vec3 p) {
    vec2 e = vec2(0.001, 0.0);
    return normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx)));
}

float march(vec3 ro, vec3 rd) {
    float t = 0.0;
    for (int i = 0; i < 90; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001 || t > 30.0) break;
        t += d;
    }
    return t;
}

vec3 shade(vec3 p, vec3 rd) {
    vec3 n = normal(p);
    vec3 id = floor(p / 2.0);
    vec3 base = pal(hash(id.xy + id.z * 7.0));
    float dif = max(dot(n, normalize(vec3(0.5, 0.8, 0.3))), 0.0);
    return base * (0.2 + 0.8 * dif) + pow(max(dot(reflect(rd, n), normalize(vec3(0.5, 0.8, 0.3))), 0.0), 30.0);
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    // Spheres sit at odd coordinates; fly down the gap between them at x = y = 0.
    vec3 ro = vec3(0.35 * sin(time * 0.3), 0.35 * cos(time * 0.2), time);
    vec3 rd = normalize(vec3(uv, 1.2));
    rd.xy = rot(time * 0.1) * rd.xy;
    vec3 fog = vec3(0.05, 0.06, 0.1);
    float t = march(ro, rd);
    vec3 col = fog;
    if (t < 30.0) {
        vec3 p = ro + rd * t;
        vec3 n = normal(p);
        col = shade(p, rd);
        // One bounce: what this sphere reflects.
        vec3 rr = reflect(rd, n);
        float t2 = march(p + n * 0.01, rr);
        vec3 refl = t2 < 30.0 ? shade(p + n * 0.01 + rr * t2, rr) : fog;
        col = mix(col, refl, 0.4 * (1.0 - max(dot(n, -rd), 0.0) * 0.5));
        col = mix(col, fog, 1.0 - exp(-t * 0.08));
    }
    fragColor = vec4(pow(col, vec3(0.85)), 1.0);
}

More More GLSL examples

Lava lamp · Circuit board · Snowfall · Ink in water · Night sky · Dithered retro · Chrome balls · Stained glass