summaryrefslogtreecommitdiff
path: root/ui/font.cpp
blob: ebd29d0528a9dd2b72618ec6b01c10d27c346064 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#include "font.h"
#include <algorithm>
#include <cctype>
#include <format>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "gl_traits.h"
#include <glRef.h>
#include <maths.h>
#include <optional>
#include <stdexcept>
#include <string>
#include <unicode.h>
#include <util.h>
#include <utility>

// IWYU pragma: no_forward_declare FT_LibraryRec_

namespace {
	std::string
	FT_Error_StringSafe(FT_Error err)
	{
		if (const auto errstr = FT_Error_String(err)) {
			return {errstr};
		}
		return std::format("Unknown FT error: {}", err);
	}

	template<auto Func, typename... Args>
	void
	FT_Check(Args &&... args)
	{
		if (const auto err = Func(std::forward<Args>(args)...)) {
			throw std::runtime_error {std::format("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_Library,
			[]() {
				FT_Library ft {};
				FT_Check<FT_Init_FreeType>(&ft);
				return ft;
			},
			FT_Done_FreeType>;

	using Face = glRef<FT_Face,
			[](FT_Library ft, const char * const name) {
				FT_Face face {};
				FT_Check<FT_New_Face>(ft, name, 0, &face);
				return face;
			},
			FT_Done_Face>;
}

Font::Font(std::filesystem::path p, unsigned s) : path {std::move(p)}, size {getTextureSize(s)}
{
	generateChars(BASIC_CHARS);
}

void
Font::generateChars(const utf8_string_view chars) const
{
	std::optional<FT> ft;
	std::optional<Face> face;

	for (auto codepoint : chars) {
		if (charsData.find(codepoint) == charsData.end()) {
			if (!ft) {
				ft.emplace();
				glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
			}
			if (!face) {
				face.emplace(*ft, path.c_str());
				FT_Set_Pixel_Sizes(*face, 0, size.z);
			}
			const 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<GLint>(texture.used), 0,
					static_cast<GLsizei>(glyph->bitmap.width), static_cast<GLsizei>(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<std::size_t>(itr - fontTextures.begin());
	}

	auto & texture = fontTextures.emplace_back();
	glBindTexture(GL_TEXTURE_2D, texture.texture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y), 0, GL_RED,
			GL_UNSIGNED_BYTE, nullptr);
	glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameter(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 utf8_string_view chars) const
{
	constexpr static const std::array<std::pair<glm::vec2, glm::vec2>, 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 codepoint : chars) {
		if (std::isspace(static_cast<int>(codepoint))) {
			pos.x += static_cast<float>(size.y) / 4.F;
			continue;
		}
		const auto & ch = charsData.at(codepoint);
		if (!ch.advance) {
			continue;
		}

		const auto charPos = pos + glm::vec2 {ch.bearing.x, ch.bearing.y - static_cast<int>(ch.size.y)};
		const auto chSize = glm::vec2 {ch.size};

		out[fontTextures[ch.textureIdx].texture].emplace_back(
				transform_array(C, [&chSize, &charPos, &ch, this](const auto & c) {
					return (charPos + (chSize * c.first))
							|| ((glm::vec2 {ch.position} + (glm::vec2 {ch.size} * c.second)) / glm::vec2 {this->size});
				}));

		pos.x += static_cast<float>(ch.advance);
	}
	return out;
}