111 lines
2.7 KiB
GLSL
111 lines
2.7 KiB
GLSL
#version 330 core
|
|
out vec4 FragColor;
|
|
|
|
struct Material {
|
|
sampler2D texture_diffuse1;
|
|
sampler2D texture_specular1;
|
|
float shininess;
|
|
};
|
|
|
|
struct DirLight {
|
|
vec3 direction;
|
|
|
|
vec3 ambient;
|
|
vec3 diffuse;
|
|
vec3 specular;
|
|
};
|
|
|
|
struct PointLight {
|
|
vec3 position;
|
|
|
|
float constant;
|
|
float linear;
|
|
float quadratic;
|
|
|
|
vec3 ambient;
|
|
vec3 diffuse;
|
|
vec3 specular;
|
|
};
|
|
|
|
#define MAX_POINT_LIGHTS 4
|
|
|
|
in vec3 FragPos;
|
|
in vec3 Normal;
|
|
in vec2 TexCoords;
|
|
|
|
uniform vec3 viewPos;
|
|
uniform Material material;
|
|
uniform DirLight dirLight;
|
|
uniform PointLight pointLights[MAX_POINT_LIGHTS];
|
|
uniform int numPointLights;
|
|
|
|
// Function prototypes
|
|
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir);
|
|
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir);
|
|
|
|
void main()
|
|
{
|
|
// Properties
|
|
vec3 norm = normalize(Normal);
|
|
vec3 viewDir = normalize(viewPos - FragPos);
|
|
|
|
// Phase 1: Directional lighting
|
|
vec3 result = CalcDirLight(dirLight, norm, viewDir);
|
|
|
|
// Phase 2: Point lights
|
|
for(int i = 0; i < 1; i++)
|
|
result += CalcPointLight(pointLights[i], norm, FragPos, viewDir);
|
|
|
|
// If no texture is bound, use a default color
|
|
vec4 texColor = vec4(0.8, 0.8, 0.8, 1.0);
|
|
|
|
FragColor = vec4(result, 1.0) * texColor;
|
|
}
|
|
|
|
// Calculates the color when using a directional light
|
|
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
|
|
{
|
|
vec3 lightDir = normalize(-light.direction);
|
|
|
|
// Diffuse shading
|
|
float diff = max(dot(normal, lightDir), 0.0);
|
|
|
|
// Specular shading
|
|
vec3 reflectDir = reflect(-lightDir, normal);
|
|
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32.0);
|
|
|
|
// Combine results
|
|
vec3 ambient = light.ambient;
|
|
vec3 diffuse = light.diffuse * diff;
|
|
vec3 specular = light.specular * spec;
|
|
|
|
return (ambient + diffuse + specular);
|
|
}
|
|
|
|
// Calculates the color when using a point light
|
|
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
|
|
{
|
|
vec3 lightDir = normalize(light.position - fragPos);
|
|
|
|
// Diffuse shading
|
|
float diff = max(dot(normal, lightDir), 0.0);
|
|
|
|
// Specular shading
|
|
vec3 reflectDir = reflect(-lightDir, normal);
|
|
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32.0);
|
|
|
|
// Attenuation
|
|
float distance = length(light.position - fragPos);
|
|
float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
|
|
|
|
// Combine results
|
|
vec3 ambient = light.ambient;
|
|
vec3 diffuse = light.diffuse * diff;
|
|
vec3 specular = light.specular * spec;
|
|
|
|
ambient *= attenuation;
|
|
diffuse *= attenuation;
|
|
specular *= attenuation;
|
|
|
|
return (ambient + diffuse + specular);
|
|
} |