| 1 |
#ifdef GL_ES |
| 2 |
precision mediump float; |
| 3 |
#endif |
| 4 |
|
| 5 |
/* This shader implements Phong shading (see http://en.wikipedia.org/wiki/Phong_reflection_model for the math). |
| 6 |
* It is not the most optimized version of it, as it sticks closely to the mathematics of the model. */ |
| 7 |
|
| 8 |
uniform vec3 light_position; |
| 9 |
/* diffuse color specifies the color of the illumination outside of the highlights, but still within the light |
| 10 |
* radius */ |
| 11 |
uniform vec4 diffuse_color; |
| 12 |
/* alpha is the shininess of a surface. 1 is dull, >1 is shiny. <1 is weird :) */ |
| 13 |
uniform float alpha; |
| 14 |
|
| 15 |
varying vec3 pixel_position; |
| 16 |
varying vec3 normal; |
| 17 |
|
| 18 |
/* Ambient color and intensity specify the color of the illumination outside the range of the light */ |
| 19 |
#define AMBIENT_COLOR vec4(1, 1, 1, 1) |
| 20 |
#define AMBIENT_INTENSITY 0.01 |
| 21 |
/* Specifies the color of the highlights */ |
| 22 |
#define SPECULAR_COLOR vec4(1, 1, 1, 1) |
| 23 |
|
| 24 |
void main() |
| 25 |
{ |
| 26 |
/* Vector pointing from the point on the surface to the light */ |
| 27 |
vec3 light_vector = light_position - pixel_position; |
| 28 |
/* Unit vector of the above */ |
| 29 |
vec3 light_dir = normalize(light_vector); |
| 30 |
/* Unit vector normal to the surface (linear interpolation between vertex normals does not produce unit vectors in most cases)*/ |
| 31 |
vec3 normal_vector = normalize(normal); |
| 32 |
|
| 33 |
/* Reflectance is used for both diffuse components and specular components. It needs to be non-negative */ |
| 34 |
float reflectance = dot(light_dir, normal_vector); |
| 35 |
reflectance = max(reflectance, 0.0); |
| 36 |
|
| 37 |
/* Computes the reflection of the light and then the degree to which it points at the camera. This also is non-negative. |
| 38 |
* (0, 0, 1) is the vector that points at the camera */ |
| 39 |
float specular_intensity = dot((2.0 * reflectance * normal_vector - light_dir), vec3(0.0, 0.0, 1.0)); |
| 40 |
specular_intensity = max(0.0, specular_intensity); |
| 41 |
specular_intensity = pow(specular_intensity, alpha); |
| 42 |
|
| 43 |
/* Compute diffuse intensity by attenuating reflectance with a simple quadratic distance falloff */ |
| 44 |
float diffuse_intensity = reflectance * 10000.0 / dot(light_vector, light_vector); |
| 45 |
|
| 46 |
/* The final color is the combination of the 3 light sources */ |
| 47 |
gl_FragColor = AMBIENT_COLOR * AMBIENT_INTENSITY + diffuse_color * diffuse_intensity + SPECULAR_COLOR * specular_intensity; |
| 48 |
} |