如何使用 OpenGL 绘制线立方体?

How to draw a line cube with OpenGL?

我正在尝试用线条绘制立方体。

这是我的代码。它只是给了我一个白色的框架,里面什么也没有。什么都没发生。我在这里做错了什么?是函数调用顺序有问题还是投影有问题?


def myInit():
    glClearColor(0.0, 0.0, 0.0, 1.0) 
    glColor3f(0.2, 0.5, 0.4)
    gluPerspective(45, 1.33, 0.1, 50.0)


vertices= (
    (100, -100, -100),
    (100, 100, -100),
    (-100, 100, -100),
    (-100, -100, -100),
    (100, -100, 100),
    (100, 100, 100),
    (-100, -100, 100),
    (-100, 100, 100)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )


def Display():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)   
glutInitWindowSize(800, 600)  
myInit()
glutDisplayFunc(Display) 
glutMainLoop()

不在 Viewing frustum 中的所有几何图形都被剪裁。立方体的大小为 200x200x200。您必须创建一个足够大的视锥体。

比如设置一个透视投影矩阵gluPerspective with a far plane of 1000.0. The projection matrix is intended to be set to the current projection matrix (GL_PROJECTION). See glMatrixMode:

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.33, 0.1, 1000.0) 


Translate ([`glTranslate`](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml)) the model along the negative z axis, in between the near plane (0.1) and far (plane). The model or view matrix has to be set to the current model view matrix (`GL_MODELVIEW`):

```py
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslate(0, 0, -500)

通过glClear清除每一帧的显示:

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # [...]

将当前双缓冲window的缓冲区替换为glutSwapBuffers,并通过调用glutPostRedisplay.

不断更新显示
def Display():
    # [...]

    glutSwapBuffers()
    glutPostRedisplay()

另见 Immediate mode and legacy OpenGL

看例子:

def init():
    glClearColor(0.0, 0.0, 0.0, 1.0) 
    
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, 1.33, 0.1, 1000.0)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(0, 0, -500)

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glColor3f(0.2, 0.5, 0.4)
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

    glutSwapBuffers()
    glutPostRedisplay()