Debian Codegraph @

CorsixTH/Src/th_gfx_font.cpp

raw
1 /*
2 Copyright (c) 2010 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "th_gfx_font.h"
24
25 #include "config.h"
26
27 #include <ft2build.h> // IWYU pragma: keep
28 // IWYU pragma: no_include "freetype/config/ftheader.h"
29
30 #include "th_strings.h"
31 #include FT_FREETYPE_H
32 #include FT_ERRORS_H
33 #include FT_GLYPH_H
34 #include FT_IMAGE_H
35 #include FT_TYPES_H
36 #include <algorithm>
37 #include <cstring>
38 #include <map>
39 #include <utility>
40 #include <vector>
41
42 #include "th_gfx.h"
43
44 namespace {
45
46 constexpr unsigned int unicode_to_font_character(
47 unsigned int codepoint, bitmap_font_character_set charset) {
48 switch (charset) {
49 case bitmap_font_character_set::cp437:
50 return unicode_to_codepage_437(codepoint);
51 case bitmap_font_character_set::mik:
52 return unicode_to_codepage_mik(codepoint);
53 default:
54 return '?';
55 }
56 }
57
58 } // namespace
59
60 bitmap_font::bitmap_font() = default;
61
62 void bitmap_font::set_sprite_sheet(sprite_sheet* pSpriteSheet,
63 bitmap_font_character_set character_set) {
64 sheet = pSpriteSheet;
65 this->character_set = character_set;
66 }
67
68 void bitmap_font::set_separation(int iCharSep, int iLineSep) {
69 letter_spacing = iCharSep;
70 line_spacing = iLineSep;
71 }
72
73 void bitmap_font::set_scale_factor(int factor) { scale_factor = factor; }
74
75 text_layout bitmap_font::get_text_dimensions(const char* sMessage,
76 size_t iMessageLength,
77 int iMaxWidth) const {
78 return draw_text_wrapped(nullptr, sMessage, iMessageLength, 0, 0, iMaxWidth,
79 INT_MAX, 0);
80 }
81
82 void bitmap_font::draw_text(render_target* pCanvas, const char* sMessage,
83 size_t iMessageLength, int iX, int iY) const {
84 pCanvas->start_nonoverlapping_draws();
85 if (iMessageLength != 0 && sheet != nullptr) {
86 const unsigned int iFirstASCII = 31;
87 unsigned int iLastASCII =
88 static_cast<unsigned int>(sheet->get_sprite_count()) + iFirstASCII;
89 const char* sMessageEnd = sMessage + iMessageLength;
90 int scaled_letter_spacing = letter_spacing * scale_factor;
91
92 while (sMessage != sMessageEnd) {
93 unsigned int iChar = unicode_to_font_character(
94 next_utf8_codepoint(sMessage, sMessageEnd), character_set);
95 if (iFirstASCII <= iChar && iChar <= iLastASCII) {
96 iChar -= iFirstASCII;
97 int iWidth;
98 int iHeight;
99 sheet->draw_sprite(pCanvas, iChar, iX, iY, thdf_nearest, 0,
100 animation_effect::none, scale_factor);
101 sheet->get_sprite_size_unchecked(iChar, &iWidth, &iHeight);
102 iWidth *= scale_factor;
103 iHeight *= scale_factor;
104 iX += iWidth + scaled_letter_spacing;
105 }
106 }
107 }
108 pCanvas->finish_nonoverlapping_draws();
109 }
110
111 text_layout bitmap_font::draw_text_wrapped(render_target* pCanvas,
112 const char* sMessage,
113 size_t iMessageLength, int iX,
114 int iY, int iWidth, int iMaxRows,
115 int iSkipRows,
116 text_alignment eAlign) const {
117 text_layout oDrawArea = {};
118 int iSkippedRows = 0;
119 if (iMessageLength != 0 && sheet != nullptr) {
120 const unsigned int iFirstASCII = 31;
121 unsigned int iLastASCII =
122 static_cast<unsigned int>(sheet->get_sprite_count()) + iFirstASCII;
123 const char* sMessageEnd = sMessage + iMessageLength;
124
125 while (sMessage != sMessageEnd && oDrawArea.row_count < iMaxRows) {
126 const char* sBreakPosition = sMessageEnd;
127 const char* sLastGoodBreakPosition = sBreakPosition;
128 int scaled_letter_spacing = letter_spacing * scale_factor;
129 int scaled_line_spacing = line_spacing * scale_factor;
130 int iMsgWidth = -scaled_letter_spacing;
131 int iMsgBreakWidth = iMsgWidth;
132 int iTallest = 0;
133 const char* s;
134 bool foundNewLine = false;
135 unsigned int iNextChar = 0;
136
137 for (s = sMessage; s != sMessageEnd;) {
138 const char* sOld = s;
139 unsigned int iChar = unicode_to_font_character(
140 next_utf8_codepoint(s, sMessageEnd), character_set);
141 iNextChar = unicode_to_font_character(static_cast<unsigned char>(*s),
142 character_set);
143 if ((iChar == '\n' && iNextChar == '\n') ||
144 (iChar == '/' && iNextChar == '/')) {
145 foundNewLine = true;
146 iMsgBreakWidth = iMsgWidth;
147 sBreakPosition = sOld;
148 break;
149 }
150 int iCharWidth = 0;
151 int iCharHeight = 0;
152 if (iFirstASCII <= iChar && iChar <= iLastASCII) {
153 sheet->get_sprite_size_unchecked(iChar - iFirstASCII, &iCharWidth,
154 &iCharHeight);
155 iCharWidth *= scale_factor;
156 iCharHeight *= scale_factor;
157 }
158 iMsgWidth += scaled_letter_spacing + iCharWidth;
159 if (iChar == ' ') {
160 sLastGoodBreakPosition = sOld;
161 iMsgBreakWidth = iMsgWidth - iCharWidth;
162 }
163
164 if (iMsgWidth > iWidth) {
165 sBreakPosition = sLastGoodBreakPosition;
166 break;
167 }
168 if (iCharHeight > iTallest) iTallest = iCharHeight;
169 }
170
171 if (s == sMessageEnd) iMsgBreakWidth = iMsgWidth;
172 if (iMsgBreakWidth > oDrawArea.width) oDrawArea.width = iMsgBreakWidth;
173
174 if (iSkippedRows >= iSkipRows) {
175 if (pCanvas) {
176 int iXOffset = 0;
177 if (iMsgBreakWidth < iWidth)
178 iXOffset = (iWidth - iMsgBreakWidth) * static_cast<int>(eAlign) / 2;
179 draw_text(pCanvas, sMessage, sBreakPosition - sMessage, iX + iXOffset,
180 iY);
181 }
182 iY += static_cast<int>(iTallest) + scaled_line_spacing;
183 oDrawArea.end_x = iMsgWidth;
184 oDrawArea.row_count++;
185 if (foundNewLine) {
186 iY += static_cast<int>(iTallest) + scaled_line_spacing;
187 oDrawArea.row_count++;
188 }
189 } else {
190 iSkippedRows++;
191 if (foundNewLine) {
192 if (iSkippedRows == iSkipRows) {
193 iY += static_cast<int>(iTallest) + scaled_line_spacing;
194 oDrawArea.row_count++;
195 }
196 iSkippedRows++;
197 }
198 }
199 sMessage = sBreakPosition;
200 if (sMessage != sMessageEnd) {
201 next_utf8_codepoint(sMessage, sMessageEnd);
202 if (foundNewLine) {
203 next_utf8_codepoint(sMessage, sMessageEnd);
204 }
205 }
206 }
207 }
208 oDrawArea.end_x = iX + oDrawArea.end_x;
209 oDrawArea.end_y = iY;
210 return oDrawArea;
211 }
212
213 FT_Library freetype_font::freetype_library = nullptr;
214 int freetype_font::freetype_init_count = 0;
215
216 freetype_font::freetype_font() {
217 for (cached_text* pEntry = cache; pEntry != cache + (1 << cache_size_log2);
218 ++pEntry) {
219 pEntry->message = nullptr;
220 pEntry->message_length = 0;
221 pEntry->message_buffer_length = 0;
222 pEntry->alignment = text_alignment::left;
223 pEntry->width = 0;
224 pEntry->height = 0;
225 pEntry->widest_line_width = 0;
226 pEntry->last_x = 0;
227 pEntry->data = nullptr;
228 pEntry->is_valid = false;
229 pEntry->texture = nullptr;
230 }
231 }
232
233 freetype_font::~freetype_font() {
234 for (cached_text* pEntry = cache; pEntry != cache + (1 << cache_size_log2);
235 ++pEntry) {
236 delete[] pEntry->message;
237 delete[] pEntry->data;
238 free_texture(pEntry);
239 }
240 if (font_face != nullptr) FT_Done_Face(font_face);
241 if (is_done_freetype_init) {
242 if (--freetype_init_count == 0) {
243 FT_Done_FreeType(freetype_library);
244 freetype_library = nullptr;
245 }
246 }
247 }
248
249 const char* freetype_font::get_copyright_notice() {
250 return "Portions of this software are copyright \xC2\xA9 2010 "
251 "The FreeType Project (www.freetype.org). All rights reserved.";
252 }
253
254 FT_Error freetype_font::initialise() {
255 if (is_done_freetype_init) return FT_Err_Ok;
256 if (freetype_init_count == 0) {
257 int iError = FT_Init_FreeType(&freetype_library);
258 if (iError != FT_Err_Ok) return iError;
259 }
260 ++freetype_init_count;
261 is_done_freetype_init = true;
262 return FT_Err_Ok;
263 }
264
265 void freetype_font::clear_cache() {
266 for (cached_text* pEntry = cache; pEntry != cache + (1 << cache_size_log2);
267 ++pEntry) {
268 pEntry->is_valid = false;
269 free_texture(pEntry);
270 }
271 }
272
273 FT_Error freetype_font::set_face(const uint8_t* pData, size_t iLength) {
274 int iError;
275 if (freetype_library == nullptr) {
276 iError = initialise();
277 if (iError != FT_Err_Ok) return iError;
278 }
279 if (font_face) {
280 iError = FT_Done_Face(font_face);
281 if (iError != FT_Err_Ok) return iError;
282 font_face = nullptr;
283 }
284 iError = FT_New_Memory_Face(freetype_library, pData,
285 static_cast<FT_Long>(iLength), 0, &font_face);
286 return iError;
287 }
288
289 FT_Error freetype_font::match_bitmap_font(sprite_sheet* font_spritesheet,
290 argb_colour* color, int* width,
291 int* height) {
292 if (font_spritesheet == nullptr) return FT_Err_Invalid_Argument;
293
294 // Try to take the size and colour of a standard character (em is generally
295 // the standard font character, but for fonts which only have numbers, zero
296 // seems like the next best choice).
297 for (const char* sCharToTry = "M0"; *sCharToTry; ++sCharToTry) {
298 unsigned int iSprite = *sCharToTry - 31;
299 if (font_spritesheet->get_sprite_size(iSprite, width, height) &&
300 font_spritesheet->get_sprite_average_colour(iSprite, color) &&
301 *width > 1 && *height > 1) {
302 return FT_Err_Ok;
303 }
304 }
305
306 // Take the average size of all characters, and the colour of one of them.
307 int iWidthSum = 0;
308 int iHeightSum = 0;
309 int iAverageNum = 0;
310 for (size_t i = 0; i < font_spritesheet->get_sprite_count(); ++i) {
311 int iWidth;
312 int iHeight;
313 font_spritesheet->get_sprite_size_unchecked(i, &iWidth, &iHeight);
314 if (iWidth <= 1 || iHeight <= 1) continue;
315 if (!font_spritesheet->get_sprite_average_colour(i, color)) continue;
316 iWidthSum += *width;
317 iHeightSum += *height;
318 ++iAverageNum;
319 }
320 if (iAverageNum == 0) return FT_Err_Divide_By_Zero;
321
322 *width = (iWidthSum + iAverageNum / 2) / iAverageNum;
323 *height = (iHeightSum + iAverageNum / 2) / iAverageNum;
324 return FT_Err_Ok;
325 }
326
327 FT_Error freetype_font::set_ideal_character_size(int iWidth, int iHeight) {
328 if (font_face == nullptr) return FT_Err_Invalid_Face_Handle;
329
330 if (is_monochrome() || iHeight <= 14 || iWidth <= 9) {
331 // Look for a bitmap strike of a similar size
332 int iBestBitmapScore = 50;
333 FT_Int iBestBitmapIndex = -1;
334 for (FT_Int i = 0; i < font_face->num_fixed_sizes; ++i) {
335 if (font_face->available_sizes[i].height > iHeight) continue;
336 int iDeltaH = iHeight - font_face->available_sizes[i].height;
337 int iDeltaW = font_face->available_sizes[i].width - iWidth;
338 int iScore = iDeltaH * iDeltaH * 3 + iDeltaW * iDeltaW;
339 if (iScore < iBestBitmapScore) {
340 iBestBitmapScore = iScore;
341 iBestBitmapIndex = i;
342 }
343 }
344
345 // Select the bitmap strike, if there was one
346 if (iBestBitmapIndex != -1)
347 return FT_Select_Size(font_face, iBestBitmapIndex);
348 }
349
350 // Go with the original size request if there was no bitmap strike, unless
351 // the size was very small, in which case scale things up, as vector fonts
352 // look rather poor at small sizes.
353 if (iHeight < 14) {
354 iWidth = iWidth * 14 / iHeight;
355 iHeight = 14;
356 }
357 if (iWidth < 9) {
358 iHeight = iHeight * 9 / iWidth;
359 iWidth = 9;
360 }
361 return FT_Set_Pixel_Sizes(font_face, iWidth, iHeight);
362 }
363
364 void freetype_font::set_font_color(argb_colour color) { font_color = color; }
365
366 void freetype_font::set_shadow_options(const font_shadow_options& options) {
367 shadow_opts = options;
368 }
369
370 text_layout freetype_font::get_text_dimensions(const char* sMessage,
371 size_t iMessageLength,
372 int iMaxWidth) const {
373 return draw_text_wrapped(nullptr, sMessage, iMessageLength, 0, 0, iMaxWidth,
374 INT_MAX, 0);
375 }
376
377 void freetype_font::draw_text(render_target* pCanvas, const char* sMessage,
378 size_t iMessageLength, int iX, int iY) const {
379 draw_text_wrapped(pCanvas, sMessage, iMessageLength, iX, iY, INT_MAX);
380 }
381
382 namespace {
383
384 struct codepoint_glyph {
385 FT_Glyph_Metrics metrics;
386 FT_Glyph glyph;
387 FT_UInt index;
388 };
389
390 enum class CJK_breakable { nonbreakable = 0, break_after, break_before };
391
392 // Determine if the character code is a suitable Chinese/Japanese/Korean
393 // character for a line break.
394 CJK_breakable isCjkBreakCharacter(unsigned int charcode) {
395 if (charcode == ideographic_space_codepoint ||
396 charcode == 0x3001 || // Ideographic comma
397 charcode == 0x3002 || // Ideographic full stop
398 charcode == 0x301e || // Double prime quotation mark
399 charcode == 0xff09 || // Fullwidth right parenthesis
400 charcode == 0xff0c || // Fullwidth comma
401 charcode == 0xff0d || // Fullwidth hyphen-minus
402 charcode == 0xff1a || // Fullwidth Colon
403 charcode == 0xff1b || // Fullwidth semicolon
404 charcode == 0xff1f) // Fullwidth question mark
405 return CJK_breakable::break_after;
406 if (charcode == 0x301d || // Reversed double prime quotation mark
407 charcode == 0xff08) // Fullwidth left parenthesis
408 return CJK_breakable::break_before;
409 return CJK_breakable::nonbreakable;
410 }
411
412 FT_Pos pixel_align(FT_Pos position) { return ((position + 63) >> 6) << 6; }
413
414 } // namespace
415
416 text_layout freetype_font::draw_text_wrapped(render_target* pCanvas,
417 const char* sMessage,
418 size_t iMessageLength, int iX,
419 int iY, int iWidth, int iMaxRows,
420 int iSkipRows,
421 text_alignment eAlign) const {
422 text_layout oDrawArea = {};
423 int iNumRows = 0;
424 int iHandledRows = 0;
425
426 if (!sMessage || sMessage[0] == '\0') {
427 return oDrawArea;
428 }
429
430 // Calculate an index into the cache to use for this piece of text.
431 size_t iHash = iMessageLength +
432 (static_cast<size_t>(iMaxRows) << (cache_size_log2 / 8)) +
433 (static_cast<size_t>(iSkipRows) << (cache_size_log2 / 4)) +
434 (static_cast<size_t>(iWidth) << (cache_size_log2 / 2)) +
435 (static_cast<size_t>(eAlign) << cache_size_log2);
436 for (size_t i = 0; i < iMessageLength; ++i)
437 iHash ^= (iHash << 5) + (iHash >> 2) + static_cast<size_t>(sMessage[i]);
438 iHash &= (1 << cache_size_log2) - 1;
439
440 cached_text* pEntry = cache + iHash;
441 if (pEntry->message_length != iMessageLength || pEntry->width > iWidth ||
442 (iWidth != INT_MAX && pEntry->width < iWidth) ||
443 pEntry->alignment != eAlign || !pEntry->is_valid ||
444 std::memcmp(pEntry->message, sMessage, iMessageLength) != 0) {
445 // Cache entry does not match the message being drawn, so discard the
446 // cache entry.
447 free_texture(pEntry);
448 delete[] pEntry->data;
449 pEntry->data = nullptr;
450 pEntry->is_valid = false;
451
452 int width_before_shadow = iWidth;
453 if (iWidth < INT_MAX && shadow_opts.enabled) {
454 width_before_shadow -= abs(shadow_opts.offset_x);
455 }
456
457 // Set the entry metadata to that of the new message.
458 if (iMessageLength > pEntry->message_buffer_length) {
459 delete[] pEntry->message;
460 pEntry->message = new char[iMessageLength];
461 pEntry->message_buffer_length = iMessageLength;
462 }
463 std::memcpy(pEntry->message, sMessage, iMessageLength);
464 pEntry->message_length = iMessageLength;
465 pEntry->width = iWidth;
466 pEntry->alignment = eAlign;
467
468 // Split the message into lines, and determine the position within the
469 // line for each character.
470 std::vector<std::pair<const char*, const char*> > vLines;
471 std::vector<FT_Vector> vCharPositions(iMessageLength);
472 std::map<unsigned int, codepoint_glyph> mapGlyphs;
473 vLines.reserve(2);
474
475 FT_Vector ftvPen = {0, 0};
476 FT_Bool bUseKerning = FT_HAS_KERNING(font_face);
477 FT_UInt iPreviousGlyphIndex = 0;
478
479 const char* sMessageStart = sMessage;
480 const char* sMessageEnd = sMessage + iMessageLength;
481 const char* sLineStart = sMessageStart;
482 const char* sLineBreakPosition = sLineStart;
483
484 while (sMessage != sMessageEnd) {
485 const char* sOldMessage = sMessage;
486 unsigned int iCode = next_utf8_codepoint(sMessage, sMessageEnd);
487 unsigned int iNextCode =
488 *reinterpret_cast<const unsigned char*>(sMessage);
489 bool bIsNewLine = (iCode == '\n' && iNextCode == '\n') ||
490 (iCode == '/' && iNextCode == '/');
491 // Just replace single line breaks with space.
492 if (!bIsNewLine && iCode == '\n') {
493 iCode = ' ';
494 }
495
496 codepoint_glyph& oGlyph = mapGlyphs[iCode];
497 if (oGlyph.glyph == nullptr) {
498 oGlyph.index = FT_Get_Char_Index(font_face, iCode);
499
500 /* FT_Error iError = */
501 FT_Load_Glyph(font_face, oGlyph.index, FT_LOAD_DEFAULT);
502 // TODO: iError != FT_Err_Ok
503
504 /* iError = */
505 FT_Get_Glyph(font_face->glyph, &oGlyph.glyph);
506 // TODO: iError != FT_Err_Ok
507
508 oGlyph.metrics = font_face->glyph->metrics;
509 }
510
511 // Apply kerning
512 if (bUseKerning && iPreviousGlyphIndex && oGlyph.index) {
513 FT_Vector ftvKerning;
514 FT_Get_Kerning(font_face, iPreviousGlyphIndex, oGlyph.index,
515 FT_KERNING_DEFAULT, &ftvKerning);
516 ftvPen.x += ftvKerning.x;
517 ftvPen.y += ftvKerning.y;
518 }
519
520 // Make an automatic line break if one is needed.
521 long line_width_with_glyph =
522 (ftvPen.x + oGlyph.metrics.horiBearingX + oGlyph.metrics.width + 63) /
523 64;
524 if (line_width_with_glyph >= width_before_shadow || bIsNewLine) {
525 if (bIsNewLine) {
526 sLineBreakPosition = sOldMessage;
527 }
528 ftvPen.x = ftvPen.y = 0;
529 iPreviousGlyphIndex = 0;
530 if (sLineStart != sLineBreakPosition) {
531 // Only really save if we have skipped enough lines
532 if (iHandledRows >= iSkipRows) {
533 vLines.push_back(std::make_pair(sLineStart, sLineBreakPosition));
534 }
535 if (bIsNewLine) {
536 if (iHandledRows + 1 >= iSkipRows) {
537 vLines.push_back(
538 std::make_pair(sLineBreakPosition, sLineBreakPosition));
539 }
540 // skip // or \n\n
541 next_utf8_codepoint(sLineBreakPosition, sMessageEnd);
542 next_utf8_codepoint(sLineBreakPosition, sMessageEnd);
543 iHandledRows++;
544 }
545 sMessage = sLineStart = sLineBreakPosition;
546 // Skip leading white space on a line
547 skip_utf8_whitespace(sMessage, sMessageEnd);
548 } else {
549 if (iHandledRows >= iSkipRows) {
550 vLines.push_back(std::make_pair(sLineStart, sOldMessage));
551 }
552 if (bIsNewLine) {
553 // skip // or \n\n
554 next_utf8_codepoint(sMessage, sMessageEnd);
555 next_utf8_codepoint(sMessage, sMessageEnd);
556 sLineStart = sLineBreakPosition = sMessage;
557 } else {
558 sMessage = sLineStart = sLineBreakPosition = sOldMessage;
559 }
560 }
561 iHandledRows++;
562 continue;
563 }
564
565 // Determine if a line can be broken at the current position.
566 if (iCode == ' ') {
567 sLineBreakPosition = sOldMessage;
568 } else {
569 switch (isCjkBreakCharacter(iCode)) {
570 case CJK_breakable::break_after:
571 // break after this codepoint (cjk codepoints are 3 bytes in
572 // utf-8)
573 sLineBreakPosition = sOldMessage + 3;
574 break;
575 case CJK_breakable::break_before:
576 // break before this codepoint
577 sLineBreakPosition = sOldMessage;
578 break;
579 default:
580 break;
581 }
582 }
583
584 // Save (unless we are skipping lines) and advance the pen.
585 if (iHandledRows >= iSkipRows) {
586 vCharPositions[sOldMessage - sMessageStart] = ftvPen;
587 }
588
589 iPreviousGlyphIndex = oGlyph.index;
590 ftvPen.x += oGlyph.metrics.horiAdvance;
591 }
592 if (sLineStart != sMessageEnd)
593 vLines.push_back(std::make_pair(sLineStart, sMessageEnd));
594 sMessage = sMessageStart;
595
596 // Finalise the position of each character (alignment might change X,
597 // and baseline / lines will change Y), and calculate overall height
598 // and widest line.
599 FT_Pos iPriorLinesHeight = 0;
600 FT_Pos iLineWidth = 0, iAlignDelta = 0, iWidestLine = 0;
601 const FT_Pos iLineSpacing = 2 << 6;
602 codepoint_glyph& oGlyph = mapGlyphs['l'];
603 FT_Pos iBearingY = oGlyph.metrics.horiBearingY;
604 FT_Pos iNormalLineHeight = oGlyph.metrics.height - iBearingY;
605
606 iBearingY = pixel_align(iBearingY);
607 iNormalLineHeight += iBearingY;
608 iNormalLineHeight += iLineSpacing;
609
610 iNormalLineHeight = pixel_align(iNormalLineHeight);
611
612 for (auto itr = vLines.begin(); itr != vLines.end() && iNumRows < iMaxRows;
613 ++itr) {
614 // Calculate the X change resulting from alignment.
615 const char* sLastChar = previous_utf8_codepoint(itr->second);
616 codepoint_glyph& oLastGlyph =
617 mapGlyphs[decode_utf8(sLastChar, sMessageEnd)];
618 iLineWidth = vCharPositions[sLastChar - sMessage].x +
619 oLastGlyph.metrics.horiBearingX + oLastGlyph.metrics.width;
620 if ((iLineWidth >> 6) < iWidth && eAlign != text_alignment::left) {
621 iAlignDelta =
622 ((iWidth * 64 - iLineWidth) * static_cast<int>(eAlign)) / 2;
623 }
624 if (iLineWidth > iWidestLine) iWidestLine = iLineWidth;
625
626 // Calculate the line height and baseline position.
627 FT_Pos iLineHeight = 0;
628 FT_Pos iBaselinePos = 0;
629 for (const char* s = itr->first; s < itr->second;) {
630 codepoint_glyph& oGlyph =
631 mapGlyphs[next_utf8_codepoint(s, sMessageEnd)];
632 FT_Pos iBearingY = oGlyph.metrics.horiBearingY;
633 FT_Pos iCoBearingY = oGlyph.metrics.height - iBearingY;
634 if (iBearingY > iBaselinePos) iBaselinePos = iBearingY;
635 if (iCoBearingY > iLineHeight) iLineHeight = iCoBearingY;
636 }
637
638 iBaselinePos = pixel_align(iBaselinePos);
639 iLineHeight += iBaselinePos;
640 iLineHeight += iLineSpacing;
641 iLineHeight = pixel_align(iLineHeight);
642
643 iNormalLineHeight = std::max(iNormalLineHeight, iLineHeight);
644
645 // Apply the character position changes.
646 for (const char* s = itr->first; s < itr->second;
647 next_utf8_codepoint(s, sMessageEnd)) {
648 FT_Vector& ftvPos = vCharPositions[s - sMessage];
649 ftvPos.x += iAlignDelta;
650 ftvPos.y += iBaselinePos + iPriorLinesHeight;
651 }
652 // Empty lines is a special case
653 if (itr->first == itr->second) {
654 iPriorLinesHeight += iNormalLineHeight;
655 } else {
656 iPriorLinesHeight += iLineHeight;
657 }
658 iNumRows++;
659 }
660 if (iPriorLinesHeight > 0) iPriorLinesHeight -= iLineSpacing;
661 pEntry->height = static_cast<int>(1 + (iPriorLinesHeight >> 6));
662 pEntry->widest_line_width = static_cast<int>(1 + (iWidestLine >> 6));
663 if (shadow_opts.enabled) {
664 pEntry->widest_line_width += std::abs(shadow_opts.offset_x);
665 pEntry->height += std::abs(shadow_opts.offset_y);
666 }
667 if (iWidth == INT_MAX) pEntry->width = pEntry->widest_line_width;
668 pEntry->row_count = iNumRows;
669 pEntry->last_x = 1 + (static_cast<int>(iLineWidth + iAlignDelta) >> 6);
670
671 // Get a bitmap for each glyph.
672 bool bIsMonochrome = is_monochrome();
673 FT_Render_Mode eRenderMode =
674 bIsMonochrome ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL;
675 for (auto itr = mapGlyphs.begin(), itrEnd = mapGlyphs.end(); itr != itrEnd;
676 ++itr) {
677 FT_Glyph_To_Bitmap(&itr->second.glyph, eRenderMode, nullptr, 1);
678 }
679
680 // Prepare a canvas for rendering.
681 pEntry->data = new uint8_t[pEntry->width * pEntry->height];
682 std::memset(pEntry->data, 0, pEntry->width * pEntry->height);
683
684 int iDrawnLines = 0;
685 // Render each character to the canvas.
686 for (auto itr = vLines.begin();
687 itr != vLines.end() && iDrawnLines < iMaxRows + iSkipRows; ++itr) {
688 iDrawnLines++;
689 for (const char* s = itr->first; s < itr->second;) {
690 FT_Vector& ftvPos = vCharPositions[s - sMessage];
691 unsigned int iCode = next_utf8_codepoint(s, sMessageEnd);
692 if (iCode == '\n') {
693 iCode = ' ';
694 }
695 FT_BitmapGlyph pGlyph =
696 reinterpret_cast<FT_BitmapGlyph>(mapGlyphs[iCode].glyph);
697 FT_Pos x = pGlyph->left + (ftvPos.x >> 6);
698 FT_Pos y = (ftvPos.y >> 6) - pGlyph->top;
699 // We may have asked for grayscale but been given monochrome,
700 // hence use the bitmap's pixel_mode rather than bIsMonochrome.
701 switch (pGlyph->bitmap.pixel_mode) {
702 case FT_PIXEL_MODE_GRAY:
703 render_gray(pEntry, &pGlyph->bitmap, x, y);
704 break;
705 case FT_PIXEL_MODE_MONO:
706 render_mono(pEntry, &pGlyph->bitmap, x, y);
707 break;
708 }
709 }
710 }
711
712 // Free all glyphs.
713 for (auto itr = mapGlyphs.begin(); itr != mapGlyphs.end(); ++itr) {
714 FT_Done_Glyph(itr->second.glyph);
715 }
716
717 pEntry->is_valid = true;
718 }
719
720 if (pCanvas != nullptr) {
721 if (pEntry->texture == nullptr) {
722 make_texture(pCanvas, pEntry);
723 }
724 draw_texture(pCanvas, pEntry, iX, iY);
725 }
726 oDrawArea.width = pEntry->widest_line_width;
727 oDrawArea.end_x = iX + pEntry->last_x;
728 oDrawArea.end_y = iY + pEntry->height;
729 oDrawArea.row_count = pEntry->row_count;
730 return oDrawArea;
731 }
732
733 // In theory, the renderers should only be invoked with coordinates which end
734 // up within the canvas being rendered to. In practice, this might not happen,
735 // at which point the following line can be removed.
736 // #define TRUST_RENDER_COORDS
737
738 void freetype_font::render_mono(cached_text* pCacheEntry, FT_Bitmap* pBitmap,
739 FT_Pos x, FT_Pos y) const {
740 uint8_t* pOutRow = pCacheEntry->data + y * pCacheEntry->width + x;
741 uint8_t* pInRow = pBitmap->buffer;
742 int rows = static_cast<int>(pBitmap->rows);
743 int width = static_cast<int>(pBitmap->width);
744 for (int iY = 0; iY < rows;
745 ++iY, pOutRow += pCacheEntry->width, pInRow += pBitmap->pitch) {
746 #ifndef TRUST_RENDER_COORDS
747 if (y + iY < 0) continue;
748 if (y + iY >= pCacheEntry->height) break;
749 #endif
750 uint8_t *pIn = pInRow, *pOut = pOutRow;
751 uint8_t iMask = 0x80;
752 for (int iX = 0; iX < width; ++iX, ++pOut) {
753 #ifndef TRUST_RENDER_COORDS
754 if (x + iX < 0) continue;
755 if (x + iX >= pCacheEntry->width) break;
756 #endif
757 if (*pIn & iMask) *pOut = 0xFF;
758 iMask = static_cast<uint8_t>(iMask / 2);
759 if (iMask == 0) {
760 iMask = 0x80;
761 ++pIn;
762 }
763 }
764 }
765 }
766
767 void freetype_font::render_gray(cached_text* pCacheEntry, FT_Bitmap* pBitmap,
768 FT_Pos x, FT_Pos y) const {
769 uint8_t* pOutRow = pCacheEntry->data + y * pCacheEntry->width + x;
770 uint8_t* pInRow = pBitmap->buffer;
771 int rows = static_cast<int>(pBitmap->rows);
772 int width = static_cast<int>(pBitmap->width);
773 for (int iY = 0; iY < rows;
774 ++iY, pOutRow += pCacheEntry->width, pInRow += pBitmap->pitch) {
775 #ifndef TRUST_RENDER_COORDS
776 if (y + iY < 0) continue;
777 if (y + iY >= pCacheEntry->height) break;
778 #endif
779 uint8_t *pIn = pInRow, *pOut = pOutRow;
780 for (int iX = 0; iX < width; ++iX, ++pIn, ++pOut) {
781 #ifndef TRUST_RENDER_COORDS
782 if (x + iX < 0) continue;
783 if (x + iX >= pCacheEntry->width) break;
784 #endif
785 unsigned int iIn = *pIn;
786 unsigned int iOut = *pOut;
787 uint8_t cMerged = static_cast<uint8_t>(iIn + iOut - (iIn * iOut) / 255);
788 *pOut = cMerged;
789 }
790 }
791 }