From 1c63cbf204b1d2c667ce9f821ccb197d0ffb0ac3 Mon Sep 17 00:00:00 2001 From: Stijn Buys Date: Wed, 11 May 2011 14:48:17 +0000 Subject: Review of the main loop timer, converted timers from float to unsigned long, corrected a number of timing bugs, improved client framerate stability. --- src/client/client.cc | 45 ++++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 23 deletions(-) (limited to 'src/client/client.cc') diff --git a/src/client/client.cc b/src/client/client.cc index d761e6e..b514e57 100644 --- a/src/client/client.cc +++ b/src/client/client.cc @@ -179,14 +179,12 @@ void Client::run() srand(seed); // default framerate 125fps, 8 milliseconds - Uint32 client_frame_lenght = 8; - - Uint32 client_current_timestamp = 0; - Uint32 client_previous_timestamp = 0; + unsigned long client_frame_lenght = 8; + unsigned long client_current_timestamp = 0; while (true) { // current time in microseconds - client_current_timestamp = SDL_GetTicks(); + client_current_timestamp = timestamp(); // calculate the desired frame length if (cl_framerate->value() < 0) { @@ -196,32 +194,33 @@ void Client::run() } if (cl_framerate->value()) { - client_frame_lenght = (Uint32) floorf(1000.0f / cl_framerate->value()); + client_frame_lenght = (unsigned long) floorf(1000.0f / cl_framerate->value()); + if (client_frame_lenght < 1) + client_frame_lenght = 1; } else { - client_frame_lenght = 0; + client_frame_lenght = 1; } - // only advance per microsecond frame - const Uint32 d = client_current_timestamp - client_previous_timestamp; - if ((d > 0)) { - if (d >= client_frame_lenght) { - frame(client_current_timestamp); - client_previous_timestamp = client_current_timestamp; - } else { - SDL_Delay(client_frame_lenght - d); - } - } else { - SDL_Delay(1); + frame(); + + // sleep for the remainder of the frame + const unsigned long elapsed = timestamp() - client_current_timestamp; + if (elapsed < client_frame_lenght - 1) { + sys::sleep (client_frame_lenght - elapsed -1); + } + + while (timestamp() < client_current_timestamp + client_frame_lenght) { + // busy waiting for the last microsecond } } } -void Client::frame(unsigned long timestamp) +void Client::frame() { input::frame(); - core::Application::frame(timestamp); + core::Application::frame(); if (!connected()) { const std::string module_label(core::Loader::label()); @@ -264,9 +263,9 @@ void Client::frame(unsigned long timestamp) } } - video::frame((float)(timestamp - previous_timestamp) / 1000.0f); - - previous_timestamp = timestamp; + const float now = timestamp(); + video::frame((float)(now - previous_timestamp) / 1000.0f); + previous_timestamp = now; } void Client::shutdown() -- cgit v1.2.3