-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfont_word_cache.cpp
354 lines (296 loc) · 9.73 KB
/
font_word_cache.cpp
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// SPDX-FileCopyrightText: Moritz Bruder <muesli4 at gmail dot com>
//
// SPDX-License-Identifier: LGPL-3.0-or-later
#include <algorithm>
#include "font_word_cache.hpp"
#include "utf8.hpp"
#include "sdl_util.hpp"
font_not_found::font_not_found(std::string msg)
: std::runtime_error("font not found: " + msg)
{
}
font_render_error::font_render_error(std::string msg)
: std::runtime_error("failed to render font: " + msg)
{
}
font_word_cache::font_word_cache(SDL_Renderer * renderer, font f)
: _renderer(renderer)
{
// load font and generate glyphs
_font = TTF_OpenFont(f.path.c_str(), f.size);
if (_font == nullptr)
throw font_not_found(TTF_GetError());
// cache join point metrics
TTF_GlyphMetrics(_font, ' ', &_space_minx, nullptr, nullptr, nullptr, &_space_advance);
}
font_word_cache::~font_word_cache()
{
TTF_CloseFont(_font);
clear();
}
font_word_cache::font_word_cache(font_word_cache && other)
: _renderer(other._renderer)
, _prerendered(std::move(other._prerendered))
, _font(other._font)
, _space_advance(other._space_advance)
, _space_minx(other._space_minx)
{
other._font = nullptr;
}
// http://stackoverflow.com/questions/18534494/convert-from-utf-8-to-unicode-c
#include <deque>
uint32_t utf8_to_ucs4(std::deque<uint8_t> coded)
{
int charcode = 0;
int t = coded.front();
coded.pop_front();
if (t < 128)
{
return t;
}
int high_bit_mask = (1 << 6) -1;
int high_bit_shift = 0;
int total_bits = 0;
const int other_bits = 6;
while((t & 0xC0) == 0xC0)
{
t <<= 1;
t &= 0xff;
total_bits += 6;
high_bit_mask >>= 1;
high_bit_shift++;
charcode <<= other_bits;
charcode |= coded.front() & ((1 << other_bits)-1);
coded.pop_front();
}
charcode |= ((t >> high_bit_shift) & high_bit_mask) << total_bits;
return charcode;
}
// get the last utf8 character from a string
uint32_t get_last_ucs4(std::string_view const s)
{
char const * ptr = s.data() + s.size() - 1;
if (*ptr == 0) ptr = " ";
std::deque<uint8_t> d;
while (is_utf8_following_byte(*ptr))
{
d.push_front(*ptr);
ptr--;
}
d.push_front(*ptr);
return utf8_to_ucs4(d);
}
uint32_t get_first_ucs4(std::string_view const s)
{
char const * ptr = s.data();
if (*ptr == 0) ptr = " ";
std::deque<uint8_t> d;
d.push_back(*ptr);
ptr++;
while (is_utf8_following_byte(*ptr))
{
d.push_back(*ptr);
ptr++;
}
return utf8_to_ucs4(d);
}
int font_word_cache::get_word_left_kerning(std::string_view const word)
{
return TTF_GetFontKerningSizeGlyphs(_font, get_last_ucs4(word), ' ');
}
int font_word_cache::get_word_right_kerning(std::string_view const word)
{
return TTF_GetFontKerningSizeGlyphs(_font, ' ', get_first_ucs4(word));
}
std::vector<word_fragment> split_words(std::string t)
{
std::vector<word_fragment> words;
std::size_t pos;
std::size_t last_pos = 0;
while ((pos = t.find(' ', last_pos)) != std::string::npos)
{
std::string const & w = t.substr(last_pos, pos - last_pos);
std::size_t num_spaces = 1;
while (pos + num_spaces < t.size())
{
if (t[pos + num_spaces] == ' ')
{
num_spaces++;
}
else
break;
}
words.push_back(word_fragment{ w, num_spaces - 1 });
last_pos = pos + num_spaces;
}
{
std::string const & w = t.substr(last_pos);
if (!w.empty())
words.push_back(word_fragment{ w, 0 });
}
return words;
}
vec font_word_cache::texture_dim_nullptr(shared_texture_ptr const & texture) const
{
if (texture == nullptr)
{
return { 0, font_line_skip() };
}
else
{
return texture_dim(texture.get());
}
}
template <typename BackInsertIt>
vec font_word_cache::compute_text_layout(std::string t, int max_line_width, BackInsertIt it)
{
vec target_size { 0, 0 };
auto word_fragments = split_words(t);
if (!word_fragments.empty())
{
int actual_max_width = 0;
auto first_texture = word(word_fragments[0].word);
vec const first_dim = texture_dim_nullptr(first_texture);
int const first_left_kerning = (word_fragments[0].extra_spaces > 0 ? get_word_left_kerning(word_fragments[0].word) : 0);
if (first_texture != nullptr)
{
*it = { first_texture, origin_rect(first_dim), { 0, 0 } };
++it;
}
int line_width = first_dim.w + first_left_kerning + word_fragments[0].extra_spaces * _space_advance;
int height = 0;
int prev_post_left_kerning = word_fragments[0].extra_spaces > 0 ? 0 : get_word_left_kerning(word_fragments[0].word);
for (std::size_t k = 1; k < word_fragments.size(); ++k)
{
auto const & current_wf = word_fragments[k];
auto current_texture = word(current_wf.word);
vec const current_dim = texture_dim_nullptr(current_texture);
int current_pre_left_kerning;
int current_post_left_kerning;
if (current_wf.extra_spaces > 0)
{
current_pre_left_kerning = get_word_left_kerning(current_wf.word);
current_post_left_kerning = 0;
}
else
{
current_pre_left_kerning = 0;
current_post_left_kerning = get_word_left_kerning(current_wf.word);
}
int const spacing = prev_post_left_kerning + _space_advance + get_word_right_kerning(current_wf.word);
int const next_line_width = line_width + spacing + current_dim.w + current_pre_left_kerning + current_wf.extra_spaces * _space_advance;
if (max_line_width == -1 || next_line_width <= max_line_width)
{
// word does fit
if (current_texture != nullptr)
{
*it = { current_texture, origin_rect(current_dim), { line_width + spacing, height } };
++it;
}
line_width = next_line_width;
}
else
{
// word does not fit, start a new line
actual_max_width = std::max(actual_max_width, line_width);
line_width = current_dim.w;
height += font_line_skip();
if (current_texture != nullptr)
{
*it = { current_texture, origin_rect(current_dim), { 0, height } };
}
}
prev_post_left_kerning = current_post_left_kerning;
}
target_size.w = std::max(actual_max_width, line_width);
target_size.h = height + font_line_skip();
}
return target_size;
}
std::tuple<vec, std::vector<copy_command>> font_word_cache::text(std::string t, int max_line_width)
{
std::vector<copy_command> copy_commands;
vec target_size = compute_text_layout(t, max_line_width, std::back_inserter(copy_commands));
return std::make_tuple(target_size, copy_commands);
}
// Not really an iterator but satisfies the use case.
struct null_iterator
{
struct assignment_dummy
{
assignment_dummy & operator=(copy_command const & t) { return *this; }
};
null_iterator & operator++() { return *this; }
assignment_dummy operator*() { return assignment_dummy(); };
};
vec font_word_cache::text_size(std::string t, int max_line_width)
{
return compute_text_layout(t, max_line_width, null_iterator());
}
int font_word_cache::text_minimum_width(std::string t)
{
int max_width = 0;
auto word_fragments = split_words(t);
for (auto wf : word_fragments)
{
max_width = std::max(max_width, texture_dim_nullptr(word(wf.word)).w + static_cast<int>(wf.extra_spaces) * _space_advance);
}
return max_width;
}
font_word_cache_entry::font_word_cache_entry(std::string word, SDL_Texture * texture)
: word(word)
, texture_ptr(texture, texture_destroyer())
{
}
shared_texture_ptr font_word_cache::word(std::string w)
{
auto & unique_hash_index = _prerendered.get<0>();
auto it = unique_hash_index.find(w);
if (it == unique_hash_index.end())
{
// protect against unsupported zero length
if (w.empty())
{
return nullptr;
}
else
{
// Render in white, then we can use the SDL_SetTextureColorMod to get
// any color.
SDL_Surface * s = TTF_RenderUTF8_Blended(_font, w.c_str(), {255, 255, 255});
if (s == nullptr)
throw font_render_error(TTF_GetError());
SDL_Texture * t = SDL_CreateTextureFromSurface(_renderer, s);
if (t == nullptr)
throw font_render_error(SDL_GetError());
// Use alpha blending to make use of the alpha channel.
if (SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND) < 0)
throw font_render_error(SDL_GetError());
if (_prerendered.size() > 40000)
{
auto & sequence_index = _prerendered.get<1>();
sequence_index.pop_front();
}
auto const & result = _prerendered.insert(font_word_cache_entry(w, t));
return result.first->texture_ptr;
}
}
else
{
auto & sequence_index = _prerendered.get<1>();
sequence_index.relocate(_prerendered.project<1>(it), sequence_index.end());
return it->texture_ptr;
}
}
unsigned int font_word_cache::font_height() const
{
return TTF_FontHeight(const_cast<TTF_Font *>(_font));
}
int font_word_cache::font_line_skip() const
{
return TTF_FontLineSkip(const_cast<TTF_Font *>(_font));
}
void font_word_cache::clear()
{
_prerendered.clear();
}