Lesson 3 of 10 · Ray marching in GLSL
The march
The ray takes safe steps. Here you see how hard it works.
This is the trick that names raymarching. The ray does not walk blind: the SDF tells it the distance to the nearest object, so it can jump exactly that far without piercing anything. It lands close, asks again, jumps less. Each loop of the for is one step.
To see it, we paint by step count: rays grazing the silhouette take many tiny steps and glow; rays heading into the void escape in a few.
t += d
t is how far the ray has advanced. d is the safe distance the SDF returns. Adding it (t+=d) is the jump. The 0.9 shortens it a touch, safer near edges.Lower the
0.9 in d*0.9 and the march takes shorter steps: more steps, thicker halo. The second slider opens the spectrum (steps*0.03).The code
precision highp float;
float map(vec3 p){
return length(p)-1.0;
}
void main(){
vec2 uv=(gl_FragCoord.xy*2.0-R)/R.y;
vec3 ro=vec3(0.0,0.0,3.0);
vec3 rd=normalize(vec3(uv,-1.5));
float t=0.0;
float steps=0.0;
for(int i=0;i<64;i++){
vec3 pos=ro+rd*t;
float d=map(pos);
if(d<0.001 || t>12.0) break;
t+=d*0.9;
steps+=1.0;
}
vec3 col=iri(steps*0.03+0.1);
col*=0.18+steps*0.013;
gl_FragColor=vec4(col,1.0);
}