ssao_optimized.frag 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #version 330 core
  2. out float fragColor;
  3. noperspective in highp vec2 v_texCoords;
  4. uniform sampler2D u_gPosition; //position view space
  5. uniform isampler2D u_gNormal;
  6. uniform sampler2D u_texNoise;
  7. uniform vec3 samples[64];
  8. uniform mat4 u_projection; // camera projection matrix
  9. uniform mat4 u_view; // camera view matrix
  10. const int kernelSize = 64;
  11. layout(std140) uniform u_SSAODATA
  12. {
  13. float radius;
  14. float bias;
  15. int samplesTestSize; // should be less than kernelSize
  16. }ssaoDATA;
  17. vec3 fromuShortToFloat(ivec3 a)
  18. {
  19. vec3 ret = a;
  20. //[0 65536] -> [0 1]
  21. ret /= 65536;
  22. //[0 1] -> [0 2]
  23. ret *= 2.f;
  24. //[0 2] -> [-1 1]
  25. ret -= 1.f;
  26. return normalize(ret);
  27. }
  28. void main()
  29. {
  30. vec2 screenSize = textureSize(u_gPosition, 0).xy/2.f; //smaller rez
  31. vec2 noiseScale = vec2(screenSize.x/4.0, screenSize.y/4.0);
  32. vec2 noisePos = v_texCoords * noiseScale;
  33. vec3 fragPos = texture(u_gPosition, v_texCoords).xyz;
  34. vec3 normal = normalize( vec3(transpose(inverse(mat3(u_view))) *
  35. fromuShortToFloat(texture(u_gNormal, v_texCoords).xyz)) );
  36. vec3 randomVec = texture2D(u_texNoise, noisePos).xyz;
  37. vec3 tangent = normalize(randomVec - normal * dot(randomVec, normal));
  38. vec3 bitangent = cross(normal, tangent);
  39. mat3 TBN = mat3(tangent, bitangent, normal);
  40. float occlusion = 0.0;
  41. int begin = int((kernelSize - ssaoDATA.samplesTestSize) * abs(randomVec.x));
  42. for(int i = begin; i < begin + ssaoDATA.samplesTestSize; ++i)
  43. {
  44. vec3 samplePos = TBN * samples[i]; // from tangent to view-space
  45. //vec3 samplePos = TBN * normalize(vec3(0.5, 0.3, 0.4));
  46. samplePos = fragPos + samplePos * ssaoDATA.radius;
  47. vec4 offset = vec4(samplePos, 1.0);
  48. offset = u_projection * offset; // from view to clip-space
  49. offset.xyz /= offset.w; // perspective divide
  50. offset.xyz = offset.xyz * 0.5 + 0.5; // transform to range 0.0 - 1.0
  51. //if(dot(normal, normalize(offset.xyz)) > 0.02) //1.14 degrees
  52. {
  53. // get sample depth
  54. //float sampleDepth = vec3( u_view * vec4(texture(u_gPosition, offset.xy).xyz,1) ).z;
  55. float sampleDepth = texture(u_gPosition, offset.xy).z; // get depth value of kernel sample
  56. // range check & accumulate
  57. float rangeCheck = smoothstep(0.0, 1.0, ssaoDATA.radius / abs(fragPos.z - sampleDepth));
  58. occlusion += (sampleDepth >= samplePos.z + ssaoDATA.bias ? 1.0 : 0.0) * rangeCheck;
  59. }
  60. }
  61. occlusion = 1.0 - (occlusion / kernelSize);
  62. fragColor = occlusion;
  63. //fragColor = v_texCoords.y;
  64. //fragColor = normal.z;
  65. //fragColor = sqrt(abs(randomVec.x));
  66. }