PDA

View Full Version : [solved] Drawing a cube



Daniel Harrison
01-23-2011, 09:09 AM
Is there something wrong with this code? It doesn't seem to draw all the faces of the cube.



#include <GL/freeglut.h>

float angle;

void display()
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glRotatef(angle, 0.5, 0.5, 0.0f);
glBegin(GL_QUADS);

// FACE ONE!!
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.0, 0.5, 0.0);
glVertex3f(0.0, 0.5, 0.5);
glVertex3f(0.5, 0.5, 0.5);

// FACE TWO!!
glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0.5, 0.0, 0.5);
glVertex3f(0.5, 0.0, 0.0);

// FACE THREE!!
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0.0, 0.5, 0.5);
glVertex3f(0.0, 0.0, 0.5);
glVertex3f(0.5, 0.0, 0.5);

// FACE FOUR!!
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.0, 0.5, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.5, 0.0, 0.0);

// FACE FIVE!!
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0.5, 0.0, 0.5);
glVertex3f(0.5, 0.0, 0.0);

// FACE SIX!!
glColor4f(0.0f, 1.0f, 1.0f, 1.0f);
glVertex3f(0.5, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.5);
glVertex3f(0.5, 0.0, 0.5);

glEnd();

glutSwapBuffers();
}

void rotation(int timer)
{
angle += 0.5f;
glutTimerFunc(1000 / 50, rotation, timer);
}

void framerate(int timer)
{
glutPostRedisplay();
glutTimerFunc(1000 / 100, framerate, timer);
}

int main(int argc, char** argv)
{
glutInit(&amp;argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowPosition(0, 0);
glutInitWindowSize(600, 600);
glutCreateWindow("dimension3");
glEnable(GL_BLEND);
glutDisplayFunc(display);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glutTimerFunc(1000 / 100, framerate, 1);
glutTimerFunc(1000 / 50, rotation, 2);
glutMainLoop();
return 0;
}

Daniel Harrison
01-23-2011, 09:29 AM
I've enabled depth test and that seems to have sorted most of the faces except one. The remaining one is no doubt an error on my part.

mobeen
01-23-2011, 09:42 AM
Hi two things,
1) You are repeating the coordinates of face two in face five
change the coordinates of face 5 to this


// FACE FIVE!!
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
glVertex3f(0., 0.5, 0.0);
glVertex3f(0., 0.5, 0.5);
glVertex3f(0., 0.0, 0.5);
glVertex3f(0., 0.0, 0.0);

2)Enable depth test
glEnable(GL_DEPTH_TEST); after u enable blending in main.

See if this hlps.
Mobeen