Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #version 330 core
- in VS_OUT {
- vec2 TexCoord;
- vec3 WorldPos;
- mat3 TBN;
- vec4 FragPosLightSpace;
- } fs_in;
- out vec4 fragColor;
- struct Material {
- sampler2D diffuseMap;
- sampler2D specularMap;
- sampler2D normalMap;
- sampler2D shadowMap;
- float shininess;
- };
- struct DirLight {
- //vec3 position;
- vec3 direction;
- vec3 ambient;
- vec3 diffuse;
- vec3 specular;
- vec3 color;
- };
- uniform vec3 viewPos;
- uniform DirLight dirLight;
- uniform Material material;
- float ShadowCalculation(vec4 fragPosLightSpace, vec3 normal, vec3 lightDir)
- {
- vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
- projCoords = projCoords * 0.5 + 0.5;
- if(projCoords.z > 1.0)
- return 0.0;
- float closestDepth = texture(material.shadowMap, projCoords.xy).r;
- float currentDepth = projCoords.z;
- float bias = max(0.05 * (1.0 - dot(normal, lightDir)), 0.005);
- //float shadow = currentDepth - bias > closestDepth ? 1.0 : 0.0;
- float shadow = 0.0;
- vec2 texelSize = 1.0 / textureSize(material.shadowMap, 0);
- for(int x = -1; x <= 1; ++x)
- {
- for(int y = -1; y <= 1; ++y)
- {
- float pcfDepth = texture(material.shadowMap, projCoords.xy + vec2(x, y) * texelSize).r;
- shadow += currentDepth - bias > pcfDepth ? 1.0 : 0.0;
- }
- }
- shadow /= 9.0;
- return shadow;
- }
- vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
- {
- vec3 color = texture(material.diffuseMap, fs_in.TexCoord).rgb;
- vec3 lightDir = normalize(-light.direction);
- vec3 halfwayDir = normalize(lightDir + viewDir); //Blinn
- float diff = max(dot(normal, lightDir), 0.0);
- vec3 reflectDir = reflect(-lightDir, normal);
- float spec = pow(max(dot(normal, halfwayDir), 0.0), material.shininess); //Blinn
- vec3 ambient = light.ambient * color;
- vec3 diffuse = light.diffuse * diff * color;
- vec3 specular = light.specular * spec * vec3(texture(material.specularMap, fs_in.TexCoord));
- float shadow = ShadowCalculation(fs_in.FragPosLightSpace, normal, lightDir);
- return (ambient + (1.0 - shadow) * (diffuse + specular));
- //return (ambient + diffuse + specular);
- }
- void main()
- {
- vec3 normal = normalize(vec3(texture(material.normalMap, fs_in.TexCoord).rgb));
- normal = normal * 2.0 - 1.0;
- normal = normalize(normal);
- //check if drawing a mirrored fragment
- vec3 tangent = fs_in.TBN[0];
- vec3 bitangent = fs_in.TBN[1];
- vec3 calcN = cross(tangent, bitangent);
- float normalsAligned = dot(calcN, fs_in.TBN[2]);
- if (normalsAligned < 0) {
- tangent =-tangent;
- mat3 TBN_CORRECT = fs_in.TBN;
- TBN_CORRECT[0] = tangent;
- normal = normalize(TBN_CORRECT * normal);
- }
- else {
- normal = normalize(fs_in.TBN * normal);
- }
- vec3 viewDir = normalize(viewPos - fs_in.WorldPos);
- vec3 result = CalcDirLight(dirLight, normal, viewDir) * dirLight.color;
- fragColor = vec4(result, 1.0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement