I'm fairly new to shaders and came across the Book of Shaders website. Early on, this piece of code appears and surprisingly he didn't teach about how variables work yet so I can't get my head around the color variable. This code simultaneously displays a left to right fading background (black to white) and a green diagonal line.
So, essentially, you declare vec3 color to be vec3(y) which means all the 3 r,g,b values will be same throughout. I get why the fading background occurs because r, g, b stay equal and range between 0 and 1.
But coming from a JS and PHP background, normally if I change the value of a variable later, only the new value is accepted. So I was expecting that the lerping value out of color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0); would overwrite the previous vec3 color = vec3(y); and be considered for gl_FragColor function. But it appears both the versions of color are drawn: the fading BG and the green line. Is this how the shader code works, by drawing every definition of a variable?
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
// Plot a line on Y using a value between 0.0-1.0
float plot(vec2 st) {
return smoothstep(0.02, 0.0, abs(st.y - st.x));
}
void main() {
vec2 st = gl_FragCoord.xy/u_resolution;
float y = st.x;
vec3 color = vec3(y);
// Plot a line
float pct = plot(st);
color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0);
gl_FragColor = vec4(color,1.0);
}
First
vec3 color = vec3(y);declarescolorand assigns the right to left black and white gradient to it. Then,color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0);assigns an new value to color which is a lerp between its old value (color), and its new valuevec3(0.0,1.0,0.0)(green). It is equivalent to do :The old value is overwritten but as the new definition uses this old value, you can still see the background gradient.