RmlUi_Backend_GLFW_VK.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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_Renderer_VK.h"
  30. // This space is intentional to prevent autoformat from reordering RmlUi_Renderer_VK behind RmlUi_Platform_GLFW
  31. #include "RmlUi_Platform_GLFW.h"
  32. #include <RmlUi/Config/Config.h>
  33. #include <RmlUi/Core/Context.h>
  34. #include <RmlUi/Core/Core.h>
  35. #include <RmlUi/Core/FileInterface.h>
  36. #include <RmlUi/Core/Log.h>
  37. #include <GLFW/glfw3.h>
  38. #include <stdint.h>
  39. #include <thread>
  40. static void SetupCallbacks(GLFWwindow* window);
  41. static void LogErrorFromGLFW(int error, const char* description)
  42. {
  43. Rml::Log::Message(Rml::Log::LT_ERROR, "GLFW error (0x%x): %s", error, description);
  44. }
  45. /**
  46. Global data used by this backend.
  47. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  48. */
  49. struct BackendData {
  50. SystemInterface_GLFW system_interface;
  51. RenderInterface_VK render_interface;
  52. GLFWwindow* window = nullptr;
  53. Rml::Context* context = nullptr;
  54. KeyDownCallback key_down_callback = nullptr;
  55. int glfw_active_modifiers = 0;
  56. bool running = true;
  57. bool context_dimensions_dirty = true;
  58. };
  59. static Rml::UniquePtr<BackendData> data;
  60. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  61. {
  62. RMLUI_ASSERT(!data);
  63. glfwSetErrorCallback(LogErrorFromGLFW);
  64. if (!glfwInit())
  65. {
  66. glfwTerminate();
  67. return false;
  68. }
  69. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  70. glfwWindowHint(GLFW_RESIZABLE, allow_resize ? GLFW_TRUE : GLFW_FALSE);
  71. glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
  72. GLFWwindow* window = glfwCreateWindow(width, height, window_name, nullptr, nullptr);
  73. if (!window)
  74. {
  75. Rml::Log::Message(Rml::Log::LT_ERROR, "GLFW failed to create window");
  76. return false;
  77. }
  78. data = Rml::MakeUnique<BackendData>();
  79. data->window = window;
  80. uint32_t count;
  81. const char** extensions = glfwGetRequiredInstanceExtensions(&count);
  82. RMLUI_VK_ASSERTMSG(extensions != nullptr, "Failed to query GLFW Vulkan extensions");
  83. if (!data->render_interface.Initialize(Rml::Vector<const char*>(extensions, extensions + count),
  84. [](VkInstance instance, VkSurfaceKHR* out_surface) {
  85. return glfwCreateWindowSurface(instance, data->window, nullptr, out_surface) == VkResult::VK_SUCCESS;
  86. ;
  87. }))
  88. {
  89. data.reset();
  90. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize Vulkan render interface");
  91. return false;
  92. }
  93. data->system_interface.SetWindow(window);
  94. data->render_interface.SetViewport(width, height);
  95. // Receive num lock and caps lock modifiers for proper handling of numpad inputs in text fields.
  96. glfwSetInputMode(window, GLFW_LOCK_KEY_MODS, GLFW_TRUE);
  97. SetupCallbacks(window);
  98. return true;
  99. }
  100. void Backend::Shutdown()
  101. {
  102. RMLUI_ASSERT(data);
  103. data->render_interface.Shutdown();
  104. glfwDestroyWindow(data->window);
  105. data.reset();
  106. glfwTerminate();
  107. }
  108. Rml::SystemInterface* Backend::GetSystemInterface()
  109. {
  110. RMLUI_ASSERT(data);
  111. return &data->system_interface;
  112. }
  113. Rml::RenderInterface* Backend::GetRenderInterface()
  114. {
  115. RMLUI_ASSERT(data);
  116. return &data->render_interface;
  117. }
  118. static bool WaitForValidSwapchain()
  119. {
  120. bool result = true;
  121. // In some situations the swapchain may become invalid, such as when the window is minimized. In this state the renderer cannot accept any render
  122. // 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
  123. // application inside this loop until we are able to recreate the swapchain and render again.
  124. while (!data->render_interface.IsSwapchainValid())
  125. {
  126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  127. if (glfwWindowShouldClose(data->window))
  128. {
  129. glfwRestoreWindow(data->window);
  130. result = false;
  131. }
  132. glfwPollEvents();
  133. data->render_interface.RecreateSwapchain();
  134. }
  135. return result;
  136. }
  137. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  138. {
  139. RMLUI_ASSERT(data && context);
  140. bool result = data->running;
  141. if (data->context_dimensions_dirty)
  142. {
  143. data->context_dimensions_dirty = false;
  144. Rml::Vector2i window_size;
  145. float dp_ratio = 1.f;
  146. glfwGetFramebufferSize(data->window, &window_size.x, &window_size.y);
  147. glfwGetWindowContentScale(data->window, &dp_ratio, nullptr);
  148. context->SetDimensions(window_size);
  149. context->SetDensityIndependentPixelRatio(dp_ratio);
  150. }
  151. data->context = context;
  152. data->key_down_callback = key_down_callback;
  153. if (power_save)
  154. glfwWaitEventsTimeout(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0));
  155. else
  156. glfwPollEvents();
  157. if (!WaitForValidSwapchain())
  158. result = false;
  159. data->context = nullptr;
  160. data->key_down_callback = nullptr;
  161. result = !glfwWindowShouldClose(data->window);
  162. glfwSetWindowShouldClose(data->window, GLFW_FALSE);
  163. return result;
  164. }
  165. void Backend::RequestExit()
  166. {
  167. RMLUI_ASSERT(data);
  168. data->running = false;
  169. glfwSetWindowShouldClose(data->window, GLFW_TRUE);
  170. }
  171. void Backend::BeginFrame()
  172. {
  173. RMLUI_ASSERT(data);
  174. data->render_interface.BeginFrame();
  175. }
  176. void Backend::PresentFrame()
  177. {
  178. RMLUI_ASSERT(data);
  179. data->render_interface.EndFrame();
  180. }
  181. static void SetupCallbacks(GLFWwindow* window)
  182. {
  183. RMLUI_ASSERT(data);
  184. // Key input
  185. glfwSetKeyCallback(window, [](GLFWwindow* /*window*/, int glfw_key, int /*scancode*/, int glfw_action, int glfw_mods) {
  186. if (!data->context)
  187. return;
  188. // Store the active modifiers for later because GLFW doesn't provide them in the callbacks to the mouse input events.
  189. data->glfw_active_modifiers = glfw_mods;
  190. // Override the default key event callback to add global shortcuts for the samples.
  191. Rml::Context* context = data->context;
  192. KeyDownCallback key_down_callback = data->key_down_callback;
  193. switch (glfw_action)
  194. {
  195. case GLFW_PRESS:
  196. case GLFW_REPEAT:
  197. {
  198. const Rml::Input::KeyIdentifier key = RmlGLFW::ConvertKey(glfw_key);
  199. const int key_modifier = RmlGLFW::ConvertKeyModifiers(glfw_mods);
  200. float dp_ratio = 1.f;
  201. glfwGetWindowContentScale(data->window, &dp_ratio, nullptr);
  202. // See if we have any global shortcuts that take priority over the context.
  203. if (key_down_callback && !key_down_callback(context, key, key_modifier, dp_ratio, true))
  204. break;
  205. // Otherwise, hand the event over to the context by calling the input handler as normal.
  206. if (!RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods))
  207. break;
  208. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  209. if (key_down_callback && !key_down_callback(context, key, key_modifier, dp_ratio, false))
  210. break;
  211. }
  212. break;
  213. case GLFW_RELEASE: RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods); break;
  214. }
  215. });
  216. glfwSetCharCallback(window, [](GLFWwindow* /*window*/, unsigned int codepoint) { RmlGLFW::ProcessCharCallback(data->context, codepoint); });
  217. glfwSetCursorEnterCallback(window, [](GLFWwindow* /*window*/, int entered) { RmlGLFW::ProcessCursorEnterCallback(data->context, entered); });
  218. // Mouse input
  219. glfwSetCursorPosCallback(window, [](GLFWwindow* window, double xpos, double ypos) {
  220. RmlGLFW::ProcessCursorPosCallback(data->context, window, xpos, ypos, data->glfw_active_modifiers);
  221. });
  222. glfwSetMouseButtonCallback(window, [](GLFWwindow* /*window*/, int button, int action, int mods) {
  223. data->glfw_active_modifiers = mods;
  224. RmlGLFW::ProcessMouseButtonCallback(data->context, button, action, mods);
  225. });
  226. glfwSetScrollCallback(window, [](GLFWwindow* /*window*/, double /*xoffset*/, double yoffset) {
  227. RmlGLFW::ProcessScrollCallback(data->context, yoffset, data->glfw_active_modifiers);
  228. });
  229. // Window events
  230. glfwSetFramebufferSizeCallback(window, [](GLFWwindow* /*window*/, int width, int height) {
  231. data->render_interface.SetViewport(width, height);
  232. RmlGLFW::ProcessFramebufferSizeCallback(data->context, width, height);
  233. });
  234. glfwSetWindowContentScaleCallback(window,
  235. [](GLFWwindow* /*window*/, float xscale, float /*yscale*/) { RmlGLFW::ProcessContentScaleCallback(data->context, xscale); });
  236. }