ssao.fragment.fx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #ifdef GL_ES
  2. precision highp float;
  3. #endif
  4. #define SAMPLES 16
  5. uniform sampler2D textureSampler;
  6. uniform sampler2D randomSampler;
  7. uniform float randTextureTiles;
  8. uniform float samplesFactor;
  9. uniform vec3 sampleSphere[16];
  10. uniform float totalStrength;
  11. uniform float radius;
  12. uniform float area;
  13. uniform float fallOff;
  14. varying vec2 vUV;
  15. const vec2 offset1 = vec2(0.0, 0.01);
  16. const vec2 offset2 = vec2(0.01, 0.0);
  17. vec3 normalFromDepth(const float depth, const vec2 coords) {
  18. float depth1 = texture2D(textureSampler, coords + offset1).r;
  19. float depth2 = texture2D(textureSampler, coords + offset2).r;
  20. vec3 p1 = vec3(offset1, depth1 - depth);
  21. vec3 p2 = vec3(offset2, depth2 - depth);
  22. vec3 normal = cross(p1, p2);
  23. normal.z = -normal.z;
  24. return normalize(normal);
  25. }
  26. void main(void)
  27. {
  28. const float base = 0.2;
  29. vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;
  30. float depth = texture2D(textureSampler, vUV).r;
  31. vec3 position = vec3(vUV, depth);
  32. vec3 normal = normalFromDepth(depth, vUV);
  33. float radiusDepth = radius / depth;
  34. float occlusion = 0.0;
  35. vec3 ray;
  36. vec3 hemiRay;
  37. float occlusionDepth;
  38. float difference;
  39. for (int i = 0; i < SAMPLES; i++)
  40. {
  41. ray = radiusDepth * reflect(sampleSphere[i], random);
  42. hemiRay = position + sign(dot(ray, normal)) * ray;
  43. occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;
  44. difference = depth - occlusionDepth;
  45. occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));
  46. }
  47. float ao = 1.0 - totalStrength * occlusion * samplesFactor;
  48. float result = clamp(ao + base, 0.0, 1.0);
  49. gl_FragColor.r = result;
  50. gl_FragColor.g = result;
  51. gl_FragColor.b = result;
  52. gl_FragColor.a = 1.0;
  53. }