Skip to content

Instantly share code, notes, and snippets.

@n-yoda
Last active October 22, 2016 07:31
Show Gist options
  • Save n-yoda/6509ed92d0cafe08a97d to your computer and use it in GitHub Desktop.
Save n-yoda/6509ed92d0cafe08a97d to your computer and use it in GitHub Desktop.
Ray marching.
#ifdef GL_ES
precision mediump float;
#endif
#extension GL_OES_standard_derivatives : enable
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
vec3 dup(vec3 x) {
return mod(x - vec3(time, 0, 0), 4.0);
}
float dist(vec3 pos) {
pos = dup(pos);
return length(pos - vec3(2, 2, 2)) - 1.0;
}
vec3 norm(vec3 pos) {
pos = dup(pos);
return normalize(pos - vec3(2, 2, 2));
}
vec3 march(vec3 origin, vec3 ray) {
for (int i = 0; i < 100; ++i) {
origin += ray * dist(origin);
}
return origin;
}
vec2 trans(vec2 p) {
vec2 r = resolution;
float m =min(r.x, r.y);
return (p * 2.0 - 1.0) * r / m;
}
void main() {
vec2 pos = trans(gl_FragCoord.xy / resolution.xy);
vec2 m = trans(mouse);
vec3 screen = vec3(pos.x, pos.y, 1.0);
vec3 camera = vec3(0, 0, 0);
vec3 light = vec3(m.x * 2.0, 0.0, m.y * 5.0 + 5.0);
vec3 ray = normalize(screen - camera);
vec3 hit = march(camera, ray);
float d = dist(hit);
if (abs(d) < 0.01) {
vec3 n = norm(hit);
vec3 l = normalize(light - hit);
float a = length(light - hit);
gl_FragColor.xyz = vec3(1, 1, 1) * dot(n, l) / a * 5.0;
} else {
gl_FragColor = vec4(0, 0, 0, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment