Hi
I have a very simple, “quick and dirty” OpenGL test program written for Windows using GLUT. It draws two colored rectangles that orbit around the X axis and the orbit position is varied by pressing ‘a’ or ‘z’.
Initially I had not set glEnable(GL_DEPTH_TEST), so the rectangles were appearing in the order they were drawn.
The problem is that when I set that, the display becomes totally random, it draws either the first rectangle or the second or neither of them without any logic. I’m sure there is something I am doing wrong, but I have no clue what…
Thanks in advance…
Here is the complete code below:
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <cmath>
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
int angle = 0;
void oglDraw()
{
angle += 360;
angle %= 360;
float fAngle = angle / (180 / 3.14159);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90, 1, 0, 10);
gluLookAt(0, 0, -1, 0, 0, 1, 0, 1, 0);
float yFactor = 1;
float zFactor = 1;
float y = yFactor * sin(fAngle);
float z = 1 + zFactor - cos(fAngle) * zFactor;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(1, 0, 0, 1);
glPolygonMode(GL_FRONT, GL_FILL);
glBegin(GL_POLYGON);
glColor4f(0, 0, 1, 1);
glVertex3f(-1.0, y-1.0, z);
glVertex3f(+1.0, y-1.0, z);
glVertex3f(+1.0, y+1.0, z);
glVertex3f(-1.0, y+1.0, z);
glEnd();
fAngle = (180 - angle) / (180 / 3.14159);
y = -yFactor * sin(fAngle);
z = 1 + zFactor - cos(fAngle) * zFactor;
glBegin(GL_POLYGON);
glColor4f(0, 1, 0, 1);
glVertex3f(-1.0, y-1.0, z);
glVertex3f(+1.0, y-1.0, z);
glVertex3f(+1.0, y+1.0, z);
glVertex3f(-1.0, y+1.0, z);
glEnd();
glFlush();
glutSwapBuffers();
}
void oglKeyboard(byte ch, int x, int y)
{
if(ch == 'z')
{
angle++;
glutPostRedisplay();
}
else
if(ch == 'a')
{
angle--;
glutPostRedisplay();
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize(1024, 768);
glutCreateWindow("OGL test");
gluOrtho2D(0, 1024, 768, 0);
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(oglDraw);
glutKeyboardFunc(oglKeyboard);
glutMainLoop();
}