RmlUi_Backend_SFML_GL2.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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_SFML.h"
  30. #include "RmlUi_Renderer_GL2.h"
  31. #include <RmlUi/Core/Context.h>
  32. #include <RmlUi/Core/Core.h>
  33. #include <RmlUi/Core/FileInterface.h>
  34. #include <RmlUi/Core/Profiling.h>
  35. #include <RmlUi/Debugger/Debugger.h>
  36. #include <SFML/Graphics.hpp>
  37. #include <SFML/Window.hpp>
  38. /**
  39. Custom render interface example for the SFML/GL2 backend.
  40. Overloads the OpenGL2 render interface to load textures through SFML's built-in texture loading functionality.
  41. */
  42. class RenderInterface_GL2_SFML : public RenderInterface_GL2 {
  43. public:
  44. // -- Inherited from Rml::RenderInterface --
  45. void RenderGeometry(Rml::CompiledGeometryHandle handle, Rml::Vector2f translation, Rml::TextureHandle texture) override
  46. {
  47. if (texture)
  48. {
  49. sf::Texture::bind((sf::Texture*)texture);
  50. texture = RenderInterface_GL2::TextureEnableWithoutBinding;
  51. }
  52. RenderInterface_GL2::RenderGeometry(handle, translation, texture);
  53. }
  54. Rml::TextureHandle LoadTexture(Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  55. {
  56. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  57. Rml::FileHandle file_handle = file_interface->Open(source);
  58. if (!file_handle)
  59. return false;
  60. file_interface->Seek(file_handle, 0, SEEK_END);
  61. size_t buffer_size = file_interface->Tell(file_handle);
  62. file_interface->Seek(file_handle, 0, SEEK_SET);
  63. using Rml::byte;
  64. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  65. file_interface->Read(buffer.get(), buffer_size, file_handle);
  66. file_interface->Close(file_handle);
  67. sf::Image image;
  68. if (!image.loadFromMemory(buffer.get(), buffer_size))
  69. return false;
  70. // Convert colors to premultiplied alpha, which is necessary for correct alpha compositing.
  71. for (unsigned int x = 0; x < image.getSize().x; x++)
  72. {
  73. for (unsigned int y = 0; y < image.getSize().y; y++)
  74. {
  75. sf::Color color = image.getPixel(x, y);
  76. color.r = (sf::Uint8)((color.r * color.a) / 255);
  77. color.g = (sf::Uint8)((color.g * color.a) / 255);
  78. color.b = (sf::Uint8)((color.b * color.a) / 255);
  79. image.setPixel(x, y, color);
  80. }
  81. }
  82. sf::Texture* texture = new sf::Texture();
  83. texture->setSmooth(true);
  84. if (!texture->loadFromImage(image))
  85. {
  86. delete texture;
  87. return false;
  88. }
  89. texture_dimensions = Rml::Vector2i(texture->getSize().x, texture->getSize().y);
  90. return (Rml::TextureHandle)texture;
  91. }
  92. Rml::TextureHandle GenerateTexture(Rml::Span<const Rml::byte> source, Rml::Vector2i source_dimensions) override
  93. {
  94. sf::Texture* texture = new sf::Texture();
  95. texture->setSmooth(true);
  96. if (!texture->create(source_dimensions.x, source_dimensions.y))
  97. {
  98. delete texture;
  99. return false;
  100. }
  101. texture->update(source.data(), source_dimensions.x, source_dimensions.y, 0, 0);
  102. return (Rml::TextureHandle)texture;
  103. }
  104. void ReleaseTexture(Rml::TextureHandle texture_handle) override { delete (sf::Texture*)texture_handle; }
  105. };
  106. // Updates the viewport and context dimensions, should be called whenever the window size changes.
  107. static void UpdateWindowDimensions(sf::RenderWindow& window, RenderInterface_GL2_SFML& render_interface, Rml::Context* context)
  108. {
  109. const int width = (int)window.getSize().x;
  110. const int height = (int)window.getSize().y;
  111. if (context)
  112. context->SetDimensions(Rml::Vector2i(width, height));
  113. sf::View view(sf::FloatRect(0.f, 0.f, (float)width, (float)height));
  114. window.setView(view);
  115. render_interface.SetViewport(width, height);
  116. }
  117. /**
  118. Global data used by this backend.
  119. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  120. */
  121. struct BackendData {
  122. SystemInterface_SFML system_interface;
  123. RenderInterface_GL2_SFML render_interface;
  124. sf::RenderWindow window;
  125. bool running = true;
  126. };
  127. static Rml::UniquePtr<BackendData> data;
  128. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  129. {
  130. RMLUI_ASSERT(!data);
  131. data = Rml::MakeUnique<BackendData>();
  132. // Create the window.
  133. sf::RenderWindow out_window;
  134. sf::ContextSettings context_settings;
  135. context_settings.stencilBits = 8;
  136. context_settings.antialiasingLevel = 2;
  137. const sf::Uint32 style = (allow_resize ? sf::Style::Default : (sf::Style::Titlebar | sf::Style::Close));
  138. data->window.create(sf::VideoMode(width, height), window_name, style, context_settings);
  139. data->window.setVerticalSyncEnabled(true);
  140. if (!data->window.isOpen())
  141. {
  142. data.reset();
  143. return false;
  144. }
  145. // Optionally apply the SFML window to the system interface so that it can change its mouse cursor.
  146. data->system_interface.SetWindow(&data->window);
  147. UpdateWindowDimensions(data->window, data->render_interface, nullptr);
  148. return true;
  149. }
  150. void Backend::Shutdown()
  151. {
  152. data.reset();
  153. }
  154. Rml::SystemInterface* Backend::GetSystemInterface()
  155. {
  156. RMLUI_ASSERT(data);
  157. return &data->system_interface;
  158. }
  159. Rml::RenderInterface* Backend::GetRenderInterface()
  160. {
  161. RMLUI_ASSERT(data);
  162. return &data->render_interface;
  163. }
  164. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  165. {
  166. RMLUI_ASSERT(data && context);
  167. // SFML does not seem to provide a way to wait for events with a timeout.
  168. (void)power_save;
  169. // The contents of this function is intended to be copied directly into your main loop.
  170. bool result = data->running;
  171. data->running = true;
  172. sf::Event ev;
  173. while (data->window.pollEvent(ev))
  174. {
  175. switch (ev.type)
  176. {
  177. case sf::Event::Resized: UpdateWindowDimensions(data->window, data->render_interface, context); break;
  178. case sf::Event::KeyPressed:
  179. {
  180. const Rml::Input::KeyIdentifier key = RmlSFML::ConvertKey(ev.key.code);
  181. const int key_modifier = RmlSFML::GetKeyModifierState();
  182. const float native_dp_ratio = 1.f;
  183. // See if we have any global shortcuts that take priority over the context.
  184. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  185. break;
  186. // Otherwise, hand the event over to the context by calling the input handler as normal.
  187. if (!RmlSFML::InputHandler(context, ev))
  188. break;
  189. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  190. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  191. break;
  192. }
  193. break;
  194. case sf::Event::Closed: result = false; break;
  195. default: RmlSFML::InputHandler(context, ev); break;
  196. }
  197. }
  198. return result;
  199. }
  200. void Backend::RequestExit()
  201. {
  202. RMLUI_ASSERT(data);
  203. data->running = false;
  204. }
  205. void Backend::BeginFrame()
  206. {
  207. RMLUI_ASSERT(data);
  208. sf::RenderWindow& window = data->window;
  209. window.resetGLStates();
  210. window.clear();
  211. data->render_interface.BeginFrame();
  212. #if 0
  213. // Draw a simple shape with SFML for demonstration purposes. Make sure to push and pop GL states as appropriate.
  214. sf::Vector2f circle_position(100.f, 100.f);
  215. window.pushGLStates();
  216. sf::CircleShape circle(50.f);
  217. circle.setPosition(circle_position);
  218. circle.setFillColor(sf::Color::Blue);
  219. circle.setOutlineColor(sf::Color::Red);
  220. circle.setOutlineThickness(10.f);
  221. window.draw(circle);
  222. window.popGLStates();
  223. #endif
  224. }
  225. void Backend::PresentFrame()
  226. {
  227. RMLUI_ASSERT(data);
  228. data->render_interface.EndFrame();
  229. data->window.display();
  230. // Optional, used to mark frames during performance profiling.
  231. RMLUI_FrameMark;
  232. }