]> git.tdb.fi Git - ttf2png.git/blob - ttf2png.c
Fix the logic for determining grid range
[ttf2png.git] / ttf2png.c
1 /*
2 ttf2png - True Type Font to PNG converter
3 Copyright (c) 2004-2008 Mikko Rasa
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 2 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, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 */
19
20 #include <stdio.h>
21 #include <ctype.h>
22 #include <unistd.h>
23 #include <getopt.h>
24 #include <png.h>
25 #include <ft2build.h>
26 #include FT_FREETYPE_H
27
28 typedef struct sImage
29 {
30         unsigned w, h;
31         char     *data;
32 } Image;
33
34 typedef struct sGlyph
35 {
36         unsigned code;
37         Image    image;
38         unsigned x, y;
39         int      offset_x;
40         int      offset_y;
41         int      advance;
42 } Glyph;
43
44 typedef struct sFont
45 {
46         unsigned size;
47         int      ascent;
48         int      descent;
49         unsigned n_glyphs;
50         Glyph    *glyphs;
51         Image    image;
52 } Font;
53
54 unsigned round_to_pot(unsigned);
55 void usage();
56 void init_font(Font *, FT_Face, unsigned, unsigned, int);
57 void render_grid(Font *, unsigned, unsigned, unsigned, int);
58 void render_packed(Font *);
59 int save_defs(const char *, const Font *);
60 int save_png(const char *, const Image *, char);
61
62 char verbose = 0;
63
64 int main(int argc, char **argv)
65 {
66         char *fn;
67         int  begin = 0;
68         int  end = 255;
69         int  size = 10;
70         int  cpl = 0;
71         int  cellw = 0;
72         int  cellh = 0;
73         char autohinter = 0;
74         char seq = 0;
75         char alpha = 0;
76         char invert = 0;
77         char pack = 0;
78
79         FT_Library freetype;
80         FT_Face    face;
81
82         int  err;
83         int  i;
84
85         char *out_fn = "font.png";
86         char *def_fn = NULL;
87
88         Font font;
89
90         if(argc<2)
91         {
92                 usage();
93                 return 1;
94         }
95
96         while((i = getopt(argc, argv, "r:s:l:c:o:atvh?ed:pi")) != -1)
97         {
98                 char *ptr;
99                 int  temp;
100                 switch(i)
101                 {
102                 case 'r':
103                         if(!strcmp(optarg, "all"))
104                         {
105                                 begin = 0;
106                                 end = 0x110000;
107                         }
108                         else
109                         {
110                                 if(!isdigit(optarg[0]))
111                                         temp = -1;
112                                 else
113                                 {
114                                         temp = strtol(optarg, &ptr, 0);
115                                         if(ptr[0]!=',' || !isdigit(ptr[1]))
116                                                 temp = -1;
117                                 }
118                                 if(temp<0)
119                                 {
120                                         printf("Not a valid range: %s\n", optarg);
121                                         exit(1);
122                                 }
123                                 else
124                                 {
125                                         begin = temp;
126                                         end = strtol(ptr+1, NULL, 0);
127                                 }
128                         }
129                         break;
130                 case 's':
131                         size = strtol(optarg, NULL, 0);
132                         break;
133                 case 'l':
134                         cpl = strtol(optarg, NULL, 0);
135                         break;
136                 case 'c':
137                         if(!strcmp(optarg, "auto"))
138                         {
139                                 cellw = 0;
140                                 cellh = 0;
141                         }
142                         else if(!strcmp(optarg, "autorect"))
143                         {
144                                 cellw = 0;
145                                 cellh = 1;
146                         }
147                         else
148                         {
149                                 cellw = strtol(optarg, &ptr, 0);
150                                 if(ptr[0]=='x' && isdigit(ptr[1]))
151                                         cellh = strtol(ptr+1, NULL, 0);
152                         }
153                         break;
154                 case 'o':
155                         out_fn = optarg;
156                         break;
157                 case 'a':
158                         autohinter = 1;
159                         break;
160                 case 't':
161                         alpha = 1;
162                         break;
163                 case 'v':
164                         ++verbose;
165                         break;
166                 case 'h':
167                 case '?':
168                         usage();
169                         return 0;
170                 case 'e':
171                         seq = 1;
172                         break;
173                 case 'd':
174                         def_fn = optarg;
175                         break;
176                 case 'p':
177                         pack = 1;
178                         break;
179                 case 'i':
180                         invert = 1;
181                         break;
182                 }
183         }
184         if(!strcmp(out_fn, "-"))
185                 verbose = 0;
186
187         if(optind!=argc-1)
188         {
189                 usage();
190                 return 1;
191         }
192
193         fn = argv[optind];
194
195         err = FT_Init_FreeType(&freetype);
196         if(err)
197         {
198                 fprintf(stderr, "Couldn't initialize FreeType library\n");
199                 return 1;
200         }
201
202         err = FT_New_Face(freetype, fn, 0, &face);
203         if(err)
204         {
205                 fprintf(stderr, "Couldn't load font file\n");
206                 if(err==FT_Err_Unknown_File_Format)
207                         fprintf(stderr, "Unknown file format\n");
208                 return 1;
209         }
210
211         if(verbose)
212         {
213                 const char *name = FT_Get_Postscript_Name(face);
214                 printf("Font name: %s\n", name);
215                 printf("Glyphs:    %ld\n", face->num_glyphs);
216         }
217
218         err = FT_Set_Pixel_Sizes(face, 0, size);
219         if(err)
220         {
221                 fprintf(stderr, "Couldn't set size\n");
222                 return 1;
223         }
224
225         font.size = size;
226         init_font(&font, face, begin, end, autohinter);
227         if(pack)
228                 render_packed(&font);
229         else
230                 render_grid(&font, cellw, cellh, cpl, seq);
231         if(invert)
232         {
233                 for(i=0; i<font.image.w*font.image.h; ++i)
234                         font.image.data[i] = 255-font.image.data[i];
235         }
236         save_png(out_fn, &font.image, alpha);
237         if(def_fn)
238                 save_defs(def_fn, &font);
239
240         for(i=0; i<font.n_glyphs; ++i)
241                 free(font.glyphs[i].image.data);
242         free(font.glyphs);
243         free(font.image.data);
244
245         FT_Done_Face(face);
246         FT_Done_FreeType(freetype);
247
248         return 0;
249 }
250
251 unsigned round_to_pot(unsigned n)
252 {
253         n -= 1;
254         n |= n>>1;
255         n |= n>>2;
256         n |= n>>4;
257         n |= n>>8;
258         n |= n>>16;
259
260         return n+1;
261 }
262
263 void usage()
264 {
265         printf("ttf2png - True Type Font to PNG converter\n"
266                 "Copyright (c) 2004-2008  Mikko Rasa, Mikkosoft Productions\n"
267                 "Distributed under the GNU General Public License\n\n"
268                 "Usage: ttf2png [options] <TTF file>\n\n"
269                 "Accepted options (default values in [brackets])\n"
270                 "  -r  Range of characters to convert in the format low,high [0,255]\n"
271                 "  -s  Font size to use, in pixels [10]\n"
272                 "  -l  Number of characters to put in one line [auto]\n"
273                 "  -c  Character cell size, in pixels [auto]\n"
274                 "  -o  Output file name (or - for stdout) [font.png]\n"
275                 "  -a  Force autohinter\n"
276                 "  -t  Render font to alpha channel\n"
277                 "  -i  Invert colors of the glyphs\n"
278                 "  -v  Increase the level of verbosity\n"
279                 "  -e  Use cells in sequence, rather than by code\n"
280                 "  -p  Pack the glyphs tightly instead of in a grid\n"
281                 "  -d  Write a definition to the given file\n"
282                 "  -h  Print this message\n");
283 }
284
285 void init_font(Font *font, FT_Face face, unsigned first, unsigned last, int autohinter)
286 {
287         unsigned i;
288         unsigned size = 0;
289
290         font->ascent = (face->size->metrics.ascender+63)>>6;
291         font->descent = (face->size->metrics.descender+63)>>6;
292
293         if(verbose>=1)
294         {
295                 printf("Ascent:    %d\n", font->ascent);
296                 printf("Descent:   %d\n", font->descent);
297         }
298
299         font->n_glyphs = 0;
300         font->glyphs = NULL;
301         for(i=first; i<=last; ++i)
302         {
303                 unsigned  n;
304                 FT_Bitmap *bmp = &face->glyph->bitmap;
305                 int       x, y;
306                 int       flags = 0;
307                 Glyph     *glyph;
308
309                 n = FT_Get_Char_Index(face, i);
310                 if(!n)
311                         continue;
312
313                 if(autohinter)
314                         flags |= FT_LOAD_FORCE_AUTOHINT;
315                 FT_Load_Glyph(face, n, flags);
316                 FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
317
318                 if(verbose>=2)
319                         printf("  Char %u: glyph %u, size %dx%d\n", i, n, bmp->width, bmp->rows);
320
321                 if(bmp->pixel_mode!=FT_PIXEL_MODE_GRAY)
322                 {
323                         fprintf(stderr, "Warning: Glyph %u skipped, not grayscale\n", n);
324                         continue;
325                 }
326
327                 if(font->n_glyphs>=size)
328                 {
329                         size += 16;
330                         font->glyphs = (Glyph *)realloc(font->glyphs, size*sizeof(Glyph));
331                 }
332
333                 glyph = &font->glyphs[font->n_glyphs++];
334                 glyph->code = i;
335                 glyph->image.w = bmp->width;
336                 glyph->image.h = bmp->rows;
337                 glyph->image.data = (char *)malloc(bmp->width*bmp->rows);
338                 glyph->offset_x = face->glyph->bitmap_left;
339                 glyph->offset_y = face->glyph->bitmap_top-bmp->rows;
340                 glyph->advance = (int)(face->glyph->advance.x+32)/64;
341
342                 if(bmp->pitch<0)
343                 {
344                         for(y=0; y<bmp->rows; ++y) for(x=0; x<bmp->width; ++x)
345                                 glyph->image.data[x+(glyph->image.h-1-y)*glyph->image.w] = bmp->buffer[x-y*bmp->pitch];
346                 }
347                 else
348                 {
349                         for(y=0; y<bmp->rows; ++y) for(x=0; x<bmp->width; ++x)
350                                 glyph->image.data[x+y*glyph->image.w] = bmp->buffer[x+y*bmp->pitch];
351                 }
352         }
353
354         if(verbose>=1)
355                 printf("Loaded %u glyphs\n", font->n_glyphs);
356 }
357
358 void render_grid(Font *font, unsigned cellw, unsigned cellh, unsigned cpl, int seq)
359 {
360         unsigned i;
361         int      top = 0, bot = 0;
362         unsigned first, last;
363         unsigned maxw = 0, maxh = 0;
364
365         for(i=0; i<font->n_glyphs; ++i)
366         {
367                 int y;
368
369                 y = font->glyphs[i].offset_y+font->glyphs[i].image.h;
370                 if(y>top)
371                         top = y;
372                 if(font->glyphs[i].offset_y<bot)
373                         bot = font->glyphs[i].offset_y;
374                 if(font->glyphs[i].image.w>maxw)
375                         maxw = font->glyphs[i].image.w;
376                 if(font->glyphs[i].image.h>maxh)
377                         maxh = font->glyphs[i].image.h;
378         }
379
380         if(cellw==0)
381         {
382                 int square = (cellh==cellw);
383                 cellw = maxw;
384                 cellh = top-bot;
385                 if(square)
386                 {
387                         if(cellh>cellw)
388                                 cellw = cellh;
389                         else
390                                 cellh = cellw;
391                 }
392         }
393
394         if(verbose>=1)
395         {
396                 printf("Max size:  %u x %u\n", maxw, maxh);
397                 printf("Y range:   [%d %d]\n", bot, top);
398                 printf("Cell size: %u x %u\n", cellw, cellh);
399                 if(maxw>cellw || top-bot>cellh)
400                         fprintf(stderr, "Warning: character size exceeds cell size\n");
401         }
402
403         if(cpl==0)
404         {
405                 for(i=1;; i<<=1)
406                 {
407                         cpl = i/cellw;
408                         if(cpl>0 && font->n_glyphs/cpl*cellh<=cpl*cellw)
409                                 break;
410                 }
411         }
412
413         first = font->glyphs[0].code;
414         if(!seq)
415                 first -= first%cpl;
416         last = font->glyphs[font->n_glyphs-1].code;
417
418         font->image.w = round_to_pot(cpl*cellw);
419         font->image.h = round_to_pot((last-first+cpl)/cpl*cellh);
420
421         font->image.data = (char *)malloc(font->image.w*font->image.h);
422         memset(font->image.data, 255, font->image.w*font->image.h);
423
424         for(i=0; i<font->n_glyphs; ++i)
425         {
426                 Glyph    *glyph;
427                 int      ci, cx, cy;
428                 unsigned x, y;
429
430                 glyph = &font->glyphs[i];
431
432                 if(seq)
433                         ci = i;
434                 else
435                         ci = glyph->code-first;
436
437                 cx = (ci%cpl)*cellw;
438                 cy = (ci/cpl)*cellh;
439
440                 if(cellw>glyph->image.w)
441                         cx += (cellw-glyph->image.w)/2;
442                 cy += top-glyph->offset_y-glyph->image.h;
443
444                 glyph->x = cx;
445                 glyph->y = cy;
446
447                 for(y=0; y<glyph->image.h; ++y) for(x=0; x<glyph->image.w; ++x)
448                 {
449                         if(cx+x<0 || cx+x>=font->image.w || cy+y<0 || cy+y>=font->image.h)
450                                 continue;
451                         font->image.data[cx+x+(cy+y)*font->image.w] = 255-glyph->image.data[x+y*glyph->image.w];
452                 }
453         }
454 }
455
456 void render_packed(Font *font)
457 {
458         unsigned i;
459         unsigned area = 0;
460         char     *used_glyphs;
461         char     *used_pixels;
462         unsigned cx = 0, cy;
463         unsigned used_h = 0;
464
465         for(i=0; i<font->n_glyphs; ++i)
466                 area += (font->glyphs[i].image.w+1)*(font->glyphs[i].image.h+1);
467
468         for(font->image.w=1;; font->image.w<<=1)
469         {
470                 font->image.h = (area*5/4)/font->image.w;
471                 if(font->image.h<=font->image.w)
472                         break;
473         }
474         font->image.h = round_to_pot(font->image.h);
475
476         font->image.data = (char *)malloc(font->image.w*font->image.h);
477         memset(font->image.data, 255, font->image.w*font->image.h);
478         used_pixels = (char *)malloc(font->image.w*font->image.h);
479         memset(used_pixels, 0, font->image.w*font->image.h);
480         used_glyphs = (char *)malloc(font->n_glyphs);
481         memset(used_glyphs, 0, font->n_glyphs);
482
483         for(cy=0; cy<font->image.h;)
484         {
485                 unsigned w;
486                 unsigned x, y;
487                 Glyph    *glyph = NULL;
488                 unsigned best_score = 0;
489                 unsigned target_h = 0;
490
491                 for(; (cx<font->image.w && used_pixels[cx+cy*font->image.w]); ++cx) ;
492                 if(cx>=font->image.w)
493                 {
494                         cx = 0;
495                         ++cy;
496                         continue;
497                 }
498                 for(w=0; (cx+w<font->image.w && !used_pixels[cx+w+cy*font->image.w]); ++w) ;
499
500                 for(x=0; x<cx; ++x)
501                 {
502                         for(y=0; (cy+y+1<font->image.h && used_pixels[cx-x+(cy+y+1)*font->image.w]); ++y) ;
503                         if(y>target_h)
504                                 target_h = y;
505                 }
506
507                 for(i=0; i<font->n_glyphs; ++i)
508                 {
509                         Glyph *g;
510
511                         g = &font->glyphs[i];
512                         if(!used_glyphs[i] && g->image.w<=w)
513                         {
514                                 unsigned score;
515
516                                 score = g->image.h+1;
517                                 if(g->image.h==target_h)
518                                         score *= g->image.w;
519                                 else
520                                         score += g->image.w;
521
522                                 if(score>best_score)
523                                 {
524                                         glyph = g;
525                                         best_score = score;
526                                 }
527                         }
528                 }
529
530                 if(!glyph)
531                 {
532                         cx += w;
533                         continue;
534                 }
535
536                 used_glyphs[glyph-font->glyphs] = 1;
537                 glyph->x = cx;
538                 glyph->y = cy;
539
540                 for(y=0; y<glyph->image.h; ++y) for(x=0; x<glyph->image.w; ++x)
541                 {
542                         if(cx+x<0 || cx+x>=font->image.w || cy+y<0 || cy+y>=font->image.h)
543                                 continue;
544                         font->image.data[cx+x+(cy+y)*font->image.w] = 255-glyph->image.data[x+y*glyph->image.w];
545                 }
546                 for(y=0; y<glyph->image.h+2; ++y) for(x=0; x<glyph->image.w+2; ++x)
547                 {
548                         if(cx+x<1 || cx+x>font->image.w || cy+y<1 || cy+y>font->image.h)
549                                 continue;
550                         used_pixels[cx+x-1+(cy+y-1)*font->image.w] = 1;
551                 }
552
553                 if(cy+glyph->image.h>used_h)
554                         used_h = cy+glyph->image.h;
555         }
556
557         font->image.h = round_to_pot(used_h);
558 }
559
560 int save_defs(const char *fn, const Font *font)
561 {
562         FILE     *out;
563         unsigned i;
564
565         out = fopen(fn, "w");
566         if(!out)
567         {
568                 fprintf(stderr, "Couldn't open %s\n",fn);
569                 return -1;
570         }
571
572         fprintf(out, "%d %d %d %d %d\n", font->image.w, font->image.h, font->size, font->ascent, font->descent);
573         for(i=0; i<font->n_glyphs; ++i)
574         {
575                 const Glyph *g = &font->glyphs[i];
576                 fprintf(out, "%u %u %u %u %u %d %d %d\n", g->code, g->x, g->y, g->image.w, g->image.h, g->offset_x, g->offset_y, g->advance);
577         }
578
579         fclose(out);
580
581         return 0;
582 }
583
584 int save_png(const char *fn, const Image *image, char alpha)
585 {
586         FILE       *out;
587         png_struct *pngs;
588         png_info   *pngi;
589         png_byte   *rows[image->h];
590         int        i;
591         png_byte   *data2;
592         int        color;
593
594         if(!strcmp(fn, "-"))
595                 out = stdout;
596         else
597         {
598                 out = fopen(fn, "wb");
599                 if(!out)
600                 {
601                         fprintf(stderr, "Couldn't open %s\n",fn);
602                         return -1;
603                 }
604         }
605
606         pngs = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
607         if(!pngs)
608         {
609                 fprintf(stderr, "Error writing PNG file\n");
610                 return -1;
611         }
612         pngi = png_create_info_struct(pngs);
613         if(!pngi)
614         {
615                 png_destroy_write_struct(&pngs, NULL);
616                 fprintf(stderr, "Error writing PNG file\n");
617                 return -1;
618         }
619
620         png_init_io(pngs, out);
621         if(alpha)
622         {
623                 data2 = (png_byte *)malloc(image->w*image->h*2);
624                 for(i=0; i<image->w*image->h; ++i)
625                 {
626                         data2[i*2] = 255;
627                         data2[i*2+1] = 255-image->data[i];
628                 }
629                 for(i=0; i<image->h; ++i)
630                         rows[i] = (png_byte *)(data2+i*image->w*2);
631                 color = PNG_COLOR_TYPE_GRAY_ALPHA;
632         }
633         else
634         {
635                 for(i=0; i<image->h; ++i)
636                         rows[i] = (png_byte *)(image->data+i*image->w);
637                 color = PNG_COLOR_TYPE_GRAY;
638         }
639         png_set_IHDR(pngs, pngi, image->w, image->h, 8, color, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
640         png_set_rows(pngs, pngi, rows);
641         png_write_png(pngs, pngi, PNG_TRANSFORM_IDENTITY, NULL);
642         png_destroy_write_struct(&pngs, &pngi);
643         if(alpha)
644                 free(data2);
645
646         if(verbose)
647                 printf("Saved %dx%d PNG image to %s\n", image->w, image->h, fn);
648
649         fclose(out);
650
651         return 0;
652 }