How to achieve Smooth Rotation using the OpenGL API

Back to OpenGL Tutorial Index

Last time we looked at rotation the cube looked 'broken' now it
looked like this because we had a single buffer running. This
means that the program is automatically drawing straight to the
window. To fix this we add a second buffer, by changing the:
glutInitDisplayMode (GLUT_SINGLE);
to:
glutInitDisplayMode (GLUT_DOUBLE);
this is giving the programa buffer to draw what it has to, then transfer
what is acctually needed to the screen.
You may notice that alot of games these days even have a triple
buffer, this is pretty redundant in OpenGL, in fact it doesn't even exist in OpenGL.

When changing the buffer from Single to Double we also have to
tell the program to swap the buffers, so we acctually see what
is on the second, and not just what we saw before.

To do this, change the line in the 'display' function that says:
glFlush();
to:
glutSwapBuffers();

And your done, the cube should be rotating perfectly.

If you have any questions, please email me at swiftless@gmail.com

#include <GL/gl.h>
#include <GL/glut.h>

GLfloat angle = 0.0; //set the angle of rotation

void cube (void) {
glRotatef(angle, 1.0, 0.0, 0.0); //rotate on the x axis
glRotatef(angle, 0.0, 1.0, 0.0); //rotate on the y axis
glRotatef(angle, 0.0, 0.0, 1.0); //rotate on the z axis
glColor3f(1.0, 0.0, 0.0);
glutWireCube(2);
}

void display (void) {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
cube();
glutSwapBuffers();
angle ++;
}

void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}

int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE); //set up the double buffering
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutIdleFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
return 0;
}

Download C++ Source Code for this Tutorial

Download Visual Basic Source Code for this Tutorial

     

 

Copyright 2008, Donald Urquhart
Proudly supported by http://www.cdadc.com