]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/fontengine.cpp
35e908b0cc66f44027b7eaeea49a7d71b886fc77
[dragonfireclient.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("fallback_font_path", font_setting_changed, NULL);
70         }
71
72         g_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL);
73         g_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL);
74         g_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL);
75         g_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL);
76 }
77
78 /******************************************************************************/
79 FontEngine::~FontEngine()
80 {
81         cleanCache();
82 }
83
84 /******************************************************************************/
85 void FontEngine::cleanCache()
86 {
87         RecursiveMutexAutoLock l(m_font_mutex);
88
89         for (auto &font_cache_it : m_font_cache) {
90
91                 for (auto &font_it : font_cache_it) {
92                         font_it.second->drop();
93                         font_it.second = nullptr;
94                 }
95                 font_cache_it.clear();
96         }
97 }
98
99 /******************************************************************************/
100 irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec)
101 {
102         return getFont(spec, false);
103 }
104
105 irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec, bool may_fail)
106 {
107         if (spec.mode == FM_Unspecified) {
108                 spec.mode = m_currentMode;
109         } else if (m_currentMode == FM_Simple) {
110                 // Freetype disabled -> Force simple mode
111                 spec.mode = (spec.mode == FM_Mono ||
112                                 spec.mode == FM_SimpleMono) ?
113                                 FM_SimpleMono : FM_Simple;
114                 // Support for those could be added, but who cares?
115                 spec.bold = false;
116                 spec.italic = false;
117         } else if (spec.mode == _FM_Fallback) {
118                 // Fallback font doesn't support these either
119                 spec.bold = false;
120                 spec.italic = false;
121         }
122
123         // Fallback to default size
124         if (spec.size == FONT_SIZE_UNSPECIFIED)
125                 spec.size = m_default_size[spec.mode];
126
127         RecursiveMutexAutoLock l(m_font_mutex);
128
129         const auto &cache = m_font_cache[spec.getHash()];
130         auto it = cache.find(spec.size);
131         if (it != cache.end())
132                 return it->second;
133
134         // Font does not yet exist
135         gui::IGUIFont *font = nullptr;
136         if (spec.mode == FM_Simple || spec.mode == FM_SimpleMono)
137                 font = initSimpleFont(spec);
138         else
139                 font = initFont(spec);
140
141         if (!font && !may_fail) {
142                 errorstream << "Minetest cannot continue without a valid font. "
143                         "Please correct the 'font_path' setting or install the font "
144                         "file in the proper location." << std::endl;
145                 abort();
146         }
147
148         m_font_cache[spec.getHash()][spec.size] = font;
149
150         return font;
151 }
152
153 /******************************************************************************/
154 unsigned int FontEngine::getTextHeight(const FontSpec &spec)
155 {
156         gui::IGUIFont *font = getFont(spec);
157
158         return font->getDimension(L"Some unimportant example String").Height;
159 }
160
161 /******************************************************************************/
162 unsigned int FontEngine::getTextWidth(const std::wstring &text, const FontSpec &spec)
163 {
164         gui::IGUIFont *font = getFont(spec);
165
166         return font->getDimension(text.c_str()).Width;
167 }
168
169 /** get line height for a specific font (including empty room between lines) */
170 unsigned int FontEngine::getLineHeight(const FontSpec &spec)
171 {
172         gui::IGUIFont *font = getFont(spec);
173
174         return font->getDimension(L"Some unimportant example String").Height
175                         + font->getKerningHeight();
176 }
177
178 /******************************************************************************/
179 unsigned int FontEngine::getDefaultFontSize()
180 {
181         return m_default_size[m_currentMode];
182 }
183
184 unsigned int FontEngine::getFontSize(FontMode mode)
185 {
186         if (m_currentMode == FM_Simple) {
187                 if (mode == FM_Mono || mode == FM_SimpleMono)
188                         return m_default_size[FM_SimpleMono];
189                 else
190                         return m_default_size[FM_Simple];
191         }
192
193         if (mode == FM_Unspecified)
194                 return m_default_size[FM_Standard];
195
196         return m_default_size[mode];
197 }
198
199 /******************************************************************************/
200 void FontEngine::readSettings()
201 {
202         if (USE_FREETYPE && g_settings->getBool("freetype")) {
203                 m_default_size[FM_Standard]  = g_settings->getU16("font_size");
204                 m_default_size[_FM_Fallback] = g_settings->getU16("font_size");
205                 m_default_size[FM_Mono]      = g_settings->getU16("mono_font_size");
206
207                 m_default_bold = g_settings->getBool("font_bold");
208                 m_default_italic = g_settings->getBool("font_italic");
209
210         } else {
211                 m_currentMode = FM_Simple;
212         }
213
214         m_default_size[FM_Simple]       = g_settings->getU16("font_size");
215         m_default_size[FM_SimpleMono]   = g_settings->getU16("mono_font_size");
216
217         cleanCache();
218         updateFontCache();
219         updateSkin();
220 }
221
222 /******************************************************************************/
223 void FontEngine::updateSkin()
224 {
225         gui::IGUIFont *font = getFont();
226         assert(font);
227
228         m_env->getSkin()->setFont(font);
229 }
230
231 /******************************************************************************/
232 void FontEngine::updateFontCache()
233 {
234         /* the only font to be initialized is default one,
235          * all others are re-initialized on demand */
236         getFont(FONT_SIZE_UNSPECIFIED, FM_Unspecified);
237 }
238
239 /******************************************************************************/
240 gui::IGUIFont *FontEngine::initFont(const FontSpec &spec)
241 {
242         assert(spec.mode != FM_Unspecified);
243         assert(spec.size != FONT_SIZE_UNSPECIFIED);
244
245         std::string setting_prefix = "";
246         if (spec.mode == FM_Mono)
247                 setting_prefix = "mono_";
248
249         std::string setting_suffix = "";
250         if (spec.bold)
251                 setting_suffix.append("_bold");
252         if (spec.italic)
253                 setting_suffix.append("_italic");
254
255         u32 size = std::floor(RenderingEngine::getDisplayDensity() *
256                         g_settings->getFloat("gui_scaling") * spec.size);
257
258         if (size == 0) {
259                 errorstream << "FontEngine: attempt to use font size 0" << std::endl;
260                 errorstream << "  display density: " << RenderingEngine::getDisplayDensity() << std::endl;
261                 abort();
262         }
263
264         u16 font_shadow       = 0;
265         u16 font_shadow_alpha = 0;
266         g_settings->getU16NoEx(setting_prefix + "font_shadow", font_shadow);
267         g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha",
268                         font_shadow_alpha);
269
270         std::string path_setting;
271         if (spec.mode == _FM_Fallback)
272                 path_setting = "fallback_font_path";
273         else
274                 path_setting = setting_prefix + "font_path" + setting_suffix;
275
276         std::string fallback_settings[] = {
277                 g_settings->get(path_setting),
278                 Settings::getLayer(SL_DEFAULTS)->get(path_setting)
279         };
280
281 #if USE_FREETYPE
282         for (const std::string &font_path : fallback_settings) {
283                 gui::CGUITTFont *font = gui::CGUITTFont::createTTFont(m_env,
284                                 font_path.c_str(), size, true, true, font_shadow,
285                                 font_shadow_alpha);
286
287                 if (!font) {
288                         errorstream << "FontEngine: Cannot load '" << font_path <<
289                                 "'. Trying to fall back to another path." << std::endl;
290                         continue;
291                 }
292
293                 if (spec.mode != _FM_Fallback) {
294                         FontSpec spec2(spec);
295                         spec2.mode = _FM_Fallback;
296                         font->setFallback(getFont(spec2, true));
297                 }
298                 return font;
299         }
300 #else
301         errorstream << "FontEngine: Tried to load TTF font but Minetest was"
302                         " compiled without Freetype." << std::endl;
303 #endif
304         return nullptr;
305 }
306
307 /** initialize a font without freetype */
308 gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec)
309 {
310         assert(spec.mode == FM_Simple || spec.mode == FM_SimpleMono);
311         assert(spec.size != FONT_SIZE_UNSPECIFIED);
312
313         const std::string &font_path = g_settings->get(
314                         (spec.mode == FM_SimpleMono) ? "mono_font_path" : "font_path");
315
316         size_t pos_dot = font_path.find_last_of('.');
317         std::string basename = font_path, ending;
318         if (pos_dot != std::string::npos)
319                 ending = lowercase(font_path.substr(pos_dot));
320
321         if (ending == ".ttf") {
322                 errorstream << "FontEngine: Found font \"" << font_path
323                                 << "\" but freetype is not available." << std::endl;
324                 return nullptr;
325         }
326
327         if (ending == ".xml" || ending == ".png")
328                 basename = font_path.substr(0, pos_dot);
329
330         u32 size = std::floor(
331                         RenderingEngine::getDisplayDensity() *
332                         g_settings->getFloat("gui_scaling") *
333                         spec.size);
334
335         irr::gui::IGUIFont *font = nullptr;
336         std::string font_extensions[] = { ".png", ".xml" };
337
338         // Find nearest matching font scale
339         // Does a "zig-zag motion" (positibe/negative), from 0 to MAX_FONT_SIZE_OFFSET
340         for (s32 zoffset = 0; zoffset < MAX_FONT_SIZE_OFFSET * 2; zoffset++) {
341                 std::stringstream path;
342
343                 // LSB to sign
344                 s32 sign = (zoffset & 1) ? -1 : 1;
345                 s32 offset = zoffset >> 1;
346
347                 for (const std::string &ext : font_extensions) {
348                         path.str(""); // Clear
349                         path << basename << "_" << (size + offset * sign) << ext;
350
351                         if (!fs::PathExists(path.str()))
352                                 continue;
353
354                         font = m_env->getFont(path.str().c_str());
355
356                         if (font) {
357                                 verbosestream << "FontEngine: found font: " << path.str() << std::endl;
358                                 break;
359                         }
360                 }
361
362                 if (font)
363                         break;
364         }
365
366         // try name direct
367         if (font == NULL) {
368                 if (fs::PathExists(font_path)) {
369                         font = m_env->getFont(font_path.c_str());
370                         if (font)
371                                 verbosestream << "FontEngine: found font: " << font_path << std::endl;
372                 }
373         }
374
375         return font;
376 }