From 1f68fe78e84f25c8ddacdc37a293a5de31725bab Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sat, 1 Jan 2022 13:01:08 +0000 Subject: First iteration with font/text support --- ui/font.cpp | 182 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ui/font.h | 48 +++++++++++++++ ui/text.cpp | 59 +++++++++++++++++++ ui/text.h | 31 ++++++++++ ui/toolbar.cpp | 2 + ui/window.cpp | 2 +- 6 files changed, 323 insertions(+), 1 deletion(-) create mode 100644 ui/font.cpp create mode 100644 ui/font.h create mode 100644 ui/text.cpp create mode 100644 ui/text.h (limited to 'ui') diff --git a/ui/font.cpp b/ui/font.cpp new file mode 100644 index 0000000..5596f20 --- /dev/null +++ b/ui/font.cpp @@ -0,0 +1,182 @@ +#include "font.h" +#include +#include +#include +#include FT_FREETYPE_H +#include +#include +#include +#include +#include +#include +#include +// IWYU pragma: no_forward_declare FT_LibraryRec_ + +std::string +FT_Error_StringSafe(FT_Error err) +{ + if (const auto errstr = FT_Error_String(err)) { + return {errstr}; + } + return std::to_string(err); +} + +template +void +FT_Check(Args &&... args) +{ + if (const auto err = Func(std::forward(args)...)) { + throw std::runtime_error {std::string {"FreeType error: "} + FT_Error_StringSafe(err)}; + } +} + +const std::string BASIC_CHARS = []() { + std::string chars; + for (char c {}; c >= 0; c++) { + if (isgraph(c)) { + chars += c; + } + } + return chars + "£€²³"; +}(); + +using FT = glRef(&ft); + return ft; + }, + FT_Done_FreeType>; + +using Face = glRef(ft, name, 0, &face); + return face; + }, + FT_Done_Face>; + +Font::Font(const char * const p, unsigned s) : path {p}, size {getTextureSize(s)} +{ + generateChars(BASIC_CHARS); +} + +void +Font::generateChars(const std::string_view chars) const +{ + std::optional ft; + std::optional face; + + for (auto c = chars.data(); c <= &chars.back(); c = next_char(c)) { + const auto codepoint = get_codepoint(c); + if (charsData.find(codepoint) == charsData.end()) { + if (!ft) { + ft.emplace(); + } + if (!face) { + face.emplace(*ft, path.c_str()); + FT_Set_Pixel_Sizes(*face, 0, size.z); + } + FT_UInt glyph_index = FT_Get_Char_Index(*face, codepoint); + if (FT_Load_Glyph(*face, glyph_index, FT_LOAD_RENDER)) { + charsData.emplace(codepoint, CharData {}); + continue; + } + + const auto & glyph = (*face)->glyph; + const auto textureIdx = getTextureWithSpace(glyph->bitmap.width); + auto & texture = fontTextures[textureIdx]; + + glTexSubImage2D(GL_TEXTURE_2D, 0, static_cast(texture.used), 0, + static_cast(glyph->bitmap.width), static_cast(glyph->bitmap.rows), GL_RED, + GL_UNSIGNED_BYTE, glyph->bitmap.buffer); + + const auto & cd = charsData + .emplace(codepoint, + CharData {textureIdx, {glyph->bitmap.width, glyph->bitmap.rows}, + {texture.used, 0}, {glyph->bitmap_left, glyph->bitmap_top}, + glyph->advance.x >> 6}) + .first->second; + texture.used += cd.size.x; + } + } +} + +std::size_t +Font::getTextureWithSpace(unsigned int adv) const +{ + if (auto itr = std::find_if(fontTextures.begin(), fontTextures.end(), + [adv, this](const FontTexture & ft) { + return (ft.used + adv) < size.x; + }); + itr != fontTextures.end()) { + glBindTexture(GL_TEXTURE_2D, itr->texture); + return static_cast(itr - fontTextures.begin()); + } + + auto & texture = fontTextures.emplace_back(); + glGenTextures(1, &texture.texture); + glBindTexture(GL_TEXTURE_2D, texture.texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast(size.x), static_cast(size.y), 0, GL_RED, + GL_UNSIGNED_BYTE, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + return fontTextures.size() - 1; +} + +glm::uvec3 +Font::getTextureSize(unsigned int height) +{ + auto pow2 = [](unsigned int target) { + unsigned int v {8}; + do { + v <<= 1; + } while (v << 1 < GL_MAX_TEXTURE_SIZE && v < target); + return v; + }; + + constexpr const unsigned int WIDTH_PER_HEIGHT {64}; + return {pow2(height * WIDTH_PER_HEIGHT), pow2(height), height}; +} + +Font::TextureQuads +Font::render(const std::string_view chars) const +{ + constexpr static const std::array, 4> C {{ + {{0, 0}, {0, 1}}, + {{1, 0}, {1, 1}}, + {{1, 1}, {1, 0}}, + {{0, 1}, {0, 0}}, + }}; + + generateChars(chars); + + glm::vec2 pos {}; + TextureQuads out; + for (auto c = chars.data(); c <= &chars.back(); c = next_char(c)) { + if (isspace(*c)) { + pos.x += static_cast(size.y) / 4.F; + continue; + } + const auto & ch = charsData.at(get_codepoint(c)); + if (!ch.advance) { + continue; + } + + const auto charPos = pos + glm::vec2 {ch.bearing.x, ch.bearing.y - static_cast(ch.size.y)}; + const auto size = glm::vec2 {ch.size}; + + Quad q; + std::transform(C.begin(), C.end(), q.begin(), [&size, &charPos, &ch, this](const auto & c) { + return (charPos + (size * c.first)) + || ((glm::vec2 {ch.position} + (glm::vec2 {ch.size} * c.second)) / glm::vec2 {this->size}); + }); + out[fontTextures[ch.textureIdx].texture].emplace_back(q); + + pos.x += static_cast(ch.advance); + } + return out; +} diff --git a/ui/font.h b/ui/font.h new file mode 100644 index 0000000..c9d834a --- /dev/null +++ b/ui/font.h @@ -0,0 +1,48 @@ +#ifndef FONT_H +#define FONT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Font { +public: + Font(const char * const path, unsigned int height); + + using Quad = std::array; + using Quads = std::vector; + using TextureQuads = std::map; + TextureQuads render(const std::string_view text) const; + + struct CharData { + size_t textureIdx; + glm::uvec2 size; + glm::uvec2 position; + glm::ivec2 bearing; + long advance; + }; + struct FontTexture { + GLuint texture; + unsigned int used; + }; + + static glm::uvec3 getTextureSize(unsigned int height); + +protected: + void generateChars(const std::string_view text) const; + const CharData getChar(char) const; + std::size_t getTextureWithSpace(unsigned int adv) const; + + std::string path; + glm::uvec3 size; + mutable std::map charsData; + mutable std::vector fontTextures; +}; + +#endif diff --git a/ui/text.cpp b/ui/text.cpp new file mode 100644 index 0000000..be696c3 --- /dev/null +++ b/ui/text.cpp @@ -0,0 +1,59 @@ +#include "text.h" +#include "font.h" +#include "gfx/gl/uiShader.h" +#include "uiComponent.h" +#include +#include +#include +#include +#include +#include + +const auto font {"/usr/share/fonts/hack/Hack-Regular.ttf"}; +Text::Text(std::string_view s, Position pos, glm::vec3 c) : UIComponent {pos}, colour {c} +{ + for (const auto & textureQuads : Font {font, static_cast(pos.size.y)}.render(s)) { + auto & rendering + = models.emplace_back(textureQuads.first, static_cast(6 * textureQuads.second.size())); + glBindVertexArray(rendering.vao); + + glBindBuffer(GL_ARRAY_BUFFER, rendering.vbo); + std::vector vertices; + vertices.reserve(6 * textureQuads.second.size()); + for (const auto & quad : textureQuads.second) { + for (auto offset = 0U; offset < 3; offset += 2) { + for (auto vertex = 0U; vertex < 3; vertex += 1) { + vertices.emplace_back(quad[(vertex + offset) % 4] + glm::vec4 {position.origin, 0, 0}); + } + } + }; + glBufferData(GL_ARRAY_BUFFER, static_cast(sizeof(glm::vec4)) * rendering.count, + glm::value_ptr(vertices.front()), GL_STATIC_DRAW); + + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), nullptr); + + glBindVertexArray(0); + } +} + +void +Text::render(const UIShader & shader, const Position &) const +{ + shader.useText(colour); + for (const auto & m : models) { + glBindTexture(GL_TEXTURE_2D, m.texture); + glBindVertexArray(m.vao); + glDrawArrays(GL_TRIANGLES, 0, m.count); + } + glBindVertexArray(0); + glBindTexture(GL_TEXTURE_2D, 0); +} + +bool +Text::handleInput(const SDL_Event &, const Position &) +{ + return false; +} + +Text::Model::Model(GLuint t, GLsizei c) : texture {t}, count {c} { } diff --git a/ui/text.h b/ui/text.h new file mode 100644 index 0000000..81122de --- /dev/null +++ b/ui/text.h @@ -0,0 +1,31 @@ +#pragma once + +#include "uiComponent.h" +#include +#include +#include +#include +#include +#include + +class UIShader; +union SDL_Event; + +class Text : public UIComponent { +public: + Text(std::string_view s, Position, glm::vec3 colour); + + void render(const UIShader &, const Position & parentPos) const override; + bool handleInput(const SDL_Event &, const Position & parentPos) override; + +private: + struct Model { + Model(GLuint, GLsizei); + GLuint texture; + GLsizei count; + glVertexArray vao; + glBuffer vbo; + }; + std::vector models; + glm::vec3 colour; +}; diff --git a/ui/toolbar.cpp b/ui/toolbar.cpp index c8febce..ada97b0 100644 --- a/ui/toolbar.cpp +++ b/ui/toolbar.cpp @@ -1,4 +1,5 @@ #include "toolbar.h" +#include "gfx/gl/uiShader.h" #include "ui/iconButton.h" #include "ui/uiComponent.h" #include "uiComponentPlacer.h" @@ -17,6 +18,7 @@ Toolbar::Toolbar(const std::initializer_list & initInfo) : UIComponent void Toolbar::render(const UIShader & uiShader, const Position & parentPos) const { + uiShader.useDefault(); const auto absPos = this->position + parentPos; icons.apply(&UIComponent::render, uiShader, absPos); } diff --git a/ui/window.cpp b/ui/window.cpp index 13c7d95..6a263aa 100644 --- a/ui/window.cpp +++ b/ui/window.cpp @@ -13,6 +13,7 @@ SDL_GL_CreateContextAndGlewInit(SDL_Window * w) if (glewInit() != GLEW_OK) { throw std::runtime_error {"Glew failed to initialize!"}; } + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_BLEND); @@ -89,7 +90,6 @@ Window::refresh(const GameState * gameState) const void Window::render(const GameState *) const { - uiShader.use(); glDisable(GL_DEPTH_TEST); uiComponents.apply(&UIComponent::render, uiShader, UIComponent::Position {}); } -- cgit v1.2.3