Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/fontdata/src/lib/graphics/text_engine/font.cc @ 8760

Last change on this file since 8760 was 8759, checked in by bensch, 18 years ago

orxonox/trunk: Material Copy constructor as should be

File size: 16.7 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_GRAPHICS
17
18#include "font.h"
19
20#ifdef HAVE_SDL_IMAGE_H
21#include <SDL_image.h>
22#else
23#include <SDL/SDL_image.h>
24#endif
25
26#include "default_font.xpm"
27
28#include "debug.h"
29#include "compiler.h"
30
31
32Font::Font()
33  : data(Font::defaultFontData)
34{
35  this->init();
36
37}
38
39/**
40 * @brief constructs a Font out of a TTF-FIle
41 * @param fontFile the File to load the font from
42 * @param fontSize the Size of the Font in Pixels
43 */
44Font::Font(const std::string& fontFile, unsigned int renderSize)
45  : data(Font::defaultFontData)
46{
47  this->init();
48
49  if (!fontFile.empty())
50    this->loadFontFromTTF(fontFile, renderSize);
51}
52
53
54/**
55 * @brief constructs a Font out of an ImageFile
56 * @param imageFile the ImageFile to load the Font From.
57 */
58Font::Font(const std::string& imageFile)
59  : data(Font::defaultFontData)
60{
61  this->init();
62
63  this->setName(imageFile);
64  //  this->setSize(fontSize);
65  SDL_Surface* image = NULL;
66  if (!imageFile.empty())
67    image = IMG_Load(imageFile.c_str());
68  else
69    return;
70  if (image != NULL)
71  {
72    this->loadFontFromSDL_Surface(image);
73    SDL_FreeSurface(image);
74  }
75  else
76    PRINTF(1)("loading from surface %s failed: %s\n", imageFile.c_str(), IMG_GetError());
77}
78
79/**
80 * @brief constructs a Font
81 * @param xpmArray the xpm-ARRAY to load the font from
82 */
83Font::Font(char** xpmArray)
84  : data(Font::defaultFontData)
85{
86  this->init();
87  this->setName("XPM-array-font");
88  //  this->setSize(fontSize);
89  SDL_Surface* image = NULL;
90  if (xpmArray != NULL)
91    image = IMG_ReadXPMFromArray(xpmArray);
92  if (image != NULL)
93  {
94    this->loadFontFromSDL_Surface(image);
95    SDL_FreeSurface(image);
96  }
97  else
98    PRINTF(1)("Loading from XPM-array failed: %s\n", IMG_GetError());
99}
100
101
102/**
103 * @brief destructs a font
104 *
105 * this releases the memory a font uses to be opened.
106 * deletes the glLists, and the TTF-handler, if present.
107 */
108Font::~Font()
109{ }
110
111Font& Font::operator=(const Font& font)
112{
113  Material::operator=(font);
114  this->data = font.data;
115
116  return *this;
117};
118
119
120/**
121 * @brief initializes a Font (with default values)
122 */
123void Font::init()
124{
125  this->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
126
127  this->setClassID(CL_FONT, "Font");
128  if (Font::defaultFontData.get() == NULL)
129  {
130     Font::initDefaultFont();
131    this->data = Font::defaultFontData;
132  }
133}
134
135FontDataPointer Font::defaultFontData(NULL);
136
137/**
138 * @brief initializes the default font
139 */
140void Font::initDefaultFont()
141{
142  // temporarily create a Font.
143  Font::defaultFontData = FontDataPointer(new FontData);
144  // apply the Data.
145  printf("before: %p\n", defaultFontData.get());
146  Font::defaultFontData = Font(font_xpm).data;
147  printf("after: %p\n", defaultFontData.get());
148}
149
150/**
151 * @brief sets The Font.
152 * @param fontFile The file containing the font.
153 * @returns true if loaded, false if something went wrong, or if a font was loaded before.
154 */
155bool Font::loadFontFromTTF(const std::string& fontFile, unsigned int renderSize)
156{
157  this->data = FontDataPointer (new FontData());
158
159  this->setName(fontFile);
160  this->data->fontTTF = TTF_OpenFont(fontFile.c_str(), renderSize);
161  this->data->renderSize = renderSize;
162
163  if(this->data->fontTTF != NULL)
164  {
165    this->setStyle("c");
166    if (this->createFastTexture())
167      return true;
168    else
169    {
170      this->data = Font::defaultFontData;
171      return false;
172    }
173  }
174  else
175  {
176    PRINTF(1)("TTF_OpenFont: %s\n", TTF_GetError());
177    this->data = Font::defaultFontData;
178    return false;
179  }
180
181}
182
183/**
184 * @brief loads a font From an XPM-array.
185 * @param xpmArray the array of the XPM to load the font from.
186 */
187bool Font::loadFontFromSDL_Surface(SDL_Surface* surface)
188{
189  if(surface == NULL)
190    return false;
191
192  this->data = FontDataPointer (new FontData());
193  // loading to a texture.
194
195  bool hasAlpha;
196  SDL_Surface* newSurf = Texture::prepareSurface(surface, hasAlpha);
197  if (newSurf != NULL)
198  {
199    this->data->texData->setSurface(newSurf);
200    this->data->texData->setAlpha(hasAlpha);
201    this->setTexture(Texture::loadTexToGL(newSurf));
202  }
203  else
204  {
205    this->data = Font::defaultFontData;
206    return false;
207  }
208
209  // initializing the Glyphs.
210  if (this->data->glyphArray == NULL)
211  {
212    float cx,cy;
213    Glyph* tmpGlyph;
214    this->data->glyphArray = new Glyph*[FONT_HIGHEST_KNOWN_CHAR];
215    for (int i = 0; i < FONT_HIGHEST_KNOWN_CHAR; i++)
216    {
217      tmpGlyph = this->data->glyphArray[i] = new Glyph;
218      cx=(float)(i%16)/16.0f;                  // X Position Of Current Character
219      cy=(float)(i/16)/16.0f;                  // Y Position Of Current Character
220
221      tmpGlyph->texCoord[0] = cx;
222      tmpGlyph->texCoord[1] = cx+0.0625f;
223      tmpGlyph->texCoord[2] = cy;
224      tmpGlyph->texCoord[3] = cy+0.0625f;
225      tmpGlyph->minX = 0.0f;
226      tmpGlyph->maxX = 1.0f;
227      tmpGlyph->minY = 0.0f;
228      tmpGlyph->maxY = 1.0f;
229      tmpGlyph->width = 1.0f;
230      tmpGlyph->advance = 1.0f;
231      tmpGlyph->bearingX = 0.0f;
232      tmpGlyph->bearingY = 0.0f;
233      tmpGlyph->height = 1.0f;
234    }
235  }
236  return true;
237}
238
239
240/**
241 * @brief sets a specific data->renderStyle
242 * @param data->renderStyle the Style to render: a string (char-array) containing:
243 *   i: italic, b: bold, u, underline
244 */
245void Font::setStyle(const std::string& renderStyle)
246{
247  this->data->renderStyle = TTF_STYLE_NORMAL;
248
249  for (unsigned int i = 0; i < renderStyle.size(); i++)
250  {
251    if (renderStyle[i] == 'b')
252      this->data->renderStyle |= TTF_STYLE_BOLD;
253    else if (renderStyle[i] == 'i')
254      this->data->renderStyle |= TTF_STYLE_ITALIC;
255    else if (renderStyle[i] == 'u')
256      this->data->renderStyle |= TTF_STYLE_UNDERLINE;
257  }
258  if (likely(this->data->fontTTF != NULL))
259    TTF_SetFontStyle(this->data->fontTTF, this->data->renderStyle);
260  //  else
261  //    PRINTF(2)("Font was not initialized, please do so before setting the Font-Style.\n");
262}
263
264/**
265 * @brief creates and exports an Image, that has all the characters
266 * stored in a Array (as an image)
267 * @param fileName the File to write the image into.
268 */
269void Font::createAsciiImage(const std::string& fileName, unsigned int size) const
270{
271  if (this->data->fontTTF == NULL)
272    return;
273  int height = this->getMaxHeight();
274
275  //
276  // Surface definition.
277  SDL_Rect tmpRect; // this represents a Rectangle for blitting.
278  SDL_Surface* tmpSurf =  SDL_CreateRGBSurface(SDL_SWSURFACE,
279                          height*size, height*size,
280                          32,
281#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
282                          0x000000FF,
283                          0x0000FF00,
284                          0x00FF0000,
285                          0xFF000000
286#else
287                          0xFF000000,
288                          0x00FF0000,
289                          0x0000FF00,
290                          0x000000FF
291#endif
292                                              );
293  tmpRect.x = 0; tmpRect.y = 0; tmpRect.w = tmpSurf->w; tmpRect.h = tmpSurf->h;
294  SDL_SetClipRect(tmpSurf, &tmpRect);
295
296  int posX, posY;
297  // all the interessting Glyphs
298  for (posY = 0; posY < 16; posY++)
299  {
300    for (posX = 0; posX < 16; posX++)
301    {
302      SDL_Surface* glyphSurf = NULL;
303      if (likely(this->data->fontTTF != NULL))
304      {
305        SDL_Color white = {255, 255, 255};
306        glyphSurf = TTF_RenderGlyph_Blended(this->data->fontTTF, posX+size*posY, white);
307      }
308      if( glyphSurf != NULL )
309      {
310        tmpRect.x = height*posX;
311        tmpRect.y = height*posY;
312        SDL_SetAlpha(glyphSurf, 0, 0);
313
314        SDL_BlitSurface(glyphSurf, NULL, tmpSurf, &tmpRect);
315        SDL_FreeSurface(glyphSurf);
316      }
317    }
318  }
319  SDL_SaveBMP(tmpSurf, fileName.c_str());
320  SDL_FreeSurface(tmpSurf);
321}
322
323
324/**
325 * @returns the maximum height of the Font, if the font was initialized, 0 otherwise
326 */
327int Font::getMaxHeight() const
328{
329  if (likely (this->data->fontTTF != NULL))
330    return TTF_FontHeight(this->data->fontTTF);
331  else
332    return 1;
333}
334
335/**
336 * @returns the maximum ascent of the Font, if the font was initialized, 0 otherwise
337 *
338 * the ascent is the pixels of the font above the baseline
339 */
340int Font::getMaxAscent() const
341{
342  if (likely(this->data->fontTTF != NULL))
343    return TTF_FontAscent(this->data->fontTTF);
344  else
345    return 0;
346}
347
348/**
349 * @returns the maximum descent of the Font, if the font was initialized, 0 otherwise
350 *
351 * the descent is the pixels of the font below the baseline
352 */
353int Font::getMaxDescent() const
354{
355  if (likely(this->data->fontTTF != NULL))
356    return TTF_FontDescent(this->data->fontTTF);
357  else
358    return 0;
359}
360
361/**
362 * @param glyph: The Glyph to set the Parameters to.
363 * @param character: The character to get info about.
364 * @returns a Glyph struct of a character. This Glyph is a pointer,
365 * and MUST be deleted by the user..
366 *
367 * This only works for horizontal fonts. see
368 * http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
369 * for more info about vertical Fonts
370 */
371bool Font::getGlyphMetrics(Glyph* glyph, Uint16 character)
372{
373  glyph->character = character;
374  if (likely (this->data->fontTTF!= NULL))
375  {
376    int miX, maX, miY, maY, adv;
377    if (TTF_GlyphMetrics(this->data->fontTTF, glyph->character,
378                     &miX, &maX,
379                     &miY, &maY,
380                     &adv) == -1)
381      return false;
382    glyph->minX = (float)miX / (float)this->data->renderSize;
383    glyph->maxX = (float)maX / (float)this->data->renderSize;
384    glyph->minY = (float)miY / (float)this->data->renderSize;
385    glyph->maxY = (float)maY / (float)this->data->renderSize;
386    glyph->advance = (float)adv / (float)this->data->renderSize;
387
388    // Calculate the Rest.
389    glyph->height = glyph->maxY - glyph->minY;
390    glyph->width = glyph->maxX - glyph->minX;
391    glyph->bearingX = (glyph->advance - glyph->width) / 2;
392    glyph->bearingY = glyph->maxY;
393
394    //printf("%c:: %d %d %d %d %d\n", character, miX, maX, miY, maY, adv);
395
396    return true;
397  }
398  return false;
399}
400
401/**
402 * @brief creates a Fast-Texture of this Font
403 */
404bool Font::createFastTexture()
405{
406  /* interesting GLYPHS:
407  *  32: space
408  *  33-47: Special Characters.
409  *  48-57: 0-9
410  *  58-63: some more special chars (minor)
411  *  65-90: A-Z
412  *  97-122: a-z
413  */
414  int numberOfGlyphs = 91;
415
416  this->initGlyphs(32, numberOfGlyphs);
417  //  this->data->glyphArray[32]->width = .5f; //!< @todo find out the real size of a Space
418
419  int rectSize = this->findOptimalFastTextureSize();
420
421  // setting default values. (maybe not needed afterwards)
422  SDL_Color tmpColor;  tmpColor.r = tmpColor.g = tmpColor.b = 0;
423  // Surface definition.
424  SDL_Rect tmpRect; // this represents a Rectangle for blitting.
425  SDL_Surface* tmpSurf =  SDL_CreateRGBSurface(SDL_HWSURFACE,
426                          rectSize, rectSize,
427                          32,
428#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
429                          0x000000FF,
430                          0x0000FF00,
431                          0x00FF0000,
432                          0xFF000000
433#else
434                          0xFF000000,
435                          0x00FF0000,
436                          0x0000FF00,
437                          0x000000FF
438#endif
439                                              );
440  tmpRect.x = 0; tmpRect.y = 0; tmpRect.w = tmpSurf->w; tmpRect.h = tmpSurf->h;
441  SDL_SetClipRect(tmpSurf, &tmpRect);
442  int maxLineHeight = this->getMaxHeight();
443
444  // all the interessting Glyphs
445  for (int i = 0; i < 128; i++)
446  {
447    SDL_Surface* glyphSurf = NULL;
448    Glyph* tmpGlyph;
449
450    if (tmpGlyph = this->data->glyphArray[i])
451    {
452      if (tmpGlyph->height*this->data->renderSize > maxLineHeight)
453        maxLineHeight = (int)(tmpGlyph->height*this->data->renderSize);
454
455      if (tmpRect.x+tmpGlyph->advance*this->data->renderSize > tmpSurf->w)
456      {
457        tmpRect.x = 0;
458        tmpRect.y = tmpRect.y + maxLineHeight;
459      }
460      if (tmpRect.y + maxLineHeight > tmpSurf->h)
461      {
462        PRINTF(1)("Protection, so font cannot write over the boundraries (!!this should not heappen!!)\n");
463        break;
464      }
465      // reading in the new Glyph
466      if (likely(this->data->fontTTF != NULL))
467      {
468        SDL_Color white = {255, 255, 255};
469        glyphSurf = TTF_RenderGlyph_Blended(this->data->fontTTF, i, white);
470      }
471      if( glyphSurf != NULL )
472      {
473        SDL_SetAlpha(glyphSurf, 0, 0);
474        int tmpY = tmpRect.y;
475        tmpRect.y += this->getMaxAscent()-(int)((float)tmpGlyph->bearingY*this->data->renderSize);
476        SDL_BlitSurface(glyphSurf, NULL, tmpSurf, &tmpRect);
477        tmpRect.y = tmpY;
478
479        tmpGlyph->texCoord[0] = (float)((float)tmpRect.x )/(float)tmpSurf->w;
480        tmpGlyph->texCoord[1] = (float)((float)tmpRect.x + tmpGlyph->width*(float)this->data->renderSize)/(float)tmpSurf->w;
481        tmpGlyph->texCoord[2] = (float)(tmpRect.y)/(float)tmpSurf->w;
482        tmpGlyph->texCoord[3] = (float)((float)tmpRect.y+(float)this->getMaxHeight())/(float)tmpSurf->w;
483        SDL_FreeSurface(glyphSurf);
484        tmpRect.x += (int)(tmpGlyph->width * this->data->renderSize) + 1;
485      }
486    }
487  }
488  // outputting the GLYPH-table
489//       char outName[1024];
490//       sprintf( outName, "%s-glyphs.bmp", this->getName());
491//       SDL_SaveBMP(tmpSurf, outName);
492  this->data->texData->setAlpha(true);
493  if (this->data->texData->setSurface(tmpSurf))
494    this->setTexture(Texture::loadTexToGL(tmpSurf));
495  return true;
496}
497
498/**
499 * @brief the Internal implementation of setting up the Texture.
500 * @param texture the Texture to load.
501 * @returns true on success, false otherwise.
502 */
503bool Font::setTexture(GLuint texture)
504{
505  bool retVal = this->data->texData->setTexture(texture);
506  this->setDiffuseMap(data->texData, 0);
507  printf("this->texture %d\n", texture);
508  //printf(this->getT)
509  this->debug();
510  return retVal;
511};
512
513/**
514 * @brief stores Glyph Metrics in an Array.
515 * @param from The Glyph to start from.
516 * @param count The number of Glyphs to start From.
517 */
518void Font::initGlyphs(Uint16 from, Uint16 count)
519{
520  /* initialize the Array, and set all its entries to NULL
521  *  only if the Glyph-array has not been initialized
522  */
523  if (!this->data->glyphArray)
524  {
525    this->data->glyphArray = new Glyph*[FONT_HIGHEST_KNOWN_CHAR];
526    for (int i = 0; i < FONT_HIGHEST_KNOWN_CHAR; i++)
527      this->data->glyphArray[i] = NULL;
528  }
529
530  Uint16 lastGlyph = from + count;
531
532  for (int i = from; i <= lastGlyph; i++)
533  {
534    // setting up all the Glyphs we like.
535    Glyph* newGlyph = new Glyph;
536    if (getGlyphMetrics(newGlyph, i))
537      data->glyphArray[i] = newGlyph;
538    else
539    {
540      delete newGlyph;
541      data->glyphArray[i] = NULL;
542    }
543  }
544  return;
545}
546
547/**
548 * @returns the optimal size to use as the texture size
549 *
550 * @todo: this algorithm can be a lot faster, althought it does
551 * not really matter within the init-context, and 128 glyphs.
552 *
553 * This function searches for a 2^n sizes texture-size, this is for
554 * openGL-version < 1.2 compatibility ( and because it is realy easy like this :))
555 */
556int Font::findOptimalFastTextureSize()
557{
558  if (this->data->glyphArray == NULL)
559    return 0;
560
561  unsigned int i;
562  unsigned int x,y; // the counters
563  int maxLineHeight = this->getMaxHeight();
564  unsigned int size = 32;  // starting Value, we have to start somewhere 32 seems reasonable. (take any small enough 2^i number)
565  bool sizeOK = false;
566  Glyph* tmpGlyph;
567
568  while (!sizeOK)
569  {
570    x = 0; y = 0;
571    for (i = 0; i < FONT_HIGHEST_KNOWN_CHAR; i++)
572    {
573      if((tmpGlyph = this->data->glyphArray[i]) != NULL)
574      {
575        // getting the height of the highest Glyph in the Line.
576        if (tmpGlyph->height*this->data->renderSize > maxLineHeight)
577          maxLineHeight = (int)(tmpGlyph->height*this->data->renderSize);
578
579        if (x + tmpGlyph->advance*this->data->renderSize > size)
580        {
581          x = 0;
582          y = y + maxLineHeight;
583          //maxLineHeight = 0;
584        }
585        if (y + maxLineHeight + 1 > size)
586          break;
587        x += (int)(tmpGlyph->advance*this->data->renderSize)+1;
588
589      }
590    }
591    if (i >= FONT_HIGHEST_KNOWN_CHAR-1 || size > 8192)
592      sizeOK = true;
593    else
594      size *= 2;
595  }
596  return size;
597}
598
599
600/**
601 * @brief a simple function to get some interesting information about this class
602 */
603void Font::debug() const
604{
605  Material::debug();
606
607  PRINT(0)("TEST %p and %p\n", this->data.get(), this->data->texData.get());
608  // print the loaded font's style
609  int style = TTF_STYLE_NORMAL;
610  if (likely(this->data->fontTTF != NULL))
611    style = TTF_GetFontStyle(this->data->fontTTF);
612  PRINTF(0)("The font style is:");
613  if(style==TTF_STYLE_NORMAL)
614    PRINTF(0)(" normal");
615  else
616  {
617    if(style&TTF_STYLE_BOLD)
618      PRINTF(0)(" bold");
619    if(style&TTF_STYLE_ITALIC)
620      PRINTF(0)(" italic");
621    if(style&TTF_STYLE_UNDERLINE)
622      PRINTF(0)(" underline");
623  }
624  PRINTF(0)("\n");
625}
Note: See TracBrowser for help on using the repository browser.