From: Mikko Rasa Date: Thu, 3 May 2018 09:04:54 +0000 (+0300) Subject: Refactor glyph bitmap copying into a separate function X-Git-Url: http://git.tdb.fi/?p=ttf2png.git;a=commitdiff_plain;h=cb68acf15406a683e2d722b3a52c4d3b8b2df70d Refactor glyph bitmap copying into a separate function Also write it in a way that doesn't duplicate the loops. --- diff --git a/ttf2png.c b/ttf2png.c index e39c328..af9f56f 100644 --- a/ttf2png.c +++ b/ttf2png.c @@ -80,6 +80,7 @@ unsigned round_to_pot(unsigned); void *alloc_image_data(size_t, size_t); int init_font(Font *, FT_Face, const Range *, unsigned, bool); int init_glyphs(Font *, FT_Face, const Range *, bool); +int copy_bitmap(const FT_Bitmap *, Image *); int render_grid(Font *, unsigned, unsigned, unsigned, bool, bool); int render_packed(Font *, unsigned, unsigned, bool); int save_defs(const char *, const Font *); @@ -560,7 +561,6 @@ int init_glyphs(Font *font, FT_Face face, const Range *range, bool autohinter) { unsigned n; FT_Bitmap *bmp = &face->glyph->bitmap; - unsigned x, y; int flags = 0; Glyph *glyph; @@ -609,14 +609,6 @@ int init_glyphs(Font *font, FT_Face face, const Range *range, bool autohinter) glyph = &font->glyphs[font->n_glyphs++]; glyph->index = n; glyph->code = i; - glyph->image.w = bmp->width; - glyph->image.h = bmp->rows; - glyph->image.data = (char *)malloc(bmp->width*bmp->rows); - if(!glyph->image.data) - { - fprintf(stderr, "Cannot allocate %d bytes of memory for glyph\n", bmp->width*bmp->rows); - return -1; - } glyph->offset_x = face->glyph->bitmap_left; glyph->offset_y = face->glyph->bitmap_top-bmp->rows; glyph->advance = (int)(face->glyph->advance.x+32)/64; @@ -624,16 +616,47 @@ int init_glyphs(Font *font, FT_Face face, const Range *range, bool autohinter) /* Copy the glyph image since FreeType uses a global buffer, which would be overwritten by the next glyph. Negative pitch means the scanlines start from the bottom. */ - if(bmp->pitch<0) - { - for(y=0; yrows; ++y) for(x=0; xwidth; ++x) - glyph->image.data[x+(glyph->image.h-1-y)*glyph->image.w] = bmp->buffer[x-y*bmp->pitch]; - } - else - { - for(y=0; yrows; ++y) for(x=0; xwidth; ++x) - glyph->image.data[x+y*glyph->image.w] = bmp->buffer[x+y*bmp->pitch]; - } + if(copy_bitmap(bmp, &glyph->image)) + return -1; + } + + return 0; +} + +int copy_bitmap(const FT_Bitmap *bmp, Image *image) +{ + unsigned x, y; + unsigned char *src; + char *dst; + + image->w = bmp->width; + image->h = bmp->rows; + if(!image->w || !image->h) + { + image->data = NULL; + return 0; + } + + image->data = (char *)malloc(image->w*image->h); + if(!image->data) + { + fprintf(stderr, "Cannot allocate %d bytes of memory for glyph\n", image->w*image->h); + return -1; + } + + if(bmp->pitch<0) + src = bmp->buffer+(bmp->rows-1)*-bmp->pitch; + else + src = bmp->buffer; + dst = image->data; + + for(y=0; yrows; ++y) + { + for(x=0; xwidth; ++x) + dst[x] = src[x]; + + src += bmp->pitch; + dst += image->w; } return 0;