RmlUi_Backend_SDL_VK.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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_VK.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. #if SDL_MAJOR_VERSION == 2 && !(SDL_VIDEO_VULKAN)
  36. #error "Only the Vulkan SDL backend is supported."
  37. #endif
  38. #if SDL_MAJOR_VERSION >= 3
  39. #include <SDL3/SDL_vulkan.h>
  40. #else
  41. #include <SDL2/SDL_vulkan.h>
  42. #endif
  43. /**
  44. Global data used by this backend.
  45. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  46. */
  47. struct BackendData {
  48. SystemInterface_SDL system_interface;
  49. RenderInterface_VK render_interface;
  50. SDL_Window* window = nullptr;
  51. bool running = true;
  52. };
  53. static Rml::UniquePtr<BackendData> data;
  54. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  55. {
  56. RMLUI_ASSERT(!data);
  57. #if SDL_MAJOR_VERSION >= 3
  58. if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS))
  59. return false;
  60. #else
  61. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  62. return false;
  63. #endif
  64. // Submit click events when focusing the window.
  65. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  66. #if SDL_MAJOR_VERSION >= 3
  67. const float window_size_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
  68. SDL_PropertiesID props = SDL_CreateProperties();
  69. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  70. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  71. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  72. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, int(width * window_size_scale));
  73. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, int(height * window_size_scale));
  74. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_VULKAN_BOOLEAN, true);
  75. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  76. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
  77. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  78. SDL_DestroyProperties(props);
  79. auto CreateSurface = [](VkInstance instance, VkSurfaceKHR* out_surface) {
  80. return SDL_Vulkan_CreateSurface(data->window, instance, nullptr, out_surface);
  81. };
  82. #else
  83. const Uint32 window_flags = (SDL_WINDOW_VULKAN | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  84. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  85. // SDL2 implicitly activates text input on window creation. Turn it off for now, it will be activated again e.g. when focusing a text input field.
  86. SDL_StopTextInput();
  87. auto CreateSurface = [](VkInstance instance, VkSurfaceKHR* out_surface) {
  88. return (bool)SDL_Vulkan_CreateSurface(data->window, instance, out_surface);
  89. };
  90. #endif
  91. if (!window)
  92. {
  93. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  94. return false;
  95. }
  96. data = Rml::MakeUnique<BackendData>();
  97. data->window = window;
  98. Rml::Vector<const char*> extensions;
  99. {
  100. unsigned int count;
  101. #if SDL_MAJOR_VERSION >= 3
  102. const char* const* extensions_list = SDL_Vulkan_GetInstanceExtensions(&count);
  103. if (!extensions_list)
  104. {
  105. data.reset();
  106. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get required vulkan extensions");
  107. return false;
  108. }
  109. extensions.resize(count);
  110. for (unsigned int i = 0; i < count; i++)
  111. extensions[i] = extensions_list[i];
  112. #else
  113. if (!SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr))
  114. {
  115. data.reset();
  116. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get required vulkan extensions");
  117. return false;
  118. }
  119. extensions.resize(count);
  120. if (!SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data()))
  121. {
  122. data.reset();
  123. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get required vulkan extensions");
  124. return false;
  125. }
  126. #endif
  127. }
  128. if (!data->render_interface.Initialize(std::move(extensions), CreateSurface))
  129. {
  130. data.reset();
  131. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize Vulkan render interface");
  132. return false;
  133. }
  134. data->system_interface.SetWindow(window);
  135. data->render_interface.SetViewport(width, height);
  136. return true;
  137. }
  138. void Backend::Shutdown()
  139. {
  140. RMLUI_ASSERT(data);
  141. data->render_interface.Shutdown();
  142. SDL_DestroyWindow(data->window);
  143. data.reset();
  144. SDL_Quit();
  145. }
  146. Rml::SystemInterface* Backend::GetSystemInterface()
  147. {
  148. RMLUI_ASSERT(data);
  149. return &data->system_interface;
  150. }
  151. Rml::RenderInterface* Backend::GetRenderInterface()
  152. {
  153. RMLUI_ASSERT(data);
  154. return &data->render_interface;
  155. }
  156. static bool WaitForValidSwapchain()
  157. {
  158. #if SDL_MAJOR_VERSION >= 3
  159. constexpr auto event_quit = SDL_EVENT_QUIT;
  160. #else
  161. constexpr auto event_quit = SDL_QUIT;
  162. #endif
  163. bool result = true;
  164. // In some situations the swapchain may become invalid, such as when the window is minimized. In this state the renderer cannot accept any render
  165. // calls. Since we don't have full control over the main loop here we may risk calls to Context::Render if we were to return. Instead, we keep the
  166. // application inside this loop until we are able to recreate the swapchain and render again.
  167. while (!data->render_interface.IsSwapchainValid())
  168. {
  169. SDL_Event ev;
  170. while (SDL_PollEvent(&ev))
  171. {
  172. if (ev.type == event_quit)
  173. {
  174. // Restore the window so that we can recreate the swapchain, and then properly release all resource and shutdown cleanly.
  175. SDL_RestoreWindow(data->window);
  176. result = false;
  177. }
  178. }
  179. SDL_Delay(10);
  180. data->render_interface.RecreateSwapchain();
  181. }
  182. return result;
  183. }
  184. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  185. {
  186. RMLUI_ASSERT(data && context);
  187. #if SDL_MAJOR_VERSION >= 3
  188. #define RMLSDL_WINDOW_EVENTS_BEGIN
  189. #define RMLSDL_WINDOW_EVENTS_END
  190. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  191. auto GetDisplayScale = []() { return SDL_GetWindowDisplayScale(data->window); };
  192. constexpr auto event_quit = SDL_EVENT_QUIT;
  193. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  194. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  195. bool has_event = false;
  196. #else
  197. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  198. case SDL_WINDOWEVENT: \
  199. { \
  200. switch (ev.window.event) \
  201. {
  202. #define RMLSDL_WINDOW_EVENTS_END \
  203. } \
  204. } \
  205. break;
  206. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  207. auto GetDisplayScale = []() { return 1.f; };
  208. constexpr auto event_quit = SDL_QUIT;
  209. constexpr auto event_key_down = SDL_KEYDOWN;
  210. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  211. int has_event = 0;
  212. #endif
  213. bool result = data->running;
  214. data->running = true;
  215. SDL_Event ev;
  216. if (power_save)
  217. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  218. else
  219. has_event = SDL_PollEvent(&ev);
  220. while (has_event)
  221. {
  222. bool propagate_event = true;
  223. switch (ev.type)
  224. {
  225. case event_quit:
  226. {
  227. propagate_event = false;
  228. result = false;
  229. }
  230. break;
  231. case event_key_down:
  232. {
  233. propagate_event = false;
  234. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  235. const int key_modifier = RmlSDL::GetKeyModifierState();
  236. const float native_dp_ratio = GetDisplayScale();
  237. // See if we have any global shortcuts that take priority over the context.
  238. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  239. break;
  240. // Otherwise, hand the event over to the context by calling the input handler as normal.
  241. if (!RmlSDL::InputEventHandler(context, data->window, ev))
  242. break;
  243. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  244. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  245. break;
  246. }
  247. break;
  248. RMLSDL_WINDOW_EVENTS_BEGIN
  249. case event_window_size_changed:
  250. {
  251. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  252. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  253. }
  254. break;
  255. RMLSDL_WINDOW_EVENTS_END
  256. default: break;
  257. }
  258. if (propagate_event)
  259. RmlSDL::InputEventHandler(context, data->window, ev);
  260. has_event = SDL_PollEvent(&ev);
  261. }
  262. if (!WaitForValidSwapchain())
  263. result = false;
  264. return result;
  265. }
  266. void Backend::RequestExit()
  267. {
  268. RMLUI_ASSERT(data);
  269. data->running = false;
  270. }
  271. void Backend::BeginFrame()
  272. {
  273. RMLUI_ASSERT(data);
  274. data->render_interface.BeginFrame();
  275. }
  276. void Backend::PresentFrame()
  277. {
  278. RMLUI_ASSERT(data);
  279. data->render_interface.EndFrame();
  280. }