-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathFPSLimiter.cpp
56 lines (46 loc) · 1.08 KB
/
FPSLimiter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "FPSLimiter.h"
#include <SDL2/SDL.h>
void FPSLimiter::TargetFPS(int fps)
{
if (fps)
{
_targetFrameTime = 1000 / fps;
}
else
{
_targetFrameTime = 0;
}
}
float FPSLimiter::FPS() const
{
uint32_t frameTimeSum{ 0 };
uint32_t frameTimeCount{ 0 };
for (auto _lastFrameTime : _lastFrameTimes)
{
if (_lastFrameTime > 0)
{
frameTimeCount++;
frameTimeSum += _lastFrameTime;
}
}
if (frameTimeCount == 0)
{
return 0.0f;
}
return 1000.0f / (static_cast<float>(frameTimeSum) / static_cast<float>(frameTimeCount));
}
void FPSLimiter::StartFrame()
{
_lastTickCount = SDL_GetTicks();
}
void FPSLimiter::EndFrame()
{
uint32_t frameTime = SDL_GetTicks() - _lastTickCount;
if (_targetFrameTime && frameTime < _targetFrameTime)
{
SDL_Delay(_targetFrameTime - frameTime);
frameTime = SDL_GetTicks() - _lastTickCount;
}
_lastFrameTimes[_nextFrameTimesOffset] = frameTime;
_nextFrameTimesOffset = (_nextFrameTimesOffset + 1) % 10;
}