1 /* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
6 #include "vg_platform.h"
9 #if defined(VG_SERVER) || defined(VG_TOOLS)
14 #include "../../dep/glad/glad.h"
16 #define GLFW_INCLUDE_GLCOREARB
22 #include "../../dep/glfw/glfw3.h"
25 #include "vg_stdint.h"
27 void vg_register_exit( void( *funcptr
)(void), const char *name
);
34 //#include "vg_steamworks.h"
39 #include "vg_gldiag.h"
50 vg_semaphore sem_allow_exec
,
56 vg_mutex mux_engine_status
;
60 k_engine_status_running
,
61 k_engine_status_crashed
64 const char *str_const_engine_err
;
67 /* Window information */
87 k_engine_stage_update
,
88 k_engine_stage_update_fixed
,
89 k_engine_stage_rendering
,
98 GLFWgamepadstate gamepad
;
100 const char *gamepad_name
;
105 struct vg_thread_info
107 enum vg_thread_purpose
109 k_thread_purpose_nothing
,
110 k_thread_purpose_main
,
111 k_thread_purpose_loader
115 int gl_context_level
;
118 static VG_THREAD_LOCAL
struct vg_thread_info vg_thread_info
;
121 //#define VG_SYNC_DEBUG
124 #define VG_SYNC_LOG(STR,...) vg_info(STR,vg_thread_info.purpose,##__VA_ARGS__)
126 #define VG_SYNC_LOG(...)
129 static void vg_fatal_exit_loop( const char *error
);
131 static void vg_ensure_engine_running(void)
133 /* Check if the engine is no longer running */
134 vg_mutex_lock( &vg
.mux_engine_status
);
135 if( vg
.engine_status
!= k_engine_status_running
)
137 VG_SYNC_LOG( "[%d] Engine is no longer running\n");
138 vg_mutex_unlock( &vg
.mux_engine_status
);
140 /* Safe to disregard loader thread from this point on, elswhere */
141 if( vg_thread_info
.purpose
== k_thread_purpose_loader
)
143 vg_semaphore_post( &vg
.sem_loader
);
146 VG_SYNC_LOG( "[%d] about to kill\n");
149 vg_mutex_unlock( &vg
.mux_engine_status
);
153 * Sync execution so that the OpenGL context is switched onto this thread.
154 * Anything after this call will be in a valid context.
156 static void vg_acquire_thread_sync(void)
158 /* We dont want to do anything if this is the main thread */
159 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
162 assert( vg_thread_info
.purpose
== k_thread_purpose_loader
);
164 vg_ensure_engine_running();
166 /* Check if thread already has the context */
167 if( vg_thread_info
.gl_context_level
)
169 vg_thread_info
.gl_context_level
++;
170 VG_SYNC_LOG( "[%d] We already have sync here\n" );
174 vg_mutex_lock( &vg
.mux_context
);
175 VG_SYNC_LOG( "[%d] Signal to sync.\n" );
177 vg_mutex_unlock( &vg
.mux_context
);
179 /* wait until told we can go */
180 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
181 vg_semaphore_wait( &vg
.sem_allow_exec
);
182 glfwMakeContextCurrent( vg
.window
);
184 /* context now valid to work in while we hold up main thread */
185 VG_SYNC_LOG( "[%d] Context acquired.\n" );
186 vg_thread_info
.gl_context_level
++;
190 * Signify that we are done with the OpenGL context in this thread.
191 * Anything after this call will be in an undefined context.
193 static void vg_release_thread_sync(void)
195 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
198 assert( vg_thread_info
.purpose
== k_thread_purpose_loader
);
200 /* signal that we are done */
201 vg_thread_info
.gl_context_level
--;
203 if( !vg_thread_info
.gl_context_level
)
205 VG_SYNC_LOG( "[%d] Releasing context.\n" );
206 glfwMakeContextCurrent( NULL
);
207 vg_semaphore_post( &vg
.sem_exec_finished
);
211 static void vg_run_synced_content(void)
213 assert( vg_thread_info
.purpose
== k_thread_purpose_main
);
215 vg_mutex_lock( &vg
.mux_context
);
217 if( vg
.exec_context
!= 0 )
219 VG_SYNC_LOG( "[%d] Allowing content (%d).\n", vg
.exec_context
);
221 /* allow operations to go */
222 vg_thread_info
.gl_context_level
= 0;
223 glfwMakeContextCurrent( NULL
);
224 vg_semaphore_post( &vg
.sem_allow_exec
);
226 /* wait for operations to complete */
227 VG_SYNC_LOG( "[%d] Waiting for content (%d).\n", vg
.exec_context
);
228 vg_semaphore_wait( &vg
.sem_exec_finished
);
230 /* check if we killed the engine */
231 vg_ensure_engine_running();
233 /* re-engage main thread */
234 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
236 glfwMakeContextCurrent( vg
.window
);
237 vg_thread_info
.gl_context_level
= 1;
240 vg_mutex_unlock( &vg
.mux_context
);
243 static void vg_opengl_sync_init(void)
245 vg_semaphore_init( &vg
.sem_allow_exec
, 0 );
246 vg_semaphore_init( &vg
.sem_exec_finished
, 0 );
247 vg_semaphore_init( &vg
.sem_loader
, 1 );
248 vg_semaphore_init( &vg
.sem_fatal
, 1 );
249 vg_mutex_init( &vg
.mux_context
);
251 vg_set_thread_name( "[vg] Main" );
252 vg_thread_info
.purpose
= k_thread_purpose_main
;
253 vg_thread_info
.gl_context_level
= 1;
256 static void vg_checkgl( const char *src_info
);
257 #define VG_STRINGIT( X ) #X
258 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
260 #include "vg_console.h"
261 #include "vg_profiler.h"
262 #include "vg_audio.h"
263 #include "vg_shader.h"
265 #include "vg_input.h"
267 #include "vg_lines.h"
268 #include "vg_debug.h"
269 #include "vg_loader.h"
273 static struct vg_profile vg_prof_update
= {.name
="update()"},
274 vg_prof_render
= {.name
="render()"};
277 static void vg_register(void) VG_GAMELOOP
;
278 static void vg_start(void) VG_GAMELOOP
;
280 static void vg_update(int loaded
) VG_GAMELOOP
;
281 static void vg_update_fixed(int loaded
) VG_GAMELOOP
;
282 static void vg_update_post(int loaded
) VG_GAMELOOP
;
284 static void vg_framebuffer_resize(int w
, int h
) VG_GAMELOOP
;
285 static void vg_render(void) VG_GAMELOOP
;
286 static void vg_ui(void) VG_GAMELOOP
;
288 static void vg_checkgl( const char *src_info
)
293 while( (err
= glGetError()) != GL_NO_ERROR
)
295 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
300 vg_fatal_exit_loop( "OpenGL Error" );
303 void vg_mouse_callback( GLFWwindow
* ptrW
, double xpos
, double ypos
)
309 void vg_scroll_callback( GLFWwindow
* ptrW
, double xoffset
, double yoffset
)
311 vg
.mouse_wheel
[0] += xoffset
;
312 vg
.mouse_wheel
[1] += yoffset
;
315 void vg_framebuffer_resize_callback( GLFWwindow
*ptrW
, int w
, int h
)
319 vg_warn( "Got a invalid framebuffer size: %dx%d... ignoring\n", w
, h
);
326 vg_framebuffer_resize(w
,h
);
329 static int vg_bake_shaders(void)
331 vg_acquire_thread_sync();
333 vg_function_push( (struct vg_cmd
)
336 .function
= vg_shaders_live_recompile
339 if( !vg_shaders_recompile() )
341 vg_shaders_free(NULL
);
342 vg_release_thread_sync();
347 vg_release_thread_sync();
348 vg_loader_highwater( NULL
, vg_shaders_free
, NULL
);
353 void vg_preload(void);
355 static void vg_load_full(void)
360 vg_loader_highwater( vg_gamepad_init
, NULL
, NULL
);
361 vg_loader_highwater( vg_lines_init
, vg_lines_free
, NULL
);
362 vg_loader_highwater( vg_audio_init
, vg_audio_free
, NULL
);
363 vg_loader_highwater( vg_profiler_init
, NULL
, NULL
);
368 vg_acquire_thread_sync();
370 vg_release_thread_sync();
373 static void vg_enter( int argc
, char *argv
[], const char *window_name
)
376 while( vg_argp( argc
, argv
) )
378 if( (arg
= vg_opt_arg( 'w' )) )
380 vg
.window_x
= atoi( arg
);
383 if( (arg
= vg_opt_arg( 'h' )) )
385 vg
.window_y
= atoi( arg
);
388 if( (arg
= vg_long_opt_arg( "samples" )) )
390 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
398 glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR
, 3 );
399 glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR
, 3 );
400 glfwWindowHint( GLFW_OPENGL_PROFILE
, GLFW_OPENGL_CORE_PROFILE
);
401 glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT
, GL_TRUE
);
402 glfwWindowHint( GLFW_CONTEXT_RELEASE_BEHAVIOR
, GLFW_RELEASE_BEHAVIOR_FLUSH
);
404 glfwWindowHint( GLFW_RESIZABLE
, GLFW_FALSE
);
405 glfwWindowHint( GLFW_DOUBLEBUFFER
, GLFW_TRUE
);
407 glfwWindowHint( GLFW_SAMPLES
, vg
.samples
);
409 GLFWmonitor
*monitor_primary
= glfwGetPrimaryMonitor();
411 const GLFWvidmode
*mode
= glfwGetVideoMode( monitor_primary
);
412 glfwWindowHint( GLFW_RED_BITS
, mode
->redBits
);
413 glfwWindowHint( GLFW_GREEN_BITS
, mode
->greenBits
);
414 glfwWindowHint( GLFW_BLUE_BITS
, mode
->blueBits
);
416 glfwWindowHint( GLFW_REFRESH_RATE
, mode
->refreshRate
);
419 vg
.window_x
= mode
->width
;
422 vg
.window_y
= mode
->height
;
424 vg
.refresh_rate
= mode
->refreshRate
;
426 if( (vg
.window
= glfwCreateWindow( vg
.window_x
, vg
.window_y
,
427 window_name
, monitor_primary
, NULL
)) )
429 glfwGetFramebufferSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
430 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
434 vg_error( "GLFW Failed to initialize\n" );
438 /* We need 3.1.2 for correct VSync on windows */
440 int vmaj
, vmin
, vrev
;
441 glfwGetVersion( &vmaj
, &vmin
, &vrev
);
444 (vmaj
== 3 && vmin
< 1) ||
445 (vmaj
== 3 && vmin
== 1 && vrev
< 2 ) )
447 vg_error( "GLFW out of date (%d.%d.%d); (3.1.2 is required)\n",
454 vg_success( "GLFW Version %d.%d.%d\n", vmaj
, vmin
, vrev
);
457 glfwMakeContextCurrent( vg
.window
);
458 glfwSwapInterval( 1 );
460 glfwSetWindowSizeLimits( vg
.window
, 800, 600, GLFW_DONT_CARE
,GLFW_DONT_CARE
);
461 glfwSetFramebufferSizeCallback( vg
.window
, vg_framebuffer_resize_callback
);
463 glfwSetCursorPosCallback( vg
.window
, vg_mouse_callback
);
464 glfwSetScrollCallback( vg
.window
, vg_scroll_callback
);
466 glfwSetCharCallback( vg
.window
, console_proc_wchar
);
467 glfwSetKeyCallback( vg
.window
, console_proc_key
);
469 glfwSetInputMode(vg_window
, GLFW_CURSOR
, GLFW_CURSOR_HIDDEN
);
472 if( !gladLoadGLLoader((GLADloadproc
)glfwGetProcAddress
) )
474 vg_error( "Glad Failed to initialize\n" );
479 const unsigned char* glver
= glGetString( GL_VERSION
);
480 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
481 vg_run_gfx_diagnostics();
483 if( !ui_default_init() )
486 if( !vg_loader_init() )
489 vg_mutex_init( &vg
.mux_engine_status
);
490 vg
.engine_status
= k_engine_status_running
;
492 vg_opengl_sync_init();
495 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
500 if( glfwWindowShouldClose( vg
.window
) )
503 v2_copy( (v2f
){ 0.0f
, 0.0f
}, vg
.mouse_wheel
);
506 vg
.time_last
= vg
.time
;
507 vg
.time
= glfwGetTime();
508 vg
.time_delta
= vg
.time
-vg
.time_last
;
512 glClearColor( 0.0f
,sinf(vg
.time
*20.0)*0.5f
+0.5f
,0.0f
,1.0f
);
513 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
528 * -------------------------------------------------------
530 vg_profile_begin( &vg_prof_update
);
533 vg
.engine_stage
= k_engine_stage_update
;
536 /* Fixed update loop */
537 vg
.engine_stage
= k_engine_stage_update_fixed
;
538 vg
.accumulator
+= vg
.time_delta
;
540 vg
.fixed_iterations
= 0;
541 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
543 vg_update_fixed( loaded
);
545 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
546 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
548 vg
.fixed_iterations
++;
549 if( vg
.fixed_iterations
== 8 )
557 * ---------------------------------------------
559 vg
.engine_stage
= k_engine_stage_update
;
560 vg_update_post( loaded
);
561 vg_profile_end( &vg_prof_update
);
563 vg_profile_begin( &vg_prof_render
);
568 vg
.engine_stage
= k_engine_stage_rendering
;
572 vg
.engine_stage
= k_engine_stage_ui
;
574 ui_begin( &ui_global_ctx
, vg
.window_x
, vg
.window_y
);
575 ui_set_mouse( &ui_global_ctx
, vg
.mouse
[0], vg
.mouse
[1],
576 vg_get_button_state( "primary" ) );
579 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
580 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
581 (ui_rect
){ 4, 4, 250, 0 }, 0
591 "refresh: %.1f (%.1fms)\n"
593 "iterations: %d (acc: %.3fms%%)\n",
594 vg
.window_x
, vg
.window_y
,
595 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
598 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
600 ui_text( &ui_global_ctx
, (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
603 audio_debug_ui( vg
.pv
);
607 ui_resolve( &ui_global_ctx
);
608 ui_draw( &ui_global_ctx
, NULL
);
612 vg_profile_end( &vg_prof_render
);
614 glfwSwapBuffers( vg
.window
);
615 vg_run_synced_content();
618 vg_console_write_persistent();
620 vg_mutex_lock( &vg
.mux_engine_status
);
621 vg
.engine_status
= k_engine_status_none
;
622 vg_mutex_unlock( &vg
.mux_engine_status
);
634 * Immediately transfer away from calling thread into a safe loop, signal for
635 * others to shutdown, then free everything once the user closes the window.
637 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, only
638 * when calling the program from outside its normal directory.
640 * A workaround is placed to skip the error loop on windows builds
642 static void vg_fatal_exit_loop( const char *error
)
644 vg_error( "Fatal error: %s\n", error
);
645 assert( vg_semaphore_trywait( &vg
.sem_fatal
) );
647 vg_mutex_lock( &vg
.mux_engine_status
);
649 if( vg
.engine_status
== k_engine_status_none
)
651 vg_mutex_unlock( &vg
.mux_engine_status
);
653 /* TODO: Correct shutdown before other systems */
658 vg_mutex_unlock( &vg
.mux_engine_status
);
663 * wait until loader checks in, it will die
670 * wait for main to get to us, it will never be used again
672 * undefined behaviour:
673 * fatal_exit_loop is called in both threads, preventing an appropriate
674 * reaction to the crash. This *should* be made
675 * obvious by the assertion
677 vg_acquire_thread_sync();
679 vg_mutex_lock( &vg
.mux_engine_status
);
680 vg
.engine_status
= k_engine_status_crashed
;
681 vg
.str_const_engine_err
= error
;
682 vg_mutex_unlock( &vg
.mux_engine_status
);
685 * Wait for loader to finish what it was doing, if it was running.
686 * Then we can continue in our nice error screen
688 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
690 vg_semaphore_wait( &vg
.sem_loader
);
697 if( glfwWindowShouldClose( vg
.window
) )
700 if( glfwGetKey( vg
.window
, GLFW_KEY_ESCAPE
) )
705 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
707 glDisable(GL_DEPTH_TEST
);
708 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
709 glBlendEquation(GL_FUNC_ADD
);
711 glClearColor( 0.15f
+ sinf(glfwGetTime())*0.1f
, 0.0f
, 0.0f
,1.0f
);
712 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
713 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
717 glfwSwapBuffers( vg
.window
);
721 /* Can now shutdown and EXIT */
732 static void vg_fatal_exit_loop( const char *error
)
734 vg_error( "Fatal error: %s\n", error
);
741 * Graphic cards will check these to force it to use the GPU
743 u32 NvOptimusEnablement
= 0x00000001;
744 int AmdPowerXpressRequestHighPerformance
= 1;