Search code examples
graphicsglslshaderfragment-shader

How to rotate each square of a pattern in fragment shader?


I have a code that produces a simple grid using glsl. I'd like to rotate the squares 45 degrees to make them diamond shapes. Here's the code:

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution;
    vec3 color = vec3(0.0);

    st *= 3.0;      // Scale up the space by 3
    st = fract(st); // Wrap around 1.0
    color = vec3(st,0.0);
    gl_FragColor = vec4(color,1.0);
}

I tried rotating the coordinates 45 degrees by adding the code bellow but it didn't work:

    vec2 rotated_st = vec2(st.x - 0.5, st.y - 0.5);
    rotated_st = vec2(rotated_st.x - rotated_st.y, rotated_st.x + rotated_st.y);
    rotated_st *= sqrt(2.0) / 2.0;
    rotated_st += vec2(0.5);

Solution

  • I'm not sure about how you added the second code you shown to the first one but I did it like this and it worked :

    void main()
    {
        vec2 st = gl_FragCoord.xy/u_resolution;
        vec3 color = vec3(0.0);
    
        st *= 3.0;      // Scale up the space by 3
    
        vec2 rotated_st = vec2(st.x - 0.5, st.y - 0.5);
        rotated_st = vec2(rotated_st.x - rotated_st.y, rotated_st.x + rotated_st.y);
        rotated_st *= sqrt(2.0) / 2.0;
        rotated_st += vec2(0.5);
    
        rotated_st = fract(rotated_st); // Wrap around 1.0
        color = vec3(rotated_st,0.0);
        gl_FragColor = vec4(color,1.0);
    }