kropcke
kropcke

Reputation: 121

Clamping FPS with gettimeofday

I'm trying to clamp my game loop to a specific FPS by employing gettimeofday. It's a very rudimentary game, so it keeps chewing up all my processing power.

Regardless of how low I set my FRAMES_PER_SECOND, it continues to try to run as fast as possible.

I got a pretty good handle on what deWiTTERS has to say about game loops, but am using gettimeofday instead of GetTickCount b/c I'm on a Mac.

Also, I'm running OSX and using C++, GLUT.

This is what my main looks like:

int main (int argc, char **argv)
{
    while (true)
    {
    timeval t1, t2;
    double elapsedTime;
    gettimeofday(&t1, NULL); // start timer

    const int FRAMES_PER_SECOND = 30;
    const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;
    double next_game_tick = elapsedTime;
    int sleep_time = 0;

    glutInit (&argc, argv);
    glutInitDisplayMode (GLUT_DOUBLE | GLUT_DEPTH); 
    glutInitWindowSize (windowWidth, windowHeight); 
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("A basic OpenGL Window"); 
    glutDisplayFunc (display); 
    glutIdleFunc (idle); 
    glutReshapeFunc (reshape);
    glutPassiveMotionFunc(mouseMovement); //check for mouse movement
    glutMouseFunc(buttonPress); //check for button press

    gettimeofday(&t2, NULL); // stop timer after one full loop
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // compute sec to ms
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // compute us to ms

    next_game_tick += SKIP_TICKS;
    sleep_time = next_game_tick - elapsedTime;
    if( sleep_time >= 0 )
        {
        sleep( sleep_time );
        }

    glutMainLoop (); 
    }
}

I've tried placing my gettimeofday and sleep functions in multiple locations, but I can't seem to find the sweet spot for them (given that my code is even correct).

Upvotes: 0

Views: 816

Answers (3)

Alan Stokes
Alan Stokes

Reputation: 18964

At the point where you initialise next_game_tick from elapsed_time you haven't yet initialised elapsed_time.

Upvotes: 0

genpfault
genpfault

Reputation: 52084

glutMainLoop():

glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never return. It will call as necessary any callbacks that have been registered.

Upvotes: 0

Justin
Justin

Reputation: 2372

That will only ever get called once. You need to put the FPS logic inside the display function I believe because glutMainLoop will never return. (which also means your while loop is not needed. )

edit: or more likely it should go inside your idle function. It has been awhile since I have used glut.

Upvotes: 4

Related Questions