1 /* Copyright (C) 2021-2023 Harry Godden (hgn) - All Rights Reserved */
7 | | .---------------------------------------------------------.
8 |API| | vg_enter( int argc, char *argv[], const char *window_name |
9 | | '---------------------------------------------------------'
12 |IMP| vg_launch_opt(void) <--.
14 | | |'---------------'
16 | | |'-----------------------------------| 1 |------.
19 | | | |IMP| vg_preload(void)
22 | | | | |IMP| vg_load(void)
24 |IMP| | vg_framebuffer_resize(void) |
26 |IMP| | |.------------- vg_start(void) ---------------'
29 |IMP| | vg_update(void)
34 |IMP| | '- vg_update_fixed(void)
39 |IMP| | vg_update_post(void)
42 |IMP| | vg_render(void)
55 #include "vg_platform.h"
62 VG_STATIC
void vg_print_backtrace(void)
70 size
= backtrace( array
, 20 );
71 strings
= backtrace_symbols( array
, size
);
73 if( strings
!= NULL
){
74 vg_error( "---------------- gnu backtrace -------------\n" );
76 for( int i
=0; i
<size
; i
++ )
77 vg_info( "%s\n", strings
[i
] );
79 vg_error( "---------------- gnu backtrace -------------\n" );
88 #include "dep/glad/glad.h"
89 #include "submodules/SDL/include/SDL.h"
90 #include "vg_stdint.h"
92 void vg_register_exit( void( *funcptr
)(void), const char *name
);
100 //#define VG_SYNC_DEBUG
102 #define VG_SYNC_LOG(STR,...) \
103 vg_info(STR,SDL_GetThreadID(NULL),##__VA_ARGS__)
105 #define VG_SYNC_LOG(...)
109 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
);
112 VG_STATIC
void vg_preload(void);
113 VG_STATIC
void vg_load(void);
116 VG_STATIC
void vg_launch_opt(void);
117 VG_STATIC
void vg_start(void);
119 VG_STATIC
void vg_framebuffer_resize(int w
, int h
);
120 VG_STATIC
void vg_update(void);
121 VG_STATIC
void vg_update_fixed(void);
122 VG_STATIC
void vg_update_post(void);
124 VG_STATIC
void vg_render(void);
125 VG_STATIC
void vg_ui(void);
131 SDL_GLContext gl_context
;
133 SDL_sem
*sem_loader
; /* allows only one loader at a time */
135 jmp_buf env_loader_exit
;
137 SDL_threadID thread_id_main
,
140 SDL_SpinLock sl_status
;
143 k_engine_status_none
,
144 k_engine_status_load_internal
,
145 k_engine_status_running
,
146 k_engine_status_crashed
150 /* Window information */
156 int display_refresh_rate
,
157 fps_limit
; /* 0: use vsync, >0: cap fps to this, no vsync */
161 k_vsync_feature_disabled
=0,
162 k_vsync_feature_enabled
=1,
163 k_vsync_feature_enabled_adaptive
=2,
164 k_vsync_feature_error
=3
177 time_fixed_accumulator
,
178 time_fixed_extrapolate
,
181 u64 time_hp
, time_hp_last
, time_spinning
;
183 int fixed_iterations
;
188 k_engine_stage_update
,
189 k_engine_stage_update_fixed
,
190 k_engine_stage_rendering
,
199 k_quality_profile_high
= 0,
200 k_quality_profile_low
= 1,
206 VG_STATIC vg
= { .time_rate
= 1.0 };
208 enum vg_thread_purpose
210 k_thread_purpose_nothing
,
211 k_thread_purpose_main
,
212 k_thread_purpose_loader
215 #include "vg_async.h"
217 VG_STATIC
enum engine_status
_vg_engine_status(void)
219 SDL_AtomicLock( &vg
.sl_status
);
220 enum engine_status status
= vg
.engine_status
;
221 SDL_AtomicUnlock( &vg
.sl_status
);
226 VG_STATIC
enum vg_thread_purpose
vg_thread_purpose(void)
228 SDL_AtomicLock( &vg
.sl_status
);
230 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) ){
231 SDL_AtomicUnlock( &vg
.sl_status
);
232 return k_thread_purpose_main
;
235 SDL_AtomicUnlock( &vg
.sl_status
);
236 return k_thread_purpose_loader
;
240 VG_STATIC
void _vg_opengl_sync_init(void)
242 vg
.sem_loader
= SDL_CreateSemaphore(1);
245 VG_STATIC
void vg_checkgl( const char *src_info
);
246 #define VG_STRINGIT( X ) #X
247 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
249 #include "vg_console.h"
250 #include "vg_profiler.h"
251 #include "vg_audio.h"
252 #include "vg_shader.h"
254 #include "vg_input.h"
256 #include "vg_lines.h"
257 #include "vg_loader.h"
261 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
262 vg_prof_render
= {.name
="render()"},
263 vg_prof_swap
= {.name
="swap"};
265 VG_STATIC
void vg_checkgl( const char *src_info
)
270 while( (err
= glGetError()) != GL_NO_ERROR
){
271 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
276 vg_fatal_error( "OpenGL Error" );
279 VG_STATIC
void async_vg_bake_shaders( void *payload
, u32 size
)
281 vg_shaders_compile();
284 VG_STATIC
void vg_bake_shaders(void)
286 vg_console_reg_cmd( "reload_shaders", vg_shaders_live_recompile
, NULL
);
287 vg_async_call( async_vg_bake_shaders
, NULL
, 0 );
290 void async_internal_complete( void *payload
, u32 size
)
292 vg_success( "Internal async setup complete\n" );
293 SDL_AtomicLock( &vg
.sl_status
);
295 if( vg
.engine_status
== k_engine_status_crashed
){
296 SDL_AtomicUnlock( &vg
.sl_status
);
300 vg
.engine_status
= k_engine_status_running
;
303 SDL_AtomicUnlock( &vg
.sl_status
);
306 VG_STATIC
void _vg_load_full(void)
311 vg_loader_step( vg_input_init
, vg_input_free
);
312 vg_loader_step( vg_lines_init
, NULL
);
313 vg_loader_step( vg_audio_init
, vg_audio_free
);
314 vg_loader_step( vg_profiler_init
, NULL
);
316 vg_async_call( async_internal_complete
, NULL
, 0 );
322 VG_STATIC
void _vg_process_events(void)
324 v2_zero( vg
.mouse_wheel
);
325 v2_zero( vg
.mouse_delta
);
329 while( SDL_PollEvent( &event
) ){
330 if( event
.type
== SDL_KEYDOWN
){
331 console_proc_key( event
.key
.keysym
);
333 else if( event
.type
== SDL_MOUSEWHEEL
){
334 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
335 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
337 else if( event
.type
== SDL_CONTROLLERDEVICEADDED
||
338 event
.type
== SDL_CONTROLLERDEVICEREMOVED
)
340 vg_input_device_event( &event
);
342 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
343 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
344 event
.type
== SDL_CONTROLLERBUTTONUP
)
346 vg_input_controller_event( &event
);
348 else if( event
.type
== SDL_MOUSEMOTION
){
349 vg
.mouse_delta
[0] += event
.motion
.xrel
;
350 vg
.mouse_delta
[1] += event
.motion
.yrel
;
352 else if( event
.type
== SDL_WINDOWEVENT
){
353 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
){
355 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
358 vg_warn( "Got a invalid framebuffer size: "
359 "%dx%d... ignoring\n", w
, h
);
365 vg_framebuffer_resize(w
,h
);
368 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
){
369 vg
.window_should_close
= 1;
372 else if( event
.type
== SDL_TEXTINPUT
){
373 console_proc_utf8( event
.text
.text
);
377 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
378 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
384 VG_STATIC
void _vg_gameloop_update(void)
386 vg_profile_begin( &vg_prof_update
);
388 vg
.engine_stage
= k_engine_stage_update
;
391 /* Fixed update loop */
392 vg
.engine_stage
= k_engine_stage_update_fixed
;
394 vg
.fixed_iterations
= 0;
395 vg_lines
.allow_input
= 1;
396 vg
.time_fixed_accumulator
+= vg
.time_delta
;
398 while( vg
.time_fixed_accumulator
>= VG_TIMESTEP_FIXED
){
400 vg_lines
.allow_input
= 0;
402 vg
.time_fixed_accumulator
-= VG_TIMESTEP_FIXED
;
403 //vg.accumulator = VG_MAX( 0.0, vg.accumulator );
405 vg
.fixed_iterations
++;
406 if( vg
.fixed_iterations
== 8 ){
410 vg_lines
.allow_input
= 1;
411 vg
.time_fixed_extrapolate
= vg
.time_fixed_accumulator
/ VG_TIMESTEP_FIXED
;
413 vg
.engine_stage
= k_engine_stage_update
;
415 vg_profile_end( &vg_prof_update
);
418 VG_STATIC
void _vg_gameloop_render(void)
420 vg_profile_begin( &vg_prof_render
);
423 vg
.engine_stage
= k_engine_stage_rendering
;
427 vg
.engine_stage
= k_engine_stage_ui
;
429 ui_begin( vg
.window_x
, vg
.window_y
);
432 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
434 int frame_target
= vg
.display_refresh_rate
;
436 if( vg
.fps_limit
> 0 ){
437 frame_target
= vg
.fps_limit
;
441 (struct vg_profile
*[]){
442 &vg_prof_update
,&vg_prof_render
,&vg_prof_swap
}, 3,
443 (1.0f
/(float)frame_target
)*1000.0f
,
444 (ui_rect
){ 4, 4, 250, 0 }, 0
452 "refresh: %d (%.1fms)\n"
454 "iterations: %d (acc: %.3fms%%)\n"
455 "time: real(%.2f) delta(%.2f) rate(%.2f)\n"
457 " extrap(%.2f) frame(%.2f) spin( %llu )\n",
459 " extrap(%.2f) frame(%.2f) spin( %lu )\n",
461 vg
.window_x
, vg
.window_y
,
462 frame_target
, (1.0f
/(float)frame_target
)*1000.0f
,
465 (vg
.time_fixed_accumulator
/VG_TIMESTEP_FIXED
)*100.0f
,
466 vg
.time
, vg
.time_delta
, vg
.time_rate
,
467 vg
.time_fixed_extrapolate
, vg
.time_frame_delta
,
470 ui_text( (ui_rect
){258, 4+24+12+12,0,0},perf
, 1,0);
474 audio_debug_ui( vg
.pv
);
482 vg_profile_end( &vg_prof_render
);
485 VG_STATIC
int vg_framefilter( double dt
)
487 if( (vg
.fps_limit
<= 0) && (vg
.vsync_feature
!= k_vsync_feature_error
) ){
488 /* turn on vsync if not enabled */
490 enum vsync_feature requested
= k_vsync_feature_enabled
;
491 if( vg
.fps_limit
< 0 ) requested
= k_vsync_feature_enabled_adaptive
;
493 if( vg
.vsync_feature
!= requested
){
494 vg_info( "Setting swap interval\n" );
496 int swap_interval
= 1;
497 if( requested
== k_vsync_feature_enabled_adaptive
) swap_interval
= -1;
499 if( SDL_GL_SetSwapInterval( swap_interval
) == -1 ){
500 if( requested
== k_vsync_feature_enabled
){
501 vg_error( "Vsync is not supported by your system\n" );
502 vg_warn( "You may be overriding it in your"
503 " graphics control panel.\n" );
506 vg_error( "Adaptive Vsync is not supported by your system\n" );
509 vg
.vsync_feature
= k_vsync_feature_error
;
510 vg
.fps_limit
= vg
.display_refresh_rate
;
512 /* TODO: Make popup to notify user that this happened */
516 vg_success( "Vsync enabled (%d)\n", requested
);
517 vg
.vsync_feature
= requested
;
524 if( vg
.vsync_feature
!= k_vsync_feature_disabled
){
525 SDL_GL_SetSwapInterval( 0 );
526 vg
.vsync_feature
= k_vsync_feature_disabled
;
529 if( vg
.fps_limit
< 25 ) vg
.fps_limit
= 25;
530 if( vg
.fps_limit
> 300 ) vg
.fps_limit
= 300;
532 double min_frametime
= 1.0/(double)vg
.fps_limit
;
533 if( vg
.time_frame_delta
< min_frametime
){
534 /* TODO: we can use high res nanosleep on Linux here */
535 double sleep_ms
= (min_frametime
-vg
.time_frame_delta
) * 1000.0;
536 u32 ms
= (u32
)floor( sleep_ms
);
551 VG_STATIC
int _vg_crashscreen(void)
554 if( vg_getkey( SDLK_ESCAPE
) )
558 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
560 glDisable(GL_DEPTH_TEST
);
561 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
562 glBlendEquation(GL_FUNC_ADD
);
564 glClearColor( 0.15f
+ sinf(vg
.time
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
565 glClear( GL_COLOR_BUFFER_BIT
);
566 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
573 VG_STATIC
void _vg_gameloop(void)
575 //vg.time_fixed_accumulator = 0.75f * (1.0f/60.0f);
577 vg
.time_hp
= SDL_GetPerformanceCounter();
578 vg
.time_hp_last
= vg
.time_hp
;
583 vg
.time_hp
= SDL_GetPerformanceCounter();
584 u64 udt
= vg
.time_hp
- vg
.time_hp_last
;
585 vg
.time_hp_last
= vg
.time_hp
;
587 double dt
= (double)udt
/ (double)SDL_GetPerformanceFrequency();
589 vg
.time_frame_delta
+= dt
;
591 if( vg_framefilter( dt
) )
594 vg_profile_begin( &vg_prof_swap
);
595 SDL_GL_SwapWindow( vg
.window
);
596 vg_profile_end( &vg_prof_swap
);
598 enum engine_status status
= _vg_engine_status();
600 vg
.time_delta
= vg
.time_frame_delta
* vg
.time_rate
;
601 vg
.time
+= vg
.time_delta
;
603 vg_run_async_checked();
604 _vg_process_events();
606 if( vg
.window_should_close
)
609 if( status
== k_engine_status_crashed
){
610 if( _vg_crashscreen() )
614 if( status
== k_engine_status_running
){
615 _vg_gameloop_update();
616 _vg_gameloop_render();
623 if( vg
.loader_ring
> 0.01f
){
624 vg
.loader_ring
-= vg
.time_frame_delta
* 0.5f
;
625 _vg_loader_render_ring( vg
.loader_ring
);
628 vg
.time_frame_delta
= 0.0;
629 vg
.time_spinning
= 0;
633 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
636 while( vg_argp( argc
, argv
) ){
637 if( (arg
= vg_opt_arg( 'w' )) ){
638 vg
.window_x
= atoi( arg
);
641 if( (arg
= vg_opt_arg( 'h' )) ){
642 vg
.window_y
= atoi( arg
);
645 if( (arg
= vg_long_opt_arg( "samples" )) ){
646 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
649 if( vg_long_opt( "use-libc-malloc" ) ){
650 vg_mem
.use_libc_malloc
= 1;
653 if( vg_long_opt( "high-performance" ) ){
654 vg
.quality_profile
= k_quality_profile_low
;
661 VG_STATIC
void _vg_init_window( const char *window_name
)
663 vg_info( "SDL_INIT\n" );
665 if( SDL_Init( SDL_INIT_VIDEO
) != 0 ){
666 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
670 SDL_InitSubSystem( SDL_INIT_AUDIO
);
671 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER
);
673 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
674 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
675 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
676 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
677 SDL_GL_CONTEXT_PROFILE_CORE
);
679 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
680 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
682 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
683 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
684 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
685 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
686 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 0 );
689 * Get monitor information
691 vg_info( "Getting display count\n" );
692 int display_count
= 0,
701 SDL_DisplayMode video_mode
;
702 if( SDL_GetDesktopDisplayMode( display_index
, &video_mode
) ){
703 vg_error( "SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError() );
708 vg
.display_refresh_rate
= video_mode
.refresh_rate
;
709 vg
.window_x
= video_mode
.w
;
710 vg
.window_y
= video_mode
.h
;
714 SDL_SetHint( "SDL_VIDEO_X11_XINERAMA", "1" );
715 SDL_SetHint( "SDL_VIDEO_X11_XRANDR", "0" );
716 SDL_SetHint( "SDL_VIDEO_X11_XVIDMODE", "0" );
719 vg_info( "CreateWindow( %d %d @%dhz )\n", vg
.window_x
, vg
.window_y
,
720 vg
.display_refresh_rate
);
722 /* TODO: Allow selecting closest video mode from launch opts */
723 if((vg
.window
= SDL_CreateWindow( window_name
,
726 0, 0, vg
.window_x
, vg
.window_y
,
727 SDL_WINDOW_BORDERLESS
|SDL_WINDOW_OPENGL
|SDL_WINDOW_INPUT_GRABBED
731 vg
.window_x
, vg
.window_y
,
733 SDL_WINDOW_FULLSCREEN_DESKTOP
|
735 SDL_WINDOW_INPUT_GRABBED
738 if( SDL_SetWindowDisplayMode( vg
.window
, &video_mode
) ){
739 vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
746 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
750 SDL_RaiseWindow( vg
.window
);
752 vg_info( "CreateContext\n" );
757 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) )){
758 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
759 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
762 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
767 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) ) {
768 vg_error( "Glad Failed to initialize\n" );
769 SDL_GL_DeleteContext( vg
.gl_context
);
774 const unsigned char* glver
= glGetString( GL_VERSION
);
775 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
777 SDL_GL_SetSwapInterval(0); /* disable vsync while loading */
779 SDL_DisplayMode dispmode
;
780 if( !SDL_GetWindowDisplayMode( vg
.window
, &dispmode
) ){
781 if( dispmode
.refresh_rate
){
782 vg
.display_refresh_rate
= dispmode
.refresh_rate
;
786 if( vg
.display_refresh_rate
< 25 || vg
.display_refresh_rate
> 300 ){
787 vg
.display_refresh_rate
= 60;
790 vg_info( "Display refresh rate: %d\n", dispmode
.refresh_rate
);
793 vg
.fps_limit
= vg
.display_refresh_rate
;
795 /* request vsync by default on linux to avoid screen tearing.
796 * this does have its own issues with compositing on X11. */
801 VG_STATIC
void _vg_terminate(void)
804 _vg_console_write_persistent();
806 SDL_AtomicLock( &vg
.sl_status
);
807 vg
.engine_status
= k_engine_status_none
;
808 SDL_AtomicUnlock( &vg
.sl_status
);
812 vg_success( "If you see this it means everything went.. \"well\".....\n" );
814 SDL_GL_DeleteContext( vg
.gl_context
);
819 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
821 _vg_process_launch_opts_internal( argc
, argv
);
827 vg_console_reg_var( "fps_limit", &vg
.fps_limit
, k_var_dtype_i32
, 0 );
828 _vg_init_window( window_name
);
832 SDL_SetRelativeMouseMode(1);
833 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
835 /* Opengl-required systems */
839 vg
.engine_status
= k_engine_status_load_internal
;
841 _vg_opengl_sync_init();
842 vg_loader_start( _vg_load_full
);
847 VG_STATIC
void vg_fatal_error( const char *fmt
, ... )
850 va_start( args
, fmt
);
851 _vg_log_write( stderr
, KRED
" fatal" KWHT
"| " KRED
, fmt
, args
);
854 vg_print_backtrace();
856 SDL_AtomicLock( &vg
.sl_status
);
857 vg
.engine_status
= k_engine_status_crashed
;
858 SDL_AtomicUnlock( &vg
.sl_status
);
860 if( vg_thread_purpose() == k_thread_purpose_loader
){
861 longjmp( vg
.env_loader_exit
, 1 );
864 vg_error( "There is no jump to the error runner thing yet! bai bai\n" );
872 VG_STATIC
void vg_fatal_error( const char *fmt
, ... )
875 va_start( args
, fmt
);
876 _vg_log_write( stderr
, KRED
" fatal" KWHT
"| " KRED
, fmt
, args
);
884 * Graphic cards will check these to force it to use the GPU
886 u32 NvOptimusEnablement
= 0x00000001;
887 int AmdPowerXpressRequestHighPerformance
= 1;
889 #endif /* VG_HEADER_H */