The following code involves the following techniques:
1. Drawing a solid cube.
2. Basic 3D transformations: rotation and translation.
3. Ambient light source.
4. Perspective viewport.
#ifdef WIN32 #include <windows.h> #endif #include <glut.h>
void Initialize(void); void Display(void); void Keyboard (unsigned char key, int x, int y); void DrawSolidCube(void);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { Initialize(); glutMainLoop(); return 0; }
void Initialize(void) { int argc; char * argv[] = {"dummy",0}; argc = 1; glutInit(&argc, (char **)&argv[0]); glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH|GLUT_ALPHA); glutInitWindowSize(300, 300); glutInitWindowPosition(-1, -1); // Let window to determine the startup position glutCreateWindow("A Simple Cube"); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); // Sets the background color - R, G, B, and alpha glShadeModel(GL_SMOOTH); // One of GL_SMOOTH or GL_FLAT glEnable(GL_LIGHT0); // Enable a single light source glColorMaterial(GL_FRONT,GL_AMBIENT); // Makes the coloring work for basic primitives glutDisplayFunc(Display); // Register Display() function glutKeyboardFunc(Keyboard); // Register Keyboard() function }
void Keyboard (unsigned char key, int x, int y) { // Keyboard events can be intepreted here with a switch-case structure //glutPostRedisplay(); }
void Display(void) { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-2.0,2.0,-2.0,2.0,2.0,-2.0); gluPerspective(30,1,1,20); glTranslatef(0,0,-3); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); DrawSolidCube(); glutSwapBuffers(); // swap the display buffer to show the new results }
void DrawSolidCube(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glColor4f(0,0,0.8f,1); // sets the color glRotatef(30,0.2,0.2,0); // rotate it for a 3D view glutSolidCube(1.5); // parameter is the length of each edge glPopMatrix(); }: : go back : :