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( int loaded )
34 |IMP| | '- vg_update_fixed( int loaded )
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(int loaded
);
81 VG_STATIC
void vg_update_fixed(int loaded
);
82 VG_STATIC
void vg_update_post(int loaded
);
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_refcount
;
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
,
182 k_quality_profile_high
= 0,
183 k_quality_profile_low
= 1,
187 VG_STATIC vg
= { .time_rate
= 1.0 };
189 struct vg_thread_info
191 enum vg_thread_purpose
193 k_thread_purpose_nothing
,
194 k_thread_purpose_main
,
195 k_thread_purpose_loader
199 int gl_context_level
;
202 VG_STATIC
void vg_fatal_exit_loop( const char *error
);
204 VG_STATIC
void vg_ensure_engine_running(void)
206 VG_SYNC_LOG( "[%d] Checks if engine is running\n" );
208 /* Check if the engine is no longer running */
209 SDL_AtomicLock( &vg
.sl_context
);
211 if( vg
.engine_status
!= k_engine_status_running
)
213 VG_SYNC_LOG( "[%d] Engine is no longer running\n");
215 /* Safe to disregard loader thread from this point on, elswhere */
216 if( vg
.thread_id_loader
== SDL_GetThreadID(NULL
) )
218 SDL_SemPost( vg
.sem_loader
);
221 SDL_AtomicUnlock( &vg
.sl_context
);
223 VG_SYNC_LOG( "[%d] is just going to hang around and wait to die\n");
224 while(1) SDL_Delay(1000);
227 SDL_AtomicUnlock( &vg
.sl_context
);
231 * Sync execution so that the OpenGL context is switched onto this thread.
232 * Anything after this call will be in a valid context.
234 VG_STATIC
void vg_acquire_thread_sync(void)
236 VG_SYNC_LOG( "[%d] Starts acquiring sync\n" );
238 /* We dont want to do anything if this is the main thread */
239 SDL_AtomicLock( &vg
.sl_context
);
240 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
242 SDL_AtomicUnlock( &vg
.sl_context
);
245 SDL_AtomicUnlock( &vg
.sl_context
);
247 vg_ensure_engine_running();
249 /* Check if thread already has the context */
250 SDL_AtomicLock( &vg
.sl_context
);
251 if( vg
.thread_id_with_opengl_context
== SDL_GetThreadID(NULL
) )
253 vg
.context_ownership_refcount
++;
254 SDL_AtomicUnlock( &vg
.sl_context
);
256 VG_SYNC_LOG( "[%d] We already have sync here\n" );
260 VG_SYNC_LOG( "[%d] Signal to sync.\n" );
262 SDL_AtomicUnlock( &vg
.sl_context
);
264 /* wait until told we can go */
265 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
267 SDL_SemWait( vg
.sem_allow_exec
);
268 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
270 VG_SYNC_LOG( "[%d] Allow exec passed\n" );
272 /* context now valid to work in while we hold up main thread */
273 SDL_AtomicLock( &vg
.sl_context
);
274 vg
.context_ownership_refcount
++;
275 SDL_AtomicUnlock( &vg
.sl_context
);
277 VG_SYNC_LOG( "[%d] Context acquired.\n" );
281 * Signify that we are done with the OpenGL context in this thread.
282 * Anything after this call will be in an undefined context.
284 VG_STATIC
void vg_release_thread_sync(void)
286 VG_SYNC_LOG( "[%d] Releases sync\n" );
288 SDL_AtomicLock( &vg
.sl_context
);
289 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
291 SDL_AtomicUnlock( &vg
.sl_context
);
295 /* signal that we are done */
296 vg
.context_ownership_refcount
--;
297 if( !vg
.context_ownership_refcount
)
299 SDL_AtomicUnlock( &vg
.sl_context
);
301 VG_SYNC_LOG( "[%d] Releasing context.\n" );
303 SDL_GL_MakeCurrent( NULL
, NULL
);
304 SDL_SemPost( vg
.sem_exec_finished
);
307 SDL_AtomicUnlock( &vg
.sl_context
);
310 VG_STATIC
void vg_run_synced_content(void)
312 SDL_AtomicLock( &vg
.sl_context
);
314 if( vg
.exec_context
!= 0 )
316 VG_SYNC_LOG( "[%d] Allowing content (%d).\n", vg
.exec_context
);
318 SDL_AtomicUnlock( &vg
.sl_context
);
320 /* allow operations to go */
321 SDL_GL_MakeCurrent( NULL
, NULL
);
322 SDL_SemPost( vg
.sem_allow_exec
);
324 /* wait for operations to complete */
325 VG_SYNC_LOG( "[%d] Waiting for content.\n" );
326 SDL_SemWait( vg
.sem_exec_finished
);
328 /* check if we killed the engine */
329 vg_ensure_engine_running();
331 /* re-engage main thread */
332 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
333 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
336 SDL_AtomicUnlock( &vg
.sl_context
);
339 VG_STATIC
void vg_opengl_sync_init(void)
341 vg
.sem_allow_exec
= SDL_CreateSemaphore(0);
342 vg
.sem_exec_finished
= SDL_CreateSemaphore(0);
343 vg
.sem_loader
= SDL_CreateSemaphore(1);
346 VG_STATIC
void vg_checkgl( const char *src_info
);
347 #define VG_STRINGIT( X ) #X
348 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
350 #include "vg_console.h"
351 #include "vg_profiler.h"
352 #include "vg_audio.h"
353 #include "vg_shader.h"
355 #include "vg_input.h"
357 #include "vg_lines.h"
358 #include "vg_loader.h"
362 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
363 vg_prof_render
= {.name
="render()"};
365 VG_STATIC
void vg_checkgl( const char *src_info
)
370 while( (err
= glGetError()) != GL_NO_ERROR
)
372 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
377 vg_fatal_exit_loop( "OpenGL Error" );
380 VG_STATIC
void vg_bake_shaders(void)
382 vg_acquire_thread_sync();
385 vg_function_push( (struct vg_cmd
)
388 .function
= vg_shaders_live_recompile
392 vg_shaders_compile();
393 vg_release_thread_sync();
396 VG_STATIC
void vg_load_full(void)
401 vg_loader_highwater( vg_input_init
, vg_input_free
, NULL
);
402 vg_loader_highwater( vg_lines_init
, NULL
, NULL
);
403 vg_loader_highwater( vg_audio_init
, vg_audio_free
, NULL
);
404 vg_loader_highwater( vg_profiler_init
, NULL
, NULL
);
409 vg_acquire_thread_sync();
411 vg_release_thread_sync();
414 VG_STATIC
void vg_process_events(void)
417 vg
.time_real_last
= vg
.time_real
;
418 vg
.time_real
= (double)SDL_GetTicks64() / 1000.0;
419 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
421 v2_zero( vg
.mouse_wheel
);
422 v2_zero( vg
.mouse_delta
);
426 while( SDL_PollEvent( &event
) )
428 if( event
.type
== SDL_KEYDOWN
)
430 console_proc_key( event
.key
.keysym
);
432 else if( event
.type
== SDL_MOUSEWHEEL
)
434 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
435 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
437 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
438 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
439 event
.type
== SDL_CONTROLLERBUTTONUP
||
440 event
.type
== SDL_CONTROLLERDEVICEADDED
||
441 event
.type
== SDL_CONTROLLERDEVICEREMOVED
444 vg_input_controller_event( &event
);
446 else if( event
.type
== SDL_MOUSEMOTION
)
448 vg
.mouse_delta
[0] += event
.motion
.xrel
;
449 vg
.mouse_delta
[1] += event
.motion
.yrel
;
451 else if( event
.type
== SDL_WINDOWEVENT
)
453 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
)
456 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
460 vg_warn( "Got a invalid framebuffer size: "
461 "%dx%d... ignoring\n", w
, h
);
468 vg_framebuffer_resize(w
,h
);
471 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
)
473 vg
.window_should_close
= 1;
476 else if( event
.type
== SDL_TEXTINPUT
)
478 console_proc_utf8( event
.text
.text
);
482 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
483 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
489 VG_STATIC
void vg_gameloop_update( int post_start
)
491 vg_profile_begin( &vg_prof_update
);
493 vg
.engine_stage
= k_engine_stage_update
;
494 vg_update( post_start
);
496 /* Fixed update loop */
497 vg
.engine_stage
= k_engine_stage_update_fixed
;
498 vg
.accumulator
+= vg
.time_delta
;
500 vg
.fixed_iterations
= 0;
501 vg_lines
.allow_input
= 1;
502 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
504 vg_update_fixed( post_start
);
505 vg_lines
.allow_input
= 0;
507 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
508 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
510 vg
.fixed_iterations
++;
511 if( vg
.fixed_iterations
== 8 )
516 vg_lines
.allow_input
= 1;
518 vg
.engine_stage
= k_engine_stage_update
;
519 vg_update_post( post_start
);
520 vg_profile_end( &vg_prof_update
);
523 VG_STATIC
void vg_gameloop_render( int post_start
)
525 vg_profile_begin( &vg_prof_render
);
530 vg
.engine_stage
= k_engine_stage_rendering
;
534 vg
.engine_stage
= k_engine_stage_ui
;
536 ui_begin( vg
.window_x
, vg
.window_y
);
539 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
542 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
543 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
544 (ui_rect
){ 4, 4, 250, 0 }, 0
554 "refresh: %.1f (%.1fms)\n"
556 "iterations: %d (acc: %.3fms%%)\n",
557 vg
.window_x
, vg
.window_y
,
558 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
561 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
563 ui_text( (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
566 audio_debug_ui( vg
.pv
);
575 vg_profile_end( &vg_prof_render
);
578 VG_STATIC
void vg_gameloop(void)
580 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
587 if( vg
.window_should_close
)
591 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
592 vg
.time
+= vg
.time_delta
;
607 vg_gameloop_update( post_start
);
608 vg_gameloop_render( post_start
);
610 SDL_GL_SwapWindow( vg
.window
);
611 vg_run_synced_content();
615 VG_STATIC
void vg_process_launch_opts_internal( int argc
, char *argv
[] )
618 while( vg_argp( argc
, argv
) )
620 if( (arg
= vg_opt_arg( 'w' )) )
622 vg
.window_x
= atoi( arg
);
625 if( (arg
= vg_opt_arg( 'h' )) )
627 vg
.window_y
= atoi( arg
);
630 if( (arg
= vg_long_opt_arg( "samples" )) )
632 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
635 if( vg_long_opt( "use-libc-malloc" ) )
637 vg_mem
.use_libc_malloc
= atoi( arg
);
640 if( vg_long_opt( "high-performance" ) )
642 vg
.quality_profile
= k_quality_profile_low
;
649 VG_STATIC
void vg_init_window( const char *window_name
)
651 if( SDL_Init(SDL_INIT_VIDEO
|SDL_INIT_AUDIO
|SDL_INIT_GAMECONTROLLER
) != 0 )
653 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
657 SDL_GL_SetSwapInterval( 1 );
658 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
659 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
660 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
661 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
662 SDL_GL_CONTEXT_PROFILE_CORE
);
664 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 1 );
665 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
666 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
667 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
668 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
672 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS
, 1 );
673 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES
, vg
.samples
);
676 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
677 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
680 * Get monitor information
682 int display_count
= 0, display_index
= 0, mode_index
= 0;
683 if( (display_count
= SDL_GetNumVideoDisplays()) < 1 )
685 vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count
);
689 /* TODO: Allow chosing the modes at startup */
690 SDL_DisplayMode mode
= { SDL_PIXELFORMAT_UNKNOWN
, 0, 0, 0, 0 };
691 if( SDL_GetDisplayMode( display_index
, mode_index
, &mode
) != 0 )
693 vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
697 vg
.refresh_rate
= mode
.refresh_rate
;
699 /* TODO: Allow selecting closest video mode from launch opts */
700 if((vg
.window
= SDL_CreateWindow( window_name
,
701 SDL_WINDOWPOS_UNDEFINED
,
702 SDL_WINDOWPOS_UNDEFINED
,
705 SDL_WINDOW_FULLSCREEN
|
707 SDL_WINDOW_INPUT_GRABBED
)))
712 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
719 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) ))
721 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
722 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
726 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
731 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) )
733 vg_error( "Glad Failed to initialize\n" );
734 SDL_GL_DeleteContext( vg
.gl_context
);
739 const unsigned char* glver
= glGetString( GL_VERSION
);
740 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
743 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
745 vg_process_launch_opts_internal( argc
, argv
);
751 vg_init_window( window_name
);
753 SDL_SetRelativeMouseMode(1);
754 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
756 /* Opengl-required systems */
760 vg
.engine_status
= k_engine_status_running
;
762 vg_opengl_sync_init();
769 vg_console_write_persistent();
771 SDL_AtomicLock( &vg
.sl_context
);
772 vg
.engine_status
= k_engine_status_none
;
773 SDL_AtomicUnlock( &vg
.sl_context
);
777 vg_success( "If you see this it means everything went.. \"well\".....\n" );
779 SDL_GL_DeleteContext( vg
.gl_context
);
784 * Immediately transfer away from calling thread into a safe loop, signal for
785 * others to shutdown, then free everything once the user closes the window.
787 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
788 * when calling the program from outside its normal directory.
790 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
793 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
796 * TODO: this on windows?
805 size
= backtrace( array
, 20 );
806 strings
= backtrace_symbols( array
, size
);
808 if( strings
!= NULL
)
810 vg_error( "---------------- gnu backtrace -------------\n" );
812 for( int i
=0; i
<size
; i
++ )
813 vg_info( "%s\n", strings
[i
] );
815 vg_error( "---------------- gnu backtrace -------------\n" );
822 vg_error( "Fatal error: %s\n", error
);
824 SDL_AtomicLock( &vg
.sl_context
);
825 if( vg
.engine_status
== k_engine_status_none
)
827 SDL_AtomicUnlock( &vg
.sl_context
);
829 /* TODO: Correct shutdown before other systems */
834 SDL_AtomicUnlock( &vg
.sl_context
);
839 * wait until loader checks in, it will die
846 * wait for main to get to us, it will never be used again
848 * undefined behaviour:
849 * fatal_exit_loop is called in both threads, preventing an appropriate
850 * reaction to the crash. This *should* be made
851 * obvious by the assertion
853 vg_acquire_thread_sync();
855 SDL_AtomicUnlock( &vg
.sl_context
);
856 vg
.engine_status
= k_engine_status_crashed
;
857 vg
.str_const_engine_err
= error
;
860 * Wait for loader to finish what it was doing, if it was running.
861 * Then we can continue in our nice error screen
863 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
865 SDL_AtomicUnlock( &vg
.sl_context
);
866 SDL_SemWait( vg
.sem_loader
);
869 SDL_AtomicUnlock( &vg
.sl_context
);
876 if( vg
.window_should_close
)
879 if( vg_getkey( SDLK_ESCAPE
) )
882 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
884 glDisable(GL_DEPTH_TEST
);
885 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
886 glBlendEquation(GL_FUNC_ADD
);
888 glClearColor( 0.15f
+ sinf(vg
.time_real
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
889 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
890 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
893 SDL_GL_SwapWindow( vg
.window
);
896 /* Can now shutdown and EXIT */
898 SDL_GL_DeleteContext( vg
.gl_context
);
906 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
908 vg_error( "Fatal error: %s\n", error
);
915 * Graphic cards will check these to force it to use the GPU
917 u32 NvOptimusEnablement
= 0x00000001;
918 int AmdPowerXpressRequestHighPerformance
= 1;
920 #endif /* VG_HEADER_H */