I want to draw 100 points on the screen using openGL. This means there will be 100 GL_POINTS randomly located on the screen each time I run the program. Currently there is only one point that remains on the screen and its position was previously given. However, my random points only appeared for a short period of time and then they disappear. I don't know what did I miss to make it work. Below is my code
#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();
}
Any idea what do I miss?