src/video/font.cpp

Go to the documentation of this file.
00001 //  SuperTux
00002 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
00003 //                     Ingo Ruhnke <grumbel@gmx.de>
00004 //
00005 //  This program is free software: you can redistribute it and/or modify
00006 //  it under the terms of the GNU General Public License as published by
00007 //  the Free Software Foundation, either version 3 of the License, or
00008 //  (at your option) any later version.
00009 //
00010 //  This program is distributed in the hope that it will be useful,
00011 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 //  GNU General Public License for more details.
00014 //
00015 //  You should have received a copy of the GNU General Public License
00016 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
00017 
00018 #include <config.h>
00019 
00020 #include <sstream>
00021 #include <stdlib.h>
00022 #include <string.h>
00023 #include <stdexcept>
00024 #include <SDL_image.h>
00025 #include <physfs.h>
00026 
00027 #include "lisp/list_iterator.hpp"
00028 #include "lisp/parser.hpp"
00029 #include "physfs/physfs_sdl.hpp"
00030 #include "supertux/screen.hpp"
00031 #include "util/file_system.hpp"
00032 #include "util/log.hpp"
00033 #include "util/utf8_iterator.hpp"
00034 #include "video/drawing_context.hpp"
00035 #include "video/font.hpp"
00036 #include "video/renderer.hpp"
00037 
00038 namespace {
00039 
00040 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
00041 {
00042   Uint8* pixels = (Uint8*)surface->pixels;
00043 
00044   for(int y = start_y; y < end_y; ++y)
00045   {
00046     const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
00047     if (p > threshold)
00048     {
00049       return false;
00050     }
00051   }
00052   return true;
00053 }
00054 
00055 } // namespace
00056 
00057 Font::Font(GlyphWidth glyph_width_,
00058            const std::string& filename,
00059            int shadowsize_) :
00060   glyph_width(glyph_width_),
00061   glyph_surfaces(),
00062   shadow_surfaces(),
00063   char_height(),
00064   shadowsize(shadowsize_),
00065   glyphs(65536)
00066 {
00067   for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
00068 
00069   const std::string fontdir = FileSystem::dirname(filename);
00070   const std::string fontname = FileSystem::basename(filename);
00071 
00072   // scan for prefix-filename in addons search path
00073   char **rc = PHYSFS_enumerateFiles(fontdir.c_str());
00074   for (char **i = rc; *i != NULL; i++) {
00075     std::string filename(*i);
00076     if( filename.rfind(fontname) != std::string::npos ) {
00077       loadFontFile(fontdir + filename);
00078     }
00079   }
00080   PHYSFS_freeList(rc);
00081 }
00082 
00083 void 
00084 Font::loadFontFile(const std::string &filename)
00085 {
00086   lisp::Parser parser;
00087   log_debug << "Loading font: " << filename << std::endl;
00088   const lisp::Lisp* root = parser.parse(filename);
00089   const lisp::Lisp* config_l = root->get_lisp("supertux-font");
00090 
00091   if(!config_l) {
00092     std::ostringstream msg;
00093     msg << "Font file:" << filename << ": is not a supertux-font file";
00094     throw std::runtime_error(msg.str());
00095   }
00096 
00097   int def_char_width=0;
00098 
00099   if( !config_l->get("glyph-width",def_char_width) ) {
00100     log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
00101   }
00102   
00103   if( !config_l->get("glyph-height",char_height) ) {
00104     std::ostringstream msg;
00105     msg << "Font:" << filename << ": misses glyph-height";
00106     throw std::runtime_error(msg.str());
00107   }
00108 
00109   lisp::ListIterator iter(config_l);
00110   while(iter.next()) {
00111     const std::string& token = iter.item();
00112     if( token == "surface" ) {
00113       const lisp::Lisp * glyphs_val = iter.lisp();
00114       int local_char_width;
00115       bool monospaced;
00116       GlyphWidth local_glyph_width;
00117       std::string glyph_image;
00118       std::string shadow_image;
00119       std::vector<std::string> chars;
00120       if( ! glyphs_val->get("glyph-width", local_char_width) ) {
00121         local_char_width = def_char_width;
00122       }
00123       if( ! glyphs_val->get("monospace", monospaced ) ) {
00124         local_glyph_width = glyph_width;
00125       }
00126       else {
00127         if( monospaced ) local_glyph_width = FIXED;
00128         else local_glyph_width = VARIABLE;
00129       }
00130       if( ! glyphs_val->get("glyphs", glyph_image) ) {
00131         std::ostringstream msg;
00132         msg << "Font:" << filename << ": missing glyphs image";
00133         throw std::runtime_error(msg.str());
00134       }
00135       if( ! glyphs_val->get("shadows", shadow_image) ) {
00136         std::ostringstream msg;
00137         msg << "Font:" << filename << ": missing shadows image";
00138         throw std::runtime_error(msg.str());
00139       }
00140       if( ! glyphs_val->get("chars", chars) || chars.size() == 0) {
00141         std::ostringstream msg;
00142         msg << "Font:" << filename << ": missing chars definition";
00143         throw std::runtime_error(msg.str());
00144       }
00145 
00146       if( local_char_width==0 ) {
00147         std::ostringstream msg;
00148         msg << "Font:" << filename << ": misses glyph-width for some surface";
00149         throw std::runtime_error(msg.str());
00150       }
00151 
00152       loadFontSurface(glyph_image, shadow_image, chars,
00153                       local_glyph_width, local_char_width);
00154     }
00155   }
00156 }
00157 
00158 void 
00159 Font::loadFontSurface(
00160   const std::string &glyphimage,
00161   const std::string &shadowimage,
00162   const std::vector<std::string> &chars,
00163   GlyphWidth glyph_width,
00164   int char_width
00165   )
00166 {
00167   SurfacePtr glyph_surface  = Surface::create("images/engine/fonts/" + glyphimage);
00168   SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage);
00169 
00170   int surface_idx = glyph_surfaces.size();
00171   glyph_surfaces.push_back(glyph_surface);
00172   shadow_surfaces.push_back(shadow_surface);
00173 
00174   int row=0, col=0;
00175   int wrap = glyph_surface->get_width() / char_width;
00176  
00177   SDL_Surface *surface = NULL;
00178   
00179   if( glyph_width == VARIABLE ) {
00180     //this does not work:
00181     // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture();
00182     surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1);
00183     if(surface == NULL) {
00184       std::ostringstream msg;
00185       msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError();
00186       throw std::runtime_error(msg.str());
00187     }
00188     SDL_LockSurface(surface);
00189   }
00190 
00191   for( unsigned int i = 0; i < chars.size(); i++) {
00192     for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) {
00193       int y = row * char_height;
00194       int x = col * char_width;
00195       if( ++col == wrap ) { col=0; row++; }
00196       if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue;
00197         
00198       Glyph glyph;
00199       glyph.surface_idx   = surface_idx;
00200       
00201       if( glyph_width == FIXED ) 
00202       {
00203         glyph.rect    = Rectf(x, y, x + char_width, y + char_height);
00204         glyph.offset  = Vector(0, 0);
00205         glyph.advance = char_width;
00206       }
00207       else 
00208       {
00209         int left = x;
00210         while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
00211           left += 1;
00212         int right = x + char_width - 1;
00213         while (right > left && vline_empty(surface, right, y, y + char_height, 64))
00214           right -= 1;
00215           
00216         if (left <= right) 
00217         {
00218           glyph.offset  = Vector(x-left, 0);
00219           glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable
00220         } 
00221         else 
00222         { // glyph is completly transparent
00223           glyph.offset  = Vector(0, 0);
00224           glyph.advance = char_width + 1; // FIXME: might be useful to make spacing configurable
00225         }
00226 
00227         glyph.rect = Rectf(x,  y, x + char_width, y + char_height);
00228       }
00229 
00230       glyphs[*chr] = glyph;
00231     }
00232     if( col>0 && col <= wrap ) { 
00233       col = 0;
00234       row++;
00235     }
00236   }
00237   
00238   if( surface != NULL ) {
00239     SDL_UnlockSurface(surface);
00240     SDL_FreeSurface(surface);
00241   }
00242 }
00243 
00244 Font::~Font()
00245 {
00246 }
00247 
00248 float
00249 Font::get_text_width(const std::string& text) const
00250 {
00251   float curr_width = 0;
00252   float last_width = 0;
00253 
00254   for(UTF8Iterator it(text); !it.done(); ++it)
00255   {
00256     if (*it == '\n')
00257     {
00258       last_width = std::max(last_width, curr_width);
00259       curr_width = 0;
00260     }
00261     else
00262     {
00263       if( glyphs.at(*it).surface_idx != -1 )
00264         curr_width += glyphs[*it].advance;
00265       else 
00266         curr_width += glyphs[0x20].advance;
00267     }
00268   }
00269 
00270   return std::max(curr_width, last_width);
00271 }
00272 
00273 float
00274 Font::get_text_height(const std::string& text) const
00275 {
00276   std::string::size_type text_height = char_height;
00277 
00278   for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
00279   { // since UTF8 multibyte characters are decoded with values
00280     // outside the ASCII range there is no risk of overlapping and
00281     // thus we don't need to decode the utf-8 string
00282     if (*it == '\n')
00283       text_height += char_height + 2;
00284   }
00285 
00286   return text_height;
00287 }
00288 
00289 float
00290 Font::get_height() const
00291 {
00292   return char_height;
00293 }
00294 
00295 std::string
00296 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
00297 {
00298   // if text is already smaller, return full text
00299   if ((int)s.length() <= line_length) {
00300     if (overflow) *overflow = "";
00301     return s;
00302   }
00303 
00304   // if we can find a whitespace character to break at, return text up to this character
00305   int i = line_length;
00306   while ((i > 0) && (s[i] != ' ')) i--;
00307   if (i > 0) {
00308     if (overflow) *overflow = s.substr(i+1);
00309     return s.substr(0, i);
00310   }
00311 
00312   // FIXME: wrap at line_length, taking care of multibyte characters
00313   if (overflow) *overflow = "";
00314   return s;
00315 }
00316 
00317 std::string
00318 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
00319 {
00320   std::string s = s_;
00321 
00322   // if text is already smaller, return full text
00323   if (get_text_width(s) <= width) {
00324     if (overflow) *overflow = "";
00325     return s;
00326   }
00327 
00328   // if we can find a whitespace character to break at, return text up to this character
00329   for (int i = s.length()-1; i >= 0; i--) {
00330     std::string s2 = s.substr(0,i);
00331     if (s[i] != ' ') continue;
00332     if (get_text_width(s2) <= width) {
00333       if (overflow) *overflow = s.substr(i+1);
00334       return s.substr(0, i);
00335     }
00336   }
00337   
00338   // FIXME: hard-wrap at width, taking care of multibyte characters
00339   if (overflow) *overflow = "";
00340   return s;
00341 }
00342 
00343 void
00344 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
00345            FontAlignment alignment, DrawingEffect drawing_effect, Color color,
00346            float alpha) const
00347 {
00348   float x = pos_.x;
00349   float y = pos_.y;
00350 
00351   std::string::size_type last = 0;
00352   for(std::string::size_type i = 0;; ++i)
00353   {
00354     if (text[i] == '\n' || i == text.size())
00355     {
00356       std::string temp = text.substr(last, i - last);
00357 
00358       // calculate X positions based on the alignment type
00359       Vector pos = Vector(x, y);
00360 
00361       if(alignment == ALIGN_CENTER)
00362         pos.x -= get_text_width(temp) / 2;
00363       else if(alignment == ALIGN_RIGHT)
00364         pos.x -= get_text_width(temp);
00365 
00366       // Cast font position to integer to get a clean drawing result and
00367       // no blurring as we would get with subpixel positions
00368       pos.x = static_cast<int>(pos.x);
00369 
00370       draw_text(renderer, temp, pos, drawing_effect, color, alpha);
00371 
00372       if (i == text.size())
00373         break;
00374 
00375       y += char_height + 2;
00376       last = i + 1;
00377     }
00378   }
00379 }
00380 
00381 void
00382 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
00383                 DrawingEffect drawing_effect, Color color, float alpha) const
00384 {
00385   if(shadowsize > 0)
00386     draw_chars(renderer, false, text, 
00387                pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
00388 
00389   draw_chars(renderer, true, text, pos, drawing_effect, color, alpha);
00390 }
00391 
00392 void
00393 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
00394                  const Vector& pos, DrawingEffect drawing_effect, Color color,
00395                  float alpha) const
00396 {
00397   Vector p = pos;
00398 
00399   for(UTF8Iterator it(text); !it.done(); ++it)
00400   {
00401     if(*it == '\n')
00402     {
00403       p.x = pos.x;
00404       p.y += char_height + 2;
00405     }
00406     else if(*it == ' ')
00407     {
00408       p.x += glyphs[0x20].advance;
00409     }
00410     else
00411     {
00412       Glyph glyph;
00413       if( glyphs.at(*it).surface_idx != -1 )
00414         glyph = glyphs[*it];
00415       else 
00416         glyph = glyphs[0x20];
00417 
00418       DrawingRequest request;
00419 
00420       request.pos = p + glyph.offset;
00421       request.drawing_effect = drawing_effect;
00422       request.color = color;
00423       request.alpha = alpha;
00424 
00425       SurfacePartRequest surfacepartrequest;
00426       surfacepartrequest.size = glyph.rect.p2 - glyph.rect.p1;
00427       surfacepartrequest.source = glyph.rect.p1;
00428       surfacepartrequest.surface = notshadow ? glyph_surfaces[glyph.surface_idx].get() : shadow_surfaces[glyph.surface_idx].get();
00429 
00430       request.request_data = &surfacepartrequest;
00431       renderer->draw_surface_part(request);
00432 
00433       p.x += glyph.advance;
00434     }
00435   }
00436 }
00437 
00438 /* EOF */

Generated on Mon Apr 14 03:38:27 2014 for SuperTux by  doxygen 1.5.1