8

I'm trying to rotate a texture in a fragment shader, instead of using the vertex shader and matrix transformations.

The rotation has the pivot at the center.

The algorithm works fine when rendering in a quad with a square shape, but when the quad has a rectangular shape the render result gets messed up. Anyone can spot the problem?

Thank you

    varying vec2 v_texcoord;
    uniform sampler2D u_texture;
    uniform float u_angle;

    void main()
    {
        vec2 coord = v_texcoord;
        float sin_factor = sin(u_angle);
        float cos_factor = cos(u_angle);
        coord = (coord - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);
        coord += 0.5;

        gl_FragColor = texture2D(u_texture, coord);
    }
PerracoLabs
  • 16,449
  • 15
  • 74
  • 127
  • I'm looking for it too ! Is it solved ? – Samsy Mar 13 '15 at 11:24
  • I did this by building a matrix to rotate outside of the shader, http://stackoverflow.com/questions/31417365/how-to-rotate-a-texture-in-a-shader-android, you may also find this helpful for figuring out the matrix components, http://www.songho.ca/opengl/gl_projectionmatrix.html – HPP Jul 14 '15 at 21:33

2 Answers2

5

The following line of code which was provided in the question:

coord = vec2(coord.x - (0.5 * Resolution.x / Resolution.y), coord.y - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);

is not quite right. There are some bracketing errors.

The correct version would be:

coord = vec2((coord.x - 0.5) * (Resolution.x / Resolution.y), coord.y - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);
Sergey
  • 7,985
  • 4
  • 48
  • 80
  • 1
    This answer makes no sense - it seems to refer to code in another answer, which has been downvoted. I'd suggest editing the original answer rather than posting a new partial answer – Tim MB Oct 19 '19 at 14:09
-1

I haven't tried it out myself, but my guess is that since you are using the texture coordinates in a rectangular space, it will cause distortion upon rotation without some factor to correct it.

You'll need to pass it a uniform that declares the width and height of your texture. With this, you can apply the aspect ratio to correct the distortion.

coord = (coord - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);

may become something like:

coord = vec2(coord.x - (0.5 * Resolution.x / Resolution.y), coord.y - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);

Like I said though, I haven't tried it out, but I have had to do this in the past for similar shaders. Might need to reverse Resolution.x / Resolution.y.