summaryrefslogtreecommitdiff
path: root/advanced_lighting/2.gamma_correction/shaders/blinn_phong.frag
blob: 331fc8b762aabcd08cf94719d91dd3074455f895 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#version 330 core

in VS_OUT {
    vec3 frag_pos;
    vec3 normal;
    vec2 tex_coords;
} fs_in;

out vec4 frag_color;

uniform sampler2D texture0;
uniform vec3 light_positions[4];
uniform vec3 light_colors[4];
uniform vec3 view_pos;
uniform bool gamma_correction;

vec3 blinn_phong(vec3 light_dir, vec3 view_dir, vec3 normal,
		vec3 light_pos, vec3 light_color)
{
    float diff = max(dot(normal, light_dir), 0.0);
    vec3 diffuse = diff*light_color;

    vec3 halfway_dir = normalize(light_dir+view_dir);
    float spec = pow(max(dot(normal, halfway_dir), 0.0), 16.0);
    vec3 specular = spec*light_color;

    float distance = length(light_pos-fs_in.frag_pos);
    float attenuation = 1.0/(gamma_correction ? distance*distance : distance);

    return((diffuse+specular)*attenuation);
}

void main(void)
{
    vec3 view_dir = normalize(view_pos-fs_in.frag_pos);
    vec3 normal = normalize(fs_in.normal);
    vec3 texture_color = texture(texture0, fs_in.tex_coords).rgb;

    vec3 lighting = vec3(0.0);
    for (int i = 0; i < 4; i++) {
        vec3 light_pos = light_positions[i];
        vec3 light_color = light_colors[i];
        vec3 light_dir = normalize(light_pos-fs_in.frag_pos);
        lighting += blinn_phong(light_dir, view_dir, normal,
                                light_pos, light_color);
    }

    texture_color *= lighting;

    float gamma = 2.2;
    if (gamma_correction)
        texture_color = pow(texture_color, vec3(1.0/gamma));

    frag_color = vec4(texture_color, 1.0);
}