Lesson 1 of 10 · Ray marching in GLSL
The ray
A camera, one ray per pixel. The sky is its direction.
Until now each pixel asked what color am I?. In 3D it asks something else: which way am I looking? Every pixel shoots a ray from the camera eye into the scene.
The eye is ro (ray origin). The direction is rd (ray direction), built from screen coordinates: normalize(vec3(uv,-fov)). Nothing to hit yet, so we paint the sky by where the ray points: one color up, another down.
ro and rd
ro is where the ray starts (the camera). rd is where it goes, a unit-length vector. All raymarching begins with these two. fov spreads the rays: higher = tighter lens, more zoom.Push
fov=1.5 to 2.5 and the world comes closer. The second slider sharpens the horizon sun (12.0).The code
precision highp float;
void main(){
vec2 uv=(gl_FragCoord.xy*2.0-R)/R.y;
vec3 ro=vec3(0.0,0.0,3.0);
float fov=1.5;
vec3 rd=normalize(vec3(uv,-fov));
float h=rd.y*0.5+0.5;
vec3 col=mix(vec3(0.42,0.16,0.12), vec3(0.10,0.14,0.40), h);
vec3 sunDir=normalize(vec3(0.3,0.25,-1.0));
float sun=pow(max(0.0,dot(rd,sunDir)),12.0);
col+=vec3(0.98,0.70,0.38)*sun*0.9;
gl_FragColor=vec4(col,1.0);
}