#version 330 core // Fragment shader for basic lighting with texture mapping out vec4 outputColor; // The final output color of the fragment // --- INPUTS --- // These come from the Vertex Shader in vec3 FragPos; in vec3 Normal; in vec2 TexCoord; in mat3 vTBN; // Tangent, Bitangent, Normal matrix struct MaterialProperty { vec3 ambientColour; vec3 diffuseColour; vec3 specularColour; float shininess; }; struct LightProperty { vec3 position; vec3 ambientColour; vec3 diffuseColour; vec3 specularColour; float constant; float linear; float quadratic; }; // --- UNIFORMS --- uniform sampler2D uTexture; // Image Texture uniform sampler2D uNormalMap; // Normal Map Texture uniform vec3 uViewPos; // Camera Position uniform MaterialProperty uMaterial; // Material Properties uniform LightProperty uPointLight; // Light Properties uniform int uUseTexture; // Flag to indicate if texture should be used uniform int uUseNormalMap; // Flag to indicate if normal map should be used vec3 CalcPointLight(LightProperty light, vec3 normal, vec3 fragPos, vec3 viewDir) { vec3 lightDir = normalize(light.position - fragPos); // 1. Diffuse shading float diff = max(dot(normal, lightDir), 0.0); // 2. Specular shading vec3 reflectDir = reflect(-lightDir, normal); float spec = pow(max(dot(viewDir, reflectDir), 0.0), uMaterial.shininess); // 3. Attenuation float distance = length(light.position - fragPos); float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance)); // 4. Combine results vec3 ambient = light.ambientColour * uMaterial.ambientColour; vec3 diffuse = light.diffuseColour * diff * uMaterial.diffuseColour; vec3 specular = light.specularColour * spec * uMaterial.specularColour; ambient *= attenuation; diffuse *= attenuation; specular *= attenuation; return (ambient + diffuse + specular); } void main() { vec3 norm; if (uUseNormalMap == 1) { vec3 normalFromTexture = texture(uNormalMap, TexCoord).rgb; vec3 colourShift = normalFromTexture * 2.0 - 1.0; // Transform from [0,1] to [-1,1] // 1. Setup Vectors norm = normalize(vTBN * colourShift); } else { norm = normalize(Normal); } vec3 viewDir = normalize(uViewPos - FragPos); // 2. Calculate Lighting using the Function vec3 result = CalcPointLight(uPointLight, norm, FragPos, viewDir); // 3. Apply Texture Switch if (uUseTexture == 1) { outputColor = vec4(result, 1.0) * texture(uTexture, TexCoord); } else { outputColor = vec4(result, 1.0); } }