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