Take a Look at my Shaders:
Vertex Shader:
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
out vec3 FragPos;
out vec3 Normal;
void main()
{
gl_Position = proj * view * model * vec4(aPos, 1.0);
FragPos = vec3(model * vec4(aPos, 1.0));
Normal = normalize(mat3(transpose(inverse(model))) * aNormal);
}
Fragment Shader:
#version 330 core
out vec4 Color;
uniform vec3 viewPos;
struct Material
{
vec3 ambient;
vec3 diffuse;
vec3 specular;
float shininess;
};
uniform Material material;
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
uniform Light light;
in vec3 FragPos;
in vec3 Normal;
void main()
{
//Calculating the Light Direction From The Fragment Towards the light source.
vec3 lightDirection = normalize(light.position - FragPos);
//Calculating the camera direction.
vec3 camDirection = normalize(viewPos - FragPos);
//Calculating the reflection of the light.
vec3 reflection = reflect(-lightDirection, Normal);
//Calculating the Diffuse Factor.
float diff = max( dot(Normal, lightDirection), 0.0f );
//Calculate Specular.
float spec = pow( max( dot(reflection, camDirection), 0.0f ), material.shininess);
//Create the 3 components.
vec3 ambient = material.ambient * light.ambient;
vec3 diffuse = (material.diffuse * diff) * light.diffuse;
vec3 specular = (material.specular * spec) * light.specular;
//Calculate the final fragment color.
Color = vec4(ambient + diffuse + specular, 1.0f);
}
I can't understand how this:
FragPos = vec3(model * vec4(aPos, 1.0));
is actually the fragment position. This is just the vertex position transformed to world coordinates. The vertex shader is gonna get called n times where n is the number of vertices, so the above code is also going to get called n times. The actual fragments are a lot more so how can the above code generate all the fragments positions? Also what is a fragments position? Is it the (x,y) you need to move on the screen in order to find that pixel? I don't think so because i read that while you are in the fragment shader the actual pixels on the screen have not been determined yet because the viewport transformation happens at the end of the fragment shader.