See code below.
/*
You need to do several things to make your code work. These are as follows:
-
Write an initialization function where you can specify clearing colors, depth
tests, etc. This is what you have done but look at the way I setup the depth test.
In the future you may want to use this function to setup other things such as
antialiasing, lighting modes and the like.
-
Write a resize function and let glut know about it. This function will be called
when the application first starts and whenever the drawing window is resized.
To let glut know abot the function, call glutReshapeFunc() as I’ve done in main().
In this function you need to setup a viewport transformation (e.g. glViewport())
and a projection transformation (e.g. gluPerspective()).
-
Define the display function and let glut know about it as you’ve done in your code.
However, here you need to apply a viewing transformation (e.g. gluLookAt()) and a
modelling transformation (ie. any set of calls to glTranslatef(), glRotatef() and glScalef()
taking place after the viewing transformation). In the code below, the modelling transformation
consists of a single call to glRotatef(). After setting up the viewing and modelling transformations
you can begin drawing.
Note that the viewing and modelling transformations can be a bit confusing in the beginning since
you can actually create a viewing transformation by means of calls to glTranslatef() and
glRotatef(). In fact this is what gluLookAt() does for you. In the code below I could have
avoided the call to gluLookAt() by replacing it with glTranslatef(0.0, 0.0, -15.0).
*/
#include <windows.h>
#include <gl/gl.h>
#include <gl/glut.h>
void initGL(void) {
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
/* depth buffer test */
glClearDepth(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
void resizeScene(GLsizei width, GLsizei height) {
if (height == 0.0)
height = 1;
/* apply viewport transformation */
glViewport(0, 0, width, height);
/* apply projection transformation */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat) width / (GLfloat) height, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); /* reset MODELVIEW matrix /
gluLookAt(0.0, 0.0, 15.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); / apply viewing transformation */
glRotatef(45.0, 1.0, 0.0, 0.0); /* apply modelling transformation */
glColor3f(0.0, 0.0, 1.0); /* draw torus with given color */
glutWireTorus(2.0, 5.0, 20, 20);
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
glutInitWindowPosition(100, 100);
glutCreateWindow(“A Simple OpenGL Torus”);
initGL();
glutDisplayFunc(display);
glutReshapeFunc(resizeScene);
glutMainLoop();
return(0);
}