1

I'm learning OpenGL. And I just learned about matching an output variable in a vertex shader to an input variable in a fragment shader by giving them the same name.

So I wrote this vertex shader:

#version 330 core
layout (location = 0) in vec3 aPos;
out vec3 vertexColor;

void main()
{
   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
   vertexColor = vec3(aPos.x, aPos.y, 1);
}

and wrote this fragment shader:

#version 330 core
in vec3 vertexColor;
out vec4 FragColor;
void main()
{
   FragColor = vec4(vertexColor.xyz, 1.0f);
}

This is what I got:

enter image description here

I thought that vertex shaders were run once per vertex, but the each triangle is colored by a gradient, which is very confusing, since it seems that the vertex shader is run for every pixel, which I don't think is the case here. So, what is going on?

0

1 Answer 1

3

The vertex shader is executed for each vertex. The fragment shader is executed for each fragment (pixel). The outputs of the vertex shader of a primitive are interpolated for the fragments covered by that primitive. The interpolated value is the input for the fragment shader. This is how you get the gradient, because the vertices of the triangle have different color attributes and these colors are interpolated over the triangle.

Sign up to request clarification or add additional context in comments.

4 Comments

In fact, this is the reason vertex and fragment shaders are separate! Data goes through the vertex shader, then the built-in interpolation, then the fragment shader
I hypothesized that might be the case, thanks! Also, is there any way to override the default interpolation logic? i.e.: could I specify a formula/function to be used in place of the default interpolation?
You can't specify your own formula, however you can use an Interpolation qualifier (e.g. flat)
@AlessandroDiCicco you could interpolate something like 0 to 1 (the default way) and then the fragment shader could calculate the real thing you want to interpolate - sometimes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.