MotionBlur.glsl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2009-2020, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <shaders/Common.glsl>
  7. // TAA blurs the edges of objects and expands them. The velocity in the edges may be zero (static object) so that will
  8. // create an outline around those objects
  9. #if !defined(TAA_FIX)
  10. # define TAA_FIX 1
  11. #endif
  12. // Perform motion blur.
  13. Vec3 motionBlur(texture2D velocityTex, sampler velocityTexSampler, texture2D toBlurTex, sampler toBlurTexSampler,
  14. texture2D depthTex, sampler depthTexSampler, Vec2 nowUv, Mat4 prevViewProjMatMulInvViewProjMat,
  15. U32 maxSamples)
  16. {
  17. // Compute previous UV
  18. Vec2 velocity = textureLod(velocityTex, velocityTexSampler, nowUv, 0.0).rg;
  19. // Compute the velocity if it's static geometry
  20. ANKI_BRANCH if(velocity.x == -1.0)
  21. {
  22. #if TAA_FIX
  23. const Vec2 a = textureLodOffset(sampler2D(velocityTex, velocityTexSampler), nowUv, 0.0, ivec2(-2, 2)).rg;
  24. const Vec2 b = textureLodOffset(sampler2D(velocityTex, velocityTexSampler), nowUv, 0.0, ivec2(2, 2)).rg;
  25. const Vec2 c = textureLodOffset(sampler2D(velocityTex, velocityTexSampler), nowUv, 0.0, ivec2(0, -2)).rg;
  26. velocity = max(max(a, b), c);
  27. ANKI_BRANCH if(velocity.x == -1.0)
  28. #endif
  29. {
  30. const F32 depth = textureLod(depthTex, depthTexSampler, nowUv, 0.0).r;
  31. const Vec4 v4 = prevViewProjMatMulInvViewProjMat * Vec4(UV_TO_NDC(nowUv), depth, 1.0);
  32. velocity = NDC_TO_UV(v4.xy / v4.w) - nowUv;
  33. }
  34. }
  35. // March direction
  36. const Vec2 slopes = abs(velocity);
  37. // Compute the sample count
  38. const Vec2 sampleCount2D = slopes * Vec2(FB_SIZE);
  39. F32 sampleCountf = max(sampleCount2D.x, sampleCount2D.y);
  40. sampleCountf = clamp(sampleCountf, 1.0, F32(maxSamples));
  41. sampleCountf = round(sampleCountf);
  42. // Loop
  43. Vec3 outColor = Vec3(0.0);
  44. ANKI_LOOP for(F32 s = 0.0; s < sampleCountf; s += 1.0)
  45. {
  46. const F32 f = s / sampleCountf;
  47. const Vec2 sampleUv = nowUv + velocity * f;
  48. outColor += textureLod(toBlurTex, toBlurTexSampler, sampleUv, 0.0).rgb;
  49. }
  50. outColor /= sampleCountf;
  51. return outColor;
  52. }