Terrain flyover

glint · Examples · Tutorials · Gallery

Raymarched fbm mountains with fog and sun, flying forward. Mouse looks around.

Terrain flyover: 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;
uniform vec2 mouse;
uniform float height;
uniform vec3 sunColor;

in vec2 v_texcoord;
out vec4 fragColor;

float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float vnoise(vec2 p) {
    vec2 i = floor(p), f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y);
}
float terrain(vec2 p) {
    float h = 0.0, a = 0.5;
    mat2 m = mat2(1.6, 1.2, -1.2, 1.6);
    for (int i = 0; i < 6; i++) { h += a * vnoise(p); p = m * p; a *= 0.5; }
    return h * height;
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    vec3 ro = vec3(0.0, height * 0.9 + 0.3, time * 0.6);
    float yaw = (mouse.x - 0.5) * 2.0, pitch = (mouse.y - 0.5) * 0.8 - 0.15;
    vec3 fw = normalize(vec3(sin(yaw), pitch, cos(yaw)));
    vec3 rt = normalize(cross(vec3(0, 1, 0), fw)), up = cross(fw, rt);
    vec3 rd = normalize(uv.x * rt + uv.y * up + 1.5 * fw);
    vec3 sun = normalize(vec3(0.6, 0.35, 0.8));

    float t = 0.05, hit = 0.0;
    for (int i = 0; i < 160; i++) {
        vec3 p = ro + rd * t;
        float d = p.y - terrain(p.xz);
        if (d < 0.002 * t) { hit = 1.0; break; }
        t += d * 0.45;
        if (t > 30.0) break;
    }
    vec3 sky = mix(vec3(0.55, 0.65, 0.8), vec3(0.2, 0.3, 0.55), clamp(rd.y * 2.0, 0.0, 1.0));
    sky += sunColor * pow(max(dot(rd, sun), 0.0), 64.0);
    vec3 col = sky;
    if (hit > 0.5) {
        vec3 p = ro + rd * t;
        vec2 e = vec2(0.01, 0.0);
        vec3 n = normalize(vec3(terrain(p.xz - e.xy) - terrain(p.xz + e.xy), 2.0 * e.x, terrain(p.xz - e.yx) - terrain(p.xz + e.yx)));
        float dif = max(dot(n, sun), 0.0);
        vec3 rock = mix(vec3(0.3, 0.25, 0.2), vec3(0.25, 0.35, 0.15), smoothstep(0.7, 0.9, n.y));
        rock = mix(rock, vec3(0.95), smoothstep(0.75, 0.9, p.y / height) * smoothstep(0.6, 0.8, n.y));  // snow
        col = rock * (dif * sunColor + vec3(0.2, 0.25, 0.35));
        col = mix(col, sky, 1.0 - exp(-0.08 * t));
    }
    fragColor = vec4(pow(col, vec3(0.8)), 1.0);
}

More Starters examples

Game of Life · Instanced cubes · Wireframe waves · Bloom · Dal Platinum · Bass rings · Radial spectrum · Ridgelines