lens_distorted.glsl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* clang-format off */
  2. [vertex]
  3. #ifdef USE_GLES_OVER_GL
  4. #define lowp
  5. #define mediump
  6. #define highp
  7. #else
  8. precision highp float;
  9. precision highp int;
  10. #endif
  11. layout(location = 0) in highp vec2 vertex;
  12. /* clang-format on */
  13. uniform vec2 offset;
  14. uniform vec2 scale;
  15. out vec2 uv_interp;
  16. void main() {
  17. uv_interp = vertex.xy * 2.0 - 1.0;
  18. vec2 v = vertex.xy * scale + offset;
  19. gl_Position = vec4(v, 0.0, 1.0);
  20. }
  21. /* clang-format off */
  22. [fragment]
  23. #ifdef USE_GLES_OVER_GL
  24. #define lowp
  25. #define mediump
  26. #define highp
  27. #else
  28. #if defined(USE_HIGHP_PRECISION)
  29. precision highp float;
  30. precision highp int;
  31. #else
  32. precision mediump float;
  33. precision mediump int;
  34. #endif
  35. #endif
  36. uniform sampler2D source; //texunit:0
  37. /* clang-format on */
  38. uniform vec2 eye_center;
  39. uniform float k1;
  40. uniform float k2;
  41. uniform float upscale;
  42. uniform float aspect_ratio;
  43. in vec2 uv_interp;
  44. layout(location = 0) out vec4 frag_color;
  45. void main() {
  46. vec2 coords = uv_interp;
  47. vec2 offset = coords - eye_center;
  48. // take aspect ratio into account
  49. offset.y /= aspect_ratio;
  50. // distort
  51. vec2 offset_sq = offset * offset;
  52. float radius_sq = offset_sq.x + offset_sq.y;
  53. float radius_s4 = radius_sq * radius_sq;
  54. float distortion_scale = 1.0 + (k1 * radius_sq) + (k2 * radius_s4);
  55. offset *= distortion_scale;
  56. // reapply aspect ratio
  57. offset.y *= aspect_ratio;
  58. // add our eye center back in
  59. coords = offset + eye_center;
  60. coords /= upscale;
  61. // and check our color
  62. if (coords.x < -1.0 || coords.y < -1.0 || coords.x > 1.0 || coords.y > 1.0) {
  63. frag_color = vec4(0.0, 0.0, 0.0, 1.0);
  64. } else {
  65. coords = (coords + vec2(1.0)) / vec2(2.0);
  66. frag_color = texture(source, coords);
  67. }
  68. }