window opengl 中的崩溃和部分渲染

window crash and partial rendering in opengl

执行时,并非所有行都打印在 window 上。此外,window 在函数 showScreen 中的 glutSwapBuffers() 之后崩溃。这是一张图片:https://imgur.com/n0oBJx9

w, h, g = 1200, 900, 1

def plot(coordinates, stringa, g, Px, Px1):
    x, y = coordinates
    while Px >= Px1:
        glBegin(GL_LINES)
        if stringa[Px] == "A":
            glVertex2f(x, y)
            glVertex2f(x, y - g)
            y -= g
        elif stringa[Px] == "B":
            glVertex2f(x, y)
            glVertex2f(x + g, y)
            x += g
        elif stringa[Px] == "C":
            glVertex2f(x, y)
            glVertex2f(x, y + g)
            y += g
        elif stringa[Px] == "D":
            glVertex2f(x, y)
            glVertex2f(x - g, y)
            x -= g
        glEnd()
        Px -= 1

def iterate():
    glViewport(0, 0, 500, 500)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0.0, 500, 0.0, 500, 0.0, 1.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def showScreen(coordinates, stringa, g, Px, Px1):
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    iterate()
    glColor3f(1.0, 0.0, 3.0)
    plot(coordinates, stringa, g, Px, Px1)
    glutSwapBuffers()
    time.sleep(5)

glutInit()
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE |GLUT_RGBA)
glutInitWindowSize(w, h)
window = glutCreateWindow("dragon curve in Opengl")
glutDisplayFunc(showScreen([300, 400], stringa, x, len(stringa)-1, 0))
glutIdleFunc(showScreen([300, 400], stringa, x, len(stringa)-1, 0)) 
end = time.perf_counter()
print(f'Terminated in {round(end - start, 2)} seconds')
glutMainLoop() 

我在 glutSwapBuffers()

之后的函数 showScreen 中遇到这个错误
freeglut (foo): Fatal error in program.  NULL display callback not permitted in GLUT 3.0+ or freeglut 2.0.1+

这个错误是什么意思,如何解决?

该错误几乎可以告诉您问题出在哪里。您没有提供显示功能。这是你写的:

glutDisplayFunc(showScreen([300, 400], stringa, x, len(stringa)-1, 0))

它的作用是调用函数 showScreen,然后从该调用中 return 得到的内容将传递给 glutDisplayFunction。您的 showScreen 函数没有 return 任何东西。

这不是你想要的。您必须使用 lambda 来捕获参数以显示屏幕,或者使用辅助函数。例如。这个

glutDisplayFunc(lambda: showScreen([300, 400], stringa, x, len(stringa)-1, 0))

但是考虑到您将视口和其他参数传递给 showScreen 的事实是不太可能的,这真的是您想要的!

错误意味着您调用了 glutDisplayFunc 但没有提供函数作为第一个参数。

我知道它看起来和你一样,但仔细看看这一行:

glutDisplayFunc(showScreen(...))

事情是这样的:

  1. 首先调用showScreen(...)然后returnsNone
  2. 此值用作 glutDisplayFunc 的第一个参数:glutDisplayFunc(None)
  3. 发生错误,因为 glutDisplayFunc 需要一个函数但得到了 None

glutIdleFunc 也会发生同样的错误。

要解决这两个问题,请给 glutDisplayFunc 和 glutIdleFunc 只是函数的名称:

glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)

现在还有一个问题,因为 glut 不会向 showScreen 提供 任何 个参数。它会 运行 像这样:showScreen().

这是个问题,因为您的 showScreen 函数需要几个参数。但实际上需要用none来定义:def showScreen(): 这意味着您将不得不以另一种方式提供这些变量。

datenwolf 建议您创建一个不接受参数且仅接受 运行s showScreen(...)

的新函数
def doShowScreen():
  showScreen(showScreen([300, 400], stringa, x, len(stringa)-1, 0))

glutDisplayFunc(doShowScreen)
glutIdleFunc(doShowScreen)