Search code examples
loopsopenglgridcubeopengl-compat

Grid of 3D cubes in OpenGL


I am here to get some help about Grid of 3D cubes in OpenGL. Right now i have only 2d Grid from following code:

glBegin(GL_QUADS);

for (GLfloat i = -5.5; i <= 5.5; i += .001) {
    glVertex3f(i, 0, 5.5); glVertex3f(i, 0, -5.5);
    glVertex3f(5.5, 0, i); glVertex3f(5.5, 0, i);
}
glEnd();

It creates many 2d cubes to form a grid


Solution

  • If you want to do this in immediate mode (glBegin/glEnd), the easiest way is to use nested loops and and glTranslate for model transformation. Since glTranslate specifies a new transformation matrix and multiplies the current matrix by the new matrix, the current matrix must be saved and restored by glPushMatrix/glPopMatrix.
    Write a function (cube) which draws a unique cube and set modify the size of the cube model by glScale:

    GLfloat size = 0.2f;
    GLfloat gap = size * 0.2f;
    
    for (int i = -5; i < 5; ++i)
    {
        for (int j = -5; j < 5; ++j)
        {
            glPushMatrix();
    
            GLfloat x = (size + gap) * (GLfloat)i;
            GLfloat y = (size + gap) * (GLfloat)j;
            glTranslatef(x, y, 0.0f);
            glScalef(size*0.5f, size*0.5f, size*0.5f);
            cube();
    
            glPopMatrix();
        }
    }
    
    void cube( void )
    {
        static const float verticies[] = {
             1, -1, -1,
             1,  1, -1,
            -1,  1, -1,
            -1, -1, -1,
             1, -1,  1,
             1,  1,  1,
            -1, -1,  1,
            -1,  1,  1,
        };
    
        static const int surfaces[] = {0,1,2,3, 3,2,7,6, 6,7,5,4, 4,5,1,0, 1,5,7,2, 4,0,3,6};
        static const float colors[] = {1,0,0, 0,1,0, 0,0,1, 1,1,0, 1,0,1, 1,0.5,0};
    
        glBegin(GL_QUADS);
        for (int side = 0; side < 6; ++side)
        {
            glColor3fv(colors + side*3);
            for (int corner = 0; corner < 4; corner++)
            {
                int vi = surfaces[side*4+corner];
                glVertex3fv(verticies + vi*3);
            }
        }
        glEnd();
    }