【发布时间】:2016-11-06 02:26:18
【问题描述】:
我想使用 openGL 在屏幕上绘制 100 个点。这意味着每次我运行程序时,屏幕上都会随机出现 100 个 GL_POINTS。目前屏幕上只剩下一个点,并且它的位置是先前给出的。然而,我的随机点只出现了很短的时间,然后就消失了。我不知道我错过了什么让它工作。下面是我的代码
#include <stdlib.h>
#include <GL/freeglut.h>
#include <math.h>
GLfloat cameraPosition[] = { 0.0, 0.2, 1.0 };
/* Random Star position */
GLfloat starX, starY, starZ;
GLint starNum = 0;
void myIdle(void){
starNum += 1;
/* Generate random number between 1 and 4. */
starX = 1.0 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 3.0));
starY = 1.0 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 3.0));
starZ = 1.0 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 3.0));
/* Now force OpenGL to redraw the change */
glutPostRedisplay();
}
// Draw a single point
void stars(GLfloat x, GLfloat y, GLfloat z){
glBegin(GL_POINTS);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(x, y, z);
glEnd();
}
// Draw random points.
void myDisplay(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLoadIdentity();
gluLookAt(cameraPosition[0], cameraPosition[1], cameraPosition[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
/* They show up on the screen randomly but they disappear after starNum greater than 100 */
if (starNum < 100){
glPushMatrix();
stars(starX, starY, starZ);
glPopMatrix();
}
/* This point will remain on the screen. */
glPushMatrix();
stars(2.0, 2.0, 2.0);
glPopMatrix();
/* swap the drawing buffers */
glutSwapBuffers();
}
void initializeGL(void){
glEnable(GL_DEPTH_TEST);
glClearColor(0, 0, 0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPointSize(2.0);
glOrtho(-4.0, 4.0, -4.0, 4.0, 0.1, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(1800, 1000);
glutInitWindowPosition(100, 150);
glutCreateWindow("Random points");
/* Register display function */
glutDisplayFunc(myDisplay);
/* Register the animation function */
glutIdleFunc(myIdle);
initializeGL();
glutMainLoop();
}
知道我错过了什么吗?
【问题讨论】:
-
你期待什么?如果
starNum < 100,您正在绘制星星,并且想知道为什么不再满足此条件时它们会消失?我不明白你的惊讶。 -
我想在屏幕上画100个点,它们的位置是随机的。基本上,我希望所有的星星都留在屏幕上。
-
OpenGL 不是场景图 API。每次调用显示函数时都需要绘制所有星星。
标签: c++ opengl graphics glut freeglut