Shader Gradient

It took me a while to grasp how gradients in Cg/HLSL work. For some reason, all the tutorials I watched/read do not teach you the basics, or at least, they do not tell you why they suddenly do this and that, and magic gradients happen.

The following is not a tutorial since I’m just a beginner. I’d like to share what I learnt in a way how I am learning. There is a logical structure, and once I got it, it all makes sense. To be honest, I’m not that interested in the visual output but in the algorithms. I don’t know if everything I’m writing here is correct but when I spot an error, I’ll edit this post.

First of all, a shader works vertex by vertex and pixel by pixel starting at the bottom left, stopping at the top right corner. The pixels between the vertices are interpolated.

The following line or a variant can be found in many tutorials:

return float4(input.uv.x, input.uv.y, 0, 1);

And it returns this:

I wondered where the black and the yellow colour came from when I just wanted a gradient from red to green. The answer is simple but not that obvious when you just look at the line of code and the picture. Take a look at the following image:

Colours consist of four components/channels: Red, Green, Blue and Alpha. As aforementioned, the shader iterates over the whole “image”, which is comparable to an array with a for loop. (I loooove arrays and for loops.)

Why is the bottom left corner black and the top right corner yellow?

                 color:  (r, g, b, a)
x == 0, y == 0   black:  (0, 0, 0, 1)
x == 1, y == 0   red:    (1, 0, 0, 1)
x == 0, y == 1   green:  (0, 1, 0, 1)
x == 1, y == 1   yellow: (1, 1, 0, 1)

Black makes sense because there is no colour, and yellow is an additive colour which consists of red and green. :D

Yes, I’m aware that this is super simple. Nevertheless, I’m happy that I grasped something. I don’t feel like a genius, I feel like someone who can now learn more to make their ideas work one day with a solid knowledge.

Next step: Bottom and top gradient on an existing picture, but the gradients are not supposed to fill the whole plane.