11#include < string>
2+ #include < functional>
23#include < stdio.h>
4+ #ifdef __EMSCRIPTEN__
5+ #include < emscripten.h>
6+ #include < emscripten/html5.h>
7+ #include < emscripten/threading.h>
8+ #include < emscripten/websocket.h>
9+ #include < emscripten/posix_socket.h>
10+ #endif
311#include " SDL.h"
412#include " imgui.h"
513#include " imgui_stdlib.h"
@@ -23,6 +31,12 @@ crp_handle player;
2331bool playing;
2432uint64_t pts;
2533
34+ #ifdef __EMSCRIPTEN__
35+ static std::function<void ()> EmscriptenMainLoopFunc;
36+ static void EmscriptenMainLoop () { EmscriptenMainLoopFunc (); }
37+ static EMSCRIPTEN_WEBSOCKET_T bridgeSocket = 0 ;
38+ #endif
39+
2640SDL_PixelFormatEnum GetPixelFormat (Format format)
2741{
2842 switch (format)
@@ -449,6 +463,11 @@ int main(int argc, char* argv[])
449463 height = 1080 ;
450464 }
451465
466+ #ifdef __EMSCRIPTEN__
467+ bridgeSocket = emscripten_init_websocket_to_posix_socket_bridge (" ws://localhost:80" );
468+ uint16_t readyState = 0 ;
469+ #endif
470+
452471 if (SDL_Init (SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER))
453472 {
454473 printf (" Could not initialize SDL: %s\n " , SDL_GetError ());
@@ -498,11 +517,11 @@ int main(int argc, char* argv[])
498517 ImGuiIO& io = ImGui::GetIO ();
499518 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
500519 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
520+ ImGui::StyleColorsDark ();
501521 ImFontConfig font_config;
502522 font_config.SizePixels = 16 .0f ;
503523 io.Fonts ->AddFontDefault (&font_config);
504524 // io.Fonts->AddFontFromFileTTF("./unifont-15.0.06.ttf", 16.0f, nullptr, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
505- ImGui::StyleColorsDark ();
506525 ImGui_ImplSDL2_InitForSDLRenderer (window, renderer);
507526 ImGui_ImplSDLRenderer2_Init (renderer);
508527
@@ -513,8 +532,21 @@ int main(int argc, char* argv[])
513532 bool is_running = true ;
514533 bool has_frame = false ;
515534 Uint64 last_time = SDL_GetTicks64 ();
535+ #ifdef __EMSCRIPTEN__
536+ io.IniFilename = nullptr ;
537+ EmscriptenMainLoopFunc = [&]() { do
538+ #else
516539 while (is_running)
540+ #endif
517541 {
542+ #ifdef __EMSCRIPTEN__
543+ if (readyState == 0 )
544+ {
545+ emscripten_websocket_get_ready_state (bridgeSocket, &readyState);
546+ if (readyState == 0 ) continue ;
547+ }
548+ #endif
549+
518550 bool force_update = false ;
519551 SDL_Event event;
520552 while (SDL_PollEvent (&event))
@@ -585,6 +617,10 @@ int main(int argc, char* argv[])
585617 ImGui_ImplSDLRenderer2_RenderDrawData (ImGui::GetDrawData (), renderer);
586618 SDL_RenderPresent (renderer);
587619 }
620+ #ifdef __EMSCRIPTEN__
621+ while (0 ); };
622+ emscripten_set_main_loop (EmscriptenMainLoop, 0 , true );
623+ #endif
588624
589625 crp_destroy (player);
590626 ImGui_ImplSDLRenderer2_Shutdown ();
0 commit comments