luluco250

Aspect Ratio Fix Shader

Mar 15th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. vec2 ps = vec2(1.0) / iResolution.xy;
  2. float ar = iResolution.x / iResolution.y;
  3. const vec2 image_res = vec2(3840, 2160);
  4. const float image_ar = image_res.x / image_res.y;
  5.  
  6. vec2 scaleUV(vec2, vec2);
  7. bool crop(vec2);
  8. vec2 correctAspect(vec2);
  9.  
  10. void main() {
  11.     vec2 uv = gl_FragCoord.xy * ps;
  12.     vec2 image_uv = correctAspect(uv);
  13.     vec3 col = texture2D(iChannel0, image_uv).rgb;
  14.     col = crop(uv) ? col : vec3(0.0);
  15.  
  16.     gl_FragColor = vec4(col, 1.0);
  17. }
  18.  
  19. vec2 scaleUV(vec2 uv, vec2 scale) {
  20.     return (uv - vec2(0.5)) * scale + vec2(0.5);
  21. }
  22.  
  23. bool crop(vec2 uv) {
  24.     bool x_or_y = ar > image_ar;
  25.     float ar_result = x_or_y ? (image_ar / ar) :
  26.                                (ar / image_ar);
  27.     float mask = (1.0 - (ar_result)) * 0.5;
  28.     return x_or_y ? (uv.x > mask && uv.x < 1.0 - mask) :
  29.                     (uv.y > mask && uv.y < 1.0 - mask);
  30. }
  31.  
  32. vec2 correctAspect(vec2 uv) {
  33.     bool x_or_y = ar > image_ar;
  34.     vec2 ar_fix = vec2(1.0);
  35.     ar_fix = x_or_y ? vec2(ar / image_ar, 1.0) :
  36.                       vec2(1.0, image_ar / ar);
  37.     uv = scaleUV(uv, ar_fix);
  38.     return uv;
  39. }
Add Comment
Please, Sign In to add comment