1 /* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
5 * [global (.data)] [temp-stack] [system-stack] [game-heap]
7 * 1. Program starts: .data memory is loaded
8 * 2. System initialization:
9 * 2a. the large heap buffer is allocated
10 * 2b. each engine system is initialized in order, using some of the
12 * 2c. game systems are also put into here
19 #include "vg_platform.h"
27 #if defined(VG_SERVER) || defined(VG_TOOLS)
32 #include "../../dep/glad/glad.h"
34 #define GLFW_INCLUDE_GLCOREARB
40 #include "../../dep/glfw/glfw3.h"
43 #include "vg_stdint.h"
45 void vg_register_exit( void( *funcptr
)(void), const char *name
);
52 //#include "vg_steamworks.h"
64 vg_semaphore sem_allow_exec
,
70 vg_mutex mux_engine_status
;
74 k_engine_status_running
,
75 k_engine_status_crashed
78 const char *str_const_engine_err
;
81 /* Window information */
104 k_engine_stage_update
,
105 k_engine_stage_update_fixed
,
106 k_engine_stage_rendering
,
115 GLFWgamepadstate gamepad
;
117 const char *gamepad_name
;
120 VG_STATIC vg
= { .time_rate
= 1.0 };
122 struct vg_thread_info
124 enum vg_thread_purpose
126 k_thread_purpose_nothing
,
127 k_thread_purpose_main
,
128 k_thread_purpose_loader
132 int gl_context_level
;
135 static VG_THREAD_LOCAL
struct vg_thread_info vg_thread_info
;
138 //#define VG_SYNC_DEBUG
141 #define VG_SYNC_LOG(STR,...) vg_info(STR,vg_thread_info.purpose,##__VA_ARGS__)
143 #define VG_SYNC_LOG(...)
146 VG_STATIC
void vg_fatal_exit_loop( const char *error
);
148 VG_STATIC
void vg_ensure_engine_running(void)
150 /* Check if the engine is no longer running */
151 vg_mutex_lock( &vg
.mux_engine_status
);
152 if( vg
.engine_status
!= k_engine_status_running
)
154 VG_SYNC_LOG( "[%d] Engine is no longer running\n");
155 vg_mutex_unlock( &vg
.mux_engine_status
);
157 /* Safe to disregard loader thread from this point on, elswhere */
158 if( vg_thread_info
.purpose
== k_thread_purpose_loader
)
160 vg_semaphore_post( &vg
.sem_loader
);
163 VG_SYNC_LOG( "[%d] about to kill\n");
166 vg_mutex_unlock( &vg
.mux_engine_status
);
170 * Sync execution so that the OpenGL context is switched onto this thread.
171 * Anything after this call will be in a valid context.
173 VG_STATIC
void vg_acquire_thread_sync(void)
175 /* We dont want to do anything if this is the main thread */
176 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
179 assert( vg_thread_info
.purpose
== k_thread_purpose_loader
);
181 vg_ensure_engine_running();
183 /* Check if thread already has the context */
184 if( vg_thread_info
.gl_context_level
)
186 vg_thread_info
.gl_context_level
++;
187 VG_SYNC_LOG( "[%d] We already have sync here\n" );
191 vg_mutex_lock( &vg
.mux_context
);
192 VG_SYNC_LOG( "[%d] Signal to sync.\n" );
194 vg_mutex_unlock( &vg
.mux_context
);
196 /* wait until told we can go */
197 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
198 vg_semaphore_wait( &vg
.sem_allow_exec
);
199 glfwMakeContextCurrent( vg
.window
);
201 /* context now valid to work in while we hold up main thread */
202 VG_SYNC_LOG( "[%d] Context acquired.\n" );
203 vg_thread_info
.gl_context_level
++;
207 * Signify that we are done with the OpenGL context in this thread.
208 * Anything after this call will be in an undefined context.
210 VG_STATIC
void vg_release_thread_sync(void)
212 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
215 assert( vg_thread_info
.purpose
== k_thread_purpose_loader
);
217 /* signal that we are done */
218 vg_thread_info
.gl_context_level
--;
220 if( !vg_thread_info
.gl_context_level
)
222 VG_SYNC_LOG( "[%d] Releasing context.\n" );
223 glfwMakeContextCurrent( NULL
);
224 vg_semaphore_post( &vg
.sem_exec_finished
);
228 VG_STATIC
void vg_run_synced_content(void)
230 assert( vg_thread_info
.purpose
== k_thread_purpose_main
);
232 vg_mutex_lock( &vg
.mux_context
);
234 if( vg
.exec_context
!= 0 )
236 VG_SYNC_LOG( "[%d] Allowing content (%d).\n", vg
.exec_context
);
238 /* allow operations to go */
239 vg_thread_info
.gl_context_level
= 0;
240 glfwMakeContextCurrent( NULL
);
241 vg_semaphore_post( &vg
.sem_allow_exec
);
243 /* wait for operations to complete */
244 VG_SYNC_LOG( "[%d] Waiting for content (%d).\n", vg
.exec_context
);
245 vg_semaphore_wait( &vg
.sem_exec_finished
);
247 /* check if we killed the engine */
248 vg_ensure_engine_running();
250 /* re-engage main thread */
251 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
253 glfwMakeContextCurrent( vg
.window
);
254 vg_thread_info
.gl_context_level
= 1;
257 vg_mutex_unlock( &vg
.mux_context
);
260 VG_STATIC
void vg_opengl_sync_init(void)
262 vg_semaphore_init( &vg
.sem_allow_exec
, 0 );
263 vg_semaphore_init( &vg
.sem_exec_finished
, 0 );
264 vg_semaphore_init( &vg
.sem_loader
, 1 );
265 vg_semaphore_init( &vg
.sem_fatal
, 1 );
266 vg_mutex_init( &vg
.mux_context
);
268 vg_set_thread_name( "[vg] Main" );
269 vg_thread_info
.purpose
= k_thread_purpose_main
;
270 vg_thread_info
.gl_context_level
= 1;
273 VG_STATIC
void vg_checkgl( const char *src_info
);
274 #define VG_STRINGIT( X ) #X
275 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
277 #include "vg_console.h"
278 #include "vg_profiler.h"
279 #include "vg_audio.h"
280 #include "vg_shader.h"
282 #include "vg_input.h"
284 #include "vg_lines.h"
285 #include "vg_loader.h"
289 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
290 vg_prof_render
= {.name
="render()"};
293 VG_STATIC
void vg_register(void) VG_GAMELOOP
;
294 VG_STATIC
void vg_start(void) VG_GAMELOOP
;
296 VG_STATIC
void vg_update(int loaded
) VG_GAMELOOP
;
297 VG_STATIC
void vg_update_fixed(int loaded
) VG_GAMELOOP
;
298 VG_STATIC
void vg_update_post(int loaded
) VG_GAMELOOP
;
300 VG_STATIC
void vg_framebuffer_resize(int w
, int h
) VG_GAMELOOP
;
301 VG_STATIC
void vg_render(void) VG_GAMELOOP
;
302 VG_STATIC
void vg_ui(void) VG_GAMELOOP
;
304 VG_STATIC
void vg_checkgl( const char *src_info
)
309 while( (err
= glGetError()) != GL_NO_ERROR
)
311 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
316 vg_fatal_exit_loop( "OpenGL Error" );
319 void vg_mouse_callback( GLFWwindow
* ptrW
, double xpos
, double ypos
)
325 void vg_scroll_callback( GLFWwindow
* ptrW
, double xoffset
, double yoffset
)
327 vg
.mouse_wheel
[0] += xoffset
;
328 vg
.mouse_wheel
[1] += yoffset
;
331 void vg_framebuffer_resize_callback( GLFWwindow
*ptrW
, int w
, int h
)
335 vg_warn( "Got a invalid framebuffer size: %dx%d... ignoring\n", w
, h
);
342 vg_framebuffer_resize(w
,h
);
345 VG_STATIC
void vg_bake_shaders(void)
347 vg_acquire_thread_sync();
350 vg_function_push( (struct vg_cmd
)
353 .function
= vg_shaders_live_recompile
357 vg_shaders_compile();
358 vg_release_thread_sync();
361 VG_STATIC
void vg_preload(void);
362 VG_STATIC
void vg_load(void);
363 VG_STATIC
void vg_load_full(void)
368 vg_loader_highwater( vg_gamepad_init
, NULL
, NULL
);
369 vg_loader_highwater( vg_lines_init
, NULL
, NULL
);
370 vg_loader_highwater( vg_audio_init
, vg_audio_free
, NULL
);
371 vg_loader_highwater( vg_profiler_init
, NULL
, NULL
);
376 vg_acquire_thread_sync();
378 vg_release_thread_sync();
381 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
384 while( vg_argp( argc
, argv
) )
386 if( (arg
= vg_opt_arg( 'w' )) )
388 vg
.window_x
= atoi( arg
);
391 if( (arg
= vg_opt_arg( 'h' )) )
393 vg
.window_y
= atoi( arg
);
396 if( (arg
= vg_long_opt_arg( "samples" )) )
398 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
406 glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR
, 3 );
407 glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR
, 3 );
408 glfwWindowHint( GLFW_OPENGL_PROFILE
, GLFW_OPENGL_CORE_PROFILE
);
409 //glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, GL_FALSE );
410 glfwWindowHint( GLFW_CONTEXT_RELEASE_BEHAVIOR
, GLFW_RELEASE_BEHAVIOR_FLUSH
);
412 glfwWindowHint( GLFW_RESIZABLE
, GLFW_FALSE
);
413 glfwWindowHint( GLFW_DOUBLEBUFFER
, GLFW_TRUE
);
415 glfwWindowHint( GLFW_SAMPLES
, vg
.samples
);
417 GLFWmonitor
*monitor_primary
= glfwGetPrimaryMonitor();
419 const GLFWvidmode
*mode
= glfwGetVideoMode( monitor_primary
);
420 glfwWindowHint( GLFW_RED_BITS
, mode
->redBits
);
421 glfwWindowHint( GLFW_GREEN_BITS
, mode
->greenBits
);
422 glfwWindowHint( GLFW_BLUE_BITS
, mode
->blueBits
);
424 glfwWindowHint( GLFW_REFRESH_RATE
, mode
->refreshRate
);
427 vg
.window_x
= mode
->width
;
430 vg
.window_y
= mode
->height
;
432 vg
.refresh_rate
= mode
->refreshRate
;
434 if( (vg
.window
= glfwCreateWindow( vg
.window_x
, vg
.window_y
,
435 window_name
, monitor_primary
, NULL
)) )
437 glfwGetFramebufferSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
438 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
442 vg_error( "GLFW Failed to initialize\n" );
446 /* We need 3.1.2 for correct VSync on windows */
448 int vmaj
, vmin
, vrev
;
449 glfwGetVersion( &vmaj
, &vmin
, &vrev
);
452 (vmaj
== 3 && vmin
< 1) ||
453 (vmaj
== 3 && vmin
== 1 && vrev
< 2 ) )
455 vg_error( "GLFW out of date (%d.%d.%d); (3.1.2 is required)\n",
462 vg_success( "GLFW Version %d.%d.%d\n", vmaj
, vmin
, vrev
);
465 glfwMakeContextCurrent( vg
.window
);
466 glfwSwapInterval( 1 );
468 glfwSetWindowSizeLimits( vg
.window
, 800, 600, GLFW_DONT_CARE
,GLFW_DONT_CARE
);
469 glfwSetFramebufferSizeCallback( vg
.window
, vg_framebuffer_resize_callback
);
471 glfwSetCursorPosCallback( vg
.window
, vg_mouse_callback
);
472 glfwSetScrollCallback( vg
.window
, vg_scroll_callback
);
474 glfwSetCharCallback( vg
.window
, console_proc_wchar
);
475 glfwSetKeyCallback( vg
.window
, console_proc_key
);
476 glfwSetInputMode( vg
.window
, GLFW_CURSOR
, GLFW_CURSOR_HIDDEN
);
478 if( !gladLoadGLLoader((GLADloadproc
)glfwGetProcAddress
) )
480 vg_error( "Glad Failed to initialize\n" );
485 const unsigned char* glver
= glGetString( GL_VERSION
);
486 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
489 * -----------------------------------------------------------------------*/
493 vg_mutex_init( &vg
.mux_engine_status
);
494 vg
.engine_status
= k_engine_status_running
;
496 vg_opengl_sync_init();
499 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
504 if( glfwWindowShouldClose( vg
.window
) )
507 v2_copy( (v2f
){ 0.0f
, 0.0f
}, vg
.mouse_wheel
);
510 vg
.time_real_last
= vg
.time_real
;
511 vg
.time_real
= glfwGetTime();
512 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
515 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
516 vg
.time
+= vg
.time_delta
;
533 * -------------------------------------------------------
535 vg_profile_begin( &vg_prof_update
);
538 vg
.engine_stage
= k_engine_stage_update
;
541 /* Fixed update loop */
542 vg
.engine_stage
= k_engine_stage_update_fixed
;
543 vg
.accumulator
+= vg
.time_delta
;
545 vg
.fixed_iterations
= 0;
546 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
548 vg_update_fixed( loaded
);
550 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
551 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
553 vg
.fixed_iterations
++;
554 if( vg
.fixed_iterations
== 8 )
562 * ---------------------------------------------
564 vg
.engine_stage
= k_engine_stage_update
;
565 vg_update_post( loaded
);
566 vg_profile_end( &vg_prof_update
);
568 vg_profile_begin( &vg_prof_render
);
573 vg
.engine_stage
= k_engine_stage_rendering
;
577 vg
.engine_stage
= k_engine_stage_ui
;
579 ui_begin( vg
.window_x
, vg
.window_y
);
580 ui_set_mouse( vg
.mouse
[0], vg
.mouse
[1],
581 vg_get_button_state( "primary" ) );
584 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
585 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
586 (ui_rect
){ 4, 4, 250, 0 }, 0
596 "refresh: %.1f (%.1fms)\n"
598 "iterations: %d (acc: %.3fms%%)\n",
599 vg
.window_x
, vg
.window_y
,
600 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
603 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
605 ui_text( (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
608 audio_debug_ui( vg
.pv
);
617 vg_profile_end( &vg_prof_render
);
619 glfwSwapBuffers( vg
.window
);
620 vg_run_synced_content();
623 vg_console_write_persistent();
625 vg_mutex_lock( &vg
.mux_engine_status
);
626 vg
.engine_status
= k_engine_status_none
;
627 vg_mutex_unlock( &vg
.mux_engine_status
);
631 vg_success( "If you see this it means everything went.. \"well\".....\n" );
636 * Immediately transfer away from calling thread into a safe loop, signal for
637 * others to shutdown, then free everything once the user closes the window.
639 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
640 * when calling the program from outside its normal directory.
642 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
645 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
648 * TODO: this on windows?
657 size
= backtrace( array
, 20 );
658 strings
= backtrace_symbols( array
, size
);
660 if( strings
!= NULL
)
662 vg_error( "---------------- gnu backtrace -------------\n" );
664 for( int i
=0; i
<size
; i
++ )
665 vg_info( "%s\n", strings
[i
] );
667 vg_error( "---------------- gnu backtrace -------------\n" );
674 vg_error( "Fatal error: %s\n", error
);
675 assert( vg_semaphore_trywait( &vg
.sem_fatal
) );
677 vg_mutex_lock( &vg
.mux_engine_status
);
679 if( vg
.engine_status
== k_engine_status_none
)
681 vg_mutex_unlock( &vg
.mux_engine_status
);
683 /* TODO: Correct shutdown before other systems */
688 vg_mutex_unlock( &vg
.mux_engine_status
);
693 * wait until loader checks in, it will die
700 * wait for main to get to us, it will never be used again
702 * undefined behaviour:
703 * fatal_exit_loop is called in both threads, preventing an appropriate
704 * reaction to the crash. This *should* be made
705 * obvious by the assertion
707 vg_acquire_thread_sync();
709 vg_mutex_lock( &vg
.mux_engine_status
);
710 vg
.engine_status
= k_engine_status_crashed
;
711 vg
.str_const_engine_err
= error
;
712 vg_mutex_unlock( &vg
.mux_engine_status
);
715 * Wait for loader to finish what it was doing, if it was running.
716 * Then we can continue in our nice error screen
718 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
720 vg_semaphore_wait( &vg
.sem_loader
);
726 if( glfwWindowShouldClose( vg
.window
) )
729 if( glfwGetKey( vg
.window
, GLFW_KEY_ESCAPE
) )
734 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
736 glDisable(GL_DEPTH_TEST
);
737 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
738 glBlendEquation(GL_FUNC_ADD
);
740 glClearColor( 0.15f
+ sinf(glfwGetTime())*0.1f
, 0.0f
, 0.0f
,1.0f
);
741 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
742 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
746 glfwSwapBuffers( vg
.window
);
749 /* Can now shutdown and EXIT */
758 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
760 vg_error( "Fatal error: %s\n", error
);
767 * Graphic cards will check these to force it to use the GPU
769 u32 NvOptimusEnablement
= 0x00000001;
770 int AmdPowerXpressRequestHighPerformance
= 1;