RmlUi_Renderer_GL3.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 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_Renderer_GL3.h"
  29. #include "flat_handle_map.h"
  30. #include <RmlUi/Core/Core.h>
  31. #include <RmlUi/Core/FileInterface.h>
  32. #include <RmlUi/Core/Log.h>
  33. #include <RmlUi/Core/Platform.h>
  34. #include <string.h>
  35. #if defined(RMLUI_PLATFORM_WIN32) && !defined(__MINGW32__)
  36. // function call missing argument list
  37. #pragma warning(disable : 4551)
  38. // unreferenced local function has been removed
  39. #pragma warning(disable : 4505)
  40. #endif
  41. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  42. #define RMLUI_SHADER_HEADER "#version 300 es\nprecision highp float;\n"
  43. #include <GLES3/gl3.h>
  44. #else
  45. #define RMLUI_SHADER_HEADER "#version 330\n"
  46. #define GLAD_GL_IMPLEMENTATION
  47. #include "RmlUi_Include_GL3.h"
  48. #endif
  49. static const char* shader_main_vertex = RMLUI_SHADER_HEADER R"(
  50. uniform vec2 _translate;
  51. uniform mat4 _transform;
  52. in vec2 inPosition;
  53. in vec4 inColor0;
  54. in vec2 inTexCoord0;
  55. out vec2 fragTexCoord;
  56. out vec4 fragColor;
  57. void main() {
  58. fragTexCoord = inTexCoord0;
  59. fragColor = inColor0;
  60. vec2 translatedPos = inPosition + _translate.xy;
  61. vec4 outPos = _transform * vec4(translatedPos, 0, 1);
  62. gl_Position = outPos;
  63. }
  64. )";
  65. static const char* shader_main_fragment_texture = RMLUI_SHADER_HEADER R"(
  66. uniform sampler2D _tex;
  67. in vec2 fragTexCoord;
  68. in vec4 fragColor;
  69. out vec4 finalColor;
  70. void main() {
  71. vec4 texColor = texture(_tex, fragTexCoord);
  72. finalColor = fragColor * texColor;
  73. }
  74. )";
  75. using Quad = Rml::Array<Rml::Vertex, 4>;
  76. using QuadHandle = flat_handle_map<Quad>::handle;
  77. static const QuadHandle InvalidQuadHandle = QuadHandle(-1);
  78. namespace Gfx {
  79. enum class ProgramUniform { Translate, Transform, Tex, Count };
  80. static const char* const program_uniform_names[(size_t)ProgramUniform::Count] = {"_translate", "_transform", "_tex"};
  81. enum class VertexAttribute { Position, Color0, TexCoord0, Count };
  82. static const char* const vertex_attribute_names[(size_t)VertexAttribute::Count] = {"inPosition", "inColor0", "inTexCoord0"};
  83. struct CompiledGeometryData {
  84. GLuint texture;
  85. GLuint vao;
  86. GLuint vbo;
  87. GLuint ibo;
  88. GLsizei draw_count;
  89. QuadHandle quad_handle;
  90. };
  91. struct ProgramData {
  92. GLuint id;
  93. GLint uniform_locations[(size_t)ProgramUniform::Count];
  94. };
  95. struct ShadersData {
  96. ProgramData program_texture;
  97. GLuint shader_main_vertex;
  98. GLuint shader_main_fragment_texture;
  99. };
  100. static void CheckGLError(const char* operation_name)
  101. {
  102. #ifdef RMLUI_DEBUG
  103. GLenum error_code = glGetError();
  104. if (error_code != GL_NO_ERROR)
  105. {
  106. static const Rml::Pair<GLenum, const char*> error_names[] = {{GL_INVALID_ENUM, "GL_INVALID_ENUM"}, {GL_INVALID_VALUE, "GL_INVALID_VALUE"},
  107. {GL_INVALID_OPERATION, "GL_INVALID_OPERATION"}, {GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY"}};
  108. const char* error_str = "''";
  109. for (auto& err : error_names)
  110. {
  111. if (err.first == error_code)
  112. {
  113. error_str = err.second;
  114. break;
  115. }
  116. }
  117. Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL error during %s. Error code 0x%x (%s).", operation_name, error_code, error_str);
  118. }
  119. #endif
  120. (void)operation_name;
  121. }
  122. // Create the shader, 'shader_type' is either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER.
  123. static GLuint CreateShader(GLenum shader_type, const char* code_string)
  124. {
  125. GLuint id = glCreateShader(shader_type);
  126. glShaderSource(id, 1, (const GLchar**)&code_string, NULL);
  127. glCompileShader(id);
  128. GLint status = 0;
  129. glGetShaderiv(id, GL_COMPILE_STATUS, &status);
  130. if (status == GL_FALSE)
  131. {
  132. GLint info_log_length = 0;
  133. glGetShaderiv(id, GL_INFO_LOG_LENGTH, &info_log_length);
  134. char* info_log_string = new char[info_log_length + 1];
  135. glGetShaderInfoLog(id, info_log_length, NULL, info_log_string);
  136. Rml::Log::Message(Rml::Log::LT_ERROR, "Compile failure in OpenGL shader: %s", info_log_string);
  137. delete[] info_log_string;
  138. glDeleteShader(id);
  139. return 0;
  140. }
  141. CheckGLError("CreateShader");
  142. return id;
  143. }
  144. static void BindAttribLocations(GLuint program)
  145. {
  146. for (GLuint i = 0; i < (GLuint)VertexAttribute::Count; i++)
  147. {
  148. glBindAttribLocation(program, i, vertex_attribute_names[i]);
  149. }
  150. CheckGLError("BindAttribLocations");
  151. }
  152. static bool CreateProgram(GLuint vertex_shader, GLuint fragment_shader, ProgramData& out_program)
  153. {
  154. GLuint id = glCreateProgram();
  155. RMLUI_ASSERT(id);
  156. BindAttribLocations(id);
  157. glAttachShader(id, vertex_shader);
  158. glAttachShader(id, fragment_shader);
  159. glLinkProgram(id);
  160. glDetachShader(id, vertex_shader);
  161. glDetachShader(id, fragment_shader);
  162. GLint status = 0;
  163. glGetProgramiv(id, GL_LINK_STATUS, &status);
  164. if (status == GL_FALSE)
  165. {
  166. GLint info_log_length = 0;
  167. glGetProgramiv(id, GL_INFO_LOG_LENGTH, &info_log_length);
  168. char* info_log_string = new char[info_log_length + 1];
  169. glGetProgramInfoLog(id, info_log_length, NULL, info_log_string);
  170. Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL program linking failure: %s", info_log_string);
  171. delete[] info_log_string;
  172. glDeleteProgram(id);
  173. return false;
  174. }
  175. out_program = {};
  176. out_program.id = id;
  177. // Make a lookup table for the uniform locations.
  178. GLint num_active_uniforms = 0;
  179. glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &num_active_uniforms);
  180. constexpr size_t name_size = 64;
  181. GLchar name_buf[name_size] = "";
  182. for (int unif = 0; unif < num_active_uniforms; ++unif)
  183. {
  184. GLint array_size = 0;
  185. GLenum type = 0;
  186. GLsizei actual_length = 0;
  187. glGetActiveUniform(id, unif, name_size, &actual_length, &array_size, &type, name_buf);
  188. GLint location = glGetUniformLocation(id, name_buf);
  189. // See if we have the name in our pre-defined name list.
  190. ProgramUniform program_uniform = ProgramUniform::Count;
  191. for (int i = 0; i < (int)ProgramUniform::Count; i++)
  192. {
  193. const char* uniform_name = program_uniform_names[i];
  194. if (strcmp(name_buf, uniform_name) == 0)
  195. {
  196. program_uniform = (ProgramUniform)i;
  197. break;
  198. }
  199. }
  200. if ((size_t)program_uniform < (size_t)ProgramUniform::Count)
  201. {
  202. out_program.uniform_locations[(size_t)program_uniform] = location;
  203. }
  204. else
  205. {
  206. Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL program uses unknown uniform '%s'.", name_buf);
  207. return false;
  208. }
  209. }
  210. CheckGLError("CreateProgram");
  211. return true;
  212. }
  213. static bool CreateShaders(ShadersData& out_shaders)
  214. {
  215. out_shaders = {};
  216. GLuint& main_vertex = out_shaders.shader_main_vertex;
  217. GLuint& main_fragment_texture = out_shaders.shader_main_fragment_texture;
  218. main_vertex = CreateShader(GL_VERTEX_SHADER, shader_main_vertex);
  219. if (!main_vertex)
  220. {
  221. Rml::Log::Message(Rml::Log::LT_ERROR, "Could not create OpenGL shader: 'shader_main_vertex'.");
  222. return false;
  223. }
  224. main_fragment_texture = CreateShader(GL_FRAGMENT_SHADER, shader_main_fragment_texture);
  225. if (!main_fragment_texture)
  226. {
  227. Rml::Log::Message(Rml::Log::LT_ERROR, "Could not create OpenGL shader: 'shader_main_fragment_texture'.");
  228. return false;
  229. }
  230. if (!CreateProgram(main_vertex, main_fragment_texture, out_shaders.program_texture))
  231. {
  232. Rml::Log::Message(Rml::Log::LT_ERROR, "Could not create OpenGL program: 'program_texture'.");
  233. return false;
  234. }
  235. return true;
  236. }
  237. static void DestroyShaders(ShadersData& shaders)
  238. {
  239. glDeleteProgram(shaders.program_texture.id);
  240. glDeleteShader(shaders.shader_main_vertex);
  241. glDeleteShader(shaders.shader_main_fragment_texture);
  242. shaders = {};
  243. }
  244. } // namespace Gfx
  245. class QuadMap {
  246. public:
  247. bool Initialize()
  248. {
  249. quads.reserve(reserved_quads);
  250. const int num_indices = 6;
  251. static const int quad_indices[] = {0, 3, 1, 1, 3, 2};
  252. glGenVertexArrays(1, &vao);
  253. glGenBuffers(1, &vbo);
  254. glGenBuffers(1, &ibo);
  255. glBindVertexArray(vao);
  256. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  257. glBufferData(GL_ARRAY_BUFFER, sizeof(Quad) * reserved_quads, nullptr, GL_DYNAMIC_DRAW);
  258. glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::Position);
  259. glVertexAttribPointer((GLuint)Gfx::VertexAttribute::Position, 2, GL_FLOAT, GL_FALSE, sizeof(Rml::Vertex),
  260. (const GLvoid*)(offsetof(Rml::Vertex, position)));
  261. glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::Color0);
  262. glVertexAttribPointer((GLuint)Gfx::VertexAttribute::Color0, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Rml::Vertex),
  263. (const GLvoid*)(offsetof(Rml::Vertex, colour)));
  264. glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::TexCoord0);
  265. glVertexAttribPointer((GLuint)Gfx::VertexAttribute::TexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(Rml::Vertex),
  266. (const GLvoid*)(offsetof(Rml::Vertex, tex_coord)));
  267. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  268. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int) * num_indices, (const void*)quad_indices, GL_STATIC_DRAW);
  269. glBindVertexArray(0);
  270. Gfx::CheckGLError("QuadInitialize");
  271. return true;
  272. }
  273. void Shutdown()
  274. {
  275. glDeleteVertexArrays(1, &vao);
  276. glDeleteBuffers(1, &vbo);
  277. glDeleteBuffers(1, &ibo);
  278. }
  279. QuadHandle Insert(const Quad& quad)
  280. {
  281. QuadHandle handle = quads.insert(quad);
  282. if ((int)handle >= reserved_quads)
  283. {
  284. reserved_quads = reserved_quads * 2;
  285. quads.reserve(reserved_quads);
  286. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  287. glBufferData(GL_ARRAY_BUFFER, sizeof(Quad) * reserved_quads, (const void*)quads.data(), GL_DYNAMIC_DRAW);
  288. }
  289. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  290. glBufferSubData(GL_ARRAY_BUFFER, sizeof(Quad) * GLintptr(handle), sizeof(Quad), (const void*)(quads.data() + int(handle)));
  291. Gfx::CheckGLError("QuadInsert");
  292. return handle;
  293. }
  294. void Erase(QuadHandle handle) { quads.erase(handle); }
  295. GLuint GetVao() const { return vao; }
  296. private:
  297. flat_handle_map<Quad> quads;
  298. int reserved_quads = 64;
  299. GLuint vao = 0;
  300. GLuint vbo = 0;
  301. GLuint ibo = 0;
  302. } quad_map;
  303. size_t num_quads = 0;
  304. size_t num_non_quads = 0;
  305. RenderInterface_GL3::RenderInterface_GL3()
  306. {
  307. shaders = Rml::MakeUnique<Gfx::ShadersData>();
  308. if (!Gfx::CreateShaders(*shaders))
  309. shaders.reset();
  310. quad_map.Initialize();
  311. const Rml::byte white_pixel[] = {0xff, 0xff, 0xff, 0xff};
  312. RenderInterface_GL3::GenerateTexture(texture_white, white_pixel, Rml::Vector2i(1, 1));
  313. }
  314. RenderInterface_GL3::~RenderInterface_GL3()
  315. {
  316. Rml::Log::Message(Rml::Log::LT_INFO, "Quads: %zu Not quads: %zu", num_quads, num_non_quads);
  317. RenderInterface_GL3::ReleaseTexture(texture_white);
  318. texture_white = {};
  319. quad_map.Shutdown();
  320. if (shaders)
  321. Gfx::DestroyShaders(*shaders);
  322. }
  323. void RenderInterface_GL3::SetViewport(int width, int height)
  324. {
  325. viewport_width = width;
  326. viewport_height = height;
  327. }
  328. void RenderInterface_GL3::BeginFrame()
  329. {
  330. RMLUI_ASSERT(viewport_width > 0 && viewport_height > 0);
  331. glViewport(0, 0, viewport_width, viewport_height);
  332. glClearStencil(0);
  333. glClearColor(0, 0, 0, 1);
  334. glDisable(GL_CULL_FACE);
  335. glEnable(GL_STENCIL_TEST);
  336. glStencilFunc(GL_ALWAYS, 1, GLuint(-1));
  337. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  338. glEnable(GL_BLEND);
  339. glBlendEquation(GL_FUNC_ADD);
  340. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  341. projection = Rml::Matrix4f::ProjectOrtho(0, (float)viewport_width, (float)viewport_height, 0, -10000, 10000);
  342. SetTransform(nullptr);
  343. glUseProgram(shaders->program_texture.id);
  344. active_texture = {};
  345. active_vao = {};
  346. }
  347. void RenderInterface_GL3::EndFrame() {}
  348. void RenderInterface_GL3::Clear()
  349. {
  350. glClearStencil(0);
  351. glClearColor(0, 0, 0, 1);
  352. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  353. }
  354. void RenderInterface_GL3::RenderGeometry(Rml::Vertex* vertices, int num_vertices, int* indices, int num_indices, const Rml::TextureHandle texture,
  355. const Rml::Vector2f& translation)
  356. {
  357. Rml::CompiledGeometryHandle geometry = CompileGeometry(vertices, num_vertices, indices, num_indices, texture);
  358. if (geometry)
  359. {
  360. RenderCompiledGeometry(geometry, translation);
  361. ReleaseCompiledGeometry(geometry);
  362. }
  363. }
  364. #if 0
  365. struct QuadMap {
  366. Rml::Vector<Quad> quads;
  367. Rml::Vector<int> handle_lookup;
  368. bool is_dirty = false;
  369. QuadHandle Insert()
  370. {
  371. QuadHandle result = QuadHandle(handle_lookup.size());
  372. auto it_handle = std::find(handle_lookup.begin(), handle_lookup.end(), -1);
  373. if (it_handle == handle_lookup.end())
  374. handle_lookup.
  375. handle_lookup.push_back(int(quads.size()));
  376. quads.push_back({});
  377. return result;
  378. }
  379. int GetIndex(QuadHandle handle) const
  380. {
  381. return handle_lookup[handle];
  382. }
  383. void Erase(QuadHandle handle)
  384. {
  385. const int erase_index = handle_lookup[handle];
  386. handle_lookup[handle] = -1;
  387. quads.erase(quads.begin() + erase_index);
  388. for (int& index : handle_lookup)
  389. if (index >= erase_index)
  390. index -= 1;
  391. }
  392. } quad_map;
  393. #endif
  394. Rml::CompiledGeometryHandle RenderInterface_GL3::CompileGeometry(Rml::Vertex* vertices, int num_vertices, int* indices, int num_indices,
  395. Rml::TextureHandle texture)
  396. {
  397. if (!texture)
  398. {
  399. texture = texture_white;
  400. }
  401. static const int quad_indices[] = {0, 3, 1, 1, 3, 2};
  402. if (num_vertices == 4 && num_indices == 6 && std::equal(std::begin(quad_indices), std::end(quad_indices), indices))
  403. {
  404. Quad quad = {vertices[0], vertices[1], vertices[2], vertices[3]};
  405. QuadHandle handle = quad_map.Insert(quad);
  406. Gfx::CompiledGeometryData* geometry = new Gfx::CompiledGeometryData{};
  407. geometry->texture = (GLuint)texture;
  408. geometry->quad_handle = handle;
  409. geometry->vao = quad_map.GetVao();
  410. num_quads += 1;
  411. return (Rml::CompiledGeometryHandle)geometry;
  412. }
  413. num_non_quads += 1;
  414. constexpr GLenum draw_usage = GL_STATIC_DRAW;
  415. GLuint vao = 0;
  416. GLuint vbo = 0;
  417. GLuint ibo = 0;
  418. glGenVertexArrays(1, &vao);
  419. glGenBuffers(1, &vbo);
  420. glGenBuffers(1, &ibo);
  421. glBindVertexArray(vao);
  422. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  423. glBufferData(GL_ARRAY_BUFFER, sizeof(Rml::Vertex) * num_vertices, (const void*)vertices, draw_usage);
  424. glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::Position);
  425. glVertexAttribPointer((GLuint)Gfx::VertexAttribute::Position, 2, GL_FLOAT, GL_FALSE, sizeof(Rml::Vertex),
  426. (const GLvoid*)(offsetof(Rml::Vertex, position)));
  427. glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::Color0);
  428. glVertexAttribPointer((GLuint)Gfx::VertexAttribute::Color0, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Rml::Vertex),
  429. (const GLvoid*)(offsetof(Rml::Vertex, colour)));
  430. glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::TexCoord0);
  431. glVertexAttribPointer((GLuint)Gfx::VertexAttribute::TexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(Rml::Vertex),
  432. (const GLvoid*)(offsetof(Rml::Vertex, tex_coord)));
  433. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  434. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int) * num_indices, (const void*)indices, draw_usage);
  435. glBindVertexArray(0);
  436. Gfx::CheckGLError("CompileGeometry");
  437. Gfx::CompiledGeometryData* geometry = new Gfx::CompiledGeometryData;
  438. geometry->quad_handle = InvalidQuadHandle;
  439. geometry->texture = (GLuint)texture;
  440. geometry->vao = vao;
  441. geometry->vbo = vbo;
  442. geometry->ibo = ibo;
  443. geometry->draw_count = num_indices;
  444. return (Rml::CompiledGeometryHandle)geometry;
  445. }
  446. void RenderInterface_GL3::RenderCompiledGeometry(Rml::CompiledGeometryHandle handle, const Rml::Vector2f& translation)
  447. {
  448. Gfx::CompiledGeometryData* geometry = (Gfx::CompiledGeometryData*)handle;
  449. if (geometry->texture != active_texture)
  450. {
  451. glBindTexture(GL_TEXTURE_2D, geometry->texture);
  452. active_texture = geometry->texture;
  453. }
  454. SubmitTransformUniform(ProgramId::Texture, shaders->program_texture.uniform_locations[(size_t)Gfx::ProgramUniform::Transform]);
  455. glUniform2fv(shaders->program_texture.uniform_locations[(size_t)Gfx::ProgramUniform::Translate], 1, &translation.x);
  456. if (geometry->vao != active_vao)
  457. {
  458. glBindVertexArray(geometry->vao);
  459. active_vao = geometry->vao;
  460. }
  461. if (geometry->quad_handle == InvalidQuadHandle)
  462. {
  463. glDrawElements(GL_TRIANGLES, geometry->draw_count, GL_UNSIGNED_INT, (const GLvoid*)0);
  464. }
  465. else
  466. {
  467. const int num_vertices = 4;
  468. const int num_indices = 6;
  469. glDrawElementsBaseVertex(GL_TRIANGLES, num_indices, GL_UNSIGNED_INT, (const GLvoid*)0, num_vertices * int(geometry->quad_handle));
  470. }
  471. Gfx::CheckGLError("RenderCompiledGeometry");
  472. }
  473. void RenderInterface_GL3::ReleaseCompiledGeometry(Rml::CompiledGeometryHandle handle)
  474. {
  475. Gfx::CompiledGeometryData* geometry = (Gfx::CompiledGeometryData*)handle;
  476. if (geometry->quad_handle == InvalidQuadHandle)
  477. {
  478. glDeleteVertexArrays(1, &geometry->vao);
  479. glDeleteBuffers(1, &geometry->vbo);
  480. glDeleteBuffers(1, &geometry->ibo);
  481. }
  482. else
  483. {
  484. quad_map.Erase(geometry->quad_handle);
  485. }
  486. delete geometry;
  487. }
  488. void RenderInterface_GL3::EnableScissorRegion(bool enable)
  489. {
  490. ScissoringState new_state = ScissoringState::Disable;
  491. if (enable)
  492. new_state = (transform_active ? ScissoringState::Stencil : ScissoringState::Scissor);
  493. if (new_state != scissoring_state)
  494. {
  495. // Disable old
  496. if (scissoring_state == ScissoringState::Scissor)
  497. glDisable(GL_SCISSOR_TEST);
  498. else if (scissoring_state == ScissoringState::Stencil)
  499. glStencilFunc(GL_ALWAYS, 1, GLuint(-1));
  500. // Enable new
  501. if (new_state == ScissoringState::Scissor)
  502. glEnable(GL_SCISSOR_TEST);
  503. else if (new_state == ScissoringState::Stencil)
  504. glStencilFunc(GL_EQUAL, 1, GLuint(-1));
  505. scissoring_state = new_state;
  506. }
  507. }
  508. void RenderInterface_GL3::SetScissorRegion(int x, int y, int width, int height)
  509. {
  510. if (transform_active)
  511. {
  512. const float left = float(x);
  513. const float right = float(x + width);
  514. const float top = float(y);
  515. const float bottom = float(y + height);
  516. Rml::Vertex vertices[4];
  517. vertices[0].position = {left, top};
  518. vertices[1].position = {right, top};
  519. vertices[2].position = {right, bottom};
  520. vertices[3].position = {left, bottom};
  521. int indices[6] = {0, 2, 1, 0, 3, 2};
  522. glClear(GL_STENCIL_BUFFER_BIT);
  523. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  524. glStencilFunc(GL_ALWAYS, 1, GLuint(-1));
  525. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  526. RenderGeometry(vertices, 4, indices, 6, 0, Rml::Vector2f(0, 0));
  527. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  528. glStencilFunc(GL_EQUAL, 1, GLuint(-1));
  529. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  530. }
  531. else
  532. {
  533. glScissor(x, viewport_height - (y + height), width, height);
  534. }
  535. }
  536. // Set to byte packing, or the compiler will expand our struct, which means it won't read correctly from file
  537. #pragma pack(1)
  538. struct TGAHeader {
  539. char idLength;
  540. char colourMapType;
  541. char dataType;
  542. short int colourMapOrigin;
  543. short int colourMapLength;
  544. char colourMapDepth;
  545. short int xOrigin;
  546. short int yOrigin;
  547. short int width;
  548. short int height;
  549. char bitsPerPixel;
  550. char imageDescriptor;
  551. };
  552. // Restore packing
  553. #pragma pack()
  554. bool RenderInterface_GL3::LoadTexture(Rml::TextureHandle& texture_handle, Rml::Vector2i& texture_dimensions, const Rml::String& source)
  555. {
  556. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  557. Rml::FileHandle file_handle = file_interface->Open(source);
  558. if (!file_handle)
  559. {
  560. return false;
  561. }
  562. file_interface->Seek(file_handle, 0, SEEK_END);
  563. size_t buffer_size = file_interface->Tell(file_handle);
  564. file_interface->Seek(file_handle, 0, SEEK_SET);
  565. if (buffer_size <= sizeof(TGAHeader))
  566. {
  567. Rml::Log::Message(Rml::Log::LT_ERROR, "Texture file size is smaller than TGAHeader, file is not a valid TGA image.");
  568. file_interface->Close(file_handle);
  569. return false;
  570. }
  571. using Rml::byte;
  572. byte* buffer = new byte[buffer_size];
  573. file_interface->Read(buffer, buffer_size, file_handle);
  574. file_interface->Close(file_handle);
  575. TGAHeader header;
  576. memcpy(&header, buffer, sizeof(TGAHeader));
  577. int color_mode = header.bitsPerPixel / 8;
  578. int image_size = header.width * header.height * 4; // We always make 32bit textures
  579. if (header.dataType != 2)
  580. {
  581. Rml::Log::Message(Rml::Log::LT_ERROR, "Only 24/32bit uncompressed TGAs are supported.");
  582. delete[] buffer;
  583. return false;
  584. }
  585. // Ensure we have at least 3 colors
  586. if (color_mode < 3)
  587. {
  588. Rml::Log::Message(Rml::Log::LT_ERROR, "Only 24 and 32bit textures are supported.");
  589. delete[] buffer;
  590. return false;
  591. }
  592. const byte* image_src = buffer + sizeof(TGAHeader);
  593. byte* image_dest = new byte[image_size];
  594. // Targa is BGR, swap to RGB and flip Y axis
  595. for (long y = 0; y < header.height; y++)
  596. {
  597. long read_index = y * header.width * color_mode;
  598. long write_index = ((header.imageDescriptor & 32) != 0) ? read_index : (header.height - y - 1) * header.width * 4;
  599. for (long x = 0; x < header.width; x++)
  600. {
  601. image_dest[write_index] = image_src[read_index + 2];
  602. image_dest[write_index + 1] = image_src[read_index + 1];
  603. image_dest[write_index + 2] = image_src[read_index];
  604. if (color_mode == 4)
  605. {
  606. const int alpha = image_src[read_index + 3];
  607. #ifdef RMLUI_SRGB_PREMULTIPLIED_ALPHA
  608. image_dest[write_index + 0] = (image_dest[write_index + 0] * alpha) / 255;
  609. image_dest[write_index + 1] = (image_dest[write_index + 1] * alpha) / 255;
  610. image_dest[write_index + 2] = (image_dest[write_index + 2] * alpha) / 255;
  611. #endif
  612. image_dest[write_index + 3] = (byte)alpha;
  613. }
  614. else
  615. {
  616. image_dest[write_index + 3] = 255;
  617. }
  618. write_index += 4;
  619. read_index += color_mode;
  620. }
  621. }
  622. texture_dimensions.x = header.width;
  623. texture_dimensions.y = header.height;
  624. bool success = GenerateTexture(texture_handle, image_dest, texture_dimensions);
  625. delete[] image_dest;
  626. delete[] buffer;
  627. return success;
  628. }
  629. bool RenderInterface_GL3::GenerateTexture(Rml::TextureHandle& texture_handle, const Rml::byte* source, const Rml::Vector2i& source_dimensions)
  630. {
  631. GLuint texture_id = 0;
  632. glGenTextures(1, &texture_id);
  633. if (texture_id == 0)
  634. {
  635. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to generate texture.");
  636. return false;
  637. }
  638. glBindTexture(GL_TEXTURE_2D, texture_id);
  639. GLint internal_format = GL_RGBA8;
  640. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, source_dimensions.x, source_dimensions.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, source);
  641. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  642. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  643. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  644. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  645. texture_handle = (Rml::TextureHandle)texture_id;
  646. return true;
  647. }
  648. void RenderInterface_GL3::ReleaseTexture(Rml::TextureHandle texture_handle)
  649. {
  650. glDeleteTextures(1, (GLuint*)&texture_handle);
  651. }
  652. void RenderInterface_GL3::SetTransform(const Rml::Matrix4f* new_transform)
  653. {
  654. transform_active = (new_transform != nullptr);
  655. transform = projection * (new_transform ? *new_transform : Rml::Matrix4f::Identity());
  656. transform_dirty_state = ProgramId::All;
  657. }
  658. void RenderInterface_GL3::SubmitTransformUniform(ProgramId program_id, int uniform_location)
  659. {
  660. if ((int)program_id & (int)transform_dirty_state)
  661. {
  662. glUniformMatrix4fv(uniform_location, 1, false, transform.data());
  663. transform_dirty_state = ProgramId((int)transform_dirty_state & ~(int)program_id);
  664. }
  665. }
  666. bool RmlGL3::Initialize(Rml::String* out_message)
  667. {
  668. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  669. if (out_message)
  670. *out_message = "Started Emscripten WebGL renderer.";
  671. #else
  672. const int gl_version = gladLoaderLoadGL();
  673. if (gl_version == 0)
  674. {
  675. if (out_message)
  676. *out_message = "Failed to initialize OpenGL context.";
  677. return false;
  678. }
  679. if (out_message)
  680. *out_message = Rml::CreateString(128, "Loaded OpenGL %d.%d.", GLAD_VERSION_MAJOR(gl_version), GLAD_VERSION_MINOR(gl_version));
  681. #endif
  682. return true;
  683. }
  684. void RmlGL3::Shutdown()
  685. {
  686. #if !defined RMLUI_PLATFORM_EMSCRIPTEN
  687. gladLoaderUnloadGL();
  688. #endif
  689. }