RmlUi_Backend_SDL_GL3.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "RmlUi_Backend.h"
  29. #include "RmlUi_Platform_SDL.h"
  30. #include "RmlUi_Renderer_GL3.h"
  31. #include <RmlUi/Core/Context.h>
  32. #include <RmlUi/Core/Core.h>
  33. #include <RmlUi/Core/FileInterface.h>
  34. #include <RmlUi/Core/Log.h>
  35. #include <RmlUi/Core/Profiling.h>
  36. #include <SDL.h>
  37. #include <SDL_image.h>
  38. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  39. #include <emscripten.h>
  40. #else
  41. #if !(SDL_VIDEO_RENDER_OGL)
  42. #error "Only the OpenGL SDL backend is supported."
  43. #endif
  44. #endif
  45. /**
  46. Custom render interface example for the SDL/GL3 backend.
  47. Overloads the OpenGL3 render interface to load textures through SDL_image's built-in texture loading functionality.
  48. */
  49. class RenderInterface_GL3_SDL : public RenderInterface_GL3 {
  50. public:
  51. RenderInterface_GL3_SDL() {}
  52. Rml::TextureHandle LoadTexture(Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  53. {
  54. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  55. Rml::FileHandle file_handle = file_interface->Open(source);
  56. if (!file_handle)
  57. return {};
  58. file_interface->Seek(file_handle, 0, SEEK_END);
  59. const size_t buffer_size = file_interface->Tell(file_handle);
  60. file_interface->Seek(file_handle, 0, SEEK_SET);
  61. using Rml::byte;
  62. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  63. file_interface->Read(buffer.get(), buffer_size, file_handle);
  64. file_interface->Close(file_handle);
  65. const size_t i_ext = source.rfind('.');
  66. Rml::String extension = (i_ext == Rml::String::npos ? Rml::String() : source.substr(i_ext + 1));
  67. SDL_Surface* surface = IMG_LoadTyped_RW(SDL_RWFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str());
  68. if (!surface)
  69. return {};
  70. texture_dimensions = {surface->w, surface->h};
  71. if (surface->format->format != SDL_PIXELFORMAT_RGBA32)
  72. {
  73. // Ensure correct format for premultiplied alpha conversion and GenerateTexture below.
  74. SDL_Surface* converted_surface = SDL_ConvertSurfaceFormat(surface, SDL_PixelFormatEnum::SDL_PIXELFORMAT_RGBA32, 0);
  75. SDL_FreeSurface(surface);
  76. if (!converted_surface)
  77. return {};
  78. surface = converted_surface;
  79. }
  80. // Convert colors to premultiplied alpha, which is necessary for correct alpha compositing.
  81. const size_t pixels_byte_size = surface->w * surface->h * 4;
  82. byte* pixels = static_cast<byte*>(surface->pixels);
  83. for (size_t i = 0; i < pixels_byte_size; i += 4)
  84. {
  85. const byte alpha = pixels[i + 3];
  86. for (size_t j = 0; j < 3; ++j)
  87. pixels[i + j] = byte(int(pixels[i + j]) * int(alpha) / 255);
  88. }
  89. Rml::TextureHandle texture_handle = RenderInterface_GL3::GenerateTexture({pixels, pixels_byte_size}, texture_dimensions);
  90. SDL_FreeSurface(surface);
  91. return texture_handle;
  92. }
  93. };
  94. /**
  95. Global data used by this backend.
  96. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  97. */
  98. struct BackendData {
  99. SystemInterface_SDL system_interface;
  100. RenderInterface_GL3_SDL render_interface;
  101. SDL_Window* window = nullptr;
  102. SDL_GLContext glcontext = nullptr;
  103. bool running = true;
  104. };
  105. static Rml::UniquePtr<BackendData> data;
  106. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  107. {
  108. RMLUI_ASSERT(!data);
  109. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  110. return false;
  111. // Submit click events when focusing the window.
  112. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  113. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  114. // GLES 3.0 (WebGL 2.0)
  115. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  116. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
  117. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  118. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  119. #else
  120. // GL 3.3 Core
  121. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  122. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  123. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  124. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  125. #endif
  126. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  127. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  128. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  129. if (!window)
  130. {
  131. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  132. return false;
  133. }
  134. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  135. SDL_GL_MakeCurrent(window, glcontext);
  136. SDL_GL_SetSwapInterval(1);
  137. if (!RmlGL3::Initialize())
  138. {
  139. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL renderer");
  140. return false;
  141. }
  142. data = Rml::MakeUnique<BackendData>();
  143. if (!data->render_interface)
  144. {
  145. data.reset();
  146. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL3 render interface");
  147. return false;
  148. }
  149. data->window = window;
  150. data->glcontext = glcontext;
  151. data->system_interface.SetWindow(window);
  152. data->render_interface.SetViewport(width, height);
  153. return true;
  154. }
  155. void Backend::Shutdown()
  156. {
  157. RMLUI_ASSERT(data);
  158. SDL_GL_DeleteContext(data->glcontext);
  159. SDL_DestroyWindow(data->window);
  160. data.reset();
  161. SDL_Quit();
  162. }
  163. Rml::SystemInterface* Backend::GetSystemInterface()
  164. {
  165. RMLUI_ASSERT(data);
  166. return &data->system_interface;
  167. }
  168. Rml::RenderInterface* Backend::GetRenderInterface()
  169. {
  170. RMLUI_ASSERT(data);
  171. return &data->render_interface;
  172. }
  173. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  174. {
  175. RMLUI_ASSERT(data && context);
  176. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  177. // Ideally we would hand over control of the main loop to emscripten:
  178. //
  179. // // Hand over control of the main loop to the WebAssembly runtime.
  180. // emscripten_set_main_loop_arg(EventLoopIteration, (void*)user_data_handle, 0, true);
  181. //
  182. // The above is the recommended approach. However, as we don't control the main loop here we have to make due with another approach. Instead, use
  183. // Asyncify to yield by sleeping.
  184. // Important: Must be linked with option -sASYNCIFY
  185. emscripten_sleep(1);
  186. #endif
  187. bool result = data->running;
  188. data->running = true;
  189. SDL_Event ev;
  190. int has_event = 0;
  191. if (power_save)
  192. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  193. else
  194. has_event = SDL_PollEvent(&ev);
  195. while (has_event)
  196. {
  197. switch (ev.type)
  198. {
  199. case SDL_QUIT:
  200. {
  201. result = false;
  202. }
  203. break;
  204. case SDL_KEYDOWN:
  205. {
  206. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(ev.key.keysym.sym);
  207. const int key_modifier = RmlSDL::GetKeyModifierState();
  208. const float native_dp_ratio = 1.f;
  209. // See if we have any global shortcuts that take priority over the context.
  210. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  211. break;
  212. // Otherwise, hand the event over to the context by calling the input handler as normal.
  213. if (!RmlSDL::InputEventHandler(context, ev))
  214. break;
  215. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  216. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  217. break;
  218. }
  219. break;
  220. case SDL_WINDOWEVENT:
  221. {
  222. switch (ev.window.event)
  223. {
  224. case SDL_WINDOWEVENT_SIZE_CHANGED:
  225. {
  226. Rml::Vector2i dimensions(ev.window.data1, ev.window.data2);
  227. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  228. }
  229. break;
  230. }
  231. RmlSDL::InputEventHandler(context, ev);
  232. }
  233. break;
  234. default:
  235. {
  236. RmlSDL::InputEventHandler(context, ev);
  237. }
  238. break;
  239. }
  240. has_event = SDL_PollEvent(&ev);
  241. }
  242. return result;
  243. }
  244. void Backend::RequestExit()
  245. {
  246. RMLUI_ASSERT(data);
  247. data->running = false;
  248. }
  249. void Backend::BeginFrame()
  250. {
  251. RMLUI_ASSERT(data);
  252. data->render_interface.Clear();
  253. data->render_interface.BeginFrame();
  254. }
  255. void Backend::PresentFrame()
  256. {
  257. RMLUI_ASSERT(data);
  258. data->render_interface.EndFrame();
  259. SDL_GL_SwapWindow(data->window);
  260. // Optional, used to mark frames during performance profiling.
  261. RMLUI_FrameMark;
  262. }