1 /******************************************************************************
2  *  Warmux is a convivial mass murder game.
3  *  Copyright (C) 2001-2011 Warmux Team.
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
18  ******************************************************************************
19  *  The stopwatch can be used to messure how much time elapses.
20  *****************************************************************************/
21 
22 #include "game/stopwatch.h"
23 #include <SDL.h>
24 #include <WARMUX_error.h>
25 
Stopwatch()26 Stopwatch::Stopwatch()
27 {
28   Reset();
29 }
30 
Reset(Double speed_value)31 void Stopwatch::Reset(Double speed_value)
32 {
33   speed       = speed_value;
34   paused      = false;
35   start_time  = SDL_GetTicks();
36   offset_time = 0;
37 }
38 
Stop()39 void Stopwatch::Stop()
40 {
41   ASSERT(!paused);
42   // Save last valid time
43   offset_time = GetValue();
44   paused      = true;
45 }
46 
Resume()47 void Stopwatch::Resume()
48 {
49   ASSERT(paused);
50   paused     = false;
51   // Start new time segment
52   start_time = SDL_GetTicks();
53 }
54 
SetPause(bool value)55 void Stopwatch::SetPause(bool value)
56 {
57   if (paused == value)
58     return;
59   if (paused) {
60     Resume();
61   } else {
62     Stop();
63   }
64 }
65 
GetValue() const66 uint Stopwatch::GetValue() const
67 {
68   if (paused)
69     return offset_time;
70   else
71     return static_cast<long>(speed * (SDL_GetTicks() - start_time)) + offset_time;
72 }
73 
SetSpeed(const Double & sp)74 void Stopwatch::SetSpeed(const Double& sp)
75 {
76   // Save current time as a new segment is about to start
77   offset_time = GetValue();
78   // Start new time segment
79   start_time  = SDL_GetTicks();
80   speed       = sp;
81 }
82 
Resynch(uint value)83 void Stopwatch::Resynch(uint value)
84 {
85   offset_time = value;
86   start_time  = SDL_GetTicks();
87 }
88