So I have this OpenGL program that displays a cube using

gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

And it allows users to modify/rotate it along the x, y and z axis using input. Right now it looks it works pretty well, however, it terminates once the image is displayed according to the users input (on wether to rotate along the x, y or z axis).

How can I modify this program so you can rotate it without it terminating? As in, displaying only the first rotation during the first input.

Or to put it simply, how can I let the users rotae this cube along the x,y and z axis in real time?

//cube.cpp
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <iostream>
using namespace std;

void init(void) 
{
   glClearColor (0.0, 0.0, 0.0, 0.0);
   glShadeModel (GL_FLAT);
}

void display(void)
{
   glClear (GL_COLOR_BUFFER_BIT);
   glColor3f (1.0, 1.0, 1.0);
   glLoadIdentity ();             /* clear the matrix */
   /* viewing transformation  */
      /* Move about the x, y and z axis*/
   cout << "Type x, y or z to rotatate the cube about that respective axis by 5 degrees." << endl;
   char input;
   cin >> input;
   if (input == 'x')
   {
      gluLookAt (5.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
   else if (input == 'y')
   {
      gluLookAt (0.0, 5.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
   else if (input == 'z')
   {
      gluLookAt (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
   else
   {
      gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
     // gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   glScalef (1.0, 2.0, 1.0);      /* modeling transformation */ 
   glutWireCube (1.0);
   glFlush ();
}

void reshape (int w, int h)
{
   glViewport (0, 0, (GLsizei) w, (GLsizei) h); 
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
   glMatrixMode (GL_MODELVIEW);
}

int main(int argc, char** argv)
{   
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
   glutInitWindowSize (500, 500); 
   glutInitWindowPosition (100, 100);
   glutCreateWindow (argv[0]);
   init ();
   glutDisplayFunc(display); 
   glutReshapeFunc(reshape);
   glutMainLoop();
   return 0;
}

Hi,

What you need is an idle callback. inside the idle callback, you basically draw the frame again. This lets you decide the contents of the frame.

The idea is like this:

void idleFunc()
{
    // You could add some code here, based on which you can change rotation angle, etc //
    glutPostRedisplay(); // lets you render the frame again. Thus, will call the display callback.
}

You register this by glutIdleFunc()(link provided above).
So, by this, you program can keep rendering frames after receiving inputs.
I hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.