OpenTTD Source 20261112-master-gbcbec5e63f
freetypefontcache.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#ifdef WITH_FREETYPE
11
12#include "../stdafx.h"
13
14#include "../debug.h"
15#include "../fontcache.h"
17#include "../fileio_func.h"
18#include "../error_func.h"
19#include "../spritecache.h"
20#include "../zoom_func.h"
21#include "../../os/unix/font_unix.h"
22#include "truetypefontcache.h"
23
25
26#include <ft2build.h>
27#include FT_FREETYPE_H
28#include FT_GLYPH_H
29#include FT_TRUETYPE_TABLES_H
30
31#include "../safeguards.h"
32
35private:
36 FT_Face face;
37
38 void SetFontSize(int pixels);
39 const Sprite *InternalGetGlyph(GlyphID key, bool aa) override;
40
41public:
42 FreeTypeFontCache(FontSize fs, FT_Face face, int pixels);
43 ~FreeTypeFontCache() override;
44 void ClearFontCache() override;
45 GlyphID MapCharToGlyph(char32_t key, bool allow_fallback = true) override;
46 std::string GetFontName() override { return fmt::format("{}, {}", face->family_name, face->style_name); }
47 bool IsBuiltInFont() override { return false; }
48 const void *GetOSHandle() override { return &face; }
49};
50
58{
59 assert(face != nullptr);
60
61 this->SetFontSize(pixels);
62}
63
64void FreeTypeFontCache::SetFontSize(int pixels)
65{
66 if (pixels == 0) {
67 /* Try to determine a good height based on the minimal height recommended by the font. */
68 int scaled_height = ScaleGUITrad(FontCache::GetDefaultFontHeight(this->fs));
69 pixels = scaled_height;
70
71 TT_Header *head = (TT_Header *)FT_Get_Sfnt_Table(this->face, ft_sfnt_head);
72 if (head != nullptr) {
73 /* Font height is minimum height plus the difference between the default
74 * height for this font size and the small size. */
75 int diff = scaled_height - ScaleGUITrad(FontCache::GetDefaultFontHeight(FontSize::Small));
76 /* Clamp() is not used as scaled_height could be greater than MAX_FONT_SIZE, which is not permitted in Clamp(). */
77 pixels = std::min(std::max(std::min<int>(head->Lowest_Rec_PPEM, MAX_FONT_MIN_REC_SIZE) + diff, scaled_height), MAX_FONT_SIZE);
78 }
79 } else {
80 pixels = ScaleGUITrad(pixels);
81 }
82 this->used_size = pixels;
83
84 FT_Error err = FT_Set_Pixel_Sizes(this->face, 0, pixels);
85 if (err != FT_Err_Ok) {
86
87 /* Find nearest size to that requested */
88 FT_Bitmap_Size *bs = this->face->available_sizes;
89 int i = this->face->num_fixed_sizes;
90 if (i > 0) { // In pathetic cases one might get no fixed sizes at all.
91 int n = bs->height;
92 FT_Int chosen = 0;
93 for (; --i; bs++) {
94 if (abs(pixels - bs->height) >= abs(pixels - n)) continue;
95 n = bs->height;
96 chosen = this->face->num_fixed_sizes - i;
97 }
98
99 /* Don't use FT_Set_Pixel_Sizes here - it might give us another
100 * error, even though the size is available (FS#5885). */
101 err = FT_Select_Size(this->face, chosen);
102 }
103 }
104
105 if (err == FT_Err_Ok) {
106 this->ascender = this->face->size->metrics.ascender >> 6;
107 this->descender = this->face->size->metrics.descender >> 6;
108 this->height = this->ascender - this->descender;
109 } else {
110 /* Both FT_Set_Pixel_Sizes and FT_Select_Size failed. */
111 Debug(Facility::Fontcache, Severity::Critical, "Font size selection failed. Using FontCache defaults.");
112 }
113}
114
119{
120 FT_Done_Face(this->face);
121 this->face = nullptr;
122 this->ClearFontCache();
123}
124
129{
130 /* Font scaling might have changed, determine font size anew if it was automatically selected. */
131 if (this->face != nullptr) this->SetFontSize(this->req_size);
132
134}
135
136
137const Sprite *FreeTypeFontCache::InternalGetGlyph(GlyphID key, bool aa)
138{
139 FT_GlyphSlot slot = this->face->glyph;
140
141 FT_Load_Glyph(this->face, key, aa ? FT_LOAD_TARGET_NORMAL : FT_LOAD_TARGET_MONO);
142 FT_Render_Glyph(this->face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
143
144 /* Despite requesting a normal glyph, FreeType may have returned a bitmap */
145 aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
146
147 /* Add 1 scaled pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
148 uint shadow = (this->fs == FontSize::Normal) ? ScaleGUITrad(1) : 0;
149 uint width = std::max(1U, (uint)slot->bitmap.width + shadow);
150 uint height = std::max(1U, (uint)slot->bitmap.rows + shadow);
151
152 /* Limit glyph size to prevent overflows later on. */
153 if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) UserError("Font glyph is too large");
154
155 /* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
156 SpriteLoader::SpriteCollection spritecollection;
157 SpriteLoader::Sprite &sprite = spritecollection[ZoomLevel::Min];
158 sprite.AllocateData(ZoomLevel::Min, static_cast<size_t>(width) * height);
160 if (aa) sprite.colours.Set(SpriteComponent::Alpha);
161 sprite.width = width;
162 sprite.height = height;
163 sprite.x_offs = slot->bitmap_left;
164 sprite.y_offs = this->ascender - slot->bitmap_top;
165
166 /* Draw shadow for medium size */
167 if (this->fs == FontSize::Normal && !aa) {
168 for (uint y = 0; y < (uint)slot->bitmap.rows; y++) {
169 for (uint x = 0; x < (uint)slot->bitmap.width; x++) {
170 if (HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
171 sprite.data[shadow + x + (shadow + y) * sprite.width].m = SHADOW_COLOUR;
172 sprite.data[shadow + x + (shadow + y) * sprite.width].a = 0xFF;
173 }
174 }
175 }
176 }
177
178 for (uint y = 0; y < (uint)slot->bitmap.rows; y++) {
179 for (uint x = 0; x < (uint)slot->bitmap.width; x++) {
180 if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
181 sprite.data[x + y * sprite.width].m = FACE_COLOUR;
182 sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
183 }
184 }
185 }
186
187 UniquePtrSpriteAllocator allocator;
188 BlitterFactory::GetCurrentBlitter()->Encode(SpriteType::Font, spritecollection, allocator);
189
190 GlyphEntry new_glyph;
191 new_glyph.data = std::move(allocator.data);
192 new_glyph.width = slot->advance.x >> 6;
193
194 return this->SetGlyphPtr(key, std::move(new_glyph)).GetSprite();
195}
196
197
198GlyphID FreeTypeFontCache::MapCharToGlyph(char32_t key, bool allow_fallback)
199{
200 assert(IsPrintable(key));
201
202 FT_UInt glyph = FT_Get_Char_Index(this->face, key);
203
204 if (glyph == 0 && allow_fallback && key >= SCC_SPRITE_START && key <= SCC_SPRITE_END) {
205 return this->parent->MapCharToGlyph(key);
206 }
207
208 return glyph;
209}
210
211FT_Library _ft_library = nullptr;
212
213class FreeTypeFontCacheFactory : public FontCacheFactory {
214public:
215 FreeTypeFontCacheFactory() : FontCacheFactory("freetype", "FreeType font provider") {}
216
219 {
220 FT_Done_FreeType(_ft_library);
221 _ft_library = nullptr;
222 }
223
224 std::unique_ptr<FontCache> LoadFont(FontSize fs, FontType fonttype, bool search, const std::string &font_name, const std::any &os_handle) const override
225 {
226 if (fonttype != FontType::TrueType) return nullptr;
227
228 if (_ft_library == nullptr) {
229 if (FT_Init_FreeType(&_ft_library) != FT_Err_Ok) {
230 ShowInfo("Unable to initialize FreeType, using sprite fonts instead");
231 return nullptr;
232 }
233
235 }
236
237 FT_Face face = nullptr;
238
239 /* If font is an absolute path to a ttf, try loading that first. */
240 int32_t index = 0;
241 if (auto ptr = std::any_cast<int32_t>(&os_handle)) {
242 index = *ptr;
243 }
244 FT_Error error = FT_New_Face(_ft_library, font_name.c_str(), index, &face);
245
246 if (error != FT_Err_Ok) {
247 /* Check if font is a relative filename in one of our search-paths. */
248 std::string full_font = FioFindFullPath(Subdirectory::Base, font_name);
249 if (!full_font.empty()) {
250 error = FT_New_Face(_ft_library, full_font.c_str(), 0, &face);
251 }
252 }
253
254#ifdef WITH_FONTCONFIG
255 /* If allowed to search, try loading based on font face name (OS-wide fonts). */
256 if (error != FT_Err_Ok && search) error = GetFontByFaceName(font_name, &face);
257#endif /* WITH_FONTCONFIG */
258
259 if (error != FT_Err_Ok) {
260 FT_Done_Face(face);
261 return nullptr;
262 }
263
264 return LoadFont(fs, face, font_name, GetFontCacheFontSize(fs));
265 }
266
267 bool FindFallbackFont(const std::string &language_isocode, class MissingGlyphSearcher *callback) const override
268 {
269#ifdef WITH_FONTCONFIG
270 if (FontConfigFindFallbackFont(language_isocode, callback)) return true;
271#endif /* WITH_FONTCONFIG */
272
273 return false;
274 }
275
276private:
277 static std::unique_ptr<FontCache> LoadFont(FontSize fs, FT_Face face, std::string_view font_name, uint size)
278 {
279 Debug(Facility::Fontcache, Severity::Warning, "Requested '{}', using '{} {}'", font_name, face->family_name, face->style_name);
280
281 /* Attempt to select the unicode character map */
282 FT_Error error = FT_Select_Charmap(face, ft_encoding_unicode);
283 if (error == FT_Err_Invalid_CharMap_Handle) {
284 /* Try to pick a different character map instead. We default to
285 * the first map, but platform_id 0 encoding_id 0 should also
286 * be unicode (strange system...) */
287 FT_CharMap found = face->charmaps[0];
288
289 for (int i = 0; i < face->num_charmaps; ++i) {
290 FT_CharMap charmap = face->charmaps[i];
291 if (charmap->platform_id == 0 && charmap->encoding_id == 0) {
292 found = charmap;
293 }
294 }
295
296 if (found != nullptr) {
297 error = FT_Set_Charmap(face, found);
298 }
299 }
300
301 if (error != FT_Err_Ok) {
302 FT_Done_Face(face);
303
304 ShowInfo("Unable to use '{}' for {} font, FreeType reported error 0x{:X}, using sprite font instead", font_name, FontSizeToName(fs), error);
305 return nullptr;
306 }
307
308 return std::make_unique<FreeTypeFontCache>(fs, face, size);
309 }
310
311private:
312 static FreeTypeFontCacheFactory instance;
313};
314
315/* static */ FreeTypeFontCacheFactory FreeTypeFontCacheFactory::instance;
316
317#endif /* WITH_FREETYPE */
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr Timpl & Set()
Set all bits.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:139
int height
The height of the font.
Definition fontcache.h:28
std::unique_ptr< FontCache > parent
The parent of this font cache.
Definition fontcache.h:26
const FontSize fs
The size of the font.
Definition fontcache.h:27
int descender
The descender value of the font.
Definition fontcache.h:30
int ascender
The ascender value of the font.
Definition fontcache.h:29
std::unique_ptr< FontCache > LoadFont(FontSize fs, FontType fonttype, bool search, const std::string &font_name, const std::any &os_handle) const override
Try loading a font with this factory.
bool FindFallbackFont(const std::string &language_isocode, class MissingGlyphSearcher *callback) const override
We would like to have a fallback font as the current one doesn't contain all characters we need.
~FreeTypeFontCacheFactory() override
Close the freetype library.
const void * GetOSHandle() override
Get the native OS font handle, if there is one.
FreeTypeFontCache(FontSize fs, FT_Face face, int pixels)
Create a new FreeTypeFontCache.
const Sprite * InternalGetGlyph(GlyphID key, bool aa) override
Load the glyph as a sprite.
void ClearFontCache() override
Reset cached glyphs.
GlyphID MapCharToGlyph(char32_t key, bool allow_fallback=true) override
Map a character into a glyph.
FT_Face face
The font face associated with this font.
std::string GetFontName() override
Get the name of this font.
~FreeTypeFontCache() override
Free everything that was allocated for this font cache.
bool IsBuiltInFont() override
Is this a built-in sprite font?
A searcher for missing glyphs.
virtual Sprite * Encode(SpriteType sprite_type, const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)=0
Convert a sprite from the loader to our own format.
SpriteCollMap< Sprite > SpriteCollection
Type defining a collection of sprites, one for each zoom level.
static constexpr int MAX_GLYPH_DIM
Maximum glyph dimensions.
int used_size
Used font size.
int req_size
Requested font size.
void ClearFontCache() override
Reset cached glyphs.
static constexpr uint MAX_FONT_MIN_REC_SIZE
Upper limit for the recommended font size in case a font file contains nonsensical values.
TrueTypeFontCache(FontSize fs, int pixels)
Create a new TrueTypeFontCache.
SpriteAllocator that allocates memory via a unique_ptr array.
Definition spritecache.h:20
Control codes that are embedded in the translation strings.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Fontcache
Fontcache message facility.
Definition debug_type.h:37
@ Warning
Warning, wrong but okay if you don't know.
Definition debug_type.h:17
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
Error reporting related functions.
Factory to 'query' all available blitters.
std::string FioFindFullPath(Subdirectory subdir, std::string_view filename)
Find a path to the filename in one of the search directories.
Definition fileio.cpp:145
Functions for standard in/out file operations.
@ Base
Base directory for all subdirectories.
Definition fileio_type.h:88
FT_Error GetFontByFaceName(std::string_view font_name, FT_Face *face)
Load a freetype font face with the given font name.
Definition font_unix.cpp:70
bool FontConfigFindFallbackFont(const std::string &language_isocode, MissingGlyphSearcher *callback)
Use FontConfig to find a fallback font.
uint GetFontCacheFontSize(FontSize fs)
Get the scalable font size to use for a FontSize.
Functions to read fonts from files and cache them.
FontType
Different types of font that can be loaded.
Definition fontcache.h:231
@ TrueType
Scalable TrueType fonts.
Definition fontcache.h:233
@ Font
A sprite used for fonts.
Definition gfx_type.h:407
FontSize
Available font sizes.
Definition gfx_type.h:248
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
A number of safeguards to prevent using unsafe methods.
Functions to cache sprites in memory.
@ Palette
Sprite has palette data.
@ Alpha
Sprite has alpha.
Definition of base types and functions in a cross-platform compatible way.
uint8_t m
Remap-channel.
uint8_t a
Alpha-channel.
Structure for passing information from the sprite loader to the blitter.
SpriteComponents colours
The colour components of the sprite with useful information.
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
uint16_t width
Width of the sprite.
int16_t x_offs
The x-offset of where the sprite will be drawn.
SpriteLoader::CommonPixel * data
The sprite itself.
uint16_t height
Height of the sprite.
int16_t y_offs
The y-offset of where the sprite will be drawn.
Data structure describing a sprite.
Container for information about a glyph.
std::unique_ptr< std::byte[]> data
The loaded sprite.
uint8_t width
The width of the glyph.
Common base definition for font file based font caches.
static const int MAX_FONT_SIZE
Maximum font size.
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
Functions related to zooming.
@ Min
Minimum zoom level.
Definition zoom_type.h:23