Search code examples
glut

GlutKeyboardFunc callback doesn't work in openGL


I am trying to simply quit the application on pressing a key in openGL and the keyboard doesn't seem to work. Neither am I am not able to quit the application just by clicking on the close button of the window. Any explanation for this behaviour? I am not recreating the window continuously either.

Here's the code snippet

void keyboardfunc(unsigned char key, int x, int y) {
cout << "Inside" ;
switch (key) {

case 'q': exit(0);
default: break;

}


int main(int argc,char ** argv) 
{ 



.
.
.
glutReshapeFunc(reshape_func);


glutDisplayFunc(draw);
glutKeyboardFunc(keyboardfunc);
myinit();

glutMainLoop();


return 0; 
}

The program is to simulate insertion sort by representing the array graphically , using a for loop I am clearing the screen every time and representing the numbers as histogram each time

Just to be clear the simulation of insertion sort works , only the keyboard callback doesn't work.


Solution

  • Your draw functions take the CPU control and don't let to execute GLUT events loop. Take into account that GLUT is single thread.

    You must register a timer. Timer will produce new rendering. Each second compute next iteration and force to redraw scene.

    void draw(){
      renderHistogram();
    }
    
    void timer(int value) {
      getNextIteration();
      glutPostRedisplay();
      glutTimerFunc(1000, timer, 1); // executed on a second
    }
    

    To register timer include this line before glutMainLoop:

    glutTimerFunc(1000, timer, 1); // executed on a second
    

    next iteration function would be:

    int i = 0, j = 0;
    void getNextIteration()
    {
        if (i == n) {
            // Array is sorted
            return;
        }
    
        int key;
        key = arr[i];
    
        if (j == 0 || arr[j] <= key) {
            // Internal loop finished, reset j, and advance i;
            arr[j + 1] = key;
            i++;
            j = i - 1;
        }
    
        arr[j + 1] = arr[j];
        j = j - 1;
    }