Skip to content

simple sphere

BLOKS Shader Bulletin Board

simple sphere

By RJ Shelton June 8, 2026

Shader Preview Unavailable

This realtime shader may be too intensive for your current device or browser.

Shader Code
//uniform vec2 iMouse;

float sdSphere(vec3 p, float r)
{
    return length(p) - r;
}

float map(vec3 p)
{
    return sdSphere(p, 1.0);
}

vec3 getNormal(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)
    ));
}

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    vec2 uv = fragCoord.xy / iResolution.xy;
    vec2 p = uv * 2.0 - 1.0;
    p.x *= iResolution.x / iResolution.y;
    
    vec3 ro = vec3(0.0, 0.0, -4.0);
    vec3 rd = normalize(vec3(p, 1.5));
    
    vec2 m = iMouse.xy;
float yaw = (m.x - 0.5) * 1.6;
float pitch = (m.y - 0.5) * 1.0;

rd.xz *= mat2(cos(yaw), -sin(yaw), sin(yaw), cos(yaw));
rd.yz *= mat2(cos(pitch), -sin(pitch), sin(pitch), cos(pitch));

    

    float t = 0.0;
    float hit = 0.0;

    for(int i = 0; i < 80; i++)
    {
        vec3 pos = ro + rd * t;
        float d = map(pos);

        if(d < 0.001)
        {
            hit = 1.0;
            break;
        }

        t += d;

        if(t > 20.0) break;
    }

    vec3 bg = vec3(0.02, 0.03, 0.08);
    vec3 col = bg;

    if(hit > 0.5)
    {
        vec3 pos = ro + rd * t;
        vec3 normal = getNormal(pos);

        vec3 lightDir = normalize(vec3(0.6, 0.8, -0.5));
        float diff = max(dot(normal, lightDir), 0.0);

        float fresnel = pow(1.0 - max(dot(normal, -rd), 0.0), 3.0);

        vec3 base = vec3(0.10, 0.20, 0.85);
        vec3 glow = vec3(0.25, 0.65, 1.0);

        col = base * (0.18 + diff * 0.85);
        col += glow * fresnel * 0.75;
    }

    // Subtle vignette
    float vignette = smoothstep(1.4, 0.2, length(p));
    col *= vignette;

    fragColor = vec4(col, 1.0);
}

← Back to Shader Bulletin Board