glutTimerFunc问题
我使用 Glut
制作一个简单的动画。在主函数中,调用了 glutTimerFunc(TIMERMSECS, animate, 0)。这两段代码生成相同的图形。
const int TIMERMSECS = 20;
float animation_time = 0;
const float animation_step = .5;
方法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();
}
方法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);
}
它们之间唯一的区别是glutTimerFunc
的位置。对于方法 1
,它看起来像是一个永远不会到达 animate()
函数末尾的递归。但为什么这仍然有效?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在任何情况下,
glutTimerFunc
都不会立即调用计时器函数。即使时间为 0,它也始终等待消息处理循环,即使如此,它也只会在所有其他消息处理完成后才会调用所请求的函数。这样,“重绘窗口”和“调整窗口大小”等重要消息仍然会得到处理。一般来说,您不应该依赖计时器函数特别准确。
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.