Lesson 4 of 10 · GLSL shaders for beginners

Coordinates

Every frag knows where it is.

From “Hello, light” to “Mixing”, every frag got the same color and the screen came out flat. To paint each one differently, a frag needs to know where it is. Every frag on the screen has a position: two numbers, X and Y. X is horizontal (left-right), Y is vertical (bottom-top). Just like the coordinate plane.

Red to the right, green to the top. The screen turns into a map of positions.

Here is the key idea: every frag runs the code on its own, but it knows its own position. The frag at the bottom-left corner knows it is (0, 0). The one at the top-right corner, once divided by the screen size, knows it is (1, 1).

vec2If vec3 is a pack of 3 numbers, vec2 is a pack of 2. We use it for positions (X, Y). Here p is the frag position divided by the screen size, so it goes from 0 to 1 instead of 0 to 1920. gl_FragCoord.xy is that position in pixels and R is the size of your screen, for example (1920, 1080).

If you put p.x as red, the red increases to the right. Put p.y as green and the green increases upward. The color is the position.

Reading the codevec2 p = gl_FragCoord.xy / R;: the frag’s position divided by the screen size. It ends up between 0 and 1.
vec3(p.x, p.y, …): red = horizontal position, green = vertical position.
0.3 + 0.2 * sin(T * 0.5): the blue moves on its own from 0.1 to 0.5 and back. You don’t need it yet, you open it in “The clock”. The Blue slider moves the 0.3.
You know these: hueShift (03 · Mixing), vec4 (02 · The three numbers).
Next: in “The gradient” position picks between two colors.
TryChange the first p.x to p.y. Red and green rise together and the top turns yellow. Now put p.x in all three channels. Three equal channels make gray, black on the left and white on the right.

The code

void main(){
  vec2 p = gl_FragCoord.xy / R;
  vec3 col = vec3(p.x, p.y, 0.3 + 0.2 * sin(T * 0.5));
  col = hueShift(col, 0.0);
  gl_FragColor = vec4(col, 1.);
}