Reflection
[opengl.git] / texturefrag.glsl
index 347cc0121f35e4487e770e922c3f633010bf0486..2a3de5508c2aa078cb47eb2220133581949c80c9 100644 (file)
@@ -1,39 +1,74 @@
 #version 330
 
 struct Material {
-       vec3 ambient;
-       vec3 diffuse;
-       vec3 specular;
+       vec4 ambient;
+       vec4 diffuse;
+       sampler2D diffuseMap;
+       vec4 specular;
+       sampler2D specularMap;
        float shininess;
+
+       float reflectivity;
+       
        bool hasTexture;
+       bool hasSpecularMap;
+
+       sampler2D normalMap;
+       bool hasNormalMap;
 };
 
-in vec3 normal;
-in vec3 fragPos;
+in vec3 defNormal, worldNormal;
 in vec2 texCoord;
 
-uniform vec3 lightPos;
-uniform vec3 viewPos;
+// These are all in tangent space
+in vec3 lightPos;
+in vec3 viewPos;
+in vec3 fragPos;
+
+in vec3 worldViewPos, worldFragPos;
+
 uniform vec4 lightColor;
 
 uniform Material material;
-uniform sampler2D tex;
+
+uniform samplerCube skybox;
 
 out vec4 FragColor;
 
+vec4 reflection(vec3 normal) {
+       vec3 I = normalize(worldFragPos - worldViewPos);
+       vec3 R = reflect(I, normalize(normal));
+       return vec4(texture(skybox, R).rgb, 1);
+}
+
 void main() {
-       vec3 lightDir = normalize(fragPos - lightPos);
-       vec3 diffuse = max(0, dot(-normal, lightDir)) * material.diffuse;
+       vec3 normal = texture(material.normalMap, texCoord).rgb;
+       normal = normalize(normal * 2 - 1);
+       if (!material.hasNormalMap)
+               normal = defNormal;
+
+       vec3 lightDir = normalize(lightPos - fragPos);
+       
+       vec4 diffTex = texture(material.diffuseMap, texCoord);
+       if (!material.hasTexture)
+               diffTex = material.diffuse;
+       
+       diffTex = mix(diffTex, reflection(worldNormal), material.reflectivity);
        
-       vec3 viewDir = normalize(fragPos - viewPos);
+       vec4 ambient = material.ambient * diffTex;
+
+       vec4 diffuse = max(0, dot(lightDir, normal)) * diffTex;
+
+       vec3 viewDir = normalize(viewPos - fragPos);
        vec3 reflectDir = reflect(-lightDir, normal);
-       vec3 specular = pow(max(0, dot(viewDir, reflectDir)), material.shininess) * material.specular;
 
-       vec4 lighting = vec4(material.ambient + diffuse + specular, 1) * lightColor;
+       vec4 specTex = texture(material.specularMap, texCoord);
+       if (!material.hasSpecularMap)
+               specTex = material.specular;
+
+       vec4 specular = pow(max(0, dot(viewDir, reflectDir)), material.shininess) * specTex;
+
+       FragColor = (ambient + diffuse + specular) * lightColor;
 
-       if (material.hasTexture)
-               FragColor = lighting * texture(tex, texCoord);
-       else
-               FragColor = lighting;
 }