based-lighting.frag
The Phong lighting fragment shader with constant object's materialgolxzn
glsl
a year ago
1.5 kB
13
Indexable
[glsl]
#version 300 core
layout(location = 0) in vec3 frag_position;
layout(location = 1) in vec3 frag_normal;
layout(location = 2) in vec2 frag_uv;
layout(location = 0) out vec4 frag_color;
struct Light {
vec3 position;
vec3 color;
};
struct Material {
vec3 ambient;
vec3 diffuse;
vec3 specular;
float shininess;
};
uniform sampler2D u_texture;
uniform Light u_light;
uniform Material u_material;
uniform vec3 u_view_position; // ONLY IF WE DON'T USE MODEL_VIEW!
void main() {
vec3 normal = normalize(frag_normal);
vec3 texel = texture(u_texture, frag_uv).rgb;
// AMBIENT COMPONENT
vec3 ambient = u_material.ambient * u_light.color; // you could use texel as well
// DIFFUSE COMPONENT
vec3 to_light = normalize(u_light.position - frag_position);
float diffuse_impact = max(dot(to_light, normal), 0.0);
vec3 diffuse = u_material.diffuse * diffuse_impact;
// SPECULAR COMPONENT
vec3 reflected = normalize(reflect(-to_light, normal));
vec3 to_eye = normalize(u_view_position - frag_position); // ONLY IF WE DON'T USE MODEL_VIEW!
// vec3 to_eye = normalize(-frag_position); // If we use MODEL_VIEW
float specular_impact = max(dot(reflected, to_eye), 0.0);
float specular_reformed = pow(specular_impact, u_material.shininess);
vec3 specular = u_material.specular * u_light.color * specular_reformed;
// GETTING RESULT FRAGMENT COLOR:
frag_color = vec4((ambient + diffuse + specular) * texel, 1.0);
}Editor is loading...
Leave a Comment