Gyroscope

glint · Examples · Tutorials · Gallery

Three chrome rings nested and each spinning about its own axis round a gold core: distance fields for tori, rotated before measuring, shaded by reflecting an environment.

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

vec3 cameraRay(vec3 ro, vec3 target, vec2 uv, float zoom) {
    vec3 f = normalize(target - ro);
    vec3 r = normalize(cross(vec3(0.0, 1.0, 0.0), f));
    vec3 u = cross(f, r);
    return normalize(uv.x * r + uv.y * u + zoom * f);
}

float sdTorus(vec3 p, vec2 t) { return length(vec2(length(p.xz) - t.x, p.y)) - t.y; }
int hit;
float map(vec3 p) {
    vec3 a = p;  a.yz = rot(time * 0.9) * a.yz;
    vec3 b = a;  b.xy = rot(time * 1.3) * b.xy;
    vec3 c = b;  c.yz = rot(time * 1.7) * c.yz;
    float r1 = sdTorus(a.xzy, vec2(1.0, 0.05));
    float r2 = sdTorus(b, vec2(0.8, 0.05));
    float r3 = sdTorus(c.yxz, vec2(0.6, 0.05));
    float core = length(p) - 0.3;
    float d = min(min(r1, r2), min(r3, core));
    hit = d == core ? 1 : 0;
    return d;
}

vec3 normal(vec3 p) {
    vec2 e = vec2(0.002, 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)));
}

vec3 env(vec3 d) {
    vec3 c = mix(vec3(0.05, 0.05, 0.08), vec3(0.6, 0.65, 0.75), smoothstep(-0.2, 0.8, d.y));
    c += vec3(1.0) * smoothstep(0.96, 0.99, abs(dot(d, normalize(vec3(1.0, 0.3, 0.0))))) * 2.0;   // two strip lights
    return c;
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    vec3 ro = vec3(0.0, 0.8, -3.2);
    vec3 rd = cameraRay(ro, vec3(0.0), uv, 1.6);
    float t = 0.0;
    for (int i = 0; i < 100; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001 || t > 10.0) break;
        t += d;
    }
    vec3 col = env(rd) * 0.3;
    if (t < 10.0) {
        vec3 p = ro + rd * t;
        vec3 n = normal(p);
        map(p);
        vec3 tint = hit == 1 ? vec3(1.0, 0.75, 0.35) : vec3(0.9);
        float fresnel = 0.3 + 0.7 * pow(1.0 - max(dot(n, -rd), 0.0), 4.0);
        col = env(reflect(rd, n)) * tint * (0.5 + 0.5 * fresnel);
    }
    fragColor = vec4(pow(col, vec3(0.4545)), 1.0);
}

More More GLSL examples

Lightning · Candle · Planet · Isometric city · Moiré · Toon shading · Mandelbox · Hyperbolic tiling