OpenGL 中的 3D 立方体网格

Grid of 3D cubes in OpenGL

我来这里是为了获得有关 OpenGL 中 3D 立方体网格的一些帮助。现在我只有来自以下代码的二维网格:

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();

它创建许多二维立方体以形成网格

如果您想在立即模式下执行此操作 (glBegin/glEnd),最简单的方法是使用嵌套循环 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.
编写一个函数(cube)绘制一个唯一的立方体并设置修改立方体模型的大小 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();
}