Search code examples
calgorithmopenglopengl-3

How to fill the plane with a list of smaller squares using nested loops in OpenGL?


I don't know in which way we can setup a plane surface that is filled with smaller squares (so that I can do better lighting effect).

My code for drawing a single square is:

void drawSquare(float x1, float y1, float x2, float y2) {
    glBegin(GL_QUADS);
        glVertex3f(x1, y1, 0.0f); // The bottom left corner  
        glVertex3f(x1, y2, 0.0f); // The top left corner  
        glVertex3f(x2, y2, 0.0f); // The top right corner  
        glVertex3f(x2, y1, 0.0f); // The bottom right corner    
    glEnd();
}

So now how can I run a nested loop to fill the surface with number of smaller squares? I'm a bit unsure about the coordinates of the smaller squares.


Solution

  • Calculate the size of the square and divide it into smaller pieces. Something like this (untested):

    void drawSquare(float x1, float y1, float x2, float y2, int xtiles, int ytiles) {
        float tile_width  = (x2 - x1) / xtiles;
        float tile_height = (y2 - y1) / ytiles;
        int x, y;
        glBegin(GL_QUADS);
            for (y = 0; y < ytiles; y++) {
                for (x = 0; x < xtiles; x++) {
                    glVertex3f(x1 + x * tile_width, y1 + y * tile_height, 0.0f); // The bottom left corner  
                    glVertex3f(x1 + x * tile_width, y1 + (y + 1) * tile_height, 0.0f); // The top left corner  
                    glVertex3f(x1 + (x + 1) * tile_width, y1 + (y + 1) * tile_height, 0.0f); // The top right corner  
                    glVertex3f(x1 + (x + 1) * tile_width, y1 + y * tile_height, 0.0f); // The bottom right corner    
                }
            }
        glEnd();
    }