1precision mediump float; 2 3in vec4 v_color; 4in vec2 v_texCoords; 5 6uniform vec3 u_viewPos; 7uniform mat4 u_inverseProjectionMatrix; 8 9uniform sampler2D u_diffuseTexture; 10uniform sampler2D u_normalTexture; 11uniform sampler2D u_positionTexture; 12uniform sampler2D u_depthTexture; 13 14out vec4 fragColor; 15 16struct Light { 17 vec3 lightPosition; 18 vec3 lightColor; 19}; 20 21const int NUM_LIGHTS = 10; 22uniform Light lights[NUM_LIGHTS]; 23 24void main () { 25 vec4 diffuse = texture(u_diffuseTexture, v_texCoords); 26 vec3 normal = normalize(texture(u_normalTexture, v_texCoords).xyz); 27 //vec3 position = texture(u_positionTexture, v_texCoords).xyz; 28 float specular = diffuse.a; 29 30 float near = 1.0; 31 float far = 100.0; 32 33 float depth = texture(u_depthTexture, v_texCoords).x * 2.0 - 1.0; 34 35 vec4 ndc = vec4(v_texCoords * 2.0 - 1.0, depth, 1.0); 36 37 vec4 position = (u_inverseProjectionMatrix * ndc); 38 position /= position.w; 39 40 vec3 lighting = diffuse.xyz * 0.3; //ambient 41 vec3 viewDir = normalize(u_viewPos - position.xyz); 42 43 vec3 halfview; 44 float spec; 45 46 float shiney = 37.0; 47 vec3 globalLightColor = vec3(1.0); 48 vec3 spotLightColor = vec3(1.0); 49 50 51 //spot light 52 for (int i = 0; i < NUM_LIGHTS; ++i) { 53 vec3 lightDir = normalize(lights[i].lightPosition - position.xyz); 54 float dist2 = dot(lightDir, lightDir); 55 lightDir *= inversesqrt(dist2); 56 float NdotL = clamp(dot(normal, lightDir), 0.0, 1.0); 57 58 float distance = length(lights[i].lightPosition - position.xyz); 59 float fallOff = (0.001 * distance) + (0.04 * distance * distance); 60 61 vec3 value = lights[i].lightColor * (NdotL / (1.0 + fallOff)); 62 63 vec3 pointdiffuse = value; 64 65 float halfDotView = max(0.0, dot(normal, normalize(lightDir + viewDir))); 66 vec3 pointSpec = value * pow(halfDotView, shiney); 67 68 lighting += (pointdiffuse + pointSpec) * diffuse.xyz; 69 } 70 71 72 73 //global light 74 vec3 globalLightDir = normalize(vec3(0.0, 100.0, 0.0) - position.xyz); 75 vec3 global = max(dot(normal, globalLightDir), 0.0) * globalLightColor * diffuse.xyz; 76 77 //specular 78 halfview = normalize(globalLightDir + viewDir); 79 spec = pow(max(dot(normal, halfview), 0.0), shiney); 80 vec3 specularglobal = globalLightColor * spec * specular; 81 82 lighting += global + specularglobal; 83 84 fragColor = vec4(lighting, 1.0); 85} 86