Search code examples
glslshaderfragment-shader

About the rotation of the ellipse


I have a shader that rotates a rectangle in GLSL as shown below.

const float PI = 3.14159265359;


mat2 rotate2d (float _angle) {
    return mat2 (cos (_angle), -sin (_angle),
                sin (_angle), cos (_angle));
}

void main (void) {

    vec2 st = (gl_FragCoord.xy * 2.0 - resolution) /min(resolution.x,resolution.y);
    float p = 0.0;
    
   st = rotate2d (sin (time) * PI) * st;
    
    vec2 c = max (abs (st) - 0.2,0.0);
    p = length (c);
    p = ceil (p);
    
    vec3 color = vec3 (1.0-p);

    gl_FragColor = vec4 (color, 1.0);

}

I want to change the rectangle of this shader to the following ellipse and rotate it at the center point p, which is an ellipse. What should I do? Is it multiplication of r.x, r.y in the horizontal and vertical directions of the ellipse with rotate2d (sin (time) * PI) in the rotation or multiplication over the whole?

// Center point
vec2 p = vec2 (0.0,0.0);
// radius
vec2 r = vec2 (2.0,1.0);
// oval shape
float d = (length (p / r) - 1.0) * min (r.x, r.y);

Solution

  • Rotate the coordinates and calculate the distance from the point to the center of the ellipse. Set the color depending on the distance:

    const float PI = 3.14159265359;
    
    mat2 rotate2d(float _angle) 
    {
        return mat2(cos(_angle), -sin(_angle), sin(_angle), cos(_angle));
    }
    
    void main (void)
    {
        vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y);    
        st = rotate2d(time * PI) * st;
    
        vec2 center = vec2(0.0, 0.0);
        vec2 ab = vec2(0.2, 0.1);
        
        vec2 e = (st - center) / vec2(0.2, 0.1);
        float d = length(e);
        vec3 color = d < 1.0 ? vec3(1.0) : vec3(0.0);
    
        gl_FragColor = vec4(color, 1.0);
    }