在 Linux 中使用过剩调整 window 大小时显示错误

Display error when resizing window using glut in Linux

我试着写了一个简单的glut程序,但是在调整大小时发现显示错误window(如图)。我在 kde 中使用 Arch Linux。 我该如何解决?

调整大小前:

调整大小后:

#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
void myinit(void)
{
  glClearColor(1.0, 1.0, 1.0, 1.0);
  glColor3f(1.0, 0.0, 0.0);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0.0, 500.0, 0.0, 500.0);
  glMatrixMode(GL_MODELVIEW);
}
void display( void )
{
  typedef GLfloat point2[2];
  point2 vertices[3]={{0.0,0.0},{250.0,500.0},{500.0,0.0}};
  int i, j, k;
  int rand();
  point2 p ={75.0,50.0};
  glClear(GL_COLOR_BUFFER_BIT);
  for( k=0; k<5000; k++)
  {
    j=rand()%3;
    p[0] = (p[0]+vertices[j][0])/2.0; 
    p[1] = (p[1]+vertices[j][1])/2.0;
    glBegin(GL_POINTS);
           glVertex2fv(p); 
    glEnd();
  }
  glFlush();
  printf ("display invokved....\n");
} 
void main(int argc, char** argv)
{
  glutInit(&argc,argv);
  glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
  glutInitWindowSize(500,500); 
  glutInitWindowPosition(0,0); 
  glutCreateWindow("Sierpinski Gasket"); 
  glutDisplayFunc(display); 
  myinit();
  glutMainLoop();
}

您需要捕获调整大小事件。在 glut 中,您必须使用函数 glutReshapeFunc 注册一个回调。在此功能中,您可以更改投影参数和视口。

下面是您程序中的一个小改动,展示了您如何做到这一点:

(...)
void reshape(int width, int height)
{
   glViewport(0, 0, width, height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluOrtho2D(0.0, width, 0.0, height);
   glMatrixMode(GL_MODELVIEW);
}
(...)
int main(int argc, char** argv)
{
(...)
   glutDisplayFunc(display); 
   glutReshapeFunc(reshape);  /* <--- */
   myinit();
(...)
}

切换到双缓冲(GLUT_DOUBLE & glutSwapBuffers())修复了我的系统:

#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
void display( void )
{
  typedef GLfloat point2[2];
  point2 vertices[3]={{0.0,0.0},{250.0,500.0},{500.0,0.0}};
  int i, j, k;
  int rand();
  point2 p ={75.0,50.0};

  glClearColor(1.0, 1.0, 1.0, 1.0);
  glClear(GL_COLOR_BUFFER_BIT);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0.0, 500.0, 0.0, 500.0);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glBegin(GL_POINTS);
  glColor3f(1.0, 0.0, 0.0);
  for( k=0; k<5000; k++)
  {
    j=rand()%3;
    p[0] = (p[0]+vertices[j][0])/2.0; 
    p[1] = (p[1]+vertices[j][1])/2.0;
    glVertex2fv(p); 
  }
  glEnd();
  glutSwapBuffers();
} 
int main(int argc, char** argv)
{
  glutInit(&argc,argv);
  glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
  glutInitWindowSize(500,500); 
  glutInitWindowPosition(0,0); 
  glutCreateWindow("Sierpinski Gasket"); 
  glutDisplayFunc(display); 
  glutMainLoop();
  return 0;
}