fontconvert.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. TrueType to Adafruit_GFX font converter. Derived from Peter Jakobs'
  3. Adafruit_ftGFX fork & makefont tool, and Paul Kourany's Adafruit_mfGFX.
  4. NOT AN ARDUINO SKETCH. This is a command-line tool for preprocessing
  5. fonts to be used with the Adafruit_GFX Arduino library.
  6. For UNIX-like systems. Outputs to stdout; redirect to header file, e.g.:
  7. ./fontconvert ~/Library/Fonts/FreeSans.ttf 18 > FreeSans18pt7b.h
  8. REQUIRES FREETYPE LIBRARY. www.freetype.org
  9. Currently this only extracts the printable 7-bit ASCII chars of a font.
  10. Will eventually extend with some int'l chars a la ftGFX, not there yet.
  11. Keep 7-bit fonts around as an option in that case, more compact.
  12. See notes at end for glyph nomenclature & other tidbits.
  13. */
  14. #include <stdio.h>
  15. #include <ctype.h>
  16. #include <ft2build.h>
  17. #include FT_GLYPH_H
  18. #include "../gfxfont.h" // Adafruit_GFX font structures
  19. #define DPI 141 // Approximate res. of Adafruit 2.8" TFT
  20. // Accumulate bits for output, with periodic hexadecimal byte write
  21. void enbit(uint8_t value) {
  22. static uint8_t row = 0, sum = 0, bit = 0x80, firstCall = 1;
  23. if(value) sum |= bit; // Set bit if needed
  24. if(!(bit >>= 1)) { // Advance to next bit, end of byte reached?
  25. if(!firstCall) { // Format output table nicely
  26. if(++row >= 12) { // Last entry on line?
  27. printf(",\n "); // Newline format output
  28. row = 0; // Reset row counter
  29. } else { // Not end of line
  30. printf(", "); // Simple comma delim
  31. }
  32. }
  33. printf("0x%02X", sum); // Write byte value
  34. sum = 0; // Clear for next byte
  35. bit = 0x80; // Reset bit counter
  36. firstCall = 0; // Formatting flag
  37. }
  38. }
  39. int main(int argc, char *argv[]) {
  40. int i, j, err, size, first=' ', last='~',
  41. bitmapOffset = 0, x, y, byte;
  42. char *fontName, c, *ptr;
  43. FT_Library library;
  44. FT_Face face;
  45. FT_Glyph glyph;
  46. FT_Bitmap *bitmap;
  47. FT_BitmapGlyphRec *g;
  48. GFXglyph *table;
  49. uint8_t bit;
  50. // Parse command line. Valid syntaxes are:
  51. // fontconvert [filename] [size]
  52. // fontconvert [filename] [size] [last char]
  53. // fontconvert [filename] [size] [first char] [last char]
  54. // Unless overridden, default first and last chars are
  55. // ' ' (space) and '~', respectively
  56. if(argc < 3) {
  57. fprintf(stderr, "Usage: %s fontfile size [first] [last]\n",
  58. argv[0]);
  59. return 1;
  60. }
  61. size = atoi(argv[2]);
  62. if(argc == 4) {
  63. last = atoi(argv[3]);
  64. } else if(argc == 5) {
  65. first = atoi(argv[3]);
  66. last = atoi(argv[4]);
  67. }
  68. if(last < first) {
  69. i = first;
  70. first = last;
  71. last = i;
  72. }
  73. ptr = strrchr(argv[1], '/'); // Find last slash in filename
  74. if(ptr) ptr++; // First character of filename (path stripped)
  75. else ptr = argv[1]; // No path; font in local dir.
  76. // Allocate space for font name and glyph table
  77. if((!(fontName = malloc(strlen(ptr) + 20))) ||
  78. (!(table = (GFXglyph *)malloc((last - first + 1) *
  79. sizeof(GFXglyph))))) {
  80. fprintf(stderr, "Malloc error\n");
  81. return 1;
  82. }
  83. // Derive font table names from filename. Period (filename
  84. // extension) is truncated and replaced with the font size & bits.
  85. strcpy(fontName, ptr);
  86. ptr = strrchr(fontName, '.'); // Find last period (file ext)
  87. if(!ptr) ptr = &fontName[strlen(fontName)]; // If none, append
  88. // Insert font size and 7/8 bit. fontName was alloc'd w/extra
  89. // space to allow this, we're not sprintfing into Forbidden Zone.
  90. sprintf(ptr, "%dpt%db", size, (last > 127) ? 8 : 7);
  91. // Space and punctuation chars in name replaced w/ underscores.
  92. for(i=0; (c=fontName[i]); i++) {
  93. if(isspace(c) || ispunct(c)) fontName[i] = '_';
  94. }
  95. // Init FreeType lib, load font
  96. if((err = FT_Init_FreeType(&library))) {
  97. fprintf(stderr, "FreeType init error: %d", err);
  98. return err;
  99. }
  100. if((err = FT_New_Face(library, argv[1], 0, &face))) {
  101. fprintf(stderr, "Font load error: %d", err);
  102. FT_Done_FreeType(library);
  103. return err;
  104. }
  105. // << 6 because '26dot6' fixed-point format
  106. FT_Set_Char_Size(face, size << 6, 0, DPI, 0);
  107. // Currently all symbols from 'first' to 'last' are processed.
  108. // Fonts may contain WAY more glyphs than that, but this code
  109. // will need to handle encoding stuff to deal with extracting
  110. // the right symbols, and that's not done yet.
  111. // fprintf(stderr, "%ld glyphs\n", face->num_glyphs);
  112. printf("const uint8_t %sBitmaps[] PROGMEM = {\n ", fontName);
  113. // Process glyphs and output huge bitmap data array
  114. for(i=first, j=0; i<=last; i++, j++) {
  115. // MONO renderer provides clean image with perfect crop
  116. // (no wasted pixels) via bitmap struct.
  117. if((err = FT_Load_Char(face, i, FT_LOAD_TARGET_MONO))) {
  118. fprintf(stderr, "Error %d loading char '%c'\n",
  119. err, i);
  120. continue;
  121. }
  122. if((err = FT_Render_Glyph(face->glyph,
  123. FT_RENDER_MODE_MONO))) {
  124. fprintf(stderr, "Error %d rendering char '%c'\n",
  125. err, i);
  126. continue;
  127. }
  128. if((err = FT_Get_Glyph(face->glyph, &glyph))) {
  129. fprintf(stderr, "Error %d getting glyph '%c'\n",
  130. err, i);
  131. continue;
  132. }
  133. bitmap = &face->glyph->bitmap;
  134. g = (FT_BitmapGlyphRec *)glyph;
  135. // Minimal font and per-glyph information is stored to
  136. // reduce flash space requirements. Glyph bitmaps are
  137. // fully bit-packed; no per-scanline pad, though end of
  138. // each character may be padded to next byte boundary
  139. // when needed. 16-bit offset means 64K max for bitmaps,
  140. // code currently doesn't check for overflow. (Doesn't
  141. // check that size & offsets are within bounds either for
  142. // that matter...please convert fonts responsibly.)
  143. table[j].bitmapOffset = bitmapOffset;
  144. table[j].width = bitmap->width;
  145. table[j].height = bitmap->rows;
  146. table[j].xAdvance = face->glyph->advance.x >> 6;
  147. table[j].xOffset = g->left;
  148. table[j].yOffset = 1 - g->top;
  149. for(y=0; y < bitmap->rows; y++) {
  150. for(x=0;x < bitmap->width; x++) {
  151. byte = x / 8;
  152. bit = 0x80 >> (x & 7);
  153. enbit(bitmap->buffer[
  154. y * bitmap->pitch + byte] & bit);
  155. }
  156. }
  157. // Pad end of char bitmap to next byte boundary if needed
  158. int n = (bitmap->width * bitmap->rows) & 7;
  159. if(n) { // Pixel count not an even multiple of 8?
  160. n = 8 - n; // # bits to next multiple
  161. while(n--) enbit(0);
  162. }
  163. bitmapOffset += (bitmap->width * bitmap->rows + 7) / 8;
  164. FT_Done_Glyph(glyph);
  165. }
  166. printf(" };\n\n"); // End bitmap array
  167. // Output glyph attributes table (one per character)
  168. printf("const GFXglyph %sGlyphs[] PROGMEM = {\n", fontName);
  169. for(i=first, j=0; i<=last; i++, j++) {
  170. printf(" { %5d, %3d, %3d, %3d, %4d, %4d }",
  171. table[j].bitmapOffset,
  172. table[j].width,
  173. table[j].height,
  174. table[j].xAdvance,
  175. table[j].xOffset,
  176. table[j].yOffset);
  177. if(i < last) {
  178. printf(", // 0x%02X", i);
  179. if((i >= ' ') && (i <= '~')) {
  180. printf(" '%c'", i);
  181. }
  182. putchar('\n');
  183. }
  184. }
  185. printf(" }; // 0x%02X", last);
  186. if((last >= ' ') && (last <= '~')) printf(" '%c'", last);
  187. printf("\n\n");
  188. // Output font structure
  189. printf("const GFXfont %s PROGMEM = {\n", fontName);
  190. printf(" (uint8_t *)%sBitmaps,\n", fontName);
  191. printf(" (GFXglyph *)%sGlyphs,\n", fontName);
  192. printf(" 0x%02X, 0x%02X, %ld };\n\n",
  193. first, last, face->size->metrics.height >> 6);
  194. printf("// Approx. %d bytes\n",
  195. bitmapOffset + (last - first + 1) * 7 + 7);
  196. // Size estimate is based on AVR struct and pointer sizes;
  197. // actual size may vary.
  198. FT_Done_FreeType(library);
  199. return 0;
  200. }
  201. /* -------------------------------------------------------------------------
  202. Character metrics are slightly different from classic GFX & ftGFX.
  203. In classic GFX: cursor position is the upper-left pixel of each 5x7
  204. character; lower extent of most glyphs (except those w/descenders)
  205. is +6 pixels in Y direction.
  206. W/new GFX fonts: cursor position is on baseline, where baseline is
  207. 'inclusive' (containing the bottom-most row of pixels in most symbols,
  208. except those with descenders; ftGFX is one pixel lower).
  209. Cursor Y will be moved automatically when switching between classic
  210. and new fonts. If you switch fonts, any print() calls will continue
  211. along the same baseline.
  212. ...........#####.. -- yOffset
  213. ..........######..
  214. ..........######..
  215. .........#######..
  216. ........#########.
  217. * = Cursor pos. ........#########.
  218. .......##########.
  219. ......#####..####.
  220. ......#####..####.
  221. *.#.. .....#####...####.
  222. .#.#. ....##############
  223. #...# ...###############
  224. #...# ...###############
  225. ##### ..#####......#####
  226. #...# .#####.......#####
  227. ====== #...# ====== #*###.........#### ======= Baseline
  228. || xOffset
  229. glyph->xOffset and yOffset are pixel offsets, in GFX coordinate space
  230. (+Y is down), from the cursor position to the top-left pixel of the
  231. glyph bitmap. i.e. yOffset is typically negative, xOffset is typically
  232. zero but a few glyphs will have other values (even negative xOffsets
  233. sometimes, totally normal). glyph->xAdvance is the distance to move
  234. the cursor on the X axis after drawing the corresponding symbol.
  235. There's also some changes with regard to 'background' color and new GFX
  236. fonts (classic fonts unchanged). See Adafruit_GFX.cpp for explanation.
  237. */