From 6fd50edff5e3de70366680814e0cfb5dabcd2e5e Mon Sep 17 00:00:00 2001 From: Charadon Date: Tue, 14 Jun 2022 16:41:52 -0400 Subject: Possibly fixed internal clock, needs testing --- src/main.c | 31 ++++++++++++++++++++----------- src/pong.h | 1 + src/title.c | 1 + 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/main.c b/src/main.c index 6f2e96e..8eaba43 100644 --- a/src/main.c +++ b/src/main.c @@ -46,16 +46,27 @@ void set_screen_mode() { } return; } - +double Started; static int internal_clock() { - const struct timespec Delay = { - 0, 16666666 + static const double Framerate = 1.0/60.0f; + double OldTime = GetTime(); + double DeltaTime = 0; + double NewTime = 0; + Started = GetTime(); + struct timespec SleepFor = { + 0, 99999 }; - struct timespec Remaining; while(GameGoing == true) { - SDL_AtomicAdd(&Ticks, 1); - nanosleep(&Delay, &Remaining); + nanosleep(&SleepFor, NULL); //Reduces CPU usage + NewTime = GetTime(); + DeltaTime += (NewTime - OldTime)/Framerate; + OldTime = NewTime; + while(DeltaTime >= 1.0) { + SDL_AtomicAdd(&Ticks, 1); + DeltaTime--; + } } + return(0); } @@ -136,6 +147,9 @@ bool play_audio(int SoundEffect) { int main(int argc, char *argv[]) { //Raylib Init InitWindow(1280, 720, "Pong"); + SDL_Init(SDL_INIT_AUDIO); + SDL_AtomicSet(&Ticks, 0); + SDL_Thread *InternalClock = SDL_CreateThread(internal_clock, "Internal Clock", NULL); SetTargetFPS(60); SetExitKey(KEY_NULL); Image Icon = LoadImage("resources/ball.png"); @@ -149,9 +163,6 @@ int main(int argc, char *argv[]) { GlobalSettings.SoundVolume = 0; GlobalSettings.MusicVolume = 0; - //SDL Init - SDL_Init(SDL_INIT_AUDIO); - //Init Variables strncpy(VersionString, "Version 0.3 - Charon", sizeof(VersionString)); @@ -162,8 +173,6 @@ int main(int argc, char *argv[]) { //Threading AudioQueueBeingModified = SDL_CreateMutex(); - SDL_AtomicSet(&Ticks, 0); - SDL_Thread *InternalClock = SDL_CreateThread(internal_clock, "Internal Clock", NULL); SDL_Thread *AudioThread = SDL_CreateThread(audio, "Audio", NULL); SDL_AtomicSet(&AudioInitializing, 0); diff --git a/src/pong.h b/src/pong.h index eef1150..2e2fd44 100644 --- a/src/pong.h +++ b/src/pong.h @@ -53,6 +53,7 @@ extern bool GameGoing; extern SDL_atomic_t Ticks; extern char VersionString[256]; extern SDL_atomic_t AudioInitializing; +extern double Started; void enemy(struct Players *Enemy, struct Balls ball); void ball(Rectangle *Player, Rectangle *Enemy, struct Balls *Ball, int *PlayerScore, int *EnemyScore); diff --git a/src/title.c b/src/title.c index 2327713..da732ba 100644 --- a/src/title.c +++ b/src/title.c @@ -498,6 +498,7 @@ int title_screen() { EndMode2D(); DrawText(VersionString, GetScreenWidth()-400, GetScreenHeight()-32, 32, GREEN); EndDrawing(); + printf("%lf, %d\n", GetTime()-Started, SDL_AtomicGet(&Ticks)); } Mix_HaltMusic(); Mix_FreeMusic(TitleMusic); -- cgit 1.4.1-2-gfad0