openglglsl

GLSL Checkerboard Pattern


I want to shade a quad with checkers:

f(P) = [floor(Px) + floor(Py)] mod 2.

My quad is:

glBegin(GL_QUADS);    
  glVertex3f(0,0,0.0);    
  glVertex3f(4,0,0.0);    
  glVertex3f(4,4,0.0);   
  glVertex3f(0,4, 0.0); 
glEnd();

The vertex shader file:

varying float factor;
float x,y;
void main(){
  x=floor(gl_Position.x);
  y=floor(gl_Position.y);
   factor = mod((x+y),2.0);
}

And the fragment shader file is:

varying float factor;
void main(){
  gl_FragColor = vec4(factor,factor,factor,1.0);
}

But I'm getting this:

alt text

It seems that the mod function doesn't work or maybe it's something else... Any help?


Solution

  • It is better to calculate this effect in fragment shader, something like that:

    vertex program =>

    varying vec2 texCoord;
    
    void main(void)
    {
       gl_Position = vec4(gl_Vertex.xy, 0.0, 1.0);
       gl_Position = sign(gl_Position);
        
       texCoord = (vec2(gl_Position.x, gl_Position.y) 
                 + vec2(1.0)) / vec2(2.0);      
    }
    

    fragment program =>

    #extension GL_EXT_gpu_shader4 : enable
    uniform sampler2D Texture0;
    varying vec2 texCoord;
    
    void main(void)
    {
        ivec2 size = textureSize2D(Texture0, 0);
        float total = floor(texCoord.x * float(size.x)) +
                      floor(texCoord.y * float(size.y));
        bool isEven = mod(total, 2.0) == 0.0;
        vec4 col1 = vec4(0.0, 0.0, 0.0, 1.0);
        vec4 col2 = vec4(1.0, 1.0, 1.0, 1.0);
        gl_FragColor = (isEven) ? col1 : col2;
    }
    

    Output =>

    alt text

    Good luck!