FontCache: Use map for efficient glyph lookup
This patch updates CachedFont to now use an std::map for cached glyphs, instead of an std::vector. std::map allows O(log n) lookup, whereas std::vector only allows O(n) lookup. Note: std::unordered_map technically has better lookup complexity here, with amortized O(1) lookup. However, hashmaps have a higher inherent overhead than red-black trees so this would only be viable when going above around 100 entries, which should never happen here for ASCII glyphs.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <glad/glad.h>
|
||||
|
||||
@@ -26,7 +27,7 @@ public:
|
||||
|
||||
class JGL::CachedFont {
|
||||
private:
|
||||
std::vector<CachedGlyph*> glyphs{};
|
||||
std::map<char, CachedGlyph*> glyphs;
|
||||
GLuint texture = 0;
|
||||
GLsizei texture_width = 0, texture_height = 0;
|
||||
unsigned int font_size = 0;
|
||||
@@ -36,7 +37,7 @@ public:
|
||||
unsigned int getFontSize();
|
||||
unsigned int getFontIndex();
|
||||
CachedGlyph* getGlyph(char c);
|
||||
std::vector<CachedGlyph*> getGlyphs();
|
||||
std::map<char, CachedGlyph*> getGlyphs();
|
||||
const GLuint* getTexture();
|
||||
const GLsizei getTextureWidth() const;
|
||||
const GLsizei getTextureHeight() const;
|
||||
|
@@ -26,7 +26,7 @@ CachedGlyph::CachedGlyph(char c, std::array<GLfloat, 12> texcoords, float x2offs
|
||||
//Because most things shown would be english characters. We can cut down on the iteration time significantly
|
||||
//by putting each english character at the beginning of the list in order of how often they usually occur in text.
|
||||
void JGL::CachedFont::appendGlyph(JGL::CachedGlyph* glyph) {
|
||||
glyphs.push_back(glyph);
|
||||
glyphs.emplace(glyph->getCharacter(), glyph);
|
||||
}
|
||||
|
||||
unsigned int JGL::CachedFont::getFontSize() {
|
||||
@@ -38,9 +38,9 @@ unsigned int JGL::CachedFont::getFontIndex() {
|
||||
}
|
||||
|
||||
CachedGlyph* JGL::CachedFont::getGlyph(char c) {
|
||||
for (const auto& g : glyphs)
|
||||
if (c == g->getCharacter())
|
||||
return g;
|
||||
auto it = glyphs.find(c);
|
||||
if (it != glyphs.end())
|
||||
return it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ CachedFont::CachedFont(GLuint texture_id, GLsizei texture_width, GLsizei texture
|
||||
this->font_index = font_index;
|
||||
}
|
||||
|
||||
std::vector<CachedGlyph*> CachedFont::getGlyphs() {
|
||||
std::map<char, CachedGlyph*> CachedFont::getGlyphs() {
|
||||
return glyphs;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user