Support for right-to-left fonts. Set (rtl #t) in
[supertux.git] / src / video / font.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //                     Ingo Ruhnke <grumbel@gmail.com>
4 //
5 //  This program is free software: you can redistribute it and/or modify
6 //  it under the terms of the GNU General Public License as published by
7 //  the Free Software Foundation, either version 3 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 General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 #include <config.h>
19
20 #include <sstream>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdexcept>
24 #include <SDL_image.h>
25 #include <physfs.h>
26
27 #include "lisp/list_iterator.hpp"
28 #include "lisp/parser.hpp"
29 #include "physfs/physfs_sdl.hpp"
30 #include "supertux/screen.hpp"
31 #include "util/file_system.hpp"
32 #include "util/log.hpp"
33 #include "util/utf8_iterator.hpp"
34 #include "video/drawing_context.hpp"
35 #include "video/drawing_request.hpp"
36 #include "video/font.hpp"
37 #include "video/renderer.hpp"
38
39 namespace {
40
41 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
42 {
43   Uint8* pixels = (Uint8*)surface->pixels;
44
45   for(int y = start_y; y < end_y; ++y)
46   {
47     const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
48     if (p > threshold)
49     {
50       return false;
51     }
52   }
53   return true;
54 }
55
56 } // namespace
57
58 Font::Font(GlyphWidth glyph_width_,
59            const std::string& filename,
60            int shadowsize_) :
61   glyph_width(glyph_width_),
62   glyph_surfaces(),
63   shadow_surfaces(),
64   char_height(),
65   shadowsize(shadowsize_),
66   border(0),
67   rtl(false),
68   glyphs(65536)
69 {
70   for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
71
72   const std::string fontdir = FileSystem::dirname(filename);
73   const std::string fontname = FileSystem::basename(filename);
74
75   // scan for prefix-filename in addons search path
76   char **rc = PHYSFS_enumerateFiles(fontdir.c_str());
77   for (char **i = rc; *i != NULL; i++) {
78     std::string filename_(*i);
79     if( filename_.rfind(fontname) != std::string::npos ) {
80       loadFontFile(fontdir + filename_);
81     }
82   }
83   PHYSFS_freeList(rc);
84 }
85
86 void
87 Font::loadFontFile(const std::string &filename)
88 {
89   lisp::Parser parser;
90   log_debug << "Loading font: " << filename << std::endl;
91   const lisp::Lisp* root = parser.parse(filename);
92   const lisp::Lisp* config_l = root->get_lisp("supertux-font");
93
94   if(!config_l) {
95     std::ostringstream msg;
96     msg << "Font file:" << filename << ": is not a supertux-font file";
97     throw std::runtime_error(msg.str());
98   }
99
100   int def_char_width=0;
101
102   if( !config_l->get("glyph-width",def_char_width) ) {
103     log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
104   }
105
106   if( !config_l->get("glyph-height",char_height) ) {
107     std::ostringstream msg;
108     msg << "Font:" << filename << ": misses glyph-height";
109     throw std::runtime_error(msg.str());
110   }
111
112   config_l->get("glyph-border", border);
113   config_l->get("rtl", rtl);
114
115   lisp::ListIterator iter(config_l);
116   while(iter.next()) {
117     const std::string& token = iter.item();
118     if( token == "surface" ) {
119       const lisp::Lisp * glyphs_val = iter.lisp();
120       int local_char_width;
121       bool monospaced;
122       GlyphWidth local_glyph_width;
123       std::string glyph_image;
124       std::string shadow_image;
125       std::vector<std::string> chars;
126       if( ! glyphs_val->get("glyph-width", local_char_width) ) {
127         local_char_width = def_char_width;
128       }
129       if( ! glyphs_val->get("monospace", monospaced ) ) {
130         local_glyph_width = glyph_width;
131       }
132       else {
133         if( monospaced ) local_glyph_width = FIXED;
134         else local_glyph_width = VARIABLE;
135       }
136       if( ! glyphs_val->get("glyphs", glyph_image) ) {
137         std::ostringstream msg;
138         msg << "Font:" << filename << ": missing glyphs image";
139         throw std::runtime_error(msg.str());
140       }
141       if( ! glyphs_val->get("shadows", shadow_image) ) {
142         std::ostringstream msg;
143         msg << "Font:" << filename << ": missing shadows image";
144         throw std::runtime_error(msg.str());
145       }
146       if( ! glyphs_val->get("chars", chars) || chars.size() == 0) {
147         std::ostringstream msg;
148         msg << "Font:" << filename << ": missing chars definition";
149         throw std::runtime_error(msg.str());
150       }
151
152       if( local_char_width==0 ) {
153         std::ostringstream msg;
154         msg << "Font:" << filename << ": misses glyph-width for some surface";
155         throw std::runtime_error(msg.str());
156       }
157
158       loadFontSurface(glyph_image, shadow_image, chars,
159                       local_glyph_width, local_char_width);
160     }
161   }
162 }
163
164 void
165 Font::loadFontSurface(
166   const std::string &glyphimage,
167   const std::string &shadowimage,
168   const std::vector<std::string> &chars,
169   GlyphWidth glyph_width_,
170   int char_width
171   )
172 {
173   SurfacePtr glyph_surface  = Surface::create("images/engine/fonts/" + glyphimage);
174   SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage);
175
176   int surface_idx = glyph_surfaces.size();
177   glyph_surfaces.push_back(glyph_surface);
178   shadow_surfaces.push_back(shadow_surface);
179
180   int row=0, col=0;
181   int wrap = glyph_surface->get_width() / char_width;
182
183   SDL_Surface *surface = NULL;
184
185   if( glyph_width_ == VARIABLE ) {
186     //this does not work:
187     // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture();
188     surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1);
189     if(surface == NULL) {
190       std::ostringstream msg;
191       msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError();
192       throw std::runtime_error(msg.str());
193     }
194     SDL_LockSurface(surface);
195   }
196
197   for( unsigned int i = 0; i < chars.size(); i++) {
198     for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) {
199       int y = row * (char_height + 2*border) + border;
200       int x = col * (char_width + 2*border) + border;
201       if( ++col == wrap ) { col=0; row++; }
202       if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue;
203
204       Glyph glyph;
205       glyph.surface_idx   = surface_idx;
206
207       if( glyph_width_ == FIXED || isdigit(*chr) )
208       {
209         glyph.rect    = Rectf(x, y, x + char_width, y + char_height);
210         glyph.offset  = Vector(0, 0);
211         glyph.advance = char_width;
212       }
213       else
214       {
215         if (y + char_height > surface->h)
216         {
217           log_warning << "error: font definition contains more letter then the images: " << glyphimage << std::endl;
218           goto abort;
219         }
220
221         int left = x;
222         while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
223           left += 1;
224         int right = x + char_width - 1;
225         while (right > left && vline_empty(surface, right, y, y + char_height, 64))
226           right -= 1;
227
228         if (left <= right)
229         {
230           glyph.offset  = Vector(x-left, 0);
231           glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable
232         }
233         else
234         { // glyph is completly transparent
235           glyph.offset  = Vector(0, 0);
236           glyph.advance = char_width + 1; // FIXME: might be useful to make spacing configurable
237         }
238
239         glyph.rect = Rectf(x,  y, x + char_width, y + char_height);
240       }
241
242       glyphs[*chr] = glyph;
243     }
244     if( col>0 && col <= wrap ) {
245       col = 0;
246       row++;
247     }
248   }
249 abort:
250
251   if( surface != NULL ) {
252     SDL_UnlockSurface(surface);
253     SDL_FreeSurface(surface);
254   }
255 }
256
257 Font::~Font()
258 {
259 }
260
261 float
262 Font::get_text_width(const std::string& text) const
263 {
264   float curr_width = 0;
265   float last_width = 0;
266
267   for(UTF8Iterator it(text); !it.done(); ++it)
268   {
269     if (*it == '\n')
270     {
271       last_width = std::max(last_width, curr_width);
272       curr_width = 0;
273     }
274     else
275     {
276       if( glyphs.at(*it).surface_idx != -1 )
277         curr_width += glyphs[*it].advance;
278       else
279         curr_width += glyphs[0x20].advance;
280     }
281   }
282
283   return std::max(curr_width, last_width);
284 }
285
286 float
287 Font::get_text_height(const std::string& text) const
288 {
289   std::string::size_type text_height = char_height;
290
291   for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
292   { // since UTF8 multibyte characters are decoded with values
293     // outside the ASCII range there is no risk of overlapping and
294     // thus we don't need to decode the utf-8 string
295     if (*it == '\n')
296       text_height += char_height + 2;
297   }
298
299   return text_height;
300 }
301
302 float
303 Font::get_height() const
304 {
305   return char_height;
306 }
307
308 std::string
309 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
310 {
311   // if text is already smaller, return full text
312   if ((int)s.length() <= line_length) {
313     if (overflow) *overflow = "";
314     return s;
315   }
316
317   // if we can find a whitespace character to break at, return text up to this character
318   int i = line_length;
319   while ((i > 0) && (s[i] != ' ')) i--;
320   if (i > 0) {
321     if (overflow) *overflow = s.substr(i+1);
322     return s.substr(0, i);
323   }
324
325   // FIXME: wrap at line_length, taking care of multibyte characters
326   if (overflow) *overflow = "";
327   return s;
328 }
329
330 std::string
331 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
332 {
333   std::string s = s_;
334
335   // if text is already smaller, return full text
336   if (get_text_width(s) <= width) {
337     if (overflow) *overflow = "";
338     return s;
339   }
340
341   // if we can find a whitespace character to break at, return text up to this character
342   for (int i = s.length()-1; i >= 0; i--) {
343     std::string s2 = s.substr(0,i);
344     if (s[i] != ' ') continue;
345     if (get_text_width(s2) <= width) {
346       if (overflow) *overflow = s.substr(i+1);
347       return s.substr(0, i);
348     }
349   }
350
351   // FIXME: hard-wrap at width, taking care of multibyte characters
352   if (overflow) *overflow = "";
353   return s;
354 }
355
356 void
357 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
358            FontAlignment alignment, DrawingEffect drawing_effect, Color color,
359            float alpha) const
360 {
361   float x = pos_.x;
362   float y = pos_.y;
363
364   std::string::size_type last = 0;
365   for(std::string::size_type i = 0;; ++i)
366   {
367     if (text[i] == '\n' || i == text.size())
368     {
369       std::string temp = text.substr(last, i - last);
370
371       // calculate X positions based on the alignment type
372       Vector pos = Vector(x, y);
373
374       if(alignment == ALIGN_CENTER)
375         pos.x -= get_text_width(temp) / 2;
376       else if(alignment == ALIGN_RIGHT)
377         pos.x -= get_text_width(temp);
378
379       // Cast font position to integer to get a clean drawing result and
380       // no blurring as we would get with subpixel positions
381       pos.x = static_cast<int>(pos.x);
382
383       draw_text(renderer, temp, pos, drawing_effect, color, alpha);
384
385       if (i == text.size())
386         break;
387
388       y += char_height + 2;
389       last = i + 1;
390     }
391   }
392 }
393
394 void
395 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
396                 DrawingEffect drawing_effect, Color color, float alpha) const
397 {
398   if(shadowsize > 0)
399     draw_chars(renderer, false, rtl ? std::string(text.rbegin(), text.rend()) : text,
400                pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
401
402   draw_chars(renderer, true, rtl ? std::string(text.rbegin(), text.rend()) : text, pos, drawing_effect, color, alpha);
403 }
404
405 void
406 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
407                  const Vector& pos, DrawingEffect drawing_effect, Color color,
408                  float alpha) const
409 {
410   Vector p = pos;
411
412   for(UTF8Iterator it(text); !it.done(); ++it)
413   {
414     if(*it == '\n')
415     {
416       p.x = pos.x;
417       p.y += char_height + 2;
418     }
419     else if(*it == ' ')
420     {
421       p.x += glyphs[0x20].advance;
422     }
423     else
424     {
425       Glyph glyph;
426       if( glyphs.at(*it).surface_idx != -1 )
427         glyph = glyphs[*it];
428       else
429         glyph = glyphs[0x20];
430
431       DrawingRequest request;
432
433       request.pos = p + glyph.offset;
434       request.drawing_effect = drawing_effect;
435       request.color = color;
436       request.alpha = alpha;
437
438       SurfacePartRequest surfacepartrequest;
439       surfacepartrequest.srcrect = glyph.rect;
440       surfacepartrequest.dstsize = glyph.rect.get_size();
441       surfacepartrequest.surface = notshadow ? glyph_surfaces[glyph.surface_idx].get() : shadow_surfaces[glyph.surface_idx].get();
442
443       request.request_data = &surfacepartrequest;
444       renderer->draw_surface_part(request);
445
446       p.x += glyph.advance;
447     }
448   }
449 }
450
451 /* EOF */