05a8286d6d86d52b8a8d499cab9f3cd30b35203e
[supertux.git] / src / video / font.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //                     Ingo Ruhnke <grumbel@gmx.de>
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 <cstdlib>
21 #include <cstring>
22 #include <stdexcept>
23 #include <SDL_image.h>
24 #include <physfs.h>
25
26 #include "physfs/physfs_sdl.hpp"
27
28 #include "util/file_system.hpp"
29
30 #include "lisp/lisp.hpp"
31 #include "lisp/list_iterator.hpp"
32 #include "lisp/parser.hpp"
33 #include "supertux/screen.hpp"
34 #include "util/log.hpp"
35 #include "video/drawing_context.hpp"
36 #include "video/font.hpp"
37 #include "video/renderer.hpp"
38
39 namespace {
40 bool     has_multibyte_mark(unsigned char c);
41 uint32_t decode_utf8(const std::string& text, size_t& p);
42 std::string encode_utf8(uint32_t code);
43
44 struct UTF8Iterator
45 {
46   const std::string&     text;
47   std::string::size_type pos;
48   uint32_t chr;
49
50   UTF8Iterator(const std::string& text_) :
51     text(text_),
52     pos(0),
53     chr()
54   {
55     try {
56       chr = decode_utf8(text, pos);
57     } catch (std::exception) {
58       log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
59       chr = 0;
60     }
61   }
62
63   bool done() const
64   {
65     return pos > text.size();
66   }
67
68   UTF8Iterator& operator++() {
69     try {
70       chr = decode_utf8(text, pos);
71     } catch (std::exception) {
72       log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
73       chr = 0;
74       ++pos;
75     }
76
77     return *this;
78   }
79
80   uint32_t operator*() const {
81     return chr;
82   }
83 };
84
85 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
86 {
87   Uint8* pixels = (Uint8*)surface->pixels;
88
89   for(int y = start_y; y < end_y; ++y)
90   {
91     const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
92     if (p > threshold)
93     {
94       return false;
95     }
96   }
97   return true;
98 }
99 } // namespace
100
101 Font::Font(GlyphWidth glyph_width_,
102            const std::string& filename,
103            int shadowsize_) :
104   glyph_width(glyph_width_),
105   glyph_surfaces(),
106   shadow_surfaces(),
107   char_height(),
108   shadowsize(shadowsize_),
109   glyphs(65536)
110 {
111   for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
112
113   const std::string fontdir = FileSystem::dirname(filename);
114   const std::string fontname = FileSystem::basename(filename);
115
116   // scan for prefix-filename in addons search path
117   char **rc = PHYSFS_enumerateFiles(fontdir.c_str());
118   for (char **i = rc; *i != NULL; i++) {
119     std::string filename(*i);
120     if( filename.rfind(fontname) != std::string::npos ) {
121       loadFontFile(fontdir + filename);
122     }
123   }
124   PHYSFS_freeList(rc);
125 }
126
127 void 
128 Font::loadFontFile(const std::string &filename)
129 {
130   lisp::Parser parser;
131   log_debug << "Loading font: " << filename << std::endl;
132   const lisp::Lisp* root = parser.parse(filename);
133   const lisp::Lisp* config_l = root->get_lisp("supertux-font");
134
135   if(!config_l) {
136     std::ostringstream msg;
137     msg << "Font file:" << filename << ": is not a supertux-font file";
138     throw std::runtime_error(msg.str());
139   }
140
141   int def_char_width=0;
142
143   if( !config_l->get("glyph-width",def_char_width) ) {
144     log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
145   }
146   
147   if( !config_l->get("glyph-height",char_height) ) {
148     std::ostringstream msg;
149     msg << "Font:" << filename << ": misses glyph-height";
150     throw std::runtime_error(msg.str());
151   }
152
153   lisp::ListIterator iter(config_l);
154   while(iter.next()) {
155     const std::string& token = iter.item();
156     if( token == "surface" ) {
157       const lisp::Lisp * glyphs_val = iter.lisp();
158       int local_char_width;
159       bool monospaced;
160       GlyphWidth local_glyph_width;
161       std::string glyph_image;
162       std::string shadow_image;
163       std::vector<std::string> chars;
164       if( ! glyphs_val->get("glyph-width", local_char_width) ) {
165         local_char_width = def_char_width;
166       }
167       if( ! glyphs_val->get("monospace", monospaced ) ) {
168         local_glyph_width = glyph_width;
169       }
170       else {
171         if( monospaced ) local_glyph_width = FIXED;
172         else local_glyph_width = VARIABLE;
173       }
174       if( ! glyphs_val->get("glyphs", glyph_image) ) {
175         std::ostringstream msg;
176         msg << "Font:" << filename << ": missing glyphs image";
177         throw std::runtime_error(msg.str());
178       }
179       if( ! glyphs_val->get("shadows", shadow_image) ) {
180         std::ostringstream msg;
181         msg << "Font:" << filename << ": missing shadows image";
182         throw std::runtime_error(msg.str());
183       }
184       if( ! glyphs_val->get("chars", chars) || chars.size() == 0) {
185         std::ostringstream msg;
186         msg << "Font:" << filename << ": missing chars definition";
187         throw std::runtime_error(msg.str());
188       }
189
190       if( local_char_width==0 ) {
191         std::ostringstream msg;
192         msg << "Font:" << filename << ": misses glyph-width for some surface";
193         throw std::runtime_error(msg.str());
194       }
195
196       loadFontSurface(glyph_image, shadow_image, chars,
197                       local_glyph_width, local_char_width);
198     }
199   }
200 }
201
202 void 
203 Font::loadFontSurface(
204   const std::string &glyphimage,
205   const std::string &shadowimage,
206   const std::vector<std::string> &chars,
207   GlyphWidth glyph_width,
208   int char_width
209   )
210 {
211   Surface glyph_surface("images/engine/fonts/" + glyphimage);
212   Surface shadow_surface("images/engine/fonts/" + shadowimage);
213
214   int surface_idx = glyph_surfaces.size();
215   glyph_surfaces.push_back(glyph_surface);
216   shadow_surfaces.push_back(shadow_surface);
217
218   int row=0, col=0;
219   int wrap = glyph_surface.get_width() / char_width;
220  
221   SDL_Surface *surface = NULL;
222   
223   if( glyph_width == VARIABLE ) {
224     //this does not work:
225     // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture();
226     surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1);
227     if(surface == NULL) {
228       std::ostringstream msg;
229       msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError();
230       throw std::runtime_error(msg.str());
231     }
232     SDL_LockSurface(surface);
233   }
234
235   for( unsigned int i = 0; i < chars.size(); i++) {
236     for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) {
237       int y = row * char_height;
238       int x = col * char_width;
239       if( ++col == wrap ) { col=0; row++; }
240       if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue;
241         
242       Glyph glyph;
243       glyph.surface_idx   = surface_idx;
244       
245       if( glyph_width == FIXED ) {
246         glyph.rect    = Rect(x, y, x + char_width, y + char_height);
247         glyph.offset  = Vector(0, 0);
248         glyph.advance = char_width;
249       }
250       else {
251         int left = x;
252         while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
253           left += 1;
254         int right = x + char_width - 1;
255         while (right > left && vline_empty(surface, right, y, y + char_height, 64))
256           right -= 1;
257           
258         if (left <= right)
259           glyph.rect = Rect(left,  y, right+1, y + char_height);
260         else // glyph is completely transparent
261           glyph.rect = Rect(x,  y, x + char_width, y + char_height);
262         
263         glyph.offset  = Vector(0, 0);
264         glyph.advance = glyph.rect.get_width() + 1; // FIXME: might be useful to make spacing configurable
265       }
266
267       glyphs[*chr] = glyph;
268     }
269     if( col>0 && col <= wrap ) { 
270       col = 0;
271       row++;
272     }
273   }
274   
275   if( surface != NULL ) {
276     SDL_UnlockSurface(surface);
277     SDL_FreeSurface(surface);
278   }
279 }
280
281 Font::~Font()
282 {
283 }
284
285 float
286 Font::get_text_width(const std::string& text) const
287 {
288   float curr_width = 0;
289   float last_width = 0;
290
291   for(UTF8Iterator it(text); !it.done(); ++it)
292   {
293     if (*it == '\n')
294     {
295       last_width = std::max(last_width, curr_width);
296       curr_width = 0;
297     }
298     else
299     {
300       if( glyphs.at(*it).surface_idx != -1 )
301         curr_width += glyphs[*it].advance;
302       else 
303         curr_width += glyphs[0x20].advance;
304     }
305   }
306
307   return std::max(curr_width, last_width);
308 }
309
310 float
311 Font::get_text_height(const std::string& text) const
312 {
313   std::string::size_type text_height = char_height;
314
315   for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
316   { // since UTF8 multibyte characters are decoded with values
317     // outside the ASCII range there is no risk of overlapping and
318     // thus we don't need to decode the utf-8 string
319     if (*it == '\n')
320       text_height += char_height + 2;
321   }
322
323   return text_height;
324 }
325
326 float
327 Font::get_height() const
328 {
329   return char_height;
330 }
331
332 std::string
333 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
334 {
335   // if text is already smaller, return full text
336   if ((int)s.length() <= line_length) {
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   int i = line_length;
343   while ((i > 0) && (s[i] != ' ')) i--;
344   if (i > 0) {
345     if (overflow) *overflow = s.substr(i+1);
346     return s.substr(0, i);
347   }
348
349   // FIXME: wrap at line_length, taking care of multibyte characters
350   if (overflow) *overflow = "";
351   return s;
352 }
353
354 std::string
355 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
356 {
357   std::string s = s_;
358
359   // if text is already smaller, return full text
360   if (get_text_width(s) <= width) {
361     if (overflow) *overflow = "";
362     return s;
363   }
364
365   // if we can find a whitespace character to break at, return text up to this character
366   for (int i = s.length()-1; i >= 0; i--) {
367     std::string s2 = s.substr(0,i);
368     if (s[i] != ' ') continue;
369     if (get_text_width(s2) <= width) {
370       if (overflow) *overflow = s.substr(i+1);
371       return s.substr(0, i);
372     }
373   }
374   
375   // FIXME: hard-wrap at width, taking care of multibyte characters
376   if (overflow) *overflow = "";
377   return s;
378 }
379
380 void
381 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
382            FontAlignment alignment, DrawingEffect drawing_effect, Color color,
383            float alpha) const
384 {
385   float x = pos_.x;
386   float y = pos_.y;
387
388   std::string::size_type last = 0;
389   for(std::string::size_type i = 0;; ++i)
390   {
391     if (text[i] == '\n' || i == text.size())
392     {
393       std::string temp = text.substr(last, i - last);
394
395       // calculate X positions based on the alignment type
396       Vector pos = Vector(x, y);
397
398       if(alignment == ALIGN_CENTER)
399         pos.x -= get_text_width(temp) / 2;
400       else if(alignment == ALIGN_RIGHT)
401         pos.x -= get_text_width(temp);
402
403       // Cast font position to integer to get a clean drawing result and
404       // no blurring as we would get with subpixel positions
405       pos.x = static_cast<int>(pos.x);
406
407       draw_text(renderer, temp, pos, drawing_effect, color, alpha);
408
409       if (i == text.size())
410         break;
411
412       y += char_height + 2;
413       last = i + 1;
414     }
415   }
416 }
417
418 void
419 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
420                 DrawingEffect drawing_effect, Color color, float alpha) const
421 {
422   if(shadowsize > 0)
423     draw_chars(renderer, false, text, 
424                pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
425
426   draw_chars(renderer, true, text, pos, drawing_effect, color, alpha);
427 }
428
429 void
430 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
431                  const Vector& pos, DrawingEffect drawing_effect, Color color,
432                  float alpha) const
433 {
434   Vector p = pos;
435
436   for(UTF8Iterator it(text); !it.done(); ++it)
437   {
438     if(*it == '\n')
439     {
440       p.x = pos.x;
441       p.y += char_height + 2;
442     }
443     else if(*it == ' ')
444     {
445       p.x += glyphs[0x20].advance;
446     }
447     else
448     {
449       Glyph glyph;
450       if( glyphs.at(*it).surface_idx != -1 )
451         glyph = glyphs[*it];
452       else 
453         glyph = glyphs[0x20];
454
455       DrawingRequest request;
456
457       request.pos = p + glyph.offset;
458       request.drawing_effect = drawing_effect;
459       request.color = color;
460       request.alpha = alpha;
461
462       SurfacePartRequest surfacepartrequest;
463       surfacepartrequest.size = glyph.rect.p2 - glyph.rect.p1;
464       surfacepartrequest.source = glyph.rect.p1;
465       surfacepartrequest.surface = notshadow ? &(glyph_surfaces[glyph.surface_idx]) : &(shadow_surfaces[glyph.surface_idx]);
466
467       request.request_data = &surfacepartrequest;
468       renderer->draw_surface_part(request);
469
470       p.x += glyph.advance;
471     }
472   }
473 }
474
475 namespace {
476
477 /**
478  * returns true if this byte matches a bitmask of 10xx.xxxx, i.e. it is the 2nd, 3rd or 4th byte of a multibyte utf8 string
479  */
480 bool has_multibyte_mark(unsigned char c) {
481   return ((c & 0300) == 0200);
482 }
483
484 /**
485  * gets unicode character at byte position @a p of UTF-8 encoded @a
486  * text, then advances @a p to the next character.
487  *
488  * @throws std::runtime_error if decoding fails.
489  * See unicode standard section 3.10 table 3-5 and 3-6 for details.
490  */
491 uint32_t decode_utf8(const std::string& text, size_t& p)
492 {
493   uint32_t c1 = (unsigned char) text[p+0];
494
495   if (has_multibyte_mark(c1)) std::runtime_error("Malformed utf-8 sequence");
496
497   if ((c1 & 0200) == 0000) {
498     // 0xxx.xxxx: 1 byte sequence
499     p+=1;
500     return c1;
501   }
502   else if ((c1 & 0340) == 0300) {
503     // 110x.xxxx: 2 byte sequence
504     if(p+1 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
505     uint32_t c2 = (unsigned char) text[p+1];
506     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
507     p+=2;
508     return (c1 & 0037) << 6 | (c2 & 0077);
509   }
510   else if ((c1 & 0360) == 0340) {
511     // 1110.xxxx: 3 byte sequence
512     if(p+2 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
513     uint32_t c2 = (unsigned char) text[p+1];
514     uint32_t c3 = (unsigned char) text[p+2];
515     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
516     if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
517     p+=3;
518     return (c1 & 0017) << 12 | (c2 & 0077) << 6 | (c3 & 0077);
519   }
520   else if ((c1 & 0370) == 0360) {
521     // 1111.0xxx: 4 byte sequence
522     if(p+3 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
523     uint32_t c2 = (unsigned char) text[p+1];
524     uint32_t c3 = (unsigned char) text[p+2];
525     uint32_t c4 = (unsigned char) text[p+4];
526     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
527     if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
528     if (!has_multibyte_mark(c4)) throw std::runtime_error("Malformed utf-8 sequence");
529     p+=4;
530     return (c1 & 0007) << 18 | (c2 & 0077) << 12 | (c3 & 0077) << 6 | (c4 & 0077);
531   }
532   throw std::runtime_error("Malformed utf-8 sequence");
533 }
534
535 } // namespace
536
537 /* EOF */