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