]> icculus.org git repositories - divverent/darkplaces.git/blob - ft2.c
stashing changes...
[divverent/darkplaces.git] / ft2.c
1 /* FreeType 2 and UTF-8 encoding support for
2  * DarkPlaces
3  */
4 #include "quakedef.h"
5
6 #include "ft2.h"
7
8 #include "ft2_defs.h"
9
10 /*
11 ================================================================================
12 Function definitions. Taken from the freetype2 headers.
13 ================================================================================
14 */
15
16
17 FT_EXPORT( FT_Error )
18 (*qFT_Init_FreeType)( FT_Library  *alibrary );
19 FT_EXPORT( FT_Error )
20 (*qFT_Done_FreeType)( FT_Library  library );
21 FT_EXPORT( FT_Error )
22 (*qFT_New_Face)( FT_Library   library,
23                  const char*  filepathname,
24                  FT_Long      face_index,
25                  FT_Face     *aface );
26 FT_EXPORT( FT_Error )
27 (*qFT_New_Memory_Face)( FT_Library      library,
28                         const FT_Byte*  file_base,
29                         FT_Long         file_size,
30                         FT_Long         face_index,
31                         FT_Face        *aface );
32 FT_EXPORT( FT_Error )
33 (*qFT_Done_Face)( FT_Face  face );
34 FT_EXPORT( FT_Error )
35 (*qFT_Select_Size)( FT_Face  face,
36                     FT_Int   strike_index );
37 FT_EXPORT( FT_Error )
38 (*qFT_Request_Size)( FT_Face          face,
39                      FT_Size_Request  req );
40 FT_EXPORT( FT_Error )
41 (*qFT_Set_Char_Size)( FT_Face     face,
42                       FT_F26Dot6  char_width,
43                       FT_F26Dot6  char_height,
44                       FT_UInt     horz_resolution,
45                       FT_UInt     vert_resolution );
46 FT_EXPORT( FT_Error )
47 (*qFT_Set_Pixel_Sizes)( FT_Face  face,
48                         FT_UInt  pixel_width,
49                         FT_UInt  pixel_height );
50 FT_EXPORT( FT_Error )
51 (*qFT_Load_Glyph)( FT_Face   face,
52                    FT_UInt   glyph_index,
53                    FT_Int32  load_flags );
54 FT_EXPORT( FT_Error )
55 (*qFT_Load_Char)( FT_Face   face,
56                   FT_ULong  char_code,
57                   FT_Int32  load_flags );
58 FT_EXPORT( FT_UInt )
59 (*qFT_Get_Char_Index)( FT_Face   face,
60                        FT_ULong  charcode );
61 FT_EXPORT( FT_Error )
62 (*qFT_Render_Glyph)( FT_GlyphSlot    slot,
63                      FT_Render_Mode  render_mode );
64 FT_EXPORT( FT_Error )
65 (*qFT_Get_Kerning)( FT_Face     face,
66                     FT_UInt     left_glyph,
67                     FT_UInt     right_glyph,
68                     FT_UInt     kern_mode,
69                     FT_Vector  *akerning );
70
71 /*
72 ================================================================================
73 Support for dynamically loading the FreeType2 library
74 ================================================================================
75 */
76
77 static dllfunction_t ft2funcs[] =
78 {
79         {"FT_Init_FreeType",            (void **) &qFT_Init_FreeType},
80         {"FT_Done_FreeType",            (void **) &qFT_Done_FreeType},
81         {"FT_New_Face",                 (void **) &qFT_New_Face},
82         {"FT_New_Memory_Face",          (void **) &qFT_New_Memory_Face},
83         {"FT_Done_Face",                (void **) &qFT_Done_Face},
84         {"FT_Select_Size",              (void **) &qFT_Select_Size},
85         {"FT_Request_Size",             (void **) &qFT_Request_Size},
86         {"FT_Set_Char_Size",            (void **) &qFT_Set_Char_Size},
87         {"FT_Set_Pixel_Sizes",          (void **) &qFT_Set_Pixel_Sizes},
88         {"FT_Load_Glyph",               (void **) &qFT_Load_Glyph},
89         {"FT_Load_Char",                (void **) &qFT_Load_Char},
90         {"FT_Get_Char_Index",           (void **) &qFT_Get_Char_Index},
91         {"FT_Render_Glyph",             (void **) &qFT_Render_Glyph},
92         {"FT_Get_Kerning",              (void **) &qFT_Get_Kerning},
93         {NULL, NULL}
94 };
95
96 /// Handle for FreeType2 DLL
97 static dllhandle_t ft2_dll = NULL;
98
99 /// Memory pool for fonts
100 static mempool_t *font_mempool= NULL;
101 static rtexturepool_t *font_texturepool = NULL;
102
103 /// FreeType library handle
104 static FT_Library font_ft2lib = NULL;
105
106 /*
107 ====================
108 Font_CloseLibrary
109
110 Unload the FreeType2 DLL
111 ====================
112 */
113 void Font_CloseLibrary (void)
114 {
115         if (font_mempool)
116                 Mem_FreePool(&font_mempool);
117         if (font_texturepool)
118                 R_FreeTexturePool(&font_texturepool);
119         if (font_ft2lib && qFT_Done_FreeType)
120         {
121                 qFT_Done_FreeType(font_ft2lib);
122                 font_ft2lib = NULL;
123         }
124         Sys_UnloadLibrary (&ft2_dll);
125 }
126
127 /*
128 ====================
129 Font_OpenLibrary
130
131 Try to load the FreeType2 DLL
132 ====================
133 */
134 qboolean Font_OpenLibrary (void)
135 {
136         const char* dllnames [] =
137         {
138 #if defined(WIN64)
139                 #error path for freetype 2 dll
140 #elif defined(WIN32)
141                 #error path for freetype 2 dll
142 #elif defined(MACOSX)
143                 "libfreetype.dylib",
144 #else
145                 "libfreetype.so.6",
146                 "libfreetype.so",
147 #endif
148                 NULL
149         };
150
151         // Already loaded?
152         if (ft2_dll)
153                 return true;
154
155         // Load the DLL
156         if (!Sys_LoadLibrary (dllnames, &ft2_dll, ft2funcs))
157                 return false;
158         return true;
159 }
160
161 /*
162 ====================
163 Font_Init
164
165 Initialize the freetype2 font subsystem
166 ====================
167 */
168
169 static font_t test_font;
170
171 static void font_start(void)
172 {
173         if (!Font_OpenLibrary())
174                 return;
175
176         if (qFT_Init_FreeType(&font_ft2lib))
177         {
178                 Con_Print("ERROR: Failed to initialize the FreeType2 library!\n");
179                 Font_CloseLibrary();
180                 return;
181         }
182
183         font_mempool = Mem_AllocPool("FONT", 0, NULL);
184         if (!font_mempool)
185         {
186                 Con_Print("ERROR: Failed to allocate FONT memory pool!\n");
187                 Font_CloseLibrary();
188                 return;
189         }
190
191         font_texturepool = R_AllocTexturePool();
192         if (!font_texturepool)
193         {
194                 Con_Print("ERROR: Failed to allocate FONT texture pool!\n");
195                 Font_CloseLibrary();
196                 return;
197         }
198
199         if (!Font_LoadFont("gfx/test", 32, &test_font))
200         {
201                 Con_Print("ERROR: Failed to load test font!\n");
202                 Font_CloseLibrary();
203                 return;
204         }
205 }
206
207 static void font_shutdown(void)
208 {
209         Font_CloseLibrary();
210 }
211
212 static void font_newmap(void)
213 {
214 }
215
216 void Font_Init(void)
217 {
218         R_RegisterModule("Font_FreeType2", font_start, font_shutdown, font_newmap);
219 }
220
221 /*
222 ================================================================================
223 UTF-8 encoding and decoding functions follow.
224 ================================================================================
225 */
226
227 /** Get the number of characters in in an UTF-8 string.
228  * @param _s    An utf-8 encoded null-terminated string.
229  * @return      The number of unicode characters in the string.
230  */
231 size_t u8_strlen(const char *_s)
232 {
233         size_t len = 0;
234         unsigned char *s = (unsigned char*)_s;
235         while (*s)
236         {
237                 // ascii char
238                 if (*s <= 0x7F)
239                 {
240                         ++len;
241                         ++s;
242                         continue;
243                 }
244
245                 // start of a wide character
246                 if (*s & 0xC0)
247                 {
248                         ++len;
249                         for (++s; *s >= 0x80 && *s <= 0xC0; ++s);
250                         continue;
251                 }
252
253                 // part of a wide character, we ignore that one
254                 if (*s <= 0xBF) // 10111111
255                 {
256                         ++s;
257                         continue;
258                 }
259         }
260         return len;
261 }
262
263 /** Fetch a character from an utf-8 encoded string.
264  * @param _s      The start of an utf-8 encoded multi-byte character.
265  * @param _end    Will point to after the first multi-byte character.
266  * @return        The 32-bit integer representation of the first multi-byte character.
267  */
268 Uchar u8_getchar(const char *_s, const char **_end)
269 {
270         const unsigned char *s = (unsigned char*)_s;
271         Uchar u;
272         unsigned char mask;
273         unsigned char v;
274
275         if (*s < 0x80)
276         {
277                 if (_end)
278                         *_end = _s + 1;
279                 return (U_int32)*s;
280         }
281
282         if (*s < 0xC0)
283         {
284                 // starting within a wide character - skip it and retrieve the one after it
285                 for (++s; *s >= 0x80 && *s < 0xC0; ++s);
286                 // or we could return '?' here?
287         }
288
289         u = 0;
290         mask = 0x7F;
291         v = *s & mask;
292         for (mask >>= 1; v > (*s & mask); mask >>= 1)
293                 v = (*s & mask);
294         u = (Uchar)(*s & mask);
295         for (++s; *s >= 0x80 && *s < 0xC0; ++s)
296                 u = (u << 6) | (*s & 0x3F);
297
298         if (_end)
299                 *_end = (const char*)s;
300
301         return u;
302 }
303
304 /** Encode a wide-character into utf-8.
305  * @param w        The wide character to encode.
306  * @param to       The target buffer the utf-8 encoded string is stored to.
307  * @param maxlen   The maximum number of bytes that fit into the target buffer.
308  * @return         Number of bytes written to the buffer, or less or equal to 0 if the buffer is too small.
309  */
310 int u8_fromchar(Uchar w, char *to, size_t maxlen)
311 {
312         size_t i, j;
313         char bt;
314         char tmp[16];
315
316         if (maxlen < 1)
317                 return -2;
318
319         if (w < 0x80)
320         {
321                 to[0] = (char)w;
322                 if (maxlen < 2)
323                         return -1;
324                 to[1] = 0;
325                 return 1;
326         }
327
328         // check how much space we need and store data into a
329         // temp buffer - this is faster than recalculating again
330         i = 0;
331         bt = 0;
332         while (w)
333         {
334                 tmp[i++] = 0x80 | (w & 0x3F);
335                 bt = (bt >> 1) | 0x80;
336                 w >>= 6;
337                 // see if we still fit into the target buffer
338                 if (i+1 >= maxlen) // +1 for the \0
339                         return -i;
340
341                 // there are no characters which take up that much space yet
342                 // and there won't be for the next many many years, still... let's be safe
343                 if (i >= sizeof(tmp))
344                         return -1;
345         }
346         tmp[i-1] |= bt;
347         for (j = 0; j < i; ++j)
348         {
349                 to[i-j-1] = tmp[j];
350         }
351
352         to[i] = 0;
353         return i;
354 }
355
356 /** Convert a utf-8 multibyte string to a wide character string.
357  * @param wcs       The target wide-character buffer.
358  * @param mb        The utf-8 encoded multibyte string to convert.
359  * @param maxlen    The maximum number of wide-characters that fit into the target buffer.
360  * @return          The number of characters written to the target buffer.
361  */
362 size_t u8_mbstowcs(Uchar *wcs, const char *mb, size_t maxlen)
363 {
364         size_t i;
365         for (i = 0; *mb && i < maxlen; ++i)
366                 *wcs++ = u8_getchar(mb, &mb);
367         if (i < maxlen)
368                 *wcs = 0;
369         return i;
370 }
371
372 /** Convert a wide-character string to a utf-8 multibyte string.
373  * @param mb      The target buffer the utf-8 string is written to.
374  * @param wcs     The wide-character string to convert.
375  * @param maxlen  The number bytes that fit into the multibyte target buffer.
376  * @return        The number of bytes written, not including the terminating \0
377  */
378 size_t u8_wcstombs(char *mb, const Uchar *wcs, size_t maxlen)
379 {
380         size_t i;
381         const char *start = mb;
382         for (i = 0; *wcs && i < maxlen; ++i)
383         {
384                 int len;
385                 if ( (len = u8_fromchar(*wcs++, mb, maxlen - i)) < 0)
386                         return (mb - start);
387                 mb += len;
388         }
389         if (i < maxlen)
390                 *mb = 0;
391         return (mb - start);
392 }
393
394 /*
395 ================================================================================
396 Implementation of a more or less lazy font loading and rendering code.
397 ================================================================================
398 */
399
400 // anything should work, but I recommend multiples of 8
401 // since the texture size should be a power of 2
402 #define FONT_CHARS_PER_LINE 16
403 #define FONT_CHAR_LINES 16
404 #define FONT_CHARS_PER_MAP (FONT_CHARS_PER_LINE * FONT_CHAR_LINES)
405
406 typedef struct glyph_slot_s
407 {
408         // we keep the quad coords here only currently
409         // if you need other info, make Font_LoadMapForIndex fill it into this slot
410         double txmin; // texture coordinate in [0,1]
411         double txmax;
412         double tymin;
413         double tymax;
414         float vxmin;
415         float vxmax;
416         float vymin;
417         float vymax;
418         float advance_x;
419         float advance_y;
420 } glyph_slot_t;
421
422 struct font_map_s
423 {
424         Uchar start;
425         struct font_map_s *next;
426
427         rtexture_t *texture;
428         glyph_slot_t glyphs[FONT_CHARS_PER_MAP];
429 };
430
431 static qboolean Font_LoadMapForIndex(font_t *font, Uchar _ch, font_map_t **outmap);
432 qboolean Font_LoadFont(const char *name, int size, font_t *font)
433 {
434         size_t namelen;
435         char filename[PATH_MAX];
436         int status;
437
438         memset(font, 0, sizeof(*font));
439
440         if (!Font_OpenLibrary())
441         {
442                 Con_Printf("WARNING: can't open load font %s\n"
443                            "You need the FreeType2 DLL to load font files\n",
444                            name);
445                 return false;
446         }
447
448         namelen = strlen(name);
449
450         memcpy(filename, name, namelen);
451         memcpy(filename + namelen, ".ttf", 5);
452
453         font->data = FS_LoadFile(filename, font_mempool, false, &font->datasize);
454         if (!font->data)
455         {
456                 // FS_LoadFile being not-quiet should print an error :)
457                 return false;
458         }
459
460
461         status = qFT_New_Memory_Face(font_ft2lib, (FT_Bytes)font->data, font->datasize, 0, (FT_Face*)&font->face);
462         if (status)
463         {
464                 Con_Printf("ERROR: can't create face for %s\n"
465                            "Error %i\n", // TODO: error strings
466                            name, status);
467                 Mem_Free(font->data);
468                 return false;
469         }
470
471         memcpy(font->name, name, namelen+1);
472         font->size = size;
473         font->glyphSize = font->size * 2;
474         font->has_kerning = !!(((FT_Face)(font->face))->face_flags & FT_FACE_FLAG_KERNING);
475
476         status = qFT_Set_Pixel_Sizes((FT_Face)font->face, size, size);
477         if (status)
478         {
479                 Con_Printf("ERROR: can't size pixel sizes for face of font %s\n"
480                            "Error %i\n", // TODO: error strings
481                            name, status);
482                 Mem_Free(font->data);
483                 return false;
484         }
485
486         if (!Font_LoadMapForIndex(font, 0, NULL))
487         {
488                 Con_Printf("ERROR: can't load the first character map for %s\n"
489                            "This is fatal\n",
490                            name);
491                 Mem_Free(font->data);
492                 return false;
493         }
494
495         return true;
496 }
497
498 void Font_UnloadFont(font_t *font)
499 {
500         if (font->data)
501                 Mem_Free(font->data);
502         if (ft2_dll)
503         {
504                 if (font->face)
505                 {
506                         qFT_Done_Face((FT_Face)font->face);
507                         font->face = NULL;
508                 }
509         }
510 }
511
512 static qboolean Font_LoadMapForIndex(font_t *font, Uchar _ch, font_map_t **outmap)
513 {
514         char map_identifier[PATH_MAX];
515         unsigned long mapidx = _ch / FONT_CHARS_PER_MAP;
516         unsigned char *data;
517         FT_ULong ch, mapch;
518         int status;
519         int tp;
520
521         FT_Face face = font->face;
522
523         int pitch;
524         int gR, gC; // glyph position: row and column
525
526         font_map_t *map;
527
528         int bytesPerPixel = 4; // change the conversion loop too if you change this!
529
530         if (outmap)
531                 *outmap = NULL;
532
533         map = Mem_Alloc(font_mempool, sizeof(font_map_t));
534         if (!map)
535         {
536                 Con_Printf("ERROR: Out of memory when loading fontmap for %s\n", font->name);
537                 return false;
538         }
539
540         pitch = font->glyphSize * FONT_CHARS_PER_LINE * bytesPerPixel;
541         data = Mem_Alloc(font_mempool, (FONT_CHAR_LINES * font->glyphSize) * pitch);
542         if (!data)
543         {
544                 Mem_Free(map);
545                 Con_Printf("ERROR: Failed to allocate memory for glyph data for font %s\n", font->name);
546                 return false;
547         }
548
549         // initialize as white texture with zero alpha
550         tp = 0;
551         while (tp < (FONT_CHAR_LINES * font->glyphSize) * pitch)
552         {
553                 data[tp++] = 0xFF;
554                 data[tp++] = 0xFF;
555                 data[tp++] = 0xFF;
556                 data[tp++] = 0x00;
557         }
558
559         map->start = mapidx * FONT_CHARS_PER_MAP;
560         if (!font->font_map)
561                 font->font_map = map;
562         else
563         {
564                 // insert the map at the right place
565                 font_map_t *next = font->font_map;
566                 while(next->next && next->next->start < map->start)
567                         next = next->next;
568                 map->next = next->next;
569                 next->next = map;
570         }
571
572         gR = 0;
573         gC = -1;
574         for (ch = map->start;
575              ch < (FT_ULong)map->start + FONT_CHARS_PER_MAP;
576              ++ch)
577         {
578                 FT_ULong glyphIndex;
579                 int w, h, x, y;
580                 FT_GlyphSlot glyph;
581                 FT_Bitmap *bmp;
582                 unsigned char *imagedata, *dst, *src;
583                 glyph_slot_t *mapglyph;
584
585                 fprintf(stderr, "------------- GLYPH INFO -----------------\n");
586
587                 ++gC;
588                 if (gC >= FONT_CHARS_PER_LINE)
589                 {
590                         gC -= FONT_CHARS_PER_LINE;
591                         ++gR;
592                 }
593
594                 imagedata = data + gR * pitch * font->glyphSize + gC * font->glyphSize * bytesPerPixel;
595                 glyphIndex = qFT_Get_Char_Index(face, ch);
596
597                 status = qFT_Load_Glyph(face, glyphIndex, FT_LOAD_DEFAULT);
598                 if (status)
599                 {
600                         Con_Printf("failed to load glyph %lu for %s\n", glyphIndex, font->name);
601                         continue;
602                 }
603
604                 status = qFT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
605                 if (status)
606                 {
607                         Con_Printf("failed to render glyph %lu for %s\n", glyphIndex, font->name);
608                         continue;
609                 }
610
611                 glyph = face->glyph;
612                 bmp = &glyph->bitmap;
613
614                 w = bmp->width;
615                 h = bmp->rows;
616
617                 if (w > font->glyphSize || h > font->glyphSize)
618                         Con_Printf("WARNING: Glyph %lu is too big in font %s\n", ch, font->name);
619
620                 switch (bmp->pixel_mode)
621                 {
622                 case FT_PIXEL_MODE_MONO:
623                         fprintf(stderr, "  Pixel Mode: MONO\n");
624                         break;
625                 case FT_PIXEL_MODE_GRAY2:
626                         fprintf(stderr, "  Pixel Mode: GRAY2\n");
627                         break;
628                 case FT_PIXEL_MODE_GRAY4:
629                         fprintf(stderr, "  Pixel Mode: GRAY4\n");
630                         break;
631                 case FT_PIXEL_MODE_GRAY:
632                         fprintf(stderr, "  Pixel Mode: GRAY\n");
633                         break;
634                 default:
635                         fprintf(stderr, "  Pixel Mode: Unknown: %i\n", bmp->pixel_mode);
636                         Mem_Free(data);
637                         return false;
638                 }
639                 for (y = 0; y < h; ++y)
640                 {
641                         dst = imagedata + y * pitch;
642                         src = bmp->buffer + y * bmp->pitch;
643
644                         switch (bmp->pixel_mode)
645                         {
646                         case FT_PIXEL_MODE_MONO:
647                                 for (x = 0; x < bmp->width; x += 8)
648                                 {
649                                         unsigned char ch = *src++;
650                                         dst += 3; // shift to alpha byte
651                                         *dst = 255 * ((ch & 0x80) >> 7); dst += 4;
652                                         *dst = 255 * ((ch & 0x40) >> 6); dst += 4;
653                                         *dst = 255 * ((ch & 0x20) >> 5); dst += 4;
654                                         *dst = 255 * ((ch & 0x10) >> 4); dst += 4;
655                                         *dst = 255 * ((ch & 0x08) >> 3); dst += 4;
656                                         *dst = 255 * ((ch & 0x04) >> 2); dst += 4;
657                                         *dst = 255 * ((ch & 0x02) >> 1); dst += 4;
658                                         *dst = 255 * ((ch & 0x01) >> 0); dst++; // compensate the first += 3
659                                 }
660                                 break;
661                         case FT_PIXEL_MODE_GRAY2:
662                                 for (x = 0; x < bmp->width; x += 4)
663                                 {
664                                         unsigned char ch = *src++;
665                                         dst += 3; // shift to alpha byte
666                                         *dst = ( ((ch & 0xA0) >> 6) * 0x55 ); ch <<= 2; dst += 4;
667                                         *dst = ( ((ch & 0xA0) >> 6) * 0x55 ); ch <<= 2; dst += 4;
668                                         *dst = ( ((ch & 0xA0) >> 6) * 0x55 ); ch <<= 2; dst += 4;
669                                         *dst = ( ((ch & 0xA0) >> 6) * 0x55 ); ch <<= 2; dst++; // compensate the +=3
670                                 }
671                                 break;
672                         case FT_PIXEL_MODE_GRAY4:
673                                 for (x = 0; x < bmp->width; x += 2)
674                                 {
675                                         unsigned char ch = *src++;
676                                         dst += 3; // shift to alpha byte
677                                         *dst = ( ((ch & 0xF0) >> 4) * 0x24); dst += 4;
678                                         *dst = ( ((ch & 0x0F) ) * 0x24); dst++; // compensate the += 3
679                                 }
680                                 break;
681                         case FT_PIXEL_MODE_GRAY:
682                                 // in this case pitch should equal width
683                                 for (tp = 0; tp < bmp->pitch; ++tp)
684                                         dst[3 + tp*4] = src[tp]; // copy the grey value into the alpha bytes
685
686                                 //memcpy((void*)dst, (void*)src, bmp->pitch);
687                                 //dst += bmp->pitch;
688                                 break;
689                         default:
690                                 break;
691                         }
692                 }
693
694                 // now fill map->glyphs[ch - map->start]
695                 mapch = ch - map->start;
696                 mapglyph = &map->glyphs[mapch];
697
698                 {
699                         double sfx = (1.0/64.0) / (double)font->size;
700                         double sfy = (1.0/64.0) / (double)font->size;
701                         double bearingX = (double)glyph->metrics.horiBearingX * sfx;
702                         double bearingY = (double)glyph->metrics.horiBearingY * sfy;
703                         double advance = (double)glyph->metrics.horiAdvance * sfx;
704                         double mWidth = (double)glyph->metrics.width * sfx;
705                         double mHeight = (double)glyph->metrics.height * sfy;
706                         //double tWidth = bmp->width / (double)font->size;
707                         //double tHeight = bmp->rows / (double)font->size;
708
709                         mapglyph->vxmin = bearingX;
710                         mapglyph->vxmax = bearingX + mWidth;
711                         mapglyph->vymin = -bearingY;
712                         mapglyph->vymax = mHeight - bearingY;
713                         mapglyph->txmin = ( (double)(gC * font->glyphSize) ) / ( (double)(font->glyphSize * FONT_CHARS_PER_LINE) );
714                         mapglyph->txmax = mapglyph->txmin + (double)bmp->width / ( (double)(font->glyphSize * FONT_CHARS_PER_LINE) );
715                         mapglyph->tymin = ( (double)(gR * font->glyphSize) ) / ( (double)(font->glyphSize * FONT_CHAR_LINES) );
716                         mapglyph->tymax = mapglyph->tymin + (double)bmp->rows / ( (double)(font->glyphSize * FONT_CHAR_LINES) );
717                         //mapglyph->advance_x = advance * font->size;
718                         mapglyph->advance_x = advance;
719                         mapglyph->advance_y = 0;
720
721                         fprintf(stderr, "  Glyph: %lu   at (%i, %i)\n", (unsigned long)ch, gC, gR);
722                         if (ch >= 32 && ch <= 128)
723                                 fprintf(stderr, "  Character: %c\n", (int)ch);
724                         fprintf(stderr, "  Vertex info:\n");
725                         fprintf(stderr, "    X: ( %f  --  %f )\n", mapglyph->vxmin, mapglyph->vxmax);
726                         fprintf(stderr, "    Y: ( %f  --  %f )\n", mapglyph->vymin, mapglyph->vymax);
727                         fprintf(stderr, "  Texture info:\n");
728                         fprintf(stderr, "    S: ( %f  --  %f )\n", mapglyph->txmin, mapglyph->txmax);
729                         fprintf(stderr, "    T: ( %f  --  %f )\n", mapglyph->tymin, mapglyph->tymax);
730                         fprintf(stderr, "  Advance: %f, %f\n", mapglyph->advance_x, mapglyph->advance_y);
731                 }
732
733                 /*
734                 g->verts[0].set(bearingX, -bearingY, 0);
735                 g->verts[1].set(bearingX + mWidth, -bearingY, 0);
736                 g->verts[2].set(bearingX + mWidth, mHeight - bearingY, 0);
737                 g->verts[3].set(bearingX, mHeight - bearingY, 0);
738                 g->texCoords[0].set(0, 0);
739                 g->texCoords[1].set(tWidth, 0);
740                 g->texCoords[2].set(tWidth, tHeight);
741                 g->texCoords[3].set(0, tHeight);
742                 g->advance = advance;
743
744                 g->verts[0].x *= sizeX;
745                 g->verts[1].x *= sizeX;
746                 g->verts[2].x *= sizeX;
747                 g->verts[3].x *= sizeX;
748                 g->verts[0].y *= sizeY;
749                 g->verts[1].y *= sizeY;
750                 g->verts[2].y *= sizeY;
751                 g->verts[3].y *= sizeY;
752                 g->advance *= sizeX;
753
754                 // xmin is the left start of the character within the texture
755                 // TODO: support vertical fonts maybe?
756                 mapglyph->advance_x = (double)glyph->metrics.horiAdvance * (1.0/64.0) / (double)font->size;
757                 mapglyph->advance_y = 0;
758                 */
759         }
760
761         // create a texture from the data now
762         dpsnprintf(map_identifier, sizeof(map_identifier), "%s_%u_%x.rgba", font->name, (unsigned)map->start/FONT_CHARS_PER_MAP, (unsigned)map->start);
763         {
764                 FILE *f = fopen(map_identifier, "wb");
765                 fwrite(data, pitch * FONT_CHAR_LINES * font->glyphSize, 1, f);
766                 fclose(f);
767         }
768         map->texture = R_LoadTexture2D(font_texturepool, map_identifier,
769                                        font->glyphSize * FONT_CHARS_PER_LINE,
770                                        font->glyphSize * FONT_CHAR_LINES,
771                                        data, TEXTYPE_RGBA, TEXF_ALPHA | TEXF_ALWAYSPRECACHE | TEXF_MIPMAP, NULL);
772         Mem_Free(data);
773         if (!map->texture)
774         {
775                 // if the first try isn't successful, keep it with a broken texture
776                 // otherwise we retry to load it every single frame where ft2 rendering is used
777                 // this would be bad...
778                 // only `data' must be freed
779                 return false;
780         }
781         if (outmap)
782                 *outmap = map;
783         return true;
784 }
785
786 extern void _DrawQ_Setup(void);
787
788 // TODO: If no additional stuff ends up in the following static functions
789 // use the DrawQ ones!
790 static void _Font_ProcessDrawFlag(int flags)
791 {
792         _DrawQ_Setup();
793         CHECKGLERROR
794         if(flags == DRAWFLAG_ADDITIVE)
795                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
796         else if(flags == DRAWFLAG_MODULATE)
797                 GL_BlendFunc(GL_DST_COLOR, GL_ZERO);
798         else if(flags == DRAWFLAG_2XMODULATE)
799                 GL_BlendFunc(GL_DST_COLOR,GL_SRC_COLOR);
800         else if(flags == DRAWFLAG_SCREEN)
801                 GL_BlendFunc(GL_ONE_MINUS_DST_COLOR,GL_ONE);
802         else
803                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
804 }
805
806 extern cvar_t r_textcontrast, r_textbrightness, r_textshadow;
807 static const vec4_t string_colors[] =
808 {
809         // Quake3 colors
810         // LordHavoc: why on earth is cyan before magenta in Quake3?
811         // LordHavoc: note: Doom3 uses white for [0] and [7]
812         {0.0, 0.0, 0.0, 1.0}, // black
813         {1.0, 0.0, 0.0, 1.0}, // red
814         {0.0, 1.0, 0.0, 1.0}, // green
815         {1.0, 1.0, 0.0, 1.0}, // yellow
816         {0.0, 0.0, 1.0, 1.0}, // blue
817         {0.0, 1.0, 1.0, 1.0}, // cyan
818         {1.0, 0.0, 1.0, 1.0}, // magenta
819         {1.0, 1.0, 1.0, 1.0}, // white
820         // [515]'s BX_COLOREDTEXT extension
821         {1.0, 1.0, 1.0, 0.5}, // half transparent
822         {0.5, 0.5, 0.5, 1.0}  // half brightness
823         // Black's color table
824         //{1.0, 1.0, 1.0, 1.0},
825         //{1.0, 0.0, 0.0, 1.0},
826         //{0.0, 1.0, 0.0, 1.0},
827         //{0.0, 0.0, 1.0, 1.0},
828         //{1.0, 1.0, 0.0, 1.0},
829         //{0.0, 1.0, 1.0, 1.0},
830         //{1.0, 0.0, 1.0, 1.0},
831         //{0.1, 0.1, 0.1, 1.0}
832 };
833
834 static void Font_GetTextColor(float color[4], int colorindex, float r, float g, float b, float a, qboolean shadow)
835 {
836         float C = r_textcontrast.value;
837         float B = r_textbrightness.value;
838         if (colorindex & 0x10000) // that bit means RGB color
839         {
840                 color[0] = ((colorindex >> 12) & 0xf) / 15.0;
841                 color[1] = ((colorindex >> 8) & 0xf) / 15.0;
842                 color[2] = ((colorindex >> 4) & 0xf) / 15.0;
843                 color[3] = (colorindex & 0xf) / 15.0;
844         }
845         else
846                 Vector4Copy(string_colors[colorindex], color);
847         Vector4Set(color, color[0] * r * C + B, color[1] * g * C + B, color[2] * b * C + B, color[3] * a);
848         if (shadow)
849         {
850                 float shadowalpha = (color[0]+color[1]+color[2]) * 0.8;
851                 Vector4Set(color, 0, 0, 0, color[3] * bound(0, shadowalpha, 1));
852         }
853 }
854
855 float Font_DrawString_Font(float startx, float starty,
856                       const char *text, size_t maxlen,
857                       float w, float h,
858                       float basered, float basegreen, float baseblue, float basealpha,
859                       int flags, int *outcolor, qboolean ignorecolorcodes,
860                       font_t *fnt)
861 {
862         int shadow, colorindex = STRING_COLOR_DEFAULT;
863         float x = startx, y, thisw;
864         float *av, *at, *ac;
865         float color[4];
866         int batchcount;
867         float vertex3f[QUADELEMENTS_MAXQUADS*4*3];
868         float texcoord2f[QUADELEMENTS_MAXQUADS*4*2];
869         float color4f[QUADELEMENTS_MAXQUADS*4*4];
870         Uchar ch, mapch;
871         size_t i;
872         const char *text_start = text;
873         int tempcolorindex;
874
875         if (maxlen < 1)
876                 maxlen = 1<<30;
877
878         _Font_ProcessDrawFlag(flags);
879
880         R_Mesh_ColorPointer(color4f, 0, 0);
881         R_Mesh_ResetTextureState();
882         R_Mesh_TexCoordPointer(0, 2, texcoord2f, 0, 0);
883         R_Mesh_VertexPointer(vertex3f, 0, 0);
884         R_SetupGenericShader(true);
885
886         ac = color4f;
887         at = texcoord2f;
888         av = vertex3f;
889         batchcount = 0;
890
891         // We render onto the baseline, so move down by the intended height.
892         // Otherwise the text appears too high since the top edge would be the base line.
893         starty += (double)h * (5.0/6.0); // don't use the complete height
894         // with sane fonts it should be possible to use the font's `ascent` value
895         // but then again, is it safe?
896
897         for (shadow = r_textshadow.value != 0 && basealpha > 0;shadow >= 0;shadow--)
898         {
899                 text = text_start;
900                 if (!outcolor || *outcolor == -1)
901                         colorindex = STRING_COLOR_DEFAULT;
902                 else
903                         colorindex = *outcolor;
904
905                 Font_GetTextColor(color, colorindex, basered, basegreen, baseblue, basealpha, shadow);
906
907                 x = startx;
908                 y = starty;
909                 if (shadow)
910                 {
911                         x += r_textshadow.value;
912                         y += r_textshadow.value;
913                 }
914                 for (i = 0;i < maxlen && *text;i++)
915                 {
916                         font_map_t *map;
917                         if (*text == STRING_COLOR_TAG && !ignorecolorcodes && i + 1 < maxlen)
918                         {
919                                 const char *before;
920                                 Uchar chx[3];
921                                 ++text;
922                                 ch = *text; // the color tag is an ASCII character!
923                                 if (ch == STRING_COLOR_RGB_TAG_CHAR)
924                                 {
925                                         // we need some preparation here
926                                         before = text;
927                                         chx[2] = 0;
928                                         if (*text) chx[0] = u8_getchar(text, &text);
929                                         if (*text) chx[1] = u8_getchar(text, &text);
930                                         if (*text) chx[2] = u8_getchar(text, &text);
931                                         if ( ( (chx[0] >= 'A' && chx[0] <= 'F') || (chx[0] >= 'a' && chx[0] <= 'f') || (chx[0] >= '0' && chx[0] <= '9') ) &&
932                                              ( (chx[1] >= 'A' && chx[1] <= 'F') || (chx[1] >= 'a' && chx[1] <= 'f') || (chx[1] >= '0' && chx[1] <= '9') ) &&
933                                              ( (chx[2] >= 'A' && chx[2] <= 'F') || (chx[2] >= 'a' && chx[2] <= 'f') || (chx[2] >= '0' && chx[2] <= '9') ) )
934                                         {
935                                         }
936                                         else
937                                                 chx[2] = 0;
938                                         text = before; // start from the first hex character
939                                 }
940                                 if (ch <= '9' && ch >= '0') // ^[0-9] found
941                                 {
942                                         colorindex = ch - '0';
943                                         Font_GetTextColor(color, colorindex, basered, basegreen, baseblue, basealpha, shadow);
944                                         continue;
945                                 }
946                                 else if (ch == STRING_COLOR_RGB_TAG_CHAR && i + 3 < maxlen && chx[2]) // ^x found
947                                 {
948                                         // building colorindex...
949                                         ch = tolower(text[i+1]);
950                                         tempcolorindex = 0x10000; // binary: 1,0000,0000,0000,0000
951                                         if (ch <= '9' && ch >= '0') tempcolorindex |= (ch - '0') << 12;
952                                         else if (ch >= 'a' && ch <= 'f') tempcolorindex |= (ch - 87) << 12;
953                                         else tempcolorindex = 0;
954                                         if (tempcolorindex)
955                                         {
956                                                 ch = tolower(text[i+2]);
957                                                 if (ch <= '9' && ch >= '0') tempcolorindex |= (ch - '0') << 8;
958                                                 else if (ch >= 'a' && ch <= 'f') tempcolorindex |= (ch - 87) << 8;
959                                                 else tempcolorindex = 0;
960                                                 if (tempcolorindex)
961                                                 {
962                                                         ch = tolower(text[i+3]);
963                                                         if (ch <= '9' && ch >= '0') tempcolorindex |= (ch - '0') << 4;
964                                                         else if (ch >= 'a' && ch <= 'f') tempcolorindex |= (ch - 87) << 4;
965                                                         else tempcolorindex = 0;
966                                                         if (tempcolorindex)
967                                                         {
968                                                                 colorindex = tempcolorindex | 0xf;
969                                                                 // ...done! now colorindex has rgba codes (1,rrrr,gggg,bbbb,aaaa)
970                                                                 //Con_Printf("^1colorindex:^7 %x\n", colorindex);
971                                                                 Font_GetTextColor(color, colorindex, basered, basegreen, baseblue, basealpha, shadow);
972                                                                 i+=3;
973                                                                 continue;
974                                                         }
975                                                 }
976                                         }
977                                 }
978                                 else if (ch == STRING_COLOR_TAG)
979                                         i++;
980                                 i--;
981                         }
982                         ch = u8_getchar(text, &text);
983
984                         map = fnt->font_map;
985                         while(map && map->start + FONT_CHARS_PER_MAP < ch)
986                                 map = map->next;
987                         if (!map)
988                         {
989                                 if (!Font_LoadMapForIndex(fnt, ch, &map))
990                                 {
991                                         shadow = -1;
992                                         break;
993                                 }
994                                 if (!map)
995                                 {
996                                         // this shouldn't happen
997                                         shadow = -1;
998                                         break;
999                                 }
1000                         }
1001
1002                         // TODO: don't call Mesh_Draw all the time
1003                         // call it when the texture changes or the batchcount hits the limit
1004
1005                         R_Mesh_TexBind(0, R_GetTexture(map->texture));
1006                         R_SetupGenericShader(true);
1007
1008                         mapch = ch - map->start;
1009                         thisw = map->glyphs[mapch].advance_x;
1010
1011                         ac[ 0] = color[0]; ac[ 1] = color[1]; ac[ 2] = color[2]; ac[ 3] = color[3];
1012                         ac[ 4] = color[0]; ac[ 5] = color[1]; ac[ 6] = color[2]; ac[ 7] = color[3];
1013                         ac[ 8] = color[0]; ac[ 9] = color[1]; ac[10] = color[2]; ac[11] = color[3];
1014                         ac[12] = color[0]; ac[13] = color[1]; ac[14] = color[2]; ac[15] = color[3];
1015                         at[0] = map->glyphs[mapch].txmin; at[1] = map->glyphs[mapch].tymin;
1016                         at[2] = map->glyphs[mapch].txmax; at[3] = map->glyphs[mapch].tymin;
1017                         at[4] = map->glyphs[mapch].txmax; at[5] = map->glyphs[mapch].tymax;
1018                         at[7] = map->glyphs[mapch].txmin; at[7] = map->glyphs[mapch].tymax;
1019
1020                         av[ 0] = x + w*map->glyphs[mapch].vxmin; av[ 1] = y + h*map->glyphs[mapch].vymin; av[ 2] = 10;
1021                         av[ 3] = x + w*map->glyphs[mapch].vxmax; av[ 4] = y + h*map->glyphs[mapch].vymin; av[ 5] = 10;
1022                         av[ 6] = x + w*map->glyphs[mapch].vxmax; av[ 7] = y + h*map->glyphs[mapch].vymax; av[ 8] = 10;
1023                         av[ 9] = x + w*map->glyphs[mapch].vxmin; av[10] = y + h*map->glyphs[mapch].vymax; av[11] = 10;
1024
1025                         GL_LockArrays(0, 4);
1026                         R_Mesh_Draw(0, 4, 0, 2, NULL, quadelements, 0, 0);
1027                         GL_LockArrays(0, 0);
1028                         x += thisw * w;
1029                 }
1030         }
1031
1032         if (outcolor)
1033                 *outcolor = colorindex;
1034
1035         // note: this relies on the proper text (not shadow) being drawn last
1036         return x;
1037 }
1038
1039 float Font_DrawString(float startx, float starty,
1040                       const char *text, size_t maxlen,
1041                       float width, float height,
1042                       float basered, float basegreen, float baseblue, float basealpha,
1043                       int flags, int *outcolor, qboolean ignorecolorcodes)
1044 {
1045         return Font_DrawString_Font(startx, starty, text, maxlen,
1046                                     width, height,
1047                                     basered, basegreen, baseblue, basealpha,
1048                                     flags, outcolor, ignorecolorcodes,
1049                                     &test_font);
1050 }
1051