better frame timing
authorhgn <hgodden00@gmail.com>
Sun, 16 Apr 2023 06:38:15 +0000 (07:38 +0100)
committerhgn <hgodden00@gmail.com>
Sun, 16 Apr 2023 06:38:15 +0000 (07:38 +0100)
vg.h

diff --git a/vg.h b/vg.h
index 777a9e381cb3b6860d70c62b70b334dd9b7947c9..8e5eafdc29f61964dcd9257afc2459763dd6ea94 100644 (file)
--- a/vg.h
+++ b/vg.h
@@ -169,7 +169,17 @@ struct vg
        samples,
        window_should_close;
 
-   float refresh_rate;
+   int display_refresh_rate,
+       fps_limit;             /* 0: use vsync, >0: cap fps to this, no vsync */
+
+   enum vsync_feature
+   {
+      k_vsync_feature_disabled=0,
+      k_vsync_feature_enabled=1,
+      k_vsync_feature_enabled_adaptive=2,
+      k_vsync_feature_error=3
+   }
+   vsync_feature;
 
    double mouse_pos[2];
    v2f mouse_delta,
@@ -178,11 +188,13 @@ struct vg
    /* Runtime */
    double time,
           time_delta,
-          frame_delta,
-          time_real,
-          time_real_last,
           time_rate,
-          accumulator;
+
+          time_fixed_accumulator,
+          time_fixed_extrapolate,
+          time_frame_delta;
+
+   u64 time_hp, time_hp_last, time_spinning;
 
    int fixed_iterations;
 
@@ -360,7 +372,8 @@ VG_STATIC void vg_checkgl( const char *src_info );
 
 /* Diagnostic */
 VG_STATIC struct vg_profile vg_prof_update = {.name="update()"},
-                            vg_prof_render = {.name="render()"};
+                            vg_prof_render = {.name="render()"},
+                            vg_prof_swap   = {.name="swap"};
 
 VG_STATIC void vg_checkgl( const char *src_info )
 {
@@ -402,10 +415,6 @@ VG_STATIC void _vg_load_full(void)
 VG_STATIC void _vg_process_events(void)
 {
    /* Update timers */
-   vg.time_real_last = vg.time_real;
-   vg.time_real = (double)SDL_GetTicks64() / 1000.0;
-   vg.frame_delta = vg.time_real-vg.time_real_last;
-   
    v2_zero( vg.mouse_wheel );
    v2_zero( vg.mouse_delta );
 
@@ -473,16 +482,17 @@ VG_STATIC void _vg_gameloop_update(void)
 
    /* Fixed update loop */
    vg.engine_stage = k_engine_stage_update_fixed;
-   vg.accumulator += vg.time_delta;
 
    vg.fixed_iterations = 0;
    vg_lines.allow_input = 1;
-   while( vg.accumulator >= (VG_TIMESTEP_FIXED-0.00125) ){
+   vg.time_fixed_accumulator += vg.time_delta;
+
+   while( vg.time_fixed_accumulator >= VG_TIMESTEP_FIXED ){
       vg_update_fixed();
       vg_lines.allow_input = 0;
 
-      vg.accumulator -= VG_TIMESTEP_FIXED;
-      vg.accumulator  = VG_MAX( 0.0, vg.accumulator );
+      vg.time_fixed_accumulator -= VG_TIMESTEP_FIXED;
+      //vg.accumulator  = VG_MAX( 0.0, vg.accumulator );
 
       vg.fixed_iterations ++;
       if( vg.fixed_iterations == 8 ){
@@ -490,6 +500,7 @@ VG_STATIC void _vg_gameloop_update(void)
       }
    }
    vg_lines.allow_input = 1;
+   vg.time_fixed_extrapolate = vg.time_fixed_accumulator / VG_TIMESTEP_FIXED;
 
    vg.engine_stage = k_engine_stage_update;
    vg_update_post();
@@ -512,28 +523,40 @@ VG_STATIC void _vg_gameloop_render(void)
 
          /* TODO */
          ui_set_mouse( vg.mouse_pos[0], vg.mouse_pos[1], 0 );
+
+         int frame_target = vg.display_refresh_rate;
+
+         if( vg.fps_limit > 0 ){
+            frame_target = vg.fps_limit;
+         }
          
          vg_profile_drawn( 
-               (struct vg_profile *[]){&vg_prof_update,&vg_prof_render}, 2,
-               (1.0f/(float)vg.refresh_rate)*1000.0f, 
+               (struct vg_profile *[]){
+                  &vg_prof_update,&vg_prof_render,&vg_prof_swap}, 3,
+               (1.0f/(float)frame_target)*1000.0f, 
                (ui_rect){ 4, 4, 250, 0 }, 0
          );
 
          if( vg_profiler ){
-            char perf[128];
+            char perf[256];
             
-            snprintf( perf, 127
+            snprintf( perf, 255
                   "x: %d y: %d\n"
-                  "refresh: %.1f (%.1fms)\n"
+                  "refresh: %d (%.1fms)\n"
                   "samples: %d\n"
-                  "iterations: %d (acc: %.3fms%%)\n",
+                  "iterations: %d (acc: %.3fms%%)\n"
+                  "time: real(%.2f) delta(%.2f) rate(%.2f)\n"
+                  "      extrap(%.2f) frame(%.2f) spin( %lu )\n",
                   vg.window_x, vg.window_y, 
-                  vg.refresh_rate, (1.0f/vg.refresh_rate)*1000.0f,
+                  frame_target, (1.0f/(float)frame_target)*1000.0f,
                   vg.samples, 
                   vg.fixed_iterations, 
-                  (vg.accumulator/VG_TIMESTEP_FIXED)*100.0f );
+                  (vg.time_fixed_accumulator/VG_TIMESTEP_FIXED)*100.0f,
+                  vg.time, vg.time_delta, vg.time_rate,
+                  vg.time_fixed_extrapolate, vg.time_frame_delta,
+                  vg.time_spinning );
 
-            ui_text( (ui_rect){258, 4+24+12,0,0},perf, 1,0);
+            ui_text( (ui_rect){258, 4+24+12+12,0,0},perf, 1,0);
          }
 
          /* FIXME */
@@ -549,20 +572,105 @@ VG_STATIC void _vg_gameloop_render(void)
    vg_profile_end( &vg_prof_render );
 }
 
+VG_STATIC int vg_framefilter( double dt )
+{
+   if( (vg.fps_limit <= 0) && (vg.vsync_feature != k_vsync_feature_error) ){
+      /* turn on vsync if not enabled */
+
+      enum vsync_feature requested = k_vsync_feature_enabled;
+      if( vg.fps_limit < 0 ) requested = k_vsync_feature_enabled_adaptive;
+
+      if( vg.vsync_feature != requested ){
+         vg_info( "Setting swap interval\n" );
+
+         int swap_interval = 1;
+         if( requested == k_vsync_feature_enabled_adaptive ) swap_interval = -1;
+
+         if( SDL_GL_SetSwapInterval( swap_interval ) == -1 ){
+            if( requested == k_vsync_feature_enabled ){
+               vg_error( "Vsync is not supported by your system\n" );
+               vg_warn( "You may be overriding it in your"
+                        " graphics control panel.\n" );
+            }
+            else{
+               vg_error( "Adaptive Vsync is not supported by your system\n" );
+            }
+
+            vg.vsync_feature = k_vsync_feature_error;
+            vg.fps_limit = vg.display_refresh_rate;
+
+            /* TODO: Make popup to notify user that this happened */
+            return 1;
+         }
+         else{
+            vg_success( "Vsync enabled (%d)\n", requested );
+            vg.vsync_feature = requested;
+         }
+      }
+
+      return 0;
+   }
+
+   if( vg.vsync_feature != k_vsync_feature_disabled ){
+      SDL_GL_SetSwapInterval( 0 );
+      vg.vsync_feature = k_vsync_feature_disabled;
+   }
+   
+   if( vg.fps_limit < 25 ) vg.fps_limit = 25;
+   if( vg.fps_limit > 300 ) vg.fps_limit = 300;
+
+   double min_frametime = 1.0/(double)vg.fps_limit;
+   if( vg.time_frame_delta < min_frametime ){
+      /* TODO: we can use high res nanosleep on Linux here */
+      double sleep_ms = (min_frametime-vg.time_frame_delta) * 1000.0;
+      u32 ms = (u32)floor( sleep_ms );
+
+      if( ms ){
+         SDL_Delay( ms );
+      }
+      else{
+         vg.time_spinning ++;
+      }
+
+      return 1;
+   }
+
+   return 0;
+}
+
 VG_STATIC void _vg_gameloop(void)
 {
-   vg.accumulator = 0.75f * (1.0f/60.0f);
+   //vg.time_fixed_accumulator = 0.75f * (1.0f/60.0f);
+
+   vg.time_hp = SDL_GetPerformanceCounter();
+   vg.time_hp_last = vg.time_hp;
 
    int post_start = 0;
    while(1){
+   
+      vg.time_hp = SDL_GetPerformanceCounter();
+      u64 udt = vg.time_hp - vg.time_hp_last;
+      vg.time_hp_last = vg.time_hp;
+
+      double dt = (double)udt / (double)SDL_GetPerformanceFrequency();
+
+      vg.time_frame_delta += dt;
+
+      if( vg_framefilter( dt ) )
+         continue;
+
+      vg_profile_begin( &vg_prof_swap );
+      SDL_GL_SwapWindow( vg.window );
+      _vg_run_synced();
+      vg_profile_end( &vg_prof_swap );
+
+      vg.time_delta = vg.time_frame_delta * vg.time_rate;
+      vg.time += vg.time_delta;
+
       _vg_process_events();
 
       if( vg.window_should_close )
          break;
-
-      /* scaled time */
-      vg.time_delta = vg.frame_delta * vg.time_rate;
-      vg.time += vg.time_delta;
       
       if( vg.is_loaded ){
          if( !post_start ){
@@ -577,8 +685,8 @@ VG_STATIC void _vg_gameloop(void)
       _vg_gameloop_update();
       _vg_gameloop_render();
 
-      SDL_GL_SwapWindow( vg.window );
-      _vg_run_synced();
+      vg.time_frame_delta = 0.0;
+      vg.time_spinning = 0;
    }
 }
 
@@ -641,46 +749,35 @@ VG_STATIC void _vg_init_window( const char *window_name )
     * Get monitor information 
     */
    vg_info( "Getting display count\n" );
-   int display_count = 0, display_index = 0, mode_index = 0;
-   if( (display_count = SDL_GetNumVideoDisplays()) < 1 ){
-      vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count );
-      exit(0);
-   }
-
+   int display_count = 0, 
+       display_index = 0, 
+       mode_index = 0;
 
 #ifdef VG_DEVWINDOW
-   vg.refresh_rate = 60;
    vg.window_x = 1000;
    vg.window_y = 800;
 #else
-   /* TODO: Allow chosing the modes at startup */
-   vg_info( "Getting default display mode\n" );
-   SDL_DisplayMode vm_ideal = { 0, 0, 0, 0, 0 };
-   if( SDL_GetDisplayMode( display_index, mode_index, &vm_ideal ) != 0 ){
-      vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
-      exit(0);
-   }
-
-   if( vg.window_x )
-      vm_ideal.w = vg.window_x;
-
-   if( vg.window_y )
-      vm_ideal.h = vg.window_y;
 
-
-   SDL_DisplayMode vm_best;
-   if( !SDL_GetClosestDisplayMode( display_index, &vm_ideal, &vm_best ) ){
-      vg_error( "SDL_GetClosestDisplayMode failed: %s", SDL_GetError() );
+   SDL_DisplayMode video_mode;
+   if( SDL_GetDesktopDisplayMode( display_index, &video_mode ) ){
+      vg_error( "SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError() );
+      SDL_Quit();
       exit(0);
    }
 
-   vg.refresh_rate = vm_best.refresh_rate;
-   vg.window_x = vm_best.w;
-   vg.window_y = vm_best.h;
+   vg.display_refresh_rate = video_mode.refresh_rate;
+   vg.window_x = video_mode.w;
+   vg.window_y = video_mode.h;
+#endif
+
+#ifndef _WIN32
+       SDL_SetHint( "SDL_VIDEO_X11_XINERAMA", "1" );
+       SDL_SetHint( "SDL_VIDEO_X11_XRANDR", "0" );
+       SDL_SetHint( "SDL_VIDEO_X11_XVIDMODE", "0" );
 #endif
 
-   vg_info( "CreateWindow( %d %d @%.2fhz )\n", vg.window_x, vg.window_y,
-                                               vg.refresh_rate );
+   vg_info( "CreateWindow( %d %d @%dhz )\n", vg.window_x, vg.window_y,
+                                             vg.display_refresh_rate );
 
    /* TODO: Allow selecting closest video mode from launch opts */
    if((vg.window = SDL_CreateWindow( window_name,
@@ -690,8 +787,7 @@ VG_STATIC void _vg_init_window( const char *window_name )
          SDL_WINDOW_BORDERLESS|SDL_WINDOW_OPENGL|SDL_WINDOW_INPUT_GRABBED
       ))){}
 #else
-                                     SDL_WINDOWPOS_UNDEFINED,
-                                     SDL_WINDOWPOS_UNDEFINED,
+                                     0, 0,
                                      vg.window_x, vg.window_y,
 
                                      SDL_WINDOW_FULLSCREEN_DESKTOP | 
@@ -699,7 +795,7 @@ VG_STATIC void _vg_init_window( const char *window_name )
                                      SDL_WINDOW_INPUT_GRABBED 
                                      )))
    {
-      if( SDL_SetWindowDisplayMode( vg.window, &vm_best ) ){
+      if( SDL_SetWindowDisplayMode( vg.window, &video_mode ) ){
          vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
          SDL_Quit();
          exit(0);
@@ -711,6 +807,8 @@ VG_STATIC void _vg_init_window( const char *window_name )
       exit(0);
    }
 
+   SDL_RaiseWindow( vg.window );
+
    vg_info( "CreateContext\n" );
 
    /* 
@@ -736,28 +834,28 @@ VG_STATIC void _vg_init_window( const char *window_name )
    const unsigned char* glver = glGetString( GL_VERSION );
    vg_success( "Load setup complete, OpenGL version: %s\n", glver );
 
-   vg_info( "Setting swap interval\n" );
-
-   if( SDL_GL_SetSwapInterval( -1 ) == -1 ){
-      vg_warn( "Adaptive Vsync not supported\n" );
-
-      if( SDL_GL_SetSwapInterval( 1 ) == -1 ){
-         vg_fatal_exit_loop( "Cannot enable Vsync! You might be overriding it"
-                             " in your graphics control panel.\n" );
-      }
-      else
-         vg_success( "Using vsync\n" );
-   }
-   else
-      vg_success( "Using adaptive Vsync\n" );
+   SDL_GL_SetSwapInterval(0); /* disable vsync while loading */
 
    SDL_DisplayMode dispmode;
    if( !SDL_GetWindowDisplayMode( vg.window, &dispmode ) ){
       if( dispmode.refresh_rate ){
-         vg.refresh_rate = dispmode.refresh_rate;
-         vg_info( "Refresh rate: %d\n", dispmode.refresh_rate );
+         vg.display_refresh_rate = dispmode.refresh_rate;
       }
    }
+
+   if( vg.display_refresh_rate < 25 || vg.display_refresh_rate > 300 ){
+      vg.display_refresh_rate = 60;
+   }
+
+   vg_info( "Display refresh rate: %d\n", dispmode.refresh_rate );
+
+#ifdef _WIN32
+   vg.fps_limit = vg.display_refresh_rate;
+#else
+   /* request vsync by default on linux to avoid screen tearing.
+    * this does have its own issues with compositing on X11. */
+   vg.fps_limit = 0;
+#endif
 }
 
 VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name )
@@ -768,6 +866,9 @@ VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name )
    vg_alloc_quota();
    _vg_log_init();
    _vg_console_init();
+   
+   vg_console_reg_var( "fps_limit", &vg.fps_limit, k_var_dtype_i32, 0 );
+
    _vg_init_window( window_name );
    
    SDL_SetRelativeMouseMode(1);
@@ -860,7 +961,7 @@ VG_STATIC void vg_fatal_exit_loop( const char *error )
          glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
          glBlendEquation(GL_FUNC_ADD);
 
-         glClearColor( 0.15f + sinf(vg.time_real)*0.1f, 0.0f, 0.0f,1.0f );
+         glClearColor( 0.15f + sinf(vg.time)*0.1f, 0.0f, 0.0f,1.0f );
          glClear( GL_COLOR_BUFFER_BIT );
          glViewport( 0,0, vg.window_x, vg.window_y );