1 /* Copyright (C) 2021-2022 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)
52 | | .-------------------------------------.
53 |API| | vg_fatal_exit_loop( const char *err ) |
54 | | '-------------------------------------'
59 |IMP| '- vg_framebuffer_resize(void)
69 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
);
72 VG_STATIC
void vg_preload(void);
73 VG_STATIC
void vg_load(void);
76 VG_STATIC
void vg_launch_opt(void);
77 VG_STATIC
void vg_start(void);
79 VG_STATIC
void vg_framebuffer_resize(int w
, int h
);
80 VG_STATIC
void vg_update(void);
81 VG_STATIC
void vg_update_fixed(void);
82 VG_STATIC
void vg_update_post(void);
84 VG_STATIC
void vg_render(void);
85 VG_STATIC
void vg_ui(void);
90 #include "vg_platform.h"
98 #include "dep/glad/glad.h"
99 #include "submodules/SDL/include/SDL.h"
100 #include "vg_stdint.h"
102 void vg_register_exit( void( *funcptr
)(void), const char *name
);
107 #include "vg_steam.h"
109 //#define VG_SYNC_DEBUG
111 #define VG_SYNC_LOG(STR,...) \
112 vg_info(STR,SDL_GetThreadID(NULL),##__VA_ARGS__)
114 #define VG_SYNC_LOG(...)
121 SDL_GLContext gl_context
;
123 SDL_SpinLock sl_context
;
124 SDL_sem
*sem_allow_exec
,
128 SDL_threadID thread_id_main
,
130 thread_id_with_opengl_context
;
131 int context_ownership_depth
;
137 k_engine_status_none
,
138 k_engine_status_running
,
139 k_engine_status_crashed
142 const char *str_const_engine_err
;
145 /* Window information */
166 int fixed_iterations
;
171 k_engine_stage_update
,
172 k_engine_stage_update_fixed
,
173 k_engine_stage_rendering
,
184 k_quality_profile_high
= 0,
185 k_quality_profile_low
= 1,
189 VG_STATIC vg
= { .time_rate
= 1.0 };
191 enum vg_thread_purpose
193 k_thread_purpose_nothing
,
194 k_thread_purpose_main
,
195 k_thread_purpose_loader
198 VG_STATIC
void vg_fatal_exit_loop( const char *error
);
201 * Checks if the engine is running
203 VG_STATIC
void _vg_ensure_engine_running(void)
205 /* Check if the engine is no longer running */
206 SDL_AtomicLock( &vg
.sl_context
);
207 enum engine_status status
= vg
.engine_status
;
208 SDL_AtomicUnlock( &vg
.sl_context
);
210 if( status
!= k_engine_status_running
)
214 VG_SYNC_LOG( "[%d] No longer running...\n");
220 VG_STATIC
enum vg_thread_purpose
vg_thread_purpose(void)
222 SDL_AtomicLock( &vg
.sl_context
);
224 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
226 SDL_AtomicUnlock( &vg
.sl_context
);
227 return k_thread_purpose_main
;
231 SDL_AtomicUnlock( &vg
.sl_context
);
232 return k_thread_purpose_loader
;
237 * Sync execution so that the OpenGL context is switched onto this thread.
238 * Anything after this call will be in a valid context.
240 VG_STATIC
void vg_acquire_thread_sync(void)
242 /* We dont want to do anything if this is the main thread */
244 if( vg_thread_purpose() == k_thread_purpose_loader
)
246 VG_SYNC_LOG( "[%d] vg_acquire_thread_sync()\n" );
247 _vg_ensure_engine_running();
249 SDL_AtomicLock( &vg
.sl_context
);
250 if( vg
.context_ownership_depth
== 0 )
252 vg
.context_ownership_depth
++;
254 SDL_AtomicUnlock( &vg
.sl_context
);
256 /* wait until told we can go */
257 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
258 SDL_SemWait( vg
.sem_allow_exec
);
260 _vg_ensure_engine_running();
262 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
263 VG_SYNC_LOG( "[%d] granted\n" );
267 vg
.context_ownership_depth
++;
268 VG_SYNC_LOG( "[%d] granted\n" );
269 SDL_AtomicUnlock( &vg
.sl_context
);
275 * Signify that we are done with the OpenGL context in this thread.
276 * Anything after this call will be in an undefined context.
278 VG_STATIC
void vg_release_thread_sync(void)
280 if( vg_thread_purpose() == k_thread_purpose_loader
)
282 VG_SYNC_LOG( "[%d] vg_release_thread_sync()\n" );
284 SDL_AtomicLock( &vg
.sl_context
);
285 vg
.context_ownership_depth
--;
287 if( vg
.context_ownership_depth
== 0 )
289 SDL_AtomicUnlock( &vg
.sl_context
);
290 VG_SYNC_LOG( "[%d] Releasing context.\n" );
291 SDL_GL_MakeCurrent( NULL
, NULL
);
292 SDL_SemPost( vg
.sem_exec_finished
);
295 SDL_AtomicUnlock( &vg
.sl_context
);
299 VG_STATIC
void _vg_run_synced(void)
301 SDL_AtomicLock( &vg
.sl_context
);
303 if( vg
.exec_context
!= 0 )
305 VG_SYNC_LOG( "[%d] _vg_run_synced() (%d).\n", vg
.exec_context
);
307 SDL_AtomicUnlock( &vg
.sl_context
);
309 /* allow operations to go */
310 SDL_GL_MakeCurrent( NULL
, NULL
);
311 SDL_SemPost( vg
.sem_allow_exec
);
313 /* wait for operations to complete */
314 VG_SYNC_LOG( "[%d] Waiting for content.\n" );
315 SDL_SemWait( vg
.sem_exec_finished
);
317 /* check if we killed the engine */
318 _vg_ensure_engine_running();
320 /* re-engage main thread */
321 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
322 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
326 VG_SYNC_LOG( "[%d] Nothing to do.\n" );
327 SDL_AtomicUnlock( &vg
.sl_context
);
331 VG_STATIC
void _vg_opengl_sync_init(void)
333 vg
.sem_allow_exec
= SDL_CreateSemaphore(0);
334 vg
.sem_exec_finished
= SDL_CreateSemaphore(0);
335 vg
.sem_loader
= SDL_CreateSemaphore(1);
338 VG_STATIC
void vg_checkgl( const char *src_info
);
339 #define VG_STRINGIT( X ) #X
340 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
342 #include "vg_console.h"
343 #include "vg_profiler.h"
344 #include "vg_audio.h"
345 #include "vg_shader.h"
347 #include "vg_input.h"
349 #include "vg_lines.h"
350 #include "vg_loader.h"
354 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
355 vg_prof_render
= {.name
="render()"};
357 VG_STATIC
void vg_checkgl( const char *src_info
)
362 while( (err
= glGetError()) != GL_NO_ERROR
)
364 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
369 vg_fatal_exit_loop( "OpenGL Error" );
372 VG_STATIC
void vg_bake_shaders(void)
374 vg_acquire_thread_sync();
377 vg_function_push( (struct vg_cmd
)
380 .function
= vg_shaders_live_recompile
384 vg_shaders_compile();
385 vg_release_thread_sync();
388 VG_STATIC
void _vg_load_full(void)
393 vg_loader_step( vg_input_init
, vg_input_free
);
394 vg_loader_step( vg_lines_init
, NULL
);
395 vg_loader_step( vg_audio_init
, vg_audio_free
);
396 vg_loader_step( vg_profiler_init
, NULL
);
402 VG_STATIC
void _vg_process_events(void)
405 vg
.time_real_last
= vg
.time_real
;
406 vg
.time_real
= (double)SDL_GetTicks64() / 1000.0;
407 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
409 v2_zero( vg
.mouse_wheel
);
410 v2_zero( vg
.mouse_delta
);
414 while( SDL_PollEvent( &event
) )
416 if( event
.type
== SDL_KEYDOWN
)
418 console_proc_key( event
.key
.keysym
);
420 else if( event
.type
== SDL_MOUSEWHEEL
)
422 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
423 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
425 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
426 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
427 event
.type
== SDL_CONTROLLERBUTTONUP
||
428 event
.type
== SDL_CONTROLLERDEVICEADDED
||
429 event
.type
== SDL_CONTROLLERDEVICEREMOVED
432 vg_input_controller_event( &event
);
434 else if( event
.type
== SDL_MOUSEMOTION
)
436 vg
.mouse_delta
[0] += event
.motion
.xrel
;
437 vg
.mouse_delta
[1] += event
.motion
.yrel
;
439 else if( event
.type
== SDL_WINDOWEVENT
)
441 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
)
444 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
448 vg_warn( "Got a invalid framebuffer size: "
449 "%dx%d... ignoring\n", w
, h
);
456 vg_framebuffer_resize(w
,h
);
459 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
)
461 vg
.window_should_close
= 1;
464 else if( event
.type
== SDL_TEXTINPUT
)
466 console_proc_utf8( event
.text
.text
);
470 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
471 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
477 VG_STATIC
void _vg_gameloop_update(void)
479 vg_profile_begin( &vg_prof_update
);
481 vg
.engine_stage
= k_engine_stage_update
;
484 /* Fixed update loop */
485 vg
.engine_stage
= k_engine_stage_update_fixed
;
486 vg
.accumulator
+= vg
.time_delta
;
488 vg
.fixed_iterations
= 0;
489 vg_lines
.allow_input
= 1;
490 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
493 vg_lines
.allow_input
= 0;
495 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
496 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
498 vg
.fixed_iterations
++;
499 if( vg
.fixed_iterations
== 8 )
504 vg_lines
.allow_input
= 1;
506 vg
.engine_stage
= k_engine_stage_update
;
508 vg_profile_end( &vg_prof_update
);
511 VG_STATIC
void _vg_gameloop_render(void)
513 vg_profile_begin( &vg_prof_render
);
518 vg
.engine_stage
= k_engine_stage_rendering
;
522 vg
.engine_stage
= k_engine_stage_ui
;
524 ui_begin( vg
.window_x
, vg
.window_y
);
527 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
530 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
531 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
532 (ui_rect
){ 4, 4, 250, 0 }, 0
542 "refresh: %.1f (%.1fms)\n"
544 "iterations: %d (acc: %.3fms%%)\n",
545 vg
.window_x
, vg
.window_y
,
546 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
549 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
551 ui_text( (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
556 audio_debug_ui( vg
.pv
);
566 vg_profile_end( &vg_prof_render
);
569 VG_STATIC
void _vg_gameloop(void)
571 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
576 _vg_process_events();
578 if( vg
.window_should_close
)
582 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
583 vg
.time
+= vg
.time_delta
;
598 _vg_gameloop_update();
599 _vg_gameloop_render();
600 audio_push_console_vol();
602 SDL_GL_SwapWindow( vg
.window
);
607 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
610 while( vg_argp( argc
, argv
) )
612 if( (arg
= vg_opt_arg( 'w' )) )
614 vg
.window_x
= atoi( arg
);
617 if( (arg
= vg_opt_arg( 'h' )) )
619 vg
.window_y
= atoi( arg
);
622 if( (arg
= vg_long_opt_arg( "samples" )) )
624 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
627 if( vg_long_opt( "use-libc-malloc" ) )
629 vg_mem
.use_libc_malloc
= 1;
632 if( vg_long_opt( "high-performance" ) )
634 vg
.quality_profile
= k_quality_profile_low
;
641 VG_STATIC
void _vg_init_window( const char *window_name
)
643 vg_info( "SDL_INIT\n" );
645 if( SDL_Init( SDL_INIT_VIDEO
) != 0 )
647 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
651 SDL_InitSubSystem( SDL_INIT_AUDIO
);
652 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER
);
654 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
655 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
656 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
657 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
658 SDL_GL_CONTEXT_PROFILE_CORE
);
660 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
661 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
663 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
664 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
665 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
666 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
667 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 0 );
670 * Get monitor information
672 vg_info( "Getting display count\n" );
673 int display_count
= 0, display_index
= 0, mode_index
= 0;
674 if( (display_count
= SDL_GetNumVideoDisplays()) < 1 )
676 vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count
);
683 /* TODO: Allow chosing the modes at startup */
684 vg_info( "Getting default display mode\n" );
685 SDL_DisplayMode vm_ideal
= { 0, 0, 0, 0, 0 };
686 if( SDL_GetDisplayMode( display_index
, mode_index
, &vm_ideal
) != 0 )
688 vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
693 vm_ideal
.w
= vg
.window_x
;
696 vm_ideal
.h
= vg
.window_y
;
699 SDL_DisplayMode vm_best
;
700 if( !SDL_GetClosestDisplayMode( display_index
, &vm_ideal
, &vm_best
) )
702 vg_error( "SDL_GetClosestDisplayMode failed: %s", SDL_GetError() );
706 vg
.refresh_rate
= vm_best
.refresh_rate
;
707 vg
.window_x
= vm_best
.w
;
708 vg
.window_y
= vm_best
.h
;
710 vg_info( "CreateWindow( %d %d @%.2fhz )\n", vg
.window_x
, vg
.window_y
,
713 /* TODO: Allow selecting closest video mode from launch opts */
714 if((vg
.window
= SDL_CreateWindow( window_name
,
715 SDL_WINDOWPOS_UNDEFINED
,
716 SDL_WINDOWPOS_UNDEFINED
,
717 vg
.window_x
, vg
.window_y
,
719 SDL_WINDOW_FULLSCREEN
|
721 SDL_WINDOW_INPUT_GRABBED
)))
723 if( SDL_SetWindowDisplayMode( vg
.window
, &vm_best
) )
725 vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
732 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
736 vg_info( "CreateContext\n" );
741 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) ))
743 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
744 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
748 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
753 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) )
755 vg_error( "Glad Failed to initialize\n" );
756 SDL_GL_DeleteContext( vg
.gl_context
);
761 const unsigned char* glver
= glGetString( GL_VERSION
);
762 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
764 vg_info( "Setting swap interval\n" );
766 if( SDL_GL_SetSwapInterval( -1 ) == -1 )
768 vg_warn( "Adaptive Vsync not supported\n" );
770 if( SDL_GL_SetSwapInterval( 1 ) == -1 )
772 vg_fatal_exit_loop( "Cannot enable Vsync! You might be overriding it"
773 " in your graphics control panel.\n" );
776 vg_success( "Using vsync\n" );
779 vg_success( "Using adaptive Vsync\n" );
781 SDL_DisplayMode dispmode
;
782 if( !SDL_GetWindowDisplayMode( vg
.window
, &dispmode
) )
784 if( dispmode
.refresh_rate
)
786 vg
.refresh_rate
= dispmode
.refresh_rate
;
787 vg_info( "Refresh rate: %d\n", dispmode
.refresh_rate
);
792 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
794 _vg_process_launch_opts_internal( argc
, argv
);
800 _vg_init_window( window_name
);
802 SDL_SetRelativeMouseMode(1);
803 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
805 /* Opengl-required systems */
809 vg
.engine_status
= k_engine_status_running
;
811 _vg_opengl_sync_init();
812 vg_loader_start( _vg_load_full
);
816 _vg_console_write_persistent();
818 SDL_AtomicLock( &vg
.sl_context
);
819 vg
.engine_status
= k_engine_status_none
;
820 SDL_AtomicUnlock( &vg
.sl_context
);
824 vg_success( "If you see this it means everything went.. \"well\".....\n" );
826 SDL_GL_DeleteContext( vg
.gl_context
);
831 * Immediately transfer away from calling thread into a safe loop, signal for
832 * others to shutdown, then free everything once the user closes the window.
834 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
835 * when calling the program from outside its normal directory.
837 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
840 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
843 * TODO: this on windows?
852 size
= backtrace( array
, 20 );
853 strings
= backtrace_symbols( array
, size
);
855 if( strings
!= NULL
)
857 vg_error( "---------------- gnu backtrace -------------\n" );
859 for( int i
=0; i
<size
; i
++ )
860 vg_info( "%s\n", strings
[i
] );
862 vg_error( "---------------- gnu backtrace -------------\n" );
869 vg_error( "Fatal error: %s\n", error
);
871 SDL_AtomicLock( &vg
.sl_context
);
872 if( vg
.engine_status
== k_engine_status_none
)
874 SDL_AtomicUnlock( &vg
.sl_context
);
876 /* TODO: Correct shutdown before other systems */
881 SDL_AtomicUnlock( &vg
.sl_context
);
883 vg_acquire_thread_sync();
885 SDL_AtomicLock( &vg
.sl_context
);
886 vg
.engine_status
= k_engine_status_crashed
;
887 vg
.str_const_engine_err
= error
;
888 SDL_AtomicUnlock( &vg
.sl_context
);
890 /* Notify other thread for curtosey */
891 if( vg_thread_purpose() == k_thread_purpose_main
)
893 SDL_AtomicLock( &vg
.sl_context
);
895 if( vg
.exec_context
!= 0 )
896 SDL_SemPost( vg
.sem_allow_exec
);
898 SDL_AtomicUnlock( &vg
.sl_context
);
905 _vg_process_events();
906 if( vg
.window_should_close
)
909 if( vg_getkey( SDLK_ESCAPE
) )
912 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
914 glDisable(GL_DEPTH_TEST
);
915 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
916 glBlendEquation(GL_FUNC_ADD
);
918 glClearColor( 0.15f
+ sinf(vg
.time_real
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
919 glClear( GL_COLOR_BUFFER_BIT
);
920 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
923 SDL_GL_SwapWindow( vg
.window
);
926 /* Can now shutdown and EXIT */
928 SDL_GL_DeleteContext( vg
.gl_context
);
936 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
938 vg_error( "Fatal error: %s\n", error
);
945 * Graphic cards will check these to force it to use the GPU
947 u32 NvOptimusEnablement
= 0x00000001;
948 int AmdPowerXpressRequestHighPerformance
= 1;
950 #endif /* VG_HEADER_H */