Rotate texture on a fragment shader in GLSL ES

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

The rotation has a center of rotation in the center.

The algorithm works great when rendering in a square with a square shape, but when the square has a rectangular shape, the rendering result becomes messy. Can anyone solve the problem?

thanks

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); } 
+6
source share
2 answers

The following line of code that 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); 

not quite right. There are some bracketing errors.

The correct version is:

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

I have not tried it myself, but I think that since you use the texture coordinates in a rectangular space, this will cause rotation distortion without any factor to fix it.

You will need to give it a shape that will declare the width and height of your texture. In doing so, you can apply aspect ratio to correct 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); 

As I said, I have not tried it, but I had to do this in the past for such shaders. You may need to change Resolution.x / Resolution.y.

-1
source

Source: https://habr.com/ru/post/981360/


All Articles