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 */
90 k_engine_stage_update
,
91 k_engine_stage_update_fixed
,
92 k_engine_stage_rendering
,
101 GLFWgamepadstate gamepad
;
103 const char *gamepad_name
;
106 static vg
= { .time_rate
= 1.0 };
108 struct vg_thread_info
110 enum vg_thread_purpose
112 k_thread_purpose_nothing
,
113 k_thread_purpose_main
,
114 k_thread_purpose_loader
118 int gl_context_level
;
121 static VG_THREAD_LOCAL
struct vg_thread_info vg_thread_info
;
124 //#define VG_SYNC_DEBUG
127 #define VG_SYNC_LOG(STR,...) vg_info(STR,vg_thread_info.purpose,##__VA_ARGS__)
129 #define VG_SYNC_LOG(...)
132 static void vg_fatal_exit_loop( const char *error
);
134 static void vg_ensure_engine_running(void)
136 /* Check if the engine is no longer running */
137 vg_mutex_lock( &vg
.mux_engine_status
);
138 if( vg
.engine_status
!= k_engine_status_running
)
140 VG_SYNC_LOG( "[%d] Engine is no longer running\n");
141 vg_mutex_unlock( &vg
.mux_engine_status
);
143 /* Safe to disregard loader thread from this point on, elswhere */
144 if( vg_thread_info
.purpose
== k_thread_purpose_loader
)
146 vg_semaphore_post( &vg
.sem_loader
);
149 VG_SYNC_LOG( "[%d] about to kill\n");
152 vg_mutex_unlock( &vg
.mux_engine_status
);
156 * Sync execution so that the OpenGL context is switched onto this thread.
157 * Anything after this call will be in a valid context.
159 static void vg_acquire_thread_sync(void)
161 /* We dont want to do anything if this is the main thread */
162 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
165 assert( vg_thread_info
.purpose
== k_thread_purpose_loader
);
167 vg_ensure_engine_running();
169 /* Check if thread already has the context */
170 if( vg_thread_info
.gl_context_level
)
172 vg_thread_info
.gl_context_level
++;
173 VG_SYNC_LOG( "[%d] We already have sync here\n" );
177 vg_mutex_lock( &vg
.mux_context
);
178 VG_SYNC_LOG( "[%d] Signal to sync.\n" );
180 vg_mutex_unlock( &vg
.mux_context
);
182 /* wait until told we can go */
183 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
184 vg_semaphore_wait( &vg
.sem_allow_exec
);
185 glfwMakeContextCurrent( vg
.window
);
187 /* context now valid to work in while we hold up main thread */
188 VG_SYNC_LOG( "[%d] Context acquired.\n" );
189 vg_thread_info
.gl_context_level
++;
193 * Signify that we are done with the OpenGL context in this thread.
194 * Anything after this call will be in an undefined context.
196 static void vg_release_thread_sync(void)
198 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
201 assert( vg_thread_info
.purpose
== k_thread_purpose_loader
);
203 /* signal that we are done */
204 vg_thread_info
.gl_context_level
--;
206 if( !vg_thread_info
.gl_context_level
)
208 VG_SYNC_LOG( "[%d] Releasing context.\n" );
209 glfwMakeContextCurrent( NULL
);
210 vg_semaphore_post( &vg
.sem_exec_finished
);
214 static void vg_run_synced_content(void)
216 assert( vg_thread_info
.purpose
== k_thread_purpose_main
);
218 vg_mutex_lock( &vg
.mux_context
);
220 if( vg
.exec_context
!= 0 )
222 VG_SYNC_LOG( "[%d] Allowing content (%d).\n", vg
.exec_context
);
224 /* allow operations to go */
225 vg_thread_info
.gl_context_level
= 0;
226 glfwMakeContextCurrent( NULL
);
227 vg_semaphore_post( &vg
.sem_allow_exec
);
229 /* wait for operations to complete */
230 VG_SYNC_LOG( "[%d] Waiting for content (%d).\n", vg
.exec_context
);
231 vg_semaphore_wait( &vg
.sem_exec_finished
);
233 /* check if we killed the engine */
234 vg_ensure_engine_running();
236 /* re-engage main thread */
237 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
239 glfwMakeContextCurrent( vg
.window
);
240 vg_thread_info
.gl_context_level
= 1;
243 vg_mutex_unlock( &vg
.mux_context
);
246 static void vg_opengl_sync_init(void)
248 vg_semaphore_init( &vg
.sem_allow_exec
, 0 );
249 vg_semaphore_init( &vg
.sem_exec_finished
, 0 );
250 vg_semaphore_init( &vg
.sem_loader
, 1 );
251 vg_semaphore_init( &vg
.sem_fatal
, 1 );
252 vg_mutex_init( &vg
.mux_context
);
254 vg_set_thread_name( "[vg] Main" );
255 vg_thread_info
.purpose
= k_thread_purpose_main
;
256 vg_thread_info
.gl_context_level
= 1;
259 static void vg_checkgl( const char *src_info
);
260 #define VG_STRINGIT( X ) #X
261 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
263 #include "vg_console.h"
264 #include "vg_profiler.h"
265 #include "vg_audio.h"
266 #include "vg_shader.h"
268 #include "vg_input.h"
270 #include "vg_lines.h"
271 #include "vg_debug.h"
272 #include "vg_loader.h"
276 static struct vg_profile vg_prof_update
= {.name
="update()"},
277 vg_prof_render
= {.name
="render()"};
280 static void vg_register(void) VG_GAMELOOP
;
281 static void vg_start(void) VG_GAMELOOP
;
283 static void vg_update(int loaded
) VG_GAMELOOP
;
284 static void vg_update_fixed(int loaded
) VG_GAMELOOP
;
285 static void vg_update_post(int loaded
) VG_GAMELOOP
;
287 static void vg_framebuffer_resize(int w
, int h
) VG_GAMELOOP
;
288 static void vg_render(void) VG_GAMELOOP
;
289 static void vg_ui(void) VG_GAMELOOP
;
291 static void vg_checkgl( const char *src_info
)
296 while( (err
= glGetError()) != GL_NO_ERROR
)
298 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
303 vg_fatal_exit_loop( "OpenGL Error" );
306 void vg_mouse_callback( GLFWwindow
* ptrW
, double xpos
, double ypos
)
312 void vg_scroll_callback( GLFWwindow
* ptrW
, double xoffset
, double yoffset
)
314 vg
.mouse_wheel
[0] += xoffset
;
315 vg
.mouse_wheel
[1] += yoffset
;
318 void vg_framebuffer_resize_callback( GLFWwindow
*ptrW
, int w
, int h
)
322 vg_warn( "Got a invalid framebuffer size: %dx%d... ignoring\n", w
, h
);
329 vg_framebuffer_resize(w
,h
);
332 static int vg_bake_shaders(void)
334 vg_acquire_thread_sync();
336 vg_function_push( (struct vg_cmd
)
339 .function
= vg_shaders_live_recompile
342 if( !vg_shaders_recompile() )
344 vg_shaders_free(NULL
);
345 vg_release_thread_sync();
350 vg_release_thread_sync();
351 vg_loader_highwater( NULL
, vg_shaders_free
, NULL
);
356 void vg_preload(void);
358 static void vg_load_full(void)
363 vg_loader_highwater( vg_gamepad_init
, NULL
, NULL
);
364 vg_loader_highwater( vg_lines_init
, vg_lines_free
, NULL
);
365 vg_loader_highwater( vg_audio_init
, vg_audio_free
, NULL
);
366 vg_loader_highwater( vg_profiler_init
, NULL
, NULL
);
371 vg_acquire_thread_sync();
373 vg_release_thread_sync();
376 static void vg_enter( int argc
, char *argv
[], const char *window_name
)
379 while( vg_argp( argc
, argv
) )
381 if( (arg
= vg_opt_arg( 'w' )) )
383 vg
.window_x
= atoi( arg
);
386 if( (arg
= vg_opt_arg( 'h' )) )
388 vg
.window_y
= atoi( arg
);
391 if( (arg
= vg_long_opt_arg( "samples" )) )
393 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
401 glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR
, 3 );
402 glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR
, 3 );
403 glfwWindowHint( GLFW_OPENGL_PROFILE
, GLFW_OPENGL_CORE_PROFILE
);
404 glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT
, GL_TRUE
);
405 glfwWindowHint( GLFW_CONTEXT_RELEASE_BEHAVIOR
, GLFW_RELEASE_BEHAVIOR_FLUSH
);
407 glfwWindowHint( GLFW_RESIZABLE
, GLFW_FALSE
);
408 glfwWindowHint( GLFW_DOUBLEBUFFER
, GLFW_TRUE
);
410 glfwWindowHint( GLFW_SAMPLES
, vg
.samples
);
412 GLFWmonitor
*monitor_primary
= glfwGetPrimaryMonitor();
414 const GLFWvidmode
*mode
= glfwGetVideoMode( monitor_primary
);
415 glfwWindowHint( GLFW_RED_BITS
, mode
->redBits
);
416 glfwWindowHint( GLFW_GREEN_BITS
, mode
->greenBits
);
417 glfwWindowHint( GLFW_BLUE_BITS
, mode
->blueBits
);
419 glfwWindowHint( GLFW_REFRESH_RATE
, mode
->refreshRate
);
422 vg
.window_x
= mode
->width
;
425 vg
.window_y
= mode
->height
;
427 vg
.refresh_rate
= mode
->refreshRate
;
429 if( (vg
.window
= glfwCreateWindow( vg
.window_x
, vg
.window_y
,
430 window_name
, monitor_primary
, NULL
)) )
432 glfwGetFramebufferSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
433 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
437 vg_error( "GLFW Failed to initialize\n" );
441 /* We need 3.1.2 for correct VSync on windows */
443 int vmaj
, vmin
, vrev
;
444 glfwGetVersion( &vmaj
, &vmin
, &vrev
);
447 (vmaj
== 3 && vmin
< 1) ||
448 (vmaj
== 3 && vmin
== 1 && vrev
< 2 ) )
450 vg_error( "GLFW out of date (%d.%d.%d); (3.1.2 is required)\n",
457 vg_success( "GLFW Version %d.%d.%d\n", vmaj
, vmin
, vrev
);
460 glfwMakeContextCurrent( vg
.window
);
461 glfwSwapInterval( 1 );
463 glfwSetWindowSizeLimits( vg
.window
, 800, 600, GLFW_DONT_CARE
,GLFW_DONT_CARE
);
464 glfwSetFramebufferSizeCallback( vg
.window
, vg_framebuffer_resize_callback
);
466 glfwSetCursorPosCallback( vg
.window
, vg_mouse_callback
);
467 glfwSetScrollCallback( vg
.window
, vg_scroll_callback
);
469 glfwSetCharCallback( vg
.window
, console_proc_wchar
);
470 glfwSetKeyCallback( vg
.window
, console_proc_key
);
472 glfwSetInputMode(vg_window
, GLFW_CURSOR
, GLFW_CURSOR_HIDDEN
);
475 if( !gladLoadGLLoader((GLADloadproc
)glfwGetProcAddress
) )
477 vg_error( "Glad Failed to initialize\n" );
482 const unsigned char* glver
= glGetString( GL_VERSION
);
483 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
484 vg_run_gfx_diagnostics();
486 if( !ui_default_init() )
489 if( !vg_loader_init() )
492 vg_mutex_init( &vg
.mux_engine_status
);
493 vg
.engine_status
= k_engine_status_running
;
495 vg_opengl_sync_init();
498 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
503 if( glfwWindowShouldClose( vg
.window
) )
506 v2_copy( (v2f
){ 0.0f
, 0.0f
}, vg
.mouse_wheel
);
509 vg
.time_real_last
= vg
.time_real
;
510 vg
.time_real
= glfwGetTime();
511 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
514 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
515 vg
.time
+= vg
.time_delta
;
520 glClearColor( 0.0f
,sinf(vg
.time
*20.0)*0.5f
+0.5f
,0.0f
,1.0f
);
521 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
537 * -------------------------------------------------------
539 vg_profile_begin( &vg_prof_update
);
542 vg
.engine_stage
= k_engine_stage_update
;
545 /* Fixed update loop */
546 vg
.engine_stage
= k_engine_stage_update_fixed
;
547 vg
.accumulator
+= vg
.time_delta
;
549 vg
.fixed_iterations
= 0;
550 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
552 vg_update_fixed( loaded
);
554 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
555 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
557 vg
.fixed_iterations
++;
558 if( vg
.fixed_iterations
== 8 )
566 * ---------------------------------------------
568 vg
.engine_stage
= k_engine_stage_update
;
569 vg_update_post( loaded
);
570 vg_profile_end( &vg_prof_update
);
572 vg_profile_begin( &vg_prof_render
);
577 vg
.engine_stage
= k_engine_stage_rendering
;
581 vg
.engine_stage
= k_engine_stage_ui
;
583 ui_begin( &ui_global_ctx
, vg
.window_x
, vg
.window_y
);
584 ui_set_mouse( &ui_global_ctx
, vg
.mouse
[0], vg
.mouse
[1],
585 vg_get_button_state( "primary" ) );
588 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
589 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
590 (ui_rect
){ 4, 4, 250, 0 }, 0
600 "refresh: %.1f (%.1fms)\n"
602 "iterations: %d (acc: %.3fms%%)\n",
603 vg
.window_x
, vg
.window_y
,
604 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
607 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
609 ui_text( &ui_global_ctx
, (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
612 audio_debug_ui( vg
.pv
);
616 ui_resolve( &ui_global_ctx
);
617 ui_draw( &ui_global_ctx
, NULL
);
621 vg_profile_end( &vg_prof_render
);
623 glfwSwapBuffers( vg
.window
);
624 vg_run_synced_content();
627 vg_console_write_persistent();
629 vg_mutex_lock( &vg
.mux_engine_status
);
630 vg
.engine_status
= k_engine_status_none
;
631 vg_mutex_unlock( &vg
.mux_engine_status
);
643 * Immediately transfer away from calling thread into a safe loop, signal for
644 * others to shutdown, then free everything once the user closes the window.
646 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, only
647 * when calling the program from outside its normal directory.
649 * A workaround is placed to skip the error loop on windows builds
651 static void vg_fatal_exit_loop( const char *error
)
653 vg_error( "Fatal error: %s\n", error
);
654 assert( vg_semaphore_trywait( &vg
.sem_fatal
) );
656 vg_mutex_lock( &vg
.mux_engine_status
);
658 if( vg
.engine_status
== k_engine_status_none
)
660 vg_mutex_unlock( &vg
.mux_engine_status
);
662 /* TODO: Correct shutdown before other systems */
667 vg_mutex_unlock( &vg
.mux_engine_status
);
672 * wait until loader checks in, it will die
679 * wait for main to get to us, it will never be used again
681 * undefined behaviour:
682 * fatal_exit_loop is called in both threads, preventing an appropriate
683 * reaction to the crash. This *should* be made
684 * obvious by the assertion
686 vg_acquire_thread_sync();
688 vg_mutex_lock( &vg
.mux_engine_status
);
689 vg
.engine_status
= k_engine_status_crashed
;
690 vg
.str_const_engine_err
= error
;
691 vg_mutex_unlock( &vg
.mux_engine_status
);
694 * Wait for loader to finish what it was doing, if it was running.
695 * Then we can continue in our nice error screen
697 if( vg_thread_info
.purpose
== k_thread_purpose_main
)
699 vg_semaphore_wait( &vg
.sem_loader
);
706 if( glfwWindowShouldClose( vg
.window
) )
709 if( glfwGetKey( vg
.window
, GLFW_KEY_ESCAPE
) )
714 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
716 glDisable(GL_DEPTH_TEST
);
717 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
718 glBlendEquation(GL_FUNC_ADD
);
720 glClearColor( 0.15f
+ sinf(glfwGetTime())*0.1f
, 0.0f
, 0.0f
,1.0f
);
721 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
722 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
726 glfwSwapBuffers( vg
.window
);
730 /* Can now shutdown and EXIT */
741 static void vg_fatal_exit_loop( const char *error
)
743 vg_error( "Fatal error: %s\n", error
);
750 * Graphic cards will check these to force it to use the GPU
752 u32 NvOptimusEnablement
= 0x00000001;
753 int AmdPowerXpressRequestHighPerformance
= 1;