Adonthell  0.4
gametime.cc
Go to the documentation of this file.
1 /*
2  $Id: gametime.cc,v 1.14 2005/04/16 17:56:32 ksterker Exp $
3 
4  Copyright (C) 2001/2002 Kai Sterker <kaisterker@linuxgames.com>
5  Part of the Adonthell Project http://adonthell.linuxgames.com
6 
7  This program is free software; you can redistribute it and/or modify
8  it under the terms of the GNU General Public License.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 /**
16  * @file gametime.cc
17  *
18  * @author Kai Sterker
19  * @brief Implements the gametime class.
20  */
21 
22 #include "gametime.h"
23 #include <SDL/SDL.h>
24 
25 double gametime::Minute;
26 u_int32 gametime::timer1;
27 u_int32 gametime::timer2;
28 u_int8 gametime::fts;
29 bool gametime::running;
30 
31 // initialize the gametime class
32 void gametime::init (u_int16 rt_minutes)
33 {
34  fts = 0;
35  timer1 = 0;
36  timer2 = 0;
37 
38  running = false;
39 
40  // Number of game cycles during rt_minutes realtime minutes
41  double cycles = (60000 * rt_minutes) / (double) CYCLE_LENGTH;
42 
43  // Calculate how many game cycles make one gametime minute,
44  // so that one gametime day lasts rt_minutes realtime minutes.
45  Minute = cycles / 1440;
46 }
47 
48 // Synchronize the game's speed to the machine it's running on.
50 {
51  // We declare this variable as static to avoid having to
52  // perform the division every time.
53  // Its value corresponds to the minimum delay between
54  // two displayed frames (see FRAME_RATE).
55  static u_int16 gfx_cycle_length = 1000 / FRAME_RATE;
56 
57  // Wait a bit if our machine performed too fast!
58  while (1)
59  {
60  timer2 = SDL_GetTicks () - timer1;
61 
62  // if the mainloop was performed faster than one frame
63  // should take, we sleep for the time remaining
64  if (timer2 >= gfx_cycle_length) break;
65  else SDL_Delay (50);
66  }
67 
68  timer1 = SDL_GetTicks () - (timer2 % CYCLE_LENGTH);
69 
70  // Calculate the number of frames to skip (if the mainloop
71  // takes longer than allowed, we drop frames (up to a certain
72  // limit) to keep the game's speed constant.)
73  fts = timer2 / CYCLE_LENGTH;
74  if (fts > FTS_LIMIT) fts = FTS_LIMIT;
75 }