GLUT consistant framerate?

Posts: 45
Joined: 2006.11
Post: #1
As an excercise I want to create a GLUT app that has a consistent, limited frame rate. To do this, I planned to use glutTimerFunc to schedule glutPostRedisplays into the future, but it didn't work (explanation below). Here is the semi-pseudo code for the display and timer func for the app.

// The desired amount of time between frames (in ms)
#define FRAME_TIME 14

void timer(int value) {

void display() {
  static bool firstFrame = true; // only true on the first frame
  static int lastMS; // the last frame's result of glutGet(GLUT_ELAPSED_TIME)
  int curMS = glutGet(GLUT_ELAPSED_TIME); // the current frame's result

  // special case for the first frame
  if(firstFrame) {
    firstFrame = false;
    lastMS = curMS;
  // difference between the last frame and the current frame
  int deltaMS = lastMS - curMS;
  lastMS = curMS; // update lastMS for the next frame

  // draw

  // see how much time the frame took to draw, if any
  int frameMS = glutGet(GLUT_ELAPSED_TIME) - curMS;

  // calculate how much time is left before the next frame should start
  int nextFrameMS = FRAME_TIME - (frameMS + deltaMS);
  if(nextFrameMS < 0)
    glutPostRedisplay(); // redraw right away, frame took longer than expected
    glutTimerFunc(nextFrameMS, timer, 0); // schedule redraw in the future

What it actually does for most values of FRAME_TIME is either 1) always call glutPostRedisplay right away, or 2) alternate every other frame calling it right away then setting up the timer, then calling it right away, then using the timer.

One of the reasons is, I think, the inaccuracy of the glutTimerFunc function, which calls the timer anywhere between 10 and 80 ms after the scheduled time.

Is this normal? Or am I doing something completely wrong? Also is there another way (through GLUT only) to implement this semi-decently? My only other idea was to spin wait in a glutIdleFunc callback until the needed amount of time passed. Not sure I like that since it over-uses the CPU and might get the app punished by the scheduler.

Quote this message in a reply
Posts: 1,482
Joined: 2002.09
Post: #2
Your timer callback is supposed to call glutTimerFunc() again. The timer only fires once.

Scott Lembcke - Howling Moon Software
Author of Chipmunk Physics - A fast and simple rigid body physics library in C.
Quote this message in a reply
Posts: 5,143
Joined: 2002.04
Post: #3
The only way to get a truly consistent frame-rate is to sync to the vertical refresh...
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  iPhone 3GS OpenGL strange framerate bug airfire 2 3,419 Dec 2, 2009 09:22 AM
Last Post: airfire
  SDL Framerate Control joellevin 10 8,325 Jan 4, 2007 01:26 PM
Last Post: arekkusu
  Capping framerate unknown 18 7,643 Jul 19, 2005 04:57 AM
Last Post: unknown
  Weird framerate problem Jesse 4 3,042 Sep 1, 2003 01:01 AM
Last Post: Jesse