Shader Basics
Task
You've written your first shaders: colors, variables, vectors, pixel positions and UV coordinates. Let's check that it all fits together before we move on to the built-in functions.
Answer all questions, then press Check answers. Each question explains its answer after the check, and you can try again as many times as you like.
:::question How many times does a fragment shader run to paint one frame?
- Once for the whole screen
- Once for every pixel
- Once for every row of pixels
- Only for the pixels that changed since the last frame
The program answers one question, what color is this pixel?, so the GPU runs it for every pixel, thousands of copies at the same time. :::
:::question
What color is vec4(1.0, 1.0, 0.0, 1.0)?
- White
- Green
- Yellow
- Orange
The first three numbers are red, green and blue light. Full red plus full green light, with no blue, makes yellow. :::
:::question
An overlay color has alpha 0.0. What do you see?
- Only the overlay color
- Only the background
- A black screen
- A half-and-half mix of the two
Alpha is how much the pixel covers the background: 1.0 is fully opaque, 0.0 is fully transparent, 0.5 is a mix.
:::
:::question
A pixel's color is vec4(0.5, 0.2, 0.8, 1.0) * 2.0. What blue value does the screen show?
-
0.8 -
1.0 -
1.6 -
0.4
Multiplying by a number scales every component: blue becomes 1.6. The screen can't be brighter than full, so values above 1.0 are shown as 1.0.
:::
:::question
What is vec3(1.0, 2.0, 3.0) * vec3(2.0, 0.5, 1.0)?
-
6.0 -
vec3(2.0, 1.0, 3.0) -
vec3(3.0, 2.5, 4.0) - A compilation error
Math on vectors works component by component: 1 * 2, 2 * 0.5, 3 * 1.
:::
:::question
Which of these swizzles are valid for vec4 color?
-
color.rgb -
color.zyx -
color.rrr -
color.xg
You can list components in any order and repeat them, but xyzw and rgba can't be mixed in one swizzle.
:::
:::question What position does the GPU give to the pixel in the corner where the coordinates start?
-
(0.0, 0.0) -
(0.5, 0.5) -
(1.0, 1.0) - It depends on the screen size
A pixel's position points to its center, counted in pixels from the corner, so the values end in .5.
:::
:::question Which of these values are the same for every pixel of one frame?
- The screen size,
iResolution - The time,
iTime - The pixel's position
- The pixel's UV coordinates
Uniforms like the screen size and the time are sent by the program, one value for all pixels. The pixel's position, and the UV computed from it, is different for every pixel. :::
:::question
The screen is 800 x 600. A pixel is at position (200.0, 450.0). What is its UV?
-
(200.0, 450.0) -
(0.25, 0.75) -
(0.75, 0.25) -
(4.0, 1.33)
UV is the pixel position divided by the screen size: 200 / 800 = 0.25, 450 / 600 = 0.75.
:::