2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 // Ingo Ruhnke <grumbel@gmail.com>
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.
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.
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/>.
24 #include <SDL_image.h>
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"
41 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
43 Uint8* pixels = (Uint8*)surface->pixels;
45 for(int y = start_y; y < end_y; ++y)
47 const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
58 Font::Font(GlyphWidth glyph_width_,
59 const std::string& filename,
61 glyph_width(glyph_width_),
65 shadowsize(shadowsize_),
70 for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
72 const std::string fontdir = FileSystem::dirname(filename);
73 const std::string fontname = FileSystem::basename(filename);
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_);
87 Font::loadFontFile(const std::string &filename)
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");
95 std::ostringstream msg;
96 msg << "Font file:" << filename << ": is not a supertux-font file";
97 throw std::runtime_error(msg.str());
100 int def_char_width=0;
102 if( !config_l->get("glyph-width",def_char_width) ) {
103 log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
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());
112 config_l->get("glyph-border", border);
113 config_l->get("rtl", rtl);
115 lisp::ListIterator iter(config_l);
117 const std::string& token = iter.item();
118 if( token == "surface" ) {
119 const lisp::Lisp * glyphs_val = iter.lisp();
120 int local_char_width;
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;
129 if( ! glyphs_val->get("monospace", monospaced ) ) {
130 local_glyph_width = glyph_width;
133 if( monospaced ) local_glyph_width = FIXED;
134 else local_glyph_width = VARIABLE;
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());
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());
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());
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());
158 loadFontSurface(glyph_image, shadow_image, chars,
159 local_glyph_width, local_char_width);
165 Font::loadFontSurface(
166 const std::string &glyphimage,
167 const std::string &shadowimage,
168 const std::vector<std::string> &chars,
169 GlyphWidth glyph_width_,
173 SurfacePtr glyph_surface = Surface::create("images/engine/fonts/" + glyphimage);
174 SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage);
176 int surface_idx = glyph_surfaces.size();
177 glyph_surfaces.push_back(glyph_surface);
178 shadow_surfaces.push_back(shadow_surface);
181 int wrap = glyph_surface->get_width() / char_width;
183 SDL_Surface *surface = NULL;
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());
194 SDL_LockSurface(surface);
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;
205 glyph.surface_idx = surface_idx;
207 if( glyph_width_ == FIXED || isdigit(*chr) )
209 glyph.rect = Rectf(x, y, x + char_width, y + char_height);
210 glyph.offset = Vector(0, 0);
211 glyph.advance = char_width;
215 if (y + char_height > surface->h)
217 log_warning << "error: font definition contains more letter then the images: " << glyphimage << std::endl;
222 while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
224 int right = x + char_width - 1;
225 while (right > left && vline_empty(surface, right, y, y + char_height, 64))
230 glyph.offset = Vector(x-left, 0);
231 glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable
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
239 glyph.rect = Rectf(x, y, x + char_width, y + char_height);
242 glyphs[*chr] = glyph;
244 if( col>0 && col <= wrap ) {
251 if( surface != NULL ) {
252 SDL_UnlockSurface(surface);
253 SDL_FreeSurface(surface);
262 Font::get_text_width(const std::string& text) const
264 float curr_width = 0;
265 float last_width = 0;
267 for(UTF8Iterator it(text); !it.done(); ++it)
271 last_width = std::max(last_width, curr_width);
276 if( glyphs.at(*it).surface_idx != -1 )
277 curr_width += glyphs[*it].advance;
279 curr_width += glyphs[0x20].advance;
283 return std::max(curr_width, last_width);
287 Font::get_text_height(const std::string& text) const
289 std::string::size_type text_height = char_height;
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
296 text_height += char_height + 2;
303 Font::get_height() const
309 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
311 // if text is already smaller, return full text
312 if ((int)s.length() <= line_length) {
313 if (overflow) *overflow = "";
317 // if we can find a whitespace character to break at, return text up to this character
319 while ((i > 0) && (s[i] != ' ')) i--;
321 if (overflow) *overflow = s.substr(i+1);
322 return s.substr(0, i);
325 // FIXME: wrap at line_length, taking care of multibyte characters
326 if (overflow) *overflow = "";
331 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
335 // if text is already smaller, return full text
336 if (get_text_width(s) <= width) {
337 if (overflow) *overflow = "";
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);
351 // FIXME: hard-wrap at width, taking care of multibyte characters
352 if (overflow) *overflow = "";
357 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
358 FontAlignment alignment, DrawingEffect drawing_effect, Color color,
364 std::string::size_type last = 0;
365 for(std::string::size_type i = 0;; ++i)
367 if (text[i] == '\n' || i == text.size())
369 std::string temp = text.substr(last, i - last);
371 // calculate X positions based on the alignment type
372 Vector pos = Vector(x, y);
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);
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);
383 draw_text(renderer, temp, pos, drawing_effect, color, alpha);
385 if (i == text.size())
388 y += char_height + 2;
395 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
396 DrawingEffect drawing_effect, Color color, float alpha) const
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);
402 draw_chars(renderer, true, rtl ? std::string(text.rbegin(), text.rend()) : text, pos, drawing_effect, color, alpha);
406 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
407 const Vector& pos, DrawingEffect drawing_effect, Color color,
412 for(UTF8Iterator it(text); !it.done(); ++it)
417 p.y += char_height + 2;
421 p.x += glyphs[0x20].advance;
426 if( glyphs.at(*it).surface_idx != -1 )
429 glyph = glyphs[0x20];
431 DrawingRequest request;
433 request.pos = p + glyph.offset;
434 request.drawing_effect = drawing_effect;
435 request.color = color;
436 request.alpha = alpha;
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();
443 request.request_data = &surfacepartrequest;
444 renderer->draw_surface_part(request);
446 p.x += glyph.advance;