spacebox/src/Timer.hpp

105 lines
3.0 KiB
C++

/* +------------------------------------------------------+
____/ \____ /| - Open source game framework licensed to freely use, |
\ / / | copy, modify and sell without restriction |
+--\ ^__^ /--+ | |
| ~/ \~ | | - created for <https://foam.shampoo.ooo> |
| ~~~~~~~~~~~~ | +------------------------------------------------------+
| SPACE ~~~~~ | /
| ~~~~~~~ BOX |/
+-------------*/
#pragma once
namespace sb
{
/*!
* Timer in seconds which can be paused arbitrarily.
*
* It must be updated every frame with the timestamp passed to Game::update, regardless of whether it is actively timing or not.
*/
class Timer
{
private:
bool timing = false, previous_is_recorded = false;
float timestamp = 0.0f, timestamp_previous = 0.0f, frame_duration = 0.0f, _elapsed = 0.0f;
public:
enum State : bool
{
OFF,
ON
};
/*!
* @return boolean indicating whether timer object is keeping time or not
*/
operator bool() const;
/*!
* Toggle timing on/off
*/
void toggle();
/*!
* @param state set timing state explictly by passing a boolean
*/
void toggle(bool state);
/*!
* Start timing.
*/
void on();
/*!
* Stop timing.
*/
void off();
/*!
* Reset time elapsed to zero.
*/
void reset();
/*!
* @return seconds elapsed on timer
*/
float elapsed() const;
/*!
* @return length of the previous frame in seconds
*/
float frame() const;
/*!
* Update the timer's elapsed time, using the amount of seconds elapsed in the program at the start of the frame to keep track.
*
* The timer should be updated every frame to keep track of the timestamp, regardless of whether it is currently timing or not.
*
* The timestamp should be forwarded from the value passed to Game::update, so that it is consistently the timestamp at the
* beginning of the frame.
*
* @param timestamp seconds elapsed since the start of the program
*/
void update(float timestamp);
/*!
* Applies delta timing to a value: returns the value as weighted by the amount of time passed since the
* last frame update, allowing for values to change the same amount over time independent of the frame rate.
* The amount passed is how much the value should change per second.
*
* @param amount any scalar value to be weighted
* @return weighted value
*/
template<typename Type>
Type delta(Type amount) const
{
return frame() * amount;
}
};
}