我正在尝试使用 OpenGl 模拟粒子系统,但我无法让它工作,这是我到目前为止所拥有的:
#include <GL/glut.h>
int main (int argc, char **argv){
// data allocation, various non opengl stuff
............
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE );
glutInitWindowPosition(100,100);
glutInitWindowSize(size, size);
glPointSize (4);
glutCreateWindow("test gl");
............
// initial state, not opengl
............
glViewport(0,0,size,size);
glutDisplayFunc(display);
glutIdleFunc(compute);
glutMainLoop();
}
void compute (void) {
// change state not opengl
glutPostRedisplay();
}
void display (void) {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
for(i = 0; i<nparticles; i++) {
// two types of particles
if (TYPE(particle[i]) == 1) glColor3f(1,0,0);
else glColor3f(0,0,1);
glVertex2f(X(particle[i]),Y(particle[i]));
}
glEnd();
glFlush();
glutSwapBuffers();
}
几秒钟后我看到一个黑色窗口(该窗口之前只有标题栏)。我哪里出错了?
LE:每个粒子的x和y坐标都在区间(0,size)内
最佳答案
尝试在代码中进行以下更改:
- 将 Main 函数移至文件末尾
- glPoinSize 调用属于 Display 函数
- 那么您应该提供一个函数来处理窗口大小的调整 glutReshapeFunc(reshape),如下所示
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble) w, 0.0, (GLdouble) h);
}
- glFlush 是从 glutSwapBuffers 函数调用的,因此您不需要它
- 插入此代码(在 glutCreateWindow 调用之后)以设置投影的初始位置
glClearColor(0.2, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 10, 0.0, 10, -1.0, 1.0);
关于OpenGL粒子系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5255405/