]> git.lizzy.rs Git - minetest.git/blob - src/client/fontengine.cpp
e537b756cf7bcea7866cb9fbe6cc0c05dcd03e74
[minetest.git] / src / client / fontengine.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2014 sapier <sapier at gmx dot net>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "fontengine.h"
21 #include <cmath>
22 #include "client/renderingengine.h"
23 #include "config.h"
24 #include "porting.h"
25 #include "filesys.h"
26 #include "gettext.h"
27
28 #if USE_FREETYPE
29 #include "irrlicht_changes/CGUITTFont.h"
30 #endif
31
32 /** maximum size distance for getting a "similar" font size */
33 #define MAX_FONT_SIZE_OFFSET 10
34
35 /** reference to access font engine, has to be initialized by main */
36 FontEngine* g_fontengine = NULL;
37
38 /** callback to be used on change of font size setting */
39 static void font_setting_changed(const std::string &name, void *userdata)
40 {
41         g_fontengine->readSettings();
42 }
43
44 /******************************************************************************/
45 FontEngine::FontEngine(gui::IGUIEnvironment* env) :
46         m_env(env)
47 {
48
49         for (u32 &i : m_default_size) {
50                 i = (FontMode) FONT_SIZE_UNSPECIFIED;
51         }
52
53         assert(g_settings != NULL); // pre-condition
54         assert(m_env != NULL); // pre-condition
55         assert(m_env->getSkin() != NULL); // pre-condition
56
57         readSettings();
58
59         if (m_currentMode != FM_Simple) {
60                 g_settings->registerChangedCallback("font_size", font_setting_changed, NULL);
61                 g_settings->registerChangedCallback("font_bold", font_setting_changed, NULL);
62                 g_settings->registerChangedCallback("font_italic", font_setting_changed, NULL);
63                 g_settings->registerChangedCallback("font_path", font_setting_changed, NULL);
64                 g_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL);
65                 g_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL);
66                 g_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL);
67                 g_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL);
68                 g_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL);
69                 g_settings->registerChangedCallback("font_size_divisible_by", font_setting_changed, NULL);
70                 g_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL);
71         }
72
73         g_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL);
74         g_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL);
75         g_settings->registerChangedCallback("mono_font_size_divisible_by", font_setting_changed, NULL);
76         g_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL);
77         g_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL);
78 }
79
80 /******************************************************************************/
81 FontEngine::~FontEngine()
82 {
83         cleanCache();
84 }
85
86 /******************************************************************************/
87 void FontEngine::cleanCache()
88 {
89         RecursiveMutexAutoLock l(m_font_mutex);
90
91         for (auto &font_cache_it : m_font_cache) {
92
93                 for (auto &font_it : font_cache_it) {
94                         font_it.second->drop();
95                         font_it.second = nullptr;
96                 }
97                 font_cache_it.clear();
98         }
99 }
100
101 /******************************************************************************/
102 irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec)
103 {
104         return getFont(spec, false);
105 }
106
107 irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec, bool may_fail)
108 {
109         if (spec.mode == FM_Unspecified) {
110                 spec.mode = m_currentMode;
111         } else if (m_currentMode == FM_Simple) {
112                 // Freetype disabled -> Force simple mode
113                 spec.mode = (spec.mode == FM_Mono ||
114                                 spec.mode == FM_SimpleMono) ?
115                                 FM_SimpleMono : FM_Simple;
116                 // Support for those could be added, but who cares?
117                 spec.bold = false;
118                 spec.italic = false;
119         } else if (spec.mode == _FM_Fallback) {
120                 // Fallback font doesn't support these either
121                 spec.bold = false;
122                 spec.italic = false;
123         }
124
125         // Fallback to default size
126         if (spec.size == FONT_SIZE_UNSPECIFIED)
127                 spec.size = m_default_size[spec.mode];
128
129         RecursiveMutexAutoLock l(m_font_mutex);
130
131         const auto &cache = m_font_cache[spec.getHash()];
132         auto it = cache.find(spec.size);
133         if (it != cache.end())
134                 return it->second;
135
136         // Font does not yet exist
137         gui::IGUIFont *font = nullptr;
138         if (spec.mode == FM_Simple || spec.mode == FM_SimpleMono)
139                 font = initSimpleFont(spec);
140         else
141                 font = initFont(spec);
142
143         if (!font && !may_fail) {
144                 errorstream << "Minetest cannot continue without a valid font. "
145                         "Please correct the 'font_path' setting or install the font "
146                         "file in the proper location." << std::endl;
147                 abort();
148         }
149
150         m_font_cache[spec.getHash()][spec.size] = font;
151
152         return font;
153 }
154
155 /******************************************************************************/
156 unsigned int FontEngine::getTextHeight(const FontSpec &spec)
157 {
158         gui::IGUIFont *font = getFont(spec);
159
160         return font->getDimension(L"Some unimportant example String").Height;
161 }
162
163 /******************************************************************************/
164 unsigned int FontEngine::getTextWidth(const std::wstring &text, const FontSpec &spec)
165 {
166         gui::IGUIFont *font = getFont(spec);
167
168         return font->getDimension(text.c_str()).Width;
169 }
170
171 /** get line height for a specific font (including empty room between lines) */
172 unsigned int FontEngine::getLineHeight(const FontSpec &spec)
173 {
174         gui::IGUIFont *font = getFont(spec);
175
176         return font->getDimension(L"Some unimportant example String").Height
177                         + font->getKerningHeight();
178 }
179
180 /******************************************************************************/
181 unsigned int FontEngine::getDefaultFontSize()
182 {
183         return m_default_size[m_currentMode];
184 }
185
186 unsigned int FontEngine::getFontSize(FontMode mode)
187 {
188         if (m_currentMode == FM_Simple) {
189                 if (mode == FM_Mono || mode == FM_SimpleMono)
190                         return m_default_size[FM_SimpleMono];
191                 else
192                         return m_default_size[FM_Simple];
193         }
194
195         if (mode == FM_Unspecified)
196                 return m_default_size[FM_Standard];
197
198         return m_default_size[mode];
199 }
200
201 /******************************************************************************/
202 void FontEngine::readSettings()
203 {
204         if (USE_FREETYPE && g_settings->getBool("freetype")) {
205                 m_default_size[FM_Standard]  = g_settings->getU16("font_size");
206                 m_default_size[_FM_Fallback] = g_settings->getU16("font_size");
207                 m_default_size[FM_Mono]      = g_settings->getU16("mono_font_size");
208
209                 m_default_bold = g_settings->getBool("font_bold");
210                 m_default_italic = g_settings->getBool("font_italic");
211
212         } else {
213                 m_currentMode = FM_Simple;
214         }
215
216         m_default_size[FM_Simple]       = g_settings->getU16("font_size");
217         m_default_size[FM_SimpleMono]   = g_settings->getU16("mono_font_size");
218
219         cleanCache();
220         updateFontCache();
221         updateSkin();
222 }
223
224 /******************************************************************************/
225 void FontEngine::updateSkin()
226 {
227         gui::IGUIFont *font = getFont();
228         assert(font);
229
230         m_env->getSkin()->setFont(font);
231 }
232
233 /******************************************************************************/
234 void FontEngine::updateFontCache()
235 {
236         /* the only font to be initialized is default one,
237          * all others are re-initialized on demand */
238         getFont(FONT_SIZE_UNSPECIFIED, FM_Unspecified);
239 }
240
241 /******************************************************************************/
242 gui::IGUIFont *FontEngine::initFont(const FontSpec &spec)
243 {
244         assert(spec.mode != FM_Unspecified);
245         assert(spec.size != FONT_SIZE_UNSPECIFIED);
246
247         std::string setting_prefix = "";
248         if (spec.mode == FM_Mono)
249                 setting_prefix = "mono_";
250
251         std::string setting_suffix = "";
252         if (spec.bold)
253                 setting_suffix.append("_bold");
254         if (spec.italic)
255                 setting_suffix.append("_italic");
256
257         u32 size = std::max<u32>(spec.size * RenderingEngine::getDisplayDensity() *
258                         g_settings->getFloat("gui_scaling"), 1);
259
260         // Constrain the font size to a certain multiple, if necessary
261         u16 divisible_by = g_settings->getU16(setting_prefix + "font_size_divisible_by");
262         if (divisible_by > 1) {
263                 size = std::max<u32>(
264                                 std::round((double)size / divisible_by) * divisible_by, divisible_by);
265         }
266
267         sanity_check(size != 0);
268
269         u16 font_shadow       = 0;
270         u16 font_shadow_alpha = 0;
271         g_settings->getU16NoEx(setting_prefix + "font_shadow", font_shadow);
272         g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha",
273                         font_shadow_alpha);
274
275         std::string path_setting;
276         if (spec.mode == _FM_Fallback)
277                 path_setting = "fallback_font_path";
278         else
279                 path_setting = setting_prefix + "font_path" + setting_suffix;
280
281         std::string fallback_settings[] = {
282                 g_settings->get(path_setting),
283                 Settings::getLayer(SL_DEFAULTS)->get(path_setting)
284         };
285
286 #if USE_FREETYPE
287         for (const std::string &font_path : fallback_settings) {
288                 gui::CGUITTFont *font = gui::CGUITTFont::createTTFont(m_env,
289                                 font_path.c_str(), size, true, true, font_shadow,
290                                 font_shadow_alpha);
291
292                 if (!font) {
293                         errorstream << "FontEngine: Cannot load '" << font_path <<
294                                 "'. Trying to fall back to another path." << std::endl;
295                         continue;
296                 }
297
298                 if (spec.mode != _FM_Fallback) {
299                         FontSpec spec2(spec);
300                         spec2.mode = _FM_Fallback;
301                         font->setFallback(getFont(spec2, true));
302                 }
303                 return font;
304         }
305 #else
306         errorstream << "FontEngine: Tried to load TTF font but Minetest was"
307                         " compiled without Freetype." << std::endl;
308 #endif
309         return nullptr;
310 }
311
312 /** initialize a font without freetype */
313 gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec)
314 {
315         assert(spec.mode == FM_Simple || spec.mode == FM_SimpleMono);
316         assert(spec.size != FONT_SIZE_UNSPECIFIED);
317
318         const std::string &font_path = g_settings->get(
319                         (spec.mode == FM_SimpleMono) ? "mono_font_path" : "font_path");
320
321         size_t pos_dot = font_path.find_last_of('.');
322         std::string basename = font_path, ending;
323         if (pos_dot != std::string::npos)
324                 ending = lowercase(font_path.substr(pos_dot));
325
326         if (ending == ".ttf") {
327                 errorstream << "FontEngine: Found font \"" << font_path
328                                 << "\" but freetype is not available." << std::endl;
329                 return nullptr;
330         }
331
332         if (ending == ".xml" || ending == ".png")
333                 basename = font_path.substr(0, pos_dot);
334
335         u32 size = std::floor(
336                         RenderingEngine::getDisplayDensity() *
337                         g_settings->getFloat("gui_scaling") *
338                         spec.size);
339
340         irr::gui::IGUIFont *font = nullptr;
341         std::string font_extensions[] = { ".png", ".xml" };
342
343         // Find nearest matching font scale
344         // Does a "zig-zag motion" (positibe/negative), from 0 to MAX_FONT_SIZE_OFFSET
345         for (s32 zoffset = 0; zoffset < MAX_FONT_SIZE_OFFSET * 2; zoffset++) {
346                 std::stringstream path;
347
348                 // LSB to sign
349                 s32 sign = (zoffset & 1) ? -1 : 1;
350                 s32 offset = zoffset >> 1;
351
352                 for (const std::string &ext : font_extensions) {
353                         path.str(""); // Clear
354                         path << basename << "_" << (size + offset * sign) << ext;
355
356                         if (!fs::PathExists(path.str()))
357                                 continue;
358
359                         font = m_env->getFont(path.str().c_str());
360
361                         if (font) {
362                                 verbosestream << "FontEngine: found font: " << path.str() << std::endl;
363                                 break;
364                         }
365                 }
366
367                 if (font)
368                         break;
369         }
370
371         // try name direct
372         if (font == NULL) {
373                 if (fs::PathExists(font_path)) {
374                         font = m_env->getFont(font_path.c_str());
375                         if (font)
376                                 verbosestream << "FontEngine: found font: " << font_path << std::endl;
377                 }
378         }
379
380         return font;
381 }