+ unsigned i;
+ unsigned area = 0;
+ char *used_glyphs;
+ unsigned *used_pixels;
+ unsigned cx = 0, cy;
+ unsigned used_h = 0;
+
+ /* Compute the total area occupied by glyphs and padding. */
+ for(i=0; i<font->n_glyphs; ++i)
+ area += (font->glyphs[i].image.w+1)*(font->glyphs[i].image.h+1);
+
+ /* Find an image size that's no higher than wide, allowing for some
+ imperfections in the packing. */
+ for(font->image.w=1;; font->image.w<<=1)
+ {
+ font->image.h = (area*5/4)/font->image.w;
+ if(font->image.h<=font->image.w)
+ break;
+ }
+ font->image.h = round_to_pot(font->image.h);
+
+ /* Allocate arrays for storing the image and keeping track of used pixels and
+ glyphs. Since glyphs are rectangular and the image is filled starting from
+ the top, it's enough to track the number of used pixels at the top of each
+ column. */
+ font->image.data = (char *)malloc(font->image.w*font->image.h);
+ memset(font->image.data, 255, font->image.w*font->image.h);
+ used_pixels = (unsigned *)malloc(font->image.w*sizeof(unsigned));
+ memset(used_pixels, 0, font->image.w*sizeof(unsigned));
+ used_glyphs = (char *)malloc(font->n_glyphs);
+ memset(used_glyphs, 0, font->n_glyphs);
+
+ for(cy=0; cy<font->image.h;)
+ {
+ unsigned w;
+ unsigned x, y;
+ Glyph *glyph = NULL;
+ unsigned best_score = 0;
+ unsigned target_h = 0;
+
+ /* Find the leftmost free pixel on this row. Also record the lowest extent of glyphs
+ to the left of the free position. */
+ for(; (cx<font->image.w && used_pixels[cx]>cy); ++cx)
+ if(used_pixels[cx]-cy-1>target_h)
+ target_h = used_pixels[cx]-cy-1;
+
+ if(cx>=font->image.w)
+ {
+ cx = 0;
+ ++cy;
+ continue;
+ }