【问题标题】:glutDisplayFunc() doesn't draw but normal function call doesglutDisplayFunc() 不绘制,但正常的函数调用可以
【发布时间】:2026-02-06 22:35:02
【问题描述】:

我无法在屏幕上显示一个简单的移动三角形,只有当我使用 glutDisplayFunc(render) 调用我的函数时才会发生这种情况。如果我像普通调用 render() 一样调用我的函数,它会很好地显示三角形,但在这种情况下,它不会为我的三角形设置动画。

所以基本上我有两个问题:

  1. 使用 glutDisplayFunc(render) 调用函数时无法绘制三角形
  2. 当调用像 render() 这样的函数时无法为三角形设置动画,但它可以绘制三角形。

下面是我的主要和显示代码:

void render()
{

currentTime = glutGet(GLUT_ELAPSED_TIME);
glClear(GL_COLOR_BUFFER_BIT);

GLfloat color[] = { (float)sin(currentTime) * 0.5f + 0.5f, (float)cos(currentTime) * 0.5f + 0.5f, 0.0f, 1.0f };

glClearBufferfv(GL_COLOR, 0, color);

GLfloat attrib[] = { (float)sin(currentTime) * 0.5f, (float)cos(currentTime) * 0.6f, 0.0f, 0.0f };

glVertexAttrib4fv(0, attrib);
// Use the program object we created earlier for rendering

glUseProgram(rendering_program);

//Draw triangle
glDrawArrays(GL_TRIANGLES,0,3);

glutSwapBuffers();

}

主要:

int main(int argc, char** argv)
{

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(600,600);
glutInitContextVersion(4,3);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutCreateWindow("Shader");

if (glewInit()) {
 cerr << "Unable to initialize GLEW ... exiting" << endl;
 exit(EXIT_FAILURE);
 }

 startup();
// render();     // WORKS FINE AND DRAW TRIANGLE
 glutDisplayFunc(render);    //DOESN'T DRAW TRIANGLE
 shutdown();

glutMainLoop();
return 0;

}

我相信着色器编译得很好,代码的那部分没有错误,因为它是在没有 glutDisplayFunc(); 的情况下绘制三角形;唯一的问题是当我使用 glutDisplayFunc(render);什么都没有画出来。

我哪里错了?我该如何解决我上面提到的两个问题?

【问题讨论】:

  • 您知道在输入glutMainLoop() 之前您正在调用shutdown(),对吧?绝对没有理由不应该使用您向我们展示的代码调用回调,我敢打赌,如果您在 render() 中设置断点,调试器将至少运行一次,当然,除非您取消注册再次回调shutdown()...
  • 天哪,我什至没有意识到这一点。 !现在可以了。谢谢你的解释。

标签: opengl glut freeglut


【解决方案1】:

glutDisplayFunc 不呈现自身。它注册了一个在必须进行渲染时应该由 glut 使用的函数。调用 ifsef 发生在 glutMainLoop() 内部的某处。由于您在开始渲染过程之前关闭了所有内容,因此在系统尝试渲染时数据不可用。

【讨论】:

  • 你解释得很好。我完全明白为什么我现在有这个问题。感谢您的及时回复,它现在可以工作了:)