为什么OpenGL中多次函数调用不起作用?

3

我试图在我的OpenGL项目中使用不同的函数创建各种对象,并通过一个名为display()的函数来调用它们。但是,当我调用两个函数时,只会显示一个函数,另一个不显示,我不知道为什么。

我尝试了以下方法:

#include <windows.h>  // for MS Windows
#include <GL/glut.h>  // GLUT, include glu.h and gl.h
#include <math.h>


void box() {

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set background color to black and opaque
    glClear(GL_COLOR_BUFFER_BIT);         // Clear the color buffer (background)
    // Draw a Red 1x1 Square centered at origin
    glBegin(GL_POLYGON);              // Each set of 4 vertices form a quad
    glColor3f(1.0f, 0.0f, 0.0f); // Red
    glVertex2f(-0.9f, -0.7f);
    glVertex2f(-0.9f, 0.7f);
    glVertex2f(0.9f, 0.7f);
    glVertex2f(0.9f, -0.7f);    // x, y

    glEnd();


    glFlush();  // Render now


}

void triangle()
{
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set background color to black and opaque
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POLYGON);              // Each set of 4 vertices form a quad
    glColor3f(0.0f, 1.0f, 0.0f); // green

    glVertex2f(-0.9f, -0.7f);
    glVertex2f(-0.4f, 0.7f);
    glVertex2f(0.1f, -0.7f);    // x, y

    glEnd();


    glFlush();  // Render now
}
void display()
{
    box();
    triangle();
}

/* Main function: GLUT runs as a console application starting at main()  */
int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitWindowSize(1000, 600);// Set the window's initial width & height
    glutCreateWindow("OpenGL Setup Test");
    //gluOrtho2D(-0.1,0.7,-0.1,0.3); // Create a window with the given title
    //glutInitWindowSize(500, 500);// Set the window's initial width & height
    glutDisplayFunc(display);// Register display callback handler for window re-paint
    glutMainLoop();           // Enter the event-processing loop
    return 0;
}

有什么建议吗?


1
glClear(GL_COLOR_BUFFER_BIT) 清除所有颜色 - apple apple
1个回答

2

在每次渲染形状之前,您都清除了缓冲区,因此擦除了刚刚绘制的先前形状。相反,您应该仅在display中清除一次。glFlush同理:

void box() {
    // Draw a Red 1x1 Square centered at origin
    glBegin(GL_POLYGON);
    glColor3f(1.0f, 0.0f, 0.0f); // Red
    glVertex2f(-0.9f, -0.7f);
    glVertex2f(-0.9f, 0.7f);
    glVertex2f(0.9f, 0.7f);
    glVertex2f(0.9f, -0.7f);    // x, y
    glEnd();
}

void triangle()
{
    glBegin(GL_POLYGON);
    glColor3f(0.0f, 1.0f, 0.0f); // green
    glVertex2f(-0.9f, -0.7f);
    glVertex2f(-0.4f, 0.7f);
    glVertex2f(0.1f, -0.7f);    // x, y
    glEnd();
}

void display()
{
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set background color to white and opaque
    glClear(GL_COLOR_BUFFER_BIT);         // Clear the color buffer (background)
    box();
    triangle();
    glFlush();  // Render now
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接