问题
I use Glut
to make a simple animation. In the main function, glutTimerFunc(TIMERMSECS, animate, 0)
is called. The two pieces of codes generate the same graphic.
const int TIMERMSECS = 20;
float animation_time = 0;
const float animation_step = .5;
Method 1:
void animate(int t){
float time_elapsed = TIMERMSECS/1000.0;
float current_step = animation_step* time_elapsed;
glutTimerFunc(TIMERMSECS, animate, 0);
if(current_step < animation_step*2)
animation_time += current_step;
glutPostRedisplay();
}
Method 2:
void animate(int t){
float time_elapsed = TIMERMSECS/1000.0;
float current_step = animation_step* time_elapsed;
if(current_step < animation_step*2)
animation_time += current_step;
glutPostRedisplay();
glutTimerFunc(TIMERMSECS, animate, 0);
}
The only difference between them is the position of glutTimerFunc
. For Method 1
, it looks like a recursive that will never reach the end of animate()
function. But why does that still work?
回答1:
glutTimerFunc
will not immediately call the timer function under any circumstances. Even if the time is 0. It always waits for the message processing loop, and even then it will only call the requested function when all other message processing has completed. That way, important messages like "repaint window" and "resize window" still get processed.
In general, you should not rely on the timer function being particularly accurate.
来源:https://stackoverflow.com/questions/7210238/gluttimerfunc-problem