Rotating a texture on a Fragment Shader in GLSL ES
Asked Answered
C

2

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);
    }
Cambogia answered 21/1, 2015 at 19:12 Comment(2)
I'm looking for it too ! Is it solved ?Hygrostat
I did this by building a matrix to rotate outside of the shader, #31417865, you may also find this helpful for figuring out the matrix components, songho.ca/opengl/gl_projectionmatrix.htmlOndometer
U
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);
Unexacting answered 24/5, 2016 at 13:15 Comment(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 answerAeromarine
X
-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.

Xray answered 24/10, 2015 at 2:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.