Skip to content

Commit

Permalink
Linux: Sleep to avoid busy looping when no vsync (Windows build broken)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsherif committed Dec 18, 2021
1 parent 4bea608 commit 2f3be4e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
23 changes: 19 additions & 4 deletions src/platform/linux/linux.c
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ int xErrorHandler(Display* display, XErrorEvent* event) {
return 0;
}

int64_t nsFromTimeSpec(struct timespec timeSpec) {
return timeSpec.tv_sec * 1000000000ll + timeSpec.tv_nsec;
}

int32_t main(int32_t argc, char const *argv[]) {
int32_t exitStatus = 1;

Expand Down Expand Up @@ -301,7 +305,7 @@ int32_t main(int32_t argc, char const *argv[]) {
XEvent event = { 0 };
XWindowAttributes xWinAtt = { 0 };
uint64_t ticks = 0;
uint64_t lastTime;
int64_t lastTime;
struct timespec timeSpec;
clock_gettime(CLOCK_MONOTONIC, &timeSpec);
lastTime = timeSpec.tv_sec * 1000000000ll + timeSpec.tv_nsec;
Expand Down Expand Up @@ -378,9 +382,20 @@ int32_t main(int32_t argc, char const *argv[]) {
systemInput.lastQuit = systemInput.quit;

clock_gettime(CLOCK_MONOTONIC, &timeSpec);
uint64_t time = timeSpec.tv_sec * 1000000000ll + timeSpec.tv_nsec;

uint64_t elapsedTime = time - lastTime;
int64_t time = nsFromTimeSpec(timeSpec);
int64_t elapsedTime = time - lastTime;

// Sleep if at least 1ms less than frame min
if (SPACE_SHOOTER_MIN_FRAME_TIME_NS - elapsedTime > 1000000) {
struct timespec sleepTime = {
.tv_nsec = SPACE_SHOOTER_MIN_FRAME_TIME_NS - elapsedTime
};
nanosleep(&sleepTime, NULL);

clock_gettime(CLOCK_MONOTONIC, &timeSpec);
time = nsFromTimeSpec(timeSpec);
elapsedTime = time - lastTime;
}

game_update(elapsedTime / 1000000.0f);
game_draw();
Expand Down
3 changes: 1 addition & 2 deletions src/shared/constants.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@
#define SPACE_SHOOTER_DEFAULT_WINDOWED_WIDTH 1200
#define SPACE_SHOOTER_DEFAULT_WINDOWED_HEIGHT 600
#define SPACE_SHOOTER_MSAA_SAMPLES 4
#define SPACE_SHOOTER_MAX_REFRESH_RATE 300
#define SPACE_SHOOTER_MIN_FRAME_TIME (1000.0f / SPACE_SHOOTER_MAX_REFRESH_RATE)
#define SPACE_SHOOTER_MIN_FRAME_TIME_NS 3000000ll

///////////
// Audio
Expand Down

0 comments on commit 2f3be4e

Please sign in to comment.