1 // https://github.com/floooh/sokol-samples/blob/master/html5/emsc.h
2 #pragma once
3 /* common emscripten platform helper functions */
4 #include <emscripten/emscripten.h>
5 #include <emscripten/html5.h>
6
7 static const char* _emsc_canvas_name = 0;
8 static bool _emsc_is_webgl2 = false;
9 static double _emsc_width = 0;
10 static double _emsc_height = 0;
11
12 enum {
13 EMSC_NONE = 0,
14 EMSC_TRY_WEBGL2 = (1<<0),
15 EMSC_ANTIALIAS = (1<<1)
16 };
17
18 /* track CSS element size changes and update the WebGL canvas size */
_emsc_size_changed(int event_type,const EmscriptenUiEvent * ui_event,void * user_data)19 static EM_BOOL _emsc_size_changed(int event_type, const EmscriptenUiEvent* ui_event, void* user_data) {
20 (void)event_type;
21 (void)ui_event;
22 (void)user_data;
23 emscripten_get_element_css_size(_emsc_canvas_name, &_emsc_width, &_emsc_height);
24 emscripten_set_canvas_element_size(_emsc_canvas_name, _emsc_width, _emsc_height);
25 return true;
26 }
27
28 /* initialize WebGL context and canvas */
emsc_init(const char * canvas_name,int flags)29 void emsc_init(const char* canvas_name, int flags) {
30 _emsc_canvas_name = canvas_name;
31 _emsc_is_webgl2 = false;
32 emscripten_get_element_css_size(canvas_name, &_emsc_width, &_emsc_height);
33 emscripten_set_canvas_element_size(canvas_name, _emsc_width, _emsc_height);
34 emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, false, _emsc_size_changed);
35 EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx;
36 EmscriptenWebGLContextAttributes attrs;
37 emscripten_webgl_init_context_attributes(&attrs);
38 attrs.antialias = flags & EMSC_ANTIALIAS;
39 if (flags & EMSC_TRY_WEBGL2) {
40 attrs.majorVersion = 2;
41 }
42 ctx = emscripten_webgl_create_context(canvas_name, &attrs);
43 if ((flags & EMSC_TRY_WEBGL2) && ctx) {
44 _emsc_is_webgl2 = true;
45 }
46 if (!ctx) {
47 /* WebGL2 not supported, fall back to WebGL */
48 attrs.majorVersion = 1;
49 ctx = emscripten_webgl_create_context(canvas_name, &attrs);
50 }
51 emscripten_webgl_make_context_current(ctx);
52 }
53
emsc_width()54 int emsc_width() {
55 return (int) _emsc_width;
56 }
57
emsc_height()58 int emsc_height() {
59 return (int) _emsc_height;
60 }
61
emsc_webgl_fallback()62 bool emsc_webgl_fallback() {
63 return !_emsc_is_webgl2;
64 }
65
66