New FPS system, editable in config

This commit is contained in:
Thomas 2022-01-06 13:41:51 +01:00
parent 3dda6a690a
commit af8476c4ba
No known key found for this signature in database
GPG Key ID: E538821A6CDFDAD7
4 changed files with 23 additions and 12 deletions

View File

@ -1,3 +1,7 @@
# General configuration
general:
maxFPS: 50
# Players config
players:
width: 250

View File

@ -10,6 +10,9 @@ typedef string configKey;
struct ConfigData {
unsigned maxFPS;
InvadersGrid grid;
unsigned startXPosition;

View File

@ -160,6 +160,8 @@ void ConfigBuilder::readInvaderType(const configKey& baseKey, InvaderTypeDef& in
void ConfigBuilder::readConfig() {
collectedData.maxFPS = getInt("general.maxFPS");
readGrid("grid");
// players

View File

@ -84,14 +84,19 @@ WinValue Game::playGame(){ // returns when game is finished
basePos = Position(200, 0);
// GAMELOOP
const int MAX_FPS = 60;
// computed in advance for performance reasons
chrono::milliseconds maxFrameTime = chrono::milliseconds(1000/confData.maxFPS);
chrono::milliseconds fpsTime;
unsigned tmpFps = 0;
unsigned fps = 0;
typedef chrono::high_resolution_clock::time_point MyTimePoint;
MyTimePoint fpsStartTime = {};
while(window.isOpen()){
chrono::time_point startTime = chrono::high_resolution_clock::now();
MyTimePoint startTime = chrono::high_resolution_clock::now();
if(fpsStartTime.time_since_epoch()==chrono::seconds(0)){
fpsStartTime = startTime;
}
pm.startFrame();
@ -118,19 +123,16 @@ WinValue Game::playGame(){ // returns when game is finished
pm.endFrame();
chrono::time_point endTime = chrono::high_resolution_clock::now();
chrono::milliseconds frameTime = chrono::duration_cast<chrono::milliseconds>(endTime-startTime);
fpsTime = fpsTime + frameTime;
if(fpsTime>chrono::seconds(1)){
MyTimePoint endTime = chrono::high_resolution_clock::now();
// This code is counted as part of frames, but that's not really something we can control
if(fpsStartTime+chrono::seconds(1) < endTime){
fps = tmpFps;
tmpFps = 0;
fpsTime = chrono::milliseconds(0);
fpsStartTime = {};
}else ++tmpFps;
// old implementation, too volatile
// cout << "FPS : " << chrono::milliseconds(1000)/frameTime << endl;
this_thread::sleep_until(startTime+chrono::duration<double, ratio<1, MAX_FPS>>(1));
this_thread::sleep_until(startTime+maxFrameTime);
}
return WinValue::NOBODY;
}