Reputation: 157
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:
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?
Upvotes: 1
Views: 900
Reputation: 210878
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.
Upvotes: 3