sftools  2.0 dev
Bunch of tools for SFML application development
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Pages
Chronometer.hpp
Go to the documentation of this file.
1 /*
2 
3  sftools - Copyright (c) 2012-2013 Marco Antognini <antognini.marco@gmail.com>
4 
5  This software is provided 'as-is', without any express or implied warranty. In
6  no event will the authors be held liable for any damages arising from the use
7  of this software.
8 
9  Permission is granted to anyone to use this software for any purpose, including
10  commercial applications, and to alter it and redistribute it freely, subject to
11  the following restrictions:
12 
13  1. The origin of this software must not be misrepresented; you must not claim
14  that you wrote the original software. If you use this software in a product,
15  an acknowledgment in the product documentation would be appreciated but is
16  not required.
17 
18  2. Altered source versions must be plainly marked as such, and must not be
19  misrepresented as being the original software.
20 
21  3. This notice may not be removed or altered from any source distribution.
22 
23  */
24 
30 #ifndef __SFTOOLS_BASE_CHRONOMETER_HPP__
31 #define __SFTOOLS_BASE_CHRONOMETER_HPP__
32 
33 #include <SFML/System/Clock.hpp>
34 
39 namespace sftools
40 {
46  {
47  public:
53  Chronometer(sf::Time initialTime = sf::Time::Zero)
54  {
55  reset();
56  add(initialTime);
57  }
58 
65  sf::Time add(sf::Time time)
66  {
67  m_time += time;
68 
69  if (m_state == STOPPED) m_state = PAUSED;
70 
71  return getElapsedTime();
72  }
73 
80  sf::Time reset(bool start = false)
81  {
82  sf::Time time = getElapsedTime();
83 
84  m_time = sf::Time::Zero;
85  m_state = STOPPED;
86 
87  if (start) resume();
88 
89  return time;
90  }
91 
99  sf::Time pause()
100  {
101  if (isRunning())
102  {
103  m_state = PAUSED;
104  m_time += m_clock.getElapsedTime();
105  }
106  return getElapsedTime();
107  }
108 
116  sf::Time resume()
117  {
118  if (!isRunning())
119  {
120  m_state = RUNNING;
121  m_clock.restart();
122  }
123  return getElapsedTime();
124  }
125 
137  sf::Time toggle()
138  {
139  if (isRunning()) pause();
140  else resume();
141 
142  return getElapsedTime();
143  }
144 
150  bool isRunning() const
151  {
152  return m_state == RUNNING;
153  }
154 
160  sf::Time getElapsedTime() const
161  {
162  switch (m_state) {
163  case STOPPED:
164  return sf::Time::Zero;
165 
166  case RUNNING:
167  return m_time + m_clock.getElapsedTime();
168 
169  case PAUSED:
170  return m_time;
171  }
172  }
173 
181  operator sf::Time() const
182  {
183  return getElapsedTime();
184  }
185 
186  private:
187  enum { STOPPED, RUNNING, PAUSED } m_state;
188  sf::Time m_time;
189  sf::Clock m_clock;
190  };
191 }
192 
193 
194 #endif // __SFTOOLS_BASE_CHRONOMETER_HPP__