ssao.frag 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // From paper http://graphics.cs.williams.edu/papers/AlchemyHPG11/
  2. // and improvements here http://graphics.cs.williams.edu/papers/SAOHPG12/
  3. uniform sampler2D dtex;
  4. uniform float radius;
  5. uniform float k = 1.5;
  6. uniform float sigma = 1.;
  7. out float AO;
  8. const float tau = 7.;
  9. const float beta = 0.002;
  10. const float epsilon = .00001;
  11. #define SAMPLES 16
  12. const float invSamples = 1. / SAMPLES;
  13. vec3 getXcYcZc(int x, int y, float zC)
  14. {
  15. // We use perspective symetric projection matrix hence P(0,2) = P(1, 2) = 0
  16. float xC= (2 * (float(x)) / screen.x - 1.) * zC / ProjectionMatrix[0][0];
  17. float yC= (2 * (float(y)) / screen.y - 1.) * zC / ProjectionMatrix[1][1];
  18. return vec3(xC, yC, zC);
  19. }
  20. void main(void)
  21. {
  22. vec2 uv = gl_FragCoord.xy / screen;
  23. float lineardepth = textureLod(dtex, uv, 0.).x;
  24. int x = int(gl_FragCoord.x), y = int(gl_FragCoord.y);
  25. vec3 FragPos = getXcYcZc(x, y, lineardepth);
  26. // get the normal of current fragment
  27. vec3 ddx = dFdx(FragPos);
  28. vec3 ddy = dFdy(FragPos);
  29. vec3 norm = normalize(cross(ddy, ddx));
  30. float r = radius / FragPos.z;
  31. float phi = 3. * (x ^ y) + x * y;
  32. float bl = 0.0;
  33. float m = log2(r) + 6 + log2(invSamples);
  34. float theta = 2. * 3.14 * tau * .5 * invSamples + phi;
  35. vec2 rotations = vec2(cos(theta), sin(theta)) * screen;
  36. vec2 offset = vec2(cos(invSamples), sin(invSamples));
  37. for(int i = 0; i < SAMPLES; ++i) {
  38. float alpha = (i + .5) * invSamples;
  39. rotations = vec2(rotations.x * offset.x - rotations.y * offset.y, rotations.x * offset.y + rotations.y * offset.x);
  40. float h = r * alpha;
  41. vec2 localoffset = h * rotations;
  42. m = m + .5;
  43. ivec2 ioccluder_uv = ivec2(x, y) + ivec2(localoffset);
  44. if (ioccluder_uv.x < 0 || ioccluder_uv.x > screen.x || ioccluder_uv.y < 0 || ioccluder_uv.y > screen.y) continue;
  45. float LinearoccluderFragmentDepth = textureLod(dtex, vec2(ioccluder_uv) / screen, max(m, 0.)).x;
  46. vec3 OccluderPos = getXcYcZc(ioccluder_uv.x, ioccluder_uv.y, LinearoccluderFragmentDepth);
  47. vec3 vi = OccluderPos - FragPos;
  48. bl += max(0, dot(vi, norm) - FragPos.z * beta) / (dot(vi, vi) + epsilon);
  49. }
  50. AO = max(pow(1.0 - min(2. * sigma * bl * invSamples, 0.99), k), 0.);
  51. }