RmlUi_Backend_SDL_VK.cpp 10 KB

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